This specification is maintained by the AgentRules Working Group. Have enhancements or want to claim maintainership?Submit Specification →
mobilecritical PriorityID: capacitor7-secure-enclave-webauthn-zero-seed-storage

Capacitor 7 Hardware-Backed Secure Enclave Biometric Key Zero-Storage Invariant

Enforces hardware-backed WebAuthn and passkey attestation synchronization strictly across native platform boundaries without exposing or persisting cryptographic seeds in WebKit or Chromium storage. Ensures that private key operations remain strictly confined to the Apple Secure Enclave and Android StrongBox/KeyStore, with zero intermediate key material crossing into webview-managed memory or storage engines.

Prohibited Anti-Pattern: Persisting Cryptographic Seeds, Ephemeral Keypairs, or Private Keys in Webview Storage Layers

Export Ready-to-Drop Configuration

Select format below to copy code or download file directly.

---
description: Capacitor 7 Hardware-Backed Secure Enclave Biometric Key Zero-Storage Invariant - Enforces hardware-backed WebAuthn and passkey attestation synchronization strictly across native platform boundaries without exposing or persisting cryptographic seeds in WebKit or Chromium storage. Ensures that private key operations remain strictly confined to the Apple Secure Enclave and Android StrongBox/KeyStore, with zero intermediate key material crossing into webview-managed memory or storage engines.
globs: src/**/*.{ts,tsx}, android/app/src/main/java/**/*.java, ios/App/App/**/*.swift
alwaysApply: true
verified_by: "agentrules.org"
license: "CC-BY-4.0"
source: "https://agentrules.org/rules/capacitor7-secure-enclave-webauthn-zero-seed-storage"
---

# Capacitor 7 Hardware-Backed Secure Enclave Biometric Key Zero-Storage Invariant

> **Severity**: CRITICAL | **Category**: mobile
> **Anti-Pattern Warning**: Persisting Cryptographic Seeds, Ephemeral Keypairs, or Private Keys in Webview Storage Layers

## System Constraints
You are a Principal Mobile Security Architect enforcing strict cryptographic boundaries in Capacitor 7 applications. You must mandate that hardware-backed asymmetric keys and WebAuthn attestations are confined to the Apple Secure Enclave and Android StrongBox/KeyStore. Strictly prevent any persistence, caching, or serialization of raw keys, seeds, or intermediate credentials within the webview boundary (localStorage, sessionStorage, IndexedDB, or in-memory global singletons).

## Strict Guidelines
- Engineers MUST ALWAYS delegate cryptographic key generation and signing directly to native platform plugins implementing Apple Secure Enclave (kSecAttrAccessControl) and Android KeyStore (StrongBox/TEE).
- Engineers MUST NOT persist, serialize, or cache intermediate cryptographic seeds, mnemonic strings, or private key material in localStorage, sessionStorage, IndexedDB, or webview cookies.
- Services MUST route backend WebAuthn challenges directly to native credential APIs (ASAuthorizationPlatformPublicKeyCredentialProvider / CredentialManager) and return only signed attestation/assertion objects to JavaScript.
- Components NEVER store persistent key references beyond the public credential ID string necessary to target the enclave key for subsequent signing operations.
- Code SHOULD enforce byte scrubbing on ArrayBuffers or TypedArrays holding server challenges immediately after native bridge execution completes.

## Bad vs Good Implementations
### Insecure Client-Side Seed Generation Stored in Web Storage vs Native Secure Enclave Passkey Bridge

#### Bad Antipattern (AI Common Hallucination)
> **Why it fails**: Generating cryptographic seeds within the JavaScript execution context and persisting them in window.localStorage completely violates hardware enclave invariants. Webview storage is vulnerable to XSS extraction, unencrypted backup inclusion, and local sandbox compromise. Raw private key material must never be generated in or exposed to JavaScript.
```typescript
import { Plugins } from '@capacitor/core';

interface KeyRegistrationPayload {
  userId: string;
  seed: string;
}

export async function registerBiometricKey(userId: string, challenge: string): Promise<void> {
  // ANTI-PATTERN: Generating cryptographic key material inside WebKit JS runtime
  const ephemeralSeed = window.crypto.getRandomValues(new Uint8Array(32));
  const seedHex = Array.from(ephemeralSeed).map(b => b.toString(16).padStart(2, '0')).join('');

  // CRITICAL VULNERABILITY: Storing raw seed in WebView LocalStorage
  localStorage.setItem(`device_seed_${userId}`, seedHex);

  // Attempting to synchronize key with backend through web layer
  await fetch('/api/auth/register-biometric', {
    method: 'POST',
    headers: { 'Content-Type': 'application/json' },
    body: JSON.stringify({ userId, seed: seedHex, challenge })
  });
}
```

#### Production Standard (Correct)
> **Standard**: Delegates cryptographic operations entirely to native Secure Enclave / StrongBox via Capacitor 7 plugin APIs. The private key never leaves native hardware, zero seeds are exposed or persisted in webview storage, and only the hardware-signed attestation statement is relayed to the authentication backend.
```typescript
import { registerPlugin } from '@capacitor/core';

export interface EnclaveWebAuthnPlugin {
  registerCredential(options: {
    challengeBase64: string;
    userIdBase64: string;
    userName: string;
    rpId: string;
  }): Promise<{
    credentialId: string;
    attestationObjectBase64: string;
    clientDataBase64: string;
  }>;
}

const EnclaveWebAuthn = registerPlugin<EnclaveWebAuthnPlugin>('EnclaveWebAuthn');

export async function registerBiometricKey(userId: string, challenge: string): Promise<string> {
  // INVARIANT FIX: Native bridge invokes Secure Enclave / KeyStore directly.
  // Challenge is passed without intermediate private seeds ever entering webview memory.
  const attestationResult = await EnclaveWebAuthn.registerCredential({
    challengeBase64: challenge,
    userIdBase64: btoa(userId),
    userName: userId,
    rpId: window.location.hostname
  });

  // Synchronize ONLY attestation data and public credential ID with backend
  const response = await fetch('/api/auth/register-attestation', {
    method: 'POST',
    headers: { 'Content-Type': 'application/json' },
    body: JSON.stringify({
      credentialId: attestationResult.credentialId,
      attestationObject: attestationResult.attestationObjectBase64,
      clientDataJSON: attestationResult.clientDataBase64
    })
  });

  if (!response.ok) {
    throw new Error('WebAuthn attestation verification failed on server');
  }

  // Only return public identifier; private key remains locked in hardware silicon
  return attestationResult.credentialId;
}
```

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 Zero-Storage Invariant

Capacitor 7 Hardware-Backed Secure Enclave Biometric Key Zero-Storage Invariant defines an industrial-grade behavioral standard for mobile engineering. Enforces hardware-backed WebAuthn and passkey attestation synchronization strictly across native platform boundaries without exposing or persisting cryptographic seeds in WebKit or Chromium storage. Ensures that private key operations remain strictly confined to the Apple Secure Enclave and Android StrongBox/KeyStore, with zero intermediate key material crossing into webview-managed memory or storage engines. 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 Cryptographic Seeds, Ephemeral Keypairs, or Private Keys in Webview Storage Layers 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 Cryptographic Seeds, Ephemeral Keypairs, or Private Keys in Webview Storage LayersCritical
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 delegate cryptographic key generation and signing directly to native platform plugins implementing Apple Secure Enclave (kSecAttrAccessControl) and Android KeyStore (StrongBox/TEE).

Engineers MUST ALWAYS delegate cryptographic key generation and signing directly to native platform plugins implementing Apple Secure Enclave (kSecAttrAccessControl) and Android KeyStore (StrongBox/TEE).

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, serialize, or cache intermediate cryptographic seeds, mnemonic strings, or private key material in localStorage, sessionStorage, IndexedDB, or webview cookies.

Engineers MUST NOT persist, serialize, or cache intermediate cryptographic seeds, mnemonic strings, or private key material in localStorage, sessionStorage, IndexedDB, or webview cookies.

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 route backend WebAuthn challenges directly to native credential APIs (ASAuthorizationPlatformPublicKeyCredentialProvider / CredentialManager) and return only signed attestation/assertion objects to JavaScript.

Services MUST route backend WebAuthn challenges directly to native credential APIs (ASAuthorizationPlatformPublicKeyCredentialProvider / CredentialManager) and return only signed attestation/assertion objects to JavaScript.

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

Components NEVER store persistent key references beyond the public credential ID string necessary to target the enclave key for subsequent signing operations.

Components NEVER store persistent key references beyond the public credential ID string necessary to target the enclave key for subsequent signing 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.
5

Code SHOULD enforce byte scrubbing on ArrayBuffers or TypedArrays holding server challenges immediately after native bridge execution completes.

Code SHOULD enforce byte scrubbing on ArrayBuffers or TypedArrays holding server challenges immediately after native bridge execution completes.

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 Zero-Storage Invariant critical for AI coding assistants?

Enforces hardware-backed WebAuthn and passkey attestation synchronization strictly across native platform boundaries without exposing or persisting cryptographic seeds in WebKit or Chromium storage. Ensures that private key operations remain strictly confined to the Apple Secure Enclave and Android StrongBox/KeyStore, with zero intermediate key material crossing into webview-managed memory or storage engines. 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 Cryptographic Seeds, Ephemeral Keypairs, or Private Keys in Webview Storage Layers) 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