@enclave-vm/core 2.14.1 → 2.15.1

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/index.js CHANGED
@@ -30,6 +30,556 @@ var __toESM = (mod, isNodeMode, target) => (target = mod != null ? __create(__ge
30
30
  ));
31
31
  var __toCommonJS = (mod) => __copyProps(__defProp({}, "__esModule", { value: true }), mod);
32
32
 
33
+ // libs/core/src/safe-error.ts
34
+ function createSafeError(message, name = "Error") {
35
+ const error = new Error(message);
36
+ error.name = name;
37
+ const SafeConstructor = /* @__PURE__ */ Object.create(null);
38
+ Object.defineProperties(SafeConstructor, {
39
+ constructor: {
40
+ value: SafeConstructor,
41
+ writable: false,
42
+ enumerable: false,
43
+ configurable: false
44
+ },
45
+ prototype: {
46
+ value: null,
47
+ writable: false,
48
+ enumerable: false,
49
+ configurable: false
50
+ },
51
+ name: {
52
+ value: "SafeError",
53
+ writable: false,
54
+ enumerable: false,
55
+ configurable: false
56
+ }
57
+ });
58
+ Object.freeze(SafeConstructor);
59
+ Object.setPrototypeOf(error, null);
60
+ Object.defineProperty(error, "constructor", {
61
+ value: SafeConstructor,
62
+ writable: false,
63
+ enumerable: false,
64
+ configurable: false
65
+ });
66
+ Object.defineProperty(error, "__proto__", {
67
+ value: null,
68
+ writable: false,
69
+ enumerable: false,
70
+ configurable: false
71
+ });
72
+ Object.defineProperty(error, "stack", {
73
+ value: void 0,
74
+ writable: false,
75
+ enumerable: false,
76
+ configurable: false
77
+ });
78
+ Object.freeze(error);
79
+ return error;
80
+ }
81
+ function createSafeTypeError(message) {
82
+ return createSafeError(message, "TypeError");
83
+ }
84
+ var init_safe_error = __esm({
85
+ "libs/core/src/safe-error.ts"() {
86
+ "use strict";
87
+ }
88
+ });
89
+
90
+ // libs/core/src/secure-proxy.ts
91
+ function getBlockedPropertiesForLevel(level) {
92
+ const blocked = /* @__PURE__ */ new Set();
93
+ if (level !== "PERMISSIVE") {
94
+ BLOCKED_PROPERTY_CATEGORIES.PROTOTYPE.forEach((p) => blocked.add(p));
95
+ }
96
+ switch (level) {
97
+ case "STRICT":
98
+ BLOCKED_PROPERTY_CATEGORIES.ITERATOR_HELPERS.forEach((p) => blocked.add(p));
99
+ BLOCKED_PROPERTY_CATEGORIES.REFLECTION.forEach((p) => blocked.add(p));
100
+ BLOCKED_PROPERTY_CATEGORIES.TIMING.forEach((p) => blocked.add(p));
101
+ break;
102
+ case "SECURE":
103
+ BLOCKED_PROPERTY_CATEGORIES.ITERATOR_HELPERS.forEach((p) => blocked.add(p));
104
+ break;
105
+ case "STANDARD":
106
+ case "PERMISSIVE":
107
+ break;
108
+ }
109
+ return blocked;
110
+ }
111
+ function buildBlockedPropertiesFromConfig(config) {
112
+ const blocked = /* @__PURE__ */ new Set();
113
+ if (config.blockConstructor) {
114
+ blocked.add("constructor");
115
+ }
116
+ if (config.blockPrototype) {
117
+ blocked.add("__proto__");
118
+ blocked.add("prototype");
119
+ }
120
+ if (config.blockLegacyAccessors) {
121
+ blocked.add("__defineGetter__");
122
+ blocked.add("__defineSetter__");
123
+ blocked.add("__lookupGetter__");
124
+ blocked.add("__lookupSetter__");
125
+ }
126
+ return blocked;
127
+ }
128
+ function createSafeReflect(securityLevel) {
129
+ if (securityLevel === "STRICT") {
130
+ return void 0;
131
+ }
132
+ const dangerousMethods = /* @__PURE__ */ new Set(["setPrototypeOf"]);
133
+ if (securityLevel === "SECURE") {
134
+ dangerousMethods.add("apply");
135
+ dangerousMethods.add("defineProperty");
136
+ }
137
+ return new Proxy(Reflect, {
138
+ get(target, prop) {
139
+ if (typeof prop === "string" && dangerousMethods.has(prop)) {
140
+ return void 0;
141
+ }
142
+ const value = Reflect.get(target, prop);
143
+ if (typeof value === "function" && prop === "construct") {
144
+ const safeConstruct = function(ctorTarget, args, newTarget) {
145
+ const AsyncFunction = async function() {
146
+ }.constructor;
147
+ const GeneratorFunction = function* () {
148
+ }.constructor;
149
+ const AsyncGeneratorFunction = async function* () {
150
+ }.constructor;
151
+ if (ctorTarget === Function || ctorTarget === AsyncFunction || ctorTarget === GeneratorFunction || ctorTarget === AsyncGeneratorFunction) {
152
+ throw createSafeError("Reflect.construct with function constructors is blocked", "SecurityError");
153
+ }
154
+ return Reflect.construct(
155
+ ctorTarget,
156
+ args,
157
+ newTarget
158
+ );
159
+ };
160
+ return createSecureProxy(safeConstruct);
161
+ }
162
+ if (typeof value === "function") {
163
+ return createSecureProxy(value);
164
+ }
165
+ return value;
166
+ }
167
+ });
168
+ }
169
+ function getFullCacheKey(options) {
170
+ const parts = [];
171
+ if (options.levelConfig) {
172
+ const cfg = options.levelConfig;
173
+ parts.push(
174
+ `L:${cfg.blockConstructor ? "C" : "c"}${cfg.blockPrototype ? "P" : "p"}${cfg.blockLegacyAccessors ? "L" : "l"}`
175
+ );
176
+ } else {
177
+ parts.push("L:default");
178
+ }
179
+ if (options.additionalBlocked && options.additionalBlocked.length > 0) {
180
+ parts.push(`B:${[...options.additionalBlocked].sort().join(",")}`);
181
+ }
182
+ const effectiveMaxDepth = options.maxDepth ?? options.levelConfig?.proxyMaxDepth ?? 10;
183
+ if (effectiveMaxDepth !== 10) {
184
+ parts.push(`D:${effectiveMaxDepth}`);
185
+ }
186
+ if (options.throwOnBlocked) {
187
+ parts.push("T:1");
188
+ }
189
+ return parts.join("|") || "default";
190
+ }
191
+ function isProxyable(value) {
192
+ if (value === null) return false;
193
+ if (typeof value !== "object" && typeof value !== "function") return false;
194
+ const tag = Object.prototype.toString.call(value);
195
+ if (NON_PROXYABLE_TYPES.has(tag)) {
196
+ return false;
197
+ }
198
+ return true;
199
+ }
200
+ function createSecureProxy(target, options = {}) {
201
+ if (!isProxyable(target)) {
202
+ return target;
203
+ }
204
+ const cacheKey = getFullCacheKey(options);
205
+ const targetCache = proxyCache.get(target);
206
+ if (targetCache) {
207
+ const cached = targetCache.get(cacheKey);
208
+ if (cached) {
209
+ return cached;
210
+ }
211
+ }
212
+ const baseBlocked = options.levelConfig ? buildBlockedPropertiesFromConfig(options.levelConfig) : new Set(BLOCKED_PROPERTIES);
213
+ const blockedSet = /* @__PURE__ */ new Set([...baseBlocked, ...options.additionalBlocked || []]);
214
+ const configuredMaxDepth = options.maxDepth ?? options.levelConfig?.proxyMaxDepth ?? 10;
215
+ const maxDepth = Number.isFinite(configuredMaxDepth) ? Math.max(configuredMaxDepth, MIN_MEMBRANE_RECURSION_DEPTH) : MIN_MEMBRANE_RECURSION_DEPTH;
216
+ const throwOnBlocked = options.throwOnBlocked ?? options.levelConfig?.throwOnBlocked ?? false;
217
+ function proxyWithDepth(obj, depth) {
218
+ if (!isProxyable(obj)) {
219
+ return obj;
220
+ }
221
+ const objCache = proxyCache.get(obj);
222
+ if (objCache) {
223
+ const cachedProxy = objCache.get(cacheKey);
224
+ if (cachedProxy) {
225
+ return cachedProxy;
226
+ }
227
+ }
228
+ if (depth > maxDepth) {
229
+ throw createSafeError(
230
+ `Security violation: secure-proxy recursion depth (${maxDepth}) exceeded. The value cannot be exposed without breaking the sandbox barrier.`,
231
+ "SecurityError"
232
+ );
233
+ }
234
+ const proxy = new Proxy(obj, {
235
+ get(target2, property, receiver) {
236
+ const propName = typeof property === "symbol" ? property.toString() : property;
237
+ const descriptor = Object.getOwnPropertyDescriptor(target2, property);
238
+ if (descriptor && !descriptor.configurable && descriptor.writable === false && "value" in descriptor) {
239
+ const exactValue = descriptor.value;
240
+ if (exactValue !== null && (typeof exactValue === "object" || typeof exactValue === "function")) {
241
+ throw createSafeError(
242
+ `Security violation: Access to '${String(propName)}' is blocked. This property cannot be exposed without breaking the sandbox barrier.`,
243
+ "SecurityError"
244
+ );
245
+ }
246
+ return exactValue;
247
+ }
248
+ if (typeof propName === "string" && blockedSet.has(propName)) {
249
+ if (options.onBlocked) {
250
+ options.onBlocked(target2, propName);
251
+ }
252
+ if (throwOnBlocked) {
253
+ throw createSafeError(
254
+ `Security violation: Access to '${propName}' is blocked. This property can be used for sandbox escape attacks.`,
255
+ "SecurityError"
256
+ );
257
+ }
258
+ return void 0;
259
+ }
260
+ if (typeof target2 === "function" && typeof propName === "string" && FUNCTION_BLOCKED_PROPERTIES.has(propName)) {
261
+ if (options.onBlocked) {
262
+ options.onBlocked(target2, propName);
263
+ }
264
+ if (throwOnBlocked) {
265
+ throw createSafeError(
266
+ `Security violation: Access to '${propName}' is blocked. This property can be used for sandbox escape attacks.`,
267
+ "SecurityError"
268
+ );
269
+ }
270
+ return void 0;
271
+ }
272
+ const value = Reflect.get(target2, property, receiver);
273
+ if (typeof value === "function") {
274
+ const tag = Object.prototype.toString.call(target2);
275
+ if (INTERNAL_SLOT_TYPES.has(tag)) {
276
+ const boundMethod = value.bind(target2);
277
+ return proxyWithDepth(boundMethod, depth + 1);
278
+ }
279
+ }
280
+ if (value !== null && (typeof value === "object" || typeof value === "function")) {
281
+ return proxyWithDepth(value, depth + 1);
282
+ }
283
+ return value;
284
+ },
285
+ // Block setting dangerous properties
286
+ set(target2, property, value, receiver) {
287
+ const propName = typeof property === "symbol" ? property.toString() : property;
288
+ if (typeof propName === "string" && blockedSet.has(propName)) {
289
+ if (options.onBlocked) {
290
+ options.onBlocked(target2, propName);
291
+ }
292
+ if (throwOnBlocked) {
293
+ throw createSafeError(
294
+ `Security violation: Setting '${propName}' is blocked. This property can be used for sandbox escape attacks.`,
295
+ "SecurityError"
296
+ );
297
+ }
298
+ return false;
299
+ }
300
+ return Reflect.set(target2, property, value, receiver);
301
+ },
302
+ // Block defining dangerous properties
303
+ defineProperty(target2, property, descriptor) {
304
+ const propName = typeof property === "symbol" ? property.toString() : property;
305
+ if (typeof propName === "string" && blockedSet.has(propName)) {
306
+ if (options.onBlocked) {
307
+ options.onBlocked(target2, propName);
308
+ }
309
+ if (throwOnBlocked) {
310
+ throw createSafeError(
311
+ `Security violation: Defining '${propName}' is blocked. This property can be used for sandbox escape attacks.`,
312
+ "SecurityError"
313
+ );
314
+ }
315
+ return false;
316
+ }
317
+ return Reflect.defineProperty(target2, property, descriptor);
318
+ },
319
+ // Filter blocked property names from enumeration (Object.keys, Object.entries, etc.)
320
+ // Must respect proxy invariants: non-configurable own properties cannot be hidden
321
+ ownKeys(target2) {
322
+ const keys = Reflect.ownKeys(target2);
323
+ return keys.filter((key) => {
324
+ const keyStr = typeof key === "symbol" ? key.toString() : key;
325
+ if (typeof keyStr !== "string" || !blockedSet.has(keyStr)) {
326
+ return true;
327
+ }
328
+ const descriptor = Object.getOwnPropertyDescriptor(target2, key);
329
+ if (descriptor && !descriptor.configurable) {
330
+ return true;
331
+ }
332
+ return false;
333
+ });
334
+ },
335
+ // Hide blocked properties from property descriptor queries (defense-in-depth)
336
+ // Must respect proxy invariants: non-configurable properties must return actual descriptor
337
+ getOwnPropertyDescriptor(target2, property) {
338
+ const propName = typeof property === "symbol" ? property.toString() : property;
339
+ const descriptor = Reflect.getOwnPropertyDescriptor(target2, property);
340
+ if (descriptor && !descriptor.configurable && descriptor.writable === false && "value" in descriptor) {
341
+ const exactValue = descriptor.value;
342
+ if (exactValue !== null && (typeof exactValue === "object" || typeof exactValue === "function")) {
343
+ throw createSafeError(
344
+ `Security violation: Access to property descriptor for '${String(propName)}' is blocked. This property cannot be exposed without breaking the sandbox barrier.`,
345
+ "SecurityError"
346
+ );
347
+ }
348
+ return descriptor;
349
+ }
350
+ if (descriptor && !descriptor.configurable && (typeof descriptor.get === "function" || typeof descriptor.set === "function")) {
351
+ throw createSafeError(
352
+ `Security violation: Access to property descriptor for '${String(propName)}' is blocked. This property cannot be exposed without breaking the sandbox barrier.`,
353
+ "SecurityError"
354
+ );
355
+ }
356
+ if (descriptor && !descriptor.configurable) {
357
+ return descriptor;
358
+ }
359
+ if (typeof propName === "string" && blockedSet.has(propName)) {
360
+ if (options.onBlocked) {
361
+ options.onBlocked(target2, propName);
362
+ }
363
+ if (throwOnBlocked) {
364
+ throw createSafeError(
365
+ `Security violation: Access to property descriptor for '${propName}' is blocked. This property can be used for sandbox escape attacks.`,
366
+ "SecurityError"
367
+ );
368
+ }
369
+ return void 0;
370
+ }
371
+ if (descriptor && (typeof descriptor.get === "function" || typeof descriptor.set === "function")) {
372
+ return {
373
+ ...descriptor,
374
+ get: typeof descriptor.get === "function" ? proxyWithDepth(descriptor.get, depth + 1) : descriptor.get,
375
+ set: typeof descriptor.set === "function" ? proxyWithDepth(descriptor.set, depth + 1) : descriptor.set
376
+ };
377
+ }
378
+ if (descriptor && "value" in descriptor) {
379
+ const value = descriptor.value;
380
+ if (value !== null && (typeof value === "object" || typeof value === "function")) {
381
+ return { ...descriptor, value: proxyWithDepth(value, depth + 1) };
382
+ }
383
+ }
384
+ return descriptor;
385
+ },
386
+ // Block getPrototypeOf to prevent prototype chain walking
387
+ getPrototypeOf() {
388
+ return null;
389
+ },
390
+ // Block setPrototypeOf
391
+ setPrototypeOf() {
392
+ return false;
393
+ },
394
+ // Intercept function calls to proxy return values
395
+ // eslint-disable-next-line @typescript-eslint/no-explicit-any -- Proxy handler signature requires any for compatibility
396
+ apply(target2, thisArg, argArray) {
397
+ const unwrappedThis = thisArg !== null && (typeof thisArg === "object" || typeof thisArg === "function") && proxyToTarget.has(thisArg) ? proxyToTarget.get(thisArg) : thisArg;
398
+ const result = Reflect.apply(target2, unwrappedThis, argArray);
399
+ if (isProxyable(result)) {
400
+ return proxyWithDepth(result, depth + 1);
401
+ }
402
+ return result;
403
+ },
404
+ // Intercept constructor calls to proxy the created instance. Without this, code such as
405
+ // `new (wrappedCtor)()` would return a RAW object whose prototype chain reaches the
406
+ // host Function constructor — the same escape class the apply trap closes for calls.
407
+ // eslint-disable-next-line @typescript-eslint/no-explicit-any -- Proxy handler signature requires any for compatibility
408
+ construct(target2, argArray, newTarget) {
409
+ const instance = Reflect.construct(target2, argArray, newTarget === proxy ? target2 : newTarget);
410
+ if (isProxyable(instance)) {
411
+ return proxyWithDepth(instance, depth + 1);
412
+ }
413
+ return instance;
414
+ }
415
+ });
416
+ let objCacheMap = proxyCache.get(obj);
417
+ if (!objCacheMap) {
418
+ objCacheMap = /* @__PURE__ */ new Map();
419
+ proxyCache.set(obj, objCacheMap);
420
+ }
421
+ objCacheMap.set(cacheKey, proxy);
422
+ proxySet.add(proxy);
423
+ proxyToTarget.set(proxy, obj);
424
+ return proxy;
425
+ }
426
+ return proxyWithDepth(target, 0);
427
+ }
428
+ function wrapGlobalsWithSecureProxy(globals, options = {}) {
429
+ const wrapped = {};
430
+ for (const [key, value] of Object.entries(globals)) {
431
+ if (value !== null && (typeof value === "object" || typeof value === "function")) {
432
+ wrapped[key] = createSecureProxy(value, options);
433
+ } else {
434
+ wrapped[key] = value;
435
+ }
436
+ }
437
+ return wrapped;
438
+ }
439
+ function createSecureStandardLibrary(options = {}) {
440
+ return wrapGlobalsWithSecureProxy(
441
+ {
442
+ Math,
443
+ JSON,
444
+ Array,
445
+ Object,
446
+ String,
447
+ Number,
448
+ Date
449
+ // Note: We intentionally don't include:
450
+ // - Function (dangerous)
451
+ // - eval (dangerous)
452
+ // - Proxy, Reflect (meta-programming)
453
+ },
454
+ options
455
+ );
456
+ }
457
+ function isSecureProxy(obj) {
458
+ if (obj === null || typeof obj !== "object") {
459
+ return false;
460
+ }
461
+ return proxySet.has(obj);
462
+ }
463
+ var MIN_MEMBRANE_RECURSION_DEPTH, BLOCKED_PROPERTY_CATEGORIES, BLOCKED_PROPERTIES, DEFAULT_SECURE_PROXY_CONFIG, FUNCTION_BLOCKED_PROPERTIES, proxyCache, proxySet, proxyToTarget, NON_PROXYABLE_TYPES, INTERNAL_SLOT_TYPES;
464
+ var init_secure_proxy = __esm({
465
+ "libs/core/src/secure-proxy.ts"() {
466
+ "use strict";
467
+ init_safe_error();
468
+ MIN_MEMBRANE_RECURSION_DEPTH = 256;
469
+ BLOCKED_PROPERTY_CATEGORIES = {
470
+ /**
471
+ * Core prototype manipulation properties (always blocked except PERMISSIVE)
472
+ */
473
+ PROTOTYPE: /* @__PURE__ */ new Set([
474
+ "constructor",
475
+ "__proto__",
476
+ "prototype",
477
+ "__defineGetter__",
478
+ "__defineSetter__",
479
+ "__lookupGetter__",
480
+ "__lookupSetter__"
481
+ ]),
482
+ /**
483
+ * Node.js 24 Iterator helper method names
484
+ * Blocked at STRICT/SECURE to prevent prototype chain access via iterators
485
+ */
486
+ ITERATOR_HELPERS: /* @__PURE__ */ new Set(["toArray", "forEach", "some", "every", "find", "reduce", "flatMap", "drop", "take"]),
487
+ /**
488
+ * Reflection properties on Object
489
+ * Blocked at STRICT to prevent introspection attacks
490
+ */
491
+ REFLECTION: /* @__PURE__ */ new Set([
492
+ "getOwnPropertyDescriptor",
493
+ "getOwnPropertyDescriptors",
494
+ "getOwnPropertyNames",
495
+ "getOwnPropertySymbols",
496
+ "getPrototypeOf",
497
+ "setPrototypeOf",
498
+ "defineProperty",
499
+ "defineProperties",
500
+ "preventExtensions",
501
+ "isExtensible",
502
+ "seal",
503
+ "isSealed",
504
+ "freeze",
505
+ "isFrozen"
506
+ ]),
507
+ /**
508
+ * Timing API properties
509
+ * Blocked at STRICT to prevent timing attacks
510
+ */
511
+ TIMING: /* @__PURE__ */ new Set(["hrtime", "timeOrigin"])
512
+ };
513
+ BLOCKED_PROPERTIES = /* @__PURE__ */ new Set([
514
+ // Code execution
515
+ "constructor",
516
+ // Prototype manipulation
517
+ "__proto__",
518
+ "prototype",
519
+ // Legacy getter/setter definition
520
+ "__defineGetter__",
521
+ "__defineSetter__",
522
+ "__lookupGetter__",
523
+ "__lookupSetter__"
524
+ ]);
525
+ DEFAULT_SECURE_PROXY_CONFIG = {
526
+ blockConstructor: true,
527
+ blockPrototype: true,
528
+ blockLegacyAccessors: true,
529
+ proxyMaxDepth: 10,
530
+ throwOnBlocked: true
531
+ };
532
+ FUNCTION_BLOCKED_PROPERTIES = /* @__PURE__ */ new Set([
533
+ // Function object properties that could leak information
534
+ "caller",
535
+ // Deprecated but still exists
536
+ "arguments"
537
+ // Deprecated but still exists
538
+ // Binding/applying could be used for exploitation
539
+ // Note: We may want to allow these in some cases
540
+ // 'bind',
541
+ // 'call',
542
+ // 'apply',
543
+ ]);
544
+ proxyCache = /* @__PURE__ */ new WeakMap();
545
+ proxySet = /* @__PURE__ */ new WeakSet();
546
+ proxyToTarget = /* @__PURE__ */ new WeakMap();
547
+ NON_PROXYABLE_TYPES = /* @__PURE__ */ new Set([
548
+ // Map/Set have internal slots but we may need to proxy them in the future
549
+ "[object Map]",
550
+ "[object Set]",
551
+ "[object WeakMap]",
552
+ "[object WeakSet]",
553
+ "[object ArrayBuffer]",
554
+ "[object SharedArrayBuffer]",
555
+ "[object DataView]",
556
+ "[object Int8Array]",
557
+ "[object Uint8Array]",
558
+ "[object Uint8ClampedArray]",
559
+ "[object Int16Array]",
560
+ "[object Uint16Array]",
561
+ "[object Int32Array]",
562
+ "[object Uint32Array]",
563
+ "[object Float32Array]",
564
+ "[object Float64Array]",
565
+ "[object BigInt64Array]",
566
+ "[object BigUint64Array]",
567
+ // Generators and iterators use internal slots
568
+ "[object Generator]",
569
+ "[object AsyncGenerator]",
570
+ "[object GeneratorFunction]",
571
+ "[object AsyncGeneratorFunction]",
572
+ // Built-in iterators
573
+ "[object Array Iterator]",
574
+ "[object String Iterator]",
575
+ "[object Map Iterator]",
576
+ "[object Set Iterator]",
577
+ "[object RegExp String Iterator]"
578
+ ]);
579
+ INTERNAL_SLOT_TYPES = /* @__PURE__ */ new Set(["[object Promise]"]);
580
+ }
581
+ });
582
+
33
583
  // libs/core/src/sidecar/reference-config.ts
34
584
  function isReferenceId(value) {
35
585
  return typeof value === "string" && REF_ID_PATTERN.test(value);
@@ -145,15 +695,42 @@ var init_reference_config = __esm({
145
695
  });
146
696
 
147
697
  // libs/core/src/sidecar/reference-resolver.ts
698
+ function untrustedLength(value) {
699
+ const rawLen = ReflectGet(value, "length");
700
+ if (typeof rawLen !== "number" || !NumberIsFinite(rawLen) || rawLen < 0) {
701
+ return 0;
702
+ }
703
+ const len = MathFloor(rawLen);
704
+ if (len > MAX_TRAVERSAL_LENGTH) {
705
+ throw new ResolutionLimitError(
706
+ `Array length ${len} exceeds maximum traversal limit (${MAX_TRAVERSAL_LENGTH})`,
707
+ "MAX_TRAVERSAL_LENGTH",
708
+ MAX_TRAVERSAL_LENGTH,
709
+ len
710
+ );
711
+ }
712
+ return len;
713
+ }
714
+ function untrustedAt(value, index) {
715
+ try {
716
+ return ReflectGet(value, index);
717
+ } catch {
718
+ return void 0;
719
+ }
720
+ }
148
721
  function isCompositeHandle(value) {
149
722
  const obj = value;
150
723
  return typeof value === "object" && value !== null && obj["__type"] === "composite" && Array.isArray(obj["__parts"]);
151
724
  }
152
- var ResolutionLimitError, ReferenceResolver;
725
+ var ReflectGet, NumberIsFinite, MathFloor, MAX_TRAVERSAL_LENGTH, ResolutionLimitError, ReferenceResolver;
153
726
  var init_reference_resolver = __esm({
154
727
  "libs/core/src/sidecar/reference-resolver.ts"() {
155
728
  "use strict";
156
729
  init_reference_config();
730
+ ReflectGet = Reflect.get;
731
+ NumberIsFinite = Number.isFinite;
732
+ MathFloor = Math.floor;
733
+ MAX_TRAVERSAL_LENGTH = 1e6;
157
734
  ResolutionLimitError = class _ResolutionLimitError extends Error {
158
735
  constructor(message, code, limit, actual) {
159
736
  super(message);
@@ -197,17 +774,24 @@ var init_reference_resolver = __esm({
197
774
  return size;
198
775
  }
199
776
  if (isCompositeHandle(value)) {
200
- return value.__parts.reduce((sum, part) => {
201
- return sum + this.predictExpandedSize(part, depth + 1);
202
- }, 0);
777
+ const parts = value.__parts;
778
+ const len = untrustedLength(parts);
779
+ let sum = 0;
780
+ for (let i = 0; i < len; i++) {
781
+ sum += this.predictExpandedSize(untrustedAt(parts, i), depth + 1);
782
+ }
783
+ return sum;
203
784
  }
204
785
  if (typeof value === "string") {
205
786
  return Buffer.byteLength(value, "utf-8");
206
787
  }
207
788
  if (Array.isArray(value)) {
208
- return value.reduce((sum, item) => {
209
- return sum + this.predictExpandedSize(item, depth + 1);
210
- }, 0);
789
+ const len = untrustedLength(value);
790
+ let sum = 0;
791
+ for (let i = 0; i < len; i++) {
792
+ sum += this.predictExpandedSize(untrustedAt(value, i), depth + 1);
793
+ }
794
+ return sum;
211
795
  }
212
796
  if (value !== null && typeof value === "object") {
213
797
  return Object.values(value).reduce((sum, val) => {
@@ -268,7 +852,12 @@ var init_reference_resolver = __esm({
268
852
  return value;
269
853
  }
270
854
  if (Array.isArray(value)) {
271
- return value.map((item) => this.resolve(item, depth + 1));
855
+ const len = untrustedLength(value);
856
+ const out = [];
857
+ for (let i = 0; i < len; i++) {
858
+ out[i] = this.resolve(untrustedAt(value, i), depth + 1);
859
+ }
860
+ return out;
272
861
  }
273
862
  if (value !== null && typeof value === "object") {
274
863
  const resolved = /* @__PURE__ */ Object.create(null);
@@ -283,15 +872,17 @@ var init_reference_resolver = __esm({
283
872
  * Resolve a composite handle by concatenating its parts
284
873
  */
285
874
  resolveComposite(handle, depth) {
286
- const parts = [];
287
- for (const part of handle.__parts) {
288
- const resolved = this.resolve(part, depth + 1);
875
+ const out = [];
876
+ const source = handle.__parts;
877
+ const len = untrustedLength(source);
878
+ for (let i = 0; i < len; i++) {
879
+ const resolved = this.resolve(untrustedAt(source, i), depth + 1);
289
880
  if (typeof resolved !== "string") {
290
881
  throw new Error(`Composite part resolved to non-string: ${typeof resolved}`);
291
882
  }
292
- parts.push(resolved);
883
+ out.push(resolved);
293
884
  }
294
- return parts.join("");
885
+ return out.join("");
295
886
  }
296
887
  /**
297
888
  * Check if a value contains any reference IDs
@@ -308,7 +899,13 @@ var init_reference_resolver = __esm({
308
899
  return true;
309
900
  }
310
901
  if (Array.isArray(value)) {
311
- return value.some((item) => this.containsReferences(item, depth + 1));
902
+ const len = untrustedLength(value);
903
+ for (let i = 0; i < len; i++) {
904
+ if (this.containsReferences(untrustedAt(value, i), depth + 1)) {
905
+ return true;
906
+ }
907
+ }
908
+ return false;
312
909
  }
313
910
  if (value !== null && typeof value === "object") {
314
911
  return Object.values(value).some((val) => this.containsReferences(val, depth + 1));
@@ -401,35 +998,53 @@ function sanitizeValue(value, options = {}, depth = 0, context = { propCount: {
401
998
  }
402
999
  context.visited.add(value);
403
1000
  }
404
- if (Array.isArray(value)) {
405
- context.propCount.count += value.length;
1001
+ if (ArrayIsArray(value)) {
1002
+ const rawLen = ReflectGet2(value, "length");
1003
+ const len = typeof rawLen === "number" && NumberIsFinite2(rawLen) && rawLen >= 0 ? MathFloor2(rawLen) : 0;
1004
+ context.propCount.count += len;
406
1005
  if (context.propCount.count > maxProperties) {
407
1006
  throw new Error(`Tool handler return value exceeds maximum properties (${maxProperties}).`);
408
1007
  }
409
- return value.map((item) => sanitizeValue(item, options, depth + 1, context));
1008
+ const result = [];
1009
+ for (let i = 0; i < len; i++) {
1010
+ let item;
1011
+ try {
1012
+ item = ReflectGet2(value, i);
1013
+ } catch {
1014
+ item = void 0;
1015
+ }
1016
+ result[i] = sanitizeValue(item, options, depth + 1, context);
1017
+ }
1018
+ return result;
410
1019
  }
411
1020
  if (value instanceof Date) {
1021
+ const time = ReflectApply(DateProtoGetTime, value, []);
412
1022
  if (allowDates) {
413
- return new Date(value.getTime());
1023
+ return new Date(time);
414
1024
  }
415
- return value.toISOString();
1025
+ return ReflectApply(DateProtoToISOString, value, []);
416
1026
  }
417
1027
  if (value instanceof Error) {
1028
+ const rawName = ReflectGet2(value, "name");
1029
+ const rawMessage = ReflectGet2(value, "message");
1030
+ const name = typeof rawName === "string" ? rawName : "Error";
1031
+ const message = typeof rawMessage === "string" ? rawMessage : "";
418
1032
  if (allowErrors) {
419
1033
  return {
420
- name: value.name,
421
- message: value.message
1034
+ name,
1035
+ message
422
1036
  // Do NOT include stack trace - could leak host information
423
1037
  };
424
1038
  }
425
- return { error: value.message };
1039
+ return { error: message };
426
1040
  }
427
1041
  if (value instanceof RegExp) {
428
- return value.toString();
1042
+ return ReflectApply(RegExpProtoToString, value, []);
429
1043
  }
430
1044
  if (value instanceof Map) {
431
- const sanitizedMap = /* @__PURE__ */ Object.create(null);
432
- for (const [key, val] of value.entries()) {
1045
+ const sanitizedMap = ObjectCreate(null);
1046
+ const entries = ReflectApply(MapProtoEntries, value, []);
1047
+ for (const [key, val] of entries) {
433
1048
  if (typeof key !== "string") continue;
434
1049
  if (DANGEROUS_KEYS.has(key)) continue;
435
1050
  context.propCount.count++;
@@ -438,13 +1053,17 @@ function sanitizeValue(value, options = {}, depth = 0, context = { propCount: {
438
1053
  return sanitizedMap;
439
1054
  }
440
1055
  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));
1056
+ const iter = ReflectApply(SetProtoValues, value, []);
1057
+ const result = [];
1058
+ for (const item of iter) {
1059
+ context.propCount.count++;
1060
+ result.push(sanitizeValue(item, options, depth + 1, context));
1061
+ }
1062
+ return result;
444
1063
  }
445
1064
  if (type === "object") {
446
- const sanitized = /* @__PURE__ */ Object.create(null);
447
- const keys = Object.keys(value);
1065
+ const sanitized = ObjectCreate(null);
1066
+ const keys = ObjectKeys(value);
448
1067
  context.propCount.count += keys.length;
449
1068
  if (context.propCount.count > maxProperties) {
450
1069
  throw new Error(`Tool handler return value exceeds maximum properties (${maxProperties}).`);
@@ -455,644 +1074,161 @@ function sanitizeValue(value, options = {}, depth = 0, context = { propCount: {
455
1074
  }
456
1075
  let propValue;
457
1076
  try {
458
- propValue = value[key];
1077
+ propValue = ReflectGet2(value, key);
459
1078
  } catch {
460
1079
  continue;
461
1080
  }
462
1081
  sanitized[key] = sanitizeValue(propValue, options, depth + 1, context);
463
1082
  }
464
- return sanitized;
465
- }
466
- return String(value);
467
- }
468
- function estimateStringSize(str) {
469
- let bytes = 2;
470
- for (let i = 0; i < str.length; i++) {
471
- const code = str.charCodeAt(i);
472
- if (code < 128) {
473
- if (code === 34 || code === 92) {
474
- bytes += 2;
475
- } else if (code < 32) {
476
- bytes += 6;
477
- } else {
478
- bytes += 1;
479
- }
480
- } else if (code < 2048) {
481
- bytes += 2;
482
- } else if (code >= 55296 && code <= 56319 && i + 1 < str.length) {
483
- const nextCode = str.charCodeAt(i + 1);
484
- if (nextCode >= 56320 && nextCode <= 57343) {
485
- bytes += 4;
486
- i++;
487
- } else {
488
- bytes += 3;
489
- }
490
- } else {
491
- bytes += 3;
492
- }
493
- }
494
- return bytes;
495
- }
496
- function estimateSerializedSize(value, maxBytes = 0, depth = 0, maxDepth = 2e3, currentPath = /* @__PURE__ */ new Set()) {
497
- if (depth > maxDepth) {
498
- throw new Error(
499
- `Structure exceeds maximum nesting depth (${maxDepth}). Deeply nested structures are rejected to prevent stack overflow attacks.`
500
- );
501
- }
502
- if (value === null) return 4;
503
- if (value === void 0) return 0;
504
- const type = typeof value;
505
- if (type === "string") {
506
- const bytes = estimateStringSize(value);
507
- if (maxBytes > 0 && bytes > maxBytes) {
508
- throw new Error(`String serialization would exceed limit: ${bytes} > ${maxBytes} bytes`);
509
- }
510
- return bytes;
511
- }
512
- if (type === "number") {
513
- const num = value;
514
- if (!Number.isFinite(num)) return 4;
515
- return String(num).length;
516
- }
517
- if (type === "boolean") {
518
- return value ? 4 : 5;
519
- }
520
- if (type === "bigint") {
521
- return String(value).length + 2;
522
- }
523
- if (type === "function" || type === "symbol") {
524
- return 0;
525
- }
526
- if (Array.isArray(value)) {
527
- if (currentPath.has(value)) {
528
- return 4;
529
- }
530
- currentPath.add(value);
531
- let size = 2;
532
- for (let i = 0; i < value.length; i++) {
533
- if (i > 0) size += 1;
534
- let elementSize = estimateSerializedSize(value[i], maxBytes, depth + 1, maxDepth, currentPath);
535
- if (elementSize === 0) elementSize = 4;
536
- size += elementSize;
537
- if (maxBytes > 0 && size > maxBytes) {
538
- currentPath.delete(value);
539
- throw new Error(
540
- `Array serialization would exceed limit: estimated ${size}+ > ${maxBytes} bytes. This often indicates repeated references to large strings that expand during JSON serialization.`
541
- );
542
- }
543
- }
544
- currentPath.delete(value);
545
- return size;
546
- }
547
- if (type === "object" && value !== null) {
548
- if (currentPath.has(value)) {
549
- return 4;
550
- }
551
- currentPath.add(value);
552
- if (value instanceof Date) {
553
- currentPath.delete(value);
554
- return 26;
555
- }
556
- if (value instanceof RegExp) {
557
- currentPath.delete(value);
558
- return 2;
559
- }
560
- let size = 2;
561
- const keys = Object.keys(value);
562
- let first = true;
563
- for (const key of keys) {
564
- if (key === "__proto__" || key === "constructor") continue;
565
- if (!first) size += 1;
566
- first = false;
567
- size += estimateStringSize(key) + 1;
568
- let propValue;
569
- try {
570
- propValue = value[key];
571
- } catch {
572
- continue;
573
- }
574
- const valueSize = estimateSerializedSize(propValue, maxBytes, depth + 1, maxDepth, currentPath);
575
- size += valueSize;
576
- if (maxBytes > 0 && size > maxBytes) {
577
- currentPath.delete(value);
578
- throw new Error(
579
- `Object serialization would exceed limit: estimated ${size}+ > ${maxBytes} bytes. This often indicates repeated references to large strings that expand during JSON serialization.`
580
- );
581
- }
582
- }
583
- currentPath.delete(value);
584
- return size;
585
- }
586
- return 0;
587
- }
588
- function checkSerializedSize(value, maxBytes) {
589
- try {
590
- const estimatedBytes = estimateSerializedSize(value, maxBytes);
591
- return { ok: true, estimatedBytes };
592
- } catch (err) {
593
- return { ok: false, error: err instanceof Error ? err.message : "Unknown error" };
594
- }
595
- }
596
- var DANGEROUS_KEYS;
597
- var init_value_sanitizer = __esm({
598
- "libs/core/src/value-sanitizer.ts"() {
599
- "use strict";
600
- DANGEROUS_KEYS = /* @__PURE__ */ new Set(["__proto__", "constructor"]);
601
- }
602
- });
603
-
604
- // libs/core/src/safe-error.ts
605
- function createSafeError(message, name = "Error") {
606
- const error = new Error(message);
607
- error.name = name;
608
- const SafeConstructor = /* @__PURE__ */ Object.create(null);
609
- Object.defineProperties(SafeConstructor, {
610
- constructor: {
611
- value: SafeConstructor,
612
- writable: false,
613
- enumerable: false,
614
- configurable: false
615
- },
616
- prototype: {
617
- value: null,
618
- writable: false,
619
- enumerable: false,
620
- configurable: false
621
- },
622
- name: {
623
- value: "SafeError",
624
- writable: false,
625
- enumerable: false,
626
- configurable: false
627
- }
628
- });
629
- Object.freeze(SafeConstructor);
630
- Object.setPrototypeOf(error, null);
631
- Object.defineProperty(error, "constructor", {
632
- value: SafeConstructor,
633
- writable: false,
634
- enumerable: false,
635
- configurable: false
636
- });
637
- Object.defineProperty(error, "__proto__", {
638
- value: null,
639
- writable: false,
640
- enumerable: false,
641
- configurable: false
642
- });
643
- Object.defineProperty(error, "stack", {
644
- value: void 0,
645
- writable: false,
646
- enumerable: false,
647
- configurable: false
648
- });
649
- Object.freeze(error);
650
- return error;
651
- }
652
- function createSafeTypeError(message) {
653
- return createSafeError(message, "TypeError");
654
- }
655
- var init_safe_error = __esm({
656
- "libs/core/src/safe-error.ts"() {
657
- "use strict";
658
- }
659
- });
660
-
661
- // libs/core/src/secure-proxy.ts
662
- function getBlockedPropertiesForLevel(level) {
663
- const blocked = /* @__PURE__ */ new Set();
664
- if (level !== "PERMISSIVE") {
665
- BLOCKED_PROPERTY_CATEGORIES.PROTOTYPE.forEach((p) => blocked.add(p));
666
- }
667
- switch (level) {
668
- case "STRICT":
669
- BLOCKED_PROPERTY_CATEGORIES.ITERATOR_HELPERS.forEach((p) => blocked.add(p));
670
- BLOCKED_PROPERTY_CATEGORIES.REFLECTION.forEach((p) => blocked.add(p));
671
- BLOCKED_PROPERTY_CATEGORIES.TIMING.forEach((p) => blocked.add(p));
672
- break;
673
- case "SECURE":
674
- BLOCKED_PROPERTY_CATEGORIES.ITERATOR_HELPERS.forEach((p) => blocked.add(p));
675
- break;
676
- case "STANDARD":
677
- case "PERMISSIVE":
678
- break;
679
- }
680
- return blocked;
681
- }
682
- function buildBlockedPropertiesFromConfig(config) {
683
- const blocked = /* @__PURE__ */ new Set();
684
- if (config.blockConstructor) {
685
- blocked.add("constructor");
686
- }
687
- if (config.blockPrototype) {
688
- blocked.add("__proto__");
689
- blocked.add("prototype");
690
- }
691
- if (config.blockLegacyAccessors) {
692
- blocked.add("__defineGetter__");
693
- blocked.add("__defineSetter__");
694
- blocked.add("__lookupGetter__");
695
- blocked.add("__lookupSetter__");
696
- }
697
- return blocked;
698
- }
699
- function createSafeReflect(securityLevel) {
700
- if (securityLevel === "STRICT") {
701
- return void 0;
702
- }
703
- const dangerousMethods = /* @__PURE__ */ new Set(["setPrototypeOf"]);
704
- if (securityLevel === "SECURE") {
705
- dangerousMethods.add("apply");
706
- dangerousMethods.add("defineProperty");
707
- }
708
- return new Proxy(Reflect, {
709
- get(target, prop) {
710
- if (typeof prop === "string" && dangerousMethods.has(prop)) {
711
- return void 0;
1083
+ return sanitized;
1084
+ }
1085
+ return String(value);
1086
+ }
1087
+ function estimateStringSize(str) {
1088
+ let bytes = 2;
1089
+ for (let i = 0; i < str.length; i++) {
1090
+ const code = str.charCodeAt(i);
1091
+ if (code < 128) {
1092
+ if (code === 34 || code === 92) {
1093
+ bytes += 2;
1094
+ } else if (code < 32) {
1095
+ bytes += 6;
1096
+ } else {
1097
+ bytes += 1;
712
1098
  }
713
- const value = Reflect.get(target, prop);
714
- if (typeof value === "function" && prop === "construct") {
715
- return function(ctorTarget, args, newTarget) {
716
- const AsyncFunction = async function() {
717
- }.constructor;
718
- const GeneratorFunction = function* () {
719
- }.constructor;
720
- const AsyncGeneratorFunction = async function* () {
721
- }.constructor;
722
- if (ctorTarget === Function || ctorTarget === AsyncFunction || ctorTarget === GeneratorFunction || ctorTarget === AsyncGeneratorFunction) {
723
- throw createSafeError("Reflect.construct with function constructors is blocked", "SecurityError");
724
- }
725
- return Reflect.construct(
726
- ctorTarget,
727
- args,
728
- newTarget
729
- );
730
- };
1099
+ } else if (code < 2048) {
1100
+ bytes += 2;
1101
+ } else if (code >= 55296 && code <= 56319 && i + 1 < str.length) {
1102
+ const nextCode = str.charCodeAt(i + 1);
1103
+ if (nextCode >= 56320 && nextCode <= 57343) {
1104
+ bytes += 4;
1105
+ i++;
1106
+ } else {
1107
+ bytes += 3;
731
1108
  }
732
- return value;
1109
+ } else {
1110
+ bytes += 3;
733
1111
  }
734
- });
1112
+ }
1113
+ return bytes;
735
1114
  }
736
- function getFullCacheKey(options) {
737
- const parts = [];
738
- if (options.levelConfig) {
739
- const cfg = options.levelConfig;
740
- parts.push(
741
- `L:${cfg.blockConstructor ? "C" : "c"}${cfg.blockPrototype ? "P" : "p"}${cfg.blockLegacyAccessors ? "L" : "l"}`
1115
+ function estimateSerializedSize(value, maxBytes = 0, depth = 0, maxDepth = 2e3, currentPath = /* @__PURE__ */ new Set()) {
1116
+ if (depth > maxDepth) {
1117
+ throw new Error(
1118
+ `Structure exceeds maximum nesting depth (${maxDepth}). Deeply nested structures are rejected to prevent stack overflow attacks.`
742
1119
  );
743
- } else {
744
- parts.push("L:default");
745
- }
746
- if (options.additionalBlocked && options.additionalBlocked.length > 0) {
747
- parts.push(`B:${[...options.additionalBlocked].sort().join(",")}`);
748
1120
  }
749
- const effectiveMaxDepth = options.maxDepth ?? options.levelConfig?.proxyMaxDepth ?? 10;
750
- if (effectiveMaxDepth !== 10) {
751
- parts.push(`D:${effectiveMaxDepth}`);
1121
+ if (value === null) return 4;
1122
+ if (value === void 0) return 0;
1123
+ const type = typeof value;
1124
+ if (type === "string") {
1125
+ const bytes = estimateStringSize(value);
1126
+ if (maxBytes > 0 && bytes > maxBytes) {
1127
+ throw new Error(`String serialization would exceed limit: ${bytes} > ${maxBytes} bytes`);
1128
+ }
1129
+ return bytes;
752
1130
  }
753
- if (options.throwOnBlocked) {
754
- parts.push("T:1");
1131
+ if (type === "number") {
1132
+ const num = value;
1133
+ if (!Number.isFinite(num)) return 4;
1134
+ return String(num).length;
755
1135
  }
756
- return parts.join("|") || "default";
757
- }
758
- function isProxyable(value) {
759
- if (value === null) return false;
760
- if (typeof value !== "object" && typeof value !== "function") return false;
761
- const tag = Object.prototype.toString.call(value);
762
- if (NON_PROXYABLE_TYPES.has(tag)) {
763
- return false;
1136
+ if (type === "boolean") {
1137
+ return value ? 4 : 5;
764
1138
  }
765
- return true;
766
- }
767
- function createSecureProxy(target, options = {}) {
768
- if (!isProxyable(target)) {
769
- return target;
1139
+ if (type === "bigint") {
1140
+ return String(value).length + 2;
770
1141
  }
771
- const cacheKey = getFullCacheKey(options);
772
- const targetCache = proxyCache.get(target);
773
- if (targetCache) {
774
- const cached = targetCache.get(cacheKey);
775
- if (cached) {
776
- return cached;
777
- }
1142
+ if (type === "function" || type === "symbol") {
1143
+ return 0;
778
1144
  }
779
- const baseBlocked = options.levelConfig ? buildBlockedPropertiesFromConfig(options.levelConfig) : new Set(BLOCKED_PROPERTIES);
780
- const blockedSet = /* @__PURE__ */ new Set([...baseBlocked, ...options.additionalBlocked || []]);
781
- const maxDepth = options.maxDepth ?? options.levelConfig?.proxyMaxDepth ?? 10;
782
- const throwOnBlocked = options.throwOnBlocked ?? options.levelConfig?.throwOnBlocked ?? false;
783
- function proxyWithDepth(obj, depth) {
784
- if (!isProxyable(obj)) {
785
- return obj;
786
- }
787
- const objCache = proxyCache.get(obj);
788
- if (objCache) {
789
- const cachedProxy = objCache.get(cacheKey);
790
- if (cachedProxy) {
791
- return cachedProxy;
792
- }
793
- }
794
- if (depth > maxDepth) {
795
- return obj;
1145
+ if (Array.isArray(value)) {
1146
+ if (currentPath.has(value)) {
1147
+ return 4;
796
1148
  }
797
- const proxy = new Proxy(obj, {
798
- get(target2, property, receiver) {
799
- const propName = typeof property === "symbol" ? property.toString() : property;
800
- const descriptor = Object.getOwnPropertyDescriptor(target2, property);
801
- const isNonConfigurable = descriptor && !descriptor.configurable;
802
- if (typeof propName === "string" && blockedSet.has(propName)) {
803
- if (options.onBlocked) {
804
- options.onBlocked(target2, propName);
805
- }
806
- if (isNonConfigurable && descriptor && !descriptor.writable) {
807
- return Reflect.get(target2, property, receiver);
808
- }
809
- if (throwOnBlocked) {
810
- throw createSafeError(
811
- `Security violation: Access to '${propName}' is blocked. This property can be used for sandbox escape attacks.`,
812
- "SecurityError"
813
- );
814
- }
815
- return void 0;
816
- }
817
- if (typeof target2 === "function" && typeof propName === "string" && FUNCTION_BLOCKED_PROPERTIES.has(propName)) {
818
- if (options.onBlocked) {
819
- options.onBlocked(target2, propName);
820
- }
821
- if (isNonConfigurable && descriptor && !descriptor.writable) {
822
- return Reflect.get(target2, property, receiver);
823
- }
824
- if (throwOnBlocked) {
825
- throw createSafeError(
826
- `Security violation: Access to '${propName}' is blocked. This property can be used for sandbox escape attacks.`,
827
- "SecurityError"
828
- );
829
- }
830
- return void 0;
831
- }
832
- const value = Reflect.get(target2, property, receiver);
833
- if (typeof value === "function") {
834
- const tag = Object.prototype.toString.call(target2);
835
- if (INTERNAL_SLOT_TYPES.has(tag)) {
836
- const boundMethod = value.bind(target2);
837
- return proxyWithDepth(boundMethod, depth + 1);
838
- }
839
- }
840
- if (value !== null && (typeof value === "object" || typeof value === "function")) {
841
- return proxyWithDepth(value, depth + 1);
842
- }
843
- return value;
844
- },
845
- // Block setting dangerous properties
846
- set(target2, property, value, receiver) {
847
- const propName = typeof property === "symbol" ? property.toString() : property;
848
- if (typeof propName === "string" && blockedSet.has(propName)) {
849
- if (options.onBlocked) {
850
- options.onBlocked(target2, propName);
851
- }
852
- if (throwOnBlocked) {
853
- throw createSafeError(
854
- `Security violation: Setting '${propName}' is blocked. This property can be used for sandbox escape attacks.`,
855
- "SecurityError"
856
- );
857
- }
858
- return false;
859
- }
860
- return Reflect.set(target2, property, value, receiver);
861
- },
862
- // Block defining dangerous properties
863
- defineProperty(target2, property, descriptor) {
864
- const propName = typeof property === "symbol" ? property.toString() : property;
865
- if (typeof propName === "string" && blockedSet.has(propName)) {
866
- if (options.onBlocked) {
867
- options.onBlocked(target2, propName);
868
- }
869
- if (throwOnBlocked) {
870
- throw createSafeError(
871
- `Security violation: Defining '${propName}' is blocked. This property can be used for sandbox escape attacks.`,
872
- "SecurityError"
873
- );
874
- }
875
- return false;
876
- }
877
- return Reflect.defineProperty(target2, property, descriptor);
878
- },
879
- // Filter blocked property names from enumeration (Object.keys, Object.entries, etc.)
880
- // Must respect proxy invariants: non-configurable own properties cannot be hidden
881
- ownKeys(target2) {
882
- const keys = Reflect.ownKeys(target2);
883
- return keys.filter((key) => {
884
- const keyStr = typeof key === "symbol" ? key.toString() : key;
885
- if (typeof keyStr !== "string" || !blockedSet.has(keyStr)) {
886
- return true;
887
- }
888
- const descriptor = Object.getOwnPropertyDescriptor(target2, key);
889
- if (descriptor && !descriptor.configurable) {
890
- return true;
891
- }
892
- return false;
893
- });
894
- },
895
- // Hide blocked properties from property descriptor queries (defense-in-depth)
896
- // Must respect proxy invariants: non-configurable properties must return actual descriptor
897
- getOwnPropertyDescriptor(target2, property) {
898
- const propName = typeof property === "symbol" ? property.toString() : property;
899
- const descriptor = Reflect.getOwnPropertyDescriptor(target2, property);
900
- if (descriptor && !descriptor.configurable) {
901
- return descriptor;
902
- }
903
- if (typeof propName === "string" && blockedSet.has(propName)) {
904
- if (options.onBlocked) {
905
- options.onBlocked(target2, propName);
906
- }
907
- if (throwOnBlocked) {
908
- throw createSafeError(
909
- `Security violation: Access to property descriptor for '${propName}' is blocked. This property can be used for sandbox escape attacks.`,
910
- "SecurityError"
911
- );
912
- }
913
- return void 0;
914
- }
915
- return descriptor;
916
- },
917
- // Block getPrototypeOf to prevent prototype chain walking
918
- getPrototypeOf() {
919
- return null;
920
- },
921
- // Block setPrototypeOf
922
- setPrototypeOf() {
923
- return false;
924
- },
925
- // Intercept function calls to proxy return values
926
- // eslint-disable-next-line @typescript-eslint/no-explicit-any -- Proxy handler signature requires any for compatibility
927
- apply(target2, thisArg, argArray) {
928
- const result = Reflect.apply(target2, thisArg, argArray);
929
- if (isProxyable(result)) {
930
- return proxyWithDepth(result, depth + 1);
931
- }
932
- return result;
1149
+ currentPath.add(value);
1150
+ let size = 2;
1151
+ for (let i = 0; i < value.length; i++) {
1152
+ if (i > 0) size += 1;
1153
+ let elementSize = estimateSerializedSize(value[i], maxBytes, depth + 1, maxDepth, currentPath);
1154
+ if (elementSize === 0) elementSize = 4;
1155
+ size += elementSize;
1156
+ if (maxBytes > 0 && size > maxBytes) {
1157
+ currentPath.delete(value);
1158
+ throw new Error(
1159
+ `Array serialization would exceed limit: estimated ${size}+ > ${maxBytes} bytes. This often indicates repeated references to large strings that expand during JSON serialization.`
1160
+ );
933
1161
  }
934
- });
935
- let objCacheMap = proxyCache.get(obj);
936
- if (!objCacheMap) {
937
- objCacheMap = /* @__PURE__ */ new Map();
938
- proxyCache.set(obj, objCacheMap);
939
1162
  }
940
- objCacheMap.set(cacheKey, proxy);
941
- proxySet.add(proxy);
942
- return proxy;
1163
+ currentPath.delete(value);
1164
+ return size;
943
1165
  }
944
- return proxyWithDepth(target, 0);
945
- }
946
- function wrapGlobalsWithSecureProxy(globals, options = {}) {
947
- const wrapped = {};
948
- for (const [key, value] of Object.entries(globals)) {
949
- if (value !== null && (typeof value === "object" || typeof value === "function")) {
950
- wrapped[key] = createSecureProxy(value, options);
951
- } else {
952
- wrapped[key] = value;
1166
+ if (type === "object" && value !== null) {
1167
+ if (currentPath.has(value)) {
1168
+ return 4;
1169
+ }
1170
+ currentPath.add(value);
1171
+ if (value instanceof Date) {
1172
+ currentPath.delete(value);
1173
+ return 26;
1174
+ }
1175
+ if (value instanceof RegExp) {
1176
+ currentPath.delete(value);
1177
+ return 2;
1178
+ }
1179
+ let size = 2;
1180
+ const keys = Object.keys(value);
1181
+ let first = true;
1182
+ for (const key of keys) {
1183
+ if (key === "__proto__" || key === "constructor") continue;
1184
+ if (!first) size += 1;
1185
+ first = false;
1186
+ size += estimateStringSize(key) + 1;
1187
+ let propValue;
1188
+ try {
1189
+ propValue = value[key];
1190
+ } catch {
1191
+ continue;
1192
+ }
1193
+ const valueSize = estimateSerializedSize(propValue, maxBytes, depth + 1, maxDepth, currentPath);
1194
+ size += valueSize;
1195
+ if (maxBytes > 0 && size > maxBytes) {
1196
+ currentPath.delete(value);
1197
+ throw new Error(
1198
+ `Object serialization would exceed limit: estimated ${size}+ > ${maxBytes} bytes. This often indicates repeated references to large strings that expand during JSON serialization.`
1199
+ );
1200
+ }
953
1201
  }
1202
+ currentPath.delete(value);
1203
+ return size;
954
1204
  }
955
- return wrapped;
956
- }
957
- function createSecureStandardLibrary(options = {}) {
958
- return wrapGlobalsWithSecureProxy(
959
- {
960
- Math,
961
- JSON,
962
- Array,
963
- Object,
964
- String,
965
- Number,
966
- Date
967
- // Note: We intentionally don't include:
968
- // - Function (dangerous)
969
- // - eval (dangerous)
970
- // - Proxy, Reflect (meta-programming)
971
- },
972
- options
973
- );
1205
+ return 0;
974
1206
  }
975
- function isSecureProxy(obj) {
976
- if (obj === null || typeof obj !== "object") {
977
- return false;
1207
+ function checkSerializedSize(value, maxBytes) {
1208
+ try {
1209
+ const estimatedBytes = estimateSerializedSize(value, maxBytes);
1210
+ return { ok: true, estimatedBytes };
1211
+ } catch (err) {
1212
+ return { ok: false, error: err instanceof Error ? err.message : "Unknown error" };
978
1213
  }
979
- return proxySet.has(obj);
980
1214
  }
981
- var BLOCKED_PROPERTY_CATEGORIES, BLOCKED_PROPERTIES, DEFAULT_SECURE_PROXY_CONFIG, FUNCTION_BLOCKED_PROPERTIES, proxyCache, proxySet, NON_PROXYABLE_TYPES, INTERNAL_SLOT_TYPES;
982
- var init_secure_proxy = __esm({
983
- "libs/core/src/secure-proxy.ts"() {
1215
+ var DANGEROUS_KEYS, ReflectApply, ReflectGet2, ArrayIsArray, ObjectKeys, ObjectCreate, NumberIsFinite2, MathFloor2, MapProtoEntries, SetProtoValues, DateProtoGetTime, DateProtoToISOString, RegExpProtoToString;
1216
+ var init_value_sanitizer = __esm({
1217
+ "libs/core/src/value-sanitizer.ts"() {
984
1218
  "use strict";
985
- init_safe_error();
986
- BLOCKED_PROPERTY_CATEGORIES = {
987
- /**
988
- * Core prototype manipulation properties (always blocked except PERMISSIVE)
989
- */
990
- PROTOTYPE: /* @__PURE__ */ new Set([
991
- "constructor",
992
- "__proto__",
993
- "prototype",
994
- "__defineGetter__",
995
- "__defineSetter__",
996
- "__lookupGetter__",
997
- "__lookupSetter__"
998
- ]),
999
- /**
1000
- * Node.js 24 Iterator helper method names
1001
- * Blocked at STRICT/SECURE to prevent prototype chain access via iterators
1002
- */
1003
- ITERATOR_HELPERS: /* @__PURE__ */ new Set(["toArray", "forEach", "some", "every", "find", "reduce", "flatMap", "drop", "take"]),
1004
- /**
1005
- * Reflection properties on Object
1006
- * Blocked at STRICT to prevent introspection attacks
1007
- */
1008
- REFLECTION: /* @__PURE__ */ new Set([
1009
- "getOwnPropertyDescriptor",
1010
- "getOwnPropertyDescriptors",
1011
- "getOwnPropertyNames",
1012
- "getOwnPropertySymbols",
1013
- "getPrototypeOf",
1014
- "setPrototypeOf",
1015
- "defineProperty",
1016
- "defineProperties",
1017
- "preventExtensions",
1018
- "isExtensible",
1019
- "seal",
1020
- "isSealed",
1021
- "freeze",
1022
- "isFrozen"
1023
- ]),
1024
- /**
1025
- * Timing API properties
1026
- * Blocked at STRICT to prevent timing attacks
1027
- */
1028
- TIMING: /* @__PURE__ */ new Set(["hrtime", "timeOrigin"])
1029
- };
1030
- BLOCKED_PROPERTIES = /* @__PURE__ */ new Set([
1031
- // Code execution
1032
- "constructor",
1033
- // Prototype manipulation
1034
- "__proto__",
1035
- "prototype",
1036
- // Legacy getter/setter definition
1037
- "__defineGetter__",
1038
- "__defineSetter__",
1039
- "__lookupGetter__",
1040
- "__lookupSetter__"
1041
- ]);
1042
- DEFAULT_SECURE_PROXY_CONFIG = {
1043
- blockConstructor: true,
1044
- blockPrototype: true,
1045
- blockLegacyAccessors: true,
1046
- proxyMaxDepth: 10,
1047
- throwOnBlocked: true
1048
- };
1049
- FUNCTION_BLOCKED_PROPERTIES = /* @__PURE__ */ new Set([
1050
- // Function object properties that could leak information
1051
- "caller",
1052
- // Deprecated but still exists
1053
- "arguments"
1054
- // Deprecated but still exists
1055
- // Binding/applying could be used for exploitation
1056
- // Note: We may want to allow these in some cases
1057
- // 'bind',
1058
- // 'call',
1059
- // 'apply',
1060
- ]);
1061
- proxyCache = /* @__PURE__ */ new WeakMap();
1062
- proxySet = /* @__PURE__ */ new WeakSet();
1063
- NON_PROXYABLE_TYPES = /* @__PURE__ */ new Set([
1064
- // Map/Set have internal slots but we may need to proxy them in the future
1065
- "[object Map]",
1066
- "[object Set]",
1067
- "[object WeakMap]",
1068
- "[object WeakSet]",
1069
- "[object ArrayBuffer]",
1070
- "[object SharedArrayBuffer]",
1071
- "[object DataView]",
1072
- "[object Int8Array]",
1073
- "[object Uint8Array]",
1074
- "[object Uint8ClampedArray]",
1075
- "[object Int16Array]",
1076
- "[object Uint16Array]",
1077
- "[object Int32Array]",
1078
- "[object Uint32Array]",
1079
- "[object Float32Array]",
1080
- "[object Float64Array]",
1081
- "[object BigInt64Array]",
1082
- "[object BigUint64Array]",
1083
- // Generators and iterators use internal slots
1084
- "[object Generator]",
1085
- "[object AsyncGenerator]",
1086
- "[object GeneratorFunction]",
1087
- "[object AsyncGeneratorFunction]",
1088
- // Built-in iterators
1089
- "[object Array Iterator]",
1090
- "[object String Iterator]",
1091
- "[object Map Iterator]",
1092
- "[object Set Iterator]",
1093
- "[object RegExp String Iterator]"
1094
- ]);
1095
- INTERNAL_SLOT_TYPES = /* @__PURE__ */ new Set(["[object Promise]"]);
1219
+ DANGEROUS_KEYS = /* @__PURE__ */ new Set(["__proto__", "constructor"]);
1220
+ ReflectApply = Reflect.apply;
1221
+ ReflectGet2 = Reflect.get;
1222
+ ArrayIsArray = Array.isArray;
1223
+ ObjectKeys = Object.keys;
1224
+ ObjectCreate = Object.create;
1225
+ NumberIsFinite2 = Number.isFinite;
1226
+ MathFloor2 = Math.floor;
1227
+ MapProtoEntries = Map.prototype.entries;
1228
+ SetProtoValues = Set.prototype.values;
1229
+ DateProtoGetTime = Date.prototype.getTime;
1230
+ DateProtoToISOString = Date.prototype.toISOString;
1231
+ RegExpProtoToString = RegExp.prototype.toString;
1096
1232
  }
1097
1233
  });
1098
1234
 
@@ -1813,7 +1949,12 @@ ${stackTraceHardeningCode}
1813
1949
  function __ag_createSecureProxy(obj, depth) {
1814
1950
  if (depth === undefined) depth = 0;
1815
1951
  if (!__ag_Proxy || !__ag_Reflect) return obj;
1816
- if (depth > 10) return obj;
1952
+ // Fail CLOSED past the recursion backstop: returning the raw target would leak an
1953
+ // unwrapped reference (see MEMBRANE_MAX_RECURSION_DEPTH). Use the hardened safe-error
1954
+ // helper (sanitized stack, nulled constructor/proto) rather than a raw Error.
1955
+ if (depth > ${MEMBRANE_MAX_RECURSION_DEPTH}) {
1956
+ throw __ag_createSafeError('Security violation: secure-proxy recursion depth exceeded.');
1957
+ }
1817
1958
  if (obj === null || (typeof obj !== 'object' && typeof obj !== 'function')) return obj;
1818
1959
 
1819
1960
  if (__ag_proxyCache) {
@@ -1836,8 +1977,15 @@ ${stackTraceHardeningCode}
1836
1977
  if (typeof value === 'function') {
1837
1978
  // Bind methods to preserve internal slots when relevant.
1838
1979
  try { value = value.bind(target); } catch (e) {}
1980
+ return __ag_createSecureProxy(value, depth + 1);
1981
+ }
1982
+ // Only objects still need proxying; primitives (e.g. length/name) are inert and must be
1983
+ // returned directly, so a deep chain cannot turn a safe primitive read into a
1984
+ // recursion-depth error.
1985
+ if (value !== null && typeof value === 'object') {
1986
+ return __ag_createSecureProxy(value, depth + 1);
1839
1987
  }
1840
- return __ag_createSecureProxy(value, depth + 1);
1988
+ return value;
1841
1989
  },
1842
1990
  apply: function(target, thisArg, args) {
1843
1991
  return __ag_Reflect.apply(target, thisArg, args);
@@ -2233,8 +2381,10 @@ ${stackTraceHardeningCode}
2233
2381
  // Reference ID pattern for detecting sidecar references
2234
2382
  const refIdPattern = /^__REF_[0-9a-f]{8}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{12}__$/i;
2235
2383
 
2236
- // Proxy cache to avoid infinite recursion and duplicate wrapping
2384
+ // Proxy caches to avoid infinite recursion and duplicate wrapping. Host-owned values are
2385
+ // cached separately from realm-owned ones because the two use different blocking rules.
2237
2386
  const proxyCache = new WeakMap();
2387
+ const hostProxyCache = new WeakMap();
2238
2388
 
2239
2389
  /**
2240
2390
  * Create a secure proxy that blocks access to dangerous properties
@@ -2243,10 +2393,23 @@ ${stackTraceHardeningCode}
2243
2393
  * IMPORTANT: Must respect JavaScript proxy invariants:
2244
2394
  * - Non-configurable properties must return their actual value
2245
2395
  * - Non-configurable non-writable properties cannot be hidden
2396
+ *
2397
+ * The host flag marks a value that originates in the HOST realm (custom globals and
2398
+ * everything reachable from what they return). The host realm is the only one with code
2399
+ * generation from strings enabled, so a raw reference that escapes from it is remote code
2400
+ * execution; such a subtree refuses the reads a realm-owned object is allowed to answer.
2246
2401
  */
2247
- function createSecureProxy(obj, depth) {
2402
+ function createSecureProxy(obj, depth, host) {
2248
2403
  if (depth === undefined) depth = 0;
2249
- if (depth > 10) return obj; // Max depth to prevent infinite recursion
2404
+ host = host === true;
2405
+ // Recursion backstop. Fail CLOSED: returning the raw target here was the reported escape.
2406
+ // A bind chain inflates depth (each read binds a FRESH function, so the identity cache never
2407
+ // dedupes it) past the cap, and the raw host function prototype chain reaches the host
2408
+ // Function constructor for RCE. Throwing keeps the membrane total; the cap sits far above any
2409
+ // legitimately-deep (pre-sanitized) value so real data is never rejected.
2410
+ if (depth > ${MEMBRANE_MAX_RECURSION_DEPTH}) {
2411
+ throw createSafeError('Security violation: secure-proxy recursion depth exceeded.');
2412
+ }
2250
2413
 
2251
2414
  // Skip primitives and null
2252
2415
  if (obj === null || typeof obj !== 'object' && typeof obj !== 'function') {
@@ -2254,8 +2417,9 @@ ${stackTraceHardeningCode}
2254
2417
  }
2255
2418
 
2256
2419
  // Check cache
2257
- if (proxyCache.has(obj)) {
2258
- return proxyCache.get(obj);
2420
+ var cache = host ? hostProxyCache : proxyCache;
2421
+ if (cache.has(obj)) {
2422
+ return cache.get(obj);
2259
2423
  }
2260
2424
 
2261
2425
  var proxy = new Proxy(obj, {
@@ -2270,14 +2434,27 @@ ${stackTraceHardeningCode}
2270
2434
  // the proxy must return the exact same value (cannot wrap/bind/proxy it).
2271
2435
  // This matters for hardened properties like Error.prepareStackTrace.
2272
2436
  if (descriptor && isNonConfigurable && 'value' in descriptor && descriptor.writable === false) {
2273
- return descriptor.value;
2437
+ var exactValue = descriptor.value;
2438
+ // On a host-owned value the exact reference cannot be handed over: it would cross
2439
+ // the barrier unwrapped and its prototype chain reaches the host Function
2440
+ // constructor. Primitives stay safe to report, so only object/function values are
2441
+ // refused, and throwing satisfies the invariant that wrapping would break.
2442
+ if (host && exactValue !== null && (typeof exactValue === 'object' || typeof exactValue === 'function')) {
2443
+ throw createSafeError(
2444
+ "Security violation: Access to '" + propName + "' is blocked. " +
2445
+ "This property cannot be exposed without breaking the sandbox barrier."
2446
+ );
2447
+ }
2448
+ return exactValue;
2274
2449
  }
2275
2450
 
2276
2451
  // Block dangerous properties - but respect proxy invariants
2277
2452
  if (blockedPropertiesSet.has(propName)) {
2278
2453
  // For non-configurable properties, we MUST return the actual value
2279
- // (JavaScript proxy invariant - can't hide non-configurable properties)
2280
- if (isNonConfigurable) {
2454
+ // (JavaScript proxy invariant - can't hide non-configurable properties).
2455
+ // Host-owned values instead deny the read: every descriptor shape that could force
2456
+ // the trap's result was handled above, so returning undefined is invariant-safe.
2457
+ if (isNonConfigurable && !host) {
2281
2458
  return Reflect.get(target, property, receiver);
2282
2459
  }
2283
2460
  if (throwOnBlocked) {
@@ -2295,13 +2472,13 @@ ${stackTraceHardeningCode}
2295
2472
  // Then recursively proxy the bound function to block constructor access
2296
2473
  if (typeof value === 'function') {
2297
2474
  var boundMethod = value.bind(target);
2298
- return createSecureProxy(boundMethod, depth + 1);
2475
+ return createSecureProxy(boundMethod, depth + 1, host);
2299
2476
  }
2300
2477
 
2301
2478
  // Recursively proxy nested objects to maintain security barrier
2302
2479
  // This prevents attacks like: process.env.__proto__.constructor
2303
2480
  if (value !== null && typeof value === 'object') {
2304
- return createSecureProxy(value, depth + 1);
2481
+ return createSecureProxy(value, depth + 1, host);
2305
2482
  }
2306
2483
 
2307
2484
  return value;
@@ -2336,7 +2513,34 @@ ${stackTraceHardeningCode}
2336
2513
  var propName = String(property);
2337
2514
  var descriptor = Reflect.getOwnPropertyDescriptor(target, property);
2338
2515
 
2339
- // Must return actual descriptor for non-configurable properties (proxy invariant)
2516
+ // Mirror the get trap's host-owned pinned-value refusal: a non-configurable, non-writable
2517
+ // data property must be reported with its exact value (proxy invariant), so on a HOST-owned
2518
+ // value an object/function would cross the barrier unwrapped via descriptor.value and its
2519
+ // prototype chain reaches the host Function constructor. Deny the read instead (throwing
2520
+ // satisfies the invariant); primitives stay safe to report.
2521
+ if (host && descriptor && !descriptor.configurable && descriptor.writable === false && 'value' in descriptor) {
2522
+ var exactValue = descriptor.value;
2523
+ if (exactValue !== null && (typeof exactValue === 'object' || typeof exactValue === 'function')) {
2524
+ throw createSafeError(
2525
+ "Security violation: Access to property descriptor for '" + propName + "' is blocked. " +
2526
+ "This property cannot be exposed without breaking the sandbox barrier."
2527
+ );
2528
+ }
2529
+ return descriptor;
2530
+ }
2531
+
2532
+ // Accessor descriptors expose raw getter/setter functions. A non-configurable accessor
2533
+ // must be reported with its exact get/set (proxy invariant) and so cannot be wrapped \u2014
2534
+ // deny it if it carries a function whose prototype chain reaches the host constructor.
2535
+ if (descriptor && !descriptor.configurable &&
2536
+ (typeof descriptor.get === 'function' || typeof descriptor.set === 'function')) {
2537
+ throw createSafeError(
2538
+ "Security violation: Access to property descriptor for '" + propName + "' is blocked. " +
2539
+ "This property cannot be exposed without breaking the sandbox barrier."
2540
+ );
2541
+ }
2542
+
2543
+ // Must return actual descriptor for other non-configurable properties (proxy invariant)
2340
2544
  if (descriptor && !descriptor.configurable) {
2341
2545
  return descriptor;
2342
2546
  }
@@ -2351,6 +2555,28 @@ ${stackTraceHardeningCode}
2351
2555
  }
2352
2556
  return undefined;
2353
2557
  }
2558
+
2559
+ // A configurable accessor's getter/setter may be safely proxied so the descriptor never
2560
+ // hands back a raw function that leads to the host Function constructor.
2561
+ if (descriptor && (typeof descriptor.get === 'function' || typeof descriptor.set === 'function')) {
2562
+ var accessorWrapped = {};
2563
+ for (var ak in descriptor) { if (Object.prototype.hasOwnProperty.call(descriptor, ak)) accessorWrapped[ak] = descriptor[ak]; }
2564
+ if (typeof descriptor.get === 'function') accessorWrapped.get = createSecureProxy(descriptor.get, depth + 1, host);
2565
+ if (typeof descriptor.set === 'function') accessorWrapped.set = createSecureProxy(descriptor.set, depth + 1, host);
2566
+ return accessorWrapped;
2567
+ }
2568
+
2569
+ // Wrap object/function values so a descriptor read cannot hand back a raw reference that
2570
+ // the get trap would otherwise have proxied.
2571
+ if (descriptor && 'value' in descriptor) {
2572
+ var value = descriptor.value;
2573
+ if (value !== null && (typeof value === 'object' || typeof value === 'function')) {
2574
+ var wrapped = {};
2575
+ for (var dk in descriptor) { if (Object.prototype.hasOwnProperty.call(descriptor, dk)) wrapped[dk] = descriptor[dk]; }
2576
+ wrapped.value = createSecureProxy(value, depth + 1, host);
2577
+ return wrapped;
2578
+ }
2579
+ }
2354
2580
  return descriptor;
2355
2581
  },
2356
2582
  ownKeys: function(target) {
@@ -2373,10 +2599,34 @@ ${stackTraceHardeningCode}
2373
2599
  getPrototypeOf: function(target) {
2374
2600
  // Return null to hide prototype chain
2375
2601
  return null;
2376
- }
2602
+ },
2603
+ // SECURITY (GHSA-grmc-r8vw-226r): the get trap re-wraps values obtained via property
2604
+ // ACCESS, but function-call results cross the same trust boundary and must be wrapped
2605
+ // too. Without an apply trap, calling a wrapped function (for example the then method
2606
+ // of the secure Promise returned by callTool) falls through to the default call and
2607
+ // returns a RAW host object; the sandbox can then walk its prototype chain
2608
+ // (Promise.prototype up to Function) to reach the host Function constructor for RCE.
2609
+ // Results are re-wrapped at a FRESH depth (0) so a chain of calls such as
2610
+ // then().then() cannot inflate depth past the recursion cap and leak an unwrapped value.
2611
+ apply: function(target, thisArg, args) {
2612
+ return createSecureProxy(Reflect.apply(target, thisArg, args), 0, host);
2613
+ }
2614
+ // NOTE: intentionally NO construct trap here (unlike the standalone secure-proxy used
2615
+ // for single-VM mode). Every constructor reachable from sandbox code resolves to an
2616
+ // inner-VM or parent-VM intrinsic, and BOTH of those realms run with code generation
2617
+ // from strings disabled, so a 'new X()' result cannot reach a usable Function
2618
+ // constructor. The only code-generation-enabled realm (the host) is reached solely via
2619
+ // host return values (callTool), which is an apply-path and is covered above. Wrapping
2620
+ // construct results would additionally break the proxy invariant for the frozen (non-
2621
+ // extensible) Error objects the harness throws (getPrototypeOf must not report null for
2622
+ // a non-extensible target), masking legitimate errors.
2377
2623
  });
2378
2624
 
2379
- proxyCache.set(obj, proxy);
2625
+ cache.set(obj, proxy);
2626
+ // Idempotency: re-wrapping an already-secure proxy must return it unchanged, so an apply
2627
+ // result that is itself already a secure proxy is not double-wrapped (which would nest
2628
+ // proxies and inflate depth toward the recursion cap).
2629
+ cache.set(proxy, proxy);
2380
2630
  return proxy;
2381
2631
  }
2382
2632
 
@@ -2754,10 +3004,20 @@ ${stackTraceHardeningCode}
2754
3004
  if (typeof fn !== 'function') {
2755
3005
  throw createSafeError('parallel() requires a callback function as second argument', 'TypeError');
2756
3006
  }
2757
- if (items.length > 100) {
3007
+ // SECURITY: items may be an attacker Proxy that only passes Array.isArray. Read the length
3008
+ // ONCE and build the promise list by index rather than items.map(fn), so a .map trap can
3009
+ // neither be handed our callback nor use a stateful length to slip past the 100-item cap.
3010
+ var len = items.length;
3011
+ if (typeof len !== 'number' || !isFinite(len) || len < 0) len = 0;
3012
+ len = Math.floor(len);
3013
+ if (len > 100) {
2758
3014
  throw createSafeError('parallel() is limited to 100 items');
2759
3015
  }
2760
- return await Promise.all(items.map(fn));
3016
+ var promises = [];
3017
+ for (var i = 0; i < len; i++) {
3018
+ promises[i] = fn(items[i], i, items);
3019
+ }
3020
+ return await Promise.all(promises);
2761
3021
  }
2762
3022
 
2763
3023
  /**
@@ -3301,10 +3561,13 @@ ${stackTraceHardeningCode}
3301
3561
  // Add user-provided globals if any (also wrapped with secure proxy and non-writable)
3302
3562
  // SECURITY: Use enumerable: false to prevent Object.assign({}, this) from copying globals
3303
3563
  // This blocks Vector 380 (Bridge-Serialized State Reflection) attack
3564
+ // Custom globals are HOST-realm values, so they are wrapped in host mode: the whole
3565
+ // subtree reachable through them (including whatever their calls return) refuses to hand
3566
+ // back a raw reference, even for descriptor shapes where a realm-owned object may.
3304
3567
  if (hostConfig.globals) {
3305
3568
  for (var uKey in hostConfig.globals) {
3306
3569
  if (hostConfig.globals.hasOwnProperty(uKey)) {
3307
- var wrappedGlobal = createSecureProxy(hostConfig.globals[uKey]);
3570
+ var wrappedGlobal = createSecureProxy(hostConfig.globals[uKey], 0, true);
3308
3571
  Object.defineProperty(innerContext, uKey, {
3309
3572
  value: wrappedGlobal,
3310
3573
  writable: false,
@@ -3413,10 +3676,11 @@ ${stackTraceHardeningCode}
3413
3676
  })();
3414
3677
  `.trim();
3415
3678
  }
3416
- var NODEJS_24_DANGEROUS_GLOBALS;
3679
+ var MEMBRANE_MAX_RECURSION_DEPTH, NODEJS_24_DANGEROUS_GLOBALS;
3417
3680
  var init_parent_vm_bootstrap = __esm({
3418
3681
  "libs/core/src/double-vm/parent-vm-bootstrap.ts"() {
3419
3682
  "use strict";
3683
+ MEMBRANE_MAX_RECURSION_DEPTH = 256;
3420
3684
  NODEJS_24_DANGEROUS_GLOBALS = {
3421
3685
  STRICT: [
3422
3686
  // Code execution - CRITICAL
@@ -6044,6 +6308,24 @@ var init_errors = __esm({
6044
6308
  });
6045
6309
 
6046
6310
  // libs/core/src/adapters/worker-pool/safe-deserialize.ts
6311
+ function mapArraySafely(value, sanitizeItem) {
6312
+ const rawLen = ReflectGet3(value, "length");
6313
+ const len = typeof rawLen === "number" && NumberIsFinite3(rawLen) && rawLen >= 0 ? MathFloor3(rawLen) : 0;
6314
+ if (len > MAX_ARRAY_LENGTH) {
6315
+ throw new MessageValidationError(`Array exceeds maximum length of ${MAX_ARRAY_LENGTH}`);
6316
+ }
6317
+ const out = [];
6318
+ for (let i = 0; i < len; i++) {
6319
+ let item;
6320
+ try {
6321
+ item = ReflectGet3(value, i);
6322
+ } catch {
6323
+ item = void 0;
6324
+ }
6325
+ out[i] = sanitizeItem(item);
6326
+ }
6327
+ return out;
6328
+ }
6047
6329
  function safeDeserialize(raw, maxSizeBytes) {
6048
6330
  if (maxSizeBytes !== void 0) {
6049
6331
  const byteLength = Buffer.byteLength(raw, "utf-8");
@@ -6071,8 +6353,8 @@ function sanitizeObjectWithDepthCheck(value, depth) {
6071
6353
  if (typeof value !== "object") {
6072
6354
  return value;
6073
6355
  }
6074
- if (Array.isArray(value)) {
6075
- return value.map((item) => sanitizeObjectWithDepthCheck(item, depth + 1));
6356
+ if (ArrayIsArray2(value)) {
6357
+ return mapArraySafely(value, (item) => sanitizeObjectWithDepthCheck(item, depth + 1));
6076
6358
  }
6077
6359
  const result = /* @__PURE__ */ Object.create(null);
6078
6360
  for (const key of Object.keys(value)) {
@@ -6100,8 +6382,8 @@ function sanitizeObject(value, depth = 0) {
6100
6382
  if (typeof value !== "object") {
6101
6383
  return value;
6102
6384
  }
6103
- if (Array.isArray(value)) {
6104
- return value.map((item) => sanitizeObject(item, depth + 1));
6385
+ if (ArrayIsArray2(value)) {
6386
+ return mapArraySafely(value, (item) => sanitizeObject(item, depth + 1));
6105
6387
  }
6106
6388
  const result = /* @__PURE__ */ Object.create(null);
6107
6389
  for (const key of Object.keys(value)) {
@@ -6111,11 +6393,16 @@ function sanitizeObject(value, depth = 0) {
6111
6393
  }
6112
6394
  return result;
6113
6395
  }
6114
- var DANGEROUS_KEYS2, MAX_DEPTH;
6396
+ var ReflectGet3, ArrayIsArray2, NumberIsFinite3, MathFloor3, MAX_ARRAY_LENGTH, DANGEROUS_KEYS2, MAX_DEPTH;
6115
6397
  var init_safe_deserialize = __esm({
6116
6398
  "libs/core/src/adapters/worker-pool/safe-deserialize.ts"() {
6117
6399
  "use strict";
6118
6400
  init_errors();
6401
+ ReflectGet3 = Reflect.get;
6402
+ ArrayIsArray2 = Array.isArray;
6403
+ NumberIsFinite3 = Number.isFinite;
6404
+ MathFloor3 = Math.floor;
6405
+ MAX_ARRAY_LENGTH = 1e6;
6119
6406
  DANGEROUS_KEYS2 = /* @__PURE__ */ new Set(["__proto__", "constructor", "prototype"]);
6120
6407
  MAX_DEPTH = 50;
6121
6408
  }
@@ -8184,6 +8471,9 @@ function validateGlobals(globals, options = {}) {
8184
8471
  }
8185
8472
  }
8186
8473
 
8474
+ // libs/core/src/enclave.ts
8475
+ init_secure_proxy();
8476
+
8187
8477
  // libs/core/src/sidecar/index.ts
8188
8478
  init_reference_config();
8189
8479
 
@@ -10284,6 +10574,9 @@ ${errorMessages}`,
10284
10574
  } else if (this.config.memoryLimit && this.config.memoryLimit > 0) {
10285
10575
  transformedCode = this.applyMemoryTrackingTransforms(transformedCode);
10286
10576
  }
10577
+ if (this.transformCode) {
10578
+ transformedCode = this.applyComputedKeyGuard(transformedCode);
10579
+ }
10287
10580
  let scoringResult;
10288
10581
  if (this.scoringGate) {
10289
10582
  scoringResult = await this.scoringGate.evaluate(transformedCode);
@@ -10381,6 +10674,21 @@ ${errorMessages}`,
10381
10674
  * @param code The code to transform
10382
10675
  * @returns The transformed code
10383
10676
  */
10677
+ applyComputedKeyGuard(code) {
10678
+ const proxyConfig = this.config.secureProxyConfig;
10679
+ const blockedKeys = [...buildBlockedPropertiesFromConfig(proxyConfig)];
10680
+ if (blockedKeys.length === 0) {
10681
+ return code;
10682
+ }
10683
+ const throwOnBlocked = proxyConfig.throwOnBlocked ?? true;
10684
+ const parseModule = (source) => acorn2.parse(source, { ecmaVersion: "latest", sourceType: "module" });
10685
+ const ast = parseModule(code);
10686
+ const { guardedCount } = (0, import_ast5.guardComputedMemberKeys)(ast, parseModule, { blockedKeys, throwOnBlocked });
10687
+ if (guardedCount === 0) {
10688
+ return code;
10689
+ }
10690
+ return (0, import_astring.generate)(ast);
10691
+ }
10384
10692
  applyMemoryTrackingTransforms(code) {
10385
10693
  const ast = acorn2.parse(code, {
10386
10694
  ecmaVersion: "latest",