@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/worker.js CHANGED
@@ -146,7 +146,14 @@ var BLOCKED_KEYS = /* @__PURE__ */ new Set([
146
146
  "__lookupSetter__"
147
147
  ]);
148
148
  function isBlockedKey(key) {
149
- return BLOCKED_KEYS.has(key);
149
+ return key === "__proto__" || BLOCKED_KEYS.has(key);
150
+ }
151
+ function assertKeyAllowed(key) {
152
+ if (isBlockedKey(key)) throw new InterpreterError(`Forbidden property access: ${key}`);
153
+ }
154
+ function readProperty(object, key) {
155
+ if (key === "__proto__" || BLOCKED_KEYS.has(key)) throw new InterpreterError(`Forbidden property access: ${key}`);
156
+ return object[key];
150
157
  }
151
158
  var MAX_STRING_OP_LENGTH = 1e6;
152
159
  var MAX_JOIN_LENGTH = 16e6;
@@ -333,13 +340,23 @@ function isScriptError(value) {
333
340
  return typeof value === "object" && value !== null && SCRIPT_ERRORS.has(value);
334
341
  }
335
342
  var Scope = class _Scope {
336
- constructor(parent) {
343
+ constructor(parent, depth) {
337
344
  this.parent = parent;
345
+ this.depth = depth ?? parent?.depth ?? 0;
338
346
  }
339
347
  vars = /* @__PURE__ */ new Map();
348
+ /**
349
+ * How many calls deep the code of this scope runs: 0 for the program, and for the body of a
350
+ * function one more than where it was called from. A block inside has the depth around it.
351
+ */
352
+ depth;
340
353
  child() {
341
354
  return new _Scope(this);
342
355
  }
356
+ /** The scope of one call of a function defined in this scope, running `depth` calls deep. */
357
+ activation(depth) {
358
+ return new _Scope(this, depth);
359
+ }
343
360
  declare(name, value, mutable) {
344
361
  this.vars.set(name, { value, mutable });
345
362
  }
@@ -366,15 +383,28 @@ var Scope = class _Scope {
366
383
  throw new InterpreterError(`'${name}' is not defined`);
367
384
  }
368
385
  };
386
+ var DEFAULT_MAX_PENDING_CALLS = 4096;
369
387
  function ignoreRejection2() {
370
388
  }
371
389
  var Interpreter = class {
372
390
  constructor(options) {
373
391
  this.options = options;
374
392
  this.globals = options.globals;
393
+ this.maxPendingCalls = options.maxPendingCalls ?? DEFAULT_MAX_PENDING_CALLS;
375
394
  }
376
395
  steps = 0;
377
- callDepth = 0;
396
+ /** Calls that have not returned: the running ones and the ones waiting on an `await` */
397
+ pendingCalls = 0;
398
+ /**
399
+ * The depth of whatever is making a call right now, for the function of the script that call
400
+ * starts. A function of the script is a host function too, and a built-in, `parallel` or a
401
+ * bound function invokes it without saying how deep it is: it reads this as it starts, in the
402
+ * same synchronous step as the call, and runs one deeper. Set by {@link withCallerDepth} for
403
+ * the synchronous part of a call only; a call that is waiting does not hold it, which is what
404
+ * keeps the depth of one chain apart from the depth of another. 0 when the host itself calls.
405
+ */
406
+ callerDepth = 0;
407
+ maxPendingCalls;
378
408
  globals;
379
409
  /** The error that ended the run (step budget, abort, allocation budget); set once, never caught */
380
410
  fatal;
@@ -388,7 +418,7 @@ var Interpreter = class {
388
418
  call(fn, args) {
389
419
  if (typeof fn !== "function") throw new InterpreterError("Attempted to call a non-function");
390
420
  if (this.interpretedFunctions.has(fn)) return fn(...args);
391
- return this.callFunction(fn, void 0, args);
421
+ return this.callFunction(fn, void 0, args, this.callerDepth);
392
422
  }
393
423
  /** Number of AST nodes evaluated so far (for execution stats). */
394
424
  get stepCount() {
@@ -710,7 +740,7 @@ var Interpreter = class {
710
740
  }
711
741
  case "MemberExpression": {
712
742
  const { object, key } = await this.evalMemberTarget(node, scope);
713
- return object[key];
743
+ return readProperty(object, key);
714
744
  }
715
745
  case "CallExpression":
716
746
  return this.evalCall(node, scope);
@@ -749,6 +779,7 @@ var Interpreter = class {
749
779
  if (node.argument.type !== "MemberExpression") throw new InterpreterError("Only a property can be deleted");
750
780
  const { object, key } = await this.evalMemberTarget(node.argument, scope);
751
781
  this.assertChangeable(object);
782
+ assertKeyAllowed(key);
752
783
  return delete object[key];
753
784
  }
754
785
  const v = await this.evalExpr(node.argument, scope);
@@ -871,7 +902,7 @@ var Interpreter = class {
871
902
  if (node.type === "MemberExpression") {
872
903
  const { object, key } = await this.evalMemberTarget(node, scope);
873
904
  return {
874
- get: () => object[key],
905
+ get: () => readProperty(object, key),
875
906
  set: (value) => this.writeMember(object, key, value)
876
907
  };
877
908
  }
@@ -890,6 +921,7 @@ var Interpreter = class {
890
921
  }
891
922
  writeMember(object, key, value) {
892
923
  this.assertChangeable(object);
924
+ assertKeyAllowed(key);
893
925
  if (Array.isArray(object)) {
894
926
  const grownTo = arrayLengthAfterWrite(object, key, value);
895
927
  if (grownTo > MAX_ARRAY_LENGTH) {
@@ -935,7 +967,7 @@ var Interpreter = class {
935
967
  let member;
936
968
  if (node.callee.type === "MemberExpression") {
937
969
  const target = await this.evalMemberTarget(node.callee, scope);
938
- member = { ...target, value: target.object[target.key] };
970
+ member = { ...target, value: readProperty(target.object, target.key) };
939
971
  fn = member.value;
940
972
  thisArg = member.object;
941
973
  } else if (node.callee.type === "Super") {
@@ -949,14 +981,16 @@ var Interpreter = class {
949
981
  }
950
982
  const args = await this.evalArguments(node.arguments, scope);
951
983
  if (typeof fn !== "function") throw new InterpreterError("Attempted to call a non-function");
952
- return this.callFunction(fn, thisArg, args);
984
+ return this.callFunction(fn, thisArg, args, scope.depth);
953
985
  }
954
986
  /**
955
987
  * Call a function with a receiver and arguments: an interpreted function, or a built-in or host
956
988
  * function after the checks that apply to it. `call` and `apply` are resolved to the function
957
989
  * they invoke first, so those checks cannot be passed by the way a call is written.
990
+ *
991
+ * @param depth - How many calls deep the code that makes this call runs
958
992
  */
959
- async callFunction(fn, thisArg, args) {
993
+ async callFunction(fn, thisArg, args, depth) {
960
994
  for (let hops = 0; fn === FunctionProtoCall || fn === FunctionProtoApply || fn === FunctionProtoBind; hops++) {
961
995
  const name = fn === FunctionProtoCall ? "call" : fn === FunctionProtoApply ? "apply" : "bind";
962
996
  if (typeof thisArg !== "function" || hops >= 8) {
@@ -972,20 +1006,20 @@ var Interpreter = class {
972
1006
  fn = target;
973
1007
  }
974
1008
  if (typeof fn !== "function") throw new InterpreterError("Attempted to call a non-function");
975
- if (++this.callDepth > this.options.maxCallDepth) {
976
- this.callDepth--;
977
- throw new InterpreterError(`Max call depth exceeded (${this.options.maxCallDepth})`);
1009
+ if (this.interpretedFunctions.has(fn)) {
1010
+ const interpreted = fn;
1011
+ return await this.withCallerDepth(depth, () => interpreted.apply(thisArg, args));
978
1012
  }
1013
+ const own = this.enterCall(depth);
979
1014
  try {
980
- if (this.interpretedFunctions.has(fn)) {
981
- return await fn.apply(thisArg, args);
982
- }
983
1015
  args = this.checkBuiltinCall(fn, thisArg, args);
984
1016
  const arrayMethod = ARRAY_METHODS.get(fn);
985
1017
  if (arrayMethod !== void 0 && HIGHER_ORDER_ARRAY_METHODS.has(arrayMethod) && typeof args[0] === "function") {
986
- return await this.callArrayMethod(thisArg, arrayMethod, args);
1018
+ return await this.callArrayMethod(thisArg, arrayMethod, args, own);
987
1019
  }
988
- const result = await fn.apply(thisArg, args);
1020
+ const builtin = fn;
1021
+ const builtinArgs = args;
1022
+ const result = await this.withCallerDepth(own, () => builtin.apply(thisArg, builtinArgs));
989
1023
  if (arrayMethod === void 0 && STRING_METHODS.get(fn) === "split" && Array.isArray(result)) {
990
1024
  if (result.length > MAX_ARRAY_LENGTH) {
991
1025
  throw new InterpreterError(`An array cannot be longer than ${MAX_ARRAY_LENGTH} items`);
@@ -994,7 +1028,36 @@ var Interpreter = class {
994
1028
  this.chargeValue(result);
995
1029
  return result;
996
1030
  } finally {
997
- this.callDepth--;
1031
+ this.pendingCalls--;
1032
+ }
1033
+ }
1034
+ /**
1035
+ * Count a call that starts `callerDepth` calls deep, until it returns.
1036
+ *
1037
+ * @returns The depth the call itself runs at
1038
+ */
1039
+ enterCall(callerDepth) {
1040
+ const depth = callerDepth + 1;
1041
+ if (depth > this.options.maxCallDepth) {
1042
+ throw new InterpreterError(`Max call depth exceeded (${this.options.maxCallDepth})`);
1043
+ }
1044
+ if (this.pendingCalls >= this.maxPendingCalls) {
1045
+ throw new InterpreterError(`Too many calls in progress at once (${this.maxPendingCalls})`);
1046
+ }
1047
+ this.pendingCalls++;
1048
+ return depth;
1049
+ }
1050
+ /**
1051
+ * Make a call with `depth` as the depth a function of the script is called from, if one starts
1052
+ * during it. It covers the synchronous part of the call, which is where a function starts.
1053
+ */
1054
+ withCallerDepth(depth, call) {
1055
+ const previous = this.callerDepth;
1056
+ this.callerDepth = depth;
1057
+ try {
1058
+ return call();
1059
+ } finally {
1060
+ this.callerDepth = previous;
998
1061
  }
999
1062
  }
1000
1063
  /** The argument list of `apply`: an array, or nothing. */
@@ -1011,7 +1074,7 @@ var Interpreter = class {
1011
1074
  bindFunction(target, boundThis, boundArgs) {
1012
1075
  this.charge((boundArgs.length + 2) * 8);
1013
1076
  return (...rest) => {
1014
- const result = this.callFunction(target, boundThis, [...boundArgs, ...rest]);
1077
+ const result = this.callFunction(target, boundThis, [...boundArgs, ...rest], this.callerDepth);
1015
1078
  result.then(void 0, ignoreRejection2);
1016
1079
  return result;
1017
1080
  };
@@ -1174,9 +1237,10 @@ var Interpreter = class {
1174
1237
  * callbacks (which are async — they may `await` tool calls) are awaited. Each
1175
1238
  * iteration ticks the step budget.
1176
1239
  */
1177
- async callArrayMethod(arr, method, args) {
1240
+ async callArrayMethod(arr, method, args, depth) {
1178
1241
  const callback = args[0];
1179
- const invoke = this.interpretedFunctions.has(callback) ? callback : (...callbackArgs) => this.callFunction(callback, void 0, callbackArgs);
1242
+ const interpreted = this.interpretedFunctions.has(callback) ? callback : void 0;
1243
+ const invoke = interpreted ? (...callbackArgs) => this.withCallerDepth(depth, () => interpreted(...callbackArgs)) : (...callbackArgs) => this.callFunction(callback, void 0, callbackArgs, depth);
1180
1244
  const cb = invoke;
1181
1245
  const each = (i) => {
1182
1246
  this.tick();
@@ -1352,7 +1416,7 @@ var Interpreter = class {
1352
1416
  else throw new InterpreterError("Unsupported destructuring key");
1353
1417
  if (BLOCKED_KEYS.has(key)) throw new InterpreterError(`Forbidden destructured key: ${key}`);
1354
1418
  taken.add(key);
1355
- await this.applyPattern(prop.value, source[key], scope, mode);
1419
+ await this.applyPattern(prop.value, readProperty(source, key), scope, mode);
1356
1420
  }
1357
1421
  return;
1358
1422
  }
@@ -1365,17 +1429,17 @@ var Interpreter = class {
1365
1429
  if (node.generator) throw new InterpreterError("Generator functions are not supported");
1366
1430
  const selfName = node.type === "FunctionExpression" && node.id ? node.id.name : void 0;
1367
1431
  const outer = selfName === void 0 ? closure : closure.child();
1368
- const call = async (args) => {
1369
- const fnScope = outer.child();
1370
- for (let i = 0; i < node.params.length; i++) {
1371
- const param = node.params[i];
1372
- if (param.type === "RestElement") {
1373
- await this.applyPattern(param.argument, args.slice(i), fnScope, "let");
1374
- break;
1375
- }
1376
- await this.applyPattern(param, args[i], fnScope, "let");
1377
- }
1432
+ const call = async (args, callerDepth) => {
1433
+ const fnScope = outer.activation(this.enterCall(callerDepth));
1378
1434
  try {
1435
+ for (let i = 0; i < node.params.length; i++) {
1436
+ const param = node.params[i];
1437
+ if (param.type === "RestElement") {
1438
+ await this.applyPattern(param.argument, args.slice(i), fnScope, "let");
1439
+ break;
1440
+ }
1441
+ await this.applyPattern(param, args[i], fnScope, "let");
1442
+ }
1379
1443
  if (node.body.type === "BlockStatement") {
1380
1444
  await this.execBlock(node.body.body, fnScope);
1381
1445
  return void 0;
@@ -1384,10 +1448,13 @@ var Interpreter = class {
1384
1448
  } catch (e) {
1385
1449
  if (e instanceof ReturnSignal) return e.value;
1386
1450
  throw e;
1451
+ } finally {
1452
+ this.pendingCalls--;
1387
1453
  }
1388
1454
  };
1455
+ const depthOfCaller = () => this.callerDepth;
1389
1456
  const interpreted = function interpreted2(...args) {
1390
- const result = call(args);
1457
+ const result = call(args, depthOfCaller());
1391
1458
  result.then(void 0, ignoreRejection2);
1392
1459
  return result;
1393
1460
  };
@@ -1407,7 +1474,7 @@ var Interpreter = class {
1407
1474
  throw new InterpreterError("Unsupported property key");
1408
1475
  }
1409
1476
  readGlobal(name) {
1410
- if (Object.prototype.hasOwnProperty.call(this.globals, name)) return this.globals[name];
1477
+ if (name !== "__proto__" && Object.prototype.hasOwnProperty.call(this.globals, name)) return this.globals[name];
1411
1478
  throw new InterpreterError(`'${name}' is not defined`);
1412
1479
  }
1413
1480
  };
@@ -1418,6 +1485,7 @@ function isIterable(v) {
1418
1485
  return v != null && typeof v[Symbol.iterator] === "function";
1419
1486
  }
1420
1487
  function isScriptData(value) {
1488
+ if (value === Object.prototype || value === Array.prototype) return false;
1421
1489
  if (Array.isArray(value)) return true;
1422
1490
  if (value === null || typeof value !== "object") return false;
1423
1491
  const prototype = Object.getPrototypeOf(value);
@@ -1674,12 +1742,12 @@ function estimateSerializedSize(value, maxBytes = 0, depth = 0, maxDepth = 2e3,
1674
1742
  }
1675
1743
  currentPath.add(value);
1676
1744
  try {
1677
- const rawLength = readProperty(value, "length");
1745
+ const rawLength = readProperty2(value, "length");
1678
1746
  const length = typeof rawLength === "number" && NumberIsFinite(rawLength) && rawLength >= 0 ? MathFloor(rawLength) : 0;
1679
1747
  let size = 2;
1680
1748
  for (let i = 0; i < length; i++) {
1681
1749
  if (i > 0) size += 1;
1682
- let elementSize = estimateSerializedSize(readProperty(value, i), maxBytes, depth + 1, maxDepth, currentPath);
1750
+ let elementSize = estimateSerializedSize(readProperty2(value, i), maxBytes, depth + 1, maxDepth, currentPath);
1683
1751
  if (elementSize === 0) elementSize = 4;
1684
1752
  size += elementSize;
1685
1753
  if (maxBytes > 0 && size > maxBytes) {
@@ -1772,7 +1840,7 @@ function estimateSerializedSize(value, maxBytes = 0, depth = 0, maxDepth = 2e3,
1772
1840
  }
1773
1841
  return 0;
1774
1842
  }
1775
- function readProperty(target, key) {
1843
+ function readProperty2(target, key) {
1776
1844
  try {
1777
1845
  return ReflectGet(target, key);
1778
1846
  } catch {
@@ -3280,6 +3348,7 @@ var InterpreterAdapter = class {
3280
3348
  instanceChecks: safe.instanceChecks,
3281
3349
  maxSteps: this.options.maxSteps ?? DEFAULT_MAX_STEPS,
3282
3350
  maxCallDepth: this.options.maxCallDepth ?? DEFAULT_MAX_CALL_DEPTH,
3351
+ maxPendingCalls: this.options.maxPendingCalls,
3283
3352
  signal: context.abortController.signal,
3284
3353
  charge
3285
3354
  });