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

Capacitor 7 Hardware Enclave WebCrypto Bridge Invariant

Enforces that all cryptographic key generation, signing, and decryption operations in Capacitor 7 hybrid applications delegate directly to hardware-backed isolated environments (Apple Secure Enclave and Android StrongBox/TEE Keystore) via native bridge plugins. Strictly prohibits the use of pure JavaScript WebCrypto polyfills, userland crypto libraries, or in-memory key representations inside the WebView context to eliminate DOM-based key exfiltration vectors. Mandates non-exportable private key handles where cryptographic material never traverses the bridge boundary.

Prohibited Anti-Pattern: Executing Cryptographic Operations in WebView Memory or Relying on Software-Only WebCrypto Polyfills

Export Ready-to-Drop Configuration

Select format below to copy code or download file directly.

---
description: Capacitor 7 Hardware Enclave WebCrypto Bridge Invariant - Enforces that all cryptographic key generation, signing, and decryption operations in Capacitor 7 hybrid applications delegate directly to hardware-backed isolated environments (Apple Secure Enclave and Android StrongBox/TEE Keystore) via native bridge plugins. Strictly prohibits the use of pure JavaScript WebCrypto polyfills, userland crypto libraries, or in-memory key representations inside the WebView context to eliminate DOM-based key exfiltration vectors. Mandates non-exportable private key handles where cryptographic material never traverses the bridge boundary.
globs: src/**/*.{ts,tsx}, ios/App/**/*.{swift,m}, android/app/**/*.{java,kt}
alwaysApply: true
verified_by: "agentrules.org"
license: "CC-BY-4.0"
source: "https://agentrules.org/rules/capacitor-7-hardware-enclave-webcrypto-bridge-invariant"
---

# Capacitor 7 Hardware Enclave WebCrypto Bridge Invariant

> **Severity**: CRITICAL | **Category**: mobile
> **Anti-Pattern Warning**: Executing Cryptographic Operations in WebView Memory or Relying on Software-Only WebCrypto Polyfills

## System Constraints
You are a Principal Mobile Systems Architect and Security Engineer enforcing strict hardware-backed cryptographic guarantees in Capacitor 7 applications. You must reject any implementation that executes cryptographic operations inside the WebView thread or relies on JavaScript-based WebCrypto polyfills (e.g., node-forge, crypto-js, subtle-crypto in-memory polyfills). Enforce delegation to Apple Secure Enclave and Android KeyStore/StrongBox via verified Capacitor native bridge plugins, ensuring private keys are flagged strictly non-exportable.

## Strict Guidelines
- Engineers MUST ALWAYS isolate cryptographic operations within native Secure Enclave (iOS) or StrongBox/TEE KeyStore (Android) via typed Capacitor 7 plugins.
- Engineers MUST NOT initialize or expose raw private keys, seed phrases, or sensitive derivation paths within the WebView JavaScript runtime or IndexedDB.
- Code SHOULD enforce native key generation with 'kSecAttrIsExtractable: false' (iOS) and 'setIsStrongBoxBacked(true)' / 'setUserAuthenticationRequired(true)' (Android).
- Services MUST register a strictly typed bridge interface returning opaque key aliases rather than raw key material across the Capacitor bridge serialization layer.
- Components NEVER store encryption keys in localStorage, sessionStorage, Capacitor Preferences, or unencrypted SQLite storage.

## Bad vs Good Implementations
### Hardware Bridge Invariant vs. In-Memory WebCrypto Polyfill

#### Bad Antipattern (AI Common Hallucination)
> **Why it fails**: Generating cryptographic keypairs inside the WebView JavaScript thread allows arbitrary script execution (XSS or malicious third-party dependencies) to extract private keys using crypto.subtle.exportKey or heap inspections. Keys are not hardware-bound.
```typescript
import { Capacitor } from '@capacitor/core';

// VULNERABLE: Generates exportable keys inside the WebView JavaScript engine
export class InsecureCryptoService {
  private keyPair: CryptoKeyPair | null = null;

  async initializeIdentity(): Promise<void> {
    // Uses WebView WebCrypto or polyfill - keys live in heap and can be dumped via XSS
    this.keyPair = await window.crypto.subtle.generateKey(
      {
        name: 'ECDSA',
        namedCurve: 'P-256',
      },
      true, // Vulnerability: key is extractable into JS memory
      ['sign', 'verify']
    );
  }

  async signPayload(payload: Uint8Array): Promise<ArrayBuffer> {
    if (!this.keyPair) throw new Error('Uninitialized');
    return await window.crypto.subtle.sign(
      { name: 'ECDSA', hash: { name: 'SHA-256' } },
      this.keyPair.privateKey,
      payload
    );
  }
}
```

#### Production Standard (Correct)
> **Standard**: The hardware bridge approach delegates key generation directly to the device's Secure Enclave or StrongBox. Private key material is marked non-exportable and never enters the WebView runtime; only opaque aliases and non-sensitive public keys pass through the Capacitor bridge.
```typescript
import { registerPlugin } from '@capacitor/core';

export interface SecureEnclavePlugin {
  generateHardwareKeyPair(options: { alias: string; requireBiometrics: boolean }): Promise<{ publicKeyDerBase64: string }>;
  signHardwarePayload(options: { alias: string; dataBase64: string }): Promise<{ signatureBase64: string }>;
  hasHardwareSecurity(): Promise<{ hasStrongBox: boolean; hasSecureEnclave: boolean }>;
}

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

export class HardwareCryptoService {
  private readonly keyAlias = 'app_auth_identity_v1';

  async initializeIdentity(): Promise<string> {
    const hardware = await SecureEnclave.hasHardwareSecurity();
    if (!hardware.hasStrongBox && !hardware.hasSecureEnclave) {
      throw new Error('Device does not meet hardware security baseline: TEE/Enclave unavailable');
    }

    // Private key NEVER crosses native bridge; strictly isolated to Secure Enclave / KeyStore
    const result = await SecureEnclave.generateHardwareKeyPair({
      alias: this.keyAlias,
      requireBiometrics: true,
    });
    return result.publicKeyDerBase64;
  }

  async signPayload(data: Uint8Array): Promise<string> {
    const dataBase64 = btoa(String.fromCharCode(...data));
    const response = await SecureEnclave.signHardwarePayload({
      alias: this.keyAlias,
      dataBase64,
    });
    return response.signatureBase64;
  }
}
```

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 Enclave WebCrypto Bridge Invariant

Capacitor 7 Hardware Enclave WebCrypto Bridge Invariant defines an industrial-grade behavioral standard for mobile engineering. Enforces that all cryptographic key generation, signing, and decryption operations in Capacitor 7 hybrid applications delegate directly to hardware-backed isolated environments (Apple Secure Enclave and Android StrongBox/TEE Keystore) via native bridge plugins. Strictly prohibits the use of pure JavaScript WebCrypto polyfills, userland crypto libraries, or in-memory key representations inside the WebView context to eliminate DOM-based key exfiltration vectors. Mandates non-exportable private key handles where cryptographic material never traverses the bridge boundary. 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: Executing Cryptographic Operations in WebView Memory or Relying on Software-Only WebCrypto Polyfills 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 DriftExecuting Cryptographic Operations in WebView Memory or Relying on Software-Only WebCrypto PolyfillsCritical
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 isolate cryptographic operations within native Secure Enclave (iOS) or StrongBox/TEE KeyStore (Android) via typed Capacitor 7 plugins.

Engineers MUST ALWAYS isolate cryptographic operations within native Secure Enclave (iOS) or StrongBox/TEE KeyStore (Android) via typed Capacitor 7 plugins.

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 initialize or expose raw private keys, seed phrases, or sensitive derivation paths within the WebView JavaScript runtime or IndexedDB.

Engineers MUST NOT initialize or expose raw private keys, seed phrases, or sensitive derivation paths within the WebView JavaScript runtime or IndexedDB.

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 enforce native key generation with 'kSecAttrIsExtractable

Code SHOULD enforce native key generation with 'kSecAttrIsExtractable: false' (iOS) and 'setIsStrongBoxBacked(true)' / 'setUserAuthenticationRequired(true)' (Android).

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 register a strictly typed bridge interface returning opaque key aliases rather than raw key material across the Capacitor bridge serialization layer.

Services MUST register a strictly typed bridge interface returning opaque key aliases rather than raw key material across the Capacitor bridge serialization layer.

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 encryption keys in localStorage, sessionStorage, Capacitor Preferences, or unencrypted SQLite storage.

Components NEVER store encryption keys in localStorage, sessionStorage, Capacitor Preferences, or unencrypted SQLite storage.

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 Enclave WebCrypto Bridge Invariant critical for AI coding assistants?

Enforces that all cryptographic key generation, signing, and decryption operations in Capacitor 7 hybrid applications delegate directly to hardware-backed isolated environments (Apple Secure Enclave and Android StrongBox/TEE Keystore) via native bridge plugins. Strictly prohibits the use of pure JavaScript WebCrypto polyfills, userland crypto libraries, or in-memory key representations inside the WebView context to eliminate DOM-based key exfiltration vectors. Mandates non-exportable private key handles where cryptographic material never traverses the bridge boundary. 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 (Executing Cryptographic Operations in WebView Memory or Relying on Software-Only WebCrypto Polyfills) 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