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

Hardware-Backed WebAuthn PRF Key Derivation and Zero-Knowledge Storage Standard

Mandates that cryptographic master keys derived via WebAuthn PRF (Pseudo-Random Function) extensions in Capacitor 7 applications remain strictly ephemeral, zero-knowledge, and memory-isolated. Prohibits persistence of raw PRF outputs, enforces cryptographically separated HKDF key derivation, and mandates explicit in-memory zeroization of raw key material to secure offline storage.

Prohibited Anti-Pattern: Persisting Raw PRF Outputs or Leaking Unwiped Key Buffers into Capacitor Storage

Export Ready-to-Drop Configuration

Select format below to copy code or download file directly.

---
description: Hardware-Backed WebAuthn PRF Key Derivation and Zero-Knowledge Storage Standard - Mandates that cryptographic master keys derived via WebAuthn PRF (Pseudo-Random Function) extensions in Capacitor 7 applications remain strictly ephemeral, zero-knowledge, and memory-isolated. Prohibits persistence of raw PRF outputs, enforces cryptographically separated HKDF key derivation, and mandates explicit in-memory zeroization of raw key material to secure offline storage.
globs: src/**/*.{ts,tsx}, src/crypto/**/*.{ts,tsx}, src/security/**/*.{ts,tsx}, src/vault/**/*.{ts,tsx}
alwaysApply: true
verified_by: "agentrules.org"
license: "CC-BY-4.0"
source: "https://agentrules.org/rules/capacitor7-webauthn-prf-secure-vault-guardrail"
---

# Hardware-Backed WebAuthn PRF Key Derivation and Zero-Knowledge Storage Standard

> **Severity**: CRITICAL | **Category**: mobile
> **Anti-Pattern Warning**: Persisting Raw PRF Outputs or Leaking Unwiped Key Buffers into Capacitor Storage

## System Constraints
You are a Principal Mobile Security Architect enforcing zero-knowledge hardware-backed security via WebAuthn PRF in Capacitor 7 applications. You must enforce that all encryption keys derived from biometric authenticators via WebAuthn PRF (hmac-secret) are non-extractable CryptoKeys or wiped immediately from memory using in-place zeroization. Raw PRF outputs, master seeds, and unwiped key buffers MUST NEVER be stored in Capacitor Preferences, SQLite, filesystem, or plain IndexedDB.

## Strict Guidelines
- Engineers MUST ALWAYS verify authenticator PRF extension support (`results.first` from `extensions.prf`) and fail closed if the hardware authenticator does not support the PRF extension.
- Engineers MUST NOT persist raw PRF evaluation outputs, intermediate entropy, or raw symmetric keys to any persistent device storage (Capacitor Preferences, SQLite, IndexedDB, or local filesystem).
- Code MUST derive operational encryption keys (e.g., AES-GCM-256) from PRF output using HKDF (RFC 5869) with a domain-separated, unique application salt and context string (info parameter).
- Services MUST execute explicit in-memory zeroization (`new Uint8Array(buffer).fill(0)`) on all mutable ArrayBuffers and TypedArrays containing raw PRF outputs inside a mandatory `finally` block.
- Components NEVER hold unencrypted sensitive vault data or operational CryptoKeys in global window state, Vue/React reactive state, or persistent stores longer than the active UI execution lifecycle.

## Bad vs Good Implementations
### Hardware-Backed PRF Key Derivation with HKDF and In-Memory Buffer Zeroization

#### Bad Antipattern (AI Common Hallucination)
> **Why it fails**: The code extracts the PRF raw output and persists it directly into Capacitor Preferences (unencrypted Android SharedPreferences or iOS NSUserDefaults). It also leaves raw cryptographic entropy exposed in garbage-collected memory without zeroization, allowing offline root extraction.
```typescript
import { Preferences } from '@capacitor/preferences';

export async function unlockVault(credentialId: Uint8Array, salt: Uint8Array) {
  // Anti-Pattern: Calling WebAuthn PRF and saving raw output directly to persistent preferences
  const assertion = (await navigator.credentials.get({
    publicKey: {
      challenge: crypto.getRandomValues(new Uint8Array(32)),
      allowCredentials: [{ id: credentialId, type: 'public-key' }],
      extensions: {
        prf: {
          eval: { first: salt }
        }
      }
    }
  })) as PublicKeyCredential;

  const results = assertion.getClientExtensionResults() as any;
  const prfRaw = results.prf?.results?.first;

  // CRITICAL VULNERABILITY: Storing raw derived PRF secret into persistent Capacitor storage
  const base64Key = btoa(String.fromCharCode(...new Uint8Array(prfRaw)));
  await Preferences.set({ key: 'master_vault_key', value: base64Key });

  return prfRaw;
}
```

#### Production Standard (Correct)
> **Standard**: Verifies hardware PRF extension support, imports PRF entropy strictly as HKDF Input Keying Material, derives a non-extractable AES-GCM-256 CryptoKey using domain separation, and guarantees explicit zeroization of the raw PRF buffer in a `finally` block before returning.
```typescript
export interface DerivedVaultKey {
  readonly cipherKey: CryptoKey;
}

export async function deriveVaultKeyWithPrf(
  credentialId: Uint8Array,
  prfSalt: Uint8Array,
  hkdfInfoContext: Uint8Array
): Promise<DerivedVaultKey> {
  const assertion = (await navigator.credentials.get({
    publicKey: {
      challenge: crypto.getRandomValues(new Uint8Array(32)),
      allowCredentials: [{ id: credentialId, type: 'public-key' }],
      userVerification: 'required',
      extensions: {
        prf: {
          eval: { first: prfSalt }
        }
      }
    }
  })) as PublicKeyCredential | null;

  if (!assertion) {
    throw new Error('Biometric assertion rejected by user or hardware.');
  }

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

  const rawPrfBuffer = extensionOutputs.prf?.results?.first;
  if (!rawPrfBuffer) {
    throw new Error('Authenticator does not support hardware PRF extension.');
  }

  const rawPrfView = new Uint8Array(rawPrfBuffer);
  try {
    // Import PRF output as raw IKM (Input Keying Material) for HKDF
    const ikmKey = await crypto.subtle.importKey(
      'raw',
      rawPrfView,
      'HKDF',
      false,
      ['deriveKey']
    );

    // Derive an unexportable AES-GCM-256 key scoped only to encryption/decryption
    const cipherKey = await crypto.subtle.deriveKey(
      {
        name: 'HKDF',
        hash: 'SHA-256',
        salt: prfSalt,
        info: hkdfInfoContext
      },
      ikmKey,
      { name: 'AES-GCM', length: 256 },
      false, // non-extractable
      ['encrypt', 'decrypt']
    );

    return { cipherKey };
  } finally {
    // INVARIANT: Explicitly zeroize mutable raw PRF buffer from memory
    rawPrfView.fill(0);
  }
}
```

Architectural Specification & Invariant Rationale

Architectural Invariant Design: Hardware-Backed WebAuthn PRF Key Derivation and Zero-Knowledge Storage Standard

Hardware-Backed WebAuthn PRF Key Derivation and Zero-Knowledge Storage Standard defines an industrial-grade behavioral standard for mobile engineering. Mandates that cryptographic master keys derived via WebAuthn PRF (Pseudo-Random Function) extensions in Capacitor 7 applications remain strictly ephemeral, zero-knowledge, and memory-isolated. Prohibits persistence of raw PRF outputs, enforces cryptographically separated HKDF key derivation, and mandates explicit in-memory zeroization of raw key material to secure offline storage. 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 PRF Outputs or Leaking Unwiped Key Buffers into Capacitor 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 DriftPersisting Raw PRF Outputs or Leaking Unwiped Key Buffers into Capacitor 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 verify authenticator PRF extension support (`results.first` from `extensions.prf`) and fail closed if the hardware authenticator does not support the PRF extension.

Engineers MUST ALWAYS verify authenticator PRF extension support (`results.first` from `extensions.prf`) and fail closed if the hardware authenticator does not support the PRF extension.

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 raw PRF evaluation outputs, intermediate entropy, or raw symmetric keys to any persistent device storage (Capacitor Preferences, SQLite, IndexedDB, or local filesystem).

Engineers MUST NOT persist raw PRF evaluation outputs, intermediate entropy, or raw symmetric keys to any persistent device storage (Capacitor Preferences, SQLite, IndexedDB, or local filesystem).

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 derive operational encryption keys (e.g., AES-GCM-256) from PRF output using HKDF (RFC 5869) with a domain-separated, unique application salt and context string (info parameter).

Code MUST derive operational encryption keys (e.g., AES-GCM-256) from PRF output using HKDF (RFC 5869) with a domain-separated, unique application salt and context string (info parameter).

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 execute explicit in-memory zeroization (`new Uint8Array(buffer).fill(0)`) on all mutable ArrayBuffers and TypedArrays containing raw PRF outputs inside a mandatory `finally` block.

Services MUST execute explicit in-memory zeroization (`new Uint8Array(buffer).fill(0)`) on all mutable ArrayBuffers and TypedArrays containing raw PRF outputs inside a mandatory `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.
5

Components NEVER hold unencrypted sensitive vault data or operational CryptoKeys in global window state, Vue/React reactive state, or persistent stores longer than the active UI execution lifecycle.

Components NEVER hold unencrypted sensitive vault data or operational CryptoKeys in global window state, Vue/React reactive state, or persistent stores longer than the active UI execution 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 Hardware-Backed WebAuthn PRF Key Derivation and Zero-Knowledge Storage Standard critical for AI coding assistants?

Mandates that cryptographic master keys derived via WebAuthn PRF (Pseudo-Random Function) extensions in Capacitor 7 applications remain strictly ephemeral, zero-knowledge, and memory-isolated. Prohibits persistence of raw PRF outputs, enforces cryptographically separated HKDF key derivation, and mandates explicit in-memory zeroization of raw key material to secure offline storage. 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 PRF Outputs or Leaking Unwiped Key Buffers into Capacitor 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

Hardware-Backed