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

WebAuthn FIDO2 LargeBlob Secure Enclave Storage & Sync Invariant

Enforces client-side envelope encryption, cryptographic origin/credential-binding in Additional Authenticated Data (AAD), and monotonic sequence vectoring for WebAuthn largeBlob operations. Prevents cross-device synchronization race conditions, split-brain forks, and cleartext credential extraction across passkey cloud sync fabrics.

Prohibited Anti-Pattern: Unencrypted LargeBlob Writes with Blind State Overwriting in Synced Authenticators

Export Ready-to-Drop Configuration

Select format below to copy code or download file directly.

---
description: WebAuthn FIDO2 LargeBlob Secure Enclave Storage & Sync Invariant - Enforces client-side envelope encryption, cryptographic origin/credential-binding in Additional Authenticated Data (AAD), and monotonic sequence vectoring for WebAuthn largeBlob operations. Prevents cross-device synchronization race conditions, split-brain forks, and cleartext credential extraction across passkey cloud sync fabrics.
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-largeblob-enclave-storage-invariant"
---

# WebAuthn FIDO2 LargeBlob Secure Enclave Storage & Sync Invariant

> **Severity**: CRITICAL | **Category**: security
> **Anti-Pattern Warning**: Unencrypted LargeBlob Writes with Blind State Overwriting in Synced Authenticators

## System Constraints
You are a Principal Cryptographic & Systems Architect enforcing strict security invariants on WebAuthn FIDO2 LargeBlob storage. You must reject any direct persistence of unencrypted payloads, blind writes without optimistic concurrency/version checks, or payloads lacking credential/origin-bound authenticated data (AAD). Synced passkeys replicate asynchronously; all state operations must be tamper-proof, crash-safe, and race-resistant.

## Strict Guidelines
- Engineers MUST ALWAYS encrypt `largeBlob` data using client-side authenticated encryption (AES-256-GCM) with keys derived from WebAuthn PRF (Pseudo-Random Function) or enclave-isolated HKDF.
- Engineers MUST ALWAYS bind the Credential ID, Relying Party ID, and exact client origin into the AEAD Additional Authenticated Data (AAD) to prevent cross-credential/cross-origin ciphertext transposition.
- Engineers MUST ALWAYS include a monotonic sequence counter and parent commit SHA-256 digest inside the encrypted envelope to detect and reject multi-device synchronization race conditions.
- Engineers MUST NOT execute blind writes via `largeBlob: { write: ... }`; all updates MUST follow a read-modify-write workflow validating the previous state digest.
- Code SHOULD zeroize ephemeral keying buffers, plaintext buffers, and intermediate derivation arrays via Uint8Array.prototype.fill(0) immediately after cryptographic serialization.
- Services MUST gracefully isolate LargeBlob sync conflicts by surfacing retry workflows using fresh authenticator reads rather than silently overwriting divergent remote states.

## Bad vs Good Implementations
### WebAuthn LargeBlob Read-Modify-Write with PRF AEAD Envelope and Concurrency Check

#### Bad Antipattern (AI Common Hallucination)
> **Why it fails**: Writing unencrypted JSON to largeBlob exposes secrets to any compromised cloud-sync transport or local authenticator logs. Performing a blind write without reading the existing generation counter causes silent data loss during multi-device synchronization races.
```typescript
import { base64url } from 'rfc4648';

// ANTI-PATTERN: Unencrypted largeBlob storage with blind overwrite
export async function updateVaultSecret(credentialId: Uint8Array, secretData: Record<string, unknown>): Promise<void> {
  const encoder = new TextEncoder();
  // Storing plaintext into largeBlob exposes data to synced cloud fabric / OS passkey monitors
  const rawPayload = encoder.encode(JSON.stringify(secretData));

  await navigator.credentials.get({
    publicKey: {
      challenge: crypto.getRandomValues(new Uint8Array(32)),
      allowCredentials: [{ id: credentialId, type: 'public-key' }],
      extensions: {
        largeBlob: {
          // Blind write causes lost updates across concurrent synced passkey devices
          write: rawPayload.buffer,
        },
      },
    },
  });
}
```

#### Production Standard (Correct)
> **Standard**: Enforces an optimistic concurrency check via monotonic sequence numbers and SHA-256 parent digests. The payload is encrypted with AES-256-GCM derived via WebAuthn PRF keys and bound to origin and credentialId via AAD, completely preventing ciphertext splicing, sync clobbering, and side-channel cloud extraction.
```typescript
interface EnclaveEnvelope {
  version: number;
  sequence: number;
  parentDigest: string; // Hex SHA-256 of previous blob
  iv: string;
  ciphertext: string;
}

export async function updateVaultSecretSecure(
  credentialId: Uint8Array,
  rpId: string,
  origin: string,
  derivedPrfKey: CryptoKey,
  mutator: (current: Uint8Array | null) => Uint8Array
): Promise<void> {
  // 1. Read existing blob state to prevent race conditions
  const readAssertion = (await navigator.credentials.get({
    publicKey: {
      challenge: crypto.getRandomValues(new Uint8Array(32)),
      allowCredentials: [{ id: credentialId, type: 'public-key' }],
      extensions: { largeBlob: { read: true } },
    },
  })) as PublicKeyCredential & { getClientExtensionResults: () => { largeBlob?: { blob?: ArrayBuffer } } };

  const existingBuffer = readAssertion.getClientExtensionResults().largeBlob?.blob;
  let currentSequence = 0;
  let parentDigestHex = '0'.repeat(64);
  let currentPlaintext: Uint8Array | null = null;

  // AAD binds the ciphertext strictly to this credential and execution context
  const aad = new TextEncoder().encode(`${rpId}|${origin}|${Array.from(credentialId).join(',')}`);

  if (existingBuffer && existingBuffer.byteLength > 0) {
    const parentHash = await crypto.subtle.digest('SHA-256', existingBuffer);
    parentDigestHex = Array.from(new Uint8Array(parentHash)).map(b => b.toString(16).padStart(2, '0')).join('');
    const envelope: EnclaveEnvelope = JSON.parse(new TextDecoder().decode(existingBuffer));
    
    currentSequence = envelope.sequence;
    const iv = Uint8Array.from(atob(envelope.iv), c => c.charCodeAt(0));
    const ct = Uint8Array.from(atob(envelope.ciphertext), c => c.charCodeAt(0));

    const decrypted = await crypto.subtle.decrypt({ name: 'AES-GCM', iv, additionalData: aad }, derivedPrfKey, ct);
    currentPlaintext = new Uint8Array(decrypted);
  }

  // 2. Compute mutation and increment sequence monotonically
  const nextPlaintext = mutator(currentPlaintext);
  const nextIv = crypto.getRandomValues(new Uint8Array(12));
  const nextCiphertext = await crypto.subtle.encrypt(
    { name: 'AES-GCM', iv: nextIv, additionalData: aad },
    derivedPrfKey,
    nextPlaintext
  );

  const nextEnvelope: EnclaveEnvelope = {
    version: 1,
    sequence: currentSequence + 1,
    parentDigest: parentDigestHex,
    iv: btoa(String.fromCharCode(...nextIv)),
    ciphertext: btoa(String.fromCharCode(...new Uint8Array(nextCiphertext))),
  };

  const nextBlob = new TextEncoder().encode(JSON.stringify(nextEnvelope));

  // 3. Atomically write the validated envelope
  await navigator.credentials.get({
    publicKey: {
      challenge: crypto.getRandomValues(new Uint8Array(32)),
      allowCredentials: [{ id: credentialId, type: 'public-key' }],
      extensions: { largeBlob: { write: nextBlob.buffer } },
    },
  });

  // Secure memory wipe of plaintexts
  nextPlaintext.fill(0);
  if (currentPlaintext) currentPlaintext.fill(0);
}
```

Architectural Specification & Invariant Rationale

Architectural Invariant Design: WebAuthn FIDO2 LargeBlob Secure Enclave Storage & Sync Invariant

WebAuthn FIDO2 LargeBlob Secure Enclave Storage & Sync Invariant defines an industrial-grade behavioral standard for security engineering. Enforces client-side envelope encryption, cryptographic origin/credential-binding in Additional Authenticated Data (AAD), and monotonic sequence vectoring for WebAuthn largeBlob operations. Prevents cross-device synchronization race conditions, split-brain forks, and cleartext credential extraction across passkey cloud sync fabrics. 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: Unencrypted LargeBlob Writes with Blind State Overwriting in Synced Authenticators 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 DriftUnencrypted LargeBlob Writes with Blind State Overwriting in Synced AuthenticatorsCritical
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 encrypt `largeBlob` data using client-side authenticated encryption (AES-256-GCM) with keys derived from WebAuthn PRF (Pseudo-Random Function) or enclave-isolated HKDF.

Engineers MUST ALWAYS encrypt `largeBlob` data using client-side authenticated encryption (AES-256-GCM) with keys derived from WebAuthn PRF (Pseudo-Random Function) or enclave-isolated HKDF.

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 bind the Credential ID, Relying Party ID, and exact client origin into the AEAD Additional Authenticated Data (AAD) to prevent cross-credential/cross-origin ciphertext transposition.

Engineers MUST ALWAYS bind the Credential ID, Relying Party ID, and exact client origin into the AEAD Additional Authenticated Data (AAD) to prevent cross-credential/cross-origin ciphertext transposition.

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 include a monotonic sequence counter and parent commit SHA-256 digest inside the encrypted envelope to detect and reject multi-device synchronization race conditions.

Engineers MUST ALWAYS include a monotonic sequence counter and parent commit SHA-256 digest inside the encrypted envelope to detect and reject multi-device synchronization race conditions.

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 execute blind writes via `largeBlob

Engineers MUST NOT execute blind writes via `largeBlob: { write: ... }`; all updates MUST follow a read-modify-write workflow validating the previous state digest.

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 SHOULD zeroize ephemeral keying buffers, plaintext buffers, and intermediate derivation arrays via Uint8Array.prototype.fill(0) immediately after cryptographic serialization.

Code SHOULD zeroize ephemeral keying buffers, plaintext buffers, and intermediate derivation arrays via Uint8Array.prototype.fill(0) immediately after cryptographic serialization.

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 gracefully isolate LargeBlob sync conflicts by surfacing retry workflows using fresh authenticator reads rather than silently overwriting divergent remote states.

Services MUST gracefully isolate LargeBlob sync conflicts by surfacing retry workflows using fresh authenticator reads rather than silently overwriting divergent remote states.

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 FIDO2 LargeBlob Secure Enclave Storage & Sync Invariant critical for AI coding assistants?

Enforces client-side envelope encryption, cryptographic origin/credential-binding in Additional Authenticated Data (AAD), and monotonic sequence vectoring for WebAuthn largeBlob operations. Prevents cross-device synchronization race conditions, split-brain forks, and cleartext credential extraction across passkey cloud sync fabrics. 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 (Unencrypted LargeBlob Writes with Blind State Overwriting in Synced Authenticators) 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