@enclave-vm/core 2.15.0 → 2.15.2

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,611 @@ 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
+ BLOCKED_PROPERTY_CATEGORIES.DESCRIPTOR_MUTATION.forEach((p) => blocked.add(p));
96
+ }
97
+ switch (level) {
98
+ case "STRICT":
99
+ BLOCKED_PROPERTY_CATEGORIES.ITERATOR_HELPERS.forEach((p) => blocked.add(p));
100
+ BLOCKED_PROPERTY_CATEGORIES.REFLECTION.forEach((p) => blocked.add(p));
101
+ BLOCKED_PROPERTY_CATEGORIES.TIMING.forEach((p) => blocked.add(p));
102
+ break;
103
+ case "SECURE":
104
+ BLOCKED_PROPERTY_CATEGORIES.ITERATOR_HELPERS.forEach((p) => blocked.add(p));
105
+ break;
106
+ case "STANDARD":
107
+ case "PERMISSIVE":
108
+ break;
109
+ }
110
+ return blocked;
111
+ }
112
+ function buildBlockedPropertiesFromConfig(config) {
113
+ const blocked = /* @__PURE__ */ new Set();
114
+ if (config.blockConstructor) {
115
+ blocked.add("constructor");
116
+ BLOCKED_PROPERTY_CATEGORIES.DESCRIPTOR_MUTATION.forEach((p) => blocked.add(p));
117
+ }
118
+ if (config.blockPrototype) {
119
+ blocked.add("__proto__");
120
+ blocked.add("prototype");
121
+ }
122
+ if (config.blockLegacyAccessors) {
123
+ blocked.add("__defineGetter__");
124
+ blocked.add("__defineSetter__");
125
+ blocked.add("__lookupGetter__");
126
+ blocked.add("__lookupSetter__");
127
+ }
128
+ return blocked;
129
+ }
130
+ function createSafeReflect(securityLevel) {
131
+ if (securityLevel === "STRICT") {
132
+ return void 0;
133
+ }
134
+ const dangerousMethods = /* @__PURE__ */ new Set(["setPrototypeOf"]);
135
+ if (securityLevel === "SECURE") {
136
+ dangerousMethods.add("apply");
137
+ dangerousMethods.add("defineProperty");
138
+ }
139
+ const refuseMutation = () => {
140
+ throw createSafeError("Reflect is read-only in the sandbox", "SecurityError");
141
+ };
142
+ return new Proxy(ReflectObject, {
143
+ set: refuseMutation,
144
+ defineProperty: refuseMutation,
145
+ deleteProperty: refuseMutation,
146
+ setPrototypeOf: refuseMutation,
147
+ preventExtensions: refuseMutation,
148
+ get(_target, prop) {
149
+ if (typeof prop === "string" && dangerousMethods.has(prop)) {
150
+ return void 0;
151
+ }
152
+ if (!PINNED_REFLECT_VALUES.has(prop)) {
153
+ return void 0;
154
+ }
155
+ const value = PINNED_REFLECT_VALUES.get(prop);
156
+ if (typeof value === "function" && prop === "construct") {
157
+ const safeConstruct = function(ctorTarget, args, ...newTarget) {
158
+ if (ctorTarget === FunctionCtor || ctorTarget === AsyncFunctionCtor || ctorTarget === GeneratorFunctionCtor || ctorTarget === AsyncGeneratorFunctionCtor) {
159
+ throw createSafeError("Reflect.construct with function constructors is blocked", "SecurityError");
160
+ }
161
+ if (newTarget.length === 0) {
162
+ return ReflectConstruct(ctorTarget, args);
163
+ }
164
+ return ReflectConstruct(
165
+ ctorTarget,
166
+ args,
167
+ newTarget[0]
168
+ );
169
+ };
170
+ return createSecureProxy(safeConstruct);
171
+ }
172
+ if (typeof value === "function") {
173
+ return createSecureProxy(value);
174
+ }
175
+ return value;
176
+ }
177
+ });
178
+ }
179
+ function getFullCacheKey(options) {
180
+ const parts = [];
181
+ if (options.levelConfig) {
182
+ const cfg = options.levelConfig;
183
+ parts.push(
184
+ `L:${cfg.blockConstructor ? "C" : "c"}${cfg.blockPrototype ? "P" : "p"}${cfg.blockLegacyAccessors ? "L" : "l"}`
185
+ );
186
+ } else {
187
+ parts.push("L:default");
188
+ }
189
+ if (options.additionalBlocked && options.additionalBlocked.length > 0) {
190
+ parts.push(`B:${[...options.additionalBlocked].sort().join(",")}`);
191
+ }
192
+ const effectiveMaxDepth = options.maxDepth ?? options.levelConfig?.proxyMaxDepth ?? 10;
193
+ if (effectiveMaxDepth !== 10) {
194
+ parts.push(`D:${effectiveMaxDepth}`);
195
+ }
196
+ if (options.throwOnBlocked) {
197
+ parts.push("T:1");
198
+ }
199
+ return parts.join("|") || "default";
200
+ }
201
+ function isProxyable(value) {
202
+ if (value === null) return false;
203
+ if (typeof value !== "object" && typeof value !== "function") return false;
204
+ const tag = ReflectApply(ObjectToString, value, []);
205
+ if (NON_PROXYABLE_TYPES.has(tag)) {
206
+ return false;
207
+ }
208
+ return true;
209
+ }
210
+ function createSecureProxy(target, options = {}) {
211
+ if (!isProxyable(target)) {
212
+ return target;
213
+ }
214
+ const cacheKey = getFullCacheKey(options);
215
+ const targetCache = proxyCache.get(target);
216
+ if (targetCache) {
217
+ const cached = targetCache.get(cacheKey);
218
+ if (cached) {
219
+ return cached;
220
+ }
221
+ }
222
+ const baseBlocked = options.levelConfig ? buildBlockedPropertiesFromConfig(options.levelConfig) : new Set(BLOCKED_PROPERTIES);
223
+ const blockedSet = /* @__PURE__ */ new Set([...baseBlocked, ...options.additionalBlocked || []]);
224
+ const configuredMaxDepth = options.maxDepth ?? options.levelConfig?.proxyMaxDepth ?? 10;
225
+ const maxDepth = Number.isFinite(configuredMaxDepth) ? Math.max(configuredMaxDepth, MIN_MEMBRANE_RECURSION_DEPTH) : MIN_MEMBRANE_RECURSION_DEPTH;
226
+ const throwOnBlocked = options.throwOnBlocked ?? options.levelConfig?.throwOnBlocked ?? false;
227
+ function proxyWithDepth(obj, depth) {
228
+ if (!isProxyable(obj)) {
229
+ return obj;
230
+ }
231
+ const objCache = proxyCache.get(obj);
232
+ if (objCache) {
233
+ const cachedProxy = objCache.get(cacheKey);
234
+ if (cachedProxy) {
235
+ return cachedProxy;
236
+ }
237
+ }
238
+ if (depth > maxDepth) {
239
+ throw createSafeError(
240
+ `Security violation: secure-proxy recursion depth (${maxDepth}) exceeded. The value cannot be exposed without breaking the sandbox barrier.`,
241
+ "SecurityError"
242
+ );
243
+ }
244
+ const proxy = new Proxy(obj, {
245
+ get(target2, property, receiver) {
246
+ const propName = typeof property === "symbol" ? property.toString() : property;
247
+ const descriptor = ObjectGetOwnPropertyDescriptor(target2, property);
248
+ if (descriptor && !descriptor.configurable && descriptor.writable === false && "value" in descriptor) {
249
+ const exactValue = descriptor.value;
250
+ if (exactValue !== null && (typeof exactValue === "object" || typeof exactValue === "function")) {
251
+ throw createSafeError(
252
+ `Security violation: Access to '${String(propName)}' is blocked. This property cannot be exposed without breaking the sandbox barrier.`,
253
+ "SecurityError"
254
+ );
255
+ }
256
+ return exactValue;
257
+ }
258
+ if (typeof propName === "string" && blockedSet.has(propName)) {
259
+ if (options.onBlocked) {
260
+ options.onBlocked(target2, propName);
261
+ }
262
+ if (throwOnBlocked) {
263
+ throw createSafeError(
264
+ `Security violation: Access to '${propName}' is blocked. This property can be used for sandbox escape attacks.`,
265
+ "SecurityError"
266
+ );
267
+ }
268
+ return void 0;
269
+ }
270
+ if (typeof target2 === "function" && typeof propName === "string" && FUNCTION_BLOCKED_PROPERTIES.has(propName)) {
271
+ if (options.onBlocked) {
272
+ options.onBlocked(target2, propName);
273
+ }
274
+ if (throwOnBlocked) {
275
+ throw createSafeError(
276
+ `Security violation: Access to '${propName}' is blocked. This property can be used for sandbox escape attacks.`,
277
+ "SecurityError"
278
+ );
279
+ }
280
+ return void 0;
281
+ }
282
+ const value = ReflectGet(target2, property, receiver);
283
+ if (typeof value === "function") {
284
+ const tag = ReflectApply(ObjectToString, target2, []);
285
+ if (INTERNAL_SLOT_TYPES.has(tag)) {
286
+ const boundMethod = ReflectApply(FunctionBind, value, [target2]);
287
+ return proxyWithDepth(boundMethod, depth + 1);
288
+ }
289
+ }
290
+ if (value !== null && (typeof value === "object" || typeof value === "function")) {
291
+ return proxyWithDepth(value, depth + 1);
292
+ }
293
+ return value;
294
+ },
295
+ // Block setting dangerous properties
296
+ set(target2, property, value, receiver) {
297
+ const propName = typeof property === "symbol" ? property.toString() : property;
298
+ if (typeof propName === "string" && blockedSet.has(propName)) {
299
+ if (options.onBlocked) {
300
+ options.onBlocked(target2, propName);
301
+ }
302
+ if (throwOnBlocked) {
303
+ throw createSafeError(
304
+ `Security violation: Setting '${propName}' is blocked. This property can be used for sandbox escape attacks.`,
305
+ "SecurityError"
306
+ );
307
+ }
308
+ return false;
309
+ }
310
+ return ReflectSet(target2, property, value, receiver);
311
+ },
312
+ // Block defining dangerous properties
313
+ defineProperty(target2, property, descriptor) {
314
+ const propName = typeof property === "symbol" ? property.toString() : property;
315
+ if (typeof propName === "string" && blockedSet.has(propName)) {
316
+ if (options.onBlocked) {
317
+ options.onBlocked(target2, propName);
318
+ }
319
+ if (throwOnBlocked) {
320
+ throw createSafeError(
321
+ `Security violation: Defining '${propName}' is blocked. This property can be used for sandbox escape attacks.`,
322
+ "SecurityError"
323
+ );
324
+ }
325
+ return false;
326
+ }
327
+ return ReflectDefineProperty(target2, property, descriptor);
328
+ },
329
+ // Filter blocked property names from enumeration (Object.keys, Object.entries, etc.)
330
+ // Must respect proxy invariants: non-configurable own properties cannot be hidden
331
+ ownKeys(target2) {
332
+ const keys = ReflectOwnKeys(target2);
333
+ return keys.filter((key) => {
334
+ const keyStr = typeof key === "symbol" ? key.toString() : key;
335
+ if (typeof keyStr !== "string" || !blockedSet.has(keyStr)) {
336
+ return true;
337
+ }
338
+ const descriptor = ObjectGetOwnPropertyDescriptor(target2, key);
339
+ if (descriptor && !descriptor.configurable) {
340
+ return true;
341
+ }
342
+ return false;
343
+ });
344
+ },
345
+ // Hide blocked properties from property descriptor queries (defense-in-depth)
346
+ // Must respect proxy invariants: non-configurable properties must return actual descriptor
347
+ getOwnPropertyDescriptor(target2, property) {
348
+ const propName = typeof property === "symbol" ? property.toString() : property;
349
+ const descriptor = ReflectGetOwnPropertyDescriptor(target2, property);
350
+ if (descriptor && !descriptor.configurable && descriptor.writable === false && "value" in descriptor) {
351
+ const exactValue = descriptor.value;
352
+ if (exactValue !== null && (typeof exactValue === "object" || typeof exactValue === "function")) {
353
+ throw createSafeError(
354
+ `Security violation: Access to property descriptor for '${String(propName)}' is blocked. This property cannot be exposed without breaking the sandbox barrier.`,
355
+ "SecurityError"
356
+ );
357
+ }
358
+ return descriptor;
359
+ }
360
+ if (descriptor && !descriptor.configurable && (typeof descriptor.get === "function" || typeof descriptor.set === "function")) {
361
+ throw createSafeError(
362
+ `Security violation: Access to property descriptor for '${String(propName)}' is blocked. This property cannot be exposed without breaking the sandbox barrier.`,
363
+ "SecurityError"
364
+ );
365
+ }
366
+ if (descriptor && !descriptor.configurable) {
367
+ return descriptor;
368
+ }
369
+ if (typeof propName === "string" && blockedSet.has(propName)) {
370
+ if (options.onBlocked) {
371
+ options.onBlocked(target2, propName);
372
+ }
373
+ if (throwOnBlocked) {
374
+ throw createSafeError(
375
+ `Security violation: Access to property descriptor for '${propName}' is blocked. This property can be used for sandbox escape attacks.`,
376
+ "SecurityError"
377
+ );
378
+ }
379
+ return void 0;
380
+ }
381
+ if (descriptor && (typeof descriptor.get === "function" || typeof descriptor.set === "function")) {
382
+ return {
383
+ ...descriptor,
384
+ get: typeof descriptor.get === "function" ? proxyWithDepth(descriptor.get, depth + 1) : descriptor.get,
385
+ set: typeof descriptor.set === "function" ? proxyWithDepth(descriptor.set, depth + 1) : descriptor.set
386
+ };
387
+ }
388
+ if (descriptor && "value" in descriptor) {
389
+ const value = descriptor.value;
390
+ if (value !== null && (typeof value === "object" || typeof value === "function")) {
391
+ return { ...descriptor, value: proxyWithDepth(value, depth + 1) };
392
+ }
393
+ }
394
+ return descriptor;
395
+ },
396
+ // Block getPrototypeOf to prevent prototype chain walking
397
+ getPrototypeOf() {
398
+ return null;
399
+ },
400
+ // Block setPrototypeOf
401
+ setPrototypeOf() {
402
+ return false;
403
+ },
404
+ // Intercept function calls to proxy return values
405
+ // eslint-disable-next-line @typescript-eslint/no-explicit-any -- Proxy handler signature requires any for compatibility
406
+ apply(target2, thisArg, argArray) {
407
+ const unwrappedThis = thisArg !== null && (typeof thisArg === "object" || typeof thisArg === "function") && proxyToTarget.has(thisArg) ? proxyToTarget.get(thisArg) : thisArg;
408
+ const result = ReflectApply(target2, unwrappedThis, argArray);
409
+ if (isProxyable(result)) {
410
+ return proxyWithDepth(result, depth + 1);
411
+ }
412
+ return result;
413
+ },
414
+ // Intercept constructor calls to proxy the created instance. Without this, code such as
415
+ // `new (wrappedCtor)()` would return a RAW object whose prototype chain reaches the
416
+ // host Function constructor — the same escape class the apply trap closes for calls.
417
+ // eslint-disable-next-line @typescript-eslint/no-explicit-any -- Proxy handler signature requires any for compatibility
418
+ construct(target2, argArray, newTarget) {
419
+ const instance = ReflectConstruct(target2, argArray, newTarget === proxy ? target2 : newTarget);
420
+ if (isProxyable(instance)) {
421
+ return proxyWithDepth(instance, depth + 1);
422
+ }
423
+ return instance;
424
+ }
425
+ });
426
+ let objCacheMap = proxyCache.get(obj);
427
+ if (!objCacheMap) {
428
+ objCacheMap = /* @__PURE__ */ new Map();
429
+ proxyCache.set(obj, objCacheMap);
430
+ }
431
+ objCacheMap.set(cacheKey, proxy);
432
+ proxySet.add(proxy);
433
+ proxyToTarget.set(proxy, obj);
434
+ return proxy;
435
+ }
436
+ return proxyWithDepth(target, 0);
437
+ }
438
+ function wrapGlobalsWithSecureProxy(globals, options = {}) {
439
+ const wrapped = {};
440
+ for (const [key, value] of Object.entries(globals)) {
441
+ if (value !== null && (typeof value === "object" || typeof value === "function")) {
442
+ wrapped[key] = createSecureProxy(value, options);
443
+ } else {
444
+ wrapped[key] = value;
445
+ }
446
+ }
447
+ return wrapped;
448
+ }
449
+ function createSecureStandardLibrary(options = {}) {
450
+ return wrapGlobalsWithSecureProxy(
451
+ {
452
+ Math,
453
+ JSON,
454
+ Array,
455
+ Object,
456
+ String,
457
+ Number,
458
+ Date
459
+ // Note: We intentionally don't include:
460
+ // - Function (dangerous)
461
+ // - eval (dangerous)
462
+ // - Proxy, Reflect (meta-programming)
463
+ },
464
+ options
465
+ );
466
+ }
467
+ function isSecureProxy(obj) {
468
+ if (obj === null || typeof obj !== "object") {
469
+ return false;
470
+ }
471
+ return proxySet.has(obj);
472
+ }
473
+ var ObjectGetOwnPropertyDescriptor, ObjectToString, FunctionBind, ReflectGet, ReflectSet, ReflectDefineProperty, ReflectGetOwnPropertyDescriptor, ReflectOwnKeys, ReflectApply, ReflectConstruct, ReflectObject, PINNED_REFLECT_VALUES, FunctionCtor, AsyncFunctionCtor, GeneratorFunctionCtor, AsyncGeneratorFunctionCtor, 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;
474
+ var init_secure_proxy = __esm({
475
+ "libs/core/src/secure-proxy.ts"() {
476
+ "use strict";
477
+ init_safe_error();
478
+ ObjectGetOwnPropertyDescriptor = Object.getOwnPropertyDescriptor;
479
+ ObjectToString = Object.prototype.toString;
480
+ FunctionBind = Function.prototype.bind;
481
+ ReflectGet = Reflect.get;
482
+ ReflectSet = Reflect.set;
483
+ ReflectDefineProperty = Reflect.defineProperty;
484
+ ReflectGetOwnPropertyDescriptor = Reflect.getOwnPropertyDescriptor;
485
+ ReflectOwnKeys = Reflect.ownKeys;
486
+ ReflectApply = Reflect.apply;
487
+ ReflectConstruct = Reflect.construct;
488
+ ReflectObject = Reflect;
489
+ PINNED_REFLECT_VALUES = /* @__PURE__ */ new Map();
490
+ for (const key of ReflectOwnKeys(ReflectObject)) {
491
+ PINNED_REFLECT_VALUES.set(key, ReflectGet(ReflectObject, key));
492
+ }
493
+ FunctionCtor = Function;
494
+ AsyncFunctionCtor = async function() {
495
+ }.constructor;
496
+ GeneratorFunctionCtor = function* () {
497
+ }.constructor;
498
+ AsyncGeneratorFunctionCtor = async function* () {
499
+ }.constructor;
500
+ MIN_MEMBRANE_RECURSION_DEPTH = 256;
501
+ BLOCKED_PROPERTY_CATEGORIES = {
502
+ /**
503
+ * Core prototype manipulation properties (always blocked except PERMISSIVE)
504
+ */
505
+ PROTOTYPE: /* @__PURE__ */ new Set([
506
+ "constructor",
507
+ "__proto__",
508
+ "prototype",
509
+ "__defineGetter__",
510
+ "__defineSetter__",
511
+ "__lookupGetter__",
512
+ "__lookupSetter__"
513
+ ]),
514
+ /**
515
+ * Property-descriptor and prototype MUTATION gadgets. These are the primitives behind the
516
+ * GHSA-3279 membrane self-leak (`Object.defineProperty(Object, 'getOwnPropertyDescriptor', hook)`
517
+ * to intercept the trap's raw target) and classic prototype pollution (`setPrototypeOf`). They
518
+ * are never needed by AgentScript and are already refused by the single-VM SafeObject
519
+ * (`DANGEROUS_OBJECT_STATIC_METHODS`), so they are blocked at every level that blocks the
520
+ * constructor (all except PERMISSIVE). Read-only reflection (getPrototypeOf, keys, entries,
521
+ * getOwnPropertyNames) is intentionally NOT here: the membrane's own getPrototypeOf/ownKeys traps
522
+ * already neutralize it for proxied values, and it has legitimate uses.
523
+ */
524
+ DESCRIPTOR_MUTATION: /* @__PURE__ */ new Set([
525
+ "getOwnPropertyDescriptor",
526
+ "getOwnPropertyDescriptors",
527
+ "defineProperty",
528
+ "defineProperties",
529
+ "setPrototypeOf"
530
+ ]),
531
+ /**
532
+ * Node.js 24 Iterator helper method names
533
+ * Blocked at STRICT/SECURE to prevent prototype chain access via iterators
534
+ */
535
+ ITERATOR_HELPERS: /* @__PURE__ */ new Set(["toArray", "forEach", "some", "every", "find", "reduce", "flatMap", "drop", "take"]),
536
+ /**
537
+ * Reflection properties on Object
538
+ * Blocked at STRICT to prevent introspection attacks
539
+ */
540
+ REFLECTION: /* @__PURE__ */ new Set([
541
+ "getOwnPropertyDescriptor",
542
+ "getOwnPropertyDescriptors",
543
+ "getOwnPropertyNames",
544
+ "getOwnPropertySymbols",
545
+ "getPrototypeOf",
546
+ "setPrototypeOf",
547
+ "defineProperty",
548
+ "defineProperties",
549
+ "preventExtensions",
550
+ "isExtensible",
551
+ "seal",
552
+ "isSealed",
553
+ "freeze",
554
+ "isFrozen"
555
+ ]),
556
+ /**
557
+ * Timing API properties
558
+ * Blocked at STRICT to prevent timing attacks
559
+ */
560
+ TIMING: /* @__PURE__ */ new Set(["hrtime", "timeOrigin"])
561
+ };
562
+ BLOCKED_PROPERTIES = /* @__PURE__ */ new Set([
563
+ // Code execution
564
+ "constructor",
565
+ // Prototype manipulation
566
+ "__proto__",
567
+ "prototype",
568
+ // Legacy getter/setter definition
569
+ "__defineGetter__",
570
+ "__defineSetter__",
571
+ "__lookupGetter__",
572
+ "__lookupSetter__",
573
+ // Descriptor / prototype mutation gadgets (GHSA-3279 self-leak + prototype pollution)
574
+ "getOwnPropertyDescriptor",
575
+ "getOwnPropertyDescriptors",
576
+ "defineProperty",
577
+ "defineProperties",
578
+ "setPrototypeOf"
579
+ ]);
580
+ DEFAULT_SECURE_PROXY_CONFIG = {
581
+ blockConstructor: true,
582
+ blockPrototype: true,
583
+ blockLegacyAccessors: true,
584
+ proxyMaxDepth: 10,
585
+ throwOnBlocked: true
586
+ };
587
+ FUNCTION_BLOCKED_PROPERTIES = /* @__PURE__ */ new Set([
588
+ // Function object properties that could leak information
589
+ "caller",
590
+ // Deprecated but still exists
591
+ "arguments"
592
+ // Deprecated but still exists
593
+ // Binding/applying could be used for exploitation
594
+ // Note: We may want to allow these in some cases
595
+ // 'bind',
596
+ // 'call',
597
+ // 'apply',
598
+ ]);
599
+ proxyCache = /* @__PURE__ */ new WeakMap();
600
+ proxySet = /* @__PURE__ */ new WeakSet();
601
+ proxyToTarget = /* @__PURE__ */ new WeakMap();
602
+ NON_PROXYABLE_TYPES = /* @__PURE__ */ new Set([
603
+ // Map/Set have internal slots but we may need to proxy them in the future
604
+ "[object Map]",
605
+ "[object Set]",
606
+ "[object WeakMap]",
607
+ "[object WeakSet]",
608
+ "[object ArrayBuffer]",
609
+ "[object SharedArrayBuffer]",
610
+ "[object DataView]",
611
+ "[object Int8Array]",
612
+ "[object Uint8Array]",
613
+ "[object Uint8ClampedArray]",
614
+ "[object Int16Array]",
615
+ "[object Uint16Array]",
616
+ "[object Int32Array]",
617
+ "[object Uint32Array]",
618
+ "[object Float32Array]",
619
+ "[object Float64Array]",
620
+ "[object BigInt64Array]",
621
+ "[object BigUint64Array]",
622
+ // Generators and iterators use internal slots
623
+ "[object Generator]",
624
+ "[object AsyncGenerator]",
625
+ "[object GeneratorFunction]",
626
+ "[object AsyncGeneratorFunction]",
627
+ // Built-in iterators
628
+ "[object Array Iterator]",
629
+ "[object String Iterator]",
630
+ "[object Map Iterator]",
631
+ "[object Set Iterator]",
632
+ "[object RegExp String Iterator]"
633
+ ]);
634
+ INTERNAL_SLOT_TYPES = /* @__PURE__ */ new Set(["[object Promise]"]);
635
+ }
636
+ });
637
+
33
638
  // libs/core/src/sidecar/reference-config.ts
34
639
  function isReferenceId(value) {
35
640
  return typeof value === "string" && REF_ID_PATTERN.test(value);
@@ -146,7 +751,7 @@ var init_reference_config = __esm({
146
751
 
147
752
  // libs/core/src/sidecar/reference-resolver.ts
148
753
  function untrustedLength(value) {
149
- const rawLen = ReflectGet(value, "length");
754
+ const rawLen = ReflectGet2(value, "length");
150
755
  if (typeof rawLen !== "number" || !NumberIsFinite(rawLen) || rawLen < 0) {
151
756
  return 0;
152
757
  }
@@ -163,7 +768,7 @@ function untrustedLength(value) {
163
768
  }
164
769
  function untrustedAt(value, index) {
165
770
  try {
166
- return ReflectGet(value, index);
771
+ return ReflectGet2(value, index);
167
772
  } catch {
168
773
  return void 0;
169
774
  }
@@ -172,12 +777,12 @@ function isCompositeHandle(value) {
172
777
  const obj = value;
173
778
  return typeof value === "object" && value !== null && obj["__type"] === "composite" && Array.isArray(obj["__parts"]);
174
779
  }
175
- var ReflectGet, NumberIsFinite, MathFloor, MAX_TRAVERSAL_LENGTH, ResolutionLimitError, ReferenceResolver;
780
+ var ReflectGet2, NumberIsFinite, MathFloor, MAX_TRAVERSAL_LENGTH, ResolutionLimitError, ReferenceResolver;
176
781
  var init_reference_resolver = __esm({
177
782
  "libs/core/src/sidecar/reference-resolver.ts"() {
178
783
  "use strict";
179
784
  init_reference_config();
180
- ReflectGet = Reflect.get;
785
+ ReflectGet2 = Reflect.get;
181
786
  NumberIsFinite = Number.isFinite;
182
787
  MathFloor = Math.floor;
183
788
  MAX_TRAVERSAL_LENGTH = 1e6;
@@ -422,772 +1027,263 @@ function sanitizeValue(value, options = {}, depth = 0, context = { propCount: {
422
1027
  `Tool handler return value exceeds maximum properties (${maxProperties}). This limit prevents memory exhaustion from large object graphs.`
423
1028
  );
424
1029
  }
425
- if (value === null || value === void 0) {
426
- return value;
427
- }
428
- const type = typeof value;
429
- if (type === "string" || type === "number" || type === "boolean") {
430
- return value;
431
- }
432
- if (type === "bigint") {
433
- return String(value);
434
- }
435
- if (type === "function") {
436
- throw new Error(
437
- "Tool handler returned a function. Functions cannot be returned to sandbox code as they could be used for code injection or host scope access."
438
- );
439
- }
440
- if (type === "symbol") {
441
- throw new Error(
442
- "Tool handler returned a symbol. Symbols cannot be returned to sandbox code as they could be used for prototype manipulation."
443
- );
444
- }
445
- if (type === "object" && value !== null) {
446
- if (context.visited.has(value)) {
447
- return "[Circular]";
448
- }
449
- context.visited.add(value);
450
- }
451
- if (ArrayIsArray(value)) {
452
- const rawLen = ReflectGet2(value, "length");
453
- const len = typeof rawLen === "number" && NumberIsFinite2(rawLen) && rawLen >= 0 ? MathFloor2(rawLen) : 0;
454
- context.propCount.count += len;
455
- if (context.propCount.count > maxProperties) {
456
- throw new Error(`Tool handler return value exceeds maximum properties (${maxProperties}).`);
457
- }
458
- const result = [];
459
- for (let i = 0; i < len; i++) {
460
- let item;
461
- try {
462
- item = ReflectGet2(value, i);
463
- } catch {
464
- item = void 0;
465
- }
466
- result[i] = sanitizeValue(item, options, depth + 1, context);
467
- }
468
- return result;
469
- }
470
- if (value instanceof Date) {
471
- const time = ReflectApply(DateProtoGetTime, value, []);
472
- if (allowDates) {
473
- return new Date(time);
474
- }
475
- return ReflectApply(DateProtoToISOString, value, []);
476
- }
477
- if (value instanceof Error) {
478
- const rawName = ReflectGet2(value, "name");
479
- const rawMessage = ReflectGet2(value, "message");
480
- const name = typeof rawName === "string" ? rawName : "Error";
481
- const message = typeof rawMessage === "string" ? rawMessage : "";
482
- if (allowErrors) {
483
- return {
484
- name,
485
- message
486
- // Do NOT include stack trace - could leak host information
487
- };
488
- }
489
- return { error: message };
490
- }
491
- if (value instanceof RegExp) {
492
- return ReflectApply(RegExpProtoToString, value, []);
493
- }
494
- if (value instanceof Map) {
495
- const sanitizedMap = ObjectCreate(null);
496
- const entries = ReflectApply(MapProtoEntries, value, []);
497
- for (const [key, val] of entries) {
498
- if (typeof key !== "string") continue;
499
- if (DANGEROUS_KEYS.has(key)) continue;
500
- context.propCount.count++;
501
- sanitizedMap[key] = sanitizeValue(val, options, depth + 1, context);
502
- }
503
- return sanitizedMap;
504
- }
505
- if (value instanceof Set) {
506
- const iter = ReflectApply(SetProtoValues, value, []);
507
- const result = [];
508
- for (const item of iter) {
509
- context.propCount.count++;
510
- result.push(sanitizeValue(item, options, depth + 1, context));
511
- }
512
- return result;
513
- }
514
- if (type === "object") {
515
- const sanitized = ObjectCreate(null);
516
- const keys = ObjectKeys(value);
517
- context.propCount.count += keys.length;
518
- if (context.propCount.count > maxProperties) {
519
- throw new Error(`Tool handler return value exceeds maximum properties (${maxProperties}).`);
520
- }
521
- for (const key of keys) {
522
- if (DANGEROUS_KEYS.has(key)) {
523
- continue;
524
- }
525
- let propValue;
526
- try {
527
- propValue = ReflectGet2(value, key);
528
- } catch {
529
- continue;
530
- }
531
- sanitized[key] = sanitizeValue(propValue, options, depth + 1, context);
532
- }
533
- return sanitized;
534
- }
535
- return String(value);
536
- }
537
- function estimateStringSize(str) {
538
- let bytes = 2;
539
- for (let i = 0; i < str.length; i++) {
540
- const code = str.charCodeAt(i);
541
- if (code < 128) {
542
- if (code === 34 || code === 92) {
543
- bytes += 2;
544
- } else if (code < 32) {
545
- bytes += 6;
546
- } else {
547
- bytes += 1;
548
- }
549
- } else if (code < 2048) {
550
- bytes += 2;
551
- } else if (code >= 55296 && code <= 56319 && i + 1 < str.length) {
552
- const nextCode = str.charCodeAt(i + 1);
553
- if (nextCode >= 56320 && nextCode <= 57343) {
554
- bytes += 4;
555
- i++;
556
- } else {
557
- bytes += 3;
558
- }
559
- } else {
560
- bytes += 3;
561
- }
562
- }
563
- return bytes;
564
- }
565
- function estimateSerializedSize(value, maxBytes = 0, depth = 0, maxDepth = 2e3, currentPath = /* @__PURE__ */ new Set()) {
566
- if (depth > maxDepth) {
567
- throw new Error(
568
- `Structure exceeds maximum nesting depth (${maxDepth}). Deeply nested structures are rejected to prevent stack overflow attacks.`
569
- );
570
- }
571
- if (value === null) return 4;
572
- if (value === void 0) return 0;
573
- const type = typeof value;
574
- if (type === "string") {
575
- const bytes = estimateStringSize(value);
576
- if (maxBytes > 0 && bytes > maxBytes) {
577
- throw new Error(`String serialization would exceed limit: ${bytes} > ${maxBytes} bytes`);
578
- }
579
- return bytes;
580
- }
581
- if (type === "number") {
582
- const num = value;
583
- if (!Number.isFinite(num)) return 4;
584
- return String(num).length;
1030
+ if (value === null || value === void 0) {
1031
+ return value;
585
1032
  }
586
- if (type === "boolean") {
587
- return value ? 4 : 5;
1033
+ const type = typeof value;
1034
+ if (type === "string" || type === "number" || type === "boolean") {
1035
+ return value;
588
1036
  }
589
1037
  if (type === "bigint") {
590
- return String(value).length + 2;
1038
+ return String(value);
591
1039
  }
592
- if (type === "function" || type === "symbol") {
593
- return 0;
1040
+ if (type === "function") {
1041
+ throw new Error(
1042
+ "Tool handler returned a function. Functions cannot be returned to sandbox code as they could be used for code injection or host scope access."
1043
+ );
594
1044
  }
595
- if (Array.isArray(value)) {
596
- if (currentPath.has(value)) {
597
- return 4;
598
- }
599
- currentPath.add(value);
600
- let size = 2;
601
- for (let i = 0; i < value.length; i++) {
602
- if (i > 0) size += 1;
603
- let elementSize = estimateSerializedSize(value[i], maxBytes, depth + 1, maxDepth, currentPath);
604
- if (elementSize === 0) elementSize = 4;
605
- size += elementSize;
606
- if (maxBytes > 0 && size > maxBytes) {
607
- currentPath.delete(value);
608
- throw new Error(
609
- `Array serialization would exceed limit: estimated ${size}+ > ${maxBytes} bytes. This often indicates repeated references to large strings that expand during JSON serialization.`
610
- );
611
- }
612
- }
613
- currentPath.delete(value);
614
- return size;
1045
+ if (type === "symbol") {
1046
+ throw new Error(
1047
+ "Tool handler returned a symbol. Symbols cannot be returned to sandbox code as they could be used for prototype manipulation."
1048
+ );
615
1049
  }
616
1050
  if (type === "object" && value !== null) {
617
- if (currentPath.has(value)) {
618
- return 4;
619
- }
620
- currentPath.add(value);
621
- if (value instanceof Date) {
622
- currentPath.delete(value);
623
- return 26;
1051
+ if (context.visited.has(value)) {
1052
+ return "[Circular]";
624
1053
  }
625
- if (value instanceof RegExp) {
626
- currentPath.delete(value);
627
- return 2;
1054
+ context.visited.add(value);
1055
+ }
1056
+ if (ArrayIsArray(value)) {
1057
+ const rawLen = ReflectGet3(value, "length");
1058
+ const len = typeof rawLen === "number" && NumberIsFinite2(rawLen) && rawLen >= 0 ? MathFloor2(rawLen) : 0;
1059
+ context.propCount.count += len;
1060
+ if (context.propCount.count > maxProperties) {
1061
+ throw new Error(`Tool handler return value exceeds maximum properties (${maxProperties}).`);
628
1062
  }
629
- let size = 2;
630
- const keys = Object.keys(value);
631
- let first = true;
632
- for (const key of keys) {
633
- if (key === "__proto__" || key === "constructor") continue;
634
- if (!first) size += 1;
635
- first = false;
636
- size += estimateStringSize(key) + 1;
637
- let propValue;
1063
+ const result = [];
1064
+ for (let i = 0; i < len; i++) {
1065
+ let item;
638
1066
  try {
639
- propValue = value[key];
1067
+ item = ReflectGet3(value, i);
640
1068
  } catch {
641
- continue;
642
- }
643
- const valueSize = estimateSerializedSize(propValue, maxBytes, depth + 1, maxDepth, currentPath);
644
- size += valueSize;
645
- if (maxBytes > 0 && size > maxBytes) {
646
- currentPath.delete(value);
647
- throw new Error(
648
- `Object serialization would exceed limit: estimated ${size}+ > ${maxBytes} bytes. This often indicates repeated references to large strings that expand during JSON serialization.`
649
- );
1069
+ item = void 0;
650
1070
  }
1071
+ result[i] = sanitizeValue(item, options, depth + 1, context);
651
1072
  }
652
- currentPath.delete(value);
653
- return size;
654
- }
655
- return 0;
656
- }
657
- function checkSerializedSize(value, maxBytes) {
658
- try {
659
- const estimatedBytes = estimateSerializedSize(value, maxBytes);
660
- return { ok: true, estimatedBytes };
661
- } catch (err) {
662
- return { ok: false, error: err instanceof Error ? err.message : "Unknown error" };
663
- }
664
- }
665
- var DANGEROUS_KEYS, ReflectApply, ReflectGet2, ArrayIsArray, ObjectKeys, ObjectCreate, NumberIsFinite2, MathFloor2, MapProtoEntries, SetProtoValues, DateProtoGetTime, DateProtoToISOString, RegExpProtoToString;
666
- var init_value_sanitizer = __esm({
667
- "libs/core/src/value-sanitizer.ts"() {
668
- "use strict";
669
- DANGEROUS_KEYS = /* @__PURE__ */ new Set(["__proto__", "constructor"]);
670
- ReflectApply = Reflect.apply;
671
- ReflectGet2 = Reflect.get;
672
- ArrayIsArray = Array.isArray;
673
- ObjectKeys = Object.keys;
674
- ObjectCreate = Object.create;
675
- NumberIsFinite2 = Number.isFinite;
676
- MathFloor2 = Math.floor;
677
- MapProtoEntries = Map.prototype.entries;
678
- SetProtoValues = Set.prototype.values;
679
- DateProtoGetTime = Date.prototype.getTime;
680
- DateProtoToISOString = Date.prototype.toISOString;
681
- RegExpProtoToString = RegExp.prototype.toString;
1073
+ return result;
682
1074
  }
683
- });
684
-
685
- // libs/core/src/safe-error.ts
686
- function createSafeError(message, name = "Error") {
687
- const error = new Error(message);
688
- error.name = name;
689
- const SafeConstructor = /* @__PURE__ */ Object.create(null);
690
- Object.defineProperties(SafeConstructor, {
691
- constructor: {
692
- value: SafeConstructor,
693
- writable: false,
694
- enumerable: false,
695
- configurable: false
696
- },
697
- prototype: {
698
- value: null,
699
- writable: false,
700
- enumerable: false,
701
- configurable: false
702
- },
703
- name: {
704
- value: "SafeError",
705
- writable: false,
706
- enumerable: false,
707
- configurable: false
1075
+ if (value instanceof Date) {
1076
+ const time = ReflectApply2(DateProtoGetTime, value, []);
1077
+ if (allowDates) {
1078
+ return new Date(time);
708
1079
  }
709
- });
710
- Object.freeze(SafeConstructor);
711
- Object.setPrototypeOf(error, null);
712
- Object.defineProperty(error, "constructor", {
713
- value: SafeConstructor,
714
- writable: false,
715
- enumerable: false,
716
- configurable: false
717
- });
718
- Object.defineProperty(error, "__proto__", {
719
- value: null,
720
- writable: false,
721
- enumerable: false,
722
- configurable: false
723
- });
724
- Object.defineProperty(error, "stack", {
725
- value: void 0,
726
- writable: false,
727
- enumerable: false,
728
- configurable: false
729
- });
730
- Object.freeze(error);
731
- return error;
732
- }
733
- function createSafeTypeError(message) {
734
- return createSafeError(message, "TypeError");
735
- }
736
- var init_safe_error = __esm({
737
- "libs/core/src/safe-error.ts"() {
738
- "use strict";
739
- }
740
- });
741
-
742
- // libs/core/src/secure-proxy.ts
743
- function getBlockedPropertiesForLevel(level) {
744
- const blocked = /* @__PURE__ */ new Set();
745
- if (level !== "PERMISSIVE") {
746
- BLOCKED_PROPERTY_CATEGORIES.PROTOTYPE.forEach((p) => blocked.add(p));
747
- }
748
- switch (level) {
749
- case "STRICT":
750
- BLOCKED_PROPERTY_CATEGORIES.ITERATOR_HELPERS.forEach((p) => blocked.add(p));
751
- BLOCKED_PROPERTY_CATEGORIES.REFLECTION.forEach((p) => blocked.add(p));
752
- BLOCKED_PROPERTY_CATEGORIES.TIMING.forEach((p) => blocked.add(p));
753
- break;
754
- case "SECURE":
755
- BLOCKED_PROPERTY_CATEGORIES.ITERATOR_HELPERS.forEach((p) => blocked.add(p));
756
- break;
757
- case "STANDARD":
758
- case "PERMISSIVE":
759
- break;
1080
+ return ReflectApply2(DateProtoToISOString, value, []);
760
1081
  }
761
- return blocked;
762
- }
763
- function buildBlockedPropertiesFromConfig(config) {
764
- const blocked = /* @__PURE__ */ new Set();
765
- if (config.blockConstructor) {
766
- blocked.add("constructor");
1082
+ if (value instanceof Error) {
1083
+ const rawName = ReflectGet3(value, "name");
1084
+ const rawMessage = ReflectGet3(value, "message");
1085
+ const name = typeof rawName === "string" ? rawName : "Error";
1086
+ const message = typeof rawMessage === "string" ? rawMessage : "";
1087
+ if (allowErrors) {
1088
+ return {
1089
+ name,
1090
+ message
1091
+ // Do NOT include stack trace - could leak host information
1092
+ };
1093
+ }
1094
+ return { error: message };
767
1095
  }
768
- if (config.blockPrototype) {
769
- blocked.add("__proto__");
770
- blocked.add("prototype");
1096
+ if (value instanceof RegExp) {
1097
+ return ReflectApply2(RegExpProtoToString, value, []);
771
1098
  }
772
- if (config.blockLegacyAccessors) {
773
- blocked.add("__defineGetter__");
774
- blocked.add("__defineSetter__");
775
- blocked.add("__lookupGetter__");
776
- blocked.add("__lookupSetter__");
1099
+ if (value instanceof Map) {
1100
+ const sanitizedMap = ObjectCreate(null);
1101
+ const entries = ReflectApply2(MapProtoEntries, value, []);
1102
+ for (const [key, val] of entries) {
1103
+ if (typeof key !== "string") continue;
1104
+ if (DANGEROUS_KEYS.has(key)) continue;
1105
+ context.propCount.count++;
1106
+ sanitizedMap[key] = sanitizeValue(val, options, depth + 1, context);
1107
+ }
1108
+ return sanitizedMap;
777
1109
  }
778
- return blocked;
779
- }
780
- function createSafeReflect(securityLevel) {
781
- if (securityLevel === "STRICT") {
782
- return void 0;
1110
+ if (value instanceof Set) {
1111
+ const iter = ReflectApply2(SetProtoValues, value, []);
1112
+ const result = [];
1113
+ for (const item of iter) {
1114
+ context.propCount.count++;
1115
+ result.push(sanitizeValue(item, options, depth + 1, context));
1116
+ }
1117
+ return result;
783
1118
  }
784
- const dangerousMethods = /* @__PURE__ */ new Set(["setPrototypeOf"]);
785
- if (securityLevel === "SECURE") {
786
- dangerousMethods.add("apply");
787
- dangerousMethods.add("defineProperty");
1119
+ if (type === "object") {
1120
+ const sanitized = ObjectCreate(null);
1121
+ const keys = ObjectKeys(value);
1122
+ context.propCount.count += keys.length;
1123
+ if (context.propCount.count > maxProperties) {
1124
+ throw new Error(`Tool handler return value exceeds maximum properties (${maxProperties}).`);
1125
+ }
1126
+ for (const key of keys) {
1127
+ if (DANGEROUS_KEYS.has(key)) {
1128
+ continue;
1129
+ }
1130
+ let propValue;
1131
+ try {
1132
+ propValue = ReflectGet3(value, key);
1133
+ } catch {
1134
+ continue;
1135
+ }
1136
+ sanitized[key] = sanitizeValue(propValue, options, depth + 1, context);
1137
+ }
1138
+ return sanitized;
788
1139
  }
789
- return new Proxy(Reflect, {
790
- get(target, prop) {
791
- if (typeof prop === "string" && dangerousMethods.has(prop)) {
792
- return void 0;
1140
+ return String(value);
1141
+ }
1142
+ function estimateStringSize(str) {
1143
+ let bytes = 2;
1144
+ for (let i = 0; i < str.length; i++) {
1145
+ const code = str.charCodeAt(i);
1146
+ if (code < 128) {
1147
+ if (code === 34 || code === 92) {
1148
+ bytes += 2;
1149
+ } else if (code < 32) {
1150
+ bytes += 6;
1151
+ } else {
1152
+ bytes += 1;
793
1153
  }
794
- const value = Reflect.get(target, prop);
795
- if (typeof value === "function" && prop === "construct") {
796
- return function(ctorTarget, args, newTarget) {
797
- const AsyncFunction = async function() {
798
- }.constructor;
799
- const GeneratorFunction = function* () {
800
- }.constructor;
801
- const AsyncGeneratorFunction = async function* () {
802
- }.constructor;
803
- if (ctorTarget === Function || ctorTarget === AsyncFunction || ctorTarget === GeneratorFunction || ctorTarget === AsyncGeneratorFunction) {
804
- throw createSafeError("Reflect.construct with function constructors is blocked", "SecurityError");
805
- }
806
- return Reflect.construct(
807
- ctorTarget,
808
- args,
809
- newTarget
810
- );
811
- };
1154
+ } else if (code < 2048) {
1155
+ bytes += 2;
1156
+ } else if (code >= 55296 && code <= 56319 && i + 1 < str.length) {
1157
+ const nextCode = str.charCodeAt(i + 1);
1158
+ if (nextCode >= 56320 && nextCode <= 57343) {
1159
+ bytes += 4;
1160
+ i++;
1161
+ } else {
1162
+ bytes += 3;
812
1163
  }
813
- return value;
1164
+ } else {
1165
+ bytes += 3;
814
1166
  }
815
- });
1167
+ }
1168
+ return bytes;
816
1169
  }
817
- function getFullCacheKey(options) {
818
- const parts = [];
819
- if (options.levelConfig) {
820
- const cfg = options.levelConfig;
821
- parts.push(
822
- `L:${cfg.blockConstructor ? "C" : "c"}${cfg.blockPrototype ? "P" : "p"}${cfg.blockLegacyAccessors ? "L" : "l"}`
1170
+ function estimateSerializedSize(value, maxBytes = 0, depth = 0, maxDepth = 2e3, currentPath = /* @__PURE__ */ new Set()) {
1171
+ if (depth > maxDepth) {
1172
+ throw new Error(
1173
+ `Structure exceeds maximum nesting depth (${maxDepth}). Deeply nested structures are rejected to prevent stack overflow attacks.`
823
1174
  );
824
- } else {
825
- parts.push("L:default");
826
- }
827
- if (options.additionalBlocked && options.additionalBlocked.length > 0) {
828
- parts.push(`B:${[...options.additionalBlocked].sort().join(",")}`);
829
1175
  }
830
- const effectiveMaxDepth = options.maxDepth ?? options.levelConfig?.proxyMaxDepth ?? 10;
831
- if (effectiveMaxDepth !== 10) {
832
- parts.push(`D:${effectiveMaxDepth}`);
1176
+ if (value === null) return 4;
1177
+ if (value === void 0) return 0;
1178
+ const type = typeof value;
1179
+ if (type === "string") {
1180
+ const bytes = estimateStringSize(value);
1181
+ if (maxBytes > 0 && bytes > maxBytes) {
1182
+ throw new Error(`String serialization would exceed limit: ${bytes} > ${maxBytes} bytes`);
1183
+ }
1184
+ return bytes;
833
1185
  }
834
- if (options.throwOnBlocked) {
835
- parts.push("T:1");
1186
+ if (type === "number") {
1187
+ const num = value;
1188
+ if (!Number.isFinite(num)) return 4;
1189
+ return String(num).length;
836
1190
  }
837
- return parts.join("|") || "default";
838
- }
839
- function isProxyable(value) {
840
- if (value === null) return false;
841
- if (typeof value !== "object" && typeof value !== "function") return false;
842
- const tag = Object.prototype.toString.call(value);
843
- if (NON_PROXYABLE_TYPES.has(tag)) {
844
- return false;
1191
+ if (type === "boolean") {
1192
+ return value ? 4 : 5;
845
1193
  }
846
- return true;
847
- }
848
- function createSecureProxy(target, options = {}) {
849
- if (!isProxyable(target)) {
850
- return target;
1194
+ if (type === "bigint") {
1195
+ return String(value).length + 2;
851
1196
  }
852
- const cacheKey = getFullCacheKey(options);
853
- const targetCache = proxyCache.get(target);
854
- if (targetCache) {
855
- const cached = targetCache.get(cacheKey);
856
- if (cached) {
857
- return cached;
858
- }
1197
+ if (type === "function" || type === "symbol") {
1198
+ return 0;
859
1199
  }
860
- const baseBlocked = options.levelConfig ? buildBlockedPropertiesFromConfig(options.levelConfig) : new Set(BLOCKED_PROPERTIES);
861
- const blockedSet = /* @__PURE__ */ new Set([...baseBlocked, ...options.additionalBlocked || []]);
862
- const maxDepth = options.maxDepth ?? options.levelConfig?.proxyMaxDepth ?? 10;
863
- const throwOnBlocked = options.throwOnBlocked ?? options.levelConfig?.throwOnBlocked ?? false;
864
- function proxyWithDepth(obj, depth) {
865
- if (!isProxyable(obj)) {
866
- return obj;
867
- }
868
- const objCache = proxyCache.get(obj);
869
- if (objCache) {
870
- const cachedProxy = objCache.get(cacheKey);
871
- if (cachedProxy) {
872
- return cachedProxy;
873
- }
874
- }
875
- if (depth > maxDepth) {
876
- return obj;
1200
+ if (Array.isArray(value)) {
1201
+ if (currentPath.has(value)) {
1202
+ return 4;
877
1203
  }
878
- const proxy = new Proxy(obj, {
879
- get(target2, property, receiver) {
880
- const propName = typeof property === "symbol" ? property.toString() : property;
881
- const descriptor = Object.getOwnPropertyDescriptor(target2, property);
882
- const isNonConfigurable = descriptor && !descriptor.configurable;
883
- if (typeof propName === "string" && blockedSet.has(propName)) {
884
- if (options.onBlocked) {
885
- options.onBlocked(target2, propName);
886
- }
887
- if (isNonConfigurable && descriptor && !descriptor.writable) {
888
- return Reflect.get(target2, property, receiver);
889
- }
890
- if (throwOnBlocked) {
891
- throw createSafeError(
892
- `Security violation: Access to '${propName}' is blocked. This property can be used for sandbox escape attacks.`,
893
- "SecurityError"
894
- );
895
- }
896
- return void 0;
897
- }
898
- if (typeof target2 === "function" && typeof propName === "string" && FUNCTION_BLOCKED_PROPERTIES.has(propName)) {
899
- if (options.onBlocked) {
900
- options.onBlocked(target2, propName);
901
- }
902
- if (isNonConfigurable && descriptor && !descriptor.writable) {
903
- return Reflect.get(target2, property, receiver);
904
- }
905
- if (throwOnBlocked) {
906
- throw createSafeError(
907
- `Security violation: Access to '${propName}' is blocked. This property can be used for sandbox escape attacks.`,
908
- "SecurityError"
909
- );
910
- }
911
- return void 0;
912
- }
913
- const value = Reflect.get(target2, property, receiver);
914
- if (typeof value === "function") {
915
- const tag = Object.prototype.toString.call(target2);
916
- if (INTERNAL_SLOT_TYPES.has(tag)) {
917
- const boundMethod = value.bind(target2);
918
- return proxyWithDepth(boundMethod, depth + 1);
919
- }
920
- }
921
- if (value !== null && (typeof value === "object" || typeof value === "function")) {
922
- return proxyWithDepth(value, depth + 1);
923
- }
924
- return value;
925
- },
926
- // Block setting dangerous properties
927
- set(target2, property, value, receiver) {
928
- const propName = typeof property === "symbol" ? property.toString() : property;
929
- if (typeof propName === "string" && blockedSet.has(propName)) {
930
- if (options.onBlocked) {
931
- options.onBlocked(target2, propName);
932
- }
933
- if (throwOnBlocked) {
934
- throw createSafeError(
935
- `Security violation: Setting '${propName}' is blocked. This property can be used for sandbox escape attacks.`,
936
- "SecurityError"
937
- );
938
- }
939
- return false;
940
- }
941
- return Reflect.set(target2, property, value, receiver);
942
- },
943
- // Block defining dangerous properties
944
- defineProperty(target2, property, descriptor) {
945
- const propName = typeof property === "symbol" ? property.toString() : property;
946
- if (typeof propName === "string" && blockedSet.has(propName)) {
947
- if (options.onBlocked) {
948
- options.onBlocked(target2, propName);
949
- }
950
- if (throwOnBlocked) {
951
- throw createSafeError(
952
- `Security violation: Defining '${propName}' is blocked. This property can be used for sandbox escape attacks.`,
953
- "SecurityError"
954
- );
955
- }
956
- return false;
957
- }
958
- return Reflect.defineProperty(target2, property, descriptor);
959
- },
960
- // Filter blocked property names from enumeration (Object.keys, Object.entries, etc.)
961
- // Must respect proxy invariants: non-configurable own properties cannot be hidden
962
- ownKeys(target2) {
963
- const keys = Reflect.ownKeys(target2);
964
- return keys.filter((key) => {
965
- const keyStr = typeof key === "symbol" ? key.toString() : key;
966
- if (typeof keyStr !== "string" || !blockedSet.has(keyStr)) {
967
- return true;
968
- }
969
- const descriptor = Object.getOwnPropertyDescriptor(target2, key);
970
- if (descriptor && !descriptor.configurable) {
971
- return true;
972
- }
973
- return false;
974
- });
975
- },
976
- // Hide blocked properties from property descriptor queries (defense-in-depth)
977
- // Must respect proxy invariants: non-configurable properties must return actual descriptor
978
- getOwnPropertyDescriptor(target2, property) {
979
- const propName = typeof property === "symbol" ? property.toString() : property;
980
- const descriptor = Reflect.getOwnPropertyDescriptor(target2, property);
981
- if (descriptor && !descriptor.configurable) {
982
- return descriptor;
983
- }
984
- if (typeof propName === "string" && blockedSet.has(propName)) {
985
- if (options.onBlocked) {
986
- options.onBlocked(target2, propName);
987
- }
988
- if (throwOnBlocked) {
989
- throw createSafeError(
990
- `Security violation: Access to property descriptor for '${propName}' is blocked. This property can be used for sandbox escape attacks.`,
991
- "SecurityError"
992
- );
993
- }
994
- return void 0;
995
- }
996
- return descriptor;
997
- },
998
- // Block getPrototypeOf to prevent prototype chain walking
999
- getPrototypeOf() {
1000
- return null;
1001
- },
1002
- // Block setPrototypeOf
1003
- setPrototypeOf() {
1004
- return false;
1005
- },
1006
- // Intercept function calls to proxy return values
1007
- // eslint-disable-next-line @typescript-eslint/no-explicit-any -- Proxy handler signature requires any for compatibility
1008
- apply(target2, thisArg, argArray) {
1009
- const unwrappedThis = thisArg !== null && (typeof thisArg === "object" || typeof thisArg === "function") && proxyToTarget.has(thisArg) ? proxyToTarget.get(thisArg) : thisArg;
1010
- const result = Reflect.apply(target2, unwrappedThis, argArray);
1011
- if (isProxyable(result)) {
1012
- return proxyWithDepth(result, depth + 1);
1013
- }
1014
- return result;
1015
- },
1016
- // Intercept constructor calls to proxy the created instance. Without this, code such as
1017
- // `new (wrappedCtor)()` would return a RAW object whose prototype chain reaches the
1018
- // host Function constructor — the same escape class the apply trap closes for calls.
1019
- // eslint-disable-next-line @typescript-eslint/no-explicit-any -- Proxy handler signature requires any for compatibility
1020
- construct(target2, argArray, newTarget) {
1021
- const instance = Reflect.construct(target2, argArray, newTarget === proxy ? target2 : newTarget);
1022
- if (isProxyable(instance)) {
1023
- return proxyWithDepth(instance, depth + 1);
1024
- }
1025
- return instance;
1204
+ currentPath.add(value);
1205
+ let size = 2;
1206
+ for (let i = 0; i < value.length; i++) {
1207
+ if (i > 0) size += 1;
1208
+ let elementSize = estimateSerializedSize(value[i], maxBytes, depth + 1, maxDepth, currentPath);
1209
+ if (elementSize === 0) elementSize = 4;
1210
+ size += elementSize;
1211
+ if (maxBytes > 0 && size > maxBytes) {
1212
+ currentPath.delete(value);
1213
+ throw new Error(
1214
+ `Array serialization would exceed limit: estimated ${size}+ > ${maxBytes} bytes. This often indicates repeated references to large strings that expand during JSON serialization.`
1215
+ );
1026
1216
  }
1027
- });
1028
- let objCacheMap = proxyCache.get(obj);
1029
- if (!objCacheMap) {
1030
- objCacheMap = /* @__PURE__ */ new Map();
1031
- proxyCache.set(obj, objCacheMap);
1032
1217
  }
1033
- objCacheMap.set(cacheKey, proxy);
1034
- proxySet.add(proxy);
1035
- proxyToTarget.set(proxy, obj);
1036
- return proxy;
1218
+ currentPath.delete(value);
1219
+ return size;
1037
1220
  }
1038
- return proxyWithDepth(target, 0);
1039
- }
1040
- function wrapGlobalsWithSecureProxy(globals, options = {}) {
1041
- const wrapped = {};
1042
- for (const [key, value] of Object.entries(globals)) {
1043
- if (value !== null && (typeof value === "object" || typeof value === "function")) {
1044
- wrapped[key] = createSecureProxy(value, options);
1045
- } else {
1046
- wrapped[key] = value;
1221
+ if (type === "object" && value !== null) {
1222
+ if (currentPath.has(value)) {
1223
+ return 4;
1224
+ }
1225
+ currentPath.add(value);
1226
+ if (value instanceof Date) {
1227
+ currentPath.delete(value);
1228
+ return 26;
1229
+ }
1230
+ if (value instanceof RegExp) {
1231
+ currentPath.delete(value);
1232
+ return 2;
1233
+ }
1234
+ let size = 2;
1235
+ const keys = Object.keys(value);
1236
+ let first = true;
1237
+ for (const key of keys) {
1238
+ if (key === "__proto__" || key === "constructor") continue;
1239
+ if (!first) size += 1;
1240
+ first = false;
1241
+ size += estimateStringSize(key) + 1;
1242
+ let propValue;
1243
+ try {
1244
+ propValue = value[key];
1245
+ } catch {
1246
+ continue;
1247
+ }
1248
+ const valueSize = estimateSerializedSize(propValue, maxBytes, depth + 1, maxDepth, currentPath);
1249
+ size += valueSize;
1250
+ if (maxBytes > 0 && size > maxBytes) {
1251
+ currentPath.delete(value);
1252
+ throw new Error(
1253
+ `Object serialization would exceed limit: estimated ${size}+ > ${maxBytes} bytes. This often indicates repeated references to large strings that expand during JSON serialization.`
1254
+ );
1255
+ }
1047
1256
  }
1257
+ currentPath.delete(value);
1258
+ return size;
1048
1259
  }
1049
- return wrapped;
1050
- }
1051
- function createSecureStandardLibrary(options = {}) {
1052
- return wrapGlobalsWithSecureProxy(
1053
- {
1054
- Math,
1055
- JSON,
1056
- Array,
1057
- Object,
1058
- String,
1059
- Number,
1060
- Date
1061
- // Note: We intentionally don't include:
1062
- // - Function (dangerous)
1063
- // - eval (dangerous)
1064
- // - Proxy, Reflect (meta-programming)
1065
- },
1066
- options
1067
- );
1260
+ return 0;
1068
1261
  }
1069
- function isSecureProxy(obj) {
1070
- if (obj === null || typeof obj !== "object") {
1071
- return false;
1262
+ function checkSerializedSize(value, maxBytes) {
1263
+ try {
1264
+ const estimatedBytes = estimateSerializedSize(value, maxBytes);
1265
+ return { ok: true, estimatedBytes };
1266
+ } catch (err) {
1267
+ return { ok: false, error: err instanceof Error ? err.message : "Unknown error" };
1072
1268
  }
1073
- return proxySet.has(obj);
1074
1269
  }
1075
- var BLOCKED_PROPERTY_CATEGORIES, BLOCKED_PROPERTIES, DEFAULT_SECURE_PROXY_CONFIG, FUNCTION_BLOCKED_PROPERTIES, proxyCache, proxySet, proxyToTarget, NON_PROXYABLE_TYPES, INTERNAL_SLOT_TYPES;
1076
- var init_secure_proxy = __esm({
1077
- "libs/core/src/secure-proxy.ts"() {
1270
+ var DANGEROUS_KEYS, ReflectApply2, ReflectGet3, ArrayIsArray, ObjectKeys, ObjectCreate, NumberIsFinite2, MathFloor2, MapProtoEntries, SetProtoValues, DateProtoGetTime, DateProtoToISOString, RegExpProtoToString;
1271
+ var init_value_sanitizer = __esm({
1272
+ "libs/core/src/value-sanitizer.ts"() {
1078
1273
  "use strict";
1079
- init_safe_error();
1080
- BLOCKED_PROPERTY_CATEGORIES = {
1081
- /**
1082
- * Core prototype manipulation properties (always blocked except PERMISSIVE)
1083
- */
1084
- PROTOTYPE: /* @__PURE__ */ new Set([
1085
- "constructor",
1086
- "__proto__",
1087
- "prototype",
1088
- "__defineGetter__",
1089
- "__defineSetter__",
1090
- "__lookupGetter__",
1091
- "__lookupSetter__"
1092
- ]),
1093
- /**
1094
- * Node.js 24 Iterator helper method names
1095
- * Blocked at STRICT/SECURE to prevent prototype chain access via iterators
1096
- */
1097
- ITERATOR_HELPERS: /* @__PURE__ */ new Set(["toArray", "forEach", "some", "every", "find", "reduce", "flatMap", "drop", "take"]),
1098
- /**
1099
- * Reflection properties on Object
1100
- * Blocked at STRICT to prevent introspection attacks
1101
- */
1102
- REFLECTION: /* @__PURE__ */ new Set([
1103
- "getOwnPropertyDescriptor",
1104
- "getOwnPropertyDescriptors",
1105
- "getOwnPropertyNames",
1106
- "getOwnPropertySymbols",
1107
- "getPrototypeOf",
1108
- "setPrototypeOf",
1109
- "defineProperty",
1110
- "defineProperties",
1111
- "preventExtensions",
1112
- "isExtensible",
1113
- "seal",
1114
- "isSealed",
1115
- "freeze",
1116
- "isFrozen"
1117
- ]),
1118
- /**
1119
- * Timing API properties
1120
- * Blocked at STRICT to prevent timing attacks
1121
- */
1122
- TIMING: /* @__PURE__ */ new Set(["hrtime", "timeOrigin"])
1123
- };
1124
- BLOCKED_PROPERTIES = /* @__PURE__ */ new Set([
1125
- // Code execution
1126
- "constructor",
1127
- // Prototype manipulation
1128
- "__proto__",
1129
- "prototype",
1130
- // Legacy getter/setter definition
1131
- "__defineGetter__",
1132
- "__defineSetter__",
1133
- "__lookupGetter__",
1134
- "__lookupSetter__"
1135
- ]);
1136
- DEFAULT_SECURE_PROXY_CONFIG = {
1137
- blockConstructor: true,
1138
- blockPrototype: true,
1139
- blockLegacyAccessors: true,
1140
- proxyMaxDepth: 10,
1141
- throwOnBlocked: true
1142
- };
1143
- FUNCTION_BLOCKED_PROPERTIES = /* @__PURE__ */ new Set([
1144
- // Function object properties that could leak information
1145
- "caller",
1146
- // Deprecated but still exists
1147
- "arguments"
1148
- // Deprecated but still exists
1149
- // Binding/applying could be used for exploitation
1150
- // Note: We may want to allow these in some cases
1151
- // 'bind',
1152
- // 'call',
1153
- // 'apply',
1154
- ]);
1155
- proxyCache = /* @__PURE__ */ new WeakMap();
1156
- proxySet = /* @__PURE__ */ new WeakSet();
1157
- proxyToTarget = /* @__PURE__ */ new WeakMap();
1158
- NON_PROXYABLE_TYPES = /* @__PURE__ */ new Set([
1159
- // Map/Set have internal slots but we may need to proxy them in the future
1160
- "[object Map]",
1161
- "[object Set]",
1162
- "[object WeakMap]",
1163
- "[object WeakSet]",
1164
- "[object ArrayBuffer]",
1165
- "[object SharedArrayBuffer]",
1166
- "[object DataView]",
1167
- "[object Int8Array]",
1168
- "[object Uint8Array]",
1169
- "[object Uint8ClampedArray]",
1170
- "[object Int16Array]",
1171
- "[object Uint16Array]",
1172
- "[object Int32Array]",
1173
- "[object Uint32Array]",
1174
- "[object Float32Array]",
1175
- "[object Float64Array]",
1176
- "[object BigInt64Array]",
1177
- "[object BigUint64Array]",
1178
- // Generators and iterators use internal slots
1179
- "[object Generator]",
1180
- "[object AsyncGenerator]",
1181
- "[object GeneratorFunction]",
1182
- "[object AsyncGeneratorFunction]",
1183
- // Built-in iterators
1184
- "[object Array Iterator]",
1185
- "[object String Iterator]",
1186
- "[object Map Iterator]",
1187
- "[object Set Iterator]",
1188
- "[object RegExp String Iterator]"
1189
- ]);
1190
- INTERNAL_SLOT_TYPES = /* @__PURE__ */ new Set(["[object Promise]"]);
1274
+ DANGEROUS_KEYS = /* @__PURE__ */ new Set(["__proto__", "constructor"]);
1275
+ ReflectApply2 = Reflect.apply;
1276
+ ReflectGet3 = Reflect.get;
1277
+ ArrayIsArray = Array.isArray;
1278
+ ObjectKeys = Object.keys;
1279
+ ObjectCreate = Object.create;
1280
+ NumberIsFinite2 = Number.isFinite;
1281
+ MathFloor2 = Math.floor;
1282
+ MapProtoEntries = Map.prototype.entries;
1283
+ SetProtoValues = Set.prototype.values;
1284
+ DateProtoGetTime = Date.prototype.getTime;
1285
+ DateProtoToISOString = Date.prototype.toISOString;
1286
+ RegExpProtoToString = RegExp.prototype.toString;
1191
1287
  }
1192
1288
  });
1193
1289
 
@@ -1908,7 +2004,12 @@ ${stackTraceHardeningCode}
1908
2004
  function __ag_createSecureProxy(obj, depth) {
1909
2005
  if (depth === undefined) depth = 0;
1910
2006
  if (!__ag_Proxy || !__ag_Reflect) return obj;
1911
- if (depth > 10) return obj;
2007
+ // Fail CLOSED past the recursion backstop: returning the raw target would leak an
2008
+ // unwrapped reference (see MEMBRANE_MAX_RECURSION_DEPTH). Use the hardened safe-error
2009
+ // helper (sanitized stack, nulled constructor/proto) rather than a raw Error.
2010
+ if (depth > ${MEMBRANE_MAX_RECURSION_DEPTH}) {
2011
+ throw __ag_createSafeError('Security violation: secure-proxy recursion depth exceeded.');
2012
+ }
1912
2013
  if (obj === null || (typeof obj !== 'object' && typeof obj !== 'function')) return obj;
1913
2014
 
1914
2015
  if (__ag_proxyCache) {
@@ -1931,8 +2032,15 @@ ${stackTraceHardeningCode}
1931
2032
  if (typeof value === 'function') {
1932
2033
  // Bind methods to preserve internal slots when relevant.
1933
2034
  try { value = value.bind(target); } catch (e) {}
2035
+ return __ag_createSecureProxy(value, depth + 1);
2036
+ }
2037
+ // Only objects still need proxying; primitives (e.g. length/name) are inert and must be
2038
+ // returned directly, so a deep chain cannot turn a safe primitive read into a
2039
+ // recursion-depth error.
2040
+ if (value !== null && typeof value === 'object') {
2041
+ return __ag_createSecureProxy(value, depth + 1);
1934
2042
  }
1935
- return __ag_createSecureProxy(value, depth + 1);
2043
+ return value;
1936
2044
  },
1937
2045
  apply: function(target, thisArg, args) {
1938
2046
  return __ag_Reflect.apply(target, thisArg, args);
@@ -2185,6 +2293,29 @@ ${stackTraceHardeningCode}
2185
2293
  } catch (e) { /* ignore */ }
2186
2294
  }
2187
2295
 
2296
+ // SECURITY (GHSA-3279): pin pristine intrinsics BEFORE any sandbox code runs, so the membrane
2297
+ // traps and the error hardening below never re-read a realm global the sandbox can overwrite.
2298
+ // The reported escape replaced Object.getOwnPropertyDescriptor with a hook; the get trap then
2299
+ // called it and handed the attacker the RAW target of a membrane proxy (the host Promise from
2300
+ // callTool), reaching the host Function constructor. The same gadget aimed at the Object.*
2301
+ // mutators below would let an attacker observe safe-error construction or defeat the final
2302
+ // freeze, leaving the returned error with a live prototype and constructor chain. Using
2303
+ // captured references makes a later monkeypatch a no-op.
2304
+ const __ag_getOwnPropertyDescriptor = Object.getOwnPropertyDescriptor;
2305
+ const __ag_defineProperty = Object.defineProperty;
2306
+ const __ag_defineProperties = Object.defineProperties;
2307
+ const __ag_setPrototypeOf = Object.setPrototypeOf;
2308
+ const __ag_objectCreate = Object.create;
2309
+ const __ag_objectFreeze = Object.freeze;
2310
+ const __ag_ReflectGet = Reflect.get;
2311
+ const __ag_ReflectSet = Reflect.set;
2312
+ const __ag_ReflectDefineProperty = Reflect.defineProperty;
2313
+ const __ag_ReflectGetOwnPropertyDescriptor = Reflect.getOwnPropertyDescriptor;
2314
+ const __ag_ReflectOwnKeys = Reflect.ownKeys;
2315
+ const __ag_ReflectApply = Reflect.apply;
2316
+ const __ag_hasOwnProperty = Object.prototype.hasOwnProperty;
2317
+ const __ag_functionBind = Function.prototype.bind;
2318
+
2188
2319
  /**
2189
2320
  * Creates a "safe" error object that cannot be used to escape the sandbox.
2190
2321
  *
@@ -2207,7 +2338,7 @@ ${stackTraceHardeningCode}
2207
2338
  var error = new Error(message);
2208
2339
  // NOTE: Use Object.defineProperty instead of direct assignment because
2209
2340
  // Error.prototype.name is frozen, and in strict mode direct assignment fails.
2210
- Object.defineProperty(error, 'name', {
2341
+ __ag_defineProperty(error, 'name', {
2211
2342
  value: name,
2212
2343
  writable: true,
2213
2344
  enumerable: false,
@@ -2216,12 +2347,12 @@ ${stackTraceHardeningCode}
2216
2347
 
2217
2348
  // CRITICAL: sever the *actual* prototype chain (native getters / Object.getPrototypeOf).
2218
2349
  // A shadowing __proto__ data property is not sufficient.
2219
- Object.setPrototypeOf(error, null);
2350
+ __ag_setPrototypeOf(error, null);
2220
2351
 
2221
2352
  // Create a null-prototype object to use as a safe "constructor"
2222
2353
  // This object has no prototype chain to climb
2223
- var SafeConstructor = Object.create(null);
2224
- Object.defineProperties(SafeConstructor, {
2354
+ var SafeConstructor = __ag_objectCreate(null);
2355
+ __ag_defineProperties(SafeConstructor, {
2225
2356
  // Make constructor point to itself to break the chain
2226
2357
  constructor: {
2227
2358
  value: SafeConstructor,
@@ -2244,11 +2375,11 @@ ${stackTraceHardeningCode}
2244
2375
  configurable: false
2245
2376
  }
2246
2377
  });
2247
- Object.freeze(SafeConstructor);
2378
+ __ag_objectFreeze(SafeConstructor);
2248
2379
 
2249
2380
  // Override the constructor property on the error instance
2250
2381
  // This breaks the prototype chain: err.constructor.constructor no longer reaches Function
2251
- Object.defineProperty(error, 'constructor', {
2382
+ __ag_defineProperty(error, 'constructor', {
2252
2383
  value: SafeConstructor,
2253
2384
  writable: false,
2254
2385
  enumerable: false,
@@ -2257,7 +2388,7 @@ ${stackTraceHardeningCode}
2257
2388
 
2258
2389
  // SECURITY: Override __proto__ on the error instance to prevent prototype chain escape
2259
2390
  // Attack vector blocked: err.__proto__.constructor.constructor('malicious code')()
2260
- Object.defineProperty(error, '__proto__', {
2391
+ __ag_defineProperty(error, '__proto__', {
2261
2392
  value: null,
2262
2393
  writable: false,
2263
2394
  enumerable: false,
@@ -2267,7 +2398,7 @@ ${stackTraceHardeningCode}
2267
2398
  // SECURITY: Remove the stack property to prevent information leakage (Vector 1230)
2268
2399
  // The stack trace can reveal internal implementation details like function names,
2269
2400
  // file paths, and line numbers which can be used for reconnaissance attacks.
2270
- Object.defineProperty(error, 'stack', {
2401
+ __ag_defineProperty(error, 'stack', {
2271
2402
  value: undefined,
2272
2403
  writable: false,
2273
2404
  enumerable: false,
@@ -2276,7 +2407,7 @@ ${stackTraceHardeningCode}
2276
2407
 
2277
2408
  // Add a unique marker to identify this as a safe error from our runtime
2278
2409
  // This is used by suspicious pattern detection to distinguish our errors from user errors
2279
- Object.defineProperty(error, SAFE_ERROR_MARKER, {
2410
+ __ag_defineProperty(error, SAFE_ERROR_MARKER, {
2280
2411
  value: true,
2281
2412
  writable: false,
2282
2413
  enumerable: false,
@@ -2284,7 +2415,7 @@ ${stackTraceHardeningCode}
2284
2415
  });
2285
2416
 
2286
2417
  // Freeze the error to prevent modifications
2287
- Object.freeze(error);
2418
+ __ag_objectFreeze(error);
2288
2419
 
2289
2420
  return error;
2290
2421
  }
@@ -2328,8 +2459,10 @@ ${stackTraceHardeningCode}
2328
2459
  // Reference ID pattern for detecting sidecar references
2329
2460
  const refIdPattern = /^__REF_[0-9a-f]{8}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{12}__$/i;
2330
2461
 
2331
- // Proxy cache to avoid infinite recursion and duplicate wrapping
2462
+ // Proxy caches to avoid infinite recursion and duplicate wrapping. Host-owned values are
2463
+ // cached separately from realm-owned ones because the two use different blocking rules.
2332
2464
  const proxyCache = new WeakMap();
2465
+ const hostProxyCache = new WeakMap();
2333
2466
 
2334
2467
  /**
2335
2468
  * Create a secure proxy that blocks access to dangerous properties
@@ -2338,10 +2471,23 @@ ${stackTraceHardeningCode}
2338
2471
  * IMPORTANT: Must respect JavaScript proxy invariants:
2339
2472
  * - Non-configurable properties must return their actual value
2340
2473
  * - Non-configurable non-writable properties cannot be hidden
2474
+ *
2475
+ * The host flag marks a value that originates in the HOST realm (custom globals and
2476
+ * everything reachable from what they return). The host realm is the only one with code
2477
+ * generation from strings enabled, so a raw reference that escapes from it is remote code
2478
+ * execution; such a subtree refuses the reads a realm-owned object is allowed to answer.
2341
2479
  */
2342
- function createSecureProxy(obj, depth) {
2480
+ function createSecureProxy(obj, depth, host) {
2343
2481
  if (depth === undefined) depth = 0;
2344
- if (depth > 10) return obj; // Max depth to prevent infinite recursion
2482
+ host = host === true;
2483
+ // Recursion backstop. Fail CLOSED: returning the raw target here was the reported escape.
2484
+ // A bind chain inflates depth (each read binds a FRESH function, so the identity cache never
2485
+ // dedupes it) past the cap, and the raw host function prototype chain reaches the host
2486
+ // Function constructor for RCE. Throwing keeps the membrane total; the cap sits far above any
2487
+ // legitimately-deep (pre-sanitized) value so real data is never rejected.
2488
+ if (depth > ${MEMBRANE_MAX_RECURSION_DEPTH}) {
2489
+ throw createSafeError('Security violation: secure-proxy recursion depth exceeded.');
2490
+ }
2345
2491
 
2346
2492
  // Skip primitives and null
2347
2493
  if (obj === null || typeof obj !== 'object' && typeof obj !== 'function') {
@@ -2349,8 +2495,9 @@ ${stackTraceHardeningCode}
2349
2495
  }
2350
2496
 
2351
2497
  // Check cache
2352
- if (proxyCache.has(obj)) {
2353
- return proxyCache.get(obj);
2498
+ var cache = host ? hostProxyCache : proxyCache;
2499
+ if (cache.has(obj)) {
2500
+ return cache.get(obj);
2354
2501
  }
2355
2502
 
2356
2503
  var proxy = new Proxy(obj, {
@@ -2358,23 +2505,35 @@ ${stackTraceHardeningCode}
2358
2505
  var propName = String(property);
2359
2506
 
2360
2507
  // Check if property is non-configurable (proxy invariant requires returning actual value)
2361
- var descriptor = Object.getOwnPropertyDescriptor(target, property);
2508
+ var descriptor = __ag_getOwnPropertyDescriptor(target, property);
2362
2509
  var isNonConfigurable = descriptor && !descriptor.configurable;
2363
2510
 
2364
2511
  // Proxy invariant: if the target has a non-configurable, non-writable data property,
2365
2512
  // the proxy must return the exact same value (cannot wrap/bind/proxy it).
2366
2513
  // This matters for hardened properties like Error.prepareStackTrace.
2367
2514
  if (descriptor && isNonConfigurable && 'value' in descriptor && descriptor.writable === false) {
2368
- return descriptor.value;
2515
+ var exactValue = descriptor.value;
2516
+ // On a host-owned value the exact reference cannot be handed over: it would cross
2517
+ // the barrier unwrapped and its prototype chain reaches the host Function
2518
+ // constructor. Primitives stay safe to report, so only object/function values are
2519
+ // refused, and throwing satisfies the invariant that wrapping would break.
2520
+ if (host && exactValue !== null && (typeof exactValue === 'object' || typeof exactValue === 'function')) {
2521
+ throw createSafeError(
2522
+ "Security violation: Access to '" + propName + "' is blocked. " +
2523
+ "This property cannot be exposed without breaking the sandbox barrier."
2524
+ );
2525
+ }
2526
+ return exactValue;
2369
2527
  }
2370
2528
 
2371
- // Block dangerous properties - but respect proxy invariants
2529
+ // Block dangerous properties. The ONLY [[Get]] invariant that forces a specific return
2530
+ // value is for a non-writable + non-configurable DATA property \u2014 already handled above.
2531
+ // Anything reaching here is configurable, a non-configurable WRITABLE data property (such
2532
+ // as a function own prototype), or a non-configurable accessor; the invariant constrains
2533
+ // none of these, so the trap must never hand back the raw value. GHSA-3279: the old
2534
+ // "isNonConfigurable and not host -> return Reflect.get(...)" branch leaked the raw
2535
+ // writable prototype, exposing a parent-realm Object and defeating the membrane.
2372
2536
  if (blockedPropertiesSet.has(propName)) {
2373
- // For non-configurable properties, we MUST return the actual value
2374
- // (JavaScript proxy invariant - can't hide non-configurable properties)
2375
- if (isNonConfigurable) {
2376
- return Reflect.get(target, property, receiver);
2377
- }
2378
2537
  if (throwOnBlocked) {
2379
2538
  throw createSafeError(
2380
2539
  "Security violation: Access to '" + propName + "' is blocked. " +
@@ -2384,19 +2543,19 @@ ${stackTraceHardeningCode}
2384
2543
  return undefined;
2385
2544
  }
2386
2545
 
2387
- var value = Reflect.get(target, property, receiver);
2546
+ var value = __ag_ReflectGet(target, property, receiver);
2388
2547
 
2389
2548
  // For function values, bind to target first (preserves internal slot access for Promises, etc.)
2390
2549
  // Then recursively proxy the bound function to block constructor access
2391
2550
  if (typeof value === 'function') {
2392
- var boundMethod = value.bind(target);
2393
- return createSecureProxy(boundMethod, depth + 1);
2551
+ var boundMethod = __ag_functionBind.call(value, target);
2552
+ return createSecureProxy(boundMethod, depth + 1, host);
2394
2553
  }
2395
2554
 
2396
2555
  // Recursively proxy nested objects to maintain security barrier
2397
2556
  // This prevents attacks like: process.env.__proto__.constructor
2398
2557
  if (value !== null && typeof value === 'object') {
2399
- return createSecureProxy(value, depth + 1);
2558
+ return createSecureProxy(value, depth + 1, host);
2400
2559
  }
2401
2560
 
2402
2561
  return value;
@@ -2412,7 +2571,7 @@ ${stackTraceHardeningCode}
2412
2571
  }
2413
2572
  return false;
2414
2573
  }
2415
- return Reflect.set(target, property, value, receiver);
2574
+ return __ag_ReflectSet(target, property, value, receiver);
2416
2575
  },
2417
2576
  defineProperty: function(target, property, descriptor) {
2418
2577
  var propName = String(property);
@@ -2425,13 +2584,40 @@ ${stackTraceHardeningCode}
2425
2584
  }
2426
2585
  return false;
2427
2586
  }
2428
- return Reflect.defineProperty(target, property, descriptor);
2587
+ return __ag_ReflectDefineProperty(target, property, descriptor);
2429
2588
  },
2430
2589
  getOwnPropertyDescriptor: function(target, property) {
2431
2590
  var propName = String(property);
2432
- var descriptor = Reflect.getOwnPropertyDescriptor(target, property);
2591
+ var descriptor = __ag_ReflectGetOwnPropertyDescriptor(target, property);
2592
+
2593
+ // Mirror the get trap's host-owned pinned-value refusal: a non-configurable, non-writable
2594
+ // data property must be reported with its exact value (proxy invariant), so on a HOST-owned
2595
+ // value an object/function would cross the barrier unwrapped via descriptor.value and its
2596
+ // prototype chain reaches the host Function constructor. Deny the read instead (throwing
2597
+ // satisfies the invariant); primitives stay safe to report.
2598
+ if (host && descriptor && !descriptor.configurable && descriptor.writable === false && 'value' in descriptor) {
2599
+ var exactValue = descriptor.value;
2600
+ if (exactValue !== null && (typeof exactValue === 'object' || typeof exactValue === 'function')) {
2601
+ throw createSafeError(
2602
+ "Security violation: Access to property descriptor for '" + propName + "' is blocked. " +
2603
+ "This property cannot be exposed without breaking the sandbox barrier."
2604
+ );
2605
+ }
2606
+ return descriptor;
2607
+ }
2608
+
2609
+ // Accessor descriptors expose raw getter/setter functions. A non-configurable accessor
2610
+ // must be reported with its exact get/set (proxy invariant) and so cannot be wrapped \u2014
2611
+ // deny it if it carries a function whose prototype chain reaches the host constructor.
2612
+ if (descriptor && !descriptor.configurable &&
2613
+ (typeof descriptor.get === 'function' || typeof descriptor.set === 'function')) {
2614
+ throw createSafeError(
2615
+ "Security violation: Access to property descriptor for '" + propName + "' is blocked. " +
2616
+ "This property cannot be exposed without breaking the sandbox barrier."
2617
+ );
2618
+ }
2433
2619
 
2434
- // Must return actual descriptor for non-configurable properties (proxy invariant)
2620
+ // Must return actual descriptor for other non-configurable properties (proxy invariant)
2435
2621
  if (descriptor && !descriptor.configurable) {
2436
2622
  return descriptor;
2437
2623
  }
@@ -2446,10 +2632,32 @@ ${stackTraceHardeningCode}
2446
2632
  }
2447
2633
  return undefined;
2448
2634
  }
2635
+
2636
+ // A configurable accessor's getter/setter may be safely proxied so the descriptor never
2637
+ // hands back a raw function that leads to the host Function constructor.
2638
+ if (descriptor && (typeof descriptor.get === 'function' || typeof descriptor.set === 'function')) {
2639
+ var accessorWrapped = {};
2640
+ for (var ak in descriptor) { if (__ag_hasOwnProperty.call(descriptor, ak)) accessorWrapped[ak] = descriptor[ak]; }
2641
+ if (typeof descriptor.get === 'function') accessorWrapped.get = createSecureProxy(descriptor.get, depth + 1, host);
2642
+ if (typeof descriptor.set === 'function') accessorWrapped.set = createSecureProxy(descriptor.set, depth + 1, host);
2643
+ return accessorWrapped;
2644
+ }
2645
+
2646
+ // Wrap object/function values so a descriptor read cannot hand back a raw reference that
2647
+ // the get trap would otherwise have proxied.
2648
+ if (descriptor && 'value' in descriptor) {
2649
+ var value = descriptor.value;
2650
+ if (value !== null && (typeof value === 'object' || typeof value === 'function')) {
2651
+ var wrapped = {};
2652
+ for (var dk in descriptor) { if (__ag_hasOwnProperty.call(descriptor, dk)) wrapped[dk] = descriptor[dk]; }
2653
+ wrapped.value = createSecureProxy(value, depth + 1, host);
2654
+ return wrapped;
2655
+ }
2656
+ }
2449
2657
  return descriptor;
2450
2658
  },
2451
2659
  ownKeys: function(target) {
2452
- var keys = Reflect.ownKeys(target);
2660
+ var keys = __ag_ReflectOwnKeys(target);
2453
2661
  return keys.filter(function(key) {
2454
2662
  var keyStr = String(key);
2455
2663
  // Keep non-blocked properties
@@ -2457,7 +2665,7 @@ ${stackTraceHardeningCode}
2457
2665
  return true;
2458
2666
  }
2459
2667
  // Must keep non-configurable properties (proxy invariant)
2460
- var descriptor = Object.getOwnPropertyDescriptor(target, key);
2668
+ var descriptor = __ag_getOwnPropertyDescriptor(target, key);
2461
2669
  if (descriptor && !descriptor.configurable) {
2462
2670
  return true;
2463
2671
  }
@@ -2478,7 +2686,7 @@ ${stackTraceHardeningCode}
2478
2686
  // Results are re-wrapped at a FRESH depth (0) so a chain of calls such as
2479
2687
  // then().then() cannot inflate depth past the recursion cap and leak an unwrapped value.
2480
2688
  apply: function(target, thisArg, args) {
2481
- return createSecureProxy(Reflect.apply(target, thisArg, args), 0);
2689
+ return createSecureProxy(__ag_ReflectApply(target, thisArg, args), 0, host);
2482
2690
  }
2483
2691
  // NOTE: intentionally NO construct trap here (unlike the standalone secure-proxy used
2484
2692
  // for single-VM mode). Every constructor reachable from sandbox code resolves to an
@@ -2491,11 +2699,11 @@ ${stackTraceHardeningCode}
2491
2699
  // a non-extensible target), masking legitimate errors.
2492
2700
  });
2493
2701
 
2494
- proxyCache.set(obj, proxy);
2702
+ cache.set(obj, proxy);
2495
2703
  // Idempotency: re-wrapping an already-secure proxy must return it unchanged, so an apply
2496
2704
  // result that is itself already a secure proxy is not double-wrapped (which would nest
2497
2705
  // proxies and inflate depth toward the recursion cap).
2498
- proxyCache.set(proxy, proxy);
2706
+ cache.set(proxy, proxy);
2499
2707
  return proxy;
2500
2708
  }
2501
2709
 
@@ -2637,7 +2845,7 @@ ${stackTraceHardeningCode}
2637
2845
  }
2638
2846
 
2639
2847
  if (response.ok === true) {
2640
- if (Object.prototype.hasOwnProperty.call(response, 'value')) {
2848
+ if (__ag_hasOwnProperty.call(response, 'value')) {
2641
2849
  return response.value;
2642
2850
  }
2643
2851
  return undefined;
@@ -3430,10 +3638,13 @@ ${stackTraceHardeningCode}
3430
3638
  // Add user-provided globals if any (also wrapped with secure proxy and non-writable)
3431
3639
  // SECURITY: Use enumerable: false to prevent Object.assign({}, this) from copying globals
3432
3640
  // This blocks Vector 380 (Bridge-Serialized State Reflection) attack
3641
+ // Custom globals are HOST-realm values, so they are wrapped in host mode: the whole
3642
+ // subtree reachable through them (including whatever their calls return) refuses to hand
3643
+ // back a raw reference, even for descriptor shapes where a realm-owned object may.
3433
3644
  if (hostConfig.globals) {
3434
3645
  for (var uKey in hostConfig.globals) {
3435
3646
  if (hostConfig.globals.hasOwnProperty(uKey)) {
3436
- var wrappedGlobal = createSecureProxy(hostConfig.globals[uKey]);
3647
+ var wrappedGlobal = createSecureProxy(hostConfig.globals[uKey], 0, true);
3437
3648
  Object.defineProperty(innerContext, uKey, {
3438
3649
  value: wrappedGlobal,
3439
3650
  writable: false,
@@ -3542,10 +3753,11 @@ ${stackTraceHardeningCode}
3542
3753
  })();
3543
3754
  `.trim();
3544
3755
  }
3545
- var NODEJS_24_DANGEROUS_GLOBALS;
3756
+ var MEMBRANE_MAX_RECURSION_DEPTH, NODEJS_24_DANGEROUS_GLOBALS;
3546
3757
  var init_parent_vm_bootstrap = __esm({
3547
3758
  "libs/core/src/double-vm/parent-vm-bootstrap.ts"() {
3548
3759
  "use strict";
3760
+ MEMBRANE_MAX_RECURSION_DEPTH = 256;
3549
3761
  NODEJS_24_DANGEROUS_GLOBALS = {
3550
3762
  STRICT: [
3551
3763
  // Code execution - CRITICAL
@@ -6174,7 +6386,7 @@ var init_errors = __esm({
6174
6386
 
6175
6387
  // libs/core/src/adapters/worker-pool/safe-deserialize.ts
6176
6388
  function mapArraySafely(value, sanitizeItem) {
6177
- const rawLen = ReflectGet3(value, "length");
6389
+ const rawLen = ReflectGet4(value, "length");
6178
6390
  const len = typeof rawLen === "number" && NumberIsFinite3(rawLen) && rawLen >= 0 ? MathFloor3(rawLen) : 0;
6179
6391
  if (len > MAX_ARRAY_LENGTH) {
6180
6392
  throw new MessageValidationError(`Array exceeds maximum length of ${MAX_ARRAY_LENGTH}`);
@@ -6183,7 +6395,7 @@ function mapArraySafely(value, sanitizeItem) {
6183
6395
  for (let i = 0; i < len; i++) {
6184
6396
  let item;
6185
6397
  try {
6186
- item = ReflectGet3(value, i);
6398
+ item = ReflectGet4(value, i);
6187
6399
  } catch {
6188
6400
  item = void 0;
6189
6401
  }
@@ -6258,12 +6470,12 @@ function sanitizeObject(value, depth = 0) {
6258
6470
  }
6259
6471
  return result;
6260
6472
  }
6261
- var ReflectGet3, ArrayIsArray2, NumberIsFinite3, MathFloor3, MAX_ARRAY_LENGTH, DANGEROUS_KEYS2, MAX_DEPTH;
6473
+ var ReflectGet4, ArrayIsArray2, NumberIsFinite3, MathFloor3, MAX_ARRAY_LENGTH, DANGEROUS_KEYS2, MAX_DEPTH;
6262
6474
  var init_safe_deserialize = __esm({
6263
6475
  "libs/core/src/adapters/worker-pool/safe-deserialize.ts"() {
6264
6476
  "use strict";
6265
6477
  init_errors();
6266
- ReflectGet3 = Reflect.get;
6478
+ ReflectGet4 = Reflect.get;
6267
6479
  ArrayIsArray2 = Array.isArray;
6268
6480
  NumberIsFinite3 = Number.isFinite;
6269
6481
  MathFloor3 = Math.floor;
@@ -8336,6 +8548,9 @@ function validateGlobals(globals, options = {}) {
8336
8548
  }
8337
8549
  }
8338
8550
 
8551
+ // libs/core/src/enclave.ts
8552
+ init_secure_proxy();
8553
+
8339
8554
  // libs/core/src/sidecar/index.ts
8340
8555
  init_reference_config();
8341
8556
 
@@ -10436,6 +10651,9 @@ ${errorMessages}`,
10436
10651
  } else if (this.config.memoryLimit && this.config.memoryLimit > 0) {
10437
10652
  transformedCode = this.applyMemoryTrackingTransforms(transformedCode);
10438
10653
  }
10654
+ if (this.transformCode) {
10655
+ transformedCode = this.applyComputedKeyGuard(transformedCode);
10656
+ }
10439
10657
  let scoringResult;
10440
10658
  if (this.scoringGate) {
10441
10659
  scoringResult = await this.scoringGate.evaluate(transformedCode);
@@ -10533,6 +10751,21 @@ ${errorMessages}`,
10533
10751
  * @param code The code to transform
10534
10752
  * @returns The transformed code
10535
10753
  */
10754
+ applyComputedKeyGuard(code) {
10755
+ const proxyConfig = this.config.secureProxyConfig;
10756
+ const blockedKeys = [...buildBlockedPropertiesFromConfig(proxyConfig)];
10757
+ if (blockedKeys.length === 0) {
10758
+ return code;
10759
+ }
10760
+ const throwOnBlocked = proxyConfig.throwOnBlocked ?? true;
10761
+ const parseModule = (source) => acorn2.parse(source, { ecmaVersion: "latest", sourceType: "module" });
10762
+ const ast = parseModule(code);
10763
+ const { guardedCount } = (0, import_ast5.guardComputedMemberKeys)(ast, parseModule, { blockedKeys, throwOnBlocked });
10764
+ if (guardedCount === 0) {
10765
+ return code;
10766
+ }
10767
+ return (0, import_astring.generate)(ast);
10768
+ }
10536
10769
  applyMemoryTrackingTransforms(code) {
10537
10770
  const ast = acorn2.parse(code, {
10538
10771
  ecmaVersion: "latest",
@@ -11266,7 +11499,11 @@ var Interpreter = class {
11266
11499
  const obj = value ?? {};
11267
11500
  for (const prop of pattern.properties) {
11268
11501
  if (prop.type === "RestElement") continue;
11269
- const key = prop.key.name;
11502
+ if (prop.computed) throw new InterpreterError("Computed destructuring keys are not allowed");
11503
+ let key;
11504
+ if (prop.key.type === "Identifier") key = prop.key.name;
11505
+ else if (prop.key.type === "Literal") key = String(prop.key.value);
11506
+ else throw new InterpreterError("Unsupported destructuring key");
11270
11507
  if (BLOCKED_KEYS.has(key)) throw new InterpreterError(`Forbidden destructured key: ${key}`);
11271
11508
  this.bindPattern(prop.value, obj[key], scope, mutable);
11272
11509
  }