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

WebAuthn PRF Extension Zero-Knowledge Envelope Encryption Standard

Mandates that client-side zero-knowledge encryption powered by the WebAuthn PRF extension derives cryptographic keys strictly in-memory using HKDF with domain separation. Prohibits transmission of raw PRF outputs or derived Key Encryption Keys (KEKs) to remote servers and requires strict envelope encryption via ephemeral Data Encryption Keys (DEKs).

Prohibited Anti-Pattern: Direct Encryption with Raw PRF Secret Outputs or Exposing Derived Keys to Server APIs

Export Ready-to-Drop Configuration

Select format below to copy code or download file directly.

---
description: WebAuthn PRF Extension Zero-Knowledge Envelope Encryption Standard - Mandates that client-side zero-knowledge encryption powered by the WebAuthn PRF extension derives cryptographic keys strictly in-memory using HKDF with domain separation. Prohibits transmission of raw PRF outputs or derived Key Encryption Keys (KEKs) to remote servers and requires strict envelope encryption via ephemeral Data Encryption Keys (DEKs).
globs: src/**/*.{ts,tsx,js,mjs}
alwaysApply: true
verified_by: "agentrules.org"
license: "CC-BY-4.0"
source: "https://agentrules.org/rules/webauthn-prf-zk-envelope-encryption-standard"
---

# WebAuthn PRF Extension Zero-Knowledge Envelope Encryption Standard

> **Severity**: CRITICAL | **Category**: security
> **Anti-Pattern Warning**: Direct Encryption with Raw PRF Secret Outputs or Exposing Derived Keys to Server APIs

## System Constraints
You are a Principal Cryptographic Architect enforcing strict zero-knowledge envelope encryption invariants using the WebAuthn PRF (Pseudo-Random Function) extension. You must guarantee that all derived keys remain within the client execution sandbox, hardware PRF outputs are expanded through HKDF with contextual domain separation, and bulk payload encryption always utilizes freshly generated ephemeral Data Encryption Keys (DEKs) wrapped by the PRF-derived Key Encryption Key (KEK).

## Strict Guidelines
- Engineers MUST ALWAYS verify that `results.getClientExtensionResults().prf` is populated before proceeding with key derivation, falling back to secure failure or re-authentication if the hardware authenticator does not support PRF.
- Engineers MUST NOT transmit raw PRF outputs (`first`, `second`), derived Key Encryption Keys (KEKs), or ephemeral Data Encryption Keys (DEKs) in plaintext to any server or intermediary.
- Engineers MUST ALWAYS expand the raw PRF output via `crypto.subtle.deriveKey` or `crypto.subtle.deriveBits` using HKDF-SHA-256 with an explicit, immutable `info` parameter for domain separation (e.g., `enc:zk-vault:v1`).
- Code MUST implement Envelope Encryption by generating a cryptographically secure random 256-bit ephemeral Data Encryption Key (DEK) via `crypto.getRandomValues()`, encrypting the payload with AES-256-GCM, and wrapping the DEK with the PRF-derived KEK via AES-KW (AES Key Wrap) or AES-256-GCM.
- Components NEVER use the raw PRF evaluation result directly as a symmetric cipher key for bulk data encryption.
- Code MUST generate a fresh, unique 96-bit Initialization Vector (IV) from `crypto.getRandomValues(new Uint8Array(12))` for every AES-GCM operation; IV reuse is strictly prohibited.
- Services MUST only accept and persist the encrypted envelope containing the ciphertext, the wrapped DEK, the IV, and the public authenticator credential ID and salt.

## Bad vs Good Implementations
### Client-Side Zero-Knowledge Encryption Flow with WebAuthn PRF

#### Bad Antipattern (AI Common Hallucination)
> **Why it fails**: The anti-pattern breaches zero-knowledge guarantees by transmitting the raw PRF output to the backend server. It also uses a static, hardcoded salt, fails to verify PRF extension support, does not derive keys using HKDF with domain separation, and skips the envelope encryption pattern entirely.
```typescript
import axios from 'axios';

// ANTI-PATTERN: Direct encryption with raw PRF output and sending raw secret to server
export async function encryptAndSaveVault(credentialId: BufferSource, data: string): Promise<void> {
  const assertion = await navigator.credentials.get({
    publicKey: {
      challenge: new Uint8Array(32),
      allowCredentials: [{ id: credentialId, type: 'public-key' }],
      extensions: {
        prf: {
          eval: { first: new Uint8Array(32).fill(1) }
        }
      } as any
    }
  }) as PublicKeyCredential;

  const results = assertion.getClientExtensionResults() as any;
  const rawPrfSecret = results.prf?.results?.first;

  // CRITICAL VULNERABILITY 1: Transmitting raw PRF secret to the backend
  // CRITICAL VULNERABILITY 2: No ephemeral DEK envelope, no domain separation via HKDF
  await axios.post('/api/vault/sync', {
    credentialId: Array.from(new Uint8Array(assertion.rawId)),
    secret: Array.from(new Uint8Array(rawPrfSecret)),
    payload: data
  });
}
```

#### Production Standard (Correct)
> **Standard**: This implementation enforces true zero-knowledge: PRF output never leaves the client, extension capability is validated, HKDF-SHA-256 provides domain separation to derive an AES-KW Key Encryption Key (KEK), an ephemeral AES-GCM-256 Data Encryption Key (DEK) is generated to encrypt the payload with a fresh 96-bit IV, and the wrapped DEK is packaged into a standard envelope.
```typescript
export interface EncryptedEnvelope {
  wrappedDek: string; // Base64 encoded wrapped DEK
  ciphertext: string; // Base64 encoded payload
  iv: string;         // Base64 encoded 96-bit IV
  salt: string;       // Base64 encoded PRF salt
}

const HKDF_INFO = new TextEncoder().encode('zk-envelope:v1:kek-derivation');

export async function encryptZeroKnowledgeEnvelope(
  credentialId: BufferSource,
  payload: Uint8Array,
  prfSalt: Uint8Array
): Promise<EncryptedEnvelope> {
  if (prfSalt.byteLength !== 32) {
    throw new Error('PRF salt must be exactly 32 bytes.');
  }

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

  if (!assertion) {
    throw new Error('Authenticator assertion failed.');
  }

  const extensionResults = assertion.getClientExtensionResults() as AuthenticationExtensionsClientOutputs & {
    prf?: { results?: { first: ArrayBuffer } };
  };

  const rawPrfSecret = extensionResults.prf?.results?.first;
  if (!rawPrfSecret) {
    throw new Error('Authenticator does not support the WebAuthn PRF extension.');
  }

  // 1. Import raw PRF output as HKDF key material (IKM)
  const ikm = await crypto.subtle.importKey(
    'raw',
    rawPrfSecret,
    'HKDF',
    false,
    ['deriveKey']
  );

  // 2. Derive Key Encryption Key (KEK) using HKDF with strict domain separation
  const kek = await crypto.subtle.deriveKey(
    {
      name: 'HKDF',
      hash: 'SHA-256',
      salt: prfSalt,
      info: HKDF_INFO
    },
    ikm,
    { name: 'AES-KW', length: 256 },
    false,
    ['wrapKey']
  );

  // 3. Generate Ephemeral Data Encryption Key (DEK)
  const dek = await crypto.subtle.generateKey(
    { name: 'AES-GCM', length: 256 },
    true,
    ['encrypt']
  );

  // 4. Wrap DEK with KEK
  const wrappedDekBuffer = await crypto.subtle.wrapKey('raw', dek, kek, 'AES-KW');

  // 5. Encrypt payload with DEK
  const iv = crypto.getRandomValues(new Uint8Array(12));
  const ciphertextBuffer = await crypto.subtle.encrypt(
    { name: 'AES-GCM', iv },
    dek,
    payload
  );

  const toBase64 = (buf: ArrayBuffer): string =>
    btoa(String.fromCharCode(...new Uint8Array(buf)));

  return {
    wrappedDek: toBase64(wrappedDekBuffer),
    ciphertext: toBase64(ciphertextBuffer),
    iv: toBase64(iv.buffer),
    salt: toBase64(prfSalt.buffer)
  };
}
```

Architectural Specification & Invariant Rationale

Architectural Invariant Design: WebAuthn PRF Extension Zero-Knowledge Envelope Encryption Standard

WebAuthn PRF Extension Zero-Knowledge Envelope Encryption Standard defines an industrial-grade behavioral standard for security engineering. Mandates that client-side zero-knowledge encryption powered by the WebAuthn PRF extension derives cryptographic keys strictly in-memory using HKDF with domain separation. Prohibits transmission of raw PRF outputs or derived Key Encryption Keys (KEKs) to remote servers and requires strict envelope encryption via ephemeral Data Encryption Keys (DEKs). 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: Direct Encryption with Raw PRF Secret Outputs or Exposing Derived Keys to Server APIs 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 DriftDirect Encryption with Raw PRF Secret Outputs or Exposing Derived Keys to Server APIsCritical
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 that `results.getClientExtensionResults().prf` is populated before proceeding with key derivation, falling back to secure failure or re-authentication if the hardware authenticator does not support PRF.

Engineers MUST ALWAYS verify that `results.getClientExtensionResults().prf` is populated before proceeding with key derivation, falling back to secure failure or re-authentication if the hardware authenticator does not support PRF.

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 (`first`, `second`), derived Key Encryption Keys (KEKs), or ephemeral Data Encryption Keys (DEKs) in plaintext to any server or intermediary.

Engineers MUST NOT transmit raw PRF outputs (`first`, `second`), derived Key Encryption Keys (KEKs), or ephemeral Data Encryption Keys (DEKs) in plaintext to any server or intermediary.

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 expand the raw PRF output via `crypto.subtle.deriveKey` or `crypto.subtle.deriveBits` using HKDF-SHA-256 with an explicit, immutable `info` parameter for domain separation (e.g., `enc

Engineers MUST ALWAYS expand the raw PRF output via `crypto.subtle.deriveKey` or `crypto.subtle.deriveBits` using HKDF-SHA-256 with an explicit, immutable `info` parameter for domain separation (e.g., `enc:zk-vault: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.
4

Code MUST implement Envelope Encryption by generating a cryptographically secure random 256-bit ephemeral Data Encryption Key (DEK) via `crypto.getRandomValues()`, encrypting the payload with AES-256-GCM, and wrapping the DEK with the PRF-derived KEK via AES-KW (AES Key Wrap) or AES-256-GCM.

Code MUST implement Envelope Encryption by generating a cryptographically secure random 256-bit ephemeral Data Encryption Key (DEK) via `crypto.getRandomValues()`, encrypting the payload with AES-256-GCM, and wrapping the DEK with the PRF-derived KEK via AES-KW (AES Key Wrap) or AES-256-GCM.

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 use the raw PRF evaluation result directly as a symmetric cipher key for bulk data encryption.

Components NEVER use the raw PRF evaluation result directly as a symmetric cipher key for bulk data encryption.

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 MUST generate a fresh, unique 96-bit Initialization Vector (IV) from `crypto.getRandomValues(new Uint8Array(12))` for every AES-GCM operation

Code MUST generate a fresh, unique 96-bit Initialization Vector (IV) from `crypto.getRandomValues(new Uint8Array(12))` for every AES-GCM operation; IV reuse is strictly prohibited.

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

Services MUST only accept and persist the encrypted envelope containing the ciphertext, the wrapped DEK, the IV, and the public authenticator credential ID and salt.

Services MUST only accept and persist the encrypted envelope containing the ciphertext, the wrapped DEK, the IV, and the public authenticator credential ID and 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.
Technical Questions & Answers

Frequently Asked Technical Questions

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

Q:Why is WebAuthn PRF Extension Zero-Knowledge Envelope Encryption Standard critical for AI coding assistants?

Mandates that client-side zero-knowledge encryption powered by the WebAuthn PRF extension derives cryptographic keys strictly in-memory using HKDF with domain separation. Prohibits transmission of raw PRF outputs or derived Key Encryption Keys (KEKs) to remote servers and requires strict envelope encryption via ephemeral Data Encryption Keys (DEKs). 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 (Direct Encryption with Raw PRF Secret Outputs or Exposing Derived Keys to Server APIs) 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