@enclave-vm/core 2.15.0 → 2.15.1

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