@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/esm/index.mjs CHANGED
@@ -8,6 +8,611 @@ 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
+ BLOCKED_PROPERTY_CATEGORIES.DESCRIPTOR_MUTATION.forEach((p) => blocked.add(p));
74
+ }
75
+ switch (level) {
76
+ case "STRICT":
77
+ BLOCKED_PROPERTY_CATEGORIES.ITERATOR_HELPERS.forEach((p) => blocked.add(p));
78
+ BLOCKED_PROPERTY_CATEGORIES.REFLECTION.forEach((p) => blocked.add(p));
79
+ BLOCKED_PROPERTY_CATEGORIES.TIMING.forEach((p) => blocked.add(p));
80
+ break;
81
+ case "SECURE":
82
+ BLOCKED_PROPERTY_CATEGORIES.ITERATOR_HELPERS.forEach((p) => blocked.add(p));
83
+ break;
84
+ case "STANDARD":
85
+ case "PERMISSIVE":
86
+ break;
87
+ }
88
+ return blocked;
89
+ }
90
+ function buildBlockedPropertiesFromConfig(config) {
91
+ const blocked = /* @__PURE__ */ new Set();
92
+ if (config.blockConstructor) {
93
+ blocked.add("constructor");
94
+ BLOCKED_PROPERTY_CATEGORIES.DESCRIPTOR_MUTATION.forEach((p) => blocked.add(p));
95
+ }
96
+ if (config.blockPrototype) {
97
+ blocked.add("__proto__");
98
+ blocked.add("prototype");
99
+ }
100
+ if (config.blockLegacyAccessors) {
101
+ blocked.add("__defineGetter__");
102
+ blocked.add("__defineSetter__");
103
+ blocked.add("__lookupGetter__");
104
+ blocked.add("__lookupSetter__");
105
+ }
106
+ return blocked;
107
+ }
108
+ function createSafeReflect(securityLevel) {
109
+ if (securityLevel === "STRICT") {
110
+ return void 0;
111
+ }
112
+ const dangerousMethods = /* @__PURE__ */ new Set(["setPrototypeOf"]);
113
+ if (securityLevel === "SECURE") {
114
+ dangerousMethods.add("apply");
115
+ dangerousMethods.add("defineProperty");
116
+ }
117
+ const refuseMutation = () => {
118
+ throw createSafeError("Reflect is read-only in the sandbox", "SecurityError");
119
+ };
120
+ return new Proxy(ReflectObject, {
121
+ set: refuseMutation,
122
+ defineProperty: refuseMutation,
123
+ deleteProperty: refuseMutation,
124
+ setPrototypeOf: refuseMutation,
125
+ preventExtensions: refuseMutation,
126
+ get(_target, prop) {
127
+ if (typeof prop === "string" && dangerousMethods.has(prop)) {
128
+ return void 0;
129
+ }
130
+ if (!PINNED_REFLECT_VALUES.has(prop)) {
131
+ return void 0;
132
+ }
133
+ const value = PINNED_REFLECT_VALUES.get(prop);
134
+ if (typeof value === "function" && prop === "construct") {
135
+ const safeConstruct = function(ctorTarget, args, ...newTarget) {
136
+ if (ctorTarget === FunctionCtor || ctorTarget === AsyncFunctionCtor || ctorTarget === GeneratorFunctionCtor || ctorTarget === AsyncGeneratorFunctionCtor) {
137
+ throw createSafeError("Reflect.construct with function constructors is blocked", "SecurityError");
138
+ }
139
+ if (newTarget.length === 0) {
140
+ return ReflectConstruct(ctorTarget, args);
141
+ }
142
+ return ReflectConstruct(
143
+ ctorTarget,
144
+ args,
145
+ newTarget[0]
146
+ );
147
+ };
148
+ return createSecureProxy(safeConstruct);
149
+ }
150
+ if (typeof value === "function") {
151
+ return createSecureProxy(value);
152
+ }
153
+ return value;
154
+ }
155
+ });
156
+ }
157
+ function getFullCacheKey(options) {
158
+ const parts = [];
159
+ if (options.levelConfig) {
160
+ const cfg = options.levelConfig;
161
+ parts.push(
162
+ `L:${cfg.blockConstructor ? "C" : "c"}${cfg.blockPrototype ? "P" : "p"}${cfg.blockLegacyAccessors ? "L" : "l"}`
163
+ );
164
+ } else {
165
+ parts.push("L:default");
166
+ }
167
+ if (options.additionalBlocked && options.additionalBlocked.length > 0) {
168
+ parts.push(`B:${[...options.additionalBlocked].sort().join(",")}`);
169
+ }
170
+ const effectiveMaxDepth = options.maxDepth ?? options.levelConfig?.proxyMaxDepth ?? 10;
171
+ if (effectiveMaxDepth !== 10) {
172
+ parts.push(`D:${effectiveMaxDepth}`);
173
+ }
174
+ if (options.throwOnBlocked) {
175
+ parts.push("T:1");
176
+ }
177
+ return parts.join("|") || "default";
178
+ }
179
+ function isProxyable(value) {
180
+ if (value === null) return false;
181
+ if (typeof value !== "object" && typeof value !== "function") return false;
182
+ const tag = ReflectApply(ObjectToString, value, []);
183
+ if (NON_PROXYABLE_TYPES.has(tag)) {
184
+ return false;
185
+ }
186
+ return true;
187
+ }
188
+ function createSecureProxy(target, options = {}) {
189
+ if (!isProxyable(target)) {
190
+ return target;
191
+ }
192
+ const cacheKey = getFullCacheKey(options);
193
+ const targetCache = proxyCache.get(target);
194
+ if (targetCache) {
195
+ const cached = targetCache.get(cacheKey);
196
+ if (cached) {
197
+ return cached;
198
+ }
199
+ }
200
+ const baseBlocked = options.levelConfig ? buildBlockedPropertiesFromConfig(options.levelConfig) : new Set(BLOCKED_PROPERTIES);
201
+ const blockedSet = /* @__PURE__ */ new Set([...baseBlocked, ...options.additionalBlocked || []]);
202
+ const configuredMaxDepth = options.maxDepth ?? options.levelConfig?.proxyMaxDepth ?? 10;
203
+ const maxDepth = Number.isFinite(configuredMaxDepth) ? Math.max(configuredMaxDepth, MIN_MEMBRANE_RECURSION_DEPTH) : MIN_MEMBRANE_RECURSION_DEPTH;
204
+ const throwOnBlocked = options.throwOnBlocked ?? options.levelConfig?.throwOnBlocked ?? false;
205
+ function proxyWithDepth(obj, depth) {
206
+ if (!isProxyable(obj)) {
207
+ return obj;
208
+ }
209
+ const objCache = proxyCache.get(obj);
210
+ if (objCache) {
211
+ const cachedProxy = objCache.get(cacheKey);
212
+ if (cachedProxy) {
213
+ return cachedProxy;
214
+ }
215
+ }
216
+ if (depth > maxDepth) {
217
+ throw createSafeError(
218
+ `Security violation: secure-proxy recursion depth (${maxDepth}) exceeded. The value cannot be exposed without breaking the sandbox barrier.`,
219
+ "SecurityError"
220
+ );
221
+ }
222
+ const proxy = new Proxy(obj, {
223
+ get(target2, property, receiver) {
224
+ const propName = typeof property === "symbol" ? property.toString() : property;
225
+ const descriptor = ObjectGetOwnPropertyDescriptor(target2, property);
226
+ if (descriptor && !descriptor.configurable && descriptor.writable === false && "value" in descriptor) {
227
+ const exactValue = descriptor.value;
228
+ if (exactValue !== null && (typeof exactValue === "object" || typeof exactValue === "function")) {
229
+ throw createSafeError(
230
+ `Security violation: Access to '${String(propName)}' is blocked. This property cannot be exposed without breaking the sandbox barrier.`,
231
+ "SecurityError"
232
+ );
233
+ }
234
+ return exactValue;
235
+ }
236
+ if (typeof propName === "string" && blockedSet.has(propName)) {
237
+ if (options.onBlocked) {
238
+ options.onBlocked(target2, propName);
239
+ }
240
+ if (throwOnBlocked) {
241
+ throw createSafeError(
242
+ `Security violation: Access to '${propName}' is blocked. This property can be used for sandbox escape attacks.`,
243
+ "SecurityError"
244
+ );
245
+ }
246
+ return void 0;
247
+ }
248
+ if (typeof target2 === "function" && typeof propName === "string" && FUNCTION_BLOCKED_PROPERTIES.has(propName)) {
249
+ if (options.onBlocked) {
250
+ options.onBlocked(target2, propName);
251
+ }
252
+ if (throwOnBlocked) {
253
+ throw createSafeError(
254
+ `Security violation: Access to '${propName}' is blocked. This property can be used for sandbox escape attacks.`,
255
+ "SecurityError"
256
+ );
257
+ }
258
+ return void 0;
259
+ }
260
+ const value = ReflectGet(target2, property, receiver);
261
+ if (typeof value === "function") {
262
+ const tag = ReflectApply(ObjectToString, target2, []);
263
+ if (INTERNAL_SLOT_TYPES.has(tag)) {
264
+ const boundMethod = ReflectApply(FunctionBind, value, [target2]);
265
+ return proxyWithDepth(boundMethod, depth + 1);
266
+ }
267
+ }
268
+ if (value !== null && (typeof value === "object" || typeof value === "function")) {
269
+ return proxyWithDepth(value, depth + 1);
270
+ }
271
+ return value;
272
+ },
273
+ // Block setting dangerous properties
274
+ set(target2, property, value, receiver) {
275
+ const propName = typeof property === "symbol" ? property.toString() : property;
276
+ if (typeof propName === "string" && blockedSet.has(propName)) {
277
+ if (options.onBlocked) {
278
+ options.onBlocked(target2, propName);
279
+ }
280
+ if (throwOnBlocked) {
281
+ throw createSafeError(
282
+ `Security violation: Setting '${propName}' is blocked. This property can be used for sandbox escape attacks.`,
283
+ "SecurityError"
284
+ );
285
+ }
286
+ return false;
287
+ }
288
+ return ReflectSet(target2, property, value, receiver);
289
+ },
290
+ // Block defining dangerous properties
291
+ defineProperty(target2, property, descriptor) {
292
+ const propName = typeof property === "symbol" ? property.toString() : property;
293
+ if (typeof propName === "string" && blockedSet.has(propName)) {
294
+ if (options.onBlocked) {
295
+ options.onBlocked(target2, propName);
296
+ }
297
+ if (throwOnBlocked) {
298
+ throw createSafeError(
299
+ `Security violation: Defining '${propName}' is blocked. This property can be used for sandbox escape attacks.`,
300
+ "SecurityError"
301
+ );
302
+ }
303
+ return false;
304
+ }
305
+ return ReflectDefineProperty(target2, property, descriptor);
306
+ },
307
+ // Filter blocked property names from enumeration (Object.keys, Object.entries, etc.)
308
+ // Must respect proxy invariants: non-configurable own properties cannot be hidden
309
+ ownKeys(target2) {
310
+ const keys = ReflectOwnKeys(target2);
311
+ return keys.filter((key) => {
312
+ const keyStr = typeof key === "symbol" ? key.toString() : key;
313
+ if (typeof keyStr !== "string" || !blockedSet.has(keyStr)) {
314
+ return true;
315
+ }
316
+ const descriptor = ObjectGetOwnPropertyDescriptor(target2, key);
317
+ if (descriptor && !descriptor.configurable) {
318
+ return true;
319
+ }
320
+ return false;
321
+ });
322
+ },
323
+ // Hide blocked properties from property descriptor queries (defense-in-depth)
324
+ // Must respect proxy invariants: non-configurable properties must return actual descriptor
325
+ getOwnPropertyDescriptor(target2, property) {
326
+ const propName = typeof property === "symbol" ? property.toString() : property;
327
+ const descriptor = ReflectGetOwnPropertyDescriptor(target2, property);
328
+ if (descriptor && !descriptor.configurable && descriptor.writable === false && "value" in descriptor) {
329
+ const exactValue = descriptor.value;
330
+ if (exactValue !== null && (typeof exactValue === "object" || typeof exactValue === "function")) {
331
+ throw createSafeError(
332
+ `Security violation: Access to property descriptor for '${String(propName)}' is blocked. This property cannot be exposed without breaking the sandbox barrier.`,
333
+ "SecurityError"
334
+ );
335
+ }
336
+ return descriptor;
337
+ }
338
+ if (descriptor && !descriptor.configurable && (typeof descriptor.get === "function" || typeof descriptor.set === "function")) {
339
+ throw createSafeError(
340
+ `Security violation: Access to property descriptor for '${String(propName)}' is blocked. This property cannot be exposed without breaking the sandbox barrier.`,
341
+ "SecurityError"
342
+ );
343
+ }
344
+ if (descriptor && !descriptor.configurable) {
345
+ return descriptor;
346
+ }
347
+ if (typeof propName === "string" && blockedSet.has(propName)) {
348
+ if (options.onBlocked) {
349
+ options.onBlocked(target2, propName);
350
+ }
351
+ if (throwOnBlocked) {
352
+ throw createSafeError(
353
+ `Security violation: Access to property descriptor for '${propName}' is blocked. This property can be used for sandbox escape attacks.`,
354
+ "SecurityError"
355
+ );
356
+ }
357
+ return void 0;
358
+ }
359
+ if (descriptor && (typeof descriptor.get === "function" || typeof descriptor.set === "function")) {
360
+ return {
361
+ ...descriptor,
362
+ get: typeof descriptor.get === "function" ? proxyWithDepth(descriptor.get, depth + 1) : descriptor.get,
363
+ set: typeof descriptor.set === "function" ? proxyWithDepth(descriptor.set, depth + 1) : descriptor.set
364
+ };
365
+ }
366
+ if (descriptor && "value" in descriptor) {
367
+ const value = descriptor.value;
368
+ if (value !== null && (typeof value === "object" || typeof value === "function")) {
369
+ return { ...descriptor, value: proxyWithDepth(value, depth + 1) };
370
+ }
371
+ }
372
+ return descriptor;
373
+ },
374
+ // Block getPrototypeOf to prevent prototype chain walking
375
+ getPrototypeOf() {
376
+ return null;
377
+ },
378
+ // Block setPrototypeOf
379
+ setPrototypeOf() {
380
+ return false;
381
+ },
382
+ // Intercept function calls to proxy return values
383
+ // eslint-disable-next-line @typescript-eslint/no-explicit-any -- Proxy handler signature requires any for compatibility
384
+ apply(target2, thisArg, argArray) {
385
+ const unwrappedThis = thisArg !== null && (typeof thisArg === "object" || typeof thisArg === "function") && proxyToTarget.has(thisArg) ? proxyToTarget.get(thisArg) : thisArg;
386
+ const result = ReflectApply(target2, unwrappedThis, argArray);
387
+ if (isProxyable(result)) {
388
+ return proxyWithDepth(result, depth + 1);
389
+ }
390
+ return result;
391
+ },
392
+ // Intercept constructor calls to proxy the created instance. Without this, code such as
393
+ // `new (wrappedCtor)()` would return a RAW object whose prototype chain reaches the
394
+ // host Function constructor — the same escape class the apply trap closes for calls.
395
+ // eslint-disable-next-line @typescript-eslint/no-explicit-any -- Proxy handler signature requires any for compatibility
396
+ construct(target2, argArray, newTarget) {
397
+ const instance = ReflectConstruct(target2, argArray, newTarget === proxy ? target2 : newTarget);
398
+ if (isProxyable(instance)) {
399
+ return proxyWithDepth(instance, depth + 1);
400
+ }
401
+ return instance;
402
+ }
403
+ });
404
+ let objCacheMap = proxyCache.get(obj);
405
+ if (!objCacheMap) {
406
+ objCacheMap = /* @__PURE__ */ new Map();
407
+ proxyCache.set(obj, objCacheMap);
408
+ }
409
+ objCacheMap.set(cacheKey, proxy);
410
+ proxySet.add(proxy);
411
+ proxyToTarget.set(proxy, obj);
412
+ return proxy;
413
+ }
414
+ return proxyWithDepth(target, 0);
415
+ }
416
+ function wrapGlobalsWithSecureProxy(globals, options = {}) {
417
+ const wrapped = {};
418
+ for (const [key, value] of Object.entries(globals)) {
419
+ if (value !== null && (typeof value === "object" || typeof value === "function")) {
420
+ wrapped[key] = createSecureProxy(value, options);
421
+ } else {
422
+ wrapped[key] = value;
423
+ }
424
+ }
425
+ return wrapped;
426
+ }
427
+ function createSecureStandardLibrary(options = {}) {
428
+ return wrapGlobalsWithSecureProxy(
429
+ {
430
+ Math,
431
+ JSON,
432
+ Array,
433
+ Object,
434
+ String,
435
+ Number,
436
+ Date
437
+ // Note: We intentionally don't include:
438
+ // - Function (dangerous)
439
+ // - eval (dangerous)
440
+ // - Proxy, Reflect (meta-programming)
441
+ },
442
+ options
443
+ );
444
+ }
445
+ function isSecureProxy(obj) {
446
+ if (obj === null || typeof obj !== "object") {
447
+ return false;
448
+ }
449
+ return proxySet.has(obj);
450
+ }
451
+ 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;
452
+ var init_secure_proxy = __esm({
453
+ "libs/core/src/secure-proxy.ts"() {
454
+ "use strict";
455
+ init_safe_error();
456
+ ObjectGetOwnPropertyDescriptor = Object.getOwnPropertyDescriptor;
457
+ ObjectToString = Object.prototype.toString;
458
+ FunctionBind = Function.prototype.bind;
459
+ ReflectGet = Reflect.get;
460
+ ReflectSet = Reflect.set;
461
+ ReflectDefineProperty = Reflect.defineProperty;
462
+ ReflectGetOwnPropertyDescriptor = Reflect.getOwnPropertyDescriptor;
463
+ ReflectOwnKeys = Reflect.ownKeys;
464
+ ReflectApply = Reflect.apply;
465
+ ReflectConstruct = Reflect.construct;
466
+ ReflectObject = Reflect;
467
+ PINNED_REFLECT_VALUES = /* @__PURE__ */ new Map();
468
+ for (const key of ReflectOwnKeys(ReflectObject)) {
469
+ PINNED_REFLECT_VALUES.set(key, ReflectGet(ReflectObject, key));
470
+ }
471
+ FunctionCtor = Function;
472
+ AsyncFunctionCtor = async function() {
473
+ }.constructor;
474
+ GeneratorFunctionCtor = function* () {
475
+ }.constructor;
476
+ AsyncGeneratorFunctionCtor = async function* () {
477
+ }.constructor;
478
+ MIN_MEMBRANE_RECURSION_DEPTH = 256;
479
+ BLOCKED_PROPERTY_CATEGORIES = {
480
+ /**
481
+ * Core prototype manipulation properties (always blocked except PERMISSIVE)
482
+ */
483
+ PROTOTYPE: /* @__PURE__ */ new Set([
484
+ "constructor",
485
+ "__proto__",
486
+ "prototype",
487
+ "__defineGetter__",
488
+ "__defineSetter__",
489
+ "__lookupGetter__",
490
+ "__lookupSetter__"
491
+ ]),
492
+ /**
493
+ * Property-descriptor and prototype MUTATION gadgets. These are the primitives behind the
494
+ * GHSA-3279 membrane self-leak (`Object.defineProperty(Object, 'getOwnPropertyDescriptor', hook)`
495
+ * to intercept the trap's raw target) and classic prototype pollution (`setPrototypeOf`). They
496
+ * are never needed by AgentScript and are already refused by the single-VM SafeObject
497
+ * (`DANGEROUS_OBJECT_STATIC_METHODS`), so they are blocked at every level that blocks the
498
+ * constructor (all except PERMISSIVE). Read-only reflection (getPrototypeOf, keys, entries,
499
+ * getOwnPropertyNames) is intentionally NOT here: the membrane's own getPrototypeOf/ownKeys traps
500
+ * already neutralize it for proxied values, and it has legitimate uses.
501
+ */
502
+ DESCRIPTOR_MUTATION: /* @__PURE__ */ new Set([
503
+ "getOwnPropertyDescriptor",
504
+ "getOwnPropertyDescriptors",
505
+ "defineProperty",
506
+ "defineProperties",
507
+ "setPrototypeOf"
508
+ ]),
509
+ /**
510
+ * Node.js 24 Iterator helper method names
511
+ * Blocked at STRICT/SECURE to prevent prototype chain access via iterators
512
+ */
513
+ ITERATOR_HELPERS: /* @__PURE__ */ new Set(["toArray", "forEach", "some", "every", "find", "reduce", "flatMap", "drop", "take"]),
514
+ /**
515
+ * Reflection properties on Object
516
+ * Blocked at STRICT to prevent introspection attacks
517
+ */
518
+ REFLECTION: /* @__PURE__ */ new Set([
519
+ "getOwnPropertyDescriptor",
520
+ "getOwnPropertyDescriptors",
521
+ "getOwnPropertyNames",
522
+ "getOwnPropertySymbols",
523
+ "getPrototypeOf",
524
+ "setPrototypeOf",
525
+ "defineProperty",
526
+ "defineProperties",
527
+ "preventExtensions",
528
+ "isExtensible",
529
+ "seal",
530
+ "isSealed",
531
+ "freeze",
532
+ "isFrozen"
533
+ ]),
534
+ /**
535
+ * Timing API properties
536
+ * Blocked at STRICT to prevent timing attacks
537
+ */
538
+ TIMING: /* @__PURE__ */ new Set(["hrtime", "timeOrigin"])
539
+ };
540
+ BLOCKED_PROPERTIES = /* @__PURE__ */ new Set([
541
+ // Code execution
542
+ "constructor",
543
+ // Prototype manipulation
544
+ "__proto__",
545
+ "prototype",
546
+ // Legacy getter/setter definition
547
+ "__defineGetter__",
548
+ "__defineSetter__",
549
+ "__lookupGetter__",
550
+ "__lookupSetter__",
551
+ // Descriptor / prototype mutation gadgets (GHSA-3279 self-leak + prototype pollution)
552
+ "getOwnPropertyDescriptor",
553
+ "getOwnPropertyDescriptors",
554
+ "defineProperty",
555
+ "defineProperties",
556
+ "setPrototypeOf"
557
+ ]);
558
+ DEFAULT_SECURE_PROXY_CONFIG = {
559
+ blockConstructor: true,
560
+ blockPrototype: true,
561
+ blockLegacyAccessors: true,
562
+ proxyMaxDepth: 10,
563
+ throwOnBlocked: true
564
+ };
565
+ FUNCTION_BLOCKED_PROPERTIES = /* @__PURE__ */ new Set([
566
+ // Function object properties that could leak information
567
+ "caller",
568
+ // Deprecated but still exists
569
+ "arguments"
570
+ // Deprecated but still exists
571
+ // Binding/applying could be used for exploitation
572
+ // Note: We may want to allow these in some cases
573
+ // 'bind',
574
+ // 'call',
575
+ // 'apply',
576
+ ]);
577
+ proxyCache = /* @__PURE__ */ new WeakMap();
578
+ proxySet = /* @__PURE__ */ new WeakSet();
579
+ proxyToTarget = /* @__PURE__ */ new WeakMap();
580
+ NON_PROXYABLE_TYPES = /* @__PURE__ */ new Set([
581
+ // Map/Set have internal slots but we may need to proxy them in the future
582
+ "[object Map]",
583
+ "[object Set]",
584
+ "[object WeakMap]",
585
+ "[object WeakSet]",
586
+ "[object ArrayBuffer]",
587
+ "[object SharedArrayBuffer]",
588
+ "[object DataView]",
589
+ "[object Int8Array]",
590
+ "[object Uint8Array]",
591
+ "[object Uint8ClampedArray]",
592
+ "[object Int16Array]",
593
+ "[object Uint16Array]",
594
+ "[object Int32Array]",
595
+ "[object Uint32Array]",
596
+ "[object Float32Array]",
597
+ "[object Float64Array]",
598
+ "[object BigInt64Array]",
599
+ "[object BigUint64Array]",
600
+ // Generators and iterators use internal slots
601
+ "[object Generator]",
602
+ "[object AsyncGenerator]",
603
+ "[object GeneratorFunction]",
604
+ "[object AsyncGeneratorFunction]",
605
+ // Built-in iterators
606
+ "[object Array Iterator]",
607
+ "[object String Iterator]",
608
+ "[object Map Iterator]",
609
+ "[object Set Iterator]",
610
+ "[object RegExp String Iterator]"
611
+ ]);
612
+ INTERNAL_SLOT_TYPES = /* @__PURE__ */ new Set(["[object Promise]"]);
613
+ }
614
+ });
615
+
11
616
  // libs/core/src/sidecar/reference-config.ts
12
617
  function isReferenceId(value) {
13
618
  return typeof value === "string" && REF_ID_PATTERN.test(value);
@@ -124,7 +729,7 @@ var init_reference_config = __esm({
124
729
 
125
730
  // libs/core/src/sidecar/reference-resolver.ts
126
731
  function untrustedLength(value) {
127
- const rawLen = ReflectGet(value, "length");
732
+ const rawLen = ReflectGet2(value, "length");
128
733
  if (typeof rawLen !== "number" || !NumberIsFinite(rawLen) || rawLen < 0) {
129
734
  return 0;
130
735
  }
@@ -141,7 +746,7 @@ function untrustedLength(value) {
141
746
  }
142
747
  function untrustedAt(value, index) {
143
748
  try {
144
- return ReflectGet(value, index);
749
+ return ReflectGet2(value, index);
145
750
  } catch {
146
751
  return void 0;
147
752
  }
@@ -150,12 +755,12 @@ function isCompositeHandle(value) {
150
755
  const obj = value;
151
756
  return typeof value === "object" && value !== null && obj["__type"] === "composite" && Array.isArray(obj["__parts"]);
152
757
  }
153
- var ReflectGet, NumberIsFinite, MathFloor, MAX_TRAVERSAL_LENGTH, ResolutionLimitError, ReferenceResolver;
758
+ var ReflectGet2, NumberIsFinite, MathFloor, MAX_TRAVERSAL_LENGTH, ResolutionLimitError, ReferenceResolver;
154
759
  var init_reference_resolver = __esm({
155
760
  "libs/core/src/sidecar/reference-resolver.ts"() {
156
761
  "use strict";
157
762
  init_reference_config();
158
- ReflectGet = Reflect.get;
763
+ ReflectGet2 = Reflect.get;
159
764
  NumberIsFinite = Number.isFinite;
160
765
  MathFloor = Math.floor;
161
766
  MAX_TRAVERSAL_LENGTH = 1e6;
@@ -427,7 +1032,7 @@ function sanitizeValue(value, options = {}, depth = 0, context = { propCount: {
427
1032
  context.visited.add(value);
428
1033
  }
429
1034
  if (ArrayIsArray(value)) {
430
- const rawLen = ReflectGet2(value, "length");
1035
+ const rawLen = ReflectGet3(value, "length");
431
1036
  const len = typeof rawLen === "number" && NumberIsFinite2(rawLen) && rawLen >= 0 ? MathFloor2(rawLen) : 0;
432
1037
  context.propCount.count += len;
433
1038
  if (context.propCount.count > maxProperties) {
@@ -437,7 +1042,7 @@ function sanitizeValue(value, options = {}, depth = 0, context = { propCount: {
437
1042
  for (let i = 0; i < len; i++) {
438
1043
  let item;
439
1044
  try {
440
- item = ReflectGet2(value, i);
1045
+ item = ReflectGet3(value, i);
441
1046
  } catch {
442
1047
  item = void 0;
443
1048
  }
@@ -446,15 +1051,15 @@ function sanitizeValue(value, options = {}, depth = 0, context = { propCount: {
446
1051
  return result;
447
1052
  }
448
1053
  if (value instanceof Date) {
449
- const time = ReflectApply(DateProtoGetTime, value, []);
1054
+ const time = ReflectApply2(DateProtoGetTime, value, []);
450
1055
  if (allowDates) {
451
1056
  return new Date(time);
452
1057
  }
453
- return ReflectApply(DateProtoToISOString, value, []);
1058
+ return ReflectApply2(DateProtoToISOString, value, []);
454
1059
  }
455
1060
  if (value instanceof Error) {
456
- const rawName = ReflectGet2(value, "name");
457
- const rawMessage = ReflectGet2(value, "message");
1061
+ const rawName = ReflectGet3(value, "name");
1062
+ const rawMessage = ReflectGet3(value, "message");
458
1063
  const name = typeof rawName === "string" ? rawName : "Error";
459
1064
  const message = typeof rawMessage === "string" ? rawMessage : "";
460
1065
  if (allowErrors) {
@@ -467,11 +1072,11 @@ function sanitizeValue(value, options = {}, depth = 0, context = { propCount: {
467
1072
  return { error: message };
468
1073
  }
469
1074
  if (value instanceof RegExp) {
470
- return ReflectApply(RegExpProtoToString, value, []);
1075
+ return ReflectApply2(RegExpProtoToString, value, []);
471
1076
  }
472
1077
  if (value instanceof Map) {
473
1078
  const sanitizedMap = ObjectCreate(null);
474
- const entries = ReflectApply(MapProtoEntries, value, []);
1079
+ const entries = ReflectApply2(MapProtoEntries, value, []);
475
1080
  for (const [key, val] of entries) {
476
1081
  if (typeof key !== "string") continue;
477
1082
  if (DANGEROUS_KEYS.has(key)) continue;
@@ -481,7 +1086,7 @@ function sanitizeValue(value, options = {}, depth = 0, context = { propCount: {
481
1086
  return sanitizedMap;
482
1087
  }
483
1088
  if (value instanceof Set) {
484
- const iter = ReflectApply(SetProtoValues, value, []);
1089
+ const iter = ReflectApply2(SetProtoValues, value, []);
485
1090
  const result = [];
486
1091
  for (const item of iter) {
487
1092
  context.propCount.count++;
@@ -502,670 +1107,161 @@ function sanitizeValue(value, options = {}, depth = 0, context = { propCount: {
502
1107
  }
503
1108
  let propValue;
504
1109
  try {
505
- propValue = ReflectGet2(value, key);
1110
+ propValue = ReflectGet3(value, key);
506
1111
  } catch {
507
1112
  continue;
508
1113
  }
509
- sanitized[key] = sanitizeValue(propValue, options, depth + 1, context);
510
- }
511
- return sanitized;
512
- }
513
- return String(value);
514
- }
515
- function estimateStringSize(str) {
516
- let bytes = 2;
517
- for (let i = 0; i < str.length; i++) {
518
- const code = str.charCodeAt(i);
519
- if (code < 128) {
520
- if (code === 34 || code === 92) {
521
- bytes += 2;
522
- } else if (code < 32) {
523
- bytes += 6;
524
- } else {
525
- bytes += 1;
526
- }
527
- } else if (code < 2048) {
528
- bytes += 2;
529
- } else if (code >= 55296 && code <= 56319 && i + 1 < str.length) {
530
- const nextCode = str.charCodeAt(i + 1);
531
- if (nextCode >= 56320 && nextCode <= 57343) {
532
- bytes += 4;
533
- i++;
534
- } else {
535
- bytes += 3;
536
- }
537
- } else {
538
- bytes += 3;
539
- }
540
- }
541
- return bytes;
542
- }
543
- function estimateSerializedSize(value, maxBytes = 0, depth = 0, maxDepth = 2e3, currentPath = /* @__PURE__ */ new Set()) {
544
- if (depth > maxDepth) {
545
- throw new Error(
546
- `Structure exceeds maximum nesting depth (${maxDepth}). Deeply nested structures are rejected to prevent stack overflow attacks.`
547
- );
548
- }
549
- if (value === null) return 4;
550
- if (value === void 0) return 0;
551
- const type = typeof value;
552
- if (type === "string") {
553
- const bytes = estimateStringSize(value);
554
- if (maxBytes > 0 && bytes > maxBytes) {
555
- throw new Error(`String serialization would exceed limit: ${bytes} > ${maxBytes} bytes`);
556
- }
557
- return bytes;
558
- }
559
- if (type === "number") {
560
- const num = value;
561
- if (!Number.isFinite(num)) return 4;
562
- return String(num).length;
563
- }
564
- if (type === "boolean") {
565
- return value ? 4 : 5;
566
- }
567
- if (type === "bigint") {
568
- return String(value).length + 2;
569
- }
570
- if (type === "function" || type === "symbol") {
571
- return 0;
572
- }
573
- if (Array.isArray(value)) {
574
- if (currentPath.has(value)) {
575
- return 4;
576
- }
577
- currentPath.add(value);
578
- let size = 2;
579
- for (let i = 0; i < value.length; i++) {
580
- if (i > 0) size += 1;
581
- let elementSize = estimateSerializedSize(value[i], maxBytes, depth + 1, maxDepth, currentPath);
582
- if (elementSize === 0) elementSize = 4;
583
- size += elementSize;
584
- if (maxBytes > 0 && size > maxBytes) {
585
- currentPath.delete(value);
586
- throw new Error(
587
- `Array serialization would exceed limit: estimated ${size}+ > ${maxBytes} bytes. This often indicates repeated references to large strings that expand during JSON serialization.`
588
- );
589
- }
590
- }
591
- currentPath.delete(value);
592
- return size;
593
- }
594
- if (type === "object" && value !== null) {
595
- if (currentPath.has(value)) {
596
- return 4;
597
- }
598
- currentPath.add(value);
599
- if (value instanceof Date) {
600
- currentPath.delete(value);
601
- return 26;
602
- }
603
- if (value instanceof RegExp) {
604
- currentPath.delete(value);
605
- return 2;
606
- }
607
- let size = 2;
608
- const keys = Object.keys(value);
609
- let first = true;
610
- for (const key of keys) {
611
- if (key === "__proto__" || key === "constructor") continue;
612
- if (!first) size += 1;
613
- first = false;
614
- size += estimateStringSize(key) + 1;
615
- let propValue;
616
- try {
617
- propValue = value[key];
618
- } catch {
619
- continue;
620
- }
621
- const valueSize = estimateSerializedSize(propValue, maxBytes, depth + 1, maxDepth, currentPath);
622
- size += valueSize;
623
- if (maxBytes > 0 && size > maxBytes) {
624
- currentPath.delete(value);
625
- throw new Error(
626
- `Object serialization would exceed limit: estimated ${size}+ > ${maxBytes} bytes. This often indicates repeated references to large strings that expand during JSON serialization.`
627
- );
628
- }
629
- }
630
- currentPath.delete(value);
631
- return size;
632
- }
633
- return 0;
634
- }
635
- function checkSerializedSize(value, maxBytes) {
636
- try {
637
- const estimatedBytes = estimateSerializedSize(value, maxBytes);
638
- return { ok: true, estimatedBytes };
639
- } catch (err) {
640
- return { ok: false, error: err instanceof Error ? err.message : "Unknown error" };
641
- }
642
- }
643
- var DANGEROUS_KEYS, ReflectApply, ReflectGet2, ArrayIsArray, ObjectKeys, ObjectCreate, NumberIsFinite2, MathFloor2, MapProtoEntries, SetProtoValues, DateProtoGetTime, DateProtoToISOString, RegExpProtoToString;
644
- var init_value_sanitizer = __esm({
645
- "libs/core/src/value-sanitizer.ts"() {
646
- "use strict";
647
- DANGEROUS_KEYS = /* @__PURE__ */ new Set(["__proto__", "constructor"]);
648
- ReflectApply = Reflect.apply;
649
- ReflectGet2 = Reflect.get;
650
- ArrayIsArray = Array.isArray;
651
- ObjectKeys = Object.keys;
652
- ObjectCreate = Object.create;
653
- NumberIsFinite2 = Number.isFinite;
654
- MathFloor2 = Math.floor;
655
- MapProtoEntries = Map.prototype.entries;
656
- SetProtoValues = Set.prototype.values;
657
- DateProtoGetTime = Date.prototype.getTime;
658
- DateProtoToISOString = Date.prototype.toISOString;
659
- RegExpProtoToString = RegExp.prototype.toString;
660
- }
661
- });
662
-
663
- // libs/core/src/safe-error.ts
664
- function createSafeError(message, name = "Error") {
665
- const error = new Error(message);
666
- error.name = name;
667
- const SafeConstructor = /* @__PURE__ */ Object.create(null);
668
- Object.defineProperties(SafeConstructor, {
669
- constructor: {
670
- value: SafeConstructor,
671
- writable: false,
672
- enumerable: false,
673
- configurable: false
674
- },
675
- prototype: {
676
- value: null,
677
- writable: false,
678
- enumerable: false,
679
- configurable: false
680
- },
681
- name: {
682
- value: "SafeError",
683
- writable: false,
684
- enumerable: false,
685
- configurable: false
686
- }
687
- });
688
- Object.freeze(SafeConstructor);
689
- Object.setPrototypeOf(error, null);
690
- Object.defineProperty(error, "constructor", {
691
- value: SafeConstructor,
692
- writable: false,
693
- enumerable: false,
694
- configurable: false
695
- });
696
- Object.defineProperty(error, "__proto__", {
697
- value: null,
698
- writable: false,
699
- enumerable: false,
700
- configurable: false
701
- });
702
- Object.defineProperty(error, "stack", {
703
- value: void 0,
704
- writable: false,
705
- enumerable: false,
706
- configurable: false
707
- });
708
- Object.freeze(error);
709
- return error;
710
- }
711
- function createSafeTypeError(message) {
712
- return createSafeError(message, "TypeError");
713
- }
714
- var init_safe_error = __esm({
715
- "libs/core/src/safe-error.ts"() {
716
- "use strict";
717
- }
718
- });
719
-
720
- // libs/core/src/secure-proxy.ts
721
- function getBlockedPropertiesForLevel(level) {
722
- const blocked = /* @__PURE__ */ new Set();
723
- if (level !== "PERMISSIVE") {
724
- BLOCKED_PROPERTY_CATEGORIES.PROTOTYPE.forEach((p) => blocked.add(p));
725
- }
726
- switch (level) {
727
- case "STRICT":
728
- BLOCKED_PROPERTY_CATEGORIES.ITERATOR_HELPERS.forEach((p) => blocked.add(p));
729
- BLOCKED_PROPERTY_CATEGORIES.REFLECTION.forEach((p) => blocked.add(p));
730
- BLOCKED_PROPERTY_CATEGORIES.TIMING.forEach((p) => blocked.add(p));
731
- break;
732
- case "SECURE":
733
- BLOCKED_PROPERTY_CATEGORIES.ITERATOR_HELPERS.forEach((p) => blocked.add(p));
734
- break;
735
- case "STANDARD":
736
- case "PERMISSIVE":
737
- break;
738
- }
739
- return blocked;
740
- }
741
- function buildBlockedPropertiesFromConfig(config) {
742
- const blocked = /* @__PURE__ */ new Set();
743
- if (config.blockConstructor) {
744
- blocked.add("constructor");
745
- }
746
- if (config.blockPrototype) {
747
- blocked.add("__proto__");
748
- blocked.add("prototype");
749
- }
750
- if (config.blockLegacyAccessors) {
751
- blocked.add("__defineGetter__");
752
- blocked.add("__defineSetter__");
753
- blocked.add("__lookupGetter__");
754
- blocked.add("__lookupSetter__");
755
- }
756
- return blocked;
757
- }
758
- function createSafeReflect(securityLevel) {
759
- if (securityLevel === "STRICT") {
760
- return void 0;
761
- }
762
- const dangerousMethods = /* @__PURE__ */ new Set(["setPrototypeOf"]);
763
- if (securityLevel === "SECURE") {
764
- dangerousMethods.add("apply");
765
- dangerousMethods.add("defineProperty");
1114
+ sanitized[key] = sanitizeValue(propValue, options, depth + 1, context);
1115
+ }
1116
+ return sanitized;
766
1117
  }
767
- return new Proxy(Reflect, {
768
- get(target, prop) {
769
- if (typeof prop === "string" && dangerousMethods.has(prop)) {
770
- return void 0;
1118
+ return String(value);
1119
+ }
1120
+ function estimateStringSize(str) {
1121
+ let bytes = 2;
1122
+ for (let i = 0; i < str.length; i++) {
1123
+ const code = str.charCodeAt(i);
1124
+ if (code < 128) {
1125
+ if (code === 34 || code === 92) {
1126
+ bytes += 2;
1127
+ } else if (code < 32) {
1128
+ bytes += 6;
1129
+ } else {
1130
+ bytes += 1;
771
1131
  }
772
- const value = Reflect.get(target, prop);
773
- if (typeof value === "function" && prop === "construct") {
774
- return function(ctorTarget, args, newTarget) {
775
- const AsyncFunction = async function() {
776
- }.constructor;
777
- const GeneratorFunction = function* () {
778
- }.constructor;
779
- const AsyncGeneratorFunction = async function* () {
780
- }.constructor;
781
- if (ctorTarget === Function || ctorTarget === AsyncFunction || ctorTarget === GeneratorFunction || ctorTarget === AsyncGeneratorFunction) {
782
- throw createSafeError("Reflect.construct with function constructors is blocked", "SecurityError");
783
- }
784
- return Reflect.construct(
785
- ctorTarget,
786
- args,
787
- newTarget
788
- );
789
- };
1132
+ } else if (code < 2048) {
1133
+ bytes += 2;
1134
+ } else if (code >= 55296 && code <= 56319 && i + 1 < str.length) {
1135
+ const nextCode = str.charCodeAt(i + 1);
1136
+ if (nextCode >= 56320 && nextCode <= 57343) {
1137
+ bytes += 4;
1138
+ i++;
1139
+ } else {
1140
+ bytes += 3;
790
1141
  }
791
- return value;
1142
+ } else {
1143
+ bytes += 3;
792
1144
  }
793
- });
1145
+ }
1146
+ return bytes;
794
1147
  }
795
- function getFullCacheKey(options) {
796
- const parts = [];
797
- if (options.levelConfig) {
798
- const cfg = options.levelConfig;
799
- parts.push(
800
- `L:${cfg.blockConstructor ? "C" : "c"}${cfg.blockPrototype ? "P" : "p"}${cfg.blockLegacyAccessors ? "L" : "l"}`
1148
+ function estimateSerializedSize(value, maxBytes = 0, depth = 0, maxDepth = 2e3, currentPath = /* @__PURE__ */ new Set()) {
1149
+ if (depth > maxDepth) {
1150
+ throw new Error(
1151
+ `Structure exceeds maximum nesting depth (${maxDepth}). Deeply nested structures are rejected to prevent stack overflow attacks.`
801
1152
  );
802
- } else {
803
- parts.push("L:default");
804
1153
  }
805
- if (options.additionalBlocked && options.additionalBlocked.length > 0) {
806
- parts.push(`B:${[...options.additionalBlocked].sort().join(",")}`);
807
- }
808
- const effectiveMaxDepth = options.maxDepth ?? options.levelConfig?.proxyMaxDepth ?? 10;
809
- if (effectiveMaxDepth !== 10) {
810
- parts.push(`D:${effectiveMaxDepth}`);
1154
+ if (value === null) return 4;
1155
+ if (value === void 0) return 0;
1156
+ const type = typeof value;
1157
+ if (type === "string") {
1158
+ const bytes = estimateStringSize(value);
1159
+ if (maxBytes > 0 && bytes > maxBytes) {
1160
+ throw new Error(`String serialization would exceed limit: ${bytes} > ${maxBytes} bytes`);
1161
+ }
1162
+ return bytes;
811
1163
  }
812
- if (options.throwOnBlocked) {
813
- parts.push("T:1");
1164
+ if (type === "number") {
1165
+ const num = value;
1166
+ if (!Number.isFinite(num)) return 4;
1167
+ return String(num).length;
814
1168
  }
815
- return parts.join("|") || "default";
816
- }
817
- function isProxyable(value) {
818
- if (value === null) return false;
819
- if (typeof value !== "object" && typeof value !== "function") return false;
820
- const tag = Object.prototype.toString.call(value);
821
- if (NON_PROXYABLE_TYPES.has(tag)) {
822
- return false;
1169
+ if (type === "boolean") {
1170
+ return value ? 4 : 5;
823
1171
  }
824
- return true;
825
- }
826
- function createSecureProxy(target, options = {}) {
827
- if (!isProxyable(target)) {
828
- return target;
1172
+ if (type === "bigint") {
1173
+ return String(value).length + 2;
829
1174
  }
830
- const cacheKey = getFullCacheKey(options);
831
- const targetCache = proxyCache.get(target);
832
- if (targetCache) {
833
- const cached = targetCache.get(cacheKey);
834
- if (cached) {
835
- return cached;
836
- }
1175
+ if (type === "function" || type === "symbol") {
1176
+ return 0;
837
1177
  }
838
- const baseBlocked = options.levelConfig ? buildBlockedPropertiesFromConfig(options.levelConfig) : new Set(BLOCKED_PROPERTIES);
839
- const blockedSet = /* @__PURE__ */ new Set([...baseBlocked, ...options.additionalBlocked || []]);
840
- const maxDepth = options.maxDepth ?? options.levelConfig?.proxyMaxDepth ?? 10;
841
- const throwOnBlocked = options.throwOnBlocked ?? options.levelConfig?.throwOnBlocked ?? false;
842
- function proxyWithDepth(obj, depth) {
843
- if (!isProxyable(obj)) {
844
- return obj;
845
- }
846
- const objCache = proxyCache.get(obj);
847
- if (objCache) {
848
- const cachedProxy = objCache.get(cacheKey);
849
- if (cachedProxy) {
850
- return cachedProxy;
851
- }
852
- }
853
- if (depth > maxDepth) {
854
- return obj;
1178
+ if (Array.isArray(value)) {
1179
+ if (currentPath.has(value)) {
1180
+ return 4;
855
1181
  }
856
- const proxy = new Proxy(obj, {
857
- get(target2, property, receiver) {
858
- const propName = typeof property === "symbol" ? property.toString() : property;
859
- const descriptor = Object.getOwnPropertyDescriptor(target2, property);
860
- const isNonConfigurable = descriptor && !descriptor.configurable;
861
- if (typeof propName === "string" && blockedSet.has(propName)) {
862
- if (options.onBlocked) {
863
- options.onBlocked(target2, propName);
864
- }
865
- if (isNonConfigurable && descriptor && !descriptor.writable) {
866
- return Reflect.get(target2, property, receiver);
867
- }
868
- if (throwOnBlocked) {
869
- throw createSafeError(
870
- `Security violation: Access to '${propName}' is blocked. This property can be used for sandbox escape attacks.`,
871
- "SecurityError"
872
- );
873
- }
874
- return void 0;
875
- }
876
- if (typeof target2 === "function" && typeof propName === "string" && FUNCTION_BLOCKED_PROPERTIES.has(propName)) {
877
- if (options.onBlocked) {
878
- options.onBlocked(target2, propName);
879
- }
880
- if (isNonConfigurable && descriptor && !descriptor.writable) {
881
- return Reflect.get(target2, property, receiver);
882
- }
883
- if (throwOnBlocked) {
884
- throw createSafeError(
885
- `Security violation: Access to '${propName}' is blocked. This property can be used for sandbox escape attacks.`,
886
- "SecurityError"
887
- );
888
- }
889
- return void 0;
890
- }
891
- const value = Reflect.get(target2, property, receiver);
892
- if (typeof value === "function") {
893
- const tag = Object.prototype.toString.call(target2);
894
- if (INTERNAL_SLOT_TYPES.has(tag)) {
895
- const boundMethod = value.bind(target2);
896
- return proxyWithDepth(boundMethod, depth + 1);
897
- }
898
- }
899
- if (value !== null && (typeof value === "object" || typeof value === "function")) {
900
- return proxyWithDepth(value, depth + 1);
901
- }
902
- return value;
903
- },
904
- // Block setting dangerous properties
905
- set(target2, property, value, receiver) {
906
- const propName = typeof property === "symbol" ? property.toString() : property;
907
- if (typeof propName === "string" && blockedSet.has(propName)) {
908
- if (options.onBlocked) {
909
- options.onBlocked(target2, propName);
910
- }
911
- if (throwOnBlocked) {
912
- throw createSafeError(
913
- `Security violation: Setting '${propName}' is blocked. This property can be used for sandbox escape attacks.`,
914
- "SecurityError"
915
- );
916
- }
917
- return false;
918
- }
919
- return Reflect.set(target2, property, value, receiver);
920
- },
921
- // Block defining dangerous properties
922
- defineProperty(target2, property, descriptor) {
923
- const propName = typeof property === "symbol" ? property.toString() : property;
924
- if (typeof propName === "string" && blockedSet.has(propName)) {
925
- if (options.onBlocked) {
926
- options.onBlocked(target2, propName);
927
- }
928
- if (throwOnBlocked) {
929
- throw createSafeError(
930
- `Security violation: Defining '${propName}' is blocked. This property can be used for sandbox escape attacks.`,
931
- "SecurityError"
932
- );
933
- }
934
- return false;
935
- }
936
- return Reflect.defineProperty(target2, property, descriptor);
937
- },
938
- // Filter blocked property names from enumeration (Object.keys, Object.entries, etc.)
939
- // Must respect proxy invariants: non-configurable own properties cannot be hidden
940
- ownKeys(target2) {
941
- const keys = Reflect.ownKeys(target2);
942
- return keys.filter((key) => {
943
- const keyStr = typeof key === "symbol" ? key.toString() : key;
944
- if (typeof keyStr !== "string" || !blockedSet.has(keyStr)) {
945
- return true;
946
- }
947
- const descriptor = Object.getOwnPropertyDescriptor(target2, key);
948
- if (descriptor && !descriptor.configurable) {
949
- return true;
950
- }
951
- return false;
952
- });
953
- },
954
- // Hide blocked properties from property descriptor queries (defense-in-depth)
955
- // Must respect proxy invariants: non-configurable properties must return actual descriptor
956
- getOwnPropertyDescriptor(target2, property) {
957
- const propName = typeof property === "symbol" ? property.toString() : property;
958
- const descriptor = Reflect.getOwnPropertyDescriptor(target2, property);
959
- if (descriptor && !descriptor.configurable) {
960
- return descriptor;
961
- }
962
- if (typeof propName === "string" && blockedSet.has(propName)) {
963
- if (options.onBlocked) {
964
- options.onBlocked(target2, propName);
965
- }
966
- if (throwOnBlocked) {
967
- throw createSafeError(
968
- `Security violation: Access to property descriptor for '${propName}' is blocked. This property can be used for sandbox escape attacks.`,
969
- "SecurityError"
970
- );
971
- }
972
- return void 0;
973
- }
974
- return descriptor;
975
- },
976
- // Block getPrototypeOf to prevent prototype chain walking
977
- getPrototypeOf() {
978
- return null;
979
- },
980
- // Block setPrototypeOf
981
- setPrototypeOf() {
982
- return false;
983
- },
984
- // Intercept function calls to proxy return values
985
- // eslint-disable-next-line @typescript-eslint/no-explicit-any -- Proxy handler signature requires any for compatibility
986
- apply(target2, thisArg, argArray) {
987
- const unwrappedThis = thisArg !== null && (typeof thisArg === "object" || typeof thisArg === "function") && proxyToTarget.has(thisArg) ? proxyToTarget.get(thisArg) : thisArg;
988
- const result = Reflect.apply(target2, unwrappedThis, argArray);
989
- if (isProxyable(result)) {
990
- return proxyWithDepth(result, depth + 1);
991
- }
992
- return result;
993
- },
994
- // Intercept constructor calls to proxy the created instance. Without this, code such as
995
- // `new (wrappedCtor)()` would return a RAW object whose prototype chain reaches the
996
- // host Function constructor — the same escape class the apply trap closes for calls.
997
- // eslint-disable-next-line @typescript-eslint/no-explicit-any -- Proxy handler signature requires any for compatibility
998
- construct(target2, argArray, newTarget) {
999
- const instance = Reflect.construct(target2, argArray, newTarget === proxy ? target2 : newTarget);
1000
- if (isProxyable(instance)) {
1001
- return proxyWithDepth(instance, depth + 1);
1002
- }
1003
- return instance;
1182
+ currentPath.add(value);
1183
+ let size = 2;
1184
+ for (let i = 0; i < value.length; i++) {
1185
+ if (i > 0) size += 1;
1186
+ let elementSize = estimateSerializedSize(value[i], maxBytes, depth + 1, maxDepth, currentPath);
1187
+ if (elementSize === 0) elementSize = 4;
1188
+ size += elementSize;
1189
+ if (maxBytes > 0 && size > maxBytes) {
1190
+ currentPath.delete(value);
1191
+ throw new Error(
1192
+ `Array serialization would exceed limit: estimated ${size}+ > ${maxBytes} bytes. This often indicates repeated references to large strings that expand during JSON serialization.`
1193
+ );
1004
1194
  }
1005
- });
1006
- let objCacheMap = proxyCache.get(obj);
1007
- if (!objCacheMap) {
1008
- objCacheMap = /* @__PURE__ */ new Map();
1009
- proxyCache.set(obj, objCacheMap);
1010
1195
  }
1011
- objCacheMap.set(cacheKey, proxy);
1012
- proxySet.add(proxy);
1013
- proxyToTarget.set(proxy, obj);
1014
- return proxy;
1196
+ currentPath.delete(value);
1197
+ return size;
1015
1198
  }
1016
- return proxyWithDepth(target, 0);
1017
- }
1018
- function wrapGlobalsWithSecureProxy(globals, options = {}) {
1019
- const wrapped = {};
1020
- for (const [key, value] of Object.entries(globals)) {
1021
- if (value !== null && (typeof value === "object" || typeof value === "function")) {
1022
- wrapped[key] = createSecureProxy(value, options);
1023
- } else {
1024
- wrapped[key] = value;
1199
+ if (type === "object" && value !== null) {
1200
+ if (currentPath.has(value)) {
1201
+ return 4;
1202
+ }
1203
+ currentPath.add(value);
1204
+ if (value instanceof Date) {
1205
+ currentPath.delete(value);
1206
+ return 26;
1207
+ }
1208
+ if (value instanceof RegExp) {
1209
+ currentPath.delete(value);
1210
+ return 2;
1211
+ }
1212
+ let size = 2;
1213
+ const keys = Object.keys(value);
1214
+ let first = true;
1215
+ for (const key of keys) {
1216
+ if (key === "__proto__" || key === "constructor") continue;
1217
+ if (!first) size += 1;
1218
+ first = false;
1219
+ size += estimateStringSize(key) + 1;
1220
+ let propValue;
1221
+ try {
1222
+ propValue = value[key];
1223
+ } catch {
1224
+ continue;
1225
+ }
1226
+ const valueSize = estimateSerializedSize(propValue, maxBytes, depth + 1, maxDepth, currentPath);
1227
+ size += valueSize;
1228
+ if (maxBytes > 0 && size > maxBytes) {
1229
+ currentPath.delete(value);
1230
+ throw new Error(
1231
+ `Object serialization would exceed limit: estimated ${size}+ > ${maxBytes} bytes. This often indicates repeated references to large strings that expand during JSON serialization.`
1232
+ );
1233
+ }
1025
1234
  }
1235
+ currentPath.delete(value);
1236
+ return size;
1026
1237
  }
1027
- return wrapped;
1028
- }
1029
- function createSecureStandardLibrary(options = {}) {
1030
- return wrapGlobalsWithSecureProxy(
1031
- {
1032
- Math,
1033
- JSON,
1034
- Array,
1035
- Object,
1036
- String,
1037
- Number,
1038
- Date
1039
- // Note: We intentionally don't include:
1040
- // - Function (dangerous)
1041
- // - eval (dangerous)
1042
- // - Proxy, Reflect (meta-programming)
1043
- },
1044
- options
1045
- );
1238
+ return 0;
1046
1239
  }
1047
- function isSecureProxy(obj) {
1048
- if (obj === null || typeof obj !== "object") {
1049
- return false;
1240
+ function checkSerializedSize(value, maxBytes) {
1241
+ try {
1242
+ const estimatedBytes = estimateSerializedSize(value, maxBytes);
1243
+ return { ok: true, estimatedBytes };
1244
+ } catch (err) {
1245
+ return { ok: false, error: err instanceof Error ? err.message : "Unknown error" };
1050
1246
  }
1051
- return proxySet.has(obj);
1052
1247
  }
1053
- var BLOCKED_PROPERTY_CATEGORIES, BLOCKED_PROPERTIES, DEFAULT_SECURE_PROXY_CONFIG, FUNCTION_BLOCKED_PROPERTIES, proxyCache, proxySet, proxyToTarget, NON_PROXYABLE_TYPES, INTERNAL_SLOT_TYPES;
1054
- var init_secure_proxy = __esm({
1055
- "libs/core/src/secure-proxy.ts"() {
1248
+ var DANGEROUS_KEYS, ReflectApply2, ReflectGet3, ArrayIsArray, ObjectKeys, ObjectCreate, NumberIsFinite2, MathFloor2, MapProtoEntries, SetProtoValues, DateProtoGetTime, DateProtoToISOString, RegExpProtoToString;
1249
+ var init_value_sanitizer = __esm({
1250
+ "libs/core/src/value-sanitizer.ts"() {
1056
1251
  "use strict";
1057
- init_safe_error();
1058
- BLOCKED_PROPERTY_CATEGORIES = {
1059
- /**
1060
- * Core prototype manipulation properties (always blocked except PERMISSIVE)
1061
- */
1062
- PROTOTYPE: /* @__PURE__ */ new Set([
1063
- "constructor",
1064
- "__proto__",
1065
- "prototype",
1066
- "__defineGetter__",
1067
- "__defineSetter__",
1068
- "__lookupGetter__",
1069
- "__lookupSetter__"
1070
- ]),
1071
- /**
1072
- * Node.js 24 Iterator helper method names
1073
- * Blocked at STRICT/SECURE to prevent prototype chain access via iterators
1074
- */
1075
- ITERATOR_HELPERS: /* @__PURE__ */ new Set(["toArray", "forEach", "some", "every", "find", "reduce", "flatMap", "drop", "take"]),
1076
- /**
1077
- * Reflection properties on Object
1078
- * Blocked at STRICT to prevent introspection attacks
1079
- */
1080
- REFLECTION: /* @__PURE__ */ new Set([
1081
- "getOwnPropertyDescriptor",
1082
- "getOwnPropertyDescriptors",
1083
- "getOwnPropertyNames",
1084
- "getOwnPropertySymbols",
1085
- "getPrototypeOf",
1086
- "setPrototypeOf",
1087
- "defineProperty",
1088
- "defineProperties",
1089
- "preventExtensions",
1090
- "isExtensible",
1091
- "seal",
1092
- "isSealed",
1093
- "freeze",
1094
- "isFrozen"
1095
- ]),
1096
- /**
1097
- * Timing API properties
1098
- * Blocked at STRICT to prevent timing attacks
1099
- */
1100
- TIMING: /* @__PURE__ */ new Set(["hrtime", "timeOrigin"])
1101
- };
1102
- BLOCKED_PROPERTIES = /* @__PURE__ */ new Set([
1103
- // Code execution
1104
- "constructor",
1105
- // Prototype manipulation
1106
- "__proto__",
1107
- "prototype",
1108
- // Legacy getter/setter definition
1109
- "__defineGetter__",
1110
- "__defineSetter__",
1111
- "__lookupGetter__",
1112
- "__lookupSetter__"
1113
- ]);
1114
- DEFAULT_SECURE_PROXY_CONFIG = {
1115
- blockConstructor: true,
1116
- blockPrototype: true,
1117
- blockLegacyAccessors: true,
1118
- proxyMaxDepth: 10,
1119
- throwOnBlocked: true
1120
- };
1121
- FUNCTION_BLOCKED_PROPERTIES = /* @__PURE__ */ new Set([
1122
- // Function object properties that could leak information
1123
- "caller",
1124
- // Deprecated but still exists
1125
- "arguments"
1126
- // Deprecated but still exists
1127
- // Binding/applying could be used for exploitation
1128
- // Note: We may want to allow these in some cases
1129
- // 'bind',
1130
- // 'call',
1131
- // 'apply',
1132
- ]);
1133
- proxyCache = /* @__PURE__ */ new WeakMap();
1134
- proxySet = /* @__PURE__ */ new WeakSet();
1135
- proxyToTarget = /* @__PURE__ */ new WeakMap();
1136
- NON_PROXYABLE_TYPES = /* @__PURE__ */ new Set([
1137
- // Map/Set have internal slots but we may need to proxy them in the future
1138
- "[object Map]",
1139
- "[object Set]",
1140
- "[object WeakMap]",
1141
- "[object WeakSet]",
1142
- "[object ArrayBuffer]",
1143
- "[object SharedArrayBuffer]",
1144
- "[object DataView]",
1145
- "[object Int8Array]",
1146
- "[object Uint8Array]",
1147
- "[object Uint8ClampedArray]",
1148
- "[object Int16Array]",
1149
- "[object Uint16Array]",
1150
- "[object Int32Array]",
1151
- "[object Uint32Array]",
1152
- "[object Float32Array]",
1153
- "[object Float64Array]",
1154
- "[object BigInt64Array]",
1155
- "[object BigUint64Array]",
1156
- // Generators and iterators use internal slots
1157
- "[object Generator]",
1158
- "[object AsyncGenerator]",
1159
- "[object GeneratorFunction]",
1160
- "[object AsyncGeneratorFunction]",
1161
- // Built-in iterators
1162
- "[object Array Iterator]",
1163
- "[object String Iterator]",
1164
- "[object Map Iterator]",
1165
- "[object Set Iterator]",
1166
- "[object RegExp String Iterator]"
1167
- ]);
1168
- INTERNAL_SLOT_TYPES = /* @__PURE__ */ new Set(["[object Promise]"]);
1252
+ DANGEROUS_KEYS = /* @__PURE__ */ new Set(["__proto__", "constructor"]);
1253
+ ReflectApply2 = Reflect.apply;
1254
+ ReflectGet3 = Reflect.get;
1255
+ ArrayIsArray = Array.isArray;
1256
+ ObjectKeys = Object.keys;
1257
+ ObjectCreate = Object.create;
1258
+ NumberIsFinite2 = Number.isFinite;
1259
+ MathFloor2 = Math.floor;
1260
+ MapProtoEntries = Map.prototype.entries;
1261
+ SetProtoValues = Set.prototype.values;
1262
+ DateProtoGetTime = Date.prototype.getTime;
1263
+ DateProtoToISOString = Date.prototype.toISOString;
1264
+ RegExpProtoToString = RegExp.prototype.toString;
1169
1265
  }
1170
1266
  });
1171
1267
 
@@ -1886,7 +1982,12 @@ ${stackTraceHardeningCode}
1886
1982
  function __ag_createSecureProxy(obj, depth) {
1887
1983
  if (depth === undefined) depth = 0;
1888
1984
  if (!__ag_Proxy || !__ag_Reflect) return obj;
1889
- if (depth > 10) return obj;
1985
+ // Fail CLOSED past the recursion backstop: returning the raw target would leak an
1986
+ // unwrapped reference (see MEMBRANE_MAX_RECURSION_DEPTH). Use the hardened safe-error
1987
+ // helper (sanitized stack, nulled constructor/proto) rather than a raw Error.
1988
+ if (depth > ${MEMBRANE_MAX_RECURSION_DEPTH}) {
1989
+ throw __ag_createSafeError('Security violation: secure-proxy recursion depth exceeded.');
1990
+ }
1890
1991
  if (obj === null || (typeof obj !== 'object' && typeof obj !== 'function')) return obj;
1891
1992
 
1892
1993
  if (__ag_proxyCache) {
@@ -1909,8 +2010,15 @@ ${stackTraceHardeningCode}
1909
2010
  if (typeof value === 'function') {
1910
2011
  // Bind methods to preserve internal slots when relevant.
1911
2012
  try { value = value.bind(target); } catch (e) {}
2013
+ return __ag_createSecureProxy(value, depth + 1);
1912
2014
  }
1913
- return __ag_createSecureProxy(value, depth + 1);
2015
+ // Only objects still need proxying; primitives (e.g. length/name) are inert and must be
2016
+ // returned directly, so a deep chain cannot turn a safe primitive read into a
2017
+ // recursion-depth error.
2018
+ if (value !== null && typeof value === 'object') {
2019
+ return __ag_createSecureProxy(value, depth + 1);
2020
+ }
2021
+ return value;
1914
2022
  },
1915
2023
  apply: function(target, thisArg, args) {
1916
2024
  return __ag_Reflect.apply(target, thisArg, args);
@@ -2163,6 +2271,29 @@ ${stackTraceHardeningCode}
2163
2271
  } catch (e) { /* ignore */ }
2164
2272
  }
2165
2273
 
2274
+ // SECURITY (GHSA-3279): pin pristine intrinsics BEFORE any sandbox code runs, so the membrane
2275
+ // traps and the error hardening below never re-read a realm global the sandbox can overwrite.
2276
+ // The reported escape replaced Object.getOwnPropertyDescriptor with a hook; the get trap then
2277
+ // called it and handed the attacker the RAW target of a membrane proxy (the host Promise from
2278
+ // callTool), reaching the host Function constructor. The same gadget aimed at the Object.*
2279
+ // mutators below would let an attacker observe safe-error construction or defeat the final
2280
+ // freeze, leaving the returned error with a live prototype and constructor chain. Using
2281
+ // captured references makes a later monkeypatch a no-op.
2282
+ const __ag_getOwnPropertyDescriptor = Object.getOwnPropertyDescriptor;
2283
+ const __ag_defineProperty = Object.defineProperty;
2284
+ const __ag_defineProperties = Object.defineProperties;
2285
+ const __ag_setPrototypeOf = Object.setPrototypeOf;
2286
+ const __ag_objectCreate = Object.create;
2287
+ const __ag_objectFreeze = Object.freeze;
2288
+ const __ag_ReflectGet = Reflect.get;
2289
+ const __ag_ReflectSet = Reflect.set;
2290
+ const __ag_ReflectDefineProperty = Reflect.defineProperty;
2291
+ const __ag_ReflectGetOwnPropertyDescriptor = Reflect.getOwnPropertyDescriptor;
2292
+ const __ag_ReflectOwnKeys = Reflect.ownKeys;
2293
+ const __ag_ReflectApply = Reflect.apply;
2294
+ const __ag_hasOwnProperty = Object.prototype.hasOwnProperty;
2295
+ const __ag_functionBind = Function.prototype.bind;
2296
+
2166
2297
  /**
2167
2298
  * Creates a "safe" error object that cannot be used to escape the sandbox.
2168
2299
  *
@@ -2185,7 +2316,7 @@ ${stackTraceHardeningCode}
2185
2316
  var error = new Error(message);
2186
2317
  // NOTE: Use Object.defineProperty instead of direct assignment because
2187
2318
  // Error.prototype.name is frozen, and in strict mode direct assignment fails.
2188
- Object.defineProperty(error, 'name', {
2319
+ __ag_defineProperty(error, 'name', {
2189
2320
  value: name,
2190
2321
  writable: true,
2191
2322
  enumerable: false,
@@ -2194,12 +2325,12 @@ ${stackTraceHardeningCode}
2194
2325
 
2195
2326
  // CRITICAL: sever the *actual* prototype chain (native getters / Object.getPrototypeOf).
2196
2327
  // A shadowing __proto__ data property is not sufficient.
2197
- Object.setPrototypeOf(error, null);
2328
+ __ag_setPrototypeOf(error, null);
2198
2329
 
2199
2330
  // Create a null-prototype object to use as a safe "constructor"
2200
2331
  // This object has no prototype chain to climb
2201
- var SafeConstructor = Object.create(null);
2202
- Object.defineProperties(SafeConstructor, {
2332
+ var SafeConstructor = __ag_objectCreate(null);
2333
+ __ag_defineProperties(SafeConstructor, {
2203
2334
  // Make constructor point to itself to break the chain
2204
2335
  constructor: {
2205
2336
  value: SafeConstructor,
@@ -2222,11 +2353,11 @@ ${stackTraceHardeningCode}
2222
2353
  configurable: false
2223
2354
  }
2224
2355
  });
2225
- Object.freeze(SafeConstructor);
2356
+ __ag_objectFreeze(SafeConstructor);
2226
2357
 
2227
2358
  // Override the constructor property on the error instance
2228
2359
  // This breaks the prototype chain: err.constructor.constructor no longer reaches Function
2229
- Object.defineProperty(error, 'constructor', {
2360
+ __ag_defineProperty(error, 'constructor', {
2230
2361
  value: SafeConstructor,
2231
2362
  writable: false,
2232
2363
  enumerable: false,
@@ -2235,7 +2366,7 @@ ${stackTraceHardeningCode}
2235
2366
 
2236
2367
  // SECURITY: Override __proto__ on the error instance to prevent prototype chain escape
2237
2368
  // Attack vector blocked: err.__proto__.constructor.constructor('malicious code')()
2238
- Object.defineProperty(error, '__proto__', {
2369
+ __ag_defineProperty(error, '__proto__', {
2239
2370
  value: null,
2240
2371
  writable: false,
2241
2372
  enumerable: false,
@@ -2245,7 +2376,7 @@ ${stackTraceHardeningCode}
2245
2376
  // SECURITY: Remove the stack property to prevent information leakage (Vector 1230)
2246
2377
  // The stack trace can reveal internal implementation details like function names,
2247
2378
  // file paths, and line numbers which can be used for reconnaissance attacks.
2248
- Object.defineProperty(error, 'stack', {
2379
+ __ag_defineProperty(error, 'stack', {
2249
2380
  value: undefined,
2250
2381
  writable: false,
2251
2382
  enumerable: false,
@@ -2254,7 +2385,7 @@ ${stackTraceHardeningCode}
2254
2385
 
2255
2386
  // Add a unique marker to identify this as a safe error from our runtime
2256
2387
  // This is used by suspicious pattern detection to distinguish our errors from user errors
2257
- Object.defineProperty(error, SAFE_ERROR_MARKER, {
2388
+ __ag_defineProperty(error, SAFE_ERROR_MARKER, {
2258
2389
  value: true,
2259
2390
  writable: false,
2260
2391
  enumerable: false,
@@ -2262,7 +2393,7 @@ ${stackTraceHardeningCode}
2262
2393
  });
2263
2394
 
2264
2395
  // Freeze the error to prevent modifications
2265
- Object.freeze(error);
2396
+ __ag_objectFreeze(error);
2266
2397
 
2267
2398
  return error;
2268
2399
  }
@@ -2306,8 +2437,10 @@ ${stackTraceHardeningCode}
2306
2437
  // Reference ID pattern for detecting sidecar references
2307
2438
  const refIdPattern = /^__REF_[0-9a-f]{8}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{12}__$/i;
2308
2439
 
2309
- // Proxy cache to avoid infinite recursion and duplicate wrapping
2440
+ // Proxy caches to avoid infinite recursion and duplicate wrapping. Host-owned values are
2441
+ // cached separately from realm-owned ones because the two use different blocking rules.
2310
2442
  const proxyCache = new WeakMap();
2443
+ const hostProxyCache = new WeakMap();
2311
2444
 
2312
2445
  /**
2313
2446
  * Create a secure proxy that blocks access to dangerous properties
@@ -2316,10 +2449,23 @@ ${stackTraceHardeningCode}
2316
2449
  * IMPORTANT: Must respect JavaScript proxy invariants:
2317
2450
  * - Non-configurable properties must return their actual value
2318
2451
  * - Non-configurable non-writable properties cannot be hidden
2452
+ *
2453
+ * The host flag marks a value that originates in the HOST realm (custom globals and
2454
+ * everything reachable from what they return). The host realm is the only one with code
2455
+ * generation from strings enabled, so a raw reference that escapes from it is remote code
2456
+ * execution; such a subtree refuses the reads a realm-owned object is allowed to answer.
2319
2457
  */
2320
- function createSecureProxy(obj, depth) {
2458
+ function createSecureProxy(obj, depth, host) {
2321
2459
  if (depth === undefined) depth = 0;
2322
- if (depth > 10) return obj; // Max depth to prevent infinite recursion
2460
+ host = host === true;
2461
+ // Recursion backstop. Fail CLOSED: returning the raw target here was the reported escape.
2462
+ // A bind chain inflates depth (each read binds a FRESH function, so the identity cache never
2463
+ // dedupes it) past the cap, and the raw host function prototype chain reaches the host
2464
+ // Function constructor for RCE. Throwing keeps the membrane total; the cap sits far above any
2465
+ // legitimately-deep (pre-sanitized) value so real data is never rejected.
2466
+ if (depth > ${MEMBRANE_MAX_RECURSION_DEPTH}) {
2467
+ throw createSafeError('Security violation: secure-proxy recursion depth exceeded.');
2468
+ }
2323
2469
 
2324
2470
  // Skip primitives and null
2325
2471
  if (obj === null || typeof obj !== 'object' && typeof obj !== 'function') {
@@ -2327,8 +2473,9 @@ ${stackTraceHardeningCode}
2327
2473
  }
2328
2474
 
2329
2475
  // Check cache
2330
- if (proxyCache.has(obj)) {
2331
- return proxyCache.get(obj);
2476
+ var cache = host ? hostProxyCache : proxyCache;
2477
+ if (cache.has(obj)) {
2478
+ return cache.get(obj);
2332
2479
  }
2333
2480
 
2334
2481
  var proxy = new Proxy(obj, {
@@ -2336,23 +2483,35 @@ ${stackTraceHardeningCode}
2336
2483
  var propName = String(property);
2337
2484
 
2338
2485
  // Check if property is non-configurable (proxy invariant requires returning actual value)
2339
- var descriptor = Object.getOwnPropertyDescriptor(target, property);
2486
+ var descriptor = __ag_getOwnPropertyDescriptor(target, property);
2340
2487
  var isNonConfigurable = descriptor && !descriptor.configurable;
2341
2488
 
2342
2489
  // Proxy invariant: if the target has a non-configurable, non-writable data property,
2343
2490
  // the proxy must return the exact same value (cannot wrap/bind/proxy it).
2344
2491
  // This matters for hardened properties like Error.prepareStackTrace.
2345
2492
  if (descriptor && isNonConfigurable && 'value' in descriptor && descriptor.writable === false) {
2346
- return descriptor.value;
2493
+ var exactValue = descriptor.value;
2494
+ // On a host-owned value the exact reference cannot be handed over: it would cross
2495
+ // the barrier unwrapped and its prototype chain reaches the host Function
2496
+ // constructor. Primitives stay safe to report, so only object/function values are
2497
+ // refused, and throwing satisfies the invariant that wrapping would break.
2498
+ if (host && exactValue !== null && (typeof exactValue === 'object' || typeof exactValue === 'function')) {
2499
+ throw createSafeError(
2500
+ "Security violation: Access to '" + propName + "' is blocked. " +
2501
+ "This property cannot be exposed without breaking the sandbox barrier."
2502
+ );
2503
+ }
2504
+ return exactValue;
2347
2505
  }
2348
2506
 
2349
- // Block dangerous properties - but respect proxy invariants
2507
+ // Block dangerous properties. The ONLY [[Get]] invariant that forces a specific return
2508
+ // value is for a non-writable + non-configurable DATA property \u2014 already handled above.
2509
+ // Anything reaching here is configurable, a non-configurable WRITABLE data property (such
2510
+ // as a function own prototype), or a non-configurable accessor; the invariant constrains
2511
+ // none of these, so the trap must never hand back the raw value. GHSA-3279: the old
2512
+ // "isNonConfigurable and not host -> return Reflect.get(...)" branch leaked the raw
2513
+ // writable prototype, exposing a parent-realm Object and defeating the membrane.
2350
2514
  if (blockedPropertiesSet.has(propName)) {
2351
- // For non-configurable properties, we MUST return the actual value
2352
- // (JavaScript proxy invariant - can't hide non-configurable properties)
2353
- if (isNonConfigurable) {
2354
- return Reflect.get(target, property, receiver);
2355
- }
2356
2515
  if (throwOnBlocked) {
2357
2516
  throw createSafeError(
2358
2517
  "Security violation: Access to '" + propName + "' is blocked. " +
@@ -2362,19 +2521,19 @@ ${stackTraceHardeningCode}
2362
2521
  return undefined;
2363
2522
  }
2364
2523
 
2365
- var value = Reflect.get(target, property, receiver);
2524
+ var value = __ag_ReflectGet(target, property, receiver);
2366
2525
 
2367
2526
  // For function values, bind to target first (preserves internal slot access for Promises, etc.)
2368
2527
  // Then recursively proxy the bound function to block constructor access
2369
2528
  if (typeof value === 'function') {
2370
- var boundMethod = value.bind(target);
2371
- return createSecureProxy(boundMethod, depth + 1);
2529
+ var boundMethod = __ag_functionBind.call(value, target);
2530
+ return createSecureProxy(boundMethod, depth + 1, host);
2372
2531
  }
2373
2532
 
2374
2533
  // Recursively proxy nested objects to maintain security barrier
2375
2534
  // This prevents attacks like: process.env.__proto__.constructor
2376
2535
  if (value !== null && typeof value === 'object') {
2377
- return createSecureProxy(value, depth + 1);
2536
+ return createSecureProxy(value, depth + 1, host);
2378
2537
  }
2379
2538
 
2380
2539
  return value;
@@ -2390,7 +2549,7 @@ ${stackTraceHardeningCode}
2390
2549
  }
2391
2550
  return false;
2392
2551
  }
2393
- return Reflect.set(target, property, value, receiver);
2552
+ return __ag_ReflectSet(target, property, value, receiver);
2394
2553
  },
2395
2554
  defineProperty: function(target, property, descriptor) {
2396
2555
  var propName = String(property);
@@ -2403,13 +2562,40 @@ ${stackTraceHardeningCode}
2403
2562
  }
2404
2563
  return false;
2405
2564
  }
2406
- return Reflect.defineProperty(target, property, descriptor);
2565
+ return __ag_ReflectDefineProperty(target, property, descriptor);
2407
2566
  },
2408
2567
  getOwnPropertyDescriptor: function(target, property) {
2409
2568
  var propName = String(property);
2410
- var descriptor = Reflect.getOwnPropertyDescriptor(target, property);
2569
+ var descriptor = __ag_ReflectGetOwnPropertyDescriptor(target, property);
2570
+
2571
+ // Mirror the get trap's host-owned pinned-value refusal: a non-configurable, non-writable
2572
+ // data property must be reported with its exact value (proxy invariant), so on a HOST-owned
2573
+ // value an object/function would cross the barrier unwrapped via descriptor.value and its
2574
+ // prototype chain reaches the host Function constructor. Deny the read instead (throwing
2575
+ // satisfies the invariant); primitives stay safe to report.
2576
+ if (host && descriptor && !descriptor.configurable && descriptor.writable === false && 'value' in descriptor) {
2577
+ var exactValue = descriptor.value;
2578
+ if (exactValue !== null && (typeof exactValue === 'object' || typeof exactValue === 'function')) {
2579
+ throw createSafeError(
2580
+ "Security violation: Access to property descriptor for '" + propName + "' is blocked. " +
2581
+ "This property cannot be exposed without breaking the sandbox barrier."
2582
+ );
2583
+ }
2584
+ return descriptor;
2585
+ }
2586
+
2587
+ // Accessor descriptors expose raw getter/setter functions. A non-configurable accessor
2588
+ // must be reported with its exact get/set (proxy invariant) and so cannot be wrapped \u2014
2589
+ // deny it if it carries a function whose prototype chain reaches the host constructor.
2590
+ if (descriptor && !descriptor.configurable &&
2591
+ (typeof descriptor.get === 'function' || typeof descriptor.set === 'function')) {
2592
+ throw createSafeError(
2593
+ "Security violation: Access to property descriptor for '" + propName + "' is blocked. " +
2594
+ "This property cannot be exposed without breaking the sandbox barrier."
2595
+ );
2596
+ }
2411
2597
 
2412
- // Must return actual descriptor for non-configurable properties (proxy invariant)
2598
+ // Must return actual descriptor for other non-configurable properties (proxy invariant)
2413
2599
  if (descriptor && !descriptor.configurable) {
2414
2600
  return descriptor;
2415
2601
  }
@@ -2424,10 +2610,32 @@ ${stackTraceHardeningCode}
2424
2610
  }
2425
2611
  return undefined;
2426
2612
  }
2613
+
2614
+ // A configurable accessor's getter/setter may be safely proxied so the descriptor never
2615
+ // hands back a raw function that leads to the host Function constructor.
2616
+ if (descriptor && (typeof descriptor.get === 'function' || typeof descriptor.set === 'function')) {
2617
+ var accessorWrapped = {};
2618
+ for (var ak in descriptor) { if (__ag_hasOwnProperty.call(descriptor, ak)) accessorWrapped[ak] = descriptor[ak]; }
2619
+ if (typeof descriptor.get === 'function') accessorWrapped.get = createSecureProxy(descriptor.get, depth + 1, host);
2620
+ if (typeof descriptor.set === 'function') accessorWrapped.set = createSecureProxy(descriptor.set, depth + 1, host);
2621
+ return accessorWrapped;
2622
+ }
2623
+
2624
+ // Wrap object/function values so a descriptor read cannot hand back a raw reference that
2625
+ // the get trap would otherwise have proxied.
2626
+ if (descriptor && 'value' in descriptor) {
2627
+ var value = descriptor.value;
2628
+ if (value !== null && (typeof value === 'object' || typeof value === 'function')) {
2629
+ var wrapped = {};
2630
+ for (var dk in descriptor) { if (__ag_hasOwnProperty.call(descriptor, dk)) wrapped[dk] = descriptor[dk]; }
2631
+ wrapped.value = createSecureProxy(value, depth + 1, host);
2632
+ return wrapped;
2633
+ }
2634
+ }
2427
2635
  return descriptor;
2428
2636
  },
2429
2637
  ownKeys: function(target) {
2430
- var keys = Reflect.ownKeys(target);
2638
+ var keys = __ag_ReflectOwnKeys(target);
2431
2639
  return keys.filter(function(key) {
2432
2640
  var keyStr = String(key);
2433
2641
  // Keep non-blocked properties
@@ -2435,7 +2643,7 @@ ${stackTraceHardeningCode}
2435
2643
  return true;
2436
2644
  }
2437
2645
  // Must keep non-configurable properties (proxy invariant)
2438
- var descriptor = Object.getOwnPropertyDescriptor(target, key);
2646
+ var descriptor = __ag_getOwnPropertyDescriptor(target, key);
2439
2647
  if (descriptor && !descriptor.configurable) {
2440
2648
  return true;
2441
2649
  }
@@ -2456,7 +2664,7 @@ ${stackTraceHardeningCode}
2456
2664
  // Results are re-wrapped at a FRESH depth (0) so a chain of calls such as
2457
2665
  // then().then() cannot inflate depth past the recursion cap and leak an unwrapped value.
2458
2666
  apply: function(target, thisArg, args) {
2459
- return createSecureProxy(Reflect.apply(target, thisArg, args), 0);
2667
+ return createSecureProxy(__ag_ReflectApply(target, thisArg, args), 0, host);
2460
2668
  }
2461
2669
  // NOTE: intentionally NO construct trap here (unlike the standalone secure-proxy used
2462
2670
  // for single-VM mode). Every constructor reachable from sandbox code resolves to an
@@ -2469,11 +2677,11 @@ ${stackTraceHardeningCode}
2469
2677
  // a non-extensible target), masking legitimate errors.
2470
2678
  });
2471
2679
 
2472
- proxyCache.set(obj, proxy);
2680
+ cache.set(obj, proxy);
2473
2681
  // Idempotency: re-wrapping an already-secure proxy must return it unchanged, so an apply
2474
2682
  // result that is itself already a secure proxy is not double-wrapped (which would nest
2475
2683
  // proxies and inflate depth toward the recursion cap).
2476
- proxyCache.set(proxy, proxy);
2684
+ cache.set(proxy, proxy);
2477
2685
  return proxy;
2478
2686
  }
2479
2687
 
@@ -2615,7 +2823,7 @@ ${stackTraceHardeningCode}
2615
2823
  }
2616
2824
 
2617
2825
  if (response.ok === true) {
2618
- if (Object.prototype.hasOwnProperty.call(response, 'value')) {
2826
+ if (__ag_hasOwnProperty.call(response, 'value')) {
2619
2827
  return response.value;
2620
2828
  }
2621
2829
  return undefined;
@@ -3408,10 +3616,13 @@ ${stackTraceHardeningCode}
3408
3616
  // Add user-provided globals if any (also wrapped with secure proxy and non-writable)
3409
3617
  // SECURITY: Use enumerable: false to prevent Object.assign({}, this) from copying globals
3410
3618
  // This blocks Vector 380 (Bridge-Serialized State Reflection) attack
3619
+ // Custom globals are HOST-realm values, so they are wrapped in host mode: the whole
3620
+ // subtree reachable through them (including whatever their calls return) refuses to hand
3621
+ // back a raw reference, even for descriptor shapes where a realm-owned object may.
3411
3622
  if (hostConfig.globals) {
3412
3623
  for (var uKey in hostConfig.globals) {
3413
3624
  if (hostConfig.globals.hasOwnProperty(uKey)) {
3414
- var wrappedGlobal = createSecureProxy(hostConfig.globals[uKey]);
3625
+ var wrappedGlobal = createSecureProxy(hostConfig.globals[uKey], 0, true);
3415
3626
  Object.defineProperty(innerContext, uKey, {
3416
3627
  value: wrappedGlobal,
3417
3628
  writable: false,
@@ -3520,10 +3731,11 @@ ${stackTraceHardeningCode}
3520
3731
  })();
3521
3732
  `.trim();
3522
3733
  }
3523
- var NODEJS_24_DANGEROUS_GLOBALS;
3734
+ var MEMBRANE_MAX_RECURSION_DEPTH, NODEJS_24_DANGEROUS_GLOBALS;
3524
3735
  var init_parent_vm_bootstrap = __esm({
3525
3736
  "libs/core/src/double-vm/parent-vm-bootstrap.ts"() {
3526
3737
  "use strict";
3738
+ MEMBRANE_MAX_RECURSION_DEPTH = 256;
3527
3739
  NODEJS_24_DANGEROUS_GLOBALS = {
3528
3740
  STRICT: [
3529
3741
  // Code execution - CRITICAL
@@ -6152,7 +6364,7 @@ var init_errors = __esm({
6152
6364
 
6153
6365
  // libs/core/src/adapters/worker-pool/safe-deserialize.ts
6154
6366
  function mapArraySafely(value, sanitizeItem) {
6155
- const rawLen = ReflectGet3(value, "length");
6367
+ const rawLen = ReflectGet4(value, "length");
6156
6368
  const len = typeof rawLen === "number" && NumberIsFinite3(rawLen) && rawLen >= 0 ? MathFloor3(rawLen) : 0;
6157
6369
  if (len > MAX_ARRAY_LENGTH) {
6158
6370
  throw new MessageValidationError(`Array exceeds maximum length of ${MAX_ARRAY_LENGTH}`);
@@ -6161,7 +6373,7 @@ function mapArraySafely(value, sanitizeItem) {
6161
6373
  for (let i = 0; i < len; i++) {
6162
6374
  let item;
6163
6375
  try {
6164
- item = ReflectGet3(value, i);
6376
+ item = ReflectGet4(value, i);
6165
6377
  } catch {
6166
6378
  item = void 0;
6167
6379
  }
@@ -6236,12 +6448,12 @@ function sanitizeObject(value, depth = 0) {
6236
6448
  }
6237
6449
  return result;
6238
6450
  }
6239
- var ReflectGet3, ArrayIsArray2, NumberIsFinite3, MathFloor3, MAX_ARRAY_LENGTH, DANGEROUS_KEYS2, MAX_DEPTH;
6451
+ var ReflectGet4, ArrayIsArray2, NumberIsFinite3, MathFloor3, MAX_ARRAY_LENGTH, DANGEROUS_KEYS2, MAX_DEPTH;
6240
6452
  var init_safe_deserialize = __esm({
6241
6453
  "libs/core/src/adapters/worker-pool/safe-deserialize.ts"() {
6242
6454
  "use strict";
6243
6455
  init_errors();
6244
- ReflectGet3 = Reflect.get;
6456
+ ReflectGet4 = Reflect.get;
6245
6457
  ArrayIsArray2 = Array.isArray;
6246
6458
  NumberIsFinite3 = Number.isFinite;
6247
6459
  MathFloor3 = Math.floor;
@@ -7938,7 +8150,12 @@ function transformMultiple(files, options, limits, singleFileTransform) {
7938
8150
 
7939
8151
  // libs/core/src/enclave.ts
7940
8152
  import { transformAgentScript, isWrappedInMain } from "@enclave-vm/ast";
7941
- import { extractLargeStrings, transformConcatenation, transformTemplateLiterals } from "@enclave-vm/ast";
8153
+ import {
8154
+ extractLargeStrings,
8155
+ transformConcatenation,
8156
+ transformTemplateLiterals,
8157
+ guardComputedMemberKeys
8158
+ } from "@enclave-vm/ast";
7942
8159
  import * as acorn2 from "acorn";
7943
8160
  import { generate } from "astring";
7944
8161
 
@@ -8237,6 +8454,9 @@ function validateGlobals(globals, options = {}) {
8237
8454
  }
8238
8455
  }
8239
8456
 
8457
+ // libs/core/src/enclave.ts
8458
+ init_secure_proxy();
8459
+
8240
8460
  // libs/core/src/sidecar/index.ts
8241
8461
  init_reference_config();
8242
8462
 
@@ -10337,6 +10557,9 @@ ${errorMessages}`,
10337
10557
  } else if (this.config.memoryLimit && this.config.memoryLimit > 0) {
10338
10558
  transformedCode = this.applyMemoryTrackingTransforms(transformedCode);
10339
10559
  }
10560
+ if (this.transformCode) {
10561
+ transformedCode = this.applyComputedKeyGuard(transformedCode);
10562
+ }
10340
10563
  let scoringResult;
10341
10564
  if (this.scoringGate) {
10342
10565
  scoringResult = await this.scoringGate.evaluate(transformedCode);
@@ -10434,6 +10657,21 @@ ${errorMessages}`,
10434
10657
  * @param code The code to transform
10435
10658
  * @returns The transformed code
10436
10659
  */
10660
+ applyComputedKeyGuard(code) {
10661
+ const proxyConfig = this.config.secureProxyConfig;
10662
+ const blockedKeys = [...buildBlockedPropertiesFromConfig(proxyConfig)];
10663
+ if (blockedKeys.length === 0) {
10664
+ return code;
10665
+ }
10666
+ const throwOnBlocked = proxyConfig.throwOnBlocked ?? true;
10667
+ const parseModule = (source) => acorn2.parse(source, { ecmaVersion: "latest", sourceType: "module" });
10668
+ const ast = parseModule(code);
10669
+ const { guardedCount } = guardComputedMemberKeys(ast, parseModule, { blockedKeys, throwOnBlocked });
10670
+ if (guardedCount === 0) {
10671
+ return code;
10672
+ }
10673
+ return generate(ast);
10674
+ }
10437
10675
  applyMemoryTrackingTransforms(code) {
10438
10676
  const ast = acorn2.parse(code, {
10439
10677
  ecmaVersion: "latest",
@@ -11167,7 +11405,11 @@ var Interpreter = class {
11167
11405
  const obj = value ?? {};
11168
11406
  for (const prop of pattern.properties) {
11169
11407
  if (prop.type === "RestElement") continue;
11170
- const key = prop.key.name;
11408
+ if (prop.computed) throw new InterpreterError("Computed destructuring keys are not allowed");
11409
+ let key;
11410
+ if (prop.key.type === "Identifier") key = prop.key.name;
11411
+ else if (prop.key.type === "Literal") key = String(prop.key.value);
11412
+ else throw new InterpreterError("Unsupported destructuring key");
11171
11413
  if (BLOCKED_KEYS.has(key)) throw new InterpreterError(`Forbidden destructured key: ${key}`);
11172
11414
  this.bindPattern(prop.value, obj[key], scope, mutable);
11173
11415
  }