@enclave-vm/core 2.15.3 → 2.16.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.
@@ -128,6 +128,9 @@ function safeSerialize(value) {
128
128
  return val;
129
129
  });
130
130
  }
131
+ function isDangerousKey(key) {
132
+ return DANGEROUS_KEYS.has(key);
133
+ }
131
134
  function sanitizeObject(value, depth = 0) {
132
135
  if (depth > MAX_DEPTH) {
133
136
  return void 0;
@@ -150,6 +153,217 @@ function sanitizeObject(value, depth = 0) {
150
153
  return result;
151
154
  }
152
155
 
156
+ // libs/core/src/adapters/worker-pool/result-encoding.ts
157
+ function encodeResult(value) {
158
+ const specialValues = [];
159
+ return { value: encodeValue(value, [], specialValues), specialValues };
160
+ }
161
+ function encodeValue(value, path, specialValues) {
162
+ if (value === void 0) {
163
+ specialValues.push({ path, kind: "undefined" });
164
+ return null;
165
+ }
166
+ if (typeof value === "number" && !Number.isFinite(value)) {
167
+ const kind = Number.isNaN(value) ? "nan" : value > 0 ? "infinity" : "-infinity";
168
+ specialValues.push({ path, kind });
169
+ return null;
170
+ }
171
+ if (value instanceof Date) {
172
+ const time = value.getTime();
173
+ specialValues.push({ path, kind: "date", time: Number.isNaN(time) ? null : time });
174
+ return null;
175
+ }
176
+ if (Array.isArray(value)) {
177
+ return value.map((item, index) => encodeValue(item, [...path, index], specialValues));
178
+ }
179
+ if (value !== null && typeof value === "object") {
180
+ const encoded = /* @__PURE__ */ Object.create(null);
181
+ for (const key of Object.keys(value)) {
182
+ if (isDangerousKey(key)) continue;
183
+ encoded[key] = encodeValue(value[key], [...path, key], specialValues);
184
+ }
185
+ return encoded;
186
+ }
187
+ return value;
188
+ }
189
+
190
+ // libs/core/src/value-sanitizer.ts
191
+ var DANGEROUS_KEYS2 = /* @__PURE__ */ new Set(["__proto__", "constructor"]);
192
+ var ReflectApply = Reflect.apply;
193
+ var ReflectGet2 = Reflect.get;
194
+ var ArrayIsArray2 = Array.isArray;
195
+ var ObjectKeys = Object.keys;
196
+ var ObjectCreate = Object.create;
197
+ var ObjectGetPrototypeOf = Object.getPrototypeOf;
198
+ var NumberIsFinite2 = Number.isFinite;
199
+ var MathFloor2 = Math.floor;
200
+ var MapProtoEntries = Map.prototype.entries;
201
+ var SetProtoValues = Set.prototype.values;
202
+ var DateProtoGetTime = Date.prototype.getTime;
203
+ var DateProtoToISOString = Date.prototype.toISOString;
204
+ var RegExpProtoSourceGetter = Object.getOwnPropertyDescriptor(RegExp.prototype, "source")?.get;
205
+ var RegExpFlagGetters = [
206
+ ["d", "hasIndices"],
207
+ ["g", "global"],
208
+ ["i", "ignoreCase"],
209
+ ["m", "multiline"],
210
+ ["s", "dotAll"],
211
+ ["u", "unicode"],
212
+ ["v", "unicodeSets"],
213
+ ["y", "sticky"]
214
+ ].map(([flag, property]) => [flag, Object.getOwnPropertyDescriptor(RegExp.prototype, property)?.get]);
215
+ var MapProtoSizeGetter = Object.getOwnPropertyDescriptor(Map.prototype, "size")?.get;
216
+ var SetProtoSizeGetter = Object.getOwnPropertyDescriptor(Set.prototype, "size")?.get;
217
+ function hasBrand(builtin, value) {
218
+ if (!builtin) return false;
219
+ try {
220
+ ReflectApply(builtin, value, []);
221
+ return true;
222
+ } catch {
223
+ return false;
224
+ }
225
+ }
226
+ function regExpToString(value) {
227
+ let flags = "";
228
+ for (const [flag, getter] of RegExpFlagGetters) {
229
+ if (getter && ReflectApply(getter, value, [])) flags += flag;
230
+ }
231
+ return `/${ReflectApply(RegExpProtoSourceGetter, value, [])}/${flags}`;
232
+ }
233
+ function isPlainObject(value) {
234
+ const prototype = ObjectGetPrototypeOf(value);
235
+ return prototype === null || ObjectGetPrototypeOf(prototype) === null;
236
+ }
237
+ function sanitizeValue(value, options = {}, depth = 0, context = { propCount: { count: 0 }, visited: /* @__PURE__ */ new WeakSet() }) {
238
+ const maxDepth = options.maxDepth ?? 20;
239
+ const maxProperties = options.maxProperties ?? 1e4;
240
+ const allowDates = options.allowDates ?? true;
241
+ const allowErrors = options.allowErrors ?? true;
242
+ if (depth > maxDepth) {
243
+ throw new Error(
244
+ `Tool handler return value exceeds maximum depth (${maxDepth}). This limit prevents deeply nested objects that could cause stack overflow.`
245
+ );
246
+ }
247
+ if (context.propCount.count > maxProperties) {
248
+ throw new Error(
249
+ `Tool handler return value exceeds maximum properties (${maxProperties}). This limit prevents memory exhaustion from large object graphs.`
250
+ );
251
+ }
252
+ if (value === null || value === void 0) {
253
+ return value;
254
+ }
255
+ const type = typeof value;
256
+ if (type === "string" || type === "number" || type === "boolean") {
257
+ return value;
258
+ }
259
+ if (type === "bigint") {
260
+ return String(value);
261
+ }
262
+ if (type === "function") {
263
+ throw new Error(
264
+ "Tool handler returned a function. Functions cannot be returned to sandbox code as they could be used for code injection or host scope access."
265
+ );
266
+ }
267
+ if (type === "symbol") {
268
+ throw new Error(
269
+ "Tool handler returned a symbol. Symbols cannot be returned to sandbox code as they could be used for prototype manipulation."
270
+ );
271
+ }
272
+ if (type === "object" && value !== null) {
273
+ if (context.visited.has(value)) {
274
+ return "[Circular]";
275
+ }
276
+ context.visited.add(value);
277
+ }
278
+ if (ArrayIsArray2(value)) {
279
+ const rawLen = ReflectGet2(value, "length");
280
+ const len = typeof rawLen === "number" && NumberIsFinite2(rawLen) && rawLen >= 0 ? MathFloor2(rawLen) : 0;
281
+ context.propCount.count += len;
282
+ if (context.propCount.count > maxProperties) {
283
+ throw new Error(`Tool handler return value exceeds maximum properties (${maxProperties}).`);
284
+ }
285
+ const result = [];
286
+ for (let i = 0; i < len; i++) {
287
+ let item;
288
+ try {
289
+ item = ReflectGet2(value, i);
290
+ } catch {
291
+ item = void 0;
292
+ }
293
+ result[i] = sanitizeValue(item, options, depth + 1, context);
294
+ }
295
+ return result;
296
+ }
297
+ const inspected = options.unwrap ? options.unwrap(value) : value;
298
+ const isPlain = isPlainObject(inspected);
299
+ if (!isPlain && hasBrand(DateProtoGetTime, inspected)) {
300
+ const time = ReflectApply(DateProtoGetTime, inspected, []);
301
+ if (allowDates) {
302
+ return new Date(time);
303
+ }
304
+ return ReflectApply(DateProtoToISOString, inspected, []);
305
+ }
306
+ if (value instanceof Error) {
307
+ const rawName = ReflectGet2(value, "name");
308
+ const rawMessage = ReflectGet2(value, "message");
309
+ const name = typeof rawName === "string" ? rawName : "Error";
310
+ const message = typeof rawMessage === "string" ? rawMessage : "";
311
+ if (allowErrors) {
312
+ return {
313
+ name,
314
+ message
315
+ // Do NOT include stack trace - could leak host information
316
+ };
317
+ }
318
+ return { error: message };
319
+ }
320
+ if (!isPlain && hasBrand(RegExpProtoSourceGetter, inspected)) {
321
+ return regExpToString(inspected);
322
+ }
323
+ if (!isPlain && hasBrand(MapProtoSizeGetter, inspected)) {
324
+ const sanitizedMap = ObjectCreate(null);
325
+ const entries = ReflectApply(MapProtoEntries, inspected, []);
326
+ for (const [key, val] of entries) {
327
+ if (typeof key !== "string") continue;
328
+ if (DANGEROUS_KEYS2.has(key)) continue;
329
+ context.propCount.count++;
330
+ sanitizedMap[key] = sanitizeValue(val, options, depth + 1, context);
331
+ }
332
+ return sanitizedMap;
333
+ }
334
+ if (!isPlain && hasBrand(SetProtoSizeGetter, inspected)) {
335
+ const iter = ReflectApply(SetProtoValues, inspected, []);
336
+ const result = [];
337
+ for (const item of iter) {
338
+ context.propCount.count++;
339
+ result.push(sanitizeValue(item, options, depth + 1, context));
340
+ }
341
+ return result;
342
+ }
343
+ if (type === "object") {
344
+ const sanitized = ObjectCreate(null);
345
+ const keys = ObjectKeys(value);
346
+ context.propCount.count += keys.length;
347
+ if (context.propCount.count > maxProperties) {
348
+ throw new Error(`Tool handler return value exceeds maximum properties (${maxProperties}).`);
349
+ }
350
+ for (const key of keys) {
351
+ if (DANGEROUS_KEYS2.has(key)) {
352
+ continue;
353
+ }
354
+ let propValue;
355
+ try {
356
+ propValue = ReflectGet2(value, key);
357
+ } catch {
358
+ continue;
359
+ }
360
+ sanitized[key] = sanitizeValue(propValue, options, depth + 1, context);
361
+ }
362
+ return sanitized;
363
+ }
364
+ return String(value);
365
+ }
366
+
153
367
  // libs/core/src/tool-namespaces.ts
154
368
  var TOOL_NAMESPACE_FACTORY_SOURCE = `
155
369
  (function () {
@@ -490,11 +704,18 @@ async function handleExecute(msg) {
490
704
  });
491
705
  return;
492
706
  }
707
+ const { value, specialValues } = encodeResult(
708
+ sanitizeValue(result, {
709
+ maxDepth: msg.config.maxSanitizeDepth,
710
+ maxProperties: msg.config.maxSanitizeProperties
711
+ })
712
+ );
493
713
  sendMessage({
494
714
  type: "result",
495
715
  requestId: msg.requestId,
496
716
  success: true,
497
- value: sanitizeObject(result),
717
+ value,
718
+ ...specialValues.length > 0 ? { specialValues } : {},
498
719
  stats: currentExecution.stats
499
720
  });
500
721
  } catch (error) {
package/types.d.ts CHANGED
@@ -282,7 +282,10 @@ export interface ToolBridgeConfig {
282
282
  }
283
283
  export interface EnclaveConfig {
284
284
  /**
285
- * Maximum execution time in milliseconds
285
+ * Maximum execution time in milliseconds. A tool call in progress when it passes is not cut
286
+ * off and its result is delivered; the script's next tool call then fails with "Execution
287
+ * aborted". A handler that never settles keeps `run()` waiting, so bound slow tools in the
288
+ * handler. @enclave-vm/browser follows the same rules.
286
289
  * Default: 30000 (30 seconds)
287
290
  */
288
291
  timeout?: number;
@@ -309,7 +312,9 @@ export interface EnclaveConfig {
309
312
  */
310
313
  maxIterations?: number;
311
314
  /**
312
- * Sandbox adapter to use
315
+ * Sandbox adapter to use. Takes effect only with `doubleVm: { enabled: false }`: with the double
316
+ * VM on (the default), scripts run in the double VM whatever this says. To run scripts with an
317
+ * adapter of your own, pass `sandboxAdapter`.
313
318
  * Default: 'vm'
314
319
  */
315
320
  adapter?: 'vm' | 'isolated-vm' | 'worker_threads';
@@ -802,6 +807,24 @@ export interface CreateEnclaveOptions extends EnclaveConfig {
802
807
  * ```
803
808
  */
804
809
  workerPoolConfig?: Partial<WorkerPoolConfig>;
810
+ /**
811
+ * Run scripts with this adapter instead of the double VM and the `adapter` option, for hosts
812
+ * without `node:vm` (a browser worker, an edge runtime): for example an `InterpreterAdapter`,
813
+ * or an adapter that hands the script to `@enclave-vm/browser`.
814
+ *
815
+ * The enclave still validates and transforms every script first, but isolation is then the
816
+ * adapter's job: it receives the transformed code and the `ExecutionContext` (limits, tool
817
+ * handler, stats, abort signal) and must enforce them. The caller owns the adapter:
818
+ * `Enclave.dispose()` does not dispose it, so one adapter can serve several enclaves.
819
+ *
820
+ * @example
821
+ * ```typescript
822
+ * import { Enclave, InterpreterAdapter } from '@enclave-vm/core';
823
+ *
824
+ * const enclave = new Enclave({ sandboxAdapter: new InterpreterAdapter() });
825
+ * ```
826
+ */
827
+ sandboxAdapter?: SandboxAdapter;
805
828
  /**
806
829
  * Secure proxy configuration override
807
830
  *
@@ -34,6 +34,12 @@ export interface SanitizeOptions {
34
34
  * @default true
35
35
  */
36
36
  allowErrors?: boolean;
37
+ /**
38
+ * Returns the object to check for a Date, Map, Set or RegExp in place of a wrapper around it
39
+ * (the single VM's secure proxy, which has no internal slots). Only builtins are read from the
40
+ * unwrapped object; everything else is still read through `value`.
41
+ */
42
+ unwrap?: (value: object) => object;
37
43
  }
38
44
  /**
39
45
  * Property counter for tracking total properties across recursive calls