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

Capacitor 7 Biometric Hardware Key Vault & Secure Enclave Isolation

Guarantees hybrid web-view runtimes never store cryptographic keys, refresh tokens, or raw session credentials inside WebStorage, IndexedDB, or memory-leaked JS closures. Mandates offloading all cryptographic signing, token persistence, and biometric challenges directly to the native iOS Secure Enclave (Keychain kSecAccessControlBiometryAny) and Android KeyStore (KeyProperties.PURPOSE_SIGN / PURPOSE_DECRYPT with setUserAuthenticationRequired) via hardened Capacitor 7 native bridges.

Prohibited Anti-Pattern: Persisting Sensitive OAuth Credentials or Cryptographic Secrets in Insecure WebStorage APIs

Export Ready-to-Drop Configuration

Select format below to copy code or download file directly.

---
description: Capacitor 7 Biometric Hardware Key Vault & Secure Enclave Isolation - Guarantees hybrid web-view runtimes never store cryptographic keys, refresh tokens, or raw session credentials inside WebStorage, IndexedDB, or memory-leaked JS closures. Mandates offloading all cryptographic signing, token persistence, and biometric challenges directly to the native iOS Secure Enclave (Keychain kSecAccessControlBiometryAny) and Android KeyStore (KeyProperties.PURPOSE_SIGN / PURPOSE_DECRYPT with setUserAuthenticationRequired) via hardened Capacitor 7 native bridges.
globs: src/**/*.{ts,tsx}, ios/App/**/*.{swift,m}, android/app/**/*.{java,kt}
alwaysApply: true
verified_by: "agentrules.org"
license: "CC-BY-4.0"
source: "https://agentrules.org/rules/capacitor-7-biometric-secure-enclave-isolation"
---

# Capacitor 7 Biometric Hardware Key Vault & Secure Enclave Isolation

> **Severity**: CRITICAL | **Category**: mobile
> **Anti-Pattern Warning**: Persisting Sensitive OAuth Credentials or Cryptographic Secrets in Insecure WebStorage APIs

## System Constraints
You are a Principal Mobile Security Architect enforcing strict hardware isolation standards for Capacitor 7 hybrid applications. You must enforce that no sensitive authentication credentials, bearer refresh tokens, or private keys ever touch browser storage engines (localStorage, sessionStorage, IndexedDB, document.cookie) or unencrypted file systems. You mandate that token exchange, payload signing, and credentials storage delegate exclusively to the native hardware-backed KeyStore and Apple Secure Enclave via secure Capacitor 7 custom plugins or validated biometric bridge implementations.

## Strict Guidelines
- Engineers MUST NEVER persist raw authentication tokens, API secrets, or private keys in window.localStorage, window.sessionStorage, IndexedDB, or document.cookie.
- Engineers MUST configure native Android KeyGenParameterSpec with setUserAuthenticationRequired(true) and setUserAuthenticationParameters with biometric flags for all high-entropy key pairs.
- Engineers MUST configure native iOS Keychain items with kSecAccessControlBiometryCurrentSet or kSecAccessControlBiometryAny paired with kSecAttrAccessibleAfterFirstUnlockThisDeviceOnly.
- Components and web services MUST interact with credentials via a non-extractable session bridge that performs cryptographic challenge-response signing within native code rather than returning raw private keys to the WebView.
- In-flight access tokens kept in JavaScript memory MUST be scoped to ephemeral short-lived closures, cleared immediately upon failure, and refreshed strictly through native biometric bridge calls.
- Services MUST handle NativeBiometricAuthenticationError gracefully, implementing secure fallback flows without downgrading security postures to insecure browser storage.

## Bad vs Good Implementations
### Token Storage & Biometric Retrieval Bridge

#### Bad Antipattern (AI Common Hallucination)
> **Why it fails**: Storing tokens in window.localStorage or Capacitor Preferences persists raw credentials unencrypted or in plaintext XML/plist stores vulnerable to cross-site scripting (XSS), root extraction, and unauthenticated device access without hardware biometric constraints.
```typescript
import { Preferences } from '@capacitor/preferences';

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

export async function persistAuthSession(session: SessionToken): Promise<void> {
  // CRITICAL SECURITY VIOLATION: Unencrypted WebStorage / SharedPreferences leak
  localStorage.setItem('auth_access_token', session.accessToken);
  await Preferences.set({
    key: 'auth_refresh_token',
    value: session.refreshToken,
  });
}

export async function getAccessToken(): Promise<string | null> {
  // Insecure retrieval directly exposed to XSS vectors in WebView
  return localStorage.getItem('auth_access_token');
}
```

#### Production Standard (Correct)
> **Standard**: Delegates storage to a native Capacitor plugin backed by the iOS Secure Enclave and Android Hardware KeyStore with biometrics mandatory. Refresh tokens remain completely inaccessible to standard WebView storage APIs, and transient access tokens remain in ephemeral memory.
```typescript
import { registerPlugin } from '@capacitor/core';

export interface SecureKeyVaultPlugin {
  storeSecretWithBiometrics(options: { key: string; secret: string; promptMessage: string }): Promise<{ success: boolean }>;
  retrieveSecretWithBiometrics(options: { key: string; promptMessage: string }): Promise<{ secret: string }>;
  signPayloadWithSecureEnclave(options: { keyAlias: string; payload: string }): Promise<{ signature: string }>;
}

const SecureKeyVault = registerPlugin<SecureKeyVaultPlugin>('SecureKeyVault');

export class NativeVaultSessionManager {
  private static ephemeralAccessToken: string | null = null;

  public static async persistRefreshToken(refreshToken: string): Promise<void> {
    await SecureKeyVault.storeSecretWithBiometrics({
      key: 'auth_refresh_token',
      secret: refreshToken,
      promptMessage: 'Authenticate to register secure credentials'
    });
  }

  public static async resolveAccessToken(refreshEndpoint: string): Promise<string> {
    if (this.ephemeralAccessToken) {
      return this.ephemeralAccessToken;
    }

    const { secret: refreshToken } = await SecureKeyVault.retrieveSecretWithBiometrics({
      key: 'auth_refresh_token',
      promptMessage: 'Authenticate to access secure enterprise session'
    });

    const response = await fetch(refreshEndpoint, {
      method: 'POST',
      headers: { 'Content-Type': 'application/json' },
      body: JSON.stringify({ token: refreshToken })
    });

    if (!response.ok) {
      throw new Error('Failed to refresh authentication credentials.');
    }

    const data = await response.json();
    this.ephemeralAccessToken = data.accessToken;
    return this.ephemeralAccessToken!;
  }

  public static clearSession(): void {
    this.ephemeralAccessToken = null;
  }
}
```

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 Hardware Key Vault & Secure Enclave Isolation

Capacitor 7 Biometric Hardware Key Vault & Secure Enclave Isolation defines an industrial-grade behavioral standard for mobile engineering. Guarantees hybrid web-view runtimes never store cryptographic keys, refresh tokens, or raw session credentials inside WebStorage, IndexedDB, or memory-leaked JS closures. Mandates offloading all cryptographic signing, token persistence, and biometric challenges directly to the native iOS Secure Enclave (Keychain kSecAccessControlBiometryAny) and Android KeyStore (KeyProperties.PURPOSE_SIGN / PURPOSE_DECRYPT with setUserAuthenticationRequired) via hardened Capacitor 7 native bridges. 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 Sensitive OAuth Credentials or Cryptographic Secrets in Insecure WebStorage APIs 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 Sensitive OAuth Credentials or Cryptographic Secrets in Insecure WebStorage APIsCritical
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 NEVER persist raw authentication tokens, API secrets, or private keys in window.localStorage, window.sessionStorage, IndexedDB, or document.cookie.

Engineers MUST NEVER persist raw authentication tokens, API secrets, or private keys in window.localStorage, window.sessionStorage, IndexedDB, or document.cookie.

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 native Android KeyGenParameterSpec with setUserAuthenticationRequired(true) and setUserAuthenticationParameters with biometric flags for all high-entropy key pairs.

Engineers MUST configure native Android KeyGenParameterSpec with setUserAuthenticationRequired(true) and setUserAuthenticationParameters with biometric flags for all high-entropy key pairs.

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 native iOS Keychain items with kSecAccessControlBiometryCurrentSet or kSecAccessControlBiometryAny paired with kSecAttrAccessibleAfterFirstUnlockThisDeviceOnly.

Engineers MUST configure native iOS Keychain items with kSecAccessControlBiometryCurrentSet or kSecAccessControlBiometryAny paired with kSecAttrAccessibleAfterFirstUnlockThisDeviceOnly.

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

Components and web services MUST interact with credentials via a non-extractable session bridge that performs cryptographic challenge-response signing within native code rather than returning raw private keys to the WebView.

Components and web services MUST interact with credentials via a non-extractable session bridge that performs cryptographic challenge-response signing within native code rather than returning raw private keys to the WebView.

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

In-flight access tokens kept in JavaScript memory MUST be scoped to ephemeral short-lived closures, cleared immediately upon failure, and refreshed strictly through native biometric bridge calls.

In-flight access tokens kept in JavaScript memory MUST be scoped to ephemeral short-lived closures, cleared immediately upon failure, and refreshed strictly through native biometric bridge calls.

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 handle NativeBiometricAuthenticationError gracefully, implementing secure fallback flows without downgrading security postures to insecure browser storage.

Services MUST handle NativeBiometricAuthenticationError gracefully, implementing secure fallback flows without downgrading security postures to insecure browser 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.
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 Key Vault & Secure Enclave Isolation critical for AI coding assistants?

Guarantees hybrid web-view runtimes never store cryptographic keys, refresh tokens, or raw session credentials inside WebStorage, IndexedDB, or memory-leaked JS closures. Mandates offloading all cryptographic signing, token persistence, and biometric challenges directly to the native iOS Secure Enclave (Keychain kSecAccessControlBiometryAny) and Android KeyStore (KeyProperties.PURPOSE_SIGN / PURPOSE_DECRYPT with setUserAuthenticationRequired) via hardened Capacitor 7 native bridges. 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 Sensitive OAuth Credentials or Cryptographic Secrets in Insecure WebStorage APIs) 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