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

Capacitor 7 Biometric Keystore Invalidation & Cryptographic Token Eviction

Enforces immediate application-tier cryptographic token invalidation upon detection of OS-level biometric enrollment state changes (KeyPermanentlyInvalidatedException on Android, errSecAuthFailed/errSecUserCanceled on iOS). Prevents unauthorized access when new biometric identities are enrolled on the host device by ensuring native secure keystore hardware-backed flags invalidate persisted session credentials.

Prohibited Anti-Pattern: Persisting Session Tokens and Fallback Keystores Across OS-Level Biometric State Mutations

Export Ready-to-Drop Configuration

Select format below to copy code or download file directly.

---
description: Capacitor 7 Biometric Keystore Invalidation & Cryptographic Token Eviction - Enforces immediate application-tier cryptographic token invalidation upon detection of OS-level biometric enrollment state changes (KeyPermanentlyInvalidatedException on Android, errSecAuthFailed/errSecUserCanceled on iOS). Prevents unauthorized access when new biometric identities are enrolled on the host device by ensuring native secure keystore hardware-backed flags invalidate persisted session credentials.
globs: src/services/auth/**/*.{ts,tsx}, src/services/storage/**/*.{ts,tsx}, src/plugins/**/*.{ts,tsx}, src/guards/**/*.{ts,tsx}
alwaysApply: true
verified_by: "agentrules.org"
license: "CC-BY-4.0"
source: "https://agentrules.org/rules/capacitor-7-biometric-keystore-invalidation-sync"
---

# Capacitor 7 Biometric Keystore Invalidation & Cryptographic Token Eviction

> **Severity**: CRITICAL | **Category**: mobile
> **Anti-Pattern Warning**: Persisting Session Tokens and Fallback Keystores Across OS-Level Biometric State Mutations

## System Constraints
You are a Principal Mobile Security Engineer enforcing Capacitor 7 Biometric Keystore Invalidation Synchronization. Mandate invariant hardware-backed secure storage tied directly to biometric authentication states. Any mutation in device biometric enrollment (e.g., adding a new fingerprint or face profile) must immediately trigger an unrecoverable hardware key invalidation, cascade to complete application-tier token eviction, clear in-memory credentials, and force re-authentication.

## Strict Guidelines
- Engineers MUST ALWAYS configure native secure storage (Android Keystore / iOS Keychain) with `setUserAuthenticationRequired(true)` and invalidate on biometric enrollment changes (Android `setInvalidatedByBiometricEnrollment(true)`).
- Engineers MUST catch native hardware invalidation errors (`KeyPermanentlyInvalidatedException`, `errSecItemNotFound`, or plugin-specific `BIOMETRIC_STATUS_CHANGED`) and trigger an immediate global session purge.
- Engineers MUST NOT silently catch cryptographic decryption failures and fall back to unauthenticated local storage or plain preferences.
- Services MUST clear all encrypted application state (SQLite databases, IndexedDB encryption keys, access and refresh tokens) upon detecting biometric invalidation.
- Components NEVER store sensitive JWTs or session keys in `@capacitor/preferences` without hardware-backed cryptographic sealing.

## Bad vs Good Implementations
### Biometric Token Decryption with Invalidation Cascade vs Silent Fallback

#### Bad Antipattern (AI Common Hallucination)
> **Why it fails**: Decouples biometric prompt verification from actual cryptographic key material. An attacker adding a new fingerprint can authenticate or bypass the prompt entirely because the token is stored unencrypted in Preferences, violating OS-level biometric invalidation guarantees.
```typescript
import { NativeBiometric } from 'capacitor-native-biometric';
import { Preferences } from '@capacitor/preferences';

export class AuthService {
  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;
      }
      return null;
    } catch (error) {
      // Flawed: Biometric changes or failures silently fall back to unencrypted storage
      console.warn('Biometric failed, attempting fallback', error);
      const { value } = await Preferences.get({ key: 'auth_token_fallback' });
      return value;
    }
  }
}
```

#### Production Standard (Correct)
> **Standard**: Binds secret retrieval directly to native hardware keystore decryption configured to invalidate upon biometric changes. Catches explicit OS invalidation exceptions, executes proactive credential destruction, and broadcasts a global session eviction event.
```typescript
import { NativeBiometric, BiometricOptions } from 'capacitor-native-biometric';
import { AppEventEmitter } from '../events/app-events';

export class AuthService {
  private static readonly CREDENTIALS_SERVER = 'com.enterprise.app.auth';

  async getSessionToken(): Promise<string> {
    try {
      const credentials = await NativeBiometric.getCredentials({
        server: AuthService.CREDENTIALS_SERVER,
      });
      return credentials.password;
    } catch (error: unknown) {
      const errMessage = error instanceof Error ? error.message : String(error);
      
      // Detect hardware-level biometric enrollment mutation or permanent key invalidation
      if (
        errMessage.includes('KeyPermanentlyInvalidatedException') ||
        errMessage.includes('BIOMETRIC_KEYS_INVALIDATED') ||
        errMessage.includes('errSecAuthFailed')
      ) {
        await this.handleBiometricTamperOrInvalidation();
      }
      throw new Error(`Secure keystore access denied: ${errMessage}`);
    }
  }

  private async handleBiometricTamperOrInvalidation(): Promise<void> {
    // Purge hardware-backed credentials and notify application core
    await NativeBiometric.deleteCredentials({
      server: AuthService.CREDENTIALS_SERVER,
    }).catch(() => {});
    
    AppEventEmitter.emit('SESSION_REVOKED_BIOMETRIC_INVALIDATION');
  }
}
```

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 Keystore Invalidation & Cryptographic Token Eviction

Capacitor 7 Biometric Keystore Invalidation & Cryptographic Token Eviction defines an industrial-grade behavioral standard for mobile engineering. Enforces immediate application-tier cryptographic token invalidation upon detection of OS-level biometric enrollment state changes (KeyPermanentlyInvalidatedException on Android, errSecAuthFailed/errSecUserCanceled on iOS). Prevents unauthorized access when new biometric identities are enrolled on the host device by ensuring native secure keystore hardware-backed flags invalidate persisted session credentials. 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 Tokens and Fallback Keystores Across OS-Level Biometric State Mutations 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 Tokens and Fallback Keystores Across OS-Level Biometric State MutationsCritical
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 secure storage (Android Keystore / iOS Keychain) with `setUserAuthenticationRequired(true)` and invalidate on biometric enrollment changes (Android `setInvalidatedByBiometricEnrollment(true)`).

Engineers MUST ALWAYS configure native secure storage (Android Keystore / iOS Keychain) with `setUserAuthenticationRequired(true)` and invalidate on biometric enrollment changes (Android `setInvalidatedByBiometricEnrollment(true)`).

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 catch native hardware invalidation errors (`KeyPermanentlyInvalidatedException`, `errSecItemNotFound`, or plugin-specific `BIOMETRIC_STATUS_CHANGED`) and trigger an immediate global session purge.

Engineers MUST catch native hardware invalidation errors (`KeyPermanentlyInvalidatedException`, `errSecItemNotFound`, or plugin-specific `BIOMETRIC_STATUS_CHANGED`) and trigger an immediate global session purge.

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 silently catch cryptographic decryption failures and fall back to unauthenticated local storage or plain preferences.

Engineers MUST NOT silently catch cryptographic decryption failures and fall back to unauthenticated local storage or plain preferences.

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 clear all encrypted application state (SQLite databases, IndexedDB encryption keys, access and refresh tokens) upon detecting biometric invalidation.

Services MUST clear all encrypted application state (SQLite databases, IndexedDB encryption keys, access and refresh tokens) upon detecting 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 JWTs or session keys in `@capacitor/preferences` without hardware-backed cryptographic sealing.

Components NEVER store sensitive JWTs or session keys in `@capacitor/preferences` without hardware-backed cryptographic sealing.

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 Keystore Invalidation & Cryptographic Token Eviction critical for AI coding assistants?

Enforces immediate application-tier cryptographic token invalidation upon detection of OS-level biometric enrollment state changes (KeyPermanentlyInvalidatedException on Android, errSecAuthFailed/errSecUserCanceled on iOS). Prevents unauthorized access when new biometric identities are enrolled on the host device by ensuring native secure keystore hardware-backed flags invalidate persisted session credentials. 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 Tokens and Fallback Keystores Across OS-Level Biometric State Mutations) 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