SW: Registering… OPFS: Checking…

Origin Capability Broker · OPFS + Service Worker FetchEvent

Slice Capability Mesh

Problem & Hypothesis: Granting scripts ambient origin storage (localStorage, IndexedDB, or root OPFS) exposes sibling private folders. A Service Worker /cap/<token>/<path> broker keeps storage scoped per task only when untrusted consumers run in opaque origins and OPFS blobs are encrypted per slice behind salted hashed names.

Confirm signal

Opaque <iframe sandbox="allow-scripts"> throws SecurityError on navigator.storage.getDirectory(), page disk enumeration shows only blob-<hash>.enc envelopes, and cross-slice decryption rejects with OperationError.

Falsify signal

Any same-origin script can reconstruct slice contents or enumerate plaintext directory names directly from navigator.storage.getDirectory() without holding the non-extractable slice key.

What to try first

Click Seed OPFS & Mint /workspace Token and Fetch /cap/.../notes.md (200), then run Escape & Write Probes (403) and the Attack Lab below.

3 Things To Try

1. Seed OPFS & Read Allowed Slice

Encrypts private/, workspace/, and shared/ with per-slice AES-256-GCM keys inside opfs://vault/<hash>.enc, mints a read-only token for workspace (5 uses, 300s TTL), and fetches /cap/<token>/notes.md.

2. Attempt Escape & Write Escalation

Probes ../private/payroll.csv traversal and a POST append request against the active read-only token. Both fail closed with 403 and appear in the Wire Audit Log.

3. Revoke Token & Re-Fetch

Marks the active capability token revoked in the Service Worker registry and immediately re-fetches /cap/<token>/notes.md to observe 410 TOKEN_REVOKED.

OPFS Encryption & Opaque Sandbox Attack Lab

Because any script in the same origin can call navigator.storage.getDirectory() directly, this vault adds (1) salted SHA-256 blob filenames + per-slice non-extractable AES-256-GCM encryption inside public/sw.js and (2) opaque-origin isolation (<iframe sandbox="allow-scripts">) so untrusted plugins cannot enumerate OPFS at all.

Vault: AES-256-GCM + Opaque Hash

Raw Disk Enumeration & Cross-Slice Key Proof

Click "Seed OPFS & Mint /workspace Token", then test raw OPFS disk entries or cross-slice decryption mismatch above.

Live Opaque-Origin Plugin (<iframe sandbox="allow-scripts" src="/sandbox-consumer">)

Seeded OPFS Directory Tree

Host-origin storage inspector (navigator.storage.getDirectory())

Select a file above to inspect its OPFS contents
OPFS preview appears here after seeding.

Mint Capability Token

Scope a bearer path prefix, HTTP method mode, use budget, and TTL

Active Capability Tokens

Synchronized with public/sw.js via MessageChannel + OPFS metadata

Token Slice Mode Uses State / TTL Actions

Capability Probe Console

Send real fetch("/cap/...") requests or evaluate directly via cap-policy.js

0 bytes
No probe sent yet /cap/…
Run Step 1 or submit a probe to inspect HTTP headers and OPFS payload.

Code & HTTP Wire Inspector

Edge audit echo idle
1. Live Service Worker FetchEvent Intercepts & Wire Headers
0 audit events
Waiting for capability fetch events on /cap/...
2. Active Policy Code (public/lib/cap-policy.js) & Selected Token Record

Selected Token Record

No token selected.

Shared Pure Policy Module Source

Loading /lib/cap-policy.js…
3. Seeded OPFS Files & Directory Manifest
Snapshot from navigator.storage.getDirectory()
Click "Seed OPFS" to populate directory handles.

1. The Problem

Browser storage APIs such as localStorage, IndexedDB, and root navigator.storage.getDirectory() grant ambient whole-origin authority: any script running in the origin can read or overwrite sibling directories such as private/.

2. The Goal

Replace ambient origin storage access with explicit URL capabilities scoped to one slice (workspace, shared, or private), one method policy (read-only or read-append), an expiration timestamp, and a finite maxUses budget.

3. How It Works

The Service Worker generates per-slice non-extractable AES-256-GCM keys, writes encrypted blobs into opfs://vault/blob-<hash>.enc using salted SHA-256 names, intercepts fetch("/cap/...") locally via cap-policy.js, decrypts only the authorized slice, and emits CAP_AUDIT messages without sending file bytes over the network.

Architecture Browser-local capability mediation & encrypted OPFS vault
Inside Browser Origin · File bytes never leave the device
Caller

Page or Sandbox Frame

fetch("/cap/<tok>/notes.md")
  • Opaque <iframe sandbox="allow-scripts"> has no OPFS API access
  • No direct private/ directory handle or slice key
Local Policy Gate

Service Worker Broker public/sw.js

  1. parseCapabilityUrl() rejects .., %2e%2e, and \
  2. Verify !revoked, now < expiresAt, and uses < maxUses
  3. Check allowedDir segment boundary and HTTP method mode
  4. Decrypt with per-slice AES-256-GCM key and post CAP_AUDIT

Fallback evaluator runs identical cap-policy.js when the Service Worker is inactive.

200 ALLOW

OPFS Vault: workspace/ · shared/

opfs://vault/blob-<hash>.enc
X-Cap-Slice X-Cap-Mode X-Cap-Remaining-Uses
403 / 410 DENY

OPFS Isolated: private/

Separate AES-256-GCM key + salt

Blocked on path traversal, expired or revoked token, or cross-slice key mismatch.

Cloudflare Edge Worker src/worker.ts

Network Edge

Serves static app, /sandbox-consumer, /api/default-files, and optional POST /api/audit-echo. Returns 404 SW_NOT_CONTROLLING if any /cap/* request bypasses the Service Worker.

Capability evaluation and AES-256-GCM encryption run inside the browser origin boundary. File payloads remain in local OPFS storage while optional audit metadata can echo to POST /api/audit-echo.
How This Is Set Up

Capability URL & Encrypted OPFS Vault Wiring

Replacing origin-wide ambient storage globals with capability URLs (/cap/<token>/<path>) mediated locally by a Service Worker over per-slice AES-256-GCM encrypted blobs in opfs://vault/.

Ambient origin storage (over-privileged)
// Ambient whole-origin authority: any same-origin code reads every slice
const payroll = localStorage.getItem("payroll_csv");
const idb = indexedDB.open("app-store", 1);

// Passing OPFS root directory exposes sibling private directories:
const root = await navigator.storage.getDirectory();
const privateDir = await root.getDirectoryHandle("private");
const secretFile = await privateDir.getFileHandle("api-keys.txt");
Scoped capability URL + encrypted vault
// Caller holds only a scoped /cap/<token>/ URL; no OPFS handle exposed
const res = await fetch(`/cap/${sliceToken}/notes.md`, { method: "GET" });
// Headers returned by public/sw.js:
// X-Cap-Decision: ALLOW | DENY
// X-Cap-Slice: workspace
// X-Cap-Remaining-Uses: 4

// Traversal or write escalation returns 403 before decrypting private/:
await fetch(`/cap/${sliceToken}/../private/payroll.csv`, { method: "POST" });
Complete Page Setup: Token Schema, Encrypted OPFS Seeding & Opaque Sandbox

End-to-end wiring from public/index.html, public/lib/cap-policy.js, public/lib/vault-crypto.js, public/app.js, and public/sw.js: the page fetches fixtures from /api/default-files, registers the module Service Worker at /sw.js, syncs capability token records over MessageChannel, and enforces slice bounds locally on every fetch("/cap/...").

<!-- 1. Page HTML Setup (public/index.html) -->
<form id="mint-form">
  <select id="mint-dir" name="allowedDir"><option value="workspace">workspace/</option></select>
  <select id="mint-mode" name="mode"><option value="read-only">read-only</option></select>
  <input id="mint-max-uses" name="maxUses" type="number" value="5">
  <input id="mint-ttl" name="ttlSeconds" type="number" value="300">
</form>
<form id="probe-form"><select id="probe-token"></select><input id="probe-path" value="notes.md"></form>
<script type="module" src="/app.js"></script>

// 2. Concrete Capability Token Record & Policy Constants (public/app.js & public/lib/cap-policy.js)
export const CAPABILITY_MODES = Object.freeze(["read-only", "read-append"]);
export const DEFAULT_SLICES = Object.freeze(["workspace", "shared", "private"]);
export const DEFAULT_MAX_APPEND_BYTES = 4096;
const tokenRecord = {
  id: generateSecureTokenId(),
  label: String(label || "").trim() || `${dirValidation.slice}-${mode}`,
  allowedDir: dirValidation.slice,
  mode: mode === "read-append" ? "read-append" : "read-only",
  createdAt: now,
  expiresAt: now + Math.max(5, Number(ttlSeconds) || 300) * 1000,
  maxUses: Math.max(1, Math.min(100, Math.floor(Number(maxUses) || 5))),
  uses: 0,
  revoked: false,
  maxAppendBytes: Math.max(16, Math.min(65536, Math.floor(Number(maxAppendBytes) || DEFAULT_MAX_APPEND_BYTES))),
};

// 3. Encrypted OPFS Vault Seeding & Opaque Sandbox Wiring (public/app.js, public/sw.js, public/sandbox-consumer.js)
const payload = await (await fetch("/api/default-files")).json();
await navigator.serviceWorker.register("/sw.js", { type: "module", scope: "/" });
// public/sw.js generates non-extractable per-slice AES-256-GCM keys and salted SHA-256 blob IDs:
const blobName = await deriveOpaqueBlobName(sliceSaltHex, file.path); // e.g. "blob-9a4e...enc"
const cipherEnvelope = await encryptSliceBytes(sliceKey, encode(file.content), file.path);
const vaultDir = await (await navigator.storage.getDirectory()).getDirectoryHandle("vault", { create: true });
await writeBytes(vaultDir, blobName, cipherEnvelope); // Zero plaintext dirs or filenames on OPFS disk

// Untrusted UI runs in <iframe sandbox="allow-scripts" src="/sandbox-consumer"> (origin = "null"):
// Calling navigator.storage.getDirectory() inside that frame throws SecurityError;
// Reads cross a transferred MessageChannel port to fetch("/cap/<token>/notes.md") via sw.js.
Core Plumbing Required Today (Service Worker FetchEvent & AES-256-GCM Decryption)
// public/sw.js — FetchEvent intercepts /cap/* locally before hitting origin
self.addEventListener("fetch", (event) => {
  const url = new URL(event.request.url);
  if (url.origin !== self.location.origin || !url.pathname.startsWith("/cap/")) return;
  event.respondWith(handleCapabilityFetch(event.request));
});

// public/sw.js + public/lib/cap-policy.js + public/lib/vault-crypto.js
const parsed = parseCapabilityUrl(request.url);
const decision = evaluateCapabilityRequest({
  tokenRecord, method, relativePath: parsed.relativePath,
  bodyBytes: bodyBytes.byteLength, nowMs: Date.now(),
});
tokenRecord.uses += 1;
await persistRegistryToOpfs();
const sliceCreds = await getOrCreateSliceCreds(decision.allowedDir);
const blobName = await deriveOpaqueBlobName(sliceCreds.saltHex, decision.opfsPath);
const root = await self.navigator.storage.getDirectory();
const vaultDir = await root.getDirectoryHandle(VAULT_DIR_NAME, { create: method === "POST" });
const fileHandle = await vaultDir.getFileHandle(blobName, { create: false });
const envelopeBytes = new Uint8Array(await (await fileHandle.getFile()).arrayBuffer());
const plainBytes = await decryptSliceBytes(sliceCreds.key, envelopeBytes, decision.opfsPath);
What disappears

Direct localStorage, IndexedDB, and root navigator.storage.getDirectory() access inside embedded tasks or untrusted slices.

What becomes explicit

Directory slice bounds (allowedDir), method mode (read-only vs. read-append), finite maxUses budgets, TTLs, and parseCapabilityUrl() traversal guards.

Platform gaps remaining

Same-origin pages share one OPFS root, so hiding paths behind a Service Worker requires origin isolation (opaque <iframe sandbox="allow-scripts">) to block navigator.storage.getDirectory() plus per-slice AES-256-GCM encryption & salted hashed filenames inside opfs://vault/ until browsers ship Service-Worker-private storage buckets.