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

Hardware-Backed PRF Client-Side Zero-Knowledge Key Derivation

Enforces strict WebAuthn Level 3 Pseudo-Random Function (PRF) extension invariants for local cryptographic key derivation. Guarantees that hardware-bound secrets evaluated via CTAP2 HMAC-secret remain isolated within client-side WebCrypto enclaves and are never transmitted to relying parties or stored extractably.

Prohibited Anti-Pattern: Transmitting Raw PRF Outputs or Derived Encryption Keys to Relying Party Servers

Export Ready-to-Drop Configuration

Select format below to copy code or download file directly.

---
description: Hardware-Backed PRF Client-Side Zero-Knowledge Key Derivation - Enforces strict WebAuthn Level 3 Pseudo-Random Function (PRF) extension invariants for local cryptographic key derivation. Guarantees that hardware-bound secrets evaluated via CTAP2 HMAC-secret remain isolated within client-side WebCrypto enclaves and are never transmitted to relying parties or stored extractably.
globs: src/**/*.{ts,tsx}, lib/**/*.{ts,tsx}, packages/auth/**/*.{ts,tsx}
alwaysApply: true
verified_by: "agentrules.org"
license: "CC-BY-4.0"
source: "https://agentrules.org/rules/webauthn-prf-client-key-derivation-security"
---

# Hardware-Backed PRF Client-Side Zero-Knowledge Key Derivation

> **Severity**: CRITICAL | **Category**: security
> **Anti-Pattern Warning**: Transmitting Raw PRF Outputs or Derived Encryption Keys to Relying Party Servers

## System Constraints
You are a Principal Security Architect enforcing the WebAuthn Level 3 PRF (Pseudo-Random Function) Client-Side Key Derivation Standard. All cryptographic keys derived through authenticator PRF outputs must strictly reside in non-extractable WebCrypto CryptoKey handles. You must reject any architecture or implementation that transmits PRF evaluation outputs, salts derived from predictable data, or resulting master keys over the network to the relying party or persists them unencrypted in non-volatile client storage.

## Strict Guidelines
- Engineers MUST ALWAYS verify browser and authenticator support for the 'prf' extension prior to requesting key derivation via PublicKeyCredential.getClientExtensionResults().
- Engineers MUST NOT transmit raw PRF output buffers (AuthenticationExtensionsClientOutputs.prf) to the relying party backend or embed them in network requests.
- Code MUST pass PRF outputs directly into window.crypto.subtle.importKey as raw key material with extractable: false to prevent memory scraping or exfiltration.
- Services MUST execute HKDF (RFC 5869) with SHA-256 and explicit domain-separation info strings (e.g., 'app-vault-encryption-v1') before using derived keys for AES-GCM or ChaCha20-Poly1305 operations.
- Components NEVER store derived CryptoKey instances, PRF results, or intermediate keying material in localStorage, sessionStorage, unencrypted IndexedDB, or component state caches.
- Code MUST use cryptographically secure random bytes (crypto.getRandomValues) or server-authenticated constant salts for the PRF eval input salt.
- Services MUST cleanly revoke or garbage collect sensitive buffers by overwriting Uint8Array inputs with zeros immediately after importing into WebCrypto.

## Bad vs Good Implementations
### WebAuthn L3 PRF Invariant Derivation vs Server Leakage

#### Bad Antipattern (AI Common Hallucination)
> **Why it fails**: Violates the zero-knowledge model by serializing and transmitting raw PRF output buffers to the relying party server. Also lacks domain separation, proper WebCrypto encapsulation, and memory-wiping guards.
```typescript
import { get } from '@github/webauthn-json';

export async function deriveClientKeyBad(credentialId: string, salt: Uint8Array) {
  // Anti-pattern: Requesting PRF and transmitting raw PRF results to the backend API
  const credential = await navigator.credentials.get({
    publicKey: {
      challenge: new Uint8Array(32),
      allowCredentials: [{ id: new Uint8Array(16), type: 'public-key' }],
      extensions: {
        prf: { eval: { first: salt } }
      }
    }
  }) as PublicKeyCredential;

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

  // CRITICAL VULNERABILITY: Leaking raw hardware-bound secret to relying party
  await fetch('/api/user/sync-key', {
    method: 'POST',
    headers: { 'Content-Type': 'application/json' },
    body: JSON.stringify({
      credentialId,
      rawPrfSecret: Array.from(new Uint8Array(prfResult as ArrayBuffer))
    })
  });

  return prfResult;
}
```

#### Production Standard (Correct)
> **Standard**: Strictly preserves hardware-backed zero-knowledge guarantees. Imports PRF evaluation directly into non-extractable WebCrypto handles, applies domain-separated HKDF (SHA-256), wipes the raw evaluation buffer from memory, and never transmits intermediate secrets to the network.
```typescript
export interface DerivedCipherEnclave {
  key: CryptoKey;
  algorithm: 'AES-GCM';
}

export async function deriveClientKeySecure(
  allowCredentialId: Uint8Array,
  salt: Uint8Array
): Promise<DerivedCipherEnclave> {
  if (!window.crypto?.subtle) {
    throw new Error('WebCrypto is not supported in this environment');
  }

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

  if (!credential) {
    throw new Error('Assertion failed or canceled by user');
  }

  const extensionOutputs = credential.getClientExtensionResults();
  const prfBuffer = extensionOutputs.prf?.results?.first;
  if (!prfBuffer) {
    throw new Error('Authenticator does not support Level 3 PRF extension');
  }

  // Step 1: Import raw PRF output non-extractably as HKDF base key material
  const basePrfKey = await window.crypto.subtle.importKey(
    'raw',
    prfBuffer,
    { name: 'HKDF' },
    false,
    ['deriveKey']
  );

  // Step 2: Zeroize intermediate byte array if available in local scope
  new Uint8Array(prfBuffer).fill(0);

  // Step 3: Enforce domain-separated HKDF derivation to non-extractable AES-GCM key
  const domainInfo = new TextEncoder().encode('zero-knowledge-vault-v1');
  const derivedKey = await window.crypto.subtle.deriveKey(
    {
      name: 'HKDF',
      hash: 'SHA-256',
      salt: new Uint8Array(32), // Authenticated constant or application-scoped salt
      info: domainInfo
    },
    basePrfKey,
    { name: 'AES-GCM', length: 256 },
    false, // extractable: false guarantees key material never leaves client enclave
    ['encrypt', 'decrypt']
  );

  return {
    key: derivedKey,
    algorithm: 'AES-GCM'
  };
}
```

Recommended MCP Servers (mcp-serverlist.com)

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

Architectural Specification & Invariant Rationale

Architectural Invariant Design: Hardware-Backed PRF Client-Side Zero-Knowledge Key Derivation

Hardware-Backed PRF Client-Side Zero-Knowledge Key Derivation defines an industrial-grade behavioral standard for security engineering. Enforces strict WebAuthn Level 3 Pseudo-Random Function (PRF) extension invariants for local cryptographic key derivation. Guarantees that hardware-bound secrets evaluated via CTAP2 HMAC-secret remain isolated within client-side WebCrypto enclaves and are never transmitted to relying parties or stored extractably. 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: Transmitting Raw PRF Outputs or Derived Encryption Keys to Relying Party Servers 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 DriftTransmitting Raw PRF Outputs or Derived Encryption Keys to Relying Party ServersCritical
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 browser and authenticator support for the 'prf' extension prior to requesting key derivation via PublicKeyCredential.getClientExtensionResults().

Engineers MUST ALWAYS verify browser and authenticator support for the 'prf' extension prior to requesting key derivation via PublicKeyCredential.getClientExtensionResults().

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 output buffers (AuthenticationExtensionsClientOutputs.prf) to the relying party backend or embed them in network requests.

Engineers MUST NOT transmit raw PRF output buffers (AuthenticationExtensionsClientOutputs.prf) to the relying party backend or embed them in network requests.

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 pass PRF outputs directly into window.crypto.subtle.importKey as raw key material with extractable

Code MUST pass PRF outputs directly into window.crypto.subtle.importKey as raw key material with extractable: false to prevent memory scraping or exfiltration.

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 execute HKDF (RFC 5869) with SHA-256 and explicit domain-separation info strings (e.g., 'app-vault-encryption-v1') before using derived keys for AES-GCM or ChaCha20-Poly1305 operations.

Services MUST execute HKDF (RFC 5869) with SHA-256 and explicit domain-separation info strings (e.g., 'app-vault-encryption-v1') before using derived keys for AES-GCM or ChaCha20-Poly1305 operations.

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 CryptoKey instances, PRF results, or intermediate keying material in localStorage, sessionStorage, unencrypted IndexedDB, or component state caches.

Components NEVER store derived CryptoKey instances, PRF results, or intermediate keying material in localStorage, sessionStorage, unencrypted IndexedDB, or component state caches.

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 use cryptographically secure random bytes (crypto.getRandomValues) or server-authenticated constant salts for the PRF eval input salt.

Code MUST use cryptographically secure random bytes (crypto.getRandomValues) or server-authenticated constant salts for the PRF eval input salt.

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 cleanly revoke or garbage collect sensitive buffers by overwriting Uint8Array inputs with zeros immediately after importing into WebCrypto.

Services MUST cleanly revoke or garbage collect sensitive buffers by overwriting Uint8Array inputs with zeros immediately after importing into WebCrypto.

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

Enforces strict WebAuthn Level 3 Pseudo-Random Function (PRF) extension invariants for local cryptographic key derivation. Guarantees that hardware-bound secrets evaluated via CTAP2 HMAC-secret remain isolated within client-side WebCrypto enclaves and are never transmitted to relying parties or stored extractably. 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 (Transmitting Raw PRF Outputs or Derived Encryption Keys to Relying Party Servers) 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-Backed