@enclave-vm/core 2.14.1 → 2.15.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/esm/index.mjs CHANGED
@@ -123,15 +123,42 @@ var init_reference_config = __esm({
123
123
  });
124
124
 
125
125
  // libs/core/src/sidecar/reference-resolver.ts
126
+ function untrustedLength(value) {
127
+ const rawLen = ReflectGet(value, "length");
128
+ if (typeof rawLen !== "number" || !NumberIsFinite(rawLen) || rawLen < 0) {
129
+ return 0;
130
+ }
131
+ const len = MathFloor(rawLen);
132
+ if (len > MAX_TRAVERSAL_LENGTH) {
133
+ throw new ResolutionLimitError(
134
+ `Array length ${len} exceeds maximum traversal limit (${MAX_TRAVERSAL_LENGTH})`,
135
+ "MAX_TRAVERSAL_LENGTH",
136
+ MAX_TRAVERSAL_LENGTH,
137
+ len
138
+ );
139
+ }
140
+ return len;
141
+ }
142
+ function untrustedAt(value, index) {
143
+ try {
144
+ return ReflectGet(value, index);
145
+ } catch {
146
+ return void 0;
147
+ }
148
+ }
126
149
  function isCompositeHandle(value) {
127
150
  const obj = value;
128
151
  return typeof value === "object" && value !== null && obj["__type"] === "composite" && Array.isArray(obj["__parts"]);
129
152
  }
130
- var ResolutionLimitError, ReferenceResolver;
153
+ var ReflectGet, NumberIsFinite, MathFloor, MAX_TRAVERSAL_LENGTH, ResolutionLimitError, ReferenceResolver;
131
154
  var init_reference_resolver = __esm({
132
155
  "libs/core/src/sidecar/reference-resolver.ts"() {
133
156
  "use strict";
134
157
  init_reference_config();
158
+ ReflectGet = Reflect.get;
159
+ NumberIsFinite = Number.isFinite;
160
+ MathFloor = Math.floor;
161
+ MAX_TRAVERSAL_LENGTH = 1e6;
135
162
  ResolutionLimitError = class _ResolutionLimitError extends Error {
136
163
  constructor(message, code, limit, actual) {
137
164
  super(message);
@@ -175,17 +202,24 @@ var init_reference_resolver = __esm({
175
202
  return size;
176
203
  }
177
204
  if (isCompositeHandle(value)) {
178
- return value.__parts.reduce((sum, part) => {
179
- return sum + this.predictExpandedSize(part, depth + 1);
180
- }, 0);
205
+ const parts = value.__parts;
206
+ const len = untrustedLength(parts);
207
+ let sum = 0;
208
+ for (let i = 0; i < len; i++) {
209
+ sum += this.predictExpandedSize(untrustedAt(parts, i), depth + 1);
210
+ }
211
+ return sum;
181
212
  }
182
213
  if (typeof value === "string") {
183
214
  return Buffer.byteLength(value, "utf-8");
184
215
  }
185
216
  if (Array.isArray(value)) {
186
- return value.reduce((sum, item) => {
187
- return sum + this.predictExpandedSize(item, depth + 1);
188
- }, 0);
217
+ const len = untrustedLength(value);
218
+ let sum = 0;
219
+ for (let i = 0; i < len; i++) {
220
+ sum += this.predictExpandedSize(untrustedAt(value, i), depth + 1);
221
+ }
222
+ return sum;
189
223
  }
190
224
  if (value !== null && typeof value === "object") {
191
225
  return Object.values(value).reduce((sum, val) => {
@@ -246,7 +280,12 @@ var init_reference_resolver = __esm({
246
280
  return value;
247
281
  }
248
282
  if (Array.isArray(value)) {
249
- return value.map((item) => this.resolve(item, depth + 1));
283
+ const len = untrustedLength(value);
284
+ const out = [];
285
+ for (let i = 0; i < len; i++) {
286
+ out[i] = this.resolve(untrustedAt(value, i), depth + 1);
287
+ }
288
+ return out;
250
289
  }
251
290
  if (value !== null && typeof value === "object") {
252
291
  const resolved = /* @__PURE__ */ Object.create(null);
@@ -261,15 +300,17 @@ var init_reference_resolver = __esm({
261
300
  * Resolve a composite handle by concatenating its parts
262
301
  */
263
302
  resolveComposite(handle, depth) {
264
- const parts = [];
265
- for (const part of handle.__parts) {
266
- const resolved = this.resolve(part, depth + 1);
303
+ const out = [];
304
+ const source = handle.__parts;
305
+ const len = untrustedLength(source);
306
+ for (let i = 0; i < len; i++) {
307
+ const resolved = this.resolve(untrustedAt(source, i), depth + 1);
267
308
  if (typeof resolved !== "string") {
268
309
  throw new Error(`Composite part resolved to non-string: ${typeof resolved}`);
269
310
  }
270
- parts.push(resolved);
311
+ out.push(resolved);
271
312
  }
272
- return parts.join("");
313
+ return out.join("");
273
314
  }
274
315
  /**
275
316
  * Check if a value contains any reference IDs
@@ -286,7 +327,13 @@ var init_reference_resolver = __esm({
286
327
  return true;
287
328
  }
288
329
  if (Array.isArray(value)) {
289
- return value.some((item) => this.containsReferences(item, depth + 1));
330
+ const len = untrustedLength(value);
331
+ for (let i = 0; i < len; i++) {
332
+ if (this.containsReferences(untrustedAt(value, i), depth + 1)) {
333
+ return true;
334
+ }
335
+ }
336
+ return false;
290
337
  }
291
338
  if (value !== null && typeof value === "object") {
292
339
  return Object.values(value).some((val) => this.containsReferences(val, depth + 1));
@@ -379,35 +426,53 @@ function sanitizeValue(value, options = {}, depth = 0, context = { propCount: {
379
426
  }
380
427
  context.visited.add(value);
381
428
  }
382
- if (Array.isArray(value)) {
383
- context.propCount.count += value.length;
429
+ if (ArrayIsArray(value)) {
430
+ const rawLen = ReflectGet2(value, "length");
431
+ const len = typeof rawLen === "number" && NumberIsFinite2(rawLen) && rawLen >= 0 ? MathFloor2(rawLen) : 0;
432
+ context.propCount.count += len;
384
433
  if (context.propCount.count > maxProperties) {
385
434
  throw new Error(`Tool handler return value exceeds maximum properties (${maxProperties}).`);
386
435
  }
387
- return value.map((item) => sanitizeValue(item, options, depth + 1, context));
436
+ const result = [];
437
+ for (let i = 0; i < len; i++) {
438
+ let item;
439
+ try {
440
+ item = ReflectGet2(value, i);
441
+ } catch {
442
+ item = void 0;
443
+ }
444
+ result[i] = sanitizeValue(item, options, depth + 1, context);
445
+ }
446
+ return result;
388
447
  }
389
448
  if (value instanceof Date) {
449
+ const time = ReflectApply(DateProtoGetTime, value, []);
390
450
  if (allowDates) {
391
- return new Date(value.getTime());
451
+ return new Date(time);
392
452
  }
393
- return value.toISOString();
453
+ return ReflectApply(DateProtoToISOString, value, []);
394
454
  }
395
455
  if (value instanceof Error) {
456
+ const rawName = ReflectGet2(value, "name");
457
+ const rawMessage = ReflectGet2(value, "message");
458
+ const name = typeof rawName === "string" ? rawName : "Error";
459
+ const message = typeof rawMessage === "string" ? rawMessage : "";
396
460
  if (allowErrors) {
397
461
  return {
398
- name: value.name,
399
- message: value.message
462
+ name,
463
+ message
400
464
  // Do NOT include stack trace - could leak host information
401
465
  };
402
466
  }
403
- return { error: value.message };
467
+ return { error: message };
404
468
  }
405
469
  if (value instanceof RegExp) {
406
- return value.toString();
470
+ return ReflectApply(RegExpProtoToString, value, []);
407
471
  }
408
472
  if (value instanceof Map) {
409
- const sanitizedMap = /* @__PURE__ */ Object.create(null);
410
- for (const [key, val] of value.entries()) {
473
+ const sanitizedMap = ObjectCreate(null);
474
+ const entries = ReflectApply(MapProtoEntries, value, []);
475
+ for (const [key, val] of entries) {
411
476
  if (typeof key !== "string") continue;
412
477
  if (DANGEROUS_KEYS.has(key)) continue;
413
478
  context.propCount.count++;
@@ -416,13 +481,17 @@ function sanitizeValue(value, options = {}, depth = 0, context = { propCount: {
416
481
  return sanitizedMap;
417
482
  }
418
483
  if (value instanceof Set) {
419
- const arr = Array.from(value);
420
- context.propCount.count += arr.length;
421
- return arr.map((item) => sanitizeValue(item, options, depth + 1, context));
484
+ const iter = ReflectApply(SetProtoValues, value, []);
485
+ const result = [];
486
+ for (const item of iter) {
487
+ context.propCount.count++;
488
+ result.push(sanitizeValue(item, options, depth + 1, context));
489
+ }
490
+ return result;
422
491
  }
423
492
  if (type === "object") {
424
- const sanitized = /* @__PURE__ */ Object.create(null);
425
- const keys = Object.keys(value);
493
+ const sanitized = ObjectCreate(null);
494
+ const keys = ObjectKeys(value);
426
495
  context.propCount.count += keys.length;
427
496
  if (context.propCount.count > maxProperties) {
428
497
  throw new Error(`Tool handler return value exceeds maximum properties (${maxProperties}).`);
@@ -433,7 +502,7 @@ function sanitizeValue(value, options = {}, depth = 0, context = { propCount: {
433
502
  }
434
503
  let propValue;
435
504
  try {
436
- propValue = value[key];
505
+ propValue = ReflectGet2(value, key);
437
506
  } catch {
438
507
  continue;
439
508
  }
@@ -571,11 +640,23 @@ function checkSerializedSize(value, maxBytes) {
571
640
  return { ok: false, error: err instanceof Error ? err.message : "Unknown error" };
572
641
  }
573
642
  }
574
- var DANGEROUS_KEYS;
643
+ var DANGEROUS_KEYS, ReflectApply, ReflectGet2, ArrayIsArray, ObjectKeys, ObjectCreate, NumberIsFinite2, MathFloor2, MapProtoEntries, SetProtoValues, DateProtoGetTime, DateProtoToISOString, RegExpProtoToString;
575
644
  var init_value_sanitizer = __esm({
576
645
  "libs/core/src/value-sanitizer.ts"() {
577
646
  "use strict";
578
647
  DANGEROUS_KEYS = /* @__PURE__ */ new Set(["__proto__", "constructor"]);
648
+ ReflectApply = Reflect.apply;
649
+ ReflectGet2 = Reflect.get;
650
+ ArrayIsArray = Array.isArray;
651
+ ObjectKeys = Object.keys;
652
+ ObjectCreate = Object.create;
653
+ NumberIsFinite2 = Number.isFinite;
654
+ MathFloor2 = Math.floor;
655
+ MapProtoEntries = Map.prototype.entries;
656
+ SetProtoValues = Set.prototype.values;
657
+ DateProtoGetTime = Date.prototype.getTime;
658
+ DateProtoToISOString = Date.prototype.toISOString;
659
+ RegExpProtoToString = RegExp.prototype.toString;
579
660
  }
580
661
  });
581
662
 
@@ -903,11 +984,23 @@ function createSecureProxy(target, options = {}) {
903
984
  // Intercept function calls to proxy return values
904
985
  // eslint-disable-next-line @typescript-eslint/no-explicit-any -- Proxy handler signature requires any for compatibility
905
986
  apply(target2, thisArg, argArray) {
906
- const result = Reflect.apply(target2, thisArg, argArray);
987
+ const unwrappedThis = thisArg !== null && (typeof thisArg === "object" || typeof thisArg === "function") && proxyToTarget.has(thisArg) ? proxyToTarget.get(thisArg) : thisArg;
988
+ const result = Reflect.apply(target2, unwrappedThis, argArray);
907
989
  if (isProxyable(result)) {
908
990
  return proxyWithDepth(result, depth + 1);
909
991
  }
910
992
  return result;
993
+ },
994
+ // Intercept constructor calls to proxy the created instance. Without this, code such as
995
+ // `new (wrappedCtor)()` would return a RAW object whose prototype chain reaches the
996
+ // host Function constructor — the same escape class the apply trap closes for calls.
997
+ // eslint-disable-next-line @typescript-eslint/no-explicit-any -- Proxy handler signature requires any for compatibility
998
+ construct(target2, argArray, newTarget) {
999
+ const instance = Reflect.construct(target2, argArray, newTarget === proxy ? target2 : newTarget);
1000
+ if (isProxyable(instance)) {
1001
+ return proxyWithDepth(instance, depth + 1);
1002
+ }
1003
+ return instance;
911
1004
  }
912
1005
  });
913
1006
  let objCacheMap = proxyCache.get(obj);
@@ -917,6 +1010,7 @@ function createSecureProxy(target, options = {}) {
917
1010
  }
918
1011
  objCacheMap.set(cacheKey, proxy);
919
1012
  proxySet.add(proxy);
1013
+ proxyToTarget.set(proxy, obj);
920
1014
  return proxy;
921
1015
  }
922
1016
  return proxyWithDepth(target, 0);
@@ -956,7 +1050,7 @@ function isSecureProxy(obj) {
956
1050
  }
957
1051
  return proxySet.has(obj);
958
1052
  }
959
- var BLOCKED_PROPERTY_CATEGORIES, BLOCKED_PROPERTIES, DEFAULT_SECURE_PROXY_CONFIG, FUNCTION_BLOCKED_PROPERTIES, proxyCache, proxySet, NON_PROXYABLE_TYPES, INTERNAL_SLOT_TYPES;
1053
+ var BLOCKED_PROPERTY_CATEGORIES, BLOCKED_PROPERTIES, DEFAULT_SECURE_PROXY_CONFIG, FUNCTION_BLOCKED_PROPERTIES, proxyCache, proxySet, proxyToTarget, NON_PROXYABLE_TYPES, INTERNAL_SLOT_TYPES;
960
1054
  var init_secure_proxy = __esm({
961
1055
  "libs/core/src/secure-proxy.ts"() {
962
1056
  "use strict";
@@ -1038,6 +1132,7 @@ var init_secure_proxy = __esm({
1038
1132
  ]);
1039
1133
  proxyCache = /* @__PURE__ */ new WeakMap();
1040
1134
  proxySet = /* @__PURE__ */ new WeakSet();
1135
+ proxyToTarget = /* @__PURE__ */ new WeakMap();
1041
1136
  NON_PROXYABLE_TYPES = /* @__PURE__ */ new Set([
1042
1137
  // Map/Set have internal slots but we may need to proxy them in the future
1043
1138
  "[object Map]",
@@ -2351,10 +2446,34 @@ ${stackTraceHardeningCode}
2351
2446
  getPrototypeOf: function(target) {
2352
2447
  // Return null to hide prototype chain
2353
2448
  return null;
2354
- }
2449
+ },
2450
+ // SECURITY (GHSA-grmc-r8vw-226r): the get trap re-wraps values obtained via property
2451
+ // ACCESS, but function-call results cross the same trust boundary and must be wrapped
2452
+ // too. Without an apply trap, calling a wrapped function (for example the then method
2453
+ // of the secure Promise returned by callTool) falls through to the default call and
2454
+ // returns a RAW host object; the sandbox can then walk its prototype chain
2455
+ // (Promise.prototype up to Function) to reach the host Function constructor for RCE.
2456
+ // Results are re-wrapped at a FRESH depth (0) so a chain of calls such as
2457
+ // then().then() cannot inflate depth past the recursion cap and leak an unwrapped value.
2458
+ apply: function(target, thisArg, args) {
2459
+ return createSecureProxy(Reflect.apply(target, thisArg, args), 0);
2460
+ }
2461
+ // NOTE: intentionally NO construct trap here (unlike the standalone secure-proxy used
2462
+ // for single-VM mode). Every constructor reachable from sandbox code resolves to an
2463
+ // inner-VM or parent-VM intrinsic, and BOTH of those realms run with code generation
2464
+ // from strings disabled, so a 'new X()' result cannot reach a usable Function
2465
+ // constructor. The only code-generation-enabled realm (the host) is reached solely via
2466
+ // host return values (callTool), which is an apply-path and is covered above. Wrapping
2467
+ // construct results would additionally break the proxy invariant for the frozen (non-
2468
+ // extensible) Error objects the harness throws (getPrototypeOf must not report null for
2469
+ // a non-extensible target), masking legitimate errors.
2355
2470
  });
2356
2471
 
2357
2472
  proxyCache.set(obj, proxy);
2473
+ // Idempotency: re-wrapping an already-secure proxy must return it unchanged, so an apply
2474
+ // result that is itself already a secure proxy is not double-wrapped (which would nest
2475
+ // proxies and inflate depth toward the recursion cap).
2476
+ proxyCache.set(proxy, proxy);
2358
2477
  return proxy;
2359
2478
  }
2360
2479
 
@@ -2732,10 +2851,20 @@ ${stackTraceHardeningCode}
2732
2851
  if (typeof fn !== 'function') {
2733
2852
  throw createSafeError('parallel() requires a callback function as second argument', 'TypeError');
2734
2853
  }
2735
- if (items.length > 100) {
2854
+ // SECURITY: items may be an attacker Proxy that only passes Array.isArray. Read the length
2855
+ // ONCE and build the promise list by index rather than items.map(fn), so a .map trap can
2856
+ // neither be handed our callback nor use a stateful length to slip past the 100-item cap.
2857
+ var len = items.length;
2858
+ if (typeof len !== 'number' || !isFinite(len) || len < 0) len = 0;
2859
+ len = Math.floor(len);
2860
+ if (len > 100) {
2736
2861
  throw createSafeError('parallel() is limited to 100 items');
2737
2862
  }
2738
- return await Promise.all(items.map(fn));
2863
+ var promises = [];
2864
+ for (var i = 0; i < len; i++) {
2865
+ promises[i] = fn(items[i], i, items);
2866
+ }
2867
+ return await Promise.all(promises);
2739
2868
  }
2740
2869
 
2741
2870
  /**
@@ -6022,6 +6151,24 @@ var init_errors = __esm({
6022
6151
  });
6023
6152
 
6024
6153
  // libs/core/src/adapters/worker-pool/safe-deserialize.ts
6154
+ function mapArraySafely(value, sanitizeItem) {
6155
+ const rawLen = ReflectGet3(value, "length");
6156
+ const len = typeof rawLen === "number" && NumberIsFinite3(rawLen) && rawLen >= 0 ? MathFloor3(rawLen) : 0;
6157
+ if (len > MAX_ARRAY_LENGTH) {
6158
+ throw new MessageValidationError(`Array exceeds maximum length of ${MAX_ARRAY_LENGTH}`);
6159
+ }
6160
+ const out = [];
6161
+ for (let i = 0; i < len; i++) {
6162
+ let item;
6163
+ try {
6164
+ item = ReflectGet3(value, i);
6165
+ } catch {
6166
+ item = void 0;
6167
+ }
6168
+ out[i] = sanitizeItem(item);
6169
+ }
6170
+ return out;
6171
+ }
6025
6172
  function safeDeserialize(raw, maxSizeBytes) {
6026
6173
  if (maxSizeBytes !== void 0) {
6027
6174
  const byteLength = Buffer.byteLength(raw, "utf-8");
@@ -6049,8 +6196,8 @@ function sanitizeObjectWithDepthCheck(value, depth) {
6049
6196
  if (typeof value !== "object") {
6050
6197
  return value;
6051
6198
  }
6052
- if (Array.isArray(value)) {
6053
- return value.map((item) => sanitizeObjectWithDepthCheck(item, depth + 1));
6199
+ if (ArrayIsArray2(value)) {
6200
+ return mapArraySafely(value, (item) => sanitizeObjectWithDepthCheck(item, depth + 1));
6054
6201
  }
6055
6202
  const result = /* @__PURE__ */ Object.create(null);
6056
6203
  for (const key of Object.keys(value)) {
@@ -6078,8 +6225,8 @@ function sanitizeObject(value, depth = 0) {
6078
6225
  if (typeof value !== "object") {
6079
6226
  return value;
6080
6227
  }
6081
- if (Array.isArray(value)) {
6082
- return value.map((item) => sanitizeObject(item, depth + 1));
6228
+ if (ArrayIsArray2(value)) {
6229
+ return mapArraySafely(value, (item) => sanitizeObject(item, depth + 1));
6083
6230
  }
6084
6231
  const result = /* @__PURE__ */ Object.create(null);
6085
6232
  for (const key of Object.keys(value)) {
@@ -6089,11 +6236,16 @@ function sanitizeObject(value, depth = 0) {
6089
6236
  }
6090
6237
  return result;
6091
6238
  }
6092
- var DANGEROUS_KEYS2, MAX_DEPTH;
6239
+ var ReflectGet3, ArrayIsArray2, NumberIsFinite3, MathFloor3, MAX_ARRAY_LENGTH, DANGEROUS_KEYS2, MAX_DEPTH;
6093
6240
  var init_safe_deserialize = __esm({
6094
6241
  "libs/core/src/adapters/worker-pool/safe-deserialize.ts"() {
6095
6242
  "use strict";
6096
6243
  init_errors();
6244
+ ReflectGet3 = Reflect.get;
6245
+ ArrayIsArray2 = Array.isArray;
6246
+ NumberIsFinite3 = Number.isFinite;
6247
+ MathFloor3 = Math.floor;
6248
+ MAX_ARRAY_LENGTH = 1e6;
6097
6249
  DANGEROUS_KEYS2 = /* @__PURE__ */ new Set(["__proto__", "constructor", "prototype"]);
6098
6250
  MAX_DEPTH = 50;
6099
6251
  }
package/index.js CHANGED
@@ -145,15 +145,42 @@ var init_reference_config = __esm({
145
145
  });
146
146
 
147
147
  // libs/core/src/sidecar/reference-resolver.ts
148
+ function untrustedLength(value) {
149
+ const rawLen = ReflectGet(value, "length");
150
+ if (typeof rawLen !== "number" || !NumberIsFinite(rawLen) || rawLen < 0) {
151
+ return 0;
152
+ }
153
+ const len = MathFloor(rawLen);
154
+ if (len > MAX_TRAVERSAL_LENGTH) {
155
+ throw new ResolutionLimitError(
156
+ `Array length ${len} exceeds maximum traversal limit (${MAX_TRAVERSAL_LENGTH})`,
157
+ "MAX_TRAVERSAL_LENGTH",
158
+ MAX_TRAVERSAL_LENGTH,
159
+ len
160
+ );
161
+ }
162
+ return len;
163
+ }
164
+ function untrustedAt(value, index) {
165
+ try {
166
+ return ReflectGet(value, index);
167
+ } catch {
168
+ return void 0;
169
+ }
170
+ }
148
171
  function isCompositeHandle(value) {
149
172
  const obj = value;
150
173
  return typeof value === "object" && value !== null && obj["__type"] === "composite" && Array.isArray(obj["__parts"]);
151
174
  }
152
- var ResolutionLimitError, ReferenceResolver;
175
+ var ReflectGet, NumberIsFinite, MathFloor, MAX_TRAVERSAL_LENGTH, ResolutionLimitError, ReferenceResolver;
153
176
  var init_reference_resolver = __esm({
154
177
  "libs/core/src/sidecar/reference-resolver.ts"() {
155
178
  "use strict";
156
179
  init_reference_config();
180
+ ReflectGet = Reflect.get;
181
+ NumberIsFinite = Number.isFinite;
182
+ MathFloor = Math.floor;
183
+ MAX_TRAVERSAL_LENGTH = 1e6;
157
184
  ResolutionLimitError = class _ResolutionLimitError extends Error {
158
185
  constructor(message, code, limit, actual) {
159
186
  super(message);
@@ -197,17 +224,24 @@ var init_reference_resolver = __esm({
197
224
  return size;
198
225
  }
199
226
  if (isCompositeHandle(value)) {
200
- return value.__parts.reduce((sum, part) => {
201
- return sum + this.predictExpandedSize(part, depth + 1);
202
- }, 0);
227
+ const parts = value.__parts;
228
+ const len = untrustedLength(parts);
229
+ let sum = 0;
230
+ for (let i = 0; i < len; i++) {
231
+ sum += this.predictExpandedSize(untrustedAt(parts, i), depth + 1);
232
+ }
233
+ return sum;
203
234
  }
204
235
  if (typeof value === "string") {
205
236
  return Buffer.byteLength(value, "utf-8");
206
237
  }
207
238
  if (Array.isArray(value)) {
208
- return value.reduce((sum, item) => {
209
- return sum + this.predictExpandedSize(item, depth + 1);
210
- }, 0);
239
+ const len = untrustedLength(value);
240
+ let sum = 0;
241
+ for (let i = 0; i < len; i++) {
242
+ sum += this.predictExpandedSize(untrustedAt(value, i), depth + 1);
243
+ }
244
+ return sum;
211
245
  }
212
246
  if (value !== null && typeof value === "object") {
213
247
  return Object.values(value).reduce((sum, val) => {
@@ -268,7 +302,12 @@ var init_reference_resolver = __esm({
268
302
  return value;
269
303
  }
270
304
  if (Array.isArray(value)) {
271
- return value.map((item) => this.resolve(item, depth + 1));
305
+ const len = untrustedLength(value);
306
+ const out = [];
307
+ for (let i = 0; i < len; i++) {
308
+ out[i] = this.resolve(untrustedAt(value, i), depth + 1);
309
+ }
310
+ return out;
272
311
  }
273
312
  if (value !== null && typeof value === "object") {
274
313
  const resolved = /* @__PURE__ */ Object.create(null);
@@ -283,15 +322,17 @@ var init_reference_resolver = __esm({
283
322
  * Resolve a composite handle by concatenating its parts
284
323
  */
285
324
  resolveComposite(handle, depth) {
286
- const parts = [];
287
- for (const part of handle.__parts) {
288
- const resolved = this.resolve(part, depth + 1);
325
+ const out = [];
326
+ const source = handle.__parts;
327
+ const len = untrustedLength(source);
328
+ for (let i = 0; i < len; i++) {
329
+ const resolved = this.resolve(untrustedAt(source, i), depth + 1);
289
330
  if (typeof resolved !== "string") {
290
331
  throw new Error(`Composite part resolved to non-string: ${typeof resolved}`);
291
332
  }
292
- parts.push(resolved);
333
+ out.push(resolved);
293
334
  }
294
- return parts.join("");
335
+ return out.join("");
295
336
  }
296
337
  /**
297
338
  * Check if a value contains any reference IDs
@@ -308,7 +349,13 @@ var init_reference_resolver = __esm({
308
349
  return true;
309
350
  }
310
351
  if (Array.isArray(value)) {
311
- return value.some((item) => this.containsReferences(item, depth + 1));
352
+ const len = untrustedLength(value);
353
+ for (let i = 0; i < len; i++) {
354
+ if (this.containsReferences(untrustedAt(value, i), depth + 1)) {
355
+ return true;
356
+ }
357
+ }
358
+ return false;
312
359
  }
313
360
  if (value !== null && typeof value === "object") {
314
361
  return Object.values(value).some((val) => this.containsReferences(val, depth + 1));
@@ -401,35 +448,53 @@ function sanitizeValue(value, options = {}, depth = 0, context = { propCount: {
401
448
  }
402
449
  context.visited.add(value);
403
450
  }
404
- if (Array.isArray(value)) {
405
- context.propCount.count += value.length;
451
+ if (ArrayIsArray(value)) {
452
+ const rawLen = ReflectGet2(value, "length");
453
+ const len = typeof rawLen === "number" && NumberIsFinite2(rawLen) && rawLen >= 0 ? MathFloor2(rawLen) : 0;
454
+ context.propCount.count += len;
406
455
  if (context.propCount.count > maxProperties) {
407
456
  throw new Error(`Tool handler return value exceeds maximum properties (${maxProperties}).`);
408
457
  }
409
- return value.map((item) => sanitizeValue(item, options, depth + 1, context));
458
+ const result = [];
459
+ for (let i = 0; i < len; i++) {
460
+ let item;
461
+ try {
462
+ item = ReflectGet2(value, i);
463
+ } catch {
464
+ item = void 0;
465
+ }
466
+ result[i] = sanitizeValue(item, options, depth + 1, context);
467
+ }
468
+ return result;
410
469
  }
411
470
  if (value instanceof Date) {
471
+ const time = ReflectApply(DateProtoGetTime, value, []);
412
472
  if (allowDates) {
413
- return new Date(value.getTime());
473
+ return new Date(time);
414
474
  }
415
- return value.toISOString();
475
+ return ReflectApply(DateProtoToISOString, value, []);
416
476
  }
417
477
  if (value instanceof Error) {
478
+ const rawName = ReflectGet2(value, "name");
479
+ const rawMessage = ReflectGet2(value, "message");
480
+ const name = typeof rawName === "string" ? rawName : "Error";
481
+ const message = typeof rawMessage === "string" ? rawMessage : "";
418
482
  if (allowErrors) {
419
483
  return {
420
- name: value.name,
421
- message: value.message
484
+ name,
485
+ message
422
486
  // Do NOT include stack trace - could leak host information
423
487
  };
424
488
  }
425
- return { error: value.message };
489
+ return { error: message };
426
490
  }
427
491
  if (value instanceof RegExp) {
428
- return value.toString();
492
+ return ReflectApply(RegExpProtoToString, value, []);
429
493
  }
430
494
  if (value instanceof Map) {
431
- const sanitizedMap = /* @__PURE__ */ Object.create(null);
432
- for (const [key, val] of value.entries()) {
495
+ const sanitizedMap = ObjectCreate(null);
496
+ const entries = ReflectApply(MapProtoEntries, value, []);
497
+ for (const [key, val] of entries) {
433
498
  if (typeof key !== "string") continue;
434
499
  if (DANGEROUS_KEYS.has(key)) continue;
435
500
  context.propCount.count++;
@@ -438,13 +503,17 @@ function sanitizeValue(value, options = {}, depth = 0, context = { propCount: {
438
503
  return sanitizedMap;
439
504
  }
440
505
  if (value instanceof Set) {
441
- const arr = Array.from(value);
442
- context.propCount.count += arr.length;
443
- return arr.map((item) => sanitizeValue(item, options, depth + 1, context));
506
+ const iter = ReflectApply(SetProtoValues, value, []);
507
+ const result = [];
508
+ for (const item of iter) {
509
+ context.propCount.count++;
510
+ result.push(sanitizeValue(item, options, depth + 1, context));
511
+ }
512
+ return result;
444
513
  }
445
514
  if (type === "object") {
446
- const sanitized = /* @__PURE__ */ Object.create(null);
447
- const keys = Object.keys(value);
515
+ const sanitized = ObjectCreate(null);
516
+ const keys = ObjectKeys(value);
448
517
  context.propCount.count += keys.length;
449
518
  if (context.propCount.count > maxProperties) {
450
519
  throw new Error(`Tool handler return value exceeds maximum properties (${maxProperties}).`);
@@ -455,7 +524,7 @@ function sanitizeValue(value, options = {}, depth = 0, context = { propCount: {
455
524
  }
456
525
  let propValue;
457
526
  try {
458
- propValue = value[key];
527
+ propValue = ReflectGet2(value, key);
459
528
  } catch {
460
529
  continue;
461
530
  }
@@ -593,11 +662,23 @@ function checkSerializedSize(value, maxBytes) {
593
662
  return { ok: false, error: err instanceof Error ? err.message : "Unknown error" };
594
663
  }
595
664
  }
596
- var DANGEROUS_KEYS;
665
+ var DANGEROUS_KEYS, ReflectApply, ReflectGet2, ArrayIsArray, ObjectKeys, ObjectCreate, NumberIsFinite2, MathFloor2, MapProtoEntries, SetProtoValues, DateProtoGetTime, DateProtoToISOString, RegExpProtoToString;
597
666
  var init_value_sanitizer = __esm({
598
667
  "libs/core/src/value-sanitizer.ts"() {
599
668
  "use strict";
600
669
  DANGEROUS_KEYS = /* @__PURE__ */ new Set(["__proto__", "constructor"]);
670
+ ReflectApply = Reflect.apply;
671
+ ReflectGet2 = Reflect.get;
672
+ ArrayIsArray = Array.isArray;
673
+ ObjectKeys = Object.keys;
674
+ ObjectCreate = Object.create;
675
+ NumberIsFinite2 = Number.isFinite;
676
+ MathFloor2 = Math.floor;
677
+ MapProtoEntries = Map.prototype.entries;
678
+ SetProtoValues = Set.prototype.values;
679
+ DateProtoGetTime = Date.prototype.getTime;
680
+ DateProtoToISOString = Date.prototype.toISOString;
681
+ RegExpProtoToString = RegExp.prototype.toString;
601
682
  }
602
683
  });
603
684
 
@@ -925,11 +1006,23 @@ function createSecureProxy(target, options = {}) {
925
1006
  // Intercept function calls to proxy return values
926
1007
  // eslint-disable-next-line @typescript-eslint/no-explicit-any -- Proxy handler signature requires any for compatibility
927
1008
  apply(target2, thisArg, argArray) {
928
- const result = Reflect.apply(target2, thisArg, argArray);
1009
+ const unwrappedThis = thisArg !== null && (typeof thisArg === "object" || typeof thisArg === "function") && proxyToTarget.has(thisArg) ? proxyToTarget.get(thisArg) : thisArg;
1010
+ const result = Reflect.apply(target2, unwrappedThis, argArray);
929
1011
  if (isProxyable(result)) {
930
1012
  return proxyWithDepth(result, depth + 1);
931
1013
  }
932
1014
  return result;
1015
+ },
1016
+ // Intercept constructor calls to proxy the created instance. Without this, code such as
1017
+ // `new (wrappedCtor)()` would return a RAW object whose prototype chain reaches the
1018
+ // host Function constructor — the same escape class the apply trap closes for calls.
1019
+ // eslint-disable-next-line @typescript-eslint/no-explicit-any -- Proxy handler signature requires any for compatibility
1020
+ construct(target2, argArray, newTarget) {
1021
+ const instance = Reflect.construct(target2, argArray, newTarget === proxy ? target2 : newTarget);
1022
+ if (isProxyable(instance)) {
1023
+ return proxyWithDepth(instance, depth + 1);
1024
+ }
1025
+ return instance;
933
1026
  }
934
1027
  });
935
1028
  let objCacheMap = proxyCache.get(obj);
@@ -939,6 +1032,7 @@ function createSecureProxy(target, options = {}) {
939
1032
  }
940
1033
  objCacheMap.set(cacheKey, proxy);
941
1034
  proxySet.add(proxy);
1035
+ proxyToTarget.set(proxy, obj);
942
1036
  return proxy;
943
1037
  }
944
1038
  return proxyWithDepth(target, 0);
@@ -978,7 +1072,7 @@ function isSecureProxy(obj) {
978
1072
  }
979
1073
  return proxySet.has(obj);
980
1074
  }
981
- var BLOCKED_PROPERTY_CATEGORIES, BLOCKED_PROPERTIES, DEFAULT_SECURE_PROXY_CONFIG, FUNCTION_BLOCKED_PROPERTIES, proxyCache, proxySet, NON_PROXYABLE_TYPES, INTERNAL_SLOT_TYPES;
1075
+ var BLOCKED_PROPERTY_CATEGORIES, BLOCKED_PROPERTIES, DEFAULT_SECURE_PROXY_CONFIG, FUNCTION_BLOCKED_PROPERTIES, proxyCache, proxySet, proxyToTarget, NON_PROXYABLE_TYPES, INTERNAL_SLOT_TYPES;
982
1076
  var init_secure_proxy = __esm({
983
1077
  "libs/core/src/secure-proxy.ts"() {
984
1078
  "use strict";
@@ -1060,6 +1154,7 @@ var init_secure_proxy = __esm({
1060
1154
  ]);
1061
1155
  proxyCache = /* @__PURE__ */ new WeakMap();
1062
1156
  proxySet = /* @__PURE__ */ new WeakSet();
1157
+ proxyToTarget = /* @__PURE__ */ new WeakMap();
1063
1158
  NON_PROXYABLE_TYPES = /* @__PURE__ */ new Set([
1064
1159
  // Map/Set have internal slots but we may need to proxy them in the future
1065
1160
  "[object Map]",
@@ -2373,10 +2468,34 @@ ${stackTraceHardeningCode}
2373
2468
  getPrototypeOf: function(target) {
2374
2469
  // Return null to hide prototype chain
2375
2470
  return null;
2376
- }
2471
+ },
2472
+ // SECURITY (GHSA-grmc-r8vw-226r): the get trap re-wraps values obtained via property
2473
+ // ACCESS, but function-call results cross the same trust boundary and must be wrapped
2474
+ // too. Without an apply trap, calling a wrapped function (for example the then method
2475
+ // of the secure Promise returned by callTool) falls through to the default call and
2476
+ // returns a RAW host object; the sandbox can then walk its prototype chain
2477
+ // (Promise.prototype up to Function) to reach the host Function constructor for RCE.
2478
+ // Results are re-wrapped at a FRESH depth (0) so a chain of calls such as
2479
+ // then().then() cannot inflate depth past the recursion cap and leak an unwrapped value.
2480
+ apply: function(target, thisArg, args) {
2481
+ return createSecureProxy(Reflect.apply(target, thisArg, args), 0);
2482
+ }
2483
+ // NOTE: intentionally NO construct trap here (unlike the standalone secure-proxy used
2484
+ // for single-VM mode). Every constructor reachable from sandbox code resolves to an
2485
+ // inner-VM or parent-VM intrinsic, and BOTH of those realms run with code generation
2486
+ // from strings disabled, so a 'new X()' result cannot reach a usable Function
2487
+ // constructor. The only code-generation-enabled realm (the host) is reached solely via
2488
+ // host return values (callTool), which is an apply-path and is covered above. Wrapping
2489
+ // construct results would additionally break the proxy invariant for the frozen (non-
2490
+ // extensible) Error objects the harness throws (getPrototypeOf must not report null for
2491
+ // a non-extensible target), masking legitimate errors.
2377
2492
  });
2378
2493
 
2379
2494
  proxyCache.set(obj, proxy);
2495
+ // Idempotency: re-wrapping an already-secure proxy must return it unchanged, so an apply
2496
+ // result that is itself already a secure proxy is not double-wrapped (which would nest
2497
+ // proxies and inflate depth toward the recursion cap).
2498
+ proxyCache.set(proxy, proxy);
2380
2499
  return proxy;
2381
2500
  }
2382
2501
 
@@ -2754,10 +2873,20 @@ ${stackTraceHardeningCode}
2754
2873
  if (typeof fn !== 'function') {
2755
2874
  throw createSafeError('parallel() requires a callback function as second argument', 'TypeError');
2756
2875
  }
2757
- if (items.length > 100) {
2876
+ // SECURITY: items may be an attacker Proxy that only passes Array.isArray. Read the length
2877
+ // ONCE and build the promise list by index rather than items.map(fn), so a .map trap can
2878
+ // neither be handed our callback nor use a stateful length to slip past the 100-item cap.
2879
+ var len = items.length;
2880
+ if (typeof len !== 'number' || !isFinite(len) || len < 0) len = 0;
2881
+ len = Math.floor(len);
2882
+ if (len > 100) {
2758
2883
  throw createSafeError('parallel() is limited to 100 items');
2759
2884
  }
2760
- return await Promise.all(items.map(fn));
2885
+ var promises = [];
2886
+ for (var i = 0; i < len; i++) {
2887
+ promises[i] = fn(items[i], i, items);
2888
+ }
2889
+ return await Promise.all(promises);
2761
2890
  }
2762
2891
 
2763
2892
  /**
@@ -6044,6 +6173,24 @@ var init_errors = __esm({
6044
6173
  });
6045
6174
 
6046
6175
  // libs/core/src/adapters/worker-pool/safe-deserialize.ts
6176
+ function mapArraySafely(value, sanitizeItem) {
6177
+ const rawLen = ReflectGet3(value, "length");
6178
+ const len = typeof rawLen === "number" && NumberIsFinite3(rawLen) && rawLen >= 0 ? MathFloor3(rawLen) : 0;
6179
+ if (len > MAX_ARRAY_LENGTH) {
6180
+ throw new MessageValidationError(`Array exceeds maximum length of ${MAX_ARRAY_LENGTH}`);
6181
+ }
6182
+ const out = [];
6183
+ for (let i = 0; i < len; i++) {
6184
+ let item;
6185
+ try {
6186
+ item = ReflectGet3(value, i);
6187
+ } catch {
6188
+ item = void 0;
6189
+ }
6190
+ out[i] = sanitizeItem(item);
6191
+ }
6192
+ return out;
6193
+ }
6047
6194
  function safeDeserialize(raw, maxSizeBytes) {
6048
6195
  if (maxSizeBytes !== void 0) {
6049
6196
  const byteLength = Buffer.byteLength(raw, "utf-8");
@@ -6071,8 +6218,8 @@ function sanitizeObjectWithDepthCheck(value, depth) {
6071
6218
  if (typeof value !== "object") {
6072
6219
  return value;
6073
6220
  }
6074
- if (Array.isArray(value)) {
6075
- return value.map((item) => sanitizeObjectWithDepthCheck(item, depth + 1));
6221
+ if (ArrayIsArray2(value)) {
6222
+ return mapArraySafely(value, (item) => sanitizeObjectWithDepthCheck(item, depth + 1));
6076
6223
  }
6077
6224
  const result = /* @__PURE__ */ Object.create(null);
6078
6225
  for (const key of Object.keys(value)) {
@@ -6100,8 +6247,8 @@ function sanitizeObject(value, depth = 0) {
6100
6247
  if (typeof value !== "object") {
6101
6248
  return value;
6102
6249
  }
6103
- if (Array.isArray(value)) {
6104
- return value.map((item) => sanitizeObject(item, depth + 1));
6250
+ if (ArrayIsArray2(value)) {
6251
+ return mapArraySafely(value, (item) => sanitizeObject(item, depth + 1));
6105
6252
  }
6106
6253
  const result = /* @__PURE__ */ Object.create(null);
6107
6254
  for (const key of Object.keys(value)) {
@@ -6111,11 +6258,16 @@ function sanitizeObject(value, depth = 0) {
6111
6258
  }
6112
6259
  return result;
6113
6260
  }
6114
- var DANGEROUS_KEYS2, MAX_DEPTH;
6261
+ var ReflectGet3, ArrayIsArray2, NumberIsFinite3, MathFloor3, MAX_ARRAY_LENGTH, DANGEROUS_KEYS2, MAX_DEPTH;
6115
6262
  var init_safe_deserialize = __esm({
6116
6263
  "libs/core/src/adapters/worker-pool/safe-deserialize.ts"() {
6117
6264
  "use strict";
6118
6265
  init_errors();
6266
+ ReflectGet3 = Reflect.get;
6267
+ ArrayIsArray2 = Array.isArray;
6268
+ NumberIsFinite3 = Number.isFinite;
6269
+ MathFloor3 = Math.floor;
6270
+ MAX_ARRAY_LENGTH = 1e6;
6119
6271
  DANGEROUS_KEYS2 = /* @__PURE__ */ new Set(["__proto__", "constructor", "prototype"]);
6120
6272
  MAX_DEPTH = 50;
6121
6273
  }
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "@enclave-vm/core",
3
- "version": "2.14.1",
3
+ "version": "2.15.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,8 +44,8 @@
44
44
  },
45
45
  "dependencies": {
46
46
  "@babel/standalone": "^7.29.0",
47
- "@enclave-vm/ast": "2.14.1",
48
- "@enclave-vm/types": "2.14.1",
47
+ "@enclave-vm/ast": "2.15.0",
48
+ "@enclave-vm/types": "2.15.0",
49
49
  "@types/estree": "1.0.8",
50
50
  "acorn": "8.15.0",
51
51
  "acorn-walk": "8.3.4",
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "@enclave-vm/core",
3
- "version": "2.14.1",
3
+ "version": "2.15.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,8 +46,8 @@
46
46
  },
47
47
  "dependencies": {
48
48
  "@babel/standalone": "^7.29.0",
49
- "@enclave-vm/ast": "2.14.1",
50
- "@enclave-vm/types": "2.14.1",
49
+ "@enclave-vm/ast": "2.15.0",
50
+ "@enclave-vm/types": "2.15.0",
51
51
  "@types/estree": "1.0.8",
52
52
  "acorn": "8.15.0",
53
53
  "acorn-walk": "8.3.4",
@@ -57,6 +57,29 @@ var MessageSizeError = class extends WorkerPoolError {
57
57
  };
58
58
 
59
59
  // libs/core/src/adapters/worker-pool/safe-deserialize.ts
60
+ var ReflectGet = Reflect.get;
61
+ var ArrayIsArray = Array.isArray;
62
+ var NumberIsFinite = Number.isFinite;
63
+ var MathFloor = Math.floor;
64
+ var MAX_ARRAY_LENGTH = 1e6;
65
+ function mapArraySafely(value, sanitizeItem) {
66
+ const rawLen = ReflectGet(value, "length");
67
+ const len = typeof rawLen === "number" && NumberIsFinite(rawLen) && rawLen >= 0 ? MathFloor(rawLen) : 0;
68
+ if (len > MAX_ARRAY_LENGTH) {
69
+ throw new MessageValidationError(`Array exceeds maximum length of ${MAX_ARRAY_LENGTH}`);
70
+ }
71
+ const out = [];
72
+ for (let i = 0; i < len; i++) {
73
+ let item;
74
+ try {
75
+ item = ReflectGet(value, i);
76
+ } catch {
77
+ item = void 0;
78
+ }
79
+ out[i] = sanitizeItem(item);
80
+ }
81
+ return out;
82
+ }
60
83
  var DANGEROUS_KEYS = /* @__PURE__ */ new Set(["__proto__", "constructor", "prototype"]);
61
84
  var MAX_DEPTH = 50;
62
85
  function safeDeserialize(raw, maxSizeBytes) {
@@ -86,8 +109,8 @@ function sanitizeObjectWithDepthCheck(value, depth) {
86
109
  if (typeof value !== "object") {
87
110
  return value;
88
111
  }
89
- if (Array.isArray(value)) {
90
- return value.map((item) => sanitizeObjectWithDepthCheck(item, depth + 1));
112
+ if (ArrayIsArray(value)) {
113
+ return mapArraySafely(value, (item) => sanitizeObjectWithDepthCheck(item, depth + 1));
91
114
  }
92
115
  const result = /* @__PURE__ */ Object.create(null);
93
116
  for (const key of Object.keys(value)) {
@@ -115,8 +138,8 @@ function sanitizeObject(value, depth = 0) {
115
138
  if (typeof value !== "object") {
116
139
  return value;
117
140
  }
118
- if (Array.isArray(value)) {
119
- return value.map((item) => sanitizeObject(item, depth + 1));
141
+ if (ArrayIsArray(value)) {
142
+ return mapArraySafely(value, (item) => sanitizeObject(item, depth + 1));
120
143
  }
121
144
  const result = /* @__PURE__ */ Object.create(null);
122
145
  for (const key of Object.keys(value)) {