@enclave-vm/core 2.19.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/index.js CHANGED
@@ -14931,7 +14931,14 @@ var BLOCKED_KEYS = /* @__PURE__ */ new Set([
14931
14931
  "__lookupSetter__"
14932
14932
  ]);
14933
14933
  function isBlockedKey(key) {
14934
- return BLOCKED_KEYS.has(key);
14934
+ return key === "__proto__" || BLOCKED_KEYS.has(key);
14935
+ }
14936
+ function assertKeyAllowed(key) {
14937
+ if (isBlockedKey(key)) throw new InterpreterError(`Forbidden property access: ${key}`);
14938
+ }
14939
+ function readProperty2(object, key) {
14940
+ if (key === "__proto__" || BLOCKED_KEYS.has(key)) throw new InterpreterError(`Forbidden property access: ${key}`);
14941
+ return object[key];
14935
14942
  }
14936
14943
  var MAX_STRING_OP_LENGTH = 1e6;
14937
14944
  var MAX_JOIN_LENGTH = 16e6;
@@ -15118,13 +15125,23 @@ function isScriptError(value) {
15118
15125
  return typeof value === "object" && value !== null && SCRIPT_ERRORS.has(value);
15119
15126
  }
15120
15127
  var Scope = class _Scope {
15121
- constructor(parent) {
15128
+ constructor(parent, depth) {
15122
15129
  this.parent = parent;
15130
+ this.depth = depth ?? parent?.depth ?? 0;
15123
15131
  }
15124
15132
  vars = /* @__PURE__ */ new Map();
15133
+ /**
15134
+ * How many calls deep the code of this scope runs: 0 for the program, and for the body of a
15135
+ * function one more than where it was called from. A block inside has the depth around it.
15136
+ */
15137
+ depth;
15125
15138
  child() {
15126
15139
  return new _Scope(this);
15127
15140
  }
15141
+ /** The scope of one call of a function defined in this scope, running `depth` calls deep. */
15142
+ activation(depth) {
15143
+ return new _Scope(this, depth);
15144
+ }
15128
15145
  declare(name, value, mutable) {
15129
15146
  this.vars.set(name, { value, mutable });
15130
15147
  }
@@ -15151,15 +15168,28 @@ var Scope = class _Scope {
15151
15168
  throw new InterpreterError(`'${name}' is not defined`);
15152
15169
  }
15153
15170
  };
15171
+ var DEFAULT_MAX_PENDING_CALLS = 4096;
15154
15172
  function ignoreRejection2() {
15155
15173
  }
15156
15174
  var Interpreter = class {
15157
15175
  constructor(options) {
15158
15176
  this.options = options;
15159
15177
  this.globals = options.globals;
15178
+ this.maxPendingCalls = options.maxPendingCalls ?? DEFAULT_MAX_PENDING_CALLS;
15160
15179
  }
15161
15180
  steps = 0;
15162
- callDepth = 0;
15181
+ /** Calls that have not returned: the running ones and the ones waiting on an `await` */
15182
+ pendingCalls = 0;
15183
+ /**
15184
+ * The depth of whatever is making a call right now, for the function of the script that call
15185
+ * starts. A function of the script is a host function too, and a built-in, `parallel` or a
15186
+ * bound function invokes it without saying how deep it is: it reads this as it starts, in the
15187
+ * same synchronous step as the call, and runs one deeper. Set by {@link withCallerDepth} for
15188
+ * the synchronous part of a call only; a call that is waiting does not hold it, which is what
15189
+ * keeps the depth of one chain apart from the depth of another. 0 when the host itself calls.
15190
+ */
15191
+ callerDepth = 0;
15192
+ maxPendingCalls;
15163
15193
  globals;
15164
15194
  /** The error that ended the run (step budget, abort, allocation budget); set once, never caught */
15165
15195
  fatal;
@@ -15173,7 +15203,7 @@ var Interpreter = class {
15173
15203
  call(fn, args) {
15174
15204
  if (typeof fn !== "function") throw new InterpreterError("Attempted to call a non-function");
15175
15205
  if (this.interpretedFunctions.has(fn)) return fn(...args);
15176
- return this.callFunction(fn, void 0, args);
15206
+ return this.callFunction(fn, void 0, args, this.callerDepth);
15177
15207
  }
15178
15208
  /** Number of AST nodes evaluated so far (for execution stats). */
15179
15209
  get stepCount() {
@@ -15495,7 +15525,7 @@ var Interpreter = class {
15495
15525
  }
15496
15526
  case "MemberExpression": {
15497
15527
  const { object, key } = await this.evalMemberTarget(node, scope);
15498
- return object[key];
15528
+ return readProperty2(object, key);
15499
15529
  }
15500
15530
  case "CallExpression":
15501
15531
  return this.evalCall(node, scope);
@@ -15534,6 +15564,7 @@ var Interpreter = class {
15534
15564
  if (node.argument.type !== "MemberExpression") throw new InterpreterError("Only a property can be deleted");
15535
15565
  const { object, key } = await this.evalMemberTarget(node.argument, scope);
15536
15566
  this.assertChangeable(object);
15567
+ assertKeyAllowed(key);
15537
15568
  return delete object[key];
15538
15569
  }
15539
15570
  const v = await this.evalExpr(node.argument, scope);
@@ -15656,7 +15687,7 @@ var Interpreter = class {
15656
15687
  if (node.type === "MemberExpression") {
15657
15688
  const { object, key } = await this.evalMemberTarget(node, scope);
15658
15689
  return {
15659
- get: () => object[key],
15690
+ get: () => readProperty2(object, key),
15660
15691
  set: (value) => this.writeMember(object, key, value)
15661
15692
  };
15662
15693
  }
@@ -15675,6 +15706,7 @@ var Interpreter = class {
15675
15706
  }
15676
15707
  writeMember(object, key, value) {
15677
15708
  this.assertChangeable(object);
15709
+ assertKeyAllowed(key);
15678
15710
  if (Array.isArray(object)) {
15679
15711
  const grownTo = arrayLengthAfterWrite(object, key, value);
15680
15712
  if (grownTo > MAX_ARRAY_LENGTH2) {
@@ -15720,7 +15752,7 @@ var Interpreter = class {
15720
15752
  let member;
15721
15753
  if (node.callee.type === "MemberExpression") {
15722
15754
  const target = await this.evalMemberTarget(node.callee, scope);
15723
- member = { ...target, value: target.object[target.key] };
15755
+ member = { ...target, value: readProperty2(target.object, target.key) };
15724
15756
  fn = member.value;
15725
15757
  thisArg = member.object;
15726
15758
  } else if (node.callee.type === "Super") {
@@ -15734,14 +15766,16 @@ var Interpreter = class {
15734
15766
  }
15735
15767
  const args = await this.evalArguments(node.arguments, scope);
15736
15768
  if (typeof fn !== "function") throw new InterpreterError("Attempted to call a non-function");
15737
- return this.callFunction(fn, thisArg, args);
15769
+ return this.callFunction(fn, thisArg, args, scope.depth);
15738
15770
  }
15739
15771
  /**
15740
15772
  * Call a function with a receiver and arguments: an interpreted function, or a built-in or host
15741
15773
  * function after the checks that apply to it. `call` and `apply` are resolved to the function
15742
15774
  * they invoke first, so those checks cannot be passed by the way a call is written.
15775
+ *
15776
+ * @param depth - How many calls deep the code that makes this call runs
15743
15777
  */
15744
- async callFunction(fn, thisArg, args) {
15778
+ async callFunction(fn, thisArg, args, depth) {
15745
15779
  for (let hops = 0; fn === FunctionProtoCall || fn === FunctionProtoApply || fn === FunctionProtoBind; hops++) {
15746
15780
  const name = fn === FunctionProtoCall ? "call" : fn === FunctionProtoApply ? "apply" : "bind";
15747
15781
  if (typeof thisArg !== "function" || hops >= 8) {
@@ -15757,20 +15791,20 @@ var Interpreter = class {
15757
15791
  fn = target;
15758
15792
  }
15759
15793
  if (typeof fn !== "function") throw new InterpreterError("Attempted to call a non-function");
15760
- if (++this.callDepth > this.options.maxCallDepth) {
15761
- this.callDepth--;
15762
- throw new InterpreterError(`Max call depth exceeded (${this.options.maxCallDepth})`);
15794
+ if (this.interpretedFunctions.has(fn)) {
15795
+ const interpreted = fn;
15796
+ return await this.withCallerDepth(depth, () => interpreted.apply(thisArg, args));
15763
15797
  }
15798
+ const own = this.enterCall(depth);
15764
15799
  try {
15765
- if (this.interpretedFunctions.has(fn)) {
15766
- return await fn.apply(thisArg, args);
15767
- }
15768
15800
  args = this.checkBuiltinCall(fn, thisArg, args);
15769
15801
  const arrayMethod = ARRAY_METHODS.get(fn);
15770
15802
  if (arrayMethod !== void 0 && HIGHER_ORDER_ARRAY_METHODS.has(arrayMethod) && typeof args[0] === "function") {
15771
- return await this.callArrayMethod(thisArg, arrayMethod, args);
15803
+ return await this.callArrayMethod(thisArg, arrayMethod, args, own);
15772
15804
  }
15773
- const result = await fn.apply(thisArg, args);
15805
+ const builtin = fn;
15806
+ const builtinArgs = args;
15807
+ const result = await this.withCallerDepth(own, () => builtin.apply(thisArg, builtinArgs));
15774
15808
  if (arrayMethod === void 0 && STRING_METHODS.get(fn) === "split" && Array.isArray(result)) {
15775
15809
  if (result.length > MAX_ARRAY_LENGTH2) {
15776
15810
  throw new InterpreterError(`An array cannot be longer than ${MAX_ARRAY_LENGTH2} items`);
@@ -15779,7 +15813,36 @@ var Interpreter = class {
15779
15813
  this.chargeValue(result);
15780
15814
  return result;
15781
15815
  } finally {
15782
- this.callDepth--;
15816
+ this.pendingCalls--;
15817
+ }
15818
+ }
15819
+ /**
15820
+ * Count a call that starts `callerDepth` calls deep, until it returns.
15821
+ *
15822
+ * @returns The depth the call itself runs at
15823
+ */
15824
+ enterCall(callerDepth) {
15825
+ const depth = callerDepth + 1;
15826
+ if (depth > this.options.maxCallDepth) {
15827
+ throw new InterpreterError(`Max call depth exceeded (${this.options.maxCallDepth})`);
15828
+ }
15829
+ if (this.pendingCalls >= this.maxPendingCalls) {
15830
+ throw new InterpreterError(`Too many calls in progress at once (${this.maxPendingCalls})`);
15831
+ }
15832
+ this.pendingCalls++;
15833
+ return depth;
15834
+ }
15835
+ /**
15836
+ * Make a call with `depth` as the depth a function of the script is called from, if one starts
15837
+ * during it. It covers the synchronous part of the call, which is where a function starts.
15838
+ */
15839
+ withCallerDepth(depth, call) {
15840
+ const previous = this.callerDepth;
15841
+ this.callerDepth = depth;
15842
+ try {
15843
+ return call();
15844
+ } finally {
15845
+ this.callerDepth = previous;
15783
15846
  }
15784
15847
  }
15785
15848
  /** The argument list of `apply`: an array, or nothing. */
@@ -15796,7 +15859,7 @@ var Interpreter = class {
15796
15859
  bindFunction(target, boundThis, boundArgs) {
15797
15860
  this.charge((boundArgs.length + 2) * 8);
15798
15861
  return (...rest) => {
15799
- const result = this.callFunction(target, boundThis, [...boundArgs, ...rest]);
15862
+ const result = this.callFunction(target, boundThis, [...boundArgs, ...rest], this.callerDepth);
15800
15863
  result.then(void 0, ignoreRejection2);
15801
15864
  return result;
15802
15865
  };
@@ -15959,9 +16022,10 @@ var Interpreter = class {
15959
16022
  * callbacks (which are async — they may `await` tool calls) are awaited. Each
15960
16023
  * iteration ticks the step budget.
15961
16024
  */
15962
- async callArrayMethod(arr, method, args) {
16025
+ async callArrayMethod(arr, method, args, depth) {
15963
16026
  const callback = args[0];
15964
- const invoke = this.interpretedFunctions.has(callback) ? callback : (...callbackArgs) => this.callFunction(callback, void 0, callbackArgs);
16027
+ const interpreted = this.interpretedFunctions.has(callback) ? callback : void 0;
16028
+ const invoke = interpreted ? (...callbackArgs) => this.withCallerDepth(depth, () => interpreted(...callbackArgs)) : (...callbackArgs) => this.callFunction(callback, void 0, callbackArgs, depth);
15965
16029
  const cb = invoke;
15966
16030
  const each = (i) => {
15967
16031
  this.tick();
@@ -16137,7 +16201,7 @@ var Interpreter = class {
16137
16201
  else throw new InterpreterError("Unsupported destructuring key");
16138
16202
  if (BLOCKED_KEYS.has(key)) throw new InterpreterError(`Forbidden destructured key: ${key}`);
16139
16203
  taken.add(key);
16140
- await this.applyPattern(prop.value, source[key], scope, mode);
16204
+ await this.applyPattern(prop.value, readProperty2(source, key), scope, mode);
16141
16205
  }
16142
16206
  return;
16143
16207
  }
@@ -16150,17 +16214,17 @@ var Interpreter = class {
16150
16214
  if (node.generator) throw new InterpreterError("Generator functions are not supported");
16151
16215
  const selfName = node.type === "FunctionExpression" && node.id ? node.id.name : void 0;
16152
16216
  const outer = selfName === void 0 ? closure : closure.child();
16153
- const call = async (args) => {
16154
- const fnScope = outer.child();
16155
- for (let i = 0; i < node.params.length; i++) {
16156
- const param = node.params[i];
16157
- if (param.type === "RestElement") {
16158
- await this.applyPattern(param.argument, args.slice(i), fnScope, "let");
16159
- break;
16160
- }
16161
- await this.applyPattern(param, args[i], fnScope, "let");
16162
- }
16217
+ const call = async (args, callerDepth) => {
16218
+ const fnScope = outer.activation(this.enterCall(callerDepth));
16163
16219
  try {
16220
+ for (let i = 0; i < node.params.length; i++) {
16221
+ const param = node.params[i];
16222
+ if (param.type === "RestElement") {
16223
+ await this.applyPattern(param.argument, args.slice(i), fnScope, "let");
16224
+ break;
16225
+ }
16226
+ await this.applyPattern(param, args[i], fnScope, "let");
16227
+ }
16164
16228
  if (node.body.type === "BlockStatement") {
16165
16229
  await this.execBlock(node.body.body, fnScope);
16166
16230
  return void 0;
@@ -16169,10 +16233,13 @@ var Interpreter = class {
16169
16233
  } catch (e) {
16170
16234
  if (e instanceof ReturnSignal) return e.value;
16171
16235
  throw e;
16236
+ } finally {
16237
+ this.pendingCalls--;
16172
16238
  }
16173
16239
  };
16240
+ const depthOfCaller = () => this.callerDepth;
16174
16241
  const interpreted = function interpreted2(...args) {
16175
- const result = call(args);
16242
+ const result = call(args, depthOfCaller());
16176
16243
  result.then(void 0, ignoreRejection2);
16177
16244
  return result;
16178
16245
  };
@@ -16192,7 +16259,7 @@ var Interpreter = class {
16192
16259
  throw new InterpreterError("Unsupported property key");
16193
16260
  }
16194
16261
  readGlobal(name) {
16195
- if (Object.prototype.hasOwnProperty.call(this.globals, name)) return this.globals[name];
16262
+ if (name !== "__proto__" && Object.prototype.hasOwnProperty.call(this.globals, name)) return this.globals[name];
16196
16263
  throw new InterpreterError(`'${name}' is not defined`);
16197
16264
  }
16198
16265
  };
@@ -16203,6 +16270,7 @@ function isIterable(v) {
16203
16270
  return v != null && typeof v[Symbol.iterator] === "function";
16204
16271
  }
16205
16272
  function isScriptData(value) {
16273
+ if (value === Object.prototype || value === Array.prototype) return false;
16206
16274
  if (Array.isArray(value)) return true;
16207
16275
  if (value === null || typeof value !== "object") return false;
16208
16276
  const prototype = Object.getPrototypeOf(value);
@@ -16644,6 +16712,7 @@ var InterpreterAdapter = class {
16644
16712
  instanceChecks: safe.instanceChecks,
16645
16713
  maxSteps: this.options.maxSteps ?? DEFAULT_MAX_STEPS,
16646
16714
  maxCallDepth: this.options.maxCallDepth ?? DEFAULT_MAX_CALL_DEPTH,
16715
+ maxPendingCalls: this.options.maxPendingCalls,
16647
16716
  signal: context.abortController.signal,
16648
16717
  charge
16649
16718
  });
@@ -56,8 +56,19 @@ export interface InterpreterOptions {
56
56
  globals: Record<string, unknown>;
57
57
  /** Max evaluated nodes before aborting (interrupts infinite loops). */
58
58
  maxSteps: number;
59
- /** Max nested call depth (interpreter-defined functions). */
59
+ /**
60
+ * How deep calls may nest: a call counts from where it is made to where it returns, along the
61
+ * chain of calls it belongs to. A callback counts as a call of the function that invokes it,
62
+ * so the tasks of one `parallel` batch each continue the chain that started the batch and do
63
+ * not add up.
64
+ */
60
65
  maxCallDepth: number;
66
+ /**
67
+ * How many calls of the whole execution may be unfinished at once, over all its chains: the
68
+ * ones that are running and the ones waiting for something they await. This bounds what the
69
+ * waiting calls hold. Default: {@link DEFAULT_MAX_PENDING_CALLS}.
70
+ */
71
+ maxPendingCalls?: number;
61
72
  /** Optional cancellation. */
62
73
  signal?: AbortSignal;
63
74
  /**
@@ -74,6 +85,8 @@ export interface InterpreterOptions {
74
85
  */
75
86
  charge?: (bytes: number) => void;
76
87
  }
88
+ /** Unfinished calls an execution may have at once, when the host sets no `maxPendingCalls`. */
89
+ export declare const DEFAULT_MAX_PENDING_CALLS = 4096;
77
90
  /**
78
91
  * Evaluate a parsed AgentScript program. Returns the resolved value of the
79
92
  * `__ag_main()` invocation (or the program's last value if no main wrapper).
@@ -81,7 +94,18 @@ export interface InterpreterOptions {
81
94
  export declare class Interpreter {
82
95
  private readonly options;
83
96
  private steps;
84
- private callDepth;
97
+ /** Calls that have not returned: the running ones and the ones waiting on an `await` */
98
+ private pendingCalls;
99
+ /**
100
+ * The depth of whatever is making a call right now, for the function of the script that call
101
+ * starts. A function of the script is a host function too, and a built-in, `parallel` or a
102
+ * bound function invokes it without saying how deep it is: it reads this as it starts, in the
103
+ * same synchronous step as the call, and runs one deeper. Set by {@link withCallerDepth} for
104
+ * the synchronous part of a call only; a call that is waiting does not hold it, which is what
105
+ * keeps the depth of one chain apart from the depth of another. 0 when the host itself calls.
106
+ */
107
+ private callerDepth;
108
+ private readonly maxPendingCalls;
85
109
  private readonly globals;
86
110
  /** The error that ended the run (step budget, abort, allocation budget); set once, never caught */
87
111
  private fatal;
@@ -158,8 +182,21 @@ export declare class Interpreter {
158
182
  * Call a function with a receiver and arguments: an interpreted function, or a built-in or host
159
183
  * function after the checks that apply to it. `call` and `apply` are resolved to the function
160
184
  * they invoke first, so those checks cannot be passed by the way a call is written.
185
+ *
186
+ * @param depth - How many calls deep the code that makes this call runs
161
187
  */
162
188
  private callFunction;
189
+ /**
190
+ * Count a call that starts `callerDepth` calls deep, until it returns.
191
+ *
192
+ * @returns The depth the call itself runs at
193
+ */
194
+ private enterCall;
195
+ /**
196
+ * Make a call with `depth` as the depth a function of the script is called from, if one starts
197
+ * during it. It covers the synchronous part of the call, which is where a function starts.
198
+ */
199
+ private withCallerDepth;
163
200
  /** The argument list of `apply`: an array, or nothing. */
164
201
  private argumentList;
165
202
  /**
@@ -199,5 +236,9 @@ export declare class Interpreter {
199
236
  /**
200
237
  * Whether a value is data a script may change: an array, or an object whose prototype is
201
238
  * `Object.prototype` or nothing. That is what literals, `JSON.parse` and tool results are made of.
239
+ *
240
+ * The two prototypes themselves fit that description (`Array.prototype` is an array, and the
241
+ * prototype of `Object.prototype` is nothing) and are nobody's data: every object and array of the
242
+ * process inherits from them.
202
243
  */
203
244
  export declare function isScriptData(value: unknown): boolean;
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "@enclave-vm/core",
3
- "version": "2.19.0",
3
+ "version": "2.19.1",
4
4
  "description": "Sandbox runtime for secure JavaScript code execution",
5
5
  "author": "AgentFront <info@agentfront.dev>",
6
6
  "homepage": "https://github.com/agentfront/enclave",
@@ -44,8 +44,8 @@
44
44
  },
45
45
  "dependencies": {
46
46
  "@babel/standalone": "^7.29.0",
47
- "@enclave-vm/ast": "2.19.0",
48
- "@enclave-vm/types": "2.19.0",
47
+ "@enclave-vm/ast": "2.19.1",
48
+ "@enclave-vm/types": "2.19.1",
49
49
  "@types/estree": "1.0.8",
50
50
  "acorn": "8.15.0",
51
51
  "acorn-walk": "8.3.4",
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "@enclave-vm/core",
3
- "version": "2.19.0",
3
+ "version": "2.19.1",
4
4
  "description": "Sandbox runtime for secure JavaScript code execution",
5
5
  "author": "AgentFront <info@agentfront.dev>",
6
6
  "homepage": "https://github.com/agentfront/enclave",
@@ -46,8 +46,8 @@
46
46
  },
47
47
  "dependencies": {
48
48
  "@babel/standalone": "^7.29.0",
49
- "@enclave-vm/ast": "2.19.0",
50
- "@enclave-vm/types": "2.19.0",
49
+ "@enclave-vm/ast": "2.19.1",
50
+ "@enclave-vm/types": "2.19.1",
51
51
  "@types/estree": "1.0.8",
52
52
  "acorn": "8.15.0",
53
53
  "acorn-walk": "8.3.4",