Skip to content

QuickJS-ng WASM sandbox - #3

Merged
mths-mcfs merged 22 commits into
mainfrom
feat/sandbox
Nov 20, 2026
Merged

mths-mcfs merged 22 commits into
mainfrom
feat/sandbox

Conversation

@mths-mcfs

@mths-mcfs mths-mcfs commented Nov 15, 2026 •

Copy link
Copy Markdown
Owner

Summary

Implements the Sandbox contract from src/core/types.ts with 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)
Loading
src/sandbox/
├── quickjs-sandbox.ts   # spawn, child flags and env, timeout and cancel (SIGKILL)
├── session.ts           # parent side: NDJSON framing, zod validation, caps, outcome
├── protocol.ts          # child -> parent schemas, parent -> child types
├── child.ts             # VM host + in-VM shim (bindings, console, JSON conversion)
└── index.ts

Defense layers:

  • VM: only ECMAScript built-ins, console and bash/read/write/edit/grep/glob. No require, import loader, process, fetch, timers, std/os; performance, DOMException and queueMicrotask are deleted. Host natives are closure-captured, never globals.
  • Memory: the hard limit is the maximum of the WebAssembly.Memory handed to the variant (16 MiB base + memoryBytes). runtime.setMemoryLimit is still set, but it does not limit anything in this build (see Decisions).
  • CPU: an interrupt handler at the deadline (uncatchable), plus the parent's SIGKILL timer at timeoutMs.
  • Replies: written with backpressure (drain), with bytes in flight and total bytes per run capped.
  • Child process: env {} (only SystemRoot on Windows; libuv on Windows still adds its required variables such as PATH, TEMP and USERNAME, and macOS adds __CF_USER_TEXT_ENCODING), --max-old-space-size=256, --disallow-code-generation-from-strings, and --permission with fs reads limited to this package and its runtime deps (no writes, no child processes, no workers, no addons).
  • Parent: every child line is hostile until it passes the zod schema. An oversize line, invalid JSON, an unknown type, an extra field, an out-of-sequence or repeated call id, a call past the cap, or args/result that are not JSON all kill the child with outcome killed. Nothing reaches onCall/onLog after the outcome.

Evidence

  • npm run verify: 144 tests pass (58 new in src/sandbox), build emits dist/sandbox/child.js, and a smoke run against dist/ works.
  • Spike: await on a binding settled after setImmediate, and Promise.all of 50 calls resolved in reverse order. Both work on the sync build without asyncify.
  • Before (setMemoryLimit only, 32 MiB limit): a loop of 100 KB strings grew the WASM heap to 1.3 GB, with no error until the deadline.
    After (capped WASM memory): oom in ~230 ms at 48 MiB of heap.
  • Attack tests (quickjs-sandbox.test.ts, session.test.ts):
    • ambient authority: typeof of 22 host names, new Function('return this')(), (0,eval)('this') (no non-standard globals), import('fs') and import('node:child_process') reject
    • canary secret in the server env: absent from outcome, logs, call args and error messages, and absent from /proc/<child>/environ on Linux
    • child under the permission model: writing a file, spawning a process and new Function all fail
    • prototype pollution and overriding JSON/Promise.prototype.then: host prototypes intact, __proto__/constructor arrive as own keys
    • infinite loop (also one that catches every error) and a binding that never replies end as timeout within deadline + 1 s; three allocation bombs end as oom; deep recursion ends as RangeError; 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 and new Array(1e8) returned end as ResultTooLarge
    • 200 bindings answered in reverse order map to the right calls; a rejection inside allSettled keeps the run alive
    • abort during a pending binding: outcome killed, child pid gone within 1 s, the second call is never forwarded; a child is never reused
    • 24 crafted child messages fed to the parent handler
  • Measured (Intel i5-8350U, Linux x86_64, Node 26.13.0, dist/ build, N=30, median):
    • return 1 end 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.
    • Spawn to first onCall: 139 ms.
    • One binding round trip: 0.14 ms sequential, 0.105 ms each across 1,000 concurrent calls.

Merge Danger

Door: two-way

New folder only. Nothing imports it yet: src/server/runtime.ts still uses FakeSandbox, and the integrator switches it.

Blast Radius: isolated

Adds two runtime dependencies, quickjs-emscripten-core and @jitl/quickjs-ng-wasmfile-release-sync (^0.32.0), with lockfile additions only. Each run spawns a ~140 ms child process.

Decisions

  • Memory limit: the real heap cap is the WASM memory maximum, set to memoryBytes plus 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 on setMemoryLimit as the brief says, which lets a script use ~2 GB.
  • Default memory: the server passes 256 MiB (DEFAULT_MEMORY_BYTES in core), so the 128 MiB default from the brief only applies when memoryBytes is not a positive number.
  • No timers in v1: setTimeout and friends are absent, and so is queueMicrotask. A script that awaits a promise nothing can settle fails right away with Deadlock instead of waiting for the timeout.
  • Limits: 2,000 calls per run, 1 MiB of console output, 10,000 chars per console line, 1 MiB of returned JSON (beyond that the run fails with ResultTooLarge instead 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 a RangeError), 256 MiB child heap.
  • Return value conversion: functions become "[Function: name]", symbols "Symbol(x)", BigInt "12n", NaN/Infinity the string form, cycles "[Circular]", errors "Name: message", a throwing getter "[threw: msg]", more than 200 levels "[Too deep]". Map/Set follow JSON ({}).
  • Errors: binding failures become Errors with name, code, plus source and reason for PermissionDenied. Thrown non-Errors become name Error with the string itself or Uncaught <inspected value>.
  • console formatting is a small Node-like inspector (depth 2, 100 items, getters not run). No %s format specifiers and no console.debug.
  • Permission model is required: the child runs with --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 ends killed (SandboxUnavailable) instead of running unrestricted. engines.node stays >=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.
  • Network from the child process: Node's permission model blocks sockets only from Node 25. On Node 22 and 24 the child process could still open a socket if code escaped the QuickJS VM; there the VM itself is the only barrier against network access. The test asserts denial where Node supports it. The alternative was requiring Node 25+.
  • Reply buffering: results waiting for a script that stopped reading (e.g. it started calls and then spins) are capped at 16 MiB, and the results sent in one run at 512 MiB. Past either cap the run ends with outcome oom (ReplyBufferFull). The alternatives were failing only the binding call, or no cap.
  • --disallow-code-generation-from-strings on the child.
  • IPC uses newline-delimited JSON on the child's stdin/stdout instead of Node's built-in IPC channel, so the parent can bound a message's size before parsing it.
  • The child runs from child.ts with Node type stripping in tests and from child.js in dist/. So child.ts has no runtime import of other project files and carries its own copy of the incoming-message schema.
  • The child exits without disposing the QuickJS runtime. Disposing with live objects aborts the WASM module, and the process ends anyway.

No contract change proposed.

🤖 Generated with Claude Code

mths-mcfs and others added 6 commits November 15, 2026 02:30
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>
mths-mcfs and others added 10 commits November 18, 2026 21:51
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>
@mths-mcfs
mths-mcfs changed the base branch from feat/scaffold to main November 19, 2026 16:33
@mths-mcfs
mths-mcfs marked this pull request as ready for review November 19, 2026 16:36
mths-mcfs and others added 2 commits November 19, 2026 18:10
- 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>
@mths-mcfs

mths-mcfs commented Nov 19, 2026 •

Copy link
Copy Markdown
Owner Author

NEEDS_HUMAN at c8d1f1c. All five GitHub Actions jobs and the local typecheck passed.

The same three mechanisms need a design review after two rounds of fixes.

  • Startup read grants need to distinguish missing metadata from an existing entry whose target cannot be resolved.
  • Queued replies need the run deadline checked at the point of writing to the child.
  • Memory errors need to be attributed to the exception that ended the run. An earlier, handled allocation failure can still mask a later script error.

One full review and two confirmation rounds closed 12 distinct findings (3 blockers, 1 major, 8 minor). The fixes are in 147b193 and c8d1f1c.

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 review

These choices apply to users and integrators when the server adopts the sandbox.

  • Shell shorthand. A command may be passed as text, using default options. Restoring the object-only form would require scripts using the shorthand to change.
  • Unresolvable waits. Scripts with no way to settle a pending promise receive a deadlock error. Waiting for the deadline would change the result to a timeout.
  • Values outside JSON. Results describe functions, large integers and cycles in text. Changing the conversion would affect scripts that consume those descriptions.
  • Binding quotas. Scripts can send up to 2,000 calls and 4,194,304 JSON characters per call. Adjusting the quotas changes which operations callers can perform in one run.
  • Result size. A return value above 1,048,576 JSON characters ends the run with a size error. Raising the limit or changing delivery would let callers return more data.
  • Reply quotas. Excess queued or total tool replies end the run with a memory error. Changing enforcement would affect scripts that read or dispatch large amounts of data.
  • Console output. Logs use a compact format and truncate long lines or output above the budget. Changing the format or limits affects people debugging scripts and tools that parse their logs.
  • Startup memory. The interpreter's initial memory counts toward the requested limit. Integrators need at least 16 MiB. Supporting smaller budgets would require a different startup allocation or accounting design.
  • Child output budget. With the default settings, over 64 MiB of calls, logs and results ends the run with a memory error. A different budget would change how much output a script can send before stopping.

@mths-mcfs mths-mcfs added the review-loop:needs-human O loop de revisão precisa de uma pessoa para continuar label Nov 19, 2026
@mths-mcfs
mths-mcfs marked this pull request as draft November 19, 2026 21:52
…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>
@mths-mcfs

Copy link
Copy Markdown
Owner Author

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 oom and the script cannot catch it. A script's own throw null or throw undefined without a refused growth stays a script error. The other two recurring mechanisms (startup read grants, run deadline) were redesigned in the same commit. Follow-ups: package-directory links still get their grant on the link path under --preserve-symlinks; bundling the child as a self-contained module.

@mths-mcfs
mths-mcfs marked this pull request as ready for review November 19, 2026 22:28
@mths-mcfs mths-mcfs removed the review-loop:needs-human O loop de revisão precisa de uma pessoa para continuar label Nov 20, 2026
mths-mcfs and others added 2 commits November 20, 2026 05:21
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>
@mths-mcfs mths-mcfs added the review-loop:ready Revisão e verificações concluídas no head avaliado label Nov 20, 2026
@mths-mcfs
mths-mcfs merged commit c6a29ad into main Nov 20, 2026
6 checks passed
@mths-mcfs

Copy link
Copy Markdown
Owner Author

MERGED to main as c6a29ad after two confirmation rounds in the incremental episode. The reviewed head was b34bf5f.

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 926652e, 74d27cf, and b34bf5f.

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

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Labels

review-loop:ready Revisão e verificações concluídas no head avaliado

Projects

None yet

Development

Successfully merging this pull request may close these issues.

1 participant