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

Zero-Knowledge Hardware-Bound Key Derivation via WebAuthn PRF Extension

Enforces strict cryptographic boundaries when deriving symmetric encryption keys using the WebAuthn Pseudo-Random Function (PRF) extension (HMAC-secret). Raw PRF outputs must be treated as volatile cryptographic material, fed immediately into an HKDF pipeline to produce ephemeral CryptoKey instances, and zeroized in memory to prevent credential and key leakage.

Prohibited Anti-Pattern: Leaking Raw PRF Outputs, Static Salts, or Un-zeroized Crypto Material in Application Memory

Export Ready-to-Drop Configuration

Select format below to copy code or download file directly.

---
description: Zero-Knowledge Hardware-Bound Key Derivation via WebAuthn PRF Extension - Enforces strict cryptographic boundaries when deriving symmetric encryption keys using the WebAuthn Pseudo-Random Function (PRF) extension (HMAC-secret). Raw PRF outputs must be treated as volatile cryptographic material, fed immediately into an HKDF pipeline to produce ephemeral CryptoKey instances, and zeroized in memory to prevent credential and key leakage.
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-zk-symmetric-key-derivation"
---

# Zero-Knowledge Hardware-Bound Key Derivation via WebAuthn PRF Extension

> **Severity**: CRITICAL | **Category**: security
> **Anti-Pattern Warning**: Leaking Raw PRF Outputs, Static Salts, or Un-zeroized Crypto Material in Application Memory

## System Constraints
You are a Principal Security Architect enforcing Zero-Knowledge WebAuthn PRF (Pseudo-Random Function) key derivation. Raw PRF outputs from hardware authenticators must never be exported, logged, stored in persistent state, or used directly as encryption keys. Every PRF evaluation must be piped through HKDF-Extract/Expand using application-scoped domain separation contexts, producing non-extractable Web Cryptography API CryptoKey instances, followed by immediate zeroization of intermediate ArrayBuffers.

## Strict Guidelines
- Engineers MUST ALWAYS inspect navigator.credentials to ensure PRF extension support ('prf' in PublicKeyCredential.getClientExtensionResults()) before dispatching assertions.
- Engineers MUST ALWAYS derive the final symmetric key using HKDF-SHA-256 with distinct, high-entropy salt and an immutable domain separation info string (e.g., 'org.app.vault.e2ee.v1').
- Engineers MUST NEVER use raw PRF evaluation bytes directly as an AES-GCM or ChaCha20-Poly1305 key without HKDF expansion.
- Engineers MUST NEVER store raw PRF seeds, salts, or unencrypted intermediate keys in localStorage, sessionStorage, IndexedDB, or server-side databases.
- Code MUST explicitly wipe transient Uint8Array buffers containing PRF outputs and derivation material using crypto.getRandomValues() or buffer zeroing immediately after CryptoKey import.
- Services MUST generate CryptoKey objects with extractable: false to prevent export or inspection via DevTools or compromised memory.

## Bad vs Good Implementations
### Insecure Direct Storage of Raw PRF Secret vs. Non-Extractable HKDF Derivation with Zeroization

#### Bad Antipattern (AI Common Hallucination)
> **Why it fails**: Uses a static/zeroed PRF salt input, exposes the raw PRF evaluation directly into localStorage, imports the raw PRF byte sequence directly as an AES-GCM key without an HKDF derivation step, and marks the CryptoKey as extractable.
```typescript
export async function deriveKeyFromAuthenticator(credentialId: Uint8Array): Promise<CryptoKey> {
  const assertion = await navigator.credentials.get({
    publicKey: {
      challenge: crypto.getRandomValues(new Uint8Array(32)),
      allowCredentials: [{ id: credentialId, type: 'public-key' }],
      extensions: {
        prf: {
          eval: { first: new Uint8Array(32) } // Flaw: Static all-zero salt
        }
      }
    }
  }) as PublicKeyCredential;

  const extensionResults = assertion.getClientExtensionResults();
  const rawPrfOutput = extensionResults.prf?.results?.first;

  // Flaw: Leaking raw PRF output to localStorage & directly using as AES key
  localStorage.setItem('raw-prf-secret', btoa(String.fromCharCode(...new Uint8Array(rawPrfOutput!))));

  return window.crypto.subtle.importKey(
    'raw',
    rawPrfOutput!,
    { name: 'AES-GCM' },
    true, // Flaw: extractable allows key exfiltration
    ['encrypt', 'decrypt']
  );
}
```

#### Production Standard (Correct)
> **Standard**: Validates PRF capability, uses high-entropy application-specific salt, passes raw PRF output into HKDF-SHA-256 with an immutable domain separation tag, marks all intermediate and derived CryptoKey instances as non-extractable, and guarantees memory zeroization via a finally block.
```typescript
export async function deriveKeyFromAuthenticator(
  credentialId: Uint8Array,
  prfSalt: Uint8Array
): Promise<CryptoKey> {
  if (prfSalt.byteLength !== 32) {
    throw new Error('PRF salt must be exactly 32 cryptographically secure bytes.');
  }

  const assertion = (await navigator.credentials.get({
    publicKey: {
      challenge: crypto.getRandomValues(new Uint8Array(32)),
      allowCredentials: [{ id: credentialId, type: 'public-key' }],
      extensions: {
        prf: {
          eval: { first: prfSalt }
        }
      }
    }
  })) as PublicKeyCredential | null;

  if (!assertion) {
    throw new Error('Credential assertion was canceled or rejected.');
  }

  const extResults = assertion.getClientExtensionResults();
  const prfResult = extResults.prf?.results?.first;
  if (!prfResult) {
    throw new Error('Authenticator did not return a valid PRF extension result.');
  }

  const intermediateSecret = new Uint8Array(prfResult);
  try {
    const hkdfKey = await window.crypto.subtle.importKey(
      'raw',
      intermediateSecret,
      { name: 'HKDF' },
      false,
      ['deriveKey']
    );

    const derivedKey = await window.crypto.subtle.deriveKey(
      {
        name: 'HKDF',
        hash: 'SHA-256',
        salt: prfSalt,
        info: new TextEncoder().encode('org.system.e2ee.v1.data-vault')
      },
      hkdfKey,
      { name: 'AES-GCM', length: 256 },
      false,
      ['encrypt', 'decrypt']
    );

    return derivedKey;
  } finally {
    // Critical: Securely zero-out raw PRF buffer in memory
    crypto.getRandomValues(intermediateSecret);
    intermediateSecret.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: Zero-Knowledge Hardware-Bound Key Derivation via WebAuthn PRF Extension

Zero-Knowledge Hardware-Bound Key Derivation via WebAuthn PRF Extension defines an industrial-grade behavioral standard for security engineering. Enforces strict cryptographic boundaries when deriving symmetric encryption keys using the WebAuthn Pseudo-Random Function (PRF) extension (HMAC-secret). Raw PRF outputs must be treated as volatile cryptographic material, fed immediately into an HKDF pipeline to produce ephemeral CryptoKey instances, and zeroized in memory to prevent credential and key leakage. 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: Leaking Raw PRF Outputs, Static Salts, or Un-zeroized Crypto Material in Application Memory 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 DriftLeaking Raw PRF Outputs, Static Salts, or Un-zeroized Crypto Material in Application MemoryCritical
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 inspect navigator.credentials to ensure PRF extension support ('prf' in PublicKeyCredential.getClientExtensionResults()) before dispatching assertions.

Engineers MUST ALWAYS inspect navigator.credentials to ensure PRF extension support ('prf' in PublicKeyCredential.getClientExtensionResults()) before dispatching assertions.

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 derive the final symmetric key using HKDF-SHA-256 with distinct, high-entropy salt and an immutable domain separation info string (e.g., 'org.app.vault.e2ee.v1').

Engineers MUST ALWAYS derive the final symmetric key using HKDF-SHA-256 with distinct, high-entropy salt and an immutable domain separation info string (e.g., 'org.app.vault.e2ee.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 use raw PRF evaluation bytes directly as an AES-GCM or ChaCha20-Poly1305 key without HKDF expansion.

Engineers MUST NEVER use raw PRF evaluation bytes directly as an AES-GCM or ChaCha20-Poly1305 key without HKDF expansion.

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 store raw PRF seeds, salts, or unencrypted intermediate keys in localStorage, sessionStorage, IndexedDB, or server-side databases.

Engineers MUST NEVER store raw PRF seeds, salts, or unencrypted intermediate keys in localStorage, sessionStorage, IndexedDB, or server-side databases.

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 wipe transient Uint8Array buffers containing PRF outputs and derivation material using crypto.getRandomValues() or buffer zeroing immediately after CryptoKey import.

Code MUST explicitly wipe transient Uint8Array buffers containing PRF outputs and derivation material using crypto.getRandomValues() or buffer zeroing immediately after CryptoKey import.

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 generate CryptoKey objects with extractable

Services MUST generate CryptoKey objects with extractable: false to prevent export or inspection via DevTools or compromised 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.
Technical Questions & Answers

Frequently Asked Technical Questions

Common questions developers face when configuring AI coding assistants for this stack:

Q:Why is Zero-Knowledge Hardware-Bound Key Derivation via WebAuthn PRF Extension critical for AI coding assistants?

Enforces strict cryptographic boundaries when deriving symmetric encryption keys using the WebAuthn Pseudo-Random Function (PRF) extension (HMAC-secret). Raw PRF outputs must be treated as volatile cryptographic material, fed immediately into an HKDF pipeline to produce ephemeral CryptoKey instances, and zeroized in memory to prevent credential and key leakage. 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 (Leaking Raw PRF Outputs, Static Salts, or Un-zeroized Crypto Material in Application Memory) 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

Zero-Knowledge