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

Deterministic Client-Side Key Derivation via WebAuthn PRF Extension

Standardizes client-side symmetric key derivation using the WebAuthn Pseudo-Random Function (PRF) extension (`eval` / `evalByCredential`). Mandates strict tenant-isolated HKDF chaining, in-memory isolation of derived root secrets, and zero transmission of derived keys or raw PRF outputs across transport layers.

Prohibited Anti-Pattern: Leaking Raw PRF Outputs to Backend APIs or Directly Using PRF Output as Symmetric Cipher Keys Without Tenant-Scoped HKDF Expansion

Export Ready-to-Drop Configuration

Select format below to copy code or download file directly.

---
description: Deterministic Client-Side Key Derivation via WebAuthn PRF Extension - Standardizes client-side symmetric key derivation using the WebAuthn Pseudo-Random Function (PRF) extension (`eval` / `evalByCredential`). Mandates strict tenant-isolated HKDF chaining, in-memory isolation of derived root secrets, and zero transmission of derived keys or raw PRF outputs across transport layers.
globs: src/**/*.{ts,tsx}, lib/**/*.{ts,tsx}, packages/**/*.{ts,tsx}
alwaysApply: true
verified_by: "agentrules.org"
license: "CC-BY-4.0"
source: "https://agentrules.org/rules/webauthn-prf-deterministic-key-derivation"
---

# Deterministic Client-Side Key Derivation via WebAuthn PRF Extension

> **Severity**: CRITICAL | **Category**: security
> **Anti-Pattern Warning**: Leaking Raw PRF Outputs to Backend APIs or Directly Using PRF Output as Symmetric Cipher Keys Without Tenant-Scoped HKDF Expansion

## System Constraints
You are a Principal Security Architect enforcing zero-knowledge client-side encryption using the WebAuthn PRF (Pseudo-Random Function) extension. Ensure that raw PRF outputs never leave browser memory, are never logged, and are strictly processed through HKDF with application- and tenant-specific context labels before generating Web Crypto API CryptoKey instances.

## Strict Guidelines
- Engineers MUST ALWAYS inspect `assertion.getClientExtensionResults().prf` to verify the hardware authenticator successfully executed the PRF evaluation before proceeding.
- Engineers MUST NOT transmit raw PRF evaluation outputs (`first` or `second` ArrayBuffers) or derived keys over any network transport or include them in serialization payloads.
- Engineers MUST ALWAYS ingest the raw 32-byte PRF output into an HKDF (RFC 5869) pipeline using `SubtleCrypto.importKey('raw', prfOutput, 'HKDF', false, ['deriveKey'])` with tenant-isolated salt and info parameters.
- Code SHOULD enforce `extractable: false` on all derived symmetric `CryptoKey` instances (e.g., AES-GCM-256) to prevent exfiltration via DOM injection or malicious extensions.
- Services MUST supply an unguessable or domain-separated `eval.first` input salt (32 bytes) during `navigator.credentials.get` that is tied strictly to the tenant or partition identity.
- Components NEVER store derived master secrets, intermediate HKDF material, or raw PRF buffers in persistent web storage (`localStorage`, `sessionStorage`, or `IndexedDB`).

## Bad vs Good Implementations
### WebAuthn PRF Output Handling and Tenant-Isolated HKDF Derivation

#### Bad Antipattern (AI Common Hallucination)
> **Why it fails**: Transmits raw PRF output to the backend server, entirely compromising zero-knowledge guarantees. Uses an all-zero static salt and bypasses HKDF contextual expansion, producing an extractable cipher key with no tenant isolation.
```typescript
import axios from 'axios';

export async function unlockVault(credentialId: string, serverChallenge: Uint8Array) {
  const assertion = await navigator.credentials.get({
    publicKey: {
      challenge: serverChallenge,
      allowCredentials: [{ id: Uint8Array.from(atob(credentialId), c => c.charCodeAt(0)), type: 'public-key' }],
      extensions: {
        // BAD: Static generic salt and directly transmitting the PRF secret to the backend
        prf: { eval: { first: new Uint8Array(32) } }
      }
    }
  }) as PublicKeyCredential;

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

  if (!rawSecret) throw new Error('PRF not supported');

  // CRITICAL SECURITY FLAW: Sending zero-knowledge PRF output over transport layer
  await axios.post('/api/vault/unlock', {
    prfSecret: Array.from(new Uint8Array(rawSecret))
  });

  // BAD: Directly using raw PRF output without HKDF contextual domain separation
  return window.crypto.subtle.importKey('raw', rawSecret, 'AES-GCM', true, ['encrypt', 'decrypt']);
}
```

#### Production Standard (Correct)
> **Standard**: Validates PRF capability, keeps the raw PRF result strictly inside the Web Crypto runtime boundary, contextually derives keys via HKDF with tenant isolation labels, and enforces extractable: false on the final AES-GCM key.
```typescript
export interface VaultKeyDerivationParams {
  credentialId: Uint8Array;
  challenge: Uint8Array;
  tenantId: string;
  appSalt: Uint8Array; // Cryptographically random, domain-separated 32-byte salt
}

export async function deriveTenantVaultKey(params: VaultKeyDerivationParams): Promise<CryptoKey> {
  const assertion = await navigator.credentials.get({
    publicKey: {
      challenge: params.challenge,
      allowCredentials: [{ id: params.credentialId, type: 'public-key' }],
      extensions: {
        prf: {
          eval: {
            first: params.appSalt
          }
        }
      }
    }
  }) as PublicKeyCredential | null;

  if (!assertion) {
    throw new Error('Credential assertion was cancelled or failed.');
  }

  const extResults = assertion.getClientExtensionResults();
  const prfResult = extResults.prf?.results?.first;

  if (!prfResult) {
    throw new Error('Authenticator failed to execute PRF extension or hardware lacks support.');
  }

  // Import raw PRF output strictly as non-extractable HKDF key material in memory
  const baseKey = await window.crypto.subtle.importKey(
    'raw',
    prfResult,
    { name: 'HKDF' },
    false,
    ['deriveKey']
  );

  const textEncoder = new TextEncoder();
  const info = textEncoder.encode(`tenant:${params.tenantId}:purpose:vault-aes-gcm-256`);
  const hkdfSalt = textEncoder.encode(`salt:v1:${params.tenantId}`);

  // Derive tenant-isolated, non-extractable AES-GCM key without persisting or leaking raw buffers
  return window.crypto.subtle.deriveKey(
    {
      name: 'HKDF',
      hash: 'SHA-256',
      salt: hkdfSalt,
      info: info
    },
    baseKey,
    { name: 'AES-GCM', length: 256 },
    false, // extractable: false prevents DOM memory dumping or exfiltration
    ['encrypt', 'decrypt']
  );
}
```

Recommended MCP Servers (mcp-serverlist.com)

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

Architectural Specification & Invariant Rationale

Architectural Invariant Design: Deterministic Client-Side Key Derivation via WebAuthn PRF Extension

Deterministic Client-Side Key Derivation via WebAuthn PRF Extension defines an industrial-grade behavioral standard for security engineering. Standardizes client-side symmetric key derivation using the WebAuthn Pseudo-Random Function (PRF) extension (`eval` / `evalByCredential`). Mandates strict tenant-isolated HKDF chaining, in-memory isolation of derived root secrets, and zero transmission of derived keys or raw PRF outputs across transport layers. 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: Leaking Raw PRF Outputs to Backend APIs or Directly Using PRF Output as Symmetric Cipher Keys Without Tenant-Scoped HKDF Expansion 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 DriftLeaking Raw PRF Outputs to Backend APIs or Directly Using PRF Output as Symmetric Cipher Keys Without Tenant-Scoped HKDF ExpansionCritical
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 inspect `assertion.getClientExtensionResults().prf` to verify the hardware authenticator successfully executed the PRF evaluation before proceeding.

Engineers MUST ALWAYS inspect `assertion.getClientExtensionResults().prf` to verify the hardware authenticator successfully executed the PRF evaluation before proceeding.

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 evaluation outputs (`first` or `second` ArrayBuffers) or derived keys over any network transport or include them in serialization payloads.

Engineers MUST NOT transmit raw PRF evaluation outputs (`first` or `second` ArrayBuffers) or derived keys over any network transport or include them in serialization payloads.

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 ingest the raw 32-byte PRF output into an HKDF (RFC 5869) pipeline using `SubtleCrypto.importKey('raw', prfOutput, 'HKDF', false, ['deriveKey'])` with tenant-isolated salt and info parameters.

Engineers MUST ALWAYS ingest the raw 32-byte PRF output into an HKDF (RFC 5869) pipeline using `SubtleCrypto.importKey('raw', prfOutput, 'HKDF', false, ['deriveKey'])` with tenant-isolated salt and info parameters.

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 SHOULD enforce `extractable

Code SHOULD enforce `extractable: false` on all derived symmetric `CryptoKey` instances (e.g., AES-GCM-256) to prevent exfiltration via DOM injection or malicious extensions.

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

Services MUST supply an unguessable or domain-separated `eval.first` input salt (32 bytes) during `navigator.credentials.get` that is tied strictly to the tenant or partition identity.

Services MUST supply an unguessable or domain-separated `eval.first` input salt (32 bytes) during `navigator.credentials.get` that is tied strictly to the tenant or partition identity.

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

Components NEVER store derived master secrets, intermediate HKDF material, or raw PRF buffers in persistent web storage (`localStorage`, `sessionStorage`, or `IndexedDB`).

Components NEVER store derived master secrets, intermediate HKDF material, or raw PRF buffers in persistent web storage (`localStorage`, `sessionStorage`, or `IndexedDB`).

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

Standardizes client-side symmetric key derivation using the WebAuthn Pseudo-Random Function (PRF) extension (`eval` / `evalByCredential`). Mandates strict tenant-isolated HKDF chaining, in-memory isolation of derived root secrets, and zero transmission of derived keys or raw PRF outputs across transport layers. 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 (Leaking Raw PRF Outputs to Backend APIs or Directly Using PRF Output as Symmetric Cipher Keys Without Tenant-Scoped HKDF Expansion) 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