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 Level 3 PRF Hardware-Bound Zero-Knowledge Key Derivation

Enforces strict cryptographic invariants for WebAuthn Level 3 PRF (Pseudo-Random Function) extension usage to derive symmetric encryption keys directly within authenticator hardware. Guarantees client-side zero-knowledge execution by isolating salt inputs and ephemeral outputs, mandating HKDF expansion into non-exportable CryptoKey objects, and immediately zeroizing transient memory buffers.

Prohibited Anti-Pattern: Deriving master cryptographic secrets via software KDFs using raw credential IDs or exporting PRF evaluation outputs to plain strings in memory

Export Ready-to-Drop Configuration

Select format below to copy code or download file directly.

---
description: WebAuthn Level 3 PRF Hardware-Bound Zero-Knowledge Key Derivation - Enforces strict cryptographic invariants for WebAuthn Level 3 PRF (Pseudo-Random Function) extension usage to derive symmetric encryption keys directly within authenticator hardware. Guarantees client-side zero-knowledge execution by isolating salt inputs and ephemeral outputs, mandating HKDF expansion into non-exportable CryptoKey objects, and immediately zeroizing transient memory buffers.
globs: src/auth/**/*.{ts,tsx}, src/crypto/**/*.{ts,tsx}, src/services/**/*.{ts,tsx}, src/lib/webauthn/**/*.{ts,tsx}
alwaysApply: true
verified_by: "agentrules.org"
license: "CC-BY-4.0"
source: "https://agentrules.org/rules/webauthn-prf-key-derivation-standard"
---

# WebAuthn Level 3 PRF Hardware-Bound Zero-Knowledge Key Derivation

> **Severity**: CRITICAL | **Category**: security
> **Anti-Pattern Warning**: Deriving master cryptographic secrets via software KDFs using raw credential IDs or exporting PRF evaluation outputs to plain strings in memory

## System Constraints
You are a Principal Security Engineer enforcing the WebAuthn Level 3 PRF (Pseudo-Random Function) Key Derivation Standard. You must mandate that all symmetric key derivations leverage the WebAuthn hardware-bound PRF extension ('prf') directly within FIDO2/WebAuthn authenticators. Ensure fallback protection is prohibited for zero-knowledge domains, PRF salts are cryptographically distinct per purpose using high-entropy seeds, outputs are imported into non-extractable WebCrypto handles (CryptoKey) via HKDF, and all transient typed arrays are defensively zeroized using zeroization passes to eliminate heap residual leaks.

## Strict Guidelines
- Engineers MUST ALWAYS verify navigator.credentials and PublicKeyCredential.isUserVerifyingPlatformAuthenticatorAvailable() prior to initiating PRF evaluations.
- Engineers MUST request the 'prf' extension explicitly during both registration (navigator.credentials.create with extensions: { prf: {} }) and authentication assertions (navigator.credentials.get with extensions: { prf: { eval: { first: Uint8Array } } }).
- Engineers MUST NOT persist or transmit the evaluated PRF output (results.first or results.second) over the network or serialize it into localStorage, IndexedDB, or plain memory structures.
- Engineers MUST IMMEDIATELY ingest the raw PRF evaluation bytes into the WebCrypto API using subtle.importKey with extractable: false to construct non-exportable CryptoKey instances.
- Code MUST explicitly wipe transient Uint8Array buffers holding raw PRF evaluations by calling buffer.fill(0) inside finally blocks immediately following key import.
- Services MUST enforce that the derived key is expanded using HKDF-SHA-256 with distinct domain separation info strings before executing AES-GCM-256 encryption or decryption.
- Components NEVER fall back to weak password-derived keys (e.g. PBKDF2/scrypt over a user password) in PRF-designated zero-knowledge workflows without strict authorization and explicit telemetry.

## Bad vs Good Implementations
### Hardware PRF Derivation vs Insecure Software Memory Handling

#### Bad Antipattern (AI Common Hallucination)
> **Why it fails**: Derives secrets using standard client-side hashing without hardware PRF guarantees, relies on predictable credential IDs, and converts sensitive cryptographic key material into a heap-allocated string vulnerable to exfiltration.
```typescript
export async function deriveEncryptionKey(credentialId: string): Promise<string> {
  // Anti-pattern: Simulating hardware derivation in software memory
  // Exposes derivation logic to heap inspection, lacks hardware isolation
  const encoder = new TextEncoder();
  const rawMaterial = encoder.encode(credentialId + 'app-master-secret');
  const hash = await crypto.subtle.digest('SHA-256', rawMaterial);
  // Leaking raw master secret to string and memory
  return Array.from(new Uint8Array(hash))
    .map((b) => b.toString(16).padStart(2, '0'))
    .join('');
}
```

#### Production Standard (Correct)
> **Standard**: Requests PRF evaluation on the authenticator hardware using a 32-byte salt, imports the hardware output as a non-extractable HKDF master key, expands it into an AES-GCM non-exportable CryptoKey with explicit info context, and deterministically zeroizes transient memory in a finally block.
```typescript
export async function deriveHardwareKey(
  credentialId: Uint8Array,
  domainSalt: Uint8Array,
  infoString: string
): Promise<CryptoKey> {
  // Production pattern: WebAuthn Level 3 PRF zero-knowledge derivation
  if (domainSalt.byteLength !== 32) {
    throw new Error('PRF salt must be 32 bytes of cryptographically secure randomness');
  }

  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: domainSalt }
        }
      }
    }
  }) as PublicKeyCredential | null;

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

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

  if (!prfResult) {
    throw new Error('PRF extension is unsupported or not enabled on this authenticator');
  }

  const transientPrfBytes = new Uint8Array(prfResult);
  try {
    const baseKey = await crypto.subtle.importKey(
      'raw',
      transientPrfBytes,
      { name: 'HKDF' },
      false,
      ['deriveKey']
    );

    return await crypto.subtle.deriveKey(
      {
        name: 'HKDF',
        hash: 'SHA-256',
        salt: new Uint8Array(32), // Independent HKDF salt
        info: new TextEncoder().encode(infoString)
      },
      baseKey,
      { name: 'AES-GCM', length: 256 },
      false, // Invariant: Root key is non-exportable
      ['encrypt', 'decrypt']
    );
  } finally {
    // Invariant: Immediate memory zeroization of raw PRF output
    transientPrfBytes.fill(0);
  }
}
```

Architectural Specification & Invariant Rationale

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

WebAuthn Level 3 PRF Hardware-Bound Zero-Knowledge Key Derivation defines an industrial-grade behavioral standard for security engineering. Enforces strict cryptographic invariants for WebAuthn Level 3 PRF (Pseudo-Random Function) extension usage to derive symmetric encryption keys directly within authenticator hardware. Guarantees client-side zero-knowledge execution by isolating salt inputs and ephemeral outputs, mandating HKDF expansion into non-exportable CryptoKey objects, and immediately zeroizing transient memory buffers. 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 master cryptographic secrets via software KDFs using raw credential IDs or exporting PRF evaluation outputs to plain strings in memory 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 master cryptographic secrets via software KDFs using raw credential IDs or exporting PRF evaluation outputs to plain strings in memoryCritical
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 navigator.credentials and PublicKeyCredential.isUserVerifyingPlatformAuthenticatorAvailable() prior to initiating PRF evaluations.

Engineers MUST ALWAYS verify navigator.credentials and PublicKeyCredential.isUserVerifyingPlatformAuthenticatorAvailable() prior to initiating PRF evaluations.

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 request the 'prf' extension explicitly during both registration (navigator.credentials.create with extensions

Engineers MUST request the 'prf' extension explicitly during both registration (navigator.credentials.create with extensions: { prf: {} }) and authentication assertions (navigator.credentials.get with extensions: { prf: { eval: { first: Uint8Array } } }).

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 persist or transmit the evaluated PRF output (results.first or results.second) over the network or serialize it into localStorage, IndexedDB, or plain memory structures.

Engineers MUST NOT persist or transmit the evaluated PRF output (results.first or results.second) over the network or serialize it into localStorage, IndexedDB, or plain memory structures.

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 IMMEDIATELY ingest the raw PRF evaluation bytes into the WebCrypto API using subtle.importKey with extractable

Engineers MUST IMMEDIATELY ingest the raw PRF evaluation bytes into the WebCrypto API using subtle.importKey with extractable: false to construct non-exportable CryptoKey instances.

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 wipe transient Uint8Array buffers holding raw PRF evaluations by calling buffer.fill(0) inside finally blocks immediately following key import.

Code MUST explicitly wipe transient Uint8Array buffers holding raw PRF evaluations by calling buffer.fill(0) inside finally blocks immediately following key import.

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

Services MUST enforce that the derived key is expanded using HKDF-SHA-256 with distinct domain separation info strings before executing AES-GCM-256 encryption or decryption.

Services MUST enforce that the derived key is expanded using HKDF-SHA-256 with distinct domain separation info strings before executing AES-GCM-256 encryption or decryption.

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

Components NEVER fall back to weak password-derived keys (e.g. PBKDF2/scrypt over a user password) in PRF-designated zero-knowledge workflows without strict authorization and explicit telemetry.

Components NEVER fall back to weak password-derived keys (e.g. PBKDF2/scrypt over a user password) in PRF-designated zero-knowledge workflows without strict authorization and explicit telemetry.

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

Enforces strict cryptographic invariants for WebAuthn Level 3 PRF (Pseudo-Random Function) extension usage to derive symmetric encryption keys directly within authenticator hardware. Guarantees client-side zero-knowledge execution by isolating salt inputs and ephemeral outputs, mandating HKDF expansion into non-exportable CryptoKey objects, and immediately zeroizing transient memory buffers. 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 master cryptographic secrets via software KDFs using raw credential IDs or exporting PRF evaluation outputs to plain strings in memory) 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