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

Capacitor 7 Hardware-Backed Biometric Authentication & Cryptographic Attestation Standard

Enforces hardware-backed cryptographic key isolation for biometric authentication in Capacitor 7 hybrid mobile applications. Mandates that biometric verification produces an asymmetric hardware-signed challenge-response generated strictly within Apple Secure Enclave or Android StrongBox Keymaster/KeyMint, preventing client-side boolean spoofing and runtime memory tampering via Frida or Objection.

Prohibited Anti-Pattern: Client-Side Boolean Trust Pattern (Vulnerable to Runtime Hooking & Injection)

Export Ready-to-Drop Configuration

Select format below to copy code or download file directly.

---
description: Capacitor 7 Hardware-Backed Biometric Authentication & Cryptographic Attestation Standard - Enforces hardware-backed cryptographic key isolation for biometric authentication in Capacitor 7 hybrid mobile applications. Mandates that biometric verification produces an asymmetric hardware-signed challenge-response generated strictly within Apple Secure Enclave or Android StrongBox Keymaster/KeyMint, preventing client-side boolean spoofing and runtime memory tampering via Frida or Objection.
globs: src/services/auth/**/*.{ts,tsx}, src/plugins/**/*.{ts,tsx}, android/app/src/main/java/**/*.java, ios/App/App/**/*.swift
alwaysApply: true
verified_by: "agentrules.org"
license: "CC-BY-4.0"
source: "https://agentrules.org/rules/capacitor-7-biometric-hardware-key-isolation"
---

# Capacitor 7 Hardware-Backed Biometric Authentication & Cryptographic Attestation Standard

> **Severity**: CRITICAL | **Category**: mobile
> **Anti-Pattern Warning**: Client-Side Boolean Trust Pattern (Vulnerable to Runtime Hooking & Injection)

## System Constraints
You are a Principal Mobile Security Architect enforcing zero-trust biometric authentication standards for Capacitor 7. You must reject any implementation that relies on client-side boolean flags (e.g., `isSuccess: true` from standard biometric plugins) to authorize sessions or release decrypted tokens. Require asymmetric cryptographic signatures where private keys are generated with `setUserAuthenticationRequired(true)` in Android KeyStore (StrongBox preferred) and `kSecAccessControlBiometryAny` in iOS Secure Enclave, validated strictly via backend challenge-response.

## Strict Guidelines
- Engineers MUST NEVER trust a client-side boolean resolution (e.g., `authenticated: true`) to mutate user session state or gate access to privileged endpoints.
- Engineers MUST ALWAYS implement challenge-response flows where the authentication server issues a high-entropy, short-lived (<= 60s), single-use cryptographic nonce.
- Hardware keys MUST be generated inside iOS Secure Enclave (`kSecAttrKeyTypeECSECPrimeRandom` with `kSecAccessControlBiometryCurrentSet` or `BiometryAny`) and Android Keystore (`KeyGenParameterSpec.Builder` with `setUserAuthenticationRequired(true)`, `AUTH_BIOMETRIC_STRONG`, and `setIsStrongBoxBacked(true)` where available).
- Services MUST transmit the hardware-signed signature and raw nonce payload to the identity backend for public key verification before issuing authorization tokens.
- WebViews MUST NOT store unencrypted session refresh tokens in `CapacitorPreferences`, `localStorage`, or `IndexedDB`; cryptographic secrets MUST remain non-exportable within native secure hardware.
- The client-side bridge MUST properly handle hardware invalidation exceptions (`KeyPermanentlyInvalidatedException` on Android and `errSecAuthFailed` on iOS) caused by new biometric enrollments or OS key invalidations, forcing full re-authentication.

## Bad vs Good Implementations
### Vulnerable Client-Side Boolean Biometric Check vs Hardware-Attested Challenge Signature

#### Bad Antipattern (AI Common Hallucination)
> **Why it fails**: The client treats biometric validation as a trusted binary outcome evaluated in the JavaScript runtime. An attacker with a rooted device or Frida can hook NativeBiometric.verifyIdentity to return `{ isSuccess: true }`, instantly releasing the token without contacting secure hardware.
```typescript
import { NativeBiometric } from 'capacitor-native-biometric';
import { Preferences } from '@capacitor/preferences';
import { authState } from './state';

export async function unlockSession(): Promise<boolean> {
  // CRITICAL VULNERABILITY: Trivial to bypass via Frida hook on verifyIdentity return value
  const result = await NativeBiometric.verifyIdentity({
    reason: 'Authenticate to access banking services',
    useFallback: false
  });

  if (result.isSuccess) {
    // Vulnerability: Token stored in software layer, exposed upon spoofed boolean
    const { value: jwt } = await Preferences.get({ key: 'user_jwt' });
    authState.token = jwt;
    authState.isAuthenticated = true;
    return true;
  }
  return false;
}
```

#### Production Standard (Correct)
> **Standard**: Authentication integrity is guaranteed by hardware-isolated asymmetric signing. Even if the WebView or Native bridging layer is hooked, an attacker cannot forge the signature of the server nonce without physical biometric execution within the Secure Enclave or StrongBox.
```typescript
import { registerPlugin } from '@capacitor/core';

interface HardwareCryptoBiometricPlugin {
  signChallenge(options: {
    challenge: string;
    promptTitle: string;
  }): Promise<{ signature: string; keyId: string }>;
}

const HardwareBiometrics = registerPlugin<HardwareCryptoBiometricPlugin>('HardwareCryptoBiometrics');

export async function unlockSessionWithHardwareAttestation(apiClient: any): Promise<void> {
  // Step 1: Obtain cryptographic single-use nonce from zero-trust identity provider
  const { challenge, nonceId } = await apiClient.post('/auth/biometric/challenge/initiate');

  // Step 2: Sign the challenge inside Secure Enclave / StrongBox; private key is strictly inaccessible outside hardware
  const { signature, keyId } = await HardwareBiometrics.signChallenge({
    challenge,
    promptTitle: 'Authenticate with Biometrics'
  });

  // Step 3: Backend verifies the signature against user's registered public key
  const sessionResponse = await apiClient.post('/auth/biometric/challenge/verify', {
    nonceId,
    keyId,
    signature
  });

  // Session is established only via cryptographically validated backend response
  sessionManager.initializeSession(sessionResponse.data.sessionToken);
}
```

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 Authentication & Cryptographic Attestation Standard

Capacitor 7 Hardware-Backed Biometric Authentication & Cryptographic Attestation Standard defines an industrial-grade behavioral standard for mobile engineering. Enforces hardware-backed cryptographic key isolation for biometric authentication in Capacitor 7 hybrid mobile applications. Mandates that biometric verification produces an asymmetric hardware-signed challenge-response generated strictly within Apple Secure Enclave or Android StrongBox Keymaster/KeyMint, preventing client-side boolean spoofing and runtime memory tampering via Frida or Objection. 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: Client-Side Boolean Trust Pattern (Vulnerable to Runtime Hooking & Injection) 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 DriftClient-Side Boolean Trust Pattern (Vulnerable to Runtime Hooking & Injection)Critical
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 trust a client-side boolean resolution (e.g., `authenticated

Engineers MUST NEVER trust a client-side boolean resolution (e.g., `authenticated: true`) to mutate user session state or gate access to privileged endpoints.

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 ALWAYS implement challenge-response flows where the authentication server issues a high-entropy, short-lived (<= 60s), single-use cryptographic nonce.

Engineers MUST ALWAYS implement challenge-response flows where the authentication server issues a high-entropy, short-lived (<= 60s), single-use cryptographic nonce.

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

Hardware keys MUST be generated inside iOS Secure Enclave (`kSecAttrKeyTypeECSECPrimeRandom` with `kSecAccessControlBiometryCurrentSet` or `BiometryAny`) and Android Keystore (`KeyGenParameterSpec.Builder` with `setUserAuthenticationRequired(true)`, `AUTH_BIOMETRIC_STRONG`, and `setIsStrongBoxBacked(true)` where available).

Hardware keys MUST be generated inside iOS Secure Enclave (`kSecAttrKeyTypeECSECPrimeRandom` with `kSecAccessControlBiometryCurrentSet` or `BiometryAny`) and Android Keystore (`KeyGenParameterSpec.Builder` with `setUserAuthenticationRequired(true)`, `AUTH_BIOMETRIC_STRONG`, and `setIsStrongBoxBacked(true)` where available).

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 transmit the hardware-signed signature and raw nonce payload to the identity backend for public key verification before issuing authorization tokens.

Services MUST transmit the hardware-signed signature and raw nonce payload to the identity backend for public key verification before issuing authorization tokens.

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

WebViews MUST NOT store unencrypted session refresh tokens in `CapacitorPreferences`, `localStorage`, or `IndexedDB`

WebViews MUST NOT store unencrypted session refresh tokens in `CapacitorPreferences`, `localStorage`, or `IndexedDB`; cryptographic secrets MUST remain non-exportable within native secure hardware.

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

The client-side bridge MUST properly handle hardware invalidation exceptions (`KeyPermanentlyInvalidatedException` on Android and `errSecAuthFailed` on iOS) caused by new biometric enrollments or OS key invalidations, forcing full re-authentication.

The client-side bridge MUST properly handle hardware invalidation exceptions (`KeyPermanentlyInvalidatedException` on Android and `errSecAuthFailed` on iOS) caused by new biometric enrollments or OS key invalidations, forcing full re-authentication.

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

Enforces hardware-backed cryptographic key isolation for biometric authentication in Capacitor 7 hybrid mobile applications. Mandates that biometric verification produces an asymmetric hardware-signed challenge-response generated strictly within Apple Secure Enclave or Android StrongBox Keymaster/KeyMint, preventing client-side boolean spoofing and runtime memory tampering via Frida or Objection. 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 (Client-Side Boolean Trust Pattern (Vulnerable to Runtime Hooking & Injection)) 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