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

Enforce WebAuthn PRF Deterministic Key Derivation and Client-Side Zero-Knowledge Isolation

Enforces hardware-backed deterministic symmetric key derivation via the WebAuthn Pseudo-Random Function (PRF) extension for client-side zero-knowledge vaults. Guarantees 32-byte input salt bounds, HKDF domain separation, ephemeral in-memory handling, and non-extractable Web Crypto keys without transmitting PRF secrets across the wire.

Prohibited Anti-Pattern: Raw PRF Output Exposure, Direct Cipher Usage Without HKDF, or Server-Side Transmission of Authenticator Secrets

Export Ready-to-Drop Configuration

Select format below to copy code or download file directly.

---
description: Enforce WebAuthn PRF Deterministic Key Derivation and Client-Side Zero-Knowledge Isolation - Enforces hardware-backed deterministic symmetric key derivation via the WebAuthn Pseudo-Random Function (PRF) extension for client-side zero-knowledge vaults. Guarantees 32-byte input salt bounds, HKDF domain separation, ephemeral in-memory handling, and non-extractable Web Crypto keys without transmitting PRF secrets across the wire.
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-deterministic-key-derivation-guardrail-webauthn-prf-ext-512"
---

# Enforce WebAuthn PRF Deterministic Key Derivation and Client-Side Zero-Knowledge Isolation

> **Severity**: CRITICAL | **Category**: security
> **Anti-Pattern Warning**: Raw PRF Output Exposure, Direct Cipher Usage Without HKDF, or Server-Side Transmission of Authenticator Secrets

## System Constraints
You are a Principal Security Architect enforcing deterministic client-side key derivation via the WebAuthn PRF (Pseudo-Random Function) extension. Never allow raw PRF output to be used directly as a symmetric cipher key, persisted in localStorage/sessionStorage/IndexedDB, or transmitted over network boundaries. Enforce mandatory HKDF-SHA256 domain separation, non-extractable CryptoKey handles, and strict 32-byte salt invariants.

## Strict Guidelines
- Engineers MUST ALWAYS verify authenticator PRF support during registration by asserting `getClientExtensionResults().prf?.enabled === true` before persisting credentials.
- Engineers MUST ALWAYS pass exactly 32-byte `Uint8Array` buffers to `eval.first` (and optional `eval.second`) in `publicKey.extensions.prf`.
- Engineers MUST NEVER use the raw PRF result (`results.first`) directly as a symmetric cipher key (e.g., AES-GCM); it MUST be ingested as HKDF key material (`HKDF`, `deriveKey`) with an application-specific domain separation `info` string.
- Services MUST NEVER transmit raw PRF output, intermediate HKDF seeds, or derived vault symmetric keys to backend endpoints or telemetry services.
- Components NEVER store PRF outputs in persistent client storage (localStorage, sessionStorage, unencrypted IndexedDB); keys MUST reside exclusively in non-extractable `CryptoKey` instances in memory and be zeroed upon session termination.
- Code SHOULD catch cases where `getClientExtensionResults().prf?.results` is missing or undefined (e.g., authenticator lack of PRF support or locked hardware) and fail closed rather than falling back to non-PRF password hashes without user disclosure.

## Bad vs Good Implementations
### Insecure Direct PRF Handling vs. Hardware-Backed HKDF Invariant

#### Bad Antipattern (AI Common Hallucination)
> **Why it fails**: Violates zero-knowledge isolation by transmitting the hardware-derived PRF secret to a remote server, stores it unencrypted in localStorage, passes an unvalidated salt length to the PRF extension, and creates an extractable AES key directly from raw PRF output without HKDF domain separation.
```typescript
export async function unlockVaultInsecure(credentialId: Uint8Array, rawSalt: string) {
  // Anti-Pattern: Non-standard salt size, direct AES-GCM import without HKDF,
  // extractable key leaked to localStorage and server payload.
  const assertion = (await navigator.credentials.get({
    publicKey: {
      challenge: crypto.getRandomValues(new Uint8Array(32)),
      allowCredentials: [{ id: credentialId, type: 'public-key' }],
      extensions: {
        prf: {
          eval: {
            first: new TextEncoder().encode(rawSalt), // Bug: Salt length not guaranteed 32 bytes
          },
        },
      },
    },
  })) as PublicKeyCredential;

  const prfResults = assertion.getClientExtensionResults().prf;
  const rawPrfKey = prfResults?.results?.first!;

  // CRITICAL: Leaking secret to backend and local storage
  await fetch('/api/vault/session', {
    method: 'POST',
    body: JSON.stringify({ prfSecret: Array.from(new Uint8Array(rawPrfKey)) }),
  });
  localStorage.setItem('cached_key', JSON.stringify(Array.from(new Uint8Array(rawPrfKey))));

  // CRITICAL: Using raw PRF output directly as AES-GCM key with extractable: true
  return crypto.subtle.importKey('raw', rawPrfKey, 'AES-GCM', true, ['decrypt', 'encrypt']);
}
```

#### Production Standard (Correct)
> **Standard**: Validates the 32-byte input salt, enforces user verification, verifies the PRF extension result from the authenticator, derives an AES-GCM key using HKDF-SHA256 with strong domain separation, keeps the key non-extractable (`extractable: false`), and never exposes or persists raw cryptographic secrets.
```typescript
const PRF_SALT_BYTE_LENGTH = 32;
const DOMAIN_SEPARATION_INFO = new TextEncoder().encode('application/zk-vault/aes-gcm-256/v1');

export async function deriveVaultKeySecure(
  credentialId: Uint8Array,
  hkdfSalt: Uint8Array
): Promise<CryptoKey> {
  if (hkdfSalt.byteLength !== PRF_SALT_BYTE_LENGTH) {
    throw new RangeError(`PRF input salt must be exactly ${PRF_SALT_BYTE_LENGTH} bytes`);
  }

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

  if (!credential) {
    throw new Error('Authentication failed or was canceled');
  }

  const extensionResults = credential.getClientExtensionResults();
  const prfResult = extensionResults.prf?.results?.first;

  if (!prfResult || !(prfResult instanceof ArrayBuffer)) {
    throw new Error('Hardware authenticator does not support or failed to evaluate PRF extension');
  }

  // Step 1: Import raw PRF output as HKDF key material
  const hkdfKey = await crypto.subtle.importKey(
    'raw',
    prfResult,
    'HKDF',
    false,
    ['deriveKey']
  );

  // Step 2: Derive non-extractable AES-GCM vault key with explicit domain separation
  const vaultKey = await crypto.subtle.deriveKey(
    {
      name: 'HKDF',
      hash: 'SHA-256',
      salt: hkdfSalt,
      info: DOMAIN_SEPARATION_INFO,
    },
    hkdfKey,
    { name: 'AES-GCM', length: 256 },
    false, // Invariant: Non-extractable CryptoKey handle
    ['encrypt', 'decrypt']
  );

  return vaultKey;
}
```

Architectural Specification & Invariant Rationale

Architectural Invariant Design: Enforce WebAuthn PRF Deterministic Key Derivation and Client-Side Zero-Knowledge Isolation

Enforce WebAuthn PRF Deterministic Key Derivation and Client-Side Zero-Knowledge Isolation defines an industrial-grade behavioral standard for security engineering. Enforces hardware-backed deterministic symmetric key derivation via the WebAuthn Pseudo-Random Function (PRF) extension for client-side zero-knowledge vaults. Guarantees 32-byte input salt bounds, HKDF domain separation, ephemeral in-memory handling, and non-extractable Web Crypto keys without transmitting PRF secrets across the wire. 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: Raw PRF Output Exposure, Direct Cipher Usage Without HKDF, or Server-Side Transmission of Authenticator Secrets 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 DriftRaw PRF Output Exposure, Direct Cipher Usage Without HKDF, or Server-Side Transmission of Authenticator SecretsCritical
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 authenticator PRF support during registration by asserting `getClientExtensionResults().prf?.enabled === true` before persisting credentials.

Engineers MUST ALWAYS verify authenticator PRF support during registration by asserting `getClientExtensionResults().prf?.enabled === true` before persisting credentials.

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 pass exactly 32-byte `Uint8Array` buffers to `eval.first` (and optional `eval.second`) in `publicKey.extensions.prf`.

Engineers MUST ALWAYS pass exactly 32-byte `Uint8Array` buffers to `eval.first` (and optional `eval.second`) in `publicKey.extensions.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.
3

Engineers MUST NEVER use the raw PRF result (`results.first`) directly as a symmetric cipher key (e.g., AES-GCM)

Engineers MUST NEVER use the raw PRF result (`results.first`) directly as a symmetric cipher key (e.g., AES-GCM); it MUST be ingested as HKDF key material (`HKDF`, `deriveKey`) with an application-specific domain separation `info` string.

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 raw PRF output, intermediate HKDF seeds, or derived vault symmetric keys to backend endpoints or telemetry services.

Services MUST NEVER transmit raw PRF output, intermediate HKDF seeds, or derived vault symmetric keys to backend endpoints or telemetry services.

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 PRF outputs in persistent client storage (localStorage, sessionStorage, unencrypted IndexedDB)

Components NEVER store PRF outputs in persistent client storage (localStorage, sessionStorage, unencrypted IndexedDB); keys MUST reside exclusively in non-extractable `CryptoKey` instances in memory and be zeroed upon session termination.

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 SHOULD catch cases where `getClientExtensionResults().prf?.results` is missing or undefined (e.g., authenticator lack of PRF support or locked hardware) and fail closed rather than falling back to non-PRF password hashes without user disclosure.

Code SHOULD catch cases where `getClientExtensionResults().prf?.results` is missing or undefined (e.g., authenticator lack of PRF support or locked hardware) and fail closed rather than falling back to non-PRF password hashes without user disclosure.

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 Enforce WebAuthn PRF Deterministic Key Derivation and Client-Side Zero-Knowledge Isolation critical for AI coding assistants?

Enforces hardware-backed deterministic symmetric key derivation via the WebAuthn Pseudo-Random Function (PRF) extension for client-side zero-knowledge vaults. Guarantees 32-byte input salt bounds, HKDF domain separation, ephemeral in-memory handling, and non-extractable Web Crypto keys without transmitting PRF secrets across the wire. 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 (Raw PRF Output Exposure, Direct Cipher Usage Without HKDF, or Server-Side Transmission of Authenticator Secrets) 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

Enforce