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

WebAuthn Level 3 PRF Extension Client-Side Zero-Knowledge Key Derivation Invariants

Enforces cryptographic invariants for WebAuthn Level 3 PRF (Pseudo-Random Function) extension usage. Mandates that PRF output materials never leave client memory, require immediate HKDF expansion into non-extractable Web Crypto keys, and strictly isolate client-side envelope encryption keys from relying party server payloads.

Prohibited Anti-Pattern: Leaking Hardware-Derived PRF Key Material to Relying Party Servers or Direct Insecure Key Usage

Export Ready-to-Drop Configuration

Select format below to copy code or download file directly.

---
description: WebAuthn Level 3 PRF Extension Client-Side Zero-Knowledge Key Derivation Invariants - Enforces cryptographic invariants for WebAuthn Level 3 PRF (Pseudo-Random Function) extension usage. Mandates that PRF output materials never leave client memory, require immediate HKDF expansion into non-extractable Web Crypto keys, and strictly isolate client-side envelope encryption keys from relying party server payloads.
globs: src/**/*.{ts,tsx}, lib/**/*.{ts,tsx}, packages/**/*.{ts,tsx}
alwaysApply: true
verified_by: "agentrules.org"
license: "CC-BY-4.0"
source: "https://agentrules.org/rules/webauthn-prf-zk-key-derivation-guardrail-webauthn-level-3-221"
---

# WebAuthn Level 3 PRF Extension Client-Side Zero-Knowledge Key Derivation Invariants

> **Severity**: CRITICAL | **Category**: security
> **Anti-Pattern Warning**: Leaking Hardware-Derived PRF Key Material to Relying Party Servers or Direct Insecure Key Usage

## System Constraints
You are a Principal Cryptographic Engineer enforcing WebAuthn Level 3 PRF Extension Zero-Knowledge Key Derivation Invariants. Mandate strict boundaries preventing any PRF symmetric key derivation material from leaking to the Relying Party server or persistent storage. Ensure all PRF outputs undergo HKDF-SHA-256 expansion into non-extractable CryptoKey instances with cryptographically distinct purpose salts.

## Strict Guidelines
- Engineers MUST ALWAYS verify PRF extension availability on registration via getClientExtensionResults().prf.supported before relying on zero-knowledge envelope encryption flows.
- Engineers MUST NEVER serialize, log, or transmit raw PRF evaluator outputs (results.extensions.prf.results.first) to the Relying Party or any remote server.
- Engineers MUST ALWAYS pipe PRF outputs directly into crypto.subtle.importKey as raw HKDF key material and derive an unextractable (extractable: false) AES-256-GCM CryptoKey.
- Code MUST NEVER use raw PRF output directly as a symmetric cipher key; an intermediate HKDF-SHA-256 extract-and-expand stage with distinct domain separation info strings is mandatory.
- Services MUST supply unique, cryptographically random PRF evaluation salts (exactly 32 bytes) stored alongside the encrypted ciphertext, never hardcoding or reusing static salts.
- Components NEVER allow client-side key derivation to succeed silently if the authenticator omits PRF results; throw explicit hardware capability exceptions.

## Bad vs Good Implementations
### Insecure: Transmitting Raw PRF Output to Server and Direct Cipher Usage

#### Bad Antipattern (AI Common Hallucination)
> **Why it fails**: Transmits raw hardware-derived PRF bytes to the authentication server, breaking the Zero-Knowledge invariant. Directly imports the PRF output into an extractable AES-GCM key without HKDF-SHA-256 domain separation.
```typescript
import { startAuthentication } from '@simplewebauthn/browser';

export async function unlockVaultInsecure(authOptions: any, salt: Uint8Array) {
  // Anti-Pattern: PRF eval configured without stripping results before sending to server
  const authResponse = await startAuthentication({
    ...authOptions,
    extensions: { prf: { eval: { first: salt } } }
  });

  const prfResult = (authResponse.clientExtensionResults as any)?.prf?.results?.first;

  // CRITICAL SECURITY FLAW: Sending PRF secret to Relying Party server
  await fetch('/api/vault/verify-and-unlock', {
    method: 'POST',
    headers: { 'Content-Type': 'application/json' },
    body: JSON.stringify({
      authResponse,
      derivedPrfSecret: Array.from(new Uint8Array(prfResult)) // Leaked to backend!
    })
  });

  // Anti-Pattern: Raw PRF bytes used directly as AES key with extractable: true
  return await crypto.subtle.importKey(
    'raw',
    prfResult,
    { name: 'AES-GCM', length: 256 },
    true,
    ['encrypt', 'decrypt']
  );
}
```

#### Production Standard (Correct)
> **Standard**: Validates authenticator PRF response locally, keeps raw PRF keying material strictly inside Web Crypto memory, never sends PRF output to the backend, and uses HKDF-SHA-256 to derive a non-extractable AES-256-GCM CryptoKey.
```typescript
export interface PrfDerivationOptions {
  credentialId: Uint8Array;
  prfSalt: Uint8Array; // Exactly 32 bytes
  domainContext: string;
}

export async function deriveHardwareEnvelopeKey({
  credentialId,
  prfSalt,
  domainContext
}: PrfDerivationOptions): Promise<CryptoKey> {
  if (!window.PublicKeyCredential) {
    throw new Error('WebAuthn is not supported in this runtime context');
  }
  if (prfSalt.byteLength !== 32) {
    throw new Error('PRF salt must be exactly 32 cryptographically secure bytes');
  }

  const assertion = (await navigator.credentials.get({
    publicKey: {
      challenge: crypto.getRandomValues(new Uint8Array(32)),
      allowCredentials: [{ id: credentialId, type: 'public-key' }],
      extensions: {
        prf: {
          eval: { first: prfSalt }
        }
      }
    }
  })) as PublicKeyCredential | null;

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

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

  const rawPrfBuffer = extensionOutputs.prf?.results?.first;
  if (!rawPrfBuffer) {
    throw new Error('Authenticator does not support Level 3 PRF or evaluation failed');
  }

  // Invariant: PRF output never leaves client. Immediately import into HKDF.
  const prfMasterKey = await crypto.subtle.importKey(
    'raw',
    rawPrfBuffer,
    { name: 'HKDF' },
    false, // Must not be extractable
    ['deriveKey']
  );

  const encoder = new TextEncoder();
  const info = encoder.encode(`zk-envelope-v1:${domainContext}`);

  // Invariant: Derive unextractable AES-256-GCM key via HKDF with domain separation
  return crypto.subtle.deriveKey(
    {
      name: 'HKDF',
      hash: 'SHA-256',
      salt: prfSalt,
      info
    },
    prfMasterKey,
    { name: 'AES-GCM', length: 256 },
    false, // Enforce non-extractable hardware-tethered key
    ['encrypt', 'decrypt']
  );
}
```

Recommended MCP Servers (mcp-serverlist.com)

Equip agent with system tools to verify code for this stack.

Architectural Specification & Invariant Rationale

Architectural Invariant Design: WebAuthn Level 3 PRF Extension Client-Side Zero-Knowledge Key Derivation Invariants

WebAuthn Level 3 PRF Extension Client-Side Zero-Knowledge Key Derivation Invariants defines an industrial-grade behavioral standard for security engineering. Enforces cryptographic invariants for WebAuthn Level 3 PRF (Pseudo-Random Function) extension usage. Mandates that PRF output materials never leave client memory, require immediate HKDF expansion into non-extractable Web Crypto keys, and strictly isolate client-side envelope encryption keys from relying party server payloads. 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: Leaking Hardware-Derived PRF Key Material to Relying Party Servers or Direct Insecure Key Usage 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 DriftLeaking Hardware-Derived PRF Key Material to Relying Party Servers or Direct Insecure Key UsageCritical
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 PRF extension availability on registration via getClientExtensionResults().prf.supported before relying on zero-knowledge envelope encryption flows.

Engineers MUST ALWAYS verify PRF extension availability on registration via getClientExtensionResults().prf.supported before relying on zero-knowledge envelope encryption flows.

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 serialize, log, or transmit raw PRF evaluator outputs (results.extensions.prf.results.first) to the Relying Party or any remote server.

Engineers MUST NEVER serialize, log, or transmit raw PRF evaluator outputs (results.extensions.prf.results.first) to the Relying Party or any remote server.

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 ALWAYS pipe PRF outputs directly into crypto.subtle.importKey as raw HKDF key material and derive an unextractable (extractable

Engineers MUST ALWAYS pipe PRF outputs directly into crypto.subtle.importKey as raw HKDF key material and derive an unextractable (extractable: false) AES-256-GCM CryptoKey.

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

Code MUST NEVER use raw PRF output directly as a symmetric cipher key

Code MUST NEVER use raw PRF output directly as a symmetric cipher key; an intermediate HKDF-SHA-256 extract-and-expand stage with distinct domain separation info strings is mandatory.

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

Services MUST supply unique, cryptographically random PRF evaluation salts (exactly 32 bytes) stored alongside the encrypted ciphertext, never hardcoding or reusing static salts.

Services MUST supply unique, cryptographically random PRF evaluation salts (exactly 32 bytes) stored alongside the encrypted ciphertext, never hardcoding or reusing static salts.

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

Components NEVER allow client-side key derivation to succeed silently if the authenticator omits PRF results

Components NEVER allow client-side key derivation to succeed silently if the authenticator omits PRF results; throw explicit hardware capability exceptions.

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 Extension Client-Side Zero-Knowledge Key Derivation Invariants critical for AI coding assistants?

Enforces cryptographic invariants for WebAuthn Level 3 PRF (Pseudo-Random Function) extension usage. Mandates that PRF output materials never leave client memory, require immediate HKDF expansion into non-extractable Web Crypto keys, and strictly isolate client-side envelope encryption keys from relying party server payloads. 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 (Leaking Hardware-Derived PRF Key Material to Relying Party Servers or Direct Insecure Key Usage) 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