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