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

Hardware-Backed Secure Enclave & Keystore Invariants for Capacitor 7

Establishes non-exportable hardware-backed cryptographic key isolation across Capacitor 7 hybrid mobile applications, binding long-lived authentication and session tokens to Apple Secure Enclave or Android StrongBox KeyMint via biometrics. Precludes token exfiltration vulnerabilities by ensuring private keys never traverse the WebKit/Chromium JavaScript bridge or sit unencrypted in WebStorage, IndexedDB, or standard SharedPreferences.

Prohibited Anti-Pattern: Persisting Raw Bearer Tokens in WebView Storage Accessible to Cross-Site Scripting (XSS)

Export Ready-to-Drop Configuration

Select format below to copy code or download file directly.

---
description: Hardware-Backed Secure Enclave & Keystore Invariants for Capacitor 7 - Establishes non-exportable hardware-backed cryptographic key isolation across Capacitor 7 hybrid mobile applications, binding long-lived authentication and session tokens to Apple Secure Enclave or Android StrongBox KeyMint via biometrics. Precludes token exfiltration vulnerabilities by ensuring private keys never traverse the WebKit/Chromium JavaScript bridge or sit unencrypted in WebStorage, IndexedDB, or standard SharedPreferences.
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-secure-enclave-keychain-persistence"
---

# Hardware-Backed Secure Enclave & Keystore Invariants for Capacitor 7

> **Severity**: CRITICAL | **Category**: mobile
> **Anti-Pattern Warning**: Persisting Raw Bearer Tokens in WebView Storage Accessible to Cross-Site Scripting (XSS)

## System Constraints
You are a Principal Mobile Security Engineer enforcing hardware-backed cryptographic storage and biometric authentication for Capacitor 7 applications. Your goal is to eliminate token exfiltration through WebKit/Chromium injection attacks. You mandate that raw persistent tokens never touch localStorage, sessionStorage, or IndexedDB. Instead, long-lived credentials must be encrypted at rest using keys isolated in the Apple Secure Enclave (kSecAccessControlUserPresence / kSecAccessControlBiometryCurrentSet) or Android StrongBox/TEE KeyStore with setUserAuthenticationRequired(true). Cryptographic signing operations must occur natively on the native bridge layer, returning only short-lived nonces or proof-of-possession assertions to the web layer.

## Strict Guidelines
- Engineers MUST ALWAYS enforce hardware-backed key generation (kSecAttrAccessControl for iOS Secure Enclave; KeyGenParameterSpec with PURPOSE_SIGN/DECRYPT on Android Keystore) via vetted Capacitor native plugins.
- Engineers MUST NOT store long-lived JWTs, refresh tokens, or sensitive API secrets in browser primitives such as window.localStorage, sessionStorage, unencrypted IndexedDB, or basic Capacitor Preferences.
- Services MUST implement challenge-response cryptographic signing across the bridge instead of passing raw private keys or persistent secrets directly into the WebView JavaScript context.
- Components NEVER store decrypted credentials in long-lived state variables; secrets must only be retrieved on-demand inside transient execution blocks and purged immediately.
- Engineers MUST configure kSecAccessControlBiometryCurrentSet on iOS to automatically invalidate hardware keys when enrolled biometric identities (Face ID/Touch ID) change.
- Bridge communication MUST enforce origin validation and context isolation to prevent malicious WebKit frame injection from invoking native credential retrieval calls.

## Bad vs Good Implementations
### Insecure Storage in LocalStorage vs. Secure Enclave Biometric Bridge

#### Bad Antipattern (AI Common Hallucination)
> **Why it fails**: Storing persistent credentials in WebStorage or standard Capacitor Preferences exposes raw tokens to XSS payloads running inside the WebView. Preferences on iOS uses unencrypted NSUserDefaults, and on Android uses standard SharedPreferences, leaving secrets fully vulnerable to file extraction on jailbroken/rooted devices.
```typescript
import { Preferences } from '@capacitor/preferences';

// CRITICAL VULNERABILITY: Storing raw refresh tokens in Preferences (NSUserDefaults / SharedPreferences)
// or WebStorage. An XSS payload can directly read this token and exfiltrate it.
export async function persistAuthToken(token: string): Promise<void> {
  localStorage.setItem('auth_token', token);
  await Preferences.set({ key: 'refresh_token', value: token });
}

export async function getAuthToken(): Promise<string | null> {
  return localStorage.getItem('auth_token');
}
```

#### Production Standard (Correct)
> **Standard**: The good pattern offloads sensitive operations to a native plugin bound to hardware-backed modules (Apple Secure Enclave / Android StrongBox). Private keys cannot be exported, and secrets are only decrypted upon successful biometric verification. Even if an attacker executes arbitrary JavaScript in the WebView, they cannot read the persistent raw secrets or exfiltrate private keys.
```typescript
import { registerPlugin } from '@capacitor/core';

interface BiometricEnclavePlugin {
  generateHardwareKey(options: { alias: string; requireBiometrics: boolean }): Promise<{ publicKey: string }>;
  signPayload(options: { alias: string; payload: string; prompt: string }): Promise<{ signature: string }>;
  storeEncryptedCredential(options: { key: string; secret: string; biometrics: boolean }): Promise<{ success: boolean }>;
  getEncryptedCredential(options: { key: string; prompt: string }): Promise<{ secret: string }>;
}

const EnclaveBridge = registerPlugin<BiometricEnclavePlugin>('BiometricEnclaveBridge');

export class SecureTokenVault {
  private static readonly KEY_ALIAS = 'app.session.credentials';

  public static async persistSessionToken(token: string): Promise<void> {
    // Delegated to native Keychain (kSecAttrAccessibleWhenUnlockedThisDeviceOnly) or Android KeyStore with StrongBox
    await EnclaveBridge.storeEncryptedCredential({
      key: this.KEY_ALIAS,
      secret: token,
      biometrics: true
    });
  }

  public static async signChallenge(challengeNonce: string): Promise<string> {
    // Private key never leaves hardware enclave; Web layer receives only the cryptographic assertion
    const { signature } = await EnclaveBridge.signPayload({
      alias: this.KEY_ALIAS,
      payload: challengeNonce,
      prompt: 'Authenticate to authorize this transaction'
    });
    return signature;
  }
}
```

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: Hardware-Backed Secure Enclave & Keystore Invariants for Capacitor 7

Hardware-Backed Secure Enclave & Keystore Invariants for Capacitor 7 defines an industrial-grade behavioral standard for mobile engineering. Establishes non-exportable hardware-backed cryptographic key isolation across Capacitor 7 hybrid mobile applications, binding long-lived authentication and session tokens to Apple Secure Enclave or Android StrongBox KeyMint via biometrics. Precludes token exfiltration vulnerabilities by ensuring private keys never traverse the WebKit/Chromium JavaScript bridge or sit unencrypted in WebStorage, IndexedDB, or standard SharedPreferences. 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 Storage Accessible to Cross-Site Scripting (XSS) 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 Storage Accessible to Cross-Site Scripting (XSS)Critical
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 enforce hardware-backed key generation (kSecAttrAccessControl for iOS Secure Enclave

Engineers MUST ALWAYS enforce hardware-backed key generation (kSecAttrAccessControl for iOS Secure Enclave; KeyGenParameterSpec with PURPOSE_SIGN/DECRYPT on Android Keystore) via vetted Capacitor native 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.
2

Engineers MUST NOT store long-lived JWTs, refresh tokens, or sensitive API secrets in browser primitives such as window.localStorage, sessionStorage, unencrypted IndexedDB, or basic Capacitor Preferences.

Engineers MUST NOT store long-lived JWTs, refresh tokens, or sensitive API secrets in browser primitives such as window.localStorage, sessionStorage, unencrypted IndexedDB, or basic Capacitor Preferences.

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

Services MUST implement challenge-response cryptographic signing across the bridge instead of passing raw private keys or persistent secrets directly into the WebView JavaScript context.

Services MUST implement challenge-response cryptographic signing across the bridge instead of passing raw private keys or persistent secrets directly into the WebView JavaScript 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

Components NEVER store decrypted credentials in long-lived state variables

Components NEVER store decrypted credentials in long-lived state variables; secrets must only be retrieved on-demand inside transient execution blocks and purged immediately.

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

Engineers MUST configure kSecAccessControlBiometryCurrentSet on iOS to automatically invalidate hardware keys when enrolled biometric identities (Face ID/Touch ID) change.

Engineers MUST configure kSecAccessControlBiometryCurrentSet on iOS to automatically invalidate hardware keys when enrolled biometric identities (Face ID/Touch ID) change.

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

Bridge communication MUST enforce origin validation and context isolation to prevent malicious WebKit frame injection from invoking native credential retrieval calls.

Bridge communication MUST enforce origin validation and context isolation to prevent malicious WebKit frame injection from invoking native credential retrieval 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.
Technical Questions & Answers

Frequently Asked Technical Questions

Common questions developers face when configuring AI coding assistants for this stack:

Q:Why is Hardware-Backed Secure Enclave & Keystore Invariants for Capacitor 7 critical for AI coding assistants?

Establishes non-exportable hardware-backed cryptographic key isolation across Capacitor 7 hybrid mobile applications, binding long-lived authentication and session tokens to Apple Secure Enclave or Android StrongBox KeyMint via biometrics. Precludes token exfiltration vulnerabilities by ensuring private keys never traverse the WebKit/Chromium JavaScript bridge or sit unencrypted in WebStorage, IndexedDB, or standard SharedPreferences. 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 Storage Accessible to Cross-Site Scripting (XSS)) 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

Hardware-Backed