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

Capacitor 7 Secure Enclave Direct-Memory Cryptographic Isolation

Enforces strict native memory isolation for hardware-backed cryptographic operations across the Capacitor 7 bridge. High-entropy key material and biometric credentials must remain locked within iOS Secure Enclave (kSecAttrAccessibleAfterFirstUnlockThisDeviceOnly) or Android StrongBox KeyStore, prohibiting serialization or leakage of private keys into the V8 or JavaScriptCore webview heap.

Prohibited Anti-Pattern: Exposing Raw Private Keys or Biometric Secrets to the Capacitor JavaScript Webview Heap

Export Ready-to-Drop Configuration

Select format below to copy code or download file directly.

---
description: Capacitor 7 Secure Enclave Direct-Memory Cryptographic Isolation - Enforces strict native memory isolation for hardware-backed cryptographic operations across the Capacitor 7 bridge. High-entropy key material and biometric credentials must remain locked within iOS Secure Enclave (kSecAttrAccessibleAfterFirstUnlockThisDeviceOnly) or Android StrongBox KeyStore, prohibiting serialization or leakage of private keys into the V8 or JavaScriptCore webview heap.
globs: src/**/*.{ts,tsx}, ios/App/**/*.{swift,h,m}, android/app/src/main/**/*.{kt,java}
alwaysApply: true
verified_by: "agentrules.org"
license: "CC-BY-4.0"
source: "https://agentrules.org/rules/capacitor-7-secure-enclave-crypto-isolation"
---

# Capacitor 7 Secure Enclave Direct-Memory Cryptographic Isolation

> **Severity**: CRITICAL | **Category**: mobile
> **Anti-Pattern Warning**: Exposing Raw Private Keys or Biometric Secrets to the Capacitor JavaScript Webview Heap

## System Constraints
You are a Principal Mobile Systems Security Engineer enforcing strict cryptographic boundaries in Capacitor 7 hybrid applications. You must mandate that raw private keys, entropy seeds, and hardware-bound biometric tokens NEVER pass across the Capacitor JavaScript bridge into the webview heap. Enforce challenge-response architectures where the bridge only transmits ephemeral challenge payloads and receives cryptographic signatures or opaque hardware key aliases.

## Strict Guidelines
- Engineers MUST ALWAYS isolate private key generation and storage inside hardware modules (iOS Secure Enclave / Android StrongBox Keystore) with non-exportable key flags.
- Engineers MUST NOT serialize, return, or bridge raw private keys, seeds, or biometric tokens into TypeScript/JavaScript webview memory.
- Code SHOULD use opaque key identifiers (UUID/string alias) in webview state, delegating all signing operations to native bridge plugins via challenge-response patterns.
- Services MUST enforce cryptographic operation boundaries natively, wiping temporary challenge buffers immediately from native memory after signing.
- Components NEVER store long-lived cryptographic credentials in localStorage, IndexedDB, or JavaScript runtime variables.

## Bad vs Good Implementations
### Hardware Enclave Signing vs. Webview Key Material Exposure

#### Bad Antipattern (AI Common Hallucination)
> **Why it fails**: Raw cryptographic private keys cross the Capacitor bridge into the webview execution context. This exposes high-entropy keys to memory inspection, XSS exfiltration, unencrypted DOM storage, and heap dump profiling.
```typescript
// ANTI-PATTERN: Extracting raw key material into webview heap across the bridge
import { registerPlugin } from '@capacitor/core';

interface InsecureCryptoPlugin {
  generateAndExportKeyPair(): Promise<{ privateKeyPem: string; publicKeyPem: string }>;
  signPayload(options: { privateKeyPem: string; data: string }): Promise<{ signature: string }>;
}

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

export async function signTransaction(payload: string): Promise<string> {
  // CRITICAL VULNERABILITY: Raw private key is exposed to V8 heap, DOM XSS, and heap snapshots
  const keys = await InsecureCrypto.generateAndExportKeyPair();
  sessionStorage.setItem('privKey', keys.privateKeyPem);
  
  const result = await InsecureCrypto.signPayload({
    privateKeyPem: keys.privateKeyPem,
    data: payload,
  });
  return result.signature;
}
```

#### Production Standard (Correct)
> **Standard**: The native bridge uses hardware isolation (Secure Enclave / StrongBox). Only an opaque alias and challenge payload traverse the bridge. The private key remains completely inaccessible to the webview runtime and JavaScript heap.
```typescript
// SECURE PATTERN: Hardware-isolated key generation with native challenge-response signing
import { registerPlugin } from '@capacitor/core';

interface SecureEnclavePlugin {
  generateHardwareKey(options: { alias: string; requireBiometrics: boolean }): Promise<{ alias: string; publicKeyDer: string }>;
  signChallenge(options: { alias: string; challengeBase64: string }): Promise<{ signatureBase64: string }>;
}

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

export async function signHardwareBoundChallenge(keyAlias: string, challengeBuffer: Uint8Array): Promise<string> {
  // Key generation occurs strictly in native Secure Enclave / StrongBox;
  // only opaque alias and public credentials pass to the webview.
  const base64Challenge = btoa(String.fromCharCode(...challengeBuffer));
  
  const response = await SecureEnclave.signChallenge({
    alias: keyAlias,
    challengeBase64: base64Challenge
  });
  
  // Private key never entered the V8/JSC heap; only the digital signature returns
  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 Secure Enclave Direct-Memory Cryptographic Isolation

Capacitor 7 Secure Enclave Direct-Memory Cryptographic Isolation defines an industrial-grade behavioral standard for mobile engineering. Enforces strict native memory isolation for hardware-backed cryptographic operations across the Capacitor 7 bridge. High-entropy key material and biometric credentials must remain locked within iOS Secure Enclave (kSecAttrAccessibleAfterFirstUnlockThisDeviceOnly) or Android StrongBox KeyStore, prohibiting serialization or leakage of private keys into the V8 or JavaScriptCore webview heap. 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: Exposing Raw Private Keys or Biometric Secrets to the Capacitor JavaScript Webview Heap 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 DriftExposing Raw Private Keys or Biometric Secrets to the Capacitor JavaScript Webview HeapCritical
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 private key generation and storage inside hardware modules (iOS Secure Enclave / Android StrongBox Keystore) with non-exportable key flags.

Engineers MUST ALWAYS isolate private key generation and storage inside hardware modules (iOS Secure Enclave / Android StrongBox Keystore) with non-exportable key flags.

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, return, or bridge raw private keys, seeds, or biometric tokens into TypeScript/JavaScript webview memory.

Engineers MUST NOT serialize, return, or bridge raw private keys, seeds, or biometric tokens into TypeScript/JavaScript webview 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

Code SHOULD use opaque key identifiers (UUID/string alias) in webview state, delegating all signing operations to native bridge plugins via challenge-response patterns.

Code SHOULD use opaque key identifiers (UUID/string alias) in webview state, delegating all signing operations to native bridge plugins via challenge-response patterns.

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 enforce cryptographic operation boundaries natively, wiping temporary challenge buffers immediately from native memory after signing.

Services MUST enforce cryptographic operation boundaries natively, wiping temporary challenge buffers immediately from native memory after signing.

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 long-lived cryptographic credentials in localStorage, IndexedDB, or JavaScript runtime variables.

Components NEVER store long-lived cryptographic credentials in localStorage, IndexedDB, or JavaScript runtime variables.

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 Enclave Direct-Memory Cryptographic Isolation critical for AI coding assistants?

Enforces strict native memory isolation for hardware-backed cryptographic operations across the Capacitor 7 bridge. High-entropy key material and biometric credentials must remain locked within iOS Secure Enclave (kSecAttrAccessibleAfterFirstUnlockThisDeviceOnly) or Android StrongBox KeyStore, prohibiting serialization or leakage of private keys into the V8 or JavaScriptCore webview heap. 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 (Exposing Raw Private Keys or Biometric Secrets to the Capacitor JavaScript Webview Heap) 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