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

Capacitor 7 Hardware-Bound Biometric Session Invalidation Invariant

Eliminates token hijacking and persistent session leakage in hybrid runtimes by tying WebView session persistence directly to Secure Enclave and Android StrongBox cryptographic key lifecycles. Mandates that authentication tokens stored across the bridge are encrypted with hardware-backed keys configured to invalidate immediately upon biometric enrollment changes or OS-level credential revocation.

Prohibited Anti-Pattern: Persisting Raw Bearer Tokens in WebView LocalStorage or Unbound Keychains Vulnerable to Extraction and Biometric Re-enrollment Hijacking

Export Ready-to-Drop Configuration

Select format below to copy code or download file directly.

---
description: Capacitor 7 Hardware-Bound Biometric Session Invalidation Invariant - Eliminates token hijacking and persistent session leakage in hybrid runtimes by tying WebView session persistence directly to Secure Enclave and Android StrongBox cryptographic key lifecycles. Mandates that authentication tokens stored across the bridge are encrypted with hardware-backed keys configured to invalidate immediately upon biometric enrollment changes or OS-level credential revocation.
globs: src/services/auth/**/*.{ts,tsx}, src/plugins/**/*.{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/capacitor7-hardware-biometric-session-invalidation"
---

# Capacitor 7 Hardware-Bound Biometric Session Invalidation Invariant

> **Severity**: CRITICAL | **Category**: mobile
> **Anti-Pattern Warning**: Persisting Raw Bearer Tokens in WebView LocalStorage or Unbound Keychains Vulnerable to Extraction and Biometric Re-enrollment Hijacking

## System Constraints
You are a Principal Mobile Security Architect enforcing zero-trust hardware-bound authentication invariants in Capacitor 7 hybrid applications. You must ensure that WebView runtimes never hold raw long-lived tokens in insecure local storage, IndexedDB, or standard unauthenticated native preferences. Every session-bearing credential must be encrypted using hardware-backed asymmetric keys generated inside iOS Secure Enclave (kSecAccessControlBiometryCurrentSet) or Android StrongBox Keymaster/KeyMint (setInvalidatedByBiometricEnrollment(true)). Any cryptographic operation failure indicating key invalidation due to newly registered biometrics or lock-screen changes must atomically purge in-memory credentials and trigger an immediate bridge-level hard logout.

## Strict Guidelines
- Engineers MUST ALWAYS store session tokens encrypted at rest via hardware-backed keychains leveraging Apple Secure Enclave or Android StrongBox/TEE.
- Engineers MUST configure iOS Keychain items with `kSecAccessControlBiometryCurrentSet` to ensure cryptographic keys automatically invalidate when new biometric enrollments occur.
- Engineers MUST configure Android KeyGenParameterSpec with `setInvalidatedByBiometricEnrollment(true)` and `setUserAuthenticationRequired(true)`.
- Engineers MUST NOT store unencrypted refresh tokens or JWTs inside WebView `localStorage`, `sessionStorage`, or `IndexedDB`.
- Code MUST trap OS-level key invalidation exceptions (`KeyPermanentlyInvalidatedException` on Android and `errSecItemNotFound` or `errSecAuthFailed` under `CurrentSet` on iOS) and unconditionally purge WebView session memory.
- Services MUST request ephemeral cryptographic signing challenges or decryption handles via the Capacitor 7 Native Bridge strictly per API transaction cycle, never caching decrypted refresh tokens across app resume cycles.

## Bad vs Good Implementations
### Hardware-Bound Biometric Token Storage and Bridge-Level Invalidation Handling

#### Bad Antipattern (AI Common Hallucination)
> **Why it fails**: Storing tokens using generic Preferences or localStorage bypasses Secure Enclave and StrongBox guarantees. If an attacker gains device access and registers a new biometric imprint, the existing session remains completely valid and accessible.
```typescript
import { Preferences } from '@capacitor/preferences';

interface Session {
  accessToken: string;
  refreshToken: string;
}

export class InsecureAuthService {
  // VULNERABLE: Tokens are stored unencrypted in WebView-accessible native preferences.
  // An attacker with WebView XSS, native backup access, or a newly enrolled fingerprint
  // retains complete session access without hardware attestation or invalidation.
  async persistSession(session: Session): Promise<void> {
    await Preferences.set({
      key: 'auth_session',
      value: JSON.stringify(session),
    });
  }

  async getSession(): Promise<Session | null> {
    const raw = await Preferences.get({ key: 'auth_session' });
    return raw.value ? JSON.parse(raw.value) : null;
  }
}
```

#### Production Standard (Correct)
> **Standard**: Tokens are hardware-encrypted with keys bound to the current biometric configuration. Modifying enrolled biometrics forces the OS to permanently invalidate the keys, which this service detects, purging in-memory and persisted state.
```typescript
import { registerPlugin } from '@capacitor/core';

export interface HardwareKeyStorePlugin {
  encryptToken(options: { alias: string; payload: string }): Promise<{ encryptedBlob: string }>;
  decryptToken(options: { alias: string; encryptedBlob: string }): Promise<{ decryptedPayload: string }>;
  purgeHardwareKeys(options: { alias: string }): Promise<void>;
}

const HardwareKeyStore = registerPlugin<HardwareKeyStorePlugin>('HardwareKeyStore');

export class SecureHardwareAuthService {
  private static readonly KEY_ALIAS = 'prod_session_hw_key';
  private static readonly STORAGE_CIPHERTEXT_KEY = 'hw_bound_auth_blob';

  async persistHardwareBoundSession(refreshToken: string): Promise<void> {
    // Hardware KeyStore creates/uses key with biometryCurrentSet & setInvalidatedByBiometricEnrollment(true)
    const { encryptedBlob } = await HardwareKeyStore.encryptToken({
      alias: SecureHardwareAuthService.KEY_ALIAS,
      payload: refreshToken,
    });
    
    sessionStorage.setItem(SecureHardwareAuthService.STORAGE_CIPHERTEXT_KEY, encryptedBlob);
  }

  async resolveHardwareBoundSession(): Promise<string> {
    const encryptedBlob = sessionStorage.getItem(SecureHardwareAuthService.STORAGE_CIPHERTEXT_KEY);
    if (!encryptedBlob) {
      throw new Error('AUTH_SESSION_NOT_FOUND');
    }

    try {
      const { decryptedPayload } = await HardwareKeyStore.decryptToken({
        alias: SecureHardwareAuthService.KEY_ALIAS,
        encryptedBlob,
      });
      return decryptedPayload;
    } catch (error: unknown) {
      const message = error instanceof Error ? error.message : String(error);
      
      // Invariant: Traps KeyPermanentlyInvalidatedException or errSecItemNotFound / errSecAuthFailed
      if (
        message.includes('KeyPermanentlyInvalidatedException') ||
        message.includes('errSecAuthFailed') ||
        message.includes('BIOMETRIC_ENROLLMENT_MODIFIED')
      ) {
        await this.handleHardwareInvalidation();
      }
      throw error;
    }
  }

  private async handleHardwareInvalidation(): Promise<void> {
    sessionStorage.clear();
    await HardwareKeyStore.purgeHardwareKeys({ alias: SecureHardwareAuthService.KEY_ALIAS });
    window.dispatchEvent(new CustomEvent('app:session-invalidated', { detail: { reason: 'BIOMETRIC_RE_ENROLLMENT' } }));
  }
}
```

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-Bound Biometric Session Invalidation Invariant

Capacitor 7 Hardware-Bound Biometric Session Invalidation Invariant defines an industrial-grade behavioral standard for mobile engineering. Eliminates token hijacking and persistent session leakage in hybrid runtimes by tying WebView session persistence directly to Secure Enclave and Android StrongBox cryptographic key lifecycles. Mandates that authentication tokens stored across the bridge are encrypted with hardware-backed keys configured to invalidate immediately upon biometric enrollment changes or OS-level credential 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: Persisting Raw Bearer Tokens in WebView LocalStorage or Unbound Keychains Vulnerable to Extraction and Biometric Re-enrollment Hijacking 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 Raw Bearer Tokens in WebView LocalStorage or Unbound Keychains Vulnerable to Extraction and Biometric Re-enrollment HijackingCritical
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 store session tokens encrypted at rest via hardware-backed keychains leveraging Apple Secure Enclave or Android StrongBox/TEE.

Engineers MUST ALWAYS store session tokens encrypted at rest via hardware-backed keychains leveraging Apple Secure Enclave or Android StrongBox/TEE.

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 configure iOS Keychain items with `kSecAccessControlBiometryCurrentSet` to ensure cryptographic keys automatically invalidate when new biometric enrollments occur.

Engineers MUST configure iOS Keychain items with `kSecAccessControlBiometryCurrentSet` to ensure cryptographic keys automatically invalidate when new biometric enrollments occur.

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 configure Android KeyGenParameterSpec with `setInvalidatedByBiometricEnrollment(true)` and `setUserAuthenticationRequired(true)`.

Engineers MUST configure Android KeyGenParameterSpec with `setInvalidatedByBiometricEnrollment(true)` and `setUserAuthenticationRequired(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.
4

Engineers MUST NOT store unencrypted refresh tokens or JWTs inside WebView `localStorage`, `sessionStorage`, or `IndexedDB`.

Engineers MUST NOT store unencrypted refresh tokens or JWTs inside WebView `localStorage`, `sessionStorage`, or `IndexedDB`.

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 trap OS-level key invalidation exceptions (`KeyPermanentlyInvalidatedException` on Android and `errSecItemNotFound` or `errSecAuthFailed` under `CurrentSet` on iOS) and unconditionally purge WebView session memory.

Code MUST trap OS-level key invalidation exceptions (`KeyPermanentlyInvalidatedException` on Android and `errSecItemNotFound` or `errSecAuthFailed` under `CurrentSet` on iOS) and unconditionally purge WebView session memory.

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

Services MUST request ephemeral cryptographic signing challenges or decryption handles via the Capacitor 7 Native Bridge strictly per API transaction cycle, never caching decrypted refresh tokens across app resume cycles.

Services MUST request ephemeral cryptographic signing challenges or decryption handles via the Capacitor 7 Native Bridge strictly per API transaction cycle, never caching decrypted refresh tokens across app resume cycles.

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-Bound Biometric Session Invalidation Invariant critical for AI coding assistants?

Eliminates token hijacking and persistent session leakage in hybrid runtimes by tying WebView session persistence directly to Secure Enclave and Android StrongBox cryptographic key lifecycles. Mandates that authentication tokens stored across the bridge are encrypted with hardware-backed keys configured to invalidate immediately upon biometric enrollment changes or OS-level credential 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 (Persisting Raw Bearer Tokens in WebView LocalStorage or Unbound Keychains Vulnerable to Extraction and Biometric Re-enrollment Hijacking) 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