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

Hardware-Bound Zero-Knowledge Encryption via WebAuthn PRF Extension

Enforces strict cryptographic handling when utilizing the WebAuthn Pseudo-Random Function (PRF) extension (`eval` / `evalByCredential`) to derive hardware-bound client-side symmetric keys. Mandates that derived PRF outputs are never transmitted over the network or persisted in plain text, requiring immediate one-way HKDF expansion into AES-GCM-256 keys with distinct domain-separated salts. Ensures proper fallback handling and runtime capability detection across authenticators to prevent plaintext data leakage.

Prohibited Anti-Pattern: Persisting raw PRF outputs, transmitting them across network boundaries, or reusing symmetric derivation inputs without HKDF domain separation

Export Ready-to-Drop Configuration

Select format below to copy code or download file directly.

---
description: Hardware-Bound Zero-Knowledge Encryption via WebAuthn PRF Extension - Enforces strict cryptographic handling when utilizing the WebAuthn Pseudo-Random Function (PRF) extension (`eval` / `evalByCredential`) to derive hardware-bound client-side symmetric keys. Mandates that derived PRF outputs are never transmitted over the network or persisted in plain text, requiring immediate one-way HKDF expansion into AES-GCM-256 keys with distinct domain-separated salts. Ensures proper fallback handling and runtime capability detection across authenticators to prevent plaintext data leakage.
globs: src/lib/crypto/**/*.{ts,js}, src/services/auth/**/*.{ts,js}, src/features/vault/**/*.{ts,tsx}, src/security/**/*.{ts,js}
alwaysApply: true
verified_by: "agentrules.org"
license: "CC-BY-4.0"
source: "https://agentrules.org/rules/webauthn-prf-zk-client-encryption"
---

# Hardware-Bound Zero-Knowledge Encryption via WebAuthn PRF Extension

> **Severity**: CRITICAL | **Category**: security
> **Anti-Pattern Warning**: Persisting raw PRF outputs, transmitting them across network boundaries, or reusing symmetric derivation inputs without HKDF domain separation

## System Constraints
You are a Principal Security Architect enforcing zero-knowledge client-side encryption via WebAuthn PRF (Pseudo-Random Function) extension. You must prevent any leakage of PRF raw outputs, reject improper salt reuse, enforce HKDF-SHA256 key derivation with explicit context labeling, verify authenticator PRF support prior to payload construction, and ensure that only ciphertext and initialization vectors are ever sent across transport boundaries.

## Strict Guidelines
- Engineers MUST ALWAYS check `clientExtensionResults.prf.supported` or runtime availability before executing PRF-dependent cryptographic flows.
- Engineers MUST NEVER transmit raw PRF output (`first` or `second` bytes) or raw Derived Master Keys to any server, logging system, or remote endpoint.
- Engineers MUST ALWAYS pipe raw PRF evaluation outputs through HKDF-SHA256 (RFC 5869) with application-specific context info (domain separation) before using the output as an AES-GCM-256 encryption key.
- Engineers MUST ALWAYS use cryptographically secure random salts (minimum 32 bytes from `crypto.getRandomValues`) for the PRF `eval` input, never hardcoded strings or predictable timestamps.
- Engineers MUST NEVER store derived symmetric keys in `localStorage`, `sessionStorage`, or unencrypted IndexedDB; keys must exist purely in transient runtime memory and be zeroized/cleared when possible.
- Components NEVER render user-encrypted data until client-side PRF derivation and local AES-GCM decryption have completed successfully inside the secure client sandbox.

## Bad vs Good Implementations
### Unsafe PRF Output Handling vs. Strict HKDF Domain Separation & Zero-Knowledge AES-GCM

#### Bad Antipattern (AI Common Hallucination)
> **Why it fails**: Directly imports the raw PRF result as an AES key without HKDF-SHA256 domain separation, ignores checking if PRF evaluation succeeded, leaks raw cryptographic key material into logs, and does not validate buffer bounds or authenticator PRF support.
```typescript
export async function decryptUserPayload(credential: PublicKeyCredential, encryptedBlob: ArrayBuffer): Promise<string> {
  const extensionResults = credential.getClientExtensionResults();
  // ANTI-PATTERN: Direct use of PRF output as a raw AES key without HKDF expansion
  // ANTI-PATTERN: No check if PRF succeeded or was supported
  const rawPrf = (extensionResults as any).prf?.results?.first as ArrayBuffer;

  // Leaking raw PRF output or using it directly as key
  const importedKey = await crypto.subtle.importKey(
    'raw',
    rawPrf,
    { name: 'AES-GCM' },
    false,
    ['decrypt']
  );

  // Leaking intermediate values to analytics or telemetry
  console.log('Derived PRF output:', new Uint8Array(rawPrf));

  const iv = encryptedBlob.slice(0, 12);
  const data = encryptedBlob.slice(12);
  const decrypted = await crypto.subtle.decrypt({ name: 'AES-GCM', iv }, importedKey, data);
  return new TextDecoder().decode(decrypted);
}
```

#### Production Standard (Correct)
> **Standard**: Validates PRF support before proceeding, strictly binds the raw PRF output to HKDF-SHA256 with domain-specific info strings, marks derived keys as non-extractable (`extractable: false`), prevents logging of secret material, and validates buffer boundaries.
```typescript
const PRF_HKDF_INFO = new TextEncoder().encode('vault:aes-gcm-256:v1');

export async function deriveKeyAndDecrypt(
  assertion: PublicKeyCredential,
  encryptedBlob: ArrayBuffer
): Promise<ArrayBuffer> {
  const extensionResults = assertion.getClientExtensionResults();
  const prfResults = extensionResults.prf?.results;

  if (!prfResults?.first) {
    throw new Error('Authenticator did not return PRF evaluation results or PRF is unsupported');
  }

  if (encryptedBlob.byteLength < 28) {
    // 12 bytes IV + 16 bytes minimum auth tag
    throw new Error('Ciphertext is malformed or too short');
  }

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

  // Step 2: Derive AES-GCM-256 key via HKDF-SHA256 with domain separation
  const iv = new Uint8Array(encryptedBlob, 0, 12);
  const ciphertext = new Uint8Array(encryptedBlob, 12);

  const derivedKey = await crypto.subtle.deriveKey(
    {
      name: 'HKDF',
      hash: 'SHA-256',
      salt: new Uint8Array(32), // Pre-shared HKDF salt or context salt
      info: PRF_HKDF_INFO
    },
    ikmKey,
    { name: 'AES-GCM', length: 256 },
    false,
    ['decrypt']
  );

  // Step 3: Zero-Knowledge Decryption in transient memory
  return crypto.subtle.decrypt(
    { name: 'AES-GCM', iv },
    derivedKey,
    ciphertext
  );
}
```

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: Hardware-Bound Zero-Knowledge Encryption via WebAuthn PRF Extension

Hardware-Bound Zero-Knowledge Encryption via WebAuthn PRF Extension defines an industrial-grade behavioral standard for security engineering. Enforces strict cryptographic handling when utilizing the WebAuthn Pseudo-Random Function (PRF) extension (`eval` / `evalByCredential`) to derive hardware-bound client-side symmetric keys. Mandates that derived PRF outputs are never transmitted over the network or persisted in plain text, requiring immediate one-way HKDF expansion into AES-GCM-256 keys with distinct domain-separated salts. Ensures proper fallback handling and runtime capability detection across authenticators to prevent plaintext data 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: Persisting raw PRF outputs, transmitting them across network boundaries, or reusing symmetric derivation inputs without 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 DriftPersisting raw PRF outputs, transmitting them across network boundaries, or reusing symmetric derivation inputs without 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 check `clientExtensionResults.prf.supported` or runtime availability before executing PRF-dependent cryptographic flows.

Engineers MUST ALWAYS check `clientExtensionResults.prf.supported` or runtime availability before executing PRF-dependent cryptographic flows.

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 (`first` or `second` bytes) or raw Derived Master Keys to any server, logging system, or remote endpoint.

Engineers MUST NEVER transmit raw PRF output (`first` or `second` bytes) or raw Derived Master Keys to any server, logging system, or remote endpoint.

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 evaluation outputs through HKDF-SHA256 (RFC 5869) with application-specific context info (domain separation) before using the output as an AES-GCM-256 encryption key.

Engineers MUST ALWAYS pipe raw PRF evaluation outputs through HKDF-SHA256 (RFC 5869) with application-specific context info (domain separation) before using the output as an AES-GCM-256 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.
4

Engineers MUST ALWAYS use cryptographically secure random salts (minimum 32 bytes from `crypto.getRandomValues`) for the PRF `eval` input, never hardcoded strings or predictable timestamps.

Engineers MUST ALWAYS use cryptographically secure random salts (minimum 32 bytes from `crypto.getRandomValues`) for the PRF `eval` input, never hardcoded strings or predictable timestamps.

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 NEVER store derived symmetric keys in `localStorage`, `sessionStorage`, or unencrypted IndexedDB

Engineers MUST NEVER store derived symmetric keys in `localStorage`, `sessionStorage`, or unencrypted IndexedDB; keys must exist purely in transient runtime memory and be zeroized/cleared when possible.

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

Components NEVER render user-encrypted data until client-side PRF derivation and local AES-GCM decryption have completed successfully inside the secure client sandbox.

Components NEVER render user-encrypted data until client-side PRF derivation and local AES-GCM decryption have completed successfully inside the secure client sandbox.

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 Hardware-Bound Zero-Knowledge Encryption via WebAuthn PRF Extension critical for AI coding assistants?

Enforces strict cryptographic handling when utilizing the WebAuthn Pseudo-Random Function (PRF) extension (`eval` / `evalByCredential`) to derive hardware-bound client-side symmetric keys. Mandates that derived PRF outputs are never transmitted over the network or persisted in plain text, requiring immediate one-way HKDF expansion into AES-GCM-256 keys with distinct domain-separated salts. Ensures proper fallback handling and runtime capability detection across authenticators to prevent plaintext data 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 (Persisting raw PRF outputs, transmitting them across network boundaries, or reusing symmetric derivation inputs without 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

Hardware-Bound