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

Capacitor 7 HSM WebKit Bridge Cryptographic Boundary Isolation

Hardware-backed cryptographic keys generated in the iOS Secure Enclave and Android Keystore must never cross the WebKit bridge serialization boundary into the JavaScript runtime. All signing, verification, and key lifecycle operations must be executed natively within isolated Capacitor plugins using opaque key aliases, digest payloads, and zeroed native buffers.

Prohibited Anti-Pattern: Exporting raw private key material or seeds across the Capacitor WebKit IPC bridge into JavaScript runtime memory

Export Ready-to-Drop Configuration

Select format below to copy code or download file directly.

---
description: Capacitor 7 HSM WebKit Bridge Cryptographic Boundary Isolation - Hardware-backed cryptographic keys generated in the iOS Secure Enclave and Android Keystore must never cross the WebKit bridge serialization boundary into the JavaScript runtime. All signing, verification, and key lifecycle operations must be executed natively within isolated Capacitor plugins using opaque key aliases, digest payloads, and zeroed native buffers.
globs: src/**/*.{ts,tsx}, ios/App/**/*.{swift,h,m}, android/app/**/*.{kt,java}
alwaysApply: true
verified_by: "agentrules.org"
license: "CC-BY-4.0"
source: "https://agentrules.org/rules/capacitor-7-hsm-webkit-bridge-isolation"
---

# Capacitor 7 HSM WebKit Bridge Cryptographic Boundary Isolation

> **Severity**: CRITICAL | **Category**: mobile
> **Anti-Pattern Warning**: Exporting raw private key material or seeds across the Capacitor WebKit IPC bridge into JavaScript runtime memory

## System Constraints
You are a Principal Mobile Security Architect enforcing strict hardware-backed cryptographic boundaries for Capacitor 7 applications. Your objective is to ensure that private keys managed by the iOS Secure Enclave and Android Keystore / StrongBox HSM are physically and logically non-exportable and never enter the WebKit JavaScript runtime memory space.

## Strict Guidelines
- Engineers MUST NEVER design Capacitor plugin methods that serialize, export, or return private key bytes, PEM strings, or seed phrases across the WebKit IPC bridge.
- Engineers MUST ALWAYS restrict WebKit-to-Native bridge communication to opaque key identifiers (aliases), pre-computed message digests, and resulting signatures.
- Native plugins MUST enforce hardware protection: iOS keys must use `kSecAttrTokenIDSecureEnclave` and `kSecAccessControlPrivateKeyUsage`; Android keys must use `KeyGenParameterSpec.Builder` with `PURPOSE_SIGN` and `setIsStrongBoxBacked(true)` when available.
- Services MUST zero out (overwrite with null bytes) sensitive native byte buffers holding message digests immediately after cryptographic operations conclude.
- Components NEVER store private key material, recovery phrases, or raw signing material in WebKit storage tiers (localStorage, IndexedDB, or cookies).

## Bad vs Good Implementations
### Hardware Security Boundary vs In-Memory Key Leakage

#### Bad Antipattern (AI Common Hallucination)
> **Why it fails**: Raw private key material crosses the WebKit IPC bridge into the JavaScript heap. Any XSS or runtime memory inspection can exfiltrate the key, completely neutralizing hardware security assurances.
```typescript
import { registerPlugin } from '@capacitor/core';

interface InsecureHsmPlugin {
  exportPrivateKey(options: { alias: string }): Promise<{ privateKeyPem: string }>;
  signPayload(options: { privateKeyPem: string; data: string }): Promise<{ signature: string }>;
}

const InsecureHsm = registerPlugin<InsecureHsmPlugin>('InsecureHsm');

export async function signTransaction(alias: string, payload: string): Promise<string> {
  // VULNERABILITY: Hardware boundary violated. Private key material is extracted
  // into the WebKit JavaScript heap, vulnerable to XSS and bridge inspection.
  const { privateKeyPem } = await InsecureHsm.exportPrivateKey({ alias });
  const { signature } = await InsecureHsm.signPayload({ privateKeyPem, data: payload });
  return signature;
}
```

#### Production Standard (Correct)
> **Standard**: The cryptographic boundary is strictly maintained. The WebKit JS environment only holds an opaque key handle and receives a raw signature generated inside the hardware boundary.
```typescript
import { registerPlugin } from '@capacitor/core';

export interface SecureHsmPlugin {
  getPublicKey(options: { alias: string }): Promise<{ publicKeyDerBase64: string }>;
  signDigest(options: {
    alias: string;
    digestHex: string;
    algorithm: 'ES256' | 'Ed25519';
  }): Promise<{ signatureBase64: string }>;
}

const SecureHsm = registerPlugin<SecureHsmPlugin>('SecureHsm');

export async function signTransactionDigest(alias: string, digestHex: string): Promise<string> {
  // ISOLATION: The private key never leaves the Secure Enclave / Android Keystore.
  // Only the non-sensitive opaque alias and pre-hashed digest cross the WebKit bridge.
  const { signatureBase64 } = await SecureHsm.signDigest({
    alias,
    digestHex,
    algorithm: 'ES256',
  });
  return 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 HSM WebKit Bridge Cryptographic Boundary Isolation

Capacitor 7 HSM WebKit Bridge Cryptographic Boundary Isolation defines an industrial-grade behavioral standard for mobile engineering. Hardware-backed cryptographic keys generated in the iOS Secure Enclave and Android Keystore must never cross the WebKit bridge serialization boundary into the JavaScript runtime. All signing, verification, and key lifecycle operations must be executed natively within isolated Capacitor plugins using opaque key aliases, digest payloads, and zeroed native buffers. 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 raw private key material or seeds across the Capacitor WebKit IPC bridge into JavaScript runtime memory 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 raw private key material or seeds across the Capacitor WebKit IPC bridge into JavaScript runtime memoryCritical
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 design Capacitor plugin methods that serialize, export, or return private key bytes, PEM strings, or seed phrases across the WebKit IPC bridge.

Engineers MUST NEVER design Capacitor plugin methods that serialize, export, or return private key bytes, PEM strings, or seed phrases across the WebKit IPC bridge.

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 ALWAYS restrict WebKit-to-Native bridge communication to opaque key identifiers (aliases), pre-computed message digests, and resulting signatures.

Engineers MUST ALWAYS restrict WebKit-to-Native bridge communication to opaque key identifiers (aliases), pre-computed message digests, and resulting signatures.

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

Native plugins MUST enforce hardware protection

Native plugins MUST enforce hardware protection: iOS keys must use `kSecAttrTokenIDSecureEnclave` and `kSecAccessControlPrivateKeyUsage`; Android keys must use `KeyGenParameterSpec.Builder` with `PURPOSE_SIGN` and `setIsStrongBoxBacked(true)` when available.

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 zero out (overwrite with null bytes) sensitive native byte buffers holding message digests immediately after cryptographic operations conclude.

Services MUST zero out (overwrite with null bytes) sensitive native byte buffers holding message digests immediately after cryptographic operations conclude.

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 private key material, recovery phrases, or raw signing material in WebKit storage tiers (localStorage, IndexedDB, or cookies).

Components NEVER store private key material, recovery phrases, or raw signing material in WebKit storage tiers (localStorage, IndexedDB, or cookies).

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 HSM WebKit Bridge Cryptographic Boundary Isolation critical for AI coding assistants?

Hardware-backed cryptographic keys generated in the iOS Secure Enclave and Android Keystore must never cross the WebKit bridge serialization boundary into the JavaScript runtime. All signing, verification, and key lifecycle operations must be executed natively within isolated Capacitor plugins using opaque key aliases, digest payloads, and zeroed native buffers. 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 raw private key material or seeds across the Capacitor WebKit IPC bridge into JavaScript runtime memory) 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