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

Capacitor 7 Biometric Keychain Hardware Entropy & Integrity Invalidation Guardrail

Mandates that hardware-backed cryptographic keys accessed through Capacitor 7 native bridges strictly bind to active biometric sets (kSecAccessControlBiometryCurrentSet and Android KeyGenParameterSpec auth-bound keys). Enforces immediate Secure Enclave/KeyStore cryptographic key destruction, volatile buffer zeroization, and session termination upon biometric enrollment modifications or root/jailbreak detection.

Prohibited Anti-Pattern: Persisting Unbound Keychain Keys or Retaining Volatile Secrets When Biometrics Mutate or Devices Are Compromised

Export Ready-to-Drop Configuration

Select format below to copy code or download file directly.

---
description: Capacitor 7 Biometric Keychain Hardware Entropy & Integrity Invalidation Guardrail - Mandates that hardware-backed cryptographic keys accessed through Capacitor 7 native bridges strictly bind to active biometric sets (kSecAccessControlBiometryCurrentSet and Android KeyGenParameterSpec auth-bound keys). Enforces immediate Secure Enclave/KeyStore cryptographic key destruction, volatile buffer zeroization, and session termination upon biometric enrollment modifications or root/jailbreak detection.
globs: src/**/*.{ts,tsx}, ios/App/**/*.{swift,m}, android/app/**/*.{kt,java}
alwaysApply: true
verified_by: "agentrules.org"
license: "CC-BY-4.0"
source: "https://agentrules.org/rules/capacitor-7-biometric-keychain-entropy-invalidation"
---

# Capacitor 7 Biometric Keychain Hardware Entropy & Integrity Invalidation Guardrail

> **Severity**: CRITICAL | **Category**: mobile
> **Anti-Pattern Warning**: Persisting Unbound Keychain Keys or Retaining Volatile Secrets When Biometrics Mutate or Devices Are Compromised

## System Constraints
You are a Principal Mobile Security Architect enforcing zero-trust hardware cryptographic invariants in Capacitor 7 applications. You must ensure all sensitive asymmetric/symmetric key pairs stored in the iOS Secure Enclave and Android Hardware KeyStore (TEE/StrongBox) are cryptographically bound to the user's explicit biometric enrollment state. Any alteration to biometric sets (new fingerprint, re-enrolled Face ID) or runtime integrity failure (jailbreak, Magisk/Zygisk hook, Frida instrumentation) must trigger instantaneous key destruction, zeroization of RAM buffers, and irrevocable session termination.

## Strict Guidelines
- Engineers MUST ALWAYS configure native Keychain queries with `kSecAccessControlBiometryCurrentSet` (iOS) and `setInvalidatedByBiometricEnrollment(true)` (Android) to ensure automatic hardware invalidation when biometric state changes.
- Engineers MUST NOT fallback to `kSecAccessControlBiometryAny` or allow device passcode fallbacks for keys securing cryptographic entropy, offline credentials, or non-repudiable auth tokens.
- Services MUST catch platform-specific invalidation errors (`KeyPermanentlyInvalidatedException`, OSStatus `-25293` / `errSecAuthFailed`) and immediately invoke hardware destruction routines across both native and web layers.
- Engineers MUST explicitly zeroize sensitive typed memory arrays (`Uint8Array.fill(0)`) immediately after cryptographic operations rather than relying on ECMAScript garbage collection.
- Components NEVER store master encryption keys, derived keys, or cleartext authentication state inside Capacitor `Preferences`, `@capacitor/storage`, local storage, or indexedDB.
- Mobile security services MUST poll or hook native device attestation and root/jailbreak state checks on app resume (`appStateChange`), terminating the session and purging local enclave keys if compromise is detected.

## Bad vs Good Implementations
### Biometric Hardware Entropy Consumption & Invalidation Handling

#### Bad Antipattern (AI Common Hallucination)
> **Why it fails**: Stores secrets in plain Capacitor Preferences, allows device passcode fallback, does not bind keys to `BiometryCurrentSet`, and leaves raw cryptographic material in the JavaScript engine garbage collection pool.
```typescript
import { Preferences } from '@capacitor/preferences';
import { BiometricAuth } from '@aparajita/capacitor-biometric-auth';

export class SessionSecurityService {
  // Anti-Pattern: Keys are stored in insecure storage without enclave binding,
  // allowing passcodes to bypass hardware entropy changes.
  async retrieveMasterKey(): Promise<string | null> {
    const authResult = await BiometricAuth.verify({
      reason: 'Confirm identity',
      allowDeviceCredential: true // Permissive fallback exposes key after biometric mutation
    });

    if (authResult.verified) {
      const { value } = await Preferences.get({ key: 'app_master_key' });
      return value; // Cleartext secret retained indefinitely in JS heap
    }
    return null;
  }
}
```

#### Production Standard (Correct)
> **Standard**: Binds keys to the native Secure Enclave/KeyStore with explicit `requireBiometryCurrentSet`, traps biometric mutation exceptions, guarantees zeroization of memory buffers, runs integrity checks, and executes complete cryptographic destruction.
```typescript
import { App } from '@capacitor/app';
import { NativeHardwareSecurityPlugin } from './plugins/hardware-security';

export interface SecureKeyBuffer {
  bytes: Uint8Array;
  destroy: () => void;
}

export class BiometricEntropyGuard {
  private static readonly KEY_ALIAS = 'secure_enclave_root_entropy';

  public static async executeWithDecryptedEntropy<T>(
    prompt: string,
    operation: (entropy: Uint8Array) => Promise<T>
  ): Promise<T> {
    // 1. Mandatory runtime integrity check prior to enclave access
    const integrity = await NativeHardwareSecurityPlugin.verifyIntegrity();
    if (integrity.isRootedOrJailbroken || integrity.debuggerAttached) {
      await this.purgeAllCryptographicState('DEVICE_INTEGRITY_COMPROMISED');
      throw new Error('Critical integrity violation: runtime environment compromised.');
    }

    let rawBuffer: Uint8Array | null = null;
    try {
      // 2. Fetch entropy with native BiometryCurrentSet constraint (auto-invalidated on enrollment changes)
      const result = await NativeHardwareSecurityPlugin.retrieveBoundEntropy({
        alias: this.KEY_ALIAS,
        biometricPrompt: prompt,
        requireBiometryCurrentSet: true,
        allowPasscodeFallback: false
      });

      rawBuffer = new Uint8Array(result.entropyBytes);
      return await operation(rawBuffer);
    } catch (error: unknown) {
      const errorMessage = error instanceof Error ? error.message : String(error);
      
      // 3. Catch platform-level invalidation (iOS: errSecAuthFailed, Android: KeyPermanentlyInvalidatedException)
      if (
        errorMessage.includes('KeyPermanentlyInvalidatedException') ||
        errorMessage.includes('errSecAuthFailed') ||
        errorMessage.includes('BIOMETRIC_SET_CHANGED')
      ) {
        await this.purgeAllCryptographicState('BIOMETRIC_ENROLLMENT_MODIFIED');
        throw new Error('Secure Enclave key permanently invalidated due to biometric modification.');
      }
      throw error;
    } finally {
      // 4. Guaranteed zeroization of volatile buffer
      if (rawBuffer) {
        rawBuffer.fill(0);
      }
    }
  }

  public static async purgeAllCryptographicState(reason: string): Promise<void> {
    console.error(`[SECURITY] Purging secure enclave keys. Reason: ${reason}`);
    await NativeHardwareSecurityPlugin.deleteBoundKey({ alias: this.KEY_ALIAS }).catch(() => {});
    await NativeHardwareSecurityPlugin.clearVolatileKeystore().catch(() => {});
    await App.exitApp();
  }
}
```

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 Biometric Keychain Hardware Entropy & Integrity Invalidation Guardrail

Capacitor 7 Biometric Keychain Hardware Entropy & Integrity Invalidation Guardrail defines an industrial-grade behavioral standard for mobile engineering. Mandates that hardware-backed cryptographic keys accessed through Capacitor 7 native bridges strictly bind to active biometric sets (kSecAccessControlBiometryCurrentSet and Android KeyGenParameterSpec auth-bound keys). Enforces immediate Secure Enclave/KeyStore cryptographic key destruction, volatile buffer zeroization, and session termination upon biometric enrollment modifications or root/jailbreak detection. 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 Unbound Keychain Keys or Retaining Volatile Secrets When Biometrics Mutate or Devices Are Compromised 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 Unbound Keychain Keys or Retaining Volatile Secrets When Biometrics Mutate or Devices Are CompromisedCritical
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 native Keychain queries with `kSecAccessControlBiometryCurrentSet` (iOS) and `setInvalidatedByBiometricEnrollment(true)` (Android) to ensure automatic hardware invalidation when biometric state changes.

Engineers MUST ALWAYS configure native Keychain queries with `kSecAccessControlBiometryCurrentSet` (iOS) and `setInvalidatedByBiometricEnrollment(true)` (Android) to ensure automatic hardware invalidation when biometric state changes.

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 fallback to `kSecAccessControlBiometryAny` or allow device passcode fallbacks for keys securing cryptographic entropy, offline credentials, or non-repudiable auth tokens.

Engineers MUST NOT fallback to `kSecAccessControlBiometryAny` or allow device passcode fallbacks for keys securing cryptographic entropy, offline credentials, or non-repudiable auth tokens.

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 catch platform-specific invalidation errors (`KeyPermanentlyInvalidatedException`, OSStatus `-25293` / `errSecAuthFailed`) and immediately invoke hardware destruction routines across both native and web layers.

Services MUST catch platform-specific invalidation errors (`KeyPermanentlyInvalidatedException`, OSStatus `-25293` / `errSecAuthFailed`) and immediately invoke hardware destruction routines across both native and web layers.

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 explicitly zeroize sensitive typed memory arrays (`Uint8Array.fill(0)`) immediately after cryptographic operations rather than relying on ECMAScript garbage collection.

Engineers MUST explicitly zeroize sensitive typed memory arrays (`Uint8Array.fill(0)`) immediately after cryptographic operations rather than relying on ECMAScript garbage collection.

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, derived keys, or cleartext authentication state inside Capacitor `Preferences`, `@capacitor/storage`, local storage, or indexedDB.

Components NEVER store master encryption keys, derived keys, or cleartext authentication state inside Capacitor `Preferences`, `@capacitor/storage`, local storage, or indexedDB.

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

Mobile security services MUST poll or hook native device attestation and root/jailbreak state checks on app resume (`appStateChange`), terminating the session and purging local enclave keys if compromise is detected.

Mobile security services MUST poll or hook native device attestation and root/jailbreak state checks on app resume (`appStateChange`), terminating the session and purging local enclave keys if compromise is detected.

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 Biometric Keychain Hardware Entropy & Integrity Invalidation Guardrail critical for AI coding assistants?

Mandates that hardware-backed cryptographic keys accessed through Capacitor 7 native bridges strictly bind to active biometric sets (kSecAccessControlBiometryCurrentSet and Android KeyGenParameterSpec auth-bound keys). Enforces immediate Secure Enclave/KeyStore cryptographic key destruction, volatile buffer zeroization, and session termination upon biometric enrollment modifications or root/jailbreak detection. 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 Unbound Keychain Keys or Retaining Volatile Secrets When Biometrics Mutate or Devices Are Compromised) 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