@johnhenry/andbox 0.1.0 → 0.1.1

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
package/README.md CHANGED
@@ -257,7 +257,8 @@ Creates a new sandboxed runtime. Returns a promise (Worker mode) or object (inli
257
257
  | `capabilities` | `Record<string, Function>` | `{}` | Host functions callable via `host.call()` (Worker mode) |
258
258
  | `defaultTimeoutMs` | `number` | `30000` | Default timeout for `evaluate()` |
259
259
  | `baseURL` | `string` | `location.href` | Base URL for relative imports |
260
- | `allowedImportHosts` | `string[]` | `[]` | Hostnames `sandboxImport()` may load remote `http(s)` modules from (besides `baseURL`'s own host). Import-map targets are host-authored and always allowed. Default: no remote imports. |
260
+ | `allowedImportHosts` | `string[]` | unset | Restricts `sandboxImport()` of remote `http(s)` modules to these hostnames (plus `baseURL`'s own host). **Unset: remote imports are allowed.** Provided: only listed hosts; `[]` denies all remote imports. Import-map targets are host-authored and always allowed. |
261
+ | `untrusted` | `boolean` | `false` | Convenience for untrusted code: selects `mode: 'wasm'`. Throws if combined with another `mode`, and rejects (never falls back to a Worker) if wasm mode is unavailable. See [Security model](#security-model). |
261
262
  | `policy` | `GatePolicy` | -- | Rate limiting policy |
262
263
  | `onConsole` | `(level, ...args) => void` | -- | Console output handler |
263
264
  | `globals` | `Record<string, any>` | `{}` | Global variables (inline/data-uri modes) |
@@ -422,6 +423,11 @@ Code runs inside a Web Worker created from a Blob URL. This gets you, for free,
422
423
 
423
424
  andbox is **not** a boundary against code that is actively trying to escape it. If you're running code you don't fully trust, read this section before you rely on `capabilities`/`policy`/`createNetworkFetch` for anything.
424
425
 
426
+ **Pick the mode by how much you trust the code:**
427
+
428
+ - **`worker` and `node-worker` are for trusted or semi-trusted code** (your own scripts, plugins from known authors, LLM output you review). They organise and throttle what the code does; they do not contain a determined attacker. Still reachable from code in these modes: the platform `import()` operator (fetches and runs remote code, an exfiltration channel; `allowedImportHosts` only governs `sandboxImport()`), timing and `SharedArrayBuffer`/`Atomics` side channels, the Worker's shared realm and heap, any global a future platform adds that is not on the deny-list, and under Node `process`, `require` and the rest of the Node API.
429
+ - **`wasm` is the mode for untrusted code**, and `createSandbox({ untrusted: true })` selects it (and throws or rejects instead of falling back if it is unavailable, or if combined with another `mode`). The code runs in QuickJS compiled to WebAssembly with no ambient authority: no `fetch`, `import()` of URLs, timers, `process` or `require` exist in that engine, and its only way out is `host.call()` through `capabilities`, `policy` and the gate. It has real limits (`fuel`, `memoryBytes`, `stackBytes`, `deadlineMs`) and a hard `terminate()` backstop. It does **not** guarantee: that your own capabilities are safe (whatever you grant is reachable, so keep them narrow), protection from engine or WebAssembly-runtime bugs (still shared process memory; for hostile multi-tenant workloads add OS-level isolation), that an in-flight capability is cancelled when the cooperative deadline fires ([andbox#35](https://github.com/johnhenry/andbox/issues/35)), or Node-level hardening (`nodeWorker.permissions` is not supported in this mode). See [`mode: 'wasm'`](#mode-wasm) and [andbox#10](https://github.com/johnhenry/andbox/issues/10).
430
+
425
431
  **What andbox guarantees:**
426
432
 
427
433
  - **No DOM access.** Worker-mode code executes in a real Worker global scope, which has no `document`, `window`, or other DOM references -- this is a platform property of Workers, not something andbox has to enforce itself.
@@ -435,12 +441,12 @@ andbox is **not** a boundary against code that is actively trying to escape it.
435
441
  **What is still yours:**
436
442
 
437
443
  - **Worker-global APIs: partly removed, not contained.** Since 0.1.0 the worker prelude deletes `fetch`, `WebSocket`, `WebSocketStream`, `WebTransport`, `EventSource`, `XMLHttpRequest`, `Worker`, `SharedWorker`, `importScripts`, `indexedDB`, `caches`, `BroadcastChannel`, `postMessage` and `self` from the global scope before any evaluated code runs (after the runtime has captured what it needs), shadows those names for evaluated code, and gives evaluated code a throwaway `this`. A script no longer gets them by name, through `globalThis`, indirect `eval` or `Function`. **This is hardening, not a boundary, and a Worker is not a security boundary.** Still reachable: the platform `import()` operator (syntax, it cannot be deleted or shadowed: it can fetch and execute remote code and is an exfiltration channel; `allowedImportHosts` only governs `sandboxImport()`), timing and `SharedArrayBuffer`/`Atomics` side channels, anything the engine or platform adds later that is not on the list above (a deny-list can only ever be incomplete), and under Node `process`, `require` and the rest of the Node API (use `nodeWorker.permissions`, and see [Node](#node)). Everything shares the Worker's realm and heap, so any prototype or intrinsic the code mutates is shared with the runtime. A different isolation primitive is required for hostile code: [`mode: 'wasm'`](#mode-wasm) (QuickJS in WebAssembly, no ambient authority) or a cross-origin iframe with a strict CSP. See [andbox#10](https://github.com/johnhenry/andbox/issues/10).
438
- - **`sandboxImport()` remote imports are deny-by-default (0.1.0), and only `sandboxImport()` is governed.** An absolute or protocol-relative `http(s)` specifier is refused (`Import denied: <host> is not in allowedImportHosts`) unless its hostname is in `allowedImportHosts` or is `baseURL`'s own host. Import-map targets and virtual modules are host-authored and unaffected. The check cannot see inside a module once loaded (its own static `import`s) and cannot stop the platform `import()` operator (see the previous item). `mode: 'wasm'` never fetches URLs at all. See [andbox#7](https://github.com/johnhenry/andbox/issues/7).
444
+ - **`sandboxImport()` remote imports: allowed unless `allowedImportHosts` is provided, and only `sandboxImport()` is governed.** With `allowedImportHosts` unset, absolute and protocol-relative `http(s)` specifiers load from any host (0.1.0 denied them by default; 0.1.1 reverted that). Pass `allowedImportHosts: [...]` to restrict to those hostnames plus `baseURL`'s own host (refused with `Import denied: <host> is not in allowedImportHosts`), or `allowedImportHosts: []` to deny all remote imports. Import-map targets and virtual modules are host-authored and unaffected. The check cannot see inside a module once loaded (its own static `import`s) and cannot stop the platform `import()` operator (see the previous item). `mode: 'wasm'` never fetches URLs at all. See [andbox#7](https://github.com/johnhenry/andbox/issues/7).
439
445
  - **A timeout cannot undo in-flight host-side effects; it can ask them to stop.** When the Worker is terminated (timeout, an aborted `evaluate()`, `dispose()`, a crash) every capability call still in flight sees `this.signal` abort, and its late result is dropped rather than delivered. Cancellation is cooperative: a capability that ignores `this.signal` still runs to completion on the host. Write effectful capabilities as `function`s (not arrows) and pass the signal on (`fetch(url, { signal: this.signal })`), and keep them idempotent. In `mode: 'wasm'`, a cooperative `deadlineMs` ends the evaluation without terminating the Worker, so the signal does not abort in that case. See [andbox#8](https://github.com/johnhenry/andbox/issues/8).
440
446
  - **`mode: 'service-worker'` does not provide isolation by merely existing.** It's a hosting mechanism -- a real Service Worker, same-origin by default, serving your `files` map with real fetch/navigation interception. Content served through it can see and touch its own origin exactly like any other same-origin page can; nothing about registering a Service Worker sandboxes what runs inside the pages it serves. If you're hosting content you don't fully trust, point this mode at a genuinely separate origin from day one -- the same recommendation the `fetch`/`WebSocket`/`Worker` item above makes for `worker` mode (a cross-origin iframe with a strict CSP), not something bolted on after the fact. See [andbox#14](https://github.com/johnhenry/andbox/issues/14).
441
447
  - **The Service Worker does not control the very first navigation into its scope.** A page/iframe navigation into `scope` that happens *before* the registration has finished activating is a normal, unintercepted network request -- Service Workers never retroactively intercept a request that already went out. `createSandbox({ mode: 'service-worker' })`'s returned promise only resolves once the registration is active (its generated script also calls `clients.claim()` on activate, which helps *already-open* clients but not fresh navigations); the documented, load-bearing contract is: don't navigate anything into `scope` until that promise resolves. Do that and every request is intercepted from the first byte, because the registration already matches `scope` before the navigation request is made. See [andbox#14](https://github.com/johnhenry/andbox/issues/14).
442
448
 
443
- If you need to run untrusted/adversarial code safely, andbox alone is not sufficient -- pair it with OS-level isolation (a separate process/container with its own network and filesystem restrictions) or use a purpose-built sandboxing runtime. Capability gating and rate limits here are for organizing and throttling code you already trust, not for containing code you don't.
449
+ If you need to run untrusted/adversarial code, use `createSandbox({ untrusted: true })` (`mode: 'wasm'`) and, for hostile multi-tenant workloads, pair it with OS-level isolation (a separate process/container with its own network and filesystem restrictions) or use a purpose-built sandboxing runtime. Capability gating and rate limits here are for organizing and throttling code you already trust, not for containing code you don't.
444
450
 
445
451
  ## Threat model by mode
446
452
 
@@ -451,7 +457,7 @@ What each mode is built to stop, and what it is not. "Hostile" means code active
451
457
  | **Runs in** | The Worker's own JS engine (`new Function`) | QuickJS-ng compiled to WebAssembly, inside the Worker / worker thread |
452
458
  | **Reaching `fetch`, `WebSocket`, `importScripts`, `indexedDB`, `postMessage`** | Removed from the global scope by the prelude (0.1.0), so not reachable by name or via `globalThis`/`eval`/`Function`. Deny-list hardening only: `import()`, timing channels and (Node) `process`/`require` remain. | Not possible. The engine has no such globals, and `constructor`/`eval`/`Function` chains only reach the guest realm. |
453
459
  | **Forging protocol messages to the host** | `postMessage`/`self` are removed; ids are random UUIDs and each `result` must echo a per-evaluate nonce. | Not possible. The guest has no `postMessage` or `self`. |
454
- | **`sandboxImport` of arbitrary URLs / Node builtins** | Remote `http(s)` URLs refused unless listed in `allowedImportHosts`; the raw `import()` operator is still unrestricted (browser), and Node builtins are blocked only with `nodeWorker.permissions` (Node). | Refused: only virtual modules resolve; no URL is fetched. |
460
+ | **`sandboxImport` of arbitrary URLs / Node builtins** | Remote `http(s)` URLs allowed unless `allowedImportHosts` is provided (then only listed hosts; `[]` denies all); the raw `import()` operator is still unrestricted (browser), and Node builtins are blocked only with `nodeWorker.permissions` (Node). | Refused: only virtual modules resolve; no URL is fetched. |
455
461
  | **Prototype-chain names via `host.call`** | Closed by the capability gate (`Object.create(null)`). | Same gate, plus the guest never sees host objects. |
456
462
  | **Infinite loops** | `terminate()` after `timeoutMs`, then a new Worker. | Deterministic `fuel` and a wall-clock `deadlineMs` stop it without a respawn; `terminate()` remains the backstop. |
457
463
  | **Memory exhaustion** | Browser: nothing but the tab limit. Node: opt-in `nodeWorker.maxMemoryMb`. | Guest heap cap plus a hard cap on the engine's linear memory. |
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "@johnhenry/andbox",
3
- "version": "0.1.0",
3
+ "version": "0.1.1",
4
4
  "type": "module",
5
5
  "description": "Sandboxed JavaScript runtime with Worker isolation, RPC, import maps, timeouts, and an optional QuickJS-in-WebAssembly mode",
6
6
  "main": "./src/index.mjs",
package/src/index.d.ts CHANGED
@@ -399,11 +399,18 @@ export interface SandboxOptions {
399
399
  unref?: boolean;
400
400
  /**
401
401
  * Hostnames `sandboxImport()` may load remote http(s) modules from, in
402
- * addition to the host of `baseURL`. Default `[]`: remote imports are
403
- * refused. Import-map targets and virtual modules are not affected. Does
404
- * not restrict the platform `import()` operator in worker mode.
402
+ * addition to the host of `baseURL`. Unset (default): remote imports are
403
+ * allowed. Provided: only these hosts; `[]` denies all remote imports.
404
+ * Import-map targets and virtual modules are not affected. Does not
405
+ * restrict the platform `import()` operator in worker mode.
405
406
  */
406
407
  allowedImportHosts?: string[];
408
+ /**
409
+ * Convenience for untrusted code: selects `mode: 'wasm'`. Throws if `mode`
410
+ * is set to anything else; rejects (never falls back to a Worker) when
411
+ * wasm mode is unavailable.
412
+ */
413
+ untrusted?: boolean;
407
414
  }
408
415
 
409
416
  /** Options for the built-in Node worker_threads mode (`nodeWorker`). */
package/src/sandbox.mjs CHANGED
@@ -316,6 +316,22 @@ const SUPPORTED_MODES = ['worker', 'node-worker', 'wasm', 'inline', 'data-uri',
316
316
  * @returns {{ execute: Function, terminate: Function } | Promise<{ evaluate: Function, defineModule: Function, dispose: Function, isDisposed: () => boolean }> | Promise<{ scriptURL: string, scope: string, define: Function, remove: Function, dispose: Function, isDisposed: () => boolean }>}
317
317
  */
318
318
  export function createSandbox(options = {}) {
319
+ if (options.untrusted === true) {
320
+ // Convenience for untrusted code: always the WebAssembly engine, never a
321
+ // silent downgrade to a Worker (andbox#10).
322
+ if (options.mode !== undefined && options.mode !== 'wasm') {
323
+ throw new Error(
324
+ `createSandbox({ untrusted: true }) requires mode: 'wasm' (got '${String(options.mode)}'); ` +
325
+ 'worker and inline modes are not a boundary for untrusted code.'
326
+ );
327
+ }
328
+ return Promise.resolve(createSandbox({ ...options, untrusted: false, mode: 'wasm' })).catch((err) => {
329
+ throw new Error(
330
+ `createSandbox({ untrusted: true }) needs mode: 'wasm', which is unavailable here: ${err?.message ?? err}`,
331
+ { cause: err }
332
+ );
333
+ });
334
+ }
319
335
  const mode = options.mode ?? 'worker';
320
336
  if (!SUPPORTED_MODES.includes(mode)) {
321
337
  throw new Error(
@@ -402,13 +418,15 @@ async function createWorkerSandbox(options = {}, forceNode = false, isWasm = fal
402
418
  onConsole,
403
419
  nodeWorker,
404
420
  unref = false,
405
- allowedImportHosts = [],
421
+ allowedImportHosts,
406
422
  } = options;
407
423
 
408
- if (!Array.isArray(allowedImportHosts) || !allowedImportHosts.every((h) => typeof h === 'string')) {
424
+ // undefined = unset: remote imports allowed. An array (even empty) restricts.
425
+ if (allowedImportHosts !== undefined &&
426
+ (!Array.isArray(allowedImportHosts) || !allowedImportHosts.every((h) => typeof h === 'string'))) {
409
427
  throw new TypeError('allowedImportHosts must be an array of hostname strings');
410
428
  }
411
- const importHosts = allowedImportHosts.map((h) => h.toLowerCase());
429
+ const importHosts = allowedImportHosts === undefined ? null : allowedImportHosts.map((h) => h.toLowerCase());
412
430
 
413
431
  // Node mode: no global Worker (and no blob: worker URLs) -> node:worker_threads.
414
432
  // An explicit workerFactory always wins; 'node-worker' forces Node; the
@@ -32,7 +32,7 @@ export function makeWorkerSource() {
32
32
  // ── State ──
33
33
  let importMap = { imports: {}, scopes: {} };
34
34
  let baseURL = 'https://andbox.local/';
35
- let allowedImportHosts = [];
35
+ let allowedImportHosts = null; // null = unset: remote imports allowed
36
36
  const virtualModules = new Map();
37
37
  // Node mode only: the adapter provides a loader that lets virtual modules
38
38
  // import each other. Captured once and removed from the global scope.
@@ -65,6 +65,7 @@ const SHADOWED = [...LOCKED_GLOBALS, 'window'];
65
65
 
66
66
  // ── Remote import policy (andbox#7) ──
67
67
  function assertImportAllowed(href) {
68
+ if (allowedImportHosts === null) return;
68
69
  let u;
69
70
  try { u = new URL(href); } catch { return; }
70
71
  if (u.protocol !== 'http:' && u.protocol !== 'https:') return;