@iso4/sandbox 0.7.0 → 0.8.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
@@ -70,7 +70,7 @@ await sandbox.dispose()
70
70
 
71
71
  ## How globals work
72
72
 
73
- `globals` wires any non-reserved name directly into the sandbox's global
73
+ `globals` wires any non-reserved identifier directly into the sandbox's global
74
74
  object as a bridge stub. The bridge is fully generic — `fetch` is not
75
75
  special-cased:
76
76
 
@@ -88,8 +88,16 @@ 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
+ Global names must be usable by bare name: iso4 refuses one that is not a
92
+ JavaScript identifier (`my-tool`) or is a reserved word (`class`, `true`)
93
+ with `ERR_INVALID_GLOBAL_NAME`. Unicode identifiers (`café`) and `eval` and
94
+ `arguments` are allowed.
95
+
91
96
  `SANDBOX_GLOBALS` is a `Set` of every name a fresh sandbox already defines.
92
- Check generated names against it before installing them.
97
+ Check generated names against it before installing them. `RESERVED_WORDS`
98
+ is a `Set` of names that cannot be a binding in module source, such as
99
+ `class` or `eval`; iso4 refuses host-module export names in it, and global
100
+ names in it other than `eval` and `arguments`.
93
101
 
94
102
  ## TypeScript-checked rebinding
95
103
 
package/dist/index.d.mts CHANGED
@@ -161,8 +161,9 @@ interface ResourceLimits {
161
161
  graceMs?: number;
162
162
  }
163
163
  /**
164
- * Host-provided globals. Any name not reserved by V8 or the runtime is
165
- * permitted. Each value becomes a bridge stub in the sandbox global object.
164
+ * Host-provided globals. Any name not reserved by the runtime that sandbox
165
+ * code can reference by bare name is permitted. Each value becomes a bridge
166
+ * stub in the sandbox global object.
166
167
  *
167
168
  * Reserved names (rejected with `ERR_RESERVED_NAME`): `console`,
168
169
  * `waitUntil`, `setTimeout`, `clearTimeout`, `Headers`, `Request`,
@@ -170,6 +171,12 @@ interface ResourceLimits {
170
171
  * are owned by the runtime; shadowing `Response` would silently break
171
172
  * serialization.
172
173
  *
174
+ * A name sandbox code cannot reference by bare name is rejected with
175
+ * `ERR_INVALID_GLOBAL_NAME`: one that is not a JavaScript identifier
176
+ * (`my-tool`, `1abc`; Unicode identifiers such as `café` are fine), or one in
177
+ * {@link RESERVED_WORDS} other than `eval` and `arguments`. Keys nested inside
178
+ * a global's value are unrestricted.
179
+ *
173
180
  * {@link SANDBOX_GLOBALS} holds every name a fresh sandbox defines, V8
174
181
  * built-ins included.
175
182
  *
@@ -901,7 +908,8 @@ interface Prefix<G extends HostGlobals = {}, M extends Imports = {}> {
901
908
  * `G` is the declared-globals shape from the matching `precompile()` call.
902
909
  * The `globals` field is typed as `Partial<G>` — only names present in `G`
903
910
  * may be overridden. Passing any other name is a TypeScript error at compile
904
- * time and `ERR_UNDECLARED_BINDING` at runtime.
911
+ * time and `ERR_UNDECLARED_BINDING` at runtime (`ERR_INVALID_GLOBAL_NAME`
912
+ * first, for a name sandbox code cannot reference by bare name).
905
913
  */
906
914
  interface PrefixRunOptions<G extends HostGlobals, M extends Imports> {
907
915
  /**
@@ -911,7 +919,8 @@ interface PrefixRunOptions<G extends HostGlobals, M extends Imports> {
911
919
  /**
912
920
  * Override implementations for a **subset** of globals declared at
913
921
  * precompile time. Only names present in `G` are accepted (TypeScript
914
- * error + runtime `ERR_UNDECLARED_BINDING` for anything else), but the
922
+ * error + runtime `ERR_UNDECLARED_BINDING` for anything else, or
923
+ * `ERR_INVALID_GLOBAL_NAME` for a name unusable by bare name), but the
915
924
  * function signature does not need to match the precompile-time handler
916
925
  * exactly — any `HostExportFunction`-compatible value is accepted.
917
926
  */
@@ -1464,18 +1473,28 @@ interface RunError {
1464
1473
  * `RunError.resetCause`.
1465
1474
  */
1466
1475
  type ResetCause = "cpu" | "memory" | "wall" | "abort" | "internal";
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";
1476
+ 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_INVALID_GLOBAL_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";
1468
1477
  //#endregion
1469
1478
  //#region src/globals.d.ts
1470
1479
  /**
1471
1480
  * Every global name a fresh sandbox defines: the JS built-ins of the bundled
1472
1481
  * V8 plus the runtime's own (`console`, `waitUntil`, timers, web classes).
1473
1482
  * A host global under one of these names replaces the built-in, or is
1474
- * silently ignored for `undefined`, `NaN` and `Infinity`.
1483
+ * silently ignored for `undefined`, `NaN` and `Infinity`. Names the grammar
1484
+ * forbids outright are in {@link RESERVED_WORDS}.
1475
1485
  */
1476
1486
  declare const SANDBOX_GLOBALS: ReadonlySet<string>;
1487
+ /**
1488
+ * Every name that cannot be a binding in module source, so it cannot be a
1489
+ * host-module export name. As host global names, all but `eval` and
1490
+ * `arguments` are refused with `ERR_INVALID_GLOBAL_NAME`. `default` is
1491
+ * included, though iso4 itself accepts it as a host-module export (emitted as
1492
+ * `export default`). Unlike {@link SANDBOX_GLOBALS}, which lists names that
1493
+ * are taken, these are names the grammar forbids.
1494
+ */
1495
+ declare const RESERVED_WORDS: ReadonlySet<string>;
1477
1496
  //#endregion
1478
1497
  //#region src/index.d.ts
1479
1498
  declare function createSandbox(options?: SandboxOptions): Promise<Sandbox>;
1480
1499
  //#endregion
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 };
1500
+ 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, RESERVED_WORDS, 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
@@ -655,7 +655,11 @@ const TsToRustMessageTypes = {
655
655
  * The host dropped an outbound streamed body (consumer cancel, dispose);
656
656
  * the runtime cancels the guest source.
657
657
  */
658
- StreamCancel: 12
658
+ StreamCancel: 12,
659
+ /**
660
+ * Orderly close: the host is done with this connection. Empty payload.
661
+ */
662
+ Close: 13
659
663
  };
660
664
  const RustToTsMessageTypes = {
661
665
  BridgeCall: 1,
@@ -1878,6 +1882,337 @@ function parseRustToTsMessageType(byte) {
1878
1882
  function formatByte(byte) {
1879
1883
  return `0x${byte.toString(16).padStart(2, "0")}`;
1880
1884
  }
1885
+ //#endregion
1886
+ //#region src/globals.ts
1887
+ /**
1888
+ * Every global name a fresh sandbox defines: the JS built-ins of the bundled
1889
+ * V8 plus the runtime's own (`console`, `waitUntil`, timers, web classes).
1890
+ * A host global under one of these names replaces the built-in, or is
1891
+ * silently ignored for `undefined`, `NaN` and `Infinity`. Names the grammar
1892
+ * forbids outright are in {@link RESERVED_WORDS}.
1893
+ */
1894
+ const SANDBOX_GLOBALS = new Set([
1895
+ "AggregateError",
1896
+ "Array",
1897
+ "ArrayBuffer",
1898
+ "AsyncDisposableStack",
1899
+ "Atomics",
1900
+ "BigInt",
1901
+ "BigInt64Array",
1902
+ "BigUint64Array",
1903
+ "Boolean",
1904
+ "DataView",
1905
+ "Date",
1906
+ "DisposableStack",
1907
+ "Error",
1908
+ "EvalError",
1909
+ "FinalizationRegistry",
1910
+ "Float16Array",
1911
+ "Float32Array",
1912
+ "Float64Array",
1913
+ "Function",
1914
+ "Headers",
1915
+ "Infinity",
1916
+ "Int16Array",
1917
+ "Int32Array",
1918
+ "Int8Array",
1919
+ "Intl",
1920
+ "Iterator",
1921
+ "JSON",
1922
+ "Map",
1923
+ "Math",
1924
+ "NaN",
1925
+ "Number",
1926
+ "Object",
1927
+ "Promise",
1928
+ "Proxy",
1929
+ "RangeError",
1930
+ "ReferenceError",
1931
+ "Reflect",
1932
+ "RegExp",
1933
+ "Request",
1934
+ "Response",
1935
+ "Set",
1936
+ "String",
1937
+ "SuppressedError",
1938
+ "Symbol",
1939
+ "SyntaxError",
1940
+ "Temporal",
1941
+ "TextDecoder",
1942
+ "TextEncoder",
1943
+ "TypeError",
1944
+ "URIError",
1945
+ "URL",
1946
+ "URLSearchParams",
1947
+ "Uint16Array",
1948
+ "Uint32Array",
1949
+ "Uint8Array",
1950
+ "Uint8ClampedArray",
1951
+ "WeakMap",
1952
+ "WeakRef",
1953
+ "WeakSet",
1954
+ "clearTimeout",
1955
+ "console",
1956
+ "decodeURI",
1957
+ "decodeURIComponent",
1958
+ "encodeURI",
1959
+ "encodeURIComponent",
1960
+ "escape",
1961
+ "eval",
1962
+ "globalThis",
1963
+ "isFinite",
1964
+ "isNaN",
1965
+ "parseFloat",
1966
+ "parseInt",
1967
+ "setTimeout",
1968
+ "undefined",
1969
+ "unescape",
1970
+ "waitUntil"
1971
+ ]);
1972
+ /**
1973
+ * Every name that cannot be a binding in module source, so it cannot be a
1974
+ * host-module export name. As host global names, all but `eval` and
1975
+ * `arguments` are refused with `ERR_INVALID_GLOBAL_NAME`. `default` is
1976
+ * included, though iso4 itself accepts it as a host-module export (emitted as
1977
+ * `export default`). Unlike {@link SANDBOX_GLOBALS}, which lists names that
1978
+ * are taken, these are names the grammar forbids.
1979
+ */
1980
+ const RESERVED_WORDS = new Set([
1981
+ "break",
1982
+ "case",
1983
+ "catch",
1984
+ "class",
1985
+ "const",
1986
+ "continue",
1987
+ "debugger",
1988
+ "default",
1989
+ "delete",
1990
+ "do",
1991
+ "else",
1992
+ "export",
1993
+ "extends",
1994
+ "finally",
1995
+ "for",
1996
+ "function",
1997
+ "if",
1998
+ "import",
1999
+ "in",
2000
+ "instanceof",
2001
+ "new",
2002
+ "return",
2003
+ "super",
2004
+ "switch",
2005
+ "this",
2006
+ "throw",
2007
+ "try",
2008
+ "typeof",
2009
+ "var",
2010
+ "void",
2011
+ "while",
2012
+ "with",
2013
+ "yield",
2014
+ "let",
2015
+ "static",
2016
+ "enum",
2017
+ "await",
2018
+ "implements",
2019
+ "package",
2020
+ "protected",
2021
+ "interface",
2022
+ "private",
2023
+ "public",
2024
+ "null",
2025
+ "true",
2026
+ "false",
2027
+ "eval",
2028
+ "arguments"
2029
+ ]);
2030
+ /**
2031
+ * A JavaScript identifier name, Unicode included: ID_Start/ID_Continue plus
2032
+ * `$`, `_`, ZWNJ and ZWJ.
2033
+ */
2034
+ const IDENTIFIER_NAME = /^[\p{ID_Start}$_][\p{ID_Continue}$\u200C\u200D]*$/u;
2035
+ /**
2036
+ * A host global name sandbox code cannot reference by bare name. Carries the
2037
+ * same code and message the runtime reports for it.
2038
+ */
2039
+ var GlobalNameError = class extends Error {
2040
+ code = "ERR_INVALID_GLOBAL_NAME";
2041
+ };
2042
+ function isBridgeWithShim(v) {
2043
+ return typeof v === "object" && v !== null && v.kind === "bridge-with-shim";
2044
+ }
2045
+ function isDataGlobal(v) {
2046
+ return typeof v === "object" && v !== null && v.kind === "data";
2047
+ }
2048
+ function isBridgeGlobal(v) {
2049
+ return typeof v === "object" && v !== null && v.kind === "bridge";
2050
+ }
2051
+ function isStringGlobal(v) {
2052
+ return typeof v === "object" && v !== null && v.kind === "string";
2053
+ }
2054
+ /**
2055
+ * Private bridge-dispatch name for a `BridgeWithShim` handler. This is a wire
2056
+ * dispatch key and an object-property key — never interpolated into generated
2057
+ * code — so any global name is safe. The runtime recognises the
2058
+ * `__iso4_<name>_h` convention (`public_record_name` in `v8.rs`) and reports
2059
+ * bridge records under the public `<name>`.
2060
+ * @param name public global name
2061
+ */
2062
+ function shimHandlerName(name) {
2063
+ return `__iso4_${name}_h`;
2064
+ }
2065
+ /**
2066
+ * Throw {@link GlobalNameError} unless sandbox code can reference `name` by
2067
+ * bare name. Mirrored by `check_bare_global_name` in `v8.rs`.
2068
+ * @param name host global name
2069
+ */
2070
+ function checkGlobalName(name) {
2071
+ if (name !== "eval" && name !== "arguments" && (!IDENTIFIER_NAME.test(name) || RESERVED_WORDS.has(name))) throw new GlobalNameError(`global '${name}' cannot be referenced by bare name in sandbox code`);
2072
+ }
2073
+ /**
2074
+ * Lower a `HostGlobals` map into wire-shaped `defs` plus the bridge-dispatch
2075
+ * map. See the module comment for the split. Throws {@link GlobalNameError}
2076
+ * for a name sandbox code cannot reference by bare name.
2077
+ * - `HostExportFunction` → `{ kind: 'bridge' }` + dispatch entry.
2078
+ * - `string` → `{ kind: 'string', expr }` (evaluated by Rust).
2079
+ * - `DataGlobal` → `{ kind: 'data', value }` (materialised by Rust).
2080
+ * - `BridgeWithShim` → `{ kind: 'shim', shim, handlerName }` + a dispatch
2081
+ * entry for the private handler under `handlerName`.
2082
+ * @param globals
2083
+ */
2084
+ function processGlobals(globals) {
2085
+ const defs = [];
2086
+ const dispatch = {};
2087
+ for (const [name, value] of Object.entries(globals)) {
2088
+ checkGlobalName(name);
2089
+ if (typeof value === "function") {
2090
+ defs.push({
2091
+ kind: "bridge",
2092
+ name,
2093
+ enumerable: true
2094
+ });
2095
+ dispatch[name] = value;
2096
+ } else if (typeof value === "string") defs.push({
2097
+ kind: "string",
2098
+ name,
2099
+ expr: value,
2100
+ enumerable: true
2101
+ });
2102
+ else if (isBridgeGlobal(value)) {
2103
+ defs.push({
2104
+ kind: "bridge",
2105
+ name,
2106
+ enumerable: value.enumerable ?? true
2107
+ });
2108
+ dispatch[name] = value.handler;
2109
+ } else if (isStringGlobal(value)) defs.push({
2110
+ kind: "string",
2111
+ name,
2112
+ expr: value.expr,
2113
+ enumerable: value.enumerable ?? true
2114
+ });
2115
+ else if (isDataGlobal(value)) defs.push({
2116
+ kind: "data",
2117
+ name,
2118
+ value: value.value,
2119
+ enumerable: value.enumerable ?? true
2120
+ });
2121
+ else if (isBridgeWithShim(value)) {
2122
+ const handlerName = shimHandlerName(name);
2123
+ defs.push({
2124
+ kind: "shim",
2125
+ name,
2126
+ shim: value.shim,
2127
+ handlerName,
2128
+ enumerable: value.enumerable ?? true
2129
+ });
2130
+ dispatch[handlerName] = value.handler;
2131
+ }
2132
+ }
2133
+ return {
2134
+ defs,
2135
+ dispatch
2136
+ };
2137
+ }
2138
+ /**
2139
+ * Resolve bridge globals for a `prefix.run()` call.
2140
+ *
2141
+ * String/data globals and shim *wrappers* are already compiled into the
2142
+ * declared prefix state, replayed by the runtime when the prefix evaluates —
2143
+ * only the bridge *stubs* they call need re-installing per run (bridge stubs
2144
+ * are bound to the run's socket). So
2145
+ * every returned def is `kind: 'bridge'`, and shimmed globals are routed to
2146
+ * their private `__iso4_<name>_h` key so rebinding updates the handler the
2147
+ * shim calls, without touching the shim itself.
2148
+ * @param runGlobals
2149
+ * @param precompileGlobals
2150
+ */
2151
+ /**
2152
+ * Resolve a per-run override for a declared bridge global.
2153
+ *
2154
+ * An omitted key falls back to the precompile-time handler (the intended
2155
+ * default). But a key that IS supplied yet is not a function — the runtime
2156
+ * shape TypeScript cannot catch, e.g. a tenant handler that resolves to
2157
+ * `undefined` — throws instead of silently reusing the (often broader) default,
2158
+ * which would be a fail-open exactly where the API is used to narrow privilege.
2159
+ * This matches the imports side, which already rejects a non-function rebind.
2160
+ * @param runGlobals the per-run rebind map
2161
+ * @param name the declared global's name
2162
+ * @param fallback the precompile-time handler used when no override is supplied
2163
+ */
2164
+ function resolveOverride(runGlobals, name, fallback) {
2165
+ if (!Object.hasOwn(runGlobals, name)) return fallback;
2166
+ const override = runGlobals[name];
2167
+ if (typeof override !== "function") throw new TypeError(`[iso4] global override "${name}" must be a function, got ${override === null ? "null" : typeof override}`);
2168
+ return override;
2169
+ }
2170
+ function extractBridgeGlobals(runGlobals, precompileGlobals) {
2171
+ const defs = [];
2172
+ const dispatch = {};
2173
+ for (const [name, value] of Object.entries(precompileGlobals)) {
2174
+ if (typeof value === "string" || isStringGlobal(value) || isDataGlobal(value)) continue;
2175
+ if (isBridgeWithShim(value)) {
2176
+ const handlerName = shimHandlerName(name);
2177
+ defs.push({
2178
+ kind: "bridge",
2179
+ name: handlerName,
2180
+ enumerable: true
2181
+ });
2182
+ dispatch[handlerName] = resolveOverride(runGlobals, name, value.handler);
2183
+ } else if (isBridgeGlobal(value)) {
2184
+ defs.push({
2185
+ kind: "bridge",
2186
+ name,
2187
+ enumerable: value.enumerable ?? true
2188
+ });
2189
+ dispatch[name] = resolveOverride(runGlobals, name, value.handler);
2190
+ } else if (typeof value === "function") {
2191
+ defs.push({
2192
+ kind: "bridge",
2193
+ name,
2194
+ enumerable: true
2195
+ });
2196
+ dispatch[name] = resolveOverride(runGlobals, name, value);
2197
+ }
2198
+ }
2199
+ for (const [name, override] of Object.entries(runGlobals)) {
2200
+ if (name in precompileGlobals) continue;
2201
+ checkGlobalName(name);
2202
+ if (typeof override === "function") {
2203
+ defs.push({
2204
+ kind: "bridge",
2205
+ name,
2206
+ enumerable: true
2207
+ });
2208
+ dispatch[name] = override;
2209
+ }
2210
+ }
2211
+ return {
2212
+ defs,
2213
+ dispatch
2214
+ };
2215
+ }
1881
2216
  /**
1882
2217
  * The dispatch-map key for one host-module function leaf. The NUL separator
1883
2218
  * cannot collide with anything a specifier or dot-joined path can contain in
@@ -2003,76 +2338,28 @@ function walkRebind(specifier, node, path, handlers, rebinds) {
2003
2338
  for (const [key, value] of Object.entries(node)) {
2004
2339
  if (value === void 0) continue;
2005
2340
  const newPath = [...path, key];
2006
- if (typeof value === "function") {
2007
- const joined = newPath.join(".");
2008
- handlers.set(importHandlerKey(specifier, joined), value);
2009
- rebinds.push({
2010
- specifier,
2011
- path: joined
2012
- });
2013
- continue;
2014
- }
2015
- if (isPlainObject(value)) {
2016
- walkRebind(specifier, value, newPath, handlers, rebinds);
2017
- continue;
2018
- }
2019
- throw new ImportRebindError("ERR_INVALID_REBIND", `import '${specifier}'.${newPath.join(".")} can only be rebound with a function; got ${describeKind(value)}`);
2020
- }
2021
- }
2022
- function isPlainObject(value) {
2023
- if (value === null || typeof value !== "object") return false;
2024
- if (Array.isArray(value)) return false;
2025
- const proto = Object.getPrototypeOf(value);
2026
- return proto === null || proto === Object.prototype;
2027
- }
2028
- const RESERVED_WORDS = new Set([
2029
- "break",
2030
- "case",
2031
- "catch",
2032
- "class",
2033
- "const",
2034
- "continue",
2035
- "debugger",
2036
- "default",
2037
- "delete",
2038
- "do",
2039
- "else",
2040
- "export",
2041
- "extends",
2042
- "finally",
2043
- "for",
2044
- "function",
2045
- "if",
2046
- "import",
2047
- "in",
2048
- "instanceof",
2049
- "new",
2050
- "return",
2051
- "super",
2052
- "switch",
2053
- "this",
2054
- "throw",
2055
- "try",
2056
- "typeof",
2057
- "var",
2058
- "void",
2059
- "while",
2060
- "with",
2061
- "yield",
2062
- "let",
2063
- "static",
2064
- "enum",
2065
- "await",
2066
- "implements",
2067
- "package",
2068
- "protected",
2069
- "interface",
2070
- "private",
2071
- "public",
2072
- "null",
2073
- "true",
2074
- "false"
2075
- ]);
2341
+ if (typeof value === "function") {
2342
+ const joined = newPath.join(".");
2343
+ handlers.set(importHandlerKey(specifier, joined), value);
2344
+ rebinds.push({
2345
+ specifier,
2346
+ path: joined
2347
+ });
2348
+ continue;
2349
+ }
2350
+ if (isPlainObject(value)) {
2351
+ walkRebind(specifier, value, newPath, handlers, rebinds);
2352
+ continue;
2353
+ }
2354
+ throw new ImportRebindError("ERR_INVALID_REBIND", `import '${specifier}'.${newPath.join(".")} can only be rebound with a function; got ${describeKind(value)}`);
2355
+ }
2356
+ }
2357
+ function isPlainObject(value) {
2358
+ if (value === null || typeof value !== "object") return false;
2359
+ if (Array.isArray(value)) return false;
2360
+ const proto = Object.getPrototypeOf(value);
2361
+ return proto === null || proto === Object.prototype;
2362
+ }
2076
2363
  /**
2077
2364
  * Whether `name` can appear as a named ESM export. JS identifier rules plus
2078
2365
  * a reserved-word filter. `default` is allowed (the runtime emits it as
@@ -2082,7 +2369,7 @@ const RESERVED_WORDS = new Set([
2082
2369
  */
2083
2370
  function isValidExportIdentifier(name) {
2084
2371
  if (name === "default") return true;
2085
- if (!/^[A-Za-z_$][A-Za-z0-9_$]*$/.test(name)) return false;
2372
+ if (!IDENTIFIER_NAME.test(name)) return false;
2086
2373
  if (RESERVED_WORDS.has(name)) return false;
2087
2374
  return true;
2088
2375
  }
@@ -2291,6 +2578,7 @@ var RuntimeIpcClient = class RuntimeIpcClient {
2291
2578
  })));
2292
2579
  await client.awaitHello();
2293
2580
  } catch (error) {
2581
+ client.broken = true;
2294
2582
  await client.dispose();
2295
2583
  throw error;
2296
2584
  }
@@ -2539,6 +2827,7 @@ var RuntimeIpcClient = class RuntimeIpcClient {
2539
2827
  async dispose() {
2540
2828
  if (this.disposed) return;
2541
2829
  this.disposed = true;
2830
+ if (!this.broken && !this.socket.destroyed) this.socket.write(encodeTsToRustFrame(TsToRustMessageTypes.Close, new Uint8Array(0)));
2542
2831
  this.socket.end();
2543
2832
  await new Promise((resolve) => {
2544
2833
  if (this.socket.destroyed) {
@@ -3300,253 +3589,6 @@ var RunPool = class {
3300
3589
  }
3301
3590
  };
3302
3591
  //#endregion
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
- ]);
3388
- function isBridgeWithShim(v) {
3389
- return typeof v === "object" && v !== null && v.kind === "bridge-with-shim";
3390
- }
3391
- function isDataGlobal(v) {
3392
- return typeof v === "object" && v !== null && v.kind === "data";
3393
- }
3394
- function isBridgeGlobal(v) {
3395
- return typeof v === "object" && v !== null && v.kind === "bridge";
3396
- }
3397
- function isStringGlobal(v) {
3398
- return typeof v === "object" && v !== null && v.kind === "string";
3399
- }
3400
- /**
3401
- * Private bridge-dispatch name for a `BridgeWithShim` handler. This is a wire
3402
- * dispatch key and an object-property key — never interpolated into generated
3403
- * code — so any global name is safe. The runtime recognises the
3404
- * `__iso4_<name>_h` convention (`public_record_name` in `v8.rs`) and reports
3405
- * bridge records under the public `<name>`.
3406
- * @param name public global name
3407
- */
3408
- function shimHandlerName(name) {
3409
- return `__iso4_${name}_h`;
3410
- }
3411
- /**
3412
- * Lower a `HostGlobals` map into wire-shaped `defs` plus the bridge-dispatch
3413
- * map. See the module comment for the split.
3414
- * - `HostExportFunction` → `{ kind: 'bridge' }` + dispatch entry.
3415
- * - `string` → `{ kind: 'string', expr }` (evaluated by Rust).
3416
- * - `DataGlobal` → `{ kind: 'data', value }` (materialised by Rust).
3417
- * - `BridgeWithShim` → `{ kind: 'shim', shim, handlerName }` + a dispatch
3418
- * entry for the private handler under `handlerName`.
3419
- * @param globals
3420
- */
3421
- function processGlobals(globals) {
3422
- const defs = [];
3423
- const dispatch = {};
3424
- for (const [name, value] of Object.entries(globals)) if (typeof value === "function") {
3425
- defs.push({
3426
- kind: "bridge",
3427
- name,
3428
- enumerable: true
3429
- });
3430
- dispatch[name] = value;
3431
- } else if (typeof value === "string") defs.push({
3432
- kind: "string",
3433
- name,
3434
- expr: value,
3435
- enumerable: true
3436
- });
3437
- else if (isBridgeGlobal(value)) {
3438
- defs.push({
3439
- kind: "bridge",
3440
- name,
3441
- enumerable: value.enumerable ?? true
3442
- });
3443
- dispatch[name] = value.handler;
3444
- } else if (isStringGlobal(value)) defs.push({
3445
- kind: "string",
3446
- name,
3447
- expr: value.expr,
3448
- enumerable: value.enumerable ?? true
3449
- });
3450
- else if (isDataGlobal(value)) defs.push({
3451
- kind: "data",
3452
- name,
3453
- value: value.value,
3454
- enumerable: value.enumerable ?? true
3455
- });
3456
- else if (isBridgeWithShim(value)) {
3457
- const handlerName = shimHandlerName(name);
3458
- defs.push({
3459
- kind: "shim",
3460
- name,
3461
- shim: value.shim,
3462
- handlerName,
3463
- enumerable: value.enumerable ?? true
3464
- });
3465
- dispatch[handlerName] = value.handler;
3466
- }
3467
- return {
3468
- defs,
3469
- dispatch
3470
- };
3471
- }
3472
- /**
3473
- * Resolve bridge globals for a `prefix.run()` call.
3474
- *
3475
- * String/data globals and shim *wrappers* are already compiled into the
3476
- * declared prefix state, replayed by the runtime when the prefix evaluates —
3477
- * only the bridge *stubs* they call need re-installing per run (bridge stubs
3478
- * are bound to the run's socket). So
3479
- * every returned def is `kind: 'bridge'`, and shimmed globals are routed to
3480
- * their private `__iso4_<name>_h` key so rebinding updates the handler the
3481
- * shim calls, without touching the shim itself.
3482
- * @param runGlobals
3483
- * @param precompileGlobals
3484
- */
3485
- /**
3486
- * Resolve a per-run override for a declared bridge global.
3487
- *
3488
- * An omitted key falls back to the precompile-time handler (the intended
3489
- * default). But a key that IS supplied yet is not a function — the runtime
3490
- * shape TypeScript cannot catch, e.g. a tenant handler that resolves to
3491
- * `undefined` — throws instead of silently reusing the (often broader) default,
3492
- * which would be a fail-open exactly where the API is used to narrow privilege.
3493
- * This matches the imports side, which already rejects a non-function rebind.
3494
- * @param runGlobals the per-run rebind map
3495
- * @param name the declared global's name
3496
- * @param fallback the precompile-time handler used when no override is supplied
3497
- */
3498
- function resolveOverride(runGlobals, name, fallback) {
3499
- if (!Object.hasOwn(runGlobals, name)) return fallback;
3500
- const override = runGlobals[name];
3501
- if (typeof override !== "function") throw new TypeError(`[iso4] global override "${name}" must be a function, got ${override === null ? "null" : typeof override}`);
3502
- return override;
3503
- }
3504
- function extractBridgeGlobals(runGlobals, precompileGlobals) {
3505
- const defs = [];
3506
- const dispatch = {};
3507
- for (const [name, value] of Object.entries(precompileGlobals)) {
3508
- if (typeof value === "string" || isStringGlobal(value) || isDataGlobal(value)) continue;
3509
- if (isBridgeWithShim(value)) {
3510
- const handlerName = shimHandlerName(name);
3511
- defs.push({
3512
- kind: "bridge",
3513
- name: handlerName,
3514
- enumerable: true
3515
- });
3516
- dispatch[handlerName] = resolveOverride(runGlobals, name, value.handler);
3517
- } else if (isBridgeGlobal(value)) {
3518
- defs.push({
3519
- kind: "bridge",
3520
- name,
3521
- enumerable: value.enumerable ?? true
3522
- });
3523
- dispatch[name] = resolveOverride(runGlobals, name, value.handler);
3524
- } else if (typeof value === "function") {
3525
- defs.push({
3526
- kind: "bridge",
3527
- name,
3528
- enumerable: true
3529
- });
3530
- dispatch[name] = resolveOverride(runGlobals, name, value);
3531
- }
3532
- }
3533
- for (const [name, override] of Object.entries(runGlobals)) {
3534
- if (name in precompileGlobals) continue;
3535
- if (typeof override === "function") {
3536
- defs.push({
3537
- kind: "bridge",
3538
- name,
3539
- enumerable: true
3540
- });
3541
- dispatch[name] = override;
3542
- }
3543
- }
3544
- return {
3545
- defs,
3546
- dispatch
3547
- };
3548
- }
3549
- //#endregion
3550
3592
  //#region src/index.ts
3551
3593
  /**
3552
3594
  * \@iso4/sandbox - public entry point.
@@ -3962,7 +4004,28 @@ var SandboxImpl = class {
3962
4004
  if (typeof options.limits?.memoryMb === "object") throw new TypeError("[@iso4/sandbox] limits.memoryMb takes a number of megabytes — the { soft, hard } form belongs on createSandbox or prepare, whose instances are reused");
3963
4005
  validateMemoryMb(options.limits?.memoryMb, "limits.memoryMb");
3964
4006
  const runMemoryMb = options.limits?.memoryMb ?? this.memoryMb;
3965
- const { defs, dispatch } = processGlobals(options.globals ?? {});
4007
+ let processed;
4008
+ try {
4009
+ processed = processGlobals(options.globals ?? {});
4010
+ } catch (e) {
4011
+ if (e instanceof GlobalNameError) return {
4012
+ status: "failed",
4013
+ ok: false,
4014
+ error: {
4015
+ code: e.code,
4016
+ name: "Error",
4017
+ message: e.message
4018
+ },
4019
+ stdout: [],
4020
+ stderr: [],
4021
+ durationMs: 0,
4022
+ wallTimeMs: 0,
4023
+ cpuTimeMs: 0,
4024
+ bridgeCalls: []
4025
+ };
4026
+ throw e;
4027
+ }
4028
+ const { defs, dispatch } = processed;
3966
4029
  await materializeHostTypesInGlobals(defs, this.brandKey);
3967
4030
  const { bindings, handlers } = processImports(options.imports);
3968
4031
  const streams = new StreamSourceRegistry();
@@ -4067,9 +4130,9 @@ var SandboxImpl = class {
4067
4130
  async prepare(options) {
4068
4131
  validateMemoryMb(options.memoryMb, "memoryMb");
4069
4132
  const prefixMemoryMb = options.memoryMb ?? this.memoryMb;
4133
+ const rawGlobals = options.globals ?? {};
4134
+ const { defs } = processGlobals(rawGlobals);
4070
4135
  return this.pool.withClient(async (client) => {
4071
- const rawGlobals = options.globals ?? {};
4072
- const { defs } = processGlobals(rawGlobals);
4073
4136
  await materializeHostTypesInGlobals(defs, this.brandKey);
4074
4137
  const { bindings, handlers } = processImports(options.imports);
4075
4138
  const result = decodePrecompileResultPayload(await client.precompile({
@@ -4217,12 +4280,14 @@ var PrefixImpl = class {
4217
4280
  if (options.signal?.aborted) return abortedResult(options.signal.reason);
4218
4281
  if (options.hardAbortSignal?.aborted) return abortedResult(options.hardAbortSignal.reason);
4219
4282
  if (options.limits !== void 0 && "memoryMb" in options.limits) throw new TypeError("[@iso4/sandbox] limits.memoryMb is not a per-run option for prefix runs: the cap is baked into the shared warm isolates at creation — set it per prefix via prepare({ memoryMb }), or the sandbox default via createSandbox({ memoryMb })");
4220
- const { defs, dispatch } = extractBridgeGlobals(options.globals ?? {}, this.defaultGlobals);
4283
+ let defs;
4284
+ let dispatch;
4221
4285
  let merged;
4222
4286
  try {
4287
+ ({defs, dispatch} = extractBridgeGlobals(options.globals ?? {}, this.defaultGlobals));
4223
4288
  merged = mergeRebindImports(options.imports, this.defaultImportHandlers);
4224
4289
  } catch (e) {
4225
- if (e instanceof ImportRebindError) return {
4290
+ if (e instanceof ImportRebindError || e instanceof GlobalNameError) return {
4226
4291
  status: "failed",
4227
4292
  ok: false,
4228
4293
  error: {
@@ -4285,4 +4350,4 @@ var PrefixImpl = class {
4285
4350
  }
4286
4351
  };
4287
4352
  //#endregion
4288
- export { SANDBOX_GLOBALS, createSandbox };
4353
+ export { RESERVED_WORDS, SANDBOX_GLOBALS, createSandbox };
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "@iso4/sandbox",
3
- "version": "0.7.0",
3
+ "version": "0.8.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.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"
52
+ "@iso4/v8-darwin-arm64": "^0.8.0",
53
+ "@iso4/v8-darwin-x64": "^0.8.0",
54
+ "@iso4/v8-linux-arm64-gnu": "^0.8.0",
55
+ "@iso4/v8-linux-x64-gnu": "^0.8.0"
56
56
  },
57
57
  "engines": {
58
58
  "node": ">=24.0.0"