This specification is maintained by the AgentRules Working Group. Have enhancements or want to claim maintainership?Submit Specification →
mobilecritical PriorityID: capacitor-secure-enclave-biometric-invalidation

Capacitor 7 Secure Enclave Dynamic Biometric Invalidation and Database Purge

Enforces immediate volatile cryptographic key zeroization, Secure Enclave/KeyStore secret invalidation, and SQLite (SQLCipher) handle purging whenever OS-level biometric enrollment changes or lock-screen authentication degrades. Guards against session hijacking caused by unauthorized fingerprint/face enrollment on compromised or shared devices.

Prohibited Anti-Pattern: Persisting Decrypted Encryption Keys in Memory and Ignoring Biometric Enrollment Changes

Export Ready-to-Drop Configuration

Select format below to copy code or download file directly.

---
description: Capacitor 7 Secure Enclave Dynamic Biometric Invalidation and Database Purge - Enforces immediate volatile cryptographic key zeroization, Secure Enclave/KeyStore secret invalidation, and SQLite (SQLCipher) handle purging whenever OS-level biometric enrollment changes or lock-screen authentication degrades. Guards against session hijacking caused by unauthorized fingerprint/face enrollment on compromised or shared devices.
globs: src/**/*.{ts,tsx}, android/app/src/main/**/*.java, ios/App/App/**/*.swift
alwaysApply: true
verified_by: "agentrules.org"
license: "CC-BY-4.0"
source: "https://agentrules.org/rules/capacitor-secure-enclave-biometric-invalidation"
---

# Capacitor 7 Secure Enclave Dynamic Biometric Invalidation and Database Purge

> **Severity**: CRITICAL | **Category**: mobile
> **Anti-Pattern Warning**: Persisting Decrypted Encryption Keys in Memory and Ignoring Biometric Enrollment Changes

## System Constraints
You are a Principal Mobile Security Architect enforcing the Capacitor 7 Secure Enclave Dynamic Biometric Invalidation Invariant. You must guarantee that any changes to OS biometric credentials (such as new fingerprint additions or passkey alterations) automatically revoke application secrets, zero out in-memory key buffers, and close offline encrypted SQLite databases immediately without relying on client-side JS storage.

## Strict Guidelines
- Engineers MUST ALWAYS configure hardware-backed keys with `.biometryCurrentSet` (iOS) or `setUserAuthenticationParameters(..., KeyProperties.AUTH_BIOMETRIC_STRONG)` and invalidate them on new enrollment via `setInvalidatedByBiometricEnrollment(true)` (Android).
- Engineers MUST NEVER cache plaintext database encryption keys in JavaScript heap variables, `localStorage`, `sessionStorage`, or IndexedDB across app lifecycle boundaries.
- Code MUST actively catch hardware cryptographic failure exceptions (e.g., `KeyPermanentlyInvalidatedException` or `errSecAuthFailed`) upon application resume and trigger an immediate emergency vault purge.
- Services MUST zeroize `Uint8Array` buffers containing raw cryptographic keys using `.fill(0)` before garbage collection or unreferencing.
- Components NEVER assume biometric validity persists across app pause/resume events without re-verifying biometric enrollment identity hash or re-authorizing against the hardware enclave.

## Bad vs Good Implementations
### Dynamic Biometric State Verification & SQLCipher Key Zeroization

#### Bad Antipattern (AI Common Hallucination)
> **Why it fails**: The raw cryptographic key is cached as an immutable string on the V8 heap, immune to manual zeroization. Furthermore, the app lifecycle listener ignores background transitions, does not close the database handle, and fails to handle biometric enrollment mutations (e.g., an attacker adding a fingerprint).
```typescript
import { App } from '@capacitor/app';
import { NativeBiometric } from 'capacitor-native-biometric';
import { SQLiteDBConnection } from '@capacitor-community/sqlite';

let cachedDbKey: string | null = null;
let dbHandle: SQLiteDBConnection | null = null;

export async function initSession(db: SQLiteDBConnection): Promise<void> {
  dbHandle = db;
  // Flaw: Unconditionally fetches secret without checking enrollment delta
  const credentials = await NativeBiometric.getCredentials({ server: 'com.app.vault' });
  cachedDbKey = credentials.password;
  await dbHandle.open();
  // Flaw: Key remains in memory indefinitely across lifecycle pauses
}

App.addListener('appStateChange', async (state) => {
  if (!state.isActive) {
    // Flaw: Does not close SQLite handle or shred key buffer on backgrounding
    console.log('App backgrounded');
  }
});
```

#### Production Standard (Correct)
> **Standard**: Cryptographic secrets are managed in mutable `Uint8Array` buffers that are explicitly zeroized using `.fill(0)`. Database handles are closed immediately upon app suspension, and hardware key acquisition rejects if new biometrics were enrolled, triggering an immediate purge.
```typescript
import { App } from '@capacitor/app';
import { SQLiteDBConnection } from '@capacitor-community/sqlite';
import { SecureEnclavePlugin } from './plugins/SecureEnclavePlugin';

class SecureDatabaseManager {
  private keyBuffer: Uint8Array | null = null;
  private db: SQLiteDBConnection | null = null;

  public async unlockDatabase(db: SQLiteDBConnection): Promise<void> {
    this.db = db;
    try {
      // Enforces hardware enclave verification configured with invalidatedByBiometricEnrollment
      const secretBytes = await SecureEnclavePlugin.acquireBiometricKey();
      this.keyBuffer = new Uint8Array(secretBytes);
      
      const hexKey = Array.from(this.keyBuffer).map(b => b.toString(16).padStart(2, '0')).join('');
      await this.db.open();
      await this.db.execute(`PRAGMA key = "x'${hexKey}'";`);
    } catch (error: unknown) {
      await this.purgeVault('KEY_INVALIDATED_OR_MUTATED');
      throw new Error('Biometric state invalidated. Session terminated.');
    }
  }

  public async purgeVault(reason: string): Promise<void> {
    if (this.keyBuffer) {
      this.keyBuffer.fill(0); // Cryptographic zeroization
      this.keyBuffer = null;
    }
    if (this.db) {
      try {
        await this.db.close();
      } catch (err) {
        console.error('Error closing SQLite DB during purge', err);
      }
      this.db = null;
    }
    await SecureEnclavePlugin.invalidateCachedTokens();
  }
}

export const vaultManager = new SecureDatabaseManager();

App.addListener('appStateChange', async (state) => {
  if (!state.isActive) {
    await vaultManager.purgeVault('LIFECYCLE_BACKGROUND');
  }
});
```

Recommended MCP Servers (mcp-serverlist.com)

Equip agent with system tools to verify code for this stack.

Recommended Agent Skills (askills.dev)

Ready-to-use executable skill functions tailored to this stack.

Architectural Specification & Invariant Rationale

Architectural Invariant Design: Capacitor 7 Secure Enclave Dynamic Biometric Invalidation and Database Purge

Capacitor 7 Secure Enclave Dynamic Biometric Invalidation and Database Purge defines an industrial-grade behavioral standard for mobile engineering. Enforces immediate volatile cryptographic key zeroization, Secure Enclave/KeyStore secret invalidation, and SQLite (SQLCipher) handle purging whenever OS-level biometric enrollment changes or lock-screen authentication degrades. Guards against session hijacking caused by unauthorized fingerprint/face enrollment on compromised or shared devices. 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: Persisting Decrypted Encryption Keys in Memory and Ignoring Biometric Enrollment Changes 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 DriftPersisting Decrypted Encryption Keys in Memory and Ignoring Biometric Enrollment ChangesCritical
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 configure hardware-backed keys with `.biometryCurrentSet` (iOS) or `setUserAuthenticationParameters(..., KeyProperties.AUTH_BIOMETRIC_STRONG)` and invalidate them on new enrollment via `setInvalidatedByBiometricEnrollment(true)` (Android).

Engineers MUST ALWAYS configure hardware-backed keys with `.biometryCurrentSet` (iOS) or `setUserAuthenticationParameters(..., KeyProperties.AUTH_BIOMETRIC_STRONG)` and invalidate them on new enrollment via `setInvalidatedByBiometricEnrollment(true)` (Android).

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 NEVER cache plaintext database encryption keys in JavaScript heap variables, `localStorage`, `sessionStorage`, or IndexedDB across app lifecycle boundaries.

Engineers MUST NEVER cache plaintext database encryption keys in JavaScript heap variables, `localStorage`, `sessionStorage`, or IndexedDB across app lifecycle boundaries.

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

Code MUST actively catch hardware cryptographic failure exceptions (e.g., `KeyPermanentlyInvalidatedException` or `errSecAuthFailed`) upon application resume and trigger an immediate emergency vault purge.

Code MUST actively catch hardware cryptographic failure exceptions (e.g., `KeyPermanentlyInvalidatedException` or `errSecAuthFailed`) upon application resume and trigger an immediate emergency vault purge.

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

Services MUST zeroize `Uint8Array` buffers containing raw cryptographic keys using `.fill(0)` before garbage collection or unreferencing.

Services MUST zeroize `Uint8Array` buffers containing raw cryptographic keys using `.fill(0)` before garbage collection or unreferencing.

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 assume biometric validity persists across app pause/resume events without re-verifying biometric enrollment identity hash or re-authorizing against the hardware enclave.

Components NEVER assume biometric validity persists across app pause/resume events without re-verifying biometric enrollment identity hash or re-authorizing against the hardware enclave.

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 Capacitor 7 Secure Enclave Dynamic Biometric Invalidation and Database Purge critical for AI coding assistants?

Enforces immediate volatile cryptographic key zeroization, Secure Enclave/KeyStore secret invalidation, and SQLite (SQLCipher) handle purging whenever OS-level biometric enrollment changes or lock-screen authentication degrades. Guards against session hijacking caused by unauthorized fingerprint/face enrollment on compromised or shared devices. 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 (Persisting Decrypted Encryption Keys in Memory and Ignoring Biometric Enrollment Changes) 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

Capacitor