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

Capacitor 7 Hardware Keystore Biometric Nonce-Binding Standard

Enforces cryptographic binding between native hardware keystore biometrics (Secure Enclave / Android StrongBox) and single-use ephemeral challenge nonces in Capacitor 7 hybrid architectures. Eliminates cross-context bridge token replay and XSS-induced authorization theft by mandating that biometric authentication produces an ephemeral ECDSA signature over a server-validated challenge rather than releasing static stored secrets or boolean authentication flags across the WebView bridge.

Prohibited Anti-Pattern: Exposing Raw Biometric Verification Booleans or Static Secrets Across the Capacitor Bridge

Export Ready-to-Drop Configuration

Select format below to copy code or download file directly.

---
description: Capacitor 7 Hardware Keystore Biometric Nonce-Binding Standard - Enforces cryptographic binding between native hardware keystore biometrics (Secure Enclave / Android StrongBox) and single-use ephemeral challenge nonces in Capacitor 7 hybrid architectures. Eliminates cross-context bridge token replay and XSS-induced authorization theft by mandating that biometric authentication produces an ephemeral ECDSA signature over a server-validated challenge rather than releasing static stored secrets or boolean authentication flags across the WebView bridge.
globs: src/**/*.{ts,tsx}, ios/App/App/**/*.swift, android/app/src/main/java/**/*.kt
alwaysApply: true
verified_by: "agentrules.org"
license: "CC-BY-4.0"
source: "https://agentrules.org/rules/capacitor7-biometric-keystore-nonce-binding"
---

# Capacitor 7 Hardware Keystore Biometric Nonce-Binding Standard

> **Severity**: CRITICAL | **Category**: mobile
> **Anti-Pattern Warning**: Exposing Raw Biometric Verification Booleans or Static Secrets Across the Capacitor Bridge

## System Constraints
You are a Principal Mobile Security Architect enforcing the Capacitor 7 Biometric Hardware Keystore Nonce-Binding Invariant. In hybrid web-to-native execution models, untrusted JavaScript inside the WebView MUST NEVER receive static sensitive authentication material upon biometric completion, nor can authorization depend on a vulnerable boolean status flag returned across the bridge. Require all biometric flows to generate or receive an ephemeral server challenge, sign that challenge within platform secure hardware (Secure Enclave or Android StrongBox/TEE Keystore) gated directly by biometric evaluation, and emit only the cryptographically signed challenge envelope.

## Strict Guidelines
- Engineers MUST ALWAYS require a server-issued or cryptographically attested single-use ephemeral challenge nonce (minimum 256 bits of entropy) before invoking biometric operations.
- Engineers MUST NOT store long-lived tokens in native secure storage to be returned directly to the WebView upon a successful biometric check.
- Code MUST mandate that biometric validation gates private key operations directly in hardware via `KeyGenParameterSpec.Builder.setUserAuthenticationRequired(true)` (Android) or `kSecAccessControlBiometryAny` / `kSecAccessControlBiometryCurrentSet` (iOS).
- Services MUST verify the cryptographic signature over the original ephemeral nonce server-side and invalidate the challenge immediately after single consumption to prevent bridge replay attacks.
- Components NEVER treat biometric verification results as simple boolean states (`{ verified: true }`) for privileged operations.

## Bad vs Good Implementations
### Vulnerable Bridge Pattern: Boolean Verification and Local Storage Secret Retrieval

#### Bad Antipattern (AI Common Hallucination)
> **Why it fails**: The biometric prompt merely returns a boolean state to the WebView, and the sensitive authentication token is statically stored and transferred across the bridge. If the WebView context is compromised via XSS or prototype pollution, an attacker can invoke storage APIs directly or forge the boolean evaluation result without hardware enforcement.
```typescript
import { BiometricAuth } from '@aparajita/capacitor-biometric-auth';
import { Preferences } from '@capacitor/preferences';

export async function authenticateAndRetrieveSession(): Promise<string> {
  // VULNERABILITY: Bridge returns an unforgeable boolean; WebView logic is bypassed
  // or manipulated via XSS / DOM injection / dev tools injection.
  const result = await BiometricAuth.verify({
    reason: 'Confirm biometrics to unlock wallet',
  });

  if (result.verified) {
    // CRITICAL: Releasing static token across the bridge allows cross-context exfiltration
    const { value } = await Preferences.get({ key: 'auth_session_token' });
    if (!value) throw new Error('Token not found');
    return value;
  }

  throw new Error('Biometric check failed');
}
```

#### Production Standard (Correct)
> **Standard**: Authentication requires signing an ephemeral server challenge using a private key residing inside the native Secure Enclave or Android Keystore. The hardware itself requires biometrics before executing the ECDSA sign operation, ensuring no static secrets cross the WebView bridge and rendering token replay impossible.
```typescript
import { registerPlugin } from '@capacitor/core';

interface HardwareSignResult {
  signature: string;
  algorithm: 'ES256';
  keyId: string;
}

interface HardwareKeystorePlugin {
  signChallenge(options: {
    challengeNonce: string;
    promptMessage: string;
  }): Promise<HardwareSignResult>;
}

const HardwareKeystore = registerPlugin<HardwareKeystorePlugin>('HardwareKeystore');

export async function authenticateWithBoundNonce(
  requestServerChallenge: () => Promise<{ nonce: string; expiresAt: number }>
): Promise<{ signature: string; nonce: string; keyId: string }> {
  // 1. Fetch single-use ephemeral challenge generated by the authorization backend
  const { nonce, expiresAt } = await requestServerChallenge();

  if (Date.now() >= expiresAt) {
    throw new Error('Ephemeral authorization challenge has expired.');
  }

  // 2. Delegate to native platform hardware (Secure Enclave / Android StrongBox Keystore)
  // The native plugin signs the nonce directly inside hardware when biometrics pass.
  const { signature, algorithm, keyId } = await HardwareKeystore.signChallenge({
    challengeNonce: nonce,
    promptMessage: 'Authenticate to sign session nonce',
  });

  if (algorithm !== 'ES256') {
    throw new Error(`Unsupported cryptographic algorithm: ${algorithm}`);
  }

  // 3. Return signature & nonce. Backend verifies the signature against stored public key
  // and marks the nonce as spent. No static secret is ever exposed across the bridge.
  return { signature, nonce, keyId };
}
```

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 Keystore Biometric Nonce-Binding Standard

Capacitor 7 Hardware Keystore Biometric Nonce-Binding Standard defines an industrial-grade behavioral standard for mobile engineering. Enforces cryptographic binding between native hardware keystore biometrics (Secure Enclave / Android StrongBox) and single-use ephemeral challenge nonces in Capacitor 7 hybrid architectures. Eliminates cross-context bridge token replay and XSS-induced authorization theft by mandating that biometric authentication produces an ephemeral ECDSA signature over a server-validated challenge rather than releasing static stored secrets or boolean authentication flags across the WebView bridge. 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: Exposing Raw Biometric Verification Booleans or Static Secrets Across the Capacitor Bridge 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 DriftExposing Raw Biometric Verification Booleans or Static Secrets Across the Capacitor BridgeCritical
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 require a server-issued or cryptographically attested single-use ephemeral challenge nonce (minimum 256 bits of entropy) before invoking biometric operations.

Engineers MUST ALWAYS require a server-issued or cryptographically attested single-use ephemeral challenge nonce (minimum 256 bits of entropy) before invoking biometric operations.

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 long-lived tokens in native secure storage to be returned directly to the WebView upon a successful biometric check.

Engineers MUST NOT store long-lived tokens in native secure storage to be returned directly to the WebView upon a successful biometric check.

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 mandate that biometric validation gates private key operations directly in hardware via `KeyGenParameterSpec.Builder.setUserAuthenticationRequired(true)` (Android) or `kSecAccessControlBiometryAny` / `kSecAccessControlBiometryCurrentSet` (iOS).

Code MUST mandate that biometric validation gates private key operations directly in hardware via `KeyGenParameterSpec.Builder.setUserAuthenticationRequired(true)` (Android) or `kSecAccessControlBiometryAny` / `kSecAccessControlBiometryCurrentSet` (iOS).

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 the cryptographic signature over the original ephemeral nonce server-side and invalidate the challenge immediately after single consumption to prevent bridge replay attacks.

Services MUST verify the cryptographic signature over the original ephemeral nonce server-side and invalidate the challenge immediately after single consumption to prevent bridge 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.
5

Components NEVER treat biometric verification results as simple boolean states (`{ verified

Components NEVER treat biometric verification results as simple boolean states (`{ verified: true }`) for privileged operations.

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 Keystore Biometric Nonce-Binding Standard critical for AI coding assistants?

Enforces cryptographic binding between native hardware keystore biometrics (Secure Enclave / Android StrongBox) and single-use ephemeral challenge nonces in Capacitor 7 hybrid architectures. Eliminates cross-context bridge token replay and XSS-induced authorization theft by mandating that biometric authentication produces an ephemeral ECDSA signature over a server-validated challenge rather than releasing static stored secrets or boolean authentication flags across the WebView bridge. 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 (Exposing Raw Biometric Verification Booleans or Static Secrets Across the Capacitor Bridge) 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