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

Capacitor 7 Secure Hardware Enclave Cryptographic Bridge Invariant

Enforces non-extractable, biometric-gated hardware key generation and cryptographic operations executing directly within the iOS Secure Enclave (kSecAttrAccessControlUserPresence / SecureElement) and Android Keystore (KeyProperties.PURPOSE_SIGN with StrongBox/TEE backing). Private key material, raw seeds, and decrypted secret payloads MUST NEVER traverse the Capacitor JavaScript-to-Native bridge or reside in volatile V8/WebKit heap memory.

Prohibited Anti-Pattern: Bridge-Transiting Cryptographic Keys and In-Memory Software Signing in Capacitor WebViews

Export Ready-to-Drop Configuration

Select format below to copy code or download file directly.

---
description: Capacitor 7 Secure Hardware Enclave Cryptographic Bridge Invariant - Enforces non-extractable, biometric-gated hardware key generation and cryptographic operations executing directly within the iOS Secure Enclave (kSecAttrAccessControlUserPresence / SecureElement) and Android Keystore (KeyProperties.PURPOSE_SIGN with StrongBox/TEE backing). Private key material, raw seeds, and decrypted secret payloads MUST NEVER traverse the Capacitor JavaScript-to-Native bridge or reside in volatile V8/WebKit heap memory.
globs: src/**/*.{ts,tsx}, ios/App/App/Plugins/**/*.{swift,h,m}, android/app/src/main/java/**/*.kt
alwaysApply: true
verified_by: "agentrules.org"
license: "CC-BY-4.0"
source: "https://agentrules.org/rules/capacitor-secure-enclave-crypto-bridge-guardrail"
---

# Capacitor 7 Secure Hardware Enclave Cryptographic Bridge Invariant

> **Severity**: CRITICAL | **Category**: mobile
> **Anti-Pattern Warning**: Bridge-Transiting Cryptographic Keys and In-Memory Software Signing in Capacitor WebViews

## System Constraints
You are a Principal Mobile Cryptography Engineer enforcing Capacitor 7 Secure Hardware Enclave Cryptographic Bridge invariants. Mandate that all asymmetric key creation, authentication gating, and digital signing occur strictly in hardware-backed isolation (iOS Secure Enclave / Android StrongBox KeyStore). Ensure that private key primitives are non-exportable and never materialized in JavaScript or bridge JSON payloads.

## Strict Guidelines
- Engineers MUST ALWAYS enforce hardware-backed key generation using `KeyGenParameterSpec` with `PURPOSE_SIGN` and `setUserAuthenticationRequired(true)` on Android, and `kSecAccessControlBiometryAny` paired with `kSecAttrTokenIDSecureEnclave` on iOS.
- Engineers MUST NEVER return raw private keys, DER-encoded secret keys, or key seeds over the Capacitor bridge into JavaScript memory.
- Cryptographic signing operations MUST accept only pre-computed challenge hashes (e.g., SHA-256 digests) across the bridge, returning only detached digital signatures (DER or raw r/s buffers).
- Bridge native code MUST verify hardware backing capabilities (e.g., StrongBox availability or Secure Enclave presence) before generating keys, falling back only to TEE if explicitly configured, but NEVER falling back to software emulation.
- Services MUST zeroize/wipe any sensitive challenge payload buffers in native memory immediately after signature generation using secure memory scrubbers.
- Components NEVER store private key metadata or key representations inside Web Storage (`localStorage`, `sessionStorage`, or `IndexedDB`).

## Bad vs Good Implementations
### Hardware Enclave Signing Bridge Invocation

#### Bad Antipattern (AI Common Hallucination)
> **Why it fails**: Exporting the private key across the Capacitor bridge leaks unencrypted cryptographic material into volatile WebKit/V8 heap memory, making it vulnerable to XSS exploits, bridge sniffing, memory scrapers, and persistent state serialization leaks.
```typescript
import { registerPlugin } from '@capacitor/core';

interface InsecureCryptoPlugin {
  generateKey(): Promise<{ privateKey: string; publicKey: string }>;
  signData(options: { privateKey: string; data: string }): Promise<{ signature: string }>;
}

const InsecureCrypto = registerPlugin<InsecureCryptoPlugin>('InsecureCrypto');

export async function signPayload(data: string): Promise<string> {
  // Anti-Pattern: Private key is fetched into WebView JS memory and sent across the bridge
  const { privateKey } = await InsecureCrypto.generateKey();
  const { signature } = await InsecureCrypto.signData({ privateKey, data });
  return signature;
}
```

#### Production Standard (Correct)
> **Standard**: Key generation happens strictly inside the hardware enclave with biometric access control. The JavaScript layer only manages key aliases and cryptographic hashes; private keys remain mathematically non-extractable.
```typescript
import { registerPlugin } from '@capacitor/core';

export interface EnclaveBridgePlugin {
  ensureEnclaveKeyPair(options: { alias: string; requireBiometry: boolean }): Promise<{ publicKeyDer: string }>;
  signHash(options: {
    alias: string;
    sha256Hex: string;
    biometricPrompt: string;
  }): Promise<{ signatureDer: string }>;
}

export const EnclaveBridge = registerPlugin<EnclaveBridgePlugin>('EnclaveBridge');

export async function signAuthenticationChallenge(alias: string, challengeDigestHex: string): Promise<string> {
  // Invariant: Private key never leaves Secure Enclave / StrongBox Keystore.
  // Only non-extractable alias and digest cross the bridge; biometrics are enforced in hardware.
  const result = await EnclaveBridge.signHash({
    alias,
    sha256Hex: challengeDigestHex,
    biometricPrompt: 'Authenticate to sign authorization challenge'
  });
  return result.signatureDer;
}
```

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 Secure Hardware Enclave Cryptographic Bridge Invariant

Capacitor 7 Secure Hardware Enclave Cryptographic Bridge Invariant defines an industrial-grade behavioral standard for mobile engineering. Enforces non-extractable, biometric-gated hardware key generation and cryptographic operations executing directly within the iOS Secure Enclave (kSecAttrAccessControlUserPresence / SecureElement) and Android Keystore (KeyProperties.PURPOSE_SIGN with StrongBox/TEE backing). Private key material, raw seeds, and decrypted secret payloads MUST NEVER traverse the Capacitor JavaScript-to-Native bridge or reside in volatile V8/WebKit heap memory. 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: Bridge-Transiting Cryptographic Keys and In-Memory Software Signing in Capacitor WebViews 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 DriftBridge-Transiting Cryptographic Keys and In-Memory Software Signing in Capacitor WebViewsCritical
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 hardware-backed key generation using `KeyGenParameterSpec` with `PURPOSE_SIGN` and `setUserAuthenticationRequired(true)` on Android, and `kSecAccessControlBiometryAny` paired with `kSecAttrTokenIDSecureEnclave` on iOS.

Engineers MUST ALWAYS enforce hardware-backed key generation using `KeyGenParameterSpec` with `PURPOSE_SIGN` and `setUserAuthenticationRequired(true)` on Android, and `kSecAccessControlBiometryAny` paired with `kSecAttrTokenIDSecureEnclave` on iOS.

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 NEVER return raw private keys, DER-encoded secret keys, or key seeds over the Capacitor bridge into JavaScript memory.

Engineers MUST NEVER return raw private keys, DER-encoded secret keys, or key seeds over the Capacitor bridge into JavaScript memory.

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

Cryptographic signing operations MUST accept only pre-computed challenge hashes (e.g., SHA-256 digests) across the bridge, returning only detached digital signatures (DER or raw r/s buffers).

Cryptographic signing operations MUST accept only pre-computed challenge hashes (e.g., SHA-256 digests) across the bridge, returning only detached digital signatures (DER or raw r/s buffers).

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

Bridge native code MUST verify hardware backing capabilities (e.g., StrongBox availability or Secure Enclave presence) before generating keys, falling back only to TEE if explicitly configured, but NEVER falling back to software emulation.

Bridge native code MUST verify hardware backing capabilities (e.g., StrongBox availability or Secure Enclave presence) before generating keys, falling back only to TEE if explicitly configured, but NEVER falling back to software emulation.

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

Services MUST zeroize/wipe any sensitive challenge payload buffers in native memory immediately after signature generation using secure memory scrubbers.

Services MUST zeroize/wipe any sensitive challenge payload buffers in native memory immediately after signature generation using secure memory scrubbers.

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 store private key metadata or key representations inside Web Storage (`localStorage`, `sessionStorage`, or `IndexedDB`).

Components NEVER store private key metadata or key representations inside Web Storage (`localStorage`, `sessionStorage`, 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.
Technical Questions & Answers

Frequently Asked Technical Questions

Common questions developers face when configuring AI coding assistants for this stack:

Q:Why is Capacitor 7 Secure Hardware Enclave Cryptographic Bridge Invariant critical for AI coding assistants?

Enforces non-extractable, biometric-gated hardware key generation and cryptographic operations executing directly within the iOS Secure Enclave (kSecAttrAccessControlUserPresence / SecureElement) and Android Keystore (KeyProperties.PURPOSE_SIGN with StrongBox/TEE backing). Private key material, raw seeds, and decrypted secret payloads MUST NEVER traverse the Capacitor JavaScript-to-Native bridge or reside in volatile V8/WebKit heap memory. 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 (Bridge-Transiting Cryptographic Keys and In-Memory Software Signing in Capacitor WebViews) 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