@iso4/sandbox 0.6.2 → 0.7.0

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
@@ -88,6 +88,9 @@ const options = {
88
88
  Functions in bridge return values are currently dropped — return plain data,
89
89
  not class instances with methods.
90
90
 
91
+ `SANDBOX_GLOBALS` is a `Set` of every name a fresh sandbox already defines.
92
+ Check generated names against it before installing them.
93
+
91
94
  ## TypeScript-checked rebinding
92
95
 
93
96
  `prepare()` infers the globals shape `G` from what you pass, and the
package/dist/index.d.mts CHANGED
@@ -170,6 +170,9 @@ interface ResourceLimits {
170
170
  * are owned by the runtime; shadowing `Response` would silently break
171
171
  * serialization.
172
172
  *
173
+ * {@link SANDBOX_GLOBALS} holds every name a fresh sandbox defines, V8
174
+ * built-ins included.
175
+ *
173
176
  * Common usage:
174
177
  * ```ts
175
178
  * globals: {
@@ -356,7 +359,7 @@ type RebindGlobals<G extends HostGlobals> = { [K in keyof G as G[K] extends stri
356
359
  type Imports<M extends Record<string, ImportValue> = Record<string, ImportValue>> = M;
357
360
  /**
358
361
  * A single import value. String = source module. Object = host module
359
- * description (the recursive walker handles all nesting).
362
+ * description (nested up to 64 levels, see {@link HostModuleObject}).
360
363
  */
361
364
  type ImportValue = string | HostModuleObject;
362
365
  /**
@@ -373,6 +376,11 @@ type ImportValue = string | HostModuleObject;
373
376
  * path: V8's format would carry them, but only as their own enumerable
374
377
  * properties, so the methods you meant to send would vanish silently. Copy
375
378
  * what you mean to send into a plain object.
379
+ *
380
+ * Shapes may nest at most 64 levels (a node's path length from its top-level
381
+ * export). A deeper shape is rejected at registration, naming the path. Plain
382
+ * objects always describe shape, so this cap also applies to deep plain-object
383
+ * data; data in any other container is bounded only by V8's deserializer.
376
384
  */
377
385
  interface HostModuleObject {
378
386
  [name: string]: HostModuleValue;
@@ -1458,7 +1466,16 @@ interface RunError {
1458
1466
  type ResetCause = "cpu" | "memory" | "wall" | "abort" | "internal";
1459
1467
  type RunErrorCode = "ERR_USER_CODE" | "ERR_MEMORY_LIMIT" | "ERR_CPU_TIMEOUT" | "ERR_WALL_TIMEOUT" | "ERR_ABORTED" | "ERR_MODULE_NOT_FOUND" | "ERR_COMPILE" | "ERR_FUNCTION_ARGUMENT_NOT_SUPPORTED" | "ERR_EXPORT_NOT_SERIALIZABLE" | "ERR_TYPE_NOT_SERIALIZABLE" | "ERR_EXPORT_TOO_LARGE" | "ERR_CALL_TARGET_NOT_FOUND" | "ERR_HOST_BRIDGE" | "ERR_BRIDGE_PAYLOAD_TOO_LARGE" | "ERR_BRIDGE_CALL_LIMIT_EXCEEDED" | "ERR_INSTANCE_RESET" | "ERR_CAPACITY_MEMORY" | "ERR_QUEUE_FULL" | "ERR_UNDECLARED_BINDING" | "ERR_RESERVED_NAME" | "ERR_FROZEN_BINDING" | "ERR_INVALID_REBIND" | "ERR_PREFIX_DID_NOT_SETTLE" | "ERR_PREFIX_BRIDGE_CALL" | "ERR_WARMUP_LIMIT" | "ERR_PREFIX_DISPOSED" | "ERR_PROTOCOL_DESYNC" | "ERR_INTERNAL";
1460
1468
  //#endregion
1469
+ //#region src/globals.d.ts
1470
+ /**
1471
+ * Every global name a fresh sandbox defines: the JS built-ins of the bundled
1472
+ * V8 plus the runtime's own (`console`, `waitUntil`, timers, web classes).
1473
+ * A host global under one of these names replaces the built-in, or is
1474
+ * silently ignored for `undefined`, `NaN` and `Infinity`.
1475
+ */
1476
+ declare const SANDBOX_GLOBALS: ReadonlySet<string>;
1477
+ //#endregion
1461
1478
  //#region src/index.d.ts
1462
1479
  declare function createSandbox(options?: SandboxOptions): Promise<Sandbox>;
1463
1480
  //#endregion
1464
- export { type BridgeCallEntry, type BridgeCallEntryBase, type BridgeCallFailureReason, type BridgeGlobal, type BridgeWithShim, type CallResult, type CallSuccess, type CallTarget, type CreateSandbox, type DataGlobal, type GlobalOptions, type HostExportData, type HostExportFunction, type HostGlobalValue, type HostGlobals, type HostModuleObject, type HostModuleValue, type ImportValue, type Imports, type MemoryLimit, type OneOffResourceLimits, type PrecompileOptions, type Prefix, type PrefixCallOptions, type PrefixRunOptions, type ReadExportsOptions, type ReadExportsResult, type RebindGlobals, type RebindHostModule, type RebindImports, type RebindValue, type ResetCause, type ResourceLimits, type RunCallOptions, type RunError, type RunErrorCode, type RunFailure, type RunOptions, type RunResult, type RunSuccess, type Sandbox, type SandboxExports, type SandboxOptions, type SandboxStats, type StringGlobal, type WaitUntilResult, createSandbox };
1481
+ export { type BridgeCallEntry, type BridgeCallEntryBase, type BridgeCallFailureReason, type BridgeGlobal, type BridgeWithShim, type CallResult, type CallSuccess, type CallTarget, type CreateSandbox, type DataGlobal, type GlobalOptions, type HostExportData, type HostExportFunction, type HostGlobalValue, type HostGlobals, type HostModuleObject, type HostModuleValue, type ImportValue, type Imports, type MemoryLimit, type OneOffResourceLimits, type PrecompileOptions, type Prefix, type PrefixCallOptions, type PrefixRunOptions, type ReadExportsOptions, type ReadExportsResult, type RebindGlobals, type RebindHostModule, type RebindImports, type RebindValue, type ResetCause, type ResourceLimits, type RunCallOptions, type RunError, type RunErrorCode, type RunFailure, type RunOptions, type RunResult, type RunSuccess, SANDBOX_GLOBALS, type Sandbox, type SandboxExports, type SandboxOptions, type SandboxStats, type StringGlobal, type WaitUntilResult, createSandbox };
package/dist/index.mjs CHANGED
@@ -9,6 +9,7 @@ import { fileURLToPath } from "node:url";
9
9
  import { createConnection } from "node:net";
10
10
  import { Buffer } from "node:buffer";
11
11
  import v8 from "node:v8";
12
+ import { types } from "node:util";
12
13
  //#region src/binary.ts
13
14
  function resolveRuntimeBinary(options = {}) {
14
15
  if (options.binaryPath) return options.binaryPath;
@@ -310,11 +311,6 @@ async function toDescriptor(value, brandKey, streams) {
310
311
  };
311
312
  }
312
313
  /**
313
- * Depth cap, matching `MAX_DEPTH` in `webcodec.rs`. Cycles are handled by the
314
- * `seen` map, so this only bounds pathologically deep graphs.
315
- */
316
- const MAX_DEPTH = 32;
317
- /**
318
314
  * Replace every `Request`/`Response`/`Headers` anywhere in `value` with a
319
315
  * branded plain object, returning a graph ordinary serialization can write.
320
316
  *
@@ -324,18 +320,43 @@ const MAX_DEPTH = 32;
324
320
  * instance and do not reuse it afterwards (streams cannot cross the boundary,
325
321
  * so the body must be buffered rather than forwarded). Object identity and
326
322
  * cycles are preserved through `seen`. `Map`/`Set` are rebuilt because a host
327
- * type can hide in either.
323
+ * type can hide in either. A value with no host type (and no Proxy) anywhere
324
+ * is returned as is, so the common case costs one scan and no copy. Depth is not capped:
325
+ * the scan is iterative and every level of the rebuild suspends on an
326
+ * `await`, so neither deepens the call stack.
328
327
  * @param value the value to transform
329
328
  * @param brandKey the sandbox's session brand key ({@link brandKeyForToken});
330
329
  * the runtime rehydrates only descriptors stamped with it
331
330
  * @param streams
332
331
  */
333
332
  async function materializeHostTypes(value, brandKey, streams) {
334
- return transform(value, brandKey, streams, /* @__PURE__ */ new Map(), 0);
333
+ if (!hasHostType(value)) return value;
334
+ return transform(value, brandKey, streams, /* @__PURE__ */ new Map());
335
+ }
336
+ function hasHostType(value) {
337
+ const seen = /* @__PURE__ */ new Set();
338
+ const stack = [];
339
+ const push = (v) => {
340
+ if (v !== null && typeof v === "object") stack.push(v);
341
+ };
342
+ push(value);
343
+ for (let v = stack.pop(); v !== void 0; v = stack.pop()) {
344
+ if (seen.has(v)) continue;
345
+ seen.add(v);
346
+ if (v instanceof globalThis.Response || v instanceof globalThis.Request || v instanceof globalThis.Headers || types.isProxy(v)) return true;
347
+ if (ArrayBuffer.isView(v) || v instanceof ArrayBuffer || v instanceof Date || v instanceof RegExp || v instanceof Error) continue;
348
+ if (Array.isArray(v)) for (const item of v) push(item);
349
+ else if (v instanceof Map) for (const [k, item] of v) {
350
+ push(k);
351
+ push(item);
352
+ }
353
+ else if (v instanceof Set) for (const item of v) push(item);
354
+ else for (const item of Object.values(v)) push(item);
355
+ }
356
+ return false;
335
357
  }
336
- async function transform(value, brandKey, streams, seen, depth) {
358
+ async function transform(value, brandKey, streams, seen) {
337
359
  if (value === null || typeof value !== "object") return value;
338
- if (depth > MAX_DEPTH) throw new HostTypeError(`[iso4] value nests deeper than ${MAX_DEPTH} levels; cannot scan it for host types`);
339
360
  const existing = seen.get(value);
340
361
  if (existing !== void 0) return existing;
341
362
  const descriptor = await toDescriptor(value, brandKey, streams);
@@ -347,24 +368,24 @@ async function transform(value, brandKey, streams, seen, depth) {
347
368
  if (Array.isArray(value)) {
348
369
  const out = [];
349
370
  seen.set(value, out);
350
- for (const item of value) out.push(await transform(item, brandKey, streams, seen, depth + 1));
371
+ for (const item of value) out.push(await transform(item, brandKey, streams, seen));
351
372
  return out;
352
373
  }
353
374
  if (value instanceof Map) {
354
375
  const out = /* @__PURE__ */ new Map();
355
376
  seen.set(value, out);
356
- for (const [k, v] of value) out.set(await transform(k, brandKey, streams, seen, depth + 1), await transform(v, brandKey, streams, seen, depth + 1));
377
+ for (const [k, v] of value) out.set(await transform(k, brandKey, streams, seen), await transform(v, brandKey, streams, seen));
357
378
  return out;
358
379
  }
359
380
  if (value instanceof Set) {
360
381
  const out = /* @__PURE__ */ new Set();
361
382
  seen.set(value, out);
362
- for (const v of value) out.add(await transform(v, brandKey, streams, seen, depth + 1));
383
+ for (const v of value) out.add(await transform(v, brandKey, streams, seen));
363
384
  return out;
364
385
  }
365
386
  const out = Object.create(null);
366
387
  seen.set(value, out);
367
- for (const [k, v] of Object.entries(value)) out[k] = await transform(v, brandKey, streams, seen, depth + 1);
388
+ for (const [k, v] of Object.entries(value)) out[k] = await transform(v, brandKey, streams, seen);
368
389
  return out;
369
390
  }
370
391
  function readStr(des) {
@@ -1857,8 +1878,6 @@ function parseRustToTsMessageType(byte) {
1857
1878
  function formatByte(byte) {
1858
1879
  return `0x${byte.toString(16).padStart(2, "0")}`;
1859
1880
  }
1860
- //#endregion
1861
- //#region src/imports.ts
1862
1881
  /**
1863
1882
  * The dispatch-map key for one host-module function leaf. The NUL separator
1864
1883
  * cannot collide with anything a specifier or dot-joined path can contain in
@@ -1925,6 +1944,7 @@ function processImports(imports) {
1925
1944
  * @param seen
1926
1945
  */
1927
1946
  function lowerNode(specifier, value, path, handlers, seen = /* @__PURE__ */ new Set()) {
1947
+ if (path.length > 64) throw new Error(`[@iso4/sandbox] imports['${specifier}'].${path.join(".")}: host-module shapes may nest at most 64 levels deep`);
1928
1948
  if (typeof value === "function") {
1929
1949
  handlers.set(importHandlerKey(specifier, path.join(".")), value);
1930
1950
  return { kind: "function" };
@@ -3281,6 +3301,90 @@ var RunPool = class {
3281
3301
  };
3282
3302
  //#endregion
3283
3303
  //#region src/globals.ts
3304
+ /**
3305
+ * Every global name a fresh sandbox defines: the JS built-ins of the bundled
3306
+ * V8 plus the runtime's own (`console`, `waitUntil`, timers, web classes).
3307
+ * A host global under one of these names replaces the built-in, or is
3308
+ * silently ignored for `undefined`, `NaN` and `Infinity`.
3309
+ */
3310
+ const SANDBOX_GLOBALS = new Set([
3311
+ "AggregateError",
3312
+ "Array",
3313
+ "ArrayBuffer",
3314
+ "AsyncDisposableStack",
3315
+ "Atomics",
3316
+ "BigInt",
3317
+ "BigInt64Array",
3318
+ "BigUint64Array",
3319
+ "Boolean",
3320
+ "DataView",
3321
+ "Date",
3322
+ "DisposableStack",
3323
+ "Error",
3324
+ "EvalError",
3325
+ "FinalizationRegistry",
3326
+ "Float16Array",
3327
+ "Float32Array",
3328
+ "Float64Array",
3329
+ "Function",
3330
+ "Headers",
3331
+ "Infinity",
3332
+ "Int16Array",
3333
+ "Int32Array",
3334
+ "Int8Array",
3335
+ "Intl",
3336
+ "Iterator",
3337
+ "JSON",
3338
+ "Map",
3339
+ "Math",
3340
+ "NaN",
3341
+ "Number",
3342
+ "Object",
3343
+ "Promise",
3344
+ "Proxy",
3345
+ "RangeError",
3346
+ "ReferenceError",
3347
+ "Reflect",
3348
+ "RegExp",
3349
+ "Request",
3350
+ "Response",
3351
+ "Set",
3352
+ "String",
3353
+ "SuppressedError",
3354
+ "Symbol",
3355
+ "SyntaxError",
3356
+ "Temporal",
3357
+ "TextDecoder",
3358
+ "TextEncoder",
3359
+ "TypeError",
3360
+ "URIError",
3361
+ "URL",
3362
+ "URLSearchParams",
3363
+ "Uint16Array",
3364
+ "Uint32Array",
3365
+ "Uint8Array",
3366
+ "Uint8ClampedArray",
3367
+ "WeakMap",
3368
+ "WeakRef",
3369
+ "WeakSet",
3370
+ "clearTimeout",
3371
+ "console",
3372
+ "decodeURI",
3373
+ "decodeURIComponent",
3374
+ "encodeURI",
3375
+ "encodeURIComponent",
3376
+ "escape",
3377
+ "eval",
3378
+ "globalThis",
3379
+ "isFinite",
3380
+ "isNaN",
3381
+ "parseFloat",
3382
+ "parseInt",
3383
+ "setTimeout",
3384
+ "undefined",
3385
+ "unescape",
3386
+ "waitUntil"
3387
+ ]);
3284
3388
  function isBridgeWithShim(v) {
3285
3389
  return typeof v === "object" && v !== null && v.kind === "bridge-with-shim";
3286
3390
  }
@@ -4181,4 +4285,4 @@ var PrefixImpl = class {
4181
4285
  }
4182
4286
  };
4183
4287
  //#endregion
4184
- export { createSandbox };
4288
+ export { SANDBOX_GLOBALS, createSandbox };
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "@iso4/sandbox",
3
- "version": "0.6.2",
3
+ "version": "0.7.0",
4
4
  "type": "module",
5
5
  "description": "Fast, sandboxed V8 isolate runtime for agent-generated JavaScript. Two-process architecture for crash isolation.",
6
6
  "keywords": [
@@ -49,10 +49,10 @@
49
49
  "vitest": "^4.1.5"
50
50
  },
51
51
  "optionalDependencies": {
52
- "@iso4/v8-darwin-arm64": "^0.6.2",
53
- "@iso4/v8-darwin-x64": "^0.6.2",
54
- "@iso4/v8-linux-arm64-gnu": "^0.6.2",
55
- "@iso4/v8-linux-x64-gnu": "^0.6.2"
52
+ "@iso4/v8-darwin-arm64": "^0.7.0",
53
+ "@iso4/v8-darwin-x64": "^0.7.0",
54
+ "@iso4/v8-linux-arm64-gnu": "^0.7.0",
55
+ "@iso4/v8-linux-x64-gnu": "^0.7.0"
56
56
  },
57
57
  "engines": {
58
58
  "node": ">=24.0.0"