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

WebAuthn PRF Zero-Knowledge Hardware Key Derivation Invariant

Enforces strict cryptographic domain separation, zero-knowledge isolation, and memory sanitization when using the WebAuthn Pseudo-Random Function (PRF) extension. Guarantees that raw PRF outputs and derived symmetric encryption keys never leave volatile client memory, are never transmitted to relying party servers, and undergo mandatory HKDF expansion.

Prohibited Anti-Pattern: Transmitting raw PRF outputs to the server, omitting HKDF context separation, or caching hardware-derived keys in unencrypted browser storage.

Export Ready-to-Drop Configuration

Select format below to copy code or download file directly.

---
description: WebAuthn PRF Zero-Knowledge Hardware Key Derivation Invariant - Enforces strict cryptographic domain separation, zero-knowledge isolation, and memory sanitization when using the WebAuthn Pseudo-Random Function (PRF) extension. Guarantees that raw PRF outputs and derived symmetric encryption keys never leave volatile client memory, are never transmitted to relying party servers, and undergo mandatory HKDF expansion.
globs: src/**/*.{ts,tsx}, lib/**/*.{ts,tsx}, packages/crypto/**/*.{ts,tsx}
alwaysApply: true
verified_by: "agentrules.org"
license: "CC-BY-4.0"
source: "https://agentrules.org/rules/webauthn-prf-zk-hardware-key-derivation-guardrail"
---

# WebAuthn PRF Zero-Knowledge Hardware Key Derivation Invariant

> **Severity**: CRITICAL | **Category**: security
> **Anti-Pattern Warning**: Transmitting raw PRF outputs to the server, omitting HKDF context separation, or caching hardware-derived keys in unencrypted browser storage.

## System Constraints
You are a Principal Security Architect and Cryptographic Engineer. Enforce zero-knowledge WebAuthn PRF (Pseudo-Random Function) derivation invariants. Raw PRF outputs from navigator.credentials.get/create must never be transmitted to any backend, must not be persisted to localStorage/IndexedDB/sessionStorage, and must be strictly expanded into application keys via HKDF (RFC 5869) with explicit domain separation before encrypting zero-knowledge client payloads.

## Strict Guidelines
- Engineers MUST ALWAYS verify the PRF extension response via `assertion.getClientExtensionResults().prf` and immediately fail closed if the authenticator returns undefined or fails PRF negotiation.
- Engineers MUST NEVER transmit raw PRF output bytes (`prfResult.results.first` or `prfResult.results.second`) to the server or include them in any server-bound assertion verification payload.
- Engineers MUST ALWAYS pipe raw PRF output through HKDF-Extract and HKDF-Expand (HMAC-SHA-256) with unique, domain-separated `info` parameters (e.g., 'vault-payload-encryption-v1') before generating symmetric keys.
- Code MUST explicitly zero out sensitive Uint8Array buffers using `crypto.getRandomValues(buffer)` or `buffer.fill(0)` immediately after importing or deriving target CryptoKeys in volatile memory.
- Engineers MUST NOT cache derived `CryptoKey` instances in persistent storage mechanisms (IndexedDB, localStorage, sessionStorage, or Service Worker cache); keys must reside only in non-exportable memory scopes during active sessions.
- Services MUST enforce cryptographic binding between the WebAuthn credential ID and the zero-knowledge ciphertext metadata to prevent cross-credential ciphertext substitution attacks.

## Bad vs Good Implementations
### Flawed PRF Key Handling (Transmission & Direct Use Anti-Pattern)

#### Bad Antipattern (AI Common Hallucination)
> **Why it fails**: Directly sends the raw PRF result to the server (destroying zero-knowledge guarantees), uses the unexpanded PRF output directly as an AES key without HKDF domain separation, and leaks the hardware-derived key material into persistent, unencrypted localStorage.
```typescript
import { client } from './api';

export async function unlockUserVault(credentialId: string, challenge: Uint8Array) {
  const assertion = await navigator.credentials.get({
    publicKey: {
      challenge,
      allowCredentials: [{ id: Uint8Array.from(atob(credentialId), c => c.charCodeAt(0)), type: 'public-key' }],
      extensions: {
        prf: {
          eval: { first: new TextEncoder().encode('global-vault-key') }
        }
      }
    }
  }) as PublicKeyCredential;

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

  // SECURITY VIOlATION: Sending raw PRF output to server, zero-knowledge invariant broken
  await client.post('/api/vault/verify-key', {
    credentialId,
    derivedKey: Array.from(new Uint8Array(rawKey!))
  });

  // SECURITY VIOLATION: Using raw PRF output directly as AES key without HKDF domain separation
  const cryptoKey = await crypto.subtle.importKey(
    'raw',
    rawKey!,
    { name: 'AES-GCM' },
    false,
    ['encrypt', 'decrypt']
  );

  // SECURITY VIOLATION: Caching raw key material in local storage
  localStorage.setItem('cached_vault_key', btoa(String.fromCharCode(...new Uint8Array(rawKey!))));
  return cryptoKey;
}
```

#### Production Standard (Correct)
> **Standard**: Verifies PRF support gracefully, avoids transmitting any PRF output across the network, enforces RFC 5869 HKDF derivation with contextual info, imports the key as non-extractable, and rigorously zeroes out memory buffers containing raw key material in a finally block.
```typescript
const HKDF_INFO_VAULT_ENCRYPTION = new TextEncoder().encode('app.zk.vault.encryption.v1');

export async function deriveVaultEncryptionKey(
  credentialId: Uint8Array,
  serverChallenge: Uint8Array,
  vaultSalt: Uint8Array
): Promise<CryptoKey> {
  const assertion = await navigator.credentials.get({
    publicKey: {
      challenge: serverChallenge,
      allowCredentials: [{ id: credentialId, type: 'public-key' }],
      extensions: {
        prf: {
          eval: {
            first: vaultSalt // Deterministic, unique salt per vault
          }
        }
      }
    }
  }) as PublicKeyCredential | null;

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

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

  // Copy raw PRF output to a mutable buffer for zeroization
  const rawPrfBuffer = new Uint8Array(prfResults.results.first.slice(0));

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

    // Derive the non-exportable symmetric encryption key with strict context separation
    const derivedKey = await crypto.subtle.deriveKey(
      {
        name: 'HKDF',
        hash: 'SHA-256',
        salt: vaultSalt,
        info: HKDF_INFO_VAULT_ENCRYPTION
      },
      ikmKey,
      { name: 'AES-GCM', length: 256 },
      false, // Invariant: Key is non-extractable
      ['encrypt', 'decrypt']
    );

    return derivedKey;
  } finally {
    // Cryptographic hygiene: Zero out raw PRF output immediately
    crypto.getRandomValues(rawPrfBuffer);
    rawPrfBuffer.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: WebAuthn PRF Zero-Knowledge Hardware Key Derivation Invariant

WebAuthn PRF Zero-Knowledge Hardware Key Derivation Invariant defines an industrial-grade behavioral standard for security engineering. Enforces strict cryptographic domain separation, zero-knowledge isolation, and memory sanitization when using the WebAuthn Pseudo-Random Function (PRF) extension. Guarantees that raw PRF outputs and derived symmetric encryption keys never leave volatile client memory, are never transmitted to relying party servers, and undergo mandatory HKDF expansion. 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: Transmitting raw PRF outputs to the server, omitting HKDF context separation, or caching hardware-derived keys in unencrypted browser storage. 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 DriftTransmitting raw PRF outputs to the server, omitting HKDF context separation, or caching hardware-derived keys in unencrypted browser storage.Critical
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 the PRF extension response via `assertion.getClientExtensionResults().prf` and immediately fail closed if the authenticator returns undefined or fails PRF negotiation.

Engineers MUST ALWAYS verify the PRF extension response via `assertion.getClientExtensionResults().prf` and immediately fail closed if the authenticator returns undefined or fails PRF negotiation.

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 NEVER transmit raw PRF output bytes (`prfResult.results.first` or `prfResult.results.second`) to the server or include them in any server-bound assertion verification payload.

Engineers MUST NEVER transmit raw PRF output bytes (`prfResult.results.first` or `prfResult.results.second`) to the server or include them in any server-bound assertion verification payload.

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 pipe raw PRF output through HKDF-Extract and HKDF-Expand (HMAC-SHA-256) with unique, domain-separated `info` parameters (e.g., 'vault-payload-encryption-v1') before generating symmetric keys.

Engineers MUST ALWAYS pipe raw PRF output through HKDF-Extract and HKDF-Expand (HMAC-SHA-256) with unique, domain-separated `info` parameters (e.g., 'vault-payload-encryption-v1') before generating symmetric 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.
4

Code MUST explicitly zero out sensitive Uint8Array buffers using `crypto.getRandomValues(buffer)` or `buffer.fill(0)` immediately after importing or deriving target CryptoKeys in volatile memory.

Code MUST explicitly zero out sensitive Uint8Array buffers using `crypto.getRandomValues(buffer)` or `buffer.fill(0)` immediately after importing or deriving target CryptoKeys in volatile memory.

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

Engineers MUST NOT cache derived `CryptoKey` instances in persistent storage mechanisms (IndexedDB, localStorage, sessionStorage, or Service Worker cache)

Engineers MUST NOT cache derived `CryptoKey` instances in persistent storage mechanisms (IndexedDB, localStorage, sessionStorage, or Service Worker cache); keys must reside only in non-exportable memory scopes during active sessions.

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 cryptographic binding between the WebAuthn credential ID and the zero-knowledge ciphertext metadata to prevent cross-credential ciphertext substitution attacks.

Services MUST enforce cryptographic binding between the WebAuthn credential ID and the zero-knowledge ciphertext metadata to prevent cross-credential ciphertext substitution attacks.

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

Enforces strict cryptographic domain separation, zero-knowledge isolation, and memory sanitization when using the WebAuthn Pseudo-Random Function (PRF) extension. Guarantees that raw PRF outputs and derived symmetric encryption keys never leave volatile client memory, are never transmitted to relying party servers, and undergo mandatory HKDF expansion. 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 (Transmitting raw PRF outputs to the server, omitting HKDF context separation, or caching hardware-derived keys in unencrypted browser storage.) 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