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

WebAuthn PRF Hardware-Backed Deterministic Client Key Derivation Invariant

Enforces strict zero-knowledge end-to-end data encryption at rest in client-side persistence layers by anchoring root key derivation to hardware-backed FIDO2/WebAuthn PRF (Pseudo-Random Function) authenticator extensions. Mandates fail-closed semantics, HKDF-SHA-256 context separation, in-memory ephemeral key handling, and zero network transmission of derived secret material.

Prohibited Anti-Pattern: Persisting raw PRF outputs, bypassing HKDF domain separation, or transmitting hardware-derived secrets across network boundaries

Export Ready-to-Drop Configuration

Select format below to copy code or download file directly.

---
description: WebAuthn PRF Hardware-Backed Deterministic Client Key Derivation Invariant - Enforces strict zero-knowledge end-to-end data encryption at rest in client-side persistence layers by anchoring root key derivation to hardware-backed FIDO2/WebAuthn PRF (Pseudo-Random Function) authenticator extensions. Mandates fail-closed semantics, HKDF-SHA-256 context separation, in-memory ephemeral key handling, and zero network transmission of derived secret material.
globs: src/crypto/**/*.{ts,tsx}, src/auth/**/*.{ts,tsx}, src/storage/**/*.{ts,tsx}, src/services/**/*.{ts,tsx}
alwaysApply: true
verified_by: "agentrules.org"
license: "CC-BY-4.0"
source: "https://agentrules.org/rules/webauthn-prf-client-key-derivation-guardrail"
---

# WebAuthn PRF Hardware-Backed Deterministic Client Key Derivation Invariant

> **Severity**: CRITICAL | **Category**: security
> **Anti-Pattern Warning**: Persisting raw PRF outputs, bypassing HKDF domain separation, or transmitting hardware-derived secrets across network boundaries

## System Constraints
You are a Principal Security Architect enforcing the WebAuthn PRF Extension Client-Side Key Derivation Invariant. Your mandate is to guarantee zero-knowledge encryption invariants: PRF outputs from hardware authenticators must never leak to the server, must never be persisted in unencrypted client storage, must always use HKDF for domain-separated subkey generation, and must fail closed if the hardware authenticator does not support the PRF extension.

## Strict Guidelines
- Engineers MUST ALWAYS feed the raw WebAuthn PRF output (`results.prf.results.first`) into an RFC 5869 HKDF-SHA-256 derivation stage before using it for encryption or indexing.
- Engineers MUST ALWAYS provide distinct cryptographic `info` parameters during HKDF expansion for different subsystems (e.g., 'app-db-encryption-v1', 'app-search-index-v1').
- Engineers MUST NEVER transmit raw PRF output buffers, derived root keys, or client-side master keys across any network transport (HTTP, WebSocket, WebRTC, Telemetry).
- Engineers MUST NEVER persist the raw PRF evaluation secret or derived raw key bytes into unencrypted LocalStorage, SessionStorage, Cookies, or IndexedDB.
- Code MUST fail closed immediately with a typed cryptographic error when `getClientExtensionResults().prf` returns undefined or empty, rejecting fallback to insecure pseudo-random generation in zero-knowledge mode.
- Code SHOULD zeroize/overwrite raw Uint8Array buffers containing temporary PRF output bytes immediately after importing into `SubtleCrypto.importKey` as an extractable: false `CryptoKey`.
- Components NEVER accept server-provided entropy as the sole PRF salt; client-side application salts MUST be deterministically generated or pinned with high entropy.

## Bad vs Good Implementations
### Anti-Pattern: Raw PRF Direct Usage, Missing HKDF, and Storage Leak

#### Bad Antipattern (AI Common Hallucination)
> **Why it fails**: This anti-pattern commits three critical security violations: it falls back silently when PRF is missing instead of failing closed; it sends the PRF secret to the backend API, destroying zero-knowledge architecture; and it persists raw master key material into localStorage, exposing it to XSS and disk exfiltration.
```typescript
import { openDB } from 'idb';

export async function unlockUserDatabase(credentialId: Uint8Array): Promise<void> {
  const credential = (await navigator.credentials.get({
    publicKey: {
      challenge: new Uint8Array(32),
      allowCredentials: [{ id: credentialId, type: 'public-key' }],
      extensions: {
        prf: {
          eval: { first: new TextEncoder().encode('database-salt') },
        },
      },
    },
  })) as PublicKeyCredential;

  const extensionResults = credential.getClientExtensionResults();
  // VULNERABILITY 1: Unchecked fallback allowing unencrypted or mock operation
  const rawPrfKey = extensionResults.prf?.results?.first;
  if (!rawPrfKey) {
    console.warn('PRF not supported, using hardcoded fallback');
    return;
  }

  // VULNERABILITY 2: Leaking hardware secret to the backend for 'verification'
  await fetch('/api/verify-key', {
    method: 'POST',
    body: JSON.stringify({ key: Array.from(new Uint8Array(rawPrfKey)) }),
  });

  // VULNERABILITY 3: Storing raw derived key unencrypted in LocalStorage
  localStorage.setItem('master_key', Buffer.from(rawPrfKey).toString('hex'));
}
```

#### Production Standard (Correct)
> **Standard**: The compliant implementation guarantees zero-knowledge operation: it fails closed if the authenticator lacks PRF support, imports the raw output as a non-extractable HKDF master secret, derives dedicated AES-GCM-256 keys using domain-separated 'info' parameters, zeroes out the temporary PRF buffer immediately in a finally block, and never transmits or persists raw secrets.
```typescript
export class ZeroKnowledgeKeyDerivationError extends Error {
  constructor(message: string) {
    super(message);
    this.name = 'ZeroKnowledgeKeyDerivationError';
  }
}

interface DerivedApplicationKeys {
  encryptionKey: CryptoKey;
}

export async function deriveClientKeysWithPrf(
  credentialId: BufferSource,
  applicationSalt: Uint8Array
): Promise<DerivedApplicationKeys> {
  if (!window.crypto?.subtle) {
    throw new ZeroKnowledgeKeyDerivationError('WebCrypto subtle is unavailable');
  }

  const challenge = new Uint8Array(32);
  crypto.getRandomValues(challenge);

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

  if (!credential) {
    throw new ZeroKnowledgeKeyDerivationError('Authentication failed: Authenticator rejected assertion');
  }

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

  // INVARIANT 1: Strict Fail-Closed Verification
  if (!rawPrfBuffer) {
    throw new ZeroKnowledgeKeyDerivationError(
      'Hardware authenticator does not support or permit the WebAuthn PRF extension'
    );
  }

  let prfIkmKey: CryptoKey | null = null;
  try {
    // INVARIANT 2: Import raw PRF output as non-extractable HKDF master secret
    prfIkmKey = await crypto.subtle.importKey(
      'raw',
      rawPrfBuffer,
      'HKDF',
      false,
      ['deriveKey']
    );

    // INVARIANT 3: HKDF domain separation with context-specific info
    const encryptionKey = await crypto.subtle.deriveKey(
      {
        name: 'HKDF',
        hash: 'SHA-256',
        salt: new Uint8Array(32), // Fixed or salt-expanded zero-point salt
        info: new TextEncoder().encode('client-payload-storage-aes-gcm-256-v1'),
      },
      prfIkmKey,
      { name: 'AES-GCM', length: 256 },
      false, // Never extractable
      ['encrypt', 'decrypt']
    );

    return { encryptionKey };
  } finally {
    // INVARIANT 4: Zeroize ephemeral memory buffer holding PRF raw material
    new Uint8Array(rawPrfBuffer).fill(0);
  }
}
```

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 Hardware-Backed Deterministic Client Key Derivation Invariant

WebAuthn PRF Hardware-Backed Deterministic Client Key Derivation Invariant defines an industrial-grade behavioral standard for security engineering. Enforces strict zero-knowledge end-to-end data encryption at rest in client-side persistence layers by anchoring root key derivation to hardware-backed FIDO2/WebAuthn PRF (Pseudo-Random Function) authenticator extensions. Mandates fail-closed semantics, HKDF-SHA-256 context separation, in-memory ephemeral key handling, and zero network transmission of derived secret material. 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: Persisting raw PRF outputs, bypassing HKDF domain separation, or transmitting hardware-derived secrets across network boundaries 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 DriftPersisting raw PRF outputs, bypassing HKDF domain separation, or transmitting hardware-derived secrets across network boundariesCritical
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 feed the raw WebAuthn PRF output (`results.prf.results.first`) into an RFC 5869 HKDF-SHA-256 derivation stage before using it for encryption or indexing.

Engineers MUST ALWAYS feed the raw WebAuthn PRF output (`results.prf.results.first`) into an RFC 5869 HKDF-SHA-256 derivation stage before using it for encryption or indexing.

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 provide distinct cryptographic `info` parameters during HKDF expansion for different subsystems (e.g., 'app-db-encryption-v1', 'app-search-index-v1').

Engineers MUST ALWAYS provide distinct cryptographic `info` parameters during HKDF expansion for different subsystems (e.g., 'app-db-encryption-v1', 'app-search-index-v1').

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 output buffers, derived root keys, or client-side master keys across any network transport (HTTP, WebSocket, WebRTC, Telemetry).

Engineers MUST NEVER transmit raw PRF output buffers, derived root keys, or client-side master keys across any network transport (HTTP, WebSocket, WebRTC, 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.
4

Engineers MUST NEVER persist the raw PRF evaluation secret or derived raw key bytes into unencrypted LocalStorage, SessionStorage, Cookies, or IndexedDB.

Engineers MUST NEVER persist the raw PRF evaluation secret or derived raw key bytes into unencrypted LocalStorage, SessionStorage, Cookies, or IndexedDB.

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 fail closed immediately with a typed cryptographic error when `getClientExtensionResults().prf` returns undefined or empty, rejecting fallback to insecure pseudo-random generation in zero-knowledge mode.

Code MUST fail closed immediately with a typed cryptographic error when `getClientExtensionResults().prf` returns undefined or empty, rejecting fallback to insecure pseudo-random generation in zero-knowledge mode.

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 SHOULD zeroize/overwrite raw Uint8Array buffers containing temporary PRF output bytes immediately after importing into `SubtleCrypto.importKey` as an extractable

Code SHOULD zeroize/overwrite raw Uint8Array buffers containing temporary PRF output bytes immediately after importing into `SubtleCrypto.importKey` as an extractable: false `CryptoKey`.

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 accept server-provided entropy as the sole PRF salt

Components NEVER accept server-provided entropy as the sole PRF salt; client-side application salts MUST be deterministically generated or pinned with high entropy.

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 Hardware-Backed Deterministic Client Key Derivation Invariant critical for AI coding assistants?

Enforces strict zero-knowledge end-to-end data encryption at rest in client-side persistence layers by anchoring root key derivation to hardware-backed FIDO2/WebAuthn PRF (Pseudo-Random Function) authenticator extensions. Mandates fail-closed semantics, HKDF-SHA-256 context separation, in-memory ephemeral key handling, and zero network transmission of derived secret material. 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 (Persisting raw PRF outputs, bypassing HKDF domain separation, or transmitting hardware-derived secrets across network boundaries) 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