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

Capacitor 7 Hardware-Backed Secure Enclave Ephemeral Storage Invariant

Enforces strict hardware-backed cryptographic key isolation (iOS Secure Enclave via Keychain Access Controls and Android 15 StrongBox Keymaster) for Capacitor 7 hybrid applications. Mandates zero-retention memory scrubbing of raw session secrets in the JavaScript runtime and explicit ephemeral native lifecycle disposal to thwart runtime inspection on rooted Android 15 or jailbroken iOS 18 environments.

Prohibited Anti-Pattern: Persisting Unencrypted or Software-Backed Session Tokens in WebView LocalStorage, Native Preferences, or Unscrubbed JS Heap

Export Ready-to-Drop Configuration

Select format below to copy code or download file directly.

---
description: Capacitor 7 Hardware-Backed Secure Enclave Ephemeral Storage Invariant - Enforces strict hardware-backed cryptographic key isolation (iOS Secure Enclave via Keychain Access Controls and Android 15 StrongBox Keymaster) for Capacitor 7 hybrid applications. Mandates zero-retention memory scrubbing of raw session secrets in the JavaScript runtime and explicit ephemeral native lifecycle disposal to thwart runtime inspection on rooted Android 15 or jailbroken iOS 18 environments.
globs: src/**/*.{ts,tsx}, ios/App/App/**/*.{swift,m,h}, android/app/src/main/**/*.{java,kt}
alwaysApply: true
verified_by: "agentrules.org"
license: "CC-BY-4.0"
source: "https://agentrules.org/rules/capacitor-7-hardware-secure-enclave-ephemeral-storage-invariant"
---

# Capacitor 7 Hardware-Backed Secure Enclave Ephemeral Storage Invariant

> **Severity**: CRITICAL | **Category**: mobile
> **Anti-Pattern Warning**: Persisting Unencrypted or Software-Backed Session Tokens in WebView LocalStorage, Native Preferences, or Unscrubbed JS Heap

## System Constraints
You are a Principal Mobile Security Architect enforcing zero-retention ephemeral memory invariants and hardware-backed cryptographic storage across Capacitor 7 hybrid applications targeting iOS 18 and Android 15. You must reject any code storing authentication tokens, private keys, or session credentials in non-hardware-backed storage engines, such as localStorage, IndexedDB, raw Capacitor Preferences, or unencrypted native SharedPreferences. Mandate that cryptographic primitives leverage iOS Secure Enclave (kSecAccessControlPrivateKeyUsage with Biometry/Passcode fallback) and Android StrongBox KeyStore (`PURPOSE_SIGN` / `PURPOSE_DECRYPT` inside isolated hardware). Enforce explicit byte-array zeroization (overwriting memory with zeroes) immediately after token consumption to mitigate heap dump exfiltration on compromised runtimes.

## Strict Guidelines
- Engineers MUST ALWAYS enforce hardware-backed cryptographic keystores (iOS Secure Enclave kSecAttrAccessibleAfterFirstUnlockThisDeviceOnly or kSecAccessControlUserPresence; Android StrongBox KeyStore via setIsStrongBoxBacked(true)).
- Engineers MUST NOT store raw bearer tokens or symmetric master secrets inside web-layer storage APIs (window.localStorage, sessionStorage, IndexedDB, or Capacitor Preferences default stores).
- Code MUST explicitly scrub mutable Uint8Array buffers containing raw cryptographic secrets or authorization headers using crypto.getRandomValues() or zeroization loops (.fill(0)) immediately after use.
- Services MUST route all token-requiring network mutations through a native bridge plugin where the secret never crosses the JavaScript-Native boundary unencrypted or remains in memory outside active dispatch.
- Components NEVER preserve session credentials in JavaScript heap closures, state management containers (e.g., Redux, Pinia, Zustand), or unmanaged GC-dependent string allocations across navigational lifecycles.

## Bad vs Good Implementations
### Hardware-Backed Ephemeral Session Key Lifecycle vs. Insecure Storage

#### Bad Antipattern (AI Common Hallucination)
> **Why it fails**: Stores secrets in standard non-hardware-backed preferences accessible via filesystem extraction on rooted devices, leaves persistent immutable String primitives in the V8/JavaScriptCore garbage collector heap, and fails to invoke StrongBox or Secure Enclave hardware access controls.
```typescript
import { Preferences } from '@capacitor/preferences';

// ANTI-PATTERN: Persisting raw session tokens in cleartext SharedPreferences/UserDefaults
// and retaining token strings permanently in JS heap memory.
export class InsecureSessionService {
  private token: string | null = null;

  async saveSession(bearerToken: string): Promise<void> {
    this.token = bearerToken;
    // Leaks to plaintext native storage, vulnerable to Android 15/iOS 18 backup extraction
    await Preferences.set({
      key: 'auth_token',
      value: bearerToken
    });
  }

  async getSession(): Promise<string | null> {
    if (this.token) return this.token;
    const { value } = await Preferences.get({ key: 'auth_token' });
    this.token = value;
    return this.token;
  }
}
```

#### Production Standard (Correct)
> **Standard**: Transfers transient byte credentials directly to native hardware isolation without caching immutable strings in the JavaScript heap, and enforces proactive memory wiping using .fill(0) within a finally block to eliminate dumpable memory artifacts.
```typescript
import { registerPlugin } from '@capacitor/core';

interface SecureEnclavePlugin {
  signChallenge(options: { alias: string; challengeBase64: string }): Promise<{ signatureBase64: string }>;
  storeEphemeralSecret(options: { alias: string; secretBase64: string }): Promise<void>;
  clearSecureStorage(options: { alias: string }): Promise<void>;
}

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

export class EphemeralSessionVault {
  private static readonly KEY_ALIAS = 'sec_session_token_hw';

  /**
   * Receives transient secret bytes, bridges immediately to native Secure Enclave/StrongBox,
   * and performs explicit zero-retention wiping on the source byte buffer.
   */
  public static async securelyStoreAndZeroize(secretBytes: Uint8Array): Promise<void> {
    let encoded = '';
    try {
      const binaryString = String.fromCharCode(...secretBytes);
      encoded = btoa(binaryString);
      
      await NativeSecureVault.storeEphemeralSecret({
        alias: this.KEY_ALIAS,
        secretBase64: encoded
      });
    } finally {
      // Mandatory invariant: Overwrite raw memory buffers immediately
      secretBytes.fill(0);
      // Overwrite temporary conversion buffer if created
      crypto.getRandomValues(secretBytes);
      secretBytes.fill(0);
    }
  }

  public static async terminateSession(): Promise<void> {
    await NativeSecureVault.clearSecureStorage({ alias: this.KEY_ALIAS });
  }
}
```

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-Backed Secure Enclave Ephemeral Storage Invariant

Capacitor 7 Hardware-Backed Secure Enclave Ephemeral Storage Invariant defines an industrial-grade behavioral standard for mobile engineering. Enforces strict hardware-backed cryptographic key isolation (iOS Secure Enclave via Keychain Access Controls and Android 15 StrongBox Keymaster) for Capacitor 7 hybrid applications. Mandates zero-retention memory scrubbing of raw session secrets in the JavaScript runtime and explicit ephemeral native lifecycle disposal to thwart runtime inspection on rooted Android 15 or jailbroken iOS 18 environments. 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: Persisting Unencrypted or Software-Backed Session Tokens in WebView LocalStorage, Native Preferences, or Unscrubbed JS 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 DriftPersisting Unencrypted or Software-Backed Session Tokens in WebView LocalStorage, Native Preferences, or Unscrubbed JS 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 enforce hardware-backed cryptographic keystores (iOS Secure Enclave kSecAttrAccessibleAfterFirstUnlockThisDeviceOnly or kSecAccessControlUserPresence

Engineers MUST ALWAYS enforce hardware-backed cryptographic keystores (iOS Secure Enclave kSecAttrAccessibleAfterFirstUnlockThisDeviceOnly or kSecAccessControlUserPresence; Android StrongBox KeyStore via setIsStrongBoxBacked(true)).

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 store raw bearer tokens or symmetric master secrets inside web-layer storage APIs (window.localStorage, sessionStorage, IndexedDB, or Capacitor Preferences default stores).

Engineers MUST NOT store raw bearer tokens or symmetric master secrets inside web-layer storage APIs (window.localStorage, sessionStorage, IndexedDB, or Capacitor Preferences default stores).

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 MUST explicitly scrub mutable Uint8Array buffers containing raw cryptographic secrets or authorization headers using crypto.getRandomValues() or zeroization loops (.fill(0)) immediately after use.

Code MUST explicitly scrub mutable Uint8Array buffers containing raw cryptographic secrets or authorization headers using crypto.getRandomValues() or zeroization loops (.fill(0)) immediately after use.

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 route all token-requiring network mutations through a native bridge plugin where the secret never crosses the JavaScript-Native boundary unencrypted or remains in memory outside active dispatch.

Services MUST route all token-requiring network mutations through a native bridge plugin where the secret never crosses the JavaScript-Native boundary unencrypted or remains in memory outside active dispatch.

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 preserve session credentials in JavaScript heap closures, state management containers (e.g., Redux, Pinia, Zustand), or unmanaged GC-dependent string allocations across navigational lifecycles.

Components NEVER preserve session credentials in JavaScript heap closures, state management containers (e.g., Redux, Pinia, Zustand), or unmanaged GC-dependent string allocations across navigational lifecycles.

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-Backed Secure Enclave Ephemeral Storage Invariant critical for AI coding assistants?

Enforces strict hardware-backed cryptographic key isolation (iOS Secure Enclave via Keychain Access Controls and Android 15 StrongBox Keymaster) for Capacitor 7 hybrid applications. Mandates zero-retention memory scrubbing of raw session secrets in the JavaScript runtime and explicit ephemeral native lifecycle disposal to thwart runtime inspection on rooted Android 15 or jailbroken iOS 18 environments. 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 (Persisting Unencrypted or Software-Backed Session Tokens in WebView LocalStorage, Native Preferences, or Unscrubbed JS 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