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

Capacitor 7 Biometric Enrollment Drift & Enclave Token Invalidation

Enforces hardware-backed cryptographic binding of Secure Enclave and Android Keystore authentication tokens to the active biometric enrollment state in Capacitor 7 applications. Guarantees that any addition or deletion of biometric records at the OS level immediately invalidates decryption keys, terminating compromised local sessions and triggering remote token revocation.

Prohibited Anti-Pattern: Relying on Stateless Software Biometric Prompts Without Hardware Key Mutation Invalidation

Export Ready-to-Drop Configuration

Select format below to copy code or download file directly.

---
description: Capacitor 7 Biometric Enrollment Drift & Enclave Token Invalidation - Enforces hardware-backed cryptographic binding of Secure Enclave and Android Keystore authentication tokens to the active biometric enrollment state in Capacitor 7 applications. Guarantees that any addition or deletion of biometric records at the OS level immediately invalidates decryption keys, terminating compromised local sessions and triggering remote token revocation.
globs: src/**/*.{ts,tsx}, android/app/src/main/java/**/*.kt, ios/App/App/**/*.swift
alwaysApply: true
verified_by: "agentrules.org"
license: "CC-BY-4.0"
source: "https://agentrules.org/rules/capacitor-7-biometric-enrollment-drift-invalidation"
---

# Capacitor 7 Biometric Enrollment Drift & Enclave Token Invalidation

> **Severity**: CRITICAL | **Category**: mobile
> **Anti-Pattern Warning**: Relying on Stateless Software Biometric Prompts Without Hardware Key Mutation Invalidation

## System Constraints
You are a Principal Mobile Security Architect enforcing hardware-backed biometric security in Capacitor 7 applications. You must ensure that biometric authentication is cryptographically bound to the Secure Enclave (iOS) and Android Keystore using mutation-invalidating access controls (kSecAccessControlBiometryCurrentSet and setInvalidatedByBiometricEnrollment(true)). Stateless software-only prompts that merely gate storage lookups without hardware-enforced enrollment invalidation are strictly forbidden.

## Strict Guidelines
- Engineers MUST ALWAYS bind biometric cryptographic keys using hardware-enforced mutation flags: 'kSecAccessControlBiometryCurrentSet' on iOS and 'setInvalidatedByBiometricEnrollment(true)' on Android.
- Engineers MUST NOT rely on boolean prompt results (e.g., NativeBiometric.verifyIdentity()) to conditionally release unencrypted or loosely secured refresh tokens from Preferences or standard Storage.
- Code MUST explicitly handle hardware invalidation errors (e.g., 'KeyPermanentlyInvalidatedException' on Android, 'errSecItemNotFound' / ACL invalidation on iOS) as high-severity security drift events.
- Services MUST execute an immediate local and remote session teardown upon catching key invalidation: notify backend API to revoke refresh tokens, purge local encrypted caches, and direct user to primary credential step-up authentication.
- Components NEVER store master session secrets under standard 'kSecAttrAccessibleAfterFirstUnlock' or Android SharedPreferences without biometric hardware signature/decryption wrapping.

## Bad vs Good Implementations
### Capacitor 7 Hardware-Bound Biometric Token Decryption with Drift Invalidation Handling

#### Bad Antipattern (AI Common Hallucination)
> **Why it fails**: The check is decoupled from cryptographic operations in the Secure Enclave/Keystore. If a rogue fingerprint is enrolled via the OS settings with a shoulder-surfed passcode, verifyIdentity() passes and exposes the session token.
```typescript
import { NativeBiometric } from 'capacitor-native-biometric';
import { Preferences } from '@capacitor/preferences';

// VULNERABILITY: An attacker who knows device PIN can enroll a rogue fingerprint.
// This boolean check passes for ANY enrolled biometric on the device.
// The stored token was not encrypted with a hardware key tied to the biometric set.
export async function getSessionTokenVulnerable(): Promise<string | null> {
  const verified = await NativeBiometric.verifyIdentity({
    reason: 'Authenticate to access banking',
    title: 'Biometric Login',
  }).then(() => true).catch(() => false);

  if (verified) {
    const { value } = await Preferences.get({ key: 'auth_token' });
    return value;
  }
  return null;
}
```

#### Production Standard (Correct)
> **Standard**: The token is encrypted with a key configured to be irrevocably destroyed by the hardware enclave if biometrics are added, altered, or deleted at the OS level. Caught drift immediately purges local secrets and executes server revocation.
```typescript
import { SecureStoragePlugin } from './plugins/secure-storage';
import { AuthService } from './services/auth.service';
import { Router } from './services/router';

export interface BiometricAuthResult {
  token: string | null;
  driftDetected: boolean;
}

export async function retrieveHardwareBoundToken(): Promise<BiometricAuthResult> {
  try {
    // Native plugin must use kSecAccessControlBiometryCurrentSet (iOS) 
    // and KeyGenParameterSpec.Builder.setInvalidatedByBiometricEnrollment(true) (Android)
    const token = await SecureStoragePlugin.getSecret({
      key: 'auth_refresh_token',
      biometricPrompt: 'Authenticate to access your account',
      invalidateOnEnrollmentMutation: true,
    });
    
    return { token, driftDetected: false };
  } catch (error: unknown) {
    const err = error as { code?: string; message?: string };
    
    // Detect hardware enclave token invalidation caused by new OS-level biometric enrollment
    if (
      err.code === 'KEY_PERMANENTLY_INVALIDATED' ||
      err.message?.includes('KeyPermanentlyInvalidatedException') ||
      err.code === 'BIOMETRY_SET_CHANGED'
    ) {
      console.error('[SECURITY] Biometric enrollment drift detected. Invalidating local session.');
      
      // Immediately revoke remote session and purge local secure storage
      await AuthService.revokeRemoteSession().catch(() => {});
      await SecureStoragePlugin.clear().catch(() => {});
      
      Router.navigate('/login', {
        state: { error: 'Biometric records changed. Re-authenticate with your primary password.' },
      });
      
      return { token: null, driftDetected: true };
    }
    
    throw error;
  }
}
```

Architectural Specification & Invariant Rationale

Architectural Invariant Design: Capacitor 7 Biometric Enrollment Drift & Enclave Token Invalidation

Capacitor 7 Biometric Enrollment Drift & Enclave Token Invalidation defines an industrial-grade behavioral standard for mobile engineering. Enforces hardware-backed cryptographic binding of Secure Enclave and Android Keystore authentication tokens to the active biometric enrollment state in Capacitor 7 applications. Guarantees that any addition or deletion of biometric records at the OS level immediately invalidates decryption keys, terminating compromised local sessions and triggering remote token 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: Relying on Stateless Software Biometric Prompts Without Hardware Key Mutation Invalidation 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 DriftRelying on Stateless Software Biometric Prompts Without Hardware Key Mutation InvalidationCritical
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 bind biometric cryptographic keys using hardware-enforced mutation flags

Engineers MUST ALWAYS bind biometric cryptographic keys using hardware-enforced mutation flags: '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.
2

Engineers MUST NOT rely on boolean prompt results (e.g., NativeBiometric.verifyIdentity()) to conditionally release unencrypted or loosely secured refresh tokens from Preferences or standard Storage.

Engineers MUST NOT rely on boolean prompt results (e.g., NativeBiometric.verifyIdentity()) to conditionally release unencrypted or loosely secured refresh tokens from Preferences or standard Storage.

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 explicitly handle hardware invalidation errors (e.g., 'KeyPermanentlyInvalidatedException' on Android, 'errSecItemNotFound' / ACL invalidation on iOS) as high-severity security drift events.

Code MUST explicitly handle hardware invalidation errors (e.g., 'KeyPermanentlyInvalidatedException' on Android, 'errSecItemNotFound' / ACL invalidation on iOS) as high-severity security drift events.

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 an immediate local and remote session teardown upon catching key invalidation

Services MUST execute an immediate local and remote session teardown upon catching key invalidation: notify backend API to revoke refresh tokens, purge local encrypted caches, and direct user to primary credential step-up authentication.

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 session secrets under standard 'kSecAttrAccessibleAfterFirstUnlock' or Android SharedPreferences without biometric hardware signature/decryption wrapping.

Components NEVER store master session secrets under standard 'kSecAttrAccessibleAfterFirstUnlock' or Android SharedPreferences without biometric hardware signature/decryption wrapping.

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 Enrollment Drift & Enclave Token Invalidation critical for AI coding assistants?

Enforces hardware-backed cryptographic binding of Secure Enclave and Android Keystore authentication tokens to the active biometric enrollment state in Capacitor 7 applications. Guarantees that any addition or deletion of biometric records at the OS level immediately invalidates decryption keys, terminating compromised local sessions and triggering remote token 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 (Relying on Stateless Software Biometric Prompts Without Hardware Key Mutation Invalidation) 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