@enclave-vm/core 2.14.0 → 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
  }