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

Capacitor 7 Hardware-Backed Biometric Keystore Attestation Standard

Mandates that webview-to-native IPC calls for privileged cryptographic operations, authorization, and sensitive transaction signing authenticate against hardware Enclave-backed keys rather than relying on software-level session tokens or bypassable boolean biometric checks. Protects against webview XSS, runtime injection, and bridge replay attacks by enforcing secure hardware asymmetric signature assertions on server-issued challenges.

Prohibited Anti-Pattern: Trusting Webview Boolean Biometric Prompts and In-Memory Bearer Tokens for High-Privilege Native Bridge Operations

Export Ready-to-Drop Configuration

Select format below to copy code or download file directly.

---
description: Capacitor 7 Hardware-Backed Biometric Keystore Attestation Standard - Mandates that webview-to-native IPC calls for privileged cryptographic operations, authorization, and sensitive transaction signing authenticate against hardware Enclave-backed keys rather than relying on software-level session tokens or bypassable boolean biometric checks. Protects against webview XSS, runtime injection, and bridge replay attacks by enforcing secure hardware asymmetric signature assertions on server-issued challenges.
globs: src/**/*.{ts,tsx}, src/plugins/**/*.{ts,tsx}, ios/App/App/**/*.{swift,h,m}, 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-biometric-keystore-attestation-standard"
---

# Capacitor 7 Hardware-Backed Biometric Keystore Attestation Standard

> **Severity**: CRITICAL | **Category**: mobile
> **Anti-Pattern Warning**: Trusting Webview Boolean Biometric Prompts and In-Memory Bearer Tokens for High-Privilege Native Bridge Operations

## System Constraints
You are a Principal Mobile Security Architect enforcing the Capacitor 7 Hardware-Backed Biometric Keystore Attestation Standard. In mobile hybrid architectures, the webview is considered an untrusted execution environment susceptible to XSS, script injection, and dynamic instrumentation. You must strictly reject any implementation where biometric checks return simple booleans to the webview or where high-privilege operations use webview-managed session tokens. Enforce that all privileged native bridge operations require hardware-backed asymmetric key assertions (iOS Secure Enclave / Android StrongBox Keymaster) bound to server-originated cryptographic challenges.

## Strict Guidelines
- Engineers MUST ALWAYS enforce that private keys are generated inside hardware security modules (iOS Secure Enclave with kSecAccessControlBiometryCurrentSet, Android KeyStore with KeyProperties.PURPOSE_SIGN and setUserAuthenticationRequired(true)).
- Engineers MUST NOT rely on client-side boolean flags (e.g., `result.authenticated === true`) returned across the Capacitor bridge to unlock sensitive backend requests or native state mutations.
- Services MUST implement a Challenge-Response protocol where the server generates a cryptographically random, single-use, time-bound nonce that the native Secure Enclave must sign.
- Code SHOULD verify hardware attestation certificates (Apple DeviceCheck/App Attest or Android Key Attestation) during key enrollment before accepting the hardware public key on the backend.
- Components NEVER store long-lived authorization credentials, private keys, or raw signing material in webview storage mechanisms (localStorage, IndexedDB, or memory state).

## Bad vs Good Implementations
### Biometric Authentication Pattern: Insecure Boolean Check vs. Hardware-Enclave Challenge Signing

#### Bad Antipattern (AI Common Hallucination)
> **Why it fails**: The webview performs a local boolean check via the bridge and dispatches an ambient session token. An attacker with XSS or runtime bridge access can bypass the `isSuccess` check and replay the request using the exposed token.
```typescript
import { Plugins } from '@capacitor/core';
const { BiometricAuth } = Plugins;

// ANTI-PATTERN: Relying on a boolean result across the bridge and sending
// a static session token from webview memory/storage.
export async function executeTransfer(amount: number, recipientId: string) {
  const authResult = await BiometricAuth.verify({
    reason: 'Confirm high-value transfer',
  });

  // VULNERABILITY: If the webview is compromised via XSS or dynamic hooking,
  // this boolean check is trivial to bypass or mock.
  if (authResult.isSuccess) {
    const token = localStorage.getItem('session_jwt');
    const response = await fetch('/api/transfer', {
      method: 'POST',
      headers: {
        'Content-Type': 'application/json',
        'Authorization': `Bearer ${token}`,
      },
      body: JSON.stringify({ amount, recipientId }),
    });
    return response.json();
  }
  throw new Error('Biometric verification failed');
}
```

#### Production Standard (Correct)
> **Standard**: The webview never holds private key material or decides authentication validity. It forwards a server-generated nonce to the native bridge where hardware (Secure Enclave/StrongBox) prompts for biometrics and directly computes an asymmetric signature (e.g. ECDSA P-256), which the server cryptographically validates.
```typescript
import { registerPlugin } from '@capacitor/core';

interface HardwareKeystorePlugin {
  signChallenge(options: { alias: string; challengePayload: string }): Promise<{ signature: string }>;
}

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

// SECURE PATTERN: Hardware-Enclave Challenge-Response Signature
export async function executeTransfer(amount: number, recipientId: string): Promise<Response> {
  // 1. Fetch single-use cryptographic challenge from the server
  const challengeRes = await fetch('/api/transfer/challenge', { method: 'POST' });
  const { challengeNonce } = await challengeRes.json();

  const transactionPayload = JSON.stringify({
    challengeNonce,
    amount,
    recipientId,
    timestamp: Date.now(),
  });

  // 2. Request native bridge to sign payload inside Secure Enclave/StrongBox.
  // Hardware enforces biometric unlock; private key never touches webview.
  const { signature } = await HardwareKeystore.signChallenge({
    alias: 'primary_hardware_key',
    challengePayload: transactionPayload,
  });

  // 3. Submit transaction with raw payload and hardware signature for server verification
  return await fetch('/api/transfer/execute', {
    method: 'POST',
    headers: { 'Content-Type': 'application/json' },
    body: JSON.stringify({
      payload: transactionPayload,
      signature,
    }),
  });
}
```

Recommended MCP Servers (mcp-serverlist.com)

Equip agent with system tools to verify code for this stack.

Architectural Specification & Invariant Rationale

Architectural Invariant Design: Capacitor 7 Hardware-Backed Biometric Keystore Attestation Standard

Capacitor 7 Hardware-Backed Biometric Keystore Attestation Standard defines an industrial-grade behavioral standard for mobile engineering. Mandates that webview-to-native IPC calls for privileged cryptographic operations, authorization, and sensitive transaction signing authenticate against hardware Enclave-backed keys rather than relying on software-level session tokens or bypassable boolean biometric checks. Protects against webview XSS, runtime injection, and bridge replay attacks by enforcing secure hardware asymmetric signature assertions on server-issued challenges. 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 Webview Boolean Biometric Prompts and In-Memory Bearer Tokens for High-Privilege Native Bridge 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 Webview Boolean Biometric Prompts and In-Memory Bearer Tokens for High-Privilege Native Bridge 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 ALWAYS enforce that private keys are generated inside hardware security modules (iOS Secure Enclave with kSecAccessControlBiometryCurrentSet, Android KeyStore with KeyProperties.PURPOSE_SIGN and setUserAuthenticationRequired(true)).

Engineers MUST ALWAYS enforce that private keys are generated inside hardware security modules (iOS Secure Enclave with kSecAccessControlBiometryCurrentSet, Android KeyStore with KeyProperties.PURPOSE_SIGN and setUserAuthenticationRequired(true)).

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 rely on client-side boolean flags (e.g., `result.authenticated === true`) returned across the Capacitor bridge to unlock sensitive backend requests or native state mutations.

Engineers MUST NOT rely on client-side boolean flags (e.g., `result.authenticated === true`) returned across the Capacitor bridge to unlock sensitive backend requests or native state mutations.

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 where the server generates a cryptographically random, single-use, time-bound nonce that the native Secure Enclave must sign.

Services MUST implement a Challenge-Response protocol where the server generates a cryptographically random, single-use, time-bound nonce that the native Secure Enclave must sign.

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 SHOULD verify hardware attestation certificates (Apple DeviceCheck/App Attest or Android Key Attestation) during key enrollment before accepting the hardware public key on the backend.

Code SHOULD verify hardware attestation certificates (Apple DeviceCheck/App Attest or Android Key Attestation) during key enrollment before accepting the hardware public key on 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.
5

Components NEVER store long-lived authorization credentials, private keys, or raw signing material in webview storage mechanisms (localStorage, IndexedDB, or memory state).

Components NEVER store long-lived authorization credentials, private keys, or raw signing material in webview storage mechanisms (localStorage, IndexedDB, or memory state).

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

Mandates that webview-to-native IPC calls for privileged cryptographic operations, authorization, and sensitive transaction signing authenticate against hardware Enclave-backed keys rather than relying on software-level session tokens or bypassable boolean biometric checks. Protects against webview XSS, runtime injection, and bridge replay attacks by enforcing secure hardware asymmetric signature assertions on server-issued challenges. 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 Webview Boolean Biometric Prompts and In-Memory Bearer Tokens for High-Privilege Native Bridge 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