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

Enforce WebAuthn Level 3 PRF Extension for Zero-Knowledge E2EE Key Derivation

Mandates client-side deterministic cryptographic key derivation via the WebAuthn Level 3 Pseudo-Random Function (PRF) extension for end-to-end encryption. Guarantees that neither raw authenticator PRF outputs nor derived encryption master keys are ever transmitted to Relying Parties (IdPs) or stored in unmanaged persistent client storage.

Prohibited Anti-Pattern: Exposing Raw PRF Outputs to Identity Providers or Omitting HKDF Domain Separation

Export Ready-to-Drop Configuration

Select format below to copy code or download file directly.

---
description: Enforce WebAuthn Level 3 PRF Extension for Zero-Knowledge E2EE Key Derivation - Mandates client-side deterministic cryptographic key derivation via the WebAuthn Level 3 Pseudo-Random Function (PRF) extension for end-to-end encryption. Guarantees that neither raw authenticator PRF outputs nor derived encryption master keys are ever transmitted to Relying Parties (IdPs) or stored in unmanaged persistent client storage.
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-e2ee-key-derivation"
---

# Enforce WebAuthn Level 3 PRF Extension for Zero-Knowledge E2EE Key Derivation

> **Severity**: CRITICAL | **Category**: security
> **Anti-Pattern Warning**: Exposing Raw PRF Outputs to Identity Providers or Omitting HKDF Domain Separation

## System Constraints
You are a Principal Cryptographic Architect enforcing secure WebAuthn Level 3 PRF (hmac-secret/prf) extension usage for zero-knowledge end-to-end encrypted (E2EE) systems. You must mandate strict client-side key derivation, enforce HKDF-SHA-256 domain separation, prohibit sending raw PRF output or master keys to relying party backends, and require fail-safe handling when authenticators lack PRF support.

## Strict Guidelines
- Engineers MUST ALWAYS process WebAuthn PRF outputs exclusively within the client-side Web Cryptography API (`crypto.subtle`) and NEVER transmit raw PRF outputs to the server or Relying Party.
- Engineers MUST ALWAYS pass raw PRF output (`results.prf.results.first`) into an HKDF (RFC 5869) key derivation step with an explicit application domain separation string (`info`) before generating symmetric cipher keys (e.g., AES-GCM-256).
- Engineers MUST NOT use the raw PRF evaluation bytes directly as an encryption or authentication key.
- Engineers MUST NOT serialize derived keys, intermediate PRF outputs, or unencrypted private key material into `localStorage`, `sessionStorage`, or indexed storage without envelope encryption.
- Code MUST verify `clientExtensionResults.prf?.enabled` during registration and verify `clientExtensionResults.prf?.results?.first` existence before attempting key derivation.
- Services MUST reject authentication payloads that attempt to include PRF execution secrets, raw salt outputs, or derived client keys in the credential transport body.
- Components NEVER fall back to weak password-derived keys or insecure pseudo-random generators if the authenticator does not support the PRF extension; they MUST raise an explicit unsupported hardware error.

## Bad vs Good Implementations
### Client-Side PRF Evaluation and HKDF Key Derivation

#### Bad Antipattern (AI Common Hallucination)
> **Why it fails**: The bad example leaks the raw PRF secret across the network boundary to the backend Relying Party, destroying the zero-knowledge E2EE guarantee. Furthermore, it imports raw PRF bytes directly as an AES-GCM key without HKDF domain separation, risking cross-protocol key reuse and cryptographic compromise.
```typescript
import { startAuthentication } from '@simplewebauthn/browser';

export async function unlockUserVault(authOptions: any) {
  // Anti-Pattern: Requesting PRF, but returning raw output to server or using raw bytes as AES key
  const assertion = await startAuthentication({
    ...authOptions,
    extensions: {
      prf: {
        eval: {
          first: new TextEncoder().encode('global-salt-value')
        }
      }
    }
  });

  const prfResults = (assertion.clientExtensionResults as any)?.prf;
  const rawPrfSecret = prfResults?.results?.first;

  // CRITICAL VULNERABILITY: Transmitting PRF output to Relying Party backend
  await fetch('/api/vault/unlock', {
    method: 'POST',
    body: JSON.stringify({ assertion, rawPrfSecret })
  });

  // CRITICAL VULNERABILITY: Direct import of raw PRF output as AES key without HKDF expansion
  return crypto.subtle.importKey(
    'raw',
    rawPrfSecret,
    { name: 'AES-GCM' },
    false,
    ['encrypt', 'decrypt']
  );
}
```

#### Production Standard (Correct)
> **Standard**: The good example treats the PRF output as raw Input Keying Material (IKM) for an HKDF derivation, incorporates application-specific context and domain separation (`info`), marks keys as non-extractable (`false`), and only transmits the standard WebAuthn response to the server without exposing cryptographic secrets.
```typescript
import { startAuthentication } from '@simplewebauthn/browser';
import type { PublicKeyCredentialRequestOptionsJSON } from '@simplewebauthn/types';

const HKDF_INFO_VAULT_ENCRYPTION = new TextEncoder().encode('org.production.vault.encryption.v1');
const DOMAIN_SALT = new TextEncoder().encode('org.production.prf.salt.e2ee.root');

export async function deriveVaultKeyFromPasskey(
  options: PublicKeyCredentialRequestOptionsJSON
): Promise<CryptoKey> {
  const assertion = await startAuthentication({
    optionsJSON: options,
    useAutoRegister: false,
  });

  // Extract PRF extension results safely
  const extensionResults = assertion.clientExtensionResults;
  const prfResult = extensionResults?.prf?.results?.first;

  if (!prfResult || !(prfResult instanceof ArrayBuffer)) {
    throw new Error('Authenticator did not return a valid PRF result. Hardware unsupported.');
  }

  // Step 1: Import raw PRF output as HKDF keying material (IKM)
  const prfKeyMaterial = await crypto.subtle.importKey(
    'raw',
    prfResult,
    { name: 'HKDF' },
    false,
    ['deriveKey']
  );

  // Step 2: Derive final AES-GCM-256 key with strict domain separation
  const derivedKey = await crypto.subtle.deriveKey(
    {
      name: 'HKDF',
      hash: 'SHA-256',
      salt: DOMAIN_SALT,
      info: HKDF_INFO_VAULT_ENCRYPTION,
    },
    prfKeyMaterial,
    { name: 'AES-GCM', length: 256 },
    false,
    ['encrypt', 'decrypt']
  );

  // Step 3: Send ONLY the standard assertion to the Relying Party (omit PRF raw output)
  const verifyResponse = await fetch('/api/auth/verify-assertion', {
    method: 'POST',
    headers: { 'Content-Type': 'application/json' },
    body: JSON.stringify(assertion),
  });

  if (!verifyResponse.ok) {
    throw new Error('Assertion verification failed on server.');
  }

  return derivedKey;
}
```

Recommended MCP Servers (mcp-serverlist.com)

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

Architectural Specification & Invariant Rationale

Architectural Invariant Design: Enforce WebAuthn Level 3 PRF Extension for Zero-Knowledge E2EE Key Derivation

Enforce WebAuthn Level 3 PRF Extension for Zero-Knowledge E2EE Key Derivation defines an industrial-grade behavioral standard for security engineering. Mandates client-side deterministic cryptographic key derivation via the WebAuthn Level 3 Pseudo-Random Function (PRF) extension for end-to-end encryption. Guarantees that neither raw authenticator PRF outputs nor derived encryption master keys are ever transmitted to Relying Parties (IdPs) or stored in unmanaged persistent client storage. 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 PRF Outputs to Identity Providers or Omitting HKDF Domain Separation 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 PRF Outputs to Identity Providers or Omitting HKDF Domain SeparationCritical
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 process WebAuthn PRF outputs exclusively within the client-side Web Cryptography API (`crypto.subtle`) and NEVER transmit raw PRF outputs to the server or Relying Party.

Engineers MUST ALWAYS process WebAuthn PRF outputs exclusively within the client-side Web Cryptography API (`crypto.subtle`) and NEVER transmit raw PRF outputs to the server or Relying Party.

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 pass raw PRF output (`results.prf.results.first`) into an HKDF (RFC 5869) key derivation step with an explicit application domain separation string (`info`) before generating symmetric cipher keys (e.g., AES-GCM-256).

Engineers MUST ALWAYS pass raw PRF output (`results.prf.results.first`) into an HKDF (RFC 5869) key derivation step with an explicit application domain separation string (`info`) before generating symmetric cipher keys (e.g., AES-GCM-256).

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 use the raw PRF evaluation bytes directly as an encryption or authentication key.

Engineers MUST NOT use the raw PRF evaluation bytes directly as an encryption or authentication 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.
4

Engineers MUST NOT serialize derived keys, intermediate PRF outputs, or unencrypted private key material into `localStorage`, `sessionStorage`, or indexed storage without envelope encryption.

Engineers MUST NOT serialize derived keys, intermediate PRF outputs, or unencrypted private key material into `localStorage`, `sessionStorage`, or indexed storage without envelope encryption.

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 verify `clientExtensionResults.prf?.enabled` during registration and verify `clientExtensionResults.prf?.results?.first` existence before attempting key derivation.

Code MUST verify `clientExtensionResults.prf?.enabled` during registration and verify `clientExtensionResults.prf?.results?.first` existence before attempting key 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.
6

Services MUST reject authentication payloads that attempt to include PRF execution secrets, raw salt outputs, or derived client keys in the credential transport body.

Services MUST reject authentication payloads that attempt to include PRF execution secrets, raw salt outputs, or derived client keys in the credential transport body.

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 or insecure pseudo-random generators if the authenticator does not support the PRF extension

Components NEVER fall back to weak password-derived keys or insecure pseudo-random generators if the authenticator does not support the PRF extension; they MUST raise an explicit unsupported hardware error.

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 Enforce WebAuthn Level 3 PRF Extension for Zero-Knowledge E2EE Key Derivation critical for AI coding assistants?

Mandates client-side deterministic cryptographic key derivation via the WebAuthn Level 3 Pseudo-Random Function (PRF) extension for end-to-end encryption. Guarantees that neither raw authenticator PRF outputs nor derived encryption master keys are ever transmitted to Relying Parties (IdPs) or stored in unmanaged persistent client storage. 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 PRF Outputs to Identity Providers or Omitting HKDF Domain Separation) 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

Enforce