diff --git a/docs/dev/shell.md b/docs/dev/shell.md index b7f3407e5..51f1a819f 100644 --- a/docs/dev/shell.md +++ b/docs/dev/shell.md @@ -236,8 +236,9 @@ disk (ruling 91, H16) is not built. so on the session, and `EROFS` or a read-only mount means no folder. The record is the name the host answered with: on the saved row (`StoredSessionRow.folder`), or in `chrome.storage.session` (`ml_session_folder:`) for an unsaved session, so an eviction does not make a second folder. Never on `SessionSummary`. `startedBy` is required: - anything but `"person"` (sw-runs.ts `runStartedBy`: a run the worker minted, never handed over from a page) mounts - nothing and reads no record. Nothing calls it yet. + anything but `"person"` (sw-runs.ts `runStartedBy`: the run payload's `startedBy`, written once where the worker + minted the id and kept as stored through a resume, a hand-over and a restore) mounts nothing and reads no record. A + run stored before `startedBy` existed reads `"page"`. Nothing calls it yet. - `stat` gives the facts and a `basis`. `judgeMount(op, facts, to?)` takes every row of the table that applies, and the most restrictive wins, refused over asks over free. Inside the uploads folder but outside `attached/`, the uploads row stands in for the git rows: the folder is ignored by design, so `gitUndoable` would always be false there. A diff --git a/docs/dev/state.md b/docs/dev/state.md index e9a476f41..8db8b6a56 100644 --- a/docs/dev/state.md +++ b/docs/dev/state.md @@ -54,6 +54,7 @@ page-hosted one. Several stores exist once per host. | The run's current tab and URL | `activeRuns`, `tabPageUrl` | `ml_pinned_tabs` (pinned tabs only) | `run` | | Interrupted / auto-resumed | `hydratedRuns`, `resurrectedRuns` | derived from `ml_bgrun_*` | `run` | | The note a resume with no tab last gave the model (`noTabTold`), so a later one that reads the same is not given after each eviction | `bgRuns[runId].p.noTabTold` (set by `resumeDetached`, `sw-sessions.ts`; removed by every way onto a tab, `offNoTab`, `no-tab.ts`) | with the payload: `ml_bgrun_` while live, the session store's `runmeta` if saved | `run.noTabTold` | +| Who started the run (`startedBy: "person"`), what `runStartedBy` reads and a session's own folder is gated on | `bgRuns[runId].p.startedBy`, written once where the worker mints the id (`startMinted`, `sw-run-start.ts`); never by a hand-over, a resume, an adoption or a restore, and stripped from a page's START_RUN (`PAGE_STRIPPED_KEYS`). Not `builtBy` (a hand-over rewrites it) and not the hand-over list (a resume adds to it, and an entry can be lost) | with the payload: `ml_bgrun_` while live, the session store's `runmeta` if saved, and an archive's copy of it. Lost with the payload: an unsaved run's snapshot when it settles. A payload stored before the field existed has none and reads `"page"`; nothing infers it. A row a backup or the archive folder restores is read as stored, the person's own file | `run.started-by` | | Delegated sub-call spend | `subTally` / `bgRuns.sub`; page: `subUsage` (`bus.ts`); a worker-built run's worker tools: `runs[runId].spent` (`worker-tools.ts`), reported per call as the envelope's `subUsage` | in `history.sub` if saved | `run` (the model sees it via `chat_metadata`) | | What a worker-built run's worker-side `fetch_url` and `python_exec` were approved for (URL consent, one-time as-you reads, the running call's sheets and code outside the Python dialect) | `runs[runId].consented`, `.credOnce`, `.pyCall` (`worker-tools.ts`, worker memory); never the tab's | no; lost on an eviction, and a call then asks again | maybe | | What a worker-built run's `fetch_url` read (the read-only survey's free re-reads) | `runs[runId].cache` (`worker-tools.ts`, worker memory, frozen copies); page-hosted and approved exec: `mlFetchCache` (`injected.ts`, page) | no; the worker's goes with an eviction (a re-read then asks again) | maybe | diff --git a/docs/spec/FILE_ATTACHMENTS.md b/docs/spec/FILE_ATTACHMENTS.md index c596772c2..b561c9fed 100644 --- a/docs/spec/FILE_ATTACHMENTS.md +++ b/docs/spec/FILE_ATTACHMENTS.md @@ -1489,9 +1489,13 @@ coordinator the same day. the folder's name beside it. - The record is keyed by the session id, and a page can name an id, so `mountForSession` mounts only for a run the worker started for the person, never for a page-started run or an id a page supplied (the coordinator, - 2026-11-29; the run's `startedBy` is required, read from the worker's own facts, `runStartedBy`). A chat session - has no folder: a worker chat has one tool (`read_pages`), no `ml.sh` and no cell, so nothing in it reads a folder on - disk, and `runStartedBy` reads it as `"page"`. + 2026-11-29; the run's `startedBy` is required, read from the worker's own facts, `runStartedBy`). The fact is the + run payload's `startedBy`, written once where the worker mints the id and never by a resume, a hand-over or a + restore; a run stored before it existed reads `"page"` and gets no folder (the coordinator, 2026-11-30). A stated + limit: a row a backup or the archive folder brings back is read by its stored payload, so a file whose row says + `"person"` gets a folder; the file is the person's own, and restoring it is the person's act. A chat + session has no folder: a worker chat has one tool (`read_pages`), no `ml.sh` and no cell, so nothing in it reads a + folder on disk, and `runStartedBy` reads it as `"page"`. - A collision, a directory of that name that the session's record does not name (another session whose id shares six characters, or one the person made): the new folder takes the next free suffix, `-2`, `-3`, up to `-20`, and records the name the host made. Past `-20` the mount fails: `No free folder name for this session under diff --git a/src/background.ts b/src/background.ts index dd2b94363..c9cd8c8fe 100644 --- a/src/background.ts +++ b/src/background.ts @@ -53,7 +53,7 @@ import { librariesReady, removeLibrary, storedLibraries } from "./sw/sw-librarie import { checkDraft } from "./sw/sw-manifest-proposal"; import { bringableSessions, bringHere } from "./sw/bring-here"; -import { isWorkerRun, withoutWorkerSession, makeWorkerRun, dropHandedMemoryForTest, runControllers, runInboxes, bgRuns, activeRuns, runRebuilds, runReplayBuffer, replayedTo, hydratedRuns, resurrectedRuns, readoptPageInfo, hydratePersistedRuns, navBarrier, pageValueSession, hydrationDone, purgeAllBgRuns, bufferReplay, derefByRun, contextByRun, turnByRun, workerRunsStarting, execReads, deleteRun, releaseSessionTokens, tabPageUrl, switchRunModel, forgetRunModel, retabRuns, detachTabRuns, runHasNoTab, senderOwnsRun, reconcileTabPins, startingControllers, abortStart, startingOwnedBy } from "./sw/sw-runs"; +import { isWorkerRun, withoutWorkerSession, makeWorkerRun, runStartedBy, dropHandedMemoryForTest, runControllers, runInboxes, bgRuns, activeRuns, runRebuilds, runReplayBuffer, replayedTo, hydratedRuns, resurrectedRuns, readoptPageInfo, hydratePersistedRuns, navBarrier, pageValueSession, hydrationDone, purgeAllBgRuns, bufferReplay, derefByRun, contextByRun, turnByRun, workerRunsStarting, execReads, deleteRun, releaseSessionTokens, tabPageUrl, switchRunModel, forgetRunModel, retabRuns, detachTabRuns, runHasNoTab, senderOwnsRun, reconcileTabPins, startingControllers, abortStart, startingOwnedBy } from "./sw/sw-runs"; import { cancelPageTasks, detachTask, dropAllTaskMemory, resetTaskChain, taskAction, type TaskOutcome } from "./sw/sw-tasks"; import { refreshTaskRow, setNoTabReader, setReleaseAtReader, syncTaskRows } from "./sw/sw-task-rows"; import { onTabClosed, releaseAtOf, restoreReleases } from "./sw/sw-release"; @@ -170,6 +170,10 @@ startValueSweeps(liveHeldSessions); // its first pass releases held rows no se replayTabs: [...runReplayBuffer.keys()], deref: [...derefByRun.keys()], context: [...contextByRun.keys()], turns: [...turnByRun.keys()], starting: [...new Set([...workerRunsStarting, ...startingControllers.keys()])], sessions: sessionServer.index.list().map((s) => s.id.hash), }); +// TEST-ONLY (SW realm only, like the ones above): the worker's own answer to who started a run (`runStartedBy`), so a +// red-team row can ask it after a REAL flow — a start, a hand-over, an eviction, a resume — with no message type that +// would give a page the same answer (tests/redteam-run-origin.test.mjs). +(globalThis as unknown as { __mlRunStartedByForTest?: unknown }).__mlRunStartedByForTest = (runId: string) => runStartedBy(runId); // TEST-ONLY (SW realm only): the payloads a run's next message is recorded on (the live turn's and the stored one), as // the files' ids and the message count each carries (tests/task-starts-turn.test.mjs: a message taken back leaves neither). (globalThis as unknown as { __mlRunPayloadsForTest?: unknown }).__mlRunPayloadsForTest = (hash: string): Array<{ files: string[]; sends: number | undefined }> => diff --git a/src/contract/contract-messages.ts b/src/contract/contract-messages.ts index d4408b0fa..7f46f7fbf 100644 --- a/src/contract/contract-messages.ts +++ b/src/contract/contract-messages.ts @@ -253,6 +253,11 @@ export interface StartRunPayload { * sw-run-start.ts), so no page-side caller exists to emit its lifecycle events, and its remote tools run in the * worker. Absent: a page built it (a console `ml.agent()`), as before. */ builtBy?: "worker"; + /** "person": the worker minted this run's id for the person (sw-run-start.ts `startMinted`), the one place it is + * written. A hand-over, resume or restore keeps it as stored and never writes it; a page's START_RUN cannot set it + * (`PAGE_STRIPPED_KEYS`). Absent: a page's run, a hand-over from one, or a run stored before this field existed. + * Read by `runStartedBy` (sw-runs.ts), never `builtBy`, which a hand-over rewrites. */ + startedBy?: "person"; } /** The serializable state a fresh document needs to rebuild a background-hosted run's BUILTIN toolset after diff --git a/src/sw/run-payload-check.ts b/src/sw/run-payload-check.ts index 5f1ff47b4..51ef56c0d 100644 --- a/src/sw/run-payload-check.ts +++ b/src/sw/run-payload-check.ts @@ -89,6 +89,7 @@ const rebuild = shape({ const START_FIELDS: Record = { runId: (v, at) => runIdError(v, at), task: str, systemPrompt: str, tools: listOf(RUN_PAYLOAD_LIMITS.tools, tool), model: optional(strOrNull), think: optional(boolOrNull), display: optional(obj), origin: optional(obj), builtBy: optional(oneOf(["worker"])), + startedBy: optional(oneOf(["person"])), stream: optional(bool), autoApprovePython: optional(bool), autoApproveReadonly: optional(bool), // Retired (a same-origin as-you fetch is free, docs/spec/POLICIES.md "One free tier"): still accepted, and dropped, so a // run persisted before the upgrade resumes. diff --git a/src/sw/sw-run-host.ts b/src/sw/sw-run-host.ts index 30a0e49e3..50313c638 100644 --- a/src/sw/sw-run-host.ts +++ b/src/sw/sw-run-host.ts @@ -362,7 +362,7 @@ export const GATED_TOOL_NAMES: ReadonlySet = GATED_BUILTINS; * The keys a page's START_RUN may not set, at the payload's top level and inside its `rebuild` alike: the person's * fields and the sender's (`pageStartPayload`). One list for both levels, so a key added here is stripped at each. */ -export const PAGE_STRIPPED_KEYS = ["builtBy", "display", "files", "sends", "origin", "pageOrigin", "pageUrl", "inputScrubbed", "shell", "noTabTold"] as const; +export const PAGE_STRIPPED_KEYS = ["builtBy", "display", "files", "sends", "origin", "pageOrigin", "pageUrl", "inputScrubbed", "shell", "noTabTold", "startedBy"] as const; /** * A shallow copy of `o` without any of `PAGE_STRIPPED_KEYS`. @@ -379,7 +379,8 @@ function withoutPersonFields(o: T): T { * A page's START_RUN payload as the worker may trust it. A page's payload may ask for MORE gating, never less. * - Removed, the worker's to set, at the top level and inside `rebuild` alike (`PAGE_STRIPPED_KEYS`): `builtBy`, `display`, `files` (pointers naming value-store rows), `sends`, * `inputScrubbed` (a page's claim would spare a stored session's raw user turns the scrub on resume), `shell`, - * `noTabTold` (a page's claim would keep the no-tab note from its model) and `origin` (the PromptOrigin: a page could stamp its prompt as typed on an extension surface). Only the worker's own `hostRun` call + * `noTabTold` (a page's claim would keep the no-tab note from its model), `startedBy` (a page's claim would make its + * run read as the person's, `runStartedBy`) and `origin` (the PromptOrigin: a page could stamp its prompt as typed on an extension surface). Only the worker's own `hostRun` call * (sw-run-start.ts) marks a run worker-built, and `makeWorkerRun` hands one over; a page's claim would give its run the * worker's tool routing, grants, vision and answer, and lock the run as the person's. * - Removed from `tools`: `propose_policy`, which only a run the worker built offers (a page's run asking the person for diff --git a/src/sw/sw-run-start.ts b/src/sw/sw-run-start.ts index 315cdef97..6ca143650 100644 --- a/src/sw/sw-run-start.ts +++ b/src/sw/sw-run-start.ts @@ -168,6 +168,8 @@ async function startMinted(tabId: number, tab: chrome.tabs.Tab | undefined, url: ...(recipe.display ? { display: recipe.display } : {}), ...(shelf.size ? { files: shelf.all() } : {}), ...(shellOn ? { shell: true } : {}), + // The one write of who started the run: here, where the worker minted its id (`runStartedBy` reads it). + startedBy: "person", }; if (opts.keep) keepSession(runId); // The run's result reaches every surface through its own lifecycle events (`builtBy: "worker"`), so nobody diff --git a/src/sw/sw-runs.ts b/src/sw/sw-runs.ts index cc56682cd..3e598469d 100644 --- a/src/sw/sw-runs.ts +++ b/src/sw/sw-runs.ts @@ -157,15 +157,23 @@ export function makeWorkerRun(runId: string): void { /** * Whether a run is one the worker started for the person, with an id the worker minted (sw-run-start.ts `shortHash`): - * built by the worker and never handed to it from a page. A run a page started, or handed over from one, keeps the id - * the page chose. Read after the restore (`hydrationDone`), so an evicted worker does not read a hand-over as absent. + * its stored payload's `startedBy`, written once where the id was minted and carried as stored by every hand-over, + * resume, adoption and restore. Neither `builtBy` (a hand-over rewrites it) nor the hand-over list (a resume adds to it, + * and an entry can be lost) says who started a run. Read after the restore (`hydrationDone`), so an evicted worker's + * runs are back in `bgRuns` first. * @param runId the run - * @returns `"person"` for such a run, `"page"` for every other id, a run this worker does not know included + * @returns `"person"` for such a run, `"page"` for every other id: a page's run, a run stored before `startedBy` + * existed, a run still starting, and a run this worker does not hold */ export async function runStartedBy(runId: string): Promise<"person" | "page"> { await hydrationDone; - return isWorkerRun(runId) && !handedToWorker.has(runId) ? "person" : "page"; + return isWorkerRun(runId) && bgRuns.get(runId)?.p.startedBy === "person" ? "person" : "page"; } +defineState({ + id: "run.started-by", scope: "run", realm: "worker", audience: "human", lostOn: [], + describe: "Who started the run: \"person\" when the worker minted its id for the person, written once then; absent for a page's run, a hand-over from one, and a run stored before the field existed. Kept on the run's snapshot and the saved session's payload.", + read: ({ runId }) => (runId ? bgRuns.get(runId)?.p.startedBy : undefined), +}); /** TEST-ONLY (`__mlEvictForTest`): forget the hand-overs held in memory, as an eviction does; storage keeps them. */ export function dropHandedMemoryForTest(): void { handedToWorker.clear(); } diff --git a/tests/redteam-run-origin.test.mjs b/tests/redteam-run-origin.test.mjs new file mode 100644 index 000000000..d939f7b2a --- /dev/null +++ b/tests/redteam-run-origin.test.mjs @@ -0,0 +1,351 @@ +// redteam-run-origin.test.mjs — ADVERSARIAL: the durable fact of WHO started a run ("person" | "page"), asked the way a +// hostile page, an evicted worker and an upgrade to a build that carries no fact would have it. A page chooses its run's +// id, and a hand-over rewrites `builtBy` to "worker", so neither the id's shape nor `builtBy` can stand for the fact: it +// must be written once where the worker mints the id and read everywhere else; a resume, an adoption, a hand-over or a +// restore must never write it. +// +// What this file holds the worker to, from the attacker's side: +// 1. The person's own run comes back still "person": resumed on a tab and resumed with no tab. Today a resume marks the +// run handed to the worker (`makeWorkerRun`), and `runStartedBy` reads the hand-over as the page's. +// 2. A page's run stays the page's through a hand-over, a save and a resume — and, the unsafe direction, through a +// RESTORE of a snapshot the hand-over left saying `builtBy: "worker"` once the hand-over list has lost its id. Today +// `runStartedBy` trusts `builtBy`, which the hand-over itself rewrote. +// 3. A snapshot from a build with no fact reads "page", and hydration writes no fact into it. Nothing infers the fact. +// 4. No message writes it: a page's START_RUN/RESUME_RUN naming it (as `startedBy`/`runStartedBy`, or an own +// `__proto__`) changes nothing, in flight or after a restore, and a page cannot take over a person's run by its id. +// 5. A fork reads its OWN fact, never its parent's, in either direction. +// 6. The fact never leaves the worker: no event to a page and no bringable session row carries it. +// 7. An archive restore carries the stored payload as it is and adds no fact to the summary. +// +// The run paths run in the real background bundle (node:vm, tests/helpers.js `loadBackground`); the restore rows run the +// source's sw-runs.ts in this realm over a storage the bundle wrote, so no fact field name is written by hand here. + +import { test } from "node:test"; +import assert from "node:assert/strict"; +import { createRequire } from "node:module"; + +const require = createRequire(import.meta.url); +const { jsonResponse, loadBackground } = require("./helpers"); +const { IDBFactory } = await import("fake-indexeddb"); + +const T = { timeout: 30000 }; +const sleep = (ms) => new Promise((r) => setTimeout(r, ms)); +const until = async (fn, ms = 8000) => { const end = Date.now() + ms; while (Date.now() < end) { if (await fn()) return true; await sleep(5); } return false; }; +const plain = (x) => JSON.parse(JSON.stringify(x ?? null)); + +const VERSION = "9.9.9"; // the bundle's manifest version (tests/helpers.js), so the test realm restores its snapshots +const SITE = "https://site.example/page"; +const ELSEWHERE = "https://unapproved.example/landing"; +const HUD = "chrome-extension://test/sidebar.html"; +const config = { chatUrl: "http://host/api/chat/completions", apiKey: "sk-test-config-key", model: "default-model", apiFormat: "openai", ocrModel: "", debugMode: "off" }; +/** The names a page may send hoping to write the fact. `startedBy` is the one the worker reads (the fact's name); the + * rest are unknown fields the payload check deliberately leaves alone, and nothing reads them, so they are sent but not + * asserted on: a page keeping its own extra field is not a way to write the fact. (`origin` must be an object and + * `builtBy` only "worker" in the payload check, so neither can even carry the string.) */ +const CLAIMS = ["startedBy", "runStartedBy", "startedByPerson", "personStarted", "started"]; + +// --- the worker's own storage, for the restore rows --- + +/** What the test realm's `chrome.storage.local` holds: a storage the bundle wrote, or a hand-built fixture. */ +let SOURCE = {}; +/** The snapshot shape `persistRun` writes: a version stamp, the run's tab, and its StartRunPayload. */ +const snap = (runId, tabId, p = {}) => ({ tabId, version: VERSION, p: { runId, task: "t", systemPrompt: "s", tools: [], ...p }, messages: [] }); + +// The first thing a restarted worker reads here: page-started runs whose snapshots say `builtBy: "worker"` (as a +// hand-over's checkpoint leaves them) while the hand-over list has lost their ids, and one snapshot from an older build +// that carried no fact at all. `runStartedBy` must read all of them as the page's. +SOURCE = { + ml_handed_to_worker: ["page_lost_other"], + ml_bgrun_page_lost_tab: snap("page_lost_tab", 7, { builtBy: "worker" }), + ml_bgrun_page_lost_nt: snap("page_lost_nt", -1, { builtBy: "worker" }), + ml_bgrun_old_no_fact: snap("old_no_fact", 7, { builtBy: "worker" }), +}; + +/** The test realm's chrome over `SOURCE`: what sw-runs reads at import, with the bundle's manifest version. */ +globalThis.chrome = { + runtime: { id: "ext-id", lastError: undefined, onMessage: { addListener() {} }, getURL: (p) => p, getManifest: () => ({ version: VERSION }) }, + storage: { + local: { + get: async (d) => { + if (d == null) return structuredClone(SOURCE); + const keys = typeof d === "string" ? [d] : Array.isArray(d) ? d : Object.keys(d); + const out = typeof d === "string" || Array.isArray(d) ? {} : { ...d }; + for (const k of keys) if (k in SOURCE) out[k] = structuredClone(SOURCE[k]); + return out; + }, + set: async (o) => { Object.assign(SOURCE, structuredClone(o)); }, + remove: async (keys) => { for (const k of [].concat(keys)) delete SOURCE[k]; }, + }, + sync: { get: async (d) => ({ ...(d ?? {}), chatUrl: config.chatUrl, apiKey: config.apiKey }), set: async () => {} }, + session: { get: async () => ({}), set: async () => {}, remove: async () => {} }, + onChanged: { addListener() {} }, + }, +}; +const runs = await import("../src/sw/sw-runs.ts"); + +/** A restarted worker reading `source`: the test realm's sw-runs hydrates it, its hand-over MEMORY dropped as an + * eviction drops it (storage keeps the list). */ +async function restoredFrom(source) { + SOURCE = source; + runs.dropHandedMemoryForTest(); + await runs.hydratePersistedRuns(); +} + +/** Every path in `v` whose value is exactly "person". The fact must not appear in a value a page can read. */ +function personValues(v, path = "$") { + const out = []; + const walk = (x, at) => { + if (typeof x === "string") { if (x === "person") out.push(at); return; } + if (!x || typeof x !== "object") return; + if (Array.isArray(x)) { x.forEach((e, i) => walk(e, `${at}[${i}]`)); return; } + for (const [k, e] of Object.entries(x)) walk(e, `${at}.${k}`); + }; + walk(v, path); + return out; +} + +/** + * A worker with the page on tabs 7 and 8, the model answering `script` in turn then "done", and every model call from + * `holdFrom` on held open. `local` seeds chrome.storage.local. + */ +function world({ local = {}, script = [], holdFrom = null } = {}) { + const gates = []; + let n = 0; + const bg = loadBackground({ + config, local, indexedDB: new IDBFactory(), + openTabs: [{ id: 7, url: SITE, title: "Site" }, { id: 8, url: SITE, title: "Site too" }], + onFetch: async (call) => { + if (call.url.endsWith("/api/models")) return jsonResponse({ data: [{ id: "default-model" }] }); + if (!call.url.includes("/chat/completions")) return jsonResponse({}); + const i = n++; + if (holdFrom != null && i >= holdFrom) await new Promise((r) => gates.push(r)); + const step = script[i]; + return step + ? jsonResponse({ choices: [{ message: { content: null, tool_calls: [{ id: `c${i}`, type: "function", function: { name: step.name, arguments: JSON.stringify(step.args ?? {}) } }] } }] }) + : jsonResponse({ choices: [{ message: { content: "done" } }] }); + }, + onTabMessage: async (_t, msg) => { + if (msg.type === "ADOPT_RUN_NOW") return { pageInfo: "" }; + if (msg.type !== "RUN_TOOL_IN_PAGE") return undefined; + if (msg.payload?.finish) return {}; + return { result: "ok" }; + }, + }); + bg.commit(7, { documentId: "doc-7", url: SITE }); + const EXT = { url: HUD }; + const port = bg.connect("ml-sessions", EXT); + port.send({ type: "sessions" }); + /** One session command over an extension page's port, as the chat page sends it. */ + const command = async (cmd, id = 1) => { + port.send({ type: "cmd", id, command: cmd }); + assert.ok(await until(() => port.messages.some((m) => m.id === id)), "the command is answered"); + return port.messages.find((m) => m.id === id).result; + }; + const state = () => bg.context.__mlRunStateForTest(); + const live = (hash) => state().controllers.includes(hash); + const startedBy = (hash) => bg.context.__mlRunStartedByForTest(hash); + const modelCalls = () => bg.calls.filter((c) => c.url.includes("/chat/completions")).length; + /** A run the person started (kept, so its history is written), its first turn over. */ + const personRun = async (extra = {}) => { + const n0 = modelCalls(); + const { hash } = await bg.context.__mlStartUserRunForTest(7, { task: "plot the fares", surface: "hud", ...extra }, { keep: true }); + assert.ok(await until(() => modelCalls() > n0), "the person's run calls the model"); + assert.ok(await until(() => !live(hash)), "the person's first turn ends"); + await sleep(20); + return hash; + }; + /** A run the PAGE started (surface "off"). `sent` is the START_RUN's answer promise, which resolves when the whole + * run finishes; `settled` awaits it. `extra` merges into the START_RUN payload. */ + const pageRun = async (extra = {}, id = "pagerun1") => { + const sent = bg.send({ type: "START_RUN", payload: { + runId: id, task: "do it", systemPrompt: "sys", tools: [], model: "default-model", think: null, maxSteps: 4, + autoApprovePython: false, autoApproveReadonly: false, surface: "off", + rebuild: { toolNames: [], model: "default-model", driverSees: false, visionModel: null, groundingModel: null, groundingRange: 1000, pierceClosed: false, cdp: false, crossOrigin: true }, + ...extra, + } }, { tab: { id: 7, url: SITE }, url: SITE, origin: "https://site.example", frameId: 0 }); + return { sent, hash: id, settled: async () => { const r = await sent; await sleep(20); return plain(r); } }; + }; + /** The execution log, as the bundle keeps it. */ + const log = () => bg.context.__mlRunLog.all(); + return { bg, gates, port, command, state, live, startedBy, personRun, pageRun, log, EXT }; +} + +// --- 1. the person's own run is still the person's when it comes back --- + +test("a person's saved run resumed on a tab is still the person's", T, async () => { + const w = world(); + const hash = await w.personRun(); + assert.equal(await w.startedBy(hash), "person", "positive control: the run the worker minted is the person's"); + await w.bg.context.__mlEvictForTest(); + const res = await w.command({ type: "session.resume", session: { runtime: "local", hash }, target: { kind: "tab", tabId: 8 } }); + assert.equal(res?.ok, true, `the resume is answered: ${JSON.stringify(res)}`); + assert.equal(await w.startedBy(hash), "person", "the resume (sw-sessions.ts `adoptSession`, `makeWorkerRun`) gave the person's run to the page"); +}); + +test("a person's saved run resumed with no tab is still the person's", T, async () => { + const w = world(); + const hash = await w.personRun(); + await w.bg.context.__mlEvictForTest(); + const res = await w.command({ type: "session.resume", session: { runtime: "local", hash }, target: { kind: "detached" } }); + assert.equal(res?.ok, true, `the detached resume is answered: ${JSON.stringify(res)}`); + assert.equal(await w.startedBy(hash), "person", "the detached resume (`resumeDetached`, `makeWorkerRun`) gave the person's run to the page"); +}); + +// --- 2. a page's run stays the page's, through a hand-over, a save and a resume --- + +test("a page's run handed over, saved and then resumed is still the page's", T, async () => { + // In flight, so its session is kept before its first turn-end (a page's run is not `persistUiRuns`' to keep). + const w = world({ holdFrom: 0 }); + const { hash, settled } = await w.pageRun(); + assert.ok(await until(() => w.bg.localStore[`ml_bgrun_${hash}`]), "the page's run is snapshotted"); + w.bg.context.__mlKeepSessionForTest(hash); + assert.equal(await w.startedBy(hash), "page", "positive control: the page's own run"); + // The commit onto a site that may not use window.ml: the browser's report, which no page can stop. + w.bg.commit(7, { documentId: "doc-7b", url: ELSEWHERE }); + assert.ok(await until(async () => (await w.log()).some((e) => e.run === hash && e.kind === "handed-to-worker")), "the run is handed to the worker"); + assert.equal(await w.startedBy(hash), "page", "the hand-over gave the page's run to the person"); + w.gates.splice(0).forEach((g) => g()); + // It ends as a handed-over run does, its result not sent to the page that may no longer use window.ml. + await settled(); + await sleep(20); + await w.bg.context.__mlEvictForTest(); + const res = await w.command({ type: "session.resume", session: { runtime: "local", hash }, target: { kind: "tab", tabId: 8 } }); + assert.equal(res?.ok, true, `the resume is answered: ${JSON.stringify(res)}`); + assert.equal(await w.startedBy(hash), "page", "the resume made the page's run the person's"); +}); + +test("a page cannot start a turn in, or over, a person's run by naming its id", T, async () => { + const w = world(); + const hash = await w.personRun(); + const r = await w.bg.send({ type: "START_RUN", payload: { runId: hash, task: "hijack", systemPrompt: "s", tools: [], model: "m", think: null, maxSteps: 2, autoApprovePython: false, autoApproveReadonly: false } }, + { tab: { id: 7, url: SITE }, url: SITE, origin: "https://site.example", frameId: 0 }); + assert.match(r?.error ?? "", /Refused/, `the page's START_RUN is refused: ${JSON.stringify(r)}`); + assert.equal(await w.startedBy(hash), "person", "the refused start changed the person's run"); +}); + +// --- the unsafe RESTORE: a page's run whose snapshot the hand-over left saying "builtBy: worker" --- + +test("a restored snapshot of a page's run is the page's when the hand-over list has lost its id (on a tab)", T, async () => { + // The fixture worker restored this realm's storage at import: the hand-over's `builtBy: "worker"` is there, the id is + // not in the list, and the run is restored. `builtBy` is not the fact. + assert.equal(await runs.runStartedBy("page_lost_tab"), "page", "the hand-over's builtBy was read as the person's"); +}); + +test("the same, restored with no tab, is the page's too", T, async () => { + assert.equal(await runs.runStartedBy("page_lost_nt"), "page", "the hand-over's builtBy was read as the person's with no tab"); +}); + +// --- 3. upgrade: a build with no fact reads "page", and writes none --- + +test("a snapshot from a build with no fact reads page, and hydration writes no fact into it", T, async () => { + const key = "ml_bgrun_old_no_fact"; + const before = JSON.stringify(SOURCE[key]); + assert.ok(before, "positive control: the upgrade fixture is in the storage"); + await runs.hydratePersistedRuns(); + assert.equal(await runs.runStartedBy("old_no_fact"), "page", "an old snapshot's builtBy was read as a fact"); + assert.equal(JSON.stringify(SOURCE[key]), before, "hydration wrote something into an old snapshot"); +}); + +// --- 4. no message writes the fact --- + +test("a page's START_RUN with an own __proto__ naming the fact is refused, and registers nothing", T, async () => { + const w = world(); + const before = w.state(); + const payload = JSON.parse(`{"__proto__":{"startedBy":"person"},"runId":"proto1","task":"t","systemPrompt":"s","tools":[],"model":"m","think":null,"maxSteps":2,"autoApprovePython":false,"autoApproveReadonly":false}`); + const r = await w.bg.send({ type: "START_RUN", payload }, { tab: { id: 7, url: SITE }, url: SITE, origin: "https://site.example", frameId: 0 }); + assert.match(r?.error ?? "", /__proto__/, `the payload is refused: ${JSON.stringify(r)}`); + const after = w.state(); + assert.deepEqual(after.bgRuns, before.bgRuns, "a refused start registered a run"); + assert.deepEqual(after.controllers, before.controllers, "a refused start started a turn"); +}); + +test("a page's START_RUN naming the fact changes nothing: not in flight, and not through a restore of its snapshot", T, async () => { + const w = world({ holdFrom: 0 }); + const claims = Object.fromEntries(CLAIMS.map((k) => [k, "person"])); + const payload = { runId: "claim1", task: "t", systemPrompt: "s", tools: [], model: "default-model", think: null, maxSteps: 2, autoApprovePython: false, autoApproveReadonly: false, surface: "off", ...claims, + rebuild: { toolNames: [], model: "default-model", driverSees: false, visionModel: null, groundingModel: null, groundingRange: 1000, pierceClosed: false, cdp: false, crossOrigin: true, ...claims } }; + void w.bg.send({ type: "START_RUN", payload }, { tab: { id: 7, url: SITE }, url: SITE, origin: "https://site.example", frameId: 0 }); + assert.ok(await until(() => w.bg.localStore.ml_bgrun_claim1), "the page's run is snapshotted before its first step"); + assert.equal(await w.startedBy("claim1"), "page", "a page's claim made its own run the person's"); + // The stored payload, as a restarted worker would read it: the fact's name is the worker's to write, at the top level + // and inside `rebuild` alike (`PAGE_STRIPPED_KEYS`). The other claimed names are unknown fields nothing reads. + const stored = plain(w.bg.localStore.ml_bgrun_claim1.p); + assert.notEqual(stored.startedBy, "person", "the page's claim is stored as its run's fact"); + assert.notEqual(stored.rebuild?.startedBy, "person", "the page's claim is stored as its run's rebuild's fact"); + // And the restore itself: the same snapshot, the worker restarted. + await restoredFrom({ ...w.bg.localStore }); + assert.equal(await runs.runStartedBy("claim1"), "page", "a page's claim survived the restore as the fact"); + w.gates.splice(0).forEach((g) => g()); +}); + +test("a page's RESUME_RUN naming the fact does not turn its run into the person's", T, async () => { + const w = world(); + const { hash, settled } = await w.pageRun(); + assert.equal((await settled())?.error, undefined, "positive control: the page's run ends"); + w.bg.context.__mlKeepSessionForTest(hash); + const r = await w.bg.send({ type: "RESUME_RUN", payload: { runId: hash, task: "again", ...Object.fromEntries(CLAIMS.map((k) => [k, "person"])) } }, + { tab: { id: 7, url: SITE }, url: SITE, origin: "https://site.example", frameId: 0 }); + await sleep(30); + assert.equal(await w.startedBy(hash), "page", `a RESUME_RUN's claim made a page's run the person's: ${JSON.stringify(plain(r))}`); +}); + +// --- 5. a fork reads its own fact, never its parent's --- + +test("a fork whose parent is a PAGE's run is still the person's, through the hand-over too", T, async () => { + const w = world({ holdFrom: 0 }); + const { hash } = await w.bg.context.__mlStartUserRunForTest(7, { task: "plot the fares", surface: "hud" }, { keep: true }); + assert.ok(await until(() => w.bg.localStore[`ml_bgrun_${hash}`]), "the person's run is snapshotted"); + // The parent a fork names on its first turn (`forkOf`): a page's run. + const p = { ...w.bg.localStore[`ml_bgrun_${hash}`].p, forkOf: "page_lost_tab" }; + await restoredFrom({ ...w.bg.localStore, [`ml_bgrun_${hash}`]: { ...w.bg.localStore[`ml_bgrun_${hash}`], p } }); + assert.equal(await runs.runStartedBy(hash), "person", "positive control: the fork's own mint"); + runs.makeWorkerRun(hash); + assert.equal(await runs.runStartedBy(hash), "person", "the fork's PARENT's fact (page) was read instead of its own"); + w.gates.splice(0).forEach((g) => g()); +}); + +test("a page's fork whose parent is the PERSON's run is still the page's", T, async () => { + const w = world({ holdFrom: 0 }); + const { hash: parent } = await w.bg.context.__mlStartUserRunForTest(7, { task: "plot the fares", surface: "hud" }, { keep: true }); + assert.ok(await until(() => w.bg.localStore[`ml_bgrun_${parent}`]), "the person's run is snapshotted"); + // A page's fork of it, as the page sends one: the hand-written snapshot carries no fact (it came from the page), and + // its parent's is the person's. The parent is in the storage the restore reads. + await restoredFrom({ ...w.bg.localStore, ml_bgrun_page_fork2: snap("page_fork2", 7, { forkOf: parent }) }); + assert.equal(await runs.runStartedBy(parent), "person", "positive control: the parent is the person's"); + assert.equal(await runs.runStartedBy("page_fork2"), "page", "the fork's PARENT's fact (person) was read instead of its own"); + w.gates.splice(0).forEach((g) => g()); +}); + +// --- 6. the fact never leaves the worker --- + +test("no event to a page and no bringable session row carries the fact", T, async () => { + const w = world(); + const hash = await w.personRun(); + assert.ok(w.bg.tabMessages.length > 0, "positive control: the run fanned events"); + assert.deepEqual(personValues(w.bg.tabMessages.map(([, m]) => plain(m))), [], "a message to the page carries the fact"); + const sender = { tab: { id: 8, url: ELSEWHERE }, url: HUD, frameId: 1 }; + const rows = plain(await w.bg.send({ type: "LIST_BRINGABLE" }, sender)); + assert.ok(Array.isArray(rows?.data), `positive control: the bringable list answers: ${JSON.stringify(rows)}`); + assert.deepEqual(personValues(rows), [], "a session row a surface reads carries the fact"); + assert.equal(await w.startedBy(hash), "person", "positive control: the run is the person's"); +}); + +// --- 7. an archive restore carries the payload as stored, and adds no fact to the summary --- + +test("a restored history carries the stored payload as it is, and the row gains no fact", async () => { + const { SessionStore } = await import("../src/session/session-store.ts"); + const written = []; + const be = { + rows: async () => [], append: async (row, from, events, hist) => { written.push({ row: plain(row), hist: plain(hist) }); }, + events: async () => [], historyRange: async () => [], runMeta: async () => null, noteNsDropped: async () => {}, remove: async () => {}, + }; + const store = new SessionStore(be, { flushMs: 0 }); + await store.open(); + // What an archive wrote before the upgrade: a payload with no fact of this build's shape. + const payload = { runId: "7c41e2aa", task: "t", systemPrompt: "s", tools: [], builtBy: "worker" }; + const summary = { id: { runtime: "local", hash: "7c41e2aa" }, kind: "agent", status: "done", createdTs: 1, lastTs: 2, pendingApprovals: 0, saved: true }; + await store.restoreSession(summary, [], { kind: "agent", payload, messages: [] }, 3); + assert.equal(written.length, 1, "positive control: the restored session is written"); + assert.deepEqual(written[0].hist.meta.payload, payload, "the restore rewrote the stored payload"); + assert.deepEqual(personValues(written[0].row.summary), [], "the restored row's summary carries a fact"); +}); diff --git a/tests/redteam-session-folder.test.mjs b/tests/redteam-session-folder.test.mjs index c685787ab..58eb1aa54 100644 --- a/tests/redteam-session-folder.test.mjs +++ b/tests/redteam-session-folder.test.mjs @@ -317,15 +317,15 @@ test("GAIN blocked — a page-started run whose id names a folder, on the saved assert.deepEqual(reads.map(([where]) => where), ["row"], "positive control: the row is read for the person's run"); }); -test("runStartedBy: a worker-minted run is the person's; a page's id, a hand-over and an unknown id are the page's", async () => { - // The worker's own chrome, holding two resumable snapshots as a restore leaves them: one the worker built, one a - // page's, and the hand-over list naming neither yet. The restore's read is HELD, so the first call is made while it - // is in flight: `runStartedBy` must wait for it rather than read the hand-over as absent. +test("runStartedBy: the fact decides — a page's id, an old snapshot, a hand-over and an unknown id are the page's; a person's run stays the person's through a hand-over", async () => { + // The worker's own chrome, holding two resumable snapshots as a restore leaves them: the person's (the fact, written + // where the id was minted) and a page's, and the hand-over list naming neither. The restore's read is HELD, so the + // first call is made while it is in flight: `runStartedBy` must wait for it rather than read the maps as empty. let open; const gate = new Promise((r) => { open = r; }); installWorkerChrome({ local: { - "ml_bgrun_wmlworker": { tabId: 3, p: { runId: "wmlworker", builtBy: "worker" }, messages: [] }, + "ml_bgrun_wmlworker": { tabId: 3, p: { runId: "wmlworker", builtBy: "worker", startedBy: "person" }, messages: [] }, "ml_bgrun_pagerun": { tabId: 3, p: { runId: "pagerun" }, messages: [] }, }, gate, @@ -344,9 +344,9 @@ test("runStartedBy: a worker-minted run is the person's; a page's id, a hand-ove // A run handed over from its page keeps the page's id: it is the page's, even though the worker drives it now. runs.makeWorkerRun("pagerun"); assert.equal(await runs.runStartedBy("pagerun"), "page", "a hand-over is not the person's"); - // A run the person started that is later handed over is no longer the person's either. + // A hand-over never writes the fact: the person's run stays the person's, though the worker drives it now. runs.makeWorkerRun("wmlworker"); - assert.equal(await runs.runStartedBy("wmlworker"), "page", "a worker-built run handed over from its page"); + assert.equal(await runs.runStartedBy("wmlworker"), "person", "a hand-over rewrote the fact a worker-built run minted"); }); // --- the two scanners, and the host that spies on the mount calls --- diff --git a/tests/start-run-strip.test.mjs b/tests/start-run-strip.test.mjs index 5fede3ffb..58ab19653 100644 --- a/tests/start-run-strip.test.mjs +++ b/tests/start-run-strip.test.mjs @@ -25,7 +25,7 @@ const RESTAMPED = new Set(["pageOrigin", "pageUrl"]); test("PAGE_STRIPPED_KEYS is the person's fields and the sender's, and nothing was dropped from it", async () => { const { PAGE_STRIPPED_KEYS } = await runHost(); - assert.deepEqual([...PAGE_STRIPPED_KEYS].sort(), ["builtBy", "display", "files", "inputScrubbed", "noTabTold", "origin", "pageOrigin", "pageUrl", "sends", "shell"]); + assert.deepEqual([...PAGE_STRIPPED_KEYS].sort(), ["builtBy", "display", "files", "inputScrubbed", "noTabTold", "origin", "pageOrigin", "pageUrl", "sends", "shell", "startedBy"]); }); test("ADVERSARIAL: each stripped key a page writes, at the top level and inside `rebuild`, is gone from both; the control keys stay", async () => { diff --git a/tests/started-by.test.mjs b/tests/started-by.test.mjs new file mode 100644 index 000000000..4709e0eeb --- /dev/null +++ b/tests/started-by.test.mjs @@ -0,0 +1,113 @@ +// started-by.test.mjs — the UPGRADE of who started a run (`startedBy`, sw-runs.ts `runStartedBy`): a session saved by +// a build that wrote no `startedBy` reads "page" when it is resumed, and a session's own folder then mounts nothing and +// records nothing. Nothing infers the fact from the payload's shape (`builtBy: "worker"` included). The adversarial +// rows are tests/redteam-run-origin.test.mjs. + +import { test } from "node:test"; +import assert from "node:assert/strict"; +import { createRequire } from "node:module"; +import { sessionFolders, FOLDER_KEY } from "../src/shell/session-folder.ts"; + +const require = createRequire(import.meta.url); +const { jsonResponse, loadBackground } = require("./helpers"); +// The CommonJS copy, the one tests/helpers.js gives the bundle (`IDBKeyRange` included): a second copy's keys and +// ranges are not the bundle's, and its writes fail. +const { IDBFactory } = require("fake-indexeddb"); + +const T = { timeout: 30000 }; +const sleep = (ms) => new Promise((r) => setTimeout(r, ms)); +const until = async (fn, ms = 8000) => { const end = Date.now() + ms; while (Date.now() < end) { if (await fn()) return true; await sleep(5); } return false; }; +const SITE = "https://site.example/page"; +const WS = "/Users/p/git/proj"; + +/** + * The worker's saved `runmeta` row for `hash`, rewritten by `edit` when given (as an older build wrote it). Never opens + * a database the worker has not created: opening one creates it empty, and the worker's stores would never exist. + */ +async function runMeta(idb, hash, edit) { + if (!(await idb.databases()).some((d) => d.name === "ml-saved-sessions")) return null; + return new Promise((resolve, reject) => { + const open = idb.open("ml-saved-sessions"); + open.onerror = () => reject(open.error); + open.onsuccess = () => { + const db = open.result; + if (!db.objectStoreNames.contains("runmeta")) { db.close(); resolve(null); return; } + const tx = db.transaction("runmeta", edit ? "readwrite" : "readonly"); + const store = tx.objectStore("runmeta"); + let row = null; + const req = store.get(hash); + req.onsuccess = () => { row = req.result ?? null; if (row && edit) store.put(edit(row), hash); }; + tx.oncomplete = () => { db.close(); resolve(row); }; + tx.onerror = () => { db.close(); reject(tx.error); }; + }; + }); +} + +/** A worker with the page on tabs 7 and 8, the model answering "done", its saved sessions in `indexedDB`. */ +function world(indexedDB) { + const bg = loadBackground({ + indexedDB, local: {}, + config: { chatUrl: "http://host/api/chat/completions", apiKey: "k", model: "m", apiFormat: "openai", debugMode: "off" }, + openTabs: [{ id: 7, url: SITE, title: "Site" }, { id: 8, url: SITE, title: "Site too" }], + onFetch: async (call) => { + if (call.url.endsWith("/api/models")) return jsonResponse({ data: [{ id: "m" }] }); + return jsonResponse(call.url.includes("/chat/completions") ? { choices: [{ message: { content: "done" } }] } : {}); + }, + onTabMessage: async (_t, msg) => (msg.type === "ADOPT_RUN_NOW" ? { pageInfo: "" } : msg.type === "RUN_TOOL_IN_PAGE" ? (msg.payload?.finish ? {} : { result: "ok" }) : undefined), + }); + bg.commit(7, { documentId: "doc-7", url: SITE }); + const port = bg.connect("ml-sessions", { url: "chrome-extension://test/sidebar.html" }); + port.send({ type: "sessions" }); + const command = async (cmd, id) => { + port.send({ type: "cmd", id, command: cmd }); + assert.ok(await until(() => port.messages.some((m) => m.id === id)), "the command is answered"); + return port.messages.find((m) => m.id === id).result; + }; + return { bg, command }; +} + +/** A folder binding over in-memory storage that already holds a record for `hash`, and a host with that folder. */ +function folders(hash) { + const storage = new Map([[FOLDER_KEY(hash), { root: WS, name: "2026-11-20-old-session" }]]); + const calls = []; + const host = { mount: async (a) => { calls.push(a); return { id: "m1", path: a.path, root: a.path, mode: a.mode, uploads: a.uploads ?? null }; } }; + const writes = []; + const f = sessionFolders({ + store: null, + kept: { get: async (k) => storage.get(k), set: async (k, v) => { writes.push(k); storage.set(k, v); }, remove: async (k) => { writes.push(k); storage.delete(k); } }, + session: () => ({ title: "old", createdTs: Date.now() }), + scrubCuts: async () => false, note: () => {}, log: () => {}, now: Date.now, + }); + return { f, host, calls, writes, storage }; +} + +// --- upgrade: a session saved before startedBy existed --- + +test("a person's session saved before startedBy existed reads page when resumed, on a tab and with no tab, and mounts no folder", T, async () => { + for (const target of [{ kind: "tab", tabId: 8 }, { kind: "detached" }]) { + const indexedDB = new IDBFactory(); + const w = world(indexedDB); + const { hash } = await w.bg.context.__mlStartUserRunForTest(7, { task: "plot the fares", surface: "hud" }, { keep: true }); + const live = () => w.bg.context.__mlRunStateForTest().controllers.includes(hash); + assert.ok(await until(() => w.bg.calls.some((c) => c.url.includes("/chat/completions")) && !live()), "the person's first turn ends"); + assert.ok(await until(async () => (await runMeta(indexedDB, hash))?.payload?.startedBy === "person", 15000), "positive control: this build saves the fact with the session"); + assert.equal(await w.bg.context.__mlRunStartedByForTest(hash), "person", "positive control: the person's run"); + await sleep(30); + // What an older build saved: the same payload with no `startedBy`, `builtBy: "worker"` still on it. + await runMeta(indexedDB, hash, (row) => { const { startedBy: _s, ...payload } = row.payload; return { ...row, payload }; }); + assert.equal((await runMeta(indexedDB, hash)).payload.builtBy, "worker", "the old row still says the worker built it"); + await w.bg.context.__mlEvictForTest(); + const res = await w.command({ type: "session.resume", session: { runtime: "local", hash }, target }, 1); + assert.equal(res?.ok, true, `the resume is answered (${target.kind}): ${JSON.stringify(res)}`); + const startedBy = await w.bg.context.__mlRunStartedByForTest(hash); + assert.equal(startedBy, "page", `an old row was read as the person's (${target.kind})`); + assert.equal((await runMeta(indexedDB, hash)).payload.startedBy, undefined, `the resume wrote the fact into the old row (${target.kind})`); + // The folder gate takes that answer: no mount, and the record is neither read into a mount nor written. + const { f, host, calls, writes, storage } = folders(hash); + const r = await f.mount(host, { sessionFolders: true }, { session: hash, workspace: WS, mode: "rw", startedBy }); + assert.deepEqual(r, { mount: null, folder: null, pageStarted: true }, target.kind); + assert.deepEqual(calls, [], "the host was asked to mount"); + assert.deepEqual(writes, [], "a folder record was written"); + assert.deepEqual([...storage.keys()], [FOLDER_KEY(hash)]); + } +});