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/src/environment.ts
CHANGED
|
@@ -18,20 +18,24 @@ function assertSafeParts(parts: string[]): void {
|
|
|
18
18
|
}
|
|
19
19
|
}
|
|
20
20
|
|
|
21
|
-
|
|
22
|
-
|
|
21
|
+
// First segment walks the scope chain (env.vars is Object.create(parent.vars))
|
|
22
|
+
// so `obj.method()` still resolves when `obj` lives in an enclosing scope.
|
|
23
|
+
// Subsequent segments use hasOwn to prevent user-land objects from leaking
|
|
24
|
+
// Object.prototype members through the lookup (e.g. `obj.toString`).
|
|
25
|
+
function deepHas(obj: any, parts: string[]): boolean {
|
|
23
26
|
assertSafeParts(parts);
|
|
24
|
-
|
|
25
|
-
|
|
27
|
+
if (parts.length === 0) return false;
|
|
28
|
+
if (!(parts[0] in obj)) return false;
|
|
29
|
+
let current = obj[parts[0]];
|
|
30
|
+
for (let i = 1; i < parts.length; i++) {
|
|
26
31
|
if (current == null || typeof current !== "object") return false;
|
|
27
|
-
if (!Object.prototype.hasOwnProperty.call(current,
|
|
28
|
-
current = current[
|
|
32
|
+
if (!Object.prototype.hasOwnProperty.call(current, parts[i])) return false;
|
|
33
|
+
current = current[parts[i]];
|
|
29
34
|
}
|
|
30
35
|
return true;
|
|
31
36
|
}
|
|
32
37
|
|
|
33
|
-
function deepGet(obj: any,
|
|
34
|
-
const parts = path.split(".");
|
|
38
|
+
function deepGet(obj: any, parts: string[]): any {
|
|
35
39
|
assertSafeParts(parts);
|
|
36
40
|
let current = obj;
|
|
37
41
|
for (const part of parts) {
|
|
@@ -41,8 +45,7 @@ function deepGet(obj: any, path: string): any {
|
|
|
41
45
|
return current;
|
|
42
46
|
}
|
|
43
47
|
|
|
44
|
-
function deepSet(obj: any,
|
|
45
|
-
const parts = path.split(".");
|
|
48
|
+
function deepSet(obj: any, parts: string[], value: any): void {
|
|
46
49
|
assertSafeParts(parts);
|
|
47
50
|
let current = obj;
|
|
48
51
|
for (let i = 0; i < parts.length - 1; i++) {
|
|
@@ -59,13 +62,85 @@ export interface Loc {
|
|
|
59
62
|
column: number;
|
|
60
63
|
}
|
|
61
64
|
|
|
65
|
+
// Per-run execution state. Shared across every scope in a single interpreter
|
|
66
|
+
// run via Environment.runtime. Replaces the previous module-global counter,
|
|
67
|
+
// so concurrent or re-entrant runs can't clobber each other's budgets.
|
|
68
|
+
export class Runtime {
|
|
69
|
+
steps: number = 0;
|
|
70
|
+
maxSteps: number;
|
|
71
|
+
maxAllocSize: number;
|
|
72
|
+
// Absolute deadline in ms (Date.now()). 0 means "no deadline".
|
|
73
|
+
deadline: number;
|
|
74
|
+
|
|
75
|
+
constructor(
|
|
76
|
+
maxSteps: number = 0,
|
|
77
|
+
maxAllocSize: number = 0,
|
|
78
|
+
maxDurationMs: number = 0
|
|
79
|
+
) {
|
|
80
|
+
this.maxSteps = maxSteps;
|
|
81
|
+
this.maxAllocSize = maxAllocSize;
|
|
82
|
+
this.deadline = maxDurationMs > 0 ? Date.now() + maxDurationMs : 0;
|
|
83
|
+
}
|
|
84
|
+
|
|
85
|
+
step(): void {
|
|
86
|
+
// Wall-clock deadline guards against hostile workloads where a single
|
|
87
|
+
// native builtin call (e.g. sort on a 1M-element array) burns CPU without
|
|
88
|
+
// advancing the step counter. Checked between interpreter steps — a single
|
|
89
|
+
// long native call can overshoot the deadline by up to that call's
|
|
90
|
+
// duration, but subsequent work is rejected.
|
|
91
|
+
if (this.deadline && Date.now() > this.deadline) {
|
|
92
|
+
throw new Error("Execution time exceeded");
|
|
93
|
+
}
|
|
94
|
+
if (this.maxSteps === 0) return;
|
|
95
|
+
if (++this.steps > this.maxSteps) {
|
|
96
|
+
throw new Error("Execution limit exceeded");
|
|
97
|
+
}
|
|
98
|
+
}
|
|
99
|
+
|
|
100
|
+
// String doubling and array spread/concat can grow exponentially in a handful
|
|
101
|
+
// of steps — 26 string doublings reach V8's ~512 MiB string-length ceiling in
|
|
102
|
+
// under a dozen statements. Check the size of every value produced by a
|
|
103
|
+
// handler so one run can't allocate unbounded memory.
|
|
104
|
+
checkSize(value: unknown): void {
|
|
105
|
+
if (this.maxAllocSize === 0) return;
|
|
106
|
+
if (typeof value === "string") {
|
|
107
|
+
if (value.length > this.maxAllocSize) {
|
|
108
|
+
throw new Error(
|
|
109
|
+
`String length ${value.length} exceeds maxAllocSize (${this.maxAllocSize})`
|
|
110
|
+
);
|
|
111
|
+
}
|
|
112
|
+
} else if (Array.isArray(value)) {
|
|
113
|
+
if (value.length > this.maxAllocSize) {
|
|
114
|
+
throw new Error(
|
|
115
|
+
`Array length ${value.length} exceeds maxAllocSize (${this.maxAllocSize})`
|
|
116
|
+
);
|
|
117
|
+
}
|
|
118
|
+
}
|
|
119
|
+
}
|
|
120
|
+
|
|
121
|
+
// Caller-projected length — used before growing an array via spread, so we
|
|
122
|
+
// reject the growth rather than wait for V8's per-call argument stack limit
|
|
123
|
+
// (which fires at ~65K args on push(...spread), a much lower ceiling than
|
|
124
|
+
// maxAllocSize is designed to enforce).
|
|
125
|
+
checkLength(projected: number): void {
|
|
126
|
+
if (this.maxAllocSize === 0) return;
|
|
127
|
+
if (projected > this.maxAllocSize) {
|
|
128
|
+
throw new Error(
|
|
129
|
+
`Length ${projected} exceeds maxAllocSize (${this.maxAllocSize})`
|
|
130
|
+
);
|
|
131
|
+
}
|
|
132
|
+
}
|
|
133
|
+
}
|
|
134
|
+
|
|
62
135
|
export default class Environment {
|
|
63
136
|
vars: Record<string, any>;
|
|
64
137
|
parent: Environment | null;
|
|
138
|
+
runtime: Runtime;
|
|
65
139
|
|
|
66
|
-
constructor(parent?: Environment) {
|
|
140
|
+
constructor(parent?: Environment, runtime?: Runtime) {
|
|
67
141
|
this.vars = Object.create(parent ? parent.vars : null);
|
|
68
142
|
this.parent = parent || null;
|
|
143
|
+
this.runtime = parent ? parent.runtime : runtime ?? new Runtime();
|
|
69
144
|
}
|
|
70
145
|
|
|
71
146
|
extend(): Environment {
|
|
@@ -91,42 +166,27 @@ export default class Environment {
|
|
|
91
166
|
return scope;
|
|
92
167
|
}
|
|
93
168
|
|
|
94
|
-
defined(
|
|
95
|
-
|
|
96
|
-
return true;
|
|
97
|
-
}
|
|
98
|
-
if (deepHas(this.vars, name)) {
|
|
99
|
-
return true;
|
|
100
|
-
}
|
|
101
|
-
return false;
|
|
169
|
+
defined(path: string[]): boolean {
|
|
170
|
+
return deepHas(this.vars, path);
|
|
102
171
|
}
|
|
103
172
|
|
|
104
|
-
get(
|
|
105
|
-
if (
|
|
106
|
-
return this.vars
|
|
107
|
-
}
|
|
108
|
-
if (deepHas(this.vars, name)) {
|
|
109
|
-
return deepGet(this.vars, name);
|
|
173
|
+
get(path: string[], loc: Loc): any {
|
|
174
|
+
if (deepHas(this.vars, path)) {
|
|
175
|
+
return deepGet(this.vars, path);
|
|
110
176
|
}
|
|
111
177
|
throw new ReferenceError(
|
|
112
|
-
`"${
|
|
178
|
+
`"${path.join(".")}" is not defined (${loc.line}:${loc.column})`
|
|
113
179
|
);
|
|
114
180
|
}
|
|
115
181
|
|
|
116
|
-
set(
|
|
117
|
-
const
|
|
118
|
-
|
|
119
|
-
if (!scope && this.parent) {
|
|
120
|
-
throw new ReferenceError(
|
|
121
|
-
`"${name}" is not defined (${loc.line}:${loc.column})`
|
|
122
|
-
);
|
|
123
|
-
}
|
|
124
|
-
deepSet((scope || this).vars, name, value);
|
|
182
|
+
set(path: string[], value: any, loc: Loc): any {
|
|
183
|
+
const scope = this.lookup(path[0]);
|
|
184
|
+
deepSet(scope.vars, path, value);
|
|
125
185
|
return value;
|
|
126
186
|
}
|
|
127
187
|
|
|
128
|
-
def(
|
|
129
|
-
deepSet(this.vars,
|
|
188
|
+
def(path: string[], value: any): any {
|
|
189
|
+
deepSet(this.vars, path, value);
|
|
130
190
|
return value;
|
|
131
191
|
}
|
|
132
192
|
}
|
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
|
-
//
|
|
28
|
-
|
|
29
|
-
|
|
30
|
-
|
|
31
|
-
|
|
32
|
-
|
|
33
|
-
|
|
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
|
-
|
|
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
|
-
|
|
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
|
-
|
|
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
|
-
|
|
79
|
-
|
|
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
|
-
|
|
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
|
-
|
|
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 (
|
|
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(
|
|
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
|
-
|
|
169
|
-
|
|
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
|
|
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 —
|
|
198
|
-
|
|
199
|
-
|
|
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
|
-
|
|
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
|
-
|
|
267
|
-
|
|
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
|
-
|
|
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
|
|
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({
|
|
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
|
-
|
|
32
|
-
|
|
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 };
|
package/dist/logic-ops.d.ts
DELETED
package/dist/logic-ops.js
DELETED