This specification is maintained by the AgentRules Working Group. Have enhancements or want to claim maintainership?Submit Specification →
securitycritical PriorityID: webauthn-prf-symmetric-key-derivation-guardrail

WebAuthn Level 3 PRF Hardware-Backed Symmetric Key Derivation Guardrail

Enforces hardware-backed zero-knowledge credential derivation using WebAuthn Level 3 PRF (Pseudo-Random Function) extension for client-side encrypted database synchronization. Mandates using constant-time cryptographic operations, HKDF key stretching with ephemeral salts, zero-allocation memory zeroing, and strict validation of authenticator PRF outputs prior to master key reconstruction.

Prohibited Anti-Pattern: Persisting Unsalted PRF Outputs or Deriving Database Encryption Keys in Extractable Non-Wiped Client Memory

Export Ready-to-Drop Configuration

Select format below to copy code or download file directly.

---
description: WebAuthn Level 3 PRF Hardware-Backed Symmetric Key Derivation Guardrail - Enforces hardware-backed zero-knowledge credential derivation using WebAuthn Level 3 PRF (Pseudo-Random Function) extension for client-side encrypted database synchronization. Mandates using constant-time cryptographic operations, HKDF key stretching with ephemeral salts, zero-allocation memory zeroing, and strict validation of authenticator PRF outputs prior to master key reconstruction.
globs: src/crypto/**/*.{ts,tsx}, src/auth/**/*.{ts,tsx}, src/storage/sync/**/*.{ts,tsx}, src/lib/security/**/*.{ts,tsx}
alwaysApply: true
verified_by: "agentrules.org"
license: "CC-BY-4.0"
source: "https://agentrules.org/rules/webauthn-prf-symmetric-key-derivation-guardrail"
---

# WebAuthn Level 3 PRF Hardware-Backed Symmetric Key Derivation Guardrail

> **Severity**: CRITICAL | **Category**: security
> **Anti-Pattern Warning**: Persisting Unsalted PRF Outputs or Deriving Database Encryption Keys in Extractable Non-Wiped Client Memory

## System Constraints
You are a Principal Security Engineer enforcing strict WebAuthn Level 3 PRF (Pseudo-Random Function) symmetric key derivation standards. You must ensure all client-side encrypted sync engines isolate key material from web storage, enforce non-extractable CryptoKey usage, perform HKDF key expansion over hardware-evaluated PRF outputs, and scrub plaintext byte buffers immediately following key derivation.

## Strict Guidelines
- Engineers MUST ALWAYS verify navigator.credentials.get() returns `authenticatorData` with extension results containing a defined `prf.results.first` buffer prior to key derivation.
- Engineers MUST ALWAYS pass the raw PRF output through HKDF (HMAC-based Extract-and-Expand Key Derivation Function) using SHA-256 and a distinct domain-separated info parameter before using it as a database encryption key (DEK) or key encryption key (KEK).
- Engineers MUST NOT store raw PRF output or intermediate derived master keys in localStorage, sessionStorage, IndexedDB, or persistable state containers.
- Engineers MUST ALWAYS overwrite raw PRF ArrayBuffers and intermediate typed arrays with zeros (crypto.getRandomValues or explicit byte zeroing) inside a `finally` block immediately after WebCrypto key import.
- Engineers MUST import derived keys into the WebCrypto API with `extractable: false` when generating the master database encryption key to prevent unauthorized exfiltration via client-side script execution (XSS).

## Bad vs Good Implementations
### Hardware-Backed PRF Output Retrieval and Secure Non-Extractable HKDF Expansion

#### Bad Antipattern (AI Common Hallucination)
> **Why it fails**: Fails to validate PRF results availability, marks the derived cryptographic key as extractable, stores raw PRF results directly in sessionStorage, and does not scrub raw key material from typed arrays, exposing sensitive material to heap inspection and XSS.
```typescript
export async function deriveDatabaseKeyBad(credentialId: Uint8Array, salt: Uint8Array): Promise<CryptoKey> {
  // VULNERABLE: Direct extraction without zeroing, missing PRF extension validation,
  // extractable key permits memory exfiltration, raw PRF bytes leak to GC.
  const assertion = (await navigator.credentials.get({
    publicKey: {
      challenge: new Uint8Array(32),
      allowCredentials: [{ id: credentialId, type: 'public-key' }],
      extensions: { prf: { eval: { first: salt } } } as any
    }
  })) as any;

  const rawPrf = assertion.getClientExtensionResults().prf.results.first;
  // Anti-pattern: Storing raw output directly into session storage
  sessionStorage.setItem('temp_prf_key', Buffer.from(rawPrf).toString('hex'));

  return await crypto.subtle.importKey(
    'raw',
    rawPrf,
    { name: 'AES-GCM' },
    true, // BAD: Extractable
    ['encrypt', 'decrypt']
  );
}
```

#### Production Standard (Correct)
> **Standard**: Validates PRF capability and payload explicitly, applies HKDF with context-specific domain separation info, enforces `extractable: false` on both the raw PRF key and the derived AES-GCM database encryption key, and zeroes out the raw PRF buffer in a `finally` block to mitigate heap dumps.
```typescript
export async function deriveDatabaseKeySecure(
  credentialId: Uint8Array,
  prfInputSalt: Uint8Array,
  hkdfInfo: Uint8Array
): Promise<CryptoKey> {
  const assertion = await navigator.credentials.get({
    publicKey: {
      challenge: crypto.getRandomValues(new Uint8Array(32)),
      allowCredentials: [{ id: credentialId, type: 'public-key' }],
      extensions: {
        prf: {
          eval: { first: prfInputSalt }
        }
      }
    }
  }) as PublicKeyCredential | null;

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

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

  const prfResult = extensionResults.prf?.results?.first;
  if (!prfResult || !(prfResult instanceof ArrayBuffer)) {
    throw new Error('Hardware authenticator does not support WebAuthn PRF extension or failed to evaluate');
  }

  const prfBytes = new Uint8Array(prfResult);

  try {
    // Import raw PRF output strictly as key material for HKDF
    const rawPrfKey = await crypto.subtle.importKey(
      'raw',
      prfBytes,
      'HKDF',
      false,
      ['deriveKey']
    );

    // Derive non-extractable AES-GCM-256 database encryption key
    return await crypto.subtle.deriveKey(
      {
        name: 'HKDF',
        hash: 'SHA-256',
        salt: prfInputSalt,
        info: hkdfInfo
      },
      rawPrfKey,
      { name: 'AES-GCM', length: 256 },
      false, // CRITICAL: Non-extractable
      ['encrypt', 'decrypt']
    );
  } finally {
    // Explicit zero-wipe of transient in-memory PRF material
    prfBytes.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: WebAuthn Level 3 PRF Hardware-Backed Symmetric Key Derivation Guardrail

WebAuthn Level 3 PRF Hardware-Backed Symmetric Key Derivation Guardrail defines an industrial-grade behavioral standard for security engineering. Enforces hardware-backed zero-knowledge credential derivation using WebAuthn Level 3 PRF (Pseudo-Random Function) extension for client-side encrypted database synchronization. Mandates using constant-time cryptographic operations, HKDF key stretching with ephemeral salts, zero-allocation memory zeroing, and strict validation of authenticator PRF outputs prior to master key reconstruction. 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 Unsalted PRF Outputs or Deriving Database Encryption Keys in Extractable Non-Wiped Client Memory 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 Unsalted PRF Outputs or Deriving Database Encryption Keys in Extractable Non-Wiped Client MemoryCritical
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 navigator.credentials.get() returns `authenticatorData` with extension results containing a defined `prf.results.first` buffer prior to key derivation.

Engineers MUST ALWAYS verify navigator.credentials.get() returns `authenticatorData` with extension results containing a defined `prf.results.first` buffer prior to key derivation.

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 ALWAYS pass the raw PRF output through HKDF (HMAC-based Extract-and-Expand Key Derivation Function) using SHA-256 and a distinct domain-separated info parameter before using it as a database encryption key (DEK) or key encryption key (KEK).

Engineers MUST ALWAYS pass the raw PRF output through HKDF (HMAC-based Extract-and-Expand Key Derivation Function) using SHA-256 and a distinct domain-separated info parameter before using it as a database encryption key (DEK) or 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.
3

Engineers MUST NOT store raw PRF output or intermediate derived master keys in localStorage, sessionStorage, IndexedDB, or persistable state containers.

Engineers MUST NOT store raw PRF output or intermediate derived master keys in localStorage, sessionStorage, IndexedDB, or persistable state containers.

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 ALWAYS overwrite raw PRF ArrayBuffers and intermediate typed arrays with zeros (crypto.getRandomValues or explicit byte zeroing) inside a `finally` block immediately after WebCrypto key import.

Engineers MUST ALWAYS overwrite raw PRF ArrayBuffers and intermediate typed arrays with zeros (crypto.getRandomValues or explicit byte zeroing) inside a `finally` block immediately after WebCrypto key import.

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 import derived keys into the WebCrypto API with `extractable

Engineers MUST import derived keys into the WebCrypto API with `extractable: false` when generating the master database encryption key to prevent unauthorized exfiltration via client-side script execution (XSS).

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 WebAuthn Level 3 PRF Hardware-Backed Symmetric Key Derivation Guardrail critical for AI coding assistants?

Enforces hardware-backed zero-knowledge credential derivation using WebAuthn Level 3 PRF (Pseudo-Random Function) extension for client-side encrypted database synchronization. Mandates using constant-time cryptographic operations, HKDF key stretching with ephemeral salts, zero-allocation memory zeroing, and strict validation of authenticator PRF outputs prior to master key reconstruction. 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 Unsalted PRF Outputs or Deriving Database Encryption Keys in Extractable Non-Wiped Client Memory) 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.

1 Rule in Stack

WebAuthn