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

Capacitor 7 Biometric Secure Storage Lifecycle Interlock Standard

Enforces deterministic in-memory zeroization of decrypted authentication tokens and sensitive credentials upon mobile OS background suspension. Mandates that resume cycles gate all WebView credential access behind biometric re-authentication backed by hardware Secure Enclave or Android KeyStore Keyset handles.

Prohibited Anti-Pattern: Persisting Raw Tokens in Memory Across Lifecycle Suspensions Bypassing Hardware Biometric Invalidation

Export Ready-to-Drop Configuration

Select format below to copy code or download file directly.

---
description: Capacitor 7 Biometric Secure Storage Lifecycle Interlock Standard - Enforces deterministic in-memory zeroization of decrypted authentication tokens and sensitive credentials upon mobile OS background suspension. Mandates that resume cycles gate all WebView credential access behind biometric re-authentication backed by hardware Secure Enclave or Android KeyStore Keyset handles.
globs: src/**/*.{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-biometric-secure-storage-lifecycle-interlock"
---

# Capacitor 7 Biometric Secure Storage Lifecycle Interlock Standard

> **Severity**: CRITICAL | **Category**: mobile
> **Anti-Pattern Warning**: Persisting Raw Tokens in Memory Across Lifecycle Suspensions Bypassing Hardware Biometric Invalidation

## System Constraints
You are a Principal Security Architect enforcing the Capacitor 7 Biometric Secure Storage Lifecycle Interlock. You must ensure all sensitive credential material held in WebView volatile memory is aggressively wiped using typed array zeroization upon app state transition to background. Furthermore, enforce that foreground restoration strictly locks access until hardware biometric authorization against Apple Secure Enclave or Android Keystore succeeds. Never allow raw tokens to remain in localStorage, regular JavaScript strings, or unzeroed memory across application suspensions.

## Strict Guidelines
- Engineers MUST ALWAYS register an `appStateChange` listener using `@capacitor/app` to capture `isActive === false` and trigger synchronous memory zeroization.
- Engineers MUST ALWAYS allocate sensitive credentials into mutable typed arrays (e.g., `Uint8Array`) to allow explicit byte-level overwriting (`crypto.getRandomValues()` followed by `.fill(0)`); immutable JavaScript primitives (`string`) MUST NOT be used for persistent in-memory session tokens.
- Engineers MUST NOT persist decrypted tokens or refresh tokens in insecure web storage mechanisms such as `localStorage`, `sessionStorage`, or unencrypted `IndexedDB`.
- Services MUST gate credential recovery on resume through hardware-backed biometric verification plugins (e.g., `@aparajita/capacitor-biometric-auth` or `@capacitor-community/keychain`) backed by `BiometricPrompt.CryptoObject` on Android and `kSecAccessControlBiometryAny` on iOS Secure Enclave.
- Components NEVER hold long-lived module-scoped references to unencrypted payloads; cryptographic handles MUST immediately lock into a dormant state when the application moves out of the foreground.

## Bad vs Good Implementations
### Vulnerable Persistence Across Lifecycle vs. Hardware-Interlocked Zeroization

#### Bad Antipattern (AI Common Hallucination)
> **Why it fails**: Immutable strings cannot be deterministically cleared from JavaScript engine garbage collectors. Storing tokens in localStorage leaves them vulnerable to extraction, and application backgrounding fails to zero out sensitive material, leaving cryptographic state vulnerable during memory dumps or device theft.
```typescript
import { App } from '@capacitor/app';

// ANTI-PATTERN: Tokens stored in immutable JavaScript strings and localStorage
let inMemoryToken: string | null = null;

export const initializeAuth = () => {
  inMemoryToken = localStorage.getItem('access_token');

  App.addListener('appStateChange', (state) => {
    // Flaw: Application backgrounding does not wipe the token from memory or storage.
    // Heap snapshot extraction or cold-boot attacks retrieve sensitive token intact.
    console.log('App state changed, isActive:', state.isActive);
  });
};

export const getAuthToken = (): string | null => {
  return inMemoryToken;
};
```

#### Production Standard (Correct)
> **Standard**: Implements an explicit zeroization pattern via `crypto.getRandomValues` and `Uint8Array.prototype.fill(0)`. Subscribes to the `@capacitor/app` lifecycle to synchronously purge raw buffers upon backgrounding. Enforces Secure Enclave/KeyStore backed biometric re-authentication prior to unlocking credentials when foregrounded.
```typescript
import { App, PluginListenerHandle } from '@capacitor/app';
import { BiometricAuth } from '@aparajita/capacitor-biometric-auth';
import { SecureStoragePlugin } from 'capacitor-secure-storage-plugin';

class SecureCredentialInterlock {
  private tokenBuffer: Uint8Array | null = null;
  private isLocked: boolean = true;
  private lifecycleHandle: PluginListenerHandle | null = null;

  public async initialize(): Promise<void> {
    this.lifecycleHandle = await App.addListener('appStateChange', async (state) => {
      if (!state.isActive) {
        this.lockAndZeroize();
      }
    });
  }

  public lockAndZeroize(): void {
    if (this.tokenBuffer) {
      crypto.getRandomValues(this.tokenBuffer);
      this.tokenBuffer.fill(0);
      this.tokenBuffer = null;
    }
    this.isLocked = true;
  }

  public async acquireToken(): Promise<Uint8Array> {
    if (!this.isLocked && this.tokenBuffer) {
      return this.tokenBuffer;
    }

    const biometryResult = await BiometricAuth.verify({
      reason: 'Biometric authorization required to unlock session keys',
      title: 'Biometric Verification',
      cancelTitle: 'Cancel',
      allowDeviceCredential: false,
      iosFallbackTitle: 'Cancel'
    });

    if (!biometryResult.hasCredentials) {
      throw new Error('SEC_ENCLAVE_AUTH_FAILED: Biometric challenge not verified');
    }

    const encryptedData = await SecureStoragePlugin.get({ key: 'secure_auth_token' });
    const encoder = new TextEncoder();
    this.tokenBuffer = encoder.encode(encryptedData.value);
    this.isLocked = false;

    return this.tokenBuffer;
  }

  public destroy(): void {
    this.lockAndZeroize();
    this.lifecycleHandle?.remove();
  }
}

export const credentialInterlock = new SecureCredentialInterlock();
```

Recommended MCP Servers (mcp-serverlist.com)

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

Recommended Agent Skills (askills.dev)

Ready-to-use executable skill functions tailored to this stack.

Architectural Specification & Invariant Rationale

Architectural Invariant Design: Capacitor 7 Biometric Secure Storage Lifecycle Interlock Standard

Capacitor 7 Biometric Secure Storage Lifecycle Interlock Standard defines an industrial-grade behavioral standard for mobile engineering. Enforces deterministic in-memory zeroization of decrypted authentication tokens and sensitive credentials upon mobile OS background suspension. Mandates that resume cycles gate all WebView credential access behind biometric re-authentication backed by hardware Secure Enclave or Android KeyStore Keyset handles. 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 Raw Tokens in Memory Across Lifecycle Suspensions Bypassing Hardware Biometric Invalidation 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 Raw Tokens in Memory Across Lifecycle Suspensions Bypassing Hardware Biometric InvalidationCritical
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 register an `appStateChange` listener using `@capacitor/app` to capture `isActive === false` and trigger synchronous memory zeroization.

Engineers MUST ALWAYS register an `appStateChange` listener using `@capacitor/app` to capture `isActive === false` and trigger synchronous memory zeroization.

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 allocate sensitive credentials into mutable typed arrays (e.g., `Uint8Array`) to allow explicit byte-level overwriting (`crypto.getRandomValues()` followed by `.fill(0)`)

Engineers MUST ALWAYS allocate sensitive credentials into mutable typed arrays (e.g., `Uint8Array`) to allow explicit byte-level overwriting (`crypto.getRandomValues()` followed by `.fill(0)`); immutable JavaScript primitives (`string`) MUST NOT be used for persistent in-memory session tokens.

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 NOT persist decrypted tokens or refresh tokens in insecure web storage mechanisms such as `localStorage`, `sessionStorage`, or unencrypted `IndexedDB`.

Engineers MUST NOT persist decrypted tokens or refresh tokens in insecure web storage mechanisms such as `localStorage`, `sessionStorage`, or unencrypted `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.
4

Services MUST gate credential recovery on resume through hardware-backed biometric verification plugins (e.g., `@aparajita/capacitor-biometric-auth` or `@capacitor-community/keychain`) backed by `BiometricPrompt.CryptoObject` on Android and `kSecAccessControlBiometryAny` on iOS Secure Enclave.

Services MUST gate credential recovery on resume through hardware-backed biometric verification plugins (e.g., `@aparajita/capacitor-biometric-auth` or `@capacitor-community/keychain`) backed by `BiometricPrompt.CryptoObject` on Android and `kSecAccessControlBiometryAny` on iOS Secure Enclave.

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 hold long-lived module-scoped references to unencrypted payloads

Components NEVER hold long-lived module-scoped references to unencrypted payloads; cryptographic handles MUST immediately lock into a dormant state when the application moves out of the foreground.

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 Secure Storage Lifecycle Interlock Standard critical for AI coding assistants?

Enforces deterministic in-memory zeroization of decrypted authentication tokens and sensitive credentials upon mobile OS background suspension. Mandates that resume cycles gate all WebView credential access behind biometric re-authentication backed by hardware Secure Enclave or Android KeyStore Keyset handles. 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 Raw Tokens in Memory Across Lifecycle Suspensions Bypassing Hardware Biometric Invalidation) 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