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-key-invalidation-standard

Capacitor 7 Biometric Hardware Key Invalidation on OS Enrollment Mutation

Enforces automatic hardware-backed cryptographic key invalidation across iOS Secure Enclave and Android KeyStore when any OS biometric enrollment state changes. Prevents unauthorized credential replay and token reuse if an adversary or secondary user registers a new biometric identity on the host device. Mandates strict lifecycle handling of invalidated key errors with forced re-authentication and session revocation.

Prohibited Anti-Pattern: Bypassing hardware-enforced biometric enrollment invalidation flags and persisting stale session tokens

Export Ready-to-Drop Configuration

Select format below to copy code or download file directly.

---
description: Capacitor 7 Biometric Hardware Key Invalidation on OS Enrollment Mutation - Enforces automatic hardware-backed cryptographic key invalidation across iOS Secure Enclave and Android KeyStore when any OS biometric enrollment state changes. Prevents unauthorized credential replay and token reuse if an adversary or secondary user registers a new biometric identity on the host device. Mandates strict lifecycle handling of invalidated key errors with forced re-authentication and session revocation.
globs: src/**/*.{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-key-invalidation-standard"
---

# Capacitor 7 Biometric Hardware Key Invalidation on OS Enrollment Mutation

> **Severity**: CRITICAL | **Category**: mobile
> **Anti-Pattern Warning**: Bypassing hardware-enforced biometric enrollment invalidation flags and persisting stale session tokens

## System Constraints
You are a Principal Mobile Security Architect enforcing the Capacitor 7 Biometric Secure Enclave Key Invalidation Standard. Mandate that all cryptographic keys stored via native plugins leverage hardware flags (`kSecAccessControlBiometryCurrentSet` on iOS and `setInvalidatedByBiometricEnrollment(true)` on Android KeyStore). Ensure that any key invalidation exception (such as `KeyPermanentlyInvalidatedException` or `errSecAuthFailed`) immediately destroys local volatile tokens, terminates server sessions, and initiates a clean re-enrollment handshake.

## Strict Guidelines
- Engineers MUST ALWAYS configure hardware key generation with OS flags that bind the key strictly to the current biometric enrollment set (`kSecAccessControlBiometryCurrentSet` on iOS, `setInvalidatedByBiometricEnrollment(true)` on Android).
- Engineers MUST NOT rely on high-level JavaScript biometric prompt success flags alone without validating cryptographic signature or decryption against hardware-bound keys.
- Services MUST catch OS-level key invalidation errors (e.g., `KeyPermanentlyInvalidatedException`, `errSecItemNotFound`, or plugin-specific `KEY_INVALIDATED` errors) and invoke explicit credential purge workflows.
- Code SHOULD enforce complete revocation of server-side refresh tokens and device registration bindings whenever a local hardware key reports invalidation.
- Components NEVER continue local auth flows using fallback plaintext storage or cached session cookies when biometric key decryption fails due to enrollment changes.

## Bad vs Good Implementations
### Hardware Biometric Key Signing with Explicit Invalidation Handling

#### Bad Antipattern (AI Common Hallucination)
> **Why it fails**: This implementation relies solely on a UI biometric challenge prompt and un-invalidated storage. Adding an unauthorized fingerprint or face to the device settings will still yield a successful prompt and expose the token, violating hardware enrollment binding guarantees.
```typescript
import { NativeBiometric } from 'capacitor-native-biometric';

export async function authenticateAndSign(challenge: string): Promise<string | null> {
  // Anti-pattern: High-level prompt verification without enrollment change invalidation
  const verified = await NativeBiometric.verifyIdentity({
    reason: 'Authenticate to access wallet',
    useFallback: true // Permits PIN fallback without hardware key binding
  });

  if (verified) {
    // Insecure: Using persistent un-invalidated key from storage
    return localStorage.getItem('user_auth_token');
  }
  return null;
}
```

#### Production Standard (Correct)
> **Standard**: The good pattern requests cryptographic operations bound to the current biometric enrollment set. If any biometric template is added or altered in OS settings, the hardware controller permanently invalidates the key. The catch block detects this specific hardware error and executes mandatory session purge and revocation.
```typescript
import { SecureStoragePlugin } from 'capacitor-secure-storage-plugin';

export interface BiometricAuthResult {
  status: 'authenticated' | 'invalidated' | 'failed';
  signature?: string;
}

export async function signWithEnclaveKey(payload: string): Promise<BiometricAuthResult> {
  try {
    // Secure: Hardware-backed operation bound to CurrentBiometricSet
    const signature = await SecureStoragePlugin.signPayloadWithBiometricKey({
      alias: 'com.app.biometric.signing.key',
      data: payload,
      // Android: setInvalidatedByBiometricEnrollment(true)
      // iOS: .biometryCurrentSet access control
      invalidateOnEnrollmentChange: true,
      promptTitle: 'Authorize Transaction'
    });
    return { status: 'authenticated', signature };
  } catch (error: unknown) {
    const errCode = (error as { code?: string })?.code;
    if (errCode === 'BIOMETRIC_KEY_INVALIDATED' || errCode === 'KeyPermanentlyInvalidatedException') {
      // Hard invariant: Invalidate session remotely and purge volatile state
      await SecureStoragePlugin.removeKey({ alias: 'com.app.biometric.signing.key' });
      await fetch('/api/v1/auth/revoke-device', { method: 'POST' });
      return { status: 'invalidated' };
    }
    return { status: 'failed' };
  }
}
```

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 Hardware Key Invalidation on OS Enrollment Mutation

Capacitor 7 Biometric Hardware Key Invalidation on OS Enrollment Mutation defines an industrial-grade behavioral standard for mobile engineering. Enforces automatic hardware-backed cryptographic key invalidation across iOS Secure Enclave and Android KeyStore when any OS biometric enrollment state changes. Prevents unauthorized credential replay and token reuse if an adversary or secondary user registers a new biometric identity on the host device. Mandates strict lifecycle handling of invalidated key errors with forced re-authentication and session revocation. 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: Bypassing hardware-enforced biometric enrollment invalidation flags and persisting stale session tokens 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 DriftBypassing hardware-enforced biometric enrollment invalidation flags and persisting stale session tokensCritical
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 key generation with OS flags that bind the key strictly to the current biometric enrollment set (`kSecAccessControlBiometryCurrentSet` on iOS, `setInvalidatedByBiometricEnrollment(true)` on Android).

Engineers MUST ALWAYS configure hardware key generation with OS flags that bind the key strictly to the current biometric enrollment set (`kSecAccessControlBiometryCurrentSet` on iOS, `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.
2

Engineers MUST NOT rely on high-level JavaScript biometric prompt success flags alone without validating cryptographic signature or decryption against hardware-bound keys.

Engineers MUST NOT rely on high-level JavaScript biometric prompt success flags alone without validating cryptographic signature or decryption against hardware-bound 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.
3

Services MUST catch OS-level key invalidation errors (e.g., `KeyPermanentlyInvalidatedException`, `errSecItemNotFound`, or plugin-specific `KEY_INVALIDATED` errors) and invoke explicit credential purge workflows.

Services MUST catch OS-level key invalidation errors (e.g., `KeyPermanentlyInvalidatedException`, `errSecItemNotFound`, or plugin-specific `KEY_INVALIDATED` errors) and invoke explicit credential purge workflows.

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

Code SHOULD enforce complete revocation of server-side refresh tokens and device registration bindings whenever a local hardware key reports invalidation.

Code SHOULD enforce complete revocation of server-side refresh tokens and device registration bindings whenever a local hardware key reports 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 continue local auth flows using fallback plaintext storage or cached session cookies when biometric key decryption fails due to enrollment changes.

Components NEVER continue local auth flows using fallback plaintext storage or cached session cookies when biometric key decryption fails due to enrollment 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.
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 Hardware Key Invalidation on OS Enrollment Mutation critical for AI coding assistants?

Enforces automatic hardware-backed cryptographic key invalidation across iOS Secure Enclave and Android KeyStore when any OS biometric enrollment state changes. Prevents unauthorized credential replay and token reuse if an adversary or secondary user registers a new biometric identity on the host device. Mandates strict lifecycle handling of invalidated key errors with forced re-authentication and session revocation. 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 (Bypassing hardware-enforced biometric enrollment invalidation flags and persisting stale session tokens) 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