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

Capacitor 7 Hardware-Backed Keystore Cryptographic Interop Contract

Enforces asymmetric payload signing exclusively within the native hardware Secure Enclave or Android Keystore via Capacitor 7 native bridges. Eliminates the persistence or exposure of raw cryptographic private keys, refresh tokens, and master credentials within the hybrid WebView JavaScript context. Mandates proof-of-possession signing using ephemeral challenge-response mechanics.

Prohibited Anti-Pattern: Exposing Raw Private Keys or Storing Static Bearer Tokens in WebView Storage

Export Ready-to-Drop Configuration

Select format below to copy code or download file directly.

---
description: Capacitor 7 Hardware-Backed Keystore Cryptographic Interop Contract - Enforces asymmetric payload signing exclusively within the native hardware Secure Enclave or Android Keystore via Capacitor 7 native bridges. Eliminates the persistence or exposure of raw cryptographic private keys, refresh tokens, and master credentials within the hybrid WebView JavaScript context. Mandates proof-of-possession signing using ephemeral challenge-response mechanics.
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/capacitor7-biometric-secure-enclave-interop"
---

# Capacitor 7 Hardware-Backed Keystore Cryptographic Interop Contract

> **Severity**: CRITICAL | **Category**: mobile
> **Anti-Pattern Warning**: Exposing Raw Private Keys or Storing Static Bearer Tokens in WebView Storage

## System Constraints
You are a Principal Mobile Security Architect enforcing the Capacitor 7 Biometric Hardware-Backed Keystore Interop Contract. You must reject any pattern that deserializes, buffers, or retains raw cryptographic private keys or long-lived authentication bearer tokens inside the JavaScript runtime (LocalStorage, IndexedDB, or in-memory variables). Mandate that all cryptographic assertion is delegated to native plugins leveraging iOS Secure Enclave (kSecAccessControlBiometryAny) or Android KeyStore (KeyGenParameterSpec with setUserAuthenticationRequired). The JavaScript layer may only receive transient challenges from the backend and hand them off to the native bridge to obtain detached signatures.

## Strict Guidelines
- Engineers MUST NEVER transfer, export, or reconstruct asymmetric private keys inside the JavaScript runtime context.
- Engineers MUST configure native Android Keystore keys with setUserAuthenticationRequired(true) and setUserAuthenticationParameters with biometric flags.
- Engineers MUST configure iOS Keychain entries using SecAccessControlCreateWithFlags with kSecAccessControlBiometryCurrentSet or kSecAccessControlBiometryAny.
- Code MUST transmit an ephemeral cryptographic challenge and a target payload to the native plugin bridge, receiving only a detached signature (DER or R+S) and public key thumbprint.
- Services MUST implement server-driven challenge-response sequences to prevent replay attacks, refusing static token caching in Capacitor Preferences or local web storage.
- Components NEVER store JWT refresh tokens or auth tokens in localStorage or IndexedDB; auth states must be verified through hardware-signed assertions.

## Bad vs Good Implementations
### Biometric Authentication via Hardware Signing vs In-Memory Key Extraction

#### Bad Antipattern (AI Common Hallucination)
> **Why it fails**: The code uses biometrics as a cosmetic gate rather than a hardware-enforced decrypt/sign prerequisite. The private key resides in unencrypted software storage accessible to any WebView script or XSS injection, violating TEE/Secure Enclave boundary guarantees.
```typescript
import { Preferences } from '@capacitor/preferences';
import { NativeBiometric } from 'capacitor-native-biometric';

export async function signTransactionBad(payload: object): Promise<string> {
  // Flaw 1: Validating biometrics via boolean check, not hardware key access
  const verified = await NativeBiometric.verifyIdentity({
    reason: 'Authenticate to sign payload'
  });
  
  if (!verified) throw new Error('Biometric failed');

  // Flaw 2: Storing raw private key/session secret in JS-accessible storage
  const { value: rawPrivateKey } = await Preferences.get({ key: 'user_private_key' });
  if (!rawPrivateKey) throw new Error('Key missing');

  // Flaw 3: Signing in JS context, exposing keys to XSS & memory inspection
  return signWithSoftwareKey(JSON.stringify(payload), rawPrivateKey);
}

declare function signWithSoftwareKey(p: string, k: string): string;
```

#### Production Standard (Correct)
> **Standard**: The signature operation delegates directly to a custom Capacitor native bridge. The private key is bound within hardware (Secure Enclave / Android Keystore) and cannot be extracted into memory. The WebView only holds the transient challenge and detached signature.
```typescript
import { registerPlugin } from '@capacitor/core';

export interface SecureBiometricSignerPlugin {
  signChallengeWithHardwareKey(options: {
    challenge: string;
    payloadHash: string;
    promptMessage: string;
  }): Promise<{ signature: string; keyId: string }>;
}

const BiometricSigner = registerPlugin<SecureBiometricSignerPlugin>('SecureBiometricSigner');

export async function signTransactionSecure(
  serverChallenge: string,
  payload: Record<string, unknown>
): Promise<{ signature: string; keyId: string }> {
  // Invariant 1: Ensure challenge is non-empty and strictly ephemeral
  if (!serverChallenge || typeof serverChallenge !== 'string') {
    throw new Error('Invalid authentication challenge');
  }

  // Invariant 2: Hash payload locally; never serialize raw secret state
  const encoder = new TextEncoder();
  const data = encoder.encode(JSON.stringify(payload));
  const hashBuffer = await crypto.subtle.digest('SHA-256', data);
  const payloadHash = Array.from(new Uint8Array(hashBuffer))
    .map((b) => b.toString(16).padStart(2, '0'))
    .join('');

  // Invariant 3: Hardware enclave executes signature natively upon biometric unlock.
  // Raw private key never touches the V8/JSC runtime.
  return await BiometricSigner.signChallengeWithHardwareKey({
    challenge: serverChallenge,
    payloadHash,
    promptMessage: 'Authorize critical operation'
  });
}
```

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 Keystore Cryptographic Interop Contract

Capacitor 7 Hardware-Backed Keystore Cryptographic Interop Contract defines an industrial-grade behavioral standard for mobile engineering. Enforces asymmetric payload signing exclusively within the native hardware Secure Enclave or Android Keystore via Capacitor 7 native bridges. Eliminates the persistence or exposure of raw cryptographic private keys, refresh tokens, and master credentials within the hybrid WebView JavaScript context. Mandates proof-of-possession signing using ephemeral challenge-response mechanics. 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 or Storing Static Bearer Tokens in WebView 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 or Storing Static Bearer Tokens in WebView 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 NEVER transfer, export, or reconstruct asymmetric private keys inside the JavaScript runtime context.

Engineers MUST NEVER transfer, export, or reconstruct asymmetric private keys inside the JavaScript runtime 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.
2

Engineers MUST configure native Android Keystore keys with setUserAuthenticationRequired(true) and setUserAuthenticationParameters with biometric flags.

Engineers MUST configure native Android Keystore keys with setUserAuthenticationRequired(true) and setUserAuthenticationParameters with biometric flags.

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 configure iOS Keychain entries using SecAccessControlCreateWithFlags with kSecAccessControlBiometryCurrentSet or kSecAccessControlBiometryAny.

Engineers MUST configure iOS Keychain entries using SecAccessControlCreateWithFlags with kSecAccessControlBiometryCurrentSet or kSecAccessControlBiometryAny.

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

Code MUST transmit an ephemeral cryptographic challenge and a target payload to the native plugin bridge, receiving only a detached signature (DER or R+S) and public key thumbprint.

Code MUST transmit an ephemeral cryptographic challenge and a target payload to the native plugin bridge, receiving only a detached signature (DER or R+S) and public key thumbprint.

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

Services MUST implement server-driven challenge-response sequences to prevent replay attacks, refusing static token caching in Capacitor Preferences or local web storage.

Services MUST implement server-driven challenge-response sequences to prevent replay attacks, refusing static token caching in Capacitor Preferences or local web storage.

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 store JWT refresh tokens or auth tokens in localStorage or IndexedDB

Components NEVER store JWT refresh tokens or auth tokens in localStorage or IndexedDB; auth states must be verified through hardware-signed assertions.

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 Keystore Cryptographic Interop Contract critical for AI coding assistants?

Enforces asymmetric payload signing exclusively within the native hardware Secure Enclave or Android Keystore via Capacitor 7 native bridges. Eliminates the persistence or exposure of raw cryptographic private keys, refresh tokens, and master credentials within the hybrid WebView JavaScript context. Mandates proof-of-possession signing using ephemeral challenge-response mechanics. 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 or Storing Static Bearer Tokens in WebView 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