This specification is maintained by the AgentRules Working Group. Have enhancements or want to claim maintainership?Submit Specification →
mobilecritical PriorityID: capacitor7-secure-enclave-zero-exposure-memory-contract

Capacitor 7 Secure Enclave Zero-Exposure Memory Contract & Bridge Transit

Enforces strict memory zeroization and non-interned byte-buffer transit for hardware-backed decrypted secrets passing between native Swift/Kotlin Secure Enclave/KeyStore and the Capacitor 7 WebView runtime. Prohibits immutable string representations of sensitive cryptographic material across the bridge to prevent plaintexts from persisting in uncompacted native heaps and V8 garbage-collection pools.

Prohibited Anti-Pattern: Leaking Hardware-Backed Secrets into Managed Heaps via Immutable String Bridge Serialization

Export Ready-to-Drop Configuration

Select format below to copy code or download file directly.

---
description: Capacitor 7 Secure Enclave Zero-Exposure Memory Contract & Bridge Transit - Enforces strict memory zeroization and non-interned byte-buffer transit for hardware-backed decrypted secrets passing between native Swift/Kotlin Secure Enclave/KeyStore and the Capacitor 7 WebView runtime. Prohibits immutable string representations of sensitive cryptographic material across the bridge to prevent plaintexts from persisting in uncompacted native heaps and V8 garbage-collection pools.
globs: ios/App/**/*.swift, android/app/**/*.kt, src/**/*.{ts,tsx}
alwaysApply: true
verified_by: "agentrules.org"
license: "CC-BY-4.0"
source: "https://agentrules.org/rules/capacitor7-secure-enclave-zero-exposure-memory-contract"
---

# Capacitor 7 Secure Enclave Zero-Exposure Memory Contract & Bridge Transit

> **Severity**: CRITICAL | **Category**: mobile
> **Anti-Pattern Warning**: Leaking Hardware-Backed Secrets into Managed Heaps via Immutable String Bridge Serialization

## System Constraints
You are a Principal Mobile Security Architect enforcing the Capacitor 7 Secure Enclave Bridge Zero-Exposure Memory Contract. All decrypted cryptographic keys, tokens, and biometric-gated secrets transiting between native platforms (iOS Swift / Android Kotlin) and the JavaScript WebView must never be represented as immutable managed strings. Native allocations must execute deterministic cryptographic wiping (memset_s / zeroize) immediately upon bridge transit, and the TypeScript runtime must operate exclusively via mutable ArrayBuffers that are overwritten with zeros immediately post-consumption.

## Strict Guidelines
- Engineers MUST NEVER instantiate decrypted secrets as Swift `String`, Kotlin `java.lang.String`, or JavaScript primitive `string` variables at any point in the lifecycle.
- Engineers MUST ALWAYS allocate decrypted secrets directly into mutable byte structures (Swift `UnsafeMutablePointer<UInt8>`, Kotlin `ByteBuffer.allocateDirect` / `ByteArray`, and TypeScript `Uint8Array`).
- Native bridge code MUST ALWAYS sanitize and zeroize memory buffers using deterministic functions (`memset_s` on iOS; explicit zero-fills/zeroize on Android) inside `defer` or `finally` blocks.
- Capacitor plugins MUST transfer binary data using Base64-encoded chunked streams or direct ArrayBuffer transport rather than JSON string object payloads.
- TypeScript consumers MUST explicitly scrub decrypted buffers via `cryptoArray.fill(0)` inside a synchronous `finally` block immediately after cryptographic usage.
- Engineers MUST NOT log, serialize to local storage, or retain references to secret byte arrays beyond the immediate scope of the consuming function.
- Plugins MUST configure SecAccessControl flags to require `kSecAccessControlBiometryAny` or `kSecAccessControlPrivateKeyUsage` directly within hardware-backed Secure Enclave/StrongBox.

## Bad vs Good Implementations
### Swift & TypeScript Bridge Memory Zeroing Contract

#### Bad Antipattern (AI Common Hallucination)
> **Why it fails**: Creating native and JavaScript strings interns the secret in managed memory heaps. Garbage collectors on both ends cannot deterministically zero immutable strings, leaving the plaintext vulnerable to Frida dumps, heap inspection, and unauthorized process dumps.
```typescript
// BAD: Decrypting to immutable String in Swift and storing as JavaScript string in WebView
// [Native Swift Capacitor Plugin]
// func getSecret(_ call: CAPPluginCall) {
//   let decryptedData = try! secureEnclave.decrypt(cipherText)
//   let tokenString = String(data: decryptedData, encoding: .utf8)! // Leaked permanently to heap
//   call.resolve(["secret": tokenString])
// }

// [Frontend TypeScript]
export async function authenticateBridge(): Promise<void> {
  const response = await SecureStoragePlugin.getSecret({ alias: 'api_token' });
  const token = response.secret; // Immutable string interned in V8 heap
  await fetch('https://api.internal/v1', {
    headers: { Authorization: `Bearer ${token}` }
  });
  // token cannot be wiped; remains accessible to memory dump forensics
}
```

#### Production Standard (Correct)
> **Standard**: Decrypted secrets reside in native memory strictly within an allocated block protected by `memset_s` in a `defer` scope. In the WebView runtime, bytes are mapped into a mutable `Uint8Array` that is explicitly cleared with zeros inside a `finally` block, ensuring zero exposure to post-execution heap dumps.
```typescript
// GOOD: Ephemeral byte handling with deterministic native memset_s and TS ArrayBuffer wiping
// [Native Swift Capacitor Plugin Contract]
// func getSecret(_ call: CAPPluginCall) {
//   var decryptedBytes = try secureEnclave.decryptRaw(cipherBytes)
//   defer { memset_s(&decryptedBytes, decryptedBytes.count, 0, decryptedBytes.count) }
//   let base64Payload = decryptedBytes.withUnsafeBytes { Data($0).base64EncodedString() }
//   call.resolve(["rawBytesBase64": base64Payload])
// }

// [Frontend TypeScript Contract]
import { SecureStoragePlugin } from './plugins/secure-storage';

export async function executeSecureOperation<T>(
  alias: string,
  consumer: (secretBytes: Uint8Array) => Promise<T>
): Promise<T> {
  const result = await SecureStoragePlugin.getSecret({ alias });
  const binaryString = atob(result.rawBytesBase64);
  const secretBytes = new Uint8Array(binaryString.length);
  
  for (let i = 0; i < binaryString.length; i++) {
    secretBytes[i] = binaryString.charCodeAt(i);
  }

  try {
    return await consumer(secretBytes);
  } finally {
    // Deterministic memory zeroization prevents V8 heap extraction
    secretBytes.fill(0);
  }
}
```

Architectural Specification & Invariant Rationale

Architectural Invariant Design: Capacitor 7 Secure Enclave Zero-Exposure Memory Contract & Bridge Transit

Capacitor 7 Secure Enclave Zero-Exposure Memory Contract & Bridge Transit defines an industrial-grade behavioral standard for mobile engineering. Enforces strict memory zeroization and non-interned byte-buffer transit for hardware-backed decrypted secrets passing between native Swift/Kotlin Secure Enclave/KeyStore and the Capacitor 7 WebView runtime. Prohibits immutable string representations of sensitive cryptographic material across the bridge to prevent plaintexts from persisting in uncompacted native heaps and V8 garbage-collection pools. 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: Leaking Hardware-Backed Secrets into Managed Heaps via Immutable String Bridge Serialization 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 DriftLeaking Hardware-Backed Secrets into Managed Heaps via Immutable String Bridge SerializationCritical
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 instantiate decrypted secrets as Swift `String`, Kotlin `java.lang.String`, or JavaScript primitive `string` variables at any point in the lifecycle.

Engineers MUST NEVER instantiate decrypted secrets as Swift `String`, Kotlin `java.lang.String`, or JavaScript primitive `string` variables at any point in the lifecycle.

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 allocate decrypted secrets directly into mutable byte structures (Swift `UnsafeMutablePointer<UInt8>`, Kotlin `ByteBuffer.allocateDirect` / `ByteArray`, and TypeScript `Uint8Array`).

Engineers MUST ALWAYS allocate decrypted secrets directly into mutable byte structures (Swift `UnsafeMutablePointer<UInt8>`, Kotlin `ByteBuffer.allocateDirect` / `ByteArray`, and TypeScript `Uint8Array`).

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 bridge code MUST ALWAYS sanitize and zeroize memory buffers using deterministic functions (`memset_s` on iOS

Native bridge code MUST ALWAYS sanitize and zeroize memory buffers using deterministic functions (`memset_s` on iOS; explicit zero-fills/zeroize on Android) inside `defer` or `finally` blocks.

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

Capacitor plugins MUST transfer binary data using Base64-encoded chunked streams or direct ArrayBuffer transport rather than JSON string object payloads.

Capacitor plugins MUST transfer binary data using Base64-encoded chunked streams or direct ArrayBuffer transport rather than JSON string object 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

TypeScript consumers MUST explicitly scrub decrypted buffers via `cryptoArray.fill(0)` inside a synchronous `finally` block immediately after cryptographic usage.

TypeScript consumers MUST explicitly scrub decrypted buffers via `cryptoArray.fill(0)` inside a synchronous `finally` block immediately after cryptographic usage.

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

Engineers MUST NOT log, serialize to local storage, or retain references to secret byte arrays beyond the immediate scope of the consuming function.

Engineers MUST NOT log, serialize to local storage, or retain references to secret byte arrays beyond the immediate scope of the consuming function.

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.
7

Plugins MUST configure SecAccessControl flags to require `kSecAccessControlBiometryAny` or `kSecAccessControlPrivateKeyUsage` directly within hardware-backed Secure Enclave/StrongBox.

Plugins MUST configure SecAccessControl flags to require `kSecAccessControlBiometryAny` or `kSecAccessControlPrivateKeyUsage` directly within hardware-backed Secure Enclave/StrongBox.

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 Zero-Exposure Memory Contract & Bridge Transit critical for AI coding assistants?

Enforces strict memory zeroization and non-interned byte-buffer transit for hardware-backed decrypted secrets passing between native Swift/Kotlin Secure Enclave/KeyStore and the Capacitor 7 WebView runtime. Prohibits immutable string representations of sensitive cryptographic material across the bridge to prevent plaintexts from persisting in uncompacted native heaps and V8 garbage-collection pools. 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 (Leaking Hardware-Backed Secrets into Managed Heaps via Immutable String Bridge Serialization) 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