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

Capacitor 7 Hardware-Backed Key Attestation and Biometric Bridge Guardrail

Enforces strict cryptographic signing of Capacitor 7 native bridge payloads using hardware-isolated private keys (iOS Secure Enclave and Android StrongBox/TEE). Binds every privileged IPC operation to an ephemeral server/native nonce and biometric authentication challenge to eliminate hybrid WebView session hijacking and compromised JavaScript context exploitation.

Prohibited Anti-Pattern: Unsigned IPC Bridge Calls Relying on In-Memory Bearer Tokens in WebView Context

Export Ready-to-Drop Configuration

Select format below to copy code or download file directly.

---
description: Capacitor 7 Hardware-Backed Key Attestation and Biometric Bridge Guardrail - Enforces strict cryptographic signing of Capacitor 7 native bridge payloads using hardware-isolated private keys (iOS Secure Enclave and Android StrongBox/TEE). Binds every privileged IPC operation to an ephemeral server/native nonce and biometric authentication challenge to eliminate hybrid WebView session hijacking and compromised JavaScript context exploitation.
globs: src/**/*.{ts,tsx}, ios/App/App/**/*.swift, android/app/src/main/**/*.kt
alwaysApply: true
verified_by: "agentrules.org"
license: "CC-BY-4.0"
source: "https://agentrules.org/rules/capacitor7-hardware-attestation-biometric-guardrail"
---

# Capacitor 7 Hardware-Backed Key Attestation and Biometric Bridge Guardrail

> **Severity**: CRITICAL | **Category**: mobile
> **Anti-Pattern Warning**: Unsigned IPC Bridge Calls Relying on In-Memory Bearer Tokens in WebView Context

## System Constraints
You are a Principal Mobile Security Architect enforcing hardware-backed attestation and biometric zero-trust IPC standards for Capacitor 7 applications. You must ensure that no privileged bridge call relies solely on web-layer credentials, tokens, or unverified arguments. Private keys must be generated inside the iOS Secure Enclave (kSecAttrAccessControl with biometryCurrentSet) or Android StrongBox Keymaster/KeyMint (PURPOSE_SIGN with setUserAuthenticationRequired). Native plugins must strictly verify cryptographic signatures across IPC payloads against device hardware certificates before executing native side effects.

## Strict Guidelines
- Engineers MUST ALWAYS store private signing keys exclusively in hardware-isolated security modules (iOS Secure Enclave or Android StrongBox/TEE) using NIST P-256 (secp256r1).
- Engineers MUST NOT store unencrypted session tokens, API keys, or long-lived authentication state in window.localStorage, IndexedDB, or WebView cookies.
- Bridge invocations for sensitive operations (e.g., transactions, crypto operations, credential mutation) MUST require a cryptographic signature over canonical payload parameters, a high-entropy nonce, and a unix timestamp.
- Native plugins MUST enforce biometric re-authentication via LocalAuthentication (iOS) or BiometricPrompt (Android) directly bound to the hardware key authorization object (LAContext / CryptoObject).
- The native bridge layer MUST reject any payload whose timestamp variance exceeds 30 seconds or whose nonce has been previously consumed (replay attack mitigation).
- Components NEVER execute raw native function triggers with ambient authority; every privileged native call must complete a two-step challenge-response exchange.

## Bad vs Good Implementations
### Insecure Bridge Invocation vs Hardware-Attested Biometric IPC Signing

#### Bad Antipattern (AI Common Hallucination)
> **Why it fails**: Passing sensitive authorization tokens across the hybrid IPC bridge allows injected JavaScript to replay commands or exfiltrate tokens. The native layer trusts any payload received from the WebView without verifying hardware-backed cryptographic custody or physical user presence.
```typescript
import { Plugins } from '@capacitor/core';
const { FinancialService } = Plugins;

// ANTI-PATTERN: Sending ambient bearer token and raw parameters over IPC bridge.
// If an XSS payload or rogue dependency compromises the WebView window context,
// full account takeover and unauthorized transactions occur without user presence.
export async function executeTransfer(recipientId: string, amountCents: number) {
  const token = localStorage.getItem('auth_token');
  
  return await FinancialService.transfer({
    recipientId,
    amountCents,
    token // Vulnerable to bridge interception and in-memory extraction
  });
}
```

#### Production Standard (Correct)
> **Standard**: Privileged operations require an ephemeral nonce verified natively. The signature is computed directly within iOS Secure Enclave / Android StrongBox via BiometricPrompt-gated keys. Even if the WebView DOM is fully compromised, an attacker cannot forge signatures or execute unauthorized actions.
```typescript
import { registerPlugin } from '@capacitor/core';

interface SignedPayloadEnvelope {
  payloadJson: string;
  signatureDerBase64: string;
  deviceKeyId: string;
  clientNonce: string;
}

interface SecureEnclavePlugin {
  generateAttestedChallenge(options: { domain: string }): Promise<{ nonce: string }>;
  signWithHardwareKey(options: {
    challenge: string;
    payload: string;
    promptMessage: string;
  }): Promise<SignedPayloadEnvelope>;
  executeAttestedTransfer(envelope: SignedPayloadEnvelope): Promise<{ txHash: string }>;
}

const EnclaveBridge = registerPlugin<SecureEnclavePlugin>('SecureEnclavePlugin');

// PRODUCTION FIX: Two-step challenge-response bound to Secure Enclave / StrongBox.
// Native hardware signs the canonical payload only upon successful biometric evaluation.
export async function executeAttestedTransfer(
  recipientId: string,
  amountCents: number
): Promise<{ txHash: string }> {
  // 1. Obtain ephemeral single-use nonce directly from native hardware module
  const { nonce } = await EnclaveBridge.generateAttestedChallenge({ domain: 'transfers.internal' });
  
  const canonicalPayload = JSON.stringify({
    recipientId,
    amountCents,
    nonce,
    timestamp: Date.now()
  });

  // 2. Hardware Enclave prompts biometric auth and signs payload via isolated SECP256R1 key
  const signedEnvelope = await EnclaveBridge.signWithHardwareKey({
    challenge: nonce,
    payload: canonicalPayload,
    promptMessage: `Authorize transfer of $${(amountCents / 100).toFixed(2)}`
  });

  // 3. Native plugin verifies enclave signature and nonce freshness prior to dispatching
  return await EnclaveBridge.executeAttestedTransfer(signedEnvelope);
}
```

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 Key Attestation and Biometric Bridge Guardrail

Capacitor 7 Hardware-Backed Key Attestation and Biometric Bridge Guardrail defines an industrial-grade behavioral standard for mobile engineering. Enforces strict cryptographic signing of Capacitor 7 native bridge payloads using hardware-isolated private keys (iOS Secure Enclave and Android StrongBox/TEE). Binds every privileged IPC operation to an ephemeral server/native nonce and biometric authentication challenge to eliminate hybrid WebView session hijacking and compromised JavaScript context exploitation. 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: Unsigned IPC Bridge Calls Relying on In-Memory Bearer Tokens in WebView Context 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 DriftUnsigned IPC Bridge Calls Relying on In-Memory Bearer Tokens in WebView ContextCritical
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 store private signing keys exclusively in hardware-isolated security modules (iOS Secure Enclave or Android StrongBox/TEE) using NIST P-256 (secp256r1).

Engineers MUST ALWAYS store private signing keys exclusively in hardware-isolated security modules (iOS Secure Enclave or Android StrongBox/TEE) using NIST P-256 (secp256r1).

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 unencrypted session tokens, API keys, or long-lived authentication state in window.localStorage, IndexedDB, or WebView cookies.

Engineers MUST NOT store unencrypted session tokens, API keys, or long-lived authentication state in window.localStorage, IndexedDB, or WebView cookies.

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

Bridge invocations for sensitive operations (e.g., transactions, crypto operations, credential mutation) MUST require a cryptographic signature over canonical payload parameters, a high-entropy nonce, and a unix timestamp.

Bridge invocations for sensitive operations (e.g., transactions, crypto operations, credential mutation) MUST require a cryptographic signature over canonical payload parameters, a high-entropy nonce, and a unix timestamp.

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 plugins MUST enforce biometric re-authentication via LocalAuthentication (iOS) or BiometricPrompt (Android) directly bound to the hardware key authorization object (LAContext / CryptoObject).

Native plugins MUST enforce biometric re-authentication via LocalAuthentication (iOS) or BiometricPrompt (Android) directly bound to the hardware key authorization object (LAContext / CryptoObject).

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

The native bridge layer MUST reject any payload whose timestamp variance exceeds 30 seconds or whose nonce has been previously consumed (replay attack mitigation).

The native bridge layer MUST reject any payload whose timestamp variance exceeds 30 seconds or whose nonce has been previously consumed (replay attack mitigation).

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

Components NEVER execute raw native function triggers with ambient authority

Components NEVER execute raw native function triggers with ambient authority; every privileged native call must complete a two-step challenge-response exchange.

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 Key Attestation and Biometric Bridge Guardrail critical for AI coding assistants?

Enforces strict cryptographic signing of Capacitor 7 native bridge payloads using hardware-isolated private keys (iOS Secure Enclave and Android StrongBox/TEE). Binds every privileged IPC operation to an ephemeral server/native nonce and biometric authentication challenge to eliminate hybrid WebView session hijacking and compromised JavaScript context exploitation. 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 (Unsigned IPC Bridge Calls Relying on In-Memory Bearer Tokens in WebView Context) 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