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

Capacitor 7 Hardware-Backed Secure Enclave Session Vault Invariant

Enforces that high-privilege authentication credentials and cryptographic tokens within Capacitor 7 hybrid applications are strictly isolated to platform-native hardware security modules (Apple Secure Enclave and Android StrongBox/TEE). Prohibits persisting session secrets within Chromium or WebKit storage partitions such as localStorage, sessionStorage, or IndexedDB, which are prone to extraction via WebView XSS or unencrypted filesystem inspectability. Mandates transient in-memory handling and hardware-backed biometric authentication gateways for token retrieval.

Prohibited Anti-Pattern: Persisting Session Tokens and Refresh Credentials in WebView Local Storage or Unencrypted Preferences

Export Ready-to-Drop Configuration

Select format below to copy code or download file directly.

---
description: Capacitor 7 Hardware-Backed Secure Enclave Session Vault Invariant - Enforces that high-privilege authentication credentials and cryptographic tokens within Capacitor 7 hybrid applications are strictly isolated to platform-native hardware security modules (Apple Secure Enclave and Android StrongBox/TEE). Prohibits persisting session secrets within Chromium or WebKit storage partitions such as localStorage, sessionStorage, or IndexedDB, which are prone to extraction via WebView XSS or unencrypted filesystem inspectability. Mandates transient in-memory handling and hardware-backed biometric authentication gateways for token retrieval.
globs: src/auth/**/*.{ts,tsx}, src/services/**/*.{ts,tsx}, src/plugins/**/*.{ts,tsx}, src/core/**/*.{ts,tsx}
alwaysApply: true
verified_by: "agentrules.org"
license: "CC-BY-4.0"
source: "https://agentrules.org/rules/capacitor-7-secure-enclave-session-vault-standard"
---

# Capacitor 7 Hardware-Backed Secure Enclave Session Vault Invariant

> **Severity**: CRITICAL | **Category**: mobile
> **Anti-Pattern Warning**: Persisting Session Tokens and Refresh Credentials in WebView Local Storage or Unencrypted Preferences

## System Constraints
You are a Principal Mobile Systems Architect and Security Engineer enforcing strict session isolation in Capacitor 7 applications. You must reject any code pattern that persists authentication tokens, JWTs, refresh tokens, or cryptographic key material inside web runtime storage (localStorage, sessionStorage, IndexedDB, or standard unencrypted cookies). Enforce native bridge integration with platform keystores (iOS Keychain backed by Secure Enclave with kSecAttrAccessibleAfterFirstUnlockThisDeviceOnly / Android Keystore backed by StrongBox Keymaster or TEE). Mandate ephemeral in-memory token states that flush on backgrounding and require biometrics or system passcode unlock for token decrypt operations.

## Strict Guidelines
- Engineers MUST ALWAYS store long-lived credentials (refresh tokens, private keys) exclusively in platform hardware-backed vaults (e.g., @ionic-enterprise/identity-vault or custom Secure Enclave/Keymaster native bridges).
- Engineers MUST NOT write authentication tokens, user credentials, or cryptographic keys to window.localStorage, window.sessionStorage, IndexedDB, or unencrypted SQLite/Preferences partitions.
- Services MUST keep access tokens in ephemeral in-memory state only, requesting them dynamically across the native bridge with hardware authentication checks when expired.
- Code SHOULD register Capacitor App lifecycle listeners (e.g., App.addListener('appStateChange')) to clear in-memory session caches and lock native vaults when the application transitions to the background.
- Components NEVER directly read session credentials from the DOM or expose raw tokens to unmonitored global window variables.

## Bad vs Good Implementations
### Hardware Vault vs. Insecure Web Storage for Hybrid Authentication

#### Bad Antipattern (AI Common Hallucination)
> **Why it fails**: Storing access tokens in localStorage exposes them to arbitrary DOM access and cross-site scripting (XSS) within the WebView. Using Capacitor Preferences without native hardware encryption writes refresh tokens directly to plaintext XML/plist files in the application sandbox, allowing extraction via backup analysis or rooted/jailbroken devices.
```typescript
import { Preferences } from '@capacitor/preferences';

interface Session {
  accessToken: string;
  refreshToken: string;
}

export class AuthService {
  // VULNERABLE: Stores high-privilege tokens in unencrypted web storage or plain SharedPreferences
  async persistSession(session: Session): Promise<void> {
    localStorage.setItem('access_token', session.accessToken);
    await Preferences.set({
      key: 'refresh_token',
      value: session.refreshToken,
    });
  }

  async getAccessToken(): Promise<string | null> {
    return localStorage.getItem('access_token');
  }
}
```

#### Production Standard (Correct)
> **Standard**: Delegates persistence entirely to hardware security modules (Apple Secure Enclave / Android StrongBox TEE) via native biometric gating. The ephemeral access token is never written to disk, and the background state listener purges in-memory secrets when the app is minimized, preventing memory dump extractions.
```typescript
import { App } from '@capacitor/app';
import {
  Vault,
  DeviceSecurityType,
  VaultType,
  BrowserVault,
} from '@ionic-enterprise/identity-vault';
import { Capacitor } from '@capacitor/core';

interface SessionSecrets {
  refreshToken: string;
}

export class SecureSessionVault {
  private static instance: SecureSessionVault;
  private vault: Vault | BrowserVault;
  private ephemeralAccessToken: string | null = null;

  private constructor() {
    const config = {
      key: 'io.enterprise.securevault.auth',
      type: VaultType.DeviceSecurity,
      deviceSecurityType: DeviceSecurityType.Biometrics,
      lockAfterBackgrounded: 2000,
      shouldClearVaultAfterTooManyFailedAttempts: true,
      customPasscodeInvalidUnlockAttempts: 3,
      unlockVaultOnLoad: false,
    };

    this.vault = Capacitor.isNativePlatform()
      ? new Vault(config)
      : new BrowserVault(); // For fallback development environments only

    this.initLifecycleProtection();
  }

  public static getInstance(): SecureSessionVault {
    if (!SecureSessionVault.instance) {
      SecureSessionVault.instance = new SecureSessionVault();
    }
    return SecureSessionVault.instance;
  }

  private initLifecycleProtection(): void {
    if (Capacitor.isNativePlatform()) {
      App.addListener('appStateChange', ({ isActive }) => {
        if (!isActive) {
          this.purgeVolatileMemory();
        }
      });
    }
  }

  public async storeRefreshToken(refreshToken: string): Promise<void> {
    await this.vault.setValue('refreshToken', refreshToken);
  }

  public async retrieveRefreshToken(): Promise<string | null> {
    if (await this.vault.isLocked()) {
      await this.vault.unlock();
    }
    return this.vault.getValue('refreshToken');
  }

  public setEphemeralAccessToken(token: string): void {
    this.ephemeralAccessToken = token;
  }

  public getEphemeralAccessToken(): string | null {
    return this.ephemeralAccessToken;
  }

  public purgeVolatileMemory(): void {
    this.ephemeralAccessToken = null;
  }

  public async clearSession(): Promise<void> {
    this.purgeVolatileMemory();
    await this.vault.clear();
  }
}
```

Architectural Specification & Invariant Rationale

Architectural Invariant Design: Capacitor 7 Hardware-Backed Secure Enclave Session Vault Invariant

Capacitor 7 Hardware-Backed Secure Enclave Session Vault Invariant defines an industrial-grade behavioral standard for mobile engineering. Enforces that high-privilege authentication credentials and cryptographic tokens within Capacitor 7 hybrid applications are strictly isolated to platform-native hardware security modules (Apple Secure Enclave and Android StrongBox/TEE). Prohibits persisting session secrets within Chromium or WebKit storage partitions such as localStorage, sessionStorage, or IndexedDB, which are prone to extraction via WebView XSS or unencrypted filesystem inspectability. Mandates transient in-memory handling and hardware-backed biometric authentication gateways for token retrieval. 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 Session Tokens and Refresh Credentials in WebView Local Storage or Unencrypted Preferences 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 Session Tokens and Refresh Credentials in WebView Local Storage or Unencrypted PreferencesCritical
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 store long-lived credentials (refresh tokens, private keys) exclusively in platform hardware-backed vaults (e.g., @ionic-enterprise/identity-vault or custom Secure Enclave/Keymaster native bridges).

Engineers MUST ALWAYS store long-lived credentials (refresh tokens, private keys) exclusively in platform hardware-backed vaults (e.g., @ionic-enterprise/identity-vault or custom Secure Enclave/Keymaster native bridges).

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 write authentication tokens, user credentials, or cryptographic keys to window.localStorage, window.sessionStorage, IndexedDB, or unencrypted SQLite/Preferences partitions.

Engineers MUST NOT write authentication tokens, user credentials, or cryptographic keys to window.localStorage, window.sessionStorage, IndexedDB, or unencrypted SQLite/Preferences partitions.

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

Services MUST keep access tokens in ephemeral in-memory state only, requesting them dynamically across the native bridge with hardware authentication checks when expired.

Services MUST keep access tokens in ephemeral in-memory state only, requesting them dynamically across the native bridge with hardware authentication checks when expired.

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

Code SHOULD register Capacitor App lifecycle listeners (e.g., App.addListener('appStateChange')) to clear in-memory session caches and lock native vaults when the application transitions to the background.

Code SHOULD register Capacitor App lifecycle listeners (e.g., App.addListener('appStateChange')) to clear in-memory session caches and lock native vaults when the application transitions to the background.

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 directly read session credentials from the DOM or expose raw tokens to unmonitored global window variables.

Components NEVER directly read session credentials from the DOM or expose raw tokens to unmonitored global window 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 Hardware-Backed Secure Enclave Session Vault Invariant critical for AI coding assistants?

Enforces that high-privilege authentication credentials and cryptographic tokens within Capacitor 7 hybrid applications are strictly isolated to platform-native hardware security modules (Apple Secure Enclave and Android StrongBox/TEE). Prohibits persisting session secrets within Chromium or WebKit storage partitions such as localStorage, sessionStorage, or IndexedDB, which are prone to extraction via WebView XSS or unencrypted filesystem inspectability. Mandates transient in-memory handling and hardware-backed biometric authentication gateways for token retrieval. 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 Session Tokens and Refresh Credentials in WebView Local Storage or Unencrypted Preferences) 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