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

Capacitor 7 Hardware-Backed Biometric Keystore and Attestation Standard

Enforces hardware-backed cryptographic key isolation using platform Secure Enclaves and StrongBox KeyStore implementations under Capacitor 7. Prohibits exposing raw private key material or long-lived authentication tokens to the JavaScript runtime heap and mandates native biometric hardware gates and server-verified attestation nonces.

Prohibited Anti-Pattern: Exposing Raw Private Keys Across the Webview Bridge and Persisting Secrets in Unattested Unbound Storage

Export Ready-to-Drop Configuration

Select format below to copy code or download file directly.

---
description: Capacitor 7 Hardware-Backed Biometric Keystore and Attestation Standard - Enforces hardware-backed cryptographic key isolation using platform Secure Enclaves and StrongBox KeyStore implementations under Capacitor 7. Prohibits exposing raw private key material or long-lived authentication tokens to the JavaScript runtime heap and mandates native biometric hardware gates and server-verified attestation nonces.
globs: src/**/*.{ts,tsx}, android/app/src/**/*.{java,kt}, ios/App/App/**/*.{swift,m}
alwaysApply: true
verified_by: "agentrules.org"
license: "CC-BY-4.0"
source: "https://agentrules.org/rules/capacitor-7-biometric-keystore-hardware-attestation"
---

# Capacitor 7 Hardware-Backed Biometric Keystore and Attestation Standard

> **Severity**: CRITICAL | **Category**: mobile
> **Anti-Pattern Warning**: Exposing Raw Private Keys Across the Webview Bridge and Persisting Secrets in Unattested Unbound Storage

## System Constraints
You are a Principal Mobile Security Architect enforcing the Capacitor 7 Biometric Hardware Keystore Key-Attestation Standard. Mandate that private keys never cross the Webview bridge into the V8/JSCore heap, all asymmetric signing is delegated to iOS Secure Enclave or Android StrongBox/TEE Keystore with hardware biometric authorization, and key creation is validated against server-issued attestation challenges.

## Strict Guidelines
- Engineers MUST ALWAYS delegate cryptographic signing and decryption directly to native hardware isolation modules (iOS Secure Enclave, Android TEE/StrongBox) rather than JavaScript libraries.
- Engineers MUST NOT transfer, export, or deserialize unencrypted private keys or hardware seed material across the Capacitor JavaScript bridge.
- Code SHOULD bind keys to biometrics using `kSecAccessControlBiometryCurrentSet` (iOS) or `KeyProperties.AUTH_BIOMETRIC_STRONG` with `setUserAuthenticationRequired(true)` (Android) to invalidate keys if biometrics change.
- Services MUST request a cryptographically secure nonce from the backend server and verify the resulting hardware attestation certificate chain before binding public keys to user accounts.
- Components NEVER store sensitive tokens or high-entropy secrets in `@capacitor/preferences`, `localStorage`, or standard unencrypted IndexedDB.

## Bad vs Good Implementations
### Hardware-Enclave Biometric Signing vs. In-Memory Webview Key Storage

#### Bad Antipattern (AI Common Hallucination)
> **Why it fails**: The private key is stored in unencrypted storage and imported directly into the JavaScript heap inside the Webview. A memory dump, XSS injection, or rooted/jailbroken runtime inspection (e.g., Frida hook) will extract the unprotected private key.
```typescript
import { Preferences } from '@capacitor/preferences';
import * as jose from 'jose';

export async function signAuthPayload(payload: Record<string, unknown>): Promise<string> {
  // Flaw 1: Private key stored in insecure, unencrypted Preferences
  const { value: rawPrivateKeyPem } = await Preferences.get({ key: 'client_private_key' });
  if (!rawPrivateKeyPem) {
    throw new Error('Key not found');
  }

  // Flaw 2: Sensitive private key imported into JavaScript heap, vulnerable to memory dumping
  const privateKey = await jose.importPKCS8(rawPrivateKeyPem, 'RS256');
  
  // Flaw 3: Signing performed in V8 runtime with no biometric hardware gate
  return await new jose.SignJWT(payload)
    .setProtectedHeader({ alg: 'RS256' })
    .setIssuedAt()
    .sign(privateKey);
}
```

#### Production Standard (Correct)
> **Standard**: The private key is generated within and isolated inside the platform Secure Enclave / StrongBox Keystore. The JavaScript runtime only passes the payload to be signed across the bridge. Biometric authentication is enforced by the native OS kernel, and only the resulting signature returns to the Webview.
```typescript
import { registerPlugin } from '@capacitor/core';

export interface SecureEnclavePlugin {
  generateAttestedKeyPair(options: { challengeNonce: string }): Promise<{
    publicKey: string;
    attestationCertificateChain: string[];
  }>;
  signHardwarePayload(options: {
    keyAlias: string;
    promptMessage: string;
    payloadBase64: string;
  }): Promise<{ signatureBase64: string }>;
}

const SecureEnclave = registerPlugin<SecureEnclavePlugin>('SecureEnclave');

export async function signAuthPayloadSecurely(
  keyAlias: string,
  payload: Record<string, unknown>
): Promise<string> {
  // Ensure payload serialization is canonical before transit
  const payloadBytes = new TextEncoder().encode(JSON.stringify(payload));
  const payloadBase64 = btoa(String.fromCharCode(...payloadBytes));

  // Hardware enclave handles biometric prompt natively; private key never touches the JS heap
  const result = await SecureEnclave.signHardwarePayload({
    keyAlias,
    promptMessage: 'Authenticate to authorize secure transaction',
    payloadBase64,
  });

  return result.signatureBase64;
}
```

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 and Attestation Standard

Capacitor 7 Hardware-Backed Biometric Keystore and Attestation Standard defines an industrial-grade behavioral standard for mobile engineering. Enforces hardware-backed cryptographic key isolation using platform Secure Enclaves and StrongBox KeyStore implementations under Capacitor 7. Prohibits exposing raw private key material or long-lived authentication tokens to the JavaScript runtime heap and mandates native biometric hardware gates and server-verified attestation nonces. 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: Exposing Raw Private Keys Across the Webview Bridge and Persisting Secrets in Unattested Unbound Storage 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 DriftExposing Raw Private Keys Across the Webview Bridge and Persisting Secrets in Unattested Unbound StorageCritical
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 delegate cryptographic signing and decryption directly to native hardware isolation modules (iOS Secure Enclave, Android TEE/StrongBox) rather than JavaScript libraries.

Engineers MUST ALWAYS delegate cryptographic signing and decryption directly to native hardware isolation modules (iOS Secure Enclave, Android TEE/StrongBox) rather than JavaScript libraries.

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 transfer, export, or deserialize unencrypted private keys or hardware seed material across the Capacitor JavaScript bridge.

Engineers MUST NOT transfer, export, or deserialize unencrypted private keys or hardware seed material across the Capacitor JavaScript bridge.

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 bind keys to biometrics using `kSecAccessControlBiometryCurrentSet` (iOS) or `KeyProperties.AUTH_BIOMETRIC_STRONG` with `setUserAuthenticationRequired(true)` (Android) to invalidate keys if biometrics change.

Code SHOULD bind keys to biometrics using `kSecAccessControlBiometryCurrentSet` (iOS) or `KeyProperties.AUTH_BIOMETRIC_STRONG` with `setUserAuthenticationRequired(true)` (Android) to invalidate keys if biometrics 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.
4

Services MUST request a cryptographically secure nonce from the backend server and verify the resulting hardware attestation certificate chain before binding public keys to user accounts.

Services MUST request a cryptographically secure nonce from the backend server and verify the resulting hardware attestation certificate chain before binding public keys to user accounts.

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 store sensitive tokens or high-entropy secrets in `@capacitor/preferences`, `localStorage`, or standard unencrypted IndexedDB.

Components NEVER store sensitive tokens or high-entropy secrets in `@capacitor/preferences`, `localStorage`, or standard unencrypted IndexedDB.

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 and Attestation Standard critical for AI coding assistants?

Enforces hardware-backed cryptographic key isolation using platform Secure Enclaves and StrongBox KeyStore implementations under Capacitor 7. Prohibits exposing raw private key material or long-lived authentication tokens to the JavaScript runtime heap and mandates native biometric hardware gates and server-verified attestation nonces. 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 (Exposing Raw Private Keys Across the Webview Bridge and Persisting Secrets in Unattested Unbound Storage) 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