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

Capacitor 7 Hardware-Backed Secure Enclave Keystore Bridge & Memory Isolation

Enforces strict biometric-gated hardware key isolation (iOS Keychain Secure Enclave and Android Hardware Keystore/StrongBox) for session tokens in Capacitor 7 hybrid architectures. Prohibits persistent token serialization within unencrypted webview runtimes (localStorage, IndexedDB, document.cookie) to prevent full credential compromise via Webview XSS or runtime heap scraping.

Prohibited Anti-Pattern: Persisting Raw Bearer Tokens in Unencrypted Web Storage or Bridging Secrets into Long-Lived JavaScript Heap Memory

Export Ready-to-Drop Configuration

Select format below to copy code or download file directly.

---
description: Capacitor 7 Hardware-Backed Secure Enclave Keystore Bridge & Memory Isolation - Enforces strict biometric-gated hardware key isolation (iOS Keychain Secure Enclave and Android Hardware Keystore/StrongBox) for session tokens in Capacitor 7 hybrid architectures. Prohibits persistent token serialization within unencrypted webview runtimes (localStorage, IndexedDB, document.cookie) to prevent full credential compromise via Webview XSS or runtime heap scraping.
globs: src/**/*.{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/capacitor-7-biometric-keystore-bridge-guardrail"
---

# Capacitor 7 Hardware-Backed Secure Enclave Keystore Bridge & Memory Isolation

> **Severity**: CRITICAL | **Category**: mobile
> **Anti-Pattern Warning**: Persisting Raw Bearer Tokens in Unencrypted Web Storage or Bridging Secrets into Long-Lived JavaScript Heap Memory

## System Constraints
You are a Principal Mobile Security Architect enforcing Capacitor 7 Biometric-Gated Hardware Keystore Storage Bridge standards. You mandate that session tokens, refresh tokens, and cryptographic signing keys are never retained in plain text across web storage APIs or the V8/JavaScriptCore persistent heap. All sensitive credentials must remain delegated to the native hardware-backed layer (Apple Secure Enclave kSecAccessControlBiometryAny and Android KeyStore KeyProperties.AUTH_BIOMETRIC_STRONG). When bridging authorization headers to HTTP requests, enforce ephemeral in-memory consumption via native interceptors or narrow-scoped, zero-fillable buffers.

## Strict Guidelines
- Engineers MUST NEVER persist authorization tokens, refresh credentials, or private cryptographic keys in web storage primitives (`localStorage`, `sessionStorage`, `IndexedDB`, or non-HTTP-only `document.cookie`).
- Engineers MUST ALWAYS delegate credential persistence to hardware-backed keychains using explicit access control policies (`kSecAccessControlBiometryCurrentSet` or `KeyProperties.AUTH_BIOMETRIC_STRONG`).
- Code SHOULD route all authenticated network operations through native HTTP clients (such as `@capacitor-community/http` or custom native transport bridges) to append authorization headers directly in the native execution frame without exposing raw tokens to the JavaScript runtime context.
- Services MUST clear ephemeral credentials immediately after execution by nullifying references and avoiding long-lived variable captures in global scopes or closure graphs.
- Native plugins MUST enforce device authentication validity windows (`setUserAuthenticationParameters(timeoutSeconds, KeyProperties.AUTH_BIOMETRIC_STRONG)`) to prevent replay attacks following biometric verification.

## Bad vs Good Implementations
### Vulnerable Plaintext Web Storage vs Biometric Hardware Storage Bridge

#### Bad Antipattern (AI Common Hallucination)
> **Why it fails**: Writing bearer tokens to Webview-accessible storage primitives (localStorage or unencrypted Preferences) exposes credentials directly to client-side injection attacks, DOM-based XSS, and unencrypted file extraction from root/jailbroken device storage.
```typescript
import { Preferences } from '@capacitor/preferences';

export class SessionManager {
  async saveSession(token: string): Promise<void> {
    // Critical Flaw: Serializes raw token to unencrypted web preferences/localStorage
    localStorage.setItem('auth_bearer_token', token);
    await Preferences.set({ key: 'auth_token', value: token });
  }

  async getSessionToken(): Promise<string | null> {
    // Critical Flaw: Accessible via XSS and readable in heap dumps
    return localStorage.getItem('auth_bearer_token');
  }
}
```

#### Production Standard (Correct)
> **Standard**: Delegates cryptographic operations and secret persistence to the native platform's Secure Enclave/KeyStore. Raw tokens never enter the Webview DOM, storage mechanisms, or long-lived JavaScript memory, neutralizing runtime XSS and heap-inspection attacks.
```typescript
import { registerPlugin } from '@capacitor/core';

export interface SecureBridgePlugin {
  storeBiometricSecret(options: { key: string; secret: string; prompt: string }): Promise<void>;
  executeSignedRequest(options: { endpoint: string; method: string; prompt: string; body?: unknown }): Promise<{ status: number; data: unknown }>;
}

const SecureBridge = registerPlugin<SecureBridgePlugin>('SecureHardwareBridge');

export class SessionManager {
  async persistSessionSecurely(refreshToken: string): Promise<void> {
    // Invariant: Native implementation sets kSecAccessControlBiometryCurrentSet / AUTH_BIOMETRIC_STRONG
    await SecureBridge.storeBiometricSecret({
      key: 'user_session_refresh',
      secret: refreshToken,
      prompt: 'Authenticate to register secure hardware access'
    });
  }

  async dispatchProtectedCall(endpoint: string, body?: unknown): Promise<unknown> {
    // Invariant: Raw bearer token is injected directly inside the native secure runtime
    // Token never crosses the JS bridge into the Webview heap
    const response = await SecureBridge.executeSignedRequest({
      endpoint,
      method: 'POST',
      prompt: 'Authenticate using biometrics to verify transaction',
      body
    });
    return response.data;
  }
}
```

Architectural Specification & Invariant Rationale

Architectural Invariant Design: Capacitor 7 Hardware-Backed Secure Enclave Keystore Bridge & Memory Isolation

Capacitor 7 Hardware-Backed Secure Enclave Keystore Bridge & Memory Isolation defines an industrial-grade behavioral standard for mobile engineering. Enforces strict biometric-gated hardware key isolation (iOS Keychain Secure Enclave and Android Hardware Keystore/StrongBox) for session tokens in Capacitor 7 hybrid architectures. Prohibits persistent token serialization within unencrypted webview runtimes (localStorage, IndexedDB, document.cookie) to prevent full credential compromise via Webview XSS or runtime heap scraping. 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 Unencrypted Web Storage or Bridging Secrets into Long-Lived JavaScript Heap Memory 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 Unencrypted Web Storage or Bridging Secrets into Long-Lived JavaScript Heap MemoryCritical
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 authorization tokens, refresh credentials, or private cryptographic keys in web storage primitives (`localStorage`, `sessionStorage`, `IndexedDB`, or non-HTTP-only `document.cookie`).

Engineers MUST NEVER persist authorization tokens, refresh credentials, or private cryptographic keys in web storage primitives (`localStorage`, `sessionStorage`, `IndexedDB`, or non-HTTP-only `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 ALWAYS delegate credential persistence to hardware-backed keychains using explicit access control policies (`kSecAccessControlBiometryCurrentSet` or `KeyProperties.AUTH_BIOMETRIC_STRONG`).

Engineers MUST ALWAYS delegate credential persistence to hardware-backed keychains using explicit access control policies (`kSecAccessControlBiometryCurrentSet` or `KeyProperties.AUTH_BIOMETRIC_STRONG`).

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

Code SHOULD route all authenticated network operations through native HTTP clients (such as `@capacitor-community/http` or custom native transport bridges) to append authorization headers directly in the native execution frame without exposing raw tokens to the JavaScript runtime context.

Code SHOULD route all authenticated network operations through native HTTP clients (such as `@capacitor-community/http` or custom native transport bridges) to append authorization headers directly in the native execution frame without exposing raw tokens to the JavaScript runtime context.

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 ephemeral credentials immediately after execution by nullifying references and avoiding long-lived variable captures in global scopes or closure graphs.

Services MUST clear ephemeral credentials immediately after execution by nullifying references and avoiding long-lived variable captures in global scopes or closure graphs.

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 plugins MUST enforce device authentication validity windows (`setUserAuthenticationParameters(timeoutSeconds, KeyProperties.AUTH_BIOMETRIC_STRONG)`) to prevent replay attacks following biometric verification.

Native plugins MUST enforce device authentication validity windows (`setUserAuthenticationParameters(timeoutSeconds, KeyProperties.AUTH_BIOMETRIC_STRONG)`) to prevent replay attacks following biometric verification.

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 Secure Enclave Keystore Bridge & Memory Isolation critical for AI coding assistants?

Enforces strict biometric-gated hardware key isolation (iOS Keychain Secure Enclave and Android Hardware Keystore/StrongBox) for session tokens in Capacitor 7 hybrid architectures. Prohibits persistent token serialization within unencrypted webview runtimes (localStorage, IndexedDB, document.cookie) to prevent full credential compromise via Webview XSS or runtime heap scraping. 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 Unencrypted Web Storage or Bridging Secrets into Long-Lived JavaScript Heap Memory) 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