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.