@enclave-vm/core 2.18.0 → 2.19.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.
@@ -1,4 +1,39 @@
1
1
  import type * as ESTree from 'estree';
2
+ /** Whether a property key is one a script may never use. */
3
+ export declare function isBlockedKey(key: string): boolean;
4
+ /**
5
+ * Longest array a script may make in one step: by assigning an index or `length`, or by
6
+ * spreading. An array of a billion holes costs nothing to make and a lot to `join`.
7
+ */
8
+ export declare const MAX_ARRAY_LENGTH = 1000000;
9
+ /**
10
+ * Declare that `fn` takes arrays as data and never converts one to text or to a number (the
11
+ * engine does that to an array wherever it expects a primitive). Arrays given to any other
12
+ * built-in or host function are measured first.
13
+ */
14
+ export declare function takesArraysAsData<F extends object>(fn: F): F;
15
+ /**
16
+ * Declare that `fn` reads only its first `count` arguments (and may convert those to text or to
17
+ * a number): an array among the others is not measured. For functions whose code is known to
18
+ * ignore what it is given beyond that, such as the stand-ins of the standard globals; a script
19
+ * hands such a function three arguments when it uses it as the callback of `map`.
20
+ */
21
+ export declare function convertsArguments<F extends object>(fn: F, count: number): F;
22
+ /**
23
+ * Declare what a call of `fn` may allocate beyond the value it returns, in bytes, from its
24
+ * arguments. It is charged to the budget BEFORE the call: the engine builds the result in one
25
+ * step, and what is charged afterwards has already been allocated.
26
+ */
27
+ export declare function chargedBeforeCall<F extends object>(fn: F, cost: (args: readonly unknown[]) => number): F;
28
+ /**
29
+ * Refuse arrays that the engine would turn into more text than a script may make in one step.
30
+ * A built-in that converts its argument (`String(x)`, `Number(x)`, `x + ''`, a property key)
31
+ * joins an array's items, and the items of the arrays inside it: an array that holds another one
32
+ * many times is small in memory and huge as text.
33
+ *
34
+ * @throws InterpreterError when the text of the arrays among `values` is longer than the limit
35
+ */
36
+ export declare function assertArrayTextWithinLimit(...values: unknown[]): void;
2
37
  /** Thrown when the instruction budget is exceeded (interrupts infinite loops). */
3
38
  export declare class StepLimitError extends Error {
4
39
  constructor(limit: number);
@@ -7,6 +42,15 @@ export declare class StepLimitError extends Error {
7
42
  export declare class InterpreterError extends Error {
8
43
  constructor(message: string);
9
44
  }
45
+ /**
46
+ * An error as script code holds it: a frozen object without a prototype that has a `name`, a
47
+ * `message`, a `code` when there is one, and a `toString`. It is what `new Error()` makes in a
48
+ * script and what a `catch` clause receives in place of a host Error object, whose `stack`
49
+ * names host files.
50
+ */
51
+ export declare function createScriptError(name: string, message: string, code?: string): object;
52
+ /** Whether a value is an error object made by {@link createScriptError}. */
53
+ export declare function isScriptError(value: unknown): boolean;
10
54
  export interface InterpreterOptions {
11
55
  /** Identifiers + values available to the script (e.g. Math, JSON, __safe_callTool). */
12
56
  globals: Record<string, unknown>;
@@ -16,6 +60,19 @@ export interface InterpreterOptions {
16
60
  maxCallDepth: number;
17
61
  /** Optional cancellation. */
18
62
  signal?: AbortSignal;
63
+ /**
64
+ * What `new` may be applied to: for each such global, the function that builds the value from
65
+ * the arguments. `new` on anything else is refused.
66
+ */
67
+ constructors?: ReadonlyMap<unknown, (args: unknown[]) => unknown>;
68
+ /** What may stand on the right of `instanceof`, with the test it performs. */
69
+ instanceChecks?: ReadonlyMap<unknown, (value: unknown) => boolean>;
70
+ /**
71
+ * Called with an estimate, in bytes, of what an evaluation step allocated (a string, an array,
72
+ * an object literal). Throws when the host's budget is used up; that error ends the run and
73
+ * cannot be caught by the script.
74
+ */
75
+ charge?: (bytes: number) => void;
19
76
  }
20
77
  /**
21
78
  * Evaluate a parsed AgentScript program. Returns the resolved value of the
@@ -26,22 +83,100 @@ export declare class Interpreter {
26
83
  private steps;
27
84
  private callDepth;
28
85
  private readonly globals;
86
+ /** The error that ended the run (step budget, abort, allocation budget); set once, never caught */
87
+ private fatal;
88
+ private readonly interpretedFunctions;
89
+ private readonly errorCopies;
29
90
  constructor(options: InterpreterOptions);
91
+ /**
92
+ * Call a function for a script, with the checks that apply to a call the script writes itself.
93
+ * For a host helper that is handed a callback (`parallel(items, fn)`): `fn` may be a function
94
+ * of the script, or a built-in or host function the script passed along.
95
+ */
96
+ call(fn: unknown, args: unknown[]): unknown;
30
97
  /** Number of AST nodes evaluated so far (for execution stats). */
31
98
  get stepCount(): number;
32
99
  run(program: ESTree.Program): Promise<unknown>;
100
+ /**
101
+ * End the run from outside: whatever of the script is still going (a function a built-in
102
+ * started and nobody awaited, a callback waiting for a tool call) stops at its next step. The
103
+ * host calls this when the execution has returned, so that no script code runs after it.
104
+ */
105
+ stop(): void;
106
+ /** End the run with an error no `catch` of the script can stop. */
107
+ private end;
33
108
  private tick;
109
+ /** Charge an allocation to the host's budget. */
110
+ private charge;
111
+ /** Charge what a host function returned, when that is a string or an array. */
112
+ private chargeValue;
34
113
  private execStatement;
35
114
  private execBlock;
115
+ /** Bind the variable of a `for…of` / `for…in` head to the value of one iteration. */
116
+ private bindLoopVariable;
117
+ /** Run one iteration of a loop body. @returns false when the loop is to stop */
118
+ private runLoopBody;
36
119
  private execForOf;
120
+ private execForIn;
37
121
  private execFor;
38
122
  private execWhile;
123
+ private execDoWhile;
124
+ private execSwitch;
125
+ private execTry;
126
+ /**
127
+ * What a `catch` clause receives. A value the script threw is its own. A host Error (a refusal
128
+ * by the interpreter, a failed tool call, a TypeError of a built-in) is replaced by a plain
129
+ * copy with its name, message and code.
130
+ */
131
+ private toScriptValue;
39
132
  private evalExpr;
40
133
  private evalTemplate;
134
+ private evalUnary;
41
135
  private evalBinary;
42
- /** Resolve a member access to `{ object, key, value }`, blocking escape keys. */
43
- private evalMember;
136
+ /** Apply a binary operator to two values. */
137
+ private binary;
138
+ /**
139
+ * Resolve a member expression to the object and the key it names, blocking escape keys.
140
+ * Inside an optional chain, a `?.` on `null` or `undefined` ends the chain.
141
+ */
142
+ private evalMemberTarget;
143
+ /** A variable or a member as something that can be read and assigned. */
144
+ private resolveReference;
145
+ /**
146
+ * Only data a script owns can be changed: arrays and plain objects that are not frozen. The
147
+ * globals, functions (the host's built-ins among them, which the whole process shares), dates
148
+ * and the error copies are not: a property set on one of them would be seen by host code.
149
+ */
150
+ private assertChangeable;
151
+ private writeMember;
152
+ /** Append what an iterable yields to an array, one step and one length check per item. */
153
+ private spreadInto;
154
+ private evalArguments;
155
+ private evalNew;
44
156
  private evalCall;
157
+ /**
158
+ * Call a function with a receiver and arguments: an interpreted function, or a built-in or host
159
+ * function after the checks that apply to it. `call` and `apply` are resolved to the function
160
+ * they invoke first, so those checks cannot be passed by the way a call is written.
161
+ */
162
+ private callFunction;
163
+ /** The argument list of `apply`: an array, or nothing. */
164
+ private argumentList;
165
+ /**
166
+ * `fn.bind(receiver, ...args)`: a function that calls `fn` through {@link callFunction}, so
167
+ * that what is checked for a call of `fn` is checked for a call of the bound function too.
168
+ */
169
+ private bindFunction;
170
+ /**
171
+ * The checks before a built-in or host function runs. The engine performs such a call in one
172
+ * step, out of reach of the step budget, and what the call allocates is only known to the
173
+ * budget when it exists: whatever could make that large is refused here, from the arguments.
174
+ *
175
+ * @returns The arguments to call the function with
176
+ */
177
+ private checkBuiltinCall;
178
+ private checkStringMethod;
179
+ private checkArrayMethod;
45
180
  /**
46
181
  * Async implementations of the higher-order array methods, so interpreter
47
182
  * callbacks (which are async — they may `await` tool calls) are awaited. Each
@@ -49,11 +184,20 @@ export declare class Interpreter {
49
184
  */
50
185
  private callArrayMethod;
51
186
  private evalAssignment;
52
- /** Assign to an Identifier or MemberExpression target (blocking escape keys). */
53
- private assignTo;
54
- private bindPattern;
187
+ /**
188
+ * Give the names in a pattern their values: a declaration (`const` / `let`), a parameter list
189
+ * or an assignment (`[a, o.b] = …`). Defaults and rest elements are handled here.
190
+ */
191
+ private applyPattern;
55
192
  /** Build an interpreter-backed function (declaration / arrow / expression). */
56
193
  private makeFunction;
194
+ /** A computed property key as text. An array as a key is its items, joined. */
195
+ private keyText;
57
196
  private propKey;
58
197
  private readGlobal;
59
198
  }
199
+ /**
200
+ * Whether a value is data a script may change: an array, or an object whose prototype is
201
+ * `Object.prototype` or nothing. That is what literals, `JSON.parse` and tool results are made of.
202
+ */
203
+ export declare function isScriptData(value: unknown): boolean;
@@ -0,0 +1,14 @@
1
+ /** What {@link createSafeGlobals} returns: the three tables the interpreter is configured with. */
2
+ export interface SafeGlobals {
3
+ /** Name to value, for the interpreter's `globals` */
4
+ globals: Record<string, unknown>;
5
+ /** What `new` may be applied to */
6
+ constructors: Map<unknown, (args: unknown[]) => unknown>;
7
+ /** What may stand on the right of `instanceof` */
8
+ instanceChecks: Map<unknown, (value: unknown) => boolean>;
9
+ }
10
+ /**
11
+ * The standard globals for one interpreter. The values are shared between interpreters: all of
12
+ * them are frozen and none of them keeps state.
13
+ */
14
+ export declare function createSafeGlobals(): SafeGlobals;
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "@enclave-vm/core",
3
- "version": "2.18.0",
3
+ "version": "2.19.0",
4
4
  "description": "Sandbox runtime for secure JavaScript code execution",
5
5
  "author": "AgentFront <info@agentfront.dev>",
6
6
  "homepage": "https://github.com/agentfront/enclave",
@@ -44,13 +44,13 @@
44
44
  },
45
45
  "dependencies": {
46
46
  "@babel/standalone": "^7.29.0",
47
- "@enclave-vm/ast": "2.18.0",
48
- "@enclave-vm/types": "2.18.0",
47
+ "@enclave-vm/ast": "2.19.0",
48
+ "@enclave-vm/types": "2.19.0",
49
49
  "@types/estree": "1.0.8",
50
50
  "acorn": "8.15.0",
51
51
  "acorn-walk": "8.3.4",
52
52
  "astring": "1.9.0",
53
- "zod": "^4.3.6"
53
+ "zod": "^4.6.6"
54
54
  },
55
55
  "peerDependencies": {
56
56
  "@huggingface/transformers": "^3.2.2",
@@ -0,0 +1,51 @@
1
+ /**
2
+ * Realm Airlock (single-VM adapter)
3
+ *
4
+ * What the single VM hands a script from the host (a value from `globals`, a host function
5
+ * behind the call gate) is a secure proxy: a HOST Proxy whose handler is host code. Three things
6
+ * are wrong with a script holding one of those directly:
7
+ *
8
+ * - the engine attributes a Proxy to the realm of its target, so a callable one counts as a host
9
+ * function wherever the engine creates something on a callable's behalf;
10
+ * - its traps are host functions, entered straight from the script: a stack overflow at the
11
+ * entry of a trap is a host `RangeError` in the script's catch block, raised before any host
12
+ * code could launder it;
13
+ * - its `set` trap writes through to the host object.
14
+ *
15
+ * The airlock puts a second proxy in front, made INSIDE the sandbox realm (see
16
+ * INNER_REALM_GUARD_SOURCE in ./double-vm/parent-vm-bootstrap): its target is a fresh object of
17
+ * that realm, its traps are functions of that realm, and what those call is the handler built
18
+ * here, which forwards to the secure proxy. The secure proxy keeps deciding what may be read and
19
+ * called; this layer decides nothing except that host values are read-only.
20
+ *
21
+ * @packageDocumentation
22
+ */
23
+ /** The sandbox realm's half of the membrane: what INNER_REALM_GUARD_SOURCE evaluates to */
24
+ export interface RealmMembrane {
25
+ /** A proxy of the realm on `target`, whose traps call `handler`'s inside a try block */
26
+ makeProxy(target: object, handler: object): object;
27
+ /** A function of the realm that calls `fn` inside a try block */
28
+ wrap<A extends unknown[], R>(fn: (...args: A) => R, needsReserve: boolean): (...args: A) => R;
29
+ /** What a script may be handed in place of a thrown value or a rejection reason */
30
+ own(value: unknown): unknown;
31
+ /** A fresh object of the realm to put a proxy on */
32
+ shell(kind: 'function' | 'array' | 'object'): object;
33
+ }
34
+ /** Both directions of the airlock */
35
+ export interface RealmAirlock {
36
+ /** What the script gets for a value that came out of a secure proxy (or is one) */
37
+ toRealm(value: unknown): unknown;
38
+ /** The secure proxy behind an airlock proxy; any other value as it is */
39
+ toHost<T>(value: T): T;
40
+ /**
41
+ * Whether an object was made in the sandbox realm: its prototype chain reaches that realm's
42
+ * `Object.prototype`. Says no to everything else, and to an object that cannot be asked.
43
+ */
44
+ isRealmValue(value: object): boolean;
45
+ }
46
+ /**
47
+ * Create the airlock of one execution.
48
+ *
49
+ * @param realm The sandbox realm's half of the membrane
50
+ */
51
+ export declare function createRealmAirlock(realm: RealmMembrane): RealmAirlock;
package/safe-error.d.ts CHANGED
@@ -10,6 +10,12 @@
10
10
  * hostError -> Error.prototype -> Error -> Function -> new Function('...')()
11
11
  * and execute arbitrary host code (e.g. `process.env`, command execution).
12
12
  */
13
+ /**
14
+ * Whether `value` is an error made by {@link createSafeError}: frozen, without a prototype chain
15
+ * or a stack, carrying only strings. Such an error is inert and may be handed to sandbox code as
16
+ * it is.
17
+ */
18
+ export declare function isSafeError(value: unknown): boolean;
13
19
  /**
14
20
  * Create an Error instance whose prototype chain is severed (actual [[Prototype]]),
15
21
  * preventing prototype-chain escape to host constructors.
package/safe-runtime.d.ts CHANGED
@@ -42,6 +42,22 @@ export interface SafeRuntimeOptions {
42
42
  * through it.
43
43
  */
44
44
  globalFunctionGate?: GlobalFunctionCallGate;
45
+ /**
46
+ * Passed to the secure proxies this runtime creates (see `SecureProxyOptions.exposeToSandbox`).
47
+ */
48
+ exposeToSandbox?: (value: unknown) => unknown;
49
+ /** Passed to the secure proxies this runtime creates (see `SecureProxyOptions.ownedBySandbox`). */
50
+ ownedBySandbox?: (value: object) => boolean;
51
+ /**
52
+ * Whether the result includes the host's standard library (`Math`, `JSON`, `Array`, `Object`,
53
+ * `String`, `Number`, `Date`) behind secure proxies, the custom globals and the loop,
54
+ * concatenation and `parallel` helpers. Default: true.
55
+ *
56
+ * The VM adapter passes `false`: a sandbox realm has intrinsics of its own, and handing it the
57
+ * HOST's makes every one of them reachable from a script (a write through the proxy changed the
58
+ * host's `Math`). With `false` the result holds `__safe_callTool` and the value globals only.
59
+ */
60
+ hostObjects?: boolean;
45
61
  }
46
62
  /**
47
63
  * Create safe runtime context with all __safe_* functions
@@ -0,0 +1,67 @@
1
+ /**
2
+ * Sandbox Promise Rejections
3
+ *
4
+ * Node.js ends the process when a promise is rejected and nothing handles it (the default,
5
+ * `--unhandled-rejections=throw`). The rule is the isolate's, so it covers the promises of a `vm`
6
+ * context too: a script that calls an async function which throws and does not await it, or
7
+ * leaves a failing tool call unawaited, would end the HOST process, after its own execution had
8
+ * returned successfully.
9
+ *
10
+ * Nothing in a script can be made to handle its own promises, and the engine offers no way to
11
+ * exempt a context. Node.js decides what to do with an unhandled rejection by emitting
12
+ * `unhandledRejection` on `process` and looking at the answer, so that is where this module
13
+ * stands: `process.emit` is wrapped, and
14
+ *
15
+ * - for a promise that is NOT of the host realm (a script's, or the sandbox runtime's), the two
16
+ * events `unhandledRejection` and `rejectionHandled` are answered here, with "handled", and go
17
+ * no further. The process goes on; no listener of the application sees the script's promise or
18
+ * its reason; Node.js prints no warning when the script handles the rejection late;
19
+ * - everything else, the application's own rejections included, goes to the `emit` that was
20
+ * there before, untouched. What Node.js or the application does with those is what it did
21
+ * without this module, in every `--unhandled-rejections` mode.
22
+ *
23
+ * A reason is never read, formatted or passed on here. Formatting one with `util.inspect`, as a
24
+ * log line or Node's printer for an uncaught error would, calls a method the value can supply
25
+ * (`nodejs.util.inspect.custom`) with the host's own `inspect` function as an argument. (The
26
+ * sandbox realms also refuse `Symbol.for` keys of that namespace: a second layer for every other
27
+ * path on which host code might format a value of a script.)
28
+ *
29
+ * The wrapper is installed the first time a sandbox is used and stays: a script's promise can
30
+ * be rejected long after its execution has ended (a tool call nobody awaited fails later).
31
+ *
32
+ * What it cannot do, and what a host should know:
33
+ *
34
+ * - under `--unhandled-rejections=strict` Node.js raises the exception before it emits anything,
35
+ * and under `=warn` it prints its warning before it emits;
36
+ * - promises of any other realm are covered too, including those of `vm` contexts the
37
+ * application created itself: nobody is told about their unhandled rejections;
38
+ * - a host that wants none of this calls {@link disableSandboxRejectionGuard}.
39
+ *
40
+ * @packageDocumentation
41
+ */
42
+ /**
43
+ * Whether a promise is one of the host realm: made by the host's `Promise` or a subclass of it.
44
+ *
45
+ * The test is for the host, not for the sandbox, on purpose. A script can give its promise any
46
+ * prototype it can reach (or none); what it cannot reach is the host's `Promise.prototype`, so it
47
+ * cannot make its promise look like the application's.
48
+ */
49
+ export declare function isHostPromise(promise: unknown): boolean;
50
+ /**
51
+ * Called by the sandbox adapters before a script runs: makes sure the wrapper is part of
52
+ * `process.emit`, unless the host has opted out with {@link disableSandboxRejectionGuard}.
53
+ *
54
+ * Other code wraps `process.emit` as well, and some of it restores an older `emit` when it is
55
+ * done, which would take this wrapper out again. So every call checks, with an event of its own
56
+ * that only the wrapper answers, and puts the wrapper back if it is gone.
57
+ */
58
+ export declare function guardSandboxRejections(): void;
59
+ /**
60
+ * For a host that wants to deal with every rejection itself: the wrapper lets everything through
61
+ * and the adapters leave it at that (or, with `false`, undo this). Such a host has to ignore, in
62
+ * its own `unhandledRejection` listener, the promises for which {@link isHostPromise} is false,
63
+ * without touching their reason: it is a value of the script.
64
+ *
65
+ * @param disabled True to leave every rejection to Node.js and the host
66
+ */
67
+ export declare function disableSandboxRejectionGuard(disabled?: boolean): void;
@@ -0,0 +1,156 @@
1
+ /**
2
+ * Compiling scripts for sandbox realms without sharing compiled code between realms.
3
+ *
4
+ * ## The engine defect this works around
5
+ *
6
+ * V8 keeps a compilation cache: compiling the same source text again returns the SAME compiled
7
+ * functions, and a `vm.Script` run in several contexts instantiates the same compiled functions in
8
+ * each. Once one of those functions has been hot enough to get baseline (Sparkplug) code, every
9
+ * NEW closure of it, in every later context, is entered through the lazy-compile builtin straight
10
+ * into that baseline code.
11
+ *
12
+ * In V8 13.x (Node.js 24) that entry path is broken for builds without the V8 sandbox, which is
13
+ * what Node.js ships. The baseline prologue saves the "dispatch handle" register into a stack
14
+ * frame that the garbage collector scans as tagged values, assuming the register holds a handle.
15
+ * Without the sandbox the calling convention does not include that register, so on this path it
16
+ * holds whatever the previous builtin left there. A garbage collection that starts while the
17
+ * function is being entered then follows that value as if it were a pointer:
18
+ *
19
+ * ClearStaleLeftTrimmedPointerVisitor::VisitRootPointers <- SIGSEGV
20
+ * InternalFrame::Iterate
21
+ * Heap::CollectGarbage
22
+ * Runtime_StackGuardWithGap
23
+ * Builtins_BaselineOutOfLinePrologue
24
+ *
25
+ * The process dies with SIGSEGV. Measured on Node.js 24.18.0 (arm64, V8 13.6.233), each process
26
+ * running one AgentScript 500 times under `--stress-incremental-marking` (which only makes
27
+ * collections frequent):
28
+ *
29
+ * - enclave 2.18.0 as released: 4 of 30 processes crashed;
30
+ * - the same code with more setup work per execution: 19 of 20;
31
+ * - with this workaround: 0 of 20 (double VM and single VM), and 0 of 56 in earlier trials;
32
+ * - the same larger setup without the workaround but with the baseline compiler switched off
33
+ * (`node --no-sparkplug`): 0 of 20, against 20 of 20 without the flag in the same batch.
34
+ *
35
+ * Without the flag the larger setup crashed 2 of 24 processes that ran the script 1,300 times.
36
+ * The x64 builtin saves the register in the same unconditional way; only arm64 was measured.
37
+ * Node.js 22 (V8 12.4) does not have the code in question, and V8 14.1 (Node.js 25) fixed it: the
38
+ * prologue now saves the register only when the calling convention includes it.
39
+ *
40
+ * ## The workaround
41
+ *
42
+ * The defect needs a compiled function to be instantiated a second time. On an affected engine
43
+ * every source compiled for a sandbox realm therefore gets a unique trailing comment, so nothing
44
+ * is ever found in the compilation cache, and a script that would have been compiled once and run
45
+ * in every context is compiled per use instead.
46
+ *
47
+ * The cost is the compilation cache itself: running the SAME script repeatedly takes as long as
48
+ * running a script the engine has not seen before (which is what a host that executes generated
49
+ * code pays anyway): 5.5 ms instead of 3.0 ms for a small script in the double VM. Each execution
50
+ * also leaves its compiled scripts (about 0.4 MB) in the engine's compilation cache, which drops
51
+ * them after several major garbage collections or when memory runs short. Engines without the
52
+ * defect keep sharing compiled code.
53
+ *
54
+ * ## A process that runs without the baseline compiler
55
+ *
56
+ * The defect is in the entry into baseline code, so a process started with `node --no-sparkplug`
57
+ * cannot have it (0 crashes in 68 processes, against 44 of 44 without the flag). There the
58
+ * workaround is switched off and compiled code is shared again, which gives the repeated-script
59
+ * time and the memory of an unaffected engine back, at the price the flag itself has: code that is
60
+ * not optimized yet runs in the interpreter. The flag is read from `process.execArgv` once, when
61
+ * this module is loaded. It cannot be given in `NODE_OPTIONS` (Node.js refuses it there), and a
62
+ * command line that mentions the baseline compiler in any other way keeps the workaround on.
63
+ *
64
+ * ## Why the comment also varies in length
65
+ *
66
+ * The engine keeps every script it compiled in its compilation cache until several major garbage
67
+ * collections have passed, and looks a new source up there by the hash of its text. V8 computes
68
+ * the hash of a string longer than 16,383 characters from its LENGTH alone, so long sources of
69
+ * one length all land on the same entry chain and the lookup compares the new source with each
70
+ * of them, character by character. Sources that differ only in a counter at their end are the
71
+ * worst case: every comparison runs to the last characters. Measured on Node.js 24.18.0 with the
72
+ * double VM's 137,000-character bootstrap, a same-length marker made one compilation take 0.85 ms
73
+ * at first, 9 ms on average over the first 1,000 executions and 26 ms over the second 1,000.
74
+ *
75
+ * The marker of a long source is therefore padded to one of {@link UNIQUE_SOURCE_LENGTHS}
76
+ * lengths in rotation: the sources compiled most recently all differ in length, hash differently
77
+ * and are never compared (0.85 ms per compilation, flat, over 6,000 executions).
78
+ *
79
+ * @packageDocumentation
80
+ */
81
+ import * as vm from 'vm';
82
+ /**
83
+ * Whether a V8 version can crash when compiled sandbox code is shared between realms (see the
84
+ * module documentation): V8 13.x, which is every Node.js 24 release.
85
+ *
86
+ * @param v8Version `process.versions.v8`, or undefined where there is no Node.js `process`
87
+ */
88
+ export declare function isSharedScriptCodeUnsafe(v8Version: string | undefined): boolean;
89
+ /**
90
+ * Whether the command line of this process switched the baseline compiler (Sparkplug) off, which
91
+ * removes the code the defect is in (see the module documentation).
92
+ *
93
+ * Only the spellings V8 accepts for that one flag count. Any other argument that mentions the
94
+ * baseline compiler, such as a `--sparkplug` that follows it or `--always-sparkplug`, makes the
95
+ * answer false: where the command line is not plainly "off", the workaround stays on.
96
+ *
97
+ * @param execArgv `process.execArgv`
98
+ */
99
+ export declare function isBaselineCompilerOff(execArgv: readonly unknown[] | undefined): boolean;
100
+ /**
101
+ * How many different lengths the marker of a long source rotates through: of the long sources of
102
+ * one length passed to {@link uniqueSource}, this many in a row all come back with different
103
+ * lengths, however many short sources are made unique in between.
104
+ */
105
+ export declare const UNIQUE_SOURCE_LENGTHS = 4096;
106
+ /**
107
+ * Return `source` with a trailing comment that makes its text unique in this process, so that the
108
+ * engine compiles it afresh. The comment is on a line of its own after the source: it changes no
109
+ * line or column number and cannot be swallowed by a `//` comment the source ends with.
110
+ *
111
+ * A source long enough for the engine to hash it by its length also gets a different length each
112
+ * time (see the module documentation).
113
+ */
114
+ export declare function uniqueSource(source: string): string;
115
+ /** What {@link createSandboxScriptApi} returns. */
116
+ export interface SandboxScriptApi {
117
+ /**
118
+ * Compile a script that is used for ONE sandbox realm (the script of an execution, or a helper
119
+ * built for it).
120
+ */
121
+ compileSandboxScript(source: string, options?: vm.ScriptOptions): vm.Script;
122
+ /**
123
+ * The `Script` class to hand to code that compiles scripts for sandbox realms itself (the
124
+ * parent VM of the double VM does).
125
+ */
126
+ SandboxScript: typeof vm.Script;
127
+ /**
128
+ * A helper script that is run in every sandbox realm an adapter creates. Where sharing
129
+ * compiled code is safe it is compiled once and run in each context; otherwise it is compiled
130
+ * for each context it is run in.
131
+ */
132
+ ReusableSandboxScript: new (source: string, options?: vm.ScriptOptions) => ReusableScript;
133
+ }
134
+ /** A script that can be run in any number of contexts. */
135
+ export interface ReusableScript {
136
+ runInContext(context: vm.Context, options?: vm.RunningScriptOptions): unknown;
137
+ }
138
+ /**
139
+ * Build the script-compilation functions for an engine.
140
+ *
141
+ * @param uniqueSources true to never share compiled code: every source is made unique before it
142
+ * is compiled, and a reusable script is compiled per use
143
+ * @param Script the script class to compile with (a test passes one that records its sources)
144
+ */
145
+ export declare function createSandboxScriptApi(uniqueSources: boolean, Script?: typeof vm.Script): SandboxScriptApi;
146
+ /**
147
+ * Whether this process can crash when compiled sandbox code is shared between realms: an affected
148
+ * engine, started with its baseline compiler on.
149
+ */
150
+ export declare const SHARED_SCRIPT_CODE_IS_UNSAFE: boolean;
151
+ /** {@link SandboxScriptApi.compileSandboxScript} for this engine. */
152
+ export declare const compileSandboxScript: (source: string, options?: vm.ScriptOptions) => vm.Script;
153
+ /** {@link SandboxScriptApi.SandboxScript} for this engine. */
154
+ export declare const SandboxScript: typeof vm.Script;
155
+ /** {@link SandboxScriptApi.ReusableSandboxScript} for this engine. */
156
+ export declare const ReusableSandboxScript: new (source: string, options?: vm.ScriptOptions) => ReusableScript;
package/secure-proxy.d.ts CHANGED
@@ -154,6 +154,20 @@ export interface SecureProxyOptions {
154
154
  gates(target: unknown): boolean;
155
155
  call(target: unknown, thisArg: unknown, args: unknown[]): unknown;
156
156
  };
157
+ /**
158
+ * Applied to every value this membrane passes INTO a script callback (the arguments and the
159
+ * receiver a host built-in calls it with), after the value has been wrapped. The single-VM
160
+ * adapter uses it to put its airlock in front of those values as well (see ./realm-airlock):
161
+ * a callback is called by host code, so what it receives does not come out of a trap.
162
+ */
163
+ exposeToSandbox?: (value: unknown) => unknown;
164
+ /**
165
+ * Whether an object was made in the sandbox realm (by the script, or for it). Such a value is
166
+ * the script's own: when a host built-in passes it to a callback (the object a script gave
167
+ * `reduce` to collect into) it goes back as it is instead of behind the membrane, where it
168
+ * would be read-only. The test must only say yes to what certainly is of that realm.
169
+ */
170
+ ownedBySandbox?: (value: object) => boolean;
157
171
  }
158
172
  /**
159
173
  * Create a secure proxy that blocks dangerous property access
@@ -178,6 +192,13 @@ export declare function wrapGlobalsWithSecureProxy(globals: Record<string, unkno
178
192
  * that block access to dangerous properties.
179
193
  */
180
194
  export declare function createSecureStandardLibrary(options?: SecureProxyOptions): Record<string, unknown>;
195
+ /**
196
+ * Whether an object that is not a secure proxy belongs to the host: its prototype chain reaches
197
+ * the host's `Object.prototype`, or it has no prototype at all (the host builds such objects for
198
+ * its results; nothing of the sandbox realm comes out of a secure proxy without a prototype).
199
+ * Every other object was made in the sandbox realm, by the script or for it.
200
+ */
201
+ export declare function isRawHostObject(value: object): boolean;
181
202
  /**
182
203
  * Check if an object is a secure proxy
183
204
  *
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "@enclave-vm/core",
3
- "version": "2.18.0",
3
+ "version": "2.19.0",
4
4
  "description": "Sandbox runtime for secure JavaScript code execution",
5
5
  "author": "AgentFront <info@agentfront.dev>",
6
6
  "homepage": "https://github.com/agentfront/enclave",
@@ -46,13 +46,13 @@
46
46
  },
47
47
  "dependencies": {
48
48
  "@babel/standalone": "^7.29.0",
49
- "@enclave-vm/ast": "2.18.0",
50
- "@enclave-vm/types": "2.18.0",
49
+ "@enclave-vm/ast": "2.19.0",
50
+ "@enclave-vm/types": "2.19.0",
51
51
  "@types/estree": "1.0.8",
52
52
  "acorn": "8.15.0",
53
53
  "acorn-walk": "8.3.4",
54
54
  "astring": "1.9.0",
55
- "zod": "^4.3.6"
55
+ "zod": "^4.6.6"
56
56
  },
57
57
  "peerDependencies": {
58
58
  "@huggingface/transformers": "^3.2.2",