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

WebAuthn PRF Extension Zero-Knowledge Key Derivation & HKDF Isolation Standard

Mandates strict zero-knowledge client-side cryptographic bounds when using the WebAuthn PRF (Pseudo-Random Function) extension. Requires non-extractable HKDF-SHA-256 expansion, distinct credential-specific salts, context-bound domain separation, and zero exposure of derived symmetric keys or raw PRF hardware outputs to relying party servers or persistent storage.

Prohibited Anti-Pattern: Exposing Raw Authenticator PRF Outputs or Directly Using PRF Results as Symmetric Cipher Keys

Export Ready-to-Drop Configuration

Select format below to copy code or download file directly.

---
description: WebAuthn PRF Extension Zero-Knowledge Key Derivation & HKDF Isolation Standard - Mandates strict zero-knowledge client-side cryptographic bounds when using the WebAuthn PRF (Pseudo-Random Function) extension. Requires non-extractable HKDF-SHA-256 expansion, distinct credential-specific salts, context-bound domain separation, and zero exposure of derived symmetric keys or raw PRF hardware outputs to relying party servers or persistent storage.
globs: src/**/auth/**/*.{ts,tsx}, src/**/crypto/**/*.{ts,tsx}, src/**/vault/**/*.{ts,tsx}, src/**/services/**/*.{ts,tsx}
alwaysApply: true
verified_by: "agentrules.org"
license: "CC-BY-4.0"
source: "https://agentrules.org/rules/webauthn-prf-client-side-key-derivation-standard"
---

# WebAuthn PRF Extension Zero-Knowledge Key Derivation & HKDF Isolation Standard

> **Severity**: CRITICAL | **Category**: security
> **Anti-Pattern Warning**: Exposing Raw Authenticator PRF Outputs or Directly Using PRF Results as Symmetric Cipher Keys

## System Constraints
You are a Principal Security Architect enforcing zero-knowledge client-side encryption using the WebAuthn PRF (hmac-secret) extension. Hardware authenticators execute HMAC operations over client-provided salts without exposing the internal root secret. You must ensure that raw PRF outputs are NEVER transmitted to servers, NEVER persisted to disk/localStorage, and NEVER directly used as symmetric keys without two-step HKDF expansion and domain separation.

## Strict Guidelines
- Engineers MUST ALWAYS feed raw WebAuthn PRF outputs through HKDF-SHA-256 (`crypto.subtle.deriveKey`) using a unique credential salt and context-specific `info` string to enforce cryptographic domain separation.
- Engineers MUST NOT transmit raw PRF extension outputs, intermediate IKM (Input Keying Material), or derived symmetric CryptoKey instances across network boundaries or include them in API payloads.
- Code MUST mark all derived symmetric keys as `extractable: false` when instantiating them via the Web Crypto API (`crypto.subtle`) to prevent memory scraping or programmatic extraction.
- Services MUST verify client extension support before requesting PRF assertions and MUST provide structured, deterministic failure modes if `assertion.getClientExtensionResults().prf` is missing or undefined.
- Components NEVER store derived cryptographic keys or PRF results in `localStorage`, `sessionStorage`, IndexedDB, or serialized state stores; keys must remain ephemeral instances within volatile memory closures.

## Bad vs Good Implementations
### WebAuthn PRF Assertion and HKDF Key Derivation Pipeline

#### Bad Antipattern (AI Common Hallucination)
> **Why it fails**: Directly persists raw PRF outputs in unencrypted localStorage and transmits raw PRF hardware material to the server over HTTP, completely invalidating zero-knowledge security guarantees and failing to perform HKDF key expansion.
```typescript
import axios from 'axios';

export async function unlockUserVaultBad(credentialId: string, serverSalt: Uint8Array) {
  // Anti-Pattern: Requesting PRF, but directly using the output and leaking it over the wire
  const assertion = await navigator.credentials.get({
    publicKey: {
      challenge: new Uint8Array(32),
      allowCredentials: [{ id: Uint8Array.from(atob(credentialId), c => c.charCodeAt(0)), type: 'public-key' }],
      extensions: {
        prf: {
          eval: {
            first: serverSalt,
          }
        }
      } as any
    }
  }) as PublicKeyCredential;

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

  // CRITICAL SECURITY FLAW: Storing raw PRF bytes in persistent storage
  localStorage.setItem('raw_key', btoa(String.fromCharCode(...new Uint8Array(rawPrfOutput))));

  // CRITICAL SECURITY FLAW: Transmitting raw authenticator derivation output to the server
  await axios.post('/api/vault/unlock', {
    credentialId,
    derivedMaterial: Array.from(new Uint8Array(rawPrfOutput))
  });
}
```

#### Production Standard (Correct)
> **Standard**: Extracts PRF results securely, enforces HKDF-SHA-256 derivation with explicit context ('vault:aes-gcm-256:v1'), flags keys as non-extractable, leaves raw material to be collected, and keeps all sensitive cryptographic material strictly within client memory.
```typescript
export interface DerivedVaultSession {
  vaultKey: CryptoKey;
}

const DOMAIN_INFO_PREFIX = new TextEncoder().encode('vault:aes-gcm-256:v1');

export async function deriveVaultKeyFromAuthenticator(
  credentialId: Uint8Array,
  prfSalt: Uint8Array
): Promise<DerivedVaultSession> {
  if (!window.PublicKeyCredential || !PublicKeyCredential.isConditionalMediationAvailable) {
    throw new Error('WebAuthn is not supported in this runtime environment.');
  }

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

  if (!assertion) {
    throw new Error('Authenticator operation aborted.');
  }

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

  const rawPrfBuffer = clientExtensions.prf?.results?.first;
  if (!rawPrfBuffer) {
    throw new Error('Authenticator did not return PRF output. Device may lack hmac-secret support.');
  }

  // Import raw PRF output strictly as non-extractable HKDF key material
  const initialKeyMaterial = await crypto.subtle.importKey(
    'raw',
    rawPrfBuffer,
    { name: 'HKDF' },
    false,
    ['deriveKey']
  );

  // Derive AES-GCM symmetric key with explicit domain separation context
  const vaultKey = await crypto.subtle.deriveKey(
    {
      name: 'HKDF',
      hash: 'SHA-256',
      salt: prfSalt,
      info: DOMAIN_INFO_PREFIX
    },
    initialKeyMaterial,
    {
      name: 'AES-GCM',
      length: 256
    },
    false, // Must not be extractable
    ['encrypt', 'decrypt']
  );

  // Return ephemeral memory reference; raw output goes out of scope and is garbage collected
  return { vaultKey };
}
```

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 Extension Zero-Knowledge Key Derivation & HKDF Isolation Standard

WebAuthn PRF Extension Zero-Knowledge Key Derivation & HKDF Isolation Standard defines an industrial-grade behavioral standard for security engineering. Mandates strict zero-knowledge client-side cryptographic bounds when using the WebAuthn PRF (Pseudo-Random Function) extension. Requires non-extractable HKDF-SHA-256 expansion, distinct credential-specific salts, context-bound domain separation, and zero exposure of derived symmetric keys or raw PRF hardware outputs to relying party servers or persistent 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: Exposing Raw Authenticator PRF Outputs or Directly Using PRF Results as Symmetric Cipher Keys 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 DriftExposing Raw Authenticator PRF Outputs or Directly Using PRF Results as Symmetric Cipher KeysCritical
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 outputs through HKDF-SHA-256 (`crypto.subtle.deriveKey`) using a unique credential salt and context-specific `info` string to enforce cryptographic domain separation.

Engineers MUST ALWAYS feed raw WebAuthn PRF outputs through HKDF-SHA-256 (`crypto.subtle.deriveKey`) using a unique credential salt and context-specific `info` string to enforce cryptographic domain separation.

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 extension outputs, intermediate IKM (Input Keying Material), or derived symmetric CryptoKey instances across network boundaries or include them in API payloads.

Engineers MUST NOT transmit raw PRF extension outputs, intermediate IKM (Input Keying Material), or derived symmetric CryptoKey instances across network boundaries or include them in API payloads.

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 mark all derived symmetric keys as `extractable

Code MUST mark all derived symmetric keys as `extractable: false` when instantiating them via the Web Crypto API (`crypto.subtle`) to prevent memory scraping or programmatic extraction.

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 verify client extension support before requesting PRF assertions and MUST provide structured, deterministic failure modes if `assertion.getClientExtensionResults().prf` is missing or undefined.

Services MUST verify client extension support before requesting PRF assertions and MUST provide structured, deterministic failure modes if `assertion.getClientExtensionResults().prf` is missing or undefined.

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 store derived cryptographic keys or PRF results in `localStorage`, `sessionStorage`, IndexedDB, or serialized state stores

Components NEVER store derived cryptographic keys or PRF results in `localStorage`, `sessionStorage`, IndexedDB, or serialized state stores; keys must remain ephemeral instances within volatile memory closures.

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 Extension Zero-Knowledge Key Derivation & HKDF Isolation Standard critical for AI coding assistants?

Mandates strict zero-knowledge client-side cryptographic bounds when using the WebAuthn PRF (Pseudo-Random Function) extension. Requires non-extractable HKDF-SHA-256 expansion, distinct credential-specific salts, context-bound domain separation, and zero exposure of derived symmetric keys or raw PRF hardware outputs to relying party servers or persistent 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 (Exposing Raw Authenticator PRF Outputs or Directly Using PRF Results as Symmetric Cipher Keys) 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