@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/esm/index.mjs CHANGED
@@ -8,6 +8,556 @@ var __export = (target, all) => {
8
8
  __defProp(target, name, { get: all[name], enumerable: true });
9
9
  };
10
10
 
11
+ // libs/core/src/safe-error.ts
12
+ function createSafeError(message, name = "Error") {
13
+ const error = new Error(message);
14
+ error.name = name;
15
+ const SafeConstructor = /* @__PURE__ */ Object.create(null);
16
+ Object.defineProperties(SafeConstructor, {
17
+ constructor: {
18
+ value: SafeConstructor,
19
+ writable: false,
20
+ enumerable: false,
21
+ configurable: false
22
+ },
23
+ prototype: {
24
+ value: null,
25
+ writable: false,
26
+ enumerable: false,
27
+ configurable: false
28
+ },
29
+ name: {
30
+ value: "SafeError",
31
+ writable: false,
32
+ enumerable: false,
33
+ configurable: false
34
+ }
35
+ });
36
+ Object.freeze(SafeConstructor);
37
+ Object.setPrototypeOf(error, null);
38
+ Object.defineProperty(error, "constructor", {
39
+ value: SafeConstructor,
40
+ writable: false,
41
+ enumerable: false,
42
+ configurable: false
43
+ });
44
+ Object.defineProperty(error, "__proto__", {
45
+ value: null,
46
+ writable: false,
47
+ enumerable: false,
48
+ configurable: false
49
+ });
50
+ Object.defineProperty(error, "stack", {
51
+ value: void 0,
52
+ writable: false,
53
+ enumerable: false,
54
+ configurable: false
55
+ });
56
+ Object.freeze(error);
57
+ return error;
58
+ }
59
+ function createSafeTypeError(message) {
60
+ return createSafeError(message, "TypeError");
61
+ }
62
+ var init_safe_error = __esm({
63
+ "libs/core/src/safe-error.ts"() {
64
+ "use strict";
65
+ }
66
+ });
67
+
68
+ // libs/core/src/secure-proxy.ts
69
+ function getBlockedPropertiesForLevel(level) {
70
+ const blocked = /* @__PURE__ */ new Set();
71
+ if (level !== "PERMISSIVE") {
72
+ BLOCKED_PROPERTY_CATEGORIES.PROTOTYPE.forEach((p) => blocked.add(p));
73
+ }
74
+ switch (level) {
75
+ case "STRICT":
76
+ BLOCKED_PROPERTY_CATEGORIES.ITERATOR_HELPERS.forEach((p) => blocked.add(p));
77
+ BLOCKED_PROPERTY_CATEGORIES.REFLECTION.forEach((p) => blocked.add(p));
78
+ BLOCKED_PROPERTY_CATEGORIES.TIMING.forEach((p) => blocked.add(p));
79
+ break;
80
+ case "SECURE":
81
+ BLOCKED_PROPERTY_CATEGORIES.ITERATOR_HELPERS.forEach((p) => blocked.add(p));
82
+ break;
83
+ case "STANDARD":
84
+ case "PERMISSIVE":
85
+ break;
86
+ }
87
+ return blocked;
88
+ }
89
+ function buildBlockedPropertiesFromConfig(config) {
90
+ const blocked = /* @__PURE__ */ new Set();
91
+ if (config.blockConstructor) {
92
+ blocked.add("constructor");
93
+ }
94
+ if (config.blockPrototype) {
95
+ blocked.add("__proto__");
96
+ blocked.add("prototype");
97
+ }
98
+ if (config.blockLegacyAccessors) {
99
+ blocked.add("__defineGetter__");
100
+ blocked.add("__defineSetter__");
101
+ blocked.add("__lookupGetter__");
102
+ blocked.add("__lookupSetter__");
103
+ }
104
+ return blocked;
105
+ }
106
+ function createSafeReflect(securityLevel) {
107
+ if (securityLevel === "STRICT") {
108
+ return void 0;
109
+ }
110
+ const dangerousMethods = /* @__PURE__ */ new Set(["setPrototypeOf"]);
111
+ if (securityLevel === "SECURE") {
112
+ dangerousMethods.add("apply");
113
+ dangerousMethods.add("defineProperty");
114
+ }
115
+ return new Proxy(Reflect, {
116
+ get(target, prop) {
117
+ if (typeof prop === "string" && dangerousMethods.has(prop)) {
118
+ return void 0;
119
+ }
120
+ const value = Reflect.get(target, prop);
121
+ if (typeof value === "function" && prop === "construct") {
122
+ const safeConstruct = function(ctorTarget, args, newTarget) {
123
+ const AsyncFunction = async function() {
124
+ }.constructor;
125
+ const GeneratorFunction = function* () {
126
+ }.constructor;
127
+ const AsyncGeneratorFunction = async function* () {
128
+ }.constructor;
129
+ if (ctorTarget === Function || ctorTarget === AsyncFunction || ctorTarget === GeneratorFunction || ctorTarget === AsyncGeneratorFunction) {
130
+ throw createSafeError("Reflect.construct with function constructors is blocked", "SecurityError");
131
+ }
132
+ return Reflect.construct(
133
+ ctorTarget,
134
+ args,
135
+ newTarget
136
+ );
137
+ };
138
+ return createSecureProxy(safeConstruct);
139
+ }
140
+ if (typeof value === "function") {
141
+ return createSecureProxy(value);
142
+ }
143
+ return value;
144
+ }
145
+ });
146
+ }
147
+ function getFullCacheKey(options) {
148
+ const parts = [];
149
+ if (options.levelConfig) {
150
+ const cfg = options.levelConfig;
151
+ parts.push(
152
+ `L:${cfg.blockConstructor ? "C" : "c"}${cfg.blockPrototype ? "P" : "p"}${cfg.blockLegacyAccessors ? "L" : "l"}`
153
+ );
154
+ } else {
155
+ parts.push("L:default");
156
+ }
157
+ if (options.additionalBlocked && options.additionalBlocked.length > 0) {
158
+ parts.push(`B:${[...options.additionalBlocked].sort().join(",")}`);
159
+ }
160
+ const effectiveMaxDepth = options.maxDepth ?? options.levelConfig?.proxyMaxDepth ?? 10;
161
+ if (effectiveMaxDepth !== 10) {
162
+ parts.push(`D:${effectiveMaxDepth}`);
163
+ }
164
+ if (options.throwOnBlocked) {
165
+ parts.push("T:1");
166
+ }
167
+ return parts.join("|") || "default";
168
+ }
169
+ function isProxyable(value) {
170
+ if (value === null) return false;
171
+ if (typeof value !== "object" && typeof value !== "function") return false;
172
+ const tag = Object.prototype.toString.call(value);
173
+ if (NON_PROXYABLE_TYPES.has(tag)) {
174
+ return false;
175
+ }
176
+ return true;
177
+ }
178
+ function createSecureProxy(target, options = {}) {
179
+ if (!isProxyable(target)) {
180
+ return target;
181
+ }
182
+ const cacheKey = getFullCacheKey(options);
183
+ const targetCache = proxyCache.get(target);
184
+ if (targetCache) {
185
+ const cached = targetCache.get(cacheKey);
186
+ if (cached) {
187
+ return cached;
188
+ }
189
+ }
190
+ const baseBlocked = options.levelConfig ? buildBlockedPropertiesFromConfig(options.levelConfig) : new Set(BLOCKED_PROPERTIES);
191
+ const blockedSet = /* @__PURE__ */ new Set([...baseBlocked, ...options.additionalBlocked || []]);
192
+ const configuredMaxDepth = options.maxDepth ?? options.levelConfig?.proxyMaxDepth ?? 10;
193
+ const maxDepth = Number.isFinite(configuredMaxDepth) ? Math.max(configuredMaxDepth, MIN_MEMBRANE_RECURSION_DEPTH) : MIN_MEMBRANE_RECURSION_DEPTH;
194
+ const throwOnBlocked = options.throwOnBlocked ?? options.levelConfig?.throwOnBlocked ?? false;
195
+ function proxyWithDepth(obj, depth) {
196
+ if (!isProxyable(obj)) {
197
+ return obj;
198
+ }
199
+ const objCache = proxyCache.get(obj);
200
+ if (objCache) {
201
+ const cachedProxy = objCache.get(cacheKey);
202
+ if (cachedProxy) {
203
+ return cachedProxy;
204
+ }
205
+ }
206
+ if (depth > maxDepth) {
207
+ throw createSafeError(
208
+ `Security violation: secure-proxy recursion depth (${maxDepth}) exceeded. The value cannot be exposed without breaking the sandbox barrier.`,
209
+ "SecurityError"
210
+ );
211
+ }
212
+ const proxy = new Proxy(obj, {
213
+ get(target2, property, receiver) {
214
+ const propName = typeof property === "symbol" ? property.toString() : property;
215
+ const descriptor = Object.getOwnPropertyDescriptor(target2, property);
216
+ if (descriptor && !descriptor.configurable && descriptor.writable === false && "value" in descriptor) {
217
+ const exactValue = descriptor.value;
218
+ if (exactValue !== null && (typeof exactValue === "object" || typeof exactValue === "function")) {
219
+ throw createSafeError(
220
+ `Security violation: Access to '${String(propName)}' is blocked. This property cannot be exposed without breaking the sandbox barrier.`,
221
+ "SecurityError"
222
+ );
223
+ }
224
+ return exactValue;
225
+ }
226
+ if (typeof propName === "string" && blockedSet.has(propName)) {
227
+ if (options.onBlocked) {
228
+ options.onBlocked(target2, propName);
229
+ }
230
+ if (throwOnBlocked) {
231
+ throw createSafeError(
232
+ `Security violation: Access to '${propName}' is blocked. This property can be used for sandbox escape attacks.`,
233
+ "SecurityError"
234
+ );
235
+ }
236
+ return void 0;
237
+ }
238
+ if (typeof target2 === "function" && typeof propName === "string" && FUNCTION_BLOCKED_PROPERTIES.has(propName)) {
239
+ if (options.onBlocked) {
240
+ options.onBlocked(target2, propName);
241
+ }
242
+ if (throwOnBlocked) {
243
+ throw createSafeError(
244
+ `Security violation: Access to '${propName}' is blocked. This property can be used for sandbox escape attacks.`,
245
+ "SecurityError"
246
+ );
247
+ }
248
+ return void 0;
249
+ }
250
+ const value = Reflect.get(target2, property, receiver);
251
+ if (typeof value === "function") {
252
+ const tag = Object.prototype.toString.call(target2);
253
+ if (INTERNAL_SLOT_TYPES.has(tag)) {
254
+ const boundMethod = value.bind(target2);
255
+ return proxyWithDepth(boundMethod, depth + 1);
256
+ }
257
+ }
258
+ if (value !== null && (typeof value === "object" || typeof value === "function")) {
259
+ return proxyWithDepth(value, depth + 1);
260
+ }
261
+ return value;
262
+ },
263
+ // Block setting dangerous properties
264
+ set(target2, property, value, receiver) {
265
+ const propName = typeof property === "symbol" ? property.toString() : property;
266
+ if (typeof propName === "string" && blockedSet.has(propName)) {
267
+ if (options.onBlocked) {
268
+ options.onBlocked(target2, propName);
269
+ }
270
+ if (throwOnBlocked) {
271
+ throw createSafeError(
272
+ `Security violation: Setting '${propName}' is blocked. This property can be used for sandbox escape attacks.`,
273
+ "SecurityError"
274
+ );
275
+ }
276
+ return false;
277
+ }
278
+ return Reflect.set(target2, property, value, receiver);
279
+ },
280
+ // Block defining dangerous properties
281
+ defineProperty(target2, property, descriptor) {
282
+ const propName = typeof property === "symbol" ? property.toString() : property;
283
+ if (typeof propName === "string" && blockedSet.has(propName)) {
284
+ if (options.onBlocked) {
285
+ options.onBlocked(target2, propName);
286
+ }
287
+ if (throwOnBlocked) {
288
+ throw createSafeError(
289
+ `Security violation: Defining '${propName}' is blocked. This property can be used for sandbox escape attacks.`,
290
+ "SecurityError"
291
+ );
292
+ }
293
+ return false;
294
+ }
295
+ return Reflect.defineProperty(target2, property, descriptor);
296
+ },
297
+ // Filter blocked property names from enumeration (Object.keys, Object.entries, etc.)
298
+ // Must respect proxy invariants: non-configurable own properties cannot be hidden
299
+ ownKeys(target2) {
300
+ const keys = Reflect.ownKeys(target2);
301
+ return keys.filter((key) => {
302
+ const keyStr = typeof key === "symbol" ? key.toString() : key;
303
+ if (typeof keyStr !== "string" || !blockedSet.has(keyStr)) {
304
+ return true;
305
+ }
306
+ const descriptor = Object.getOwnPropertyDescriptor(target2, key);
307
+ if (descriptor && !descriptor.configurable) {
308
+ return true;
309
+ }
310
+ return false;
311
+ });
312
+ },
313
+ // Hide blocked properties from property descriptor queries (defense-in-depth)
314
+ // Must respect proxy invariants: non-configurable properties must return actual descriptor
315
+ getOwnPropertyDescriptor(target2, property) {
316
+ const propName = typeof property === "symbol" ? property.toString() : property;
317
+ const descriptor = Reflect.getOwnPropertyDescriptor(target2, property);
318
+ if (descriptor && !descriptor.configurable && descriptor.writable === false && "value" in descriptor) {
319
+ const exactValue = descriptor.value;
320
+ if (exactValue !== null && (typeof exactValue === "object" || typeof exactValue === "function")) {
321
+ throw createSafeError(
322
+ `Security violation: Access to property descriptor for '${String(propName)}' is blocked. This property cannot be exposed without breaking the sandbox barrier.`,
323
+ "SecurityError"
324
+ );
325
+ }
326
+ return descriptor;
327
+ }
328
+ if (descriptor && !descriptor.configurable && (typeof descriptor.get === "function" || typeof descriptor.set === "function")) {
329
+ throw createSafeError(
330
+ `Security violation: Access to property descriptor for '${String(propName)}' is blocked. This property cannot be exposed without breaking the sandbox barrier.`,
331
+ "SecurityError"
332
+ );
333
+ }
334
+ if (descriptor && !descriptor.configurable) {
335
+ return descriptor;
336
+ }
337
+ if (typeof propName === "string" && blockedSet.has(propName)) {
338
+ if (options.onBlocked) {
339
+ options.onBlocked(target2, propName);
340
+ }
341
+ if (throwOnBlocked) {
342
+ throw createSafeError(
343
+ `Security violation: Access to property descriptor for '${propName}' is blocked. This property can be used for sandbox escape attacks.`,
344
+ "SecurityError"
345
+ );
346
+ }
347
+ return void 0;
348
+ }
349
+ if (descriptor && (typeof descriptor.get === "function" || typeof descriptor.set === "function")) {
350
+ return {
351
+ ...descriptor,
352
+ get: typeof descriptor.get === "function" ? proxyWithDepth(descriptor.get, depth + 1) : descriptor.get,
353
+ set: typeof descriptor.set === "function" ? proxyWithDepth(descriptor.set, depth + 1) : descriptor.set
354
+ };
355
+ }
356
+ if (descriptor && "value" in descriptor) {
357
+ const value = descriptor.value;
358
+ if (value !== null && (typeof value === "object" || typeof value === "function")) {
359
+ return { ...descriptor, value: proxyWithDepth(value, depth + 1) };
360
+ }
361
+ }
362
+ return descriptor;
363
+ },
364
+ // Block getPrototypeOf to prevent prototype chain walking
365
+ getPrototypeOf() {
366
+ return null;
367
+ },
368
+ // Block setPrototypeOf
369
+ setPrototypeOf() {
370
+ return false;
371
+ },
372
+ // Intercept function calls to proxy return values
373
+ // eslint-disable-next-line @typescript-eslint/no-explicit-any -- Proxy handler signature requires any for compatibility
374
+ apply(target2, thisArg, argArray) {
375
+ const unwrappedThis = thisArg !== null && (typeof thisArg === "object" || typeof thisArg === "function") && proxyToTarget.has(thisArg) ? proxyToTarget.get(thisArg) : thisArg;
376
+ const result = Reflect.apply(target2, unwrappedThis, argArray);
377
+ if (isProxyable(result)) {
378
+ return proxyWithDepth(result, depth + 1);
379
+ }
380
+ return result;
381
+ },
382
+ // Intercept constructor calls to proxy the created instance. Without this, code such as
383
+ // `new (wrappedCtor)()` would return a RAW object whose prototype chain reaches the
384
+ // host Function constructor — the same escape class the apply trap closes for calls.
385
+ // eslint-disable-next-line @typescript-eslint/no-explicit-any -- Proxy handler signature requires any for compatibility
386
+ construct(target2, argArray, newTarget) {
387
+ const instance = Reflect.construct(target2, argArray, newTarget === proxy ? target2 : newTarget);
388
+ if (isProxyable(instance)) {
389
+ return proxyWithDepth(instance, depth + 1);
390
+ }
391
+ return instance;
392
+ }
393
+ });
394
+ let objCacheMap = proxyCache.get(obj);
395
+ if (!objCacheMap) {
396
+ objCacheMap = /* @__PURE__ */ new Map();
397
+ proxyCache.set(obj, objCacheMap);
398
+ }
399
+ objCacheMap.set(cacheKey, proxy);
400
+ proxySet.add(proxy);
401
+ proxyToTarget.set(proxy, obj);
402
+ return proxy;
403
+ }
404
+ return proxyWithDepth(target, 0);
405
+ }
406
+ function wrapGlobalsWithSecureProxy(globals, options = {}) {
407
+ const wrapped = {};
408
+ for (const [key, value] of Object.entries(globals)) {
409
+ if (value !== null && (typeof value === "object" || typeof value === "function")) {
410
+ wrapped[key] = createSecureProxy(value, options);
411
+ } else {
412
+ wrapped[key] = value;
413
+ }
414
+ }
415
+ return wrapped;
416
+ }
417
+ function createSecureStandardLibrary(options = {}) {
418
+ return wrapGlobalsWithSecureProxy(
419
+ {
420
+ Math,
421
+ JSON,
422
+ Array,
423
+ Object,
424
+ String,
425
+ Number,
426
+ Date
427
+ // Note: We intentionally don't include:
428
+ // - Function (dangerous)
429
+ // - eval (dangerous)
430
+ // - Proxy, Reflect (meta-programming)
431
+ },
432
+ options
433
+ );
434
+ }
435
+ function isSecureProxy(obj) {
436
+ if (obj === null || typeof obj !== "object") {
437
+ return false;
438
+ }
439
+ return proxySet.has(obj);
440
+ }
441
+ 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;
442
+ var init_secure_proxy = __esm({
443
+ "libs/core/src/secure-proxy.ts"() {
444
+ "use strict";
445
+ init_safe_error();
446
+ MIN_MEMBRANE_RECURSION_DEPTH = 256;
447
+ BLOCKED_PROPERTY_CATEGORIES = {
448
+ /**
449
+ * Core prototype manipulation properties (always blocked except PERMISSIVE)
450
+ */
451
+ PROTOTYPE: /* @__PURE__ */ new Set([
452
+ "constructor",
453
+ "__proto__",
454
+ "prototype",
455
+ "__defineGetter__",
456
+ "__defineSetter__",
457
+ "__lookupGetter__",
458
+ "__lookupSetter__"
459
+ ]),
460
+ /**
461
+ * Node.js 24 Iterator helper method names
462
+ * Blocked at STRICT/SECURE to prevent prototype chain access via iterators
463
+ */
464
+ ITERATOR_HELPERS: /* @__PURE__ */ new Set(["toArray", "forEach", "some", "every", "find", "reduce", "flatMap", "drop", "take"]),
465
+ /**
466
+ * Reflection properties on Object
467
+ * Blocked at STRICT to prevent introspection attacks
468
+ */
469
+ REFLECTION: /* @__PURE__ */ new Set([
470
+ "getOwnPropertyDescriptor",
471
+ "getOwnPropertyDescriptors",
472
+ "getOwnPropertyNames",
473
+ "getOwnPropertySymbols",
474
+ "getPrototypeOf",
475
+ "setPrototypeOf",
476
+ "defineProperty",
477
+ "defineProperties",
478
+ "preventExtensions",
479
+ "isExtensible",
480
+ "seal",
481
+ "isSealed",
482
+ "freeze",
483
+ "isFrozen"
484
+ ]),
485
+ /**
486
+ * Timing API properties
487
+ * Blocked at STRICT to prevent timing attacks
488
+ */
489
+ TIMING: /* @__PURE__ */ new Set(["hrtime", "timeOrigin"])
490
+ };
491
+ BLOCKED_PROPERTIES = /* @__PURE__ */ new Set([
492
+ // Code execution
493
+ "constructor",
494
+ // Prototype manipulation
495
+ "__proto__",
496
+ "prototype",
497
+ // Legacy getter/setter definition
498
+ "__defineGetter__",
499
+ "__defineSetter__",
500
+ "__lookupGetter__",
501
+ "__lookupSetter__"
502
+ ]);
503
+ DEFAULT_SECURE_PROXY_CONFIG = {
504
+ blockConstructor: true,
505
+ blockPrototype: true,
506
+ blockLegacyAccessors: true,
507
+ proxyMaxDepth: 10,
508
+ throwOnBlocked: true
509
+ };
510
+ FUNCTION_BLOCKED_PROPERTIES = /* @__PURE__ */ new Set([
511
+ // Function object properties that could leak information
512
+ "caller",
513
+ // Deprecated but still exists
514
+ "arguments"
515
+ // Deprecated but still exists
516
+ // Binding/applying could be used for exploitation
517
+ // Note: We may want to allow these in some cases
518
+ // 'bind',
519
+ // 'call',
520
+ // 'apply',
521
+ ]);
522
+ proxyCache = /* @__PURE__ */ new WeakMap();
523
+ proxySet = /* @__PURE__ */ new WeakSet();
524
+ proxyToTarget = /* @__PURE__ */ new WeakMap();
525
+ NON_PROXYABLE_TYPES = /* @__PURE__ */ new Set([
526
+ // Map/Set have internal slots but we may need to proxy them in the future
527
+ "[object Map]",
528
+ "[object Set]",
529
+ "[object WeakMap]",
530
+ "[object WeakSet]",
531
+ "[object ArrayBuffer]",
532
+ "[object SharedArrayBuffer]",
533
+ "[object DataView]",
534
+ "[object Int8Array]",
535
+ "[object Uint8Array]",
536
+ "[object Uint8ClampedArray]",
537
+ "[object Int16Array]",
538
+ "[object Uint16Array]",
539
+ "[object Int32Array]",
540
+ "[object Uint32Array]",
541
+ "[object Float32Array]",
542
+ "[object Float64Array]",
543
+ "[object BigInt64Array]",
544
+ "[object BigUint64Array]",
545
+ // Generators and iterators use internal slots
546
+ "[object Generator]",
547
+ "[object AsyncGenerator]",
548
+ "[object GeneratorFunction]",
549
+ "[object AsyncGeneratorFunction]",
550
+ // Built-in iterators
551
+ "[object Array Iterator]",
552
+ "[object String Iterator]",
553
+ "[object Map Iterator]",
554
+ "[object Set Iterator]",
555
+ "[object RegExp String Iterator]"
556
+ ]);
557
+ INTERNAL_SLOT_TYPES = /* @__PURE__ */ new Set(["[object Promise]"]);
558
+ }
559
+ });
560
+
11
561
  // libs/core/src/sidecar/reference-config.ts
12
562
  function isReferenceId(value) {
13
563
  return typeof value === "string" && REF_ID_PATTERN.test(value);
@@ -123,15 +673,42 @@ var init_reference_config = __esm({
123
673
  });
124
674
 
125
675
  // libs/core/src/sidecar/reference-resolver.ts
676
+ function untrustedLength(value) {
677
+ const rawLen = ReflectGet(value, "length");
678
+ if (typeof rawLen !== "number" || !NumberIsFinite(rawLen) || rawLen < 0) {
679
+ return 0;
680
+ }
681
+ const len = MathFloor(rawLen);
682
+ if (len > MAX_TRAVERSAL_LENGTH) {
683
+ throw new ResolutionLimitError(
684
+ `Array length ${len} exceeds maximum traversal limit (${MAX_TRAVERSAL_LENGTH})`,
685
+ "MAX_TRAVERSAL_LENGTH",
686
+ MAX_TRAVERSAL_LENGTH,
687
+ len
688
+ );
689
+ }
690
+ return len;
691
+ }
692
+ function untrustedAt(value, index) {
693
+ try {
694
+ return ReflectGet(value, index);
695
+ } catch {
696
+ return void 0;
697
+ }
698
+ }
126
699
  function isCompositeHandle(value) {
127
700
  const obj = value;
128
701
  return typeof value === "object" && value !== null && obj["__type"] === "composite" && Array.isArray(obj["__parts"]);
129
702
  }
130
- var ResolutionLimitError, ReferenceResolver;
703
+ var ReflectGet, NumberIsFinite, MathFloor, MAX_TRAVERSAL_LENGTH, ResolutionLimitError, ReferenceResolver;
131
704
  var init_reference_resolver = __esm({
132
705
  "libs/core/src/sidecar/reference-resolver.ts"() {
133
706
  "use strict";
134
707
  init_reference_config();
708
+ ReflectGet = Reflect.get;
709
+ NumberIsFinite = Number.isFinite;
710
+ MathFloor = Math.floor;
711
+ MAX_TRAVERSAL_LENGTH = 1e6;
135
712
  ResolutionLimitError = class _ResolutionLimitError extends Error {
136
713
  constructor(message, code, limit, actual) {
137
714
  super(message);
@@ -175,17 +752,24 @@ var init_reference_resolver = __esm({
175
752
  return size;
176
753
  }
177
754
  if (isCompositeHandle(value)) {
178
- return value.__parts.reduce((sum, part) => {
179
- return sum + this.predictExpandedSize(part, depth + 1);
180
- }, 0);
755
+ const parts = value.__parts;
756
+ const len = untrustedLength(parts);
757
+ let sum = 0;
758
+ for (let i = 0; i < len; i++) {
759
+ sum += this.predictExpandedSize(untrustedAt(parts, i), depth + 1);
760
+ }
761
+ return sum;
181
762
  }
182
763
  if (typeof value === "string") {
183
764
  return Buffer.byteLength(value, "utf-8");
184
765
  }
185
766
  if (Array.isArray(value)) {
186
- return value.reduce((sum, item) => {
187
- return sum + this.predictExpandedSize(item, depth + 1);
188
- }, 0);
767
+ const len = untrustedLength(value);
768
+ let sum = 0;
769
+ for (let i = 0; i < len; i++) {
770
+ sum += this.predictExpandedSize(untrustedAt(value, i), depth + 1);
771
+ }
772
+ return sum;
189
773
  }
190
774
  if (value !== null && typeof value === "object") {
191
775
  return Object.values(value).reduce((sum, val) => {
@@ -246,7 +830,12 @@ var init_reference_resolver = __esm({
246
830
  return value;
247
831
  }
248
832
  if (Array.isArray(value)) {
249
- return value.map((item) => this.resolve(item, depth + 1));
833
+ const len = untrustedLength(value);
834
+ const out = [];
835
+ for (let i = 0; i < len; i++) {
836
+ out[i] = this.resolve(untrustedAt(value, i), depth + 1);
837
+ }
838
+ return out;
250
839
  }
251
840
  if (value !== null && typeof value === "object") {
252
841
  const resolved = /* @__PURE__ */ Object.create(null);
@@ -261,15 +850,17 @@ var init_reference_resolver = __esm({
261
850
  * Resolve a composite handle by concatenating its parts
262
851
  */
263
852
  resolveComposite(handle, depth) {
264
- const parts = [];
265
- for (const part of handle.__parts) {
266
- const resolved = this.resolve(part, depth + 1);
853
+ const out = [];
854
+ const source = handle.__parts;
855
+ const len = untrustedLength(source);
856
+ for (let i = 0; i < len; i++) {
857
+ const resolved = this.resolve(untrustedAt(source, i), depth + 1);
267
858
  if (typeof resolved !== "string") {
268
859
  throw new Error(`Composite part resolved to non-string: ${typeof resolved}`);
269
860
  }
270
- parts.push(resolved);
861
+ out.push(resolved);
271
862
  }
272
- return parts.join("");
863
+ return out.join("");
273
864
  }
274
865
  /**
275
866
  * Check if a value contains any reference IDs
@@ -286,7 +877,13 @@ var init_reference_resolver = __esm({
286
877
  return true;
287
878
  }
288
879
  if (Array.isArray(value)) {
289
- return value.some((item) => this.containsReferences(item, depth + 1));
880
+ const len = untrustedLength(value);
881
+ for (let i = 0; i < len; i++) {
882
+ if (this.containsReferences(untrustedAt(value, i), depth + 1)) {
883
+ return true;
884
+ }
885
+ }
886
+ return false;
290
887
  }
291
888
  if (value !== null && typeof value === "object") {
292
889
  return Object.values(value).some((val) => this.containsReferences(val, depth + 1));
@@ -379,35 +976,53 @@ function sanitizeValue(value, options = {}, depth = 0, context = { propCount: {
379
976
  }
380
977
  context.visited.add(value);
381
978
  }
382
- if (Array.isArray(value)) {
383
- context.propCount.count += value.length;
979
+ if (ArrayIsArray(value)) {
980
+ const rawLen = ReflectGet2(value, "length");
981
+ const len = typeof rawLen === "number" && NumberIsFinite2(rawLen) && rawLen >= 0 ? MathFloor2(rawLen) : 0;
982
+ context.propCount.count += len;
384
983
  if (context.propCount.count > maxProperties) {
385
984
  throw new Error(`Tool handler return value exceeds maximum properties (${maxProperties}).`);
386
985
  }
387
- return value.map((item) => sanitizeValue(item, options, depth + 1, context));
986
+ const result = [];
987
+ for (let i = 0; i < len; i++) {
988
+ let item;
989
+ try {
990
+ item = ReflectGet2(value, i);
991
+ } catch {
992
+ item = void 0;
993
+ }
994
+ result[i] = sanitizeValue(item, options, depth + 1, context);
995
+ }
996
+ return result;
388
997
  }
389
998
  if (value instanceof Date) {
999
+ const time = ReflectApply(DateProtoGetTime, value, []);
390
1000
  if (allowDates) {
391
- return new Date(value.getTime());
1001
+ return new Date(time);
392
1002
  }
393
- return value.toISOString();
1003
+ return ReflectApply(DateProtoToISOString, value, []);
394
1004
  }
395
1005
  if (value instanceof Error) {
1006
+ const rawName = ReflectGet2(value, "name");
1007
+ const rawMessage = ReflectGet2(value, "message");
1008
+ const name = typeof rawName === "string" ? rawName : "Error";
1009
+ const message = typeof rawMessage === "string" ? rawMessage : "";
396
1010
  if (allowErrors) {
397
1011
  return {
398
- name: value.name,
399
- message: value.message
1012
+ name,
1013
+ message
400
1014
  // Do NOT include stack trace - could leak host information
401
1015
  };
402
1016
  }
403
- return { error: value.message };
1017
+ return { error: message };
404
1018
  }
405
1019
  if (value instanceof RegExp) {
406
- return value.toString();
1020
+ return ReflectApply(RegExpProtoToString, value, []);
407
1021
  }
408
1022
  if (value instanceof Map) {
409
- const sanitizedMap = /* @__PURE__ */ Object.create(null);
410
- for (const [key, val] of value.entries()) {
1023
+ const sanitizedMap = ObjectCreate(null);
1024
+ const entries = ReflectApply(MapProtoEntries, value, []);
1025
+ for (const [key, val] of entries) {
411
1026
  if (typeof key !== "string") continue;
412
1027
  if (DANGEROUS_KEYS.has(key)) continue;
413
1028
  context.propCount.count++;
@@ -416,13 +1031,17 @@ function sanitizeValue(value, options = {}, depth = 0, context = { propCount: {
416
1031
  return sanitizedMap;
417
1032
  }
418
1033
  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));
1034
+ const iter = ReflectApply(SetProtoValues, value, []);
1035
+ const result = [];
1036
+ for (const item of iter) {
1037
+ context.propCount.count++;
1038
+ result.push(sanitizeValue(item, options, depth + 1, context));
1039
+ }
1040
+ return result;
422
1041
  }
423
1042
  if (type === "object") {
424
- const sanitized = /* @__PURE__ */ Object.create(null);
425
- const keys = Object.keys(value);
1043
+ const sanitized = ObjectCreate(null);
1044
+ const keys = ObjectKeys(value);
426
1045
  context.propCount.count += keys.length;
427
1046
  if (context.propCount.count > maxProperties) {
428
1047
  throw new Error(`Tool handler return value exceeds maximum properties (${maxProperties}).`);
@@ -433,7 +1052,7 @@ function sanitizeValue(value, options = {}, depth = 0, context = { propCount: {
433
1052
  }
434
1053
  let propValue;
435
1054
  try {
436
- propValue = value[key];
1055
+ propValue = ReflectGet2(value, key);
437
1056
  } catch {
438
1057
  continue;
439
1058
  }
@@ -441,636 +1060,153 @@ function sanitizeValue(value, options = {}, depth = 0, context = { propCount: {
441
1060
  }
442
1061
  return sanitized;
443
1062
  }
444
- return String(value);
445
- }
446
- function estimateStringSize(str) {
447
- let bytes = 2;
448
- for (let i = 0; i < str.length; i++) {
449
- const code = str.charCodeAt(i);
450
- if (code < 128) {
451
- if (code === 34 || code === 92) {
452
- bytes += 2;
453
- } else if (code < 32) {
454
- bytes += 6;
455
- } else {
456
- bytes += 1;
457
- }
458
- } else if (code < 2048) {
459
- bytes += 2;
460
- } else if (code >= 55296 && code <= 56319 && i + 1 < str.length) {
461
- const nextCode = str.charCodeAt(i + 1);
462
- if (nextCode >= 56320 && nextCode <= 57343) {
463
- bytes += 4;
464
- i++;
465
- } else {
466
- bytes += 3;
467
- }
468
- } else {
469
- bytes += 3;
470
- }
471
- }
472
- return bytes;
473
- }
474
- function estimateSerializedSize(value, maxBytes = 0, depth = 0, maxDepth = 2e3, currentPath = /* @__PURE__ */ new Set()) {
475
- if (depth > maxDepth) {
476
- throw new Error(
477
- `Structure exceeds maximum nesting depth (${maxDepth}). Deeply nested structures are rejected to prevent stack overflow attacks.`
478
- );
479
- }
480
- if (value === null) return 4;
481
- if (value === void 0) return 0;
482
- const type = typeof value;
483
- if (type === "string") {
484
- const bytes = estimateStringSize(value);
485
- if (maxBytes > 0 && bytes > maxBytes) {
486
- throw new Error(`String serialization would exceed limit: ${bytes} > ${maxBytes} bytes`);
487
- }
488
- return bytes;
489
- }
490
- if (type === "number") {
491
- const num = value;
492
- if (!Number.isFinite(num)) return 4;
493
- return String(num).length;
494
- }
495
- if (type === "boolean") {
496
- return value ? 4 : 5;
497
- }
498
- if (type === "bigint") {
499
- return String(value).length + 2;
500
- }
501
- if (type === "function" || type === "symbol") {
502
- return 0;
503
- }
504
- if (Array.isArray(value)) {
505
- if (currentPath.has(value)) {
506
- return 4;
507
- }
508
- currentPath.add(value);
509
- let size = 2;
510
- for (let i = 0; i < value.length; i++) {
511
- if (i > 0) size += 1;
512
- let elementSize = estimateSerializedSize(value[i], maxBytes, depth + 1, maxDepth, currentPath);
513
- if (elementSize === 0) elementSize = 4;
514
- size += elementSize;
515
- if (maxBytes > 0 && size > maxBytes) {
516
- currentPath.delete(value);
517
- throw new Error(
518
- `Array serialization would exceed limit: estimated ${size}+ > ${maxBytes} bytes. This often indicates repeated references to large strings that expand during JSON serialization.`
519
- );
520
- }
521
- }
522
- currentPath.delete(value);
523
- return size;
524
- }
525
- if (type === "object" && value !== null) {
526
- if (currentPath.has(value)) {
527
- return 4;
528
- }
529
- currentPath.add(value);
530
- if (value instanceof Date) {
531
- currentPath.delete(value);
532
- return 26;
533
- }
534
- if (value instanceof RegExp) {
535
- currentPath.delete(value);
536
- return 2;
537
- }
538
- let size = 2;
539
- const keys = Object.keys(value);
540
- let first = true;
541
- for (const key of keys) {
542
- if (key === "__proto__" || key === "constructor") continue;
543
- if (!first) size += 1;
544
- first = false;
545
- size += estimateStringSize(key) + 1;
546
- let propValue;
547
- try {
548
- propValue = value[key];
549
- } catch {
550
- continue;
551
- }
552
- const valueSize = estimateSerializedSize(propValue, maxBytes, depth + 1, maxDepth, currentPath);
553
- size += valueSize;
554
- if (maxBytes > 0 && size > maxBytes) {
555
- currentPath.delete(value);
556
- throw new Error(
557
- `Object serialization would exceed limit: estimated ${size}+ > ${maxBytes} bytes. This often indicates repeated references to large strings that expand during JSON serialization.`
558
- );
559
- }
560
- }
561
- currentPath.delete(value);
562
- return size;
563
- }
564
- return 0;
565
- }
566
- function checkSerializedSize(value, maxBytes) {
567
- try {
568
- const estimatedBytes = estimateSerializedSize(value, maxBytes);
569
- return { ok: true, estimatedBytes };
570
- } catch (err) {
571
- return { ok: false, error: err instanceof Error ? err.message : "Unknown error" };
572
- }
573
- }
574
- var DANGEROUS_KEYS;
575
- var init_value_sanitizer = __esm({
576
- "libs/core/src/value-sanitizer.ts"() {
577
- "use strict";
578
- DANGEROUS_KEYS = /* @__PURE__ */ new Set(["__proto__", "constructor"]);
579
- }
580
- });
581
-
582
- // libs/core/src/safe-error.ts
583
- function createSafeError(message, name = "Error") {
584
- const error = new Error(message);
585
- error.name = name;
586
- const SafeConstructor = /* @__PURE__ */ Object.create(null);
587
- Object.defineProperties(SafeConstructor, {
588
- constructor: {
589
- value: SafeConstructor,
590
- writable: false,
591
- enumerable: false,
592
- configurable: false
593
- },
594
- prototype: {
595
- value: null,
596
- writable: false,
597
- enumerable: false,
598
- configurable: false
599
- },
600
- name: {
601
- value: "SafeError",
602
- writable: false,
603
- enumerable: false,
604
- configurable: false
605
- }
606
- });
607
- Object.freeze(SafeConstructor);
608
- Object.setPrototypeOf(error, null);
609
- Object.defineProperty(error, "constructor", {
610
- value: SafeConstructor,
611
- writable: false,
612
- enumerable: false,
613
- configurable: false
614
- });
615
- Object.defineProperty(error, "__proto__", {
616
- value: null,
617
- writable: false,
618
- enumerable: false,
619
- configurable: false
620
- });
621
- Object.defineProperty(error, "stack", {
622
- value: void 0,
623
- writable: false,
624
- enumerable: false,
625
- configurable: false
626
- });
627
- Object.freeze(error);
628
- return error;
629
- }
630
- function createSafeTypeError(message) {
631
- return createSafeError(message, "TypeError");
632
- }
633
- var init_safe_error = __esm({
634
- "libs/core/src/safe-error.ts"() {
635
- "use strict";
636
- }
637
- });
638
-
639
- // libs/core/src/secure-proxy.ts
640
- function getBlockedPropertiesForLevel(level) {
641
- const blocked = /* @__PURE__ */ new Set();
642
- if (level !== "PERMISSIVE") {
643
- BLOCKED_PROPERTY_CATEGORIES.PROTOTYPE.forEach((p) => blocked.add(p));
644
- }
645
- switch (level) {
646
- case "STRICT":
647
- BLOCKED_PROPERTY_CATEGORIES.ITERATOR_HELPERS.forEach((p) => blocked.add(p));
648
- BLOCKED_PROPERTY_CATEGORIES.REFLECTION.forEach((p) => blocked.add(p));
649
- BLOCKED_PROPERTY_CATEGORIES.TIMING.forEach((p) => blocked.add(p));
650
- break;
651
- case "SECURE":
652
- BLOCKED_PROPERTY_CATEGORIES.ITERATOR_HELPERS.forEach((p) => blocked.add(p));
653
- break;
654
- case "STANDARD":
655
- case "PERMISSIVE":
656
- break;
657
- }
658
- return blocked;
659
- }
660
- function buildBlockedPropertiesFromConfig(config) {
661
- const blocked = /* @__PURE__ */ new Set();
662
- if (config.blockConstructor) {
663
- blocked.add("constructor");
664
- }
665
- if (config.blockPrototype) {
666
- blocked.add("__proto__");
667
- blocked.add("prototype");
668
- }
669
- if (config.blockLegacyAccessors) {
670
- blocked.add("__defineGetter__");
671
- blocked.add("__defineSetter__");
672
- blocked.add("__lookupGetter__");
673
- blocked.add("__lookupSetter__");
674
- }
675
- return blocked;
676
- }
677
- function createSafeReflect(securityLevel) {
678
- if (securityLevel === "STRICT") {
679
- return void 0;
680
- }
681
- const dangerousMethods = /* @__PURE__ */ new Set(["setPrototypeOf"]);
682
- if (securityLevel === "SECURE") {
683
- dangerousMethods.add("apply");
684
- dangerousMethods.add("defineProperty");
685
- }
686
- return new Proxy(Reflect, {
687
- get(target, prop) {
688
- if (typeof prop === "string" && dangerousMethods.has(prop)) {
689
- return void 0;
1063
+ return String(value);
1064
+ }
1065
+ function estimateStringSize(str) {
1066
+ let bytes = 2;
1067
+ for (let i = 0; i < str.length; i++) {
1068
+ const code = str.charCodeAt(i);
1069
+ if (code < 128) {
1070
+ if (code === 34 || code === 92) {
1071
+ bytes += 2;
1072
+ } else if (code < 32) {
1073
+ bytes += 6;
1074
+ } else {
1075
+ bytes += 1;
690
1076
  }
691
- const value = Reflect.get(target, prop);
692
- if (typeof value === "function" && prop === "construct") {
693
- return function(ctorTarget, args, newTarget) {
694
- const AsyncFunction = async function() {
695
- }.constructor;
696
- const GeneratorFunction = function* () {
697
- }.constructor;
698
- const AsyncGeneratorFunction = async function* () {
699
- }.constructor;
700
- if (ctorTarget === Function || ctorTarget === AsyncFunction || ctorTarget === GeneratorFunction || ctorTarget === AsyncGeneratorFunction) {
701
- throw createSafeError("Reflect.construct with function constructors is blocked", "SecurityError");
702
- }
703
- return Reflect.construct(
704
- ctorTarget,
705
- args,
706
- newTarget
707
- );
708
- };
1077
+ } else if (code < 2048) {
1078
+ bytes += 2;
1079
+ } else if (code >= 55296 && code <= 56319 && i + 1 < str.length) {
1080
+ const nextCode = str.charCodeAt(i + 1);
1081
+ if (nextCode >= 56320 && nextCode <= 57343) {
1082
+ bytes += 4;
1083
+ i++;
1084
+ } else {
1085
+ bytes += 3;
709
1086
  }
710
- return value;
1087
+ } else {
1088
+ bytes += 3;
711
1089
  }
712
- });
1090
+ }
1091
+ return bytes;
713
1092
  }
714
- function getFullCacheKey(options) {
715
- const parts = [];
716
- if (options.levelConfig) {
717
- const cfg = options.levelConfig;
718
- parts.push(
719
- `L:${cfg.blockConstructor ? "C" : "c"}${cfg.blockPrototype ? "P" : "p"}${cfg.blockLegacyAccessors ? "L" : "l"}`
1093
+ function estimateSerializedSize(value, maxBytes = 0, depth = 0, maxDepth = 2e3, currentPath = /* @__PURE__ */ new Set()) {
1094
+ if (depth > maxDepth) {
1095
+ throw new Error(
1096
+ `Structure exceeds maximum nesting depth (${maxDepth}). Deeply nested structures are rejected to prevent stack overflow attacks.`
720
1097
  );
721
- } else {
722
- parts.push("L:default");
723
- }
724
- if (options.additionalBlocked && options.additionalBlocked.length > 0) {
725
- parts.push(`B:${[...options.additionalBlocked].sort().join(",")}`);
726
1098
  }
727
- const effectiveMaxDepth = options.maxDepth ?? options.levelConfig?.proxyMaxDepth ?? 10;
728
- if (effectiveMaxDepth !== 10) {
729
- parts.push(`D:${effectiveMaxDepth}`);
1099
+ if (value === null) return 4;
1100
+ if (value === void 0) return 0;
1101
+ const type = typeof value;
1102
+ if (type === "string") {
1103
+ const bytes = estimateStringSize(value);
1104
+ if (maxBytes > 0 && bytes > maxBytes) {
1105
+ throw new Error(`String serialization would exceed limit: ${bytes} > ${maxBytes} bytes`);
1106
+ }
1107
+ return bytes;
730
1108
  }
731
- if (options.throwOnBlocked) {
732
- parts.push("T:1");
1109
+ if (type === "number") {
1110
+ const num = value;
1111
+ if (!Number.isFinite(num)) return 4;
1112
+ return String(num).length;
733
1113
  }
734
- return parts.join("|") || "default";
735
- }
736
- function isProxyable(value) {
737
- if (value === null) return false;
738
- if (typeof value !== "object" && typeof value !== "function") return false;
739
- const tag = Object.prototype.toString.call(value);
740
- if (NON_PROXYABLE_TYPES.has(tag)) {
741
- return false;
1114
+ if (type === "boolean") {
1115
+ return value ? 4 : 5;
742
1116
  }
743
- return true;
744
- }
745
- function createSecureProxy(target, options = {}) {
746
- if (!isProxyable(target)) {
747
- return target;
1117
+ if (type === "bigint") {
1118
+ return String(value).length + 2;
748
1119
  }
749
- const cacheKey = getFullCacheKey(options);
750
- const targetCache = proxyCache.get(target);
751
- if (targetCache) {
752
- const cached = targetCache.get(cacheKey);
753
- if (cached) {
754
- return cached;
755
- }
1120
+ if (type === "function" || type === "symbol") {
1121
+ return 0;
756
1122
  }
757
- const baseBlocked = options.levelConfig ? buildBlockedPropertiesFromConfig(options.levelConfig) : new Set(BLOCKED_PROPERTIES);
758
- const blockedSet = /* @__PURE__ */ new Set([...baseBlocked, ...options.additionalBlocked || []]);
759
- const maxDepth = options.maxDepth ?? options.levelConfig?.proxyMaxDepth ?? 10;
760
- const throwOnBlocked = options.throwOnBlocked ?? options.levelConfig?.throwOnBlocked ?? false;
761
- function proxyWithDepth(obj, depth) {
762
- if (!isProxyable(obj)) {
763
- return obj;
764
- }
765
- const objCache = proxyCache.get(obj);
766
- if (objCache) {
767
- const cachedProxy = objCache.get(cacheKey);
768
- if (cachedProxy) {
769
- return cachedProxy;
770
- }
771
- }
772
- if (depth > maxDepth) {
773
- return obj;
1123
+ if (Array.isArray(value)) {
1124
+ if (currentPath.has(value)) {
1125
+ return 4;
774
1126
  }
775
- const proxy = new Proxy(obj, {
776
- get(target2, property, receiver) {
777
- const propName = typeof property === "symbol" ? property.toString() : property;
778
- const descriptor = Object.getOwnPropertyDescriptor(target2, property);
779
- const isNonConfigurable = descriptor && !descriptor.configurable;
780
- if (typeof propName === "string" && blockedSet.has(propName)) {
781
- if (options.onBlocked) {
782
- options.onBlocked(target2, propName);
783
- }
784
- if (isNonConfigurable && descriptor && !descriptor.writable) {
785
- return Reflect.get(target2, property, receiver);
786
- }
787
- if (throwOnBlocked) {
788
- throw createSafeError(
789
- `Security violation: Access to '${propName}' is blocked. This property can be used for sandbox escape attacks.`,
790
- "SecurityError"
791
- );
792
- }
793
- return void 0;
794
- }
795
- if (typeof target2 === "function" && typeof propName === "string" && FUNCTION_BLOCKED_PROPERTIES.has(propName)) {
796
- if (options.onBlocked) {
797
- options.onBlocked(target2, propName);
798
- }
799
- if (isNonConfigurable && descriptor && !descriptor.writable) {
800
- return Reflect.get(target2, property, receiver);
801
- }
802
- if (throwOnBlocked) {
803
- throw createSafeError(
804
- `Security violation: Access to '${propName}' is blocked. This property can be used for sandbox escape attacks.`,
805
- "SecurityError"
806
- );
807
- }
808
- return void 0;
809
- }
810
- const value = Reflect.get(target2, property, receiver);
811
- if (typeof value === "function") {
812
- const tag = Object.prototype.toString.call(target2);
813
- if (INTERNAL_SLOT_TYPES.has(tag)) {
814
- const boundMethod = value.bind(target2);
815
- return proxyWithDepth(boundMethod, depth + 1);
816
- }
817
- }
818
- if (value !== null && (typeof value === "object" || typeof value === "function")) {
819
- return proxyWithDepth(value, depth + 1);
820
- }
821
- return value;
822
- },
823
- // Block setting dangerous properties
824
- set(target2, property, value, receiver) {
825
- const propName = typeof property === "symbol" ? property.toString() : property;
826
- if (typeof propName === "string" && blockedSet.has(propName)) {
827
- if (options.onBlocked) {
828
- options.onBlocked(target2, propName);
829
- }
830
- if (throwOnBlocked) {
831
- throw createSafeError(
832
- `Security violation: Setting '${propName}' is blocked. This property can be used for sandbox escape attacks.`,
833
- "SecurityError"
834
- );
835
- }
836
- return false;
837
- }
838
- return Reflect.set(target2, property, value, receiver);
839
- },
840
- // Block defining dangerous properties
841
- defineProperty(target2, property, descriptor) {
842
- const propName = typeof property === "symbol" ? property.toString() : property;
843
- if (typeof propName === "string" && blockedSet.has(propName)) {
844
- if (options.onBlocked) {
845
- options.onBlocked(target2, propName);
846
- }
847
- if (throwOnBlocked) {
848
- throw createSafeError(
849
- `Security violation: Defining '${propName}' is blocked. This property can be used for sandbox escape attacks.`,
850
- "SecurityError"
851
- );
852
- }
853
- return false;
854
- }
855
- return Reflect.defineProperty(target2, property, descriptor);
856
- },
857
- // Filter blocked property names from enumeration (Object.keys, Object.entries, etc.)
858
- // Must respect proxy invariants: non-configurable own properties cannot be hidden
859
- ownKeys(target2) {
860
- const keys = Reflect.ownKeys(target2);
861
- return keys.filter((key) => {
862
- const keyStr = typeof key === "symbol" ? key.toString() : key;
863
- if (typeof keyStr !== "string" || !blockedSet.has(keyStr)) {
864
- return true;
865
- }
866
- const descriptor = Object.getOwnPropertyDescriptor(target2, key);
867
- if (descriptor && !descriptor.configurable) {
868
- return true;
869
- }
870
- return false;
871
- });
872
- },
873
- // Hide blocked properties from property descriptor queries (defense-in-depth)
874
- // Must respect proxy invariants: non-configurable properties must return actual descriptor
875
- getOwnPropertyDescriptor(target2, property) {
876
- const propName = typeof property === "symbol" ? property.toString() : property;
877
- const descriptor = Reflect.getOwnPropertyDescriptor(target2, property);
878
- if (descriptor && !descriptor.configurable) {
879
- return descriptor;
880
- }
881
- if (typeof propName === "string" && blockedSet.has(propName)) {
882
- if (options.onBlocked) {
883
- options.onBlocked(target2, propName);
884
- }
885
- if (throwOnBlocked) {
886
- throw createSafeError(
887
- `Security violation: Access to property descriptor for '${propName}' is blocked. This property can be used for sandbox escape attacks.`,
888
- "SecurityError"
889
- );
890
- }
891
- return void 0;
892
- }
893
- return descriptor;
894
- },
895
- // Block getPrototypeOf to prevent prototype chain walking
896
- getPrototypeOf() {
897
- return null;
898
- },
899
- // Block setPrototypeOf
900
- setPrototypeOf() {
901
- return false;
902
- },
903
- // Intercept function calls to proxy return values
904
- // eslint-disable-next-line @typescript-eslint/no-explicit-any -- Proxy handler signature requires any for compatibility
905
- apply(target2, thisArg, argArray) {
906
- const result = Reflect.apply(target2, thisArg, argArray);
907
- if (isProxyable(result)) {
908
- return proxyWithDepth(result, depth + 1);
909
- }
910
- return result;
1127
+ currentPath.add(value);
1128
+ let size = 2;
1129
+ for (let i = 0; i < value.length; i++) {
1130
+ if (i > 0) size += 1;
1131
+ let elementSize = estimateSerializedSize(value[i], maxBytes, depth + 1, maxDepth, currentPath);
1132
+ if (elementSize === 0) elementSize = 4;
1133
+ size += elementSize;
1134
+ if (maxBytes > 0 && size > maxBytes) {
1135
+ currentPath.delete(value);
1136
+ throw new Error(
1137
+ `Array serialization would exceed limit: estimated ${size}+ > ${maxBytes} bytes. This often indicates repeated references to large strings that expand during JSON serialization.`
1138
+ );
911
1139
  }
912
- });
913
- let objCacheMap = proxyCache.get(obj);
914
- if (!objCacheMap) {
915
- objCacheMap = /* @__PURE__ */ new Map();
916
- proxyCache.set(obj, objCacheMap);
917
1140
  }
918
- objCacheMap.set(cacheKey, proxy);
919
- proxySet.add(proxy);
920
- return proxy;
1141
+ currentPath.delete(value);
1142
+ return size;
921
1143
  }
922
- return proxyWithDepth(target, 0);
923
- }
924
- function wrapGlobalsWithSecureProxy(globals, options = {}) {
925
- const wrapped = {};
926
- for (const [key, value] of Object.entries(globals)) {
927
- if (value !== null && (typeof value === "object" || typeof value === "function")) {
928
- wrapped[key] = createSecureProxy(value, options);
929
- } else {
930
- wrapped[key] = value;
1144
+ if (type === "object" && value !== null) {
1145
+ if (currentPath.has(value)) {
1146
+ return 4;
1147
+ }
1148
+ currentPath.add(value);
1149
+ if (value instanceof Date) {
1150
+ currentPath.delete(value);
1151
+ return 26;
1152
+ }
1153
+ if (value instanceof RegExp) {
1154
+ currentPath.delete(value);
1155
+ return 2;
1156
+ }
1157
+ let size = 2;
1158
+ const keys = Object.keys(value);
1159
+ let first = true;
1160
+ for (const key of keys) {
1161
+ if (key === "__proto__" || key === "constructor") continue;
1162
+ if (!first) size += 1;
1163
+ first = false;
1164
+ size += estimateStringSize(key) + 1;
1165
+ let propValue;
1166
+ try {
1167
+ propValue = value[key];
1168
+ } catch {
1169
+ continue;
1170
+ }
1171
+ const valueSize = estimateSerializedSize(propValue, maxBytes, depth + 1, maxDepth, currentPath);
1172
+ size += valueSize;
1173
+ if (maxBytes > 0 && size > maxBytes) {
1174
+ currentPath.delete(value);
1175
+ throw new Error(
1176
+ `Object serialization would exceed limit: estimated ${size}+ > ${maxBytes} bytes. This often indicates repeated references to large strings that expand during JSON serialization.`
1177
+ );
1178
+ }
931
1179
  }
1180
+ currentPath.delete(value);
1181
+ return size;
932
1182
  }
933
- return wrapped;
934
- }
935
- function createSecureStandardLibrary(options = {}) {
936
- return wrapGlobalsWithSecureProxy(
937
- {
938
- Math,
939
- JSON,
940
- Array,
941
- Object,
942
- String,
943
- Number,
944
- Date
945
- // Note: We intentionally don't include:
946
- // - Function (dangerous)
947
- // - eval (dangerous)
948
- // - Proxy, Reflect (meta-programming)
949
- },
950
- options
951
- );
1183
+ return 0;
952
1184
  }
953
- function isSecureProxy(obj) {
954
- if (obj === null || typeof obj !== "object") {
955
- return false;
1185
+ function checkSerializedSize(value, maxBytes) {
1186
+ try {
1187
+ const estimatedBytes = estimateSerializedSize(value, maxBytes);
1188
+ return { ok: true, estimatedBytes };
1189
+ } catch (err) {
1190
+ return { ok: false, error: err instanceof Error ? err.message : "Unknown error" };
956
1191
  }
957
- return proxySet.has(obj);
958
1192
  }
959
- var BLOCKED_PROPERTY_CATEGORIES, BLOCKED_PROPERTIES, DEFAULT_SECURE_PROXY_CONFIG, FUNCTION_BLOCKED_PROPERTIES, proxyCache, proxySet, NON_PROXYABLE_TYPES, INTERNAL_SLOT_TYPES;
960
- var init_secure_proxy = __esm({
961
- "libs/core/src/secure-proxy.ts"() {
1193
+ var DANGEROUS_KEYS, ReflectApply, ReflectGet2, ArrayIsArray, ObjectKeys, ObjectCreate, NumberIsFinite2, MathFloor2, MapProtoEntries, SetProtoValues, DateProtoGetTime, DateProtoToISOString, RegExpProtoToString;
1194
+ var init_value_sanitizer = __esm({
1195
+ "libs/core/src/value-sanitizer.ts"() {
962
1196
  "use strict";
963
- init_safe_error();
964
- BLOCKED_PROPERTY_CATEGORIES = {
965
- /**
966
- * Core prototype manipulation properties (always blocked except PERMISSIVE)
967
- */
968
- PROTOTYPE: /* @__PURE__ */ new Set([
969
- "constructor",
970
- "__proto__",
971
- "prototype",
972
- "__defineGetter__",
973
- "__defineSetter__",
974
- "__lookupGetter__",
975
- "__lookupSetter__"
976
- ]),
977
- /**
978
- * Node.js 24 Iterator helper method names
979
- * Blocked at STRICT/SECURE to prevent prototype chain access via iterators
980
- */
981
- ITERATOR_HELPERS: /* @__PURE__ */ new Set(["toArray", "forEach", "some", "every", "find", "reduce", "flatMap", "drop", "take"]),
982
- /**
983
- * Reflection properties on Object
984
- * Blocked at STRICT to prevent introspection attacks
985
- */
986
- REFLECTION: /* @__PURE__ */ new Set([
987
- "getOwnPropertyDescriptor",
988
- "getOwnPropertyDescriptors",
989
- "getOwnPropertyNames",
990
- "getOwnPropertySymbols",
991
- "getPrototypeOf",
992
- "setPrototypeOf",
993
- "defineProperty",
994
- "defineProperties",
995
- "preventExtensions",
996
- "isExtensible",
997
- "seal",
998
- "isSealed",
999
- "freeze",
1000
- "isFrozen"
1001
- ]),
1002
- /**
1003
- * Timing API properties
1004
- * Blocked at STRICT to prevent timing attacks
1005
- */
1006
- TIMING: /* @__PURE__ */ new Set(["hrtime", "timeOrigin"])
1007
- };
1008
- BLOCKED_PROPERTIES = /* @__PURE__ */ new Set([
1009
- // Code execution
1010
- "constructor",
1011
- // Prototype manipulation
1012
- "__proto__",
1013
- "prototype",
1014
- // Legacy getter/setter definition
1015
- "__defineGetter__",
1016
- "__defineSetter__",
1017
- "__lookupGetter__",
1018
- "__lookupSetter__"
1019
- ]);
1020
- DEFAULT_SECURE_PROXY_CONFIG = {
1021
- blockConstructor: true,
1022
- blockPrototype: true,
1023
- blockLegacyAccessors: true,
1024
- proxyMaxDepth: 10,
1025
- throwOnBlocked: true
1026
- };
1027
- FUNCTION_BLOCKED_PROPERTIES = /* @__PURE__ */ new Set([
1028
- // Function object properties that could leak information
1029
- "caller",
1030
- // Deprecated but still exists
1031
- "arguments"
1032
- // Deprecated but still exists
1033
- // Binding/applying could be used for exploitation
1034
- // Note: We may want to allow these in some cases
1035
- // 'bind',
1036
- // 'call',
1037
- // 'apply',
1038
- ]);
1039
- proxyCache = /* @__PURE__ */ new WeakMap();
1040
- proxySet = /* @__PURE__ */ new WeakSet();
1041
- NON_PROXYABLE_TYPES = /* @__PURE__ */ new Set([
1042
- // Map/Set have internal slots but we may need to proxy them in the future
1043
- "[object Map]",
1044
- "[object Set]",
1045
- "[object WeakMap]",
1046
- "[object WeakSet]",
1047
- "[object ArrayBuffer]",
1048
- "[object SharedArrayBuffer]",
1049
- "[object DataView]",
1050
- "[object Int8Array]",
1051
- "[object Uint8Array]",
1052
- "[object Uint8ClampedArray]",
1053
- "[object Int16Array]",
1054
- "[object Uint16Array]",
1055
- "[object Int32Array]",
1056
- "[object Uint32Array]",
1057
- "[object Float32Array]",
1058
- "[object Float64Array]",
1059
- "[object BigInt64Array]",
1060
- "[object BigUint64Array]",
1061
- // Generators and iterators use internal slots
1062
- "[object Generator]",
1063
- "[object AsyncGenerator]",
1064
- "[object GeneratorFunction]",
1065
- "[object AsyncGeneratorFunction]",
1066
- // Built-in iterators
1067
- "[object Array Iterator]",
1068
- "[object String Iterator]",
1069
- "[object Map Iterator]",
1070
- "[object Set Iterator]",
1071
- "[object RegExp String Iterator]"
1072
- ]);
1073
- INTERNAL_SLOT_TYPES = /* @__PURE__ */ new Set(["[object Promise]"]);
1197
+ DANGEROUS_KEYS = /* @__PURE__ */ new Set(["__proto__", "constructor"]);
1198
+ ReflectApply = Reflect.apply;
1199
+ ReflectGet2 = Reflect.get;
1200
+ ArrayIsArray = Array.isArray;
1201
+ ObjectKeys = Object.keys;
1202
+ ObjectCreate = Object.create;
1203
+ NumberIsFinite2 = Number.isFinite;
1204
+ MathFloor2 = Math.floor;
1205
+ MapProtoEntries = Map.prototype.entries;
1206
+ SetProtoValues = Set.prototype.values;
1207
+ DateProtoGetTime = Date.prototype.getTime;
1208
+ DateProtoToISOString = Date.prototype.toISOString;
1209
+ RegExpProtoToString = RegExp.prototype.toString;
1074
1210
  }
1075
1211
  });
1076
1212
 
@@ -1791,7 +1927,12 @@ ${stackTraceHardeningCode}
1791
1927
  function __ag_createSecureProxy(obj, depth) {
1792
1928
  if (depth === undefined) depth = 0;
1793
1929
  if (!__ag_Proxy || !__ag_Reflect) return obj;
1794
- if (depth > 10) return obj;
1930
+ // Fail CLOSED past the recursion backstop: returning the raw target would leak an
1931
+ // unwrapped reference (see MEMBRANE_MAX_RECURSION_DEPTH). Use the hardened safe-error
1932
+ // helper (sanitized stack, nulled constructor/proto) rather than a raw Error.
1933
+ if (depth > ${MEMBRANE_MAX_RECURSION_DEPTH}) {
1934
+ throw __ag_createSafeError('Security violation: secure-proxy recursion depth exceeded.');
1935
+ }
1795
1936
  if (obj === null || (typeof obj !== 'object' && typeof obj !== 'function')) return obj;
1796
1937
 
1797
1938
  if (__ag_proxyCache) {
@@ -1814,8 +1955,15 @@ ${stackTraceHardeningCode}
1814
1955
  if (typeof value === 'function') {
1815
1956
  // Bind methods to preserve internal slots when relevant.
1816
1957
  try { value = value.bind(target); } catch (e) {}
1958
+ return __ag_createSecureProxy(value, depth + 1);
1817
1959
  }
1818
- return __ag_createSecureProxy(value, depth + 1);
1960
+ // Only objects still need proxying; primitives (e.g. length/name) are inert and must be
1961
+ // returned directly, so a deep chain cannot turn a safe primitive read into a
1962
+ // recursion-depth error.
1963
+ if (value !== null && typeof value === 'object') {
1964
+ return __ag_createSecureProxy(value, depth + 1);
1965
+ }
1966
+ return value;
1819
1967
  },
1820
1968
  apply: function(target, thisArg, args) {
1821
1969
  return __ag_Reflect.apply(target, thisArg, args);
@@ -2211,8 +2359,10 @@ ${stackTraceHardeningCode}
2211
2359
  // Reference ID pattern for detecting sidecar references
2212
2360
  const refIdPattern = /^__REF_[0-9a-f]{8}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{12}__$/i;
2213
2361
 
2214
- // Proxy cache to avoid infinite recursion and duplicate wrapping
2362
+ // Proxy caches to avoid infinite recursion and duplicate wrapping. Host-owned values are
2363
+ // cached separately from realm-owned ones because the two use different blocking rules.
2215
2364
  const proxyCache = new WeakMap();
2365
+ const hostProxyCache = new WeakMap();
2216
2366
 
2217
2367
  /**
2218
2368
  * Create a secure proxy that blocks access to dangerous properties
@@ -2221,10 +2371,23 @@ ${stackTraceHardeningCode}
2221
2371
  * IMPORTANT: Must respect JavaScript proxy invariants:
2222
2372
  * - Non-configurable properties must return their actual value
2223
2373
  * - Non-configurable non-writable properties cannot be hidden
2374
+ *
2375
+ * The host flag marks a value that originates in the HOST realm (custom globals and
2376
+ * everything reachable from what they return). The host realm is the only one with code
2377
+ * generation from strings enabled, so a raw reference that escapes from it is remote code
2378
+ * execution; such a subtree refuses the reads a realm-owned object is allowed to answer.
2224
2379
  */
2225
- function createSecureProxy(obj, depth) {
2380
+ function createSecureProxy(obj, depth, host) {
2226
2381
  if (depth === undefined) depth = 0;
2227
- if (depth > 10) return obj; // Max depth to prevent infinite recursion
2382
+ host = host === true;
2383
+ // Recursion backstop. Fail CLOSED: returning the raw target here was the reported escape.
2384
+ // A bind chain inflates depth (each read binds a FRESH function, so the identity cache never
2385
+ // dedupes it) past the cap, and the raw host function prototype chain reaches the host
2386
+ // Function constructor for RCE. Throwing keeps the membrane total; the cap sits far above any
2387
+ // legitimately-deep (pre-sanitized) value so real data is never rejected.
2388
+ if (depth > ${MEMBRANE_MAX_RECURSION_DEPTH}) {
2389
+ throw createSafeError('Security violation: secure-proxy recursion depth exceeded.');
2390
+ }
2228
2391
 
2229
2392
  // Skip primitives and null
2230
2393
  if (obj === null || typeof obj !== 'object' && typeof obj !== 'function') {
@@ -2232,8 +2395,9 @@ ${stackTraceHardeningCode}
2232
2395
  }
2233
2396
 
2234
2397
  // Check cache
2235
- if (proxyCache.has(obj)) {
2236
- return proxyCache.get(obj);
2398
+ var cache = host ? hostProxyCache : proxyCache;
2399
+ if (cache.has(obj)) {
2400
+ return cache.get(obj);
2237
2401
  }
2238
2402
 
2239
2403
  var proxy = new Proxy(obj, {
@@ -2248,14 +2412,27 @@ ${stackTraceHardeningCode}
2248
2412
  // the proxy must return the exact same value (cannot wrap/bind/proxy it).
2249
2413
  // This matters for hardened properties like Error.prepareStackTrace.
2250
2414
  if (descriptor && isNonConfigurable && 'value' in descriptor && descriptor.writable === false) {
2251
- return descriptor.value;
2415
+ var exactValue = descriptor.value;
2416
+ // On a host-owned value the exact reference cannot be handed over: it would cross
2417
+ // the barrier unwrapped and its prototype chain reaches the host Function
2418
+ // constructor. Primitives stay safe to report, so only object/function values are
2419
+ // refused, and throwing satisfies the invariant that wrapping would break.
2420
+ if (host && exactValue !== null && (typeof exactValue === 'object' || typeof exactValue === 'function')) {
2421
+ throw createSafeError(
2422
+ "Security violation: Access to '" + propName + "' is blocked. " +
2423
+ "This property cannot be exposed without breaking the sandbox barrier."
2424
+ );
2425
+ }
2426
+ return exactValue;
2252
2427
  }
2253
2428
 
2254
2429
  // Block dangerous properties - but respect proxy invariants
2255
2430
  if (blockedPropertiesSet.has(propName)) {
2256
2431
  // For non-configurable properties, we MUST return the actual value
2257
- // (JavaScript proxy invariant - can't hide non-configurable properties)
2258
- if (isNonConfigurable) {
2432
+ // (JavaScript proxy invariant - can't hide non-configurable properties).
2433
+ // Host-owned values instead deny the read: every descriptor shape that could force
2434
+ // the trap's result was handled above, so returning undefined is invariant-safe.
2435
+ if (isNonConfigurable && !host) {
2259
2436
  return Reflect.get(target, property, receiver);
2260
2437
  }
2261
2438
  if (throwOnBlocked) {
@@ -2273,13 +2450,13 @@ ${stackTraceHardeningCode}
2273
2450
  // Then recursively proxy the bound function to block constructor access
2274
2451
  if (typeof value === 'function') {
2275
2452
  var boundMethod = value.bind(target);
2276
- return createSecureProxy(boundMethod, depth + 1);
2453
+ return createSecureProxy(boundMethod, depth + 1, host);
2277
2454
  }
2278
2455
 
2279
2456
  // Recursively proxy nested objects to maintain security barrier
2280
2457
  // This prevents attacks like: process.env.__proto__.constructor
2281
2458
  if (value !== null && typeof value === 'object') {
2282
- return createSecureProxy(value, depth + 1);
2459
+ return createSecureProxy(value, depth + 1, host);
2283
2460
  }
2284
2461
 
2285
2462
  return value;
@@ -2314,7 +2491,34 @@ ${stackTraceHardeningCode}
2314
2491
  var propName = String(property);
2315
2492
  var descriptor = Reflect.getOwnPropertyDescriptor(target, property);
2316
2493
 
2317
- // Must return actual descriptor for non-configurable properties (proxy invariant)
2494
+ // Mirror the get trap's host-owned pinned-value refusal: a non-configurable, non-writable
2495
+ // data property must be reported with its exact value (proxy invariant), so on a HOST-owned
2496
+ // value an object/function would cross the barrier unwrapped via descriptor.value and its
2497
+ // prototype chain reaches the host Function constructor. Deny the read instead (throwing
2498
+ // satisfies the invariant); primitives stay safe to report.
2499
+ if (host && descriptor && !descriptor.configurable && descriptor.writable === false && 'value' in descriptor) {
2500
+ var exactValue = descriptor.value;
2501
+ if (exactValue !== null && (typeof exactValue === 'object' || typeof exactValue === 'function')) {
2502
+ throw createSafeError(
2503
+ "Security violation: Access to property descriptor for '" + propName + "' is blocked. " +
2504
+ "This property cannot be exposed without breaking the sandbox barrier."
2505
+ );
2506
+ }
2507
+ return descriptor;
2508
+ }
2509
+
2510
+ // Accessor descriptors expose raw getter/setter functions. A non-configurable accessor
2511
+ // must be reported with its exact get/set (proxy invariant) and so cannot be wrapped \u2014
2512
+ // deny it if it carries a function whose prototype chain reaches the host constructor.
2513
+ if (descriptor && !descriptor.configurable &&
2514
+ (typeof descriptor.get === 'function' || typeof descriptor.set === 'function')) {
2515
+ throw createSafeError(
2516
+ "Security violation: Access to property descriptor for '" + propName + "' is blocked. " +
2517
+ "This property cannot be exposed without breaking the sandbox barrier."
2518
+ );
2519
+ }
2520
+
2521
+ // Must return actual descriptor for other non-configurable properties (proxy invariant)
2318
2522
  if (descriptor && !descriptor.configurable) {
2319
2523
  return descriptor;
2320
2524
  }
@@ -2329,6 +2533,28 @@ ${stackTraceHardeningCode}
2329
2533
  }
2330
2534
  return undefined;
2331
2535
  }
2536
+
2537
+ // A configurable accessor's getter/setter may be safely proxied so the descriptor never
2538
+ // hands back a raw function that leads to the host Function constructor.
2539
+ if (descriptor && (typeof descriptor.get === 'function' || typeof descriptor.set === 'function')) {
2540
+ var accessorWrapped = {};
2541
+ for (var ak in descriptor) { if (Object.prototype.hasOwnProperty.call(descriptor, ak)) accessorWrapped[ak] = descriptor[ak]; }
2542
+ if (typeof descriptor.get === 'function') accessorWrapped.get = createSecureProxy(descriptor.get, depth + 1, host);
2543
+ if (typeof descriptor.set === 'function') accessorWrapped.set = createSecureProxy(descriptor.set, depth + 1, host);
2544
+ return accessorWrapped;
2545
+ }
2546
+
2547
+ // Wrap object/function values so a descriptor read cannot hand back a raw reference that
2548
+ // the get trap would otherwise have proxied.
2549
+ if (descriptor && 'value' in descriptor) {
2550
+ var value = descriptor.value;
2551
+ if (value !== null && (typeof value === 'object' || typeof value === 'function')) {
2552
+ var wrapped = {};
2553
+ for (var dk in descriptor) { if (Object.prototype.hasOwnProperty.call(descriptor, dk)) wrapped[dk] = descriptor[dk]; }
2554
+ wrapped.value = createSecureProxy(value, depth + 1, host);
2555
+ return wrapped;
2556
+ }
2557
+ }
2332
2558
  return descriptor;
2333
2559
  },
2334
2560
  ownKeys: function(target) {
@@ -2351,10 +2577,34 @@ ${stackTraceHardeningCode}
2351
2577
  getPrototypeOf: function(target) {
2352
2578
  // Return null to hide prototype chain
2353
2579
  return null;
2354
- }
2580
+ },
2581
+ // SECURITY (GHSA-grmc-r8vw-226r): the get trap re-wraps values obtained via property
2582
+ // ACCESS, but function-call results cross the same trust boundary and must be wrapped
2583
+ // too. Without an apply trap, calling a wrapped function (for example the then method
2584
+ // of the secure Promise returned by callTool) falls through to the default call and
2585
+ // returns a RAW host object; the sandbox can then walk its prototype chain
2586
+ // (Promise.prototype up to Function) to reach the host Function constructor for RCE.
2587
+ // Results are re-wrapped at a FRESH depth (0) so a chain of calls such as
2588
+ // then().then() cannot inflate depth past the recursion cap and leak an unwrapped value.
2589
+ apply: function(target, thisArg, args) {
2590
+ return createSecureProxy(Reflect.apply(target, thisArg, args), 0, host);
2591
+ }
2592
+ // NOTE: intentionally NO construct trap here (unlike the standalone secure-proxy used
2593
+ // for single-VM mode). Every constructor reachable from sandbox code resolves to an
2594
+ // inner-VM or parent-VM intrinsic, and BOTH of those realms run with code generation
2595
+ // from strings disabled, so a 'new X()' result cannot reach a usable Function
2596
+ // constructor. The only code-generation-enabled realm (the host) is reached solely via
2597
+ // host return values (callTool), which is an apply-path and is covered above. Wrapping
2598
+ // construct results would additionally break the proxy invariant for the frozen (non-
2599
+ // extensible) Error objects the harness throws (getPrototypeOf must not report null for
2600
+ // a non-extensible target), masking legitimate errors.
2355
2601
  });
2356
2602
 
2357
- proxyCache.set(obj, proxy);
2603
+ cache.set(obj, proxy);
2604
+ // Idempotency: re-wrapping an already-secure proxy must return it unchanged, so an apply
2605
+ // result that is itself already a secure proxy is not double-wrapped (which would nest
2606
+ // proxies and inflate depth toward the recursion cap).
2607
+ cache.set(proxy, proxy);
2358
2608
  return proxy;
2359
2609
  }
2360
2610
 
@@ -2732,10 +2982,20 @@ ${stackTraceHardeningCode}
2732
2982
  if (typeof fn !== 'function') {
2733
2983
  throw createSafeError('parallel() requires a callback function as second argument', 'TypeError');
2734
2984
  }
2735
- if (items.length > 100) {
2985
+ // SECURITY: items may be an attacker Proxy that only passes Array.isArray. Read the length
2986
+ // ONCE and build the promise list by index rather than items.map(fn), so a .map trap can
2987
+ // neither be handed our callback nor use a stateful length to slip past the 100-item cap.
2988
+ var len = items.length;
2989
+ if (typeof len !== 'number' || !isFinite(len) || len < 0) len = 0;
2990
+ len = Math.floor(len);
2991
+ if (len > 100) {
2736
2992
  throw createSafeError('parallel() is limited to 100 items');
2737
2993
  }
2738
- return await Promise.all(items.map(fn));
2994
+ var promises = [];
2995
+ for (var i = 0; i < len; i++) {
2996
+ promises[i] = fn(items[i], i, items);
2997
+ }
2998
+ return await Promise.all(promises);
2739
2999
  }
2740
3000
 
2741
3001
  /**
@@ -3279,10 +3539,13 @@ ${stackTraceHardeningCode}
3279
3539
  // Add user-provided globals if any (also wrapped with secure proxy and non-writable)
3280
3540
  // SECURITY: Use enumerable: false to prevent Object.assign({}, this) from copying globals
3281
3541
  // This blocks Vector 380 (Bridge-Serialized State Reflection) attack
3542
+ // Custom globals are HOST-realm values, so they are wrapped in host mode: the whole
3543
+ // subtree reachable through them (including whatever their calls return) refuses to hand
3544
+ // back a raw reference, even for descriptor shapes where a realm-owned object may.
3282
3545
  if (hostConfig.globals) {
3283
3546
  for (var uKey in hostConfig.globals) {
3284
3547
  if (hostConfig.globals.hasOwnProperty(uKey)) {
3285
- var wrappedGlobal = createSecureProxy(hostConfig.globals[uKey]);
3548
+ var wrappedGlobal = createSecureProxy(hostConfig.globals[uKey], 0, true);
3286
3549
  Object.defineProperty(innerContext, uKey, {
3287
3550
  value: wrappedGlobal,
3288
3551
  writable: false,
@@ -3391,10 +3654,11 @@ ${stackTraceHardeningCode}
3391
3654
  })();
3392
3655
  `.trim();
3393
3656
  }
3394
- var NODEJS_24_DANGEROUS_GLOBALS;
3657
+ var MEMBRANE_MAX_RECURSION_DEPTH, NODEJS_24_DANGEROUS_GLOBALS;
3395
3658
  var init_parent_vm_bootstrap = __esm({
3396
3659
  "libs/core/src/double-vm/parent-vm-bootstrap.ts"() {
3397
3660
  "use strict";
3661
+ MEMBRANE_MAX_RECURSION_DEPTH = 256;
3398
3662
  NODEJS_24_DANGEROUS_GLOBALS = {
3399
3663
  STRICT: [
3400
3664
  // Code execution - CRITICAL
@@ -6022,6 +6286,24 @@ var init_errors = __esm({
6022
6286
  });
6023
6287
 
6024
6288
  // libs/core/src/adapters/worker-pool/safe-deserialize.ts
6289
+ function mapArraySafely(value, sanitizeItem) {
6290
+ const rawLen = ReflectGet3(value, "length");
6291
+ const len = typeof rawLen === "number" && NumberIsFinite3(rawLen) && rawLen >= 0 ? MathFloor3(rawLen) : 0;
6292
+ if (len > MAX_ARRAY_LENGTH) {
6293
+ throw new MessageValidationError(`Array exceeds maximum length of ${MAX_ARRAY_LENGTH}`);
6294
+ }
6295
+ const out = [];
6296
+ for (let i = 0; i < len; i++) {
6297
+ let item;
6298
+ try {
6299
+ item = ReflectGet3(value, i);
6300
+ } catch {
6301
+ item = void 0;
6302
+ }
6303
+ out[i] = sanitizeItem(item);
6304
+ }
6305
+ return out;
6306
+ }
6025
6307
  function safeDeserialize(raw, maxSizeBytes) {
6026
6308
  if (maxSizeBytes !== void 0) {
6027
6309
  const byteLength = Buffer.byteLength(raw, "utf-8");
@@ -6049,8 +6331,8 @@ function sanitizeObjectWithDepthCheck(value, depth) {
6049
6331
  if (typeof value !== "object") {
6050
6332
  return value;
6051
6333
  }
6052
- if (Array.isArray(value)) {
6053
- return value.map((item) => sanitizeObjectWithDepthCheck(item, depth + 1));
6334
+ if (ArrayIsArray2(value)) {
6335
+ return mapArraySafely(value, (item) => sanitizeObjectWithDepthCheck(item, depth + 1));
6054
6336
  }
6055
6337
  const result = /* @__PURE__ */ Object.create(null);
6056
6338
  for (const key of Object.keys(value)) {
@@ -6078,8 +6360,8 @@ function sanitizeObject(value, depth = 0) {
6078
6360
  if (typeof value !== "object") {
6079
6361
  return value;
6080
6362
  }
6081
- if (Array.isArray(value)) {
6082
- return value.map((item) => sanitizeObject(item, depth + 1));
6363
+ if (ArrayIsArray2(value)) {
6364
+ return mapArraySafely(value, (item) => sanitizeObject(item, depth + 1));
6083
6365
  }
6084
6366
  const result = /* @__PURE__ */ Object.create(null);
6085
6367
  for (const key of Object.keys(value)) {
@@ -6089,11 +6371,16 @@ function sanitizeObject(value, depth = 0) {
6089
6371
  }
6090
6372
  return result;
6091
6373
  }
6092
- var DANGEROUS_KEYS2, MAX_DEPTH;
6374
+ var ReflectGet3, ArrayIsArray2, NumberIsFinite3, MathFloor3, MAX_ARRAY_LENGTH, DANGEROUS_KEYS2, MAX_DEPTH;
6093
6375
  var init_safe_deserialize = __esm({
6094
6376
  "libs/core/src/adapters/worker-pool/safe-deserialize.ts"() {
6095
6377
  "use strict";
6096
6378
  init_errors();
6379
+ ReflectGet3 = Reflect.get;
6380
+ ArrayIsArray2 = Array.isArray;
6381
+ NumberIsFinite3 = Number.isFinite;
6382
+ MathFloor3 = Math.floor;
6383
+ MAX_ARRAY_LENGTH = 1e6;
6097
6384
  DANGEROUS_KEYS2 = /* @__PURE__ */ new Set(["__proto__", "constructor", "prototype"]);
6098
6385
  MAX_DEPTH = 50;
6099
6386
  }
@@ -7786,7 +8073,12 @@ function transformMultiple(files, options, limits, singleFileTransform) {
7786
8073
 
7787
8074
  // libs/core/src/enclave.ts
7788
8075
  import { transformAgentScript, isWrappedInMain } from "@enclave-vm/ast";
7789
- import { extractLargeStrings, transformConcatenation, transformTemplateLiterals } from "@enclave-vm/ast";
8076
+ import {
8077
+ extractLargeStrings,
8078
+ transformConcatenation,
8079
+ transformTemplateLiterals,
8080
+ guardComputedMemberKeys
8081
+ } from "@enclave-vm/ast";
7790
8082
  import * as acorn2 from "acorn";
7791
8083
  import { generate } from "astring";
7792
8084
 
@@ -8085,6 +8377,9 @@ function validateGlobals(globals, options = {}) {
8085
8377
  }
8086
8378
  }
8087
8379
 
8380
+ // libs/core/src/enclave.ts
8381
+ init_secure_proxy();
8382
+
8088
8383
  // libs/core/src/sidecar/index.ts
8089
8384
  init_reference_config();
8090
8385
 
@@ -10185,6 +10480,9 @@ ${errorMessages}`,
10185
10480
  } else if (this.config.memoryLimit && this.config.memoryLimit > 0) {
10186
10481
  transformedCode = this.applyMemoryTrackingTransforms(transformedCode);
10187
10482
  }
10483
+ if (this.transformCode) {
10484
+ transformedCode = this.applyComputedKeyGuard(transformedCode);
10485
+ }
10188
10486
  let scoringResult;
10189
10487
  if (this.scoringGate) {
10190
10488
  scoringResult = await this.scoringGate.evaluate(transformedCode);
@@ -10282,6 +10580,21 @@ ${errorMessages}`,
10282
10580
  * @param code The code to transform
10283
10581
  * @returns The transformed code
10284
10582
  */
10583
+ applyComputedKeyGuard(code) {
10584
+ const proxyConfig = this.config.secureProxyConfig;
10585
+ const blockedKeys = [...buildBlockedPropertiesFromConfig(proxyConfig)];
10586
+ if (blockedKeys.length === 0) {
10587
+ return code;
10588
+ }
10589
+ const throwOnBlocked = proxyConfig.throwOnBlocked ?? true;
10590
+ const parseModule = (source) => acorn2.parse(source, { ecmaVersion: "latest", sourceType: "module" });
10591
+ const ast = parseModule(code);
10592
+ const { guardedCount } = guardComputedMemberKeys(ast, parseModule, { blockedKeys, throwOnBlocked });
10593
+ if (guardedCount === 0) {
10594
+ return code;
10595
+ }
10596
+ return generate(ast);
10597
+ }
10285
10598
  applyMemoryTrackingTransforms(code) {
10286
10599
  const ast = acorn2.parse(code, {
10287
10600
  ecmaVersion: "latest",