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

Capacitor 7 Secure Enclave Hardware-Bound Token Storage Standard

Enforces that all OAuth refresh tokens and long-lived cryptographic credentials in Capacitor 7 hybrid applications are exclusively stored in biometric-gated, hardware-backed secure elements (iOS Secure Enclave via Keychain Services and Android Keystore with StrongBox/Keymaster). Prohibits fallback to unencrypted web storage, SQLite, or standard application preferences to prevent token exfiltration on compromised, rooted, or jailbroken devices. Mandates transient, memory-only caching of short-lived access tokens while forcing biometric step-up authentication on every refresh cycle.

Prohibited Anti-Pattern: Persisting Refresh Tokens in Capacitor Preferences or Non-Hardware-Bound Web Storage

Export Ready-to-Drop Configuration

Select format below to copy code or download file directly.

---
description: Capacitor 7 Secure Enclave Hardware-Bound Token Storage Standard - Enforces that all OAuth refresh tokens and long-lived cryptographic credentials in Capacitor 7 hybrid applications are exclusively stored in biometric-gated, hardware-backed secure elements (iOS Secure Enclave via Keychain Services and Android Keystore with StrongBox/Keymaster). Prohibits fallback to unencrypted web storage, SQLite, or standard application preferences to prevent token exfiltration on compromised, rooted, or jailbroken devices. Mandates transient, memory-only caching of short-lived access tokens while forcing biometric step-up authentication on every refresh cycle.
globs: src/auth/**/*.{ts,tsx}, src/services/**/*.{ts,tsx}, src/plugins/**/*.{ts,tsx}
alwaysApply: true
verified_by: "agentrules.org"
license: "CC-BY-4.0"
source: "https://agentrules.org/rules/capacitor-7-secure-enclave-token-storage"
---

# Capacitor 7 Secure Enclave Hardware-Bound Token Storage Standard

> **Severity**: CRITICAL | **Category**: mobile
> **Anti-Pattern Warning**: Persisting Refresh Tokens in Capacitor Preferences or Non-Hardware-Bound Web Storage

## System Constraints
You are a Principal Mobile Security Architect enforcing the Capacitor 7 Secure Enclave Hardware-Bound Token Storage Standard. You must ensure that OAuth refresh tokens, signing keys, and sensitive long-lived session secrets are NEVER stored in standard persistent containers (such as @capacitor/preferences, localStorage, IndexedDB, or standard unencrypted SQLite). Refresh tokens MUST be hardware-bound using native plugins that interface directly with the iOS Secure Enclave (kSecAttrAccessControl with biometryCurrentSet / devicePasscode) and Android Keystore (setUserAuthenticationRequired with StrongBox Keymaster backing). Short-lived access tokens MUST remain strictly in volatile memory. Reject any architecture that fails to handle biometric cancellation gracefully or falls back to software-only encryption.

## Strict Guidelines
- Engineers MUST NEVER persist OAuth refresh tokens or root cryptographic keys in '@capacitor/preferences', 'localStorage', 'sessionStorage', or unencrypted SQLite databases.
- Engineers MUST ALWAYS bind refresh token storage to native hardware keychains using biometric-gated access control policies (kSecAccessControlBiometryAny or kSecAccessControlUserPresence on iOS; setUserAuthenticationRequired(true) on Android).
- Services MUST keep short-lived access tokens strictly in volatile JavaScript memory (module-scoped variables or in-memory state stores) and purge them immediately upon application backgrounding or termination.
- Engineers MUST configure keychain items with 'kSecAttrAccessibleAfterFirstUnlockThisDeviceOnly' on iOS to prevent items from being transferred via unencrypted iCloud backups or mobile device management (MDM) image cloning.
- Token refresh flows MUST implement step-up biometric prompt handling and MUST gracefully revoke credentials and terminate the session if biometric enrollment changes (e.g., BiometryCurrentSet invalidation) or if hardware authentication fails.
- Code MUST explicitly handle platform-specific hardware unavailability errors (e.g., absence of Secure Enclave or StrongBox) by denying token generation rather than downgrading to software-only persistent storage.

## Bad vs Good Implementations
### Insecure Storage in Capacitor Preferences vs Hardware-Bound Biometric Keychain Storage

#### Bad Antipattern (AI Common Hallucination)
> **Why it fails**: Using @capacitor/preferences writes tokens directly to plaintext XML backing files (NSUserDefaults and SharedPreferences). On rooted Android or jailbroken iOS devices, these files can be extracted directly using standard filesystem tools or backup inspection, leading to immediate account takeover.
```typescript
import { Preferences } from '@capacitor/preferences';

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

export class AuthService {
  // VULNERABLE: Preferences writes to NSUserDefaults (iOS) and SharedPreferences (Android)
  // Both are stored in plaintext XML on the filesystem, easily extracted via root/jailbreak.
  async persistSession(session: AuthSession): Promise<void> {
    await Preferences.set({
      key: 'auth_tokens',
      value: JSON.stringify(session),
    });
  }

  async getRefreshToken(): Promise<string | null> {
    const { value } = await Preferences.get({ key: 'auth_tokens' });
    if (!value) return null;
    const parsed = JSON.parse(value) as AuthSession;
    return parsed.refreshToken;
  }
}
```

#### Production Standard (Correct)
> **Standard**: Access tokens are kept strictly in volatile memory, while refresh tokens are held in native hardware keychains gated by 'biometryCurrentSet' and 'afterFirstUnlockThisDeviceOnly'. Even on jailbroken/rooted devices, the private master keys never leave the Secure Enclave or StrongBox chip without explicit, interactive biometric authorization.
```typescript
import { NativeBiometricSecureStorage } from '@/plugins/biometric-secure-storage';

interface MemorySession {
  accessToken: string;
  expiresAt: number;
}

export class AuthService {
  // Invariant: Access tokens live strictly in volatile memory
  private volatileSession: MemorySession | null = null;
  private static readonly REFRESH_TOKEN_KEY = 'oauth_refresh_token_hw_bound';

  async saveRefreshToken(refreshToken: string): Promise<void> {
    // Invariant: Enforce hardware-backed Secure Enclave / StrongBox with biometric gate
    await NativeBiometricSecureStorage.set({
      key: AuthService.REFRESH_TOKEN_KEY,
      value: refreshToken,
      accessControl: 'biometryCurrentSet',
      accessibility: 'afterFirstUnlockThisDeviceOnly',
      requireHardwareEnclave: true,
      promptTitle: 'Authenticate to register secure credentials',
    });
  }

  async getValidAccessToken(): Promise<string> {
    const now = Date.now();
    if (this.volatileSession && this.volatileSession.expiresAt > now + 30000) {
      return this.volatileSession.accessToken;
    }

    // Invariant: Refresh requires hardware biometric gate step-up
    const refreshToken = await NativeBiometricSecureStorage.get({
      key: AuthService.REFRESH_TOKEN_KEY,
      promptTitle: 'Authenticate to renew secure session',
      promptReason: 'Access to refresh credentials requires biometric verification',
    });

    if (!refreshToken) {
      throw new Error('SEC_ENCLAVE_TOKEN_NOT_FOUND: Re-authentication required');
    }

    return this.refreshVolatileToken(refreshToken);
  }

  private async refreshVolatileToken(refreshToken: string): Promise<string> {
    // Exchange hardware-gated refresh token for a new short-lived access token
    const response = await fetch('https://auth.example.com/oauth/token', {
      method: 'POST',
      headers: { 'Content-Type': 'application/json' },
      body: JSON.stringify({ grant_type: 'refresh_token', refresh_token: refreshToken }),
    });

    if (!response.ok) {
      await NativeBiometricSecureStorage.remove({ key: AuthService.REFRESH_TOKEN_KEY });
      throw new Error('TOKEN_EXCHANGE_FAILED');
    }

    const data = await response.json();
    this.volatileSession = {
      accessToken: data.access_token,
      expiresAt: Date.now() + data.expires_in * 1000,
    };
    return this.volatileSession.accessToken;
  }
}
```

Architectural Specification & Invariant Rationale

Architectural Invariant Design: Capacitor 7 Secure Enclave Hardware-Bound Token Storage Standard

Capacitor 7 Secure Enclave Hardware-Bound Token Storage Standard defines an industrial-grade behavioral standard for mobile engineering. Enforces that all OAuth refresh tokens and long-lived cryptographic credentials in Capacitor 7 hybrid applications are exclusively stored in biometric-gated, hardware-backed secure elements (iOS Secure Enclave via Keychain Services and Android Keystore with StrongBox/Keymaster). Prohibits fallback to unencrypted web storage, SQLite, or standard application preferences to prevent token exfiltration on compromised, rooted, or jailbroken devices. Mandates transient, memory-only caching of short-lived access tokens while forcing biometric step-up authentication on every refresh cycle. 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 Refresh Tokens in Capacitor Preferences or Non-Hardware-Bound Web Storage 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 Refresh Tokens in Capacitor Preferences or Non-Hardware-Bound Web StorageCritical
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 OAuth refresh tokens or root cryptographic keys in '@capacitor/preferences', 'localStorage', 'sessionStorage', or unencrypted SQLite databases.

Engineers MUST NEVER persist OAuth refresh tokens or root cryptographic keys in '@capacitor/preferences', 'localStorage', 'sessionStorage', or unencrypted SQLite databases.

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 bind refresh token storage to native hardware keychains using biometric-gated access control policies (kSecAccessControlBiometryAny or kSecAccessControlUserPresence on iOS

Engineers MUST ALWAYS bind refresh token storage to native hardware keychains using biometric-gated access control policies (kSecAccessControlBiometryAny or kSecAccessControlUserPresence on iOS; setUserAuthenticationRequired(true) on Android).

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 short-lived access tokens strictly in volatile JavaScript memory (module-scoped variables or in-memory state stores) and purge them immediately upon application backgrounding or termination.

Services MUST keep short-lived access tokens strictly in volatile JavaScript memory (module-scoped variables or in-memory state stores) and purge them immediately upon application backgrounding or termination.

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 configure keychain items with 'kSecAttrAccessibleAfterFirstUnlockThisDeviceOnly' on iOS to prevent items from being transferred via unencrypted iCloud backups or mobile device management (MDM) image cloning.

Engineers MUST configure keychain items with 'kSecAttrAccessibleAfterFirstUnlockThisDeviceOnly' on iOS to prevent items from being transferred via unencrypted iCloud backups or mobile device management (MDM) image cloning.

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

Token refresh flows MUST implement step-up biometric prompt handling and MUST gracefully revoke credentials and terminate the session if biometric enrollment changes (e.g., BiometryCurrentSet invalidation) or if hardware authentication fails.

Token refresh flows MUST implement step-up biometric prompt handling and MUST gracefully revoke credentials and terminate the session if biometric enrollment changes (e.g., BiometryCurrentSet invalidation) or if hardware authentication fails.

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 explicitly handle platform-specific hardware unavailability errors (e.g., absence of Secure Enclave or StrongBox) by denying token generation rather than downgrading to software-only persistent storage.

Code MUST explicitly handle platform-specific hardware unavailability errors (e.g., absence of Secure Enclave or StrongBox) by denying token generation rather than downgrading to software-only persistent storage.

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 Hardware-Bound Token Storage Standard critical for AI coding assistants?

Enforces that all OAuth refresh tokens and long-lived cryptographic credentials in Capacitor 7 hybrid applications are exclusively stored in biometric-gated, hardware-backed secure elements (iOS Secure Enclave via Keychain Services and Android Keystore with StrongBox/Keymaster). Prohibits fallback to unencrypted web storage, SQLite, or standard application preferences to prevent token exfiltration on compromised, rooted, or jailbroken devices. Mandates transient, memory-only caching of short-lived access tokens while forcing biometric step-up authentication on every refresh cycle. 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 Refresh Tokens in Capacitor Preferences or Non-Hardware-Bound Web Storage) 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