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

Capacitor 7 Hardware-Backed Keystore Invalidation Standard

Enforces hardware-backed cryptographic key invalidation across iOS Secure Enclave and Android KeyStore whenever device biometric enrollments change. Mandates kSecAccessControlBiometryCurrentSet on iOS and setInvalidatedByBiometricEnrollment(true) on Android to prevent rogue biometric additions from decrypting persisted session tokens. Requires deterministic detection of permanent key invalidation errors with mandatory local secret eviction and re-authentication workflows in Capacitor 7 plugins.

Prohibited Anti-Pattern: Permitting Persistent Secret Access Across Biometric Enrollment Changes via BiometryAny or Unconstrained Keystore Flags

Export Ready-to-Drop Configuration

Select format below to copy code or download file directly.

---
description: Capacitor 7 Hardware-Backed Keystore Invalidation Standard - Enforces hardware-backed cryptographic key invalidation across iOS Secure Enclave and Android KeyStore whenever device biometric enrollments change. Mandates kSecAccessControlBiometryCurrentSet on iOS and setInvalidatedByBiometricEnrollment(true) on Android to prevent rogue biometric additions from decrypting persisted session tokens. Requires deterministic detection of permanent key invalidation errors with mandatory local secret eviction and re-authentication workflows in Capacitor 7 plugins.
globs: android/app/src/main/**/*.kt, android/app/src/main/**/*.java, ios/App/App/**/*.swift, src/services/**/*.{ts,tsx}, src/plugins/**/*.{ts,tsx}
alwaysApply: true
verified_by: "agentrules.org"
license: "CC-BY-4.0"
source: "https://agentrules.org/rules/capacitor-7-biometric-keystore-invalidation"
---

# Capacitor 7 Hardware-Backed Keystore Invalidation Standard

> **Severity**: CRITICAL | **Category**: mobile
> **Anti-Pattern Warning**: Permitting Persistent Secret Access Across Biometric Enrollment Changes via BiometryAny or Unconstrained Keystore Flags

## System Constraints
You are a Principal Mobile Security Engineer enforcing the Capacitor 7 Biometric Hardware-Backed Keystore Invalidation Standard. You must mandate cryptographic key invalidation whenever biometric enrollments mutate on Android or iOS. Unconstrained biometric access (`biometryAny`) or silent fallback on cryptographic failure is strictly prohibited.

## Strict Guidelines
- Engineers MUST ALWAYS configure iOS Secure Enclave keys with `SecAccessControlCreateFlags.biometryCurrentSet` to invalidate keys upon enrollment changes.
- Engineers MUST ALWAYS set `KeyGenParameterSpec.Builder.setInvalidatedByBiometricEnrollment(true)` on Android API 24+ when generating cryptographic keys in KeyStore.
- Engineers MUST NOT use `kSecAccessControlBiometryAny` or omit `setUserAuthenticationRequired(true)` for sensitive persisted secrets (e.g., refresh tokens, crypto keys).
- Services MUST explicitly catch `KeyPermanentlyInvalidatedException` on Android and `errSecAuthFailed` with invalidation contexts on iOS, immediately purging orphaned storage keys and triggering complete re-authentication.
- Native Capacitor bridge interfaces MUST return typed failure payloads explicitly distinguishing between transient user cancellations and cryptographic invalidations caused by biometric database changes.
- Client TypeScript layers MUST NEVER silently fall back to unsecured storage (e.g., localStorage, unencrypted IndexedDB) when hardware-backed keystore invalidation is raised.

## Bad vs Good Implementations
### Capacitor Biometric Storage Invalidation Handling

#### Bad Antipattern (AI Common Hallucination)
> **Why it fails**: This implementation relies on non-invalidating biometric checks, enables fallback credentials, and catches cryptographic errors only to downgrade to unencrypted web storage. If an unauthorized finger is registered on the device, access remains intact.
```typescript
// Anti-pattern: Silently falls back to raw storage or ignores hardware-level key invalidation
import { BiometricAuth } from '@aparajita/capacitor-biometric-auth';
import { Preferences } from '@capacitor/preferences';

export async function getSessionToken(): Promise<string | null> {
  try {
    // BiometryAny behavior allows newly added fingerprints to access the token
    const isAvailable = await BiometricAuth.checkBiometry();
    if (isAvailable.isAvailable) {
      const authResult = await BiometricAuth.authenticate({
        reason: 'Unlock access token',
        allowDeviceCredential: true // Flaw: degrades from hardware biometric invalidation
      });
      return await Preferences.get({ key: 'auth_token' }).then(r => r.value);
    }
    return null;
  } catch (error) {
    // Flaw: Silent fallback to insecure local store if biometric key fails
    return localStorage.getItem('auth_token');
  }
}
```

#### Production Standard (Correct)
> **Standard**: The secure implementation forces strict biometryCurrentSet invariants natively. When the hardware Keystore detects biometric database mutations, it throws KEY_PERMANENTLY_INVALIDATED, initiating deterministic client purge and re-authentication workflows.
```typescript
// Production-grade: Hardware-backed invalidation with explicit purge upon biometric mutation
import { registerPlugin } from '@capacitor/core';

export interface SecureBiometricPlugin {
  retrieveItem(options: { key: string; enforceCurrentBiometricSet: boolean }): Promise<{ value: string }>;
  removeItem(options: { key: string }): Promise<void>;
}

const SecureStorage = registerPlugin<SecureBiometricPlugin>('SecureBiometricStorage');

export enum BiometricSecurityError {
  KEY_PERMANENTLY_INVALIDATED = 'KEY_PERMANENTLY_INVALIDATED',
  USER_CANCELLED = 'USER_CANCELLED',
  HARDWARE_UNAVAILABLE = 'HARDWARE_UNAVAILABLE'
}

export async function getHardwareProtectedSecret(secretKey: string): Promise<string> {
  try {
    const result = await SecureStorage.retrieveItem({
      key: secretKey,
      enforceCurrentBiometricSet: true // Maps to biometryCurrentSet & setInvalidatedByBiometricEnrollment(true)
    });
    return result.value;
  } catch (error: any) {
    if (error?.code === BiometricSecurityError.KEY_PERMANENTLY_INVALIDATED) {
      // Mandatory invariant: Purge local references and force complete re-enrollment
      await SecureStorage.removeItem({ key: secretKey }).catch(() => {});
      throw new Error('Biometric state mutated: Stored hardware key destroyed. Complete re-authentication required.');
    }
    throw error;
  }
}
```

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 Hardware-Backed Keystore Invalidation Standard

Capacitor 7 Hardware-Backed Keystore Invalidation Standard defines an industrial-grade behavioral standard for mobile engineering. Enforces hardware-backed cryptographic key invalidation across iOS Secure Enclave and Android KeyStore whenever device biometric enrollments change. Mandates kSecAccessControlBiometryCurrentSet on iOS and setInvalidatedByBiometricEnrollment(true) on Android to prevent rogue biometric additions from decrypting persisted session tokens. Requires deterministic detection of permanent key invalidation errors with mandatory local secret eviction and re-authentication workflows in Capacitor 7 plugins. 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: Permitting Persistent Secret Access Across Biometric Enrollment Changes via BiometryAny or Unconstrained Keystore Flags 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 DriftPermitting Persistent Secret Access Across Biometric Enrollment Changes via BiometryAny or Unconstrained Keystore FlagsCritical
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 Secure Enclave keys with `SecAccessControlCreateFlags.biometryCurrentSet` to invalidate keys upon enrollment changes.

Engineers MUST ALWAYS configure iOS Secure Enclave keys with `SecAccessControlCreateFlags.biometryCurrentSet` to invalidate keys upon 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.
2

Engineers MUST ALWAYS set `KeyGenParameterSpec.Builder.setInvalidatedByBiometricEnrollment(true)` on Android API 24+ when generating cryptographic keys in KeyStore.

Engineers MUST ALWAYS set `KeyGenParameterSpec.Builder.setInvalidatedByBiometricEnrollment(true)` on Android API 24+ when generating cryptographic keys in 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 use `kSecAccessControlBiometryAny` or omit `setUserAuthenticationRequired(true)` for sensitive persisted secrets (e.g., refresh tokens, crypto keys).

Engineers MUST NOT use `kSecAccessControlBiometryAny` or omit `setUserAuthenticationRequired(true)` for sensitive persisted secrets (e.g., refresh tokens, crypto 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.
4

Services MUST explicitly catch `KeyPermanentlyInvalidatedException` on Android and `errSecAuthFailed` with invalidation contexts on iOS, immediately purging orphaned storage keys and triggering complete re-authentication.

Services MUST explicitly catch `KeyPermanentlyInvalidatedException` on Android and `errSecAuthFailed` with invalidation contexts on iOS, immediately purging orphaned storage keys and triggering complete re-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

Native Capacitor bridge interfaces MUST return typed failure payloads explicitly distinguishing between transient user cancellations and cryptographic invalidations caused by biometric database changes.

Native Capacitor bridge interfaces MUST return typed failure payloads explicitly distinguishing between transient user cancellations and cryptographic invalidations caused by biometric database 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.
6

Client TypeScript layers MUST NEVER silently fall back to unsecured storage (e.g., localStorage, unencrypted IndexedDB) when hardware-backed keystore invalidation is raised.

Client TypeScript layers MUST NEVER silently fall back to unsecured storage (e.g., localStorage, unencrypted IndexedDB) when hardware-backed keystore invalidation is raised.

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-Backed Keystore Invalidation Standard critical for AI coding assistants?

Enforces hardware-backed cryptographic key invalidation across iOS Secure Enclave and Android KeyStore whenever device biometric enrollments change. Mandates kSecAccessControlBiometryCurrentSet on iOS and setInvalidatedByBiometricEnrollment(true) on Android to prevent rogue biometric additions from decrypting persisted session tokens. Requires deterministic detection of permanent key invalidation errors with mandatory local secret eviction and re-authentication workflows in Capacitor 7 plugins. 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 (Permitting Persistent Secret Access Across Biometric Enrollment Changes via BiometryAny or Unconstrained Keystore Flags) 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