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

WebAuthn PRF Extension Zero-Knowledge Key Derivation Standard

Enforces strict cryptographic hygiene and zero-knowledge boundaries when deriving hardware-backed symmetric encryption keys using the WebAuthn PRF (Pseudo-Random Function) extension. Requires non-extractable CryptoKey derivation via HKDF domain separation, client-side isolation preventing PRF leak to relaying parties, and deterministic fallback validation.

Prohibited Anti-Pattern: Directly Utilizing Raw PRF Output as AES Keys or Leaking PRF Extension Outputs to the Relaying Party Server

Export Ready-to-Drop Configuration

Select format below to copy code or download file directly.

---
description: WebAuthn PRF Extension Zero-Knowledge Key Derivation Standard - Enforces strict cryptographic hygiene and zero-knowledge boundaries when deriving hardware-backed symmetric encryption keys using the WebAuthn PRF (Pseudo-Random Function) extension. Requires non-extractable CryptoKey derivation via HKDF domain separation, client-side isolation preventing PRF leak to relaying parties, and deterministic fallback validation.
globs: src/**/*.{ts,tsx}
alwaysApply: true
verified_by: "agentrules.org"
license: "CC-BY-4.0"
source: "https://agentrules.org/rules/webauthn-prf-e2ee-key-derivation-standard"
---

# WebAuthn PRF Extension Zero-Knowledge Key Derivation Standard

> **Severity**: CRITICAL | **Category**: security
> **Anti-Pattern Warning**: Directly Utilizing Raw PRF Output as AES Keys or Leaking PRF Extension Outputs to the Relaying Party Server

## System Constraints
You are a Principal Security Architect enforcing zero-knowledge client-side encryption using the WebAuthn PRF (hmac-secret) extension. Mandate that raw PRF outputs are never used directly as cipher keys, never transmitted to relaying parties or servers, and always processed through HKDF with domain-separated context strings to derive non-extractable CryptoKeys.

## Strict Guidelines
- Engineers MUST ALWAYS treat the WebAuthn PRF output as raw key material (IKM) and pass it through HKDF (RFC 5869) via Web Crypto `SubtleCrypto.deriveKey` with an explicit `info` tag and domain-separated context.
- Engineers MUST NEVER use the raw PRF result directly as a symmetric cipher key (e.g., passing raw PRF output directly as an AES-GCM key).
- Engineers MUST NEVER serialize or transmit PRF extension results (`clientExtensionResults.prf`) or derived keys to the Relaying Party (RP) or backend API; credentials sent for assertion verification MUST omit the PRF secret.
- Engineers MUST verify PRF capability during registration by inspecting `credential.getClientExtensionResults().prf?.enabled === true` before persisting credentials intended for zero-knowledge vault access.
- Code MUST explicitly zeroize in-memory raw PRF `ArrayBuffer` instances (using `new Uint8Array(buffer).fill(0)`) immediately after importing into a non-extractable `CryptoKey`.
- Code MUST import derived keys with `extractable: false` when using `window.crypto.subtle` to prevent exfiltration via XSS or prototype pollution.
- Services MUST generate and securely distribute random, unique 32-byte PRF salts per vault/credential, rather than relying on static or globally hardcoded PRF evaluation inputs.

## Bad vs Good Implementations
### WebAuthn PRF Key Derivation and Client-Side Isolation

#### Bad Antipattern (AI Common Hallucination)
> **Why it fails**: The anti-pattern leaks the raw PRF evaluation output to the backend server inside the assertion payload, breaking the zero-knowledge model. Furthermore, it imports the raw PRF output directly as an extractable AES-GCM key without HKDF-based domain separation, violating cryptographic derivation standards.
```typescript
import { startAuthentication } from '@simplewebauthn/browser';

export async function unlockVaultInsecure(options: any) {
  // Anti-pattern: Sending raw PRF output to server and using raw PRF bytes as AES key
  const assertion = await startAuthentication(options);
  const extensionResults = assertion.clientExtensionResults as any;
  const rawPrfKey = extensionResults.prf.results.first;

  // CRITICAL SECURITY FLAW: Sending PRF output to RP server
  await fetch('/api/vault/verify-and-unlock', {
    method: 'POST',
    headers: { 'Content-Type': 'application/json' },
    body: JSON.stringify(assertion), // PRF results leaked to RP!
  });

  // CRITICAL SECURITY FLAW: Direct use of raw PRF output without HKDF expansion
  return window.crypto.subtle.importKey(
    'raw',
    rawPrfKey,
    { name: 'AES-GCM' },
    true, // extractable = true is dangerous
    ['decrypt']
  );
}
```

#### Production Standard (Correct)
> **Standard**: The secure implementation imports the raw PRF output as HKDF key material, derives a non-extractable AES-GCM-256 key using cryptographic context separation, purges PRF results from the assertion before sending it to the Relaying Party server, and explicitly zeroes out the raw PRF memory buffer.
```typescript
import { startAuthentication } from '@simplewebauthn/browser';
import type { PublicKeyCredentialWithExtensions } from './types';

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

export async function unlockVaultSecure(
  authOptions: CredentialRequestOptions,
  vaultSalt: Uint8Array
): Promise<CryptoKey> {
  // 1. Inject PRF extension evaluation input into authentication options
  const optionsWithPrf: CredentialRequestOptions = {
    ...authOptions,
    publicKey: {
      ...authOptions.publicKey!,
      extensions: {
        ...authOptions.publicKey?.extensions,
        prf: {
          eval: {
            first: vaultSalt,
          },
        },
      },
    },
  };

  const credential = (await navigator.credentials.get(
    optionsWithPrf
  )) as PublicKeyCredentialWithExtensions | null;

  if (!credential) {
    throw new Error('Authentication aborted or failed.');
  }

  const clientExtensions = credential.getClientExtensionResults();
  const prfResults = clientExtensions.prf?.results;
  if (!prfResults?.first) {
    throw new Error('Hardware authenticator does not support or return PRF output.');
  }

  // Copy raw PRF result into mutable buffer for guaranteed sanitization
  const rawPrfBuffer = new Uint8Array(prfResults.first);

  try {
    // 2. Import raw PRF output as HKDF key material
    const basePrfKey = await window.crypto.subtle.importKey(
      'raw',
      rawPrfBuffer,
      'HKDF',
      false,
      ['deriveKey']
    );

    // 3. Derive non-extractable AES-GCM vault decryption key via HKDF
    const derivedVaultKey = await window.crypto.subtle.deriveKey(
      {
        name: 'HKDF',
        hash: 'SHA-256',
        salt: vaultSalt,
        info: HKDF_INFO_VAULT,
      },
      basePrfKey,
      { name: 'AES-GCM', length: 256 },
      false, // non-extractable
      ['decrypt', 'encrypt']
    );

    // 4. Strip PRF output before sending assertion to Relaying Party
    const assertionPayload = credential.toJSON();
    if (assertionPayload.clientExtensionResults?.prf) {
      delete assertionPayload.clientExtensionResults.prf;
    }

    await fetch('/api/auth/verify-assertion', {
      method: 'POST',
      headers: { 'Content-Type': 'application/json' },
      body: JSON.stringify(assertionPayload),
    });

    return derivedVaultKey;
  } finally {
    // 5. Zeroize sensitive ephemeral raw PRF buffer
    rawPrfBuffer.fill(0);
  }
}
```

Architectural Specification & Invariant Rationale

Architectural Invariant Design: WebAuthn PRF Extension Zero-Knowledge Key Derivation Standard

WebAuthn PRF Extension Zero-Knowledge Key Derivation Standard defines an industrial-grade behavioral standard for security engineering. Enforces strict cryptographic hygiene and zero-knowledge boundaries when deriving hardware-backed symmetric encryption keys using the WebAuthn PRF (Pseudo-Random Function) extension. Requires non-extractable CryptoKey derivation via HKDF domain separation, client-side isolation preventing PRF leak to relaying parties, and deterministic fallback validation. 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: Directly Utilizing Raw PRF Output as AES Keys or Leaking PRF Extension Outputs to the Relaying Party Server 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 DriftDirectly Utilizing Raw PRF Output as AES Keys or Leaking PRF Extension Outputs to the Relaying Party ServerCritical
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 treat the WebAuthn PRF output as raw key material (IKM) and pass it through HKDF (RFC 5869) via Web Crypto `SubtleCrypto.deriveKey` with an explicit `info` tag and domain-separated context.

Engineers MUST ALWAYS treat the WebAuthn PRF output as raw key material (IKM) and pass it through HKDF (RFC 5869) via Web Crypto `SubtleCrypto.deriveKey` with an explicit `info` tag and domain-separated context.

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 use the raw PRF result directly as a symmetric cipher key (e.g., passing raw PRF output directly as an AES-GCM key).

Engineers MUST NEVER use the raw PRF result directly as a symmetric cipher key (e.g., passing raw PRF output directly as an AES-GCM key).

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 NEVER serialize or transmit PRF extension results (`clientExtensionResults.prf`) or derived keys to the Relaying Party (RP) or backend API

Engineers MUST NEVER serialize or transmit PRF extension results (`clientExtensionResults.prf`) or derived keys to the Relaying Party (RP) or backend API; credentials sent for assertion verification MUST omit the PRF secret.

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 verify PRF capability during registration by inspecting `credential.getClientExtensionResults().prf?.enabled === true` before persisting credentials intended for zero-knowledge vault access.

Engineers MUST verify PRF capability during registration by inspecting `credential.getClientExtensionResults().prf?.enabled === true` before persisting credentials intended for zero-knowledge vault access.

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 MUST explicitly zeroize in-memory raw PRF `ArrayBuffer` instances (using `new Uint8Array(buffer).fill(0)`) immediately after importing into a non-extractable `CryptoKey`.

Code MUST explicitly zeroize in-memory raw PRF `ArrayBuffer` instances (using `new Uint8Array(buffer).fill(0)`) immediately after importing into a non-extractable `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.
6

Code MUST import derived keys with `extractable

Code MUST import derived keys with `extractable: false` when using `window.crypto.subtle` to prevent exfiltration via XSS or prototype pollution.

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.
7

Services MUST generate and securely distribute random, unique 32-byte PRF salts per vault/credential, rather than relying on static or globally hardcoded PRF evaluation inputs.

Services MUST generate and securely distribute random, unique 32-byte PRF salts per vault/credential, rather than relying on static or globally hardcoded PRF evaluation inputs.

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 Standard critical for AI coding assistants?

Enforces strict cryptographic hygiene and zero-knowledge boundaries when deriving hardware-backed symmetric encryption keys using the WebAuthn PRF (Pseudo-Random Function) extension. Requires non-extractable CryptoKey derivation via HKDF domain separation, client-side isolation preventing PRF leak to relaying parties, and deterministic fallback validation. 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 (Directly Utilizing Raw PRF Output as AES Keys or Leaking PRF Extension Outputs to the Relaying Party Server) 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