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

Hardware-Backed KeyStore & Enclave Attestation Bridge Standard

Enforces a zero-trust bridge architecture between Capacitor 7 WebViews and native hardware security modules (Apple Secure Enclave and Android StrongBox/TEE KeyStore). Mandates that cryptographic keys never enter the JavaScript execution context and signatures are bound to server-generated nonces verified exclusively on remote backends.

Prohibited Anti-Pattern: Trusting Client-Side Biometric Booleans and Storing Ephemeral Private Keys in WebView Contexts

Export Ready-to-Drop Configuration

Select format below to copy code or download file directly.

---
description: Hardware-Backed KeyStore & Enclave Attestation Bridge Standard - Enforces a zero-trust bridge architecture between Capacitor 7 WebViews and native hardware security modules (Apple Secure Enclave and Android StrongBox/TEE KeyStore). Mandates that cryptographic keys never enter the JavaScript execution context and signatures are bound to server-generated nonces verified exclusively on remote backends.
globs: src/**/*.{ts,tsx}, ios/App/**/*.{swift,m}, android/app/**/*.{kt,java}
alwaysApply: true
verified_by: "agentrules.org"
license: "CC-BY-4.0"
source: "https://agentrules.org/rules/capacitor-7-hardware-keystore-attestation-bridge-capacitor-7-hard-749"
---

# Hardware-Backed KeyStore & Enclave Attestation Bridge Standard

> **Severity**: CRITICAL | **Category**: mobile
> **Anti-Pattern Warning**: Trusting Client-Side Biometric Booleans and Storing Ephemeral Private Keys in WebView Contexts

## System Constraints
You are a Principal Mobile Systems and Security Architect enforcing zero-trust hardware attestation in Capacitor 7 applications. The JavaScript environment (WebView) must be treated as completely compromised or untrusted. You must ensure that all biometric operations, cryptographic identity assertions, and key generations execute strictly inside native hardware boundaries (Apple Secure Enclave, Android StrongBox Keymaster/TEE). JavaScript must act solely as an orchestrator for passing opaque challenges and receiving signed attestation payloads. Never accept boolean success flags from biometric plugins as proof of authentication.

## Strict Guidelines
- Engineers MUST NEVER generate, store, or import raw asymmetric private keys inside the JavaScript/WebView runtime (e.g., LocalStorage, IndexedDB, or WebCrypto).
- Engineers MUST ALWAYS require a server-generated cryptographic nonce/challenge for every biometric signing operation to prevent replay attacks.
- Code SHOULD verify hardware attestation certificate chains on the remote backend before provisioning or trusting any client public key.
- Services MUST configure native keys using Android KeyGenParameterSpec with setIsStrongBoxBacked(true) and setUserAuthenticationRequired(true), or iOS SecAccessControlCreateWithFlags with kSecAccessControlBiometryCurrentSet.
- Components NEVER determine authorization based on boolean bridge return values like `result.authenticated === true`; authorization must be strictly validated by the backend through signature verification against the registered hardware key.

## Bad vs Good Implementations
### Vulnerable Bridge: Client-Side Biometric Gate with Local Key Storage

#### Bad Antipattern (AI Common Hallucination)
> **Why it fails**: The authentication gate relies on a vulnerable boolean flag returned across the Capacitor bridge, which can be trivial to patch using instrumentation frameworks like Frida. Additionally, the signing key resides in WebView accessible storage rather than hardware-isolated security modules.
```typescript
import { NativeBiometric } from 'capacitor-native-biometric';
import { Preferences } from '@capacitor/preferences';

export async function authorizeTransaction(transactionId: string, amount: number) {
  // ANTI-PATTERN: Relying on a boolean result across the bridge.
  // An attacker with WebView injection or Frida can hook this call to return true.
  const result = await NativeBiometric.verifyIdentity({
    reason: 'Confirm transaction',
    title: 'Biometric Authentication',
  });

  if (result.authenticated) {
    // ANTI-PATTERN: Private key or bearer token retrieved and used inside JS environment
    const { value: privateKeyHex } = await Preferences.get({ key: 'client_signing_key' });
    const payload = JSON.stringify({ transactionId, amount, timestamp: Date.now() });
    
    // Sign locally in JS without hardware isolation
    const signature = await insecureJsSign(payload, privateKeyHex!);
    return fetch('/api/v1/transfer', {
      method: 'POST',
      headers: { 'Content-Type': 'application/json' },
      body: JSON.stringify({ payload, signature }),
    });
  }
  throw new Error('Biometrics failed');
}
```

#### Production Standard (Correct)
> **Standard**: JavaScript acts only as an orchestrator. The server provides a cryptographically random, replay-protected nonce. The native bridge passes the nonce to the hardware security module (Secure Enclave / Android StrongBox KeyStore), where biometric authorization directly unblocks the hardware key operation. The private key never touches WebView memory, and authorization is validated on the backend via mathematical signature verification.
```typescript
import { registerPlugin } from '@capacitor/core';

export interface HardwareSignatureResult {
  keyAlias: string;
  signatureBase64: string;
  signedNonce: string;
  algorithm: 'SHA256withECDSA';
}

export interface SecureBridgePlugin {
  signChallengeWithHardwareKey(options: {
    keyAlias: string;
    challenge: string;
    promptMessage: string;
  }): Promise<HardwareSignatureResult>;
}

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

export async function authorizeTransaction(transactionId: string, amount: number): Promise<Response> {
  // 1. Fetch single-use cryptographic challenge directly from secure backend
  const challengeRes = await fetch('/api/v1/auth/challenge', {
    method: 'POST',
    headers: { 'Content-Type': 'application/json' },
    body: JSON.stringify({ transactionId, amount }),
  });
  const { challenge } = (await challengeRes.json()) as { challenge: string };

  // 2. Hardware Enclave/TEE prompts user natively and signs the challenge directly.
  // The private key is non-exportable and never leaves the hardware security boundary.
  const hardwareSignature = await SecureBridge.signChallengeWithHardwareKey({
    keyAlias: 'auth_attestation_key',
    challenge,
    promptMessage: `Authorize transfer of $${amount.toFixed(2)}`,
  });

  // 3. Delegate signature verification entirely to the remote backend
  return fetch('/api/v1/transfer/verify-and-execute', {
    method: 'POST',
    headers: { 'Content-Type': 'application/json' },
    body: JSON.stringify({
      transactionId,
      amount,
      challenge: hardwareSignature.signedNonce,
      signature: hardwareSignature.signatureBase64,
      keyAlias: hardwareSignature.keyAlias,
    }),
  });
}
```

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 KeyStore & Enclave Attestation Bridge Standard

Hardware-Backed KeyStore & Enclave Attestation Bridge Standard defines an industrial-grade behavioral standard for mobile engineering. Enforces a zero-trust bridge architecture between Capacitor 7 WebViews and native hardware security modules (Apple Secure Enclave and Android StrongBox/TEE KeyStore). Mandates that cryptographic keys never enter the JavaScript execution context and signatures are bound to server-generated nonces verified exclusively on remote backends. 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: Trusting Client-Side Biometric Booleans and Storing Ephemeral Private Keys in WebView Contexts 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 DriftTrusting Client-Side Biometric Booleans and Storing Ephemeral Private Keys in WebView ContextsCritical
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 generate, store, or import raw asymmetric private keys inside the JavaScript/WebView runtime (e.g., LocalStorage, IndexedDB, or WebCrypto).

Engineers MUST NEVER generate, store, or import raw asymmetric private keys inside the JavaScript/WebView runtime (e.g., LocalStorage, IndexedDB, or WebCrypto).

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 require a server-generated cryptographic nonce/challenge for every biometric signing operation to prevent replay attacks.

Engineers MUST ALWAYS require a server-generated cryptographic nonce/challenge for every biometric signing operation to prevent replay attacks.

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 verify hardware attestation certificate chains on the remote backend before provisioning or trusting any client public key.

Code SHOULD verify hardware attestation certificate chains on the remote backend before provisioning or trusting any 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.
4

Services MUST configure native keys using Android KeyGenParameterSpec with setIsStrongBoxBacked(true) and setUserAuthenticationRequired(true), or iOS SecAccessControlCreateWithFlags with kSecAccessControlBiometryCurrentSet.

Services MUST configure native keys using Android KeyGenParameterSpec with setIsStrongBoxBacked(true) and setUserAuthenticationRequired(true), or iOS SecAccessControlCreateWithFlags with kSecAccessControlBiometryCurrentSet.

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 determine authorization based on boolean bridge return values like `result.authenticated === true`

Components NEVER determine authorization based on boolean bridge return values like `result.authenticated === true`; authorization must be strictly validated by the backend through signature verification against the registered hardware 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.
Technical Questions & Answers

Frequently Asked Technical Questions

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

Q:Why is Hardware-Backed KeyStore & Enclave Attestation Bridge Standard critical for AI coding assistants?

Enforces a zero-trust bridge architecture between Capacitor 7 WebViews and native hardware security modules (Apple Secure Enclave and Android StrongBox/TEE KeyStore). Mandates that cryptographic keys never enter the JavaScript execution context and signatures are bound to server-generated nonces verified exclusively on remote backends. 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 (Trusting Client-Side Biometric Booleans and Storing Ephemeral Private Keys in WebView Contexts) 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