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

Capacitor 7 Hardware-Backed Key Attestation & Enclave Isolation Guardrail

Enforces asymmetric cryptographic signing inside platform hardware enclaves (Apple Secure Enclave, Android StrongBox/TEE) for hybrid Capacitor 7 mobile runtimes. Prevents storing, caching, or transporting private keys and raw authorization bearer tokens in WebView memory (DOM/localStorage/IndexedDB) to thwart runtime memory dumping and cross-site scripting extraction attacks.

Prohibited Anti-Pattern: Persisting Session Bearer Tokens in WebView Storage and Emulating Biometric Auth via Web Crypto Soft-Keys

Export Ready-to-Drop Configuration

Select format below to copy code or download file directly.

---
description: Capacitor 7 Hardware-Backed Key Attestation & Enclave Isolation Guardrail - Enforces asymmetric cryptographic signing inside platform hardware enclaves (Apple Secure Enclave, Android StrongBox/TEE) for hybrid Capacitor 7 mobile runtimes. Prevents storing, caching, or transporting private keys and raw authorization bearer tokens in WebView memory (DOM/localStorage/IndexedDB) to thwart runtime memory dumping and cross-site scripting extraction attacks.
globs: src/**/*.{ts,tsx}, ios/App/App/**/*.{swift,m}, android/app/src/main/java/**/*.kt
alwaysApply: true
verified_by: "agentrules.org"
license: "CC-BY-4.0"
source: "https://agentrules.org/rules/capacitor-7-biometric-enclave-attestation-standard-capacitor-7-biom-295"
---

# Capacitor 7 Hardware-Backed Key Attestation & Enclave Isolation Guardrail

> **Severity**: CRITICAL | **Category**: mobile
> **Anti-Pattern Warning**: Persisting Session Bearer Tokens in WebView Storage and Emulating Biometric Auth via Web Crypto Soft-Keys

## System Constraints
You are a Principal Mobile Architect enforcing the Capacitor 7 Biometric Enclave Cryptographic Key Attestation Standard. Enforce zero-trust architecture across the WebView-to-Native bridge. Invariant: Private keys must never leave Apple Secure Enclave or Android KeyStore StrongBox/TEE, and authorization must utilize short-lived hardware-signed challenge-response attestations rather than static bearer tokens stored in the JavaScript runtime.

## Strict Guidelines
- Engineers MUST ALWAYS generate asymmetric ECDSA keys (P-256/secp256r1) directly inside the Secure Enclave (kSecAttrAccessibleAfterFirstUnlockThisDeviceOnly) or Android KeyStore with StrongBox backed protection.
- Engineers MUST NOT store long-lived JWTs, OAuth access tokens, or unencrypted refresh tokens in localStorage, sessionStorage, IndexedDB, or Capacitor Preferences.
- Engineers MUST implement challenge-response authorization where every sensitive transaction or token renewal signs an ephemeral server-generated nonce within the hardware enclave upon explicit biometric validation (BiometricPrompt / LocalAuthentication).
- Services MUST verify hardware key attestation chains (Apple App Attest or Android Key Attestation root certificates) on the backend server before provisioning trust to a generated client public key.
- Components NEVER expose private key material or allow signature operations without user biometric interaction or OS-level biometry lock timeouts (setUserAuthenticationRequired(true)).
- Bridge handlers MUST zeroize native memory buffers containing decrypted payloads immediately after passing verified results to bridge responses.

## Bad vs Good Implementations
### Biometric Authentication: Token Storage vs Enclave Challenge Signing

#### Bad Antipattern (AI Common Hallucination)
> **Why it fails**: Flawed design: Biometric check is decoupled from key usage. Once biometrics pass, a static bearer token is extracted from storage into JavaScript memory, exposing it to memory inspection, XSS exploits, and jailbreak hooks. The token can be replayed indefinitely.
```typescript
import { Preferences } from '@capacitor/preferences';
import { BiometricAuth } from '@aparajita/capacitor-biometric-auth';

export async function authenticateAndExecute(actionPayload: any): Promise<void> {
  // VULNERABLE: Biometrics only guards retrieval of a raw bearer token from insecure storage
  const biometricsAvailable = await BiometricAuth.checkBiometry();
  if (biometricsAvailable.isAvailable) {
    await BiometricAuth.verify({
      reason: 'Confirm transaction authorization'
    });
    
    // Bearer token resides in plaintext in Preferences / WebView accessible memory
    const { value: bearerToken } = await Preferences.get({ key: 'auth_jwt_token' });
    
    await fetch('https://api.domain.com/v1/transfer', {
      method: 'POST',
      headers: {
        'Authorization': `Bearer ${bearerToken}`,
        'Content-Type': 'application/json'
      },
      body: JSON.stringify(actionPayload)
    });
  }
}
```

#### Production Standard (Correct)
> **Standard**: Zero-trust design: Hardware key pair is created in hardware enclave with attestation certificates verified on the backend. Private keys never touch JavaScript memory. Authorizations execute via ephemeral, non-replayable challenges signed directly in hardware upon biometric confirmation.
```typescript
import { registerPlugin } from '@capacitor/core';

export interface SecureEnclavePlugin {
  generateHardwareKey(options: { alias: string; requireStrongBox: boolean }): Promise<{ attestationCertificateChain: string[]; publicKey: string }>;
  signHardwareChallenge(options: { alias: string; challenge: string; promptMessage: string }): Promise<{ signature: string }>;
}

const EnclaveSigner = registerPlugin<SecureEnclavePlugin>('SecureEnclaveSigner');

export async function executeAttestedTransaction(actionPayload: Record<string, unknown>): Promise<Response> {
  // 1. Fetch single-use cryptographic challenge from the server
  const challengeResponse = await fetch('https://api.domain.com/v1/auth/challenge', { method: 'POST' });
  const { challenge, nonceId } = await challengeResponse.json();

  // 2. Hash payload combined with the nonce to prevent tampering
  const messageToSign = `${nonceId}:${JSON.stringify(actionPayload)}:${challenge}`;

  // 3. Delegate signature to Secure Enclave / StrongBox; triggers biometric prompt in native runtime
  // Private key NEVER enters WebView or app user-space memory
  const { signature } = await EnclaveSigner.signHardwareChallenge({
    alias: 'com.app.keys.biometric_auth',
    challenge: messageToSign,
    promptMessage: 'Confirm transfer with biometrics'
  });

  // 4. Send attested signature and payload; backend validates enclave-signed nonce
  return await fetch('https://api.domain.com/v1/transfer', {
    method: 'POST',
    headers: {
      'Content-Type': 'application/json',
      'X-Signature': signature,
      'X-Nonce-Id': nonceId
    },
    body: JSON.stringify(actionPayload)
  });
}
```

Recommended MCP Servers (mcp-serverlist.com)

Equip agent with system tools to verify code for this stack.

Architectural Specification & Invariant Rationale

Architectural Invariant Design: Capacitor 7 Hardware-Backed Key Attestation & Enclave Isolation Guardrail

Capacitor 7 Hardware-Backed Key Attestation & Enclave Isolation Guardrail defines an industrial-grade behavioral standard for mobile engineering. Enforces asymmetric cryptographic signing inside platform hardware enclaves (Apple Secure Enclave, Android StrongBox/TEE) for hybrid Capacitor 7 mobile runtimes. Prevents storing, caching, or transporting private keys and raw authorization bearer tokens in WebView memory (DOM/localStorage/IndexedDB) to thwart runtime memory dumping and cross-site scripting extraction attacks. 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 Session Bearer Tokens in WebView Storage and Emulating Biometric Auth via Web Crypto Soft-Keys 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 Session Bearer Tokens in WebView Storage and Emulating Biometric Auth via Web Crypto Soft-KeysCritical
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 asymmetric ECDSA keys (P-256/secp256r1) directly inside the Secure Enclave (kSecAttrAccessibleAfterFirstUnlockThisDeviceOnly) or Android KeyStore with StrongBox backed protection.

Engineers MUST ALWAYS generate asymmetric ECDSA keys (P-256/secp256r1) directly inside the Secure Enclave (kSecAttrAccessibleAfterFirstUnlockThisDeviceOnly) or Android KeyStore with StrongBox backed protection.

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, OAuth access tokens, or unencrypted refresh tokens in localStorage, sessionStorage, IndexedDB, or Capacitor Preferences.

Engineers MUST NOT store long-lived JWTs, OAuth access tokens, or unencrypted refresh tokens in localStorage, sessionStorage, IndexedDB, or 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

Engineers MUST implement challenge-response authorization where every sensitive transaction or token renewal signs an ephemeral server-generated nonce within the hardware enclave upon explicit biometric validation (BiometricPrompt / LocalAuthentication).

Engineers MUST implement challenge-response authorization where every sensitive transaction or token renewal signs an ephemeral server-generated nonce within the hardware enclave upon explicit biometric validation (BiometricPrompt / LocalAuthentication).

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 verify hardware key attestation chains (Apple App Attest or Android Key Attestation root certificates) on the backend server before provisioning trust to a generated client public key.

Services MUST verify hardware key attestation chains (Apple App Attest or Android Key Attestation root certificates) on the backend server before provisioning trust to a generated client public key.

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

Components NEVER expose private key material or allow signature operations without user biometric interaction or OS-level biometry lock timeouts (setUserAuthenticationRequired(true)).

Components NEVER expose private key material or allow signature operations without user biometric interaction or OS-level biometry lock timeouts (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.
6

Bridge handlers MUST zeroize native memory buffers containing decrypted payloads immediately after passing verified results to bridge responses.

Bridge handlers MUST zeroize native memory buffers containing decrypted payloads immediately after passing verified results to bridge responses.

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 Key Attestation & Enclave Isolation Guardrail critical for AI coding assistants?

Enforces asymmetric cryptographic signing inside platform hardware enclaves (Apple Secure Enclave, Android StrongBox/TEE) for hybrid Capacitor 7 mobile runtimes. Prevents storing, caching, or transporting private keys and raw authorization bearer tokens in WebView memory (DOM/localStorage/IndexedDB) to thwart runtime memory dumping and cross-site scripting extraction attacks. 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 Session Bearer Tokens in WebView Storage and Emulating Biometric Auth via Web Crypto Soft-Keys) 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