Repository navigation
QuickJS-ng WASM sandbox - #3
Conversation
Add the project skeleton (package, TypeScript strict ESM, vitest, CI on Linux, macOS and Windows, Apache-2.0 LICENSE and NOTICE, CLAUDE.md and AGENTS.md) and the frozen contracts the sandbox, host adapter, tool and benchmark parts build against. The run path is executable end to end with test fakes: MCP tools/call -> FakeSandbox -> Dispatcher (prepare, static rules, hooks, re-prepare on updated args, commit) -> StaticHostAdapter -> MemoryToolRuntime, with mutation ordering, cancellation, transactions with rollback, output caps with overflow files, and a command hook runner that kills the process group on timeout. Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
- Commit a dispatcher-owned deep-frozen copy of each prepared call; deep freeze now descends into objects that are already frozen. - Bound every await on adapter and runtime code by the run's abort signal or a grace: prepare, PostToolUse (which now receives the signal), loadPolicy (the run deadline starts before it), in-flight calls on stop, rollback and dispose. - Kill the command hook's whole process group on every completion path, so a backgrounded descendant cannot outlive the hook. - Send protocol and validation errors through the capped result formatter. Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
Runs each script in a fresh Node child process (empty env, bounded heap, Node permission model) that hosts a QuickJS-ng VM from the sync WASM build. Bindings are deferred promises settled by the parent's replies; the parent validates every child message and kills the child on anything unexpected, on timeout and on cancel. The WASM memory maximum is the real heap limit, because QuickJS-ng's own accounting undercounts in this build. Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
Lower the default QuickJS stack to 128 KiB: 256 KiB overflowed the Node stack on macOS with Node 22. A host stack overflow now ends the run as a RangeError script error. The permission-model test allows the variables the OS layer adds to every child env (libuv on Windows, macOS's encoding hint). Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
…early aborts - Replies to the child go through a writer that respects backpressure and caps the bytes waiting for the child (16 MiB) and the bytes sent per run (512 MiB); past a cap the run ends with outcome oom (ReplyBufferFull) instead of growing the server's memory. - The child runs with --permission or, on Node 22.0 to 22.12, --experimental-permission (one comma-separated read grant with the * wildcard, the only form those versions honor). Without either flag the sandbox refuses to start. - The abort listener is registered before onSpawn runs and the signal is re-checked after it; no call is forwarded once the signal is aborted. Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
Before Node 25 the permission model allows the probe's socket; the probe then exits and resets the connection, which the test server must ignore. Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
- Validate adapter decisions with a schema, reject non-string tool names and refresh the call summary after a hook rewrite. - Keep overflow output out of non-private state directories and off Windows. - Match path patterns across newlines and treat "..name" as inside a root. - Run a single deadline from the start of the run, counting policy loading, and give the sandbox the time left rounded up. - Roll back only after queued writes and edits end, report a pending rollback, and dispose the journal after the rollback has really finished. - Make the fake sandbox check its deadline before steps and calls, yield between steps, and tie its deadline and sleeps to one signal. - Describe the placeholder runtime the default server serves, with a runnable example. - Resolve in-memory paths against the session cwd and roots (Windows paths included), track file revisions for rollback, and run grep and glob in a stoppable worker thread. - Accept only a single --host option in serve. - Skip spawning a hook whose run was already cancelled and stop recording calls in the default runtime. Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
- Fake runtime: cap concurrent search workers per runtime; extra searches wait in a cancelable queue and a slot is reused only after its worker exits. - Fake runtime: build the search job after a slot is held, send grep content only for files that pass the name filter, and reject a search that would copy more than the text limit. - Fake runtime: count edit occurrences and build the diff without per-match or per-line arrays. - Normalize Windows drive paths in the fake runtime and path patterns, and restore original revisions on rollback. - Run: check the deadline before opening a transaction and word the pending-rollback warning accurately. Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
…untime Network-share (UNC) paths are not supported: POSIX resolution folds their leading `//` while protected-path patterns keep it, so a protected share could go unrecognized. The fixed root, seeded files, session cwd and roots, and call paths now refuse UNC paths before any call is prepared. Edit and write preparation now size the change from cheap counts first and refuse, before building the edited text or the diff, an edit with more than MAX_EDIT_REPLACEMENTS (50,000) replacements or a diff over MAX_DIFF_LINES (200,000) lines. Changes under the budget produce the same text and diff. Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
- The session roots are checked for network-share (UNC) paths even when a fixed root replaces them, so a UNC session root is refused, not ignored. - setFile and revision refuse UNC paths like every other path entry point. - The diff line budget counts the rows the diff actually has: a text that ends with a line break no longer counts one extra row. Edit preparation works out whether the edited text ends with one from where the replaced occurrences sit, still before building the text or the diff, so diffs of up to MAX_DIFF_LINES rows are prepared and only larger ones refused. Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
Keep POSIX paths with redundant leading slashes local. Return actionable guidance when an edit exceeds the replacement limit. Stop glob after its first extra match and skip setup for cancelled searches.
Match local protection patterns and resolved paths with the same leading-slash normalization. Use one resolved key for in-memory reads, writes and file revisions. Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
- Parent caps the bytes it reads from the child per run at 64 MiB (at least two frames), counted per chunk before parsing, and kills a child that sends more console output than the cap plus room for its truncation note. - Child refuses any frame, the first one included, that would push its unread stdout past a cap the parent sizes to hold one valid frame; the final outcome is written outside that cap. - WASM memory ceiling counts the build's initial allocation; memoryBytes below it is a typed oom. - Replies are sized exactly before JSON.stringify, so a reply over the remaining budget is never built; the final byte count stays exact. - Child read grants: entry directory and loaded package directories, plus exact package.json and node_modules lookup paths; one flag per path, wildcard for directories on Node 22.0-22.12, symlinks preserved. - One monotonic deadline from run entry; the parent checks it before handling each frame and before sending start. - start has its own size limit outside the reply quotas. - Concrete script errors stay errors when memory is near its ceiling; error name/message getters that throw are guarded. - Console formatting reads array items by descriptor and carries text as JSON so NUL survives. - Strict UTF-8 decoding of child frames; empty lines are rejected. - The QuickJS variant is checked for both loader functions before use. - The child environment test requires that the read happened. Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
- Check the run deadline right before forwarding a call or log, settling a result, sending a reply and writing start. - Classify an ambiguous script failure as oom only after a WASM memory growth failed, not from initial memory size. - Write child messages as UTF-8 buffers so the pending-output cap counts bytes. - Size JSON lines without building intermediate arrays; cover sparse arrays. - Validate dependency names and refuse unexpected package lookup entries and asterisk paths in read grants. - Process only whole frames within the input budget, independent of chunking. Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
|
NEEDS_HUMAN at The same three mechanisms need a design review after two rounds of fixes.
One full review and two confirmation rounds closed 12 distinct findings (3 blockers, 1 major, 8 minor). The fixes are in Added lines grew from 2,166 to 2,459, excluding 26 lockfile lines. Code grew from 1,300 to 1,457 and tests from 866 to 1,002. Documentation added zero lines. The local checks also covered the compiled sandbox on Node 22.0, 22.12 and 24. The three remaining edge cases were assessed through source review. The full suite ran in CI. Two follow-ups remain. Improve the test assertion for a tool reply after script intrinsics change and preserve boxed primitive values in JSON results. Other behavior choices noted in reviewThese choices apply to users and integrators when the server adopts the sandbox.
|
…ause Startup read grants: one lstat-based probe classifies every candidate as absent, a regular file, or anything else. Only absent entries and regular files get a grant; links (dangling or not), directories and other entries get none, so a dangling link is no longer granted as "missing". Run deadline: every write to the child (start, immediate replies and the queue flush) goes through one emit point that reads the monotonic clock right before stream.write, after measuring, encoding and dequeuing. Past the deadline nothing is written and the run ends through the existing timeout path. Out of memory is fatal: when every size the Emscripten glue tries for one growth request is refused, the child exits with OOM_EXIT_CODE from inside the refused growth, so no catch, finally or later statement of the script runs, and the parent reports oom. The persistent growth-failure flag no longer classifies later exceptions, so a script's own throw null or throw undefined stays a script error. Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
|
Decision recorded for the next review round (the owner decided on 2026-11-19): running out of memory is fatal. When the WASM memory growth is refused, the run ends as |
Reject unexpected entries covered by recursive grants and omit unrelated files from dependency lookups. Stop preparing replies at the deadline and honor it when the child reports an out-of-memory exit.
- The sandbox child writes each message to stdout synchronously, so an exit from inside a refused memory growth no longer drops calls and logs written before it. - The child-side pending output cap is gone, since nothing queues in the child any more. Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
|
MERGED to The review closed one major and six minor findings. The corrections narrow startup read grants, enforce the deadline during reply preparation and child exit, and preserve logs and tool calls emitted before fatal memory exhaustion. Correction commits were The PR grew from 2,700 to 2,775 added lines. Source grew from 1,519 to 1,535 lines and tests from 1,181 to 1,240. The count excludes the lockfile. All five GitHub Actions jobs passed, as did the local typecheck and targeted tests. The built sandbox started and returned a result on Node 22.0.0 and 22.12.0. CI run Two edge cases remain. An unusual dependency layout can prevent startup under the older Node 22 permission model. An engine rejection above its 2 GiB ceiling can still reach the script as a catchable error while the physical cap holds. The review checked these cases in source. Node 22.12 loader check |
Summary
Implements the
Sandboxcontract fromsrc/core/types.tswith QuickJS-ng (sync WASM build) inside a fresh, locked-down Node child process per run.sequenceDiagram participant D as Dispatcher (onCall) participant P as QuickJsSandbox / ChildSession (parent) participant C as child.ts (Node, --permission, env {}) participant VM as QuickJS-ng VM P->>C: start {code, timeoutMs, limits} C->>VM: shim + (async function () {code}) VM->>C: read({path}) -> deferred promise C->>P: call {id, tool, args JSON} P->>D: onCall(tool, args) D-->>P: CallReply P->>C: reply {id, reply} C->>VM: resolve/reject, executePendingJobs() VM->>C: done(result JSON) C->>P: done {outcome} P->>C: SIGKILL (always, never reused)Defense layers:
consoleandbash/read/write/edit/grep/glob. Norequire,importloader,process,fetch, timers,std/os;performance,DOMExceptionandqueueMicrotaskare deleted. Host natives are closure-captured, never globals.maximumof theWebAssembly.Memoryhanded to the variant (16 MiB base +memoryBytes).runtime.setMemoryLimitis still set, but it does not limit anything in this build (see Decisions).timeoutMs.drain), with bytes in flight and total bytes per run capped.{}(onlySystemRooton Windows; libuv on Windows still adds its required variables such asPATH,TEMPandUSERNAME, and macOS adds__CF_USER_TEXT_ENCODING),--max-old-space-size=256,--disallow-code-generation-from-strings, and--permissionwith fs reads limited to this package and its runtime deps (no writes, no child processes, no workers, no addons).killed. Nothing reachesonCall/onLogafter the outcome.Evidence
npm run verify: 144 tests pass (58 new insrc/sandbox), build emitsdist/sandbox/child.js, and a smoke run againstdist/works.awaiton a binding settled aftersetImmediate, andPromise.allof 50 calls resolved in reverse order. Both work on the sync build without asyncify.After (capped WASM memory):
oomin ~230 ms at 48 MiB of heap.quickjs-sandbox.test.ts,session.test.ts):typeofof 22 host names,new Function('return this')(),(0,eval)('this')(no non-standard globals),import('fs')andimport('node:child_process')reject/proc/<child>/environon Linuxnew Functionall failJSON/Promise.prototype.then: host prototypes intact,__proto__/constructorarrive as own keystimeoutwithin deadline + 1 s; three allocation bombs end asoom; deep recursion ends asRangeError; 10,000 calls: 2,000 forwarded, 8,000 rejected inside the VM; console spam and a 500k-char line are capped; a 5 MiB string andnew Array(1e8)returned end asResultTooLargeallSettledkeeps the run alivekilled, child pid gone within 1 s, the second call is never forwarded; a child is never reuseddist/build, N=30, median):return 1end to end: 140 ms (p90 149). Node with these flags starts in ~33 ms; loading zod, quickjs-emscripten and compiling the WASM adds ~73 ms.onCall: 139 ms.Merge Danger
Door: two-way
New folder only. Nothing imports it yet:
src/server/runtime.tsstill usesFakeSandbox, and the integrator switches it.Blast Radius: isolated
Adds two runtime dependencies,
quickjs-emscripten-coreand@jitl/quickjs-ng-wasmfile-release-sync(^0.32.0), with lockfile additions only. Each run spawns a ~140 ms child process.Decisions
memoryBytesplus the build's 16 MiB base. QuickJS-ng's own limit does not work in this build (it reports "malloc_usable_size unavailable" and undercounts large allocations). The alternative was relying onsetMemoryLimitas the brief says, which lets a script use ~2 GB.DEFAULT_MEMORY_BYTESin core), so the 128 MiB default from the brief only applies whenmemoryBytesis not a positive number.setTimeoutand friends are absent, and so isqueueMicrotask. A script that awaits a promise nothing can settle fails right away withDeadlockinstead of waiting for the timeout.ResultTooLargeinstead of returning a truncated value), 4 MiB of JSON args per call, 128 KiB VM stack, about 800 frames of plain recursion (the WASM build runs on the Node stack: 512 KiB crashed on Linux and 256 KiB on macOS with Node 22; a host stack overflow still ends the run as aRangeError), 256 MiB child heap."[Function: name]", symbols"Symbol(x)", BigInt"12n",NaN/Infinitythe string form, cycles"[Circular]", errors"Name: message", a throwing getter"[threw: msg]", more than 200 levels"[Too deep]".Map/Setfollow JSON ({}).Errors withname,code, plussourceandreasonforPermissionDenied. Thrown non-Errors become nameErrorwith the string itself orUncaught <inspected value>.consoleformatting is a small Node-like inspector (depth 2, 100 items, getters not run). No%sformat specifiers and noconsole.debug.--permission(Node 22.13+) or--experimental-permission(Node 22.0 to 22.12; one comma-separated read grant with the*wildcard, the only form those versions honor). On a Node with neither, every run endskilled(SandboxUnavailable) instead of running unrestricted.engines.nodestays>=22: every 22.x has one of the flags (checked on 22.0.0, 22.12.0, 24.0.0 and 26.13.0). The alternative was running without the permission model where it is missing.oom(ReplyBufferFull). The alternatives were failing only the binding call, or no cap.--disallow-code-generation-from-stringson the child.child.tswith Node type stripping in tests and fromchild.jsindist/. Sochild.tshas no runtime import of other project files and carries its own copy of the incoming-message schema.No contract change proposed.
🤖 Generated with Claude Code