This specification is maintained by the AgentRules Working Group. Have enhancements or want to claim maintainership?Submit Specification →
mobilecritical PriorityID: capacitor7-biometric-hardware-session-attestation

Capacitor 7 Biometric Hardware-Backed Session Key Attestation & Invalidation Guardrail

Enforces asymmetric session key pair generation bound to device hardware keystores (iOS Secure Enclave and Android Hardware-backed Keystore/StrongBox) with mandatory biometric user presence authentication. Keys must strictly enforce deterministic invalidation upon any biometric enrollment changes (`kSecAccessControlBiometryAny` combined with strict enrollment monitoring on iOS, and `setInvalidatedByBiometricEnrollment(true)` on Android) to prevent session hijacking via newly enrolled fingerprints or faces.

Prohibited Anti-Pattern: Persisting Unbound Software Session Tokens or Failing to Invalidate Hardware Keys on Biometric Database Mutation

Export Ready-to-Drop Configuration

Select format below to copy code or download file directly.

---
description: Capacitor 7 Biometric Hardware-Backed Session Key Attestation & Invalidation Guardrail - Enforces asymmetric session key pair generation bound to device hardware keystores (iOS Secure Enclave and Android Hardware-backed Keystore/StrongBox) with mandatory biometric user presence authentication. Keys must strictly enforce deterministic invalidation upon any biometric enrollment changes (`kSecAccessControlBiometryAny` combined with strict enrollment monitoring on iOS, and `setInvalidatedByBiometricEnrollment(true)` on Android) to prevent session hijacking via newly enrolled fingerprints or faces.
globs: src/services/auth/**/*.{ts,tsx}, src/plugins/**/*.{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/capacitor7-biometric-hardware-session-attestation"
---

# Capacitor 7 Biometric Hardware-Backed Session Key Attestation & Invalidation Guardrail

> **Severity**: CRITICAL | **Category**: mobile
> **Anti-Pattern Warning**: Persisting Unbound Software Session Tokens or Failing to Invalidate Hardware Keys on Biometric Database Mutation

## System Constraints
You are a Principal Mobile Security Engineer enforcing Capacitor 7 Biometric Hardware-Backed Session Key Attestation. You must ensure that authentication session tokens are signed exclusively by asymmetric keys residing inside the iOS Secure Enclave or Android StrongBox/TEE. Keys must be flagged for hardware-level revocation whenever device biometric enrollment changes, and signatures must be verified on the backend with hardware attestation payloads.

## Strict Guidelines
- Engineers MUST ALWAYS generate cryptographic session keys inside hardware-backed storage (Secure Enclave on iOS via kSecAttrTokenIDSecureEnclave, StrongBox or TEE on Android via KeyGenParameterSpec) using NIST P-256 (secp256r1).
- Engineers MUST ALWAYS enforce deterministic revocation upon biometric enrollment modification: on Android, set `KeyGenParameterSpec.Builder.setInvalidatedByBiometricEnrollment(true)`; on iOS, track biometric database state changes via `LAContext.evaluatedPolicyDomainState` or use `kSecAccessControlBiometryCurrentSet`.
- Engineers MUST NOT store raw JWTs, refresh tokens, or bearer credentials in `CapacitorPreferences`, `localStorage`, or standard unauthenticated SecureStorage plugins.
- Services MUST attest client possession via a challenge-response handshake where the client signs a cryptographically random, server-generated nonce using the biometric-bound private key.
- Code MUST explicitly handle `KeyPermanentlyInvalidatedException` on Android and `errSecAuthFailed` / domain state change errors on iOS by purging the local hardware key reference and forcing complete re-authentication.
- Components NEVER trigger biometric challenge prompts without an active, unexpired cryptographic challenge payload received directly from the authentication backend.

## Bad vs Good Implementations
### Hardware Biometric Key Attestation & Deterministic Invalidation Flow

#### Bad Antipattern (AI Common Hallucination)
> **Why it fails**: Performs biometric verification decoupled from the cryptographic key. Uses unauthenticated Capacitor Preferences to store a raw token. If a malicious actor registers a new fingerprint on an unlocked device, they gain full access because the token is not bound to a hardware key that invalidates on biometric enrollment changes.
```typescript
import { Preferences } from '@capacitor/preferences';
import { NativeBiometric } from 'capacitor-native-biometric';

export class AuthService {
  // VULNERABLE: Soft verification with persistent token in standard storage
  async authenticateSession(): Promise<string | null> {
    const verified = await NativeBiometric.verifyIdentity({
      reason: 'Log in to your account',
      title: 'Biometric Login',
    }).then(() => true).catch(() => false);

    if (verified) {
      // CRITICAL FLAW: Raw session token retrieved without hardware key verification.
      // If an attacker adds a new fingerprint to the OS, this check still succeeds.
      const { value } = await Preferences.get({ key: 'auth_jwt_token' });
      return value;
    }
    return null;
  }
}
```

#### Production Standard (Correct)
> **Standard**: Delegates cryptographic operations to hardware-backed storage (Secure Enclave / StrongBox). Configures keys to be irreversibly invalidated if biometric enrollments change. Uses challenge signing rather than retrieving static secrets.
```typescript
import { registerPlugin } from '@capacitor/core';

export interface SecureBiometricKeyPlugin {
  generateHardwareKey(options: { alias: string; invalidateOnEnrollment: boolean }): Promise<{ publicKeyDerHex: string }>;
  signHardwareChallenge(options: { alias: string; challengeBase64: string }): Promise<{ signatureDerHex: string }>;
  purgeHardwareKey(options: { alias: string }): Promise<void>;
}

const BiometricKey = registerPlugin<SecureBiometricKeyPlugin>('SecureBiometricKey');

export class AuthService {
  private readonly keyAlias = 'app.session.biometric.key';

  async createBiometricHardwareSession(): Promise<{ publicKeyDerHex: string }> {
    // Hardware keystore generation with biometric invalidation enforced in native plugin
    return await BiometricKey.generateHardwareKey({
      alias: this.keyAlias,
      invalidateOnEnrollment: true, // Android: setInvalidatedByBiometricEnrollment(true) | iOS: kSecAccessControlBiometryCurrentSet
    });
  }

  async authenticateChallenge(challengeBase64: string): Promise<string> {
    try {
      const { signatureDerHex } = await BiometricKey.signHardwareChallenge({
        alias: this.keyAlias,
        challengeBase64,
      });
      return signatureDerHex;
    } catch (error: any) {
      if (error?.code === 'KEY_PERMANENTLY_INVALIDATED' || error?.code === 'BIOMETRIC_SET_CHANGED') {
        await BiometricKey.purgeHardwareKey({ alias: this.keyAlias });
        throw new Error('Biometric database modified. Hardware key invalidated. Re-authentication required.');
      }
      throw error;
    }
  }
}
```

Architectural Specification & Invariant Rationale

Architectural Invariant Design: Capacitor 7 Biometric Hardware-Backed Session Key Attestation & Invalidation Guardrail

Capacitor 7 Biometric Hardware-Backed Session Key Attestation & Invalidation Guardrail defines an industrial-grade behavioral standard for mobile engineering. Enforces asymmetric session key pair generation bound to device hardware keystores (iOS Secure Enclave and Android Hardware-backed Keystore/StrongBox) with mandatory biometric user presence authentication. Keys must strictly enforce deterministic invalidation upon any biometric enrollment changes (`kSecAccessControlBiometryAny` combined with strict enrollment monitoring on iOS, and `setInvalidatedByBiometricEnrollment(true)` on Android) to prevent session hijacking via newly enrolled fingerprints or faces. 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 Unbound Software Session Tokens or Failing to Invalidate Hardware Keys on Biometric Database Mutation 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 Unbound Software Session Tokens or Failing to Invalidate Hardware Keys on Biometric Database MutationCritical
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 generate cryptographic session keys inside hardware-backed storage (Secure Enclave on iOS via kSecAttrTokenIDSecureEnclave, StrongBox or TEE on Android via KeyGenParameterSpec) using NIST P-256 (secp256r1).

Engineers MUST ALWAYS generate cryptographic session keys inside hardware-backed storage (Secure Enclave on iOS via kSecAttrTokenIDSecureEnclave, StrongBox or TEE on Android via KeyGenParameterSpec) using NIST P-256 (secp256r1).

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 enforce deterministic revocation upon biometric enrollment modification

Engineers MUST ALWAYS enforce deterministic revocation upon biometric enrollment modification: on Android, set `KeyGenParameterSpec.Builder.setInvalidatedByBiometricEnrollment(true)`; on iOS, track biometric database state changes via `LAContext.evaluatedPolicyDomainState` or use `kSecAccessControlBiometryCurrentSet`.

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 store raw JWTs, refresh tokens, or bearer credentials in `CapacitorPreferences`, `localStorage`, or standard unauthenticated SecureStorage plugins.

Engineers MUST NOT store raw JWTs, refresh tokens, or bearer credentials in `CapacitorPreferences`, `localStorage`, or standard unauthenticated SecureStorage plugins.

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 attest client possession via a challenge-response handshake where the client signs a cryptographically random, server-generated nonce using the biometric-bound private key.

Services MUST attest client possession via a challenge-response handshake where the client signs a cryptographically random, server-generated nonce using the biometric-bound private key.

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

Code MUST explicitly handle `KeyPermanentlyInvalidatedException` on Android and `errSecAuthFailed` / domain state change errors on iOS by purging the local hardware key reference and forcing complete re-authentication.

Code MUST explicitly handle `KeyPermanentlyInvalidatedException` on Android and `errSecAuthFailed` / domain state change errors on iOS by purging the local hardware key reference and forcing 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.
6

Components NEVER trigger biometric challenge prompts without an active, unexpired cryptographic challenge payload received directly from the authentication backend.

Components NEVER trigger biometric challenge prompts without an active, unexpired cryptographic challenge payload received directly from the authentication backend.

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-Backed Session Key Attestation & Invalidation Guardrail critical for AI coding assistants?

Enforces asymmetric session key pair generation bound to device hardware keystores (iOS Secure Enclave and Android Hardware-backed Keystore/StrongBox) with mandatory biometric user presence authentication. Keys must strictly enforce deterministic invalidation upon any biometric enrollment changes (`kSecAccessControlBiometryAny` combined with strict enrollment monitoring on iOS, and `setInvalidatedByBiometricEnrollment(true)` on Android) to prevent session hijacking via newly enrolled fingerprints or faces. 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 Unbound Software Session Tokens or Failing to Invalidate Hardware Keys on Biometric Database Mutation) 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