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

Zero-Knowledge Envelope Key Derivation & Wrapping via WebAuthn PRF Extension

Enforces cryptographically isolated client-side envelope decryption derived directly from hardware passkey authenticators via the WebAuthn PRF (Pseudo-Random Function) extension. Prohibits server-side master key escrow, prevents raw PRF output usage, and mandates HKDF-SHA256 domain-separated key stretching with authenticated DEK wrapping and immediate memory zeroing.

Prohibited Anti-Pattern: Directly Utilizing Raw WebAuthn PRF Output as Encryption Keys or Leaking Derived Key Material to RP Servers

Export Ready-to-Drop Configuration

Select format below to copy code or download file directly.

---
description: Zero-Knowledge Envelope Key Derivation & Wrapping via WebAuthn PRF Extension - Enforces cryptographically isolated client-side envelope decryption derived directly from hardware passkey authenticators via the WebAuthn PRF (Pseudo-Random Function) extension. Prohibits server-side master key escrow, prevents raw PRF output usage, and mandates HKDF-SHA256 domain-separated key stretching with authenticated DEK wrapping and immediate memory zeroing.
globs: src/**/{auth,crypto,security,vault}/**/*.{ts,tsx}, lib/**/{crypto,webauthn}/**/*.{ts,js}
alwaysApply: true
verified_by: "agentrules.org"
license: "CC-BY-4.0"
source: "https://agentrules.org/rules/webauthn-prf-zk-key-wrapping-standard"
---

# Zero-Knowledge Envelope Key Derivation & Wrapping via WebAuthn PRF Extension

> **Severity**: CRITICAL | **Category**: security
> **Anti-Pattern Warning**: Directly Utilizing Raw WebAuthn PRF Output as Encryption Keys or Leaking Derived Key Material to RP Servers

## System Constraints
You are a Principal Security Architect enforcing zero-knowledge client-side encryption using the WebAuthn PRF (hmac-secret) extension. You must guarantee that derived keys never leave client-side volatile memory, hardware authenticators are queried with domain-separated salts, raw PRF bytes undergo HKDF-SHA256 stretching before being used as Key Encryption Keys (KEKs), and Data Encryption Keys (DEKs) are wrapped exclusively via authenticated encryption.

## Strict Guidelines
- Engineers MUST ALWAYS derive a Key Encryption Key (KEK) using HKDF-SHA256 from the authenticator's PRF extension output rather than consuming raw PRF bytes directly.
- Engineers MUST NOT transmit raw PRF outputs, derived KEKs, or unencrypted Data Encryption Keys (DEKs) over network boundaries or to Relying Party (RP) APIs.
- Code SHOULD provide deterministic domain separation using cryptographic context strings (e.g., credential ID, application ID, purpose) in the HKDF `info` parameter.
- Services MUST wrap client-side Data Encryption Keys using authenticated primitives (AES-GCM-256 with authenticated additional data or RFC 3394 AES-KW) and persist only the ciphertext, initialization vector, and public salt.
- Components NEVER persist plaintext keys to non-volatile storage (`localStorage`, `sessionStorage`, unencrypted `IndexedDB`) and MUST securely overwrite in-memory byte arrays (`buf.fill(0)`) immediately after cryptographic execution.

## Bad vs Good Implementations
### WebAuthn PRF Key Derivation and Envelope Decryption

#### Bad Antipattern (AI Common Hallucination)
> **Why it fails**: The anti-pattern sends authentication data and encrypted secrets to the server for processing, completely destroying the zero-knowledge model. It also fails to specify the client-side PRF evaluation parameters and persists plaintext key material into unencrypted local storage.
```typescript
import { startAuthentication } from '@simplewebauthn/browser';

export async function unlockUserVault(encryptedDEK: string, serverChallenge: any) {
  // Anti-Pattern: Missing PRF extension payload, sending assertion to server to decrypt,
  // or using raw PRF results directly without HKDF domain separation
  const assertion = await startAuthentication({
    optionsJSON: serverChallenge,
  });

  // CRITICAL SECURITY FLAW: Sending PRF output/assertion to server for decryption
  const response = await fetch('/api/vault/decrypt', {
    method: 'POST',
    headers: { 'Content-Type': 'application/json' },
    body: JSON.stringify({ assertion, encryptedDEK }),
  });

  const { plaintextKey } = await response.json();
  localStorage.setItem('master_key', plaintextKey); // CRITICAL: Insecure persistence
  return plaintextKey;
}
```

#### Production Standard (Correct)
> **Standard**: This conforms strictly to Zero-Knowledge principles: the passkey PRF extension calculates key material entirely in client hardware, stretches it through HKDF-SHA256 with explicit domain separation, unwraps the DEK via WebCrypto without exposing raw key bytes to JavaScript or network layers, and explicitly zeroes out transient memory buffers.
```typescript
import { startAuthentication } from '@simplewebauthn/browser';

interface PrfAuthenticationResponse extends PublicKeyCredential {
  getClientExtensionResults(): AuthenticationExtensionsClientOutputs & {
    prf?: { results?: { first: ArrayBuffer } };
  };
}

export async function unlockUserVault(
  optionsJSON: PublicKeyCredentialRequestOptionsJSON,
  salt: Uint8Array,
  wrappedDEK: Uint8Array,
  iv: Uint8Array,
  vaultId: string
): Promise<CryptoKey> {
  // 1. Inject PRF extension evaluation input into authentication options
  const extendedOptions = {
    ...optionsJSON,
    extensions: {
      ...optionsJSON.extensions,
      prf: {
        eval: {
          first: salt.buffer,
        },
      },
    },
  };

  const assertion = (await startAuthentication({
    optionsJSON: extendedOptions,
  })) as unknown as PrfAuthenticationResponse;

  const prfResults = assertion.getClientExtensionResults().prf?.results;
  if (!prfResults?.first) {
    throw new Error('Authenticator did not return PRF output or PRF extension unsupported');
  }

  const rawPrfBytes = new Uint8Array(prfResults.first);

  try {
    // 2. Import raw PRF output into WebCrypto as raw HKDF key material
    const prfBaseKey = await crypto.subtle.importKey(
      'raw',
      rawPrfBytes,
      'HKDF',
      false,
      ['deriveKey']
    );

    // 3. Derive Key Encryption Key (KEK) using HKDF with domain-specific info
    const infoBuffer = new TextEncoder().encode(`zk-envelope-kek-v1:${vaultId}`);
    const kek = await crypto.subtle.deriveKey(
      {
        name: 'HKDF',
        hash: 'SHA-256',
        salt: salt.buffer,
        info: infoBuffer,
      },
      prfBaseKey,
      { name: 'AES-GCM', length: 256 },
      false,
      ['unwrapKey']
    );

    // 4. Unwrap Data Encryption Key (DEK) client-side in memory
    const dek = await crypto.subtle.unwrapKey(
      'raw',
      wrappedDEK,
      kek,
      {
        name: 'AES-GCM',
        iv: iv,
        additionalData: infoBuffer,
      },
      { name: 'AES-GCM', length: 256 },
      false,
      ['encrypt', 'decrypt']
    );

    return dek;
  } finally {
    // 5. Memory hygiene: overwrite raw PRF buffer immediately
    rawPrfBytes.fill(0);
  }
}
```

Architectural Specification & Invariant Rationale

Architectural Invariant Design: Zero-Knowledge Envelope Key Derivation & Wrapping via WebAuthn PRF Extension

Zero-Knowledge Envelope Key Derivation & Wrapping via WebAuthn PRF Extension defines an industrial-grade behavioral standard for security engineering. Enforces cryptographically isolated client-side envelope decryption derived directly from hardware passkey authenticators via the WebAuthn PRF (Pseudo-Random Function) extension. Prohibits server-side master key escrow, prevents raw PRF output usage, and mandates HKDF-SHA256 domain-separated key stretching with authenticated DEK wrapping and immediate memory zeroing. 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: Directly Utilizing Raw WebAuthn PRF Output as Encryption Keys or Leaking Derived Key Material to RP Servers 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 DriftDirectly Utilizing Raw WebAuthn PRF Output as Encryption Keys or Leaking Derived Key Material to RP ServersCritical
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 derive a Key Encryption Key (KEK) using HKDF-SHA256 from the authenticator's PRF extension output rather than consuming raw PRF bytes directly.

Engineers MUST ALWAYS derive a Key Encryption Key (KEK) using HKDF-SHA256 from the authenticator's PRF extension output rather than consuming raw PRF bytes directly.

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 NOT transmit raw PRF outputs, derived KEKs, or unencrypted Data Encryption Keys (DEKs) over network boundaries or to Relying Party (RP) APIs.

Engineers MUST NOT transmit raw PRF outputs, derived KEKs, or unencrypted Data Encryption Keys (DEKs) over network boundaries or to Relying Party (RP) APIs.

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

Code SHOULD provide deterministic domain separation using cryptographic context strings (e.g., credential ID, application ID, purpose) in the HKDF `info` parameter.

Code SHOULD provide deterministic domain separation using cryptographic context strings (e.g., credential ID, application ID, purpose) in the HKDF `info` parameter.

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

Services MUST wrap client-side Data Encryption Keys using authenticated primitives (AES-GCM-256 with authenticated additional data or RFC 3394 AES-KW) and persist only the ciphertext, initialization vector, and public salt.

Services MUST wrap client-side Data Encryption Keys using authenticated primitives (AES-GCM-256 with authenticated additional data or RFC 3394 AES-KW) and persist only the ciphertext, initialization vector, and public salt.

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

Components NEVER persist plaintext keys to non-volatile storage (`localStorage`, `sessionStorage`, unencrypted `IndexedDB`) and MUST securely overwrite in-memory byte arrays (`buf.fill(0)`) immediately after cryptographic execution.

Components NEVER persist plaintext keys to non-volatile storage (`localStorage`, `sessionStorage`, unencrypted `IndexedDB`) and MUST securely overwrite in-memory byte arrays (`buf.fill(0)`) immediately after cryptographic execution.

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 Envelope Key Derivation & Wrapping via WebAuthn PRF Extension critical for AI coding assistants?

Enforces cryptographically isolated client-side envelope decryption derived directly from hardware passkey authenticators via the WebAuthn PRF (Pseudo-Random Function) extension. Prohibits server-side master key escrow, prevents raw PRF output usage, and mandates HKDF-SHA256 domain-separated key stretching with authenticated DEK wrapping and immediate memory zeroing. 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 (Directly Utilizing Raw WebAuthn PRF Output as Encryption Keys or Leaking Derived Key Material to RP Servers) 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