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

Mandate HKDF Domain Separation and Zero-Knowledge Invariants for WebAuthn PRF Key Derivation

WebAuthn PRF (Pseudo-Random Function) extension derives deterministic symmetric key material directly inside hardware authenticators for client-side encryption. Applications must strictly mandate HKDF-SHA-256 expansion with domain separation on the PRF output, verify authenticator extension support before cryptographic operations, and never allow the raw authenticator output to be utilized directly as a cipher key or transmitted to servers.

Prohibited Anti-Pattern: Direct Cipher Instantiation with Raw PRF Output Lacking HKDF Domain Separation and Secure Buffer Zeroization

Export Ready-to-Drop Configuration

Select format below to copy code or download file directly.

---
description: Mandate HKDF Domain Separation and Zero-Knowledge Invariants for WebAuthn PRF Key Derivation - WebAuthn PRF (Pseudo-Random Function) extension derives deterministic symmetric key material directly inside hardware authenticators for client-side encryption. Applications must strictly mandate HKDF-SHA-256 expansion with domain separation on the PRF output, verify authenticator extension support before cryptographic operations, and never allow the raw authenticator output to be utilized directly as a cipher key or transmitted to servers.
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-client-side-key-derivation-guardrail"
---

# Mandate HKDF Domain Separation and Zero-Knowledge Invariants for WebAuthn PRF Key Derivation

> **Severity**: CRITICAL | **Category**: security
> **Anti-Pattern Warning**: Direct Cipher Instantiation with Raw PRF Output Lacking HKDF Domain Separation and Secure Buffer Zeroization

## System Constraints
You are a Principal Cryptographic Systems Architect enforcing WebAuthn PRF (Pseudo-Random Function) client-side key derivation invariants. Never allow engineers to use raw authenticator PRF outputs directly as encryption keys. Mandate HKDF-SHA-256 context-bound derivation, ensure explicit check for PRF support in authenticator responses, enforce zero-knowledge architecture where neither raw keys nor derived keys are transmitted or persisted unencrypted, and scrub intermediate key material from memory.

## Strict Guidelines
- Engineers MUST ALWAYS run authenticator PRF output through HKDF-SHA-256 with distinct domain-separation `info` and `salt` parameters before instantiating AES-256-GCM or ChaCha20-Poly1305 ciphers.
- Engineers MUST NOT use raw PRF output (`results.prf.first` or `results.prf.second`) directly as an encryption or MAC key.
- Engineers MUST ALWAYS verify that `assertion.getClientExtensionResults().prf?.results` exists and contains non-null derivation output before proceeding with decryption workflows.
- Engineers MUST explicitly handle authenticators lacking PRF capabilities without falling back to insecure, hardcoded, or server-derived keys without explicit authorization and user consent.
- Code MUST zero out raw PRF output arrays (`Uint8Array.fill(0)`) immediately after importing the keying material into `SubtleCrypto`.
- Services MUST NEVER transmit raw PRF inputs, salt seeds, or derived encryption keys to the server; only encrypted ciphertext, IVs, and public cryptographic parameters may traverse the boundary.

## Bad vs Good Implementations
### WebAuthn PRF Key Derivation & AES-GCM Key Generation

#### Bad Antipattern (AI Common Hallucination)
> **Why it fails**: Raw PRF output is directly imported as an AES-GCM key without HKDF-SHA-256 derivation. This violates cryptographic domain separation, risks key reuse collisions across different encryption targets, neglects validation of the extension payload, and leaves raw hardware key buffers in client memory.
```typescript
async function deriveVaultKeyBad(credentialId: Uint8Array, salt: Uint8Array): Promise<CryptoKey> {
  // VULNERABLE: Direct consumption of PRF output without HKDF domain separation
  const assertion = await navigator.credentials.get({
    publicKey: {
      challenge: crypto.getRandomValues(new Uint8Array(32)),
      allowCredentials: [{ id: credentialId, type: 'public-key' }],
      extensions: {
        prf: {
          eval: { first: salt }
        }
      }
    }
  }) as PublicKeyCredential;

  const prfResults = (assertion.getClientExtensionResults() as any).prf;
  const rawPrfKey = prfResults.results.first;

  // DANGEROUS: Using raw PRF output directly as AES key leaves it vulnerable
  // to cross-protocol key collision and lacks context-binding.
  return crypto.subtle.importKey(
    'raw',
    rawPrfKey,
    { name: 'AES-GCM', length: 256 },
    false,
    ['encrypt', 'decrypt']
  );
}
```

#### Production Standard (Correct)
> **Standard**: Verifies PRF extension support explicitly, imports the PRF output as input keying material strictly scoped to HKDF, derives the AES-GCM cipher key with explicit cryptographic domain separation info and salt, sets non-extractable flags, and securely zeroes the raw memory buffer.
```typescript
async function deriveVaultKey(credentialId: Uint8Array, prfSalt: Uint8Array, contextInfo: string): Promise<CryptoKey> {
  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: prfSalt }
        }
      }
    }
  }) as PublicKeyCredential | null;

  if (!assertion) {
    throw new Error('Authentication failed or was aborted by user.');
  }

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

  const rawPrfBuffer = extensionResults.prf?.results?.first;
  if (!rawPrfBuffer) {
    throw new Error('Authenticator does not support WebAuthn PRF extension.');
  }

  const rawPrfArray = new Uint8Array(rawPrfBuffer);

  try {
    // Import PRF output as raw IKM (Input Keying Material) strictly for HKDF
    const initialKeyMaterial = await crypto.subtle.importKey(
      'raw',
      rawPrfArray,
      'HKDF',
      false,
      ['deriveKey']
    );

    // Derive dedicated AES-256-GCM cipher key bound to explicit context
    const derivedKey = await crypto.subtle.deriveKey(
      {
        name: 'HKDF',
        hash: 'SHA-256',
        salt: prfSalt,
        info: new TextEncoder().encode(`passkey-prf:v1:${contextInfo}`)
      },
      initialKeyMaterial,
      { name: 'AES-GCM', length: 256 },
      false,
      ['encrypt', 'decrypt']
    );

    return derivedKey;
  } finally {
    // Ensure intermediate raw secret memory is scrubbed immediately
    rawPrfArray.fill(0);
  }
}
```

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: Mandate HKDF Domain Separation and Zero-Knowledge Invariants for WebAuthn PRF Key Derivation

Mandate HKDF Domain Separation and Zero-Knowledge Invariants for WebAuthn PRF Key Derivation defines an industrial-grade behavioral standard for security engineering. WebAuthn PRF (Pseudo-Random Function) extension derives deterministic symmetric key material directly inside hardware authenticators for client-side encryption. Applications must strictly mandate HKDF-SHA-256 expansion with domain separation on the PRF output, verify authenticator extension support before cryptographic operations, and never allow the raw authenticator output to be utilized directly as a cipher key or transmitted to servers. 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: Direct Cipher Instantiation with Raw PRF Output Lacking HKDF Domain Separation and Secure Buffer Zeroization 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 DriftDirect Cipher Instantiation with Raw PRF Output Lacking HKDF Domain Separation and Secure Buffer ZeroizationCritical
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 run authenticator PRF output through HKDF-SHA-256 with distinct domain-separation `info` and `salt` parameters before instantiating AES-256-GCM or ChaCha20-Poly1305 ciphers.

Engineers MUST ALWAYS run authenticator PRF output through HKDF-SHA-256 with distinct domain-separation `info` and `salt` parameters before instantiating AES-256-GCM or ChaCha20-Poly1305 ciphers.

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 use raw PRF output (`results.prf.first` or `results.prf.second`) directly as an encryption or MAC key.

Engineers MUST NOT use raw PRF output (`results.prf.first` or `results.prf.second`) directly as an encryption or MAC 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 ALWAYS verify that `assertion.getClientExtensionResults().prf?.results` exists and contains non-null derivation output before proceeding with decryption workflows.

Engineers MUST ALWAYS verify that `assertion.getClientExtensionResults().prf?.results` exists and contains non-null derivation output before proceeding with decryption workflows.

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 explicitly handle authenticators lacking PRF capabilities without falling back to insecure, hardcoded, or server-derived keys without explicit authorization and user consent.

Engineers MUST explicitly handle authenticators lacking PRF capabilities without falling back to insecure, hardcoded, or server-derived keys without explicit authorization and user consent.

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 zero out raw PRF output arrays (`Uint8Array.fill(0)`) immediately after importing the keying material into `SubtleCrypto`.

Code MUST zero out raw PRF output arrays (`Uint8Array.fill(0)`) immediately after importing the keying material into `SubtleCrypto`.

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 NEVER transmit raw PRF inputs, salt seeds, or derived encryption keys to the server

Services MUST NEVER transmit raw PRF inputs, salt seeds, or derived encryption keys to the server; only encrypted ciphertext, IVs, and public cryptographic parameters may traverse the boundary.

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 Mandate HKDF Domain Separation and Zero-Knowledge Invariants for WebAuthn PRF Key Derivation critical for AI coding assistants?

WebAuthn PRF (Pseudo-Random Function) extension derives deterministic symmetric key material directly inside hardware authenticators for client-side encryption. Applications must strictly mandate HKDF-SHA-256 expansion with domain separation on the PRF output, verify authenticator extension support before cryptographic operations, and never allow the raw authenticator output to be utilized directly as a cipher key or transmitted to servers. 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 (Direct Cipher Instantiation with Raw PRF Output Lacking HKDF Domain Separation and Secure Buffer Zeroization) 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

Mandate