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

Hardware-Backed Biometric Attestation and Cryptographic Replay-Resistant Bridge Binding

Requires all Capacitor 7 native biometric verification flows to utilize hardware-backed key attestation (Secure Enclave/StrongBox) with cryptographic challenge-response validation. Forbids relying on boolean bridge evaluation responses ({ success: true }), enforcing backend signature verification and strict session-nonce binding across native-to-web boundaries.

Prohibited Anti-Pattern: Trusting Boolean Native Bridge Returns for Biometric Authorization Without Hardware-Backed Cryptographic Attestation

Export Ready-to-Drop Configuration

Select format below to copy code or download file directly.

---
description: Hardware-Backed Biometric Attestation and Cryptographic Replay-Resistant Bridge Binding - Requires all Capacitor 7 native biometric verification flows to utilize hardware-backed key attestation (Secure Enclave/StrongBox) with cryptographic challenge-response validation. Forbids relying on boolean bridge evaluation responses ({ success: true }), enforcing backend signature verification and strict session-nonce binding across native-to-web boundaries.
globs: src/**/services/auth/**/*.{ts,tsx}, src/**/plugins/**/*.{ts,tsx}, src/**/biometrics/**/*.{ts,tsx}, src/**/security/**/*.{ts,tsx}
alwaysApply: true
verified_by: "agentrules.org"
license: "CC-BY-4.0"
source: "https://agentrules.org/rules/capacitor7-biometric-attestation-replay-binding"
---

# Hardware-Backed Biometric Attestation and Cryptographic Replay-Resistant Bridge Binding

> **Severity**: CRITICAL | **Category**: mobile
> **Anti-Pattern Warning**: Trusting Boolean Native Bridge Returns for Biometric Authorization Without Hardware-Backed Cryptographic Attestation

## System Constraints
You are a Principal Mobile Security Architect enforcing Capacitor 7 Biometric Key Attestation and Replay-Resistant Session Binding. Mandate that all biometric authentication across the native-to-web cross-bridge uses hardware-backed cryptographic challenge-response schemes, binding backend sessions to Secure Enclave or StrongBox signatures rather than trusting client-side boolean flags.

## Strict Guidelines
- Engineers MUST NEVER trust client-side boolean results (e.g., `result.isSuccess === true` or `{ verified: true }`) across the Capacitor bridge to authorize sensitive state transitions.
- Engineers MUST request an ephemeral cryptographic challenge (minimum 256-bit cryptographically secure pseudorandom nonce, max 60-second TTL) from the backend authorization server prior to every native biometric prompt.
- Engineers MUST generate private keys in native hardware-backed storage (iOS Secure Enclave / Android StrongBox/Keystore) flagged with strict biometric user authentication requirements (`UserPresence` or `BiometricAny`).
- Native biometric plugins MUST return a cryptographic signature of the server challenge along with the hardware key ID, device attestation chain, and an incrementing monotonic counter across the bridge.
- Web client services MUST transmit the signature, original challenge, and hardware metadata to the backend for asymmetric signature validation and nonce invalidation before issuing or elevating a session token.
- Authentication payloads MUST cryptographically bind the ephemeral challenge to the active WebView origin, native bundle identifier, and target user ID to prevent cross-app relay and confused-deputy attacks.
- Components NEVER store unprotected private keys or cached biometric credentials in LocalStorage, IndexedDB, or standard unencrypted bridge preferences.

## Bad vs Good Implementations
### Naive Boolean Bridge Check vs. Cryptographic Hardware Attestation

#### Bad Antipattern (AI Common Hallucination)
> **Why it fails**: Trusts a malleable boolean response across the Capacitor native-to-web bridge. A local runtime hook (e.g., Frida or WebView JavaScript injection) can override `result.isSuccess` to true without user interaction or biometric validation, allowing unauthorized privilege escalation.
```typescript
import { NativeBiometric } from '@capgo/capacitor-native-biometric';
import { api } from '@/services/api';

export async function authenticateWithBiometrics(userId: string): Promise<boolean> {
  // VULNERABLE: Relies on boolean returned across Capacitor bridge.
  // Can be hooked/spoofed via Frida, injected JS, or compromised WebView bridge.
  const result = await NativeBiometric.verifyIdentity({
    reason: 'Authorize transaction',
    title: 'Biometric Login',
  });

  if (result.isSuccess) {
    // Insecure: Client informs server that biometric auth succeeded
    const session = await api.post('/auth/session/elevate', { userId, verified: true });
    localStorage.setItem('session_token', session.token);
    return true;
  }

  return false;
}
```

#### Production Standard (Correct)
> **Standard**: Implements an end-to-end cryptographic challenge-response flow. The server issues a single-use nonce. The native layer signs the nonce inside hardware-backed storage (Secure Enclave/StrongBox) gated by biometrics. The server verifies the signature against the registered public key, preventing bridge tampering, replay attacks, and client spoofing.
```typescript
import { SecureHardwareBiometrics } from '@/plugins/secure-hardware-biometrics';
import { apiClient } from '@/services/api-client';

interface BiometricChallengeResponse {
  challengeId: string;
  nonce: string; // Base64 encoded 256-bit server nonce
  expiresAt: number;
}

interface BiometricVerificationPayload {
  challengeId: string;
  keyId: string;
  signature: string; // Base64 ECDSA P-256 signature from Secure Enclave/StrongBox
  deviceAttestationCert?: string;
  counter: number;
}

export async function authenticateWithHardwareBiometrics(userId: string): Promise<string> {
  // 1. Fetch single-use ephemeral challenge from the backend
  const challenge = await apiClient.post<BiometricChallengeResponse>('/auth/biometrics/challenge', {
    userId,
    clientTime: Date.now(),
  });

  // 2. Instruct native hardware key (Secure Enclave / Android Keystore) to sign the nonce
  // Hardware will only release signature upon physical biometric confirmation
  const signResult = await SecureHardwareBiometrics.signChallenge({
    keyAlias: `user-biometric-key-${userId}`,
    challengeNonce: challenge.nonce,
    promptTitle: 'Authorize Session',
    promptSubtitle: 'Confirm biometric identity',
  });

  const payload: BiometricVerificationPayload = {
    challengeId: challenge.challengeId,
    keyId: signResult.keyId,
    signature: signResult.signature,
    deviceAttestationCert: signResult.attestationCertChain,
    counter: signResult.operationCounter,
  };

  // 3. Cryptographically verify signature and invalidate nonce on server
  const response = await apiClient.post<{ sessionToken: string }>('/auth/biometrics/verify', payload);
  return response.sessionToken;
}
```

Architectural Specification & Invariant Rationale

Architectural Invariant Design: Hardware-Backed Biometric Attestation and Cryptographic Replay-Resistant Bridge Binding

Hardware-Backed Biometric Attestation and Cryptographic Replay-Resistant Bridge Binding defines an industrial-grade behavioral standard for mobile engineering. Requires all Capacitor 7 native biometric verification flows to utilize hardware-backed key attestation (Secure Enclave/StrongBox) with cryptographic challenge-response validation. Forbids relying on boolean bridge evaluation responses ({ success: true }), enforcing backend signature verification and strict session-nonce binding across native-to-web boundaries. 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 Native Bridge Returns for Biometric Authorization Without Hardware-Backed Cryptographic Attestation 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 Native Bridge Returns for Biometric Authorization Without Hardware-Backed Cryptographic AttestationCritical
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 client-side boolean results (e.g., `result.isSuccess === true` or `{ verified

Engineers MUST NEVER trust client-side boolean results (e.g., `result.isSuccess === true` or `{ verified: true }`) across the Capacitor bridge to authorize sensitive state transitions.

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 request an ephemeral cryptographic challenge (minimum 256-bit cryptographically secure pseudorandom nonce, max 60-second TTL) from the backend authorization server prior to every native biometric prompt.

Engineers MUST request an ephemeral cryptographic challenge (minimum 256-bit cryptographically secure pseudorandom nonce, max 60-second TTL) from the backend authorization server prior to every native biometric prompt.

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 generate private keys in native hardware-backed storage (iOS Secure Enclave / Android StrongBox/Keystore) flagged with strict biometric user authentication requirements (`UserPresence` or `BiometricAny`).

Engineers MUST generate private keys in native hardware-backed storage (iOS Secure Enclave / Android StrongBox/Keystore) flagged with strict biometric user authentication requirements (`UserPresence` or `BiometricAny`).

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

Native biometric plugins MUST return a cryptographic signature of the server challenge along with the hardware key ID, device attestation chain, and an incrementing monotonic counter across the bridge.

Native biometric plugins MUST return a cryptographic signature of the server challenge along with the hardware key ID, device attestation chain, and an incrementing monotonic counter across the bridge.

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

Web client services MUST transmit the signature, original challenge, and hardware metadata to the backend for asymmetric signature validation and nonce invalidation before issuing or elevating a session token.

Web client services MUST transmit the signature, original challenge, and hardware metadata to the backend for asymmetric signature validation and nonce invalidation before issuing or elevating a session token.

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

Authentication payloads MUST cryptographically bind the ephemeral challenge to the active WebView origin, native bundle identifier, and target user ID to prevent cross-app relay and confused-deputy attacks.

Authentication payloads MUST cryptographically bind the ephemeral challenge to the active WebView origin, native bundle identifier, and target user ID to prevent cross-app relay and confused-deputy 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.
7

Components NEVER store unprotected private keys or cached biometric credentials in LocalStorage, IndexedDB, or standard unencrypted bridge preferences.

Components NEVER store unprotected private keys or cached biometric credentials in LocalStorage, IndexedDB, or standard unencrypted bridge preferences.

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 Attestation and Cryptographic Replay-Resistant Bridge Binding critical for AI coding assistants?

Requires all Capacitor 7 native biometric verification flows to utilize hardware-backed key attestation (Secure Enclave/StrongBox) with cryptographic challenge-response validation. Forbids relying on boolean bridge evaluation responses ({ success: true }), enforcing backend signature verification and strict session-nonce binding across native-to-web boundaries. 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 Native Bridge Returns for Biometric Authorization Without Hardware-Backed Cryptographic Attestation) 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