This specification is maintained by the AgentRules Working Group. Have enhancements or want to claim maintainership?Submit Specification →
mobilecritical PriorityID: capacitor-secure-enclave-hardware-attested-derivation

Capacitor 7 Secure Enclave Hardware-Attested Key Derivation Standard

Enforces hardware-backed cryptographic operations directly within the hardware security module (Apple Secure Enclave / Android StrongBox Keystore) rather than trusting boolean bridge responses from biometric prompts. Dynamic memory injection tools (e.g., Frida, Objection) can trivially hook JavaScript-to-native bridges and boolean biometric evaluations; authentication must be cryptographically bound to hardware key unwrap/signing operations with server-nonce attestation.

Prohibited Anti-Pattern: Trusting Boolean Biometric Bridge Responses and Decoupling Biometric Prompts from Hardware Cryptographic Operations

Export Ready-to-Drop Configuration

Select format below to copy code or download file directly.

---
description: Capacitor 7 Secure Enclave Hardware-Attested Key Derivation Standard - Enforces hardware-backed cryptographic operations directly within the hardware security module (Apple Secure Enclave / Android StrongBox Keystore) rather than trusting boolean bridge responses from biometric prompts. Dynamic memory injection tools (e.g., Frida, Objection) can trivially hook JavaScript-to-native bridges and boolean biometric evaluations; authentication must be cryptographically bound to hardware key unwrap/signing operations with server-nonce attestation.
globs: src/**/*.{ts,tsx}, ios/App/App/**/*.{swift,m}, android/app/src/main/java/**/*.{java,kt}
alwaysApply: true
verified_by: "agentrules.org"
license: "CC-BY-4.0"
source: "https://agentrules.org/rules/capacitor-secure-enclave-hardware-attested-derivation"
---

# Capacitor 7 Secure Enclave Hardware-Attested Key Derivation Standard

> **Severity**: CRITICAL | **Category**: mobile
> **Anti-Pattern Warning**: Trusting Boolean Biometric Bridge Responses and Decoupling Biometric Prompts from Hardware Cryptographic Operations

## System Constraints
You are a Principal Mobile Security Architect enforcing the Capacitor 7 Secure Enclave Hardware-Attested Key Derivation Standard. You must reject any implementation where biometric authentication returns a boolean state used to unlock client-side secrets. Mandate that all sensitive operations use cryptographic challenges signed or decrypted directly within the Secure Enclave or Android StrongBox KeyStore requiring hardware-level biometric gatekeeping.

## Strict Guidelines
- Engineers MUST NEVER rely on boolean checks (e.g., `BiometricAuth.verify({ ... }).success === true`) to unlock secrets or authorize critical operations in the Web layer.
- Engineers MUST require keys to be generated in hardware (`kSecAttrAccessControl` with `.biometryCurrentSet` on iOS; `KeyGenParameterSpec` with `setUserAuthenticationRequired(true)` and `AUTH_BIOMETRIC_STRONG` on Android).
- Services MUST implement a Challenge-Response protocol: the backend generates a cryptographically secure ephemeral nonce (e.g., 32-byte CSPRNG) that the hardware module signs using the hardware-bound private key.
- Code MUST invalidate keys when biometrics change by using hardware flags (`kSecAccessControlBiometryCurrentSet` on iOS, `setInvalidatedByBiometricEnrollment(true)` on Android StrongBox).
- Components NEVER store encryption master keys in `CapacitorPreferences`, `localStorage`, or standard non-hardware-backed keychains.
- Native plugins MUST perform the hardware cryptographic operation directly during the prompt lifecycle, failing completely if the secure element rejects the derivation challenge.

## Bad vs Good Implementations
### Vulnerable Boolean Biometric Gate vs. Hardware-Attested Nonce Signing

#### Bad Antipattern (AI Common Hallucination)
> **Why it fails**: The Web layer checks a boolean flag returned across the Capacitor bridge. An attacker using Frida or runtime instrumentation can hook NativeBiometric.verifyIdentity to return true, bypassing authentication entirely and obtaining the token stored in insecure storage.
```typescript
import { NativeBiometric } from 'capacitor-native-biometric';
import { Preferences } from '@capacitor/preferences';

export async function authenticateAndExecute(payload: unknown): Promise<void> {
  // VULNERABLE: Frida hook can intercept this method call
  // and return { isVerified: true } without any biometric interaction.
  const result = await NativeBiometric.verifyIdentity({
    reason: 'Authenticate to sign transaction',
    title: 'Sign In'
  });

  if (result.isVerified) {
    // VULNERABLE: Secret retrieved into memory via insecure storage
    // after a bypassable boolean check
    const rawToken = await Preferences.get({ key: 'auth_token' });
    await fetch('https://api.example.com/execute', {
      method: 'POST',
      headers: { Authorization: `Bearer ${rawToken.value}` },
      body: JSON.stringify(payload)
    });
  } else {
    throw new Error('Biometric authentication failed');
  }
}
```

#### Production Standard (Correct)
> **Standard**: Eliminates the boolean check vulnerability. The biometric prompt is hardware-gated by the Secure Enclave / StrongBox Keystore. The private key cannot be accessed directly or hooked in JavaScript memory, and transaction authorization is mathematically attested through an ephemeral server-issued nonce.
```typescript
import { registerPlugin } from '@capacitor/core';

interface HardwareKeyPlugin {
  signChallengeWithHardwareKey(options: {
    alias: string;
    challenge: string;
    promptTitle: string;
  }): Promise<{ signature: string; keyId: string }>;
}

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

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

  // 2. Hardware crypto operation: Secure Enclave/StrongBox prompts user and signs the nonce
  // inside isolated silicon. The private key never enters application memory.
  const { signature, keyId } = await SecureEnclave.signChallengeWithHardwareKey({
    alias: 'enterprise_session_key',
    challenge,
    promptTitle: 'Authorize Transaction'
  });

  // 3. Server validates cryptographic signature against enrolled public key
  const response = await fetch('https://api.example.com/execute', {
    method: 'POST',
    headers: { 'Content-Type': 'application/json' },
    body: JSON.stringify({
      payload,
      keyId,
      challenge,
      signature
    })
  });

  if (!response.ok) {
    throw new Error('Cryptographic signature verification failed');
  }
}
```

Architectural Specification & Invariant Rationale

Architectural Invariant Design: Capacitor 7 Secure Enclave Hardware-Attested Key Derivation Standard

Capacitor 7 Secure Enclave Hardware-Attested Key Derivation Standard defines an industrial-grade behavioral standard for mobile engineering. Enforces hardware-backed cryptographic operations directly within the hardware security module (Apple Secure Enclave / Android StrongBox Keystore) rather than trusting boolean bridge responses from biometric prompts. Dynamic memory injection tools (e.g., Frida, Objection) can trivially hook JavaScript-to-native bridges and boolean biometric evaluations; authentication must be cryptographically bound to hardware key unwrap/signing operations with server-nonce attestation. 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 Boolean Biometric Bridge Responses and Decoupling Biometric Prompts from Hardware Cryptographic Operations 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 Boolean Biometric Bridge Responses and Decoupling Biometric Prompts from Hardware Cryptographic OperationsCritical
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 rely on boolean checks (e.g., `BiometricAuth.verify({ ... }).success === true`) to unlock secrets or authorize critical operations in the Web layer.

Engineers MUST NEVER rely on boolean checks (e.g., `BiometricAuth.verify({ ... }).success === true`) to unlock secrets or authorize critical operations in the Web layer.

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 require keys to be generated in hardware (`kSecAttrAccessControl` with `.biometryCurrentSet` on iOS

Engineers MUST require keys to be generated in hardware (`kSecAttrAccessControl` with `.biometryCurrentSet` on iOS; `KeyGenParameterSpec` with `setUserAuthenticationRequired(true)` and `AUTH_BIOMETRIC_STRONG` on Android).

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

Services MUST implement a Challenge-Response protocol

Services MUST implement a Challenge-Response protocol: the backend generates a cryptographically secure ephemeral nonce (e.g., 32-byte CSPRNG) that the hardware module signs using the hardware-bound private 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

Code MUST invalidate keys when biometrics change by using hardware flags (`kSecAccessControlBiometryCurrentSet` on iOS, `setInvalidatedByBiometricEnrollment(true)` on Android StrongBox).

Code MUST invalidate keys when biometrics change by using hardware flags (`kSecAccessControlBiometryCurrentSet` on iOS, `setInvalidatedByBiometricEnrollment(true)` on Android StrongBox).

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 encryption master keys in `CapacitorPreferences`, `localStorage`, or standard non-hardware-backed keychains.

Components NEVER store encryption master keys in `CapacitorPreferences`, `localStorage`, or standard non-hardware-backed keychains.

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

Native plugins MUST perform the hardware cryptographic operation directly during the prompt lifecycle, failing completely if the secure element rejects the derivation challenge.

Native plugins MUST perform the hardware cryptographic operation directly during the prompt lifecycle, failing completely if the secure element rejects the derivation challenge.

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 Secure Enclave Hardware-Attested Key Derivation Standard critical for AI coding assistants?

Enforces hardware-backed cryptographic operations directly within the hardware security module (Apple Secure Enclave / Android StrongBox Keystore) rather than trusting boolean bridge responses from biometric prompts. Dynamic memory injection tools (e.g., Frida, Objection) can trivially hook JavaScript-to-native bridges and boolean biometric evaluations; authentication must be cryptographically bound to hardware key unwrap/signing operations with server-nonce attestation. 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 Boolean Biometric Bridge Responses and Decoupling Biometric Prompts from Hardware Cryptographic Operations) 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