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

Capacitor 7 Hardware-Backed Secure Enclave & StrongBox Biometric Binding

Enforces zero-leakage cryptographic operations across Capacitor 7 bridges by anchoring authentication secrets strictly within hardware-isolated boundaries. Requires asymmetric key pairs generated inside iOS Secure Enclave or Android StrongBox with biometric access controls, performing challenge signing exclusively inside native silicon rather than surfacing raw tokens to the WebView memory space.

Prohibited Anti-Pattern: Decoupled Local Biometric Verification Followed by Insecure Secret Retrieval in JavaScript Memory

Export Ready-to-Drop Configuration

Select format below to copy code or download file directly.

---
description: Capacitor 7 Hardware-Backed Secure Enclave & StrongBox Biometric Binding - Enforces zero-leakage cryptographic operations across Capacitor 7 bridges by anchoring authentication secrets strictly within hardware-isolated boundaries. Requires asymmetric key pairs generated inside iOS Secure Enclave or Android StrongBox with biometric access controls, performing challenge signing exclusively inside native silicon rather than surfacing raw tokens to the WebView memory space.
globs: src/**/*.{ts,tsx}, ios/App/App/**/*.{swift,m,h}, android/app/src/main/**/*.{kt,java}
alwaysApply: true
verified_by: "agentrules.org"
license: "CC-BY-4.0"
source: "https://agentrules.org/rules/capacitor-7-hardware-secure-enclave-biometric-binding"
---

# Capacitor 7 Hardware-Backed Secure Enclave & StrongBox Biometric Binding

> **Severity**: CRITICAL | **Category**: mobile
> **Anti-Pattern Warning**: Decoupled Local Biometric Verification Followed by Insecure Secret Retrieval in JavaScript Memory

## System Constraints
You are a Principal Mobile Security Architect enforcing hardware-backed cryptographic biometric authentication in Capacitor 7 applications. Your goal is to eliminate token leakage vulnerabilities across the WebView bridge. You MUST mandate that all biometric authentication relies on native hardware key generation (iOS Secure Enclave via kSecAccessControlBiometryAny/CurrentSet, Android Keystore StrongBox via setUserAuthenticationRequired) where the hardware enclave signs server-issued challenges directly. You MUST reject any design that prompts biometrics via software boolean checks or transmits unencrypted private keys/refresh tokens into the JavaScript runtime.

## Strict Guidelines
- Engineers MUST ALWAYS generate cryptographic keys with hardware-isolation flags: kSecAttrTokenIDSecureEnclave on iOS and setIsStrongBoxBacked(true) with fallback to KeyProperties.PURPOSE_SIGN on Android.
- Engineers MUST NOT store raw enterprise refresh tokens or private keys in Capacitor Preferences, LocalStorage, SQLite, or standard unconstrained Keychain/Keystore instances.
- Services MUST implement server-driven challenge-response protocols: the server issues an ephemeral nonce, which is signed inside the hardware enclave upon successful biometric trigger, returning only the cryptographic signature to the backend.
- Code MUST configure biometric access controls (UserAuthenticationRequired / kSecAccessControlBiometryCurrentSet) so that key usage fails instantly at the silicon level if biometric identity is invalidated, altered, or unauthenticated.
- Components NEVER accept a boolean 'biometricsSucceeded: true' result from native plugins as authorization to access sensitive APIs; authorization MUST require a cryptographically verified enclave signature or hardware-decrypted ephemeral session ticket.

## Bad vs Good Implementations
### Hardware Enclave Challenge Signing vs Naive Biometric Gate

#### Bad Antipattern (AI Common Hallucination)
> **Why it fails**: The bad example treats biometrics as a cosmetic client-side gatekeeper. A compromised WebView, rogue XSS script, or runtime injection (e.g., Frida) can trivially bypass the boolean condition or directly dump the plaintext secret from Preferences/V8 memory.
```typescript
// ANTI-PATTERN: Decoupled biometric check followed by reading raw secret into JS memory
import { BiometricAuth } from '@aparajita/capacitor-biometric-auth';
import { Preferences } from '@capacitor/preferences';

export async function authenticateEnterpriseSession(): Promise<string> {
  // Flaw 1: Boolean biometric check can be hooked or bypassed via Frida/runtime manipulation
  const biometrics = await BiometricAuth.verify({
    reason: 'Scan fingerprint or FaceID to authenticate',
  });

  if (!biometrics.verified) {
    throw new Error('Biometric challenge rejected');
  }

  // Flaw 2: Enterprise token is stored in unencrypted/software storage and exposed directly to WebView V8 heap
  const { value: rawRefreshToken } = await Preferences.get({ key: 'enterprise_refresh_token' });
  if (!rawRefreshToken) {
    throw new Error('Token missing');
  }

  return rawRefreshToken;
}
```

#### Production Standard (Correct)
> **Standard**: The good example utilizes a hardware-backed enclave challenge. The private key resides permanently in hardware silicon and cannot be extracted into the WebView runtime. Authorization is proven via an enclave-produced cryptographic signature over a server nonce, activated only by biometric authorization.
```typescript
// PRODUCTION STANDARD: Challenge-response signing anchored in hardware enclave
import { registerPlugin } from '@capacitor/core';

interface HardwareEnclavePlugin {
  signChallengeWithEnclave(options: {
    keyAlias: string;
    challengeNonce: string;
    promptTitle: string;
  }): Promise<{ signatureBase64: string; algorithm: string }>;
}

const EnclaveBridge = registerPlugin<HardwareEnclavePlugin>('HardwareEnclaveAuth');

export async function authenticateEnterpriseSession(serverNonce: string): Promise<string> {
  if (!serverNonce || serverNonce.length < 32) {
    throw new Error('Cryptographically secure server nonce is required');
  }

  // Key invariant: Private key NEVER exists in software memory.
  // Native layer delegates directly to iOS Secure Enclave (kSecAttrTokenIDSecureEnclave)
  // or Android StrongBox Keystore requiring biometric authentication during the crypto op.
  const { signatureBase64 } = await EnclaveBridge.signChallengeWithEnclave({
    keyAlias: 'enterprise_auth_key',
    challengeNonce: serverNonce,
    promptTitle: 'Authenticate Enterprise Identity'
  });

  // Return only the enclave-generated signature for server-side verification
  return signatureBase64;
}
```

Architectural Specification & Invariant Rationale

Architectural Invariant Design: Capacitor 7 Hardware-Backed Secure Enclave & StrongBox Biometric Binding

Capacitor 7 Hardware-Backed Secure Enclave & StrongBox Biometric Binding defines an industrial-grade behavioral standard for mobile engineering. Enforces zero-leakage cryptographic operations across Capacitor 7 bridges by anchoring authentication secrets strictly within hardware-isolated boundaries. Requires asymmetric key pairs generated inside iOS Secure Enclave or Android StrongBox with biometric access controls, performing challenge signing exclusively inside native silicon rather than surfacing raw tokens to the WebView memory space. 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: Decoupled Local Biometric Verification Followed by Insecure Secret Retrieval in JavaScript 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 DriftDecoupled Local Biometric Verification Followed by Insecure Secret Retrieval in JavaScript 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 generate cryptographic keys with hardware-isolation flags

Engineers MUST ALWAYS generate cryptographic keys with hardware-isolation flags: kSecAttrTokenIDSecureEnclave on iOS and setIsStrongBoxBacked(true) with fallback to KeyProperties.PURPOSE_SIGN 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.
2

Engineers MUST NOT store raw enterprise refresh tokens or private keys in Capacitor Preferences, LocalStorage, SQLite, or standard unconstrained Keychain/Keystore instances.

Engineers MUST NOT store raw enterprise refresh tokens or private keys in Capacitor Preferences, LocalStorage, SQLite, or standard unconstrained Keychain/Keystore instances.

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 server-driven challenge-response protocols

Services MUST implement server-driven challenge-response protocols: the server issues an ephemeral nonce, which is signed inside the hardware enclave upon successful biometric trigger, returning only the cryptographic signature to the backend.

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 configure biometric access controls (UserAuthenticationRequired / kSecAccessControlBiometryCurrentSet) so that key usage fails instantly at the silicon level if biometric identity is invalidated, altered, or unauthenticated.

Code MUST configure biometric access controls (UserAuthenticationRequired / kSecAccessControlBiometryCurrentSet) so that key usage fails instantly at the silicon level if biometric identity is invalidated, altered, or unauthenticated.

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 accept a boolean 'biometricsSucceeded

Components NEVER accept a boolean 'biometricsSucceeded: true' result from native plugins as authorization to access sensitive APIs; authorization MUST require a cryptographically verified enclave signature or hardware-decrypted ephemeral session ticket.

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 Secure Enclave & StrongBox Biometric Binding critical for AI coding assistants?

Enforces zero-leakage cryptographic operations across Capacitor 7 bridges by anchoring authentication secrets strictly within hardware-isolated boundaries. Requires asymmetric key pairs generated inside iOS Secure Enclave or Android StrongBox with biometric access controls, performing challenge signing exclusively inside native silicon rather than surfacing raw tokens to the WebView memory space. 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 (Decoupled Local Biometric Verification Followed by Insecure Secret Retrieval in JavaScript 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

Capacitor