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

Capacitor 7 Hardware-Backed Biometric Keystore Isolation Standard

Enforces mandatory hardware-backed asymmetric key pair generation inside the Secure Enclave (iOS) and Android Keystore backed by StrongBox or TEE across Capacitor 7 bridges. Prohibits persisting decrypted master tokens or private keys inside standard web storage or unauthenticated native Preferences, requiring challenge-response cryptographic attestation and biometric gating for every signature operation.

Prohibited Anti-Pattern: Persisting Raw Bearer Tokens in Web Storage or Unauthenticated SharedPreferences Without Hardware Keystore Isolation

Export Ready-to-Drop Configuration

Select format below to copy code or download file directly.

---
description: Capacitor 7 Hardware-Backed Biometric Keystore Isolation Standard - Enforces mandatory hardware-backed asymmetric key pair generation inside the Secure Enclave (iOS) and Android Keystore backed by StrongBox or TEE across Capacitor 7 bridges. Prohibits persisting decrypted master tokens or private keys inside standard web storage or unauthenticated native Preferences, requiring challenge-response cryptographic attestation and biometric gating for every signature operation.
globs: src/**/*.{ts,tsx}, android/app/src/main/**/*.{java,kt}, ios/App/App/**/*.{swift,m}
alwaysApply: true
verified_by: "agentrules.org"
license: "CC-BY-4.0"
source: "https://agentrules.org/rules/capacitor7-hardware-biometric-keystore-isolation-standard"
---

# Capacitor 7 Hardware-Backed Biometric Keystore Isolation Standard

> **Severity**: CRITICAL | **Category**: mobile
> **Anti-Pattern Warning**: Persisting Raw Bearer Tokens in Web Storage or Unauthenticated SharedPreferences Without Hardware Keystore Isolation

## System Constraints
You are a Principal Mobile Security Engineer enforcing the Capacitor 7 Hardware-Backed Biometric Keystore Isolation Standard. You must mandate that all sensitive credentials, refresh tokens, and cryptographic identity keys are isolated inside native hardware keystores (Apple Secure Enclave and Android KeyStore with StrongBox/TEE). Never permit storing raw symmetric credentials in localStorage, IndexedDB, or standard Capacitor Preferences. Enforce challenge-response asymmetric signing through native plugins where private keys remain non-exportable and are gated behind biometric authentication (`UserVerificationRequirement`).

## Strict Guidelines
- Engineers MUST ALWAYS generate non-exportable asymmetric key pairs (P-256 / secp256r1) directly inside the hardware security module (Secure Enclave on iOS, StrongBox Keymaster on Android).
- Engineers MUST NOT store unencrypted refresh tokens, access tokens, or private cryptographic keys in WebView storage primitives (`localStorage`, `sessionStorage`, `IndexedDB`, or web-accessible SQLite).
- Native plugins MUST enforce biometric user presence (`BIOMETRIC_STRONG` / `kSecAccessControlBiometryAny` or `kSecAccessControlBiometryCurrentSet`) on every private key invocation.
- Services MUST implement challenge-response token issuance: the web layer receives an ephemeral non-replayable nonce from the server, delegates signing to the native hardware bridge, and transmits only the detached signature and public attestation.
- Native bridges MUST configure KeyGenParameterSpec with `setIsStrongBoxBacked(true)` (falling back gracefully to standard TEE only if unavailable) and set `setUserAuthenticationRequired(true)` with strict timeout or per-use authorization.
- Components NEVER hold decrypted symmetric keys in JavaScript memory across lifecycle events; cryptographic operations must remain encapsulated in native bridge threads.

## Bad vs Good Implementations
### Hardware Biometric Signing vs Insecure Web Storage

#### Bad Antipattern (AI Common Hallucination)
> **Why it fails**: Persisting raw bearer tokens in standard Preferences exposes them in plaintext files accessible to root users, backup systems, or jailbroken exploit runtimes without hardware attestation or biometric challenges.
```typescript
import { Preferences } from '@capacitor/preferences';
import axios from 'axios';

export async function authenticateTransaction(transactionId: string): Promise<void> {
  // CRITICAL SECURITY FLAW: Raw tokens or private keys in software storage
  // Vulnerable to file-system extraction on rooted/compromised devices or XSS injection
  const { value: rawToken } = await Preferences.get({ key: 'auth_jwt_token' });
  
  if (!rawToken) {
    throw new Error('Token not found');
  }

  await axios.post('/api/transactions/execute', {
    transactionId,
    token: rawToken
  });
}
```

#### Production Standard (Correct)
> **Standard**: Private keys never leave the hardware module. The WebView only passes the backend challenge nonce to the hardware-backed native bridge, requiring live biometric gating to produce an asymmetric signature.
```typescript
import { registerPlugin } from '@capacitor/core';

export interface SecureEnclavePlugin {
  signChallenge(options: {
    alias: string;
    challenge: string;
    promptMessage: string;
  }): Promise<{ signature: string; keyAttestation?: string }>;
}

const HardwareVault = registerPlugin<SecureEnclavePlugin>('SecureEnclaveVault');

export async function authenticateTransaction(transactionId: string, challengeNonce: string): Promise<void> {
  // Invariant: Non-exportable key in StrongBox/Secure Enclave signs nonce after biometric check
  const { signature, keyAttestation } = await HardwareVault.signChallenge({
    alias: 'identity_attestation_key',
    challenge: challengeNonce,
    promptMessage: 'Authenticate with biometrics to confirm transaction'
  });

  const response = await fetch('/api/transactions/execute', {
    method: 'POST',
    headers: { 'Content-Type': 'application/json' },
    body: JSON.stringify({
      transactionId,
      challengeNonce,
      signature,
      keyAttestation
    })
  });

  if (!response.ok) {
    throw new Error(`Execution failed: ${response.statusText}`);
  }
}
```

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-Backed Biometric Keystore Isolation Standard

Capacitor 7 Hardware-Backed Biometric Keystore Isolation Standard defines an industrial-grade behavioral standard for mobile engineering. Enforces mandatory hardware-backed asymmetric key pair generation inside the Secure Enclave (iOS) and Android Keystore backed by StrongBox or TEE across Capacitor 7 bridges. Prohibits persisting decrypted master tokens or private keys inside standard web storage or unauthenticated native Preferences, requiring challenge-response cryptographic attestation and biometric gating for every signature operation. 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 Web Storage or Unauthenticated SharedPreferences Without Hardware Keystore Isolation 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 Web Storage or Unauthenticated SharedPreferences Without Hardware Keystore IsolationCritical
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 non-exportable asymmetric key pairs (P-256 / secp256r1) directly inside the hardware security module (Secure Enclave on iOS, StrongBox Keymaster on Android).

Engineers MUST ALWAYS generate non-exportable asymmetric key pairs (P-256 / secp256r1) directly inside the hardware security module (Secure Enclave on iOS, StrongBox Keymaster on Android).

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 unencrypted refresh tokens, access tokens, or private cryptographic keys in WebView storage primitives (`localStorage`, `sessionStorage`, `IndexedDB`, or web-accessible SQLite).

Engineers MUST NOT store unencrypted refresh tokens, access tokens, or private cryptographic keys in WebView storage primitives (`localStorage`, `sessionStorage`, `IndexedDB`, or web-accessible SQLite).

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

Native plugins MUST enforce biometric user presence (`BIOMETRIC_STRONG` / `kSecAccessControlBiometryAny` or `kSecAccessControlBiometryCurrentSet`) on every private key invocation.

Native plugins MUST enforce biometric user presence (`BIOMETRIC_STRONG` / `kSecAccessControlBiometryAny` or `kSecAccessControlBiometryCurrentSet`) on every private key invocation.

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 implement challenge-response token issuance

Services MUST implement challenge-response token issuance: the web layer receives an ephemeral non-replayable nonce from the server, delegates signing to the native hardware bridge, and transmits only the detached signature and public attestation.

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 bridges MUST configure KeyGenParameterSpec with `setIsStrongBoxBacked(true)` (falling back gracefully to standard TEE only if unavailable) and set `setUserAuthenticationRequired(true)` with strict timeout or per-use authorization.

Native bridges MUST configure KeyGenParameterSpec with `setIsStrongBoxBacked(true)` (falling back gracefully to standard TEE only if unavailable) and set `setUserAuthenticationRequired(true)` with strict timeout or per-use authorization.

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 hold decrypted symmetric keys in JavaScript memory across lifecycle events

Components NEVER hold decrypted symmetric keys in JavaScript memory across lifecycle events; cryptographic operations must remain encapsulated in native bridge threads.

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 Biometric Keystore Isolation Standard critical for AI coding assistants?

Enforces mandatory hardware-backed asymmetric key pair generation inside the Secure Enclave (iOS) and Android Keystore backed by StrongBox or TEE across Capacitor 7 bridges. Prohibits persisting decrypted master tokens or private keys inside standard web storage or unauthenticated native Preferences, requiring challenge-response cryptographic attestation and biometric gating for every signature operation. 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 Web Storage or Unauthenticated SharedPreferences Without Hardware Keystore Isolation) 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