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-enclave-standard

WebAuthn PRF Zero-Knowledge Key Derivation & Enclave Isolation Standard

Enforces hardware-bound client-side symmetric key derivation via the WebAuthn Pseudo-Random Function (PRF) extension for end-to-end encrypted vaults. Guarantees that derived cryptographic secrets and PRF outputs never leave the client enclave, remain non-extractable within the Web Cryptography API, and are never transmitted to application servers or persisted to unencrypted client storage.

Prohibited Anti-Pattern: Leaking PRF outputs to application backends or persisting derived master keys in extractable client storage

Export Ready-to-Drop Configuration

Select format below to copy code or download file directly.

---
description: WebAuthn PRF Zero-Knowledge Key Derivation & Enclave Isolation Standard - Enforces hardware-bound client-side symmetric key derivation via the WebAuthn Pseudo-Random Function (PRF) extension for end-to-end encrypted vaults. Guarantees that derived cryptographic secrets and PRF outputs never leave the client enclave, remain non-extractable within the Web Cryptography API, and are never transmitted to application servers or persisted to unencrypted client storage.
globs: src/**/*.{ts,tsx,js,jsx}, lib/**/*.{ts,tsx,js,jsx}
alwaysApply: true
verified_by: "agentrules.org"
license: "CC-BY-4.0"
source: "https://agentrules.org/rules/webauthn-prf-zk-key-derivation-enclave-standard"
---

# WebAuthn PRF Zero-Knowledge Key Derivation & Enclave Isolation Standard

> **Severity**: CRITICAL | **Category**: security
> **Anti-Pattern Warning**: Leaking PRF outputs to application backends or persisting derived master keys in extractable client storage

## System Constraints
You are a Principal Security Architect enforcing the WebAuthn PRF Zero-Knowledge Key Derivation & Enclave Isolation Standard. Mandate that all client-side encryption flows utilizing the WebAuthn PRF extension import outputs directly into non-extractable WebCrypto keys, derive subkeys via HKDF with domain separation, immediately zero transient memory buffers, and strictly prohibit transmitting raw PRF outputs, derived symmetric keys, or plaintext vault content to remote services.

## Strict Guidelines
- Engineers MUST ALWAYS verify client support for WebAuthn PRF via `PublicKeyCredential.isUserVerifyingPlatformAuthenticatorAvailable()` and the `getClientExtensionResults().prf` return shape prior to invoking cryptographic workflows.
- Engineers MUST ALWAYS import the PRF output buffer into `crypto.subtle.importKey` with `extractable: false` using HKDF-SHA256 to ensure secrets cannot be accessed by third-party scripts or DOM injection.
- Engineers MUST ALWAYS use distinct, domain-separated HKDF salt and info parameters (e.g., separate keys for vault encryption vs. vault integrity validation).
- Engineers MUST ALWAYS wipe transient typed array memory (`buffer.fill(0)`) containing the raw PRF output immediately after importing into WebCrypto.
- Engineers MUST NOT transmit the raw PRF evaluation result (`first` or `second` bytes) or derived symmetric vault keys across the network to any server under any circumstance.
- Engineers MUST NOT store raw derived keys, intermediate PRF buffers, or unencrypted secrets in `localStorage`, `sessionStorage`, `IndexedDB`, or client-side application state stores (e.g., Redux, Zustand).
- Services MUST only receive and store zero-knowledge cryptographic primitives: the public salt, credential ID, initialization vectors (IVs), and ciphertext.

## Bad vs Good Implementations
### Hardware-Bound PRF Key Derivation and Zero-Memory Enclave Import

#### Bad Antipattern (AI Common Hallucination)
> **Why it fails**: The anti-pattern transmits the raw hardware PRF output to the application server (destroying zero-knowledge architecture) and saves the unencrypted raw key to localStorage where it is vulnerable to cross-site scripting (XSS) and client-side extraction.
```typescript
// BAD: Transmitting PRF raw output to backend and storing extractable symmetric keys
export async function unlockVaultBad(credentialId: Uint8Array, salt: Uint8Array) {
  const credential = (await navigator.credentials.get({
    publicKey: {
      challenge: new Uint8Array(32),
      allowCredentials: [{ id: credentialId, type: 'public-key' }],
      extensions: {
        prf: { eval: { first: salt } }
      }
    }
  })) as PublicKeyCredential;

  const extensionResults = credential.getClientExtensionResults() as any;
  const prfOutput = new Uint8Array(extensionResults.prf.results.first);

  // CRITICAL VULNERABILITY: Leaking PRF output to server and exposing to local storage
  await fetch('/api/vault/session', {
    method: 'POST',
    body: JSON.stringify({ prfKey: Array.from(prfOutput) })
  });

  localStorage.setItem('raw_vault_key', JSON.stringify(Array.from(prfOutput)));
  return prfOutput;
}
```

#### Production Standard (Correct)
> **Standard**: The hardened implementation forces user verification, validates the PRF extension result, imports the output as an unextractable HKDF key directly in WebCrypto, uses domain-separated context derivation for AES-GCM-256, and ensures the intermediate raw PRF buffer is securely scrubbed via fill(0).
```typescript
// GOOD: Hardware-bound derivation, non-extractable WebCrypto key, explicit memory clearing
export async function deriveVaultEncryptionKey(
  credentialId: Uint8Array,
  salt: Uint8Array,
  domainContext: string
): 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 PublicKeyCredential | null;

  if (!credential) {
    throw new Error('WebAuthn credential assertion failed');
  }

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

  if (!prfResult) {
    throw new Error('Authenticator did not return a valid PRF extension evaluation');
  }

  const rawPrfBuffer = new Uint8Array(prfResult);

  try {
    // Import PRF output directly as a non-extractable HKDF master secret
    const hkdfMasterKey = await crypto.subtle.importKey(
      'raw',
      rawPrfBuffer,
      { name: 'HKDF' },
      false, // non-extractable
      ['deriveKey']
    );

    // Derive dedicated AES-GCM-256 vault key with cryptographically separated info context
    const vaultKey = await crypto.subtle.deriveKey(
      {
        name: 'HKDF',
        hash: 'SHA-256',
        salt: salt,
        info: new TextEncoder().encode(`e2ee-vault:${domainContext}`)
      },
      hkdfMasterKey,
      { name: 'AES-GCM', length: 256 },
      false, // non-extractable
      ['encrypt', 'decrypt']
    );

    return vaultKey;
  } finally {
    // Guarantee transient PRF raw buffer is scrubbed from memory immediately
    rawPrfBuffer.fill(0);
  }
}
```

Architectural Specification & Invariant Rationale

Architectural Invariant Design: WebAuthn PRF Zero-Knowledge Key Derivation & Enclave Isolation Standard

WebAuthn PRF Zero-Knowledge Key Derivation & Enclave Isolation Standard defines an industrial-grade behavioral standard for security engineering. Enforces hardware-bound client-side symmetric key derivation via the WebAuthn Pseudo-Random Function (PRF) extension for end-to-end encrypted vaults. Guarantees that derived cryptographic secrets and PRF outputs never leave the client enclave, remain non-extractable within the Web Cryptography API, and are never transmitted to application servers or persisted to unencrypted client 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: Leaking PRF outputs to application backends or persisting derived master keys in extractable client 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 DriftLeaking PRF outputs to application backends or persisting derived master keys in extractable client 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 verify client support for WebAuthn PRF via `PublicKeyCredential.isUserVerifyingPlatformAuthenticatorAvailable()` and the `getClientExtensionResults().prf` return shape prior to invoking cryptographic workflows.

Engineers MUST ALWAYS verify client support for WebAuthn PRF via `PublicKeyCredential.isUserVerifyingPlatformAuthenticatorAvailable()` and the `getClientExtensionResults().prf` return shape prior to invoking cryptographic workflows.

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 import the PRF output buffer into `crypto.subtle.importKey` with `extractable

Engineers MUST ALWAYS import the PRF output buffer into `crypto.subtle.importKey` with `extractable: false` using HKDF-SHA256 to ensure secrets cannot be accessed by third-party scripts or DOM 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.
3

Engineers MUST ALWAYS use distinct, domain-separated HKDF salt and info parameters (e.g., separate keys for vault encryption vs. vault integrity validation).

Engineers MUST ALWAYS use distinct, domain-separated HKDF salt and info parameters (e.g., separate keys for vault encryption vs. vault integrity validation).

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 ALWAYS wipe transient typed array memory (`buffer.fill(0)`) containing the raw PRF output immediately after importing into WebCrypto.

Engineers MUST ALWAYS wipe transient typed array memory (`buffer.fill(0)`) containing the raw PRF output immediately after importing into WebCrypto.

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

Engineers MUST NOT transmit the raw PRF evaluation result (`first` or `second` bytes) or derived symmetric vault keys across the network to any server under any circumstance.

Engineers MUST NOT transmit the raw PRF evaluation result (`first` or `second` bytes) or derived symmetric vault keys across the network to any server under any circumstance.

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 NOT store raw derived keys, intermediate PRF buffers, or unencrypted secrets in `localStorage`, `sessionStorage`, `IndexedDB`, or client-side application state stores (e.g., Redux, Zustand).

Engineers MUST NOT store raw derived keys, intermediate PRF buffers, or unencrypted secrets in `localStorage`, `sessionStorage`, `IndexedDB`, or client-side application state stores (e.g., Redux, Zustand).

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.
7

Services MUST only receive and store zero-knowledge cryptographic primitives

Services MUST only receive and store zero-knowledge cryptographic primitives: the public salt, credential ID, initialization vectors (IVs), and ciphertext.

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 Zero-Knowledge Key Derivation & Enclave Isolation Standard critical for AI coding assistants?

Enforces hardware-bound client-side symmetric key derivation via the WebAuthn Pseudo-Random Function (PRF) extension for end-to-end encrypted vaults. Guarantees that derived cryptographic secrets and PRF outputs never leave the client enclave, remain non-extractable within the Web Cryptography API, and are never transmitted to application servers or persisted to unencrypted client 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 (Leaking PRF outputs to application backends or persisting derived master keys in extractable client 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