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

Enforce WebAuthn PRF Zero-Knowledge Key Derivation and Conditional Mediation Hygiene

Enforces zero-knowledge client-side encryption architectures utilizing WebAuthn Pseudo-Random Function (PRF) extensions and Conditional Mediation. Guarantees that authenticator-derived symmetric roots are never exposed to the server, never persisted unencrypted in local storage, and strictly isolated as non-extractable cryptographic keys.

Prohibited Anti-Pattern: Exposing raw PRF outputs to the network, failing to isolate derived keys, or persisting authenticator roots in browser storage.

Export Ready-to-Drop Configuration

Select format below to copy code or download file directly.

---
description: Enforce WebAuthn PRF Zero-Knowledge Key Derivation and Conditional Mediation Hygiene - Enforces zero-knowledge client-side encryption architectures utilizing WebAuthn Pseudo-Random Function (PRF) extensions and Conditional Mediation. Guarantees that authenticator-derived symmetric roots are never exposed to the server, never persisted unencrypted in local storage, and strictly isolated as non-extractable cryptographic keys.
globs: src/**/*.{ts,tsx}, lib/**/*.{ts,tsx}
alwaysApply: true
verified_by: "agentrules.org"
license: "CC-BY-4.0"
source: "https://agentrules.org/rules/webauthn-conditional-mediation-prf-vault-derivation"
---

# Enforce WebAuthn PRF Zero-Knowledge Key Derivation and Conditional Mediation Hygiene

> **Severity**: CRITICAL | **Category**: security
> **Anti-Pattern Warning**: Exposing raw PRF outputs to the network, failing to isolate derived keys, or persisting authenticator roots in browser storage.

## System Constraints
You are a Principal Security Architect enforcing zero-knowledge WebAuthn PRF client vault invariants. The PRF (Pseudo-Random Function) extension derives hardware-bound secrets directly from client authenticators. You must mandate that raw PRF outputs are never transmitted over the wire, never stored in persistent browser storage (localStorage, IndexedDB), are always derived into non-extractable CryptoKey handles using HKDF, and that conditional mediation flows gracefully manage AbortController lifecycles.

## Strict Guidelines
- Engineers MUST ALWAYS isolate raw PRF extension outputs in transient memory and immediately derive non-extractable Web Crypto `CryptoKey` instances using HKDF (RFC 5869).
- Engineers MUST NOT transmit raw PRF outputs, authenticator seeds, or derived master encryption keys to any backend service or logging pipeline.
- Code SHOULD verify `PublicKeyCredential.isConditionalMediationAvailable()` before passing `mediation: 'conditional'` to `navigator.credentials.get()`.
- Services MUST enforce authenticated symmetric encryption (AES-256-GCM or ChaCha20-Poly1305) with unique 96-bit cryptographically secure IVs for all vault operations using the PRF-derived key.
- Components NEVER store PRF evaluation secrets or plain text decryption keys in Web Storage APIs (`localStorage`, `sessionStorage`) or unencrypted IndexedDB stores.
- Engineers MUST ALWAYS attach an `AbortController` signal to conditional mediation queries and abort pending requests prior to initiating modal or secondary registration flows.

## Bad vs Good Implementations
### WebAuthn PRF Key Derivation and Conditional Mediation

#### Bad Antipattern (AI Common Hallucination)
> **Why it fails**: This code violates the zero-knowledge trust model by transmitting the raw hardware-derived PRF output over HTTP to a backend server. Additionally, it caches the secret in plaintext within `localStorage` where XSS attacks can read it, and fails to handle `AbortSignal` lifecycle or Web Crypto isolation.
```typescript
import { client } from './api';

export async function unlockVaultInsecurely(challenge: string, salt: Uint8Array) {
  // Flaw 1: No conditional mediation support detection
  // Flaw 2: Passing raw PRF output directly over the wire to backend
  // Flaw 3: Persisting raw PRF buffer in localStorage
  const credential = (await navigator.credentials.get({
    mediation: 'conditional',
    publicKey: {
      challenge: Uint8Array.from(atob(challenge), c => c.charCodeAt(0)),
      extensions: {
        prf: {
          eval: { first: salt }
        }
      }
    }
  })) as PublicKeyCredential;

  const prfExtension = credential.getClientExtensionResults().prf;
  const rawPrfKey = new Uint8Array(prfExtension?.results?.first!);

  // CRITICAL: Transmitting hardware-derived root secret to server violates zero-knowledge
  await client.post('/api/vault/verify', {
    credentialId: credential.id,
    rawPrfKey: Array.from(rawPrfKey)
  });

  // CRITICAL: Insecure persistence of raw cryptographic key
  localStorage.setItem('cached_prf_secret', JSON.stringify(Array.from(rawPrfKey)));

  return rawPrfKey;
}
```

#### Production Standard (Correct)
> **Standard**: Derives a non-extractable `AES-GCM` CryptoKey handle through HKDF within the client Web Crypto boundary, zeroizes raw memory immediately in a `finally` block, respects the `AbortController` lifecycle, and never transmits the PRF output or master keys across the network.
```typescript
export interface VaultDerivationResult {
  vaultKey: CryptoKey;
  credentialId: string;
}

export async function unlockVaultSecurely(
  challenge: Uint8Array,
  salt: Uint8Array,
  abortSignal: AbortSignal
): Promise<VaultDerivationResult | null> {
  const isConditionalAvailable =
    typeof window !== 'undefined' &&
    window.PublicKeyCredential &&
    await window.PublicKeyCredential.isConditionalMediationAvailable?.();

  const credential = (await navigator.credentials.get({
    signal: abortSignal,
    mediation: isConditionalAvailable ? 'conditional' : 'optional',
    publicKey: {
      challenge,
      timeout: 60000,
      userVerification: 'required',
      extensions: {
        prf: {
          eval: { first: salt }
        }
      }
    }
  })) as PublicKeyCredential | null;

  if (!credential) return null;

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

  if (!prfResult) {
    throw new Error('Authenticator did not return a PRF evaluation for vault derivation.');
  }

  // Transiently import raw PRF output to derive non-extractable AES-GCM vault key via HKDF
  const rawPrfBuffer = new Uint8Array(prfResult);
  try {
    const ikmKey = await crypto.subtle.importKey(
      'raw',
      rawPrfBuffer,
      'HKDF',
      false,
      ['deriveKey']
    );

    const vaultKey = await crypto.subtle.deriveKey(
      {
        name: 'HKDF',
        hash: 'SHA-256',
        salt: new Uint8Array(32), // Domain-separated salt
        info: new TextEncoder().encode('webauthn-zero-knowledge-vault-v1')
      },
      ikmKey,
      { name: 'AES-GCM', length: 256 },
      false, // non-extractable: cannot be exported from Web Crypto sandbox
      ['encrypt', 'decrypt']
    );

    return {
      vaultKey,
      credentialId: credential.id
    };
  } finally {
    // Scrub sensitive raw memory buffer
    rawPrfBuffer.fill(0);
  }
}
```

Recommended MCP Servers (mcp-serverlist.com)

Equip agent with system tools to verify code for this stack.

Architectural Specification & Invariant Rationale

Architectural Invariant Design: Enforce WebAuthn PRF Zero-Knowledge Key Derivation and Conditional Mediation Hygiene

Enforce WebAuthn PRF Zero-Knowledge Key Derivation and Conditional Mediation Hygiene defines an industrial-grade behavioral standard for security engineering. Enforces zero-knowledge client-side encryption architectures utilizing WebAuthn Pseudo-Random Function (PRF) extensions and Conditional Mediation. Guarantees that authenticator-derived symmetric roots are never exposed to the server, never persisted unencrypted in local storage, and strictly isolated as non-extractable cryptographic keys. 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: Exposing raw PRF outputs to the network, failing to isolate derived keys, or persisting authenticator roots in browser storage. 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 DriftExposing raw PRF outputs to the network, failing to isolate derived keys, or persisting authenticator roots in browser storage.Critical
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 isolate raw PRF extension outputs in transient memory and immediately derive non-extractable Web Crypto `CryptoKey` instances using HKDF (RFC 5869).

Engineers MUST ALWAYS isolate raw PRF extension outputs in transient memory and immediately derive non-extractable Web Crypto `CryptoKey` instances using HKDF (RFC 5869).

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, authenticator seeds, or derived master encryption keys to any backend service or logging pipeline.

Engineers MUST NOT transmit raw PRF outputs, authenticator seeds, or derived master encryption keys to any backend service or logging pipeline.

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 verify `PublicKeyCredential.isConditionalMediationAvailable()` before passing `mediation

Code SHOULD verify `PublicKeyCredential.isConditionalMediationAvailable()` before passing `mediation: 'conditional'` to `navigator.credentials.get()`.

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 enforce authenticated symmetric encryption (AES-256-GCM or ChaCha20-Poly1305) with unique 96-bit cryptographically secure IVs for all vault operations using the PRF-derived key.

Services MUST enforce authenticated symmetric encryption (AES-256-GCM or ChaCha20-Poly1305) with unique 96-bit cryptographically secure IVs for all vault operations using the PRF-derived 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.
5

Components NEVER store PRF evaluation secrets or plain text decryption keys in Web Storage APIs (`localStorage`, `sessionStorage`) or unencrypted IndexedDB stores.

Components NEVER store PRF evaluation secrets or plain text decryption keys in Web Storage APIs (`localStorage`, `sessionStorage`) or unencrypted IndexedDB stores.

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

Engineers MUST ALWAYS attach an `AbortController` signal to conditional mediation queries and abort pending requests prior to initiating modal or secondary registration flows.

Engineers MUST ALWAYS attach an `AbortController` signal to conditional mediation queries and abort pending requests prior to initiating modal or secondary registration 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.
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 Zero-Knowledge Key Derivation and Conditional Mediation Hygiene critical for AI coding assistants?

Enforces zero-knowledge client-side encryption architectures utilizing WebAuthn Pseudo-Random Function (PRF) extensions and Conditional Mediation. Guarantees that authenticator-derived symmetric roots are never exposed to the server, never persisted unencrypted in local storage, and strictly isolated as non-extractable cryptographic keys. 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 (Exposing raw PRF outputs to the network, failing to isolate derived keys, or persisting authenticator roots in browser storage.) 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