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

Capacitor 7 Biometric Cryptographic Keystore Invalidation on Device Lock State

Mandates that volatile cryptographic keys, decrypted authorization tokens, and hardware-backed biometric cryptographic handles in Capacitor 7 applications are irrevocably zeroized from runtime memory whenever the application yields focus, transitions to the background, or the device enters a locked state. Prevents memory extraction, unauthorized forensic access, and stale biometric authentication states across app lifecycle boundaries.

Prohibited Anti-Pattern: Retaining Plaintext Secrets and Unlocked Cryptographic Sessions in JavaScript Memory Across App Pause/Lock Lifecycle Events

Export Ready-to-Drop Configuration

Select format below to copy code or download file directly.

---
description: Capacitor 7 Biometric Cryptographic Keystore Invalidation on Device Lock State - Mandates that volatile cryptographic keys, decrypted authorization tokens, and hardware-backed biometric cryptographic handles in Capacitor 7 applications are irrevocably zeroized from runtime memory whenever the application yields focus, transitions to the background, or the device enters a locked state. Prevents memory extraction, unauthorized forensic access, and stale biometric authentication states across app lifecycle boundaries.
globs: src/**/*.{ts,tsx}, ios/App/App/**/*.{swift,m}, android/app/src/main/**/*.{java,kt}
alwaysApply: true
verified_by: "agentrules.org"
license: "CC-BY-4.0"
source: "https://agentrules.org/rules/capacitor-7-biometric-keystore-lock-invalidation"
---

# Capacitor 7 Biometric Cryptographic Keystore Invalidation on Device Lock State

> **Severity**: CRITICAL | **Category**: mobile
> **Anti-Pattern Warning**: Retaining Plaintext Secrets and Unlocked Cryptographic Sessions in JavaScript Memory Across App Pause/Lock Lifecycle Events

## System Constraints
You are a Principal Mobile Security Engineer enforcing Capacitor 7 Biometric Cryptographic Keystore Invalidation on Device Lock State. You ensure that volatile cryptographic material, unlocked Secure Enclave/Android Keystore session pointers, and sensitive decrypted payloads are aggressively expunged and wiped using zeroization upon app pause, backgrounding, or device lock events.

## Strict Guidelines
- Engineers MUST ALWAYS register native lifecycle listeners via `@capacitor/app` (`appStateChange`) during boot and bind them directly to a cryptographic session revocation routine.
- Engineers MUST NOT cache hardware-unlocked cryptographic keys or raw decrypted access/refresh tokens in volatile JavaScript heap (e.g., Redux, Pinia, React state, module-level singletons) beyond an immediate cryptographic operation.
- Services MUST overwrite memory buffers containing ephemeral symmetric keys or biometric payloads with zeroes (`TypedArray.prototype.fill(0)`) immediately prior to releasing references.
- Services MUST invoke native hardware invalidation (e.g., closing `BiometricPrompt` crypto sessions or dropping `LAContext` instances) whenever `isActive` becomes `false` in Capacitor 7.
- Components NEVER render sensitive unlocked state or cryptographic primitives without wrapping them in an ephemeral context that defaults to invalidated upon lifecycle state transitions.
- Native plugins MUST enforce `setUserAuthenticationRequired(true)` with zero timeout or require cryptographic authentication per operation (`BIOMETRIC_STRONG`) to prevent background memory retention in native keystore daemons.

## Bad vs Good Implementations
### Biometric Keystore Session Invalidation on App Background State

#### Bad Antipattern (AI Common Hallucination)
> **Why it fails**: The secret is retained indefinitely as an immutable string on the JavaScript V8/JavaScriptCore heap. Immutable strings cannot be overwritten or zeroized. Furthermore, the class completely ignores Capacitor App lifecycle state changes, leaving decrypted cryptographic material in memory when the device is locked or placed in the background.
```typescript
import { App } from '@capacitor/app';

class KeyringService {
  private decryptedKey: string | null = null;

  async unlockKey(biometricToken: string): Promise<string> {
    // ANTI-PATTERN: Decrypting and holding the raw key indefinitely in JS runtime memory
    this.decryptedKey = await window.crypto.subtle.exportKey('raw', 
      await this.deriveKey(biometricToken)
    ).then(b => Array.from(new Uint8Array(b)).join(''));
    
    // Fails to listen to lock/background events, leaving secret exposed to memory dumps
    return this.decryptedKey;
  }

  getKey(): string | null {
    return this.decryptedKey;
  }

  private async deriveKey(token: string): Promise<CryptoKey> {
    return {} as CryptoKey; // Mock implementation
  }
}
```

#### Production Standard (Correct)
> **Standard**: Ephemeral cryptographic material is stored exclusively within a mutable `Uint8Array`. The class binds to Capacitor 7's `App.addListener('appStateChange')`. When `state.isActive` resolves to `false` (triggered by lock-screen engagement, multitasking switch, or background transition), the buffer is explicitly wiped with `.fill(0)` and dereferenced immediately.
```typescript
import { App, AppState } from '@capacitor/app';
import { PluginListenerHandle } from '@capacitor/core';

export class SecureKeyringSession {
  private ephemeralKeyBytes: Uint8Array | null = null;
  private lifecycleHandle: PluginListenerHandle | null = null;

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

  setDecryptedKey(sourceBuffer: Uint8Array): void {
    // Allocate isolated volatile buffer
    this.ephemeralKeyBytes = new Uint8Array(sourceBuffer.length);
    this.ephemeralKeyBytes.set(sourceBuffer);
  }

  purgeCryptographicMaterial(): void {
    if (this.ephemeralKeyBytes) {
      // Mandatory zeroization to defeat cold boot and heap inspection
      this.ephemeralKeyBytes.fill(0);
      this.ephemeralKeyBytes = null;
    }
  }

  async dispose(): Promise<void> {
    this.purgeCryptographicMaterial();
    if (this.lifecycleHandle) {
      await this.lifecycleHandle.remove();
      this.lifecycleHandle = null;
    }
  }
}
```

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 Cryptographic Keystore Invalidation on Device Lock State

Capacitor 7 Biometric Cryptographic Keystore Invalidation on Device Lock State defines an industrial-grade behavioral standard for mobile engineering. Mandates that volatile cryptographic keys, decrypted authorization tokens, and hardware-backed biometric cryptographic handles in Capacitor 7 applications are irrevocably zeroized from runtime memory whenever the application yields focus, transitions to the background, or the device enters a locked state. Prevents memory extraction, unauthorized forensic access, and stale biometric authentication states across app lifecycle boundaries. 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 Secrets and Unlocked Cryptographic Sessions in JavaScript Memory Across App Pause/Lock Lifecycle Events 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 Secrets and Unlocked Cryptographic Sessions in JavaScript Memory Across App Pause/Lock Lifecycle EventsCritical
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 native lifecycle listeners via `@capacitor/app` (`appStateChange`) during boot and bind them directly to a cryptographic session revocation routine.

Engineers MUST ALWAYS register native lifecycle listeners via `@capacitor/app` (`appStateChange`) during boot and bind them directly to a cryptographic session revocation routine.

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 hardware-unlocked cryptographic keys or raw decrypted access/refresh tokens in volatile JavaScript heap (e.g., Redux, Pinia, React state, module-level singletons) beyond an immediate cryptographic operation.

Engineers MUST NOT cache hardware-unlocked cryptographic keys or raw decrypted access/refresh tokens in volatile JavaScript heap (e.g., Redux, Pinia, React state, module-level singletons) beyond an immediate cryptographic operation.

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 overwrite memory buffers containing ephemeral symmetric keys or biometric payloads with zeroes (`TypedArray.prototype.fill(0)`) immediately prior to releasing references.

Services MUST overwrite memory buffers containing ephemeral symmetric keys or biometric payloads with zeroes (`TypedArray.prototype.fill(0)`) immediately prior to releasing 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.
4

Services MUST invoke native hardware invalidation (e.g., closing `BiometricPrompt` crypto sessions or dropping `LAContext` instances) whenever `isActive` becomes `false` in Capacitor 7.

Services MUST invoke native hardware invalidation (e.g., closing `BiometricPrompt` crypto sessions or dropping `LAContext` instances) whenever `isActive` becomes `false` in Capacitor 7.

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 render sensitive unlocked state or cryptographic primitives without wrapping them in an ephemeral context that defaults to invalidated upon lifecycle state transitions.

Components NEVER render sensitive unlocked state or cryptographic primitives without wrapping them in an ephemeral context that defaults to invalidated upon lifecycle state transitions.

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

Native plugins MUST enforce `setUserAuthenticationRequired(true)` with zero timeout or require cryptographic authentication per operation (`BIOMETRIC_STRONG`) to prevent background memory retention in native keystore daemons.

Native plugins MUST enforce `setUserAuthenticationRequired(true)` with zero timeout or require cryptographic authentication per operation (`BIOMETRIC_STRONG`) to prevent background memory retention in native keystore daemons.

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 Cryptographic Keystore Invalidation on Device Lock State critical for AI coding assistants?

Mandates that volatile cryptographic keys, decrypted authorization tokens, and hardware-backed biometric cryptographic handles in Capacitor 7 applications are irrevocably zeroized from runtime memory whenever the application yields focus, transitions to the background, or the device enters a locked state. Prevents memory extraction, unauthorized forensic access, and stale biometric authentication states across app lifecycle boundaries. 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 Secrets and Unlocked Cryptographic Sessions in JavaScript Memory Across App Pause/Lock Lifecycle Events) 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