This specification is maintained by the AgentRules Working Group. Have enhancements or want to claim maintainership?Submit Specification →
mobilecritical PriorityID: capacitor-secure-enclave-webcrypto-attestation-bridge

Hardware-Backed WebCrypto Enclave Bridge Invariants and Attestation Guardrails

Enforces hardware-backed cryptographic key generation and signing isolation within iOS Secure Enclave and Android Keystore (StrongBox) through Capacitor 7 native bridges. Ensures asymmetric private keys are strictly non-exportable and never materialized inside the hybrid WebView JavaScript execution context, while enforcing cryptographic hardware attestation tokens on all signing operations.

Prohibited Anti-Pattern: Exporting Private Key Material to Hybrid WebViews or Bypassing Hardware Attestation Proofs

Export Ready-to-Drop Configuration

Select format below to copy code or download file directly.

---
description: Hardware-Backed WebCrypto Enclave Bridge Invariants and Attestation Guardrails - Enforces hardware-backed cryptographic key generation and signing isolation within iOS Secure Enclave and Android Keystore (StrongBox) through Capacitor 7 native bridges. Ensures asymmetric private keys are strictly non-exportable and never materialized inside the hybrid WebView JavaScript execution context, while enforcing cryptographic hardware attestation tokens on all signing operations.
globs: src/**/*.{ts,tsx}, ios/App/App/**/*.{swift,m}, android/app/src/main/java/**/*.{kt,java}
alwaysApply: true
verified_by: "agentrules.org"
license: "CC-BY-4.0"
source: "https://agentrules.org/rules/capacitor-secure-enclave-webcrypto-attestation-bridge"
---

# Hardware-Backed WebCrypto Enclave Bridge Invariants and Attestation Guardrails

> **Severity**: CRITICAL | **Category**: mobile
> **Anti-Pattern Warning**: Exporting Private Key Material to Hybrid WebViews or Bypassing Hardware Attestation Proofs

## System Constraints
You are a Principal Security Architect enforcing Capacitor 7 Hardware-Backed WebCrypto Enclave Attestation Bridge standards. Mandate that private keys never enter WebView heap space, verify non-exportable flags on native keychains, and enforce remote hardware attestation challenges for all cryptographic operations.

## Strict Guidelines
- Engineers MUST ALWAYS enforce key generation via native Secure Enclave (kSecAttrAccessibleAfterFirstUnlockThisDeviceOnly) or Android StrongBox (KeyProperties.PURPOSE_SIGN) with exportability flags explicitly set to false.
- Engineers MUST NOT serialize, mirror, or pass raw private key bytes across the Capacitor JavaScript-to-Native bridge under any circumstance.
- Code SHOULD return opaque KeyIdentifier handles to the WebView mimicking non-extractable CryptoKey objects rather than exposing key parameters.
- Services MUST validate server-issued cryptographic nonces within attestation certificates (Apple DeviceCheck / DCAppAttestService or Android Key Attestation) prior to accepting signed payloads.
- Components NEVER store persistent cryptographic material in standard Web Storage (localStorage, IndexedDB) without wrapping under an Enclave-derived hardware key.

## Bad vs Good Implementations
### Secure Enclave Hardware Key Generation vs In-Memory WebCrypto Polyfill

#### Bad Antipattern (AI Common Hallucination)
> **Why it fails**: Generating the keypair within the browser WebCrypto context with extractable=true risks memory-scraping attacks in the WebView heap and exposes the raw private key over the Capacitor serialized bridge.
```typescript
import { registerPlugin } from '@capacitor/core';

// Anti-pattern: Generating exportable software keys in WebView and saving to native bridge
export async function initEnclaveKey(alias: string): Promise<CryptoKeyPair> {
  const keyPair = await window.crypto.subtle.generateKey(
    {
      name: 'ECDSA',
      namedCurve: 'P-256',
    },
    true, // CRITICAL FLAW: Private key marked extractable in WebView
    ['sign', 'verify']
  );
  
  const exportedPrivate = await window.crypto.subtle.exportKey('pkcs8', keyPair.privateKey);
  const Bridge = registerPlugin<{ storeKey: (opts: { alias: string; key: ArrayBuffer }) => Promise<void> }>('Bridge');
  await Bridge.storeKey({ alias, key: exportedPrivate }); // Leaks private key across bridge
  
  return keyPair;
}
```

#### Production Standard (Correct)
> **Standard**: Delegates cryptographic generation directly to the native Secure Enclave / StrongBox layer, yielding an unexportable hardware key and returning only an opaque handle with remote attestation proofs back to the hybrid environment.
```typescript
import { registerPlugin } from '@capacitor/core';

export interface EnclaveKeyHandle {
  readonly keyId: string;
  readonly algorithm: 'ES256';
  readonly attestationStatement: string; // Base64 DER encoded
}

interface SecureEnclavePlugin {
  generateHardwareKey(options: { alias: string; challenge: string }): Promise<EnclaveKeyHandle>;
  signWithHardwareKey(options: { keyId: string; data: string }): Promise<{ signature: string }>;
}

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

export async function initEnclaveKey(alias: string, serverChallenge: string): Promise<EnclaveKeyHandle> {
  // Invariant: Native Secure Enclave / Strongbox creates non-exportable hardware key and binds to challenge
  const handle = await SecureEnclave.generateHardwareKey({
    alias,
    challenge: serverChallenge
  });
  
  // Private key remains bound to hardware; WebView holds only opaque identifier and hardware attestation cert
  return Object.freeze({
    keyId: handle.keyId,
    algorithm: 'ES256',
    attestationStatement: handle.attestationStatement
  });
}
```

Architectural Specification & Invariant Rationale

Architectural Invariant Design: Hardware-Backed WebCrypto Enclave Bridge Invariants and Attestation Guardrails

Hardware-Backed WebCrypto Enclave Bridge Invariants and Attestation Guardrails defines an industrial-grade behavioral standard for mobile engineering. Enforces hardware-backed cryptographic key generation and signing isolation within iOS Secure Enclave and Android Keystore (StrongBox) through Capacitor 7 native bridges. Ensures asymmetric private keys are strictly non-exportable and never materialized inside the hybrid WebView JavaScript execution context, while enforcing cryptographic hardware attestation tokens on all signing operations. 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: Exporting Private Key Material to Hybrid WebViews or Bypassing Hardware Attestation Proofs 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 DriftExporting Private Key Material to Hybrid WebViews or Bypassing Hardware Attestation ProofsCritical
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 key generation via native Secure Enclave (kSecAttrAccessibleAfterFirstUnlockThisDeviceOnly) or Android StrongBox (KeyProperties.PURPOSE_SIGN) with exportability flags explicitly set to false.

Engineers MUST ALWAYS enforce key generation via native Secure Enclave (kSecAttrAccessibleAfterFirstUnlockThisDeviceOnly) or Android StrongBox (KeyProperties.PURPOSE_SIGN) with exportability flags explicitly set to false.

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 serialize, mirror, or pass raw private key bytes across the Capacitor JavaScript-to-Native bridge under any circumstance.

Engineers MUST NOT serialize, mirror, or pass raw private key bytes across the Capacitor JavaScript-to-Native bridge under any circumstance.

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 SHOULD return opaque KeyIdentifier handles to the WebView mimicking non-extractable CryptoKey objects rather than exposing key parameters.

Code SHOULD return opaque KeyIdentifier handles to the WebView mimicking non-extractable CryptoKey objects rather than exposing key parameters.

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 validate server-issued cryptographic nonces within attestation certificates (Apple DeviceCheck / DCAppAttestService or Android Key Attestation) prior to accepting signed payloads.

Services MUST validate server-issued cryptographic nonces within attestation certificates (Apple DeviceCheck / DCAppAttestService or Android Key Attestation) prior to accepting signed payloads.

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 persistent cryptographic material in standard Web Storage (localStorage, IndexedDB) without wrapping under an Enclave-derived hardware key.

Components NEVER store persistent cryptographic material in standard Web Storage (localStorage, IndexedDB) without wrapping under an Enclave-derived hardware key.

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 WebCrypto Enclave Bridge Invariants and Attestation Guardrails critical for AI coding assistants?

Enforces hardware-backed cryptographic key generation and signing isolation within iOS Secure Enclave and Android Keystore (StrongBox) through Capacitor 7 native bridges. Ensures asymmetric private keys are strictly non-exportable and never materialized inside the hybrid WebView JavaScript execution context, while enforcing cryptographic hardware attestation tokens on all signing operations. 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 (Exporting Private Key Material to Hybrid WebViews or Bypassing Hardware Attestation Proofs) 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