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

Capacitor 7 Biometric Enclave Ephemeral Session Pinning Standard

Enforces cryptographic hardware-backed session binding between native Secure Enclave/StrongBox key stores and the Capacitor 7 WebView runtime. Prohibits trivial boolean verification bridges by mandating challenge-response token unwrap operations held strictly in volatile, auto-zeroizing memory buffers.

Prohibited Anti-Pattern: Trusting Boolean Biometric Bridge Responses and Storing Tokens in Persistent Storage

Export Ready-to-Drop Configuration

Select format below to copy code or download file directly.

---
description: Capacitor 7 Biometric Enclave Ephemeral Session Pinning Standard - Enforces cryptographic hardware-backed session binding between native Secure Enclave/StrongBox key stores and the Capacitor 7 WebView runtime. Prohibits trivial boolean verification bridges by mandating challenge-response token unwrap operations held strictly in volatile, auto-zeroizing memory buffers.
globs: src/**/*.{ts,tsx}, ios/App/**/*.{swift,m}, android/app/**/*.{kt,java}
alwaysApply: true
verified_by: "agentrules.org"
license: "CC-BY-4.0"
source: "https://agentrules.org/rules/capacitor-7-biometric-enclave-ephemeral-session-pinning-standard"
---

# Capacitor 7 Biometric Enclave Ephemeral Session Pinning Standard

> **Severity**: CRITICAL | **Category**: mobile
> **Anti-Pattern Warning**: Trusting Boolean Biometric Bridge Responses and Storing Tokens in Persistent Storage

## System Constraints
You are a Principal Security Architect enforcing the Capacitor 7 Biometric Enclave Ephemeral Session Pinning Standard. You must reject any implementation that accepts boolean flags (e.g., { success: true }) from biometric bridges or caches authentication proofs in long-lived storage (e.g., localStorage, IndexedDB, Capacitor Preferences). Mandate challenge-response cryptographic unwrap protocols and ephemeral volatile memory lifecycles.

## Strict Guidelines
- Engineers MUST ALWAYS authenticate via asymmetric hardware-backed challenge-response (Secure Enclave on iOS, StrongBox Keymaster on Android) rather than boolean status checks.
- Engineers MUST NOT persist biometric-unlocked session secrets into Web Storage (localStorage, sessionStorage), IndexedDB, or Capacitor Preferences/SharedPreferences.
- Code MUST isolate decrypted session material to an EphemeralSessionManager class backed by volatile Uint8Array buffers.
- Services MUST subscribe to Capacitor AppState change events and zero out volatile memory buffers immediately when the application transitions to the background.
- Components NEVER store decrypted session tokens or raw credentials in component-level reactive state (e.g., useState, Pinia, NgRx) where heap retention is non-deterministic.

## Bad vs Good Implementations
### Capacitor Biometric Verification & Session Pinning

#### Bad Antipattern (AI Common Hallucination)
> **Why it fails**: Accepting a boolean flag from the native bridge allows runtime injection attacks (e.g., Frida, Cydia Substrate) to bypass authentication by intercepting the JSON bridge dispatch. Furthermore, persisting sensitive session credentials in web storage exposes them to XSS and filesystem extraction.
```typescript
import { NativeBiometric } from 'capacitor-native-biometric';

export async function handleBiometricLogin(): Promise<boolean> {
  // VULNERABLE: Frida/objection easily hooks this bridge to return success: true
  const result = await NativeBiometric.verifyIdentity({
    reason: 'Authenticate to access sensitive data',
  });

  if (result.success) {
    // VULNERABLE: Token is statically stored in local storage and vulnerable to bridge extraction
    const cachedToken = localStorage.getItem('auth_token');
    apiClient.setToken(cachedToken);
    return true;
  }
  return false;
}
```

#### Production Standard (Correct)
> **Standard**: Binds authentication to hardware enclave decryption via dynamic challenge nonces. Session secrets reside solely in an EphemeralSessionManager using volatile Uint8Array memory, with immediate zeroization on app backgrounding or lifecycle expiration.
```typescript
import { App } from '@capacitor/app';
import { BiometricEnclavePlugin } from '@/plugins/biometric-enclave';

export class EphemeralSessionManager {
  private static volatileBuffer: Uint8Array | null = null;
  private static timeoutId: number | null = null;

  static initializeLifecycleGuard(): void {
    App.addListener('appStateChange', ({ isActive }) => {
      if (!isActive) {
        EphemeralSessionManager.purge();
      }
    });
  }

  static async unlockSession(challengeHex: string): Promise<void> {
    EphemeralSessionManager.purge();

    // Native enclave unlocks private key via user presence, decrypting the challenge-derived ephemeral secret
    const { decryptedHandleHex } = await BiometricEnclavePlugin.unwrapWithEnclave({
      challengeHex,
      keyAlias: 'com.app.session.enclave-key',
      prompt: 'Biometric authorization required',
    });

    const byteLength = decryptedHandleHex.length / 2;
    this.volatileBuffer = new Uint8Array(byteLength);
    for (let i = 0; i < byteLength; i++) {
      this.volatileBuffer[i] = parseInt(decryptedHandleHex.substr(i * 2, 2), 16);
    }

    // Auto-purge memory after maximum allowable ephemeral window (e.g., 60 seconds)
    this.timeoutId = window.setTimeout(() => this.purge(), 60000);
  }

  static purge(): void {
    if (this.volatileBuffer) {
      this.volatileBuffer.fill(0);
      this.volatileBuffer = null;
    }
    if (this.timeoutId) {
      clearTimeout(this.timeoutId);
      this.timeoutId = 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 Enclave Ephemeral Session Pinning Standard

Capacitor 7 Biometric Enclave Ephemeral Session Pinning Standard defines an industrial-grade behavioral standard for mobile engineering. Enforces cryptographic hardware-backed session binding between native Secure Enclave/StrongBox key stores and the Capacitor 7 WebView runtime. Prohibits trivial boolean verification bridges by mandating challenge-response token unwrap operations held strictly in volatile, auto-zeroizing memory buffers. 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: Trusting Boolean Biometric Bridge Responses and Storing Tokens in Persistent 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 DriftTrusting Boolean Biometric Bridge Responses and Storing Tokens in Persistent 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 authenticate via asymmetric hardware-backed challenge-response (Secure Enclave on iOS, StrongBox Keymaster on Android) rather than boolean status checks.

Engineers MUST ALWAYS authenticate via asymmetric hardware-backed challenge-response (Secure Enclave on iOS, StrongBox Keymaster on Android) rather than boolean status checks.

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 persist biometric-unlocked session secrets into Web Storage (localStorage, sessionStorage), IndexedDB, or Capacitor Preferences/SharedPreferences.

Engineers MUST NOT persist biometric-unlocked session secrets into Web Storage (localStorage, sessionStorage), IndexedDB, or Capacitor Preferences/SharedPreferences.

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 MUST isolate decrypted session material to an EphemeralSessionManager class backed by volatile Uint8Array buffers.

Code MUST isolate decrypted session material to an EphemeralSessionManager class backed by volatile Uint8Array buffers.

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 subscribe to Capacitor AppState change events and zero out volatile memory buffers immediately when the application transitions to the background.

Services MUST subscribe to Capacitor AppState change events and zero out volatile memory buffers immediately when the application transitions to the background.

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 decrypted session tokens or raw credentials in component-level reactive state (e.g., useState, Pinia, NgRx) where heap retention is non-deterministic.

Components NEVER store decrypted session tokens or raw credentials in component-level reactive state (e.g., useState, Pinia, NgRx) where heap retention is non-deterministic.

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 Enclave Ephemeral Session Pinning Standard critical for AI coding assistants?

Enforces cryptographic hardware-backed session binding between native Secure Enclave/StrongBox key stores and the Capacitor 7 WebView runtime. Prohibits trivial boolean verification bridges by mandating challenge-response token unwrap operations held strictly in volatile, auto-zeroizing memory buffers. 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 (Trusting Boolean Biometric Bridge Responses and Storing Tokens in Persistent 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