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

Hardware-Bound WebAuthn PRF Zero-Knowledge Key Derivation Standard

Enforces strict implementation invariants for client-side cryptographic key derivation using WebAuthn Level 3 Pseudo-Random Function (PRF) extensions (HMAC-secret). Guarantees that derived symmetric keys bound to hardware authenticators are never exported, stored in persistent plaintext, or transmitted over network boundaries, ensuring absolute zero-knowledge client-side encryption.

Prohibited Anti-Pattern: Deriving Encryption Keys from Insecure Authenticators or Caching Raw PRF Evaluation Outputs in Memory or LocalStorage

Export Ready-to-Drop Configuration

Select format below to copy code or download file directly.

---
description: Hardware-Bound WebAuthn PRF Zero-Knowledge Key Derivation Standard - Enforces strict implementation invariants for client-side cryptographic key derivation using WebAuthn Level 3 Pseudo-Random Function (PRF) extensions (HMAC-secret). Guarantees that derived symmetric keys bound to hardware authenticators are never exported, stored in persistent plaintext, or transmitted over network boundaries, ensuring absolute zero-knowledge client-side encryption.
globs: src/**/*.{ts,tsx}, lib/**/*.{ts,tsx}
alwaysApply: true
verified_by: "agentrules.org"
license: "CC-BY-4.0"
source: "https://agentrules.org/rules/webauthn-prf-key-derivation-standard-webauthn-prf-pse-591"
---

# Hardware-Bound WebAuthn PRF Zero-Knowledge Key Derivation Standard

> **Severity**: CRITICAL | **Category**: security
> **Anti-Pattern Warning**: Deriving Encryption Keys from Insecure Authenticators or Caching Raw PRF Evaluation Outputs in Memory or LocalStorage

## System Constraints
You are a Principal Security Architect and Cryptography Engineer enforcing the WebAuthn PRF (Pseudo-Random Function) Client-Side Key Derivation Standard. You must reject any implementation that uses software-simulated keys when hardware PRF is requested, leaks raw PRF outputs into logs or storage, derives encryption keys using weak sub-salts, or fails to zeroize intermediate WebCrypto buffers.

## Strict Guidelines
- Engineers MUST ALWAYS verify client capability for WebAuthn PRF extension using `PublicKeyCredential.isUserVerifyingPlatformAuthenticatorAvailable()` and inspecting `getClientExtensionResults().prf` before attempting derivation.
- Engineers MUST ALWAYS derive actual symmetric encryption keys (e.g., AES-GCM-256) from the hardware PRF output using HKDF (RFC 5869) with a domain-separated salt and info string, rather than using the raw PRF evaluation output directly as a key.
- Engineers MUST NOT store raw PRF output, intermediate HKDF buffers, or derived CryptoKey instances in localStorage, sessionStorage, IndexedDB, or persist them unencrypted in any client-side storage.
- Code MUST set `extractable: false` on all WebCrypto `CryptoKey` imports resulting from PRF key derivations to prevent memory scraping and DOM-based extraction.
- Services MUST enforce `userVerification: 'required'` during credential generation and assertion when PRF keys are derived to guarantee biometric or PIN presence.
- Components NEVER transmit raw PRF inputs (`first`, `second` evaluation buffers) or raw PRF outputs to the backend server or over network transports.

## Bad vs Good Implementations
### WebAuthn PRF Key Derivation with HKDF and Non-Extractable CryptoKey

#### Bad Antipattern (AI Common Hallucination)
> **Why it fails**: The bad implementation allows non-user-verified assertions, assumes PRF output is directly a symmetric key without domain separation via HKDF, extracts the raw key material into memory as a hex string, and critically persists the master key into localStorage where it is vulnerable to XSS and storage leakage.
```typescript
export async function deriveKeyInsecure(credentialId: Uint8Array, rawSalt: Uint8Array): Promise<string> {
  const assertion = await navigator.credentials.get({
    publicKey: {
      challenge: new Uint8Array(32),
      allowCredentials: [{ id: credentialId, type: 'public-key' }],
      // Flaw 1: userVerification not required
      userVerification: 'preferred',
      extensions: {
        prf: {
          eval: { first: rawSalt }
        }
      }
    }
  }) as PublicKeyCredential;

  const extensionResults = assertion.getClientExtensionResults();
  const rawOutput = (extensionResults as any).prf?.results?.first;
  if (!rawOutput) {
    throw new Error('PRF evaluation failed');
  }

  // Flaw 2: Leaking raw PRF output to localStorage as a plaintext hex key
  const keyHex = Array.from(new Uint8Array(rawOutput))
    .map(b => b.toString(16).padStart(2, '0'))
    .join('');
  localStorage.setItem('encryption_master_key', keyHex);
  return keyHex;
}
```

#### Production Standard (Correct)
> **Standard**: The good implementation strictly enforces userVerification: 'required', uses the WebAuthn PRF Level 3 extension structure, passes the output directly to WebCrypto HKDF as non-extractable initial key material, derives a final AES-GCM-256 key with domain separation, and keeps extractable set to false to prevent runtime exfiltration.
```typescript
export async function deriveHardwareBoundKey(
  credentialId: Uint8Array,
  salt: Uint8Array,
  domainContext: string
): Promise<CryptoKey> {
  if (!window.PublicKeyCredential) {
    throw new Error('WebAuthn is not supported in this environment');
  }

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

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

  const prfResults = assertion.getClientExtensionResults().prf;
  const rawPrfSecret = prfResults?.results?.first;
  if (!rawPrfSecret) {
    throw new Error('Authenticator did not return PRF evaluation result');
  }

  // Import PRF output as raw IKM into non-extractable HKDF key
  const initialKeyMaterial = await crypto.subtle.importKey(
    'raw',
    rawPrfSecret,
    'HKDF',
    false,
    ['deriveKey']
  );

  // Derive non-extractable AES-GCM encryption key using domain-separated HKDF
  const enc = new TextEncoder();
  return await crypto.subtle.deriveKey(
    {
      name: 'HKDF',
      hash: 'SHA-256',
      salt: enc.encode('zk-webauthn-prf-v1-salt'),
      info: enc.encode(`app-context:${domainContext}`)
    },
    initialKeyMaterial,
    { name: 'AES-GCM', length: 256 },
    false,
    ['encrypt', 'decrypt']
  );
}
```

Architectural Specification & Invariant Rationale

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

Hardware-Bound WebAuthn PRF Zero-Knowledge Key Derivation Standard defines an industrial-grade behavioral standard for security engineering. Enforces strict implementation invariants for client-side cryptographic key derivation using WebAuthn Level 3 Pseudo-Random Function (PRF) extensions (HMAC-secret). Guarantees that derived symmetric keys bound to hardware authenticators are never exported, stored in persistent plaintext, or transmitted over network boundaries, ensuring absolute zero-knowledge client-side encryption. 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: Deriving Encryption Keys from Insecure Authenticators or Caching Raw PRF Evaluation Outputs in Memory or LocalStorage 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 DriftDeriving Encryption Keys from Insecure Authenticators or Caching Raw PRF Evaluation Outputs in Memory or LocalStorageCritical
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 client capability for WebAuthn PRF extension using `PublicKeyCredential.isUserVerifyingPlatformAuthenticatorAvailable()` and inspecting `getClientExtensionResults().prf` before attempting derivation.

Engineers MUST ALWAYS verify client capability for WebAuthn PRF extension using `PublicKeyCredential.isUserVerifyingPlatformAuthenticatorAvailable()` and inspecting `getClientExtensionResults().prf` before attempting 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 derive actual symmetric encryption keys (e.g., AES-GCM-256) from the hardware PRF output using HKDF (RFC 5869) with a domain-separated salt and info string, rather than using the raw PRF evaluation output directly as a key.

Engineers MUST ALWAYS derive actual symmetric encryption keys (e.g., AES-GCM-256) from the hardware PRF output using HKDF (RFC 5869) with a domain-separated salt and info string, rather than using the raw PRF evaluation output directly as a 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 NOT store raw PRF output, intermediate HKDF buffers, or derived CryptoKey instances in localStorage, sessionStorage, IndexedDB, or persist them unencrypted in any client-side storage.

Engineers MUST NOT store raw PRF output, intermediate HKDF buffers, or derived CryptoKey instances in localStorage, sessionStorage, IndexedDB, or persist them unencrypted in any client-side storage.

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 set `extractable

Code MUST set `extractable: false` on all WebCrypto `CryptoKey` imports resulting from PRF key derivations to prevent memory scraping and DOM-based 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.
5

Services MUST enforce `userVerification

Services MUST enforce `userVerification: 'required'` during credential generation and assertion when PRF keys are derived to guarantee biometric or PIN presence.

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 transmit raw PRF inputs (`first`, `second` evaluation buffers) or raw PRF outputs to the backend server or over network transports.

Components NEVER transmit raw PRF inputs (`first`, `second` evaluation buffers) or raw PRF outputs to the backend server or over network transports.

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 Hardware-Bound WebAuthn PRF Zero-Knowledge Key Derivation Standard critical for AI coding assistants?

Enforces strict implementation invariants for client-side cryptographic key derivation using WebAuthn Level 3 Pseudo-Random Function (PRF) extensions (HMAC-secret). Guarantees that derived symmetric keys bound to hardware authenticators are never exported, stored in persistent plaintext, or transmitted over network boundaries, ensuring absolute zero-knowledge client-side encryption. 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 (Deriving Encryption Keys from Insecure Authenticators or Caching Raw PRF Evaluation Outputs in Memory or LocalStorage) 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

Hardware-Bound