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

Hardware-Backed Biometric Enclave Key Binding & Re-Authentication Invariant

High-entropy cryptographic keys, access tokens, and signing secrets in Capacitor 7 applications must be strictly bound to hardware-backed security modules (Apple Secure Enclave via SecAccessControl and Android KeyStore via StrongBox Keymaster) with mandatory per-use or short-window biometric presence. Web-layer persistence stores (localStorage, IndexedDB) or software-backed Keychain/Keystore fallback without explicit user re-authentication invariants permit zero-day sandbox exfiltration and are strictly prohibited.

Prohibited Anti-Pattern: Persisting Sensitive Cryptographic Material in Insecure Webviews or Software Keychains Without Biometric Hardware Binding

Export Ready-to-Drop Configuration

Select format below to copy code or download file directly.

---
description: Hardware-Backed Biometric Enclave Key Binding & Re-Authentication Invariant - High-entropy cryptographic keys, access tokens, and signing secrets in Capacitor 7 applications must be strictly bound to hardware-backed security modules (Apple Secure Enclave via SecAccessControl and Android KeyStore via StrongBox Keymaster) with mandatory per-use or short-window biometric presence. Web-layer persistence stores (localStorage, IndexedDB) or software-backed Keychain/Keystore fallback without explicit user re-authentication invariants permit zero-day sandbox exfiltration and are strictly prohibited.
globs: src/services/**/*.{ts,tsx}, src/crypto/**/*.{ts,tsx}, src/auth/**/*.{ts,tsx}, ios/App/App/**/*.{swift,m}, android/app/src/main/java/**/*.{java,kt}
alwaysApply: true
verified_by: "agentrules.org"
license: "CC-BY-4.0"
source: "https://agentrules.org/rules/capacitor-7-biometric-secure-enclave-keychain-invariant"
---

# Hardware-Backed Biometric Enclave Key Binding & Re-Authentication Invariant

> **Severity**: CRITICAL | **Category**: mobile
> **Anti-Pattern Warning**: Persisting Sensitive Cryptographic Material in Insecure Webviews or Software Keychains Without Biometric Hardware Binding

## System Constraints
You are a Principal Mobile Security Architect enforcing the Capacitor 7 Biometric-Bound Secure Enclave Keychain Invariant. You must reject any code storing sensitive session keys, private keys, or refresh tokens in insecure web storage (localStorage, IndexedDB, @capacitor/preferences) or unconstrained software keychains. Mandate that every cryptographic secret is stored via an abstraction leveraging SecAccessControl (kSecAccessControlBiometryAny/CurrentSet) on iOS and Android Keystore with setUserAuthenticationRequired(true) on Android, ensuring that cryptographic operations fail immediately if biometric verification is bypassed or compromised.

## Strict Guidelines
- Engineers MUST ALWAYS enforce hardware-backed key generation and storage using native plugins that utilize kSecAccessControlBiometryCurrentSet or kSecAccessControlUserPresence on iOS and KeyGenParameterSpec.Builder with setUserAuthenticationRequired(true) on Android.
- Engineers MUST NOT persist cryptographic private keys, passkeys, high-entropy API tokens, or mTLS identities in localStorage, IndexedDB, Capacitor Preferences (@capacitor/preferences), or plain SQLite databases.
- Engineers MUST ALWAYS invalidate cryptographic keys or tokens when biometric enrollment changes (e.g., new fingerprints or facial vectors registered) by enforcing kSecAccessControlBiometryCurrentSet on iOS and setInvalidatedByBiometricEnrollment(true) on Android.
- Services MUST NEVER cache decrypted key material in JavaScript memory longer than the lifecycle of the immediate signing or decryption operation.
- Components and Native bridges MUST handle BiometricAuthError (user canceled, lockout, hardware unavailable) gracefully without falling back to unencrypted or unauthenticated storage alternatives.
- Code SHOULD verify hardware-backed module availability (e.g., Secure Enclave / StrongBox) at app runtime initialization prior to generating root identity keys.

## Bad vs Good Implementations
### Insecure Web/Preferences Storage vs. Hardware-Bound Biometric Enclave Native Storage

#### Bad Antipattern (AI Common Hallucination)
> **Why it fails**: Storing cryptographic secrets or auth tokens in @capacitor/preferences leaves them vulnerable to extraction via backup inspection, rooted/jailbroken file systems, or WebKit sandbox exploits. It entirely lacks hardware Secure Enclave binding and requires no biometric verification to access.
```typescript
import { Preferences } from '@capacitor/preferences';

export class AuthService {
  // VULNERABLE: Stores raw high-entropy signing key in plain-text/unprotected sandbox preferences
  async saveSigningKey(privateKeyPem: string): Promise<void> {
    await Preferences.set({
      key: 'user_signing_key',
      value: privateKeyPem
    });
  }

  async signPayload(payload: string): Promise<string> {
    const { value } = await Preferences.get({ key: 'user_signing_key' });
    if (!value) throw new Error('Key not found');
    // Vulnerable: Key is accessible to any script injection or physical sandbox extraction
    return `signed-${payload}-with-${value}`;
  }
}
```

#### Production Standard (Correct)
> **Standard**: Private keys never cross the WebKit/JS bridge into memory. The native plugin creates an asymmetric keypair inside the hardware Secure Enclave / KeyStore with biometric constraints. Any signing operation triggers a hardware-managed biometric prompt, rendering sandbox exfiltration attacks useless.
```typescript
import { registerPlugin } from '@capacitor/core';

export interface SecureEnclavePlugin {
  generateEnclaveKey(options: { alias: string; requireBiometry: boolean }): Promise<{ publicKey: string }>;
  signWithEnclave(options: { alias: string; dataToSign: string; prompt: string }): Promise<{ signature: string }>;
  isHardwareBackedAvailable(): Promise<{ secureEnclave: boolean; strongBox: boolean }>;
}

const SecureEnclave = registerPlugin<SecureEnclavePlugin>('SecureEnclave');

export class EnclaveAuthService {
  private readonly KEY_ALIAS = 'app_signing_identity_v1';

  async initializeIdentity(): Promise<string> {
    const hardware = await SecureEnclave.isHardwareBackedAvailable();
    if (!hardware.secureEnclave && !hardware.strongBox) {
      throw new Error('Hardware-backed Secure Enclave / StrongBox unavailable on this device.');
    }

    // Enforces native SecAccessControl (iOS) / KeyGenParameterSpec with setUserAuthenticationRequired (Android)
    const { publicKey } = await SecureEnclave.generateEnclaveKey({
      alias: this.KEY_ALIAS,
      requireBiometry: true
    });
    return publicKey;
  }

  async signPayload(payload: string): Promise<string> {
    // Native layer prompts for biometric presence; secret key never enters the JS bridge or memory space
    const { signature } = await SecureEnclave.signWithEnclave({
      alias: this.KEY_ALIAS,
      dataToSign: payload,
      prompt: 'Authenticate to authorize cryptographic operation'
    });
    return signature;
  }
}
```

Architectural Specification & Invariant Rationale

Architectural Invariant Design: Hardware-Backed Biometric Enclave Key Binding & Re-Authentication Invariant

Hardware-Backed Biometric Enclave Key Binding & Re-Authentication Invariant defines an industrial-grade behavioral standard for mobile engineering. High-entropy cryptographic keys, access tokens, and signing secrets in Capacitor 7 applications must be strictly bound to hardware-backed security modules (Apple Secure Enclave via SecAccessControl and Android KeyStore via StrongBox Keymaster) with mandatory per-use or short-window biometric presence. Web-layer persistence stores (localStorage, IndexedDB) or software-backed Keychain/Keystore fallback without explicit user re-authentication invariants permit zero-day sandbox exfiltration and are strictly prohibited. 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 Sensitive Cryptographic Material in Insecure Webviews or Software Keychains Without Biometric Hardware Binding 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 Sensitive Cryptographic Material in Insecure Webviews or Software Keychains Without Biometric Hardware BindingCritical
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 enforce hardware-backed key generation and storage using native plugins that utilize kSecAccessControlBiometryCurrentSet or kSecAccessControlUserPresence on iOS and KeyGenParameterSpec.Builder with setUserAuthenticationRequired(true) on Android.

Engineers MUST ALWAYS enforce hardware-backed key generation and storage using native plugins that utilize kSecAccessControlBiometryCurrentSet or kSecAccessControlUserPresence on iOS and KeyGenParameterSpec.Builder with setUserAuthenticationRequired(true) on 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 NOT persist cryptographic private keys, passkeys, high-entropy API tokens, or mTLS identities in localStorage, IndexedDB, Capacitor Preferences (@capacitor/preferences), or plain SQLite databases.

Engineers MUST NOT persist cryptographic private keys, passkeys, high-entropy API tokens, or mTLS identities in localStorage, IndexedDB, Capacitor Preferences (@capacitor/preferences), or plain SQLite databases.

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

Engineers MUST ALWAYS invalidate cryptographic keys or tokens when biometric enrollment changes (e.g., new fingerprints or facial vectors registered) by enforcing kSecAccessControlBiometryCurrentSet on iOS and setInvalidatedByBiometricEnrollment(true) on Android.

Engineers MUST ALWAYS invalidate cryptographic keys or tokens when biometric enrollment changes (e.g., new fingerprints or facial vectors registered) by enforcing kSecAccessControlBiometryCurrentSet on iOS and setInvalidatedByBiometricEnrollment(true) on 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.
4

Services MUST NEVER cache decrypted key material in JavaScript memory longer than the lifecycle of the immediate signing or decryption operation.

Services MUST NEVER cache decrypted key material in JavaScript memory longer than the lifecycle of the immediate signing or decryption operation.

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 and Native bridges MUST handle BiometricAuthError (user canceled, lockout, hardware unavailable) gracefully without falling back to unencrypted or unauthenticated storage alternatives.

Components and Native bridges MUST handle BiometricAuthError (user canceled, lockout, hardware unavailable) gracefully without falling back to unencrypted or unauthenticated storage alternatives.

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

Code SHOULD verify hardware-backed module availability (e.g., Secure Enclave / StrongBox) at app runtime initialization prior to generating root identity keys.

Code SHOULD verify hardware-backed module availability (e.g., Secure Enclave / StrongBox) at app runtime initialization prior to generating root identity keys.

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-Backed Biometric Enclave Key Binding & Re-Authentication Invariant critical for AI coding assistants?

High-entropy cryptographic keys, access tokens, and signing secrets in Capacitor 7 applications must be strictly bound to hardware-backed security modules (Apple Secure Enclave via SecAccessControl and Android KeyStore via StrongBox Keymaster) with mandatory per-use or short-window biometric presence. Web-layer persistence stores (localStorage, IndexedDB) or software-backed Keychain/Keystore fallback without explicit user re-authentication invariants permit zero-day sandbox exfiltration and are strictly prohibited. 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 Sensitive Cryptographic Material in Insecure Webviews or Software Keychains Without Biometric Hardware Binding) 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-Backed