This specification is maintained by the AgentRules Working Group. Have enhancements or want to claim maintainership?Submit Specification →
mobilecritical PriorityID: capacitor7-wkwebview-partition-keychain-sync

Capacitor 7 WKWebView Partitioned Storage & Keychain Sync Invariant

Enforces hardware-backed Secure Enclave (iOS Keychain / Android KeyStore) persistence for sensitive credentials to bypass WebKit partitioned storage evictions. WebKit storage APIs (localStorage, IndexedDB) are subject to iOS ITP, low-memory purge, and OS upgrades, requiring credentials to be held in an isolated native enclave and synced ephemerally to memory.

Prohibited Anti-Pattern: Persisting Sensitive Auth Tokens in WebKit LocalStorage or Plaintext IndexedDB Subject to iOS Cache Eviction and Sandbox Leaks

Export Ready-to-Drop Configuration

Select format below to copy code or download file directly.

---
description: Capacitor 7 WKWebView Partitioned Storage & Keychain Sync Invariant - Enforces hardware-backed Secure Enclave (iOS Keychain / Android KeyStore) persistence for sensitive credentials to bypass WebKit partitioned storage evictions. WebKit storage APIs (localStorage, IndexedDB) are subject to iOS ITP, low-memory purge, and OS upgrades, requiring credentials to be held in an isolated native enclave and synced ephemerally to memory.
globs: src/**/*.{ts,tsx}, ios/App/**/*.{swift,m}
alwaysApply: true
verified_by: "agentrules.org"
license: "CC-BY-4.0"
source: "https://agentrules.org/rules/capacitor7-wkwebview-partition-keychain-sync"
---

# Capacitor 7 WKWebView Partitioned Storage & Keychain Sync Invariant

> **Severity**: CRITICAL | **Category**: mobile
> **Anti-Pattern Warning**: Persisting Sensitive Auth Tokens in WebKit LocalStorage or Plaintext IndexedDB Subject to iOS Cache Eviction and Sandbox Leaks

## System Constraints
You are a Principal Mobile Architect enforcing the Capacitor 7 WKWebView Partitioned Storage & Keychain Sync Invariant. You must guarantee that no authentication credentials, session tokens, or cryptographic keys are persisted in WebKit-managed client-side storage layers (localStorage, sessionStorage, unencrypted IndexedDB) due to iOS 17/18 WebKit storage partitioning and arbitrary OS cache evictions. Mandate hardware-backed Secure Enclave (Keychain) storage for persistence and strictly managed ephemeral in-memory references for runtime access.

## Strict Guidelines
- Engineers MUST NEVER persist sensitive session tokens (access tokens, refresh tokens, API keys) in `window.localStorage`, `window.sessionStorage`, or standard WebKit `indexedDB`.
- Engineers MUST use hardware-backed native Keychain bindings (e.g., SecureStoragePlugin configured with `kSecAttrAccessibleAfterFirstUnlockThisDeviceOnly`) when running on native Capacitor platforms.
- Engineers MUST maintain an ephemeral in-memory cache for API authorization headers, populated strictly on app bootstrap or after biometric re-authentication from the native Keychain.
- Engineers MUST flush in-memory authentication states immediately upon receiving Capacitor `appStateChange` background events or explicit sign-out triggers.
- Services MUST implement automatic fallback or synchronization boundaries that detect when the WKWebView process terminates (`WebContentProcessDidTerminate`) and securely re-hydrate credentials from the native bridge without unencrypted disk writes.
- HTTP interceptors MUST read access tokens directly from the in-memory secure vault singleton, never querying web storage APIs.

## Bad vs Good Implementations
### Token Storage and Retrieval via Web Storage vs. Secure Enclave Bridge

#### Bad Antipattern (AI Common Hallucination)
> **Why it fails**: Persisting session secrets to `localStorage` or default `Preferences` (UserDefaults) exposes credentials to arbitrary WebKit cache purges during low-memory conditions and leaves sensitive tokens unencrypted on the filesystem without Secure Enclave protection.
```typescript
import { Preferences } from '@capacitor/preferences';

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

// ANTI-PATTERN: Relying on WebKit localStorage or unencrypted Capacitor Preferences
// for critical auth tokens subject to WKWebView eviction and unencrypted disk serialization.
export class AuthService {
  public async persistSession(session: Session): Promise<void> {
    // Vulnerable: localStorage is evicted under iOS memory pressure / ITP partitions
    window.localStorage.setItem('access_token', session.accessToken);
    
    // Vulnerable: Preferences on iOS uses unencrypted UserDefaults by default
    await Preferences.set({
      key: 'refresh_token',
      value: session.refreshToken,
    });
  }

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

#### Production Standard (Correct)
> **Standard**: Access tokens remain exclusively in volatile runtime memory, completely bypassing WebKit disk partitions. Refresh tokens are delegated to native hardware-backed Secure Enclave storage, preventing silent user session drops caused by iOS storage eviction policies.
```typescript
import { Capacitor } from '@capacitor/core';
import { SecureStoragePlugin } from 'capacitor-secure-storage-plugin';

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

// PRODUCTION FIX: Isolate secrets to Secure Enclave / Keychain with ephemeral memory cache
export class SecureSessionVault {
  private static instance: SecureSessionVault;
  private inMemoryAccessToken: string | null = null;

  private constructor() {}

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

  public async storeSession(session: Session): Promise<void> {
    // Maintain access token solely in volatile memory
    this.inMemoryAccessToken = session.accessToken;

    if (Capacitor.isNativePlatform()) {
      // Securely seal refresh token inside native hardware Keychain / Keystore
      await SecureStoragePlugin.set({
        key: 'auth_refresh_token',
        value: session.refreshToken,
      });
    } else {
      // Fallback for secure context web development only (e.g., in-memory or HttpOnly cookies)
      sessionStorage.setItem('ephemeral_dev_refresh', session.refreshToken);
    }
  }

  public async getAccessToken(): Promise<string | null> {
    return this.inMemoryAccessToken;
  }

  public async getRefreshToken(): Promise<string | null> {
    if (Capacitor.isNativePlatform()) {
      try {
        const { value } = await SecureStoragePlugin.get({ key: 'auth_refresh_token' });
        return value;
      } catch {
        return null;
      }
    }
    return sessionStorage.getItem('ephemeral_dev_refresh');
  }

  public async clear(): Promise<void> {
    this.inMemoryAccessToken = null;
    if (Capacitor.isNativePlatform()) {
      await SecureStoragePlugin.remove({ key: 'auth_refresh_token' }).catch(() => {});
    } else {
      sessionStorage.clear();
    }
  }
}
```

Recommended MCP Servers (mcp-serverlist.com)

Equip agent with system tools to verify code for this stack.

Architectural Specification & Invariant Rationale

Architectural Invariant Design: Capacitor 7 WKWebView Partitioned Storage & Keychain Sync Invariant

Capacitor 7 WKWebView Partitioned Storage & Keychain Sync Invariant defines an industrial-grade behavioral standard for mobile engineering. Enforces hardware-backed Secure Enclave (iOS Keychain / Android KeyStore) persistence for sensitive credentials to bypass WebKit partitioned storage evictions. WebKit storage APIs (localStorage, IndexedDB) are subject to iOS ITP, low-memory purge, and OS upgrades, requiring credentials to be held in an isolated native enclave and synced ephemerally to memory. 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 Sensitive Auth Tokens in WebKit LocalStorage or Plaintext IndexedDB Subject to iOS Cache Eviction and Sandbox Leaks 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 Sensitive Auth Tokens in WebKit LocalStorage or Plaintext IndexedDB Subject to iOS Cache Eviction and Sandbox LeaksCritical
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 persist sensitive session tokens (access tokens, refresh tokens, API keys) in `window.localStorage`, `window.sessionStorage`, or standard WebKit `indexedDB`.

Engineers MUST NEVER persist sensitive session tokens (access tokens, refresh tokens, API keys) in `window.localStorage`, `window.sessionStorage`, or standard WebKit `indexedDB`.

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 use hardware-backed native Keychain bindings (e.g., SecureStoragePlugin configured with `kSecAttrAccessibleAfterFirstUnlockThisDeviceOnly`) when running on native Capacitor platforms.

Engineers MUST use hardware-backed native Keychain bindings (e.g., SecureStoragePlugin configured with `kSecAttrAccessibleAfterFirstUnlockThisDeviceOnly`) when running on native Capacitor platforms.

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

Engineers MUST maintain an ephemeral in-memory cache for API authorization headers, populated strictly on app bootstrap or after biometric re-authentication from the native Keychain.

Engineers MUST maintain an ephemeral in-memory cache for API authorization headers, populated strictly on app bootstrap or after biometric re-authentication from the native Keychain.

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

Engineers MUST flush in-memory authentication states immediately upon receiving Capacitor `appStateChange` background events or explicit sign-out triggers.

Engineers MUST flush in-memory authentication states immediately upon receiving Capacitor `appStateChange` background events or explicit sign-out triggers.

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

Services MUST implement automatic fallback or synchronization boundaries that detect when the WKWebView process terminates (`WebContentProcessDidTerminate`) and securely re-hydrate credentials from the native bridge without unencrypted disk writes.

Services MUST implement automatic fallback or synchronization boundaries that detect when the WKWebView process terminates (`WebContentProcessDidTerminate`) and securely re-hydrate credentials from the native bridge without unencrypted disk writes.

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

HTTP interceptors MUST read access tokens directly from the in-memory secure vault singleton, never querying web storage APIs.

HTTP interceptors MUST read access tokens directly from the in-memory secure vault singleton, never querying web storage APIs.

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 WKWebView Partitioned Storage & Keychain Sync Invariant critical for AI coding assistants?

Enforces hardware-backed Secure Enclave (iOS Keychain / Android KeyStore) persistence for sensitive credentials to bypass WebKit partitioned storage evictions. WebKit storage APIs (localStorage, IndexedDB) are subject to iOS ITP, low-memory purge, and OS upgrades, requiring credentials to be held in an isolated native enclave and synced ephemerally to memory. 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 Sensitive Auth Tokens in WebKit LocalStorage or Plaintext IndexedDB Subject to iOS Cache Eviction and Sandbox Leaks) 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