This specification is maintained by the AgentRules Working Group. Have enhancements or want to claim maintainership?Submit Specification →
mobilecritical PriorityID: capacitor-7-webauthn-prf-vault-cryptography

Capacitor 7 Hardware-Derived WebAuthn PRF Vault Cryptography Standard

Mandates hardware-bound client-side cryptographic vault operations in Capacitor 7 using the WebAuthn PRF (Pseudo-Random Function) extension. Eliminates persistent symmetric master keys by deriving non-extractable CryptoKey instances on-demand via hardware authenticators (iOS Secure Enclave and Android Keystore passkeys) combined with HKDF key stretching.

Prohibited Anti-Pattern: Persisting Static Symmetric Keys in Local Storage or Directly Exposing Raw PRF Buffers without HKDF Expansion and Buffer Zeroization

Export Ready-to-Drop Configuration

Select format below to copy code or download file directly.

---
description: Capacitor 7 Hardware-Derived WebAuthn PRF Vault Cryptography Standard - Mandates hardware-bound client-side cryptographic vault operations in Capacitor 7 using the WebAuthn PRF (Pseudo-Random Function) extension. Eliminates persistent symmetric master keys by deriving non-extractable CryptoKey instances on-demand via hardware authenticators (iOS Secure Enclave and Android Keystore passkeys) combined with HKDF key stretching.
globs: src/vault/**/*.{ts,tsx}, src/crypto/**/*.{ts,tsx}, src/services/**/*.{ts,tsx}, src/security/**/*.{ts,tsx}
alwaysApply: true
verified_by: "agentrules.org"
license: "CC-BY-4.0"
source: "https://agentrules.org/rules/capacitor-7-webauthn-prf-vault-cryptography"
---

# Capacitor 7 Hardware-Derived WebAuthn PRF Vault Cryptography Standard

> **Severity**: CRITICAL | **Category**: mobile
> **Anti-Pattern Warning**: Persisting Static Symmetric Keys in Local Storage or Directly Exposing Raw PRF Buffers without HKDF Expansion and Buffer Zeroization

## System Constraints
You are a Principal Mobile Cryptography Engineer enforcing the Capacitor 7 WebAuthn PRF Hardware-Derived Vault Cryptography Standard. Enforce zero persistent raw key storage across all mobile platforms. Mandate that all symmetric key material is dynamically derived from FIDO2/WebAuthn Level 3 PRF (Pseudo-Random Function) extensions via platform authenticators (Secure Enclave, StrongBox). Keys must be imported as non-extractable WebCrypto CryptoKey objects stretched via HKDF-SHA-256 before performing AES-256-GCM operations. All intermediate ArrayBuffers and TypedArrays containing raw entropy or plaintext MUST be zeroized immediately after consumption.

## Strict Guidelines
- Engineers MUST ALWAYS verify platform authenticator PRF extension support using PublicKeyCredential.getClientCapabilities() or credential creation evaluation before initiating vault initialization.
- Engineers MUST NEVER persist raw symmetric keys, intermediate PRF seed outputs, or unencrypted vault material in @capacitor/preferences, localStorage, IndexedDB, or filesystem storage.
- Engineers MUST treat WebAuthn PRF outputs as high-entropy input key material (IKM) and pass them through HKDF (HMAC-based Extract-and-Expand Key Derivation Function, RFC 5869) using SHA-256 with a unique context info string before deriving the operational AES-256-GCM key.
- Keys derived via crypto.subtle.deriveKey MUST specify { extractable: false } to prevent memory-dump extraction attacks from webview inspectors or compromised dependencies.
- Engineers MUST explicitly zeroize (using .fill(0)) all sensitive Uint8Array buffers (intermediate PRF results, plaintext buffers, HKDF salts) immediately after use in a finally block.
- Services MUST generate cryptographically secure 96-bit (12-byte) initialization vectors (IVs) for each individual AES-256-GCM encryption operation using crypto.getRandomValues(). IVs MUST NEVER be reused.
- Components NEVER hold decrypted vault records in persistent state, singletons, or global stores longer than necessary for the immediate rendering lifecycle.

## Bad vs Good Implementations
### Hardware PRF Vault Key Derivation and Decryption

#### Bad Antipattern (AI Common Hallucination)
> **Why it fails**: The anti-pattern persists the raw cryptographic key material into @capacitor/preferences, uses raw PRF output directly as an AES key without proper HKDF key expansion, imports the key as extractable: true, reuses a weak static salt, and fails to zeroize sensitive byte arrays in memory.
```typescript
import { Preferences } from '@capacitor/preferences';

// ANTI-PATTERN: Storing static symmetric keys or raw PRF output directly in preferences or extracting raw key material
export async function decryptVaultBad(encryptedPayload: string, credentialIdBase64: string): Promise<string> {
  // Flaw 1: Reading stored static key or persisting derived master key directly
  const storedKey = await Preferences.get({ key: 'vault_master_key' });
  if (storedKey.value) {
    return decryptWithKey(storedKey.value, encryptedPayload);
  }

  // Flaw 2: Using raw PRF output directly as AES key without HKDF expansion
  const credential = (await navigator.credentials.get({
    publicKey: {
      challenge: new Uint8Array(32),
      allowCredentials: [{
        id: Uint8Array.from(atob(credentialIdBase64), c => c.charCodeAt(0)),
        type: 'public-key'
      }],
      extensions: {
        prf: {
          eval: {
            first: new TextEncoder().encode('insecure-static-salt')
          }
        }
      } as any
    }
  })) as any;

  const prfExtension = credential.getClientExtensionResults().prf;
  const rawPrfKey = new Uint8Array(prfExtension.results.first);

  // Flaw 3: Key is marked extractable: true and raw bytes linger in memory
  const cryptoKey = await crypto.subtle.importKey(
    'raw',
    rawPrfKey,
    { name: 'AES-GCM' },
    true,
    ['decrypt']
  );

  // Flaw 4: No zeroization of rawPrfKey buffer
  await Preferences.set({ key: 'vault_master_key', value: btoa(String.fromCharCode(...rawPrfKey)) });

  return 'insecure-decrypted-value';
}

function decryptWithKey(key: string, data: string): string {
  return 'unimplemented';
}
```

#### Production Standard (Correct)
> **Standard**: The production implementation derives an AES-256-GCM key on demand using WebAuthn PRF combined with HKDF key stretching. The derived key is imported with extractable: false to prevent memory leakage. No symmetric keys are ever persisted to disk or webview storage, and all raw entropy buffers are zeroized in a finally block.
```typescript
export interface EncryptedVaultEnvelope {
  ciphertext: Uint8Array;
  iv: Uint8Array;
  authTagLengthBits?: number; // Defaults to 128
}

export async function decryptVaultRecord(
  envelope: EncryptedVaultEnvelope,
  credentialId: Uint8Array,
  hkdfSalt: Uint8Array,
  infoContext: string
): Promise<Uint8Array> {
  // 1. Evaluate WebAuthn PRF extension via platform authenticator
  const assertion = (await navigator.credentials.get({
    publicKey: {
      challenge: crypto.getRandomValues(new Uint8Array(32)),
      allowCredentials: [{
        id: credentialId,
        type: 'public-key',
        transports: ['internal']
      }],
      userVerification: 'required',
      extensions: {
        prf: {
          eval: {
            first: hkdfSalt
          }
        }
      } as AuthenticationExtensionsClientInputs
    }
  })) as PublicKeyCredential | null;

  if (!assertion) {
    throw new Error('WebAuthn assertion failed or was cancelled by user');
  }

  const extensionResults = assertion.getClientExtensionResults() as AuthenticationExtensionsClientOutputs & {
    prf?: { results?: { first?: ArrayBuffer } };
  };

  const rawPrfBuffer = extensionResults.prf?.results?.first;
  if (!rawPrfBuffer) {
    throw new Error('Authenticator did not return PRF output');
  }

  const prfBytes = new Uint8Array(rawPrfBuffer);
  const infoBytes = new TextEncoder().encode(infoContext);

  try {
    // 2. Import PRF output as non-extractable HKDF master key material (IKM)
    const hkdfKey = await crypto.subtle.importKey(
      'raw',
      prfBytes,
      { name: 'HKDF' },
      false,
      ['deriveKey']
    );

    // 3. Derive non-extractable AES-256-GCM operational key via HKDF-SHA-256
    const aesKey = await crypto.subtle.deriveKey(
      {
        name: 'HKDF',
        hash: 'SHA-256',
        salt: hkdfSalt,
        info: infoBytes
      },
      hkdfKey,
      { name: 'AES-GCM', length: 256 },
      false,
      ['decrypt']
    );

    // 4. Perform AES-256-GCM authenticated decryption
    const decrypted = await crypto.subtle.decrypt(
      {
        name: 'AES-GCM',
        iv: envelope.iv,
        tagLength: envelope.authTagLengthBits ?? 128
      },
      aesKey,
      envelope.ciphertext
    );

    return new Uint8Array(decrypted);
  } finally {
    // 5. Zeroize raw intermediate buffers immediately
    prfBytes.fill(0);
  }
}
```

Architectural Specification & Invariant Rationale

Architectural Invariant Design: Capacitor 7 Hardware-Derived WebAuthn PRF Vault Cryptography Standard

Capacitor 7 Hardware-Derived WebAuthn PRF Vault Cryptography Standard defines an industrial-grade behavioral standard for mobile engineering. Mandates hardware-bound client-side cryptographic vault operations in Capacitor 7 using the WebAuthn PRF (Pseudo-Random Function) extension. Eliminates persistent symmetric master keys by deriving non-extractable CryptoKey instances on-demand via hardware authenticators (iOS Secure Enclave and Android Keystore passkeys) combined with HKDF key stretching. 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 Static Symmetric Keys in Local Storage or Directly Exposing Raw PRF Buffers without HKDF Expansion and Buffer Zeroization 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 Static Symmetric Keys in Local Storage or Directly Exposing Raw PRF Buffers without HKDF Expansion and Buffer ZeroizationCritical
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 verify platform authenticator PRF extension support using PublicKeyCredential.getClientCapabilities() or credential creation evaluation before initiating vault initialization.

Engineers MUST ALWAYS verify platform authenticator PRF extension support using PublicKeyCredential.getClientCapabilities() or credential creation evaluation before initiating vault initialization.

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 NEVER persist raw symmetric keys, intermediate PRF seed outputs, or unencrypted vault material in @capacitor/preferences, localStorage, IndexedDB, or filesystem storage.

Engineers MUST NEVER persist raw symmetric keys, intermediate PRF seed outputs, or unencrypted vault material in @capacitor/preferences, localStorage, IndexedDB, or filesystem storage.

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 treat WebAuthn PRF outputs as high-entropy input key material (IKM) and pass them through HKDF (HMAC-based Extract-and-Expand Key Derivation Function, RFC 5869) using SHA-256 with a unique context info string before deriving the operational AES-256-GCM key.

Engineers MUST treat WebAuthn PRF outputs as high-entropy input key material (IKM) and pass them through HKDF (HMAC-based Extract-and-Expand Key Derivation Function, RFC 5869) using SHA-256 with a unique context info string before deriving the operational AES-256-GCM key.

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

Keys derived via crypto.subtle.deriveKey MUST specify { extractable

Keys derived via crypto.subtle.deriveKey MUST specify { extractable: false } to prevent memory-dump extraction attacks from webview inspectors or compromised dependencies.

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

Engineers MUST explicitly zeroize (using .fill(0)) all sensitive Uint8Array buffers (intermediate PRF results, plaintext buffers, HKDF salts) immediately after use in a finally block.

Engineers MUST explicitly zeroize (using .fill(0)) all sensitive Uint8Array buffers (intermediate PRF results, plaintext buffers, HKDF salts) immediately after use in a finally block.

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

Services MUST generate cryptographically secure 96-bit (12-byte) initialization vectors (IVs) for each individual AES-256-GCM encryption operation using crypto.getRandomValues(). IVs MUST NEVER be reused.

Services MUST generate cryptographically secure 96-bit (12-byte) initialization vectors (IVs) for each individual AES-256-GCM encryption operation using crypto.getRandomValues(). IVs MUST NEVER be reused.

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.
7

Components NEVER hold decrypted vault records in persistent state, singletons, or global stores longer than necessary for the immediate rendering lifecycle.

Components NEVER hold decrypted vault records in persistent state, singletons, or global stores longer than necessary for the immediate rendering lifecycle.

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-Derived WebAuthn PRF Vault Cryptography Standard critical for AI coding assistants?

Mandates hardware-bound client-side cryptographic vault operations in Capacitor 7 using the WebAuthn PRF (Pseudo-Random Function) extension. Eliminates persistent symmetric master keys by deriving non-extractable CryptoKey instances on-demand via hardware authenticators (iOS Secure Enclave and Android Keystore passkeys) combined with HKDF key stretching. 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 Static Symmetric Keys in Local Storage or Directly Exposing Raw PRF Buffers without HKDF Expansion and Buffer Zeroization) 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