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

Deterministic Salt Ratcheting and HKDF Expansion for WebAuthn PRF Zero-Knowledge Cryptographic Envelopes

Hardware-backed symmetric keys derived via the WebAuthn PRF (hmac-secret) extension must never utilize static salts, raw PRF outputs as direct symmetric keys, or non-versioned derivation contexts. Client-side zero-knowledge envelopes must enforce HKDF-SHA-256 domain separation, monotonic salt ratcheting across write epochs, and immediate zeroization of transient key material in memory to guarantee offline cryptographic confidentiality.

Prohibited Anti-Pattern: Static Salt Re-use and Direct Cipher Key Casting of Raw WebAuthn PRF Outputs

Export Ready-to-Drop Configuration

Select format below to copy code or download file directly.

---
description: Deterministic Salt Ratcheting and HKDF Expansion for WebAuthn PRF Zero-Knowledge Cryptographic Envelopes - Hardware-backed symmetric keys derived via the WebAuthn PRF (hmac-secret) extension must never utilize static salts, raw PRF outputs as direct symmetric keys, or non-versioned derivation contexts. Client-side zero-knowledge envelopes must enforce HKDF-SHA-256 domain separation, monotonic salt ratcheting across write epochs, and immediate zeroization of transient key material in memory to guarantee offline cryptographic confidentiality.
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-derivation-salt-rotation-standard"
---

# Deterministic Salt Ratcheting and HKDF Expansion for WebAuthn PRF Zero-Knowledge Cryptographic Envelopes

> **Severity**: CRITICAL | **Category**: security
> **Anti-Pattern Warning**: Static Salt Re-use and Direct Cipher Key Casting of Raw WebAuthn PRF Outputs

## System Constraints
You are a Principal Security Architect enforcing zero-knowledge client-side encryption standards using WebAuthn PRF (Pseudo-Random Function) extensions. You must ensure all cryptographic operations strictly decouple hardware entropy derivation from cipher execution via HKDF, mandate monotonic salt ratcheting per cryptographic envelope version, enforce strict envelope schema validation, and ensure all transient key material is zeroized.

## Strict Guidelines
- Engineers MUST ALWAYS pipe raw WebAuthn PRF output through HKDF-SHA-256 (Extract-and-Expand) with a non-empty, domain-separated 'info' parameter before instantiating symmetric cipher primitives.
- Engineers MUST NOT utilize static, constant, or user-identifier-derived salts directly for the WebAuthn PRF input; a unique, cryptographically random salt (minimum 32 bytes) must be generated per envelope generation and ratcheted monotonically.
- Code MUST encapsulate ciphertext inside an authenticated envelope structure containing 'version', 'epoch', 'salt', 'nonce', and 'ciphertext' to preserve cryptographic agility and offline verification.
- Services MUST NEVER transmit the raw WebAuthn PRF derived key or master key material across the network boundary; all derived keys must be held strictly in ephemeral memory and immediately scrubbed with 'Uint8Array.fill(0)' or CryptoKey destruction.
- Components NEVER store unencrypted keys or intermediate derivation materials in localStorage, sessionStorage, IndexedDB, or web worker shared memory without authenticated zero-knowledge envelope wrappers.

## Bad vs Good Implementations
### WebAuthn PRF Derivation and Symmetric Envelope Encryption

#### Bad Antipattern (AI Common Hallucination)
> **Why it fails**: The bad example uses a static salt across derivations, completely destroying forward secrecy and enabling cross-session tracking. It maps the raw PRF output directly into an AES-GCM key without HKDF expansion or domain separation tags, fails to version the cryptographic envelope, and leaves sensitive key bytes allocated in memory without zeroization.
```typescript
import { get } from '@github/webauthn-json';

// ANTI-PATTERN: Static salt, direct use of raw PRF output as AES-GCM key,
// lack of domain separation, and no memory zeroization.
export async function encryptUserData(credentialId: string, plaintext: Uint8Array): Promise<Uint8Array> {
  const STATIC_SALT = new TextEncoder().encode('my-app-static-salt-constant-1234');

  const assertion = await get({
    publicKey: {
      challenge: 'c29tZS1yYW5kb20tY2hhbGxlbmdl',
      allowCredentials: [{ id: credentialId, type: 'public-key' }],
      extensions: {
        prf: {
          eval: { first: STATIC_SALT }
        }
      }
    }
  });

  // DANGEROUS: Using raw PRF output directly as raw cipher key
  const prfResult = new Uint8Array(assertion.clientExtensionResults.prf.results.first);
  const key = await crypto.subtle.importKey('raw', prfResult, 'AES-GCM', false, ['encrypt']);

  const iv = crypto.getRandomValues(new Uint8Array(12));
  const ciphertext = await crypto.subtle.encrypt({ name: 'AES-GCM', iv }, key, plaintext);

  // Flawed: Raw concatenation with no versioning, no ratcheting, leak risk
  const output = new Uint8Array(iv.length + ciphertext.byteLength);
  output.set(iv, 0);
  output.set(new Uint8Array(ciphertext), iv.length);
  return output;
}
```

#### Production Standard (Correct)
> **Standard**: The good example generates unique cryptographically secure 32-byte salts per operation, utilizes HKDF-SHA-256 with explicit domain and epoch binding (`info` and `additionalData`), versions the resulting envelope structure, and ensures immediate deterministic zeroization of the transient PRF entropy buffer within a `finally` block.
```typescript
export interface ZeroKnowledgeEnvelope {
  version: 1;
  epoch: number;
  salt: string; // base64url 32-byte salt
  nonce: string; // base64url 12-byte IV
  ciphertext: string; // base64url encrypted payload
}

function zeroize(buffer: Uint8Array): void {
  buffer.fill(0);
}

export async function encryptWithPrfEnvelope(
  credentialId: BufferSource,
  challenge: BufferSource,
  currentEpoch: number,
  plaintext: Uint8Array
): Promise<ZeroKnowledgeEnvelope> {
  // 1. Generate fresh 32-byte cryptographically secure salt for this envelope version
  const salt = crypto.getRandomValues(new Uint8Array(32));
  const nonce = crypto.getRandomValues(new Uint8Array(12));

  const assertion = await navigator.credentials.get({
    publicKey: {
      challenge,
      allowCredentials: [{ id: credentialId, type: 'public-key' }],
      extensions: {
        prf: { eval: { first: salt } }
      }
    }
  }) as PublicKeyCredential;

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

  if (!extResults.prf?.results?.first) {
    throw new Error('WebAuthn PRF extension evaluation failed or unsupported.');
  }

  const rawPrfOutput = new Uint8Array(extResults.prf.results.first);

  try {
    // 2. HKDF-SHA-256 with rigorous domain separation
    const prfKeyMaterial = await crypto.subtle.importKey(
      'raw',
      rawPrfOutput,
      'HKDF',
      false,
      ['deriveKey']
    );

    const domainInfo = new TextEncoder().encode(`AES-256-GCM:WebAuthn-PRF-Envelope:v1:epoch=${currentEpoch}`);
    const derivedKey = await crypto.subtle.deriveKey(
      {
        name: 'HKDF',
        hash: 'SHA-256',
        salt,
        info: domainInfo
      },
      prfKeyMaterial,
      { name: 'AES-GCM', length: 256 },
      false,
      ['encrypt']
    );

    // 3. Encrypt payload with explicit authenticated data (AAD) binding envelope metadata
    const aad = new TextEncoder().encode(`v1:${currentEpoch}`);
    const encryptedBuffer = await crypto.subtle.encrypt(
      { name: 'AES-GCM', iv: nonce, additionalData: aad },
      derivedKey,
      plaintext
    );

    return {
      version: 1,
      epoch: currentEpoch,
      salt: Buffer.from(salt).toString('base64url'),
      nonce: Buffer.from(nonce).toString('base64url'),
      ciphertext: Buffer.from(encryptedBuffer).toString('base64url')
    };
  } finally {
    // 4. Secure zeroization of transient PRF key bytes
    zeroize(rawPrfOutput);
  }
}
```

Architectural Specification & Invariant Rationale

Architectural Invariant Design: Deterministic Salt Ratcheting and HKDF Expansion for WebAuthn PRF Zero-Knowledge Cryptographic Envelopes

Deterministic Salt Ratcheting and HKDF Expansion for WebAuthn PRF Zero-Knowledge Cryptographic Envelopes defines an industrial-grade behavioral standard for security engineering. Hardware-backed symmetric keys derived via the WebAuthn PRF (hmac-secret) extension must never utilize static salts, raw PRF outputs as direct symmetric keys, or non-versioned derivation contexts. Client-side zero-knowledge envelopes must enforce HKDF-SHA-256 domain separation, monotonic salt ratcheting across write epochs, and immediate zeroization of transient key material in memory to guarantee offline cryptographic confidentiality. 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: Static Salt Re-use and Direct Cipher Key Casting of Raw WebAuthn PRF Outputs 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 DriftStatic Salt Re-use and Direct Cipher Key Casting of Raw WebAuthn PRF OutputsCritical
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 pipe raw WebAuthn PRF output through HKDF-SHA-256 (Extract-and-Expand) with a non-empty, domain-separated 'info' parameter before instantiating symmetric cipher primitives.

Engineers MUST ALWAYS pipe raw WebAuthn PRF output through HKDF-SHA-256 (Extract-and-Expand) with a non-empty, domain-separated 'info' parameter before instantiating symmetric cipher primitives.

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 utilize static, constant, or user-identifier-derived salts directly for the WebAuthn PRF input

Engineers MUST NOT utilize static, constant, or user-identifier-derived salts directly for the WebAuthn PRF input; a unique, cryptographically random salt (minimum 32 bytes) must be generated per envelope generation and ratcheted monotonically.

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 MUST encapsulate ciphertext inside an authenticated envelope structure containing 'version', 'epoch', 'salt', 'nonce', and 'ciphertext' to preserve cryptographic agility and offline verification.

Code MUST encapsulate ciphertext inside an authenticated envelope structure containing 'version', 'epoch', 'salt', 'nonce', and 'ciphertext' to preserve cryptographic agility and offline verification.

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 NEVER transmit the raw WebAuthn PRF derived key or master key material across the network boundary

Services MUST NEVER transmit the raw WebAuthn PRF derived key or master key material across the network boundary; all derived keys must be held strictly in ephemeral memory and immediately scrubbed with 'Uint8Array.fill(0)' or CryptoKey destruction.

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 store unencrypted keys or intermediate derivation materials in localStorage, sessionStorage, IndexedDB, or web worker shared memory without authenticated zero-knowledge envelope wrappers.

Components NEVER store unencrypted keys or intermediate derivation materials in localStorage, sessionStorage, IndexedDB, or web worker shared memory without authenticated zero-knowledge envelope wrappers.

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 Deterministic Salt Ratcheting and HKDF Expansion for WebAuthn PRF Zero-Knowledge Cryptographic Envelopes critical for AI coding assistants?

Hardware-backed symmetric keys derived via the WebAuthn PRF (hmac-secret) extension must never utilize static salts, raw PRF outputs as direct symmetric keys, or non-versioned derivation contexts. Client-side zero-knowledge envelopes must enforce HKDF-SHA-256 domain separation, monotonic salt ratcheting across write epochs, and immediate zeroization of transient key material in memory to guarantee offline cryptographic confidentiality. 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 (Static Salt Re-use and Direct Cipher Key Casting of Raw WebAuthn PRF Outputs) 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

Deterministic