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

WebAuthn PRF Hardware Key Derivation and Zero-Knowledge Storage Standard

Enforces cryptographic invariants when deriving client-side zero-knowledge encryption keys via the WebAuthn PRF (Pseudo-Random Function) extension. Requires non-extractable WebCrypto handles, HKDF domain separation, strict authenticator capability validation, and explicit zeroing of raw PRF output to prevent hardware-backed secrets from leaking to networks or storage.

Prohibited Anti-Pattern: Exposing Raw PRF Outputs, Omitting HKDF Domain Separation, or Allowing Extractable Hardware-Derived Keys

Export Ready-to-Drop Configuration

Select format below to copy code or download file directly.

---
description: WebAuthn PRF Hardware Key Derivation and Zero-Knowledge Storage Standard - Enforces cryptographic invariants when deriving client-side zero-knowledge encryption keys via the WebAuthn PRF (Pseudo-Random Function) extension. Requires non-extractable WebCrypto handles, HKDF domain separation, strict authenticator capability validation, and explicit zeroing of raw PRF output to prevent hardware-backed secrets from leaking to networks or storage.
globs: src/**/*.{ts,tsx}, lib/**/*.{ts,tsx}, services/**/*.{ts,tsx}
alwaysApply: true
verified_by: "agentrules.org"
license: "CC-BY-4.0"
source: "https://agentrules.org/rules/webauthn-prf-zk-key-derivation"
---

# WebAuthn PRF Hardware Key Derivation and Zero-Knowledge Storage Standard

> **Severity**: CRITICAL | **Category**: security
> **Anti-Pattern Warning**: Exposing Raw PRF Outputs, Omitting HKDF Domain Separation, or Allowing Extractable Hardware-Derived Keys

## System Constraints
You are a Principal Security Architect enforcing hardware-backed zero-knowledge architecture using the WebAuthn PRF (Pseudo-Random Function) extension. You must guarantee that all encryption keys rooted in biometric hardware authenticators remain strictly client-side, zero-knowledge, non-extractable, and domain-separated.

## Strict Guidelines
- Engineers MUST ALWAYS verify that 'prf' is supported and enabled in 'credential.getClientExtensionResults().prf' before executing cryptographic operations.
- Engineers MUST NEVER transmit the raw PRF evaluation output buffer ('results.first') or derived plaintext keys over network transports, telemetry, or browser storage.
- Code MUST ALWAYS feed the raw PRF output into HKDF-SHA256 (RFC 5869) with an explicit, versioned 'info' parameter and domain salt to achieve cryptographic domain separation before creating cipher keys.
- Code MUST ALWAYS import derived symmetric keys (e.g., AES-GCM) with 'extractable: false' into the WebCrypto API subsystem so keys cannot be extracted via memory dumps or XSS injection.
- Services MUST fail closed if the hardware authenticator does not report PRF extension support during credential creation, disallowing unencrypted fallback storage without explicit user consent.
- Components MUST overwrite and zero out transient Uint8Array buffers containing raw PRF evaluations immediately after HKDF derivation using 'crypto.getRandomValues()' or array zeroing.

## Bad vs Good Implementations
### Hardware PRF Derivation with HKDF and Non-Extractable CryptoKey

#### Bad Antipattern (AI Common Hallucination)
> **Why it fails**: Transmits raw PRF output to a remote server, destroying the zero-knowledge invariant. Does not use HKDF domain separation, fails to check if PRF succeeded, does not zero out intermediate memory, and returns an extractable plaintext key representation.
```typescript
import { get } from '@github/webauthn-json';

export async function deriveVaultKeyBad(credentialId: string, salt: Uint8Array): Promise<string> {
  const credential = await navigator.credentials.get({
    publicKey: {
      challenge: new Uint8Array(32),
      allowCredentials: [{ id: new TextEncoder().encode(credentialId), type: 'public-key' }],
      extensions: { prf: { eval: { first: salt } } } as any,
    },
  }) as any;

  // CRITICAL VULNERABILITY: Raw PRF output transmitted directly to server
  const rawPrf = credential.getClientExtensionResults().prf.results.first;
  const base64Key = btoa(String.fromCharCode(...new Uint8Array(rawPrf)));
  
  await fetch('/api/user/sync-key', {
    method: 'POST',
    body: JSON.stringify({ key: base64Key }),
  });

  return base64Key;
}
```

#### Production Standard (Correct)
> **Standard**: Validates the PRF extension response, derives an non-extractable WebCrypto AES-GCM handle using HKDF-SHA256 with domain separation, keeps keys strictly in browser secure enclaves without network transmission, and zeroes memory buffers in a finally block.
```typescript
export interface PrfDerivationOptions {
  credentialId: BufferSource;
  salt: Uint8Array; // 32 bytes cryptographically secure salt
  domainInfo: string;
}

export async function deriveHardwareVaultKey({
  credentialId,
  salt,
  domainInfo,
}: PrfDerivationOptions): Promise<CryptoKey> {
  const credential = (await navigator.credentials.get({
    publicKey: {
      challenge: crypto.getRandomValues(new Uint8Array(32)),
      allowCredentials: [{ id: credentialId, type: 'public-key' }],
      userVerification: 'required',
      extensions: {
        prf: {
          eval: { first: salt },
        },
      } as AuthenticationExtensionsClientInputs,
    },
  })) as PublicKeyCredential | null;

  if (!credential) {
    throw new Error('Authentication assertion aborted or rejected.');
  }

  const extensions = credential.getClientExtensionResults() as AuthenticationExtensionsClientOutputs & {
    prf?: { results?: { first: ArrayBuffer } };
  };

  const rawPrfBuffer = extensions.prf?.results?.first;
  if (!rawPrfBuffer) {
    throw new Error('Authenticator did not return PRF output. Hardware key derivation unsupported.');
  }

  const transientPrfBytes = new Uint8Array(rawPrfBuffer);

  try {
    // Import PRF output as IKM (Input Keying Material) into WebCrypto
    const prfMasterKey = await crypto.subtle.importKey(
      'raw',
      transientPrfBytes,
      'HKDF',
      false,
      ['deriveKey']
    );

    // Derive non-extractable AES-GCM encryption key bound to application domain
    return await crypto.subtle.deriveKey(
      {
        name: 'HKDF',
        hash: 'SHA-256',
        salt: salt,
        info: new TextEncoder().encode(domainInfo),
      },
      prfMasterKey,
      { name: 'AES-GCM', length: 256 },
      false, // Invariant: Must be non-extractable
      ['encrypt', 'decrypt']
    );
  } finally {
    // Invariant: Zero intermediate raw PRF memory immediately
    crypto.getRandomValues(transientPrfBytes);
    transientPrfBytes.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 Hardware Key Derivation and Zero-Knowledge Storage Standard

WebAuthn PRF Hardware Key Derivation and Zero-Knowledge Storage Standard defines an industrial-grade behavioral standard for security engineering. Enforces cryptographic invariants when deriving client-side zero-knowledge encryption keys via the WebAuthn PRF (Pseudo-Random Function) extension. Requires non-extractable WebCrypto handles, HKDF domain separation, strict authenticator capability validation, and explicit zeroing of raw PRF output to prevent hardware-backed secrets from leaking to networks or storage. 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, Omitting HKDF Domain Separation, or Allowing Extractable Hardware-Derived Keys 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, Omitting HKDF Domain Separation, or Allowing Extractable Hardware-Derived KeysCritical
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 that 'prf' is supported and enabled in 'credential.getClientExtensionResults().prf' before executing cryptographic operations.

Engineers MUST ALWAYS verify that 'prf' is supported and enabled in 'credential.getClientExtensionResults().prf' before executing cryptographic operations.

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 NEVER transmit the raw PRF evaluation output buffer ('results.first') or derived plaintext keys over network transports, telemetry, or browser storage.

Engineers MUST NEVER transmit the raw PRF evaluation output buffer ('results.first') or derived plaintext keys over network transports, telemetry, or browser storage.

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 MUST ALWAYS feed the raw PRF output into HKDF-SHA256 (RFC 5869) with an explicit, versioned 'info' parameter and domain salt to achieve cryptographic domain separation before creating cipher keys.

Code MUST ALWAYS feed the raw PRF output into HKDF-SHA256 (RFC 5869) with an explicit, versioned 'info' parameter and domain salt to achieve cryptographic domain separation before creating cipher 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.
4

Code MUST ALWAYS import derived symmetric keys (e.g., AES-GCM) with 'extractable

Code MUST ALWAYS import derived symmetric keys (e.g., AES-GCM) with 'extractable: false' into the WebCrypto API subsystem so keys cannot be extracted via memory dumps or XSS injection.

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 fail closed if the hardware authenticator does not report PRF extension support during credential creation, disallowing unencrypted fallback storage without explicit user consent.

Services MUST fail closed if the hardware authenticator does not report PRF extension support during credential creation, disallowing unencrypted fallback storage without explicit user consent.

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 MUST overwrite and zero out transient Uint8Array buffers containing raw PRF evaluations immediately after HKDF derivation using 'crypto.getRandomValues()' or array zeroing.

Components MUST overwrite and zero out transient Uint8Array buffers containing raw PRF evaluations immediately after HKDF derivation using 'crypto.getRandomValues()' or array zeroing.

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 Hardware Key Derivation and Zero-Knowledge Storage Standard critical for AI coding assistants?

Enforces cryptographic invariants when deriving client-side zero-knowledge encryption keys via the WebAuthn PRF (Pseudo-Random Function) extension. Requires non-extractable WebCrypto handles, HKDF domain separation, strict authenticator capability validation, and explicit zeroing of raw PRF output to prevent hardware-backed secrets from leaking to networks or storage. 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, Omitting HKDF Domain Separation, or Allowing Extractable Hardware-Derived Keys) 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