@enclave-vm/core 2.18.0 → 2.19.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/README.md +239 -39
- package/SECURITY-AUDIT.md +85 -77
- package/adapters/interpreter-adapter.d.ts +37 -1
- package/adapters/worker-pool/config.d.ts +4 -2
- package/adapters/worker-pool/memory-monitor.d.ts +16 -2
- package/adapters/worker-pool/protocol.d.ts +52 -8
- package/adapters/worker-pool/worker-pool-adapter.d.ts +45 -2
- package/adapters/worker-pool/worker-script.d.ts +14 -4
- package/adapters/worker-pool/worker-slot.d.ts +99 -2
- package/console-handler.d.ts +5 -0
- package/deadline-guard.d.ts +65 -0
- package/double-vm/double-vm-wrapper.d.ts +11 -2
- package/double-vm/parent-vm-bootstrap.d.ts +118 -0
- package/enclave.d.ts +30 -0
- package/esm/index.mjs +12544 -8318
- package/esm/worker.mjs +2994 -202
- package/execution-deadline.d.ts +69 -0
- package/global-function-gate.d.ts +22 -1
- package/globals-validator.d.ts +12 -0
- package/index.d.ts +1 -0
- package/index.js +12461 -8236
- package/interpreter/interpreter.d.ts +192 -7
- package/interpreter/safe-globals.d.ts +14 -0
- package/package.json +4 -4
- package/realm-airlock.d.ts +51 -0
- package/safe-error.d.ts +6 -0
- package/safe-runtime.d.ts +16 -0
- package/sandbox-rejections.d.ts +67 -0
- package/sandbox-script.d.ts +156 -0
- package/secure-proxy.d.ts +21 -0
- package/src/adapters/worker-pool/package.json +4 -4
- package/src/adapters/worker-pool/worker-script.js +8604 -640
- package/stack-reserve.d.ts +46 -0
- package/tool-bridge.d.ts +34 -2
- package/types.d.ts +68 -5
- package/worker.js +2994 -202
package/esm/worker.mjs
CHANGED
|
@@ -1,6 +1,101 @@
|
|
|
1
1
|
// libs/core/src/adapters/interpreter-adapter.ts
|
|
2
2
|
import * as acorn from "acorn";
|
|
3
3
|
|
|
4
|
+
// libs/core/src/stack-reserve.ts
|
|
5
|
+
var ReflectApply = Reflect.apply;
|
|
6
|
+
var HOST_STACK_RESERVE_BYTES = 128 * 1024;
|
|
7
|
+
var SLOTS = [];
|
|
8
|
+
for (let slot = 0; slot < HOST_STACK_RESERVE_BYTES / 8; slot++) {
|
|
9
|
+
SLOTS[slot] = 0;
|
|
10
|
+
}
|
|
11
|
+
function nothing() {
|
|
12
|
+
}
|
|
13
|
+
function hasHostStackReserve() {
|
|
14
|
+
try {
|
|
15
|
+
ReflectApply(nothing, void 0, SLOTS);
|
|
16
|
+
return true;
|
|
17
|
+
} catch {
|
|
18
|
+
return false;
|
|
19
|
+
}
|
|
20
|
+
}
|
|
21
|
+
|
|
22
|
+
// libs/core/src/console-handler.ts
|
|
23
|
+
var CONSOLE_LEVELS = /* @__PURE__ */ new Set(["log", "info", "warn", "error", "debug"]);
|
|
24
|
+
var ignoreRejection = () => void 0;
|
|
25
|
+
function createConsoleSink(handler, limits) {
|
|
26
|
+
let callCount = 0;
|
|
27
|
+
let totalLength = 0;
|
|
28
|
+
return (level, message) => {
|
|
29
|
+
if (!CONSOLE_LEVELS.has(level) || typeof message !== "string") return;
|
|
30
|
+
callCount++;
|
|
31
|
+
totalLength += message.length;
|
|
32
|
+
if (callCount > limits.maxConsoleCalls || totalLength > limits.maxConsoleOutputBytes) return;
|
|
33
|
+
try {
|
|
34
|
+
if (!hasHostStackReserve()) return;
|
|
35
|
+
Promise.resolve(handler(level, message)).catch(ignoreRejection);
|
|
36
|
+
} catch {
|
|
37
|
+
}
|
|
38
|
+
};
|
|
39
|
+
}
|
|
40
|
+
var CONSOLE_FACTORY_SOURCE = `
|
|
41
|
+
(function () {
|
|
42
|
+
'use strict';
|
|
43
|
+
var stringify = JSON.stringify;
|
|
44
|
+
// The realm's own String, even where a sandbox global shadows it.
|
|
45
|
+
var toText = ''.constructor;
|
|
46
|
+
var freeze = Object.freeze;
|
|
47
|
+
var RealmError = Error;
|
|
48
|
+
|
|
49
|
+
function formatArgument(value) {
|
|
50
|
+
if (value === undefined) return 'undefined';
|
|
51
|
+
if (value === null) return 'null';
|
|
52
|
+
if (typeof value === 'object') {
|
|
53
|
+
try {
|
|
54
|
+
var json = stringify(value);
|
|
55
|
+
return json === undefined ? '' : json;
|
|
56
|
+
} catch (e) {
|
|
57
|
+
return toText(value);
|
|
58
|
+
}
|
|
59
|
+
}
|
|
60
|
+
return toText(value);
|
|
61
|
+
}
|
|
62
|
+
|
|
63
|
+
return function install(write, maxCalls, maxBytes) {
|
|
64
|
+
var callCount = 0;
|
|
65
|
+
var totalBytes = 0;
|
|
66
|
+
|
|
67
|
+
function method(level) {
|
|
68
|
+
return (...args) => {
|
|
69
|
+
callCount++;
|
|
70
|
+
if (callCount > maxCalls) {
|
|
71
|
+
throw new RealmError('Console call limit exceeded (max: ' + maxCalls + '). This limit prevents I/O flood attacks.');
|
|
72
|
+
}
|
|
73
|
+
var line = '';
|
|
74
|
+
for (var i = 0; i < args.length; i++) {
|
|
75
|
+
line += (i === 0 ? '' : ' ') + formatArgument(args[i]);
|
|
76
|
+
}
|
|
77
|
+
totalBytes += line.length;
|
|
78
|
+
if (totalBytes > maxBytes) {
|
|
79
|
+
throw new RealmError('Console output size limit exceeded (max: ' + maxBytes + ' bytes). This limit prevents I/O flood attacks.');
|
|
80
|
+
}
|
|
81
|
+
try {
|
|
82
|
+
write(level, line);
|
|
83
|
+
} catch (e) {}
|
|
84
|
+
};
|
|
85
|
+
}
|
|
86
|
+
|
|
87
|
+
return freeze({
|
|
88
|
+
__proto__: null,
|
|
89
|
+
log: method('log'),
|
|
90
|
+
info: method('info'),
|
|
91
|
+
warn: method('warn'),
|
|
92
|
+
error: method('error'),
|
|
93
|
+
debug: method('debug')
|
|
94
|
+
});
|
|
95
|
+
};
|
|
96
|
+
})()
|
|
97
|
+
`.trim();
|
|
98
|
+
|
|
4
99
|
// libs/core/src/interpreter/interpreter.ts
|
|
5
100
|
var BLOCKED_KEYS = /* @__PURE__ */ new Set([
|
|
6
101
|
"__proto__",
|
|
@@ -11,7 +106,21 @@ var BLOCKED_KEYS = /* @__PURE__ */ new Set([
|
|
|
11
106
|
"__lookupGetter__",
|
|
12
107
|
"__lookupSetter__"
|
|
13
108
|
]);
|
|
109
|
+
function isBlockedKey(key) {
|
|
110
|
+
return key === "__proto__" || BLOCKED_KEYS.has(key);
|
|
111
|
+
}
|
|
112
|
+
function assertKeyAllowed(key) {
|
|
113
|
+
if (isBlockedKey(key)) throw new InterpreterError(`Forbidden property access: ${key}`);
|
|
114
|
+
}
|
|
115
|
+
function readProperty(object, key) {
|
|
116
|
+
if (key === "__proto__" || BLOCKED_KEYS.has(key)) throw new InterpreterError(`Forbidden property access: ${key}`);
|
|
117
|
+
return object[key];
|
|
118
|
+
}
|
|
14
119
|
var MAX_STRING_OP_LENGTH = 1e6;
|
|
120
|
+
var MAX_JOIN_LENGTH = 16e6;
|
|
121
|
+
var MAX_TEXT_NESTING = 64;
|
|
122
|
+
var MAX_TEXT_ITEMS = 8e6;
|
|
123
|
+
var MAX_ARRAY_LENGTH = 1e6;
|
|
15
124
|
var HIGHER_ORDER_ARRAY_METHODS = /* @__PURE__ */ new Set([
|
|
16
125
|
"map",
|
|
17
126
|
"flatMap",
|
|
@@ -21,9 +130,132 @@ var HIGHER_ORDER_ARRAY_METHODS = /* @__PURE__ */ new Set([
|
|
|
21
130
|
"every",
|
|
22
131
|
"find",
|
|
23
132
|
"findIndex",
|
|
133
|
+
"findLast",
|
|
134
|
+
"findLastIndex",
|
|
24
135
|
"reduce",
|
|
25
|
-
"
|
|
136
|
+
"reduceRight",
|
|
137
|
+
"sort",
|
|
138
|
+
"toSorted"
|
|
139
|
+
]);
|
|
140
|
+
var FunctionProtoCall = Function.prototype.call;
|
|
141
|
+
var FunctionProtoApply = Function.prototype.apply;
|
|
142
|
+
var FunctionProtoBind = Function.prototype.bind;
|
|
143
|
+
var FunctionProtoToString = Function.prototype.toString;
|
|
144
|
+
function methodsOf(prototype) {
|
|
145
|
+
const methods = /* @__PURE__ */ new Map();
|
|
146
|
+
for (const name of Object.getOwnPropertyNames(prototype)) {
|
|
147
|
+
if (name === "constructor") continue;
|
|
148
|
+
const descriptor = Object.getOwnPropertyDescriptor(prototype, name);
|
|
149
|
+
if (descriptor && typeof descriptor.value === "function") methods.set(descriptor.value, name);
|
|
150
|
+
}
|
|
151
|
+
return methods;
|
|
152
|
+
}
|
|
153
|
+
var ARRAY_METHODS = methodsOf(Array.prototype);
|
|
154
|
+
var STRING_METHODS = methodsOf(String.prototype);
|
|
155
|
+
var ARRAY_DATA_ARGUMENTS = /* @__PURE__ */ new Map([
|
|
156
|
+
["push", () => true],
|
|
157
|
+
["unshift", () => true],
|
|
158
|
+
["concat", () => true],
|
|
159
|
+
["includes", (index) => index === 0],
|
|
160
|
+
["indexOf", (index) => index === 0],
|
|
161
|
+
["lastIndexOf", (index) => index === 0],
|
|
162
|
+
["fill", (index) => index === 0],
|
|
163
|
+
["splice", (index) => index >= 2],
|
|
164
|
+
["toSpliced", (index) => index >= 2],
|
|
165
|
+
["with", (index) => index === 1],
|
|
166
|
+
["reduce", (index) => index === 1],
|
|
167
|
+
["reduceRight", (index) => index === 1]
|
|
26
168
|
]);
|
|
169
|
+
var ARRAY_DATA_FUNCTIONS = /* @__PURE__ */ new WeakSet();
|
|
170
|
+
function takesArraysAsData(fn) {
|
|
171
|
+
ARRAY_DATA_FUNCTIONS.add(fn);
|
|
172
|
+
return fn;
|
|
173
|
+
}
|
|
174
|
+
var CONVERTED_ARGUMENTS = /* @__PURE__ */ new WeakMap();
|
|
175
|
+
function convertsArguments(fn, count) {
|
|
176
|
+
CONVERTED_ARGUMENTS.set(fn, count);
|
|
177
|
+
return fn;
|
|
178
|
+
}
|
|
179
|
+
var CALL_COSTS = /* @__PURE__ */ new WeakMap();
|
|
180
|
+
function chargedBeforeCall(fn, cost) {
|
|
181
|
+
CALL_COSTS.set(fn, cost);
|
|
182
|
+
return fn;
|
|
183
|
+
}
|
|
184
|
+
function newTextMeasure() {
|
|
185
|
+
return { length: 0, items: 0, active: /* @__PURE__ */ new Set(), functions: /* @__PURE__ */ new Map() };
|
|
186
|
+
}
|
|
187
|
+
function scalarTextLength(item, measure) {
|
|
188
|
+
switch (typeof item) {
|
|
189
|
+
case "number":
|
|
190
|
+
case "boolean":
|
|
191
|
+
return 32;
|
|
192
|
+
// also covers a number in the longest locale format
|
|
193
|
+
case "bigint":
|
|
194
|
+
return String(item).length;
|
|
195
|
+
case "function": {
|
|
196
|
+
let length = measure.functions.get(item);
|
|
197
|
+
if (length === void 0) {
|
|
198
|
+
try {
|
|
199
|
+
length = FunctionProtoToString.call(item).length;
|
|
200
|
+
} catch {
|
|
201
|
+
length = 0;
|
|
202
|
+
}
|
|
203
|
+
measure.functions.set(item, length);
|
|
204
|
+
}
|
|
205
|
+
return length;
|
|
206
|
+
}
|
|
207
|
+
case "object": {
|
|
208
|
+
if (isScriptError(item)) {
|
|
209
|
+
const error = item;
|
|
210
|
+
return String(error.name).length + 2 + String(error.message).length;
|
|
211
|
+
}
|
|
212
|
+
return 96;
|
|
213
|
+
}
|
|
214
|
+
default:
|
|
215
|
+
return 0;
|
|
216
|
+
}
|
|
217
|
+
}
|
|
218
|
+
function measureArrayText(array, separatorLength, measure, depth) {
|
|
219
|
+
if (depth > MAX_TEXT_NESTING) {
|
|
220
|
+
measure.length = Number.POSITIVE_INFINITY;
|
|
221
|
+
return;
|
|
222
|
+
}
|
|
223
|
+
measure.length += separatorLength * Math.max(0, array.length - 1);
|
|
224
|
+
measure.active.add(array);
|
|
225
|
+
for (let i = 0; i < array.length && measure.length <= MAX_JOIN_LENGTH; i++) {
|
|
226
|
+
if (++measure.items > MAX_TEXT_ITEMS) {
|
|
227
|
+
measure.length = Number.POSITIVE_INFINITY;
|
|
228
|
+
break;
|
|
229
|
+
}
|
|
230
|
+
const item = array[i];
|
|
231
|
+
if (typeof item === "string") measure.length += item.length;
|
|
232
|
+
else if (item === null || item === void 0) continue;
|
|
233
|
+
else if (Array.isArray(item)) {
|
|
234
|
+
if (!measure.active.has(item)) measureArrayText(item, 1, measure, depth + 1);
|
|
235
|
+
} else measure.length += scalarTextLength(item, measure);
|
|
236
|
+
}
|
|
237
|
+
measure.active.delete(array);
|
|
238
|
+
}
|
|
239
|
+
function flatLength(array, depth, limit, nesting = 0) {
|
|
240
|
+
if (nesting > MAX_TEXT_NESTING) return Number.POSITIVE_INFINITY;
|
|
241
|
+
let count = 0;
|
|
242
|
+
for (let i = 0; i < array.length && count <= limit; i++) {
|
|
243
|
+
const item = array[i];
|
|
244
|
+
if (depth >= 1 && Array.isArray(item)) count += flatLength(item, depth - 1, limit - count, nesting + 1);
|
|
245
|
+
else count++;
|
|
246
|
+
}
|
|
247
|
+
return count;
|
|
248
|
+
}
|
|
249
|
+
var TEXT_TOO_LONG = `An array cannot be turned into a text of more than ${MAX_JOIN_LENGTH} chars`;
|
|
250
|
+
function assertArrayTextWithinLimit(...values) {
|
|
251
|
+
let measure;
|
|
252
|
+
for (const value of values) {
|
|
253
|
+
if (!Array.isArray(value)) continue;
|
|
254
|
+
measure ??= newTextMeasure();
|
|
255
|
+
measureArrayText(value, 1, measure, 0);
|
|
256
|
+
if (measure.length > MAX_JOIN_LENGTH) throw new InterpreterError(TEXT_TOO_LONG);
|
|
257
|
+
}
|
|
258
|
+
}
|
|
27
259
|
var StepLimitError = class extends Error {
|
|
28
260
|
constructor(limit) {
|
|
29
261
|
super(`Execution step limit exceeded (${limit})`);
|
|
@@ -45,14 +277,47 @@ var BreakSignal = class {
|
|
|
45
277
|
};
|
|
46
278
|
var ContinueSignal = class {
|
|
47
279
|
};
|
|
280
|
+
var ChainShortCircuit = class {
|
|
281
|
+
};
|
|
282
|
+
function isControlSignal(value) {
|
|
283
|
+
return value instanceof ReturnSignal || value instanceof BreakSignal || value instanceof ContinueSignal || value instanceof ChainShortCircuit;
|
|
284
|
+
}
|
|
285
|
+
var SCRIPT_ERRORS = /* @__PURE__ */ new WeakSet();
|
|
286
|
+
function createScriptError(name, message, code) {
|
|
287
|
+
const error = /* @__PURE__ */ Object.create(null);
|
|
288
|
+
error["name"] = name;
|
|
289
|
+
error["message"] = message;
|
|
290
|
+
if (code !== void 0) error["code"] = code;
|
|
291
|
+
Object.defineProperty(error, "toString", {
|
|
292
|
+
value: function toString() {
|
|
293
|
+
return message ? `${name}: ${message}` : name;
|
|
294
|
+
},
|
|
295
|
+
enumerable: false
|
|
296
|
+
});
|
|
297
|
+
SCRIPT_ERRORS.add(error);
|
|
298
|
+
return Object.freeze(error);
|
|
299
|
+
}
|
|
300
|
+
function isScriptError(value) {
|
|
301
|
+
return typeof value === "object" && value !== null && SCRIPT_ERRORS.has(value);
|
|
302
|
+
}
|
|
48
303
|
var Scope = class _Scope {
|
|
49
|
-
constructor(parent) {
|
|
304
|
+
constructor(parent, depth) {
|
|
50
305
|
this.parent = parent;
|
|
306
|
+
this.depth = depth ?? parent?.depth ?? 0;
|
|
51
307
|
}
|
|
52
308
|
vars = /* @__PURE__ */ new Map();
|
|
309
|
+
/**
|
|
310
|
+
* How many calls deep the code of this scope runs: 0 for the program, and for the body of a
|
|
311
|
+
* function one more than where it was called from. A block inside has the depth around it.
|
|
312
|
+
*/
|
|
313
|
+
depth;
|
|
53
314
|
child() {
|
|
54
315
|
return new _Scope(this);
|
|
55
316
|
}
|
|
317
|
+
/** The scope of one call of a function defined in this scope, running `depth` calls deep. */
|
|
318
|
+
activation(depth) {
|
|
319
|
+
return new _Scope(this, depth);
|
|
320
|
+
}
|
|
56
321
|
declare(name, value, mutable) {
|
|
57
322
|
this.vars.set(name, { value, mutable });
|
|
58
323
|
}
|
|
@@ -79,14 +344,43 @@ var Scope = class _Scope {
|
|
|
79
344
|
throw new InterpreterError(`'${name}' is not defined`);
|
|
80
345
|
}
|
|
81
346
|
};
|
|
347
|
+
var DEFAULT_MAX_PENDING_CALLS = 4096;
|
|
348
|
+
function ignoreRejection2() {
|
|
349
|
+
}
|
|
82
350
|
var Interpreter = class {
|
|
83
351
|
constructor(options) {
|
|
84
352
|
this.options = options;
|
|
85
353
|
this.globals = options.globals;
|
|
354
|
+
this.maxPendingCalls = options.maxPendingCalls ?? DEFAULT_MAX_PENDING_CALLS;
|
|
86
355
|
}
|
|
87
356
|
steps = 0;
|
|
88
|
-
|
|
357
|
+
/** Calls that have not returned: the running ones and the ones waiting on an `await` */
|
|
358
|
+
pendingCalls = 0;
|
|
359
|
+
/**
|
|
360
|
+
* The depth of whatever is making a call right now, for the function of the script that call
|
|
361
|
+
* starts. A function of the script is a host function too, and a built-in, `parallel` or a
|
|
362
|
+
* bound function invokes it without saying how deep it is: it reads this as it starts, in the
|
|
363
|
+
* same synchronous step as the call, and runs one deeper. Set by {@link withCallerDepth} for
|
|
364
|
+
* the synchronous part of a call only; a call that is waiting does not hold it, which is what
|
|
365
|
+
* keeps the depth of one chain apart from the depth of another. 0 when the host itself calls.
|
|
366
|
+
*/
|
|
367
|
+
callerDepth = 0;
|
|
368
|
+
maxPendingCalls;
|
|
89
369
|
globals;
|
|
370
|
+
/** The error that ended the run (step budget, abort, allocation budget); set once, never caught */
|
|
371
|
+
fatal;
|
|
372
|
+
interpretedFunctions = /* @__PURE__ */ new WeakSet();
|
|
373
|
+
errorCopies = /* @__PURE__ */ new WeakMap();
|
|
374
|
+
/**
|
|
375
|
+
* Call a function for a script, with the checks that apply to a call the script writes itself.
|
|
376
|
+
* For a host helper that is handed a callback (`parallel(items, fn)`): `fn` may be a function
|
|
377
|
+
* of the script, or a built-in or host function the script passed along.
|
|
378
|
+
*/
|
|
379
|
+
call(fn, args) {
|
|
380
|
+
if (typeof fn !== "function") throw new InterpreterError("Attempted to call a non-function");
|
|
381
|
+
if (this.interpretedFunctions.has(fn)) return fn(...args);
|
|
382
|
+
return this.callFunction(fn, void 0, args, this.callerDepth);
|
|
383
|
+
}
|
|
90
384
|
/** Number of AST nodes evaluated so far (for execution stats). */
|
|
91
385
|
get stepCount() {
|
|
92
386
|
return this.steps;
|
|
@@ -109,18 +403,48 @@ var Interpreter = class {
|
|
|
109
403
|
}
|
|
110
404
|
return last;
|
|
111
405
|
}
|
|
406
|
+
/**
|
|
407
|
+
* End the run from outside: whatever of the script is still going (a function a built-in
|
|
408
|
+
* started and nobody awaited, a callback waiting for a tool call) stops at its next step. The
|
|
409
|
+
* host calls this when the execution has returned, so that no script code runs after it.
|
|
410
|
+
*/
|
|
411
|
+
stop() {
|
|
412
|
+
if (this.fatal === void 0) this.fatal = new InterpreterError("Execution ended");
|
|
413
|
+
}
|
|
414
|
+
/** End the run with an error no `catch` of the script can stop. */
|
|
415
|
+
end(error) {
|
|
416
|
+
if (this.fatal === void 0) this.fatal = error;
|
|
417
|
+
throw this.fatal;
|
|
418
|
+
}
|
|
112
419
|
tick() {
|
|
113
|
-
if (this.
|
|
114
|
-
if (
|
|
420
|
+
if (this.fatal !== void 0) throw this.fatal;
|
|
421
|
+
if (this.options.signal?.aborted) this.end(new InterpreterError("Execution aborted"));
|
|
422
|
+
if (++this.steps > this.options.maxSteps) this.end(new StepLimitError(this.options.maxSteps));
|
|
423
|
+
}
|
|
424
|
+
/** Charge an allocation to the host's budget. */
|
|
425
|
+
charge(bytes) {
|
|
426
|
+
const charge = this.options.charge;
|
|
427
|
+
if (!charge || bytes <= 0) return;
|
|
428
|
+
try {
|
|
429
|
+
charge(bytes);
|
|
430
|
+
} catch (error) {
|
|
431
|
+
this.end(error);
|
|
432
|
+
}
|
|
433
|
+
}
|
|
434
|
+
/** Charge what a host function returned, when that is a string or an array. */
|
|
435
|
+
chargeValue(value) {
|
|
436
|
+
if (typeof value === "string") this.charge(value.length * 2);
|
|
437
|
+
else if (Array.isArray(value)) this.charge(value.length * 8);
|
|
115
438
|
}
|
|
116
439
|
// ── Statements ─────────────────────────────────────────────────────────────
|
|
117
440
|
async execStatement(node, scope) {
|
|
118
441
|
this.tick();
|
|
119
442
|
switch (node.type) {
|
|
120
443
|
case "VariableDeclaration": {
|
|
444
|
+
const mode = node.kind === "const" ? "const" : "let";
|
|
121
445
|
for (const d of node.declarations) {
|
|
122
446
|
const value = d.init ? await this.evalExpr(d.init, scope) : void 0;
|
|
123
|
-
this.
|
|
447
|
+
await this.applyPattern(d.id, value, scope, mode);
|
|
124
448
|
}
|
|
125
449
|
return void 0;
|
|
126
450
|
}
|
|
@@ -137,15 +461,27 @@ var Interpreter = class {
|
|
|
137
461
|
return void 0;
|
|
138
462
|
case "ForOfStatement":
|
|
139
463
|
return this.execForOf(node, scope);
|
|
464
|
+
case "ForInStatement":
|
|
465
|
+
return this.execForIn(node, scope);
|
|
140
466
|
case "ForStatement":
|
|
141
467
|
return this.execFor(node, scope);
|
|
142
468
|
case "WhileStatement":
|
|
143
469
|
return this.execWhile(node, scope);
|
|
470
|
+
case "DoWhileStatement":
|
|
471
|
+
return this.execDoWhile(node, scope);
|
|
472
|
+
case "SwitchStatement":
|
|
473
|
+
return this.execSwitch(node, scope);
|
|
474
|
+
case "TryStatement":
|
|
475
|
+
return this.execTry(node, scope);
|
|
476
|
+
case "ThrowStatement":
|
|
477
|
+
throw await this.evalExpr(node.argument, scope);
|
|
144
478
|
case "ReturnStatement":
|
|
145
479
|
throw new ReturnSignal(node.argument ? await this.evalExpr(node.argument, scope) : void 0);
|
|
146
480
|
case "BreakStatement":
|
|
481
|
+
if (node.label) throw new InterpreterError("Labeled break is not supported");
|
|
147
482
|
throw new BreakSignal();
|
|
148
483
|
case "ContinueStatement":
|
|
484
|
+
if (node.label) throw new InterpreterError("Labeled continue is not supported");
|
|
149
485
|
throw new ContinueSignal();
|
|
150
486
|
case "EmptyStatement":
|
|
151
487
|
return void 0;
|
|
@@ -165,25 +501,44 @@ var Interpreter = class {
|
|
|
165
501
|
}
|
|
166
502
|
return void 0;
|
|
167
503
|
}
|
|
504
|
+
/** Bind the variable of a `for…of` / `for…in` head to the value of one iteration. */
|
|
505
|
+
async bindLoopVariable(left, value, scope) {
|
|
506
|
+
if (left.type === "VariableDeclaration") {
|
|
507
|
+
await this.applyPattern(left.declarations[0].id, value, scope, left.kind === "const" ? "const" : "let");
|
|
508
|
+
} else {
|
|
509
|
+
await this.applyPattern(left, value, scope, "assign");
|
|
510
|
+
}
|
|
511
|
+
}
|
|
512
|
+
/** Run one iteration of a loop body. @returns false when the loop is to stop */
|
|
513
|
+
async runLoopBody(body, scope) {
|
|
514
|
+
try {
|
|
515
|
+
await this.execStatement(body, scope);
|
|
516
|
+
} catch (e) {
|
|
517
|
+
if (e instanceof BreakSignal) return false;
|
|
518
|
+
if (!(e instanceof ContinueSignal)) throw e;
|
|
519
|
+
}
|
|
520
|
+
return true;
|
|
521
|
+
}
|
|
168
522
|
async execForOf(node, scope) {
|
|
523
|
+
if (node.await) throw new InterpreterError("for await is not supported");
|
|
169
524
|
const iterable = await this.evalExpr(node.right, scope);
|
|
170
525
|
if (!isIterable(iterable)) throw new InterpreterError("for-of target is not iterable");
|
|
171
526
|
for (const item of iterable) {
|
|
172
527
|
this.tick();
|
|
173
528
|
const inner = scope.child();
|
|
174
|
-
|
|
175
|
-
if (
|
|
176
|
-
|
|
177
|
-
|
|
178
|
-
|
|
179
|
-
|
|
180
|
-
|
|
181
|
-
|
|
182
|
-
|
|
183
|
-
|
|
184
|
-
|
|
185
|
-
|
|
186
|
-
|
|
529
|
+
await this.bindLoopVariable(node.left, item, inner);
|
|
530
|
+
if (!await this.runLoopBody(node.body, inner)) break;
|
|
531
|
+
}
|
|
532
|
+
}
|
|
533
|
+
async execForIn(node, scope) {
|
|
534
|
+
const object = await this.evalExpr(node.right, scope);
|
|
535
|
+
if (object === null || object === void 0) return;
|
|
536
|
+
for (const key of Object.keys(object)) {
|
|
537
|
+
this.tick();
|
|
538
|
+
if (BLOCKED_KEYS.has(key)) continue;
|
|
539
|
+
const inner = scope.child();
|
|
540
|
+
await this.bindLoopVariable(node.left, key, inner);
|
|
541
|
+
if (!await this.runLoopBody(node.body, inner)) break;
|
|
187
542
|
}
|
|
188
543
|
}
|
|
189
544
|
async execFor(node, scope) {
|
|
@@ -194,31 +549,78 @@ var Interpreter = class {
|
|
|
194
549
|
}
|
|
195
550
|
while (node.test ? truthy(await this.evalExpr(node.test, inner)) : true) {
|
|
196
551
|
this.tick();
|
|
197
|
-
|
|
198
|
-
await this.execStatement(node.body, inner.child());
|
|
199
|
-
} catch (e) {
|
|
200
|
-
if (e instanceof BreakSignal) break;
|
|
201
|
-
if (!(e instanceof ContinueSignal)) throw e;
|
|
202
|
-
}
|
|
552
|
+
if (!await this.runLoopBody(node.body, inner.child())) break;
|
|
203
553
|
if (node.update) await this.evalExpr(node.update, inner);
|
|
204
554
|
}
|
|
205
555
|
}
|
|
206
556
|
async execWhile(node, scope) {
|
|
207
557
|
while (truthy(await this.evalExpr(node.test, scope))) {
|
|
208
558
|
this.tick();
|
|
209
|
-
|
|
210
|
-
|
|
211
|
-
|
|
212
|
-
|
|
213
|
-
|
|
559
|
+
if (!await this.runLoopBody(node.body, scope.child())) break;
|
|
560
|
+
}
|
|
561
|
+
}
|
|
562
|
+
async execDoWhile(node, scope) {
|
|
563
|
+
do {
|
|
564
|
+
this.tick();
|
|
565
|
+
if (!await this.runLoopBody(node.body, scope.child())) break;
|
|
566
|
+
} while (truthy(await this.evalExpr(node.test, scope)));
|
|
567
|
+
}
|
|
568
|
+
async execSwitch(node, scope) {
|
|
569
|
+
const value = await this.evalExpr(node.discriminant, scope);
|
|
570
|
+
const inner = scope.child();
|
|
571
|
+
let start = -1;
|
|
572
|
+
for (let i = 0; i < node.cases.length && start === -1; i++) {
|
|
573
|
+
const test = node.cases[i].test;
|
|
574
|
+
if (test && await this.evalExpr(test, inner) === value) start = i;
|
|
575
|
+
}
|
|
576
|
+
if (start === -1) start = node.cases.findIndex((clause) => !clause.test);
|
|
577
|
+
if (start === -1) return;
|
|
578
|
+
try {
|
|
579
|
+
for (let i = start; i < node.cases.length; i++) {
|
|
580
|
+
for (const stmt of node.cases[i].consequent) await this.execStatement(stmt, inner);
|
|
214
581
|
}
|
|
582
|
+
} catch (e) {
|
|
583
|
+
if (!(e instanceof BreakSignal)) throw e;
|
|
584
|
+
}
|
|
585
|
+
}
|
|
586
|
+
async execTry(node, scope) {
|
|
587
|
+
try {
|
|
588
|
+
await this.execBlock(node.block.body, scope.child());
|
|
589
|
+
} catch (thrown) {
|
|
590
|
+
if (!node.handler || isControlSignal(thrown) || this.fatal !== void 0) throw thrown;
|
|
591
|
+
const inner = scope.child();
|
|
592
|
+
if (node.handler.param) await this.applyPattern(node.handler.param, this.toScriptValue(thrown), inner, "let");
|
|
593
|
+
await this.execBlock(node.handler.body.body, inner);
|
|
594
|
+
} finally {
|
|
595
|
+
if (node.finalizer && this.fatal === void 0) await this.execBlock(node.finalizer.body, scope.child());
|
|
215
596
|
}
|
|
216
597
|
}
|
|
598
|
+
/**
|
|
599
|
+
* What a `catch` clause receives. A value the script threw is its own. A host Error (a refusal
|
|
600
|
+
* by the interpreter, a failed tool call, a TypeError of a built-in) is replaced by a plain
|
|
601
|
+
* copy with its name, message and code.
|
|
602
|
+
*/
|
|
603
|
+
toScriptValue(thrown) {
|
|
604
|
+
if (!(thrown instanceof Error)) return thrown;
|
|
605
|
+
const known = this.errorCopies.get(thrown);
|
|
606
|
+
if (known) return known;
|
|
607
|
+
const code = thrown.code;
|
|
608
|
+
const copy = createScriptError(
|
|
609
|
+
typeof thrown.name === "string" ? thrown.name : "Error",
|
|
610
|
+
typeof thrown.message === "string" ? thrown.message : "",
|
|
611
|
+
typeof code === "string" ? code : void 0
|
|
612
|
+
);
|
|
613
|
+
this.errorCopies.set(thrown, copy);
|
|
614
|
+
return copy;
|
|
615
|
+
}
|
|
217
616
|
// ── Expressions ──────────────────────────────────────────────────────────--
|
|
218
617
|
async evalExpr(node, scope) {
|
|
219
618
|
this.tick();
|
|
220
619
|
switch (node.type) {
|
|
221
620
|
case "Literal":
|
|
621
|
+
if (node.regex) {
|
|
622
|
+
throw new InterpreterError("Regular expressions are not supported");
|
|
623
|
+
}
|
|
222
624
|
return node.value;
|
|
223
625
|
case "Identifier":
|
|
224
626
|
return scope.has(node.name) ? scope.get(node.name) : this.readGlobal(node.name);
|
|
@@ -230,49 +632,50 @@ var Interpreter = class {
|
|
|
230
632
|
if (el == null) {
|
|
231
633
|
arr.push(void 0);
|
|
232
634
|
} else if (el.type === "SpreadElement") {
|
|
233
|
-
|
|
234
|
-
if (!isIterable(spread)) throw new InterpreterError("Spread target is not iterable");
|
|
235
|
-
for (const v of spread) arr.push(v);
|
|
635
|
+
this.spreadInto(arr, await this.evalExpr(el.argument, scope));
|
|
236
636
|
} else {
|
|
237
637
|
arr.push(await this.evalExpr(el, scope));
|
|
238
638
|
}
|
|
239
639
|
}
|
|
640
|
+
this.charge(arr.length * 8);
|
|
240
641
|
return arr;
|
|
241
642
|
}
|
|
242
643
|
case "ObjectExpression": {
|
|
243
644
|
const obj = {};
|
|
645
|
+
let count = 0;
|
|
244
646
|
for (const prop of node.properties) {
|
|
245
647
|
if (prop.type === "SpreadElement") {
|
|
246
648
|
const spread = await this.evalExpr(prop.argument, scope);
|
|
247
649
|
if (spread && typeof spread === "object") {
|
|
248
650
|
for (const [k, v] of Object.entries(spread)) {
|
|
249
|
-
|
|
651
|
+
this.tick();
|
|
652
|
+
if (!BLOCKED_KEYS.has(k)) {
|
|
653
|
+
obj[k] = v;
|
|
654
|
+
count++;
|
|
655
|
+
}
|
|
250
656
|
}
|
|
251
657
|
}
|
|
252
658
|
continue;
|
|
253
659
|
}
|
|
660
|
+
if (prop.kind !== "init") throw new InterpreterError("Getters and setters are not supported");
|
|
254
661
|
const key = await this.propKey(prop, scope);
|
|
255
662
|
if (BLOCKED_KEYS.has(key)) throw new InterpreterError(`Forbidden property key: ${key}`);
|
|
256
663
|
obj[key] = await this.evalExpr(prop.value, scope);
|
|
664
|
+
count++;
|
|
257
665
|
}
|
|
666
|
+
this.charge(count * 16);
|
|
258
667
|
return obj;
|
|
259
668
|
}
|
|
260
|
-
case "UnaryExpression":
|
|
261
|
-
|
|
262
|
-
|
|
263
|
-
|
|
264
|
-
|
|
265
|
-
|
|
266
|
-
|
|
267
|
-
|
|
268
|
-
|
|
269
|
-
|
|
270
|
-
return typeof v;
|
|
271
|
-
case "~":
|
|
272
|
-
return ~v;
|
|
273
|
-
default:
|
|
274
|
-
throw new InterpreterError(`Unsupported unary operator: ${node.operator}`);
|
|
275
|
-
}
|
|
669
|
+
case "UnaryExpression":
|
|
670
|
+
return this.evalUnary(node, scope);
|
|
671
|
+
case "UpdateExpression": {
|
|
672
|
+
const ref = await this.resolveReference(node.argument, scope);
|
|
673
|
+
const current = ref.get();
|
|
674
|
+
assertArrayTextWithinLimit(current);
|
|
675
|
+
const before = Number(current);
|
|
676
|
+
const after = node.operator === "++" ? before + 1 : before - 1;
|
|
677
|
+
ref.set(after);
|
|
678
|
+
return node.prefix ? after : before;
|
|
276
679
|
}
|
|
277
680
|
case "BinaryExpression":
|
|
278
681
|
return this.evalBinary(node, scope);
|
|
@@ -284,10 +687,26 @@ var Interpreter = class {
|
|
|
284
687
|
}
|
|
285
688
|
case "ConditionalExpression":
|
|
286
689
|
return truthy(await this.evalExpr(node.test, scope)) ? this.evalExpr(node.consequent, scope) : this.evalExpr(node.alternate, scope);
|
|
287
|
-
case "
|
|
288
|
-
|
|
690
|
+
case "SequenceExpression": {
|
|
691
|
+
let last;
|
|
692
|
+
for (const expression of node.expressions) last = await this.evalExpr(expression, scope);
|
|
693
|
+
return last;
|
|
694
|
+
}
|
|
695
|
+
case "ChainExpression":
|
|
696
|
+
try {
|
|
697
|
+
return await this.evalExpr(node.expression, scope);
|
|
698
|
+
} catch (e) {
|
|
699
|
+
if (e instanceof ChainShortCircuit) return void 0;
|
|
700
|
+
throw e;
|
|
701
|
+
}
|
|
702
|
+
case "MemberExpression": {
|
|
703
|
+
const { object, key } = await this.evalMemberTarget(node, scope);
|
|
704
|
+
return readProperty(object, key);
|
|
705
|
+
}
|
|
289
706
|
case "CallExpression":
|
|
290
707
|
return this.evalCall(node, scope);
|
|
708
|
+
case "NewExpression":
|
|
709
|
+
return this.evalNew(node, scope);
|
|
291
710
|
case "AwaitExpression":
|
|
292
711
|
return await this.evalExpr(node.argument, scope);
|
|
293
712
|
case "AssignmentExpression":
|
|
@@ -303,16 +722,79 @@ var Interpreter = class {
|
|
|
303
722
|
let out = "";
|
|
304
723
|
for (let i = 0; i < node.quasis.length; i++) {
|
|
305
724
|
out += node.quasis[i].value.cooked ?? "";
|
|
306
|
-
if (i < node.expressions.length)
|
|
725
|
+
if (i < node.expressions.length) {
|
|
726
|
+
const value = await this.evalExpr(node.expressions[i], scope);
|
|
727
|
+
assertArrayTextWithinLimit(value);
|
|
728
|
+
out += String(value);
|
|
729
|
+
if (out.length > MAX_JOIN_LENGTH) throw new InterpreterError(TEXT_TOO_LONG);
|
|
730
|
+
}
|
|
307
731
|
}
|
|
732
|
+
this.charge(out.length * 2);
|
|
308
733
|
return out;
|
|
309
734
|
}
|
|
735
|
+
async evalUnary(node, scope) {
|
|
736
|
+
if (node.operator === "typeof" && node.argument.type === "Identifier" && !scope.has(node.argument.name) && !Object.prototype.hasOwnProperty.call(this.globals, node.argument.name)) {
|
|
737
|
+
return "undefined";
|
|
738
|
+
}
|
|
739
|
+
if (node.operator === "delete") {
|
|
740
|
+
if (node.argument.type !== "MemberExpression") throw new InterpreterError("Only a property can be deleted");
|
|
741
|
+
const { object, key } = await this.evalMemberTarget(node.argument, scope);
|
|
742
|
+
this.assertChangeable(object);
|
|
743
|
+
assertKeyAllowed(key);
|
|
744
|
+
return delete object[key];
|
|
745
|
+
}
|
|
746
|
+
const v = await this.evalExpr(node.argument, scope);
|
|
747
|
+
switch (node.operator) {
|
|
748
|
+
case "!":
|
|
749
|
+
return !truthy(v);
|
|
750
|
+
case "-":
|
|
751
|
+
assertArrayTextWithinLimit(v);
|
|
752
|
+
return -v;
|
|
753
|
+
case "+":
|
|
754
|
+
assertArrayTextWithinLimit(v);
|
|
755
|
+
return +v;
|
|
756
|
+
case "typeof":
|
|
757
|
+
return typeof v;
|
|
758
|
+
case "~":
|
|
759
|
+
assertArrayTextWithinLimit(v);
|
|
760
|
+
return ~v;
|
|
761
|
+
case "void":
|
|
762
|
+
return void 0;
|
|
763
|
+
default:
|
|
764
|
+
throw new InterpreterError(`Unsupported unary operator: ${node.operator}`);
|
|
765
|
+
}
|
|
766
|
+
}
|
|
310
767
|
async evalBinary(node, scope) {
|
|
768
|
+
if (node.left.type === "PrivateIdentifier") throw new InterpreterError("Private names are not supported");
|
|
311
769
|
const l = await this.evalExpr(node.left, scope);
|
|
312
770
|
const r = await this.evalExpr(node.right, scope);
|
|
313
|
-
|
|
314
|
-
|
|
315
|
-
|
|
771
|
+
if (node.operator === "in") {
|
|
772
|
+
if (r === null || typeof r !== "object" && typeof r !== "function") {
|
|
773
|
+
throw new InterpreterError("Cannot use 'in' on a value that is not an object");
|
|
774
|
+
}
|
|
775
|
+
assertArrayTextWithinLimit(l);
|
|
776
|
+
const key = String(l);
|
|
777
|
+
if (BLOCKED_KEYS.has(key)) throw new InterpreterError(`Forbidden property access: ${key}`);
|
|
778
|
+
return key in r;
|
|
779
|
+
}
|
|
780
|
+
if (node.operator === "instanceof") {
|
|
781
|
+
const check = this.options.instanceChecks?.get(r);
|
|
782
|
+
if (!check) throw new InterpreterError("instanceof works with the built-in types the sandbox provides only");
|
|
783
|
+
return check(l);
|
|
784
|
+
}
|
|
785
|
+
return this.binary(node.operator, l, r);
|
|
786
|
+
}
|
|
787
|
+
/** Apply a binary operator to two values. */
|
|
788
|
+
binary(operator, left, right) {
|
|
789
|
+
if (operator !== "===" && operator !== "!==") assertArrayTextWithinLimit(left, right);
|
|
790
|
+
const l = left;
|
|
791
|
+
const r = right;
|
|
792
|
+
switch (operator) {
|
|
793
|
+
case "+": {
|
|
794
|
+
const sum = l + r;
|
|
795
|
+
if (typeof sum === "string") this.charge((sum.length - (typeof left === "string" ? left.length : 0)) * 2);
|
|
796
|
+
return sum;
|
|
797
|
+
}
|
|
316
798
|
case "-":
|
|
317
799
|
return l - r;
|
|
318
800
|
case "*":
|
|
@@ -352,60 +834,363 @@ var Interpreter = class {
|
|
|
352
834
|
case ">>>":
|
|
353
835
|
return l >>> r;
|
|
354
836
|
default:
|
|
355
|
-
throw new InterpreterError(`Unsupported binary operator: ${
|
|
837
|
+
throw new InterpreterError(`Unsupported binary operator: ${operator}`);
|
|
356
838
|
}
|
|
357
839
|
}
|
|
358
|
-
/**
|
|
359
|
-
|
|
840
|
+
/**
|
|
841
|
+
* Resolve a member expression to the object and the key it names, blocking escape keys.
|
|
842
|
+
* Inside an optional chain, a `?.` on `null` or `undefined` ends the chain.
|
|
843
|
+
*/
|
|
844
|
+
async evalMemberTarget(node, scope) {
|
|
845
|
+
if (node.object.type === "Super") throw new InterpreterError("super is not supported");
|
|
360
846
|
const object = await this.evalExpr(node.object, scope);
|
|
361
|
-
|
|
847
|
+
if (node.optional && (object === null || object === void 0)) throw new ChainShortCircuit();
|
|
848
|
+
if (node.property.type === "PrivateIdentifier") throw new InterpreterError("Private names are not supported");
|
|
849
|
+
const key = node.computed ? this.keyText(await this.evalExpr(node.property, scope)) : node.property.name;
|
|
362
850
|
if (BLOCKED_KEYS.has(key)) throw new InterpreterError(`Forbidden property access: ${key}`);
|
|
363
851
|
if (object == null) throw new InterpreterError(`Cannot read '${key}' of ${String(object)}`);
|
|
364
|
-
|
|
365
|
-
return { object, key, value };
|
|
852
|
+
return { object, key };
|
|
366
853
|
}
|
|
367
|
-
|
|
368
|
-
|
|
369
|
-
|
|
370
|
-
|
|
371
|
-
|
|
372
|
-
|
|
373
|
-
|
|
374
|
-
}
|
|
375
|
-
|
|
854
|
+
/** A variable or a member as something that can be read and assigned. */
|
|
855
|
+
async resolveReference(node, scope) {
|
|
856
|
+
if (node.type === "Identifier") {
|
|
857
|
+
const name = node.name;
|
|
858
|
+
return {
|
|
859
|
+
get: () => scope.get(name),
|
|
860
|
+
set: (value) => scope.set(name, value)
|
|
861
|
+
};
|
|
862
|
+
}
|
|
863
|
+
if (node.type === "MemberExpression") {
|
|
864
|
+
const { object, key } = await this.evalMemberTarget(node, scope);
|
|
865
|
+
return {
|
|
866
|
+
get: () => readProperty(object, key),
|
|
867
|
+
set: (value) => this.writeMember(object, key, value)
|
|
868
|
+
};
|
|
869
|
+
}
|
|
870
|
+
throw new InterpreterError(`Unsupported assignment target: ${node.type}`);
|
|
871
|
+
}
|
|
872
|
+
/**
|
|
873
|
+
* Only data a script owns can be changed: arrays and plain objects that are not frozen. The
|
|
874
|
+
* globals, functions (the host's built-ins among them, which the whole process shares), dates
|
|
875
|
+
* and the error copies are not: a property set on one of them would be seen by host code.
|
|
876
|
+
*/
|
|
877
|
+
assertChangeable(object) {
|
|
878
|
+
if (!isScriptData(object)) {
|
|
879
|
+
throw new InterpreterError("Only objects and arrays the script created can be changed");
|
|
880
|
+
}
|
|
881
|
+
if (Object.isFrozen(object)) throw new InterpreterError("Cannot change a read-only value");
|
|
882
|
+
}
|
|
883
|
+
writeMember(object, key, value) {
|
|
884
|
+
this.assertChangeable(object);
|
|
885
|
+
assertKeyAllowed(key);
|
|
886
|
+
if (Array.isArray(object)) {
|
|
887
|
+
const grownTo = arrayLengthAfterWrite(object, key, value);
|
|
888
|
+
if (grownTo > MAX_ARRAY_LENGTH) {
|
|
889
|
+
throw new InterpreterError(`An array cannot be longer than ${MAX_ARRAY_LENGTH} items`);
|
|
890
|
+
}
|
|
891
|
+
if (grownTo > object.length) this.charge((grownTo - object.length) * 8);
|
|
892
|
+
}
|
|
893
|
+
object[key] = value;
|
|
894
|
+
}
|
|
895
|
+
/** Append what an iterable yields to an array, one step and one length check per item. */
|
|
896
|
+
spreadInto(target, iterable) {
|
|
897
|
+
if (!isIterable(iterable)) throw new InterpreterError("Spread target is not iterable");
|
|
898
|
+
for (const value of iterable) {
|
|
899
|
+
this.tick();
|
|
900
|
+
if (target.length >= MAX_ARRAY_LENGTH) {
|
|
901
|
+
throw new InterpreterError(`An array cannot be longer than ${MAX_ARRAY_LENGTH} items`);
|
|
376
902
|
}
|
|
903
|
+
target.push(value);
|
|
904
|
+
}
|
|
905
|
+
}
|
|
906
|
+
async evalArguments(nodes, scope) {
|
|
907
|
+
const args = [];
|
|
908
|
+
for (const a of nodes) {
|
|
909
|
+
if (a.type === "SpreadElement") this.spreadInto(args, await this.evalExpr(a.argument, scope));
|
|
910
|
+
else args.push(await this.evalExpr(a, scope));
|
|
377
911
|
}
|
|
912
|
+
return args;
|
|
913
|
+
}
|
|
914
|
+
async evalNew(node, scope) {
|
|
915
|
+
if (node.callee.type === "Super") throw new InterpreterError("super is not supported");
|
|
916
|
+
const callee = await this.evalExpr(node.callee, scope);
|
|
917
|
+
const construct = this.options.constructors?.get(callee);
|
|
918
|
+
if (!construct) throw new InterpreterError("new works with the built-in types the sandbox provides only");
|
|
919
|
+
const args = await this.evalArguments(node.arguments, scope);
|
|
920
|
+
if (!ARRAY_DATA_FUNCTIONS.has(callee)) assertArrayTextWithinLimit(...args);
|
|
921
|
+
const value = construct(args);
|
|
922
|
+
this.chargeValue(value);
|
|
923
|
+
return value;
|
|
924
|
+
}
|
|
925
|
+
async evalCall(node, scope) {
|
|
378
926
|
let fn;
|
|
379
927
|
let thisArg;
|
|
928
|
+
let member;
|
|
380
929
|
if (node.callee.type === "MemberExpression") {
|
|
381
|
-
const
|
|
382
|
-
|
|
383
|
-
|
|
384
|
-
|
|
385
|
-
|
|
386
|
-
|
|
387
|
-
const produced = m.key === "repeat" ? m.object.length * (n > 0 ? n : 0) : Math.max(m.object.length, n > 0 ? n : 0);
|
|
388
|
-
if (produced > MAX_STRING_OP_LENGTH) {
|
|
389
|
-
throw new InterpreterError(
|
|
390
|
-
`String '${m.key}' would produce ${produced} chars, exceeding the ${MAX_STRING_OP_LENGTH} limit`
|
|
391
|
-
);
|
|
392
|
-
}
|
|
393
|
-
}
|
|
394
|
-
fn = m.value;
|
|
395
|
-
thisArg = m.object;
|
|
930
|
+
const target = await this.evalMemberTarget(node.callee, scope);
|
|
931
|
+
member = { ...target, value: readProperty(target.object, target.key) };
|
|
932
|
+
fn = member.value;
|
|
933
|
+
thisArg = member.object;
|
|
934
|
+
} else if (node.callee.type === "Super") {
|
|
935
|
+
throw new InterpreterError("super is not supported");
|
|
396
936
|
} else {
|
|
397
937
|
fn = await this.evalExpr(node.callee, scope);
|
|
398
938
|
thisArg = void 0;
|
|
399
939
|
}
|
|
940
|
+
if (node.optional && (fn === null || fn === void 0)) {
|
|
941
|
+
throw new ChainShortCircuit();
|
|
942
|
+
}
|
|
943
|
+
const args = await this.evalArguments(node.arguments, scope);
|
|
944
|
+
if (typeof fn !== "function") throw new InterpreterError("Attempted to call a non-function");
|
|
945
|
+
return this.callFunction(fn, thisArg, args, scope.depth);
|
|
946
|
+
}
|
|
947
|
+
/**
|
|
948
|
+
* Call a function with a receiver and arguments: an interpreted function, or a built-in or host
|
|
949
|
+
* function after the checks that apply to it. `call` and `apply` are resolved to the function
|
|
950
|
+
* they invoke first, so those checks cannot be passed by the way a call is written.
|
|
951
|
+
*
|
|
952
|
+
* @param depth - How many calls deep the code that makes this call runs
|
|
953
|
+
*/
|
|
954
|
+
async callFunction(fn, thisArg, args, depth) {
|
|
955
|
+
for (let hops = 0; fn === FunctionProtoCall || fn === FunctionProtoApply || fn === FunctionProtoBind; hops++) {
|
|
956
|
+
const name = fn === FunctionProtoCall ? "call" : fn === FunctionProtoApply ? "apply" : "bind";
|
|
957
|
+
if (typeof thisArg !== "function" || hops >= 8) {
|
|
958
|
+
throw new InterpreterError(`'${name}' works on a function only`);
|
|
959
|
+
}
|
|
960
|
+
if (typeof args[0] === "function") {
|
|
961
|
+
throw new InterpreterError(`'${name}' cannot make a function the receiver of a call`);
|
|
962
|
+
}
|
|
963
|
+
const target = thisArg;
|
|
964
|
+
if (fn === FunctionProtoBind) return this.bindFunction(target, args[0], args.slice(1));
|
|
965
|
+
thisArg = args[0];
|
|
966
|
+
args = fn === FunctionProtoCall ? args.slice(1) : this.argumentList(args[1]);
|
|
967
|
+
fn = target;
|
|
968
|
+
}
|
|
400
969
|
if (typeof fn !== "function") throw new InterpreterError("Attempted to call a non-function");
|
|
401
|
-
if (
|
|
402
|
-
|
|
970
|
+
if (this.interpretedFunctions.has(fn)) {
|
|
971
|
+
const interpreted = fn;
|
|
972
|
+
return await this.withCallerDepth(depth, () => interpreted.apply(thisArg, args));
|
|
973
|
+
}
|
|
974
|
+
const own = this.enterCall(depth);
|
|
975
|
+
try {
|
|
976
|
+
args = this.checkBuiltinCall(fn, thisArg, args);
|
|
977
|
+
const arrayMethod = ARRAY_METHODS.get(fn);
|
|
978
|
+
if (arrayMethod !== void 0 && HIGHER_ORDER_ARRAY_METHODS.has(arrayMethod) && typeof args[0] === "function") {
|
|
979
|
+
return await this.callArrayMethod(thisArg, arrayMethod, args, own);
|
|
980
|
+
}
|
|
981
|
+
const builtin = fn;
|
|
982
|
+
const builtinArgs = args;
|
|
983
|
+
const result = await this.withCallerDepth(own, () => builtin.apply(thisArg, builtinArgs));
|
|
984
|
+
if (arrayMethod === void 0 && STRING_METHODS.get(fn) === "split" && Array.isArray(result)) {
|
|
985
|
+
if (result.length > MAX_ARRAY_LENGTH) {
|
|
986
|
+
throw new InterpreterError(`An array cannot be longer than ${MAX_ARRAY_LENGTH} items`);
|
|
987
|
+
}
|
|
988
|
+
}
|
|
989
|
+
this.chargeValue(result);
|
|
990
|
+
return result;
|
|
991
|
+
} finally {
|
|
992
|
+
this.pendingCalls--;
|
|
993
|
+
}
|
|
994
|
+
}
|
|
995
|
+
/**
|
|
996
|
+
* Count a call that starts `callerDepth` calls deep, until it returns.
|
|
997
|
+
*
|
|
998
|
+
* @returns The depth the call itself runs at
|
|
999
|
+
*/
|
|
1000
|
+
enterCall(callerDepth) {
|
|
1001
|
+
const depth = callerDepth + 1;
|
|
1002
|
+
if (depth > this.options.maxCallDepth) {
|
|
403
1003
|
throw new InterpreterError(`Max call depth exceeded (${this.options.maxCallDepth})`);
|
|
404
1004
|
}
|
|
1005
|
+
if (this.pendingCalls >= this.maxPendingCalls) {
|
|
1006
|
+
throw new InterpreterError(`Too many calls in progress at once (${this.maxPendingCalls})`);
|
|
1007
|
+
}
|
|
1008
|
+
this.pendingCalls++;
|
|
1009
|
+
return depth;
|
|
1010
|
+
}
|
|
1011
|
+
/**
|
|
1012
|
+
* Make a call with `depth` as the depth a function of the script is called from, if one starts
|
|
1013
|
+
* during it. It covers the synchronous part of the call, which is where a function starts.
|
|
1014
|
+
*/
|
|
1015
|
+
withCallerDepth(depth, call) {
|
|
1016
|
+
const previous = this.callerDepth;
|
|
1017
|
+
this.callerDepth = depth;
|
|
405
1018
|
try {
|
|
406
|
-
return
|
|
1019
|
+
return call();
|
|
407
1020
|
} finally {
|
|
408
|
-
this.
|
|
1021
|
+
this.callerDepth = previous;
|
|
1022
|
+
}
|
|
1023
|
+
}
|
|
1024
|
+
/** The argument list of `apply`: an array, or nothing. */
|
|
1025
|
+
argumentList(value) {
|
|
1026
|
+
if (value === null || value === void 0) return [];
|
|
1027
|
+
if (!Array.isArray(value)) throw new InterpreterError("'apply' takes its arguments as an array");
|
|
1028
|
+
this.charge(value.length * 8);
|
|
1029
|
+
return [...value];
|
|
1030
|
+
}
|
|
1031
|
+
/**
|
|
1032
|
+
* `fn.bind(receiver, ...args)`: a function that calls `fn` through {@link callFunction}, so
|
|
1033
|
+
* that what is checked for a call of `fn` is checked for a call of the bound function too.
|
|
1034
|
+
*/
|
|
1035
|
+
bindFunction(target, boundThis, boundArgs) {
|
|
1036
|
+
this.charge((boundArgs.length + 2) * 8);
|
|
1037
|
+
return (...rest) => {
|
|
1038
|
+
const result = this.callFunction(target, boundThis, [...boundArgs, ...rest], this.callerDepth);
|
|
1039
|
+
result.then(void 0, ignoreRejection2);
|
|
1040
|
+
return result;
|
|
1041
|
+
};
|
|
1042
|
+
}
|
|
1043
|
+
/**
|
|
1044
|
+
* The checks before a built-in or host function runs. The engine performs such a call in one
|
|
1045
|
+
* step, out of reach of the step budget, and what the call allocates is only known to the
|
|
1046
|
+
* budget when it exists: whatever could make that large is refused here, from the arguments.
|
|
1047
|
+
*
|
|
1048
|
+
* @returns The arguments to call the function with
|
|
1049
|
+
*/
|
|
1050
|
+
checkBuiltinCall(fn, thisArg, args) {
|
|
1051
|
+
const arrayMethod = ARRAY_METHODS.get(fn);
|
|
1052
|
+
const stringMethod = arrayMethod === void 0 ? STRING_METHODS.get(fn) : void 0;
|
|
1053
|
+
let arrayText = 0;
|
|
1054
|
+
if (!ARRAY_DATA_FUNCTIONS.has(fn)) {
|
|
1055
|
+
const isData = arrayMethod === void 0 ? void 0 : ARRAY_DATA_ARGUMENTS.get(arrayMethod);
|
|
1056
|
+
const converted = CONVERTED_ARGUMENTS.get(fn) ?? args.length;
|
|
1057
|
+
let measure;
|
|
1058
|
+
const measureArray = (value) => {
|
|
1059
|
+
measure ??= newTextMeasure();
|
|
1060
|
+
measureArrayText(value, 1, measure, 0);
|
|
1061
|
+
if (measure.length > MAX_JOIN_LENGTH) throw new InterpreterError(TEXT_TOO_LONG);
|
|
1062
|
+
};
|
|
1063
|
+
for (let i = 0; i < args.length && i < converted; i++) {
|
|
1064
|
+
const arg = args[i];
|
|
1065
|
+
if (Array.isArray(arg) && !isData?.(i)) measureArray(arg);
|
|
1066
|
+
}
|
|
1067
|
+
if (arrayMethod === void 0 && stringMethod === void 0 && Array.isArray(thisArg)) measureArray(thisArg);
|
|
1068
|
+
arrayText = measure?.length ?? 0;
|
|
1069
|
+
}
|
|
1070
|
+
if (stringMethod !== void 0) args = this.checkStringMethod(stringMethod, thisArg, args, arrayText);
|
|
1071
|
+
else if (arrayMethod !== void 0) this.checkArrayMethod(arrayMethod, thisArg, args);
|
|
1072
|
+
const cost = CALL_COSTS.get(fn);
|
|
1073
|
+
if (cost) this.charge(cost(args));
|
|
1074
|
+
return args;
|
|
1075
|
+
}
|
|
1076
|
+
checkStringMethod(name, receiver, args, arrayText) {
|
|
1077
|
+
if (typeof receiver !== "string") throw new InterpreterError(`String '${name}' works on a string only`);
|
|
1078
|
+
if (name === "match" || name === "matchAll" || name === "search") {
|
|
1079
|
+
throw new InterpreterError(`String '${name}' is not supported: it runs a regular expression`);
|
|
1080
|
+
}
|
|
1081
|
+
if (name === "replace" || name === "replaceAll") {
|
|
1082
|
+
const replacement = args[1];
|
|
1083
|
+
if (typeof replacement === "function") {
|
|
1084
|
+
throw new InterpreterError(`String '${name}' does not take a function in the sandbox`);
|
|
1085
|
+
}
|
|
1086
|
+
if (typeof replacement === "object" && replacement !== null) {
|
|
1087
|
+
throw new InterpreterError(`String '${name}' takes a text as the replacement`);
|
|
1088
|
+
}
|
|
1089
|
+
const text = String(replacement);
|
|
1090
|
+
const search = args[0];
|
|
1091
|
+
const searchLength = typeof search === "string" ? search.length : 0;
|
|
1092
|
+
const matches = name === "replace" ? 1 : searchLength > 0 ? Math.floor(receiver.length / searchLength) : receiver.length + 1;
|
|
1093
|
+
let dollars = 0;
|
|
1094
|
+
for (let at = text.indexOf("$"); at !== -1; at = text.indexOf("$", at + 1)) dollars++;
|
|
1095
|
+
const perMatch = text.length + dollars * receiver.length;
|
|
1096
|
+
if (matches * perMatch > MAX_STRING_OP_LENGTH) {
|
|
1097
|
+
throw new InterpreterError(
|
|
1098
|
+
`String '${name}' could produce more than ${MAX_STRING_OP_LENGTH} chars with this replacement`
|
|
1099
|
+
);
|
|
1100
|
+
}
|
|
1101
|
+
return args;
|
|
1102
|
+
}
|
|
1103
|
+
if (name === "repeat" || name === "padStart" || name === "padEnd") {
|
|
1104
|
+
const n = Number(args[0]);
|
|
1105
|
+
const produced = name === "repeat" ? receiver.length * (n > 0 ? n : 0) : Math.max(receiver.length, n > 0 ? n : 0);
|
|
1106
|
+
if (produced > MAX_STRING_OP_LENGTH) {
|
|
1107
|
+
throw new InterpreterError(
|
|
1108
|
+
`String '${name}' would produce ${produced} chars, exceeding the ${MAX_STRING_OP_LENGTH} limit`
|
|
1109
|
+
);
|
|
1110
|
+
}
|
|
1111
|
+
return args;
|
|
1112
|
+
}
|
|
1113
|
+
if (name === "concat") {
|
|
1114
|
+
let produced = receiver.length + arrayText;
|
|
1115
|
+
for (let i = 0; i < args.length && produced <= MAX_JOIN_LENGTH; i++) {
|
|
1116
|
+
const arg = args[i];
|
|
1117
|
+
if (typeof arg === "string") produced += arg.length;
|
|
1118
|
+
else if (!Array.isArray(arg)) produced += scalarTextLength(arg, newTextMeasure());
|
|
1119
|
+
}
|
|
1120
|
+
if (produced > MAX_JOIN_LENGTH) {
|
|
1121
|
+
throw new InterpreterError(`String 'concat' would produce more than ${MAX_JOIN_LENGTH} chars`);
|
|
1122
|
+
}
|
|
1123
|
+
return args;
|
|
1124
|
+
}
|
|
1125
|
+
if (name === "split") {
|
|
1126
|
+
const asked = args[1] === void 0 ? Number.POSITIVE_INFINITY : Number(args[1]) >>> 0;
|
|
1127
|
+
return [args[0], Math.min(asked, MAX_ARRAY_LENGTH + 1)];
|
|
1128
|
+
}
|
|
1129
|
+
return args;
|
|
1130
|
+
}
|
|
1131
|
+
checkArrayMethod(name, receiver, args) {
|
|
1132
|
+
if (!Array.isArray(receiver)) throw new InterpreterError(`Array '${name}' works on an array only`);
|
|
1133
|
+
const tooLong2 = () => {
|
|
1134
|
+
throw new InterpreterError(`An array cannot be longer than ${MAX_ARRAY_LENGTH} items`);
|
|
1135
|
+
};
|
|
1136
|
+
switch (name) {
|
|
1137
|
+
// `join` writes every item and a separator between them into one string, in one step; so
|
|
1138
|
+
// do the two conversions to text.
|
|
1139
|
+
case "join":
|
|
1140
|
+
case "toString":
|
|
1141
|
+
case "toLocaleString": {
|
|
1142
|
+
const separator = name !== "join" || args.length === 0 || args[0] === void 0 ? "," : String(args[0]);
|
|
1143
|
+
const measure = newTextMeasure();
|
|
1144
|
+
measureArrayText(receiver, separator.length, measure, 0);
|
|
1145
|
+
if (measure.length > MAX_JOIN_LENGTH) {
|
|
1146
|
+
throw new InterpreterError(`Array '${name}' would produce more than ${MAX_JOIN_LENGTH} chars`);
|
|
1147
|
+
}
|
|
1148
|
+
return;
|
|
1149
|
+
}
|
|
1150
|
+
// Without a comparison function the engine compares the items as text: strings as they
|
|
1151
|
+
// are, and an array among the items joined, again for every comparison.
|
|
1152
|
+
case "sort":
|
|
1153
|
+
case "toSorted": {
|
|
1154
|
+
if (typeof args[0] === "function") return;
|
|
1155
|
+
const measure = newTextMeasure();
|
|
1156
|
+
for (let i = 0; i < receiver.length && measure.length <= MAX_JOIN_LENGTH; i++) {
|
|
1157
|
+
const item = receiver[i];
|
|
1158
|
+
if (Array.isArray(item)) measureArrayText(item, 1, measure, 1);
|
|
1159
|
+
}
|
|
1160
|
+
if (measure.length > MAX_JOIN_LENGTH) throw new InterpreterError(TEXT_TOO_LONG);
|
|
1161
|
+
return;
|
|
1162
|
+
}
|
|
1163
|
+
// Growth by the arguments (a spread makes them many): charged before it happens.
|
|
1164
|
+
case "push":
|
|
1165
|
+
case "unshift":
|
|
1166
|
+
if (receiver.length + args.length > MAX_ARRAY_LENGTH) tooLong2();
|
|
1167
|
+
this.charge(args.length * 8);
|
|
1168
|
+
return;
|
|
1169
|
+
case "splice":
|
|
1170
|
+
case "toSpliced": {
|
|
1171
|
+
const added = Math.max(0, args.length - 2);
|
|
1172
|
+
if (receiver.length + added > MAX_ARRAY_LENGTH) tooLong2();
|
|
1173
|
+
if (name === "splice") this.charge(added * 8);
|
|
1174
|
+
return;
|
|
1175
|
+
}
|
|
1176
|
+
// A new array of the receiver and every array among the arguments: one array, given many
|
|
1177
|
+
// times, is small in memory and large once copied.
|
|
1178
|
+
case "concat": {
|
|
1179
|
+
let length = receiver.length;
|
|
1180
|
+
for (let i = 0; i < args.length && length <= MAX_ARRAY_LENGTH; i++) {
|
|
1181
|
+
const arg = args[i];
|
|
1182
|
+
length += Array.isArray(arg) ? arg.length : 1;
|
|
1183
|
+
}
|
|
1184
|
+
if (length > MAX_ARRAY_LENGTH) tooLong2();
|
|
1185
|
+
return;
|
|
1186
|
+
}
|
|
1187
|
+
case "flat": {
|
|
1188
|
+
const depth = args[0] === void 0 ? 1 : Number(args[0]);
|
|
1189
|
+
if (flatLength(receiver, Number.isNaN(depth) ? 0 : depth, MAX_ARRAY_LENGTH) > MAX_ARRAY_LENGTH) tooLong2();
|
|
1190
|
+
return;
|
|
1191
|
+
}
|
|
1192
|
+
default:
|
|
1193
|
+
return;
|
|
409
1194
|
}
|
|
410
1195
|
}
|
|
411
1196
|
/**
|
|
@@ -413,8 +1198,11 @@ var Interpreter = class {
|
|
|
413
1198
|
* callbacks (which are async — they may `await` tool calls) are awaited. Each
|
|
414
1199
|
* iteration ticks the step budget.
|
|
415
1200
|
*/
|
|
416
|
-
async callArrayMethod(arr, method, args) {
|
|
417
|
-
const
|
|
1201
|
+
async callArrayMethod(arr, method, args, depth) {
|
|
1202
|
+
const callback = args[0];
|
|
1203
|
+
const interpreted = this.interpretedFunctions.has(callback) ? callback : void 0;
|
|
1204
|
+
const invoke = interpreted ? (...callbackArgs) => this.withCallerDepth(depth, () => interpreted(...callbackArgs)) : (...callbackArgs) => this.callFunction(callback, void 0, callbackArgs, depth);
|
|
1205
|
+
const cb = invoke;
|
|
418
1206
|
const each = (i) => {
|
|
419
1207
|
this.tick();
|
|
420
1208
|
return cb(arr[i], i, arr);
|
|
@@ -423,20 +1211,23 @@ var Interpreter = class {
|
|
|
423
1211
|
case "map": {
|
|
424
1212
|
const out = [];
|
|
425
1213
|
for (let i = 0; i < arr.length; i++) out.push(await each(i));
|
|
1214
|
+
this.charge(out.length * 8);
|
|
426
1215
|
return out;
|
|
427
1216
|
}
|
|
428
1217
|
case "flatMap": {
|
|
429
1218
|
const out = [];
|
|
430
1219
|
for (let i = 0; i < arr.length; i++) {
|
|
431
1220
|
const v = await each(i);
|
|
432
|
-
if (Array.isArray(v))
|
|
1221
|
+
if (Array.isArray(v)) this.spreadInto(out, v);
|
|
433
1222
|
else out.push(v);
|
|
434
1223
|
}
|
|
1224
|
+
this.charge(out.length * 8);
|
|
435
1225
|
return out;
|
|
436
1226
|
}
|
|
437
1227
|
case "filter": {
|
|
438
1228
|
const out = [];
|
|
439
1229
|
for (let i = 0; i < arr.length; i++) if (truthy(await each(i))) out.push(arr[i]);
|
|
1230
|
+
this.charge(out.length * 8);
|
|
440
1231
|
return out;
|
|
441
1232
|
}
|
|
442
1233
|
case "forEach":
|
|
@@ -454,116 +1245,197 @@ var Interpreter = class {
|
|
|
454
1245
|
case "findIndex":
|
|
455
1246
|
for (let i = 0; i < arr.length; i++) if (truthy(await each(i))) return i;
|
|
456
1247
|
return -1;
|
|
457
|
-
case "
|
|
1248
|
+
case "findLast":
|
|
1249
|
+
for (let i = arr.length - 1; i >= 0; i--) if (truthy(await each(i))) return arr[i];
|
|
1250
|
+
return void 0;
|
|
1251
|
+
case "findLastIndex":
|
|
1252
|
+
for (let i = arr.length - 1; i >= 0; i--) if (truthy(await each(i))) return i;
|
|
1253
|
+
return -1;
|
|
1254
|
+
case "reduce":
|
|
1255
|
+
case "reduceRight": {
|
|
458
1256
|
const reducer = cb;
|
|
1257
|
+
const fromRight = method === "reduceRight";
|
|
1258
|
+
const order = arr.map((_, i) => fromRight ? arr.length - 1 - i : i);
|
|
459
1259
|
let acc;
|
|
460
1260
|
let start = 0;
|
|
461
1261
|
if (args.length > 1) acc = args[1];
|
|
462
1262
|
else {
|
|
463
1263
|
if (arr.length === 0) throw new InterpreterError("Reduce of empty array with no initial value");
|
|
464
|
-
acc = arr[0];
|
|
1264
|
+
acc = arr[order[0]];
|
|
465
1265
|
start = 1;
|
|
466
1266
|
}
|
|
467
|
-
for (let
|
|
1267
|
+
for (let n = start; n < order.length; n++) {
|
|
468
1268
|
this.tick();
|
|
469
|
-
acc = await reducer(acc, arr[
|
|
1269
|
+
acc = await reducer(acc, arr[order[n]], order[n], arr);
|
|
470
1270
|
}
|
|
471
1271
|
return acc;
|
|
472
1272
|
}
|
|
473
|
-
case "sort":
|
|
1273
|
+
case "sort":
|
|
1274
|
+
case "toSorted": {
|
|
1275
|
+
const target = method === "sort" ? arr : [...arr];
|
|
1276
|
+
if (method === "sort") this.assertChangeable(arr);
|
|
1277
|
+
else this.charge(target.length * 8);
|
|
474
1278
|
const cmp = cb;
|
|
475
|
-
for (let i = 1; i <
|
|
1279
|
+
for (let i = 1; i < target.length; i++) {
|
|
476
1280
|
let j = i;
|
|
477
1281
|
while (j > 0) {
|
|
478
1282
|
this.tick();
|
|
479
|
-
if (await cmp(
|
|
480
|
-
[
|
|
1283
|
+
if (await cmp(target[j - 1], target[j]) <= 0) break;
|
|
1284
|
+
[target[j - 1], target[j]] = [target[j], target[j - 1]];
|
|
481
1285
|
j--;
|
|
482
1286
|
}
|
|
483
1287
|
}
|
|
484
|
-
return
|
|
1288
|
+
return target;
|
|
485
1289
|
}
|
|
486
1290
|
default:
|
|
487
1291
|
throw new InterpreterError(`Unsupported array method: ${method}`);
|
|
488
1292
|
}
|
|
489
1293
|
}
|
|
490
1294
|
async evalAssignment(node, scope) {
|
|
491
|
-
const value = await this.evalExpr(node.right, scope);
|
|
492
1295
|
if (node.operator === "=") {
|
|
493
|
-
|
|
1296
|
+
if (node.left.type === "MemberExpression") {
|
|
1297
|
+
const { object, key } = await this.evalMemberTarget(node.left, scope);
|
|
1298
|
+
const assigned = await this.evalExpr(node.right, scope);
|
|
1299
|
+
this.writeMember(object, key, assigned);
|
|
1300
|
+
return assigned;
|
|
1301
|
+
}
|
|
1302
|
+
const value = await this.evalExpr(node.right, scope);
|
|
1303
|
+
await this.applyPattern(node.left, value, scope, "assign");
|
|
494
1304
|
return value;
|
|
495
1305
|
}
|
|
496
|
-
const
|
|
497
|
-
const
|
|
498
|
-
|
|
499
|
-
|
|
500
|
-
|
|
501
|
-
|
|
502
|
-
|
|
503
|
-
|
|
504
|
-
if (target.type === "Identifier") {
|
|
505
|
-
scope.set(target.name, value);
|
|
506
|
-
return;
|
|
507
|
-
}
|
|
508
|
-
if (target.type === "MemberExpression") {
|
|
509
|
-
throw new InterpreterError("Member assignment is not supported in AgentScript");
|
|
1306
|
+
const ref = await this.resolveReference(node.left, scope);
|
|
1307
|
+
const current = ref.get();
|
|
1308
|
+
if (node.operator === "||=" || node.operator === "&&=" || node.operator === "??=") {
|
|
1309
|
+
const assign = node.operator === "||=" ? !truthy(current) : node.operator === "&&=" ? truthy(current) : current === null || current === void 0;
|
|
1310
|
+
if (!assign) return current;
|
|
1311
|
+
const value = await this.evalExpr(node.right, scope);
|
|
1312
|
+
ref.set(value);
|
|
1313
|
+
return value;
|
|
510
1314
|
}
|
|
511
|
-
|
|
1315
|
+
const next = this.binary(node.operator.slice(0, -1), current, await this.evalExpr(node.right, scope));
|
|
1316
|
+
ref.set(next);
|
|
1317
|
+
return next;
|
|
512
1318
|
}
|
|
513
|
-
|
|
514
|
-
|
|
515
|
-
|
|
516
|
-
|
|
517
|
-
|
|
518
|
-
|
|
519
|
-
|
|
520
|
-
|
|
521
|
-
|
|
522
|
-
|
|
523
|
-
|
|
524
|
-
|
|
525
|
-
|
|
526
|
-
|
|
527
|
-
|
|
528
|
-
if (prop.type === "RestElement") continue;
|
|
529
|
-
if (prop.computed) throw new InterpreterError("Computed destructuring keys are not allowed");
|
|
530
|
-
let key;
|
|
531
|
-
if (prop.key.type === "Identifier") key = prop.key.name;
|
|
532
|
-
else if (prop.key.type === "Literal") key = String(prop.key.value);
|
|
533
|
-
else throw new InterpreterError("Unsupported destructuring key");
|
|
534
|
-
if (BLOCKED_KEYS.has(key)) throw new InterpreterError(`Forbidden destructured key: ${key}`);
|
|
535
|
-
this.bindPattern(prop.value, obj[key], scope, mutable);
|
|
1319
|
+
/**
|
|
1320
|
+
* Give the names in a pattern their values: a declaration (`const` / `let`), a parameter list
|
|
1321
|
+
* or an assignment (`[a, o.b] = …`). Defaults and rest elements are handled here.
|
|
1322
|
+
*/
|
|
1323
|
+
async applyPattern(pattern, value, scope, mode) {
|
|
1324
|
+
switch (pattern.type) {
|
|
1325
|
+
case "Identifier":
|
|
1326
|
+
if (mode === "assign") scope.set(pattern.name, value);
|
|
1327
|
+
else scope.declare(pattern.name, value, mode === "let");
|
|
1328
|
+
return;
|
|
1329
|
+
case "MemberExpression": {
|
|
1330
|
+
if (mode !== "assign") throw new InterpreterError("Unsupported binding pattern: MemberExpression");
|
|
1331
|
+
const { object, key } = await this.evalMemberTarget(pattern, scope);
|
|
1332
|
+
this.writeMember(object, key, value);
|
|
1333
|
+
return;
|
|
536
1334
|
}
|
|
537
|
-
|
|
1335
|
+
case "AssignmentPattern":
|
|
1336
|
+
await this.applyPattern(
|
|
1337
|
+
pattern.left,
|
|
1338
|
+
value === void 0 ? await this.evalExpr(pattern.right, scope) : value,
|
|
1339
|
+
scope,
|
|
1340
|
+
mode
|
|
1341
|
+
);
|
|
1342
|
+
return;
|
|
1343
|
+
case "ArrayPattern": {
|
|
1344
|
+
const items = [];
|
|
1345
|
+
this.spreadInto(items, value);
|
|
1346
|
+
for (let i = 0; i < pattern.elements.length; i++) {
|
|
1347
|
+
const element = pattern.elements[i];
|
|
1348
|
+
if (!element) continue;
|
|
1349
|
+
if (element.type === "RestElement") {
|
|
1350
|
+
await this.applyPattern(element.argument, items.slice(i), scope, mode);
|
|
1351
|
+
break;
|
|
1352
|
+
}
|
|
1353
|
+
await this.applyPattern(element, items[i], scope, mode);
|
|
1354
|
+
}
|
|
1355
|
+
return;
|
|
1356
|
+
}
|
|
1357
|
+
case "ObjectPattern": {
|
|
1358
|
+
if (value === null || value === void 0) {
|
|
1359
|
+
throw new InterpreterError(`Cannot destructure ${String(value)}`);
|
|
1360
|
+
}
|
|
1361
|
+
const source = value;
|
|
1362
|
+
const taken = /* @__PURE__ */ new Set();
|
|
1363
|
+
for (const prop of pattern.properties) {
|
|
1364
|
+
if (prop.type === "RestElement") {
|
|
1365
|
+
const rest = {};
|
|
1366
|
+
for (const key2 of Object.keys(source)) {
|
|
1367
|
+
this.tick();
|
|
1368
|
+
if (!taken.has(key2) && !BLOCKED_KEYS.has(key2)) rest[key2] = source[key2];
|
|
1369
|
+
}
|
|
1370
|
+
await this.applyPattern(prop.argument, rest, scope, mode);
|
|
1371
|
+
continue;
|
|
1372
|
+
}
|
|
1373
|
+
if (prop.computed) throw new InterpreterError("Computed destructuring keys are not allowed");
|
|
1374
|
+
let key;
|
|
1375
|
+
if (prop.key.type === "Identifier") key = prop.key.name;
|
|
1376
|
+
else if (prop.key.type === "Literal") key = String(prop.key.value);
|
|
1377
|
+
else throw new InterpreterError("Unsupported destructuring key");
|
|
1378
|
+
if (BLOCKED_KEYS.has(key)) throw new InterpreterError(`Forbidden destructured key: ${key}`);
|
|
1379
|
+
taken.add(key);
|
|
1380
|
+
await this.applyPattern(prop.value, readProperty(source, key), scope, mode);
|
|
1381
|
+
}
|
|
1382
|
+
return;
|
|
1383
|
+
}
|
|
1384
|
+
default:
|
|
1385
|
+
throw new InterpreterError(`Unsupported binding pattern: ${pattern.type}`);
|
|
538
1386
|
}
|
|
539
|
-
throw new InterpreterError(`Unsupported binding pattern: ${pattern.type}`);
|
|
540
1387
|
}
|
|
541
1388
|
/** Build an interpreter-backed function (declaration / arrow / expression). */
|
|
542
1389
|
makeFunction(node, closure) {
|
|
543
|
-
|
|
544
|
-
|
|
545
|
-
|
|
546
|
-
|
|
1390
|
+
if (node.generator) throw new InterpreterError("Generator functions are not supported");
|
|
1391
|
+
const selfName = node.type === "FunctionExpression" && node.id ? node.id.name : void 0;
|
|
1392
|
+
const outer = selfName === void 0 ? closure : closure.child();
|
|
1393
|
+
const call = async (args, callerDepth) => {
|
|
1394
|
+
const fnScope = outer.activation(this.enterCall(callerDepth));
|
|
547
1395
|
try {
|
|
1396
|
+
for (let i = 0; i < node.params.length; i++) {
|
|
1397
|
+
const param = node.params[i];
|
|
1398
|
+
if (param.type === "RestElement") {
|
|
1399
|
+
await this.applyPattern(param.argument, args.slice(i), fnScope, "let");
|
|
1400
|
+
break;
|
|
1401
|
+
}
|
|
1402
|
+
await this.applyPattern(param, args[i], fnScope, "let");
|
|
1403
|
+
}
|
|
548
1404
|
if (node.body.type === "BlockStatement") {
|
|
549
|
-
await
|
|
1405
|
+
await this.execBlock(node.body.body, fnScope);
|
|
550
1406
|
return void 0;
|
|
551
1407
|
}
|
|
552
|
-
return await
|
|
1408
|
+
return await this.evalExpr(node.body, fnScope);
|
|
553
1409
|
} catch (e) {
|
|
554
1410
|
if (e instanceof ReturnSignal) return e.value;
|
|
555
1411
|
throw e;
|
|
1412
|
+
} finally {
|
|
1413
|
+
this.pendingCalls--;
|
|
556
1414
|
}
|
|
557
1415
|
};
|
|
1416
|
+
const depthOfCaller = () => this.callerDepth;
|
|
1417
|
+
const interpreted = function interpreted2(...args) {
|
|
1418
|
+
const result = call(args, depthOfCaller());
|
|
1419
|
+
result.then(void 0, ignoreRejection2);
|
|
1420
|
+
return result;
|
|
1421
|
+
};
|
|
1422
|
+
this.interpretedFunctions.add(interpreted);
|
|
1423
|
+
if (selfName !== void 0) outer.declare(selfName, interpreted, false);
|
|
1424
|
+
return interpreted;
|
|
1425
|
+
}
|
|
1426
|
+
/** A computed property key as text. An array as a key is its items, joined. */
|
|
1427
|
+
keyText(value) {
|
|
1428
|
+
assertArrayTextWithinLimit(value);
|
|
1429
|
+
return String(value);
|
|
558
1430
|
}
|
|
559
1431
|
async propKey(prop, scope) {
|
|
560
|
-
if (prop.computed) return
|
|
1432
|
+
if (prop.computed) return this.keyText(await this.evalExpr(prop.key, scope));
|
|
561
1433
|
if (prop.key.type === "Identifier") return prop.key.name;
|
|
562
1434
|
if (prop.key.type === "Literal") return String(prop.key.value);
|
|
563
1435
|
throw new InterpreterError("Unsupported property key");
|
|
564
1436
|
}
|
|
565
1437
|
readGlobal(name) {
|
|
566
|
-
if (Object.prototype.hasOwnProperty.call(this.globals, name)) return this.globals[name];
|
|
1438
|
+
if (name !== "__proto__" && Object.prototype.hasOwnProperty.call(this.globals, name)) return this.globals[name];
|
|
567
1439
|
throw new InterpreterError(`'${name}' is not defined`);
|
|
568
1440
|
}
|
|
569
1441
|
};
|
|
@@ -573,26 +1445,1218 @@ function truthy(v) {
|
|
|
573
1445
|
function isIterable(v) {
|
|
574
1446
|
return v != null && typeof v[Symbol.iterator] === "function";
|
|
575
1447
|
}
|
|
576
|
-
function
|
|
577
|
-
|
|
578
|
-
|
|
579
|
-
|
|
580
|
-
|
|
581
|
-
|
|
582
|
-
|
|
583
|
-
|
|
584
|
-
|
|
585
|
-
|
|
586
|
-
|
|
587
|
-
|
|
588
|
-
case "**":
|
|
589
|
-
return l ** r;
|
|
590
|
-
default:
|
|
591
|
-
throw new InterpreterError(`Unsupported compound operator: ${op}=`);
|
|
1448
|
+
function isScriptData(value) {
|
|
1449
|
+
if (value === Object.prototype || value === Array.prototype) return false;
|
|
1450
|
+
if (Array.isArray(value)) return true;
|
|
1451
|
+
if (value === null || typeof value !== "object") return false;
|
|
1452
|
+
const prototype = Object.getPrototypeOf(value);
|
|
1453
|
+
return prototype === Object.prototype || prototype === null;
|
|
1454
|
+
}
|
|
1455
|
+
function arrayLengthAfterWrite(array, key, value) {
|
|
1456
|
+
if (key === "length") {
|
|
1457
|
+
const length = Number(value);
|
|
1458
|
+
if (!Number.isInteger(length) || length < 0) throw new InterpreterError("Invalid array length");
|
|
1459
|
+
return length;
|
|
592
1460
|
}
|
|
1461
|
+
const index = Number(key);
|
|
1462
|
+
if (Number.isInteger(index) && index >= 0 && String(index) === key) return Math.max(array.length, index + 1);
|
|
1463
|
+
return array.length;
|
|
593
1464
|
}
|
|
594
1465
|
|
|
595
|
-
// libs/core/src/
|
|
1466
|
+
// libs/core/src/value-sanitizer.ts
|
|
1467
|
+
var DANGEROUS_KEYS = /* @__PURE__ */ new Set(["__proto__", "constructor"]);
|
|
1468
|
+
var ReflectApply2 = Reflect.apply;
|
|
1469
|
+
var ReflectGet = Reflect.get;
|
|
1470
|
+
var ArrayIsArray = Array.isArray;
|
|
1471
|
+
var ObjectKeys = Object.keys;
|
|
1472
|
+
var ObjectCreate = Object.create;
|
|
1473
|
+
var ObjectGetPrototypeOf = Object.getPrototypeOf;
|
|
1474
|
+
var NumberIsFinite = Number.isFinite;
|
|
1475
|
+
var MathFloor = Math.floor;
|
|
1476
|
+
var MapProtoEntries = Map.prototype.entries;
|
|
1477
|
+
var SetProtoValues = Set.prototype.values;
|
|
1478
|
+
var DateProtoGetTime = Date.prototype.getTime;
|
|
1479
|
+
var DateProtoToISOString = Date.prototype.toISOString;
|
|
1480
|
+
var RegExpProtoSourceGetter = Object.getOwnPropertyDescriptor(RegExp.prototype, "source")?.get;
|
|
1481
|
+
var RegExpFlagGetters = [
|
|
1482
|
+
["d", "hasIndices"],
|
|
1483
|
+
["g", "global"],
|
|
1484
|
+
["i", "ignoreCase"],
|
|
1485
|
+
["m", "multiline"],
|
|
1486
|
+
["s", "dotAll"],
|
|
1487
|
+
["u", "unicode"],
|
|
1488
|
+
["v", "unicodeSets"],
|
|
1489
|
+
["y", "sticky"]
|
|
1490
|
+
].map(([flag, property]) => [flag, Object.getOwnPropertyDescriptor(RegExp.prototype, property)?.get]);
|
|
1491
|
+
var MapProtoSizeGetter = Object.getOwnPropertyDescriptor(Map.prototype, "size")?.get;
|
|
1492
|
+
var SetProtoSizeGetter = Object.getOwnPropertyDescriptor(Set.prototype, "size")?.get;
|
|
1493
|
+
function hasBrand(builtin, value) {
|
|
1494
|
+
if (!builtin) return false;
|
|
1495
|
+
try {
|
|
1496
|
+
ReflectApply2(builtin, value, []);
|
|
1497
|
+
return true;
|
|
1498
|
+
} catch {
|
|
1499
|
+
return false;
|
|
1500
|
+
}
|
|
1501
|
+
}
|
|
1502
|
+
function regExpToString(value) {
|
|
1503
|
+
let flags = "";
|
|
1504
|
+
for (const [flag, getter] of RegExpFlagGetters) {
|
|
1505
|
+
if (getter && ReflectApply2(getter, value, [])) flags += flag;
|
|
1506
|
+
}
|
|
1507
|
+
return `/${ReflectApply2(RegExpProtoSourceGetter, value, [])}/${flags}`;
|
|
1508
|
+
}
|
|
1509
|
+
function isPlainObject(value) {
|
|
1510
|
+
const prototype = ObjectGetPrototypeOf(value);
|
|
1511
|
+
return prototype === null || ObjectGetPrototypeOf(prototype) === null;
|
|
1512
|
+
}
|
|
1513
|
+
function sanitizeValue(value, options = {}, depth = 0, context = { propCount: { count: 0 }, visited: /* @__PURE__ */ new WeakSet() }) {
|
|
1514
|
+
const maxDepth = options.maxDepth ?? 20;
|
|
1515
|
+
const maxProperties = options.maxProperties ?? 1e4;
|
|
1516
|
+
const allowDates = options.allowDates ?? true;
|
|
1517
|
+
const allowErrors = options.allowErrors ?? true;
|
|
1518
|
+
if (depth > maxDepth) {
|
|
1519
|
+
throw new Error(
|
|
1520
|
+
`Tool handler return value exceeds maximum depth (${maxDepth}). This limit prevents deeply nested objects that could cause stack overflow.`
|
|
1521
|
+
);
|
|
1522
|
+
}
|
|
1523
|
+
if (context.propCount.count > maxProperties) {
|
|
1524
|
+
throw new Error(
|
|
1525
|
+
`Tool handler return value exceeds maximum properties (${maxProperties}). This limit prevents memory exhaustion from large object graphs.`
|
|
1526
|
+
);
|
|
1527
|
+
}
|
|
1528
|
+
if (value === null || value === void 0) {
|
|
1529
|
+
return value;
|
|
1530
|
+
}
|
|
1531
|
+
const type = typeof value;
|
|
1532
|
+
if (type === "string" || type === "number" || type === "boolean") {
|
|
1533
|
+
return value;
|
|
1534
|
+
}
|
|
1535
|
+
if (type === "bigint") {
|
|
1536
|
+
return String(value);
|
|
1537
|
+
}
|
|
1538
|
+
if (type === "function") {
|
|
1539
|
+
throw new Error(
|
|
1540
|
+
"Tool handler returned a function. Functions cannot be returned to sandbox code as they could be used for code injection or host scope access."
|
|
1541
|
+
);
|
|
1542
|
+
}
|
|
1543
|
+
if (type === "symbol") {
|
|
1544
|
+
throw new Error(
|
|
1545
|
+
"Tool handler returned a symbol. Symbols cannot be returned to sandbox code as they could be used for prototype manipulation."
|
|
1546
|
+
);
|
|
1547
|
+
}
|
|
1548
|
+
if (type === "object" && value !== null) {
|
|
1549
|
+
if (context.visited.has(value)) {
|
|
1550
|
+
return "[Circular]";
|
|
1551
|
+
}
|
|
1552
|
+
context.visited.add(value);
|
|
1553
|
+
}
|
|
1554
|
+
if (ArrayIsArray(value)) {
|
|
1555
|
+
const rawLen = ReflectGet(value, "length");
|
|
1556
|
+
const len = typeof rawLen === "number" && NumberIsFinite(rawLen) && rawLen >= 0 ? MathFloor(rawLen) : 0;
|
|
1557
|
+
context.propCount.count += len;
|
|
1558
|
+
if (context.propCount.count > maxProperties) {
|
|
1559
|
+
throw new Error(`Tool handler return value exceeds maximum properties (${maxProperties}).`);
|
|
1560
|
+
}
|
|
1561
|
+
const result = [];
|
|
1562
|
+
for (let i = 0; i < len; i++) {
|
|
1563
|
+
let item;
|
|
1564
|
+
try {
|
|
1565
|
+
item = ReflectGet(value, i);
|
|
1566
|
+
} catch {
|
|
1567
|
+
item = void 0;
|
|
1568
|
+
}
|
|
1569
|
+
result[i] = sanitizeValue(item, options, depth + 1, context);
|
|
1570
|
+
}
|
|
1571
|
+
return result;
|
|
1572
|
+
}
|
|
1573
|
+
const inspected = options.unwrap ? options.unwrap(value) : value;
|
|
1574
|
+
const isPlain = isPlainObject(inspected);
|
|
1575
|
+
if (!isPlain && hasBrand(DateProtoGetTime, inspected)) {
|
|
1576
|
+
const time = ReflectApply2(DateProtoGetTime, inspected, []);
|
|
1577
|
+
if (allowDates) {
|
|
1578
|
+
return new Date(time);
|
|
1579
|
+
}
|
|
1580
|
+
return ReflectApply2(DateProtoToISOString, inspected, []);
|
|
1581
|
+
}
|
|
1582
|
+
if (value instanceof Error) {
|
|
1583
|
+
const rawName = ReflectGet(value, "name");
|
|
1584
|
+
const rawMessage = ReflectGet(value, "message");
|
|
1585
|
+
const name = typeof rawName === "string" ? rawName : "Error";
|
|
1586
|
+
const message = typeof rawMessage === "string" ? rawMessage : "";
|
|
1587
|
+
if (allowErrors) {
|
|
1588
|
+
return {
|
|
1589
|
+
name,
|
|
1590
|
+
message
|
|
1591
|
+
// Do NOT include stack trace - could leak host information
|
|
1592
|
+
};
|
|
1593
|
+
}
|
|
1594
|
+
return { error: message };
|
|
1595
|
+
}
|
|
1596
|
+
if (!isPlain && hasBrand(RegExpProtoSourceGetter, inspected)) {
|
|
1597
|
+
return regExpToString(inspected);
|
|
1598
|
+
}
|
|
1599
|
+
if (!isPlain && hasBrand(MapProtoSizeGetter, inspected)) {
|
|
1600
|
+
const sanitizedMap = ObjectCreate(null);
|
|
1601
|
+
const entries = ReflectApply2(MapProtoEntries, inspected, []);
|
|
1602
|
+
for (const [key, val] of entries) {
|
|
1603
|
+
if (typeof key !== "string") continue;
|
|
1604
|
+
if (DANGEROUS_KEYS.has(key)) continue;
|
|
1605
|
+
context.propCount.count++;
|
|
1606
|
+
sanitizedMap[key] = sanitizeValue(val, options, depth + 1, context);
|
|
1607
|
+
}
|
|
1608
|
+
return sanitizedMap;
|
|
1609
|
+
}
|
|
1610
|
+
if (!isPlain && hasBrand(SetProtoSizeGetter, inspected)) {
|
|
1611
|
+
const iter = ReflectApply2(SetProtoValues, inspected, []);
|
|
1612
|
+
const result = [];
|
|
1613
|
+
for (const item of iter) {
|
|
1614
|
+
context.propCount.count++;
|
|
1615
|
+
result.push(sanitizeValue(item, options, depth + 1, context));
|
|
1616
|
+
}
|
|
1617
|
+
return result;
|
|
1618
|
+
}
|
|
1619
|
+
if (type === "object") {
|
|
1620
|
+
const sanitized = ObjectCreate(null);
|
|
1621
|
+
const keys = ObjectKeys(value);
|
|
1622
|
+
context.propCount.count += keys.length;
|
|
1623
|
+
if (context.propCount.count > maxProperties) {
|
|
1624
|
+
throw new Error(`Tool handler return value exceeds maximum properties (${maxProperties}).`);
|
|
1625
|
+
}
|
|
1626
|
+
for (const key of keys) {
|
|
1627
|
+
if (DANGEROUS_KEYS.has(key)) {
|
|
1628
|
+
continue;
|
|
1629
|
+
}
|
|
1630
|
+
let propValue;
|
|
1631
|
+
try {
|
|
1632
|
+
propValue = ReflectGet(value, key);
|
|
1633
|
+
} catch {
|
|
1634
|
+
continue;
|
|
1635
|
+
}
|
|
1636
|
+
sanitized[key] = sanitizeValue(propValue, options, depth + 1, context);
|
|
1637
|
+
}
|
|
1638
|
+
return sanitized;
|
|
1639
|
+
}
|
|
1640
|
+
return String(value);
|
|
1641
|
+
}
|
|
1642
|
+
function estimateStringSize(str) {
|
|
1643
|
+
let bytes = 2;
|
|
1644
|
+
for (let i = 0; i < str.length; i++) {
|
|
1645
|
+
const code = str.charCodeAt(i);
|
|
1646
|
+
if (code < 128) {
|
|
1647
|
+
if (code === 34 || code === 92) {
|
|
1648
|
+
bytes += 2;
|
|
1649
|
+
} else if (code < 32) {
|
|
1650
|
+
bytes += 6;
|
|
1651
|
+
} else {
|
|
1652
|
+
bytes += 1;
|
|
1653
|
+
}
|
|
1654
|
+
} else if (code < 2048) {
|
|
1655
|
+
bytes += 2;
|
|
1656
|
+
} else if (code >= 55296 && code <= 57343) {
|
|
1657
|
+
const nextCode = code <= 56319 && i + 1 < str.length ? str.charCodeAt(i + 1) : 0;
|
|
1658
|
+
if (nextCode >= 56320 && nextCode <= 57343) {
|
|
1659
|
+
bytes += 4;
|
|
1660
|
+
i++;
|
|
1661
|
+
} else {
|
|
1662
|
+
bytes += 6;
|
|
1663
|
+
}
|
|
1664
|
+
} else {
|
|
1665
|
+
bytes += 3;
|
|
1666
|
+
}
|
|
1667
|
+
}
|
|
1668
|
+
return bytes;
|
|
1669
|
+
}
|
|
1670
|
+
function estimateSerializedSize(value, maxBytes = 0, depth = 0, maxDepth = 2e3, currentPath = /* @__PURE__ */ new Set()) {
|
|
1671
|
+
if (depth > maxDepth) {
|
|
1672
|
+
throw new Error(
|
|
1673
|
+
`Structure exceeds maximum nesting depth (${maxDepth}). Deeply nested structures are rejected to prevent stack overflow attacks.`
|
|
1674
|
+
);
|
|
1675
|
+
}
|
|
1676
|
+
if (value === null) return 4;
|
|
1677
|
+
if (value === void 0) return 0;
|
|
1678
|
+
const type = typeof value;
|
|
1679
|
+
if (type === "string") {
|
|
1680
|
+
const bytes = estimateStringSize(value);
|
|
1681
|
+
if (maxBytes > 0 && bytes > maxBytes) {
|
|
1682
|
+
throw new Error(`String serialization would exceed limit: ${bytes} > ${maxBytes} bytes`);
|
|
1683
|
+
}
|
|
1684
|
+
return bytes;
|
|
1685
|
+
}
|
|
1686
|
+
if (type === "number") {
|
|
1687
|
+
const num = value;
|
|
1688
|
+
if (!NumberIsFinite(num)) return 4;
|
|
1689
|
+
return String(num).length;
|
|
1690
|
+
}
|
|
1691
|
+
if (type === "boolean") {
|
|
1692
|
+
return value ? 4 : 5;
|
|
1693
|
+
}
|
|
1694
|
+
if (type === "bigint") {
|
|
1695
|
+
return String(value).length + 2;
|
|
1696
|
+
}
|
|
1697
|
+
if (type === "function" || type === "symbol") {
|
|
1698
|
+
return 0;
|
|
1699
|
+
}
|
|
1700
|
+
if (ArrayIsArray(value)) {
|
|
1701
|
+
if (currentPath.has(value)) {
|
|
1702
|
+
return 4;
|
|
1703
|
+
}
|
|
1704
|
+
currentPath.add(value);
|
|
1705
|
+
try {
|
|
1706
|
+
const rawLength = readProperty2(value, "length");
|
|
1707
|
+
const length = typeof rawLength === "number" && NumberIsFinite(rawLength) && rawLength >= 0 ? MathFloor(rawLength) : 0;
|
|
1708
|
+
let size = 2;
|
|
1709
|
+
for (let i = 0; i < length; i++) {
|
|
1710
|
+
if (i > 0) size += 1;
|
|
1711
|
+
let elementSize = estimateSerializedSize(readProperty2(value, i), maxBytes, depth + 1, maxDepth, currentPath);
|
|
1712
|
+
if (elementSize === 0) elementSize = 4;
|
|
1713
|
+
size += elementSize;
|
|
1714
|
+
if (maxBytes > 0 && size > maxBytes) {
|
|
1715
|
+
throw new Error(
|
|
1716
|
+
`Array serialization would exceed limit: estimated ${size}+ > ${maxBytes} bytes. This often indicates repeated references to large strings that expand during JSON serialization.`
|
|
1717
|
+
);
|
|
1718
|
+
}
|
|
1719
|
+
}
|
|
1720
|
+
return size;
|
|
1721
|
+
} finally {
|
|
1722
|
+
currentPath.delete(value);
|
|
1723
|
+
}
|
|
1724
|
+
}
|
|
1725
|
+
if (type === "object") {
|
|
1726
|
+
const object = value;
|
|
1727
|
+
if (currentPath.has(object)) {
|
|
1728
|
+
return 4;
|
|
1729
|
+
}
|
|
1730
|
+
if (!isPlainObject(object)) {
|
|
1731
|
+
if (hasBrand(DateProtoGetTime, object)) {
|
|
1732
|
+
return 26;
|
|
1733
|
+
}
|
|
1734
|
+
if (hasBrand(RegExpProtoSourceGetter, object)) {
|
|
1735
|
+
return estimateStringSize(regExpToString(object));
|
|
1736
|
+
}
|
|
1737
|
+
const isMap = hasBrand(MapProtoSizeGetter, object);
|
|
1738
|
+
if (isMap || hasBrand(SetProtoSizeGetter, object)) {
|
|
1739
|
+
currentPath.add(object);
|
|
1740
|
+
try {
|
|
1741
|
+
let size = 2;
|
|
1742
|
+
let first = true;
|
|
1743
|
+
const add = (bytes) => {
|
|
1744
|
+
size += bytes;
|
|
1745
|
+
if (maxBytes > 0 && size > maxBytes) {
|
|
1746
|
+
throw new Error(
|
|
1747
|
+
`${isMap ? "Map" : "Set"} serialization would exceed limit: estimated ${size}+ > ${maxBytes} bytes. This often indicates repeated references to large strings that expand during JSON serialization.`
|
|
1748
|
+
);
|
|
1749
|
+
}
|
|
1750
|
+
};
|
|
1751
|
+
if (isMap) {
|
|
1752
|
+
const entries = ReflectApply2(MapProtoEntries, object, []);
|
|
1753
|
+
for (const [key, entryValue] of entries) {
|
|
1754
|
+
if (typeof key !== "string" || DANGEROUS_KEYS.has(key)) continue;
|
|
1755
|
+
if (!first) size += 1;
|
|
1756
|
+
first = false;
|
|
1757
|
+
add(estimateStringSize(key) + 1);
|
|
1758
|
+
add(estimateSerializedSize(entryValue, maxBytes, depth + 1, maxDepth, currentPath));
|
|
1759
|
+
}
|
|
1760
|
+
} else {
|
|
1761
|
+
const items = ReflectApply2(SetProtoValues, object, []);
|
|
1762
|
+
for (const item of items) {
|
|
1763
|
+
if (!first) size += 1;
|
|
1764
|
+
first = false;
|
|
1765
|
+
add(estimateSerializedSize(item, maxBytes, depth + 1, maxDepth, currentPath) || 4);
|
|
1766
|
+
}
|
|
1767
|
+
}
|
|
1768
|
+
return size;
|
|
1769
|
+
} finally {
|
|
1770
|
+
currentPath.delete(object);
|
|
1771
|
+
}
|
|
1772
|
+
}
|
|
1773
|
+
}
|
|
1774
|
+
currentPath.add(object);
|
|
1775
|
+
try {
|
|
1776
|
+
let size = 2;
|
|
1777
|
+
const keys = ObjectKeys(object);
|
|
1778
|
+
let first = true;
|
|
1779
|
+
for (const key of keys) {
|
|
1780
|
+
if (DANGEROUS_KEYS.has(key)) continue;
|
|
1781
|
+
let propValue;
|
|
1782
|
+
try {
|
|
1783
|
+
propValue = ReflectGet(object, key);
|
|
1784
|
+
} catch {
|
|
1785
|
+
continue;
|
|
1786
|
+
}
|
|
1787
|
+
if (!first) size += 1;
|
|
1788
|
+
first = false;
|
|
1789
|
+
size += estimateStringSize(key) + 1;
|
|
1790
|
+
size += estimateSerializedSize(propValue, maxBytes, depth + 1, maxDepth, currentPath);
|
|
1791
|
+
if (maxBytes > 0 && size > maxBytes) {
|
|
1792
|
+
throw new Error(
|
|
1793
|
+
`Object serialization would exceed limit: estimated ${size}+ > ${maxBytes} bytes. This often indicates repeated references to large strings that expand during JSON serialization.`
|
|
1794
|
+
);
|
|
1795
|
+
}
|
|
1796
|
+
}
|
|
1797
|
+
return size;
|
|
1798
|
+
} finally {
|
|
1799
|
+
currentPath.delete(object);
|
|
1800
|
+
}
|
|
1801
|
+
}
|
|
1802
|
+
return 0;
|
|
1803
|
+
}
|
|
1804
|
+
function readProperty2(target, key) {
|
|
1805
|
+
try {
|
|
1806
|
+
return ReflectGet(target, key);
|
|
1807
|
+
} catch {
|
|
1808
|
+
return void 0;
|
|
1809
|
+
}
|
|
1810
|
+
}
|
|
1811
|
+
function checkSerializedSize(value, maxBytes) {
|
|
1812
|
+
try {
|
|
1813
|
+
const estimatedBytes = estimateSerializedSize(value, maxBytes);
|
|
1814
|
+
return { ok: true, estimatedBytes };
|
|
1815
|
+
} catch (err) {
|
|
1816
|
+
return { ok: false, error: err instanceof Error ? err.message : "Unknown error" };
|
|
1817
|
+
}
|
|
1818
|
+
}
|
|
1819
|
+
|
|
1820
|
+
// libs/core/src/interpreter/safe-globals.ts
|
|
1821
|
+
var MAX_JSON_TEXT_BYTES = 32 * 1024 * 1024;
|
|
1822
|
+
var MAX_JSON_INDENT = 10;
|
|
1823
|
+
function indentationSize(value, indent, limit, depth, path) {
|
|
1824
|
+
if (value === null || typeof value !== "object" || path.has(value)) return 0;
|
|
1825
|
+
const isArray = Array.isArray(value);
|
|
1826
|
+
const keys = isArray ? void 0 : Object.keys(value);
|
|
1827
|
+
const count = isArray ? value.length : keys.length;
|
|
1828
|
+
if (count === 0) return 0;
|
|
1829
|
+
let size = count * (1 + indent * (depth + 1) + (isArray ? 0 : 1)) + 1 + indent * depth;
|
|
1830
|
+
path.add(value);
|
|
1831
|
+
for (let index = 0; index < count && size <= limit; index++) {
|
|
1832
|
+
const item = isArray ? value[index] : value[keys[index]];
|
|
1833
|
+
size += indentationSize(item, indent, limit - size, depth + 1, path);
|
|
1834
|
+
}
|
|
1835
|
+
path.delete(value);
|
|
1836
|
+
return size;
|
|
1837
|
+
}
|
|
1838
|
+
function utf8Length(text) {
|
|
1839
|
+
let bytes = 0;
|
|
1840
|
+
for (let index = 0; index < text.length; index++) {
|
|
1841
|
+
const code = text.charCodeAt(index);
|
|
1842
|
+
if (code < 128) bytes += 1;
|
|
1843
|
+
else if (code < 2048) bytes += 2;
|
|
1844
|
+
else if (code >= 55296 && code <= 56319 && index + 1 < text.length) {
|
|
1845
|
+
const next = text.charCodeAt(index + 1);
|
|
1846
|
+
if (next >= 56320 && next <= 57343) {
|
|
1847
|
+
bytes += 4;
|
|
1848
|
+
index++;
|
|
1849
|
+
} else bytes += 3;
|
|
1850
|
+
} else bytes += 3;
|
|
1851
|
+
}
|
|
1852
|
+
return bytes;
|
|
1853
|
+
}
|
|
1854
|
+
function indentOf(space) {
|
|
1855
|
+
if (typeof space === "number") return Math.max(0, Math.min(MAX_JSON_INDENT, Math.floor(space) || 0));
|
|
1856
|
+
if (typeof space === "string") return utf8Length(space.slice(0, MAX_JSON_INDENT));
|
|
1857
|
+
return 0;
|
|
1858
|
+
}
|
|
1859
|
+
function parsedJsonCost(text) {
|
|
1860
|
+
let structural = 0;
|
|
1861
|
+
for (let index = 0; index < text.length; index++) {
|
|
1862
|
+
const code = text.charCodeAt(index);
|
|
1863
|
+
if (code === 44 || code === 58 || code === 91 || code === 123) structural++;
|
|
1864
|
+
}
|
|
1865
|
+
return text.length * 2 + structural * 16;
|
|
1866
|
+
}
|
|
1867
|
+
function frozenRecord(members) {
|
|
1868
|
+
const record = /* @__PURE__ */ Object.create(null);
|
|
1869
|
+
for (const key of Object.keys(members)) record[key] = members[key];
|
|
1870
|
+
return Object.freeze(record);
|
|
1871
|
+
}
|
|
1872
|
+
function frozenFunction(fn, members) {
|
|
1873
|
+
for (const key of Object.keys(members)) {
|
|
1874
|
+
Object.defineProperty(fn, key, { value: members[key], enumerable: true });
|
|
1875
|
+
}
|
|
1876
|
+
return Object.freeze(fn);
|
|
1877
|
+
}
|
|
1878
|
+
function tooLong() {
|
|
1879
|
+
throw new RangeError(`An array cannot be longer than ${MAX_ARRAY_LENGTH} items`);
|
|
1880
|
+
}
|
|
1881
|
+
function checkedLength(value) {
|
|
1882
|
+
const length = Number(value);
|
|
1883
|
+
if (!Number.isInteger(length) || length < 0) throw new RangeError("Invalid array length");
|
|
1884
|
+
if (length > MAX_ARRAY_LENGTH) tooLong();
|
|
1885
|
+
return length;
|
|
1886
|
+
}
|
|
1887
|
+
function dataKeys(value) {
|
|
1888
|
+
return Object.keys(value).filter((key) => !isBlockedKey(key));
|
|
1889
|
+
}
|
|
1890
|
+
var SafeMath = (() => {
|
|
1891
|
+
const members = {};
|
|
1892
|
+
for (const key of Object.getOwnPropertyNames(Math)) {
|
|
1893
|
+
members[key] = Math[key];
|
|
1894
|
+
}
|
|
1895
|
+
return frozenRecord(members);
|
|
1896
|
+
})();
|
|
1897
|
+
var SafeJSON = frozenRecord({
|
|
1898
|
+
parse(text, reviver) {
|
|
1899
|
+
if (reviver !== void 0) throw new TypeError("JSON.parse does not take a reviver in the sandbox");
|
|
1900
|
+
return JSON.parse(String(text));
|
|
1901
|
+
},
|
|
1902
|
+
stringify(value, replacer, space) {
|
|
1903
|
+
if (typeof replacer === "function") {
|
|
1904
|
+
throw new TypeError("JSON.stringify does not take a replacer function in the sandbox");
|
|
1905
|
+
}
|
|
1906
|
+
const size = checkSerializedSize(value, MAX_JSON_TEXT_BYTES);
|
|
1907
|
+
if (!size.ok) throw new RangeError(`JSON.stringify: the text would be too large (${size.error})`);
|
|
1908
|
+
const indent = indentOf(space);
|
|
1909
|
+
if (indent > 0) {
|
|
1910
|
+
const budget = MAX_JSON_TEXT_BYTES - size.estimatedBytes;
|
|
1911
|
+
if (indentationSize(value, indent, budget, 0, /* @__PURE__ */ new Set()) > budget) {
|
|
1912
|
+
throw new RangeError("JSON.stringify: the text would be too large with this indentation");
|
|
1913
|
+
}
|
|
1914
|
+
}
|
|
1915
|
+
return JSON.stringify(
|
|
1916
|
+
value,
|
|
1917
|
+
Array.isArray(replacer) ? replacer : void 0,
|
|
1918
|
+
space
|
|
1919
|
+
);
|
|
1920
|
+
}
|
|
1921
|
+
});
|
|
1922
|
+
chargedBeforeCall(SafeJSON["parse"], (args) => parsedJsonCost(String(args[0])));
|
|
1923
|
+
takesArraysAsData(SafeJSON["stringify"]);
|
|
1924
|
+
var SafeObject = frozenRecord({
|
|
1925
|
+
keys: (value) => dataKeys(value),
|
|
1926
|
+
values: (value) => dataKeys(value).map((key) => value[key]),
|
|
1927
|
+
entries: (value) => dataKeys(value).map((key) => [key, value[key]]),
|
|
1928
|
+
fromEntries(entries) {
|
|
1929
|
+
const result = {};
|
|
1930
|
+
let count = 0;
|
|
1931
|
+
for (const entry of entries) {
|
|
1932
|
+
if (++count > MAX_ARRAY_LENGTH) tooLong();
|
|
1933
|
+
if (entry === null || typeof entry !== "object") throw new TypeError("Each entry must be a [key, value] pair");
|
|
1934
|
+
assertArrayTextWithinLimit(entry[0]);
|
|
1935
|
+
const key = String(entry[0]);
|
|
1936
|
+
if (!isBlockedKey(key)) result[key] = entry[1];
|
|
1937
|
+
}
|
|
1938
|
+
return result;
|
|
1939
|
+
},
|
|
1940
|
+
assign(target, ...sources) {
|
|
1941
|
+
if (!isScriptData(target) || Object.isFrozen(target)) {
|
|
1942
|
+
throw new TypeError("Object.assign needs an object or array the script created as its target");
|
|
1943
|
+
}
|
|
1944
|
+
for (const source of sources) {
|
|
1945
|
+
if (source === null || source === void 0) continue;
|
|
1946
|
+
for (const key of dataKeys(source)) {
|
|
1947
|
+
target[key] = source[key];
|
|
1948
|
+
}
|
|
1949
|
+
}
|
|
1950
|
+
return target;
|
|
1951
|
+
},
|
|
1952
|
+
freeze: (value) => isScriptData(value) ? Object.freeze(value) : value,
|
|
1953
|
+
isFrozen: (value) => Object.isFrozen(value),
|
|
1954
|
+
is: (left, right) => Object.is(left, right),
|
|
1955
|
+
hasOwn(value, key) {
|
|
1956
|
+
assertArrayTextWithinLimit(key);
|
|
1957
|
+
const name = String(key);
|
|
1958
|
+
return !isBlockedKey(name) && Object.prototype.hasOwnProperty.call(Object(value), name);
|
|
1959
|
+
}
|
|
1960
|
+
});
|
|
1961
|
+
for (const key of Object.keys(SafeObject)) takesArraysAsData(SafeObject[key]);
|
|
1962
|
+
function makeArray(args) {
|
|
1963
|
+
if (args.length === 1 && typeof args[0] === "number") return new Array(checkedLength(args[0]));
|
|
1964
|
+
return [...args];
|
|
1965
|
+
}
|
|
1966
|
+
var SafeArray = frozenFunction((...args) => makeArray(args), {
|
|
1967
|
+
isArray: (value) => Array.isArray(value),
|
|
1968
|
+
of: (...items) => [...items],
|
|
1969
|
+
from(source, map) {
|
|
1970
|
+
if (map !== void 0) throw new TypeError("Array.from does not take a function in the sandbox");
|
|
1971
|
+
if (source === null || source === void 0) throw new TypeError("Array.from needs a value");
|
|
1972
|
+
const result = [];
|
|
1973
|
+
if (typeof source[Symbol.iterator] === "function") {
|
|
1974
|
+
for (const item of source) {
|
|
1975
|
+
if (result.length >= MAX_ARRAY_LENGTH) tooLong();
|
|
1976
|
+
result.push(item);
|
|
1977
|
+
}
|
|
1978
|
+
return result;
|
|
1979
|
+
}
|
|
1980
|
+
const length = checkedLength(source.length ?? 0);
|
|
1981
|
+
for (let index = 0; index < length; index++) result.push(source[index]);
|
|
1982
|
+
return result;
|
|
1983
|
+
}
|
|
1984
|
+
});
|
|
1985
|
+
takesArraysAsData(SafeArray);
|
|
1986
|
+
for (const key of Object.keys(SafeArray)) {
|
|
1987
|
+
takesArraysAsData(SafeArray[key]);
|
|
1988
|
+
}
|
|
1989
|
+
function toStringValue(value) {
|
|
1990
|
+
return typeof value === "function" ? "function () { [sandboxed code] }" : String(value);
|
|
1991
|
+
}
|
|
1992
|
+
var SafeString = frozenFunction((...args) => args.length === 0 ? "" : toStringValue(args[0]), {
|
|
1993
|
+
fromCharCode: (...codes) => String.fromCharCode(...codes),
|
|
1994
|
+
fromCodePoint: (...codes) => String.fromCodePoint(...codes)
|
|
1995
|
+
});
|
|
1996
|
+
var SafeNumber = frozenFunction((...args) => args.length === 0 ? 0 : Number(args[0]), {
|
|
1997
|
+
isFinite: (value) => Number.isFinite(value),
|
|
1998
|
+
isInteger: (value) => Number.isInteger(value),
|
|
1999
|
+
isNaN: (value) => Number.isNaN(value),
|
|
2000
|
+
isSafeInteger: (value) => Number.isSafeInteger(value),
|
|
2001
|
+
parseFloat: (value) => Number.parseFloat(String(value)),
|
|
2002
|
+
parseInt: (value, radix) => Number.parseInt(String(value), radix),
|
|
2003
|
+
EPSILON: Number.EPSILON,
|
|
2004
|
+
MAX_SAFE_INTEGER: Number.MAX_SAFE_INTEGER,
|
|
2005
|
+
MIN_SAFE_INTEGER: Number.MIN_SAFE_INTEGER,
|
|
2006
|
+
MAX_VALUE: Number.MAX_VALUE,
|
|
2007
|
+
MIN_VALUE: Number.MIN_VALUE,
|
|
2008
|
+
POSITIVE_INFINITY: Number.POSITIVE_INFINITY,
|
|
2009
|
+
NEGATIVE_INFINITY: Number.NEGATIVE_INFINITY,
|
|
2010
|
+
NaN: Number.NaN
|
|
2011
|
+
});
|
|
2012
|
+
function makeDate(args) {
|
|
2013
|
+
if (args.length === 0) return /* @__PURE__ */ new Date();
|
|
2014
|
+
if (args.length === 1) return new Date(args[0]);
|
|
2015
|
+
return new Date(...args);
|
|
2016
|
+
}
|
|
2017
|
+
var SafeDate = frozenFunction(() => (/* @__PURE__ */ new Date()).toString(), {
|
|
2018
|
+
now: () => Date.now(),
|
|
2019
|
+
parse: (text) => Date.parse(String(text)),
|
|
2020
|
+
UTC: (...parts) => Date.UTC(...parts)
|
|
2021
|
+
});
|
|
2022
|
+
var ERROR_TYPES = ["Error", "TypeError", "RangeError", "SyntaxError", "ReferenceError", "EvalError", "URIError"];
|
|
2023
|
+
function errorType(name) {
|
|
2024
|
+
const make = (args) => createScriptError(name, args.length === 0 || args[0] === void 0 ? "" : toStringValue(args[0]));
|
|
2025
|
+
return {
|
|
2026
|
+
facade: frozenFunction((...args) => make(args), {}),
|
|
2027
|
+
make,
|
|
2028
|
+
// Every error is an `Error`; the other types are told apart by their name.
|
|
2029
|
+
isInstance: (value) => isScriptError(value) && (name === "Error" || value.name === name)
|
|
2030
|
+
};
|
|
2031
|
+
}
|
|
2032
|
+
var SAFE_ERRORS = ERROR_TYPES.map((name) => [name, errorType(name)]);
|
|
2033
|
+
var SAFE_GLOBALS = Object.freeze({
|
|
2034
|
+
Math: SafeMath,
|
|
2035
|
+
JSON: SafeJSON,
|
|
2036
|
+
Object: SafeObject,
|
|
2037
|
+
Array: SafeArray,
|
|
2038
|
+
String: SafeString,
|
|
2039
|
+
Number: SafeNumber,
|
|
2040
|
+
Date: SafeDate,
|
|
2041
|
+
...Object.fromEntries(SAFE_ERRORS.map(([name, type]) => [name, type.facade])),
|
|
2042
|
+
...Object.fromEntries(SAFE_ERRORS.map(([name, type]) => [`__safe_${name}`, type.facade])),
|
|
2043
|
+
NaN: Number.NaN,
|
|
2044
|
+
Infinity: Number.POSITIVE_INFINITY,
|
|
2045
|
+
undefined: void 0,
|
|
2046
|
+
isNaN: Object.freeze((value) => Number.isNaN(Number(value))),
|
|
2047
|
+
isFinite: Object.freeze((value) => Number.isFinite(Number(value))),
|
|
2048
|
+
parseFloat: Object.freeze((value) => Number.parseFloat(String(value))),
|
|
2049
|
+
parseInt: Object.freeze(
|
|
2050
|
+
(value, radix) => Number.parseInt(String(value), radix)
|
|
2051
|
+
),
|
|
2052
|
+
encodeURI: Object.freeze((value) => encodeURI(String(value))),
|
|
2053
|
+
encodeURIComponent: Object.freeze((value) => encodeURIComponent(String(value))),
|
|
2054
|
+
decodeURI: Object.freeze((value) => decodeURI(String(value))),
|
|
2055
|
+
decodeURIComponent: Object.freeze((value) => decodeURIComponent(String(value)))
|
|
2056
|
+
});
|
|
2057
|
+
convertsArguments(SafeString, 1);
|
|
2058
|
+
convertsArguments(SafeNumber, 1);
|
|
2059
|
+
convertsArguments(SafeDate, 0);
|
|
2060
|
+
for (const [name, count] of [
|
|
2061
|
+
["isFinite", 0],
|
|
2062
|
+
["isInteger", 0],
|
|
2063
|
+
["isNaN", 0],
|
|
2064
|
+
["isSafeInteger", 0],
|
|
2065
|
+
["parseFloat", 1],
|
|
2066
|
+
["parseInt", 2]
|
|
2067
|
+
]) {
|
|
2068
|
+
convertsArguments(SafeNumber[name], count);
|
|
2069
|
+
}
|
|
2070
|
+
convertsArguments(SafeDate["now"], 0);
|
|
2071
|
+
convertsArguments(SafeDate["parse"], 1);
|
|
2072
|
+
for (const [name, count] of [
|
|
2073
|
+
["isNaN", 1],
|
|
2074
|
+
["isFinite", 1],
|
|
2075
|
+
["parseFloat", 1],
|
|
2076
|
+
["parseInt", 2],
|
|
2077
|
+
["encodeURI", 1],
|
|
2078
|
+
["encodeURIComponent", 1],
|
|
2079
|
+
["decodeURI", 1],
|
|
2080
|
+
["decodeURIComponent", 1]
|
|
2081
|
+
]) {
|
|
2082
|
+
convertsArguments(SAFE_GLOBALS[name], count);
|
|
2083
|
+
}
|
|
2084
|
+
for (const [, type] of SAFE_ERRORS) convertsArguments(type.facade, 1);
|
|
2085
|
+
var MATH_PARAMETERS = {
|
|
2086
|
+
abs: 1,
|
|
2087
|
+
acos: 1,
|
|
2088
|
+
acosh: 1,
|
|
2089
|
+
asin: 1,
|
|
2090
|
+
asinh: 1,
|
|
2091
|
+
atan: 1,
|
|
2092
|
+
atanh: 1,
|
|
2093
|
+
atan2: 2,
|
|
2094
|
+
cbrt: 1,
|
|
2095
|
+
ceil: 1,
|
|
2096
|
+
clz32: 1,
|
|
2097
|
+
cos: 1,
|
|
2098
|
+
cosh: 1,
|
|
2099
|
+
exp: 1,
|
|
2100
|
+
expm1: 1,
|
|
2101
|
+
floor: 1,
|
|
2102
|
+
fround: 1,
|
|
2103
|
+
imul: 2,
|
|
2104
|
+
log: 1,
|
|
2105
|
+
log1p: 1,
|
|
2106
|
+
log10: 1,
|
|
2107
|
+
log2: 1,
|
|
2108
|
+
pow: 2,
|
|
2109
|
+
random: 0,
|
|
2110
|
+
round: 1,
|
|
2111
|
+
sign: 1,
|
|
2112
|
+
sin: 1,
|
|
2113
|
+
sinh: 1,
|
|
2114
|
+
sqrt: 1,
|
|
2115
|
+
tan: 1,
|
|
2116
|
+
tanh: 1,
|
|
2117
|
+
trunc: 1
|
|
2118
|
+
};
|
|
2119
|
+
for (const name of Object.keys(MATH_PARAMETERS)) {
|
|
2120
|
+
const fn = SafeMath[name];
|
|
2121
|
+
if (typeof fn === "function") convertsArguments(fn, MATH_PARAMETERS[name]);
|
|
2122
|
+
}
|
|
2123
|
+
function createSafeGlobals() {
|
|
2124
|
+
return {
|
|
2125
|
+
globals: { ...SAFE_GLOBALS },
|
|
2126
|
+
constructors: new Map([
|
|
2127
|
+
[SafeDate, makeDate],
|
|
2128
|
+
[SafeArray, makeArray],
|
|
2129
|
+
...SAFE_ERRORS.map(([, type]) => [type.facade, type.make])
|
|
2130
|
+
]),
|
|
2131
|
+
instanceChecks: new Map([
|
|
2132
|
+
[SafeDate, (value) => value instanceof Date],
|
|
2133
|
+
[SafeArray, (value) => Array.isArray(value)],
|
|
2134
|
+
[SafeObject, (value) => typeof value === "object" && value !== null || typeof value === "function"],
|
|
2135
|
+
...SAFE_ERRORS.map(([, type]) => [type.facade, type.isInstance])
|
|
2136
|
+
])
|
|
2137
|
+
};
|
|
2138
|
+
}
|
|
2139
|
+
|
|
2140
|
+
// libs/core/src/memory-tracker.ts
|
|
2141
|
+
var MemoryLimitError = class _MemoryLimitError extends Error {
|
|
2142
|
+
constructor(message, usedBytes, limitBytes) {
|
|
2143
|
+
super(message);
|
|
2144
|
+
this.usedBytes = usedBytes;
|
|
2145
|
+
this.limitBytes = limitBytes;
|
|
2146
|
+
this.name = "MemoryLimitError";
|
|
2147
|
+
if (Error.captureStackTrace) {
|
|
2148
|
+
Error.captureStackTrace(this, _MemoryLimitError);
|
|
2149
|
+
}
|
|
2150
|
+
}
|
|
2151
|
+
/** Error code for identification */
|
|
2152
|
+
code = "MEMORY_LIMIT_EXCEEDED";
|
|
2153
|
+
};
|
|
2154
|
+
function estimateStringSize2(str) {
|
|
2155
|
+
return str.length * 2 + 40;
|
|
2156
|
+
}
|
|
2157
|
+
function estimateArraySize(length, elementEstimate = 8) {
|
|
2158
|
+
return 32 + length * elementEstimate;
|
|
2159
|
+
}
|
|
2160
|
+
function estimateObjectSize(propertyCount) {
|
|
2161
|
+
return 56 + propertyCount * 32;
|
|
2162
|
+
}
|
|
2163
|
+
var MemoryTracker = class {
|
|
2164
|
+
trackedBytes = 0;
|
|
2165
|
+
peakTrackedBytes = 0;
|
|
2166
|
+
allocationCount = 0;
|
|
2167
|
+
config;
|
|
2168
|
+
constructor(config = {}) {
|
|
2169
|
+
this.config = {
|
|
2170
|
+
memoryLimit: config.memoryLimit ?? 0,
|
|
2171
|
+
trackStrings: config.trackStrings ?? true,
|
|
2172
|
+
trackArrays: config.trackArrays ?? true,
|
|
2173
|
+
trackObjects: config.trackObjects ?? true
|
|
2174
|
+
};
|
|
2175
|
+
}
|
|
2176
|
+
/**
|
|
2177
|
+
* Start tracking (resets all counters)
|
|
2178
|
+
*/
|
|
2179
|
+
start() {
|
|
2180
|
+
this.trackedBytes = 0;
|
|
2181
|
+
this.peakTrackedBytes = 0;
|
|
2182
|
+
this.allocationCount = 0;
|
|
2183
|
+
}
|
|
2184
|
+
/**
|
|
2185
|
+
* Track an allocation
|
|
2186
|
+
*
|
|
2187
|
+
* @param bytes Number of bytes allocated
|
|
2188
|
+
* @throws {MemoryLimitError} If memory limit is exceeded
|
|
2189
|
+
*/
|
|
2190
|
+
track(bytes) {
|
|
2191
|
+
if (typeof bytes !== "number" || Number.isNaN(bytes)) {
|
|
2192
|
+
if (this.config.memoryLimit > 0) {
|
|
2193
|
+
throw new MemoryLimitError(
|
|
2194
|
+
"Memory limit exceeded: allocation size is not a number",
|
|
2195
|
+
this.trackedBytes,
|
|
2196
|
+
this.config.memoryLimit
|
|
2197
|
+
);
|
|
2198
|
+
}
|
|
2199
|
+
return;
|
|
2200
|
+
}
|
|
2201
|
+
if (bytes <= 0) return;
|
|
2202
|
+
this.trackedBytes += bytes;
|
|
2203
|
+
this.allocationCount++;
|
|
2204
|
+
if (this.trackedBytes > this.peakTrackedBytes) {
|
|
2205
|
+
this.peakTrackedBytes = this.trackedBytes;
|
|
2206
|
+
}
|
|
2207
|
+
if (this.config.memoryLimit > 0 && this.trackedBytes > this.config.memoryLimit) {
|
|
2208
|
+
throw new MemoryLimitError(
|
|
2209
|
+
`Memory limit exceeded: ${this.formatBytes(this.trackedBytes)} used > ${this.formatBytes(
|
|
2210
|
+
this.config.memoryLimit
|
|
2211
|
+
)} limit`,
|
|
2212
|
+
this.trackedBytes,
|
|
2213
|
+
this.config.memoryLimit
|
|
2214
|
+
);
|
|
2215
|
+
}
|
|
2216
|
+
}
|
|
2217
|
+
/**
|
|
2218
|
+
* Track a string allocation
|
|
2219
|
+
*
|
|
2220
|
+
* @param str String that was allocated
|
|
2221
|
+
* @throws {MemoryLimitError} If memory limit is exceeded
|
|
2222
|
+
*/
|
|
2223
|
+
trackString(str) {
|
|
2224
|
+
if (!this.config.trackStrings) return;
|
|
2225
|
+
this.track(estimateStringSize2(str));
|
|
2226
|
+
}
|
|
2227
|
+
/**
|
|
2228
|
+
* Track an array allocation
|
|
2229
|
+
*
|
|
2230
|
+
* @param length Array length
|
|
2231
|
+
* @param elementEstimate Optional per-element size estimate
|
|
2232
|
+
* @throws {MemoryLimitError} If memory limit is exceeded
|
|
2233
|
+
*/
|
|
2234
|
+
trackArray(length, elementEstimate) {
|
|
2235
|
+
if (!this.config.trackArrays) return;
|
|
2236
|
+
this.track(estimateArraySize(length, elementEstimate));
|
|
2237
|
+
}
|
|
2238
|
+
/**
|
|
2239
|
+
* Track an object allocation
|
|
2240
|
+
*
|
|
2241
|
+
* @param propertyCount Number of properties
|
|
2242
|
+
* @throws {MemoryLimitError} If memory limit is exceeded
|
|
2243
|
+
*/
|
|
2244
|
+
trackObject(propertyCount) {
|
|
2245
|
+
if (!this.config.trackObjects) return;
|
|
2246
|
+
this.track(estimateObjectSize(propertyCount));
|
|
2247
|
+
}
|
|
2248
|
+
/**
|
|
2249
|
+
* Release tracked memory (for GC simulation)
|
|
2250
|
+
*
|
|
2251
|
+
* @param bytes Number of bytes to release
|
|
2252
|
+
*/
|
|
2253
|
+
release(bytes) {
|
|
2254
|
+
if (typeof bytes !== "number" || !(bytes > 0)) return;
|
|
2255
|
+
this.trackedBytes = Math.max(0, this.trackedBytes - bytes);
|
|
2256
|
+
}
|
|
2257
|
+
/**
|
|
2258
|
+
* Get current memory usage snapshot
|
|
2259
|
+
*
|
|
2260
|
+
* @returns Snapshot of memory usage
|
|
2261
|
+
*/
|
|
2262
|
+
getSnapshot() {
|
|
2263
|
+
return {
|
|
2264
|
+
trackedBytes: this.trackedBytes,
|
|
2265
|
+
peakTrackedBytes: this.peakTrackedBytes,
|
|
2266
|
+
allocationCount: this.allocationCount
|
|
2267
|
+
};
|
|
2268
|
+
}
|
|
2269
|
+
/**
|
|
2270
|
+
* Get configured memory limit
|
|
2271
|
+
*
|
|
2272
|
+
* @returns Memory limit in bytes (0 = unlimited)
|
|
2273
|
+
*/
|
|
2274
|
+
getLimit() {
|
|
2275
|
+
return this.config.memoryLimit;
|
|
2276
|
+
}
|
|
2277
|
+
/**
|
|
2278
|
+
* Check if tracking is enabled
|
|
2279
|
+
*
|
|
2280
|
+
* @returns True if any tracking is enabled
|
|
2281
|
+
*/
|
|
2282
|
+
isEnabled() {
|
|
2283
|
+
return this.config.trackStrings || this.config.trackArrays || this.config.trackObjects;
|
|
2284
|
+
}
|
|
2285
|
+
/**
|
|
2286
|
+
* Format bytes as human-readable string
|
|
2287
|
+
*
|
|
2288
|
+
* @param bytes Number of bytes
|
|
2289
|
+
* @returns Formatted string (e.g., "10.5MB")
|
|
2290
|
+
*/
|
|
2291
|
+
formatBytes(bytes) {
|
|
2292
|
+
if (bytes >= 1024 * 1024 * 1024) return `${(bytes / 1024 / 1024 / 1024).toFixed(2)}GB`;
|
|
2293
|
+
if (bytes >= 1024 * 1024) return `${(bytes / 1024 / 1024).toFixed(2)}MB`;
|
|
2294
|
+
if (bytes >= 1024) return `${(bytes / 1024).toFixed(2)}KB`;
|
|
2295
|
+
return `${bytes}B`;
|
|
2296
|
+
}
|
|
2297
|
+
};
|
|
2298
|
+
|
|
2299
|
+
// libs/core/src/sidecar/reference-config.ts
|
|
2300
|
+
var REFERENCE_CONFIGS = {
|
|
2301
|
+
/**
|
|
2302
|
+
* STRICT: Maximum security for untrusted code
|
|
2303
|
+
*
|
|
2304
|
+
* - Very small limits to prevent any memory-based attacks
|
|
2305
|
+
* - No composite handles (references cannot be concatenated)
|
|
2306
|
+
* - Aggressive extraction threshold
|
|
2307
|
+
*/
|
|
2308
|
+
STRICT: {
|
|
2309
|
+
maxTotalSize: 16 * 1024 * 1024,
|
|
2310
|
+
// 16MB total
|
|
2311
|
+
maxReferenceSize: 4 * 1024 * 1024,
|
|
2312
|
+
// 4MB per reference
|
|
2313
|
+
extractionThreshold: 64 * 1024,
|
|
2314
|
+
// 64KB extraction threshold
|
|
2315
|
+
maxResolvedSize: 8 * 1024 * 1024,
|
|
2316
|
+
// 8MB max resolved
|
|
2317
|
+
allowComposites: false,
|
|
2318
|
+
// No concatenation of references
|
|
2319
|
+
maxReferenceCount: 50,
|
|
2320
|
+
// Max 50 references
|
|
2321
|
+
maxResolutionDepth: 5
|
|
2322
|
+
// Shallow resolution
|
|
2323
|
+
},
|
|
2324
|
+
/**
|
|
2325
|
+
* SECURE: High security with more headroom
|
|
2326
|
+
*
|
|
2327
|
+
* - Moderate limits for trusted AI code
|
|
2328
|
+
* - No composite handles by default
|
|
2329
|
+
* - Standard extraction threshold
|
|
2330
|
+
*/
|
|
2331
|
+
SECURE: {
|
|
2332
|
+
maxTotalSize: 64 * 1024 * 1024,
|
|
2333
|
+
// 64MB total
|
|
2334
|
+
maxReferenceSize: 16 * 1024 * 1024,
|
|
2335
|
+
// 16MB per reference
|
|
2336
|
+
extractionThreshold: 256 * 1024,
|
|
2337
|
+
// 256KB extraction threshold
|
|
2338
|
+
maxResolvedSize: 32 * 1024 * 1024,
|
|
2339
|
+
// 32MB max resolved
|
|
2340
|
+
allowComposites: false,
|
|
2341
|
+
// No concatenation of references
|
|
2342
|
+
maxReferenceCount: 100,
|
|
2343
|
+
// Max 100 references
|
|
2344
|
+
maxResolutionDepth: 10
|
|
2345
|
+
// Moderate resolution depth
|
|
2346
|
+
},
|
|
2347
|
+
/**
|
|
2348
|
+
* STANDARD: Balanced security and functionality
|
|
2349
|
+
*
|
|
2350
|
+
* - Standard limits for internal tools
|
|
2351
|
+
* - Composite handles allowed
|
|
2352
|
+
* - Larger extraction threshold
|
|
2353
|
+
*/
|
|
2354
|
+
STANDARD: {
|
|
2355
|
+
maxTotalSize: 256 * 1024 * 1024,
|
|
2356
|
+
// 256MB total
|
|
2357
|
+
maxReferenceSize: 64 * 1024 * 1024,
|
|
2358
|
+
// 64MB per reference
|
|
2359
|
+
extractionThreshold: 1024 * 1024,
|
|
2360
|
+
// 1MB extraction threshold
|
|
2361
|
+
maxResolvedSize: 128 * 1024 * 1024,
|
|
2362
|
+
// 128MB max resolved
|
|
2363
|
+
allowComposites: true,
|
|
2364
|
+
// Allow concatenation
|
|
2365
|
+
maxReferenceCount: 500,
|
|
2366
|
+
// Max 500 references
|
|
2367
|
+
maxResolutionDepth: 20
|
|
2368
|
+
// Deep resolution
|
|
2369
|
+
},
|
|
2370
|
+
/**
|
|
2371
|
+
* PERMISSIVE: Minimal restrictions
|
|
2372
|
+
*
|
|
2373
|
+
* - Large limits for development/debugging
|
|
2374
|
+
* - All features enabled
|
|
2375
|
+
* - High extraction threshold
|
|
2376
|
+
*/
|
|
2377
|
+
PERMISSIVE: {
|
|
2378
|
+
maxTotalSize: 1024 * 1024 * 1024,
|
|
2379
|
+
// 1GB total
|
|
2380
|
+
maxReferenceSize: 256 * 1024 * 1024,
|
|
2381
|
+
// 256MB per reference
|
|
2382
|
+
extractionThreshold: 4 * 1024 * 1024,
|
|
2383
|
+
// 4MB extraction threshold
|
|
2384
|
+
maxResolvedSize: 512 * 1024 * 1024,
|
|
2385
|
+
// 512MB max resolved
|
|
2386
|
+
allowComposites: true,
|
|
2387
|
+
// Allow concatenation
|
|
2388
|
+
maxReferenceCount: 1e3,
|
|
2389
|
+
// Max 1000 references
|
|
2390
|
+
maxResolutionDepth: 50
|
|
2391
|
+
// Very deep resolution
|
|
2392
|
+
}
|
|
2393
|
+
};
|
|
2394
|
+
var 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;
|
|
2395
|
+
function isReferenceId(value) {
|
|
2396
|
+
return typeof value === "string" && REF_ID_PATTERN.test(value);
|
|
2397
|
+
}
|
|
2398
|
+
|
|
2399
|
+
// libs/core/src/sidecar/reference-resolver.ts
|
|
2400
|
+
var ReflectGet2 = Reflect.get;
|
|
2401
|
+
var NumberIsFinite2 = Number.isFinite;
|
|
2402
|
+
var MathFloor2 = Math.floor;
|
|
2403
|
+
var MAX_TRAVERSAL_LENGTH = 1e6;
|
|
2404
|
+
function untrustedLength(value) {
|
|
2405
|
+
const rawLen = ReflectGet2(value, "length");
|
|
2406
|
+
if (typeof rawLen !== "number" || !NumberIsFinite2(rawLen) || rawLen < 0) {
|
|
2407
|
+
return 0;
|
|
2408
|
+
}
|
|
2409
|
+
const len = MathFloor2(rawLen);
|
|
2410
|
+
if (len > MAX_TRAVERSAL_LENGTH) {
|
|
2411
|
+
throw new ResolutionLimitError(
|
|
2412
|
+
`Array length ${len} exceeds maximum traversal limit (${MAX_TRAVERSAL_LENGTH})`,
|
|
2413
|
+
"MAX_TRAVERSAL_LENGTH",
|
|
2414
|
+
MAX_TRAVERSAL_LENGTH,
|
|
2415
|
+
len
|
|
2416
|
+
);
|
|
2417
|
+
}
|
|
2418
|
+
return len;
|
|
2419
|
+
}
|
|
2420
|
+
function untrustedAt(value, index) {
|
|
2421
|
+
try {
|
|
2422
|
+
return ReflectGet2(value, index);
|
|
2423
|
+
} catch {
|
|
2424
|
+
return void 0;
|
|
2425
|
+
}
|
|
2426
|
+
}
|
|
2427
|
+
var ResolutionLimitError = class _ResolutionLimitError extends Error {
|
|
2428
|
+
constructor(message, code, limit, actual) {
|
|
2429
|
+
super(message);
|
|
2430
|
+
this.code = code;
|
|
2431
|
+
this.limit = limit;
|
|
2432
|
+
this.actual = actual;
|
|
2433
|
+
this.name = "ResolutionLimitError";
|
|
2434
|
+
Object.setPrototypeOf(this, _ResolutionLimitError.prototype);
|
|
2435
|
+
}
|
|
2436
|
+
};
|
|
2437
|
+
function isCompositeHandle(value) {
|
|
2438
|
+
const obj = value;
|
|
2439
|
+
return typeof value === "object" && value !== null && obj["__type"] === "composite" && Array.isArray(obj["__parts"]);
|
|
2440
|
+
}
|
|
2441
|
+
var ReferenceResolver = class {
|
|
2442
|
+
constructor(sidecar, config) {
|
|
2443
|
+
this.sidecar = sidecar;
|
|
2444
|
+
this.config = config;
|
|
2445
|
+
}
|
|
2446
|
+
/**
|
|
2447
|
+
* Predict the expanded size of a value WITHOUT allocating memory
|
|
2448
|
+
*
|
|
2449
|
+
* This calculates the total size if all references were resolved,
|
|
2450
|
+
* enabling fail-fast before any memory allocation occurs.
|
|
2451
|
+
*
|
|
2452
|
+
* @param value - The value to analyze
|
|
2453
|
+
* @param depth - Current recursion depth (internal)
|
|
2454
|
+
* @returns Estimated size in bytes
|
|
2455
|
+
* @throws ResolutionLimitError if depth limit exceeded
|
|
2456
|
+
*/
|
|
2457
|
+
predictExpandedSize(value, depth = 0) {
|
|
2458
|
+
if (depth > this.config.maxResolutionDepth) {
|
|
2459
|
+
throw new ResolutionLimitError(
|
|
2460
|
+
`Maximum resolution depth exceeded (${this.config.maxResolutionDepth})`,
|
|
2461
|
+
"MAX_RESOLUTION_DEPTH",
|
|
2462
|
+
this.config.maxResolutionDepth,
|
|
2463
|
+
depth
|
|
2464
|
+
);
|
|
2465
|
+
}
|
|
2466
|
+
if (isReferenceId(value)) {
|
|
2467
|
+
const size = this.sidecar.getSize(value);
|
|
2468
|
+
if (size === void 0) {
|
|
2469
|
+
return value.length;
|
|
2470
|
+
}
|
|
2471
|
+
return size;
|
|
2472
|
+
}
|
|
2473
|
+
if (isCompositeHandle(value)) {
|
|
2474
|
+
const parts = value.__parts;
|
|
2475
|
+
const len = untrustedLength(parts);
|
|
2476
|
+
let sum = 0;
|
|
2477
|
+
for (let i = 0; i < len; i++) {
|
|
2478
|
+
sum += this.predictExpandedSize(untrustedAt(parts, i), depth + 1);
|
|
2479
|
+
}
|
|
2480
|
+
return sum;
|
|
2481
|
+
}
|
|
2482
|
+
if (typeof value === "string") {
|
|
2483
|
+
return Buffer.byteLength(value, "utf-8");
|
|
2484
|
+
}
|
|
2485
|
+
if (Array.isArray(value)) {
|
|
2486
|
+
const len = untrustedLength(value);
|
|
2487
|
+
let sum = 0;
|
|
2488
|
+
for (let i = 0; i < len; i++) {
|
|
2489
|
+
sum += this.predictExpandedSize(untrustedAt(value, i), depth + 1);
|
|
2490
|
+
}
|
|
2491
|
+
return sum;
|
|
2492
|
+
}
|
|
2493
|
+
if (value !== null && typeof value === "object") {
|
|
2494
|
+
return Object.values(value).reduce((sum, val) => {
|
|
2495
|
+
return sum + this.predictExpandedSize(val, depth + 1);
|
|
2496
|
+
}, 0);
|
|
2497
|
+
}
|
|
2498
|
+
if (typeof value === "number") return 8;
|
|
2499
|
+
if (typeof value === "boolean") return 1;
|
|
2500
|
+
if (value === null || value === void 0) return 0;
|
|
2501
|
+
return 0;
|
|
2502
|
+
}
|
|
2503
|
+
/**
|
|
2504
|
+
* Check if resolution would exceed size limits
|
|
2505
|
+
*
|
|
2506
|
+
* @param value - The value to check
|
|
2507
|
+
* @returns true if resolution would exceed maxResolvedSize
|
|
2508
|
+
*/
|
|
2509
|
+
wouldExceedLimit(value) {
|
|
2510
|
+
try {
|
|
2511
|
+
const size = this.predictExpandedSize(value);
|
|
2512
|
+
return size > this.config.maxResolvedSize;
|
|
2513
|
+
} catch {
|
|
2514
|
+
return true;
|
|
2515
|
+
}
|
|
2516
|
+
}
|
|
2517
|
+
/**
|
|
2518
|
+
* Resolve all reference IDs in a value tree
|
|
2519
|
+
*
|
|
2520
|
+
* Recursively walks the value and replaces reference IDs with
|
|
2521
|
+
* their actual data from the sidecar.
|
|
2522
|
+
*
|
|
2523
|
+
* @param value - The value to resolve
|
|
2524
|
+
* @param depth - Current recursion depth (internal)
|
|
2525
|
+
* @returns The resolved value with references replaced
|
|
2526
|
+
* @throws ResolutionLimitError if limits exceeded
|
|
2527
|
+
* @throws ReferenceNotFoundError if a reference doesn't exist
|
|
2528
|
+
*/
|
|
2529
|
+
resolve(value, depth = 0) {
|
|
2530
|
+
if (depth > this.config.maxResolutionDepth) {
|
|
2531
|
+
throw new ResolutionLimitError(
|
|
2532
|
+
`Maximum resolution depth exceeded during resolution (${this.config.maxResolutionDepth})`,
|
|
2533
|
+
"MAX_RESOLUTION_DEPTH",
|
|
2534
|
+
this.config.maxResolutionDepth,
|
|
2535
|
+
depth
|
|
2536
|
+
);
|
|
2537
|
+
}
|
|
2538
|
+
if (isReferenceId(value)) {
|
|
2539
|
+
const data = this.sidecar.retrieveString(value);
|
|
2540
|
+
if (data === void 0) {
|
|
2541
|
+
throw new Error(`Unknown reference: ${value}`);
|
|
2542
|
+
}
|
|
2543
|
+
return data;
|
|
2544
|
+
}
|
|
2545
|
+
if (isCompositeHandle(value)) {
|
|
2546
|
+
if (!this.config.allowComposites) {
|
|
2547
|
+
throw new Error(
|
|
2548
|
+
"Cannot concatenate reference IDs. Pass references directly to callTool arguments. Composite handles are disabled in the current security configuration."
|
|
2549
|
+
);
|
|
2550
|
+
}
|
|
2551
|
+
return this.resolveComposite(value, depth);
|
|
2552
|
+
}
|
|
2553
|
+
if (typeof value === "string") {
|
|
2554
|
+
return value;
|
|
2555
|
+
}
|
|
2556
|
+
if (Array.isArray(value)) {
|
|
2557
|
+
const len = untrustedLength(value);
|
|
2558
|
+
const out = [];
|
|
2559
|
+
for (let i = 0; i < len; i++) {
|
|
2560
|
+
out[i] = this.resolve(untrustedAt(value, i), depth + 1);
|
|
2561
|
+
}
|
|
2562
|
+
return out;
|
|
2563
|
+
}
|
|
2564
|
+
if (value !== null && typeof value === "object") {
|
|
2565
|
+
const resolved = /* @__PURE__ */ Object.create(null);
|
|
2566
|
+
for (const [key, val] of Object.entries(value)) {
|
|
2567
|
+
resolved[key] = this.resolve(val, depth + 1);
|
|
2568
|
+
}
|
|
2569
|
+
return resolved;
|
|
2570
|
+
}
|
|
2571
|
+
return value;
|
|
2572
|
+
}
|
|
2573
|
+
/**
|
|
2574
|
+
* Resolve a composite handle by concatenating its parts
|
|
2575
|
+
*/
|
|
2576
|
+
resolveComposite(handle, depth) {
|
|
2577
|
+
const out = [];
|
|
2578
|
+
const source = handle.__parts;
|
|
2579
|
+
const len = untrustedLength(source);
|
|
2580
|
+
for (let i = 0; i < len; i++) {
|
|
2581
|
+
const resolved = this.resolve(untrustedAt(source, i), depth + 1);
|
|
2582
|
+
if (typeof resolved !== "string") {
|
|
2583
|
+
throw new Error(`Composite part resolved to non-string: ${typeof resolved}`);
|
|
2584
|
+
}
|
|
2585
|
+
out.push(resolved);
|
|
2586
|
+
}
|
|
2587
|
+
return out.join("");
|
|
2588
|
+
}
|
|
2589
|
+
/**
|
|
2590
|
+
* Check if a value contains any reference IDs
|
|
2591
|
+
*
|
|
2592
|
+
* @param value - The value to check
|
|
2593
|
+
* @param depth - Current recursion depth (internal)
|
|
2594
|
+
* @returns true if the value or any nested value is a reference
|
|
2595
|
+
*/
|
|
2596
|
+
containsReferences(value, depth = 0) {
|
|
2597
|
+
if (depth > this.config.maxResolutionDepth) {
|
|
2598
|
+
return false;
|
|
2599
|
+
}
|
|
2600
|
+
if (isReferenceId(value) || isCompositeHandle(value)) {
|
|
2601
|
+
return true;
|
|
2602
|
+
}
|
|
2603
|
+
if (Array.isArray(value)) {
|
|
2604
|
+
const len = untrustedLength(value);
|
|
2605
|
+
for (let i = 0; i < len; i++) {
|
|
2606
|
+
if (this.containsReferences(untrustedAt(value, i), depth + 1)) {
|
|
2607
|
+
return true;
|
|
2608
|
+
}
|
|
2609
|
+
}
|
|
2610
|
+
return false;
|
|
2611
|
+
}
|
|
2612
|
+
if (value !== null && typeof value === "object") {
|
|
2613
|
+
return Object.values(value).some((val) => this.containsReferences(val, depth + 1));
|
|
2614
|
+
}
|
|
2615
|
+
return false;
|
|
2616
|
+
}
|
|
2617
|
+
/**
|
|
2618
|
+
* Create a composite handle from multiple reference parts
|
|
2619
|
+
*
|
|
2620
|
+
* Used by __safe_concat__ when allowComposites is true.
|
|
2621
|
+
*
|
|
2622
|
+
* @param parts - Reference IDs or strings to combine
|
|
2623
|
+
* @returns A composite handle or the concatenated string
|
|
2624
|
+
* @throws Error if composites not allowed or limits exceeded
|
|
2625
|
+
*/
|
|
2626
|
+
createComposite(parts) {
|
|
2627
|
+
const hasReferences = parts.some((p) => isReferenceId(p));
|
|
2628
|
+
if (!hasReferences) {
|
|
2629
|
+
return parts.join("");
|
|
2630
|
+
}
|
|
2631
|
+
if (!this.config.allowComposites) {
|
|
2632
|
+
throw new Error(
|
|
2633
|
+
"Cannot concatenate reference IDs. Pass references directly to callTool arguments. Composite handles are disabled in the current security configuration."
|
|
2634
|
+
);
|
|
2635
|
+
}
|
|
2636
|
+
const estimatedSize = parts.reduce((sum, part) => {
|
|
2637
|
+
if (isReferenceId(part)) {
|
|
2638
|
+
return sum + (this.sidecar.getSize(part) ?? part.length);
|
|
2639
|
+
}
|
|
2640
|
+
return sum + Buffer.byteLength(part, "utf-8");
|
|
2641
|
+
}, 0);
|
|
2642
|
+
if (estimatedSize > this.config.maxResolvedSize) {
|
|
2643
|
+
throw new ResolutionLimitError(
|
|
2644
|
+
`Composite would exceed maximum resolved size: ${estimatedSize} > ${this.config.maxResolvedSize}`,
|
|
2645
|
+
"MAX_RESOLVED_SIZE",
|
|
2646
|
+
this.config.maxResolvedSize,
|
|
2647
|
+
estimatedSize
|
|
2648
|
+
);
|
|
2649
|
+
}
|
|
2650
|
+
return {
|
|
2651
|
+
__type: "composite",
|
|
2652
|
+
__operation: "concat",
|
|
2653
|
+
__parts: parts,
|
|
2654
|
+
__estimatedSize: estimatedSize
|
|
2655
|
+
};
|
|
2656
|
+
}
|
|
2657
|
+
};
|
|
2658
|
+
|
|
2659
|
+
// libs/core/src/stack-trace.ts
|
|
596
2660
|
var SENSITIVE_STACK_PATTERNS = [
|
|
597
2661
|
// Unix file system paths
|
|
598
2662
|
/\/Users\/[^/]+\/[^\s):]*/gi,
|
|
@@ -743,44 +2807,519 @@ function sanitizeStackTrace(stack, sanitize = true) {
|
|
|
743
2807
|
return bounded.split("\n").map((line) => FRAME_LINE.test(line) ? REDACTED_FRAME : redactLine(line)).join("\n");
|
|
744
2808
|
}
|
|
745
2809
|
|
|
2810
|
+
// libs/core/src/tool-bridge.ts
|
|
2811
|
+
var TOOL_BRIDGE_PROTOCOL_VERSION = 1;
|
|
2812
|
+
function utf8ByteLength(value) {
|
|
2813
|
+
return Buffer.byteLength(value, "utf8");
|
|
2814
|
+
}
|
|
2815
|
+
function jsonReplacer(_key, value) {
|
|
2816
|
+
if (typeof value === "bigint") return value.toString();
|
|
2817
|
+
if (typeof value === "number" && !Number.isFinite(value)) return null;
|
|
2818
|
+
return value;
|
|
2819
|
+
}
|
|
2820
|
+
function safeJsonStringify(value) {
|
|
2821
|
+
return JSON.stringify(value, jsonReplacer);
|
|
2822
|
+
}
|
|
2823
|
+
function truncateForErrorMessage(value, maxChars) {
|
|
2824
|
+
if (value.length <= maxChars) return value;
|
|
2825
|
+
return `${value.slice(0, maxChars)}\u2026`;
|
|
2826
|
+
}
|
|
2827
|
+
function toErrorPayload(error, fallbackName, fallbackMessage, code) {
|
|
2828
|
+
const safe = {
|
|
2829
|
+
name: fallbackName,
|
|
2830
|
+
message: fallbackMessage,
|
|
2831
|
+
code
|
|
2832
|
+
};
|
|
2833
|
+
if (error && typeof error === "object") {
|
|
2834
|
+
const maybeName = error.name;
|
|
2835
|
+
const maybeMessage = error.message;
|
|
2836
|
+
const maybeCode = error.code;
|
|
2837
|
+
if (typeof maybeName === "string" && maybeName) safe.name = maybeName;
|
|
2838
|
+
if (typeof maybeMessage === "string" && maybeMessage) safe.message = maybeMessage;
|
|
2839
|
+
if (typeof maybeCode === "string" && maybeCode) safe.code = maybeCode;
|
|
2840
|
+
} else if (typeof error === "string" && error) {
|
|
2841
|
+
safe.message = error;
|
|
2842
|
+
}
|
|
2843
|
+
safe.message = truncateForErrorMessage(String(safe.message || fallbackMessage), 4096);
|
|
2844
|
+
safe.name = truncateForErrorMessage(String(safe.name || fallbackName), 128);
|
|
2845
|
+
return safe;
|
|
2846
|
+
}
|
|
2847
|
+
function serializeResponse(response, maxPayloadBytes) {
|
|
2848
|
+
let json;
|
|
2849
|
+
try {
|
|
2850
|
+
json = safeJsonStringify(response);
|
|
2851
|
+
} catch {
|
|
2852
|
+
json = JSON.stringify({
|
|
2853
|
+
v: TOOL_BRIDGE_PROTOCOL_VERSION,
|
|
2854
|
+
ok: false,
|
|
2855
|
+
error: {
|
|
2856
|
+
name: "ToolBridgeError",
|
|
2857
|
+
message: "Tool bridge failed to serialize response",
|
|
2858
|
+
code: "TOOL_BRIDGE_SERIALIZE_FAILED"
|
|
2859
|
+
}
|
|
2860
|
+
});
|
|
2861
|
+
}
|
|
2862
|
+
if (utf8ByteLength(json) <= maxPayloadBytes) return json;
|
|
2863
|
+
const minimal = {
|
|
2864
|
+
v: TOOL_BRIDGE_PROTOCOL_VERSION,
|
|
2865
|
+
ok: false,
|
|
2866
|
+
error: {
|
|
2867
|
+
name: "ToolBridgeError",
|
|
2868
|
+
message: "Tool bridge payload exceeded maximum size",
|
|
2869
|
+
code: "TOOL_BRIDGE_PAYLOAD_TOO_LARGE"
|
|
2870
|
+
}
|
|
2871
|
+
};
|
|
2872
|
+
return JSON.stringify(minimal);
|
|
2873
|
+
}
|
|
2874
|
+
function parseToolBridgeRequest(requestJson) {
|
|
2875
|
+
let parsed;
|
|
2876
|
+
try {
|
|
2877
|
+
parsed = JSON.parse(requestJson);
|
|
2878
|
+
} catch {
|
|
2879
|
+
return { ok: false, error: "Tool request must be valid JSON" };
|
|
2880
|
+
}
|
|
2881
|
+
if (!parsed || typeof parsed !== "object" || Array.isArray(parsed)) {
|
|
2882
|
+
return { ok: false, error: "Tool request must be a JSON object" };
|
|
2883
|
+
}
|
|
2884
|
+
const v = parsed.v;
|
|
2885
|
+
const tool = parsed.tool;
|
|
2886
|
+
const args = parsed.args;
|
|
2887
|
+
if (v !== TOOL_BRIDGE_PROTOCOL_VERSION) {
|
|
2888
|
+
return { ok: false, error: "Unsupported tool bridge protocol version" };
|
|
2889
|
+
}
|
|
2890
|
+
if (typeof tool !== "string" || !tool) {
|
|
2891
|
+
return { ok: false, error: "Tool name must be a non-empty string" };
|
|
2892
|
+
}
|
|
2893
|
+
if (!args || typeof args !== "object" || Array.isArray(args)) {
|
|
2894
|
+
return { ok: false, error: "Tool arguments must be a JSON object" };
|
|
2895
|
+
}
|
|
2896
|
+
return { ok: true, request: { v: TOOL_BRIDGE_PROTOCOL_VERSION, tool, args } };
|
|
2897
|
+
}
|
|
2898
|
+
function encodeToolBridgeRequest(tool, args) {
|
|
2899
|
+
return safeJsonStringify({ v: TOOL_BRIDGE_PROTOCOL_VERSION, tool, args });
|
|
2900
|
+
}
|
|
2901
|
+
function encodeToolBridgeFailure(name, message, code, maxPayloadBytes) {
|
|
2902
|
+
return serializeResponse(
|
|
2903
|
+
{ v: TOOL_BRIDGE_PROTOCOL_VERSION, ok: false, error: { name, message, code } },
|
|
2904
|
+
maxPayloadBytes
|
|
2905
|
+
);
|
|
2906
|
+
}
|
|
2907
|
+
function toolCallLimitMessage(maxToolCalls) {
|
|
2908
|
+
return `Maximum tool call limit exceeded (${maxToolCalls}). This limit prevents runaway script execution.`;
|
|
2909
|
+
}
|
|
2910
|
+
function createRelayedToolBridge(executionContext, options, relay) {
|
|
2911
|
+
const { config, stats } = executionContext;
|
|
2912
|
+
const maxPayloadBytes = config.toolBridge?.maxPayloadBytes ?? 5 * 1024 * 1024;
|
|
2913
|
+
return async (requestJson) => {
|
|
2914
|
+
try {
|
|
2915
|
+
if (typeof requestJson !== "string") {
|
|
2916
|
+
return encodeToolBridgeFailure(
|
|
2917
|
+
"ToolBridgeError",
|
|
2918
|
+
"Tool request must be a string",
|
|
2919
|
+
"TOOL_BRIDGE_BAD_REQUEST",
|
|
2920
|
+
maxPayloadBytes
|
|
2921
|
+
);
|
|
2922
|
+
}
|
|
2923
|
+
if (utf8ByteLength(requestJson) > maxPayloadBytes) {
|
|
2924
|
+
return encodeToolBridgeFailure(
|
|
2925
|
+
"ToolBridgeError",
|
|
2926
|
+
`Tool request exceeds maximum size (${maxPayloadBytes} bytes)`,
|
|
2927
|
+
"TOOL_BRIDGE_REQUEST_TOO_LARGE",
|
|
2928
|
+
maxPayloadBytes
|
|
2929
|
+
);
|
|
2930
|
+
}
|
|
2931
|
+
if (executionContext.aborted) {
|
|
2932
|
+
return encodeToolBridgeFailure("AbortError", "Execution aborted", "EXECUTION_ABORTED", maxPayloadBytes);
|
|
2933
|
+
}
|
|
2934
|
+
if (options.updateStats) {
|
|
2935
|
+
stats.toolCallCount++;
|
|
2936
|
+
}
|
|
2937
|
+
if (!options.limitChecked && stats.toolCallCount > config.maxToolCalls) {
|
|
2938
|
+
return encodeToolBridgeFailure(
|
|
2939
|
+
"ToolLimitError",
|
|
2940
|
+
toolCallLimitMessage(config.maxToolCalls),
|
|
2941
|
+
"MAX_TOOL_CALLS_EXCEEDED",
|
|
2942
|
+
maxPayloadBytes
|
|
2943
|
+
);
|
|
2944
|
+
}
|
|
2945
|
+
const responseJson = await relay(requestJson);
|
|
2946
|
+
if (typeof responseJson !== "string" || utf8ByteLength(responseJson) > maxPayloadBytes) {
|
|
2947
|
+
return encodeToolBridgeFailure(
|
|
2948
|
+
"ToolBridgeError",
|
|
2949
|
+
`Tool response exceeds maximum size (${maxPayloadBytes} bytes)`,
|
|
2950
|
+
"TOOL_BRIDGE_RESPONSE_TOO_LARGE",
|
|
2951
|
+
maxPayloadBytes
|
|
2952
|
+
);
|
|
2953
|
+
}
|
|
2954
|
+
return responseJson;
|
|
2955
|
+
} catch (error) {
|
|
2956
|
+
const safeError = toErrorPayload(error, "ToolBridgeError", "Tool bridge failure", "TOOL_BRIDGE_FAILURE");
|
|
2957
|
+
return serializeResponse({ v: TOOL_BRIDGE_PROTOCOL_VERSION, ok: false, error: safeError }, maxPayloadBytes);
|
|
2958
|
+
}
|
|
2959
|
+
};
|
|
2960
|
+
}
|
|
2961
|
+
function createHostToolBridge(executionContext, options) {
|
|
2962
|
+
if (typeof executionContext.hostToolBridge === "function") {
|
|
2963
|
+
return createRelayedToolBridge(executionContext, options, executionContext.hostToolBridge);
|
|
2964
|
+
}
|
|
2965
|
+
const { config, stats, toolHandler, sidecar, referenceConfig } = executionContext;
|
|
2966
|
+
const maxPayloadBytes = config.toolBridge?.maxPayloadBytes ?? 5 * 1024 * 1024;
|
|
2967
|
+
const resolver = sidecar && referenceConfig ? new ReferenceResolver(sidecar, referenceConfig) : void 0;
|
|
2968
|
+
return async (requestJson) => {
|
|
2969
|
+
try {
|
|
2970
|
+
if (typeof requestJson !== "string") {
|
|
2971
|
+
return serializeResponse(
|
|
2972
|
+
{
|
|
2973
|
+
v: TOOL_BRIDGE_PROTOCOL_VERSION,
|
|
2974
|
+
ok: false,
|
|
2975
|
+
error: {
|
|
2976
|
+
name: "ToolBridgeError",
|
|
2977
|
+
message: "Tool request must be a string",
|
|
2978
|
+
code: "TOOL_BRIDGE_BAD_REQUEST"
|
|
2979
|
+
}
|
|
2980
|
+
},
|
|
2981
|
+
maxPayloadBytes
|
|
2982
|
+
);
|
|
2983
|
+
}
|
|
2984
|
+
if (utf8ByteLength(requestJson) > maxPayloadBytes) {
|
|
2985
|
+
return serializeResponse(
|
|
2986
|
+
{
|
|
2987
|
+
v: TOOL_BRIDGE_PROTOCOL_VERSION,
|
|
2988
|
+
ok: false,
|
|
2989
|
+
error: {
|
|
2990
|
+
name: "ToolBridgeError",
|
|
2991
|
+
message: `Tool request exceeds maximum size (${maxPayloadBytes} bytes)`,
|
|
2992
|
+
code: "TOOL_BRIDGE_REQUEST_TOO_LARGE"
|
|
2993
|
+
}
|
|
2994
|
+
},
|
|
2995
|
+
maxPayloadBytes
|
|
2996
|
+
);
|
|
2997
|
+
}
|
|
2998
|
+
if (executionContext.aborted) {
|
|
2999
|
+
return serializeResponse(
|
|
3000
|
+
{
|
|
3001
|
+
v: TOOL_BRIDGE_PROTOCOL_VERSION,
|
|
3002
|
+
ok: false,
|
|
3003
|
+
error: { name: "AbortError", message: "Execution aborted", code: "EXECUTION_ABORTED" }
|
|
3004
|
+
},
|
|
3005
|
+
maxPayloadBytes
|
|
3006
|
+
);
|
|
3007
|
+
}
|
|
3008
|
+
if (options.updateStats) {
|
|
3009
|
+
stats.toolCallCount++;
|
|
3010
|
+
}
|
|
3011
|
+
if (!options.limitChecked && stats.toolCallCount > config.maxToolCalls) {
|
|
3012
|
+
return serializeResponse(
|
|
3013
|
+
{
|
|
3014
|
+
v: TOOL_BRIDGE_PROTOCOL_VERSION,
|
|
3015
|
+
ok: false,
|
|
3016
|
+
error: {
|
|
3017
|
+
name: "ToolLimitError",
|
|
3018
|
+
message: toolCallLimitMessage(config.maxToolCalls),
|
|
3019
|
+
code: "MAX_TOOL_CALLS_EXCEEDED"
|
|
3020
|
+
}
|
|
3021
|
+
},
|
|
3022
|
+
maxPayloadBytes
|
|
3023
|
+
);
|
|
3024
|
+
}
|
|
3025
|
+
if (!toolHandler) {
|
|
3026
|
+
return serializeResponse(
|
|
3027
|
+
{
|
|
3028
|
+
v: TOOL_BRIDGE_PROTOCOL_VERSION,
|
|
3029
|
+
ok: false,
|
|
3030
|
+
error: {
|
|
3031
|
+
name: "ToolBridgeError",
|
|
3032
|
+
message: "No tool handler configured. Cannot execute tool calls.",
|
|
3033
|
+
code: "NO_TOOL_HANDLER"
|
|
3034
|
+
}
|
|
3035
|
+
},
|
|
3036
|
+
maxPayloadBytes
|
|
3037
|
+
);
|
|
3038
|
+
}
|
|
3039
|
+
const parsed = parseToolBridgeRequest(requestJson);
|
|
3040
|
+
if (!parsed.ok) {
|
|
3041
|
+
return serializeResponse(
|
|
3042
|
+
{
|
|
3043
|
+
v: TOOL_BRIDGE_PROTOCOL_VERSION,
|
|
3044
|
+
ok: false,
|
|
3045
|
+
error: { name: "ToolBridgeError", message: parsed.error, code: "TOOL_BRIDGE_BAD_REQUEST" }
|
|
3046
|
+
},
|
|
3047
|
+
maxPayloadBytes
|
|
3048
|
+
);
|
|
3049
|
+
}
|
|
3050
|
+
const { tool, args } = parsed.request;
|
|
3051
|
+
const sanitizedArgs = sanitizeValue(args, {
|
|
3052
|
+
maxDepth: config.maxSanitizeDepth,
|
|
3053
|
+
maxProperties: config.maxSanitizeProperties,
|
|
3054
|
+
allowDates: false,
|
|
3055
|
+
allowErrors: false
|
|
3056
|
+
});
|
|
3057
|
+
if (!sanitizedArgs || typeof sanitizedArgs !== "object" || Array.isArray(sanitizedArgs)) {
|
|
3058
|
+
return serializeResponse(
|
|
3059
|
+
{
|
|
3060
|
+
v: TOOL_BRIDGE_PROTOCOL_VERSION,
|
|
3061
|
+
ok: false,
|
|
3062
|
+
error: { name: "TypeError", message: "Tool arguments must be an object", code: "INVALID_TOOL_ARGS" }
|
|
3063
|
+
},
|
|
3064
|
+
maxPayloadBytes
|
|
3065
|
+
);
|
|
3066
|
+
}
|
|
3067
|
+
let resolvedArgs = sanitizedArgs;
|
|
3068
|
+
if (resolver && resolver.containsReferences(resolvedArgs)) {
|
|
3069
|
+
if (resolver.wouldExceedLimit(resolvedArgs)) {
|
|
3070
|
+
return serializeResponse(
|
|
3071
|
+
{
|
|
3072
|
+
v: TOOL_BRIDGE_PROTOCOL_VERSION,
|
|
3073
|
+
ok: false,
|
|
3074
|
+
error: {
|
|
3075
|
+
name: "ToolBridgeError",
|
|
3076
|
+
message: "Arguments would exceed maximum resolved size when references are expanded. Reduce the amount of data passed to the tool.",
|
|
3077
|
+
code: "REFERENCE_RESOLUTION_LIMIT"
|
|
3078
|
+
}
|
|
3079
|
+
},
|
|
3080
|
+
maxPayloadBytes
|
|
3081
|
+
);
|
|
3082
|
+
}
|
|
3083
|
+
try {
|
|
3084
|
+
resolvedArgs = resolver.resolve(resolvedArgs);
|
|
3085
|
+
} catch (error) {
|
|
3086
|
+
if (error instanceof ResolutionLimitError) {
|
|
3087
|
+
return serializeResponse(
|
|
3088
|
+
{
|
|
3089
|
+
v: TOOL_BRIDGE_PROTOCOL_VERSION,
|
|
3090
|
+
ok: false,
|
|
3091
|
+
error: {
|
|
3092
|
+
name: "ToolBridgeError",
|
|
3093
|
+
message: `Failed to resolve references in tool arguments: ${error.message}`,
|
|
3094
|
+
code: "REFERENCE_RESOLUTION_FAILED"
|
|
3095
|
+
}
|
|
3096
|
+
},
|
|
3097
|
+
maxPayloadBytes
|
|
3098
|
+
);
|
|
3099
|
+
}
|
|
3100
|
+
const safeError = toErrorPayload(
|
|
3101
|
+
error,
|
|
3102
|
+
"ToolBridgeError",
|
|
3103
|
+
"Reference resolution failed",
|
|
3104
|
+
"REFERENCE_RESOLUTION_FAILED"
|
|
3105
|
+
);
|
|
3106
|
+
return serializeResponse(
|
|
3107
|
+
{
|
|
3108
|
+
v: TOOL_BRIDGE_PROTOCOL_VERSION,
|
|
3109
|
+
ok: false,
|
|
3110
|
+
error: safeError
|
|
3111
|
+
},
|
|
3112
|
+
maxPayloadBytes
|
|
3113
|
+
);
|
|
3114
|
+
}
|
|
3115
|
+
}
|
|
3116
|
+
let result;
|
|
3117
|
+
try {
|
|
3118
|
+
result = await toolHandler(tool, resolvedArgs);
|
|
3119
|
+
} catch (error) {
|
|
3120
|
+
const safeError = toErrorPayload(error, "ToolError", `Tool call failed: ${tool}`, "TOOL_CALL_FAILED");
|
|
3121
|
+
return serializeResponse(
|
|
3122
|
+
{
|
|
3123
|
+
v: TOOL_BRIDGE_PROTOCOL_VERSION,
|
|
3124
|
+
ok: false,
|
|
3125
|
+
error: { ...safeError, toolError: true }
|
|
3126
|
+
},
|
|
3127
|
+
maxPayloadBytes
|
|
3128
|
+
);
|
|
3129
|
+
}
|
|
3130
|
+
let sanitizedResult;
|
|
3131
|
+
try {
|
|
3132
|
+
sanitizedResult = sanitizeValue(result, {
|
|
3133
|
+
maxDepth: config.maxSanitizeDepth,
|
|
3134
|
+
maxProperties: config.maxSanitizeProperties,
|
|
3135
|
+
allowDates: false,
|
|
3136
|
+
allowErrors: true
|
|
3137
|
+
});
|
|
3138
|
+
} catch (error) {
|
|
3139
|
+
const safeError = toErrorPayload(
|
|
3140
|
+
error,
|
|
3141
|
+
"ToolBridgeError",
|
|
3142
|
+
"Tool returned an unsupported value",
|
|
3143
|
+
"TOOL_RESULT_NOT_SAFE"
|
|
3144
|
+
);
|
|
3145
|
+
return serializeResponse(
|
|
3146
|
+
{
|
|
3147
|
+
v: TOOL_BRIDGE_PROTOCOL_VERSION,
|
|
3148
|
+
ok: false,
|
|
3149
|
+
error: { ...safeError, toolError: true }
|
|
3150
|
+
},
|
|
3151
|
+
maxPayloadBytes
|
|
3152
|
+
);
|
|
3153
|
+
}
|
|
3154
|
+
if (sidecar && referenceConfig && typeof sanitizedResult === "string") {
|
|
3155
|
+
const size = utf8ByteLength(sanitizedResult);
|
|
3156
|
+
if (size >= referenceConfig.extractionThreshold) {
|
|
3157
|
+
try {
|
|
3158
|
+
const refId = sidecar.store(sanitizedResult, "tool-result", { origin: tool });
|
|
3159
|
+
sanitizedResult = refId;
|
|
3160
|
+
} catch {
|
|
3161
|
+
}
|
|
3162
|
+
}
|
|
3163
|
+
}
|
|
3164
|
+
const okResponse = sanitizedResult === void 0 ? { v: TOOL_BRIDGE_PROTOCOL_VERSION, ok: true } : { v: TOOL_BRIDGE_PROTOCOL_VERSION, ok: true, value: sanitizedResult };
|
|
3165
|
+
let okJson;
|
|
3166
|
+
try {
|
|
3167
|
+
okJson = safeJsonStringify(okResponse);
|
|
3168
|
+
} catch (error) {
|
|
3169
|
+
const safeError = toErrorPayload(
|
|
3170
|
+
error,
|
|
3171
|
+
"ToolBridgeError",
|
|
3172
|
+
"Tool result must be JSON-serializable",
|
|
3173
|
+
"TOOL_RESULT_NOT_JSON"
|
|
3174
|
+
);
|
|
3175
|
+
return serializeResponse(
|
|
3176
|
+
{
|
|
3177
|
+
v: TOOL_BRIDGE_PROTOCOL_VERSION,
|
|
3178
|
+
ok: false,
|
|
3179
|
+
error: { ...safeError, toolError: true }
|
|
3180
|
+
},
|
|
3181
|
+
maxPayloadBytes
|
|
3182
|
+
);
|
|
3183
|
+
}
|
|
3184
|
+
if (utf8ByteLength(okJson) > maxPayloadBytes) {
|
|
3185
|
+
return serializeResponse(
|
|
3186
|
+
{
|
|
3187
|
+
v: TOOL_BRIDGE_PROTOCOL_VERSION,
|
|
3188
|
+
ok: false,
|
|
3189
|
+
error: {
|
|
3190
|
+
name: "ToolBridgeError",
|
|
3191
|
+
message: `Tool response exceeds maximum size (${maxPayloadBytes} bytes)`,
|
|
3192
|
+
code: "TOOL_BRIDGE_RESPONSE_TOO_LARGE",
|
|
3193
|
+
toolError: true
|
|
3194
|
+
}
|
|
3195
|
+
},
|
|
3196
|
+
maxPayloadBytes
|
|
3197
|
+
);
|
|
3198
|
+
}
|
|
3199
|
+
return okJson;
|
|
3200
|
+
} catch (error) {
|
|
3201
|
+
const safeError = toErrorPayload(error, "ToolBridgeError", "Tool bridge failure", "TOOL_BRIDGE_FAILURE");
|
|
3202
|
+
return serializeResponse(
|
|
3203
|
+
{
|
|
3204
|
+
v: TOOL_BRIDGE_PROTOCOL_VERSION,
|
|
3205
|
+
ok: false,
|
|
3206
|
+
error: safeError
|
|
3207
|
+
},
|
|
3208
|
+
maxPayloadBytes
|
|
3209
|
+
);
|
|
3210
|
+
}
|
|
3211
|
+
};
|
|
3212
|
+
}
|
|
3213
|
+
|
|
746
3214
|
// libs/core/src/adapters/interpreter-adapter.ts
|
|
747
|
-
var SAFE_GLOBALS = Object.freeze({ Math, JSON });
|
|
748
3215
|
var DEFAULT_MAX_STEPS = 5e6;
|
|
749
3216
|
var DEFAULT_MAX_CALL_DEPTH = 256;
|
|
3217
|
+
var DEFAULT_MAX_ALLOCATION_BYTES = 64 * 1024 * 1024;
|
|
3218
|
+
var MAX_PARALLEL_ITEMS = 100;
|
|
3219
|
+
var MAX_SERIALIZED_RESULT_BYTES = 50 * 1024 * 1024;
|
|
3220
|
+
var DEFAULT_MAX_CONSOLE_CALLS = 100;
|
|
3221
|
+
var DEFAULT_MAX_CONSOLE_OUTPUT_BYTES = 64 * 1024;
|
|
3222
|
+
function sandboxError(message, name = "Error", code) {
|
|
3223
|
+
const error = new Error(message);
|
|
3224
|
+
error.name = name;
|
|
3225
|
+
if (code !== void 0) error.code = code;
|
|
3226
|
+
return error;
|
|
3227
|
+
}
|
|
3228
|
+
function frozenRecord2(members) {
|
|
3229
|
+
const record = /* @__PURE__ */ Object.create(null);
|
|
3230
|
+
for (const key of Object.keys(members)) record[key] = members[key];
|
|
3231
|
+
return Object.freeze(record);
|
|
3232
|
+
}
|
|
3233
|
+
function frozenDataCopy(name, value) {
|
|
3234
|
+
if (value === null || typeof value !== "object" && typeof value !== "function") return value;
|
|
3235
|
+
let json;
|
|
3236
|
+
try {
|
|
3237
|
+
json = typeof value === "function" ? void 0 : JSON.stringify(value);
|
|
3238
|
+
} catch {
|
|
3239
|
+
json = void 0;
|
|
3240
|
+
}
|
|
3241
|
+
if (json === void 0) {
|
|
3242
|
+
throw sandboxError(
|
|
3243
|
+
`Custom global "${name}" cannot be given to the interpreter: it supports JSON data only (no functions)`,
|
|
3244
|
+
"TypeError"
|
|
3245
|
+
);
|
|
3246
|
+
}
|
|
3247
|
+
const freeze = (item) => {
|
|
3248
|
+
if (item !== null && typeof item === "object") {
|
|
3249
|
+
for (const key of Object.keys(item)) freeze(item[key]);
|
|
3250
|
+
Object.freeze(item);
|
|
3251
|
+
}
|
|
3252
|
+
return item;
|
|
3253
|
+
};
|
|
3254
|
+
return freeze(JSON.parse(json));
|
|
3255
|
+
}
|
|
3256
|
+
function consoleText(value) {
|
|
3257
|
+
if (typeof value === "string") return value;
|
|
3258
|
+
if (typeof value === "function") return "[Function]";
|
|
3259
|
+
if (value === null || typeof value !== "object") return String(value);
|
|
3260
|
+
if (isScriptError(value)) {
|
|
3261
|
+
const error = value;
|
|
3262
|
+
return error.message ? `${error.name}: ${error.message}` : error.name;
|
|
3263
|
+
}
|
|
3264
|
+
try {
|
|
3265
|
+
return JSON.stringify(value) ?? "[object]";
|
|
3266
|
+
} catch {
|
|
3267
|
+
return "[object]";
|
|
3268
|
+
}
|
|
3269
|
+
}
|
|
750
3270
|
var InterpreterAdapter = class {
|
|
751
3271
|
constructor(options = {}) {
|
|
752
3272
|
this.options = options;
|
|
753
3273
|
}
|
|
754
3274
|
async execute(code, context) {
|
|
755
3275
|
const startTime = Date.now();
|
|
756
|
-
let toolCallCount = 0;
|
|
757
3276
|
const sanitizeStacks = context.config.sanitizeStackTraces === true;
|
|
758
|
-
const
|
|
759
|
-
|
|
760
|
-
|
|
761
|
-
|
|
762
|
-
|
|
763
|
-
|
|
764
|
-
if (typeof toolHandler !== "function") {
|
|
765
|
-
throw new Error("No toolHandler configured for the sandbox");
|
|
766
|
-
}
|
|
767
|
-
return toolHandler(name, args);
|
|
768
|
-
};
|
|
769
|
-
const globals = { ...SAFE_GLOBALS, __safe_callTool };
|
|
3277
|
+
const stats = context.stats ?? (context.stats = {
|
|
3278
|
+
duration: 0,
|
|
3279
|
+
toolCallCount: 0,
|
|
3280
|
+
iterationCount: 0,
|
|
3281
|
+
startTime
|
|
3282
|
+
});
|
|
770
3283
|
let program;
|
|
771
3284
|
try {
|
|
772
3285
|
program = acorn.parse(code, { ecmaVersion: "latest", sourceType: "script" });
|
|
773
3286
|
} catch (error) {
|
|
774
|
-
return this.fail(error, startTime, toolCallCount, 0, sanitizeStacks, "SyntaxError");
|
|
3287
|
+
return this.fail(error, startTime, stats.toolCallCount, 0, sanitizeStacks, "SyntaxError");
|
|
3288
|
+
}
|
|
3289
|
+
const memoryLimit = context.config.memoryLimit;
|
|
3290
|
+
const adapterLimit = this.options.maxAllocationBytes ?? DEFAULT_MAX_ALLOCATION_BYTES;
|
|
3291
|
+
const allocationLimit = typeof memoryLimit === "number" && memoryLimit > 0 ? Math.min(memoryLimit, adapterLimit) : adapterLimit;
|
|
3292
|
+
const tracker = new MemoryTracker({ memoryLimit: Number.isFinite(allocationLimit) ? allocationLimit : 0 });
|
|
3293
|
+
const charge = (bytes) => tracker.track(bytes);
|
|
3294
|
+
let interpreter;
|
|
3295
|
+
try {
|
|
3296
|
+
const safe = createSafeGlobals();
|
|
3297
|
+
const callbacks = {
|
|
3298
|
+
call: () => {
|
|
3299
|
+
throw sandboxError("The interpreter is not running");
|
|
3300
|
+
}
|
|
3301
|
+
};
|
|
3302
|
+
const runtime = this.runtimeGlobals(context, charge, callbacks);
|
|
3303
|
+
for (const name of Object.keys(runtime)) {
|
|
3304
|
+
if (!Object.prototype.hasOwnProperty.call(safe.globals, name)) safe.globals[name] = runtime[name];
|
|
3305
|
+
}
|
|
3306
|
+
interpreter = new Interpreter({
|
|
3307
|
+
globals: safe.globals,
|
|
3308
|
+
constructors: safe.constructors,
|
|
3309
|
+
instanceChecks: safe.instanceChecks,
|
|
3310
|
+
maxSteps: this.options.maxSteps ?? DEFAULT_MAX_STEPS,
|
|
3311
|
+
maxCallDepth: this.options.maxCallDepth ?? DEFAULT_MAX_CALL_DEPTH,
|
|
3312
|
+
maxPendingCalls: this.options.maxPendingCalls,
|
|
3313
|
+
signal: context.abortController.signal,
|
|
3314
|
+
charge
|
|
3315
|
+
});
|
|
3316
|
+
const running = interpreter;
|
|
3317
|
+
callbacks.call = (fn, args) => running.call(fn, args);
|
|
3318
|
+
} catch (error) {
|
|
3319
|
+
return this.fail(error, startTime, stats.toolCallCount, 0, sanitizeStacks);
|
|
775
3320
|
}
|
|
776
3321
|
const timeout = context.config.timeout;
|
|
777
3322
|
const timer = timeout && timeout > 0 ? setTimeout(() => context.abortController.abort(), timeout) : void 0;
|
|
778
|
-
const interpreter = new Interpreter({
|
|
779
|
-
globals,
|
|
780
|
-
maxSteps: this.options.maxSteps ?? DEFAULT_MAX_STEPS,
|
|
781
|
-
maxCallDepth: this.options.maxCallDepth ?? DEFAULT_MAX_CALL_DEPTH,
|
|
782
|
-
signal: context.abortController.signal
|
|
783
|
-
});
|
|
784
3323
|
let timeoutHandle;
|
|
785
3324
|
const TIMED_OUT = /* @__PURE__ */ Symbol("timeout");
|
|
786
3325
|
const deadline = timeout && timeout > 0 ? new Promise((resolve) => {
|
|
@@ -794,40 +3333,293 @@ var InterpreterAdapter = class {
|
|
|
794
3333
|
return this.fail(
|
|
795
3334
|
new Error(`Execution timed out after ${timeout}ms`),
|
|
796
3335
|
startTime,
|
|
797
|
-
toolCallCount,
|
|
3336
|
+
stats.toolCallCount,
|
|
798
3337
|
interpreter.stepCount,
|
|
799
3338
|
sanitizeStacks,
|
|
800
3339
|
"TimeoutError",
|
|
801
3340
|
"EXECUTION_TIMEOUT"
|
|
802
3341
|
);
|
|
803
3342
|
}
|
|
804
|
-
return
|
|
805
|
-
success: true,
|
|
806
|
-
value: outcome,
|
|
807
|
-
stats: this.stats(startTime, toolCallCount, interpreter.stepCount)
|
|
808
|
-
};
|
|
3343
|
+
return this.succeed(outcome, context, startTime, stats.toolCallCount, interpreter.stepCount);
|
|
809
3344
|
} catch (error) {
|
|
810
3345
|
const code2 = error instanceof StepLimitError ? "STEP_LIMIT_EXCEEDED" : void 0;
|
|
811
|
-
return this.fail(
|
|
3346
|
+
return this.fail(
|
|
3347
|
+
error,
|
|
3348
|
+
startTime,
|
|
3349
|
+
stats.toolCallCount,
|
|
3350
|
+
interpreter.stepCount,
|
|
3351
|
+
sanitizeStacks,
|
|
3352
|
+
void 0,
|
|
3353
|
+
code2
|
|
3354
|
+
);
|
|
812
3355
|
} finally {
|
|
813
3356
|
if (timer) clearTimeout(timer);
|
|
814
3357
|
if (timeoutHandle) clearTimeout(timeoutHandle);
|
|
3358
|
+
interpreter.stop();
|
|
815
3359
|
}
|
|
816
3360
|
}
|
|
817
3361
|
dispose() {
|
|
818
3362
|
}
|
|
3363
|
+
/**
|
|
3364
|
+
* What transformed AgentScript refers to beyond the standard globals: the helpers the
|
|
3365
|
+
* transformer emits, and the console, tool namespaces and custom globals of this execution.
|
|
3366
|
+
*/
|
|
3367
|
+
runtimeGlobals(context, charge, callbacks) {
|
|
3368
|
+
const { config } = context;
|
|
3369
|
+
const callTool = this.createCallTool(context);
|
|
3370
|
+
const resolver = context.sidecar && context.referenceConfig ? new ReferenceResolver(context.sidecar, context.referenceConfig) : void 0;
|
|
3371
|
+
const joinReferences = (parts) => {
|
|
3372
|
+
if (!resolver) {
|
|
3373
|
+
throw sandboxError(
|
|
3374
|
+
"Cannot concatenate reference IDs: reference system not configured. Pass references directly to callTool arguments instead."
|
|
3375
|
+
);
|
|
3376
|
+
}
|
|
3377
|
+
return resolver.createComposite(parts);
|
|
3378
|
+
};
|
|
3379
|
+
const concat = (left, right) => {
|
|
3380
|
+
if (typeof left === "number" && typeof right === "number") return left + right;
|
|
3381
|
+
if (typeof left === "string" && isReferenceId(left) || typeof right === "string" && isReferenceId(right)) {
|
|
3382
|
+
return joinReferences([String(left), String(right)]);
|
|
3383
|
+
}
|
|
3384
|
+
const result = left + right;
|
|
3385
|
+
if (typeof result === "string") {
|
|
3386
|
+
charge((result.length - (typeof left === "string" ? left.length : 0)) * 2);
|
|
3387
|
+
}
|
|
3388
|
+
return result;
|
|
3389
|
+
};
|
|
3390
|
+
const template = (quasis, ...values) => {
|
|
3391
|
+
if (!Array.isArray(quasis)) throw sandboxError("Template pieces must be an array", "TypeError");
|
|
3392
|
+
const parts = [];
|
|
3393
|
+
let hasReference = false;
|
|
3394
|
+
for (let i = 0; i < quasis.length; i++) {
|
|
3395
|
+
parts.push(String(quasis[i]));
|
|
3396
|
+
if (i < values.length) {
|
|
3397
|
+
const value = values[i];
|
|
3398
|
+
if (typeof value === "string" && isReferenceId(value)) hasReference = true;
|
|
3399
|
+
parts.push(String(value));
|
|
3400
|
+
}
|
|
3401
|
+
}
|
|
3402
|
+
if (hasReference) return joinReferences(parts.filter((part) => part !== ""));
|
|
3403
|
+
const result = parts.join("");
|
|
3404
|
+
charge(result.length * 2);
|
|
3405
|
+
return result;
|
|
3406
|
+
};
|
|
3407
|
+
const maxIterations = typeof config.maxIterations === "number" ? config.maxIterations : Number.POSITIVE_INFINITY;
|
|
3408
|
+
const signal = context.abortController.signal;
|
|
3409
|
+
function* forOf(iterable) {
|
|
3410
|
+
let iterations = 0;
|
|
3411
|
+
for (const item of iterable) {
|
|
3412
|
+
if (signal.aborted) throw sandboxError("Execution aborted");
|
|
3413
|
+
if (++iterations > maxIterations) {
|
|
3414
|
+
throw sandboxError(
|
|
3415
|
+
`Maximum iteration limit exceeded (${maxIterations}). This limit prevents infinite loops.`
|
|
3416
|
+
);
|
|
3417
|
+
}
|
|
3418
|
+
yield item;
|
|
3419
|
+
}
|
|
3420
|
+
}
|
|
3421
|
+
const parallel = async (first, second) => {
|
|
3422
|
+
let tasks;
|
|
3423
|
+
if (typeof second === "function") {
|
|
3424
|
+
if (!Array.isArray(first)) throw sandboxError("parallel requires an array of items", "TypeError");
|
|
3425
|
+
const items = first;
|
|
3426
|
+
tasks = items.map((item, index) => () => callbacks.call(second, [item, index, items]));
|
|
3427
|
+
} else {
|
|
3428
|
+
if (!Array.isArray(first) || !first.every((task) => typeof task === "function")) {
|
|
3429
|
+
throw sandboxError("parallel requires an array of functions", "TypeError");
|
|
3430
|
+
}
|
|
3431
|
+
tasks = first.map((task) => () => callbacks.call(task, []));
|
|
3432
|
+
}
|
|
3433
|
+
if (tasks.length > MAX_PARALLEL_ITEMS) {
|
|
3434
|
+
throw sandboxError(
|
|
3435
|
+
`Cannot execute more than ${MAX_PARALLEL_ITEMS} operations in parallel. Split into smaller batches.`
|
|
3436
|
+
);
|
|
3437
|
+
}
|
|
3438
|
+
const settled = await Promise.allSettled(tasks.map(async (task) => task()));
|
|
3439
|
+
const failures = settled.filter((result) => result.status === "rejected");
|
|
3440
|
+
if (failures.length > 0) {
|
|
3441
|
+
const messages = failures.map((failure) => this.describe(failure.reason).message).join("\n");
|
|
3442
|
+
throw sandboxError(`${failures.length} of ${tasks.length} parallel operations failed:
|
|
3443
|
+
${messages}`);
|
|
3444
|
+
}
|
|
3445
|
+
return settled.map((result) => result.value);
|
|
3446
|
+
};
|
|
3447
|
+
const globals = {
|
|
3448
|
+
__safe_callTool: callTool,
|
|
3449
|
+
__safe_concat: concat,
|
|
3450
|
+
__safe_template: template,
|
|
3451
|
+
// Both go through the items of an array they are given and never convert it to text, so
|
|
3452
|
+
// the interpreter does not measure it first (as it does for a built-in that might).
|
|
3453
|
+
__safe_forOf: takesArraysAsData(forOf),
|
|
3454
|
+
__safe_parallel: takesArraysAsData(parallel),
|
|
3455
|
+
__maxIterations: maxIterations
|
|
3456
|
+
};
|
|
3457
|
+
if (typeof context.consoleHandler === "function") {
|
|
3458
|
+
const maxConsoleCalls = config.maxConsoleCalls ?? DEFAULT_MAX_CONSOLE_CALLS;
|
|
3459
|
+
const maxConsoleOutputBytes = config.maxConsoleOutputBytes ?? DEFAULT_MAX_CONSOLE_OUTPUT_BYTES;
|
|
3460
|
+
const sink = createConsoleSink(context.consoleHandler, { maxConsoleCalls, maxConsoleOutputBytes });
|
|
3461
|
+
let consoleCalls = 0;
|
|
3462
|
+
let consoleLength = 0;
|
|
3463
|
+
const write = (level) => (...args) => {
|
|
3464
|
+
consoleCalls++;
|
|
3465
|
+
if (consoleCalls > maxConsoleCalls) {
|
|
3466
|
+
throw sandboxError(
|
|
3467
|
+
`Console call limit exceeded (max: ${maxConsoleCalls}). This limit prevents I/O flood attacks.`
|
|
3468
|
+
);
|
|
3469
|
+
}
|
|
3470
|
+
const line = args.map(consoleText).join(" ");
|
|
3471
|
+
consoleLength += line.length;
|
|
3472
|
+
if (consoleLength > maxConsoleOutputBytes) {
|
|
3473
|
+
throw sandboxError(
|
|
3474
|
+
`Console output size limit exceeded (max: ${maxConsoleOutputBytes} bytes). This limit prevents I/O flood attacks.`
|
|
3475
|
+
);
|
|
3476
|
+
}
|
|
3477
|
+
sink(level, line);
|
|
3478
|
+
};
|
|
3479
|
+
globals["__safe_console"] = frozenRecord2({
|
|
3480
|
+
log: write("log"),
|
|
3481
|
+
info: write("info"),
|
|
3482
|
+
warn: write("warn"),
|
|
3483
|
+
error: write("error")
|
|
3484
|
+
});
|
|
3485
|
+
}
|
|
3486
|
+
for (const namespace of context.toolNamespaces ?? []) {
|
|
3487
|
+
const methods = {};
|
|
3488
|
+
for (const method of namespace.methods) {
|
|
3489
|
+
if (isBlockedKey(method.name)) continue;
|
|
3490
|
+
methods[method.name] = (args, options) => callTool(method.toolName, args === void 0 ? {} : args, options);
|
|
3491
|
+
}
|
|
3492
|
+
globals[namespace.name] = frozenRecord2(methods);
|
|
3493
|
+
}
|
|
3494
|
+
const custom = config.globals;
|
|
3495
|
+
if (custom && typeof custom === "object") {
|
|
3496
|
+
for (const name of Object.keys(custom)) {
|
|
3497
|
+
if (name.startsWith("__") || Object.prototype.hasOwnProperty.call(globals, name)) continue;
|
|
3498
|
+
globals[name] = frozenDataCopy(name, custom[name]);
|
|
3499
|
+
}
|
|
3500
|
+
}
|
|
3501
|
+
return globals;
|
|
3502
|
+
}
|
|
3503
|
+
/**
|
|
3504
|
+
* `callTool(name, args, options)` for the script, through the host tool bridge: the request
|
|
3505
|
+
* and the response cross as JSON, so the handler never receives a value of the script and the
|
|
3506
|
+
* script never receives an object of the handler.
|
|
3507
|
+
*/
|
|
3508
|
+
createCallTool(context) {
|
|
3509
|
+
const configured = context.config.toolHandler;
|
|
3510
|
+
const bridgeContext = context.toolHandler === void 0 && typeof configured === "function" ? Object.create(context, { toolHandler: { value: configured } }) : context;
|
|
3511
|
+
const bridge = createHostToolBridge(bridgeContext, { updateStats: true });
|
|
3512
|
+
return async (toolName, args, options) => {
|
|
3513
|
+
let throwOnError = true;
|
|
3514
|
+
if (options !== void 0 && options !== null) {
|
|
3515
|
+
if (typeof options !== "object") throw sandboxError("callTool options must be an object", "TypeError");
|
|
3516
|
+
throwOnError = options.throwOnError !== false;
|
|
3517
|
+
}
|
|
3518
|
+
if (typeof toolName !== "string" || !toolName) {
|
|
3519
|
+
throw sandboxError("Tool name must be a non-empty string", "TypeError");
|
|
3520
|
+
}
|
|
3521
|
+
if (typeof args !== "object" || args === null || Array.isArray(args)) {
|
|
3522
|
+
throw sandboxError("Tool arguments must be an object", "TypeError");
|
|
3523
|
+
}
|
|
3524
|
+
let requestJson;
|
|
3525
|
+
try {
|
|
3526
|
+
requestJson = encodeToolBridgeRequest(toolName, args);
|
|
3527
|
+
} catch {
|
|
3528
|
+
throw sandboxError("Tool arguments must be JSON-serializable", "TypeError");
|
|
3529
|
+
}
|
|
3530
|
+
let response;
|
|
3531
|
+
try {
|
|
3532
|
+
response = JSON.parse(await bridge(requestJson));
|
|
3533
|
+
} catch {
|
|
3534
|
+
throw sandboxError("Tool bridge returned invalid JSON");
|
|
3535
|
+
}
|
|
3536
|
+
if (!response || typeof response !== "object" || Array.isArray(response)) {
|
|
3537
|
+
throw sandboxError("Tool bridge returned invalid response");
|
|
3538
|
+
}
|
|
3539
|
+
const reply = response;
|
|
3540
|
+
if (reply.ok === true) {
|
|
3541
|
+
return throwOnError ? reply.value : { success: true, data: reply.value };
|
|
3542
|
+
}
|
|
3543
|
+
if (reply.ok === false && reply.error && typeof reply.error === "object") {
|
|
3544
|
+
const message = typeof reply.error["message"] === "string" ? reply.error["message"] : "Tool call failed";
|
|
3545
|
+
const name = typeof reply.error["name"] === "string" ? reply.error["name"] : "Error";
|
|
3546
|
+
const code = typeof reply.error["code"] === "string" ? reply.error["code"] : void 0;
|
|
3547
|
+
if (!throwOnError && reply.error["toolError"] === true) {
|
|
3548
|
+
return { success: false, error: { name, message, toolName, ...code !== void 0 ? { code } : {} } };
|
|
3549
|
+
}
|
|
3550
|
+
throw sandboxError(message, name, code);
|
|
3551
|
+
}
|
|
3552
|
+
throw sandboxError("Tool bridge returned invalid response");
|
|
3553
|
+
};
|
|
3554
|
+
}
|
|
3555
|
+
/**
|
|
3556
|
+
* The value a script returned, as the caller gets it: plain host data, like from every other
|
|
3557
|
+
* adapter. A function, or a result that would serialize to more than the memory limit, fails
|
|
3558
|
+
* the execution.
|
|
3559
|
+
*/
|
|
3560
|
+
succeed(value, context, startTime, toolCallCount, stepCount) {
|
|
3561
|
+
const { config } = context;
|
|
3562
|
+
const stats = this.stats(startTime, toolCallCount, stepCount);
|
|
3563
|
+
if (typeof config.memoryLimit === "number" && config.memoryLimit > 0 && value !== void 0) {
|
|
3564
|
+
const sizeCheck = checkSerializedSize(value, Math.min(config.memoryLimit, MAX_SERIALIZED_RESULT_BYTES));
|
|
3565
|
+
if (!sizeCheck.ok) {
|
|
3566
|
+
return {
|
|
3567
|
+
success: false,
|
|
3568
|
+
error: {
|
|
3569
|
+
name: "MemoryLimitError",
|
|
3570
|
+
message: `Return value serialization would exceed memory limit: ${sizeCheck.error}`,
|
|
3571
|
+
code: "SERIALIZATION_LIMIT_EXCEEDED"
|
|
3572
|
+
},
|
|
3573
|
+
stats
|
|
3574
|
+
};
|
|
3575
|
+
}
|
|
3576
|
+
}
|
|
3577
|
+
const maxDepth = config.maxSanitizeDepth;
|
|
3578
|
+
const maxProperties = config.maxSanitizeProperties;
|
|
3579
|
+
return {
|
|
3580
|
+
success: true,
|
|
3581
|
+
value: sanitizeValue(value, { maxDepth, maxProperties, allowDates: true, allowErrors: true }),
|
|
3582
|
+
stats
|
|
3583
|
+
};
|
|
3584
|
+
}
|
|
819
3585
|
stats(startTime, toolCallCount, iterationCount) {
|
|
820
3586
|
const endTime = Date.now();
|
|
821
3587
|
return { duration: endTime - startTime, toolCallCount, iterationCount, startTime, endTime };
|
|
822
3588
|
}
|
|
3589
|
+
/**
|
|
3590
|
+
* What ended an execution, as a name and a message. A script can throw any value: a string is
|
|
3591
|
+
* the message, an object contributes its `name`, `message` and `code` when they are strings.
|
|
3592
|
+
*/
|
|
3593
|
+
describe(thrown) {
|
|
3594
|
+
if (thrown instanceof Error) {
|
|
3595
|
+
const code = thrown.code;
|
|
3596
|
+
return {
|
|
3597
|
+
name: thrown.name,
|
|
3598
|
+
message: thrown.message,
|
|
3599
|
+
stack: thrown.stack,
|
|
3600
|
+
...typeof code === "string" ? { code } : {}
|
|
3601
|
+
};
|
|
3602
|
+
}
|
|
3603
|
+
if (typeof thrown === "string") return { name: "Error", message: thrown };
|
|
3604
|
+
if (thrown !== null && typeof thrown === "object") {
|
|
3605
|
+
const value = thrown;
|
|
3606
|
+
return {
|
|
3607
|
+
name: typeof value.name === "string" ? value.name : "Error",
|
|
3608
|
+
message: typeof value.message === "string" ? value.message : "The script threw a value that is not an error",
|
|
3609
|
+
...typeof value.code === "string" ? { code: value.code } : {}
|
|
3610
|
+
};
|
|
3611
|
+
}
|
|
3612
|
+
return { name: "Error", message: `The script threw ${String(thrown)}` };
|
|
3613
|
+
}
|
|
823
3614
|
fail(error, startTime, toolCallCount, iterationCount, sanitizeStacks, name, code) {
|
|
824
|
-
const
|
|
825
|
-
const stack = sanitizeStackTrace(
|
|
3615
|
+
const described = this.describe(error);
|
|
3616
|
+
const stack = sanitizeStackTrace(described.stack, sanitizeStacks);
|
|
3617
|
+
const errorCode = code ?? described.code;
|
|
826
3618
|
const execError = {
|
|
827
|
-
message:
|
|
828
|
-
name: name ??
|
|
3619
|
+
message: described.message,
|
|
3620
|
+
name: name ?? described.name,
|
|
829
3621
|
...stack ? { stack } : {},
|
|
830
|
-
...
|
|
3622
|
+
...errorCode ? { code: errorCode } : {}
|
|
831
3623
|
};
|
|
832
3624
|
return { success: false, error: execError, stats: this.stats(startTime, toolCallCount, iterationCount) };
|
|
833
3625
|
}
|