This specification is maintained by the AgentRules Working Group. Have enhancements or want to claim maintainership?Submit Specification →
mobilecritical PriorityID: capacitor-7-hardware-attestation-sqlite-guardrail

Hardware Enclave Attestation-Gated SQLite Store Initialization

Enforces cryptographic hardware-backed attestation (Apple App Attest / Google Play Integrity) verified against an authoritative backend before releasing local SQLCipher decryption keys into memory. Prohibits local-only client trust decisions, hardcoded key derivation parameters, and unencrypted passphrase caching across Capacitor 7 bridge boundaries.

Prohibited Anti-Pattern: Decrypting Local Embedded Databases Using Client-Decided Biometric Checks or Unattested Keystore Material

Export Ready-to-Drop Configuration

Select format below to copy code or download file directly.

---
description: Hardware Enclave Attestation-Gated SQLite Store Initialization - Enforces cryptographic hardware-backed attestation (Apple App Attest / Google Play Integrity) verified against an authoritative backend before releasing local SQLCipher decryption keys into memory. Prohibits local-only client trust decisions, hardcoded key derivation parameters, and unencrypted passphrase caching across Capacitor 7 bridge boundaries.
globs: src/**/*.{ts,tsx}, android/app/src/main/**/*.kt, ios/App/App/**/*.swift
alwaysApply: true
verified_by: "agentrules.org"
license: "CC-BY-4.0"
source: "https://agentrules.org/rules/capacitor-7-hardware-attestation-sqlite-guardrail"
---

# Hardware Enclave Attestation-Gated SQLite Store Initialization

> **Severity**: CRITICAL | **Category**: mobile
> **Anti-Pattern Warning**: Decrypting Local Embedded Databases Using Client-Decided Biometric Checks or Unattested Keystore Material

## System Constraints
You are a Principal Security Architect enforcing Zero-Trust Mobile Cryptography in Capacitor 7 environments. You must prevent any pattern where local SQLite/SQLCipher databases are opened using static keys, raw Capacitor Preferences/Storage, or unverified hardware enclave keys. All database decryption keys must be protected via remote server-verified hardware attestation (DCAppAttestService or Play Integrity API) with single-use cryptographic nonces to prevent replay attacks, Frida hooking, and unauthorized runtime access in rooted/tampered environments.

## Strict Guidelines
- Engineers MUST ALWAYS obtain a cryptographically secure, short-lived nonce from the authoritative backend before generating a hardware attestation payload.
- Engineers MUST NOT evaluate attestation statements, device integrity verdicts, or app integrity tokens client-side within JavaScript/TypeScript or native bridge code.
- Services MUST exchange verified backend attestation tokens for a securely wrapped Database Encryption Key (DEK) or Key Derivation Salt via TLS 1.3 with certificate pinning.
- Engineers MUST configure SQLite/SQLCipher plugins to hold passphrases only in volatile ephemeral memory and scrub passphrase strings/buffers immediately after the database handle opens.
- Components NEVER store master encryption keys, raw DEKs, or SQLCipher passphrases in @capacitor/preferences, localStorage, or standard unencrypted iOS/Android shared preferences.
- Bridge plugins MUST strictly bind hardware keys to Secure Enclave (kSecAccessControlPrivateKeyUsage) on iOS and StrongBox/TEE-backed AndroidKeyStore with user authentication requirements.
- Error handling routines MUST immediately wipe cached state, close open database connections, and purge cached credentials if attestation verification fails or device tampering is flagged.

## Bad vs Good Implementations
### Hardware Attestation vs Local Key Storage for SQLite Initialization

#### Bad Antipattern (AI Common Hallucination)
> **Why it fails**: The database key is stored in Capacitor Preferences (unencrypted on web, insecurely keyed on mobile) and loaded unconditionally into memory without verifying application integrity, runtime tampering, or hardware presence via App Attest/Play Integrity. An attacker on a rooted device with Frida can read the key or inspect the storage sandbox.
```typescript
import { Preferences } from '@capacitor/preferences';
import { CapacitorSQLite, SQLiteConnection } from '@capacitor-community/sqlite';

const sqlite = new SQLiteConnection(CapacitorSQLite);

export async function initDatabase(): Promise<void> {
  // VULNERABLE: Decryption key is retrieved from unauthenticated, static storage
  // and decrypted directly in client runtime without hardware integrity verification.
  const { value: dbKey } = await Preferences.get({ key: 'sqlite_encryption_key' });
  
  if (!dbKey) {
    throw new Error('Database key not found');
  }

  const db = await sqlite.createConnection(
    'secure_app_data',
    false,
    'no-encryption',
    1,
    false
  );

  // Database passphrase passed in plaintext from untrusted local storage
  await db.open();
}
```

#### Production Standard (Correct)
> **Standard**: SQLite decryption is gated behind a hardware enclave attestation challenge-response cycle verified exclusively by the authoritative backend. The client cannot produce or access the database decryption key without passing cryptographic integrity validation, protecting encrypted storage from tampered environments.
```typescript
import { CapacitorSQLite, SQLiteConnection } from '@capacitor-community/sqlite';
import { NativeAttestationPlugin } from './plugins/NativeAttestationPlugin';
import { apiClient } from './security/ApiClient';

const sqlite = new SQLiteConnection(CapacitorSQLite);

export async function initializeAttestedDatabase(): Promise<void> {
  // 1. Fetch server-generated single-use cryptographic nonce
  const { nonce, sessionChallengeId } = await apiClient.requestAttestationChallenge();

  // 2. Generate hardware-backed enclave attestation statement using native bridge
  const attestationResult = await NativeAttestationPlugin.generateAttestationStatement({
    nonce,
    keyId: 'app_sqlite_enclave_key',
  });

  // 3. Exchange hardware attestation with backend for ephemeral decryption key (DEK)
  // Backend verifies Apple App Attest / Google Play Integrity against platform APIs
  const { ephemeralDekToken } = await apiClient.verifyAndReleaseKey({
    challengeId: sessionChallengeId,
    attestationPayload: attestationResult.payload,
    clientHardwareFingerprint: attestationResult.keyIdentifier,
  });

  // 4. Unwrap ephemeral key in-memory only and initialize SQLCipher connection
  const db = await sqlite.createConnection(
    'secure_app_data',
    true, // encrypted
    'secret',
    1,
    false
  );

  try {
    // Open using the remotely attested ephemeral key
    await db.open();
    await db.execute(`PRAGMA key = '${ephemeralDekToken}';`);
  } finally {
    // Enforce immediate zeroization of transient memory pointer reference
    apiClient.scrubMemoryToken(ephemeralDekToken);
  }
}
```

Architectural Specification & Invariant Rationale

Architectural Invariant Design: Hardware Enclave Attestation-Gated SQLite Store Initialization

Hardware Enclave Attestation-Gated SQLite Store Initialization defines an industrial-grade behavioral standard for mobile engineering. Enforces cryptographic hardware-backed attestation (Apple App Attest / Google Play Integrity) verified against an authoritative backend before releasing local SQLCipher decryption keys into memory. Prohibits local-only client trust decisions, hardcoded key derivation parameters, and unencrypted passphrase caching across Capacitor 7 bridge boundaries. Modern software architectures require strict adherence to deterministic patterns to guarantee high availability, maintainability, and zero security vulnerabilities.

Framework Paradigm Shift & Drift MechanicsLLMs are trained on millions of open-source repositories containing outdated code, legacy idioms, and unpatched antipatterns. When coding assistants generate implementations for this stack, they default to common statistical tokens: Decrypting Local Embedded Databases Using Client-Decided Biometric Checks or Unattested Keystore Material Without an explicit system instruction file, developers spend hours debugging silent failures.
Failure Modes & Production Blast Radius

Hazard Analysis: What Breaks Without This Rule

The following failure modes have been cataloged from hundreds of hours of production code reviews where AI assistants produced non-compliant implementations:

Failure ModeAI Symptom (The Anti-Pattern)SeverityProduction Impact & Remedy
AI Hallucination & Deprecation DriftDecrypting Local Embedded Databases Using Client-Decided Biometric Checks or Unattested Keystore MaterialCritical
Violating this industrial standard introduces regression bugs, security risks, and unexpected runtime failures in production.
Enforce explicit behavioral system directives across all AI coding assistants in your repository.
Silent Architecture InconsistencyAI assistants produce mixed paradigms across files, creating fragmented codebase conventions.Medium
Increases cognitive load during code reviews and leads to maintenance debt across engineering teams.
Pin project conventions in .cursor/rules, CLAUDE.md, and AGENTS.md so all team agents follow identical guardrails.
Architectural Directives in Detail

Step-by-Step Production Directives

Each rule constraint below is injected into the AI agent's system prompt to establish deterministic boundaries:

1

Engineers MUST ALWAYS obtain a cryptographically secure, short-lived nonce from the authoritative backend before generating a hardware attestation payload.

Engineers MUST ALWAYS obtain a cryptographically secure, short-lived nonce from the authoritative backend before generating a hardware attestation payload.

Rationale:AI models frequently generate unconstrained code here because statistical language distributions lack project-specific architectural context. Mandating this directive ensures that generated code adheres to verified industrial production requirements.
Enforcement:Integrated into the Agent Pack rule file. When Cursor, Claude Code, or Codex processes this prompt, it applies this constraint before emitting syntax.
2

Engineers MUST NOT evaluate attestation statements, device integrity verdicts, or app integrity tokens client-side within JavaScript/TypeScript or native bridge code.

Engineers MUST NOT evaluate attestation statements, device integrity verdicts, or app integrity tokens client-side within JavaScript/TypeScript or native bridge code.

Rationale:AI models frequently generate unconstrained code here because statistical language distributions lack project-specific architectural context. Mandating this directive ensures that generated code adheres to verified industrial production requirements.
Enforcement:Integrated into the Agent Pack rule file. When Cursor, Claude Code, or Codex processes this prompt, it applies this constraint before emitting syntax.
3

Services MUST exchange verified backend attestation tokens for a securely wrapped Database Encryption Key (DEK) or Key Derivation Salt via TLS 1.3 with certificate pinning.

Services MUST exchange verified backend attestation tokens for a securely wrapped Database Encryption Key (DEK) or Key Derivation Salt via TLS 1.3 with certificate pinning.

Rationale:AI models frequently generate unconstrained code here because statistical language distributions lack project-specific architectural context. Mandating this directive ensures that generated code adheres to verified industrial production requirements.
Enforcement:Integrated into the Agent Pack rule file. When Cursor, Claude Code, or Codex processes this prompt, it applies this constraint before emitting syntax.
4

Engineers MUST configure SQLite/SQLCipher plugins to hold passphrases only in volatile ephemeral memory and scrub passphrase strings/buffers immediately after the database handle opens.

Engineers MUST configure SQLite/SQLCipher plugins to hold passphrases only in volatile ephemeral memory and scrub passphrase strings/buffers immediately after the database handle opens.

Rationale:AI models frequently generate unconstrained code here because statistical language distributions lack project-specific architectural context. Mandating this directive ensures that generated code adheres to verified industrial production requirements.
Enforcement:Integrated into the Agent Pack rule file. When Cursor, Claude Code, or Codex processes this prompt, it applies this constraint before emitting syntax.
5

Components NEVER store master encryption keys, raw DEKs, or SQLCipher passphrases in @capacitor/preferences, localStorage, or standard unencrypted iOS/Android shared preferences.

Components NEVER store master encryption keys, raw DEKs, or SQLCipher passphrases in @capacitor/preferences, localStorage, or standard unencrypted iOS/Android shared preferences.

Rationale:AI models frequently generate unconstrained code here because statistical language distributions lack project-specific architectural context. Mandating this directive ensures that generated code adheres to verified industrial production requirements.
Enforcement:Integrated into the Agent Pack rule file. When Cursor, Claude Code, or Codex processes this prompt, it applies this constraint before emitting syntax.
6

Bridge plugins MUST strictly bind hardware keys to Secure Enclave (kSecAccessControlPrivateKeyUsage) on iOS and StrongBox/TEE-backed AndroidKeyStore with user authentication requirements.

Bridge plugins MUST strictly bind hardware keys to Secure Enclave (kSecAccessControlPrivateKeyUsage) on iOS and StrongBox/TEE-backed AndroidKeyStore with user authentication requirements.

Rationale:AI models frequently generate unconstrained code here because statistical language distributions lack project-specific architectural context. Mandating this directive ensures that generated code adheres to verified industrial production requirements.
Enforcement:Integrated into the Agent Pack rule file. When Cursor, Claude Code, or Codex processes this prompt, it applies this constraint before emitting syntax.
7

Error handling routines MUST immediately wipe cached state, close open database connections, and purge cached credentials if attestation verification fails or device tampering is flagged.

Error handling routines MUST immediately wipe cached state, close open database connections, and purge cached credentials if attestation verification fails or device tampering is flagged.

Rationale:AI models frequently generate unconstrained code here because statistical language distributions lack project-specific architectural context. Mandating this directive ensures that generated code adheres to verified industrial production requirements.
Enforcement:Integrated into the Agent Pack rule file. When Cursor, Claude Code, or Codex processes this prompt, it applies this constraint before emitting syntax.
Technical Questions & Answers

Frequently Asked Technical Questions

Common questions developers face when configuring AI coding assistants for this stack:

Q:Why is Hardware Enclave Attestation-Gated SQLite Store Initialization critical for AI coding assistants?

Enforces cryptographic hardware-backed attestation (Apple App Attest / Google Play Integrity) verified against an authoritative backend before releasing local SQLCipher decryption keys into memory. Prohibits local-only client trust decisions, hardcoded key derivation parameters, and unencrypted passphrase caching across Capacitor 7 bridge boundaries. Without explicit behavioral boundaries, AI coding assistants (Cursor, Claude Code, Windsurf, Codex) rely on training data averages, which frequently produce deprecated, inefficient, or vulnerable code patterns.

Q:How does adopting this rule prevent AI hallucinations?

This rule explicitly declares what the AI must avoid (Decrypting Local Embedded Databases Using Client-Decided Biometric Checks or Unattested Keystore Material) and prescribes verified positive examples. Grounding the LLM with negative and positive pairs eliminates guesswork.

Q:Which AI coding environments are supported?

This specification is multi-platform compatible: Cursor (.cursor/rules/*.mdc & .cursorrules), Anthropic Claude Code (CLAUDE.md), Windsurf (.windsurfrules), Codex / Cline (AGENTS.md), and GitHub Copilot (.github/copilot-instructions.md).

Q:Can I combine this rule with other technology stacks?

Yes. Use the Interactive Stack Builder or download an Agent Pack to merge this rule with other frontend, backend, database, security, and DevOps rules without syntax collision.

Open Specification · CC BY 4.0·Free for Personal, Team & Commercial In-Repo Use

Citation & Open Source Attribution Guidelines

This specification is licensed under Creative Commons Attribution 4.0 International (CC BY 4.0). You are completely free to adapt and share this rule in your workspace. If citing, including in public AI benchmark datasets, or redistributing, attribution to AgentRules.org is required.

Related MOBILE Rules

View all rules →
1 Rule in Stack

Hardware