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

Capacitor 7 Biometric Keychain Partitioning & Ephemeral Session Boundary Standard

Mandates isolating authentication credentials to native hardware enclaves (iOS Keychain / Android KeyStore) across Capacitor 7 native-web bridges. Enforces an ephemeral, in-memory-only session model within the WebView runtime, guaranteeing credentials survive OS webview sandbox purges without ever persisting secrets in insecure web storage.

Prohibited Anti-Pattern: Persisting Sensitive Session Credentials into Unencrypted Web Storage or Misconfiguring Biometric Enclave Partitioning in Hybrid WebViews

Export Ready-to-Drop Configuration

Select format below to copy code or download file directly.

---
description: Capacitor 7 Biometric Keychain Partitioning & Ephemeral Session Boundary Standard - Mandates isolating authentication credentials to native hardware enclaves (iOS Keychain / Android KeyStore) across Capacitor 7 native-web bridges. Enforces an ephemeral, in-memory-only session model within the WebView runtime, guaranteeing credentials survive OS webview sandbox purges without ever persisting secrets in insecure web storage.
globs: src/**/*.{ts,tsx}, ios/**/*.{swift,m}, android/**/*.{java,kt}
alwaysApply: true
verified_by: "agentrules.org"
license: "CC-BY-4.0"
source: "https://agentrules.org/rules/capacitor-7-biometric-keychain-session-sync"
---

# Capacitor 7 Biometric Keychain Partitioning & Ephemeral Session Boundary Standard

> **Severity**: CRITICAL | **Category**: mobile
> **Anti-Pattern Warning**: Persisting Sensitive Session Credentials into Unencrypted Web Storage or Misconfiguring Biometric Enclave Partitioning in Hybrid WebViews

## System Constraints
You are a Principal Mobile Architect enforcing strict security boundaries for Capacitor 7 hybrid applications. WebViews are inherently volatile and vulnerable to both OS sandbox cache-evictions and XSS-based storage exfiltration. You must enforce that all persistent credentials live strictly within native hardware enclaves (iOS Keychain with kSecAccessControl, Android KeyStore with EncryptedSharedPreferences). In-memory JavaScript runtimes must treat authentication state as strictly ephemeral, rehydrating exclusively via authenticated native bridges upon app launch, foreground transitions, or WebView process termination.

## Strict Guidelines
- Engineers MUST NEVER write authentication tokens, refresh tokens, or cryptography keys to window.localStorage, window.sessionStorage, or standard IndexedDB.
- Engineers MUST store persistent session secrets exclusively through native Keychain/KeyStore plugins configured with hardware-backed biometric access controls (e.g., kSecAccessControlBiometryCurrentSet or Android BiometricPrompt with KeyGenParameterSpec userAuthenticationRequired).
- Services MUST isolate the WebView token runtime to volatile memory (in-memory closures or reactive state machines) that explicitly clears on foreground resignation or inactivity timeouts.
- Engineers MUST handle App lifecycle resume events (Capacitor App.addListener('appStateChange')) by verifying biometrics and rehydrating the in-memory token cache rather than reading from disk.
- Keychain entries MUST use unique, partitioned service identifiers and access groups (e.g., kSecAttrService / kSecAttrAccessGroup) to prevent namespace collisions or cross-app leaks across app suites.
- Code MUST handle OS-level webview sandbox resets and WKWebView/Android WebView process terminations gracefully by re-triggering the native biometric unlock boundary rather than redirecting to full unauthenticated logouts.

## Bad vs Good Implementations
### Biometric Keychain Partition and In-Memory Token Manager

#### Bad Antipattern (AI Common Hallucination)
> **Why it fails**: Writing tokens to localStorage exposes credentials to XSS vectors and unencrypted web storage. Falling back to default Capacitor Preferences stores credentials in plaintext NSUserDefaults/SharedPreferences without hardware-backed biometric gating, leaving tokens vulnerable to backup extraction and sandbox purges.
```typescript
import { Preferences } from '@capacitor/preferences';

// VULNERABLE: Persists sensitive access & refresh tokens to Web Storage / unencrypted SharedPreferences
export class InsecureSessionManager {
  async saveSession(tokens: { accessToken: string; refreshToken: string }): Promise<void> {
    // Vulnerable to XSS token theft and OS sandbox data wipes
    localStorage.setItem('access_token', tokens.accessToken);
    
    // Capacitor Preferences uses unencrypted NSUserDefaults / SharedPreferences by default
    await Preferences.set({
      key: 'refresh_token',
      value: tokens.refreshToken,
    });
  }

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

#### Production Standard (Correct)
> **Standard**: This architecture partitions persistence entirely to the native hardware enclave (iOS Keychain / Android KeyStore) protected by biometric gates (biometryCurrentSet). The WebView runtime holds tokens strictly in ephemeral memory (RAM), auto-purges them when backgrounded, and transparently rehydrates via biometric challenge, ensuring immunity against XSS storage scraping and OS webview cache purges.
```typescript
import { App } from '@capacitor/app';
import { BiometricAuth, BiometryType } from '@aparajita/capacitor-biometric-auth';
import { NativeBiometricVault } from '@/services/native-vault';

export interface SessionTokens {
  accessToken: string;
  expiresAt: number;
}

export class SecureBiometricSessionManager {
  private static instance: SecureBiometricSessionManager;
  // EPHEMERAL ONLY: Access token resides in RAM; never written to WebView storage
  private ephemeralToken: string | null = null;
  private tokenExpiration: number = 0;
  private isAuthenticating: boolean = false;

  private readonly KEYCHAIN_SERVICE = 'com.enterprise.app.secure.session';
  private readonly REFRESH_KEY = 'biometric_refresh_token';

  private constructor() {
    this.registerLifecycleHooks();
  }

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

  private registerLifecycleHooks(): void {
    // Wipe ephemeral memory on backgrounding to enforce biometric unlock on resume
    App.addListener('appStateChange', ({ isActive }) => {
      if (!isActive) {
        this.purgeEphemeralState();
      }
    });
  }

  public purgeEphemeralState(): void {
    this.ephemeralToken = null;
    this.tokenExpiration = 0;
  }

  public async storeRefreshToken(refreshToken: string): Promise<void> {
    const biometry = await BiometricAuth.checkBiometry();
    if (!biometry.isAvailable) {
      throw new Error('Biometric hardware enclave unavailable');
    }

    // Persist securely to Hardware-Backed Keychain / Android KeyStore
    await NativeBiometricVault.setSecureItem({
      service: this.KEYCHAIN_SERVICE,
      key: this.REFRESH_KEY,
      value: refreshToken,
      accessControl: 'biometryCurrentSet', // Invalidates if fingerprints/FaceID are modified
      accessibility: 'afterFirstUnlockThisDeviceOnly',
    });
  }

  public async getValidAccessToken(): Promise<string> {
    const now = Date.now();
    if (this.ephemeralToken && this.tokenExpiration > now + 30_000) {
      return this.ephemeralToken;
    }

    return this.rehydrateSessionThroughBiometrics();
  }

  private async rehydrateSessionThroughBiometrics(): Promise<string> {
    if (this.isAuthenticating) {
      throw new Error('Biometric rehydration already in progress');
    }
    this.isAuthenticating = true;

    try {
      await BiometricAuth.authenticate({
        reason: 'Unlock your secure session',
        cancelTitle: 'Cancel',
        allowDeviceCredential: false,
      });

      const refreshToken = await NativeBiometricVault.getSecureItem({
        service: this.KEYCHAIN_SERVICE,
        key: this.REFRESH_KEY,
      });

      if (!refreshToken) {
        throw new Error('No persistent session found');
      }

      // Exchange refresh token for fresh short-lived access token
      const newTokens = await this.performTokenExchange(refreshToken);
      this.ephemeralToken = newTokens.accessToken;
      this.tokenExpiration = newTokens.expiresAt;

      return this.ephemeralToken;
    } finally {
      this.isAuthenticating = false;
    }
  }

  private async performTokenExchange(refreshToken: string): Promise<SessionTokens> {
    // Ephemeral network exchange: returns tokens directly to native memory boundary
    const response = await fetch('https://api.enterprise.com/auth/refresh', {
      method: 'POST',
      headers: { 'Content-Type': 'application/json' },
      body: JSON.stringify({ refreshToken }),
    });

    if (!response.ok) {
      throw new Error('Failed to refresh authentication token');
    }

    return response.json();
  }
}
```

Architectural Specification & Invariant Rationale

Architectural Invariant Design: Capacitor 7 Biometric Keychain Partitioning & Ephemeral Session Boundary Standard

Capacitor 7 Biometric Keychain Partitioning & Ephemeral Session Boundary Standard defines an industrial-grade behavioral standard for mobile engineering. Mandates isolating authentication credentials to native hardware enclaves (iOS Keychain / Android KeyStore) across Capacitor 7 native-web bridges. Enforces an ephemeral, in-memory-only session model within the WebView runtime, guaranteeing credentials survive OS webview sandbox purges without ever persisting secrets in insecure web storage. 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 Session Credentials into Unencrypted Web Storage or Misconfiguring Biometric Enclave Partitioning in Hybrid WebViews 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 Session Credentials into Unencrypted Web Storage or Misconfiguring Biometric Enclave Partitioning in Hybrid WebViewsCritical
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 write authentication tokens, refresh tokens, or cryptography keys to window.localStorage, window.sessionStorage, or standard IndexedDB.

Engineers MUST NEVER write authentication tokens, refresh tokens, or cryptography keys to window.localStorage, window.sessionStorage, or standard 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 store persistent session secrets exclusively through native Keychain/KeyStore plugins configured with hardware-backed biometric access controls (e.g., kSecAccessControlBiometryCurrentSet or Android BiometricPrompt with KeyGenParameterSpec userAuthenticationRequired).

Engineers MUST store persistent session secrets exclusively through native Keychain/KeyStore plugins configured with hardware-backed biometric access controls (e.g., kSecAccessControlBiometryCurrentSet or Android BiometricPrompt with KeyGenParameterSpec userAuthenticationRequired).

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 isolate the WebView token runtime to volatile memory (in-memory closures or reactive state machines) that explicitly clears on foreground resignation or inactivity timeouts.

Services MUST isolate the WebView token runtime to volatile memory (in-memory closures or reactive state machines) that explicitly clears on foreground resignation or inactivity timeouts.

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 handle App lifecycle resume events (Capacitor App.addListener('appStateChange')) by verifying biometrics and rehydrating the in-memory token cache rather than reading from disk.

Engineers MUST handle App lifecycle resume events (Capacitor App.addListener('appStateChange')) by verifying biometrics and rehydrating the in-memory token cache rather than reading from disk.

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

Keychain entries MUST use unique, partitioned service identifiers and access groups (e.g., kSecAttrService / kSecAttrAccessGroup) to prevent namespace collisions or cross-app leaks across app suites.

Keychain entries MUST use unique, partitioned service identifiers and access groups (e.g., kSecAttrService / kSecAttrAccessGroup) to prevent namespace collisions or cross-app leaks across app suites.

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

Code MUST handle OS-level webview sandbox resets and WKWebView/Android WebView process terminations gracefully by re-triggering the native biometric unlock boundary rather than redirecting to full unauthenticated logouts.

Code MUST handle OS-level webview sandbox resets and WKWebView/Android WebView process terminations gracefully by re-triggering the native biometric unlock boundary rather than redirecting to full unauthenticated logouts.

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 Biometric Keychain Partitioning & Ephemeral Session Boundary Standard critical for AI coding assistants?

Mandates isolating authentication credentials to native hardware enclaves (iOS Keychain / Android KeyStore) across Capacitor 7 native-web bridges. Enforces an ephemeral, in-memory-only session model within the WebView runtime, guaranteeing credentials survive OS webview sandbox purges without ever persisting secrets in insecure web storage. 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 Session Credentials into Unencrypted Web Storage or Misconfiguring Biometric Enclave Partitioning in Hybrid WebViews) 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