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

WebAuthn PRF Client-Side Zero-Knowledge Key Derivation Invariants

Enforces strict client-side isolation of WebAuthn Pseudo-Random Function (PRF) extension outputs and derived cryptographic keys. Mandates sanitization of credential assertions prior to server transmission, HKDF domain separation for key derivation, and storage of derived keys solely within non-extractable CryptoKey primitives.

Prohibited Anti-Pattern: Transmitting raw PRF outputs to Relying Party servers or persisting derived keys into extractable browser storage.

Export Ready-to-Drop Configuration

Select format below to copy code or download file directly.

---
description: WebAuthn PRF Client-Side Zero-Knowledge Key Derivation Invariants - Enforces strict client-side isolation of WebAuthn Pseudo-Random Function (PRF) extension outputs and derived cryptographic keys. Mandates sanitization of credential assertions prior to server transmission, HKDF domain separation for key derivation, and storage of derived keys solely within non-extractable CryptoKey primitives.
globs: src/**/*.{ts,tsx}, lib/**/*.{ts,tsx}
alwaysApply: true
verified_by: "agentrules.org"
license: "CC-BY-4.0"
source: "https://agentrules.org/rules/passkey-prf-client-side-zk-encryption-invariant"
---

# WebAuthn PRF Client-Side Zero-Knowledge Key Derivation Invariants

> **Severity**: CRITICAL | **Category**: security
> **Anti-Pattern Warning**: Transmitting raw PRF outputs to Relying Party servers or persisting derived keys into extractable browser storage.

## System Constraints
You are a Principal Security Architect enforcing zero-knowledge client-side encryption using WebAuthn PRF extensions. Your mandate is to ensure that biometric hardware secrets never leak to the server, raw PRF extension outputs are stripped from authentication payloads before transport, and all symmetric keys are derived using strict HKDF domain separation inside non-extractable WebCrypto primitives.

## Strict Guidelines
- Engineers MUST ALWAYS strip `clientExtensionResults.prf` from the WebAuthn assertion payload before transmitting the credential to the Relying Party (RP) backend.
- Engineers MUST ALWAYS pass the raw 32-byte PRF output through HKDF-SHA-256 with an explicit, distinct application salt and context info string before initializing symmetric ciphers.
- Engineers MUST import derived keys into the Web Cryptography API using `{ extractable: false }` to prevent client-side script inspection or memory exfiltration via cross-site vulnerabilities.
- Engineers MUST NOT persist raw PRF outputs, HKDF master seeds, or plaintext derived keys to `localStorage`, `sessionStorage`, or unencrypted IndexedDB.
- Code MUST verify authenticator PRF compatibility during registration by validating `clientExtensionResults.prf?.supported === true` before provisioning zero-knowledge vaults.
- Services MUST enforce that the server Relying Party strictly receives standard authenticator data and client data JSON, rejecting any client payloads attempting to register PRF evaluation results on backend stores.

## Bad vs Good Implementations
### WebAuthn PRF Extraction, Payload Sanitization, and Non-Extractable Key Derivation

#### Bad Antipattern (AI Common Hallucination)
> **Why it fails**: The implementation transmits the entire assertion response, including `clientExtensionResults.prf`, directly to the server. This breaks the zero-knowledge invariant by exposing the hardware-derived PRF secret to the network and backend. Furthermore, it bypasses HKDF domain separation and writes sensitive key material directly into persistent, extractable `localStorage`.
```typescript
import { startAuthentication } from '@simplewebauthn/browser';

export async function unlockVaultInsecure(authOptions: any) {
  // Anti-pattern: Sending unmodified PRF extension results to server
  const assertion = await startAuthentication({
    optionsJSON: {
      ...authOptions,
      extensions: { prf: { eval: { first: new Uint8Array(32).fill(1) } } },
    },
  });

  // CRITICAL SECURITY FLAW: Raw PRF extension output leaked to backend server
  const verifyRes = await fetch('/api/auth/verify', {
    method: 'POST',
    body: JSON.stringify(assertion),
  });

  // CRITICAL SECURITY FLAW: Using raw PRF output directly as AES key & storing in localStorage
  const rawPrf = assertion.clientExtensionResults?.prf?.results?.first;
  const keyBytes = new Uint8Array(rawPrf);
  localStorage.setItem('raw_prf_key', JSON.stringify(Array.from(keyBytes)));
  return keyBytes;
}
```

#### Production Standard (Correct)
> **Standard**: The good pattern strips `clientExtensionResults` prior to sending the assertion to the RP backend, maintaining the zero-knowledge boundary. It imports the raw PRF result directly into WebCrypto as an ephemeral HKDF intermediate key (IKM) and derives a strictly non-extractable AES-GCM-256 key without ever persisting raw cryptographic material to disk or insecure browser storage.
```typescript
import { startAuthentication } from '@simplewebauthn/browser';

const HKDF_SALT = new TextEncoder().encode('app:zk-vault:salt:v1');
const HKDF_INFO = new TextEncoder().encode('aes-gcm-256-encryption-key');

export async function unlockVaultSecure(authOptions: PublicKeyCredentialRequestOptionsJSON): Promise<CryptoKey> {
  const prfSalt = crypto.getRandomValues(new Uint8Array(32));
  const assertion = await startAuthentication({
    optionsJSON: {
      ...authOptions,
      extensions: {
        prf: {
          eval: { first: prfSalt },
        },
      },
    },
  });

  const rawPrfBuffer = assertion.clientExtensionResults?.prf?.results?.first;
  if (!rawPrfBuffer) {
    throw new Error('Authenticator did not return a PRF output; zero-knowledge derivation aborted.');
  }

  // INVARIANT: Strip clientExtensionResults before server transmission to preserve zero-knowledge
  const sanitizedAssertion = { ...assertion };
  delete sanitizedAssertion.clientExtensionResults;

  const verifyRes = await fetch('/api/auth/verify', {
    method: 'POST',
    headers: { 'Content-Type': 'application/json' },
    body: JSON.stringify(sanitizedAssertion),
  });
  if (!verifyRes.ok) throw new Error('Assertion validation failed.');

  // INVARIANT: Import as IKM and derive isolated, non-extractable AES-GCM CryptoKey via HKDF
  const ikm = await crypto.subtle.importKey(
    'raw',
    rawPrfBuffer,
    'HKDF',
    false,
    ['deriveKey']
  );

  return crypto.subtle.deriveKey(
    {
      name: 'HKDF',
      hash: 'SHA-256',
      salt: HKDF_SALT,
      info: HKDF_INFO,
    },
    ikm,
    { name: 'AES-GCM', length: 256 },
    false, // extractable: false prevents exfiltration from client memory
    ['encrypt', 'decrypt']
  );
}
```

Recommended MCP Servers (mcp-serverlist.com)

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

Recommended Agent Skills (askills.dev)

Ready-to-use executable skill functions tailored to this stack.

Architectural Specification & Invariant Rationale

Architectural Invariant Design: WebAuthn PRF Client-Side Zero-Knowledge Key Derivation Invariants

WebAuthn PRF Client-Side Zero-Knowledge Key Derivation Invariants defines an industrial-grade behavioral standard for security engineering. Enforces strict client-side isolation of WebAuthn Pseudo-Random Function (PRF) extension outputs and derived cryptographic keys. Mandates sanitization of credential assertions prior to server transmission, HKDF domain separation for key derivation, and storage of derived keys solely within non-extractable CryptoKey primitives. 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: Transmitting raw PRF outputs to Relying Party servers or persisting derived keys into extractable 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 DriftTransmitting raw PRF outputs to Relying Party servers or persisting derived keys into extractable 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 strip `clientExtensionResults.prf` from the WebAuthn assertion payload before transmitting the credential to the Relying Party (RP) backend.

Engineers MUST ALWAYS strip `clientExtensionResults.prf` from the WebAuthn assertion payload before transmitting the credential to the Relying Party (RP) backend.

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 the raw 32-byte PRF output through HKDF-SHA-256 with an explicit, distinct application salt and context info string before initializing symmetric ciphers.

Engineers MUST ALWAYS pass the raw 32-byte PRF output through HKDF-SHA-256 with an explicit, distinct application salt and context info string before initializing symmetric ciphers.

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 import derived keys into the Web Cryptography API using `{ extractable

Engineers MUST import derived keys into the Web Cryptography API using `{ extractable: false }` to prevent client-side script inspection or memory exfiltration via cross-site vulnerabilities.

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

Engineers MUST NOT persist raw PRF outputs, HKDF master seeds, or plaintext derived keys to `localStorage`, `sessionStorage`, or unencrypted IndexedDB.

Engineers MUST NOT persist raw PRF outputs, HKDF master seeds, or plaintext derived keys to `localStorage`, `sessionStorage`, or unencrypted 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.
5

Code MUST verify authenticator PRF compatibility during registration by validating `clientExtensionResults.prf?.supported === true` before provisioning zero-knowledge vaults.

Code MUST verify authenticator PRF compatibility during registration by validating `clientExtensionResults.prf?.supported === true` before provisioning zero-knowledge vaults.

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

Services MUST enforce that the server Relying Party strictly receives standard authenticator data and client data JSON, rejecting any client payloads attempting to register PRF evaluation results on backend stores.

Services MUST enforce that the server Relying Party strictly receives standard authenticator data and client data JSON, rejecting any client payloads attempting to register PRF evaluation results on backend 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.
Technical Questions & Answers

Frequently Asked Technical Questions

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

Q:Why is WebAuthn PRF Client-Side Zero-Knowledge Key Derivation Invariants critical for AI coding assistants?

Enforces strict client-side isolation of WebAuthn Pseudo-Random Function (PRF) extension outputs and derived cryptographic keys. Mandates sanitization of credential assertions prior to server transmission, HKDF domain separation for key derivation, and storage of derived keys solely within non-extractable CryptoKey primitives. 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 (Transmitting raw PRF outputs to Relying Party servers or persisting derived keys into extractable 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

WebAuthn