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

Hardware-Backed Biometric Assertion and Secure Enclave Isolation for Capacitor 7

Enforces asymmetric cryptographic signing inside platform hardware secure elements (Apple Secure Enclave, Android StrongBox/TEE) via custom Capacitor 7 bridge plugins. Invariant: Private keys MUST NEVER be exportable or accessible within the hybrid WebView JavaScript realm; the WebView layer is strictly limited to passing ephemeral server challenges and receiving cryptographically signed assertions.

Prohibited Anti-Pattern: Exporting Raw Private Keys or Performing Cryptographic Operations in WebView Memory

Export Ready-to-Drop Configuration

Select format below to copy code or download file directly.

---
description: Hardware-Backed Biometric Assertion and Secure Enclave Isolation for Capacitor 7 - Enforces asymmetric cryptographic signing inside platform hardware secure elements (Apple Secure Enclave, Android StrongBox/TEE) via custom Capacitor 7 bridge plugins. Invariant: Private keys MUST NEVER be exportable or accessible within the hybrid WebView JavaScript realm; the WebView layer is strictly limited to passing ephemeral server challenges and receiving cryptographically signed assertions.
globs: src/**/*.{ts,tsx}, ios/App/App/**/*.{swift,h,m}, android/app/src/main/**/*.{java,kt}
alwaysApply: true
verified_by: "agentrules.org"
license: "CC-BY-4.0"
source: "https://agentrules.org/rules/capacitor7-secure-enclave-biometric-assertion-bridge"
---

# Hardware-Backed Biometric Assertion and Secure Enclave Isolation for Capacitor 7

> **Severity**: CRITICAL | **Category**: mobile
> **Anti-Pattern Warning**: Exporting Raw Private Keys or Performing Cryptographic Operations in WebView Memory

## System Constraints
You are a Principal Mobile Security Architect enforcing zero-trust hardware cryptographic boundaries in Capacitor 7 applications. Your directive is to strictly prohibit symmetric secret storage, raw private key handling, or web-crypto signing inside the hybrid JavaScript/Chromium/WebKit environment. You must enforce that all biometric-bound key-pairs are generated with non-exportable hardware flags (kSecAttrTokenIDSecureEnclave, StrongBox/TEE KeyGenParameterSpec) and executed through an asynchronous assertion bridge requiring server-driven replay-protected challenges.

## Strict Guidelines
- Engineers MUST ALWAYS isolate cryptographic key generation inside native Secure Enclave or Android StrongBox KeyStore providers, exposing only the public key in X.509/SPKI DER format to the WebView.
- Engineers MUST NOT persist private keys, seed phrases, or master encryption keys in WebView Storage, IndexedDB, Capacitor Preferences, or WebKit LocalStorage under any circumstances.
- Code MUST demand an ephemeral, single-use, server-generated cryptographic nonce (challenge) for biometric assertion signatures to prevent transaction replay attacks.
- Services MUST verify biometric assertion signatures on the backend server against the registered public key, rather than relying on boolean native-layer success callbacks like 'biometricAuthenticated: true'.
- Native plugins MUST configure UserPresence or BiometryCurrentSet access control flags (e.g., AccessControlFlags.biometryCurrentSet in Swift and setUserAuthenticationRequired(true) in Kotlin) to invalidate keys when new biometric enrollments occur.
- Components NEVER store or reconstruct high-entropy session secrets directly from JavaScript when an enclave-backed hardware signature satisfies authentication invariants.

## Bad vs Good Implementations
### Flawed Client-Side Biometric Evaluation vs. Hardware-Bound Challenge Signing

#### Bad Antipattern (AI Common Hallucination)
> **Why it fails**: Relies on a bypassable client-side boolean return value ('result.success') and exposes sensitive authorization bearer credentials to the hybrid WebView JavaScript environment, vulnerable to XSS and runtime instrumentation.
```typescript
import { NativeBiometric } from 'capacitor-native-biometric';

// CRITICAL FLAW: Trusting a boolean client-side flag and storing raw tokens in JS storage
export async function authenticateTransaction(payload: Record<string, unknown>): Promise<void> {
  const result = await NativeBiometric.verifyIdentity({
    reason: 'Authenticate to complete transaction',
    title: 'Biometric Verification'
  });

  // Client-side verification can be bypassed via runtime hook / Frida
  if (result.success) {
    const masterToken = localStorage.getItem('MASTER_DEVICE_KEY');
    await fetch('https://api.internal/transact', {
      method: 'POST',
      headers: { 'Authorization': `Bearer ${masterToken}` },
      body: JSON.stringify(payload)
    });
  } else {
    throw new Error('Biometric check failed');
  }
}
```

#### Production Standard (Correct)
> **Standard**: Private keys never enter WebView memory. Authentication relies on an asymmetric signature generated inside platform hardware (Secure Enclave / Android KeyStore) over an ephemeral server nonce, verified authoritatively by the backend API.
```typescript
import { registerPlugin } from '@capacitor/core';

export interface SecureEnclavePlugin {
  signChallenge(options: {
    keyAlias: string;
    challenge: string;
    promptMessage: string;
  }): Promise<{ signature: string; algorithm: 'ES256'; rawAssertion: string }>;
}

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

export async function authenticateTransactionSecurely(payload: Record<string, unknown>): Promise<Response> {
  // 1. Fetch ephemeral server nonce to prevent replay attacks
  const challengeResponse = await fetch('https://api.internal/challenge/issue', { method: 'POST' });
  const { challengeNonce } = await challengeResponse.json() as { challengeNonce: string };

  // 2. Transmit challenge across bridge; signing occurs inside isolated Secure Enclave / StrongBox
  const { signature } = await SecureEnclave.signChallenge({
    keyAlias: 'auth_device_bound_v1',
    challenge: challengeNonce,
    promptMessage: 'Confirm transaction with biometrics'
  });

  // 3. Dispatch payload and cryptographic proof to backend for ECDSA verification
  return fetch('https://api.internal/transact', {
    method: 'POST',
    headers: { 'Content-Type': 'application/json' },
    body: JSON.stringify({
      payload,
      challengeNonce,
      signature
    })
  });
}
```

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 Biometric Assertion and Secure Enclave Isolation for Capacitor 7

Hardware-Backed Biometric Assertion and Secure Enclave Isolation for Capacitor 7 defines an industrial-grade behavioral standard for mobile engineering. Enforces asymmetric cryptographic signing inside platform hardware secure elements (Apple Secure Enclave, Android StrongBox/TEE) via custom Capacitor 7 bridge plugins. Invariant: Private keys MUST NEVER be exportable or accessible within the hybrid WebView JavaScript realm; the WebView layer is strictly limited to passing ephemeral server challenges and receiving cryptographically signed assertions. 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: Exporting Raw Private Keys or Performing Cryptographic Operations in WebView Memory 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 DriftExporting Raw Private Keys or Performing Cryptographic Operations in WebView MemoryCritical
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 isolate cryptographic key generation inside native Secure Enclave or Android StrongBox KeyStore providers, exposing only the public key in X.509/SPKI DER format to the WebView.

Engineers MUST ALWAYS isolate cryptographic key generation inside native Secure Enclave or Android StrongBox KeyStore providers, exposing only the public key in X.509/SPKI DER format to the WebView.

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 persist private keys, seed phrases, or master encryption keys in WebView Storage, IndexedDB, Capacitor Preferences, or WebKit LocalStorage under any circumstances.

Engineers MUST NOT persist private keys, seed phrases, or master encryption keys in WebView Storage, IndexedDB, Capacitor Preferences, or WebKit LocalStorage under any circumstances.

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 MUST demand an ephemeral, single-use, server-generated cryptographic nonce (challenge) for biometric assertion signatures to prevent transaction replay attacks.

Code MUST demand an ephemeral, single-use, server-generated cryptographic nonce (challenge) for biometric assertion signatures to prevent transaction 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.
4

Services MUST verify biometric assertion signatures on the backend server against the registered public key, rather than relying on boolean native-layer success callbacks like 'biometricAuthenticated

Services MUST verify biometric assertion signatures on the backend server against the registered public key, rather than relying on boolean native-layer success callbacks like 'biometricAuthenticated: 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.
5

Native plugins MUST configure UserPresence or BiometryCurrentSet access control flags (e.g., AccessControlFlags.biometryCurrentSet in Swift and setUserAuthenticationRequired(true) in Kotlin) to invalidate keys when new biometric enrollments occur.

Native plugins MUST configure UserPresence or BiometryCurrentSet access control flags (e.g., AccessControlFlags.biometryCurrentSet in Swift and setUserAuthenticationRequired(true) in Kotlin) to invalidate keys when new biometric enrollments occur.

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 or reconstruct high-entropy session secrets directly from JavaScript when an enclave-backed hardware signature satisfies authentication invariants.

Components NEVER store or reconstruct high-entropy session secrets directly from JavaScript when an enclave-backed hardware signature satisfies authentication invariants.

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 Biometric Assertion and Secure Enclave Isolation for Capacitor 7 critical for AI coding assistants?

Enforces asymmetric cryptographic signing inside platform hardware secure elements (Apple Secure Enclave, Android StrongBox/TEE) via custom Capacitor 7 bridge plugins. Invariant: Private keys MUST NEVER be exportable or accessible within the hybrid WebView JavaScript realm; the WebView layer is strictly limited to passing ephemeral server challenges and receiving cryptographically signed assertions. 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 (Exporting Raw Private Keys or Performing Cryptographic Operations in WebView Memory) 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