scriptable 0.1.1 → 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/CHANGELOG.md +28 -0
- package/README.md +13 -0
- package/SECURITY_FIXES.md +81 -0
- package/dist/environment.d.ts +16 -5
- package/dist/environment.js +83 -35
- package/dist/evaluate.d.ts +0 -1
- package/dist/evaluate.js +194 -48
- package/dist/index.d.ts +28 -3
- package/dist/index.js +12 -7
- package/package.json +2 -2
- package/src/__tests__/audit-followups.test.ts +206 -0
- package/src/__tests__/security.test.ts +391 -0
- package/src/__tests__/semantic-fixes.test.ts +171 -0
- package/src/environment.ts +97 -37
- package/src/evaluate.ts +190 -51
- package/src/index.ts +48 -7
- package/dist/logic-ops.d.ts +0 -2
- package/dist/logic-ops.js +0 -5
- package/src/logic-ops.ts +0 -6
package/dist/evaluate.js
CHANGED
|
@@ -1,5 +1,4 @@
|
|
|
1
1
|
import binaryOps from "./binary-ops.js";
|
|
2
|
-
import logicOps from "./logic-ops.js";
|
|
3
2
|
// Properties that enable sandbox escape (prototype chain → Function constructor)
|
|
4
3
|
// or prototype pollution. Blocked in both MemberExpression and deep path access.
|
|
5
4
|
const BLOCKED_PROPS = new Set([
|
|
@@ -16,23 +15,61 @@ function assertSafeProperty(prop) {
|
|
|
16
15
|
throw new Error(`Access to property '${prop}' is not allowed`);
|
|
17
16
|
}
|
|
18
17
|
}
|
|
19
|
-
//
|
|
20
|
-
|
|
21
|
-
|
|
22
|
-
|
|
23
|
-
|
|
24
|
-
|
|
18
|
+
// Sentinel thrown by ReturnStatement and caught at the nearest function
|
|
19
|
+
// boundary (makeFunc). Without this, a `return` nested inside an `if` (or
|
|
20
|
+
// any non-ReturnStatement node) would be evaluated but the enclosing
|
|
21
|
+
// BlockStatement would keep iterating the remaining statements — so
|
|
22
|
+
// `function f(n) { if (n==0) return 1; f(0); return n; }` would fall
|
|
23
|
+
// through to `f(0)` after the guarded return and recurse forever.
|
|
24
|
+
class ReturnValue {
|
|
25
|
+
constructor(value) {
|
|
26
|
+
this.value = value;
|
|
27
|
+
}
|
|
25
28
|
}
|
|
26
29
|
function loc(exp) {
|
|
27
30
|
return exp.loc.start;
|
|
28
31
|
}
|
|
32
|
+
// Resolve an LHS or callee expression to an array of path segments. Used by
|
|
33
|
+
// AssignmentExpression target and CallExpression callee. Unlike full
|
|
34
|
+
// evaluation, this walks Identifier → name and stitches member accesses into
|
|
35
|
+
// a segment list; but it *does* evaluate the key of a computed member
|
|
36
|
+
// (`a[k]`) in the runtime env so the path reflects the actual property being
|
|
37
|
+
// addressed. Returning segments (not a dotted string) keeps dot-containing
|
|
38
|
+
// keys like `a["x.y"]` as a single segment — a dotted string would be
|
|
39
|
+
// re-split on the way through deepSet and write to `a.x.y` instead.
|
|
40
|
+
function evalAsPath(exp, env, functions) {
|
|
41
|
+
if (exp.type === "Identifier")
|
|
42
|
+
return [exp.name];
|
|
43
|
+
if (exp.type === "Literal")
|
|
44
|
+
return [String(exp.value)];
|
|
45
|
+
if (exp.type === "MemberExpression") {
|
|
46
|
+
const objParts = evalAsPath(exp.object, env, functions);
|
|
47
|
+
const propStr = exp.computed
|
|
48
|
+
? String(evaluate(exp.property, env, functions))
|
|
49
|
+
: String(exp.property.name);
|
|
50
|
+
assertSafeProperty(propStr);
|
|
51
|
+
return [...objParts, propStr];
|
|
52
|
+
}
|
|
53
|
+
throw new Error("Cannot evaluate " + exp.type + " as assignment target");
|
|
54
|
+
}
|
|
29
55
|
function makeFunc(params, body, env, functions) {
|
|
30
|
-
|
|
56
|
+
// Fresh scope per invocation — a scope hoisted to closure creation time was
|
|
57
|
+
// shared across every call, so recursion overwrote the caller's params and
|
|
58
|
+
// any let/const it had set on the function scope. `env` is the closure's
|
|
59
|
+
// captured lexical parent; extend it anew on every call.
|
|
31
60
|
return (...args) => {
|
|
61
|
+
const scope = env.extend();
|
|
32
62
|
params.forEach((param, idx) => {
|
|
33
|
-
scope.def(param, idx < args.length ? args[idx] : false);
|
|
63
|
+
scope.def([param], idx < args.length ? args[idx] : false);
|
|
34
64
|
});
|
|
35
|
-
|
|
65
|
+
try {
|
|
66
|
+
return evaluate(body, scope, functions);
|
|
67
|
+
}
|
|
68
|
+
catch (err) {
|
|
69
|
+
if (err instanceof ReturnValue)
|
|
70
|
+
return err.value;
|
|
71
|
+
throw err;
|
|
72
|
+
}
|
|
36
73
|
};
|
|
37
74
|
}
|
|
38
75
|
const evals = {
|
|
@@ -45,7 +82,13 @@ const evals = {
|
|
|
45
82
|
for (const el of exp.elements) {
|
|
46
83
|
if (el && el.type === "SpreadElement") {
|
|
47
84
|
const spread = evaluate(el.argument, env, functions);
|
|
48
|
-
|
|
85
|
+
// Check projected length before growing. push(...spread) hits V8's
|
|
86
|
+
// argument-stack limit (~65K) well below maxAllocSize, so enforce here
|
|
87
|
+
// and grow via a loop instead.
|
|
88
|
+
const addLen = spread && typeof spread.length === "number" ? spread.length : 0;
|
|
89
|
+
env.runtime.checkLength(result.length + addLen);
|
|
90
|
+
for (const item of spread)
|
|
91
|
+
result.push(item);
|
|
49
92
|
}
|
|
50
93
|
else if (el) {
|
|
51
94
|
result.push(evaluate(el, env, functions));
|
|
@@ -54,8 +97,31 @@ const evals = {
|
|
|
54
97
|
return result;
|
|
55
98
|
},
|
|
56
99
|
AssignmentExpression(exp, env, functions) {
|
|
57
|
-
|
|
58
|
-
|
|
100
|
+
// Previously the operator was ignored, so `a += 1` silently behaved as
|
|
101
|
+
// `a = 1`. Compound ops now read the current value, combine with the rhs
|
|
102
|
+
// via the matching binary op, and write back. Logical compounds
|
|
103
|
+
// (`||=`, `&&=`, `??=`) short-circuit: rhs is only evaluated and written
|
|
104
|
+
// when the gate condition holds.
|
|
105
|
+
const target = evalAsPath(exp.left, env, functions);
|
|
106
|
+
if (exp.operator === "=") {
|
|
107
|
+
return env.set(target, evaluate(exp.right, env, functions), loc(exp));
|
|
108
|
+
}
|
|
109
|
+
const current = env.get(target, loc(exp));
|
|
110
|
+
if (exp.operator === "||=") {
|
|
111
|
+
return current || env.set(target, evaluate(exp.right, env, functions), loc(exp));
|
|
112
|
+
}
|
|
113
|
+
if (exp.operator === "&&=") {
|
|
114
|
+
return current && env.set(target, evaluate(exp.right, env, functions), loc(exp));
|
|
115
|
+
}
|
|
116
|
+
if (exp.operator === "??=") {
|
|
117
|
+
return current ?? env.set(target, evaluate(exp.right, env, functions), loc(exp));
|
|
118
|
+
}
|
|
119
|
+
const op = exp.operator.slice(0, -1);
|
|
120
|
+
if (!binaryOps[op]) {
|
|
121
|
+
throw new Error(`Unsupported assignment operator: ${exp.operator}`);
|
|
122
|
+
}
|
|
123
|
+
const rhs = evaluate(exp.right, env, functions);
|
|
124
|
+
return env.set(target, binaryOps[op](current, rhs), loc(exp));
|
|
59
125
|
},
|
|
60
126
|
BinaryExpression(exp, env, functions) {
|
|
61
127
|
const left = evaluate(exp.left, env, functions);
|
|
@@ -67,36 +133,59 @@ const evals = {
|
|
|
67
133
|
let result;
|
|
68
134
|
for (const part of exp.body) {
|
|
69
135
|
result = evaluate(part, scope, functions);
|
|
70
|
-
if (part.type === "ReturnStatement") {
|
|
71
|
-
break;
|
|
72
|
-
}
|
|
73
136
|
}
|
|
74
137
|
return result;
|
|
75
138
|
},
|
|
76
139
|
CallExpression(exp, env, functions) {
|
|
77
|
-
|
|
78
|
-
//
|
|
140
|
+
// Path-based resolution for static callees (Identifier / MemberExpression)
|
|
141
|
+
// lets us look up builtins in the `functions` map and dotted-path names in
|
|
142
|
+
// env. For dynamic callees (e.g. `f()()`, `(() => 1)()`), evaluate the
|
|
143
|
+
// callee as a value and call it directly if it's a function.
|
|
144
|
+
let fn;
|
|
145
|
+
let name;
|
|
146
|
+
if (exp.callee.type === "Identifier" ||
|
|
147
|
+
exp.callee.type === "MemberExpression") {
|
|
148
|
+
const path = evalAsPath(exp.callee, env, functions);
|
|
149
|
+
name = path.join(".");
|
|
150
|
+
// hasOwn, not `functions[name]`: a plain-object `functions` map inherits
|
|
151
|
+
// from Object.prototype, so `functions["constructor"]` would resolve to
|
|
152
|
+
// `Object`, `functions["toString"]` to `Object.prototype.toString`, etc.
|
|
153
|
+
// Not directly exploitable today (returned wrappers can't reach blocked
|
|
154
|
+
// props) but a foot-gun the moment a builtin shares a name with an
|
|
155
|
+
// Object.prototype member.
|
|
156
|
+
if (Object.prototype.hasOwnProperty.call(functions, name)) {
|
|
157
|
+
fn = functions[name];
|
|
158
|
+
}
|
|
159
|
+
else if (env.defined(path)) {
|
|
160
|
+
const value = env.get(path, loc(exp));
|
|
161
|
+
if (typeof value === "function")
|
|
162
|
+
fn = value;
|
|
163
|
+
}
|
|
164
|
+
}
|
|
165
|
+
else {
|
|
166
|
+
const value = evaluate(exp.callee, env, functions);
|
|
167
|
+
if (typeof value === "function")
|
|
168
|
+
fn = value;
|
|
169
|
+
}
|
|
170
|
+
// Collect args, handling spread. Same V8 argument-stack consideration
|
|
171
|
+
// as ArrayExpression — cap projected length and grow via a loop.
|
|
79
172
|
const args = [];
|
|
80
173
|
for (const arg of exp.arguments) {
|
|
81
174
|
if (arg.type === "SpreadElement") {
|
|
82
175
|
const spread = evaluate(arg.argument, env, functions);
|
|
83
|
-
|
|
176
|
+
const addLen = spread && typeof spread.length === "number" ? spread.length : 0;
|
|
177
|
+
env.runtime.checkLength(args.length + addLen);
|
|
178
|
+
for (const item of spread)
|
|
179
|
+
args.push(item);
|
|
84
180
|
}
|
|
85
181
|
else {
|
|
86
182
|
args.push(evaluate(arg, env, functions));
|
|
87
183
|
}
|
|
88
184
|
}
|
|
89
|
-
if (
|
|
90
|
-
return
|
|
91
|
-
}
|
|
92
|
-
if (env.defined(func)) {
|
|
93
|
-
const customFunc = env.get(func, loc(exp));
|
|
94
|
-
if (typeof customFunc === "function") {
|
|
95
|
-
return customFunc(...args);
|
|
96
|
-
}
|
|
97
|
-
}
|
|
185
|
+
if (fn)
|
|
186
|
+
return fn(...args);
|
|
98
187
|
const l = loc(exp);
|
|
99
|
-
throw new Error(`${
|
|
188
|
+
throw new Error(`${name ?? exp.callee.type} is not a function (${l.line}:${l.column})`);
|
|
100
189
|
},
|
|
101
190
|
ConditionalExpression(exp, env, functions) {
|
|
102
191
|
const test = evaluate(exp.test, env, functions);
|
|
@@ -110,11 +199,11 @@ const evals = {
|
|
|
110
199
|
FunctionDeclaration(exp, env, functions) {
|
|
111
200
|
const name = evaluate(exp.id);
|
|
112
201
|
const params = exp.params.map((param) => evaluate(param));
|
|
113
|
-
env.set(name, makeFunc(params, exp.body, env, functions), loc(exp));
|
|
202
|
+
env.set([name], makeFunc(params, exp.body, env, functions), loc(exp));
|
|
114
203
|
},
|
|
115
204
|
Identifier(exp, env) {
|
|
116
205
|
if (env) {
|
|
117
|
-
return env.get(exp.name, loc(exp));
|
|
206
|
+
return env.get([exp.name], loc(exp));
|
|
118
207
|
}
|
|
119
208
|
return exp.name;
|
|
120
209
|
},
|
|
@@ -131,17 +220,22 @@ const evals = {
|
|
|
131
220
|
return exp.value;
|
|
132
221
|
},
|
|
133
222
|
LogicalExpression(exp, env, functions) {
|
|
223
|
+
// Short-circuit: `a || b` must not evaluate `b` when `a` is truthy, and
|
|
224
|
+
// `a && b` must not evaluate `b` when `a` is falsy. Previously both sides
|
|
225
|
+
// were evaluated eagerly, which broke the common `guard && action` idiom.
|
|
134
226
|
const left = evaluate(exp.left, env, functions);
|
|
135
|
-
|
|
136
|
-
|
|
227
|
+
switch (exp.operator) {
|
|
228
|
+
case "||":
|
|
229
|
+
return left || evaluate(exp.right, env, functions);
|
|
230
|
+
case "&&":
|
|
231
|
+
return left && evaluate(exp.right, env, functions);
|
|
232
|
+
case "??":
|
|
233
|
+
return left ?? evaluate(exp.right, env, functions);
|
|
234
|
+
default:
|
|
235
|
+
throw new Error(`Unsupported logical operator: ${exp.operator}`);
|
|
236
|
+
}
|
|
137
237
|
},
|
|
138
238
|
MemberExpression(exp, env, functions) {
|
|
139
|
-
if (!env) {
|
|
140
|
-
const obj = evaluate(exp.object);
|
|
141
|
-
const prop = evaluate(exp.property);
|
|
142
|
-
assertSafeProperty(prop);
|
|
143
|
-
return `${obj}.${prop}`;
|
|
144
|
-
}
|
|
145
239
|
const obj = evaluate(exp.object, env, functions);
|
|
146
240
|
if (exp.computed) {
|
|
147
241
|
const prop = evaluate(exp.property, env, functions);
|
|
@@ -154,14 +248,56 @@ const evals = {
|
|
|
154
248
|
},
|
|
155
249
|
ObjectExpression(exp, env, functions) {
|
|
156
250
|
const result = {};
|
|
251
|
+
// Track own-key count so we can bound via checkLength without an O(N)
|
|
252
|
+
// Object.keys(result).length call on every iteration.
|
|
253
|
+
let ownCount = 0;
|
|
157
254
|
for (const prop of exp.properties) {
|
|
158
255
|
if (prop.type === "SpreadElement") {
|
|
159
256
|
const spread = evaluate(prop.argument, env, functions);
|
|
160
|
-
Object.assign
|
|
257
|
+
// Object.assign invokes setters, which includes Object.prototype's
|
|
258
|
+
// __proto__ setter when source has own __proto__. Copy own enumerable
|
|
259
|
+
// keys manually and drop blocked keys so a spread can't set the
|
|
260
|
+
// prototype of result or plant a booby-trapped own "constructor".
|
|
261
|
+
if (spread != null && typeof spread === "object") {
|
|
262
|
+
const keys = Object.keys(spread);
|
|
263
|
+
// Project before writing: `reduce(arr, (a,k) => ({...a,[k]:k}), {})`
|
|
264
|
+
// grows the accumulator by one key per step and would otherwise run
|
|
265
|
+
// until maxSteps exhausts, leaving a maxSteps-sized object behind.
|
|
266
|
+
env.runtime.checkLength(ownCount + keys.length);
|
|
267
|
+
for (const key of keys) {
|
|
268
|
+
if (!BLOCKED_PROPS.has(key)) {
|
|
269
|
+
if (!Object.prototype.hasOwnProperty.call(result, key)) {
|
|
270
|
+
ownCount++;
|
|
271
|
+
}
|
|
272
|
+
result[key] = spread[key];
|
|
273
|
+
}
|
|
274
|
+
}
|
|
275
|
+
}
|
|
161
276
|
}
|
|
162
277
|
else {
|
|
163
|
-
// Property —
|
|
164
|
-
|
|
278
|
+
// Property — non-computed keys are Identifier (shorthand/name) or
|
|
279
|
+
// Literal; computed keys (`{[expr]: v}`) require evaluating the
|
|
280
|
+
// expression. The previous code ignored `computed`, so `{[k]: v}`
|
|
281
|
+
// silently used the identifier NAME "k" instead of its value.
|
|
282
|
+
let key;
|
|
283
|
+
if (prop.computed) {
|
|
284
|
+
key = String(evaluate(prop.key, env, functions));
|
|
285
|
+
}
|
|
286
|
+
else if (prop.key.type === "Identifier") {
|
|
287
|
+
key = prop.key.name;
|
|
288
|
+
}
|
|
289
|
+
else {
|
|
290
|
+
key = String(prop.key.value);
|
|
291
|
+
}
|
|
292
|
+
// Block "__proto__", "constructor", etc. as keys so user code can't
|
|
293
|
+
// set the prototype of a fresh object via literal syntax, and so an
|
|
294
|
+
// object leaving the sandbox can't carry a booby-trapped "constructor"
|
|
295
|
+
// into the caller's scope.
|
|
296
|
+
assertSafeProperty(key);
|
|
297
|
+
if (!Object.prototype.hasOwnProperty.call(result, key)) {
|
|
298
|
+
env.runtime.checkLength(ownCount + 1);
|
|
299
|
+
ownCount++;
|
|
300
|
+
}
|
|
165
301
|
result[key] = evaluate(prop.value, env, functions);
|
|
166
302
|
}
|
|
167
303
|
}
|
|
@@ -175,7 +311,9 @@ const evals = {
|
|
|
175
311
|
return result;
|
|
176
312
|
},
|
|
177
313
|
ReturnStatement(exp, env, functions) {
|
|
178
|
-
|
|
314
|
+
// Throw a sentinel so control unwinds to the nearest function boundary
|
|
315
|
+
// regardless of which nested construct (if/block/etc.) contains the return.
|
|
316
|
+
throw new ReturnValue(exp.argument ? evaluate(exp.argument, env, functions) : undefined);
|
|
179
317
|
},
|
|
180
318
|
TemplateLiteral(exp, env, functions) {
|
|
181
319
|
let result = "";
|
|
@@ -217,15 +355,23 @@ const evals = {
|
|
|
217
355
|
VariableDeclarator(exp, env, functions) {
|
|
218
356
|
const name = evaluate(exp.id);
|
|
219
357
|
const value = exp.init ? evaluate(exp.init, env, functions) : undefined;
|
|
220
|
-
return env.def(name, value);
|
|
358
|
+
return env.def([name], value);
|
|
221
359
|
},
|
|
222
360
|
};
|
|
223
361
|
function evaluate(exp, env, functions) {
|
|
224
|
-
|
|
225
|
-
|
|
226
|
-
|
|
362
|
+
// env is absent when we're resolving a static path (AssignmentExpression
|
|
363
|
+
// target, CallExpression callee, function/variable names, params). Those
|
|
364
|
+
// branches don't execute user code, so the counter only needs to run here.
|
|
365
|
+
if (env)
|
|
366
|
+
env.runtime.step();
|
|
227
367
|
if (evals[exp.type]) {
|
|
228
|
-
|
|
368
|
+
const result = evals[exp.type](exp, env, functions);
|
|
369
|
+
// checkSize inspects strings and arrays; other return types are no-ops.
|
|
370
|
+
// Covers both interpreter-built values (BinaryExpression +, TemplateLiteral,
|
|
371
|
+
// ArrayExpression) and builtin results (CallExpression).
|
|
372
|
+
if (env)
|
|
373
|
+
env.runtime.checkSize(result);
|
|
374
|
+
return result;
|
|
229
375
|
}
|
|
230
376
|
throw new Error("Cannot evaluate " + exp.type);
|
|
231
377
|
}
|
package/dist/index.d.ts
CHANGED
|
@@ -1,13 +1,38 @@
|
|
|
1
1
|
import type { FunctionMap } from "./builtin-functions.js";
|
|
2
|
-
import Environment from "./environment.js";
|
|
2
|
+
import Environment, { Runtime } from "./environment.js";
|
|
3
3
|
export interface RunnerOptions {
|
|
4
4
|
functions?: FunctionMap;
|
|
5
5
|
maxSteps?: number;
|
|
6
|
+
/**
|
|
7
|
+
* Maximum length (in UTF-16 code units) of the source string. The step
|
|
8
|
+
* counter only bounds execution; parsing a multi-megabyte string still
|
|
9
|
+
* consumes proportional CPU and memory inside acorn before the interpreter
|
|
10
|
+
* runs. Set to 0 to disable. Defaults to 64 KiB.
|
|
11
|
+
*/
|
|
12
|
+
maxCodeSize?: number;
|
|
13
|
+
/**
|
|
14
|
+
* Maximum length of any string or array value produced during a run, and
|
|
15
|
+
* maximum key count of any object literal. String concatenation, array
|
|
16
|
+
* spread, and object spread-accumulation can grow exponentially in a handful
|
|
17
|
+
* of steps, well within the step budget. Set to 0 to disable. Defaults to
|
|
18
|
+
* 1,000,000 (strings ≤ 1M UTF-16 units ≈ 2 MB; arrays ≤ 1M elements;
|
|
19
|
+
* objects ≤ 1M keys).
|
|
20
|
+
*/
|
|
21
|
+
maxAllocSize?: number;
|
|
22
|
+
/**
|
|
23
|
+
* Maximum wall-clock duration of a single run, in milliseconds. Checked
|
|
24
|
+
* between interpreter steps — a single long native builtin call (e.g.
|
|
25
|
+
* `sort` on a large array) can overshoot the deadline by up to its own
|
|
26
|
+
* duration, but subsequent interpreter work is rejected. Set to 0 to
|
|
27
|
+
* disable. Defaults to 0 (disabled); set to a positive value for hostile
|
|
28
|
+
* multi-tenant workloads.
|
|
29
|
+
*/
|
|
30
|
+
maxDurationMs?: number;
|
|
6
31
|
}
|
|
7
32
|
export interface RunResult {
|
|
8
33
|
result: any;
|
|
9
34
|
env: Record<string, any>;
|
|
10
35
|
}
|
|
11
|
-
export default function runner({ functions, maxSteps }?: RunnerOptions): (code: string, env?: Record<string, any>, debug?: boolean) => RunResult;
|
|
12
|
-
export { Environment };
|
|
36
|
+
export default function runner({ functions, maxSteps, maxCodeSize, maxAllocSize, maxDurationMs, }?: RunnerOptions): (code: string, env?: Record<string, any>, debug?: boolean) => RunResult;
|
|
37
|
+
export { Environment, Runtime };
|
|
13
38
|
export type { FunctionMap };
|
package/dist/index.js
CHANGED
|
@@ -1,7 +1,7 @@
|
|
|
1
1
|
import * as acorn from "acorn";
|
|
2
|
-
import evaluate
|
|
2
|
+
import evaluate from "./evaluate.js";
|
|
3
3
|
import builtinFuncs from "./builtin-functions.js";
|
|
4
|
-
import Environment from "./environment.js";
|
|
4
|
+
import Environment, { Runtime } from "./environment.js";
|
|
5
5
|
function parse(code) {
|
|
6
6
|
return acorn.parse(code, {
|
|
7
7
|
ecmaVersion: "latest",
|
|
@@ -10,17 +10,22 @@ function parse(code) {
|
|
|
10
10
|
});
|
|
11
11
|
}
|
|
12
12
|
const DEFAULT_MAX_STEPS = 100000;
|
|
13
|
-
|
|
13
|
+
const DEFAULT_MAX_CODE_SIZE = 64 * 1024;
|
|
14
|
+
const DEFAULT_MAX_ALLOC_SIZE = 1000000;
|
|
15
|
+
const DEFAULT_MAX_DURATION_MS = 0;
|
|
16
|
+
export default function runner({ functions = builtinFuncs, maxSteps = DEFAULT_MAX_STEPS, maxCodeSize = DEFAULT_MAX_CODE_SIZE, maxAllocSize = DEFAULT_MAX_ALLOC_SIZE, maxDurationMs = DEFAULT_MAX_DURATION_MS, } = {}) {
|
|
14
17
|
return (code, env = {}, debug) => {
|
|
18
|
+
if (maxCodeSize > 0 && code.length > maxCodeSize) {
|
|
19
|
+
throw new Error(`Source exceeds maxCodeSize (${code.length} > ${maxCodeSize})`);
|
|
20
|
+
}
|
|
15
21
|
const ast = parse(code);
|
|
16
22
|
debug && console.log(JSON.stringify(ast.body, null, 2));
|
|
17
|
-
|
|
18
|
-
const globalEnv = new Environment();
|
|
23
|
+
const globalEnv = new Environment(undefined, new Runtime(maxSteps, maxAllocSize, maxDurationMs));
|
|
19
24
|
Object.keys(env).forEach((key) => {
|
|
20
|
-
globalEnv.def(key, env[key]);
|
|
25
|
+
globalEnv.def([key], env[key]);
|
|
21
26
|
});
|
|
22
27
|
const result = evaluate(ast, globalEnv, functions);
|
|
23
28
|
return { result, env: globalEnv.vars };
|
|
24
29
|
};
|
|
25
30
|
}
|
|
26
|
-
export { Environment };
|
|
31
|
+
export { Environment, Runtime };
|
package/package.json
CHANGED
|
@@ -1,6 +1,6 @@
|
|
|
1
1
|
{
|
|
2
2
|
"name": "scriptable",
|
|
3
|
-
"version": "0.
|
|
3
|
+
"version": "0.2.0",
|
|
4
4
|
"type": "module",
|
|
5
5
|
"main": "dist/index.js",
|
|
6
6
|
"types": "dist/index.d.ts",
|
|
@@ -22,7 +22,7 @@
|
|
|
22
22
|
"devDependencies": {
|
|
23
23
|
"@changesets/cli": "^2.30.0",
|
|
24
24
|
"typescript": "^5.7.0",
|
|
25
|
-
"vitest": "^
|
|
25
|
+
"vitest": "^4.1.4"
|
|
26
26
|
},
|
|
27
27
|
"scripts": {
|
|
28
28
|
"build": "tsc",
|
|
@@ -0,0 +1,206 @@
|
|
|
1
|
+
import { describe, it, expect } from "vitest";
|
|
2
|
+
import runner from "../index.js";
|
|
3
|
+
|
|
4
|
+
// Regressions for four additional findings from the v0.1.1 audit that were
|
|
5
|
+
// deferred until after the initial hardening pass. See
|
|
6
|
+
// `.changeset/audit-followups.md` for narrative context.
|
|
7
|
+
|
|
8
|
+
describe("Finding 4 — literal-dot keys survive the path refactor", () => {
|
|
9
|
+
// Pre-fix, evalAsPath built a dotted string ("a.x.y"), so a key like
|
|
10
|
+
// `a["x.y"]` was split by deepSet into `a.x.y` on write but read back via
|
|
11
|
+
// a flat `obj["x.y"]` lookup — silent inconsistency. Post-fix, paths are
|
|
12
|
+
// string[] segments and dots inside a segment stay literal.
|
|
13
|
+
const run = runner();
|
|
14
|
+
|
|
15
|
+
it("a['x.y'] = 1 stores under the literal key 'x.y'", () => {
|
|
16
|
+
const { env } = run(`a = {}; a["x.y"] = 1;`);
|
|
17
|
+
expect(Object.prototype.hasOwnProperty.call(env.a, "x.y")).toBe(true);
|
|
18
|
+
expect(env.a["x.y"]).toBe(1);
|
|
19
|
+
expect(env.a.x).toBeUndefined();
|
|
20
|
+
});
|
|
21
|
+
|
|
22
|
+
it("read-after-write through the same bracket expression round-trips", () => {
|
|
23
|
+
const { result } = run(`a = {}; a["x.y"] = 42; a["x.y"];`);
|
|
24
|
+
expect(result).toBe(42);
|
|
25
|
+
});
|
|
26
|
+
|
|
27
|
+
it("compound assignment on a dotted literal key still works", () => {
|
|
28
|
+
const { env } = run(`a = { "x.y": 1 }; a["x.y"] += 10;`);
|
|
29
|
+
expect(env.a["x.y"]).toBe(11);
|
|
30
|
+
});
|
|
31
|
+
|
|
32
|
+
it("blocked props remain blocked even when embedded in a dotted string", () => {
|
|
33
|
+
// 'a.__proto__' as a full literal key is NOT the blocked string "__proto__"
|
|
34
|
+
// (it's the 11-char string), so this is allowed as a plain property. The
|
|
35
|
+
// real prototype-pollution vector is the literal "__proto__" segment,
|
|
36
|
+
// still caught by assertSafeProperty.
|
|
37
|
+
expect(() => run(`a = {}; a["__proto__"] = 1;`)).toThrow(
|
|
38
|
+
"Access to property '__proto__' is not allowed"
|
|
39
|
+
);
|
|
40
|
+
});
|
|
41
|
+
});
|
|
42
|
+
|
|
43
|
+
describe("Finding 5 — dotted paths resolve through parent scope", () => {
|
|
44
|
+
// Pre-fix, env.vars = Object.create(parent.vars) made parent variables
|
|
45
|
+
// visible via prototype chain, but deepHas used hasOwn on the first segment
|
|
46
|
+
// so `obj.method()` inside a nested function threw "obj.method is not a
|
|
47
|
+
// function". Post-fix, the first segment uses `in` (walks the chain);
|
|
48
|
+
// subsequent segments still use hasOwn so Object.prototype can't leak in.
|
|
49
|
+
const run = runner();
|
|
50
|
+
|
|
51
|
+
it("calls a method on a parent-scope object from inside a function", () => {
|
|
52
|
+
const { result } = run(`
|
|
53
|
+
obj = { double: (x) => x * 2 };
|
|
54
|
+
function f() { return obj.double(5); }
|
|
55
|
+
f();
|
|
56
|
+
`);
|
|
57
|
+
expect(result).toBe(10);
|
|
58
|
+
});
|
|
59
|
+
|
|
60
|
+
it("reads a nested property on a parent-scope object", () => {
|
|
61
|
+
const { result } = run(`
|
|
62
|
+
config = { db: { host: "localhost", port: 5432 } };
|
|
63
|
+
function f() { return config.db.port; }
|
|
64
|
+
f();
|
|
65
|
+
`);
|
|
66
|
+
expect(result).toBe(5432);
|
|
67
|
+
});
|
|
68
|
+
|
|
69
|
+
it("still blocks Object.prototype leak on subsequent segments", () => {
|
|
70
|
+
// `obj.toString` would resolve to Object.prototype.toString if hasOwn
|
|
71
|
+
// weren't applied after the first segment. Make sure it doesn't.
|
|
72
|
+
expect(() =>
|
|
73
|
+
run(`
|
|
74
|
+
obj = {};
|
|
75
|
+
function f() { return obj.toString(); }
|
|
76
|
+
f();
|
|
77
|
+
`)
|
|
78
|
+
).toThrow(/is not a function|is not defined/);
|
|
79
|
+
});
|
|
80
|
+
|
|
81
|
+
it("still blocks constructor on any segment", () => {
|
|
82
|
+
expect(() =>
|
|
83
|
+
run(`
|
|
84
|
+
obj = {};
|
|
85
|
+
function f() { return obj.constructor; }
|
|
86
|
+
f();
|
|
87
|
+
`)
|
|
88
|
+
).toThrow("Access to property 'constructor' is not allowed");
|
|
89
|
+
});
|
|
90
|
+
});
|
|
91
|
+
|
|
92
|
+
describe("Finding 7 — maxAllocSize bounds object key growth", () => {
|
|
93
|
+
it("spread accumulation under the cap still works", () => {
|
|
94
|
+
const run = runner({ maxSteps: 0, maxAllocSize: 50 });
|
|
95
|
+
const { env } = run(`
|
|
96
|
+
acc = {};
|
|
97
|
+
acc = {...acc, a: 1};
|
|
98
|
+
acc = {...acc, b: 2};
|
|
99
|
+
acc = {...acc, c: 3};
|
|
100
|
+
`);
|
|
101
|
+
expect(env.acc).toEqual({ a: 1, b: 2, c: 3 });
|
|
102
|
+
});
|
|
103
|
+
|
|
104
|
+
it("recursive {...acc, [k]: k} growth trips the cap", () => {
|
|
105
|
+
// Use recursion instead of reduce(bigArr, ...) so the array literal check
|
|
106
|
+
// doesn't fire first — all that's in scope is a primitive counter. Each
|
|
107
|
+
// ObjectExpression spread projects ownCount + 1; once that exceeds
|
|
108
|
+
// maxAllocSize, checkLength throws.
|
|
109
|
+
const run = runner({ maxSteps: 0, maxAllocSize: 10 });
|
|
110
|
+
expect(() =>
|
|
111
|
+
run(`
|
|
112
|
+
grow = (acc, n) => n > 0 ? grow({...acc, ["k" + n]: n}, n - 1) : acc;
|
|
113
|
+
grow({}, 50);
|
|
114
|
+
`)
|
|
115
|
+
).toThrow(/Length.*exceeds maxAllocSize/);
|
|
116
|
+
});
|
|
117
|
+
|
|
118
|
+
it("object literal with > maxAllocSize keys throws on construction", () => {
|
|
119
|
+
const run = runner({ maxAllocSize: 3 });
|
|
120
|
+
const keys = ["a: 1", "b: 2", "c: 3", "d: 4"].join(", ");
|
|
121
|
+
expect(() => run(`({ ${keys} })`)).toThrow(
|
|
122
|
+
/Length.*exceeds maxAllocSize/
|
|
123
|
+
);
|
|
124
|
+
});
|
|
125
|
+
|
|
126
|
+
it("repeated keys within one literal don't over-count", () => {
|
|
127
|
+
// Same key written twice is still one own key; cap shouldn't trip.
|
|
128
|
+
const run = runner({ maxAllocSize: 1 });
|
|
129
|
+
expect(() => run(`({ a: 1, a: 2 })`)).not.toThrow();
|
|
130
|
+
});
|
|
131
|
+
|
|
132
|
+
it("objects under the cap still build", () => {
|
|
133
|
+
const run = runner({ maxAllocSize: 10 });
|
|
134
|
+
const { result } = run(`({ a: 1, b: 2, c: 3 })`);
|
|
135
|
+
expect(result).toEqual({ a: 1, b: 2, c: 3 });
|
|
136
|
+
});
|
|
137
|
+
});
|
|
138
|
+
|
|
139
|
+
describe("Finding 6 — maxDurationMs bounds wall-clock runs", () => {
|
|
140
|
+
it("a long-running injected builtin trips the deadline on the next step", () => {
|
|
141
|
+
const run = runner({
|
|
142
|
+
maxSteps: 0,
|
|
143
|
+
maxDurationMs: 20,
|
|
144
|
+
functions: {
|
|
145
|
+
slow: (ms: number) => {
|
|
146
|
+
const end = Date.now() + ms;
|
|
147
|
+
while (Date.now() < end) {
|
|
148
|
+
/* burn */
|
|
149
|
+
}
|
|
150
|
+
return 1;
|
|
151
|
+
},
|
|
152
|
+
add: (a: number, b: number) => a + b,
|
|
153
|
+
},
|
|
154
|
+
});
|
|
155
|
+
// slow(100) runs inside V8 (~100ms), overshoots the 20ms deadline. The
|
|
156
|
+
// next interpreter step — evaluating `add(1, 2)` — sees the deadline
|
|
157
|
+
// passed and throws.
|
|
158
|
+
expect(() => run(`slow(100); add(1, 2);`)).toThrow(
|
|
159
|
+
"Execution time exceeded"
|
|
160
|
+
);
|
|
161
|
+
});
|
|
162
|
+
|
|
163
|
+
it("scripts that finish inside the deadline succeed", () => {
|
|
164
|
+
const run = runner({ maxDurationMs: 5000 });
|
|
165
|
+
const { result } = run(`1 + 2 + 3`);
|
|
166
|
+
expect(result).toBe(6);
|
|
167
|
+
});
|
|
168
|
+
|
|
169
|
+
it("maxDurationMs=0 disables the deadline", () => {
|
|
170
|
+
const run = runner({
|
|
171
|
+
maxDurationMs: 0,
|
|
172
|
+
maxSteps: 1000,
|
|
173
|
+
functions: {
|
|
174
|
+
slow: () => {
|
|
175
|
+
const end = Date.now() + 30;
|
|
176
|
+
while (Date.now() < end) {
|
|
177
|
+
/* burn */
|
|
178
|
+
}
|
|
179
|
+
return 1;
|
|
180
|
+
},
|
|
181
|
+
},
|
|
182
|
+
});
|
|
183
|
+
expect(() => run(`slow()`)).not.toThrow();
|
|
184
|
+
});
|
|
185
|
+
|
|
186
|
+
it("deadline supersedes subsequent work even if maxSteps would still allow it", () => {
|
|
187
|
+
// Step counter never trips (maxSteps=0 disables), so wall-clock is the
|
|
188
|
+
// only gate. Confirm the deadline still fires.
|
|
189
|
+
const run = runner({
|
|
190
|
+
maxSteps: 0,
|
|
191
|
+
maxDurationMs: 10,
|
|
192
|
+
functions: {
|
|
193
|
+
slow: (ms: number) => {
|
|
194
|
+
const end = Date.now() + ms;
|
|
195
|
+
while (Date.now() < end) {
|
|
196
|
+
/* burn */
|
|
197
|
+
}
|
|
198
|
+
return 1;
|
|
199
|
+
},
|
|
200
|
+
},
|
|
201
|
+
});
|
|
202
|
+
expect(() => run(`slow(50); slow(50);`)).toThrow(
|
|
203
|
+
"Execution time exceeded"
|
|
204
|
+
);
|
|
205
|
+
});
|
|
206
|
+
});
|