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

Capacitor 7 Hardware-Backed Key Derivation and Biometric Prompt Invariants

Guarantees offline cached access tokens remain cryptographically bound to the Secure Enclave or Android Keystore until explicit user presence is verified. Eliminates soft-gated authentication checks where biometric verification is merely an application-layer Boolean check rather than an cryptographic prerequisite for unwrapping AES-GCM encryption keys.

Prohibited Anti-Pattern: Soft-Gating Biometrics via Client-Side Booleans and Static Device Storage

Export Ready-to-Drop Configuration

Select format below to copy code or download file directly.

---
description: Capacitor 7 Hardware-Backed Key Derivation and Biometric Prompt Invariants - Guarantees offline cached access tokens remain cryptographically bound to the Secure Enclave or Android Keystore until explicit user presence is verified. Eliminates soft-gated authentication checks where biometric verification is merely an application-layer Boolean check rather than an cryptographic prerequisite for unwrapping AES-GCM encryption keys.
globs: src/services/auth/**/*.{ts,tsx}, src/services/storage/**/*.{ts,tsx}, src/plugins/**/*.{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-hardware-biometric-key-derivation"
---

# Capacitor 7 Hardware-Backed Key Derivation and Biometric Prompt Invariants

> **Severity**: CRITICAL | **Category**: mobile
> **Anti-Pattern Warning**: Soft-Gating Biometrics via Client-Side Booleans and Static Device Storage

## System Constraints
You are a Principal Mobile Architect enforcing cryptographic invariants for Capacitor 7. You strictly mandate that sensitive credentials and offline access tokens stored at rest are wrapped using cryptographic keys bound to hardware-backed keystores (iOS Secure Enclave via Keychain AccessControl, Android StrongBox/TEE Keystore with setUserAuthenticationRequired). Biometric validation MUST NOT be a client-side boolean verification; it must be a cryptographic gating requirement where the decryption operation itself fails if hardware-backed user presence is not established.

## Strict Guidelines
- Engineers MUST ALWAYS tie access token decryption directly to hardware-backed cryptographic operations where keys require kSecAccessControlBiometryAny or UserAuthenticationRequirement.BIOMETRIC_STRONG.
- Engineers MUST NOT rely on high-level biometric plugins that merely return a boolean success/failure flag without performing hardware key unwrap operations.
- Code MUST handle cryptographic authentication failures (e.g., LAErrorUserCancel, KeyPermanentlyInvalidatedException) explicitly, invalidating local session tokens upon key corruption or enrollment modification.
- Services MUST ensure that cryptographic master keys are generated inside the Secure Enclave or Hardware Keystore and never exported into JavaScript or webview memory in cleartext.
- Components NEVER store sensitive access tokens in standard unencrypted web storage, unconstrained SQLite databases, or standard Capacitor Preferences.

## Bad vs Good Implementations
### Hardware-Bound Key Decryption vs Application-Level Boolean Gating

#### Bad Antipattern (AI Common Hallucination)
> **Why it fails**: Biometric verification is treated as a flow-control boolean. The cached token is stored in unconstrained Capacitor Preferences, which can be extracted directly via device backups, rooted/jailbroken file systems, or runtime JavaScript modification without interacting with the Secure Enclave.
```typescript
import { NativeBiometric } from 'capacitor-native-biometric';
import { Preferences } from '@capacitor/preferences';

export async function getCachedAccessToken(): Promise<string | null> {
  // VULNERABILITY: Soft-biometric gating. Verification returns a boolean;
  // an attacker with filesystem access or a patched webview runtime can bypass
  // the verification check and read the plaintext token directly.
  const result = await NativeBiometric.verifyIdentity({
    reason: 'Authenticate to access your account',
    title: 'Biometric Login',
  });

  if (result.success) {
    const { value } = await Preferences.get({ key: 'auth_token' });
    return value;
  }
  return null;
}
```

#### Production Standard (Correct)
> **Standard**: Token decryption is delegated directly to hardware-backed native keystores. The decryption key never leaves the Secure Enclave/TEE, and the operation fails at the cryptographic layer if user presence is not verified, preventing runtime bypassing.
```typescript
import { registerPlugin } from '@capacitor/core';

interface HardwareKeyStorePlugin {
  decryptBoundToken(options: { encryptedBlob: string; promptMessage: string }): Promise<{ plainToken: string }>;
}

const HardwareKeyStore = registerPlugin<HardwareKeyStorePlugin>('HardwareKeyStore');

export async function getCachedAccessToken(encryptedBlob: string): Promise<string> {
  // INVARIANT: The native plugin calls SecItemCopyMatching (iOS) with kSecAccessControlBiometryCurrentSet
  // or Cipher.init (Android) with KeyProperties.AUTH_BIOMETRIC_STRONG.
  // The decryption hardware fails at the chip level unless explicit biometric presence unwraps the key.
  try {
    const response = await HardwareKeyStore.decryptBoundToken({
      encryptedBlob,
      promptMessage: 'Unlock secure session key',
    });
    return response.plainToken;
  } catch (error: unknown) {
    const err = error as { code?: string; message?: string };
    if (err.code === 'KEY_INVALIDATED') {
      // Enrolled biometrics changed; invalidate session cache
      await HardwareKeyStore.decryptBoundToken({ encryptedBlob: '', promptMessage: '' }).catch(() => {});
    }
    throw new Error(`Cryptographic unlock failed: ${err.message ?? 'Unknown'}`);
  }
}
```

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 Hardware-Backed Key Derivation and Biometric Prompt Invariants

Capacitor 7 Hardware-Backed Key Derivation and Biometric Prompt Invariants defines an industrial-grade behavioral standard for mobile engineering. Guarantees offline cached access tokens remain cryptographically bound to the Secure Enclave or Android Keystore until explicit user presence is verified. Eliminates soft-gated authentication checks where biometric verification is merely an application-layer Boolean check rather than an cryptographic prerequisite for unwrapping AES-GCM encryption keys. 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: Soft-Gating Biometrics via Client-Side Booleans and Static Device 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 DriftSoft-Gating Biometrics via Client-Side Booleans and Static Device 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 tie access token decryption directly to hardware-backed cryptographic operations where keys require kSecAccessControlBiometryAny or UserAuthenticationRequirement.BIOMETRIC_STRONG.

Engineers MUST ALWAYS tie access token decryption directly to hardware-backed cryptographic operations where keys require kSecAccessControlBiometryAny or UserAuthenticationRequirement.BIOMETRIC_STRONG.

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 rely on high-level biometric plugins that merely return a boolean success/failure flag without performing hardware key unwrap operations.

Engineers MUST NOT rely on high-level biometric plugins that merely return a boolean success/failure flag without performing hardware key unwrap operations.

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 handle cryptographic authentication failures (e.g., LAErrorUserCancel, KeyPermanentlyInvalidatedException) explicitly, invalidating local session tokens upon key corruption or enrollment modification.

Code MUST handle cryptographic authentication failures (e.g., LAErrorUserCancel, KeyPermanentlyInvalidatedException) explicitly, invalidating local session tokens upon key corruption or enrollment modification.

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 ensure that cryptographic master keys are generated inside the Secure Enclave or Hardware Keystore and never exported into JavaScript or webview memory in cleartext.

Services MUST ensure that cryptographic master keys are generated inside the Secure Enclave or Hardware Keystore and never exported into JavaScript or webview memory in cleartext.

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 tokens in standard unencrypted web storage, unconstrained SQLite databases, or standard Capacitor Preferences.

Components NEVER store sensitive access tokens in standard unencrypted web storage, unconstrained SQLite databases, or standard Capacitor Preferences.

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 Key Derivation and Biometric Prompt Invariants critical for AI coding assistants?

Guarantees offline cached access tokens remain cryptographically bound to the Secure Enclave or Android Keystore until explicit user presence is verified. Eliminates soft-gated authentication checks where biometric verification is merely an application-layer Boolean check rather than an cryptographic prerequisite for unwrapping AES-GCM encryption keys. 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 (Soft-Gating Biometrics via Client-Side Booleans and Static Device 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