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

WebAuthn PRF Zero-Knowledge Key Derivation & HKDF Domain Separation Standard

Mandates cryptographic domain separation, zero-knowledge isolation, and memory hygiene when deriving client-side symmetric keys via the WebAuthn PRF (Pseudo-Random Function) extension. Prevents raw PRF output exposure to remote servers, direct use of raw PRF bytes as cipher keys, and silent authentication failures on authenticators lacking PRF support.

Prohibited Anti-Pattern: Direct Cipher Usage of Raw PRF Secret, Exposing PRF Output to Server Payloads, or Missing HKDF Domain Separation

Export Ready-to-Drop Configuration

Select format below to copy code or download file directly.

---
description: WebAuthn PRF Zero-Knowledge Key Derivation & HKDF Domain Separation Standard - Mandates cryptographic domain separation, zero-knowledge isolation, and memory hygiene when deriving client-side symmetric keys via the WebAuthn PRF (Pseudo-Random Function) extension. Prevents raw PRF output exposure to remote servers, direct use of raw PRF bytes as cipher keys, and silent authentication failures on authenticators lacking PRF support.
globs: src/**/*.{ts,tsx}, lib/**/*.{ts,tsx}, services/**/*.{ts,tsx}
alwaysApply: true
verified_by: "agentrules.org"
license: "CC-BY-4.0"
source: "https://agentrules.org/rules/webauthn-prf-zk-client-key-derivation-guardrail"
---

# WebAuthn PRF Zero-Knowledge Key Derivation & HKDF Domain Separation Standard

> **Severity**: CRITICAL | **Category**: security
> **Anti-Pattern Warning**: Direct Cipher Usage of Raw PRF Secret, Exposing PRF Output to Server Payloads, or Missing HKDF Domain Separation

## System Constraints
You are a Principal Security Architect enforcing zero-knowledge client cryptographic invariants for WebAuthn PRF extensions. Mandate that raw PRF outputs are treated as ephemeral cryptographic seeds, never transmitted to servers, never persisted to Web Storage (localStorage/sessionStorage/IndexedDB), and never used directly as symmetric cipher keys. Require HKDF-SHA-256 derivation with strict domain-separation labels and PRF capability verification before handling sensitive cryptographic operations.

## Strict Guidelines
- Engineers MUST ALWAYS feed raw WebAuthn PRF output through HKDF-SHA-256 (RFC 5869) with explicit context labels ('info') and non-zero salts to derive encryption (AES-GCM) and authentication keys.
- Engineers MUST NOT transmit raw PRF outputs, HKDF master seeds, or derived plaintext symmetric keys across the network or persist them into Web Storage (localStorage, sessionStorage, unencrypted IndexedDB).
- Services MUST verify `credential.getClientExtensionResults().prf?.enabled` during registration before binding the passkey to a zero-knowledge recovery or storage workflow.
- Components NEVER use the raw 32-byte PRF output directly as an AES-GCM or ChaCha20-Poly1305 key without key derivation expansion and proper algorithm import bindings.
- Code SHOULD zeroize ephemeral Uint8Array buffers containing raw PRF evaluations immediately after key derivation using `.fill(0)` to minimize in-memory exposure windows.
- Client code MUST provide explicit, non-crashing fallbacks and error handling when `authenticatorData` flags indicate the hardware authenticator does not support or denies the PRF extension.

## Bad vs Good Implementations
### WebAuthn PRF Evaluation and HKDF Key Derivation

#### Bad Antipattern (AI Common Hallucination)
> **Why it fails**: Raw PRF output is directly imported as an AES-GCM cipher key instead of deriving through HKDF with contextual domain separation. The raw PRF output is dangerously exfiltrated to the backend server, completely violating the zero-knowledge model. Furthermore, PRF extension availability is not validated, leading to unhandled runtime exceptions on incompatible authenticators.
```typescript
import { get } from '@github/webauthn-json';

export async function getVaultKey(credentialId: string, serverChallenge: string): Promise<CryptoKey> {
  const credential = await navigator.credentials.get({
    publicKey: {
      challenge: new TextEncoder().encode(serverChallenge),
      allowCredentials: [{ id: new TextEncoder().encode(credentialId), type: 'public-key' }],
      extensions: {
        // ANTI-PATTERN: Fixed arbitrary string as salt without domain separation
        prf: { eval: { first: new TextEncoder().encode('my-secret-salt') } }
      }
    }
  }) as PublicKeyCredential;

  const extensionResults = credential.getClientExtensionResults() as any;
  const rawPrf = new Uint8Array(extensionResults.prf.results.first);

  // ANTI-PATTERN: Leaking PRF material to server for verification/storage
  await fetch('/api/user/sync-key', {
    method: 'POST',
    body: JSON.stringify({ prfBackup: Array.from(rawPrf) })
  });

  // ANTI-PATTERN: Direct use of raw PRF output as AES-GCM key without HKDF
  return window.crypto.subtle.importKey(
    'raw',
    rawPrf,
    { name: 'AES-GCM', length: 256 },
    false,
    ['encrypt', 'decrypt']
  );
}
```

#### Production Standard (Correct)
> **Standard**: Validates PRF support and response presence gracefully. Strictly uses the PRF output as an HKDF master secret to derive an AES-GCM-256 key with distinct domain-separated info labels. The derived key is non-extractable, zero raw material leaves the client, and the memory buffer is immediately wiped via `.fill(0)`.
```typescript
const PRF_HKDF_SALT = new TextEncoder().encode('org.production.zk-vault.v1.salt');
const PRF_HKDF_INFO = new TextEncoder().encode('org.production.zk-vault.v1.aes-gcm-encryption');

export async function deriveZeroKnowledgeVaultKey(
  credentialId: BufferSource,
  authChallenge: BufferSource,
  prfEvaluationSalt: Uint8Array
): Promise<CryptoKey> {
  if (prfEvaluationSalt.byteLength !== 32) {
    throw new RangeError('PRF input salt must be cryptographically secure and exactly 32 bytes.');
  }

  const credential = await navigator.credentials.get({
    publicKey: {
      challenge: authChallenge,
      allowCredentials: [{ id: credentialId, type: 'public-key' }],
      extensions: {
        prf: {
          eval: { first: prfEvaluationSalt }
        }
      }
    }
  }) as PublicKeyCredential | null;

  if (!credential) {
    throw new Error('Authenticator operation aborted or cancelled.');
  }

  const extensionResults = credential.getClientExtensionResults();
  const prfResult = extensionResults.prf?.results?.first;

  if (!prfResult) {
    throw new Error('Authenticator did not return PRF output. Device may lack PRF support or permission was denied.');
  }

  const rawPrfBytes = new Uint8Array(prfResult);

  try {
    // Import PRF output as an HKDF key derivation master secret (non-extractable)
    const prfKeyMaterial = await crypto.subtle.importKey(
      'raw',
      rawPrfBytes,
      { name: 'HKDF' },
      false,
      ['deriveKey']
    );

    // Derive dedicated symmetric key with explicit domain separation parameters
    return await crypto.subtle.deriveKey(
      {
        name: 'HKDF',
        hash: 'SHA-256',
        salt: PRF_HKDF_SALT,
        info: PRF_HKDF_INFO
      },
      prfKeyMaterial,
      { name: 'AES-GCM', length: 256 },
      false,
      ['encrypt', 'decrypt']
    );
  } finally {
    // Zeroize ephemeral memory buffer immediately
    rawPrfBytes.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 PRF Zero-Knowledge Key Derivation & HKDF Domain Separation Standard

WebAuthn PRF Zero-Knowledge Key Derivation & HKDF Domain Separation Standard defines an industrial-grade behavioral standard for security engineering. Mandates cryptographic domain separation, zero-knowledge isolation, and memory hygiene when deriving client-side symmetric keys via the WebAuthn PRF (Pseudo-Random Function) extension. Prevents raw PRF output exposure to remote servers, direct use of raw PRF bytes as cipher keys, and silent authentication failures on authenticators lacking PRF support. 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: Direct Cipher Usage of Raw PRF Secret, Exposing PRF Output to Server Payloads, or Missing HKDF Domain Separation 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 DriftDirect Cipher Usage of Raw PRF Secret, Exposing PRF Output to Server Payloads, or Missing HKDF Domain SeparationCritical
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 feed raw WebAuthn PRF output through HKDF-SHA-256 (RFC 5869) with explicit context labels ('info') and non-zero salts to derive encryption (AES-GCM) and authentication keys.

Engineers MUST ALWAYS feed raw WebAuthn PRF output through HKDF-SHA-256 (RFC 5869) with explicit context labels ('info') and non-zero salts to derive encryption (AES-GCM) and authentication keys.

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 transmit raw PRF outputs, HKDF master seeds, or derived plaintext symmetric keys across the network or persist them into Web Storage (localStorage, sessionStorage, unencrypted IndexedDB).

Engineers MUST NOT transmit raw PRF outputs, HKDF master seeds, or derived plaintext symmetric keys across the network or persist them into Web Storage (localStorage, sessionStorage, unencrypted 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.
3

Services MUST verify `credential.getClientExtensionResults().prf?.enabled` during registration before binding the passkey to a zero-knowledge recovery or storage workflow.

Services MUST verify `credential.getClientExtensionResults().prf?.enabled` during registration before binding the passkey to a zero-knowledge recovery or storage workflow.

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 use the raw 32-byte PRF output directly as an AES-GCM or ChaCha20-Poly1305 key without key derivation expansion and proper algorithm import bindings.

Components NEVER use the raw 32-byte PRF output directly as an AES-GCM or ChaCha20-Poly1305 key without key derivation expansion and proper algorithm import bindings.

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 zeroize ephemeral Uint8Array buffers containing raw PRF evaluations immediately after key derivation using `.fill(0)` to minimize in-memory exposure windows.

Code SHOULD zeroize ephemeral Uint8Array buffers containing raw PRF evaluations immediately after key derivation using `.fill(0)` to minimize in-memory exposure windows.

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

Client code MUST provide explicit, non-crashing fallbacks and error handling when `authenticatorData` flags indicate the hardware authenticator does not support or denies the PRF extension.

Client code MUST provide explicit, non-crashing fallbacks and error handling when `authenticatorData` flags indicate the hardware authenticator does not support or denies 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.
Technical Questions & Answers

Frequently Asked Technical Questions

Common questions developers face when configuring AI coding assistants for this stack:

Q:Why is WebAuthn PRF Zero-Knowledge Key Derivation & HKDF Domain Separation Standard critical for AI coding assistants?

Mandates cryptographic domain separation, zero-knowledge isolation, and memory hygiene when deriving client-side symmetric keys via the WebAuthn PRF (Pseudo-Random Function) extension. Prevents raw PRF output exposure to remote servers, direct use of raw PRF bytes as cipher keys, and silent authentication failures on authenticators lacking PRF support. 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 (Direct Cipher Usage of Raw PRF Secret, Exposing PRF Output to Server Payloads, or Missing HKDF Domain Separation) 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