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

WebAuthn PRF Client-Side Zero-Knowledge Storage Invariant

Enforces zero-knowledge local storage encryption derived via WebAuthn PRF (Pseudo-Random Function) extension hardware seeds. Mandates transient in-memory derivation, strict domain separation via HKDF, total prevention of PRF output leakage to backend servers, and non-extractable CryptoKey management.

Prohibited Anti-Pattern: Transmitting WebAuthn PRF output to backend authentication endpoints and caching derived raw keys in persistent browser storage

Export Ready-to-Drop Configuration

Select format below to copy code or download file directly.

---
description: WebAuthn PRF Client-Side Zero-Knowledge Storage Invariant - Enforces zero-knowledge local storage encryption derived via WebAuthn PRF (Pseudo-Random Function) extension hardware seeds. Mandates transient in-memory derivation, strict domain separation via HKDF, total prevention of PRF output leakage to backend servers, and non-extractable CryptoKey management.
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-zk-local-storage-invariant"
---

# WebAuthn PRF Client-Side Zero-Knowledge Storage Invariant

> **Severity**: CRITICAL | **Category**: security
> **Anti-Pattern Warning**: Transmitting WebAuthn PRF output to backend authentication endpoints and caching derived raw keys in persistent browser storage

## System Constraints
You are a Principal Security Architect enforcing strict Zero-Knowledge Client-Side Encryption via WebAuthn PRF extension. Enforce that raw PRF outputs and derived symmetric keys are never persisted to disk, never transmitted across network boundaries to any server, and must always be expanded via HKDF into non-extractable CryptoKey handles with immediate memory sanitization.

## Strict Guidelines
- Engineers MUST ALWAYS strip and sanitize `clientExtensionResults.prf` from authentication assertion payloads before transmitting assertion responses to relying party servers.
- Engineers MUST ALWAYS process the raw PRF byte output as an input key material (IKM) through HKDF-SHA256 with explicit domain separation context before generating AES-GCM symmetric encryption keys.
- Engineers MUST NEVER persist the derived encryption keys, PRF seeds, or raw intermediate buffers to Web Storage (`localStorage`, `sessionStorage`), IndexedDB, or OPFS.
- Code MUST instantiate the derived cryptographic key with `extractable: false` using the Web Cryptography API (`crypto.subtle`).
- Services MUST zero-fill transient raw memory buffers (`Uint8Array.prototype.fill(0)`) immediately after importing them into the Web Crypto subsystem.
- Components NEVER fall back to unauthenticated or unencrypted storage when the authenticator lacks PRF extension support; an explicit unsupported hardware error must be raised.

## Bad vs Good Implementations
### WebAuthn PRF Key Derivation and Network Sanitization

#### Bad Antipattern (AI Common Hallucination)
> **Why it fails**: The implementation exposes client-side PRF secret seeds to the server by sending the unsanitized assertion response over the network, bypasses HKDF domain separation by directly using raw PRF bytes as a cipher key, and completely invalidates zero-knowledge invariants by writing the key to unencrypted localStorage.
```typescript
import { startAuthentication } from '@simplewebauthn/browser';

export async function unlockVault(authOptions: any) {
  const assertion = await startAuthentication(authOptions);

  // CRITICAL VULNERABILITY: Raw assertion sent directly to server,
  // leaking the PRF output to relying party backend.
  await fetch('/api/verify-assertion', {
    method: 'POST',
    body: JSON.stringify(assertion)
  });

  // CRITICAL VULNERABILITY: Using PRF output directly as AES key without HKDF
  // and persisting raw key material in localStorage.
  const rawPrf = (assertion.clientExtensionResults as any).prf?.results?.first;
  const base64Key = btoa(String.fromCharCode(...new Uint8Array(rawPrf)));
  window.localStorage.setItem('vault_key', base64Key);

  return base64Key;
}
```

#### Production Standard (Correct)
> **Standard**: The fixed implementation clones and deletes the PRF results prior to network serialization, preserves zero-knowledge isolation from the relying party server, enforces HKDF domain separation, ensures the resulting CryptoKey is marked non-extractable, and proactively overwrites the transient raw PRF buffer in memory.
```typescript
import { startAuthentication } from '@simplewebauthn/browser';
import type { AuthenticationResponseJSON } from '@simplewebauthn/types';

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

export async function unlockVaultSecure(authOptions: any): Promise<CryptoKey> {
  const assertion: AuthenticationResponseJSON = await startAuthentication(authOptions);

  const prfResult = assertion.clientExtensionResults?.prf?.results?.first;
  if (!prfResult) {
    throw new Error('Authenticator does not support PRF extension or eval failed');
  }

  // Copy PRF output into transient memory
  const rawPrfBuffer = new Uint8Array(prfResult);

  // INVARIANT: Strip PRF extension results before transmitting to backend server
  const serverPayload = structuredClone(assertion);
  if (serverPayload.clientExtensionResults?.prf) {
    delete serverPayload.clientExtensionResults.prf;
  }

  const verifyPromise = fetch('/api/verify-assertion', {
    method: 'POST',
    headers: { 'Content-Type': 'application/json' },
    body: JSON.stringify(serverPayload)
  });

  try {
    // INVARIANT: Expand PRF output via HKDF into non-extractable AES-GCM-256 key
    const baseKey = await crypto.subtle.importKey(
      'raw',
      rawPrfBuffer,
      'HKDF',
      false,
      ['deriveKey']
    );

    const derivedKey = await crypto.subtle.deriveKey(
      {
        name: 'HKDF',
        hash: 'SHA-256',
        salt: HKDF_SALT,
        info: HKDF_INFO
      },
      baseKey,
      { name: 'AES-GCM', length: 256 },
      false, // non-extractable
      ['encrypt', 'decrypt']
    );

    const serverRes = await verifyPromise;
    if (!serverRes.ok) {
      throw new Error('Assertion validation failed on server');
    }

    return derivedKey;
  } finally {
    // INVARIANT: Zero transient memory buffers immediately
    rawPrfBuffer.fill(0);
  }
}
```

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 Storage Invariant

WebAuthn PRF Client-Side Zero-Knowledge Storage Invariant defines an industrial-grade behavioral standard for security engineering. Enforces zero-knowledge local storage encryption derived via WebAuthn PRF (Pseudo-Random Function) extension hardware seeds. Mandates transient in-memory derivation, strict domain separation via HKDF, total prevention of PRF output leakage to backend servers, and non-extractable CryptoKey management. 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 WebAuthn PRF output to backend authentication endpoints and caching derived raw keys in persistent 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 WebAuthn PRF output to backend authentication endpoints and caching derived raw keys in persistent browser storageCritical
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 and sanitize `clientExtensionResults.prf` from authentication assertion payloads before transmitting assertion responses to relying party servers.

Engineers MUST ALWAYS strip and sanitize `clientExtensionResults.prf` from authentication assertion payloads before transmitting assertion responses to relying party servers.

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 process the raw PRF byte output as an input key material (IKM) through HKDF-SHA256 with explicit domain separation context before generating AES-GCM symmetric encryption keys.

Engineers MUST ALWAYS process the raw PRF byte output as an input key material (IKM) through HKDF-SHA256 with explicit domain separation context before generating AES-GCM symmetric encryption keys.

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 persist the derived encryption keys, PRF seeds, or raw intermediate buffers to Web Storage (`localStorage`, `sessionStorage`), IndexedDB, or OPFS.

Engineers MUST NEVER persist the derived encryption keys, PRF seeds, or raw intermediate buffers to Web Storage (`localStorage`, `sessionStorage`), IndexedDB, or OPFS.

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 MUST instantiate the derived cryptographic key with `extractable

Code MUST instantiate the derived cryptographic key with `extractable: false` using the Web Cryptography API (`crypto.subtle`).

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 zero-fill transient raw memory buffers (`Uint8Array.prototype.fill(0)`) immediately after importing them into the Web Crypto subsystem.

Services MUST zero-fill transient raw memory buffers (`Uint8Array.prototype.fill(0)`) immediately after importing them into the Web Crypto subsystem.

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 fall back to unauthenticated or unencrypted storage when the authenticator lacks PRF extension support

Components NEVER fall back to unauthenticated or unencrypted storage when the authenticator lacks PRF extension support; an explicit unsupported hardware error must be raised.

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 Storage Invariant critical for AI coding assistants?

Enforces zero-knowledge local storage encryption derived via WebAuthn PRF (Pseudo-Random Function) extension hardware seeds. Mandates transient in-memory derivation, strict domain separation via HKDF, total prevention of PRF output leakage to backend servers, and non-extractable CryptoKey management. 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 WebAuthn PRF output to backend authentication endpoints and caching derived raw keys in persistent 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