scriptable 0.1.1 → 0.2.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/LICENSE +21 -0
- package/README.md +13 -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 +6 -2
- package/.changeset/README.md +0 -8
- package/.changeset/config.json +0 -11
- package/.github/workflows/release.yml +0 -62
- package/CHANGELOG.md +0 -14
- package/dist/logic-ops.d.ts +0 -2
- package/dist/logic-ops.js +0 -5
- package/scripts/release.js +0 -127
- package/src/__tests__/break-out.test.ts +0 -43
- package/src/__tests__/builtin-functions-date.test.ts +0 -75
- package/src/__tests__/builtin-functions.test.ts +0 -56
- package/src/__tests__/expressions.test.ts +0 -13
- package/src/__tests__/functions.test.ts +0 -81
- package/src/__tests__/logic.test.ts +0 -54
- package/src/__tests__/new-features.test.ts +0 -158
- package/src/__tests__/security.test.ts +0 -399
- package/src/__tests__/variables.test.ts +0 -200
- package/src/binary-ops.ts +0 -18
- package/src/builtin-functions.ts +0 -177
- package/src/environment.ts +0 -132
- package/src/evaluate.ts +0 -275
- package/src/index.ts +0 -42
- package/src/logic-ops.ts +0 -6
- package/tsconfig.json +0 -16
package/LICENSE
ADDED
|
@@ -0,0 +1,21 @@
|
|
|
1
|
+
MIT License
|
|
2
|
+
|
|
3
|
+
Copyright (c) 2024 Jason Galea
|
|
4
|
+
|
|
5
|
+
Permission is hereby granted, free of charge, to any person obtaining a copy
|
|
6
|
+
of this software and associated documentation files (the "Software"), to deal
|
|
7
|
+
in the Software without restriction, including without limitation the rights
|
|
8
|
+
to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
|
|
9
|
+
copies of the Software, and to permit persons to whom the Software is
|
|
10
|
+
furnished to do so, subject to the following conditions:
|
|
11
|
+
|
|
12
|
+
The above copyright notice and this permission notice shall be included in all
|
|
13
|
+
copies or substantial portions of the Software.
|
|
14
|
+
|
|
15
|
+
THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
|
|
16
|
+
IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
|
|
17
|
+
FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
|
|
18
|
+
AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
|
|
19
|
+
LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
|
|
20
|
+
OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
|
|
21
|
+
SOFTWARE.
|
package/README.md
CHANGED
|
@@ -49,6 +49,10 @@ The default `functions` include array/collection operations (`map`, `filter`, `r
|
|
|
49
49
|
**`runner(options?)`** returns an executor function.
|
|
50
50
|
|
|
51
51
|
- `options.functions` — `Record<string, Function>` of callable functions (defaults to built-in set)
|
|
52
|
+
- `options.maxSteps` — AST nodes evaluated per run before throwing `Execution limit exceeded`. Defaults to `100_000`. Set to `0` to disable.
|
|
53
|
+
- `options.maxCodeSize` — maximum source length in UTF-16 code units, checked before parsing. Defaults to `65_536` (64 KiB). Set to `0` to disable.
|
|
54
|
+
- `options.maxAllocSize` — maximum length of any string or array produced during a run, and maximum key count of any object literal. Defaults to `1_000_000` (~2 MB for strings, 1M elements for arrays, 1M keys for objects). Set to `0` to disable.
|
|
55
|
+
- `options.maxDurationMs` — wall-clock deadline per run, in milliseconds. Checked between interpreter steps, so a single long native builtin call (e.g. `sort` on a large array) can overshoot by up to its own duration before subsequent work is rejected. Defaults to `0` (disabled); set a positive value for hostile multi-tenant workloads.
|
|
52
56
|
|
|
53
57
|
**`run(code, env?, debug?)`** executes code and returns `{ result, env }`.
|
|
54
58
|
|
|
@@ -57,6 +61,15 @@ The default `functions` include array/collection operations (`map`, `filter`, `r
|
|
|
57
61
|
- `debug` — if truthy, logs the AST to console
|
|
58
62
|
- Returns `result` (value of last expression) and `env` (all variables after execution)
|
|
59
63
|
|
|
64
|
+
### Trust boundary
|
|
65
|
+
|
|
66
|
+
The sandbox contains user code — it does **not** sanitize values or callables you inject. Anything you put in `env` or `options.functions` is trusted:
|
|
67
|
+
|
|
68
|
+
- Passing a function (e.g. `Function`, `eval`, a host method that shells out) lets the script invoke it directly.
|
|
69
|
+
- Passing an object with a getter runs that getter when the script reads the property.
|
|
70
|
+
|
|
71
|
+
If you need to expose host capabilities, wrap them in plain functions that validate their inputs and return only primitives or plain objects.
|
|
72
|
+
|
|
60
73
|
## Supported syntax
|
|
61
74
|
|
|
62
75
|
| Node type | Examples |
|
package/dist/environment.d.ts
CHANGED
|
@@ -2,15 +2,26 @@ export interface Loc {
|
|
|
2
2
|
line: number;
|
|
3
3
|
column: number;
|
|
4
4
|
}
|
|
5
|
+
export declare class Runtime {
|
|
6
|
+
steps: number;
|
|
7
|
+
maxSteps: number;
|
|
8
|
+
maxAllocSize: number;
|
|
9
|
+
deadline: number;
|
|
10
|
+
constructor(maxSteps?: number, maxAllocSize?: number, maxDurationMs?: number);
|
|
11
|
+
step(): void;
|
|
12
|
+
checkSize(value: unknown): void;
|
|
13
|
+
checkLength(projected: number): void;
|
|
14
|
+
}
|
|
5
15
|
export default class Environment {
|
|
6
16
|
vars: Record<string, any>;
|
|
7
17
|
parent: Environment | null;
|
|
8
|
-
|
|
18
|
+
runtime: Runtime;
|
|
19
|
+
constructor(parent?: Environment, runtime?: Runtime);
|
|
9
20
|
extend(): Environment;
|
|
10
21
|
getGlobalScope(): Environment;
|
|
11
22
|
lookup(name: string): Environment;
|
|
12
|
-
defined(
|
|
13
|
-
get(
|
|
14
|
-
set(
|
|
15
|
-
def(
|
|
23
|
+
defined(path: string[]): boolean;
|
|
24
|
+
get(path: string[], loc: Loc): any;
|
|
25
|
+
set(path: string[], value: any, loc: Loc): any;
|
|
26
|
+
def(path: string[], value: any): any;
|
|
16
27
|
}
|
package/dist/environment.js
CHANGED
|
@@ -16,21 +16,27 @@ function assertSafeParts(parts) {
|
|
|
16
16
|
}
|
|
17
17
|
}
|
|
18
18
|
}
|
|
19
|
-
|
|
20
|
-
|
|
19
|
+
// First segment walks the scope chain (env.vars is Object.create(parent.vars))
|
|
20
|
+
// so `obj.method()` still resolves when `obj` lives in an enclosing scope.
|
|
21
|
+
// Subsequent segments use hasOwn to prevent user-land objects from leaking
|
|
22
|
+
// Object.prototype members through the lookup (e.g. `obj.toString`).
|
|
23
|
+
function deepHas(obj, parts) {
|
|
21
24
|
assertSafeParts(parts);
|
|
22
|
-
|
|
23
|
-
|
|
25
|
+
if (parts.length === 0)
|
|
26
|
+
return false;
|
|
27
|
+
if (!(parts[0] in obj))
|
|
28
|
+
return false;
|
|
29
|
+
let current = obj[parts[0]];
|
|
30
|
+
for (let i = 1; i < parts.length; i++) {
|
|
24
31
|
if (current == null || typeof current !== "object")
|
|
25
32
|
return false;
|
|
26
|
-
if (!Object.prototype.hasOwnProperty.call(current,
|
|
33
|
+
if (!Object.prototype.hasOwnProperty.call(current, parts[i]))
|
|
27
34
|
return false;
|
|
28
|
-
current = current[
|
|
35
|
+
current = current[parts[i]];
|
|
29
36
|
}
|
|
30
37
|
return true;
|
|
31
38
|
}
|
|
32
|
-
function deepGet(obj,
|
|
33
|
-
const parts = path.split(".");
|
|
39
|
+
function deepGet(obj, parts) {
|
|
34
40
|
assertSafeParts(parts);
|
|
35
41
|
let current = obj;
|
|
36
42
|
for (const part of parts) {
|
|
@@ -40,8 +46,7 @@ function deepGet(obj, path) {
|
|
|
40
46
|
}
|
|
41
47
|
return current;
|
|
42
48
|
}
|
|
43
|
-
function deepSet(obj,
|
|
44
|
-
const parts = path.split(".");
|
|
49
|
+
function deepSet(obj, parts, value) {
|
|
45
50
|
assertSafeParts(parts);
|
|
46
51
|
let current = obj;
|
|
47
52
|
for (let i = 0; i < parts.length - 1; i++) {
|
|
@@ -52,10 +57,66 @@ function deepSet(obj, path, value) {
|
|
|
52
57
|
}
|
|
53
58
|
current[parts[parts.length - 1]] = value;
|
|
54
59
|
}
|
|
60
|
+
// Per-run execution state. Shared across every scope in a single interpreter
|
|
61
|
+
// run via Environment.runtime. Replaces the previous module-global counter,
|
|
62
|
+
// so concurrent or re-entrant runs can't clobber each other's budgets.
|
|
63
|
+
export class Runtime {
|
|
64
|
+
constructor(maxSteps = 0, maxAllocSize = 0, maxDurationMs = 0) {
|
|
65
|
+
this.steps = 0;
|
|
66
|
+
this.maxSteps = maxSteps;
|
|
67
|
+
this.maxAllocSize = maxAllocSize;
|
|
68
|
+
this.deadline = maxDurationMs > 0 ? Date.now() + maxDurationMs : 0;
|
|
69
|
+
}
|
|
70
|
+
step() {
|
|
71
|
+
// Wall-clock deadline guards against hostile workloads where a single
|
|
72
|
+
// native builtin call (e.g. sort on a 1M-element array) burns CPU without
|
|
73
|
+
// advancing the step counter. Checked between interpreter steps — a single
|
|
74
|
+
// long native call can overshoot the deadline by up to that call's
|
|
75
|
+
// duration, but subsequent work is rejected.
|
|
76
|
+
if (this.deadline && Date.now() > this.deadline) {
|
|
77
|
+
throw new Error("Execution time exceeded");
|
|
78
|
+
}
|
|
79
|
+
if (this.maxSteps === 0)
|
|
80
|
+
return;
|
|
81
|
+
if (++this.steps > this.maxSteps) {
|
|
82
|
+
throw new Error("Execution limit exceeded");
|
|
83
|
+
}
|
|
84
|
+
}
|
|
85
|
+
// String doubling and array spread/concat can grow exponentially in a handful
|
|
86
|
+
// of steps — 26 string doublings reach V8's ~512 MiB string-length ceiling in
|
|
87
|
+
// under a dozen statements. Check the size of every value produced by a
|
|
88
|
+
// handler so one run can't allocate unbounded memory.
|
|
89
|
+
checkSize(value) {
|
|
90
|
+
if (this.maxAllocSize === 0)
|
|
91
|
+
return;
|
|
92
|
+
if (typeof value === "string") {
|
|
93
|
+
if (value.length > this.maxAllocSize) {
|
|
94
|
+
throw new Error(`String length ${value.length} exceeds maxAllocSize (${this.maxAllocSize})`);
|
|
95
|
+
}
|
|
96
|
+
}
|
|
97
|
+
else if (Array.isArray(value)) {
|
|
98
|
+
if (value.length > this.maxAllocSize) {
|
|
99
|
+
throw new Error(`Array length ${value.length} exceeds maxAllocSize (${this.maxAllocSize})`);
|
|
100
|
+
}
|
|
101
|
+
}
|
|
102
|
+
}
|
|
103
|
+
// Caller-projected length — used before growing an array via spread, so we
|
|
104
|
+
// reject the growth rather than wait for V8's per-call argument stack limit
|
|
105
|
+
// (which fires at ~65K args on push(...spread), a much lower ceiling than
|
|
106
|
+
// maxAllocSize is designed to enforce).
|
|
107
|
+
checkLength(projected) {
|
|
108
|
+
if (this.maxAllocSize === 0)
|
|
109
|
+
return;
|
|
110
|
+
if (projected > this.maxAllocSize) {
|
|
111
|
+
throw new Error(`Length ${projected} exceeds maxAllocSize (${this.maxAllocSize})`);
|
|
112
|
+
}
|
|
113
|
+
}
|
|
114
|
+
}
|
|
55
115
|
export default class Environment {
|
|
56
|
-
constructor(parent) {
|
|
116
|
+
constructor(parent, runtime) {
|
|
57
117
|
this.vars = Object.create(parent ? parent.vars : null);
|
|
58
118
|
this.parent = parent || null;
|
|
119
|
+
this.runtime = parent ? parent.runtime : runtime ?? new Runtime();
|
|
59
120
|
}
|
|
60
121
|
extend() {
|
|
61
122
|
return new Environment(this);
|
|
@@ -77,35 +138,22 @@ export default class Environment {
|
|
|
77
138
|
}
|
|
78
139
|
return scope;
|
|
79
140
|
}
|
|
80
|
-
defined(
|
|
81
|
-
|
|
82
|
-
return true;
|
|
83
|
-
}
|
|
84
|
-
if (deepHas(this.vars, name)) {
|
|
85
|
-
return true;
|
|
86
|
-
}
|
|
87
|
-
return false;
|
|
141
|
+
defined(path) {
|
|
142
|
+
return deepHas(this.vars, path);
|
|
88
143
|
}
|
|
89
|
-
get(
|
|
90
|
-
if (
|
|
91
|
-
return this.vars
|
|
144
|
+
get(path, loc) {
|
|
145
|
+
if (deepHas(this.vars, path)) {
|
|
146
|
+
return deepGet(this.vars, path);
|
|
92
147
|
}
|
|
93
|
-
|
|
94
|
-
return deepGet(this.vars, name);
|
|
95
|
-
}
|
|
96
|
-
throw new ReferenceError(`"${name}" is not defined (${loc.line}:${loc.column})`);
|
|
148
|
+
throw new ReferenceError(`"${path.join(".")}" is not defined (${loc.line}:${loc.column})`);
|
|
97
149
|
}
|
|
98
|
-
set(
|
|
99
|
-
const
|
|
100
|
-
|
|
101
|
-
if (!scope && this.parent) {
|
|
102
|
-
throw new ReferenceError(`"${name}" is not defined (${loc.line}:${loc.column})`);
|
|
103
|
-
}
|
|
104
|
-
deepSet((scope || this).vars, name, value);
|
|
150
|
+
set(path, value, loc) {
|
|
151
|
+
const scope = this.lookup(path[0]);
|
|
152
|
+
deepSet(scope.vars, path, value);
|
|
105
153
|
return value;
|
|
106
154
|
}
|
|
107
|
-
def(
|
|
108
|
-
deepSet(this.vars,
|
|
155
|
+
def(path, value) {
|
|
156
|
+
deepSet(this.vars, path, value);
|
|
109
157
|
return value;
|
|
110
158
|
}
|
|
111
159
|
}
|
package/dist/evaluate.d.ts
CHANGED
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 };
|