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

Capacitor 7 Hardware Keystore Invalidation on Biometric Enrollment Mutation

Enforces strict hardware-backed cryptographic invalidation boundaries for persistent secrets across Capacitor 7 iOS and Android targets. Mandates iOS kSecAccessControlBiometryCurrentSet and Android KeyPermanentlyInvalidatedException traps such that any addition, deletion, or modification of biometric templates permanently destroys the decryption key material and triggers complete client session purge.

Prohibited Anti-Pattern: Persisting Session Secrets with Weak Keychain ACLs or Silently Swallowing Hardware Key Invalidation Exceptions

Export Ready-to-Drop Configuration

Select format below to copy code or download file directly.

---
description: Capacitor 7 Hardware Keystore Invalidation on Biometric Enrollment Mutation - Enforces strict hardware-backed cryptographic invalidation boundaries for persistent secrets across Capacitor 7 iOS and Android targets. Mandates iOS kSecAccessControlBiometryCurrentSet and Android KeyPermanentlyInvalidatedException traps such that any addition, deletion, or modification of biometric templates permanently destroys the decryption key material and triggers complete client session purge.
globs: src/**/*.{ts,tsx}, ios/App/App/**/*.{swift,m}, android/app/src/main/**/*.{kt,java}
alwaysApply: true
verified_by: "agentrules.org"
license: "CC-BY-4.0"
source: "https://agentrules.org/rules/capacitor-biometric-keystore-invalidation-boundary"
---

# Capacitor 7 Hardware Keystore Invalidation on Biometric Enrollment Mutation

> **Severity**: CRITICAL | **Category**: mobile
> **Anti-Pattern Warning**: Persisting Session Secrets with Weak Keychain ACLs or Silently Swallowing Hardware Key Invalidation Exceptions

## System Constraints
You are a Principal Mobile Security Architect enforcing zero-trust hardware boundaries in Capacitor 7 applications. Your directive is to ensure that biometric hardware key storage uses strict OS-level enrollment binding. If device biometrics mutate (new fingerprint added, Face ID reset), any stored key material MUST become irrecoverable at the hardware layer, and the application must deterministically purge session state rather than degrading to insecure authentication or ignoring hardware exceptions.

## Strict Guidelines
- Engineers MUST ALWAYS configure iOS Keychain access controls using `kSecAccessControlBiometryCurrentSet` rather than `kSecAccessControlBiometryAny` to ensure keys are invalidated when enrollments change.
- Engineers MUST ALWAYS set `.setInvalidatedByBiometricEnrollment(true)` explicitly on Android `KeyGenParameterSpec.Builder` when generating MasterKeys or KeyPairs in the Android Keystore.
- Engineers MUST NOT swallow `KeyPermanentlyInvalidatedException` (Android) or `errSecItemNotFound`/`errSecAuthFailed` (iOS) in native plugins or the Capacitor TypeScript bridge.
- Services MUST execute a total security purge (clear local databases, invalidate server tokens via revocation endpoints, destroy state caches) when the hardware keystore signals biometric invalidation.
- Components NEVER store sensitive access or refresh tokens in `@capacitor/preferences`, Web `localStorage`, or IndexedDB without hardware-backed biometric encryption wrappers.

## Bad vs Good Implementations
### Hardware Biometric Keystore Boundary in Capacitor 7 Service

#### Bad Antipattern (AI Common Hallucination)
> **Why it fails**: Decoupling biometric evaluation from cryptographic key unwrapping is fatally flawed. Adding a new fingerprint to the operating system satisfies verifyIdentity(), and the unencrypted Preferences store hands over the token. Furthermore, enrollment changes do not invalidate the token.
```typescript
import { Preferences } from '@capacitor/preferences';
import { NativeBiometric } from 'capacitor-native-biometric';

export class AuthService {
  // ANTI-PATTERN: Verifying biometrics separately from key storage.
  // An attacker adding a fingerprint to the device bypasses security because
  // the token is stored in unauthenticated persistent storage.
  async getSessionToken(): Promise<string | null> {
    try {
      const result = await NativeBiometric.verifyIdentity({
        reason: 'Authenticate to access your account',
      });
      
      if (result) {
        const { value } = await Preferences.get({ key: 'auth_token' });
        return value;
      }
    } catch (e) {
      console.error('Biometric failed, keeping cached token', e);
    }
    return null;
  }
}
```

#### Production Standard (Correct)
> **Standard**: Binds authentication directly to cryptographic decryption in the hardware keystore. When biometric enrollment changes, the operating system's hardware keystore invalidates the key material, throwing a specific error. The service traps this condition and triggers an immediate local security purge.
```typescript
import { SecureStoragePlugin } from './plugins/secureStorage';
import { TelemetryService } from './telemetry';

export interface SecureSessionResult {
  status: 'SUCCESS' | 'BIOMETRICS_INVALIDATED' | 'USER_CANCELED';
  token: string | null;
}

export class SecureAuthVault {
  /**
   * Retrieves token bound directly to Secure Enclave / Android Keystore.
   * Hardware configuration requires:
   * - iOS: SecAccessControlCreateWithFlags(..., kSecAccessControlBiometryCurrentSet, ...)
   * - Android: KeyGenParameterSpec.Builder(..., PURPOSE_DECRYPT).setInvalidatedByBiometricEnrollment(true)
   */
  static async getSessionToken(): Promise<SecureSessionResult> {
    try {
      const decryptedToken = await SecureStoragePlugin.getHardwareKey({
        key: 'session_credential',
        promptMessage: 'Authenticate to access secure enclave',
      });
      return { status: 'SUCCESS', token: decryptedToken };
    } catch (error: any) {
      if (error?.code === 'BIOMETRIC_ENROLLMENT_CHANGED' || error?.code === 'KEY_PERMANENTLY_INVALIDATED') {
        TelemetryService.logSecurityEvent('HARDWARE_KEY_SELF_DESTRUCT_TRIGGERED', { error });
        // Mandatory invariant: Purge local artifacts immediately
        await this.purgeCompromisedSession();
        return { status: 'BIOMETRICS_INVALIDATED', token: null };
      }
      
      if (error?.code === 'USER_CANCELED') {
        return { status: 'USER_CANCELED', token: null };
      }
      
      throw error;
    }
  }

  private static async purgeCompromisedSession(): Promise<void> {
    await SecureStoragePlugin.clearHardwareKeys();
    sessionStorage.clear();
    window.dispatchEvent(new CustomEvent('app:force-reauthentication', {
      detail: { reason: 'BIOMETRIC_TEMPLATE_MUTATION' }
    }));
  }
}
```

Architectural Specification & Invariant Rationale

Architectural Invariant Design: Capacitor 7 Hardware Keystore Invalidation on Biometric Enrollment Mutation

Capacitor 7 Hardware Keystore Invalidation on Biometric Enrollment Mutation defines an industrial-grade behavioral standard for mobile engineering. Enforces strict hardware-backed cryptographic invalidation boundaries for persistent secrets across Capacitor 7 iOS and Android targets. Mandates iOS kSecAccessControlBiometryCurrentSet and Android KeyPermanentlyInvalidatedException traps such that any addition, deletion, or modification of biometric templates permanently destroys the decryption key material and triggers complete client session purge. 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 Session Secrets with Weak Keychain ACLs or Silently Swallowing Hardware Key Invalidation Exceptions 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 Session Secrets with Weak Keychain ACLs or Silently Swallowing Hardware Key Invalidation ExceptionsCritical
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 iOS Keychain access controls using `kSecAccessControlBiometryCurrentSet` rather than `kSecAccessControlBiometryAny` to ensure keys are invalidated when enrollments change.

Engineers MUST ALWAYS configure iOS Keychain access controls using `kSecAccessControlBiometryCurrentSet` rather than `kSecAccessControlBiometryAny` to ensure keys are invalidated when enrollments change.

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 ALWAYS set `.setInvalidatedByBiometricEnrollment(true)` explicitly on Android `KeyGenParameterSpec.Builder` when generating MasterKeys or KeyPairs in the Android Keystore.

Engineers MUST ALWAYS set `.setInvalidatedByBiometricEnrollment(true)` explicitly on Android `KeyGenParameterSpec.Builder` when generating MasterKeys or KeyPairs in the Android Keystore.

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 NOT swallow `KeyPermanentlyInvalidatedException` (Android) or `errSecItemNotFound`/`errSecAuthFailed` (iOS) in native plugins or the Capacitor TypeScript bridge.

Engineers MUST NOT swallow `KeyPermanentlyInvalidatedException` (Android) or `errSecItemNotFound`/`errSecAuthFailed` (iOS) in native plugins or the Capacitor TypeScript bridge.

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 execute a total security purge (clear local databases, invalidate server tokens via revocation endpoints, destroy state caches) when the hardware keystore signals biometric invalidation.

Services MUST execute a total security purge (clear local databases, invalidate server tokens via revocation endpoints, destroy state caches) when the hardware keystore signals biometric invalidation.

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 sensitive access or refresh tokens in `@capacitor/preferences`, Web `localStorage`, or IndexedDB without hardware-backed biometric encryption wrappers.

Components NEVER store sensitive access or refresh tokens in `@capacitor/preferences`, Web `localStorage`, or IndexedDB without hardware-backed biometric encryption wrappers.

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 Hardware Keystore Invalidation on Biometric Enrollment Mutation critical for AI coding assistants?

Enforces strict hardware-backed cryptographic invalidation boundaries for persistent secrets across Capacitor 7 iOS and Android targets. Mandates iOS kSecAccessControlBiometryCurrentSet and Android KeyPermanentlyInvalidatedException traps such that any addition, deletion, or modification of biometric templates permanently destroys the decryption key material and triggers complete client session purge. 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 Session Secrets with Weak Keychain ACLs or Silently Swallowing Hardware Key Invalidation Exceptions) 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