scriptable 0.1.0 → 0.2.0

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/src/evaluate.ts CHANGED
@@ -1,6 +1,5 @@
1
1
  import type { Node } from "acorn";
2
2
  import binaryOps from "./binary-ops.js";
3
- import logicOps from "./logic-ops.js";
4
3
  import type Environment from "./environment.js";
5
4
  import type { FunctionMap } from "./builtin-functions.js";
6
5
 
@@ -24,31 +23,67 @@ function assertSafeProperty(prop: string): void {
24
23
  }
25
24
  }
26
25
 
27
- // Execution step counter — reset via resetStepCounter() before each run.
28
- let _steps = 0;
29
- let _maxSteps = 0;
30
-
31
- export function resetStepCounter(maxSteps: number): void {
32
- _steps = 0;
33
- _maxSteps = maxSteps;
26
+ // Sentinel thrown by ReturnStatement and caught at the nearest function
27
+ // boundary (makeFunc). Without this, a `return` nested inside an `if` (or
28
+ // any non-ReturnStatement node) would be evaluated but the enclosing
29
+ // BlockStatement would keep iterating the remaining statements — so
30
+ // `function f(n) { if (n==0) return 1; f(0); return n; }` would fall
31
+ // through to `f(0)` after the guarded return and recurse forever.
32
+ class ReturnValue {
33
+ constructor(public value: any) {}
34
34
  }
35
35
 
36
36
  function loc(exp: AnyNode) {
37
37
  return exp.loc!.start;
38
38
  }
39
39
 
40
+ // Resolve an LHS or callee expression to an array of path segments. Used by
41
+ // AssignmentExpression target and CallExpression callee. Unlike full
42
+ // evaluation, this walks Identifier → name and stitches member accesses into
43
+ // a segment list; but it *does* evaluate the key of a computed member
44
+ // (`a[k]`) in the runtime env so the path reflects the actual property being
45
+ // addressed. Returning segments (not a dotted string) keeps dot-containing
46
+ // keys like `a["x.y"]` as a single segment — a dotted string would be
47
+ // re-split on the way through deepSet and write to `a.x.y` instead.
48
+ function evalAsPath(
49
+ exp: AnyNode,
50
+ env: Environment,
51
+ functions: FunctionMap
52
+ ): string[] {
53
+ if (exp.type === "Identifier") return [exp.name];
54
+ if (exp.type === "Literal") return [String(exp.value)];
55
+ if (exp.type === "MemberExpression") {
56
+ const objParts = evalAsPath(exp.object, env, functions);
57
+ const propStr = exp.computed
58
+ ? String(evaluate(exp.property, env, functions))
59
+ : String((exp.property as AnyNode).name);
60
+ assertSafeProperty(propStr);
61
+ return [...objParts, propStr];
62
+ }
63
+ throw new Error("Cannot evaluate " + exp.type + " as assignment target");
64
+ }
65
+
40
66
  function makeFunc(
41
67
  params: string[],
42
68
  body: AnyNode,
43
69
  env: Environment,
44
70
  functions: FunctionMap
45
71
  ) {
46
- const scope = env.extend();
72
+ // Fresh scope per invocation — a scope hoisted to closure creation time was
73
+ // shared across every call, so recursion overwrote the caller's params and
74
+ // any let/const it had set on the function scope. `env` is the closure's
75
+ // captured lexical parent; extend it anew on every call.
47
76
  return (...args: any[]) => {
77
+ const scope = env.extend();
48
78
  params.forEach((param, idx) => {
49
- scope.def(param, idx < args.length ? args[idx] : false);
79
+ scope.def([param], idx < args.length ? args[idx] : false);
50
80
  });
51
- return evaluate(body, scope, functions);
81
+ try {
82
+ return evaluate(body, scope, functions);
83
+ } catch (err) {
84
+ if (err instanceof ReturnValue) return err.value;
85
+ throw err;
86
+ }
52
87
  };
53
88
  }
54
89
 
@@ -66,7 +101,13 @@ const evals: Record<
66
101
  for (const el of exp.elements) {
67
102
  if (el && el.type === "SpreadElement") {
68
103
  const spread = evaluate(el.argument, env, functions);
69
- result.push(...spread);
104
+ // Check projected length before growing. push(...spread) hits V8's
105
+ // argument-stack limit (~65K) well below maxAllocSize, so enforce here
106
+ // and grow via a loop instead.
107
+ const addLen =
108
+ spread && typeof spread.length === "number" ? spread.length : 0;
109
+ env.runtime.checkLength(result.length + addLen);
110
+ for (const item of spread) result.push(item);
70
111
  } else if (el) {
71
112
  result.push(evaluate(el, env, functions));
72
113
  }
@@ -75,8 +116,31 @@ const evals: Record<
75
116
  },
76
117
 
77
118
  AssignmentExpression(exp, env, functions) {
78
- const target = evaluate(exp.left);
79
- return env.set(target, evaluate(exp.right, env, functions), loc(exp));
119
+ // Previously the operator was ignored, so `a += 1` silently behaved as
120
+ // `a = 1`. Compound ops now read the current value, combine with the rhs
121
+ // via the matching binary op, and write back. Logical compounds
122
+ // (`||=`, `&&=`, `??=`) short-circuit: rhs is only evaluated and written
123
+ // when the gate condition holds.
124
+ const target = evalAsPath(exp.left, env, functions);
125
+ if (exp.operator === "=") {
126
+ return env.set(target, evaluate(exp.right, env, functions), loc(exp));
127
+ }
128
+ const current = env.get(target, loc(exp));
129
+ if (exp.operator === "||=") {
130
+ return current || env.set(target, evaluate(exp.right, env, functions), loc(exp));
131
+ }
132
+ if (exp.operator === "&&=") {
133
+ return current && env.set(target, evaluate(exp.right, env, functions), loc(exp));
134
+ }
135
+ if (exp.operator === "??=") {
136
+ return current ?? env.set(target, evaluate(exp.right, env, functions), loc(exp));
137
+ }
138
+ const op = exp.operator.slice(0, -1);
139
+ if (!binaryOps[op]) {
140
+ throw new Error(`Unsupported assignment operator: ${exp.operator}`);
141
+ }
142
+ const rhs = evaluate(exp.right, env, functions);
143
+ return env.set(target, binaryOps[op](current, rhs), loc(exp));
80
144
  },
81
145
 
82
146
  BinaryExpression(exp, env, functions) {
@@ -90,39 +154,60 @@ const evals: Record<
90
154
  let result;
91
155
  for (const part of exp.body) {
92
156
  result = evaluate(part, scope, functions);
93
- if (part.type === "ReturnStatement") {
94
- break;
95
- }
96
157
  }
97
158
  return result;
98
159
  },
99
160
 
100
161
  CallExpression(exp, env, functions) {
101
- const func = evaluate(exp.callee);
162
+ // Path-based resolution for static callees (Identifier / MemberExpression)
163
+ // lets us look up builtins in the `functions` map and dotted-path names in
164
+ // env. For dynamic callees (e.g. `f()()`, `(() => 1)()`), evaluate the
165
+ // callee as a value and call it directly if it's a function.
166
+ let fn: Function | undefined;
167
+ let name: string | undefined;
168
+ if (
169
+ exp.callee.type === "Identifier" ||
170
+ exp.callee.type === "MemberExpression"
171
+ ) {
172
+ const path = evalAsPath(exp.callee, env, functions);
173
+ name = path.join(".");
174
+ // hasOwn, not `functions[name]`: a plain-object `functions` map inherits
175
+ // from Object.prototype, so `functions["constructor"]` would resolve to
176
+ // `Object`, `functions["toString"]` to `Object.prototype.toString`, etc.
177
+ // Not directly exploitable today (returned wrappers can't reach blocked
178
+ // props) but a foot-gun the moment a builtin shares a name with an
179
+ // Object.prototype member.
180
+ if (Object.prototype.hasOwnProperty.call(functions, name)) {
181
+ fn = functions[name];
182
+ } else if (env.defined(path)) {
183
+ const value = env.get(path, loc(exp));
184
+ if (typeof value === "function") fn = value;
185
+ }
186
+ } else {
187
+ const value = evaluate(exp.callee, env, functions);
188
+ if (typeof value === "function") fn = value;
189
+ }
102
190
 
103
- // Collect args, handling spread
191
+ // Collect args, handling spread. Same V8 argument-stack consideration
192
+ // as ArrayExpression — cap projected length and grow via a loop.
104
193
  const args: any[] = [];
105
194
  for (const arg of exp.arguments) {
106
195
  if (arg.type === "SpreadElement") {
107
196
  const spread = evaluate(arg.argument, env, functions);
108
- args.push(...spread);
197
+ const addLen =
198
+ spread && typeof spread.length === "number" ? spread.length : 0;
199
+ env.runtime.checkLength(args.length + addLen);
200
+ for (const item of spread) args.push(item);
109
201
  } else {
110
202
  args.push(evaluate(arg, env, functions));
111
203
  }
112
204
  }
113
205
 
114
- if (functions[func]) {
115
- return functions[func](...args);
116
- }
117
-
118
- if (env.defined(func)) {
119
- const customFunc = env.get(func, loc(exp));
120
- if (typeof customFunc === "function") {
121
- return customFunc(...args);
122
- }
123
- }
206
+ if (fn) return fn(...args);
124
207
  const l = loc(exp);
125
- throw new Error(`${func} is not a function (${l.line}:${l.column})`);
208
+ throw new Error(
209
+ `${name ?? exp.callee.type} is not a function (${l.line}:${l.column})`
210
+ );
126
211
  },
127
212
 
128
213
  ConditionalExpression(exp, env, functions) {
@@ -139,12 +224,12 @@ const evals: Record<
139
224
  FunctionDeclaration(exp, env, functions) {
140
225
  const name = evaluate(exp.id);
141
226
  const params = exp.params.map((param: AnyNode) => evaluate(param));
142
- env.set(name, makeFunc(params, exp.body, env, functions), loc(exp));
227
+ env.set([name], makeFunc(params, exp.body, env, functions), loc(exp));
143
228
  },
144
229
 
145
230
  Identifier(exp, env) {
146
231
  if (env) {
147
- return env.get(exp.name, loc(exp));
232
+ return env.get([exp.name], loc(exp));
148
233
  }
149
234
  return exp.name;
150
235
  },
@@ -164,18 +249,23 @@ const evals: Record<
164
249
  },
165
250
 
166
251
  LogicalExpression(exp, env, functions) {
252
+ // Short-circuit: `a || b` must not evaluate `b` when `a` is truthy, and
253
+ // `a && b` must not evaluate `b` when `a` is falsy. Previously both sides
254
+ // were evaluated eagerly, which broke the common `guard && action` idiom.
167
255
  const left = evaluate(exp.left, env, functions);
168
- const right = evaluate(exp.right, env, functions);
169
- return logicOps[exp.operator](left, right);
256
+ switch (exp.operator) {
257
+ case "||":
258
+ return left || evaluate(exp.right, env, functions);
259
+ case "&&":
260
+ return left && evaluate(exp.right, env, functions);
261
+ case "??":
262
+ return left ?? evaluate(exp.right, env, functions);
263
+ default:
264
+ throw new Error(`Unsupported logical operator: ${exp.operator}`);
265
+ }
170
266
  },
171
267
 
172
268
  MemberExpression(exp, env, functions) {
173
- if (!env) {
174
- const obj = evaluate(exp.object);
175
- const prop = evaluate(exp.property);
176
- assertSafeProperty(prop);
177
- return `${obj}.${prop}`;
178
- }
179
269
  const obj = evaluate(exp.object, env, functions);
180
270
  if (exp.computed) {
181
271
  const prop = evaluate(exp.property, env, functions);
@@ -189,14 +279,53 @@ const evals: Record<
189
279
 
190
280
  ObjectExpression(exp, env, functions) {
191
281
  const result: Record<string, any> = {};
282
+ // Track own-key count so we can bound via checkLength without an O(N)
283
+ // Object.keys(result).length call on every iteration.
284
+ let ownCount = 0;
192
285
  for (const prop of exp.properties) {
193
286
  if (prop.type === "SpreadElement") {
194
287
  const spread = evaluate(prop.argument, env, functions);
195
- Object.assign(result, spread);
288
+ // Object.assign invokes setters, which includes Object.prototype's
289
+ // __proto__ setter when source has own __proto__. Copy own enumerable
290
+ // keys manually and drop blocked keys so a spread can't set the
291
+ // prototype of result or plant a booby-trapped own "constructor".
292
+ if (spread != null && typeof spread === "object") {
293
+ const keys = Object.keys(spread);
294
+ // Project before writing: `reduce(arr, (a,k) => ({...a,[k]:k}), {})`
295
+ // grows the accumulator by one key per step and would otherwise run
296
+ // until maxSteps exhausts, leaving a maxSteps-sized object behind.
297
+ env.runtime.checkLength(ownCount + keys.length);
298
+ for (const key of keys) {
299
+ if (!BLOCKED_PROPS.has(key)) {
300
+ if (!Object.prototype.hasOwnProperty.call(result, key)) {
301
+ ownCount++;
302
+ }
303
+ result[key] = (spread as Record<string, any>)[key];
304
+ }
305
+ }
306
+ }
196
307
  } else {
197
- // Property — key can be Identifier or Literal
198
- const key =
199
- prop.key.type === "Identifier" ? prop.key.name : prop.key.value;
308
+ // Property — non-computed keys are Identifier (shorthand/name) or
309
+ // Literal; computed keys (`{[expr]: v}`) require evaluating the
310
+ // expression. The previous code ignored `computed`, so `{[k]: v}`
311
+ // silently used the identifier NAME "k" instead of its value.
312
+ let key: string;
313
+ if (prop.computed) {
314
+ key = String(evaluate(prop.key, env, functions));
315
+ } else if (prop.key.type === "Identifier") {
316
+ key = prop.key.name;
317
+ } else {
318
+ key = String(prop.key.value);
319
+ }
320
+ // Block "__proto__", "constructor", etc. as keys so user code can't
321
+ // set the prototype of a fresh object via literal syntax, and so an
322
+ // object leaving the sandbox can't carry a booby-trapped "constructor"
323
+ // into the caller's scope.
324
+ assertSafeProperty(key);
325
+ if (!Object.prototype.hasOwnProperty.call(result, key)) {
326
+ env.runtime.checkLength(ownCount + 1);
327
+ ownCount++;
328
+ }
200
329
  result[key] = evaluate(prop.value, env, functions);
201
330
  }
202
331
  }
@@ -212,7 +341,11 @@ const evals: Record<
212
341
  },
213
342
 
214
343
  ReturnStatement(exp, env, functions) {
215
- return evaluate(exp.argument, env, functions);
344
+ // Throw a sentinel so control unwinds to the nearest function boundary
345
+ // regardless of which nested construct (if/block/etc.) contains the return.
346
+ throw new ReturnValue(
347
+ exp.argument ? evaluate(exp.argument, env, functions) : undefined
348
+ );
216
349
  },
217
350
 
218
351
  TemplateLiteral(exp, env, functions) {
@@ -258,16 +391,22 @@ const evals: Record<
258
391
  VariableDeclarator(exp, env, functions) {
259
392
  const name = evaluate(exp.id);
260
393
  const value = exp.init ? evaluate(exp.init, env, functions) : undefined;
261
- return env.def(name, value);
394
+ return env.def([name], value);
262
395
  },
263
396
  };
264
397
 
265
398
  function evaluate(exp: AnyNode, env?: any, functions?: any): any {
266
- if (_maxSteps > 0 && ++_steps > _maxSteps) {
267
- throw new Error("Execution limit exceeded");
268
- }
399
+ // env is absent when we're resolving a static path (AssignmentExpression
400
+ // target, CallExpression callee, function/variable names, params). Those
401
+ // branches don't execute user code, so the counter only needs to run here.
402
+ if (env) env.runtime.step();
269
403
  if (evals[exp.type]) {
270
- return evals[exp.type](exp, env, functions);
404
+ const result = evals[exp.type](exp, env, functions);
405
+ // checkSize inspects strings and arrays; other return types are no-ops.
406
+ // Covers both interpreter-built values (BinaryExpression +, TemplateLiteral,
407
+ // ArrayExpression) and builtin results (CallExpression).
408
+ if (env) env.runtime.checkSize(result);
409
+ return result;
271
410
  }
272
411
  throw new Error("Cannot evaluate " + exp.type);
273
412
  }
package/src/index.ts CHANGED
@@ -1,8 +1,8 @@
1
1
  import * as acorn from "acorn";
2
- import evaluate, { resetStepCounter } from "./evaluate.js";
2
+ import evaluate from "./evaluate.js";
3
3
  import builtinFuncs from "./builtin-functions.js";
4
4
  import type { FunctionMap } from "./builtin-functions.js";
5
- import Environment from "./environment.js";
5
+ import Environment, { Runtime } from "./environment.js";
6
6
 
7
7
  function parse(code: string) {
8
8
  return acorn.parse(code, {
@@ -15,6 +15,31 @@ function parse(code: string) {
15
15
  export interface RunnerOptions {
16
16
  functions?: FunctionMap;
17
17
  maxSteps?: number;
18
+ /**
19
+ * Maximum length (in UTF-16 code units) of the source string. The step
20
+ * counter only bounds execution; parsing a multi-megabyte string still
21
+ * consumes proportional CPU and memory inside acorn before the interpreter
22
+ * runs. Set to 0 to disable. Defaults to 64 KiB.
23
+ */
24
+ maxCodeSize?: number;
25
+ /**
26
+ * Maximum length of any string or array value produced during a run, and
27
+ * maximum key count of any object literal. String concatenation, array
28
+ * spread, and object spread-accumulation can grow exponentially in a handful
29
+ * of steps, well within the step budget. Set to 0 to disable. Defaults to
30
+ * 1,000,000 (strings ≤ 1M UTF-16 units ≈ 2 MB; arrays ≤ 1M elements;
31
+ * objects ≤ 1M keys).
32
+ */
33
+ maxAllocSize?: number;
34
+ /**
35
+ * Maximum wall-clock duration of a single run, in milliseconds. Checked
36
+ * between interpreter steps — a single long native builtin call (e.g.
37
+ * `sort` on a large array) can overshoot the deadline by up to its own
38
+ * duration, but subsequent interpreter work is rejected. Set to 0 to
39
+ * disable. Defaults to 0 (disabled); set to a positive value for hostile
40
+ * multi-tenant workloads.
41
+ */
42
+ maxDurationMs?: number;
18
43
  }
19
44
 
20
45
  export interface RunResult {
@@ -23,20 +48,36 @@ export interface RunResult {
23
48
  }
24
49
 
25
50
  const DEFAULT_MAX_STEPS = 100_000;
51
+ const DEFAULT_MAX_CODE_SIZE = 64 * 1024;
52
+ const DEFAULT_MAX_ALLOC_SIZE = 1_000_000;
53
+ const DEFAULT_MAX_DURATION_MS = 0;
26
54
 
27
- export default function runner({ functions = builtinFuncs, maxSteps = DEFAULT_MAX_STEPS }: RunnerOptions = {}) {
55
+ export default function runner({
56
+ functions = builtinFuncs,
57
+ maxSteps = DEFAULT_MAX_STEPS,
58
+ maxCodeSize = DEFAULT_MAX_CODE_SIZE,
59
+ maxAllocSize = DEFAULT_MAX_ALLOC_SIZE,
60
+ maxDurationMs = DEFAULT_MAX_DURATION_MS,
61
+ }: RunnerOptions = {}) {
28
62
  return (code: string, env: Record<string, any> = {}, debug?: boolean): RunResult => {
63
+ if (maxCodeSize > 0 && code.length > maxCodeSize) {
64
+ throw new Error(
65
+ `Source exceeds maxCodeSize (${code.length} > ${maxCodeSize})`
66
+ );
67
+ }
29
68
  const ast = parse(code);
30
69
  debug && console.log(JSON.stringify(ast.body, null, 2));
31
- resetStepCounter(maxSteps);
32
- const globalEnv = new Environment();
70
+ const globalEnv = new Environment(
71
+ undefined,
72
+ new Runtime(maxSteps, maxAllocSize, maxDurationMs)
73
+ );
33
74
  Object.keys(env).forEach((key) => {
34
- globalEnv.def(key, env[key]);
75
+ globalEnv.def([key], env[key]);
35
76
  });
36
77
  const result = evaluate(ast, globalEnv, functions);
37
78
  return { result, env: globalEnv.vars };
38
79
  };
39
80
  }
40
81
 
41
- export { Environment };
82
+ export { Environment, Runtime };
42
83
  export type { FunctionMap };
@@ -1,10 +0,0 @@
1
- {
2
- "permissions": {
3
- "allow": [
4
- "Bash(npx vitest:*)",
5
- "Bash(pnpm test:*)",
6
- "WebSearch",
7
- "Bash(git push:*)"
8
- ]
9
- }
10
- }
@@ -1,2 +0,0 @@
1
- declare const logicOps: Record<string, (l: unknown, r: unknown) => unknown>;
2
- export default logicOps;
package/dist/logic-ops.js DELETED
@@ -1,5 +0,0 @@
1
- const logicOps = {
2
- "||": (l, r) => l || r,
3
- "&&": (l, r) => l && r,
4
- };
5
- export default logicOps;
package/src/logic-ops.ts DELETED
@@ -1,6 +0,0 @@
1
- const logicOps: Record<string, (l: unknown, r: unknown) => unknown> = {
2
- "||": (l: any, r: any) => l || r,
3
- "&&": (l: any, r: any) => l && r,
4
- };
5
-
6
- export default logicOps;