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

Capacitor 7 Hardware-Backed Key Attestation and Native Bridge Cryptographic Guardrail

Mandates that all critical Capacitor 7 native plugin dispatches authenticate through hardware-backed cryptographic key attestation (Apple Secure Enclave and Android StrongBox/TEE KeyStore). Prevents runtime payload injection, memory tampering, and Frida/Xposed bridge interception by enforcing per-dispatch signed nonces across the JavaScript-to-Native barrier.

Prohibited Anti-Pattern: Unsigned Native Plugin Dispatches Vulnerable to WebView Bridge Interception and Tampering

Export Ready-to-Drop Configuration

Select format below to copy code or download file directly.

---
description: Capacitor 7 Hardware-Backed Key Attestation and Native Bridge Cryptographic Guardrail - Mandates that all critical Capacitor 7 native plugin dispatches authenticate through hardware-backed cryptographic key attestation (Apple Secure Enclave and Android StrongBox/TEE KeyStore). Prevents runtime payload injection, memory tampering, and Frida/Xposed bridge interception by enforcing per-dispatch signed nonces across the JavaScript-to-Native barrier.
globs: src/**/*.{ts,tsx}, ios/App/App/**/*.swift, android/app/src/**/*.kt
alwaysApply: true
verified_by: "agentrules.org"
license: "CC-BY-4.0"
source: "https://agentrules.org/rules/capacitor-7-hardware-key-attestation-guardrail"
---

# Capacitor 7 Hardware-Backed Key Attestation and Native Bridge Cryptographic Guardrail

> **Severity**: CRITICAL | **Category**: mobile
> **Anti-Pattern Warning**: Unsigned Native Plugin Dispatches Vulnerable to WebView Bridge Interception and Tampering

## System Constraints
You are a Principal Mobile Security Architect enforcing zero-trust hardware-backed attestation for Capacitor 7 hybrid applications. You must mandate that high-privilege native bridge invocations (such as biometrics, credential storage, cryptographic signing, and payment operations) never accept raw, unauthenticated JavaScript payloads. All plugin interfaces must implement hardware-bound key attestation using Apple's Secure Enclave (kSecAccessControlPrivateKeyUsage) and Android KeyStore (KeyProperties.PURPOSE_SIGN with StrongBox or TEE backing). Dispatches must enforce client-side payload digest signing bound to server- or native-issued cryptographic nonces to mitigate bridge manipulation and in-memory dynamic instrumentation.

## Strict Guidelines
- Engineers MUST NEVER dispatch high-privilege native plugin methods via naked, unauthenticated Capacitor `registerPlugin` calls without cryptographic envelope verification.
- Engineers MUST generate asymmetric keys within hardware-isolated environments (Apple Secure Enclave on iOS; Android StrongBox or TEE KeyStore on Android) marked non-exportable.
- Every sensitive plugin dispatch MUST require a single-use, time-bound cryptographic nonce issued by the secure native context or the backend to prevent replay attacks.
- Native plugins MUST compute a SHA-256 digest of incoming invocation payloads, verify the hardware-backed signature against the attested public key, and abort execution if verification fails.
- Hybrid bridge adapters MUST validate that the device has passed basic hardware integrity attestation (App Attest on iOS; Play Integrity API with MEETS_STRONG_INTEGRITY on Android) before trusting bridge keys.
- Engineers MUST NOT persist hardware-bound private keys in localStorage, IndexedDB, or standard unencrypted filesystem directories.

## Bad vs Good Implementations
### Unauthenticated Naked Plugin Call vs. Hardware-Attested Cryptographic Bridge Envelope

#### Bad Antipattern (AI Common Hallucination)
> **Why it fails**: Directly calling native plugin methods with plain JavaScript objects allows any runtime hook (e.g., Frida, malicious WebView script injection, devtools protocol) to mutate payload parameters before reaching the native OS layer.
```typescript
import { registerPlugin } from '@capacitor/core';

interface SecurePaymentPlugin {
  transferFunds(options: { recipientId: string; amount: number }): Promise<{ txId: string }>;
}

const Payment = registerPlugin<SecurePaymentPlugin>('SecurePayment');

// ANTI-PATTERN: Direct dispatch over the window.Capacitor bridge.
// An attacker with Frida or a compromised WebView runtime can intercept,
// modify recipientId/amount in memory, or replay the invocation.
export async function executeTransfer(recipientId: string, amount: number) {
  return await Payment.transferFunds({ recipientId, amount });
}
```

#### Production Standard (Correct)
> **Standard**: The payload is sealed with a hardware-backed key signature and bound to an ephemeral nonce. The native layer verifies the cryptographic signature within the Secure Enclave/TEE before processing the transfer, rendering runtime WebView tampering ineffective.
```typescript
import { registerPlugin } from '@capacitor/core';

interface AttestedEnvelope {
  payloadJson: string;
  nonce: string;
  signatureBase64: string;
  keyAlias: string;
}

interface HardwareVaultPlugin {
  getAttestedNonce(): Promise<{ nonce: string }>;
  signPayload(options: { payload: string; keyAlias: string }): Promise<{ signature: string }>;
}

interface SecurePaymentPlugin {
  transferFundsAttested(envelope: AttestedEnvelope): Promise<{ txId: string }>;
}

const Vault = registerPlugin<HardwareVaultPlugin>('HardwareVault');
const Payment = registerPlugin<SecurePaymentPlugin>('SecurePayment');

// PRODUCTION INVARIANT: Dispatches require Secure Enclave/KeyStore signed envelopes with ephemeral nonces.
export async function executeTransfer(recipientId: string, amount: number) {
  const keyAlias = 'sec_ops_key';
  
  // 1. Fetch single-use hardware-bound cryptographic nonce
  const { nonce } = await Vault.getAttestedNonce();
  
  // 2. Canonicalize payload and append nonce
  const payloadJson = JSON.stringify({ recipientId, amount, nonce });
  
  // 3. Request hardware-backed asymmetric signature from Secure Enclave / StrongBox
  const { signature } = await Vault.signPayload({ payload: payloadJson, keyAlias });
  
  // 4. Dispatch envelope to native layer where signature & nonce are strictly validated
  return await Payment.transferFundsAttested({
    payloadJson,
    nonce,
    signatureBase64: signature,
    keyAlias
  });
}
```

Architectural Specification & Invariant Rationale

Architectural Invariant Design: Capacitor 7 Hardware-Backed Key Attestation and Native Bridge Cryptographic Guardrail

Capacitor 7 Hardware-Backed Key Attestation and Native Bridge Cryptographic Guardrail defines an industrial-grade behavioral standard for mobile engineering. Mandates that all critical Capacitor 7 native plugin dispatches authenticate through hardware-backed cryptographic key attestation (Apple Secure Enclave and Android StrongBox/TEE KeyStore). Prevents runtime payload injection, memory tampering, and Frida/Xposed bridge interception by enforcing per-dispatch signed nonces across the JavaScript-to-Native barrier. 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 Native Plugin Dispatches Vulnerable to WebView Bridge Interception and Tampering 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 Native Plugin Dispatches Vulnerable to WebView Bridge Interception and TamperingCritical
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 dispatch high-privilege native plugin methods via naked, unauthenticated Capacitor `registerPlugin` calls without cryptographic envelope verification.

Engineers MUST NEVER dispatch high-privilege native plugin methods via naked, unauthenticated Capacitor `registerPlugin` calls without cryptographic envelope verification.

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 generate asymmetric keys within hardware-isolated environments (Apple Secure Enclave on iOS

Engineers MUST generate asymmetric keys within hardware-isolated environments (Apple Secure Enclave on iOS; Android StrongBox or TEE KeyStore on Android) marked non-exportable.

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

Every sensitive plugin dispatch MUST require a single-use, time-bound cryptographic nonce issued by the secure native context or the backend to prevent replay attacks.

Every sensitive plugin dispatch MUST require a single-use, time-bound cryptographic nonce issued by the secure native context or the backend to prevent 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.
4

Native plugins MUST compute a SHA-256 digest of incoming invocation payloads, verify the hardware-backed signature against the attested public key, and abort execution if verification fails.

Native plugins MUST compute a SHA-256 digest of incoming invocation payloads, verify the hardware-backed signature against the attested public key, and abort execution if verification fails.

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

Hybrid bridge adapters MUST validate that the device has passed basic hardware integrity attestation (App Attest on iOS

Hybrid bridge adapters MUST validate that the device has passed basic hardware integrity attestation (App Attest on iOS; Play Integrity API with MEETS_STRONG_INTEGRITY on Android) before trusting bridge keys.

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

Engineers MUST NOT persist hardware-bound private keys in localStorage, IndexedDB, or standard unencrypted filesystem directories.

Engineers MUST NOT persist hardware-bound private keys in localStorage, IndexedDB, or standard unencrypted filesystem directories.

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 Native Bridge Cryptographic Guardrail critical for AI coding assistants?

Mandates that all critical Capacitor 7 native plugin dispatches authenticate through hardware-backed cryptographic key attestation (Apple Secure Enclave and Android StrongBox/TEE KeyStore). Prevents runtime payload injection, memory tampering, and Frida/Xposed bridge interception by enforcing per-dispatch signed nonces across the JavaScript-to-Native barrier. 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 Native Plugin Dispatches Vulnerable to WebView Bridge Interception and Tampering) 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