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,8 @@
1
+ # Changesets
2
+
3
+ Hello and welcome! This folder has been automatically generated by `@changesets/cli`, a build tool that works
4
+ with multi-package repos, or single-package repos to help you version and publish your code. You can
5
+ find the full documentation for it [in our repository](https://github.com/changesets/changesets).
6
+
7
+ We have a quick list of common questions to get you started engaging with this project in
8
+ [our documentation](https://github.com/changesets/changesets/blob/main/docs/common-questions.md).
@@ -0,0 +1,11 @@
1
+ {
2
+ "$schema": "https://unpkg.com/@changesets/config@3.1.3/schema.json",
3
+ "changelog": "@changesets/cli/changelog",
4
+ "commit": false,
5
+ "fixed": [],
6
+ "linked": [],
7
+ "access": "public",
8
+ "baseBranch": "main",
9
+ "updateInternalDependencies": "patch",
10
+ "ignore": []
11
+ }
@@ -0,0 +1,62 @@
1
+ name: release
2
+
3
+ # Publishes to npm via OIDC trusted publishing — no NPM_TOKEN secret.
4
+ #
5
+ # Triggered by pushing an annotated tag like `v0.1.1`. The local `pnpm release`
6
+ # script handles versioning, committing, tagging, and pushing — the tag push
7
+ # is what starts this workflow.
8
+ #
9
+ # If this workflow file is renamed, update the matching Trusted Publisher
10
+ # config at https://www.npmjs.com/package/scriptable/access — the
11
+ # "Workflow filename" field takes the basename only (e.g. `release.yml`).
12
+
13
+ on:
14
+ push:
15
+ tags:
16
+ - "v*"
17
+
18
+ jobs:
19
+ publish:
20
+ runs-on: ubuntu-latest
21
+ permissions:
22
+ # id-token: write is required for OIDC trusted publishing to npm.
23
+ # This lets `changeset publish` exchange a short-lived GitHub Actions
24
+ # token for an npm publish token — no long-lived NPM_TOKEN secret
25
+ # ever exists in this repo.
26
+ id-token: write
27
+ contents: read
28
+
29
+ steps:
30
+ - uses: actions/checkout@v6
31
+
32
+ - uses: pnpm/action-setup@v5
33
+ with:
34
+ version: 10
35
+
36
+ # Node 24, NOT 22. npm trusted publishing requires npm >= 11.5.1, and
37
+ # Node 22 LTS is permanently stuck on npm 10.9.x.
38
+ - uses: actions/setup-node@v6
39
+ with:
40
+ node-version: 24
41
+ registry-url: https://registry.npmjs.org
42
+ cache: pnpm
43
+
44
+ - name: Install dependencies
45
+ run: pnpm install --frozen-lockfile --ignore-scripts
46
+
47
+ - name: Test
48
+ run: pnpm test
49
+
50
+ - name: Build
51
+ run: pnpm build
52
+
53
+ # --no-git-tag: the tag already exists (we pushed it from the
54
+ # maintainer's laptop — that tag push is what triggered this
55
+ # workflow), so skip changesets' tag creation step.
56
+ # NPM_CONFIG_PROVENANCE=true: stamps the package with an npm
57
+ # provenance attestation so the npmjs.com page shows "Built
58
+ # and signed on GitHub Actions".
59
+ - name: Publish to npm
60
+ run: pnpm exec changeset publish --no-git-tag
61
+ env:
62
+ NPM_CONFIG_PROVENANCE: "true"
package/CHANGELOG.md ADDED
@@ -0,0 +1,42 @@
1
+ # scriptable
2
+
3
+ ## 0.2.0
4
+
5
+ ### Minor Changes
6
+
7
+ - 3fcb7fc: Add `maxAllocSize` option to `runner()` (default 1,000,000). Caps the length of any string or array value produced during a run. Without this bound, exponential growth from string concat (`s = s + s`), template literals, or `concat()` stayed well within the step budget — 26 doublings from an 8-char seed could allocate ~512 MiB. Array spread now also enforces projected length before growing, using a loop instead of `push(...spread)` so enforcement fires at `maxAllocSize` rather than V8's ~65K argument-stack ceiling. Set to `0` to disable.
8
+ - ae442ce: Add `maxCodeSize` option to `runner()` (default 64 KiB). The step counter bounds execution but not parsing — acorn still reads multi-megabyte input before the interpreter sees it, which is ~200ms of CPU per 50 MB on a modern machine. Sources over the limit now throw before `acorn.parse` is called. Set to `0` to disable.
9
+
10
+ ### Patch Changes
11
+
12
+ - ed90a55: Address the remaining findings from the v0.1.1 security audit:
13
+
14
+ - **Computed keys with literal dots are preserved** (audit #4). `evalAsPath` now returns `string[]` segments instead of a dotted string, so `a["x.y"] = 1` stores under the literal key `"x.y"` rather than being silently re-split into `a.x.y` by `deepSet`. Read and write are now consistent. The change is internal — `evalAsPath` and the `Environment` get/set/def/defined methods now take `string[]`; the public `runner` API is unchanged.
15
+ - **Dotted paths resolve through parent scope** (audit #5). `deepHas`/`deepGet` used `hasOwnProperty` on every segment, but `env.vars = Object.create(parent.vars)` makes outer-scope variables visible only via the prototype chain — so `obj.method()` inside a nested function threw `"obj.method is not a function"` whenever `obj` lived in an enclosing scope. First segment now uses `in` (walks the chain); subsequent segments still use `hasOwn` so user-land objects can't leak `Object.prototype` members through the lookup.
16
+ - **`maxAllocSize` now bounds object key count** (audit #7). Previously only strings and arrays were size-checked, so `reduce(arr, (acc, k) => ({...acc, [k]: k}), {})` could grow an accumulator to `maxSteps` keys without tripping any cap. `ObjectExpression` now projects `ownCount + (spread ? spread.keys : 1)` against `maxAllocSize` before each write.
17
+ - **New `options.maxDurationMs`** bounds wall-clock time per run (audit #6). The step counter only increments inside `evaluate()`, so long native builtin calls (`sort` on a 1M-element array ≈ 1.7s) run uninterrupted. The deadline is checked in `Runtime.step()` between interpreter steps — a single long native call can overshoot by up to its own duration, but subsequent work is rejected. Defaults to `0` (disabled); opt in for hostile multi-tenant workloads.
18
+
19
+ - 4548bd1: Block `__proto__`, `constructor`, `prototype`, and the legacy descriptor methods as keys in object literals (`{ "__proto__": … }`, `{ [expr]: … }`, shorthand, and spread). Previously user code could set the prototype of a fresh object via literal `__proto__` and emit booby-trapped "constructor" own properties that would ride along when the caller merged `env.vars` into a host object. Also fixes `{[identifier]: value}` — the computed key now evaluates to the identifier's value instead of the literal name.
20
+ - b950626: Fix computed member access on the LHS of assignments and on call targets. Previously `a[k] = v` wrote to a property named `k` (the identifier name) instead of the property named by the _value_ of `k`; the same bug affected dotted-path resolution of call targets. The LHS and callee resolver now evaluates the key of a computed member (`a[expr]`) in the current environment, and rejects runtime-resolved blocked keys (`k = "constructor"; a[k] = …`). CallExpression now also handles dynamic callees (e.g. `f()()`, `((x) => x)(v)`) by evaluating the callee as a value when it isn't a static path.
21
+ - ed90a55: Harden builtin lookup and fix two long-standing semantic bugs surfaced by a security audit:
22
+
23
+ - `CallExpression` now resolves builtins with `hasOwn` instead of `functions[name]`. A plain-object `functions` map inherits from `Object.prototype`, so `constructor()` previously resolved to `Object` and returned `{}`, `toString()` resolved to `Object.prototype.toString`, etc. Not directly exploitable (blocked property access on the returned wrappers still threw) but a defense-in-depth gap that vanished the moment a builtin name collided with an `Object.prototype` member.
24
+ - `LogicalExpression` now short-circuits. `a || b` and `a && b` used to eagerly evaluate both sides, so `guard && action()` always ran `action()`. `??` is also supported.
25
+ - `AssignmentExpression` now honours its operator. `a += 1` used to silently behave as `a = 1`; compound ops (`+=`, `-=`, `*=`, `/=`, `%=`, `||=`, `&&=`, `??=`) now read-combine-write, with the logical compounds short-circuiting. The LHS still goes through the blocked-property checks.
26
+
27
+ - 9b3897a: Fix `return` statements nested inside `if` (or any other non-`ReturnStatement` node) so they correctly short-circuit the enclosing function body. Previously `BlockStatement` only broke its iteration loop when the _immediate_ statement was a `ReturnStatement`, so `function f(n) { if (n == 0) return 1; … }` would evaluate the guarded return but then continue executing the statements after the `if`. `ReturnStatement` now throws a `ReturnValue` sentinel that unwinds to the nearest function boundary (`makeFunc`), which is the standard control-flow mechanism for tree-walking interpreters. This also unblocks idiomatic recursive functions that use a guard-then-recurse pattern.
28
+ - 0cea1d6: Give each function invocation its own scope. `makeFunc` previously hoisted `const scope = env.extend()` to closure-creation time and reused it for every call, so a recursive call overwrote the caller's params (and any `let`/`const` set on the function scope). Moved the `env.extend()` inside the returned closure so every call gets a fresh child of the captured lexical parent.
29
+ - 0fbe14e: Move execution step counter from module-global state onto a per-run `Runtime` carried by `Environment`. Previously, a synchronously re-entrant run (e.g. a caller-injected function that itself invokes the interpreter) would reset the shared counter and silently bypass the outer run's `maxSteps` budget. Each run now owns its own step state.
30
+
31
+ ## 0.1.1
32
+
33
+ ### Patch Changes
34
+
35
+ - e243ccb: Releases are now published from GitHub Actions via npm OIDC trusted publishing. Each published artifact carries an npm provenance attestation, and no `NPM_TOKEN` secret is stored anywhere.
36
+
37
+ ## 0.1.0
38
+
39
+ ### Minor Changes
40
+
41
+ - Rewritten in TypeScript, using the `acorn` parser. All legacy runtime dependencies have been dropped.
42
+ - Hardened the sandbox: fixed a set of sandbox-escape and prototype-pollution vectors, and added DoS protections (execution limits) so runaway scripts can no longer lock up the host process.
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 |
@@ -137,3 +150,49 @@ All tests ported to Vitest. The moment-dependent date tests now use `Intl.DateTi
137
150
  - ESM (`"type": "module"`) with TypeScript build
138
151
  - pnpm for package management
139
152
  - `exports` field with types
153
+
154
+ ## Contributing
155
+
156
+ ### Adding a changeset
157
+
158
+ Every user-facing change needs a changeset so it appears in the CHANGELOG:
159
+
160
+ ```bash
161
+ pnpm changeset # interactive: pick patch/minor/major, write a summary
162
+ git add .changeset # commit the generated .changeset/*.md file with your PR
163
+ ```
164
+
165
+ ### Releasing
166
+
167
+ ```bash
168
+ pnpm release
169
+ ```
170
+
171
+ This runs the release script (`scripts/release.js`), which:
172
+
173
+ 1. Guards: clean tree, on `main`, up to date with `origin/main`, pending changesets exist.
174
+ 2. Runs tests and build as a safety gate.
175
+ 3. Consumes changesets to bump `package.json` and update `CHANGELOG.md`.
176
+ 4. Commits as `Version X.Y.Z` and shows the diff.
177
+ 5. Prompts for confirmation (last chance to abort).
178
+ 6. Pushes `main`, creates an annotated `vX.Y.Z` tag, and pushes the tag.
179
+ 7. The tag push triggers `.github/workflows/release.yml`, which publishes to npm via OIDC trusted publishing with provenance attestation. No `NPM_TOKEN` is involved.
180
+
181
+ ### Recovery: if the release workflow fails after the tag is pushed
182
+
183
+ The version commit is on `main` and the tag is pushed, but npm publish failed. You can't rerun `pnpm release` because the changesets have already been consumed.
184
+
185
+ ```bash
186
+ # 1. Delete the tag locally and on the remote
187
+ git tag -d vX.Y.Z
188
+ git push origin :refs/tags/vX.Y.Z
189
+
190
+ # 2. Fix whatever broke, commit on main
191
+ git commit -am "fix(ci): ..."
192
+ git push origin main
193
+
194
+ # 3. Re-tag HEAD (annotated!) and push to re-trigger the workflow.
195
+ # Same version number — this is a retry, not a new version.
196
+ git tag -a vX.Y.Z -m "Version X.Y.Z"
197
+ git push origin vX.Y.Z
198
+ ```
@@ -0,0 +1,81 @@
1
+ # Security Audit — scriptable@0.1.1
2
+
3
+ ## Scope
4
+
5
+ `scriptable` is a sandboxed JavaScript expression evaluator. User code is parsed by `acorn` into an AST and executed by a tree-walking interpreter in `src/evaluate.ts`. The audit covered the interpreter surface, the environment/scope implementation, builtin functions, and the dependency tree.
6
+
7
+ ## Audit findings
8
+
9
+ ### Code-injection sinks (eval / new Function / child_process)
10
+
11
+ **None present.** `rg "\beval\b|new Function|child_process|execSync"` across `src/` matches only identifiers inside *user-supplied script strings in tests* (e.g. `eval("1+1")` as an attacker payload, which the sandbox correctly rejects with `"eval is not a function"`). The interpreter never lowers user code into the host's `eval` or `Function` — it walks the acorn AST directly.
12
+
13
+ > Explicit non-change: **did not introduce `vm2`.** `vm2` was deprecated in 2023 after multiple unfixable sandbox-escape CVEs (GHSA-ch3r-j5x3-6q2m, GHSA-g644-9gfx-q4q4, GHSA-cchq-frhr-rjg8). Swapping the current AST-walker for `vm2` would be a security regression, not a mitigation. The existing "interpret the AST, never hand a string to the host runtime" design is strictly safer than any `vm`-module–based sandbox.
14
+
15
+ ### Prototype pollution / sandbox escape
16
+
17
+ Already hardened. `BLOCKED_PROPS = {constructor, __proto__, prototype, __defineGetter__, __defineSetter__, __lookupGetter__, __lookupSetter__}` is enforced in four places:
18
+
19
+ 1. `evaluate.ts` `MemberExpression` — blocks `a.constructor`, `a["__proto__"]`, and variable-indirected forms (`k = "constructor"; a[k]`).
20
+ 2. `evaluate.ts` `evalAsPath` — blocks the same names on assignment LHS and call callees (`a.__proto__ = x`, `a.constructor(...)`).
21
+ 3. `evaluate.ts` `ObjectExpression` — rejects blocked keys as object-literal keys (static, computed, and shorthand), so `{__proto__: {...}}` cannot set the prototype of a fresh literal; spreads drop blocked own-keys by manual copy (not `Object.assign`, which invokes the `__proto__` setter).
22
+ 4. `environment.ts` `assertSafeParts` — `deepHas` / `deepGet` / `deepSet` re-check every segment so nothing slips through a deep path.
23
+
24
+ Host-provided `env` values flow through the same sandbox (`env.constructor` still throws). 84 tests in `security.test.ts` plus 17 in `audit-followups.test.ts` cover these paths.
25
+
26
+ ### Forbidden language surface
27
+
28
+ `ThisExpression`, `NewExpression`, `ImportExpression`, and `arguments` have no `evals[...]` handler, so they throw `"Cannot evaluate <Type>"` or `"<name> is not defined"` — i.e. `eval`, `Function`, `require`, `process`, `globalThis`, and `import()` are all unreachable.
29
+
30
+ ### DoS controls (per-run limits)
31
+
32
+ Already in place via `Runtime`:
33
+
34
+ - `maxSteps` (default 100 000) — interpreter step budget, checked every `evaluate()`.
35
+ - `maxCodeSize` (default 64 KiB) — bounds parser work before acorn runs.
36
+ - `maxAllocSize` (default 1 000 000) — bounds string length, array length, and object own-key count; checked on every value returned from a handler and projected before array/spread growth to trip before V8's 65 K argument-stack limit.
37
+ - `maxDurationMs` (default 0, opt-in) — wall-clock deadline checked between steps; guards against long native builtin calls (`sort` on 1M-element array) that don't advance the step counter.
38
+
39
+ Counters live on a per-run `Runtime` instance (not a module global), so re-entrant runs (`runInner` callback pattern) can't leak budget between caller and callee — regression test at `security.test.ts:297`.
40
+
41
+ ### Dependencies
42
+
43
+ `pnpm audit` reported:
44
+
45
+ | Severity | Package | Advisory |
46
+ |----------|---------|----------|
47
+ | high | vite (transitive via vitest) | [GHSA-v2wj-q39q-566r](https://github.com/advisories/GHSA-v2wj-q39q-566r) — `server.fs.deny` bypass |
48
+ | high | vite | [GHSA-p9ff-h696-f583](https://github.com/advisories/GHSA-p9ff-h696-f583) — arbitrary file read via dev-server WebSocket |
49
+ | moderate | vite | [GHSA-4w7w-66w2-5vf9](https://github.com/advisories/GHSA-4w7w-66w2-5vf9) — path traversal in optimized deps |
50
+
51
+ All three are **dev-dependency-only** (vitest's test-runner dev-server) and do not ship to consumers of `@lecstor/scriptable`. Runtime dep is only `acorn@^8.14.1`, which has no open advisories.
52
+
53
+ ## Changes made
54
+
55
+ ### 1. `package.json` — update vitest and pin vite to a patched version
56
+
57
+ ```diff
58
+ - "vitest": "^3.1.0"
59
+ + "vitest": "^4.1.4"
60
+ + "pnpm": { "overrides": { "vite": "^7.3.2" } }
61
+ ```
62
+
63
+ - Bumped `vitest` 3.2.4 → 4.1.4.
64
+ - Added a `pnpm.overrides` entry forcing `vite` to ≥ 7.3.2 (earliest version patched for all three advisories). `vitest@4.1.4`'s peer resolves to `vite@7.3.1`, which is still vulnerable; the override pulls 7.3.2+ without breaking the peer range.
65
+ - Regenerated `pnpm-lock.yaml`; `pnpm audit` now reports **"No known vulnerabilities found"**.
66
+
67
+ ### 2. Validation
68
+
69
+ All 198 existing tests pass on the updated toolchain (`pnpm test`), including the 101 security/audit-followup tests exercising prototype-chain blocks, `__proto__` handling, deep-path pollution, DoS caps, and re-entrance isolation.
70
+
71
+ ## Items considered and deliberately not changed
72
+
73
+ - **`var` in `src/`** — the only occurrence is `if (exp.kind === "var")` in `evaluate.ts:379`, where the interpreter handles the `var` keyword from *user scripts*. No TypeScript source uses `var` itself.
74
+ - **CSP / strict headers** — not applicable. `scriptable` is a library, not a server; it emits no HTTP responses. A CSP would belong to the embedder, not the library.
75
+ - **"Use strict"** — `type: "module"` in `package.json` makes every `src/*.ts` implicit strict mode; adding `"use strict"` directives would be dead code.
76
+ - **Replacing the AST walker with `vm2` / `vm` / `isolated-vm`** — see note above. The current design is strictly safer than `vm2` and does not require a native addon the way `isolated-vm` does.
77
+
78
+ ## Residual risk
79
+
80
+ - Host-provided builtins (`functions` map) and host-provided `env` values run with full host privilege. A caller that passes `{ fs }` into `env` has voluntarily handed the sandbox a filesystem. This is by design and documented in the README; the sandbox only guarantees that the *script text* cannot reach host capabilities it was not explicitly given.
81
+ - `maxDurationMs` defaults to `0` (disabled). Single-tenant callers running trusted templates don't need it; multi-tenant hostile workloads should opt in.
@@ -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
- constructor(parent?: Environment);
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(name: string): boolean;
13
- get(name: string, loc: Loc): any;
14
- set(name: string, value: any, loc: Loc): any;
15
- def(name: string, value: any): any;
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
  }
@@ -16,21 +16,27 @@ function assertSafeParts(parts) {
16
16
  }
17
17
  }
18
18
  }
19
- function deepHas(obj, path) {
20
- const parts = path.split(".");
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
- let current = obj;
23
- for (const part of parts) {
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, part))
33
+ if (!Object.prototype.hasOwnProperty.call(current, parts[i]))
27
34
  return false;
28
- current = current[part];
35
+ current = current[parts[i]];
29
36
  }
30
37
  return true;
31
38
  }
32
- function deepGet(obj, path) {
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, path, value) {
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(name) {
81
- if (name in this.vars) {
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(name, loc) {
90
- if (name in this.vars) {
91
- return this.vars[name];
144
+ get(path, loc) {
145
+ if (deepHas(this.vars, path)) {
146
+ return deepGet(this.vars, path);
92
147
  }
93
- if (deepHas(this.vars, name)) {
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(name, value, loc) {
99
- const baseName = name.replace(/\..*/, "");
100
- const scope = this.lookup(baseName);
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(name, value) {
108
- deepSet(this.vars, name, value);
155
+ def(path, value) {
156
+ deepSet(this.vars, path, value);
109
157
  return value;
110
158
  }
111
159
  }
@@ -1,5 +1,4 @@
1
1
  import type { Node } from "acorn";
2
2
  type AnyNode = Node & Record<string, any>;
3
- export declare function resetStepCounter(maxSteps: number): void;
4
3
  declare function evaluate(exp: AnyNode, env?: any, functions?: any): any;
5
4
  export default evaluate;