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

Hardware-Bound Zero-Knowledge Encryption via WebAuthn PRF Extension

Enforces strict cryptographic domain separation and ephemeral memory isolation for symmetric keys derived via the WebAuthn Pseudo-Random Function (PRF) extension. Guarantees that raw PRF outputs and derived symmetric keys remain completely client-side, non-extractable, and hardware-bound without leaking key material or authenticating hashes to remote servers or persistent web storage.

Prohibited Anti-Pattern: Direct Raw PRF Key Ingestion, Extractable CryptoKey Storage, and Server-Side PRF Output Transmission

Export Ready-to-Drop Configuration

Select format below to copy code or download file directly.

---
description: Hardware-Bound Zero-Knowledge Encryption via WebAuthn PRF Extension - Enforces strict cryptographic domain separation and ephemeral memory isolation for symmetric keys derived via the WebAuthn Pseudo-Random Function (PRF) extension. Guarantees that raw PRF outputs and derived symmetric keys remain completely client-side, non-extractable, and hardware-bound without leaking key material or authenticating hashes to remote servers or persistent web storage.
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-hardware-bound-zk-encryption"
---

# Hardware-Bound Zero-Knowledge Encryption via WebAuthn PRF Extension

> **Severity**: CRITICAL | **Category**: security
> **Anti-Pattern Warning**: Direct Raw PRF Key Ingestion, Extractable CryptoKey Storage, and Server-Side PRF Output Transmission

## System Constraints
You are a Principal Security Architect enforcing the WebAuthn PRF Hardware-Derived Zero-Knowledge Encryption Standard. You must reject any implementation that uses raw PRF output directly as a cipher key, persists derived keys to non-volatile client storage, transmits PRF output/derived keys over the network, or imports keys as extractable WebCrypto primitives.

## Strict Guidelines
- Engineers MUST ALWAYS run PRF output through HKDF-SHA256 (RFC 5869) with an explicit, distinct application info/context parameter before using it for symmetric operations.
- Engineers MUST NEVER use raw authenticator PRF outputs directly as an AES-GCM or ChaCha20-Poly1305 encryption key.
- Engineers MUST ALWAYS configure WebCrypto importKey with `extractable: false` when importing derived hardware-bound symmetric keys.
- Code MUST NEVER serialize, log, or persist raw PRF output, intermediate HKDF entropy, or derived plaintext keys to localStorage, sessionStorage, IndexedDB, or server payloads.
- Engineers MUST verify `results.getClientExtensionResults().prf?.enabled` during registration before asserting hardware-bound zero-knowledge capability.
- Services MUST generate cryptographically secure, randomized 32-byte salts per credential context and MUST NEVER share static salts across tenant or user domains.
- Components MUST zero out all intermediate ArrayBuffers and TypedArrays containing raw PRF evaluations immediately after key derivation.

## Bad vs Good Implementations
### Hardware-Bound PRF Symmetric Key Derivation and Zero-Knowledge Payload Decryption

#### Bad Antipattern (AI Common Hallucination)
> **Why it fails**: Directly uses raw PRF output without HKDF domain separation, marks the imported CryptoKey as extractable, stores the raw PRF entropy in localStorage (violating zero-knowledge hardware-binding guarantees), and fails to validate extension capability or zero out memory.
```typescript
import { get } from '@github/webauthn-json';

// ANTI-PATTERN: Direct usage of PRF output, extractable keys, and localStorage storage
export async function decryptUserDataBad(credentialId: string, salt: Uint8Array, encryptedPayload: ArrayBuffer) {
  const credential = await navigator.credentials.get({
    publicKey: {
      challenge: new Uint8Array(32),
      allowCredentials: [{ id: Uint8Array.from(atob(credentialId), c => c.charCodeAt(0)), type: 'public-key' }],
      extensions: {
        prf: {
          eval: { first: salt }
        }
      }
    }
  }) as PublicKeyCredential;

  const extensionResults = credential.getClientExtensionResults();
  // CRITICAL: Typecast without validation and directly using raw PRF output as AES key
  const rawPrf = (extensionResults as any).prf.results.first as ArrayBuffer;

  // VULNERABILITY: Extractable set to true, risking memory exfiltration
  const key = await crypto.subtle.importKey(
    'raw',
    rawPrf,
    { name: 'AES-GCM' },
    true,
    ['decrypt']
  );

  // VULNERABILITY: Storing raw key material in persistent local storage
  localStorage.setItem('cached_derived_key', btoa(String.fromCharCode(...new Uint8Array(rawPrf))));

  return crypto.subtle.decrypt(
    { name: 'AES-GCM', iv: new Uint8Array(12) },
    key,
    encryptedPayload
  );
}
```

#### Production Standard (Correct)
> **Standard**: Validates PRF support, binds authentication to user verification, subjects raw PRF entropy to HKDF-SHA256 with an explicit domain separation context, imports and derives strictly non-extractable CryptoKeys (`extractable: false`), and securely wipes sensitive intermediate byte arrays from memory.
```typescript
export interface HardwareDerivedKeyResult {
  key: CryptoKey;
}

export async function deriveHardwareBoundKey(
  credentialId: Uint8Array,
  salt: Uint8Array,
  infoContext: string
): Promise<CryptoKey> {
  if (salt.byteLength !== 32) {
    throw new Error('PRF salt must be strictly 32 bytes.');
  }

  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
          }
        }
      }
    }
  });

  if (!(credential instanceof PublicKeyCredential)) {
    throw new Error('Credential retrieval failed or returned unexpected type.');
  }

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

  if (!prfResult || !(prfResult instanceof ArrayBuffer)) {
    throw new Error('Authenticator did not return a valid PRF evaluation result.');
  }

  let rawPrfView: Uint8Array | null = new Uint8Array(prfResult);
  let initialKeyMaterial: CryptoKey | null = null;

  try {
    // Import raw PRF output as HKDF key material
    initialKeyMaterial = await crypto.subtle.importKey(
      'raw',
      rawPrfView,
      'HKDF',
      false,
      ['deriveKey']
    );

    const infoBuffer = new TextEncoder().encode(infoContext);

    // Derive an unextractable symmetric AES-GCM-256 key with cryptographic domain separation
    return await crypto.subtle.deriveKey(
      {
        name: 'HKDF',
        hash: 'SHA-256',
        salt: salt,
        info: infoBuffer
      },
      initialKeyMaterial,
      {
        name: 'AES-GCM',
        length: 256
      },
      false, // Strictly non-extractable
      ['encrypt', 'decrypt']
    );
  } finally {
    // Wipe transient buffers immediately to maintain memory-bound zero-knowledge
    if (rawPrfView) {
      rawPrfView.fill(0);
      rawPrfView = null;
    }
  }
}
```

Architectural Specification & Invariant Rationale

Architectural Invariant Design: Hardware-Bound Zero-Knowledge Encryption via WebAuthn PRF Extension

Hardware-Bound Zero-Knowledge Encryption via WebAuthn PRF Extension defines an industrial-grade behavioral standard for security engineering. Enforces strict cryptographic domain separation and ephemeral memory isolation for symmetric keys derived via the WebAuthn Pseudo-Random Function (PRF) extension. Guarantees that raw PRF outputs and derived symmetric keys remain completely client-side, non-extractable, and hardware-bound without leaking key material or authenticating hashes to remote servers or persistent web 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: Direct Raw PRF Key Ingestion, Extractable CryptoKey Storage, and Server-Side PRF Output Transmission 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 DriftDirect Raw PRF Key Ingestion, Extractable CryptoKey Storage, and Server-Side PRF Output TransmissionCritical
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 run PRF output through HKDF-SHA256 (RFC 5869) with an explicit, distinct application info/context parameter before using it for symmetric operations.

Engineers MUST ALWAYS run PRF output through HKDF-SHA256 (RFC 5869) with an explicit, distinct application info/context parameter before using it for symmetric 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 use raw authenticator PRF outputs directly as an AES-GCM or ChaCha20-Poly1305 encryption key.

Engineers MUST NEVER use raw authenticator PRF outputs directly as an AES-GCM or ChaCha20-Poly1305 encryption key.

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 configure WebCrypto importKey with `extractable

Engineers MUST ALWAYS configure WebCrypto importKey with `extractable: false` when importing derived hardware-bound symmetric 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 NEVER serialize, log, or persist raw PRF output, intermediate HKDF entropy, or derived plaintext keys to localStorage, sessionStorage, IndexedDB, or server payloads.

Code MUST NEVER serialize, log, or persist raw PRF output, intermediate HKDF entropy, or derived plaintext keys to localStorage, sessionStorage, IndexedDB, or server 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.
5

Engineers MUST verify `results.getClientExtensionResults().prf?.enabled` during registration before asserting hardware-bound zero-knowledge capability.

Engineers MUST verify `results.getClientExtensionResults().prf?.enabled` during registration before asserting hardware-bound zero-knowledge capability.

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 generate cryptographically secure, randomized 32-byte salts per credential context and MUST NEVER share static salts across tenant or user domains.

Services MUST generate cryptographically secure, randomized 32-byte salts per credential context and MUST NEVER share static salts across tenant or user domains.

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

Components MUST zero out all intermediate ArrayBuffers and TypedArrays containing raw PRF evaluations immediately after key derivation.

Components MUST zero out all intermediate ArrayBuffers and TypedArrays containing raw PRF evaluations immediately after key derivation.

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 Hardware-Bound Zero-Knowledge Encryption via WebAuthn PRF Extension critical for AI coding assistants?

Enforces strict cryptographic domain separation and ephemeral memory isolation for symmetric keys derived via the WebAuthn Pseudo-Random Function (PRF) extension. Guarantees that raw PRF outputs and derived symmetric keys remain completely client-side, non-extractable, and hardware-bound without leaking key material or authenticating hashes to remote servers or persistent web 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 (Direct Raw PRF Key Ingestion, Extractable CryptoKey Storage, and Server-Side PRF Output Transmission) 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

Hardware-Bound