diff --git a/package-lock.json b/package-lock.json index 596f70d..8dca43c 100644 --- a/package-lock.json +++ b/package-lock.json @@ -9,7 +9,9 @@ "version": "0.0.0", "license": "Apache-2.0", "dependencies": { + "@jitl/quickjs-ng-wasmfile-release-sync": "^0.32.0", "@modelcontextprotocol/sdk": "^1.32.2", + "quickjs-emscripten-core": "^0.32.0", "zod": "^4.6.7" }, "bin": { @@ -73,6 +75,21 @@ "hono": "^4 || ^5.0.0-0" } }, + "node_modules/@jitl/quickjs-ffi-types": { + "version": "0.32.0", + "resolved": "https://registry.npmjs.org/@jitl/quickjs-ffi-types/-/quickjs-ffi-types-0.32.0.tgz", + "integrity": "sha512-v9T+GQpmk43VDJ7d72sf0Nexhk+ArvtUihW27dy7lqAl0zBObFKtSBBIm5RBjwIhE8VwsPPm9PNuvPvNqLWUEg==", + "license": "MIT" + }, + "node_modules/@jitl/quickjs-ng-wasmfile-release-sync": { + "version": "0.32.0", + "resolved": "https://registry.npmjs.org/@jitl/quickjs-ng-wasmfile-release-sync/-/quickjs-ng-wasmfile-release-sync-0.32.0.tgz", + "integrity": "sha512-XAX2jjZWWh3M0YaRqi82xMKNW/gkF6mo3MpW3UY2cmVxnQai1JuboVsJQVoLU629iEL4XWvHtO4h5lo7NRnAcg==", + "license": "MIT", + "dependencies": { + "@jitl/quickjs-ffi-types": "0.32.0" + } + }, "node_modules/@jridgewell/resolve-uri": { "version": "3.1.3", "resolved": "https://registry.npmjs.org/@jridgewell/resolve-uri/-/resolve-uri-3.1.3.tgz", @@ -2235,6 +2252,15 @@ "url": "https://github.com/sponsors/ljharb" } }, + "node_modules/quickjs-emscripten-core": { + "version": "0.32.0", + "resolved": "https://registry.npmjs.org/quickjs-emscripten-core/-/quickjs-emscripten-core-0.32.0.tgz", + "integrity": "sha512-QFnPfjFey8EqknSrSxe1hZrf1/8z7/6s1QzGOmKo6++02r7QRRX7ZoyNaZh7JuVjWsVW87KnQrbZqnHkOAzUyg==", + "license": "MIT", + "dependencies": { + "@jitl/quickjs-ffi-types": "0.32.0" + } + }, "node_modules/range-parser": { "version": "1.3.0", "resolved": "https://registry.npmjs.org/range-parser/-/range-parser-1.3.0.tgz", diff --git a/package.json b/package.json index 1d1997d..dd7b34e 100644 --- a/package.json +++ b/package.json @@ -27,7 +27,9 @@ "bench": "node -e \"console.log('bench: not implemented yet')\"" }, "dependencies": { + "@jitl/quickjs-ng-wasmfile-release-sync": "^0.32.0", "@modelcontextprotocol/sdk": "^1.32.2", + "quickjs-emscripten-core": "^0.32.0", "zod": "^4.6.7" }, "devDependencies": { diff --git a/src/sandbox/child.ts b/src/sandbox/child.ts new file mode 100644 index 0000000..c85284a --- /dev/null +++ b/src/sandbox/child.ts @@ -0,0 +1,693 @@ +/** + * Sandbox child process. Started by `QuickJsSandbox` for exactly one run with + * a minimal env, then killed. It reads newline-delimited JSON from stdin + * (`start`, then `reply`s), runs the script in a QuickJS-ng WASM VM (sync + * build) and writes `call`, `log` and `done` messages to stdout. + * + * Inside the VM the script sees only standard ECMAScript built-ins, `console` + * and the async bindings. Each binding call creates a QuickJS deferred promise + * that this process settles when the parent replies; pending jobs are then + * drained until the script's promise settles. + * + * This file has no runtime import of other project files (only `import type`), + * so Node can run it from source with type stripping during tests. + */ +import { newQuickJSWASMModuleFromVariant, newVariant, type QuickJSContext, type QuickJSDeferredPromise, type QuickJSHandle, type QuickJSRuntime, type QuickJSSyncVariant, type QuickJSWASMModule } from 'quickjs-emscripten-core'; +import * as variantModule from '@jitl/quickjs-ng-wasmfile-release-sync'; +import { writeSync } from 'node:fs'; +import { z } from 'zod'; +import type { ChildMessage, SandboxLimits, StartMessage } from './protocol.js'; + +/** File name the script is compiled under; stack frames of the script carry it. */ +const SCRIPT_FILE = 'script.js'; +const SHIM_FILE = 'shim.js'; +const MAX_ERROR_CHARS = 10_000; +const WASM_PAGE_BYTES = 64 * 1024; + +/** The part of the WebAssembly API this file uses (the project's `lib` has no WebAssembly types). */ +interface WasmMemory { + grow(deltaPages: number): number; +} +declare const WebAssembly: { readonly Memory: new (descriptor: { initial: number; maximum: number }) => WasmMemory }; +/** Initial memory of the WASM build (its INITIAL_MEMORY, 16 MiB). */ +const INITIAL_PAGES = 256; +/** Largest memory the WASM build declares (2 GiB). */ +const MAX_PAGES = 32_768; +/** + * Exit code that tells the parent the engine ran out of memory. The child exits with it from inside + * the refused memory growth, so no message can follow; must equal `OOM_EXIT_CODE` in protocol.ts. + */ +const OOM_EXIT_CODE = 86; +/** + * Sizes the Emscripten glue tries per growth request before the allocation fails (its `_emscripten_resize_heap` + * retries with 20%, 10% and 5% of overgrowth); a success in between means the request was served. + */ +const GROW_ATTEMPTS = 3; + +// --------------------------------------------------------------------------- +// Incoming messages (from the parent). Validated even though the parent is the +// trusted side: a malformed message ends the process. +// --------------------------------------------------------------------------- + +const int = z.number().int().positive(); +const LimitsSchema = z.strictObject({ + memoryBytes: int, + stackBytes: int, + maxCalls: int, + maxLogBytes: int, + maxLogLineChars: int, + maxResultChars: int, + maxArgsChars: int, +}); +const BindingErrorSchema = z.strictObject({ + name: z.enum(['PermissionDenied', 'ToolError']), + message: z.string(), + code: z.string(), + source: z.string().optional(), +}); +const ParentMessageSchema = z.discriminatedUnion('type', [ + z.strictObject({ type: z.literal('start'), code: z.string(), timeoutMs: z.number().positive(), limits: LimitsSchema }), + z.strictObject({ + type: z.literal('reply'), + id: int, + reply: z.discriminatedUnion('ok', [ + z.strictObject({ ok: z.literal(true), value: z.unknown() }), + z.strictObject({ ok: z.literal(false), error: BindingErrorSchema }), + ]), + }), +]); +type IncomingMessage = z.infer; + +const retryWait = new Int32Array(new SharedArrayBuffer(4)); + +/** + * Writes a complete message to stdout before returning. The child can then exit during a memory growth + * failure without dropping earlier messages. If the pipe is full, the parent can still enforce its deadline. + */ +function writeMessage(message: ChildMessage): void { + const bytes = Buffer.from(`${JSON.stringify(message)}\n`, 'utf8'); + let offset = 0; + while (offset < bytes.length) { + try { + offset += writeSync(1, bytes, offset); + } catch (err) { + if (!(err instanceof Error && 'code' in err && err.code === 'EAGAIN')) fatal(`could not write to the parent: ${err instanceof Error ? err.message : String(err)}`); + Atomics.wait(retryWait, 0, 0, 1); + } + } +} + +/** Writes the final message and exits. */ +function exitWith(outcome: DoneOutcome): void { + writeMessage({ type: 'done', outcome }); + process.exit(0); +} + +function fatal(message: string): never { + process.stderr.write(`sandbox child: ${message}\n`); + process.exit(70); +} + +// --------------------------------------------------------------------------- +// In-VM shim. Evaluated before the script; its completion value is a function +// that receives the host natives (never exposed as globals), installs the +// bindings and `console`, and returns the runner. It captures the intrinsics +// it uses first, so a script that overrides `JSON.stringify` or +// `Promise.prototype.then` only breaks its own values. +// --------------------------------------------------------------------------- + +const SHIM = String.raw`(function (hostCall, hostLog, hostDone, maxResultChars, maxLogLineChars) { + 'use strict'; + var G = globalThis; + var stringify = JSON.stringify, parse = JSON.parse; + var apply = Reflect.apply; + var defineProperty = Object.defineProperty, getOwnPropertyDescriptor = Object.getOwnPropertyDescriptor; + var objectKeys = Object.keys, isArray = Array.isArray, numberIsFinite = Number.isFinite, objectIs = Object.is; + var promiseThen = Promise.prototype.then, promiseResolve = Promise.resolve, promiseReject = Promise.reject, PromiseCtor = Promise; + var ErrorCtor = Error, TypeErrorCtor = TypeError, StringCtor = String; + var symbolToString = Symbol.prototype.toString, stringSlice = String.prototype.slice, arrayJoin = Array.prototype.join; + var dateToISOString = Date.prototype.toISOString, DateCtor = Date, RegExpCtor = RegExp, MapCtor = Map, SetCtor = Set; + var regexpToString = RegExp.prototype.toString; + var mapForEach = Map.prototype.forEach, setForEach = Set.prototype.forEach; + var mapSize = getOwnPropertyDescriptor(Map.prototype, 'size').get, setSize = getOwnPropertyDescriptor(Set.prototype, 'size').get; + var identifier = /^[A-Za-z_$][A-Za-z0-9_$]*$/, regexpTest = RegExp.prototype.test; + + // Not ECMAScript: removed so the script sees only the standard library. + var extras = ['performance', 'DOMException', 'queueMicrotask']; + for (var x = 0; x < extras.length; x++) { try { delete G[extras[x]]; } catch (e) { /* keep going */ } } + + function push(list, item) { list[list.length] = item; } + function join(list, sep) { return apply(arrayJoin, list, [sep]); } + function cut(text, max) { return text.length > max ? apply(stringSlice, text, [0, max]) + '... [truncated]' : text; } + function isError(v) { try { return v instanceof ErrorCtor; } catch (e) { return false; } } + function safeString(v) { try { return StringCtor(v); } catch (e) { return '[unprintable value]'; } } + function fnName(f) { + try { var n = f.name; return typeof n === 'string' && n !== '' ? n : 'anonymous'; } catch (e) { return 'anonymous'; } + } + function messageOf(e) { try { return isError(e) ? safeString(e.message) : safeString(e); } catch (x) { return 'unknown error'; } } + function define(name, value) { defineProperty(G, name, { value: value, writable: true, enumerable: false, configurable: true }); } + + // ---- console: Node-like formatting, without running getters -------------- + function inspect(v, depth, seen, top) { + switch (typeof v) { + case 'string': return top ? v : "'" + v + "'"; + case 'number': return objectIs(v, -0) ? '-0' : StringCtor(v); + case 'bigint': return StringCtor(v) + 'n'; + case 'boolean': case 'undefined': return StringCtor(v); + case 'symbol': return apply(symbolToString, v, []); + case 'function': return '[Function: ' + fnName(v) + ']'; + } + if (v === null) return 'null'; + try { + for (var s = 0; s < seen.length; s++) if (seen[s] === v) return '[Circular]'; + if (isError(v)) return safeString(v.name) + ': ' + safeString(v.message); + if (v instanceof DateCtor) { try { return apply(dateToISOString, v, []); } catch (e) { return 'Invalid Date'; } } + if (v instanceof RegExpCtor) return apply(regexpToString, v, []); + var parts = []; + push(seen, v); + if (v instanceof MapCtor) { + if (depth > 2) { seen.length--; return '[Map]'; } + apply(mapForEach, v, [function (val, key) { push(parts, inspect(key, depth + 1, seen, false) + ' => ' + inspect(val, depth + 1, seen, false)); }]); + seen.length--; + return 'Map(' + apply(mapSize, v, []) + ') {' + (parts.length ? ' ' + join(parts, ', ') + ' ' : '') + '}'; + } + if (v instanceof SetCtor) { + if (depth > 2) { seen.length--; return '[Set]'; } + apply(setForEach, v, [function (val) { push(parts, inspect(val, depth + 1, seen, false)); }]); + seen.length--; + return 'Set(' + apply(setSize, v, []) + ') {' + (parts.length ? ' ' + join(parts, ', ') + ' ' : '') + '}'; + } + if (isArray(v)) { + if (depth > 2) { seen.length--; return '[Array]'; } + var n = v.length, shown = n > 100 ? 100 : n; + for (var i = 0; i < shown; i++) { + var item = getOwnPropertyDescriptor(v, i); + push(parts, item === undefined ? 'undefined' : 'value' in item ? inspect(item.value, depth + 1, seen, false) : '[Getter/Setter]'); + } + if (n > shown) push(parts, '... ' + (n - shown) + ' more items'); + seen.length--; + return parts.length ? '[ ' + join(parts, ', ') + ' ]' : '[]'; + } + if (depth > 2) { seen.length--; return '[Object]'; } + var keys = objectKeys(v), shownKeys = keys.length > 100 ? 100 : keys.length; + for (var k = 0; k < shownKeys; k++) { + var key = keys[k], d = getOwnPropertyDescriptor(v, key); + var label = apply(regexpTest, identifier, [key]) ? key : "'" + key + "'"; + var shownValue = d === undefined ? 'undefined' : 'value' in d ? inspect(d.value, depth + 1, seen, false) : '[Getter/Setter]'; + push(parts, label + ': ' + shownValue); + } + if (keys.length > shownKeys) push(parts, '... ' + (keys.length - shownKeys) + ' more properties'); + seen.length--; + return parts.length ? '{ ' + join(parts, ', ') + ' }' : '{}'; + } catch (e) { + return '[uninspectable: ' + messageOf(e) + ']'; + } + } + function logger(level) { + return function () { + var parts = []; + for (var i = 0; i < arguments.length; i++) push(parts, inspect(arguments[i], 0, [], true)); + // JSON text: the native side reads strings up to the first NUL character. + hostLog(level, stringify(cut(join(parts, ' '), maxLogLineChars))); + }; + } + define('console', { log: logger('log'), info: logger('info'), warn: logger('warn'), error: logger('error') }); + + // ---- bindings ----------------------------------------------------------- + function bindingError(text) { + var info; + try { info = parse(text); } catch (e) { info = { name: 'ToolError', message: 'invalid binding error', code: 'tool-error' }; } + var err = new ErrorCtor(safeString(info.message)); + defineProperty(err, 'name', { value: safeString(info.name), writable: true, enumerable: false, configurable: true }); + defineProperty(err, 'code', { value: safeString(info.code), writable: true, enumerable: true, configurable: true }); + if (info.source !== undefined) { + defineProperty(err, 'source', { value: safeString(info.source), writable: true, enumerable: true, configurable: true }); + defineProperty(err, 'reason', { value: safeString(info.message), writable: true, enumerable: true, configurable: true }); + } + return err; + } + function invoke(tool, arg) { + var json; + try { json = stringify(arg); } catch (e) { + return apply(promiseReject, PromiseCtor, [new TypeErrorCtor(tool + ': the argument is not JSON-serializable: ' + messageOf(e))]); + } + if (json === undefined) json = 'null'; + return apply(promiseThen, hostCall(tool, json), [function (text) { return parse(text); }, function (text) { throw bindingError(text); }]); + } + var bindings = { + bash: function bash(arg) { return invoke('bash', typeof arg === 'string' ? { command: arg } : arg); }, + read: function read(arg) { return invoke('read', arg); }, + write: function write(arg) { return invoke('write', arg); }, + edit: function edit(arg) { return invoke('edit', arg); }, + grep: function grep(arg) { return invoke('grep', arg); }, + glob: function glob(arg) { return invoke('glob', arg); }, + }; + var names = objectKeys(bindings); + for (var b = 0; b < names.length; b++) define(names[b], bindings[names[b]]); + + // ---- return value: JSON, with non-JSON values described ----------------- + var tooLarge = {}; + function serialize(root) { + var out = [], size = 0, stack = []; + function emit(text) { + size += text.length; + if (size > maxResultChars) throw tooLarge; + push(out, text); + } + function value(v, key, inArray, depth) { + try { + if (v !== null && (typeof v === 'object' || typeof v === 'bigint') && typeof v.toJSON === 'function') v = v.toJSON(key); + } catch (e) { + if (e === tooLarge) throw e; + emit(stringify('[toJSON threw: ' + messageOf(e) + ']')); + return; + } + switch (typeof v) { + case 'string': emit(stringify(v)); return; + case 'number': emit(numberIsFinite(v) ? stringify(v) : stringify(StringCtor(v))); return; + case 'boolean': emit(v ? 'true' : 'false'); return; + case 'undefined': emit(inArray || depth === 0 ? 'null' : '"[undefined]"'); return; + case 'bigint': emit(stringify(StringCtor(v) + 'n')); return; + case 'symbol': emit(stringify(apply(symbolToString, v, []))); return; + case 'function': emit(stringify('[Function: ' + fnName(v) + ']')); return; + } + if (v === null) { emit('null'); return; } + for (var s = 0; s < stack.length; s++) if (stack[s] === v) { emit('"[Circular]"'); return; } + if (depth >= 200) { emit('"[Too deep]"'); return; } + try { + if (isError(v)) { emit(stringify(safeString(v.name) + ': ' + safeString(v.message))); return; } + push(stack, v); + if (isArray(v)) { + emit('['); + for (var i = 0, n = v.length; i < n; i++) { + if (i > 0) emit(','); + var item; + try { item = v[i]; } catch (e) { if (e === tooLarge) throw e; item = '[threw: ' + messageOf(e) + ']'; } + value(item, StringCtor(i), true, depth + 1); + } + emit(']'); + } else { + var keys = objectKeys(v), first = true; + emit('{'); + for (var k = 0; k < keys.length; k++) { + var prop; + try { prop = v[keys[k]]; } catch (e) { if (e === tooLarge) throw e; prop = '[threw: ' + messageOf(e) + ']'; } + if (prop === undefined) continue; + if (!first) emit(','); + first = false; + emit(stringify(keys[k]) + ':'); + value(prop, keys[k], false, depth + 1); + } + emit('}'); + } + stack.length--; + } catch (e) { + if (e === tooLarge) throw e; + throw new TypeErrorCtor('the return value cannot be serialized: ' + messageOf(e)); + } + } + value(root, '', false, 0); + return join(out, ''); + } + + // ---- runner --------------------------------------------------------------- + function readProp(o, key, fallback) { try { return o[key]; } catch (x) { return fallback; } } + function errorInfo(e) { + var info; + if (isError(e)) { + var stack = readProp(e, 'stack', undefined); + info = { name: safeString(readProp(e, 'name', 'Error')), message: safeString(readProp(e, 'message', '[unreadable message]')) }; + if (typeof stack === 'string') info.stack = stack; + } else { + info = { name: 'Error', message: typeof e === 'string' ? e : 'Uncaught ' + inspect(e, 0, [], false) }; + } + return stringify(info); + } + return function run(fn) { + var started; + try { started = typeof fn === 'function' ? fn() : fn; } catch (e) { hostDone('E' + errorInfo(e)); return; } + apply(promiseThen, apply(promiseResolve, PromiseCtor, [started]), [ + function (v) { + var text; + try { text = serialize(v); } catch (e) { + if (e === tooLarge) { + hostDone('E' + stringify({ name: 'ResultTooLarge', message: 'the return value is larger than ' + maxResultChars + ' characters of JSON; return less data' })); + return; + } + hostDone('E' + errorInfo(e)); + return; + } + hostDone('R' + text); + }, + function (e) { hostDone('E' + errorInfo(e)); }, + ]); + }; +})`; + +// --------------------------------------------------------------------------- +// One run. +// --------------------------------------------------------------------------- + +type DoneOutcome = Extract['outcome']; + +interface ErrorInfo { + readonly name: string; + readonly message: string; + readonly stack?: string; +} + +const LooseErrorSchema = z.object({ name: z.string(), message: z.string(), stack: z.string().optional() }); + +/** Keeps only the stack frames of the script itself. */ +function trimStack(stack: string | undefined): string | undefined { + if (stack === undefined) return undefined; + const frames = stack.split('\n').filter((line) => line.includes(`${SCRIPT_FILE}:`)); + return frames.length > 0 ? frames.join('\n').slice(0, MAX_ERROR_CHARS) : undefined; +} + +function toErrorInfo(raw: unknown): ErrorInfo { + const parsed = LooseErrorSchema.safeParse(raw); + if (!parsed.success) return { name: 'Error', message: typeof raw === 'string' ? raw.slice(0, MAX_ERROR_CHARS) : 'unknown error' }; + const stack = trimStack(parsed.data.stack); + const base = { name: parsed.data.name.slice(0, 200), message: parsed.data.message.slice(0, MAX_ERROR_CHARS) }; + return stack === undefined ? base : { ...base, stack }; +} + +function isOutOfMemory(info: ErrorInfo): boolean { + return /out of memory/i.test(info.message); +} + +/** + * The variant package's types describe its CommonJS entry, while Node loads + * its ESM entry, whose default export is the variant itself. Checked at + * runtime instead of cast. + */ +function syncVariant(candidate: unknown): QuickJSSyncVariant { + if (typeof candidate === 'object' && candidate !== null && 'type' in candidate && candidate.type === 'sync' && 'importFFI' in candidate && 'importModuleLoader' in candidate) { + if (typeof candidate.importFFI === 'function' && typeof candidate.importModuleLoader === 'function') return candidate as QuickJSSyncVariant; + } + if (typeof candidate === 'object' && candidate !== null && 'default' in candidate) return syncVariant(candidate.default); + throw new Error('the QuickJS variant package did not load as expected'); +} + +/** + * Makes running out of memory fatal for the run. QuickJS-ng's own accounting (`runtime.setMemoryLimit`) undercounts + * in this WASM build because `malloc_usable_size` is unavailable, so the hard limit is the maximum of the WebAssembly + * memory itself. When every size the glue tries for one growth request is refused, + * the allocation is about to fail and the engine would throw into the script (an InternalError, or `null` when it + * cannot even build one). Instead the process exits right here, inside the refused growth: control never returns to + * the WASM code, so no catch, finally or later statement of the script runs. QuickJS's interrupt handler cannot do + * this: the engine polls it once every 10,000 interrupt points, long after a catch block has run. + */ +function exitOnRefusedGrowth(memory: WasmMemory): void { + const grow = memory.grow.bind(memory); + let refused = 0; + memory.grow = (deltaPages) => { + try { + const previous = grow(deltaPages); + refused = 0; + return previous; + } catch (err) { + refused++; + if (refused >= GROW_ATTEMPTS) process.exit(OOM_EXIT_CODE); + throw err; + } + }; +} + +/** Pages of WASM memory a run may use: all of it, initial memory included, fits in `memoryBytes`. */ +function memoryPages(memoryBytes: number): number { + return Math.min(MAX_PAGES, Math.floor(memoryBytes / WASM_PAGE_BYTES)); +} + +class VmRun { + readonly #rt: QuickJSRuntime; + readonly #ctx: QuickJSContext; + readonly #limits: SandboxLimits; + readonly #deadline: number; + readonly #pending = new Map(); + readonly #timer: NodeJS.Timeout; + #nextId = 1; + #logBytes = 0; + #logCapped = false; + #done = false; + + constructor(qjs: QuickJSWASMModule, start: StartMessage) { + this.#limits = start.limits; + this.#deadline = Date.now() + start.timeoutMs; + this.#rt = qjs.newRuntime(); + this.#rt.setMemoryLimit(start.limits.memoryBytes); + this.#rt.setMaxStackSize(start.limits.stackBytes); + // Also stops a script that keeps running after the run ended, so the final message can flush. + this.#rt.setInterruptHandler(() => this.#done || Date.now() > this.#deadline); + this.#ctx = this.#rt.newContext(); + this.#timer = setTimeout(() => this.#finish({ ok: false, kind: 'timeout', error: { name: 'Timeout', message: `the script did not finish within ${start.timeoutMs} ms` } }), start.timeoutMs); + } + + begin(code: string): void { + try { + this.#begin(code); + } catch (err) { + this.#hostFailure(err); + } + } + + #begin(code: string): void { + const ctx = this.#ctx; + const shim = ctx.evalCode(SHIM, SHIM_FILE, { type: 'global' }); + if (shim.error) return this.#fail(shim.error); + const natives = [this.#callNative(), this.#logNative(), this.#doneNative(), ctx.newNumber(this.#limits.maxResultChars), ctx.newNumber(this.#limits.maxLogLineChars)]; + const runner = ctx.callFunction(shim.value, ctx.undefined, natives); + shim.value.dispose(); + for (const handle of natives) handle.dispose(); + if (runner.error) return this.#fail(runner.error); + + const compiled = ctx.evalCode(`(async function () {${code}\n})`, SCRIPT_FILE, { type: 'global' }); + if (compiled.error) { + runner.value.dispose(); + return this.#fail(compiled.error); + } + const started = ctx.callFunction(runner.value, ctx.undefined, compiled.value); + runner.value.dispose(); + compiled.value.dispose(); + if (started.error) return this.#fail(started.error); + started.value.dispose(); + this.#drain(); + } + + reply(message: Extract): void { + try { + this.#reply(message); + } catch (err) { + this.#hostFailure(err); + } + } + + #reply(message: Extract): void { + if (this.#done) return; + const deferred = this.#pending.get(message.id); + if (!deferred) return; + this.#pending.delete(message.id); + const { reply } = message; + const text = (reply.ok ? JSON.stringify(reply.value) : JSON.stringify(reply.error)) ?? 'null'; + const handle = this.#ctx.newString(text); + if (reply.ok) deferred.resolve(handle); + else deferred.reject(handle); + handle.dispose(); + deferred.dispose(); + this.#drain(); + } + + #callNative(): QuickJSHandle { + const ctx = this.#ctx; + return ctx.newFunction('call', (toolHandle, argsHandle) => { + const tool = ctx.getString(toolHandle); + const args = ctx.getString(argsHandle); + const deferred = ctx.newPromise(); + const handle = deferred.handle.dup(); + if (this.#done) { + this.#refuse(deferred, 'cancelled', 'the run has ended'); + } else if (this.#nextId > this.#limits.maxCalls) { + this.#refuse(deferred, 'tool-error', `binding call limit reached: a run may make at most ${this.#limits.maxCalls} calls`); + } else if (args.length > this.#limits.maxArgsChars) { + this.#refuse(deferred, 'invalid-args', `the arguments of ${tool} are larger than ${this.#limits.maxArgsChars} characters of JSON`); + } else { + const id = this.#nextId++; + this.#pending.set(id, deferred); + writeMessage({ type: 'call', id, tool, args }); + } + return handle; + }); + } + + #refuse(deferred: QuickJSDeferredPromise, code: string, message: string): void { + const handle = this.#ctx.newString(JSON.stringify({ name: 'ToolError', code, message })); + deferred.reject(handle); + handle.dispose(); + deferred.dispose(); + } + + #logNative(): QuickJSHandle { + const ctx = this.#ctx; + return ctx.newFunction('log', (levelHandle, textHandle) => { + if (this.#logCapped || this.#done) return; + const rawLevel = ctx.getString(levelHandle); + const level = rawLevel === 'info' || rawLevel === 'warn' || rawLevel === 'error' ? rawLevel : 'log'; + let decoded: unknown; + try { + decoded = JSON.parse(ctx.getString(textHandle)); + } catch { + return; + } + if (typeof decoded !== 'string') return; + let text = decoded; + if (text.length > this.#limits.maxLogLineChars) text = `${text.slice(0, this.#limits.maxLogLineChars)}... [truncated]`; + const bytes = Buffer.byteLength(text, 'utf8') + 1; + if (this.#logBytes + bytes > this.#limits.maxLogBytes) { + this.#logCapped = true; + writeMessage({ type: 'log', level: 'warn', text: `[console output truncated: the limit of ${this.#limits.maxLogBytes} bytes was reached]` }); + return; + } + this.#logBytes += bytes; + writeMessage({ type: 'log', level, text }); + }); + } + + #doneNative(): QuickJSHandle { + const ctx = this.#ctx; + return ctx.newFunction('done', (textHandle) => { + const text = ctx.getString(textHandle); + if (text.startsWith('R')) { + const value = text.slice(1); + if (value.length > this.#limits.maxResultChars) { + return this.#finish({ ok: false, kind: 'error', error: { name: 'ResultTooLarge', message: `the return value is larger than ${this.#limits.maxResultChars} characters of JSON; return less data` } }); + } + return this.#finish({ ok: true, value }); + } + let raw: unknown; + try { + raw = JSON.parse(text.slice(1)); + } catch { + raw = 'the script failed with an unreadable error'; + } + const info = toErrorInfo(raw); + // An explicit memory error with no refused growth behind it (e.g. one allocation over the QuickJS limit). + if (info.name === 'InternalError' && isOutOfMemory(info)) return this.#finish({ ok: false, kind: 'oom', error: info }); + this.#finish({ ok: false, kind: 'error', error: info }); + }); + } + + #drain(): void { + if (this.#done) return; + const jobs = this.#rt.executePendingJobs(); + if (jobs.error) return this.#fail(jobs.error); + jobs.dispose(); + if (!this.#done && this.#pending.size === 0 && !this.#rt.hasPendingJob()) { + this.#finish({ + ok: false, + kind: 'error', + error: { name: 'Deadlock', message: 'the script is waiting for a promise that nothing can settle (there are no timers and no pending binding calls)' }, + }); + } + } + + /** The VM threw past the shim: an interrupt (deadline), out of memory, a syntax error or a shim failure. */ + #fail(errorHandle: QuickJSHandle): void { + let raw: unknown; + try { + raw = this.#ctx.dump(errorHandle); + } catch { + raw = 'out of memory'; + } + try { + errorHandle.dispose(); + } catch { + // The process exits after the run; a leaked handle does not matter then. + } + const info = toErrorInfo(raw); + if (Date.now() > this.#deadline || info.message === 'interrupted') { + return this.#finish({ ok: false, kind: 'timeout', error: { name: 'Timeout', message: 'the script did not finish within its time limit' } }); + } + this.#finish({ ok: false, kind: isOutOfMemory(info) ? 'oom' : 'error', error: info }); + } + + /** A host-side exception (e.g. a WASM trap when an allocation inside the bindings layer fails). */ + #hostFailure(err: unknown): void { + const message = err instanceof Error ? err.message : String(err); + // Deep recursion that outruns the Node stack before QuickJS's own check: the run ends, as a script error. + if (err instanceof RangeError && /call stack/i.test(message)) { + return this.#finish({ ok: false, kind: 'error', error: { name: 'RangeError', message: 'Maximum call stack size exceeded' } }); + } + const oom = /out of memory/i.test(message); + this.#finish({ ok: false, kind: oom ? 'oom' : 'error', error: { name: oom ? 'InternalError' : 'SandboxError', message: oom ? 'out of memory' : message.slice(0, MAX_ERROR_CHARS) } }); + } + + /** + * Sends the outcome and exits. The runtime is not disposed: the process + * ends here, and disposing a runtime with live objects aborts the WASM + * module instead of returning. + */ + #finish(outcome: DoneOutcome): void { + if (this.#done) return; + this.#done = true; + clearTimeout(this.#timer); + exitWith(outcome); + } +} + +// --------------------------------------------------------------------------- +// Main: read stdin lines, start on the first `start`, route replies. +// --------------------------------------------------------------------------- + +let run: VmRun | undefined; +let started = false; +const early: Extract[] = []; +let buffered = ''; + +function onMessage(message: IncomingMessage): void { + if (message.type === 'start') { + if (started) fatal('received a second start message'); + started = true; + const pages = memoryPages(message.limits.memoryBytes); + if (pages < INITIAL_PAGES) { + return exitWith({ ok: false, kind: 'oom', error: { name: 'InternalError', message: `memoryBytes ${message.limits.memoryBytes} is below the ${INITIAL_PAGES * WASM_PAGE_BYTES} bytes the QuickJS build needs` } }); + } + const memory = new WebAssembly.Memory({ initial: INITIAL_PAGES, maximum: pages }); + exitOnRefusedGrowth(memory); + newQuickJSWASMModuleFromVariant(newVariant(syncVariant(variantModule), { wasmMemory: memory })).then( + (qjs) => { + run = new VmRun(qjs, message); + run.begin(message.code); + for (const reply of early.splice(0)) run.reply(reply); + }, + (err: unknown) => fatal(`could not load QuickJS: ${err instanceof Error ? err.message : String(err)}`), + ); + return; + } + if (run) run.reply(message); + else early.push(message); +} + +process.stdin.setEncoding('utf8'); +process.stdin.on('data', (chunk: string) => { + buffered += chunk; + let nl = buffered.indexOf('\n'); + while (nl !== -1) { + const line = buffered.slice(0, nl); + buffered = buffered.slice(nl + 1); + if (line.trim() !== '') { + let raw: unknown; + try { + raw = JSON.parse(line); + } catch { + fatal('received a message that is not JSON'); + } + const parsed = ParentMessageSchema.safeParse(raw); + if (!parsed.success) fatal('received an invalid message'); + onMessage(parsed.data); + } + nl = buffered.indexOf('\n'); + } +}); +// The parent went away: nothing can reply any more. +process.stdin.on('end', () => process.exit(0)); diff --git a/src/sandbox/index.ts b/src/sandbox/index.ts new file mode 100644 index 0000000..dcdd065 --- /dev/null +++ b/src/sandbox/index.ts @@ -0,0 +1 @@ +export { QuickJsSandbox, DEFAULT_SANDBOX_MEMORY_BYTES, type QuickJsSandboxOptions } from './quickjs-sandbox.js'; diff --git a/src/sandbox/protocol.ts b/src/sandbox/protocol.ts new file mode 100644 index 0000000..92fd395 --- /dev/null +++ b/src/sandbox/protocol.ts @@ -0,0 +1,94 @@ +/** + * Wire protocol between the sandbox parent (server process) and the sandbox + * child process. Messages are newline-delimited JSON: parent → child on the + * child's stdin, child → parent on the child's stdout. + * + * Each side validates what it receives. This file holds the parent side: the + * schemas of child messages (the child is treated as hostile) and the types + * of the messages the parent sends. The child (`child.ts`) has no runtime + * import of this file, so it can run from source with Node type stripping. + */ +import { z } from 'zod'; +import type { CallReply } from '../core/types.js'; + +/** + * Exit code of a child whose engine ran out of memory: it exits from inside the refused memory growth, before any + * more script code runs, so no `done` message comes. Must equal `OOM_EXIT_CODE` in child.ts. + */ +export const OOM_EXIT_CODE = 86; + +/** Limits of one run, sent to the child in the `start` message. */ +export interface SandboxLimits { + /** Ceiling of the WASM memory of the run, the memory the QuickJS build allocates up front included. */ + readonly memoryBytes: number; + /** QuickJS stack limit (`runtime.setMaxStackSize`). */ + readonly stackBytes: number; + /** Maximum binding calls per run; later calls reject inside the VM. */ + readonly maxCalls: number; + /** Maximum total console bytes per run; later lines are dropped. */ + readonly maxLogBytes: number; + /** Maximum length of one console line, in characters. */ + readonly maxLogLineChars: number; + /** Maximum length of the JSON-serialized return value, in characters. */ + readonly maxResultChars: number; + /** Maximum length of the JSON-serialized arguments of one call, in characters. */ + readonly maxArgsChars: number; +} + +/** First message of a run: what to execute and with which limits. */ +export interface StartMessage { + readonly type: 'start'; + readonly code: string; + /** Wall-clock budget left for the script when the message was sent. */ + readonly timeoutMs: number; + readonly limits: SandboxLimits; +} + +/** Answer to one binding call. */ +export interface ReplyMessage { + readonly type: 'reply'; + readonly id: number; + readonly reply: CallReply; +} + +export type ParentMessage = StartMessage | ReplyMessage; + +/** Longest tool name a child may send. Real names are at most 5 characters. */ +export const MAX_TOOL_NAME_CHARS = 64; + +const ScriptErrorSchema = z.strictObject({ + name: z.string().max(1_000), + message: z.string().max(100_000), + stack: z.string().max(100_000).optional(), +}); + +/** + * Schema of child → parent messages, built for the limits of one run so that + * every string field is bounded. + */ +export function childMessageSchema(limits: SandboxLimits) { + return z.discriminatedUnion('type', [ + z.strictObject({ + type: z.literal('call'), + id: z.number().int().min(1), + tool: z.string().max(MAX_TOOL_NAME_CHARS), + /** JSON text of the arguments. */ + args: z.string().max(limits.maxArgsChars), + }), + z.strictObject({ + type: z.literal('log'), + level: z.enum(['log', 'info', 'warn', 'error']), + text: z.string().max(limits.maxLogLineChars + 200), + }), + z.strictObject({ + type: z.literal('done'), + outcome: z.discriminatedUnion('ok', [ + /** `value` is the JSON text of the return value. */ + z.strictObject({ ok: z.literal(true), value: z.string().max(limits.maxResultChars) }), + z.strictObject({ ok: z.literal(false), kind: z.enum(['error', 'timeout', 'oom']), error: ScriptErrorSchema }), + ]), + }), + ]); +} + +export type ChildMessage = z.infer>; diff --git a/src/sandbox/quickjs-sandbox.test.ts b/src/sandbox/quickjs-sandbox.test.ts new file mode 100644 index 0000000..229e792 --- /dev/null +++ b/src/sandbox/quickjs-sandbox.test.ts @@ -0,0 +1,800 @@ +import { spawn } from 'node:child_process'; +import { existsSync, mkdirSync, mkdtempSync, readFileSync, rmSync, symlinkSync, writeFileSync } from 'node:fs'; +import { createServer } from 'node:net'; +import { tmpdir } from 'node:os'; +import { dirname, join } from 'node:path'; +import { afterEach, beforeEach, describe, expect, it } from 'vitest'; +import type { CallReply, LogLevel, SandboxOutcome, ToolResult } from '../core/types.js'; +import { childEntryPath, childEnv, childExecArgv, permissionFlag, QuickJsSandbox, readGrants, SandboxUnavailableError, type QuickJsSandboxOptions } from './quickjs-sandbox.js'; + +interface Recorded { + readonly outcome: SandboxOutcome; + readonly calls: { tool: string; args: unknown }[]; + readonly logs: { level: LogLevel; text: string }[]; + readonly elapsedMs: number; +} + +type OnCall = (tool: string, args: unknown, index: number) => Promise; + +/** Every binding call succeeds with `{tool, args}` after a host turn. */ +const echo: OnCall = async (tool, args) => { + await new Promise((resolve) => setImmediate(resolve)); + return ok({ tool, args }); +}; + +/** Test replies carry arbitrary data; the sandbox forwards any JSON value. */ +function ok(value: unknown): CallReply { + return { ok: true, value: value as ToolResult }; +} + +async function run( + code: string, + options: { onCall?: OnCall; timeoutMs?: number; memoryBytes?: number; signal?: AbortSignal; sandbox?: QuickJsSandboxOptions } = {}, +): Promise { + const sandbox = new QuickJsSandbox(options.sandbox); + const calls: Recorded['calls'] = []; + const logs: Recorded['logs'] = []; + const onCall = options.onCall ?? echo; + const started = Date.now(); + const outcome = await sandbox.run(code, { + timeoutMs: options.timeoutMs ?? 10_000, + memoryBytes: options.memoryBytes ?? 64 * 1024 * 1024, + signal: options.signal ?? new AbortController().signal, + onCall: (tool, args) => { + calls.push({ tool, args }); + return onCall(tool, args, calls.length - 1); + }, + onLog: (level, text) => logs.push({ level, text }), + }); + return { outcome, calls, logs, elapsedMs: Date.now() - started }; +} + +function value(outcome: SandboxOutcome): unknown { + if (!outcome.ok) throw new Error(`expected ok, got ${outcome.kind}: ${outcome.error.name}: ${outcome.error.message}`); + return outcome.value; +} + +function failure(outcome: SandboxOutcome): Extract { + if (outcome.ok) throw new Error(`expected a failure, got ${JSON.stringify(outcome.value)}`); + return outcome; +} + +function processGone(pid: number): boolean { + try { + process.kill(pid, 0); + return false; + } catch { + return true; + } +} + +describe('QuickJsSandbox: script semantics', () => { + it('runs the code as an async function body and returns JSON', async () => { + const { outcome } = await run('const a = [1, 2, 3]; return { sum: a.reduce((x, y) => x + y, 0), s: "ok", n: null, b: true };'); + expect(value(outcome)).toEqual({ sum: 6, s: 'ok', n: null, b: true }); + }); + + it('returns null when the script returns nothing', async () => { + expect(value((await run('const x = 1;')).outcome)).toBeNull(); + }); + + it('normalizes binding arguments to the contract shapes', async () => { + const { outcome, calls } = await run(` + await bash('ls -la'); + await bash({ command: 'pwd', cwd: 'src', timeoutMs: 5 }); + await read({ path: 'a.txt', offset: 2, limit: 3 }); + await write({ path: 'b.txt', content: 'x' }); + await edit({ path: 'b.txt', oldString: 'x', newString: 'y', replaceAll: true }); + await grep({ pattern: 'TODO', glob: '*.ts', ignoreCase: true }); + await glob({ pattern: '**/*.ts', maxResults: 10 }); + return 'done'; + `); + expect(value(outcome)).toBe('done'); + expect(calls).toEqual([ + { tool: 'bash', args: { command: 'ls -la' } }, + { tool: 'bash', args: { command: 'pwd', cwd: 'src', timeoutMs: 5 } }, + { tool: 'read', args: { path: 'a.txt', offset: 2, limit: 3 } }, + { tool: 'write', args: { path: 'b.txt', content: 'x' } }, + { tool: 'edit', args: { path: 'b.txt', oldString: 'x', newString: 'y', replaceAll: true } }, + { tool: 'grep', args: { pattern: 'TODO', glob: '*.ts', ignoreCase: true } }, + { tool: 'glob', args: { pattern: '**/*.ts', maxResults: 10 } }, + ]); + }); + + it('passes the binding result into the script', async () => { + const { outcome } = await run('const r = await read({ path: "x" }); return r.args.path + ":" + r.tool;'); + expect(value(outcome)).toBe('x:read'); + }); + + it('rehydrates binding errors as Error objects the script can catch', async () => { + const { outcome } = await run( + ` + const out = []; + for (const path of ['denied', 'missing']) { + try { await read({ path }); } catch (e) { + out.push({ isError: e instanceof Error, name: e.name, message: e.message, code: e.code, source: e.source ?? null, reason: e.reason ?? null }); + } + } + return out; + `, + { + onCall: async (_tool, args, index) => + index === 0 + ? { ok: false, error: { name: 'PermissionDenied', code: 'denied', source: 'hook', message: `blocked ${JSON.stringify(args)}` } } + : { ok: false, error: { name: 'ToolError', code: 'not-found', message: 'no such file' } }, + }, + ); + expect(value(outcome)).toEqual([ + { isError: true, name: 'PermissionDenied', message: 'blocked {"path":"denied"}', code: 'denied', source: 'hook', reason: 'blocked {"path":"denied"}' }, + { isError: true, name: 'ToolError', message: 'no such file', code: 'not-found', source: null, reason: null }, + ]); + }); + + it('reports an uncaught throw with the script frames only', async () => { + const { outcome } = await run('function inner() { throw new TypeError("bad thing"); }\ninner();'); + const f = failure(outcome); + expect(f.kind).toBe('error'); + expect(f.error.name).toBe('TypeError'); + expect(f.error.message).toBe('bad thing'); + expect(f.error.stack).toContain('script.js:1'); + expect(f.error.stack).not.toContain('shim.js'); + }); + + it('reports a syntax error', async () => { + const f = failure((await run('return (;')).outcome); + expect(f.kind).toBe('error'); + expect(f.error.name).toBe('SyntaxError'); + }); + + it('reports thrown non-Error values', async () => { + expect(failure((await run('throw "plain";')).outcome).error).toEqual({ name: 'Error', message: 'plain' }); + expect(failure((await run('throw { a: 1 };')).outcome).error.message).toBe('Uncaught { a: 1 }'); + }); + + it('converts non-JSON return values to descriptive strings', async () => { + const { outcome } = await run(` + const cyclic = { name: 'c' }; cyclic.self = cyclic; + return { fn: function named() {}, arrow: () => 1, sym: Symbol('s'), big: 12n, nan: NaN, inf: -Infinity, + cyclic, date: new Date(0), err: new RangeError('r'), undef: undefined, arr: [undefined, 1], map: new Map([[1, 2]]) }; + `); + expect(value(outcome)).toEqual({ + fn: '[Function: named]', + arrow: '[Function: arrow]', + sym: 'Symbol(s)', + big: '12n', + nan: 'NaN', + inf: '-Infinity', + cyclic: { name: 'c', self: '[Circular]' }, + date: '1970-01-01T00:00:00.000Z', + err: 'RangeError: r', + arr: [null, 1], + map: {}, + }); + }); + + it('turns a throwing getter into a description instead of crashing', async () => { + const { outcome } = await run('return { get bad() { throw new Error("no"); }, ok: 1 };'); + expect(value(outcome)).toEqual({ bad: '[threw: no]', ok: 1 }); + }); + + it('formats console output like Node and keeps the level', async () => { + const { logs } = await run(` + console.log('a', 1, { k: 'v', n: [1, 2] }, null, undefined); + console.info('i'); console.warn('w'); console.error(new Error('boom')); + `); + expect(logs).toEqual([ + { level: 'log', text: "a 1 { k: 'v', n: [ 1, 2 ] } null undefined" }, + { level: 'info', text: 'i' }, + { level: 'warn', text: 'w' }, + { level: 'error', text: 'Error: boom' }, + ]); + }); + + it('reports an error whose name or message getter throws', async () => { + const f = failure((await run('const e = new Error("x"); Object.defineProperty(e, "message", { get() { throw 1; } }); throw e;')).outcome); + expect(f.kind).toBe('error'); + expect(f.error).toMatchObject({ name: 'Error', message: '[unreadable message]' }); + }); + + it('formats arrays in console output without running their getters and keeps text after a NUL', async () => { + const { outcome, logs } = await run('const a = [1, 2]; let reads = 0; Object.defineProperty(a, 1, { get() { reads++; return 3; } }); console.log(a); console.log("a\\u0000b"); return reads;'); + expect(value(outcome)).toBe(0); + expect(logs.map((l) => l.text)).toEqual(['[ 1, [Getter/Setter] ]', 'a\u0000b']); + }); + + it('keeps a script error when the WASM memory starts close to its maximum, and reports oom below it', async () => { + const thrown = failure((await run('throw new Error("boom");', { memoryBytes: 17 * 1024 * 1024 })).outcome); + expect(thrown).toMatchObject({ kind: 'error', error: { name: 'Error', message: 'boom' } }); + for (const empty of ['null', 'undefined']) { + expect(failure((await run(`throw ${empty};`, { memoryBytes: 17 * 1024 * 1024 })).outcome)).toMatchObject({ kind: 'error', error: { message: `Uncaught ${empty}` } }); + } + const small = failure((await run('return 1;', { memoryBytes: 1024 * 1024 })).outcome); + expect(small).toMatchObject({ kind: 'oom', error: { name: 'InternalError', message: expect.stringContaining('below') } }); + }); + + it('fails fast when the script waits on a promise nothing can settle', async () => { + const { outcome, elapsedMs } = await run('await new Promise(() => {});', { timeoutMs: 10_000 }); + expect(failure(outcome).error.name).toBe('Deadlock'); + expect(elapsedMs).toBeLessThan(5_000); + }); + + it('rejects a binding argument that is not JSON-serializable without calling the host', async () => { + const { outcome, calls } = await run('const a = {}; a.a = a; try { await read(a); } catch (e) { return e.name + ": " + (e.message.includes("JSON") ? "json" : e.message); }'); + expect(value(outcome)).toBe('TypeError: json'); + expect(calls).toEqual([]); + }); +}); + +/** + * Variables the OS layer adds to every child env even when the parent passes + * an empty one: libuv on Windows copies these required ones, macOS adds its + * text-encoding hint. None of them is a server secret. + */ +const PLATFORM_ENV = new Set( + process.platform === 'win32' + ? ['HOMEDRIVE', 'HOMEPATH', 'LOGONSERVER', 'PATH', 'SYSTEMDRIVE', 'SYSTEMROOT', 'TEMP', 'USERDOMAIN', 'USERNAME', 'USERPROFILE', 'WINDIR'] + : process.platform === 'darwin' + ? ['__CF_USER_TEXT_ENCODING'] + : [], +); + +describe('QuickJsSandbox: no ambient authority', () => { + it('exposes no host objects, module loading or timers', async () => { + const { outcome, calls } = await run(` + const names = ['require', 'process', 'fetch', 'Deno', 'Bun', 'std', 'os', 'module', 'exports', 'Buffer', + 'setTimeout', 'setInterval', 'setImmediate', 'queueMicrotask', 'performance', 'XMLHttpRequest', 'WebSocket', + 'importScripts', 'print', 'scriptArgs', '__acm_call', 'hostCall']; + const types = {}; + for (const n of names) types[n] = typeof globalThis[n]; + const viaFunction = new Function('return this')(); + const viaEval = (0, eval)('this'); + const extra = (g) => Object.getOwnPropertyNames(g).filter((k) => !STANDARD.includes(k)); + let dynamicImport; + try { await import('fs'); dynamicImport = 'loaded'; } catch (e) { dynamicImport = 'rejected'; } + let nodeImport; + try { await import('node:child_process'); nodeImport = 'loaded'; } catch (e) { nodeImport = 'rejected'; } + return { types, same: viaFunction === globalThis && viaEval === globalThis, extraFn: extra(viaFunction), extraEval: extra(viaEval), dynamicImport, nodeImport }; + `.replace( + 'STANDARD', + JSON.stringify([ + 'Object', 'Function', 'Error', 'EvalError', 'RangeError', 'ReferenceError', 'SyntaxError', 'TypeError', 'URIError', 'InternalError', + 'AggregateError', 'Iterator', 'Array', 'parseInt', 'parseFloat', 'isNaN', 'isFinite', 'decodeURI', 'decodeURIComponent', 'encodeURI', + 'encodeURIComponent', 'escape', 'unescape', 'Infinity', 'NaN', 'undefined', 'Number', 'Boolean', 'String', 'Math', 'Reflect', 'Symbol', + 'eval', 'globalThis', 'Date', 'RegExp', 'JSON', 'Proxy', 'Map', 'Set', 'WeakMap', 'WeakSet', 'ArrayBuffer', 'SharedArrayBuffer', + 'Uint8ClampedArray', 'Int8Array', 'Uint8Array', 'Int16Array', 'Uint16Array', 'Int32Array', 'Uint32Array', 'BigInt64Array', + 'BigUint64Array', 'Float16Array', 'Float32Array', 'Float64Array', 'DataView', 'Promise', 'BigInt', 'WeakRef', 'FinalizationRegistry', + 'console', 'bash', 'read', 'write', 'edit', 'grep', 'glob', + ]), + )); + const result = value(outcome); + expect(result).toEqual({ + types: Object.fromEntries( + ['require', 'process', 'fetch', 'Deno', 'Bun', 'std', 'os', 'module', 'exports', 'Buffer', 'setTimeout', 'setInterval', 'setImmediate', + 'queueMicrotask', 'performance', 'XMLHttpRequest', 'WebSocket', 'importScripts', 'print', 'scriptArgs', '__acm_call', 'hostCall'].map((n) => [n, 'undefined']), + ), + same: true, + extraFn: [], + extraEval: [], + dynamicImport: 'rejected', + nodeImport: 'rejected', + }); + expect(calls).toEqual([]); + }); + + it('starts the child with an env that has none of the server secrets', () => { + const env = childEnv({ ACM_TEST_CANARY: 'secret', PATH: '/bin', HOME: '/home/x', GITHUB_TOKEN: 't' }, 'linux'); + expect(env).toEqual({}); + expect(childEnv({ ACM_TEST_CANARY: 'secret', SystemRoot: 'C:\\Windows' }, 'win32')).toEqual({ SystemRoot: 'C:\\Windows' }); + }); + + it('runs the child process under the Node permission model of the running Node', async () => { + const target = join(tmpdir(), `acm-permission-probe-${process.pid}`); + const server = createServer((socket) => { + // Where Node allows the connection (before Node 25) the probe exits right away and resets it. + socket.on('error', () => undefined); + socket.end('hello'); + }); + await new Promise((resolve) => server.listen(0, '127.0.0.1', resolve)); + const address = server.address(); + const port = typeof address === 'object' && address !== null ? address.port : 0; + const probe = `const r = {}; const fs = require('fs'); + try { fs.writeFileSync(${JSON.stringify(target)}, 'x'); r.write = 'allowed'; } catch (e) { r.write = e.code; } + try { require('child_process').execFileSync(process.execPath, ['-e', '0']); r.spawn = 'allowed'; } catch (e) { r.spawn = e.code; } + try { new (require('worker_threads').Worker)('0', { eval: true }).terminate(); r.worker = 'allowed'; } catch (e) { r.worker = e.code; } + try { new Function('return 1')(); r.codegen = 'allowed'; } catch (e) { r.codegen = e.name; } + r.env = Object.keys(process.env).filter((k) => !PLATFORM_ENV.has(k.toUpperCase())); + const done = (v) => { r.socket = v; console.log(JSON.stringify(r)); process.exit(0); }; + try { + const s = require('net').connect(${port}, '127.0.0.1'); + s.on('connect', () => done('allowed')); + s.on('error', (e) => done(e.code)); + } catch (e) { done(e.code); }`; + try { + const flags = childExecArgv(childEntryPath(), 256).filter((flag) => flag !== '--experimental-strip-types'); + const child = spawn(process.execPath, [...flags, '-e', probe.replace('PLATFORM_ENV', `new Set(${JSON.stringify([...PLATFORM_ENV])})`)], { + env: childEnv(), + stdio: ['ignore', 'pipe', 'pipe'], + }); + let stdout = ''; + child.stdout.on('data', (chunk: Buffer) => (stdout += chunk.toString())); + await new Promise((resolve) => child.on('close', resolve)); + const result = JSON.parse(stdout) as Record; + expect({ ...result, socket: undefined }).toEqual({ write: 'ERR_ACCESS_DENIED', spawn: 'ERR_ACCESS_DENIED', worker: 'ERR_ACCESS_DENIED', codegen: 'EvalError', env: [], socket: undefined }); + expect(existsSync(target)).toBe(false); + // Node's permission model covers the network only from Node 25 (the release that added --allow-net). + if (process.allowedNodeEnvironmentFlags.has('--allow-net')) expect(result.socket).toBe('ERR_ACCESS_DENIED'); + } finally { + await new Promise((resolve) => server.close(resolve)); + } + }); + + it('uses whichever permission flag this Node has and refuses to start without one', async () => { + expect(permissionFlag(new Set(['--permission', '--experimental-permission']))).toBe('--permission'); + expect(permissionFlag(new Set(['--experimental-permission']))).toBe('--experimental-permission'); + const legacy = childExecArgv('child.js', 64, new Set(['--experimental-permission'])); + expect(legacy).toContain('--experimental-permission'); + expect(legacy).toContain('--preserve-symlinks'); + expect(legacy).toContain(`--allow-fs-read=${join(dirname(childEntryPath()), '*')}`); + expect(() => childExecArgv('child.js', 64, new Set())).toThrow(SandboxUnavailableError); + expect(permissionFlag()).toBeDefined(); + }); + + it('lets the child read only its own entry directory and the packages it loads', () => { + const { dirs, files } = readGrants(); + const packages = ['@jitl/quickjs-ffi-types', '@jitl/quickjs-ng-wasmfile-release-sync', 'quickjs-emscripten-core', 'zod']; + expect(dirs.sort()).toEqual([...packages.map((name) => join(process.cwd(), 'node_modules', name)), dirname(childEntryPath())].sort()); + expect(files).toContain(join(process.cwd(), 'package.json')); + }); + + describe('read grants for probed paths', () => { + let root = ''; + beforeEach(() => { + root = mkdtempSync(join(tmpdir(), 'acm-grants-')); + }); + afterEach(() => { + rmSync(root, { recursive: true, force: true }); + }); + + /** Builds `/a/b/entry` (the child entry directory) with a regular package.json at `/a`; returns the entry. */ + function layout(): { entry: string; probed: string; above: string } { + const entry = join(root, 'a', 'b', 'entry'); + mkdirSync(entry, { recursive: true }); + writeFileSync(join(root, 'a', 'package.json'), '{}'); + return { entry, probed: join(root, 'a', 'b', 'package.json'), above: join(root, 'a', 'package.json') }; + } + + it('grants an absent ancestor manifest and keeps walking to the first regular one', () => { + const { entry, probed, above } = layout(); + const { files } = readGrants(entry, []); + expect(files).toContain(probed); + expect(files).toContain(above); + }); + + it('never grants an ancestor manifest that is a dangling link', () => { + const { entry, probed, above } = layout(); + symlinkSync(join(root, 'missing-target.json'), probed); + const { files, dirs } = readGrants(entry, []); + expect([...files, ...dirs]).not.toContain(probed); + expect(files).not.toContain(above); + }); + + it('never grants an ancestor manifest that links to a regular file', () => { + const { entry, probed } = layout(); + writeFileSync(join(root, 'target.json'), '{}'); + symlinkSync(join(root, 'target.json'), probed); + const { files, dirs } = readGrants(entry, []); + expect([...files, ...dirs]).not.toContain(probed); + }); + + it('never grants a directory in place of an ancestor manifest', () => { + const { entry, probed } = layout(); + mkdirSync(probed); + const { files, dirs } = readGrants(entry, []); + expect([...files, ...dirs]).not.toContain(probed); + }); + + it('refuses a directory grant that covers an unexpected manifest entry', () => { + const { entry } = layout(); + mkdirSync(join(entry, 'package.json')); + expect(() => readGrants(entry, [])).toThrow(SandboxUnavailableError); + }); + + it('omits a regular file found where a dependency directory was expected', () => { + const { entry } = layout(); + const candidate = join(root, 'a', 'b', 'node_modules', 'dep'); + mkdirSync(dirname(candidate), { recursive: true }); + writeFileSync(candidate, 'not a package'); + expect(readGrants(entry, ['dep']).files).not.toContain(candidate); + }); + + it('never grants a node_modules lookup entry that is a link without a package, and still finds the package above it', () => { + const { entry } = layout(); + const linked = join(root, 'a', 'b', 'node_modules', 'dep'); + mkdirSync(dirname(linked), { recursive: true }); + symlinkSync(join(root, 'missing-dep'), linked); + const real = join(root, 'a', 'node_modules', 'dep'); + mkdirSync(real, { recursive: true }); + writeFileSync(join(real, 'package.json'), '{}'); + const { files, dirs } = readGrants(entry, ['dep']); + expect([...files, ...dirs]).not.toContain(linked); + expect(dirs).toContain(real); + }); + }); + + it('never lets the script observe a canary secret from the server env', async () => { + const canary = `canary-${Math.random().toString(36).slice(2)}-${Date.now()}`; + process.env.ACM_TEST_CANARY = canary; + let childEnviron: string | undefined; + try { + let pid = 0; + const recorded = await run( + ` + const seen = []; + const scan = (o, depth) => { if (depth > 3 || o === null || (typeof o !== 'object' && typeof o !== 'function')) return; + for (const k of Object.getOwnPropertyNames(o)) { seen.push(k); try { scan(o[k], depth + 1); } catch {} } }; + scan(globalThis, 0); + try { await bash({ command: 'echo $ACM_TEST_CANARY' }); } catch (e) { seen.push(e.message, String(e.stack)); } + try { await read({ path: '/proc/self/environ' }); } catch (e) { seen.push(e.message); } + try { null.x; } catch (e) { seen.push(String(e.stack)); } + console.log(seen.join(' ')); + return seen.join(' '); + `, + { + sandbox: { onSpawn: (p) => (pid = p) }, + onCall: async (tool) => { + if (process.platform === 'linux' && pid > 0 && childEnviron === undefined) childEnviron = readFileSync(`/proc/${pid}/environ`, 'utf8'); + return { ok: false, error: { name: 'ToolError', code: 'tool-error', message: `${tool} failed` } }; + }, + }, + ); + const everything = JSON.stringify(recorded); + expect(recorded.outcome.ok).toBe(true); + expect(everything).not.toContain(canary); + if (process.platform === 'linux') { + expect(childEnviron).toBeTypeOf('string'); + expect(childEnviron).not.toContain(canary); + expect(childEnviron).not.toContain('PATH='); + } + } finally { + delete process.env.ACM_TEST_CANARY; + } + }); +}); + +describe('QuickJsSandbox: prototype pollution', () => { + it('keeps host prototypes intact and parses hostile keys as own data', async () => { + const { outcome } = await run(` + Object.prototype.polluted = 1; + Array.prototype.map = function () { return 'hijacked'; }; + JSON.stringify = () => '"hijacked"'; + Promise.prototype.then = function () { throw new Error('hijacked then'); }; + const viaParse = JSON.parse('{"__proto__": {"injected": true}, "constructor": {"prototype": {"injected": true}}}'); + const literal = { ['__proto__']: { injected: true }, constructor: { prototype: { injected: true } }, list: [1, 2] }; + return { viaParse, literal }; + `); + const result = value(outcome); + expect(({} as Record).polluted).toBeUndefined(); + expect([1].map((x) => x + 1)).toEqual([2]); + expect(Object.prototype).not.toHaveProperty('injected'); + const top = result as Record>; + for (const key of ['viaParse', 'literal'] as const) { + const obj = top[key]; + expect(obj).toBeDefined(); + if (!obj) continue; + expect(Object.getPrototypeOf(obj)).toBe(Object.prototype); + expect(Object.keys(obj)).toContain('__proto__'); + expect((obj as { injected?: unknown }).injected).toBeUndefined(); + expect(({} as { injected?: unknown }).injected).toBeUndefined(); + expect(Object.hasOwn(obj, 'polluted')).toBe(false); + } + }); + + it('keeps bindings working after the script overrides intrinsics', async () => { + const { outcome } = await run(` + JSON.parse = () => 'hijacked'; + JSON.stringify = () => 'hijacked'; + Promise.prototype.then = function () { throw new Error('hijacked then'); }; + const r = read({ path: 'p' }); + return 'called'; + `); + expect(value(outcome)).toBe('called'); + }); +}); + +describe('QuickJsSandbox: resource abuse', () => { + it('stops an infinite loop with outcome timeout within the deadline plus a small margin', async () => { + const { outcome, elapsedMs } = await run('for (;;) {}', { timeoutMs: 1_000 }); + expect(failure(outcome).kind).toBe('timeout'); + expect(elapsedMs).toBeLessThan(1_000 + 1_000); + }); + + it('stops a loop that catches every error', async () => { + const { outcome, elapsedMs } = await run('for (;;) { try { for (;;) {} } catch (e) {} }', { timeoutMs: 800 }); + expect(failure(outcome).kind).toBe('timeout'); + expect(elapsedMs).toBeLessThan(800 + 1_000); + }); + + it('times out while a binding never replies', async () => { + const { outcome, elapsedMs } = await run('await read({ path: "slow" });', { timeoutMs: 600, onCall: () => new Promise(() => undefined) }); + expect(failure(outcome).kind).toBe('timeout'); + expect(elapsedMs).toBeLessThan(600 + 1_000); + }); + + it('counts the time spent starting the child against the deadline', async () => { + let spawnReturnedAt = 0; + const onSpawn = (): void => { + const until = performance.now() + 400; + while (performance.now() < until); + spawnReturnedAt = performance.now(); + }; + const { outcome, calls } = await run('await read({ path: "x" }); return 1;', { timeoutMs: 300, sandbox: { onSpawn } }); + expect(failure(outcome)).toMatchObject({ kind: 'timeout', error: { message: 'the script did not finish within 300 ms' } }); + expect(calls).toEqual([]); + expect(performance.now() - spawnReturnedAt).toBeLessThan(100); + }); + + it('reports an allocation bomb as oom', async () => { + const arrays = await run('const a = []; for (let i = 0; ; i++) a.push("x".repeat(100000) + i);', { memoryBytes: 32 * 1024 * 1024 }); + expect(failure(arrays.outcome).kind).toBe('oom'); + const objects = await run('const a = []; for (;;) a.push({ a: 1, b: [1, 2, 3] });', { memoryBytes: 32 * 1024 * 1024 }); + expect(failure(objects.outcome).kind).toBe('oom'); + const single = await run('return "x".repeat(1e9).length;', { memoryBytes: 32 * 1024 * 1024 }); + expect(failure(single.outcome).kind).toBe('oom'); + }); + + it('enforces memoryBytes as the real heap limit', async () => { + const fill = (mib: number): string => `const a = []; for (let i = 0; i < ${mib * 10}; i++) a.push("x".repeat(100000) + i); return a.length;`; + expect(value((await run(fill(16), { memoryBytes: 48 * 1024 * 1024 })).outcome)).toBe(160); + expect(failure((await run(fill(96), { memoryBytes: 48 * 1024 * 1024 })).outcome).kind).toBe('oom'); + }); + + it('turns deep recursion into a script error, not a crash', async () => { + const f = failure((await run('function f(n) { return f(n + 1) + 1; } return f(0);')).outcome); + expect(f.kind).toBe('error'); + expect(f.error.name).toBe('RangeError'); + const caught = await run('function f() { f(); } try { f(); } catch (e) { return e.name; }'); + expect(value(caught.outcome)).toBe('RangeError'); + }); + + it('refuses binding calls after the cap and never forwards them', async () => { + const { outcome, calls } = await run( + ` + const settled = await Promise.allSettled(Array.from({ length: 10000 }, (_, i) => glob({ pattern: String(i) }))); + const rejected = settled.filter((s) => s.status === 'rejected'); + return { fulfilled: settled.length - rejected.length, rejected: rejected.length, sample: rejected[0].reason.message, code: rejected[0].reason.code }; + `, + { onCall: async () => ok({ files: [], truncated: false }) }, + ); + expect(value(outcome)).toEqual({ fulfilled: 2000, rejected: 8000, sample: expect.stringContaining('at most 2000 calls'), code: 'tool-error' }); + expect(calls).toHaveLength(2000); + }); + + it('caps console spam', async () => { + const { logs, outcome } = await run('for (let i = 0; i < 200000; i++) console.log("spam line " + i + " " + "y".repeat(80));', { + sandbox: { maxLogBytes: 256 * 1024 }, + }); + expect(outcome.ok).toBe(true); + const bytes = logs.reduce((n, l) => n + Buffer.byteLength(l.text) + 1, 0); + expect(bytes).toBeLessThanOrEqual(256 * 1024 + 1024); + expect(logs.at(-1)?.text).toContain('console output truncated'); + }); + + it('cuts a single huge console line', async () => { + const { logs } = await run('console.log("z".repeat(500000));'); + expect(logs).toHaveLength(1); + expect(logs[0]?.text.length).toBeLessThan(10_100); + expect(logs[0]?.text).toContain('[truncated]'); + }); + + it('bounds a gigantic return value', async () => { + const str = failure((await run('return "x".repeat(5 * 1024 * 1024);')).outcome); + expect(str.error.name).toBe('ResultTooLarge'); + const arr = await run('return new Array(1e8);'); + expect(failure(arr.outcome).error.name).toBe('ResultTooLarge'); + expect(arr.elapsedMs).toBeLessThan(5_000); + }); +}); + +describe('QuickJsSandbox: out of memory is fatal', () => { + const MEMORY = 32 * 1024 * 1024; + /** Fills the heap with small objects: the engine's growth is refused and it could not even build an error object. */ + const objectBomb = 'for (;;) a.push({ a: 1, b: [1, 2, 3] });'; + /** Fills the heap with 100 kB strings: the engine could still build an InternalError for the script to catch. */ + const stringBomb = 'for (let i = 0; ; i++) a.push("x".repeat(100000) + i);'; + /** Visible effects a catch block would leave if it ran: it frees the heap first, then logs and calls a binding. */ + const caught = 'a = null; console.log("catch ran"); await read({ path: "after-oom" });'; + + it('(1) ends an uncaught allocation bomb as oom', async () => { + const { outcome } = await run(`let a = []; ${objectBomb}`, { memoryBytes: MEMORY }); + expect(failure(outcome)).toMatchObject({ kind: 'oom', error: { name: 'InternalError', message: expect.stringContaining('out of memory') } }); + }); + + it('(2) ends the run at the refused growth: a catch never runs, whatever the script throws or returns next', async () => { + for (const [bomb, after] of [[objectBomb, 'throw null;'], [stringBomb, 'throw undefined;'], [objectBomb, 'return "recovered";']]) { + const { outcome, logs, calls } = await run(`let a = []; try { ${bomb} } catch (e) { ${caught} } finally { console.log("finally ran"); }\n${after}`, { memoryBytes: MEMORY }); + expect(logs).toEqual([]); + expect(calls).toEqual([]); + expect(failure(outcome)).toMatchObject({ kind: 'oom', error: { name: 'InternalError' } }); + } + }); + + it('(3) reports throw null or undefined as a script error when no growth was refused', async () => { + for (const empty of ['null', 'undefined']) { + expect(failure((await run(`throw ${empty};`, { memoryBytes: MEMORY })).outcome)).toMatchObject({ kind: 'error', error: { name: 'Error', message: `Uncaught ${empty}` } }); + // A memory error the QuickJS limit raises before any growth is an ordinary, catchable error. + const { outcome, logs } = await run(`try { "x".repeat(1e9); } catch (e) { console.log(e.name); } throw ${empty};`, { memoryBytes: MEMORY }); + expect(failure(outcome)).toMatchObject({ kind: 'error', error: { message: `Uncaught ${empty}` } }); + expect(logs.map((l) => l.text)).toEqual(['InternalError']); + } + }); + + it('(4) keeps an explicit memory error as oom', async () => { + const { outcome } = await run('return "x".repeat(1e9).length;', { memoryBytes: MEMORY }); + expect(failure(outcome)).toMatchObject({ kind: 'oom', error: { name: 'InternalError', message: 'out of memory' } }); + }); + + it('(5) delivers the logs and calls made before the refused growth, in order, while the parent is slow to read', async () => { + const lines = 4_000; + const pad = 'p'.repeat(200); + const logs: string[] = []; + const calls: string[] = []; + let stalled = false; + const outcome = await new QuickJsSandbox().run( + `for (let i = 0; i < ${lines}; i++) console.log("line " + i + "${pad}"); read({ path: "before-oom" }); let a = []; ${objectBomb}`, + { + timeoutMs: 10_000, + memoryBytes: MEMORY, + signal: new AbortController().signal, + onCall: (tool) => { + calls.push(tool); + return Promise.resolve(ok(null)); + }, + onLog: (_level, text) => { + // The parent stops reading for a moment, so the child's output backs up while the script fills the heap. + if (!stalled) { + stalled = true; + const until = Date.now() + 300; + while (Date.now() < until); + } + logs.push(text); + }, + }, + ); + expect(failure(outcome)).toMatchObject({ kind: 'oom', error: { name: 'InternalError' } }); + expect(logs).toEqual(Array.from({ length: lines }, (_, i) => `line ${i}${pad}`)); + expect(calls).toEqual(['read']); + }); +}); + +describe('QuickJsSandbox: reply buffering', () => { + const bigRead = (): Promise => + Promise.resolve(ok({ path: '/example.txt', content: 'x'.repeat(1024 * 1024), startLine: 1, totalLines: 1, truncated: false })); + + it('ends a run whose script stops reading binding results instead of buffering them', async () => { + const before = process.memoryUsage(); + const { outcome, calls, elapsedMs } = await run('for (let i = 0; i < 200; i++) read({ path: "x" }); while (true) {}', { + timeoutMs: 10_000, + onCall: bigRead, + sandbox: { maxPendingReplyBytes: 16 * 1024 * 1024 }, + }); + const f = failure(outcome); + expect(f.kind).toBe('oom'); + expect(f.error.name).toBe('ReplyBufferFull'); + expect(calls.length).toBeGreaterThan(16); + expect(elapsedMs).toBeLessThan(5_000); + const after = process.memoryUsage(); + expect(after.external + after.arrayBuffers - (before.external + before.arrayBuffers)).toBeLessThan(64 * 1024 * 1024); + }); + + it('does not count the script itself against the reply quotas', async () => { + const code = `// ${'p'.repeat(8_192)}\nreturn await read({ path: 'x' });`; + const { outcome } = await run(code, { sandbox: { maxReplyBytes: 4_096, maxPendingReplyBytes: 4_096 } }); + expect(value(outcome)).toEqual({ tool: 'read', args: { path: 'x' } }); + }); + + it('caps the total bytes of binding results per run', async () => { + const { outcome } = await run('for (let i = 0; i < 20; i++) await read({ path: "x" }); return "read all";', { + onCall: bigRead, + sandbox: { maxReplyBytes: 8 * 1024 * 1024 }, + }); + expect(failure(outcome).error.name).toBe('ReplyBufferFull'); + const fine = await run('for (let i = 0; i < 20; i++) await read({ path: "x" }); return "read all";', { onCall: bigRead }); + expect(value(fine.outcome)).toBe('read all'); + }); +}); + +describe('QuickJsSandbox: concurrency', () => { + it('resolves Promise.all of 200 bindings answered in reverse order', async () => { + const waiting: (() => void)[] = []; + const { outcome } = await run('return await Promise.all(Array.from({ length: 200 }, (_, i) => read({ path: "f" + i })));', { + onCall: (_tool, args, index) => + new Promise((resolve) => { + waiting.push(() => resolve(ok({ echo: args, index }))); + if (waiting.length === 200) { + for (const answer of [...waiting].reverse()) setImmediate(answer); + } + }), + }); + const result = value(outcome) as { echo: { path: string }; index: number }[]; + expect(result).toHaveLength(200); + result.forEach((r, i) => { + expect(r.echo.path).toBe(`f${i}`); + expect(r.index).toBe(i); + }); + }); + + it('keeps running when one binding inside Promise.allSettled rejects', async () => { + const { outcome } = await run( + 'const s = await Promise.allSettled([read({ path: "a" }), read({ path: "b" }), read({ path: "c" })]); return s.map((x) => x.status + ":" + (x.status === "fulfilled" ? x.value.path : x.reason.code));', + { + onCall: async (_tool, args) => { + const path = (args as { path: string }).path; + await new Promise((resolve) => setTimeout(resolve, path === 'a' ? 20 : 1)); + return path === 'b' ? { ok: false, error: { name: 'ToolError', code: 'not-found', message: 'missing' } } : ok({ path }); + }, + }, + ); + expect(value(outcome)).toEqual(['fulfilled:a', 'rejected:not-found', 'fulfilled:c']); + }); +}); + +describe('QuickJsSandbox: cancellation', () => { + it('kills the child during a pending binding and forwards no later call', async () => { + const controller = new AbortController(); + let pid = 0; + const started = Date.now(); + const { outcome, calls } = await run('await read({ path: "first" }); await read({ path: "second" }); return "finished";', { + signal: controller.signal, + sandbox: { onSpawn: (p) => (pid = p) }, + onCall: async () => { + setTimeout(() => controller.abort(), 10); + await new Promise((resolve) => setTimeout(resolve, 100)); + return ok({ late: true }); + }, + }); + expect(failure(outcome).kind).toBe('killed'); + expect(pid).toBeGreaterThan(0); + while (!processGone(pid) && Date.now() - started < 1_000) await new Promise((resolve) => setTimeout(resolve, 10)); + expect(processGone(pid)).toBe(true); + await new Promise((resolve) => setTimeout(resolve, 200)); + expect(calls).toEqual([{ tool: 'read', args: { path: 'first' } }]); + }); + + it('stops the run when the signal is aborted while the child starts', async () => { + const controller = new AbortController(); + let pid = 0; + const { outcome, calls } = await run('await write({ path: "example.txt", content: "x" }); return 42;', { + signal: controller.signal, + sandbox: { + onSpawn: (p) => { + pid = p; + controller.abort(); + }, + }, + }); + expect(failure(outcome).kind).toBe('killed'); + expect(calls).toEqual([]); + const started = Date.now(); + while (!processGone(pid) && Date.now() - started < 1_000) await new Promise((resolve) => setTimeout(resolve, 10)); + expect(processGone(pid)).toBe(true); + }); + + it('does not start a child when the signal is already aborted', async () => { + const controller = new AbortController(); + controller.abort(); + let spawned = false; + const { outcome } = await run('return 1;', { signal: controller.signal, sandbox: { onSpawn: () => (spawned = true) } }); + expect(failure(outcome).kind).toBe('killed'); + expect(spawned).toBe(false); + }); + + it('never reuses a child across runs', async () => { + const pids: number[] = []; + const sandbox = { onSpawn: (p: number) => pids.push(p) }; + await run('globalThis.leak = 42; return 1;', { sandbox }); + const second = await run('return typeof globalThis.leak;', { sandbox }); + expect(value(second.outcome)).toBe('undefined'); + expect(pids).toHaveLength(2); + expect(pids[0]).not.toBe(pids[1]); + }); +}); diff --git a/src/sandbox/quickjs-sandbox.ts b/src/sandbox/quickjs-sandbox.ts new file mode 100644 index 0000000..e33cf5e --- /dev/null +++ b/src/sandbox/quickjs-sandbox.ts @@ -0,0 +1,317 @@ +import { spawn } from 'node:child_process'; +import { existsSync, lstatSync, readFileSync, type Stats } from 'node:fs'; +import { dirname, join, sep } from 'node:path'; +import { fileURLToPath } from 'node:url'; +import { z } from 'zod'; +import { errorMessage } from '../core/errors.js'; +import { MAX_CODE_CHARS } from '../core/schemas.js'; +import type { Sandbox, SandboxOutcome, SandboxRunOptions } from '../core/types.js'; +import type { ParentMessage, SandboxLimits } from './protocol.js'; +import { ChildSession, killedOutcome } from './session.js'; +import { BoundedWriter } from './writer.js'; + +/** Default QuickJS heap limit when `memoryBytes` is not usable. */ +export const DEFAULT_SANDBOX_MEMORY_BYTES = 128 * 1024 * 1024; + +/** Limits and process settings of `QuickJsSandbox`. Every field has a default. */ +export interface QuickJsSandboxOptions { + /** Maximum binding calls per run. Default 2,000. */ + readonly maxCalls?: number; + /** Maximum console bytes per run. Default 1 MiB. */ + readonly maxLogBytes?: number; + /** Maximum characters of one console line. Default 10,000. */ + readonly maxLogLineChars?: number; + /** Maximum characters of the JSON return value. Default 1 MiB. */ + readonly maxResultChars?: number; + /** Maximum characters of the JSON arguments of one call. Default 4 MiB. */ + readonly maxArgsChars?: number; + /** QuickJS stack limit. Default 128 KiB: the WASM build runs on the Node stack, and 256 KiB already overflows it on macOS with Node 22. */ + readonly stackBytes?: number; + /** + * Most bytes of binding results that may wait for the child to read them. + * A script that starts calls and then never yields (a busy loop) stops + * reading; past this cap the run ends with outcome `oom`. Default 16 MiB. + */ + readonly maxPendingReplyBytes?: number; + /** Most bytes of binding results sent to the child in one run; past it the run ends with outcome `oom`. Default 512 MiB. */ + readonly maxReplyBytes?: number; + /** `--max-old-space-size` of the child process, in MiB. Default 256. */ + readonly childHeapMb?: number; + /** Called with the pid of each child process (tests use it to check the child is gone). */ + readonly onSpawn?: (pid: number) => void; +} + +const DEFAULTS = { + maxCalls: 2_000, + maxLogBytes: 1024 * 1024, + maxLogLineChars: 10_000, + maxResultChars: 1024 * 1024, + maxArgsChars: 4 * 1024 * 1024, + stackBytes: 128 * 1024, + childHeapMb: 256, + maxPendingReplyBytes: 16 * 1024 * 1024, + maxReplyBytes: 512 * 1024 * 1024, +} as const; + +/** Most bytes the child may send in one run (calls, logs and the outcome), unless one frame needs more; past it the run ends with outcome `oom`. */ +const MAX_CHILD_OUTPUT_BYTES = 64 * 1024 * 1024; +/** Largest `start` message: the longest accepted script, JSON-escaped, plus the limits. */ +const MAX_START_BYTES = 6 * MAX_CODE_CHARS + 64 * 1024; + +const here = dirname(fileURLToPath(import.meta.url)); + +/** The child entry: compiled `child.js` next to this file, or `child.ts` when running from source. */ +export function childEntryPath(): string { + const compiled = join(here, 'child.js'); + return existsSync(compiled) ? compiled : join(here, 'child.ts'); +} + +/** + * Environment of the child: nothing from the server env except what Node + * itself needs to start on Windows. No tokens, no PATH, no HOME. + */ +export function childEnv(parentEnv: NodeJS.ProcessEnv = process.env, platform: NodeJS.Platform = process.platform): Record { + const env: Record = {}; + if (platform === 'win32') { + for (const key of ['SystemRoot', 'SYSTEMROOT']) { + const value = parentEnv[key]; + if (value !== undefined) env[key] = value; + } + } + return env; +} + +/** Packages the child imports; their runtime dependencies come from their package.json files. */ +const CHILD_PACKAGES = ['quickjs-emscripten-core', '@jitl/quickjs-ng-wasmfile-release-sync', 'zod']; +const packageName = z.string().regex(/^(?:@[a-z\d][a-z\d._~-]*\/)?[a-z\d][a-z\d._~-]*$/i); +const ManifestSchema = z.object({ dependencies: z.record(packageName, z.string()).optional() }); + +/** What a probed path is, read without following a link at the path itself. */ +type ProbedEntry = 'absent' | 'file' | 'other'; + +/** + * Classifies a path the child's Node may look up. A manifest may be a regular file, and an absent path may + * need a grant for Node's lookup. Links, directories and other unexpected entries must stay outside the grants. + */ +function probeEntry(path: string): ProbedEntry { + let stat: Stats; + try { + stat = lstatSync(path); + } catch (err) { + return err instanceof Error && 'code' in err && err.code === 'ENOENT' ? 'absent' : 'other'; + } + return stat.isFile() ? 'file' : 'other'; +} + +/** + * What the child may read, with symlinks preserved: its entry directory, the directories of the packages it loads + * and, as exact paths, each package.json and `node_modules/` candidate Node looks up on the way that + * `probeEntry` allows. A package directory is granted at the path Node loads it from, which is a link under pnpm or + * `npm link`. + */ +export function readGrants(from: string = here, packages: readonly string[] = CHILD_PACKAGES): { readonly dirs: string[]; readonly files: string[] } { + const dirs = new Set([from]); + const files = new Set(); + const excluded = new Set(); + // The nearest package.json above the entry; the walk ends at the first path that exists in any form. + for (let dir = from; ; dir = dirname(dir)) { + const path = join(dir, 'package.json'); + const entry = probeEntry(path); + if (entry === 'other') excluded.add(path); + else files.add(path); + if (entry !== 'absent' || dirname(dir) === dir) break; + } + const visit = (start: string, name: string): void => { + for (let dir = start; ; dir = dirname(dir)) { + const candidate = join(dir, 'node_modules', name); + if (existsSync(join(candidate, 'package.json'))) { + if (dirs.has(candidate)) return; + dirs.add(candidate); + const manifest = ManifestSchema.parse(JSON.parse(readFileSync(join(candidate, 'package.json'), 'utf8'))); + for (const dependency of Object.keys(manifest.dependencies ?? {})) visit(candidate, dependency); + return; + } + // Not a package: Node's lookup goes on to the parent directory. + if (probeEntry(candidate) === 'absent') files.add(candidate); + else excluded.add(candidate); + if (dirname(dir) === dir) return; + } + }; + for (const name of packages) visit(from, name); + // A grant inside a granted directory is redundant, and Node's permission tree can lose a shorter grant added after a longer one. + const outside = (path: string): boolean => ![...dirs].some((dir) => path.startsWith(dir + sep)); + if ([...excluded].some((path) => dirs.has(path) || !outside(path))) { + throw new SandboxUnavailableError('An unexpected lookup entry is covered by a sandbox directory grant'); + } + return { dirs: [...dirs].filter(outside), files: [...files].filter(outside) }; +} + +/** Thrown when this Node cannot start the child under its permission model. */ +export class SandboxUnavailableError extends Error { + override readonly name = 'SandboxUnavailableError'; +} + +/** + * The flag that turns on Node's permission model: `--permission` (Node + * 22.13+, 23.5+) or `--experimental-permission` (Node 22.0 to 22.12). + */ +export function permissionFlag(flags: ReadonlySet = process.allowedNodeEnvironmentFlags): '--permission' | '--experimental-permission' | undefined { + if (flags.has('--permission')) return '--permission'; + if (flags.has('--experimental-permission')) return '--experimental-permission'; + return undefined; +} + +/** + * Node flags of the child. Fails closed: without a permission model the + * child would have the server's full file, process and worker access, so + * this throws `SandboxUnavailableError` instead of returning flags without it. + */ +export function childExecArgv(entry: string, heapMb: number, flags: ReadonlySet = process.allowedNodeEnvironmentFlags): string[] { + const permission = permissionFlag(flags); + if (permission === undefined) { + throw new SandboxUnavailableError(`Node ${process.version} has no permission model (--permission or --experimental-permission); the sandbox refuses to start without it`); + } + const args = [`--max-old-space-size=${heapMb}`, '--disallow-code-generation-from-strings']; + if (entry.endsWith('.ts') && !('typescript' in process.features && process.features.typescript)) args.push('--experimental-strip-types'); + args.push(permission, '--preserve-symlinks', '--preserve-symlinks-main'); + const { dirs, files } = readGrants(); + if ([...dirs, ...files].some((path) => path.includes('*'))) { + throw new SandboxUnavailableError('The sandbox cannot grant literal read access to a path containing an asterisk'); + } + // Node 22.0 to 22.12 grants a directory itself only, unless it ends with the `*` wildcard; one flag per path adds up on every version. + const paths = [...files, ...(permission === '--permission' ? dirs : dirs.map((dir) => join(dir, '*')))]; + if (permission === '--experimental-permission' && paths.some((path) => path.includes(','))) { + throw new SandboxUnavailableError(`Node ${process.version} cannot grant read access to a path that contains a comma; upgrade to Node 22.13 or later`); + } + for (const path of paths) args.push(`--allow-fs-read=${path}`); + return args; +} + +function positive(value: number | undefined, fallback: number): number { + return value !== undefined && Number.isFinite(value) && value >= 1 ? Math.floor(value) : fallback; +} + +/** + * The real sandbox: each run starts a fresh Node child process (minimal env, + * bounded heap, Node permission model when available) that runs the script + * in a QuickJS-ng WASM VM. The parent enforces the deadline and cancellation + * with SIGKILL and validates every message from the child. A child is never + * reused. + */ +export class QuickJsSandbox implements Sandbox { + readonly #options: QuickJsSandboxOptions; + readonly #entry: string; + + constructor(options: QuickJsSandboxOptions = {}) { + this.#options = options; + this.#entry = childEntryPath(); + } + + run(code: string, opts: SandboxRunOptions): Promise { + const startedAt = performance.now(); + if (opts.signal.aborted) return Promise.resolve(killedOutcome('the run was stopped before the script started')); + const o = this.#options; + const limits: SandboxLimits = { + memoryBytes: positive(opts.memoryBytes, DEFAULT_SANDBOX_MEMORY_BYTES), + stackBytes: positive(o.stackBytes, DEFAULTS.stackBytes), + maxCalls: positive(o.maxCalls, DEFAULTS.maxCalls), + maxLogBytes: positive(o.maxLogBytes, DEFAULTS.maxLogBytes), + maxLogLineChars: positive(o.maxLogLineChars, DEFAULTS.maxLogLineChars), + maxResultChars: positive(o.maxResultChars, DEFAULTS.maxResultChars), + maxArgsChars: positive(o.maxArgsChars, DEFAULTS.maxArgsChars), + }; + const timeoutMs = positive(opts.timeoutMs, 1); + const deadline = startedAt + timeoutMs; + // Each string field is bounded in characters; JSON escaping turns one character into at most 6 bytes. + const maxFrameBytes = 6 * Math.max(limits.maxArgsChars, limits.maxResultChars, limits.maxLogLineChars + 200) + 64 * 1024; + + let execArgv: string[]; + try { + execArgv = childExecArgv(this.#entry, positive(o.childHeapMb, DEFAULTS.childHeapMb)); + } catch (err) { + return Promise.resolve({ ok: false, kind: 'killed', error: { name: 'SandboxUnavailable', message: errorMessage(err) } }); + } + + let child: ReturnType; + try { + child = spawn(process.execPath, [...execArgv, this.#entry], { + env: childEnv(), + cwd: here, + stdio: ['pipe', 'pipe', 'pipe'], + windowsHide: true, + }); + } catch (err) { + return Promise.resolve(killedOutcome(`could not start the sandbox process: ${errorMessage(err)}`)); + } + const { stdin, stdout, stderr } = child; + if (!stdin || !stdout || !stderr) { + child.kill('SIGKILL'); + return Promise.resolve(killedOutcome('the sandbox process has no stdio pipes')); + } + + let session: ChildSession | undefined; + const writer = new BoundedWriter(stdin, { + maxPendingBytes: positive(o.maxPendingReplyBytes, DEFAULTS.maxPendingReplyBytes), + maxTotalBytes: positive(o.maxReplyBytes, DEFAULTS.maxReplyBytes), + deadline, + onExpired: () => session?.timeOut(), + onOverflow: (message) => session?.finish({ ok: false, kind: 'oom', error: { name: 'ReplyBufferFull', message } }), + }); + const active = new ChildSession({ + limits, + maxFrameBytes, + maxTotalBytes: Math.max(MAX_CHILD_OUTPUT_BYTES, 2 * maxFrameBytes), + deadline, + timeoutMs, + hooks: { + onCall: (tool, args) => { + // Never forward a call once the run is stopped, even if the abort event has not been seen yet. + if (opts.signal.aborted) { + active.kill('the run was stopped'); + return Promise.resolve({ ok: false, error: { name: 'ToolError', code: 'cancelled', message: 'the run was stopped' } }); + } + return opts.onCall(tool, args); + }, + onLog: (level, text) => opts.onLog(level, text), + send: (message) => void writer.writeJson(message), + kill: () => { + writer.close(); + child.kill('SIGKILL'); + stdin.destroy(); + }, + }, + }); + session = active; + + // Listen for abort before any callback runs, then re-check: an abort during `onSpawn` must stop the run. + const onAbort = (): void => active.kill('the run was stopped'); + opts.signal.addEventListener('abort', onAbort, { once: true }); + if (child.pid !== undefined) { + try { + o.onSpawn?.(child.pid); + } catch (err) { + active.kill(`onSpawn failed: ${errorMessage(err)}`); + } + } + if (opts.signal.aborted) active.kill('the run was stopped before the script started'); + + stdout.on('data', (chunk: Buffer) => active.feed(chunk)); + stderr.on('data', (chunk: Buffer) => active.stderr(chunk)); + stdin.on('error', () => undefined); + child.on('error', (err) => active.kill(`sandbox process error: ${errorMessage(err)}`)); + child.on('close', (exitCode, signal) => active.exited(exitCode, signal)); + + const timer = setTimeout(() => active.timeOut(), Math.max(0, deadline - performance.now())); + if (!active.finished && !active.expired()) { + // `start` has its own size limit; the reply quotas count only binding results. The writer checks the deadline. + const start = Buffer.from(`${JSON.stringify({ type: 'start', code, timeoutMs: Math.max(1, Math.floor(deadline - performance.now())), limits } satisfies ParentMessage)}\n`, 'utf8'); + if (start.length > MAX_START_BYTES) active.kill(`the script is larger than ${MAX_START_BYTES} bytes`); + else writer.writeStart(start); + } + + return active.outcome.finally(() => { + clearTimeout(timer); + opts.signal.removeEventListener('abort', onAbort); + }); + } +} diff --git a/src/sandbox/session.test.ts b/src/sandbox/session.test.ts new file mode 100644 index 0000000..37e5c5c --- /dev/null +++ b/src/sandbox/session.test.ts @@ -0,0 +1,277 @@ +import { describe, expect, it, vi } from 'vitest'; +import type { CallReply, LogLevel, SandboxOutcome, ToolResult } from '../core/types.js'; +import { OOM_EXIT_CODE, type ParentMessage, type SandboxLimits } from './protocol.js'; +import { ChildSession } from './session.js'; + +const LIMITS: SandboxLimits = { + memoryBytes: 1024 * 1024, + stackBytes: 64 * 1024, + maxCalls: 3, + maxLogBytes: 100, + maxLogLineChars: 50, + maxResultChars: 500, + maxArgsChars: 200, +}; + +function setup(onCall?: (tool: string, args: unknown) => Promise, maxTotalBytes = 100_000, deadline = Infinity) { + const sent: ParentMessage[] = []; + const logs: { level: LogLevel; text: string }[] = []; + const calls: { tool: string; args: unknown }[] = []; + let kills = 0; + const session = new ChildSession({ + limits: LIMITS, + maxFrameBytes: 1_000, + maxTotalBytes, + deadline, + timeoutMs: 1_000, + hooks: { + onCall: (tool, args) => { + calls.push({ tool, args }); + return onCall ? onCall(tool, args) : Promise.resolve({ ok: true, value: { files: [], truncated: false } satisfies ToolResult }); + }, + onLog: (level, text) => logs.push({ level, text }), + send: (m) => sent.push(m), + kill: () => kills++, + }, + }); + const line = (message: unknown): void => session.feed(Buffer.from(`${JSON.stringify(message)}\n`)); + return { session, sent, logs, calls, line, kills: () => kills }; +} + +async function killed(session: ChildSession): Promise { + const outcome: SandboxOutcome = await session.outcome; + if (outcome.ok || outcome.kind !== 'killed') throw new Error(`expected killed, got ${JSON.stringify(outcome)}`); + return outcome.error.message; +} + +const tick = (): Promise => new Promise((resolve) => setImmediate(resolve)); + +describe('ChildSession: valid traffic', () => { + it('forwards calls, replies with the same id, passes logs and settles on done', async () => { + const t = setup(); + t.line({ type: 'call', id: 1, tool: 'glob', args: '{"pattern":"*.ts"}' }); + t.line({ type: 'log', level: 'warn', text: 'careful' }); + await tick(); + expect(t.calls).toEqual([{ tool: 'glob', args: { pattern: '*.ts' } }]); + expect(t.sent).toEqual([{ type: 'reply', id: 1, reply: { ok: true, value: { files: [], truncated: false } } }]); + expect(t.logs).toEqual([{ level: 'warn', text: 'careful' }]); + t.line({ type: 'done', outcome: { ok: true, value: '{"a":[1,2]}' } }); + expect(await t.session.outcome).toEqual({ ok: true, value: { a: [1, 2] } }); + expect(t.kills()).toBe(1); + }); + + it('reassembles messages split across chunks and several messages in one chunk', async () => { + const t = setup(); + const text = `${JSON.stringify({ type: 'log', level: 'log', text: 'one' })}\n${JSON.stringify({ type: 'log', level: 'log', text: 'two' })}\n`; + t.session.feed(Buffer.from(text.slice(0, 7))); + t.session.feed(Buffer.from(text.slice(7, 40))); + t.session.feed(Buffer.from(text.slice(40))); + expect(t.logs.map((l) => l.text)).toEqual(['one', 'two']); + }); + + it('passes error outcomes through', async () => { + const t = setup(); + t.line({ type: 'done', outcome: { ok: false, kind: 'oom', error: { name: 'InternalError', message: 'out of memory' } } }); + expect(await t.session.outcome).toEqual({ ok: false, kind: 'oom', error: { name: 'InternalError', message: 'out of memory' } }); + }); + + it('parses hostile keys in the return value as own data', async () => { + const t = setup(); + t.line({ type: 'done', outcome: { ok: true, value: '{"__proto__":{"polluted":true},"constructor":{"prototype":{"polluted":true}}}' } }); + const outcome = await t.session.outcome; + expect(outcome.ok).toBe(true); + const result = outcome.ok ? outcome.value : undefined; + expect(Object.getPrototypeOf(result)).toBe(Object.prototype); + expect(Object.keys(result as object)).toEqual(['__proto__', 'constructor']); + expect(({} as { polluted?: unknown }).polluted).toBeUndefined(); + }); + + it('kills a child that sends console output past the cap and the room for its truncation note', async () => { + const t = setup(); + for (let i = 0; i < 100; i++) t.line({ type: 'log', level: 'log', text: 'x'.repeat(40) }); + expect(await killed(t.session)).toContain('console output'); + const bytes = t.logs.reduce((n, l) => n + l.text.length + 1, 0); + expect(bytes).toBeLessThanOrEqual(LIMITS.maxLogBytes + 1_024); + expect(t.logs.length).toBeLessThan(100); + }); +}); + +describe('ChildSession: hostile child messages', () => { + it('kills on a line larger than the frame limit, even without a newline', async () => { + const t = setup(); + t.session.feed(Buffer.alloc(600, 0x61)); + expect(t.session.finished).toBe(false); + t.session.feed(Buffer.alloc(600, 0x61)); + expect(await killed(t.session)).toContain('larger than 1000 bytes'); + expect(t.kills()).toBe(1); + }); + + it('kills on an oversize string field', async () => { + const t = setup(); + t.line({ type: 'log', level: 'log', text: 'y'.repeat(300) }); + expect(await killed(t.session)).toContain('invalid message'); + }); + + it('ends at the input budget and forwards the same complete frames regardless of chunking', async () => { + const frame = (id: number) => Buffer.from(`${JSON.stringify({ type: 'call', id, tool: 'read', args: '{"path":"sample.txt"}' })}\n`); + const first = frame(1); + const second = frame(2); + for (const chunks of [[first, second], [Buffer.concat([first, second])]]) { + const t = setup(undefined, first.length + 1); + for (const chunk of chunks) t.session.feed(chunk); + expect(await t.session.outcome).toMatchObject({ ok: false, kind: 'oom', error: { name: 'OutputLimit' } }); + expect(t.calls).toEqual([{ tool: 'read', args: { path: 'sample.txt' } }]); + } + }); + + it('handles no frame once the deadline has passed', async () => { + const t = setup(undefined, 100_000, performance.now() - 1); + t.line({ type: 'log', level: 'log', text: 'late' }); + expect(await t.session.outcome).toMatchObject({ ok: false, kind: 'timeout', error: { name: 'Timeout' } }); + expect(t.logs).toEqual([]); + }); + + it('times out instead of forwarding, settling or replying once the deadline passes after the frame check', async () => { + let now = 0; + const clock = vi.spyOn(performance, 'now').mockImplementation(() => now++); + try { + for (const message of [ + { type: 'call', id: 1, tool: 'read', args: '{"path":"sample.txt"}' }, + { type: 'log', level: 'log', text: 'late' }, + { type: 'done', outcome: { ok: true, value: '1' } }, + ]) { + now = 0; + const t = setup(undefined, 100_000, 1); + t.line(message); + expect(await t.session.outcome).toMatchObject({ ok: false, kind: 'timeout' }); + expect([t.calls, t.logs]).toEqual([[], []]); + } + now = 0; + let answer!: (reply: CallReply) => void; + const t = setup(() => new Promise((resolve) => (answer = resolve)), 100_000, 2); + t.line({ type: 'call', id: 1, tool: 'read', args: '{"path":"sample.txt"}' }); + expect(t.calls).toHaveLength(1); + answer({ ok: true, value: { files: [], truncated: false } }); + expect(await t.session.outcome).toMatchObject({ ok: false, kind: 'timeout' }); + expect(t.sent).toEqual([]); + } finally { + clock.mockRestore(); + } + }); + + it('kills on a line that is not valid UTF-8 and on an empty line', async () => { + const t = setup(); + t.session.feed(Buffer.concat([Buffer.from('{"type":"log","level":"log","text":"a'), Buffer.from([0xff]), Buffer.from('"}\n')])); + expect(await killed(t.session)).toContain('not UTF-8'); + expect(t.logs).toEqual([]); + const empty = setup(); + empty.session.feed(Buffer.from('\n')); + expect(await killed(empty.session)).toContain('not JSON'); + }); + + it('kills on a line that is not JSON', async () => { + const t = setup(); + t.session.feed(Buffer.from('{"type": "call", \n')); + expect(await killed(t.session)).toContain('not JSON'); + }); + + it.each([ + ['unknown type', { type: 'exec', command: 'rm -rf /' }], + ['missing fields', { type: 'call', id: 1 }], + ['extra field', { type: 'log', level: 'log', text: 'x', extra: 1 }], + ['bad level', { type: 'log', level: 'debug', text: 'x' }], + ['non-integer id', { type: 'call', id: 1.5, tool: 'read', args: '{}' }], + ['outcome kind the child may not claim', { type: 'done', outcome: { ok: false, kind: 'killed', error: { name: 'x', message: 'y' } } }], + ['array instead of object', [1, 2, 3]], + ['null', null], + ])('kills on %s', async (_label, message) => { + const t = setup(); + t.line(message); + expect(await killed(t.session)).toContain('invalid message'); + expect(t.calls).toEqual([]); + }); + + it('kills on a call id out of sequence', async () => { + const t = setup(); + t.line({ type: 'call', id: 2, tool: 'read', args: '{}' }); + expect(await killed(t.session)).toContain('expected 1'); + expect(t.calls).toEqual([]); + }); + + it('kills on a repeated call id', async () => { + const t = setup(); + t.line({ type: 'call', id: 1, tool: 'read', args: '{}' }); + t.line({ type: 'call', id: 1, tool: 'read', args: '{}' }); + expect(await killed(t.session)).toContain('expected 2'); + expect(t.calls).toHaveLength(1); + }); + + it('kills when the child exceeds the call cap', async () => { + const t = setup(); + for (let id = 1; id <= 4; id++) t.line({ type: 'call', id, tool: 'read', args: '{}' }); + expect(await killed(t.session)).toContain('limit of 3'); + expect(t.calls).toHaveLength(3); + }); + + it('kills on call arguments that are not JSON', async () => { + const t = setup(); + t.line({ type: 'call', id: 1, tool: 'read', args: '{nope' }); + expect(await killed(t.session)).toContain('not JSON'); + expect(t.calls).toEqual([]); + }); + + it('kills on a return value that is not JSON', async () => { + const t = setup(); + t.line({ type: 'done', outcome: { ok: true, value: 'undefined' } }); + expect(await killed(t.session)).toContain('not JSON'); + }); + + it('ignores everything after the outcome and sends no late replies', async () => { + let release: (reply: CallReply) => void = () => undefined; + const t = setup(() => new Promise((resolve) => (release = resolve))); + t.line({ type: 'call', id: 1, tool: 'read', args: '{}' }); + t.session.kill('stopped by test'); + t.line({ type: 'call', id: 2, tool: 'read', args: '{}' }); + t.line({ type: 'log', level: 'log', text: 'late' }); + release({ ok: true, value: { files: [], truncated: false } }); + await tick(); + expect(await killed(t.session)).toBe('stopped by test'); + expect(t.calls).toHaveLength(1); + expect(t.sent).toEqual([]); + expect(t.logs).toEqual([]); + expect(t.kills()).toBe(1); + }); + + it('turns an unexpected exit into killed with the stderr tail', async () => { + const t = setup(); + t.session.stderr(Buffer.from('fatal: something broke\n')); + t.session.exited(134, null); + const message = await killed(t.session); + expect(message).toContain('exited unexpectedly (code 134)'); + expect(message).toContain('something broke'); + }); + + it('ends the run as oom when the child exits with the out-of-memory code, and as killed when it is signalled', async () => { + const t = setup(); + t.session.exited(OOM_EXIT_CODE, null); + expect(await t.session.outcome).toMatchObject({ ok: false, kind: 'oom', error: { name: 'InternalError' } }); + const signalled = setup(); + signalled.session.exited(OOM_EXIT_CODE, 'SIGKILL'); + expect(await killed(signalled.session)).toContain('signal SIGKILL'); + }); + + it('times out when the child exits with the out-of-memory code after the deadline', async () => { + const t = setup(undefined, 100_000, performance.now() - 1); + t.session.exited(OOM_EXIT_CODE, null); + expect(await t.session.outcome).toMatchObject({ ok: false, kind: 'timeout', error: { name: 'Timeout' } }); + }); + + it('answers a throwing onCall with a tool error instead of crashing', async () => { + const t = setup(() => { + throw new Error('dispatcher bug'); + }); + t.line({ type: 'call', id: 1, tool: 'read', args: '{}' }); + await tick(); + expect(t.sent).toEqual([{ type: 'reply', id: 1, reply: { ok: false, error: { name: 'ToolError', code: 'tool-error', message: 'dispatcher bug' } } }]); + }); +}); diff --git a/src/sandbox/session.ts b/src/sandbox/session.ts new file mode 100644 index 0000000..9332490 --- /dev/null +++ b/src/sandbox/session.ts @@ -0,0 +1,245 @@ +import type { CallReply, LogLevel, SandboxOutcome } from '../core/types.js'; +import { errorMessage } from '../core/errors.js'; +import { childMessageSchema, OOM_EXIT_CODE, type ChildMessage, type ParentMessage, type SandboxLimits } from './protocol.js'; + +/** What a `ChildSession` needs from the outside world. */ +export interface SessionHooks { + /** Forwards a binding call to the dispatcher. Untrusted `tool` and `args`. */ + onCall(tool: string, args: unknown): Promise; + onLog(level: LogLevel, text: string): void; + /** Writes one message to the child. */ + send(message: ParentMessage): void; + /** Kills the child (SIGKILL). Called exactly once, when the session ends. */ + kill(): void; +} + +export interface SessionOptions { + readonly limits: SandboxLimits; + /** Longest line accepted from the child, in bytes. A longer line kills the child. */ + readonly maxFrameBytes: number; + /** Most bytes accepted from the child's stdout over the whole run; past it the run ends with outcome `oom`. */ + readonly maxTotalBytes: number; + /** `performance.now()` time past which no frame is handled; the run ends with outcome `timeout`. */ + readonly deadline: number; + readonly timeoutMs: number; + readonly hooks: SessionHooks; +} + +/** Bytes of log output tolerated above `maxLogBytes` (the child's own "truncated" note). */ +const LOG_SLACK_BYTES = 1_024; +const STDERR_TAIL_CHARS = 2_000; +const utf8 = new TextDecoder('utf-8', { fatal: true, ignoreBOM: true }); + +/** Builds a `killed` outcome. */ +export function killedOutcome(message: string): SandboxOutcome { + return { ok: false, kind: 'killed', error: { name: 'Killed', message } }; +} + +/** + * Parent side of one sandbox run. It reads the child's stdout as + * newline-delimited JSON and treats every message as hostile: an oversize + * line, invalid JSON, an unknown message type, an unexpected call id, more + * calls than the cap or invalid argument JSON kills the child with outcome + * `killed`. It forwards valid calls to `onCall`, logs to `onLog` (capped), and + * settles `outcome` once. After the outcome is settled nothing reaches the + * hooks any more: later messages and late `onCall` replies are dropped. + */ +export class ChildSession { + readonly outcome: Promise; + readonly #limits: SandboxLimits; + readonly #maxFrameBytes: number; + readonly #maxTotalBytes: number; + readonly #deadline: number; + readonly #timeoutMs: number; + readonly #hooks: SessionHooks; + readonly #schema: ReturnType; + #resolve!: (outcome: SandboxOutcome) => void; + #finished = false; + #chunks: Buffer[] = []; + #chunkBytes = 0; + #totalBytes = 0; + #nextCallId = 1; + #logBytes = 0; + #stderr = ''; + + constructor(options: SessionOptions) { + this.#limits = options.limits; + this.#maxFrameBytes = options.maxFrameBytes; + this.#maxTotalBytes = options.maxTotalBytes; + this.#deadline = options.deadline; + this.#timeoutMs = options.timeoutMs; + this.#hooks = options.hooks; + this.#schema = childMessageSchema(options.limits); + this.outcome = new Promise((resolve) => { + this.#resolve = resolve; + }); + } + + get finished(): boolean { + return this.#finished; + } + + /** Number of binding calls forwarded to `onCall`. */ + get callCount(): number { + return this.#nextCallId - 1; + } + + /** Feeds raw bytes from the child's stdout. */ + feed(chunk: Buffer): void { + if (this.#finished) return; + const remaining = this.#maxTotalBytes - this.#totalBytes; + const overflow = chunk.length > remaining; + let rest = chunk.subarray(0, remaining); + this.#totalBytes += rest.length; + while (!this.#finished && rest.length > 0) { + const nl = rest.indexOf(0x0a); + if (nl === -1) { + this.#chunkBytes += rest.length; + if (this.#chunkBytes > this.#maxFrameBytes) return this.kill(`sandbox sent a message larger than ${this.#maxFrameBytes} bytes`); + if (!overflow) this.#chunks.push(rest); + break; + } + const head = rest.subarray(0, nl); + if (this.#chunkBytes + head.length > this.#maxFrameBytes) { + return this.kill(`sandbox sent a message larger than ${this.#maxFrameBytes} bytes`); + } + const line = this.#chunks.length === 0 ? head : Buffer.concat([...this.#chunks, head]); + this.#chunks = []; + this.#chunkBytes = 0; + rest = rest.subarray(nl + 1); + let text: string; + try { + text = utf8.decode(line); + } catch { + return this.kill('sandbox sent a message that is not UTF-8'); + } + this.handleLine(text); + } + if (overflow && !this.#finished) { + this.finish({ ok: false, kind: 'oom', error: { name: 'OutputLimit', message: `the script sent more than ${this.#maxTotalBytes} bytes of child output` } }); + } + } + + /** Handles one complete line from the child. */ + handleLine(line: string): void { + if (this.#finished) return; + let raw: unknown; + try { + raw = JSON.parse(line); + } catch { + return this.kill('sandbox sent a message that is not JSON'); + } + const parsed = this.#schema.safeParse(raw); + if (!parsed.success) return this.kill(`sandbox sent an invalid message: ${parsed.error.issues[0]?.message ?? 'unknown issue'}`); + // Checked per frame: one stdout chunk can carry many frames that arrive after the deadline. + if (this.expired()) return; + this.#handle(parsed.data); + } + + /** Keeps the tail of the child's stderr for the `killed` message of an unexpected exit. */ + stderr(chunk: Buffer): void { + this.#stderr = (this.#stderr + chunk.toString('utf8')).slice(-STDERR_TAIL_CHARS); + } + + /** The child exited. Before an outcome, that is a crash, unless the child reports that its engine ran out of memory. */ + exited(code: number | null, signal: string | null): void { + if (this.#finished) return; + if (code === OOM_EXIT_CODE && signal === null) { + if (this.expired()) return; + return this.finish({ ok: false, kind: 'oom', error: { name: 'InternalError', message: 'out of memory: the script needed more memory than memoryBytes allows' } }); + } + const how = signal !== null ? `signal ${signal}` : `code ${String(code)}`; + const tail = this.#stderr.trim(); + this.kill(`sandbox process exited unexpectedly (${how})${tail ? `: ${tail}` : ''}`); + } + + /** Ends the session with `outcome` and kills the child. Idempotent. */ + finish(outcome: SandboxOutcome): void { + if (this.#finished) return; + this.#finished = true; + this.#chunks = []; + try { + this.#hooks.kill(); + } finally { + this.#resolve(outcome); + } + } + + kill(reason: string): void { + this.finish(killedOutcome(reason)); + } + + timeOut(): void { + this.finish({ ok: false, kind: 'timeout', error: { name: 'Timeout', message: `the script did not finish within ${this.#timeoutMs} ms` } }); + } + + /** Times the run out once the deadline has passed. Checked right before anything is forwarded, written or settled. */ + expired(): boolean { + if (performance.now() < this.#deadline) return false; + this.timeOut(); + return true; + } + + #handle(message: ChildMessage): void { + switch (message.type) { + case 'call': + return this.#call(message.id, message.tool, message.args); + case 'log': + return this.#log(message.level, message.text); + case 'done': + return this.#done(message.outcome); + } + } + + #call(id: number, tool: string, argsJson: string): void { + if (id !== this.#nextCallId) return this.kill(`sandbox sent call id ${id}, expected ${this.#nextCallId}`); + if (id > this.#limits.maxCalls) return this.kill(`sandbox exceeded the limit of ${this.#limits.maxCalls} binding calls`); + let args: unknown; + try { + args = JSON.parse(argsJson); + } catch { + return this.kill('sandbox sent call arguments that are not JSON'); + } + if (this.expired()) return; + this.#nextCallId++; + let pending: Promise; + try { + pending = this.#hooks.onCall(tool, args); + } catch (err) { + pending = Promise.reject(err); + } + pending + .catch((err: unknown): CallReply => ({ ok: false, error: { name: 'ToolError', code: 'tool-error', message: errorMessage(err) } })) + .then((reply) => { + if (this.#finished || this.expired()) return; + try { + this.#hooks.send({ type: 'reply', id, reply }); + } catch (err) { + this.kill(`could not send a reply to the sandbox: ${errorMessage(err)}`); + } + }); + } + + #log(level: LogLevel, text: string): void { + const bytes = Buffer.byteLength(text, 'utf8') + 1; + if (this.#logBytes + bytes > this.#limits.maxLogBytes + LOG_SLACK_BYTES) return this.kill(`sandbox sent more than ${this.#limits.maxLogBytes} bytes of console output`); + this.#logBytes += bytes; + if (this.expired()) return; + this.#hooks.onLog(level, text); + } + + #done(outcome: Extract['outcome']): void { + if (!outcome.ok) { + const { name, message, stack } = outcome.error; + return this.finish({ ok: false, kind: outcome.kind, error: stack === undefined ? { name, message } : { name, message, stack } }); + } + let value: unknown; + try { + value = JSON.parse(outcome.value); + } catch { + return this.kill('sandbox sent a return value that is not JSON'); + } + if (this.expired()) return; + this.finish({ ok: true, value }); + } +} diff --git a/src/sandbox/writer.test.ts b/src/sandbox/writer.test.ts new file mode 100644 index 0000000..787559d --- /dev/null +++ b/src/sandbox/writer.test.ts @@ -0,0 +1,163 @@ +import { EventEmitter } from 'node:events'; +import { describe, expect, it, vi } from 'vitest'; +import { BoundedWriter, jsonBytes, type BoundedWriterOptions } from './writer.js'; + +/** A stream whose reader is stalled until `drainAll()`; it reports false once 10 bytes are buffered. */ +class StalledStream extends EventEmitter { + readonly written: string[] = []; + buffered = 0; + destroyed = false; + get writableLength(): number { + return this.buffered; + } + write(chunk: Buffer): boolean { + this.written.push(chunk.toString('utf8')); + this.buffered += chunk.length; + return this.buffered < 10; + } + drainAll(): void { + this.buffered = 0; + this.emit('drain'); + } +} + +/** Options with no deadline; tests override what they exercise. */ +function options(overrides: Partial = {}): BoundedWriterOptions { + return { maxPendingBytes: 100, maxTotalBytes: 1_000, deadline: Infinity, onExpired: () => undefined, onOverflow: () => undefined, ...overrides }; +} + +/** A fake monotonic clock and the deadline the writer is given. */ +function fakeClock(): { now: () => number; deadline: number; cross: () => void; expirations: () => number; onExpired: () => void } { + let time = 0; + let expired = 0; + return { now: () => time, deadline: 1_000, cross: () => (time = 1_000), expirations: () => expired, onExpired: () => expired++ }; +} + +describe('BoundedWriter', () => { + it('stops writing on backpressure and resumes in order on drain', () => { + const stream = new StalledStream(); + const writer = new BoundedWriter(stream, options()); + for (const line of ['aaaaaaaaaaaa', 'b', 'c']) expect(writer.write(line)).toBe(true); + expect(stream.written).toEqual(['aaaaaaaaaaaa']); + expect(writer.pendingBytes).toBe(14); + stream.drainAll(); + expect(stream.written).toEqual(['aaaaaaaaaaaa', 'b', 'c']); + }); + + it('discards queued replies if the deadline passes before drain', () => { + const stream = new StalledStream(); + const clock = fakeClock(); + const writer = new BoundedWriter(stream, options(clock)); + expect(writer.write('first reply\n')).toBe(true); + expect(writer.writeJson({ result: 'queued' })).toBe(true); + clock.cross(); + stream.drainAll(); + expect(stream.written).toEqual(['first reply\n']); + expect(writer.pendingBytes).toBe(0); + expect(writer.writeJson({ result: 'late' })).toBe(false); + expect(clock.expirations()).toBe(1); + }); + + it('writes nothing when the deadline passes while a queued reply is taken off the queue', () => { + const stream = new StalledStream(); + const clock = fakeClock(); + const writer = new BoundedWriter(stream, options(clock)); + expect(writer.write('first reply\n')).toBe(true); + expect(writer.writeJson({ result: 'queued' })).toBe(true); + // Time passes while the writer takes the queued reply off its queue, after any check made before that. + const shift = Array.prototype.shift; + let dequeued = 0; + Array.prototype.shift = function (this: T[]): T | undefined { + const item: T | undefined = Reflect.apply(shift, this, []); + if (Buffer.isBuffer(item) && item.toString('utf8') === '{"result":"queued"}\n') { + dequeued++; + clock.cross(); + } + return item; + }; + try { + stream.drainAll(); + } finally { + Array.prototype.shift = shift; + } + expect(dequeued).toBe(1); + expect(stream.written).toEqual(['first reply\n']); + expect(clock.expirations()).toBe(1); + expect(writer.pendingBytes).toBe(0); + }); + + it.each([ + ['sizing', 1], + ['serializing', 2], + ] as const)('discards a reply under backpressure if the deadline passes while %s it', (_phase, readAtExpiry) => { + const stream = new StalledStream(); + const clock = fakeClock(); + const writer = new BoundedWriter(stream, options(clock)); + const initial = 'first reply\n'; + expect(writer.write(initial)).toBe(true); + let reads = 0; + const reply = { + get content(): string { + if (++reads === readAtExpiry) clock.cross(); + return 'late'; + }, + }; + expect(writer.writeJson(reply)).toBe(false); + expect(reads).toBe(readAtExpiry); + expect(stream.written).toEqual([initial]); + expect(writer.pendingBytes).toBe(stream.writableLength); + expect(clock.expirations()).toBe(1); + }); + + it('writes the start message outside the caps, and not once the deadline has passed', () => { + const stream = new StalledStream(); + const clock = fakeClock(); + const writer = new BoundedWriter(stream, options({ ...clock, maxPendingBytes: 4, maxTotalBytes: 4 })); + expect(writer.writeStart(Buffer.from('start-12\n'))).toBe(true); + stream.drainAll(); + expect(writer.write('ab\n')).toBe(true); + expect(stream.written).toEqual(['start-12\n', 'ab\n']); + const late = new BoundedWriter(new StalledStream(), options(clock)); + clock.cross(); + expect(late.writeStart(Buffer.from('start\n'))).toBe(false); + expect(clock.expirations()).toBe(1); + }); + + it('calls onOverflow once and keeps memory bounded when the reader never reads', () => { + const stream = new StalledStream(); + const overflows: string[] = []; + const writer = new BoundedWriter(stream, options({ maxPendingBytes: 50, maxTotalBytes: 10_000, onOverflow: (m) => overflows.push(m) })); + let accepted = 0; + for (let i = 0; i < 1_000; i++) if (writer.write('0123456789')) accepted++; + expect(accepted).toBe(5); + expect(writer.pendingBytes).toBeLessThanOrEqual(50); + expect(overflows).toHaveLength(1); + expect(overflows[0]).toContain('not read yet'); + }); + + it('sizes a JSON line exactly and never builds one that is over a cap', () => { + const value = { ok: true, value: { content: 'a"\\\n\u0001é€😀\ud800\udc00x', n: [1, null, undefined, -0.5], sparse: Array(2), skip: undefined } }; + expect(jsonBytes(value, Infinity)).toBe(Buffer.byteLength(JSON.stringify(value))); + const stream = new StalledStream(); + const writer = new BoundedWriter(stream, options({ maxPendingBytes: 1_000, maxTotalBytes: 50 })); + expect(writer.writeJson({ a: 'b' })).toBe(true); + const stringify = vi.spyOn(JSON, 'stringify'); + expect(writer.writeJson({ content: 'z'.repeat(100) })).toBe(false); + const stringified = stringify.mock.calls.length; + stringify.mockRestore(); + expect(stringified).toBe(0); + expect(stream.written).toEqual(['{"a":"b"}\n']); + }); + + it('caps the total bytes even when the reader keeps up', () => { + const stream = new StalledStream(); + const overflows: string[] = []; + const writer = new BoundedWriter(stream, options({ maxPendingBytes: 1_000, maxTotalBytes: 25, onOverflow: (m) => overflows.push(m) })); + expect(writer.write('012345678')).toBe(true); + stream.drainAll(); + expect(writer.write('012345678')).toBe(true); + stream.drainAll(); + expect(writer.write('012345678')).toBe(false); + expect(overflows[0]).toContain('in total'); + }); +}); diff --git a/src/sandbox/writer.ts b/src/sandbox/writer.ts new file mode 100644 index 0000000..d70dd49 --- /dev/null +++ b/src/sandbox/writer.ts @@ -0,0 +1,183 @@ +/** The part of a Node `Writable` that `BoundedWriter` uses. */ +export interface WritableLike { + write(chunk: Buffer): boolean; + readonly writableLength: number; + readonly destroyed: boolean; + once(event: 'drain', listener: () => void): unknown; +} + +export interface BoundedWriterOptions { + /** Most bytes that may wait for the reader (stream buffer plus local queue). */ + readonly maxPendingBytes: number; + /** Most bytes written over the writer's lifetime. */ + readonly maxTotalBytes: number; + /** Monotonic time past which nothing is written. */ + readonly deadline: number; + /** Monotonic clock compared with `deadline`. Default `performance.now`. */ + readonly now?: () => number; + /** Called once when the deadline stops a write; nothing is written after it. */ + readonly onExpired: () => void; + /** Called once when a limit would be exceeded; nothing is written after it. */ + readonly onOverflow: (message: string) => void; +} + +/** + * The only writer to a stream that a possibly stalled reader consumes (the + * sandbox child's stdin). It respects backpressure: once a write returns + * false, lines wait in a local queue until `drain`. The bytes waiting (stream + * buffer plus queue) and the bytes written in total are both capped, so a + * reader that stops reading can never make the writer's process grow without + * bound; hitting a cap calls `onOverflow` instead. + * + * Every byte reaches the stream through `#emit`, which reads the clock right + * before `stream.write`, after the line is sized, encoded and taken off the + * queue: past the deadline nothing more is written and `onExpired` is called. + */ +export class BoundedWriter { + readonly #stream: WritableLike; + readonly #options: BoundedWriterOptions; + #queue: Buffer[] = []; + #queuedBytes = 0; + #totalBytes = 0; + #waitingForDrain = false; + #closed = false; + + constructor(stream: WritableLike, options: BoundedWriterOptions) { + this.#stream = stream; + this.#options = options; + } + + /** Bytes buffered in the stream or queued here, not yet taken by the reader. */ + get pendingBytes(): number { + return this.#stream.writableLength + this.#queuedBytes; + } + + /** Writes or queues `line`, counted against both caps. Returns false when the writer is closed, a cap was hit or the deadline passed. */ + write(line: string): boolean { + if (!this.#canWrite()) return false; + const bytes = Buffer.byteLength(line, 'utf8'); + if (!this.#fits(bytes)) return false; + // Buffers live outside the V8 heap, so pending replies do not count against the server's heap limit. + const chunk = Buffer.from(line, 'utf8'); + this.#totalBytes += bytes; + if (this.#waitingForDrain || this.#queue.length > 0) { + if (!this.#canWrite()) return false; + this.#queue.push(chunk); + this.#queuedBytes += bytes; + return true; + } + return this.#emit(chunk); + } + + /** Writes `value` as one JSON line, sized first so that a line over a cap is never built. */ + writeJson(value: unknown): boolean { + if (!this.#canWrite()) return false; + const room = Math.min(this.#options.maxTotalBytes - this.#totalBytes, this.#options.maxPendingBytes - this.pendingBytes); + const bytes = jsonBytes(value, room) + 1; + return this.#canWrite() && this.#fits(bytes) && this.write(`${JSON.stringify(value)}\n`); + } + + /** Writes `chunk` outside both caps: the sandbox's `start` message, sent before any reply, whose size the caller limits. */ + writeStart(chunk: Buffer): boolean { + return this.#emit(chunk); + } + + /** Drops queued lines; later writes are ignored. */ + close(): void { + this.#closed = true; + this.#queue = []; + this.#queuedBytes = 0; + } + + /** The single call of `stream.write`. */ + #emit(chunk: Buffer): boolean { + if (!this.#canWrite()) return false; + if (!this.#stream.write(chunk)) this.#waitForDrain(); + return true; + } + + #canWrite(): boolean { + if (this.#closed || this.#stream.destroyed) return false; + if (!this.#expired()) return true; + this.close(); + this.#options.onExpired(); + return false; + } + + #expired(): boolean { + return (this.#options.now?.() ?? performance.now()) >= this.#options.deadline; + } + + #fits(bytes: number): boolean { + if (this.#totalBytes + bytes > this.#options.maxTotalBytes) { + return this.#overflow(`binding results sent to the script exceeded ${this.#options.maxTotalBytes} bytes in total`); + } + if (this.pendingBytes + bytes > this.#options.maxPendingBytes) { + return this.#overflow(`binding results the script has not read yet exceeded ${this.#options.maxPendingBytes} bytes`); + } + return true; + } + + /** Past the deadline a full buffer is a timeout, not an overflow. */ + #overflow(message: string): false { + this.close(); + if (this.#expired()) this.#options.onExpired(); + else this.#options.onOverflow(message); + return false; + } + + #waitForDrain(): void { + this.#waitingForDrain = true; + this.#stream.once('drain', () => { + this.#waitingForDrain = false; + this.#flush(); + }); + } + + #flush(): void { + while (!this.#waitingForDrain && this.#queue.length > 0) { + const chunk = this.#queue.shift(); + if (chunk === undefined) break; + this.#queuedBytes -= chunk.length; + if (!this.#emit(chunk)) return; + } + } +} + +/** UTF-8 bytes of `JSON.stringify(value)` for plain JSON data (binding replies), without building it; stops once past `limit`. */ +export function jsonBytes(value: unknown, limit: number): number { + let n = 0; + const visit = (v: unknown): void => { + if (typeof v === 'string') { + n += 2; + for (let i = 0; i < v.length && n <= limit; i++) { + const c = v.charCodeAt(i); + const pair = c >= 0xd800 && c < 0xdc00 && (v.charCodeAt(i + 1) & 0xfc00) === 0xdc00; + if (pair) i++; + // 0x3700 marks \b \t \n \f \r, the control characters with a two-character escape; lone surrogates become \uXXXX. + n += pair ? 4 : c < 0x20 ? ((0x3700 >> c) & 1 ? 2 : 6) : c === 0x22 || c === 0x5c ? 2 : c < 0x80 ? 1 : c < 0x800 ? 2 : c >= 0xd800 && c < 0xe000 ? 6 : 3; + } + } else if (Array.isArray(v)) { + n += 2 + Math.max(0, v.length - 1); + for (let index = 0; index < v.length && n <= limit; index++) visit(v[index] ?? null); + } else if (typeof v === 'object' && v !== null) { + n += 2; + let first = true; + for (const key in v) { + if (n > limit) return; + if (!Object.hasOwn(v, key)) continue; + const item: unknown = Reflect.get(v, key); + if (item === undefined) continue; + n += first ? 1 : 2; + first = false; + visit(key); + if (n > limit) return; + visit(item); + } + } else { + n += (JSON.stringify(v) ?? 'null').length; + } + }; + visit(value); + return n; +}