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

WebAuthn PRF Deterministic Key Derivation & Zero-Knowledge Storage Invariant

Enforces strict cryptographic domain separation and ephemeral memory confinement when utilizing the WebAuthn Pseudo-Random Function (PRF) extension. Raw PRF outputs must never be transmitted to backends, persisted unencrypted, or used directly as encryption keys without HKDF expansion into non-extractable WebCrypto keys.

Prohibited Anti-Pattern: Exposing Raw Authenticator PRF Outputs or Using PRF Bytes Directly as Symmetric Keys Without Domain-Separated HKDF Expansion

Export Ready-to-Drop Configuration

Select format below to copy code or download file directly.

---
description: WebAuthn PRF Deterministic Key Derivation & Zero-Knowledge Storage Invariant - Enforces strict cryptographic domain separation and ephemeral memory confinement when utilizing the WebAuthn Pseudo-Random Function (PRF) extension. Raw PRF outputs must never be transmitted to backends, persisted unencrypted, or used directly as encryption keys without HKDF expansion into non-extractable WebCrypto keys.
globs: src/**/auth/**/*.{ts,tsx}, src/**/crypto/**/*.{ts,tsx}, src/**/security/**/*.{ts,tsx}, src/**/storage/**/*.{ts,tsx}
alwaysApply: true
verified_by: "agentrules.org"
license: "CC-BY-4.0"
source: "https://agentrules.org/rules/webauthn-prf-deterministic-key-derivation-guardrail"
---

# WebAuthn PRF Deterministic Key Derivation & Zero-Knowledge Storage Invariant

> **Severity**: CRITICAL | **Category**: security
> **Anti-Pattern Warning**: Exposing Raw Authenticator PRF Outputs or Using PRF Bytes Directly as Symmetric Keys Without Domain-Separated HKDF Expansion

## System Constraints
You are a Principal Security Architect enforcing zero-knowledge WebAuthn PRF invariants. Mandate that raw PRF outputs generated by client authenticators remain strictly client-side, non-extractable, and isolated to ephemeral memory. Ensure that all derived keys pass through HKDF with contextual domain separation before performing client-side encryption, and reject any design that transmits authenticator secrets to the relying party or persists master symmetric material into unencrypted local storage.

## Strict Guidelines
- Engineers MUST ALWAYS verify client extension results using `credential.getClientExtensionResults().prf` and validate PRF execution before attempting cryptographic operations.
- Engineers MUST ALWAYS feed raw PRF output bytes into a secondary Key Derivation Function (HKDF-SHA-256) with domain-specific `salt` and `info` parameters before use as an AES-GCM or storage encryption key.
- Engineers MUST NEVER transmit raw PRF outputs, intermediate HKDF entropy, or PRF derivation inputs containing backend secrets across the network or include them in relying party assertion verification payloads.
- Engineers MUST NEVER mark derived WebCrypto symmetric keys as `extractable: true` or serialize them into `localStorage`, `IndexedDB`, or cookies.
- Code MUST explicitly overwrite and clear raw PRF `ArrayBuffer` allocations in client memory immediately after HKDF key expansion using `crypto.getRandomValues()` or zero-fill wipes.
- Services MUST enforce that the relying party server only receives and verifies the standard WebAuthn assertion signature, maintaining complete zero-knowledge blindness to local encryption keys.

## Bad vs Good Implementations
### WebAuthn PRF Execution, HKDF Domain Separation, and Zero-Knowledge Storage

#### Bad Antipattern (AI Common Hallucination)
> **Why it fails**: The code extracts the raw PRF evaluation bytes and transmits them directly to the backend API, destroying zero-knowledge guarantees. It also fails to apply HKDF domain separation, uses PRF output directly as a key, and commits the ultimate security flaw of writing the raw master key to localStorage.
```typescript
import { startAuthentication } from '@simplewebauthn/browser';

export async function unlockLocalVault(authOptions: any): Promise<void> {
  // Anti-pattern: Missing PRF extension payload or passing raw PRF output over the wire
  const assertion = await startAuthentication(authOptions);
  const extensionResults = assertion.getClientExtensionResults() as any;
  
  // CRITICAL FLAW 1: Direct use of raw PRF output as AES key without HKDF
  const rawPrfKey = extensionResults.prf?.results?.first;
  if (!rawPrfKey) throw new Error('PRF failed');

  // CRITICAL FLAW 2: Transmitting PRF secret to backend in sync payload
  await fetch('/api/vault/sync', {
    method: 'POST',
    body: JSON.stringify({ assertion, rawPrfKey: Array.from(new Uint8Array(rawPrfKey)) })
  });

  // CRITICAL FLAW 3: Storing master secret in localStorage unencrypted
  localStorage.setItem('master_key', Buffer.from(rawPrfKey).toString('hex'));
}
```

#### Production Standard (Correct)
> **Standard**: Enforces strict domain separation using WebCrypto HKDF-SHA-256 with scoped `info` and `salt`. The derived AES-GCM key is marked non-extractable (`extractable: false`), preventing key extraction even in memory dump or XSS scenarios. Raw PRF buffers are zeroized in a `finally` block, and no cryptographic keys or PRF outputs ever leave the client.
```typescript
import { startAuthentication } from '@simplewebauthn/browser';
import type { PublicKeyCredentialWithClientExtensionResults } from '@simplewebauthn/browser';

const HKDF_INFO_VAULT_ENCRYPTION = new TextEncoder().encode('org.production.vault.encryption.v1');

export async function deriveZeroKnowledgeVaultKey(
  options: Parameters<typeof startAuthentication>[0],
  clientSalt: Uint8Array
): Promise<CryptoKey> {
  const credential = await startAuthentication({
    ...options,
    extensions: {
      ...options.extensions,
      prf: {
        eval: {
          first: clientSalt,
        },
      },
    },
  }) as PublicKeyCredentialWithClientExtensionResults;

  const extensionResults = credential.getClientExtensionResults();
  const prfResults = extensionResults.prf?.results;
  
  if (!prfResults?.first) {
    throw new Error('Authenticator does not support or failed to evaluate WebAuthn PRF extension.');
  }

  const rawPrfBuffer = new Uint8Array(prfResults.first);

  try {
    // Import PRF output as initial keying material (IKM)
    const ikmKey = await crypto.subtle.importKey(
      'raw',
      rawPrfBuffer,
      'HKDF',
      false,
      ['deriveKey']
    );

    // Derive a non-extractable AES-GCM key with explicit domain separation
    const derivedKey = await crypto.subtle.deriveKey(
      {
        name: 'HKDF',
        hash: 'SHA-256',
        salt: clientSalt,
        info: HKDF_INFO_VAULT_ENCRYPTION,
      },
      ikmKey,
      { name: 'AES-GCM', length: 256 },
      false, // non-extractable: cannot be exported or leaked via XSS memory inspection
      ['encrypt', 'decrypt']
    );

    return derivedKey;
  } finally {
    // Ephemeral memory zeroization: zero out the raw PRF buffer immediately
    crypto.getRandomValues(rawPrfBuffer);
  }
}
```

Recommended MCP Servers (mcp-serverlist.com)

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

Architectural Specification & Invariant Rationale

Architectural Invariant Design: WebAuthn PRF Deterministic Key Derivation & Zero-Knowledge Storage Invariant

WebAuthn PRF Deterministic Key Derivation & Zero-Knowledge Storage Invariant defines an industrial-grade behavioral standard for security engineering. Enforces strict cryptographic domain separation and ephemeral memory confinement when utilizing the WebAuthn Pseudo-Random Function (PRF) extension. Raw PRF outputs must never be transmitted to backends, persisted unencrypted, or used directly as encryption keys without HKDF expansion into non-extractable WebCrypto keys. 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: Exposing Raw Authenticator PRF Outputs or Using PRF Bytes Directly as Symmetric Keys Without Domain-Separated HKDF Expansion 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 DriftExposing Raw Authenticator PRF Outputs or Using PRF Bytes Directly as Symmetric Keys Without Domain-Separated HKDF ExpansionCritical
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 extension results using `credential.getClientExtensionResults().prf` and validate PRF execution before attempting cryptographic operations.

Engineers MUST ALWAYS verify client extension results using `credential.getClientExtensionResults().prf` and validate PRF execution before attempting cryptographic 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.
2

Engineers MUST ALWAYS feed raw PRF output bytes into a secondary Key Derivation Function (HKDF-SHA-256) with domain-specific `salt` and `info` parameters before use as an AES-GCM or storage encryption key.

Engineers MUST ALWAYS feed raw PRF output bytes into a secondary Key Derivation Function (HKDF-SHA-256) with domain-specific `salt` and `info` parameters before use as an AES-GCM or storage encryption 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 transmit raw PRF outputs, intermediate HKDF entropy, or PRF derivation inputs containing backend secrets across the network or include them in relying party assertion verification payloads.

Engineers MUST NEVER transmit raw PRF outputs, intermediate HKDF entropy, or PRF derivation inputs containing backend secrets across the network or include them in relying party assertion verification payloads.

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 NEVER mark derived WebCrypto symmetric keys as `extractable

Engineers MUST NEVER mark derived WebCrypto symmetric keys as `extractable: true` or serialize them into `localStorage`, `IndexedDB`, or cookies.

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 overwrite and clear raw PRF `ArrayBuffer` allocations in client memory immediately after HKDF key expansion using `crypto.getRandomValues()` or zero-fill wipes.

Code MUST explicitly overwrite and clear raw PRF `ArrayBuffer` allocations in client memory immediately after HKDF key expansion using `crypto.getRandomValues()` or zero-fill wipes.

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 relying party server only receives and verifies the standard WebAuthn assertion signature, maintaining complete zero-knowledge blindness to local encryption keys.

Services MUST enforce that the relying party server only receives and verifies the standard WebAuthn assertion signature, maintaining complete zero-knowledge blindness to local encryption keys.

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 Deterministic Key Derivation & Zero-Knowledge Storage Invariant critical for AI coding assistants?

Enforces strict cryptographic domain separation and ephemeral memory confinement when utilizing the WebAuthn Pseudo-Random Function (PRF) extension. Raw PRF outputs must never be transmitted to backends, persisted unencrypted, or used directly as encryption keys without HKDF expansion into non-extractable WebCrypto keys. 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 (Exposing Raw Authenticator PRF Outputs or Using PRF Bytes Directly as Symmetric Keys Without Domain-Separated HKDF Expansion) 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