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

Capacitor 7 Hardware-Backed Secure Enclave Biometric Key Wrapping Standard

Enforces hardware-backed cryptographic envelope encryption for all persisted mobile session state and sensitive credentials in Capacitor 7 applications. Session keys must be wrapped using Key Encryption Keys (KEKs) bound directly to the Apple Secure Enclave or Android StrongBox KeyStore with biometric authentication gating, preventing offline token extraction via cold-boot or root exploits.

Prohibited Anti-Pattern: Persisting raw authentication tokens or encryption keys in Capacitor Preferences, UserDefaults, or unauthenticated Keychains

Export Ready-to-Drop Configuration

Select format below to copy code or download file directly.

---
description: Capacitor 7 Hardware-Backed Secure Enclave Biometric Key Wrapping Standard - Enforces hardware-backed cryptographic envelope encryption for all persisted mobile session state and sensitive credentials in Capacitor 7 applications. Session keys must be wrapped using Key Encryption Keys (KEKs) bound directly to the Apple Secure Enclave or Android StrongBox KeyStore with biometric authentication gating, preventing offline token extraction via cold-boot or root exploits.
globs: src/**/*.{ts,tsx}, ios/App/App/**/*.{swift,m}, android/app/src/main/**/*.{kt,java}
alwaysApply: true
verified_by: "agentrules.org"
license: "CC-BY-4.0"
source: "https://agentrules.org/rules/capacitor-7-secure-enclave-biometric-key-wrapping"
---

# Capacitor 7 Hardware-Backed Secure Enclave Biometric Key Wrapping Standard

> **Severity**: CRITICAL | **Category**: mobile
> **Anti-Pattern Warning**: Persisting raw authentication tokens or encryption keys in Capacitor Preferences, UserDefaults, or unauthenticated Keychains

## System Constraints
You are a Principal Mobile Security Architect enforcing the Capacitor 7 Secure Enclave Biometric Key Wrapping Standard. You must mandate that all persisted sensitive session state, offline database master keys, and authentication tokens are protected via hardware-backed envelope encryption. Unencrypted platform storage (SharedPreferences, NSUserDefaults, raw IndexedDB) and standard unauthenticated Keychain/Keystore access without hardware-level biometric constraints are strictly forbidden.

## Strict Guidelines
- Engineers MUST ALWAYS use envelope encryption: a high-entropy Data Encryption Key (DEK) encrypts local payloads via AES-256-GCM, and the DEK is wrapped by a hardware-backed Key Encryption Key (KEK).
- Engineers MUST configure KEK generation within the platform's hardware security module (Secure Enclave on iOS via kSecAttrTokenIDSecureEnclave, StrongBox or TEE on Android KeyStore).
- Engineers MUST require explicit biometric authentication flags on the KEK: 'kSecAccessControlBiometryCurrentSet' on iOS and 'setUserAuthenticationRequired(true)' with 'setInvalidatedByBiometricEnrollment(true)' on Android.
- Engineers MUST NOT store raw JWTs, refresh tokens, encryption keys, or sensitive PII in '@capacitor/preferences', localStorage, sessionStorage, or unencrypted SQLite/IndexedDB.
- Services MUST clear decrypted DEKs and plaintext session state from memory immediately after execution or when the application enters the background.
- Components NEVER directly invoke storage calls without handling biometric failure, hardware-absence, cancellation, and key invalidation exceptions gracefully.

## Bad vs Good Implementations
### Biometric Envelope Key Wrapping vs Insecure Capacitor Preferences

#### Bad Antipattern (AI Common Hallucination)
> **Why it fails**: Using standard Capacitor Preferences writes JSON data directly to NSUserDefaults (iOS) and SharedPreferences (Android) without cryptographic protection or hardware binding, allowing straightforward token extraction via device backups or root/jailbreak exploits.
```typescript
import { Preferences } from '@capacitor/preferences';

// CRITICAL FLAW: Persisting raw access and refresh tokens directly into plaintext platform storage.
// Vulnerable to filesystem extraction via physical acquisition, cold-boot, or rooted/jailbroken devices.
export async function persistSession(session: { accessToken: string; refreshToken: string }): Promise<void> {
  await Preferences.set({
    key: 'auth_session',
    value: JSON.stringify(session)
  });
}
```

#### Production Standard (Correct)
> **Standard**: Implements envelope encryption where the payload is encrypted using AES-GCM-256, and the DEK is wrapped by a hardware-backed Secure Enclave key configured with strict biometric access controls. Cold-boot and root compromises cannot decrypt the payload without triggering the hardware biometric enclave.
```typescript
import { SecureStoragePlugin } from './plugins/secure-storage';

interface SessionState {
  accessToken: string;
  refreshToken: string;
}

// PRODUCTION FIX: Envelope encryption backed by Secure Enclave / Android StrongBox KeyStore.
// The session payload is encrypted with an ephemeral AES-GCM-256 DEK, which is wrapped
// by a platform hardware key gated by biometrics (biometryCurrentSet / userAuthenticationRequired).
export async function persistSessionSecurely(session: SessionState): Promise<void> {
  const payload = new TextEncoder().encode(JSON.stringify(session));
  
  // Generate ephemeral 256-bit DEK
  const dek = crypto.getRandomValues(new Uint8Array(32));
  const iv = crypto.getRandomValues(new Uint8Array(12));
  
  const importedKey = await crypto.subtle.importKey(
    'raw',
    dek,
    { name: 'AES-GCM' },
    false,
    ['encrypt']
  );

  const encryptedPayload = await crypto.subtle.encrypt(
    { name: 'AES-GCM', iv },
    importedKey,
    payload
  );

  // Delegate wrapping the DEK to native Secure Enclave / StrongBox with biometric requirement
  const wrappedDek = await SecureStoragePlugin.wrapKeyWithHardwareEnclave({
    rawKeyBase64: btoa(String.fromCharCode(...dek)),
    accessControl: 'biometryCurrentSet',
    requireStrongBox: true
  });

  // Securely persist only ciphertext, wrapped key, and initialization vector
  await SecureStoragePlugin.persistEncryptedBlob({
    wrappedDek: wrappedDek.cipherText,
    iv: btoa(String.fromCharCode(...iv)),
    cipherText: btoa(String.fromCharCode(...new Uint8Array(encryptedPayload)))
  });

  // Zero-out sensitive key material in memory
  dek.fill(0);
}
```

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 Secure Enclave Biometric Key Wrapping Standard

Capacitor 7 Hardware-Backed Secure Enclave Biometric Key Wrapping Standard defines an industrial-grade behavioral standard for mobile engineering. Enforces hardware-backed cryptographic envelope encryption for all persisted mobile session state and sensitive credentials in Capacitor 7 applications. Session keys must be wrapped using Key Encryption Keys (KEKs) bound directly to the Apple Secure Enclave or Android StrongBox KeyStore with biometric authentication gating, preventing offline token extraction via cold-boot or root exploits. 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 authentication tokens or encryption keys in Capacitor Preferences, UserDefaults, or unauthenticated Keychains 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 authentication tokens or encryption keys in Capacitor Preferences, UserDefaults, or unauthenticated KeychainsCritical
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 use envelope encryption

Engineers MUST ALWAYS use envelope encryption: a high-entropy Data Encryption Key (DEK) encrypts local payloads via AES-256-GCM, and the DEK is wrapped by a hardware-backed Key Encryption Key (KEK).

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 configure KEK generation within the platform's hardware security module (Secure Enclave on iOS via kSecAttrTokenIDSecureEnclave, StrongBox or TEE on Android KeyStore).

Engineers MUST configure KEK generation within the platform's hardware security module (Secure Enclave on iOS via kSecAttrTokenIDSecureEnclave, StrongBox or TEE on Android KeyStore).

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 require explicit biometric authentication flags on the KEK

Engineers MUST require explicit biometric authentication flags on the KEK: 'kSecAccessControlBiometryCurrentSet' on iOS and 'setUserAuthenticationRequired(true)' with 'setInvalidatedByBiometricEnrollment(true)' on Android.

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

Engineers MUST NOT store raw JWTs, refresh tokens, encryption keys, or sensitive PII in '@capacitor/preferences', localStorage, sessionStorage, or unencrypted SQLite/IndexedDB.

Engineers MUST NOT store raw JWTs, refresh tokens, encryption keys, or sensitive PII in '@capacitor/preferences', localStorage, sessionStorage, or unencrypted SQLite/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.
5

Services MUST clear decrypted DEKs and plaintext session state from memory immediately after execution or when the application enters the background.

Services MUST clear decrypted DEKs and plaintext session state from memory immediately after execution or when the application enters 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.
6

Components NEVER directly invoke storage calls without handling biometric failure, hardware-absence, cancellation, and key invalidation exceptions gracefully.

Components NEVER directly invoke storage calls without handling biometric failure, hardware-absence, cancellation, and key invalidation exceptions gracefully.

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 Secure Enclave Biometric Key Wrapping Standard critical for AI coding assistants?

Enforces hardware-backed cryptographic envelope encryption for all persisted mobile session state and sensitive credentials in Capacitor 7 applications. Session keys must be wrapped using Key Encryption Keys (KEKs) bound directly to the Apple Secure Enclave or Android StrongBox KeyStore with biometric authentication gating, preventing offline token extraction via cold-boot or root exploits. 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 authentication tokens or encryption keys in Capacitor Preferences, UserDefaults, or unauthenticated Keychains) 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