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-ephemerality

Capacitor 7 Hardware-Backed Biometric Storage and In-Memory Session Ephemerality

Enforces strict hardware-backed Secure Enclave and Android Keystore cryptographic credential management using Capacitor 7 security primitives. Mandates immediate deterministic sanitization of in-memory symmetric session keys, token references, and decrypted cryptographic state upon mobile OS backgrounding or lifecycle suspension to prevent cold-boot and runtime heap-inspection attacks.

Prohibited Anti-Pattern: Retaining Plaintext Tokens in JavaScript Memory Across App State Transitions or Persisting Cryptographic Keys in Unencrypted Local Storage

Export Ready-to-Drop Configuration

Select format below to copy code or download file directly.

---
description: Capacitor 7 Hardware-Backed Biometric Storage and In-Memory Session Ephemerality - Enforces strict hardware-backed Secure Enclave and Android Keystore cryptographic credential management using Capacitor 7 security primitives. Mandates immediate deterministic sanitization of in-memory symmetric session keys, token references, and decrypted cryptographic state upon mobile OS backgrounding or lifecycle suspension to prevent cold-boot and runtime heap-inspection attacks.
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-ephemerality"
---

# Capacitor 7 Hardware-Backed Biometric Storage and In-Memory Session Ephemerality

> **Severity**: CRITICAL | **Category**: mobile
> **Anti-Pattern Warning**: Retaining Plaintext Tokens in JavaScript Memory Across App State Transitions or Persisting Cryptographic Keys in Unencrypted Local Storage

## System Constraints
You are a Principal Security Architect enforcing Capacitor 7 Biometric Secure Storage Session Ephemerality. Mandate that sensitive credentials never reside in unencrypted WebView storage (localStorage, IndexedDB) or persistent JavaScript runtime singletons across OS lifecycle transitions. Require immediate zeroization and cryptographic revocation of session state whenever Capacitor's App state transitions to 'pause' or 'appStateChange.isActive === false'. Ensure hardware-backed Keystore/Secure Enclave access requires real-time user biometric authentication, without caching decrypted payloads in global variables.

## Strict Guidelines
- Engineers MUST ALWAYS integrate Capacitor App lifecycle listeners ('appStateChange' and 'pause') to trigger deterministic memory zeroization and session invalidation immediately upon backgrounding.
- Engineers MUST NOT cache decrypted cryptographic material, symmetric keys, or authorization tokens inside global state, closure-scoped variables, or state stores across background lifecycle events.
- Code SHOULD leverage hardware-backed storage primitives requiring user biometric re-authentication via Secure Enclave/Keymaster on each cryptographic transaction rather than keeping master credentials decrypted in runtime memory.
- Services MUST zero out Uint8Array buffers containing sensitive credentials using crypto.getRandomValues or explicit buffer filling (.fill(0)) before nullifying references.
- Components NEVER store sensitive access credentials or refresh tokens in localStorage, sessionStorage, or unencrypted IndexedDB.

## Bad vs Good Implementations
### Vulnerable In-Memory State Retention vs. Ephemeral Zero-Fill Buffer Invalidation

#### Bad Antipattern (AI Common Hallucination)
> **Why it fails**: The session token is persisted in unencrypted WebView localStorage and held in a long-lived heap variable across background transitions. A compromised runtime environment or memory-dump attack on backgrounded processes can scrape the plaintext token directly from memory.
```typescript
import { App } from '@capacitor/app';

// Anti-pattern: Session token persists in global JavaScript heap
class InsecureSessionManager {
  private cachedToken: string | null = null;

  constructor() {
    App.addListener('appStateChange', (state) => {
      // Flaw: Only logging lifecycle change, leaving decrypted secret in heap
      console.log('App active state changed:', state.isActive);
    });
  }

  public setSession(token: string): void {
    this.cachedToken = token;
    localStorage.setItem('auth_token', token); // Critical Flaw: Persistent plain text
  }

  public getSession(): string | null {
    return this.cachedToken;
  }
}

export const sessionManager = new InsecureSessionManager();
```

#### Production Standard (Correct)
> **Standard**: Implements deterministic memory zeroization using Uint8Array.fill(0) overwritten with random values, triggered synchronously when the app enters the background. Sensitive material is never written to unencrypted storage and requires biometric verification via hardware isolation to re-acquire.
```typescript
import { App } from '@capacitor/app';
import { NativeBiometric } from 'capacitor-native-biometric';

export class EphemeralSessionManager {
  private ephemeralKeyBuffer: Uint8Array | null = null;
  private listenerHandle: Promise<any> | null = null;

  constructor() {
    this.initLifecycleGuards();
  }

  private initLifecycleGuards(): void {
    this.listenerHandle = App.addListener('appStateChange', ({ isActive }) => {
      if (!isActive) {
        this.purgeMemoryState();
      }
    });
  }

  public async authenticateAndLoadKey(serverKey: string): Promise<Uint8Array> {
    // Verify biometric presence strictly backed by Secure Enclave / Android Keystore
    await NativeBiometric.verifyIdentity({
      reason: 'Authenticate to decrypt the ephemeral session',
      title: 'Biometric Authentication',
    });

    const encoder = new TextEncoder();
    const rawBytes = encoder.encode(serverKey);
    this.ephemeralKeyBuffer = new Uint8Array(rawBytes.length);
    this.ephemeralKeyBuffer.set(rawBytes);
    return this.ephemeralKeyBuffer;
  }

  public purgeMemoryState(): void {
    if (this.ephemeralKeyBuffer) {
      // Cryptographic zeroization: overwrite memory before dereference
      crypto.getRandomValues(this.ephemeralKeyBuffer);
      this.ephemeralKeyBuffer.fill(0);
      this.ephemeralKeyBuffer = null;
    }
  }

  public async destroy(): Promise<void> {
    this.purgeMemoryState();
    const handle = await this.listenerHandle;
    if (handle) {
      await handle.remove();
    }
  }
}

export const sessionManager = new EphemeralSessionManager();
```

Architectural Specification & Invariant Rationale

Architectural Invariant Design: Capacitor 7 Hardware-Backed Biometric Storage and In-Memory Session Ephemerality

Capacitor 7 Hardware-Backed Biometric Storage and In-Memory Session Ephemerality defines an industrial-grade behavioral standard for mobile engineering. Enforces strict hardware-backed Secure Enclave and Android Keystore cryptographic credential management using Capacitor 7 security primitives. Mandates immediate deterministic sanitization of in-memory symmetric session keys, token references, and decrypted cryptographic state upon mobile OS backgrounding or lifecycle suspension to prevent cold-boot and runtime heap-inspection attacks. 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: Retaining Plaintext Tokens in JavaScript Memory Across App State Transitions or Persisting Cryptographic Keys in Unencrypted Local 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 DriftRetaining Plaintext Tokens in JavaScript Memory Across App State Transitions or Persisting Cryptographic Keys in Unencrypted Local 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 ALWAYS integrate Capacitor App lifecycle listeners ('appStateChange' and 'pause') to trigger deterministic memory zeroization and session invalidation immediately upon backgrounding.

Engineers MUST ALWAYS integrate Capacitor App lifecycle listeners ('appStateChange' and 'pause') to trigger deterministic memory zeroization and session invalidation immediately upon backgrounding.

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 cache decrypted cryptographic material, symmetric keys, or authorization tokens inside global state, closure-scoped variables, or state stores across background lifecycle events.

Engineers MUST NOT cache decrypted cryptographic material, symmetric keys, or authorization tokens inside global state, closure-scoped variables, or state stores across background lifecycle events.

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

Code SHOULD leverage hardware-backed storage primitives requiring user biometric re-authentication via Secure Enclave/Keymaster on each cryptographic transaction rather than keeping master credentials decrypted in runtime memory.

Code SHOULD leverage hardware-backed storage primitives requiring user biometric re-authentication via Secure Enclave/Keymaster on each cryptographic transaction rather than keeping master credentials decrypted in runtime memory.

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 zero out Uint8Array buffers containing sensitive credentials using crypto.getRandomValues or explicit buffer filling (.fill(0)) before nullifying references.

Services MUST zero out Uint8Array buffers containing sensitive credentials using crypto.getRandomValues or explicit buffer filling (.fill(0)) before nullifying references.

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 store sensitive access credentials or refresh tokens in localStorage, sessionStorage, or unencrypted IndexedDB.

Components NEVER store sensitive access credentials or refresh tokens in 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.
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 Biometric Storage and In-Memory Session Ephemerality critical for AI coding assistants?

Enforces strict hardware-backed Secure Enclave and Android Keystore cryptographic credential management using Capacitor 7 security primitives. Mandates immediate deterministic sanitization of in-memory symmetric session keys, token references, and decrypted cryptographic state upon mobile OS backgrounding or lifecycle suspension to prevent cold-boot and runtime heap-inspection attacks. 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 (Retaining Plaintext Tokens in JavaScript Memory Across App State Transitions or Persisting Cryptographic Keys in Unencrypted Local 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