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.
@@ -0,0 +1,171 @@
1
+ import { describe, it, expect } from "vitest";
2
+ import runner from "../index.js";
3
+
4
+ const run = runner();
5
+
6
+ // Regressions for three semantic/security bugs discovered in the v0.1.1 audit.
7
+
8
+ describe("functions lookup uses hasOwn (no Object.prototype walk)", () => {
9
+ it("`constructor()` does not resolve to Object via prototype chain", () => {
10
+ // Pre-fix: `functions['constructor']` inherited `Object` from Object.prototype,
11
+ // so this call succeeded and returned `{}`. Post-fix the builtin map is
12
+ // checked with hasOwn, so the call falls through to env lookup and throws.
13
+ expect(() => run(`constructor()`)).toThrow(
14
+ "Access to property 'constructor' is not allowed"
15
+ );
16
+ });
17
+
18
+ it("`toString()` does not resolve to Object.prototype.toString", () => {
19
+ expect(() => run(`toString()`)).toThrow(
20
+ /is not a function|is not defined/
21
+ );
22
+ });
23
+
24
+ it("`valueOf()` does not resolve to Object.prototype.valueOf", () => {
25
+ expect(() => run(`valueOf()`)).toThrow(/is not a function|is not defined/);
26
+ });
27
+
28
+ it("`hasOwnProperty()` does not resolve to Object.prototype method", () => {
29
+ expect(() => run(`hasOwnProperty()`)).toThrow(
30
+ /is not a function|is not defined/
31
+ );
32
+ });
33
+
34
+ it("real builtins still resolve", () => {
35
+ const { result } = run(`map([1, 2, 3], (x) => x * 2)`);
36
+ expect(result).toEqual([2, 4, 6]);
37
+ });
38
+
39
+ it("user-supplied functions map with Object.prototype inheritance is still safe", () => {
40
+ // A caller may pass a plain object literal. hasOwn defends against that
41
+ // too, not just the default builtins.
42
+ const run2 = runner({ functions: { add: (a: number, b: number) => a + b } });
43
+ expect(() => run2(`constructor()`)).toThrow(
44
+ /Access to property|is not a function|is not defined/
45
+ );
46
+ const { result } = run2(`add(2, 3)`);
47
+ expect(result).toEqual(5);
48
+ });
49
+ });
50
+
51
+ describe("LogicalExpression short-circuits", () => {
52
+ it("`false && side()` does not evaluate side effect", () => {
53
+ const code = `
54
+ count = 0;
55
+ side = () => { count = count + 1; return 1; };
56
+ result = false && side();
57
+ count;
58
+ `;
59
+ const { result } = run(code);
60
+ expect(result).toEqual(0);
61
+ });
62
+
63
+ it("`true || side()` does not evaluate side effect", () => {
64
+ const code = `
65
+ count = 0;
66
+ side = () => { count = count + 1; return 1; };
67
+ result = true || side();
68
+ count;
69
+ `;
70
+ const { result } = run(code);
71
+ expect(result).toEqual(0);
72
+ });
73
+
74
+ it("`true && side()` does evaluate the right side", () => {
75
+ const code = `
76
+ count = 0;
77
+ side = () => { count = count + 1; return 42; };
78
+ result = true && side();
79
+ [result, count];
80
+ `;
81
+ const { result } = run(code);
82
+ expect(result).toEqual([42, 1]);
83
+ });
84
+
85
+ it("`null ?? value` returns value (and `0 ?? x` returns 0)", () => {
86
+ expect(run(`null ?? "fallback"`).result).toEqual("fallback");
87
+ expect(run(`0 ?? "fallback"`).result).toEqual(0);
88
+ expect(run(`"" ?? "fallback"`).result).toEqual("");
89
+ });
90
+
91
+ it("`x ?? side()` does not evaluate side effect when x is defined", () => {
92
+ const code = `
93
+ count = 0;
94
+ side = () => { count = count + 1; return "fallback"; };
95
+ result = "value" ?? side();
96
+ count;
97
+ `;
98
+ const { result } = run(code);
99
+ expect(result).toEqual(0);
100
+ });
101
+ });
102
+
103
+ describe("AssignmentExpression compound operators", () => {
104
+ it("`+=` adds", () => {
105
+ const { env } = run(`a = 10; a += 5;`);
106
+ expect(env.a).toEqual(15);
107
+ });
108
+
109
+ it("`-=` subtracts", () => {
110
+ const { env } = run(`a = 10; a -= 3;`);
111
+ expect(env.a).toEqual(7);
112
+ });
113
+
114
+ it("`*=` multiplies", () => {
115
+ const { env } = run(`a = 4; a *= 3;`);
116
+ expect(env.a).toEqual(12);
117
+ });
118
+
119
+ it("`/=` divides", () => {
120
+ const { env } = run(`a = 12; a /= 4;`);
121
+ expect(env.a).toEqual(3);
122
+ });
123
+
124
+ it("`%=` modulo", () => {
125
+ const { env } = run(`a = 10; a %= 3;`);
126
+ expect(env.a).toEqual(1);
127
+ });
128
+
129
+ it("`+=` on strings concatenates", () => {
130
+ const { env } = run(`s = "hello"; s += " world";`);
131
+ expect(env.s).toEqual("hello world");
132
+ });
133
+
134
+ it("compound assignment works on nested paths", () => {
135
+ const { env } = run(`o = { n: 1 }; o.n += 10;`);
136
+ expect(env.o.n).toEqual(11);
137
+ });
138
+
139
+ it("`||=` writes only when lhs is falsy", () => {
140
+ expect(run(`a = 0; a ||= 5; a;`).result).toEqual(5);
141
+ expect(run(`a = 7; a ||= 5; a;`).result).toEqual(7);
142
+ });
143
+
144
+ it("`&&=` writes only when lhs is truthy", () => {
145
+ expect(run(`a = 0; a &&= 5; a;`).result).toEqual(0);
146
+ expect(run(`a = 7; a &&= 5; a;`).result).toEqual(5);
147
+ });
148
+
149
+ it("`??=` writes only when lhs is nullish", () => {
150
+ expect(run(`a = null; a ??= 5; a;`).result).toEqual(5);
151
+ expect(run(`a = 0; a ??= 5; a;`).result).toEqual(0);
152
+ });
153
+
154
+ it("`||=` does not evaluate rhs when lhs is truthy", () => {
155
+ const code = `
156
+ count = 0;
157
+ side = () => { count = count + 1; return 42; };
158
+ a = 7;
159
+ a ||= side();
160
+ [a, count];
161
+ `;
162
+ const { result } = run(code);
163
+ expect(result).toEqual([7, 0]);
164
+ });
165
+
166
+ it("compound assignment still blocks dangerous paths on the LHS", () => {
167
+ expect(() => run(`o = {}; o.__proto__ += 1`)).toThrow(
168
+ "Access to property '__proto__' is not allowed"
169
+ );
170
+ });
171
+ });
@@ -18,20 +18,24 @@ function assertSafeParts(parts: string[]): void {
18
18
  }
19
19
  }
20
20
 
21
- function deepHas(obj: any, path: string): boolean {
22
- const parts = path.split(".");
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
- let current = obj;
25
- for (const part of parts) {
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, part)) return false;
28
- current = current[part];
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, path: string): 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, path: string, value: any): void {
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(name: string): boolean {
95
- if (name in this.vars) {
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(name: string, loc: Loc): any {
105
- if (name in this.vars) {
106
- return this.vars[name];
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
- `"${name}" is not defined (${loc.line}:${loc.column})`
178
+ `"${path.join(".")}" is not defined (${loc.line}:${loc.column})`
113
179
  );
114
180
  }
115
181
 
116
- set(name: string, value: any, loc: Loc): any {
117
- const baseName = name.replace(/\..*/, "");
118
- const scope = this.lookup(baseName);
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(name: string, value: any): any {
129
- deepSet(this.vars, name, value);
188
+ def(path: string[], value: any): any {
189
+ deepSet(this.vars, path, value);
130
190
  return value;
131
191
  }
132
192
  }