From 1618874f10acacd5173c4393e590f36263e2b1f5 Mon Sep 17 00:00:00 2001 From: Timothy Wayne Gregg Date: Sun, 25 Oct 2026 18:14:56 -0400 Subject: [PATCH] feat: inspect bounded NodeVM source configuration candidates --- .github/workflows/tests.yml | 2 +- AGENTS.md | 2 +- README.md | 37 ++++- SHA256SUMS | 2 +- docs/IMPLEMENTATION.md | 4 + docs/REFERENCE.md | 45 +++++- examples/source.example.js | 4 + test_source.py | 168 ++++++++++++++++++++++ vm2_nesting_check.py | 271 ++++++++++++++++++++++++++++++++++-- 9 files changed, 520 insertions(+), 15 deletions(-) create mode 100644 examples/source.example.js create mode 100644 test_source.py diff --git a/.github/workflows/tests.yml b/.github/workflows/tests.yml index 705522a..15b4996 100644 --- a/.github/workflows/tests.yml +++ b/.github/workflows/tests.yml @@ -16,7 +16,7 @@ jobs: strategy: fail-fast: false matrix: - os: [ubuntu-latest, windows-latest] + os: [ubuntu-latest, windows-latest, macos-latest] python: ['3.10', '3.14'] steps: - name: Check out repository diff --git a/AGENTS.md b/AGENTS.md index 5926206..0a016f0 100644 --- a/AGENTS.md +++ b/AGENTS.md @@ -8,7 +8,7 @@ before changing this project. This repository covers only **CVE-2026-92935** (vm2 array-shaped require nesting escape). Its aliases refer to the same exploit. Keep unrelated vulnerabilities in separate repositories. -The repository contains the offline checker `vm2_nesting_check.py`, synthetic tests and CI. Preserve the exact affected interval, disputed boundaries and reviewed fixed line; no network mode or application execution is implemented. +The repository contains the offline checker `vm2_nesting_check.py`, synthetic tests and CI. Optional --source produces bounded lexical NodeVM candidates, never runtime configuration or taint proof. Preserve the exact affected interval, disputed boundaries and reviewed fixed line; no network mode or application execution is implemented. ## Project map diff --git a/README.md b/README.md index 2042121..62e4aae 100644 --- a/README.md +++ b/README.md @@ -36,7 +36,42 @@ The reviewed fixed line is `3.11.x`; future lines remain unknown rather than ext | `require_configuration_is_array_shaped` | require configuration is array-shaped | | `attacker_supplied_javascript_executed` | attacker-supplied JavaScript executed | -Each observation is boolean or null, is unverified, and never changes the package-version result. No source search, taint analysis, reachability test, or runtime evaluation is performed. Absent observations do not establish mitigation. +Each observation is boolean or null, is unverified, and never changes the package-version result. Optional source inspection produces separate lexical candidates. No taint analysis, reachability test or runtime evaluation is performed. Absent observations do not establish mitigation. + +## Source review candidates + +```sh +python vm2_nesting_check.py --source examples/source.example.js --source-root examples --format json +python vm2_nesting_check.py --version 3.11.6 --source examples/source.example.js --source-root examples --format html +``` + +Select files explicitly with repeatable `--source`; `--source-root` is required +and all selected paths must resolve inside it. Nothing is traversed or executed. +The scanner recognizes simple literal `vm2` CommonJS/ES imports, including +destructuring aliases and namespace `.NodeVM` construction. For each `new` +candidate it records the relative path/line, literal `nesting`, array/object or +literal `require` shape, and a lexical association to `.run()` on a directly +assigned variable. A string argument is not proof of trusted input; a variable +argument is not proof of attacker control. Source rows always have status +`unknown`, exploitability `not_tested` and unfilled operator preconditions. +They never inherit a separately supplied version's assessment. + +This is a bounded lexical review aid, not an AST or binding/flow analysis. +Shadowing, reassignment, execution order, computed imports/options, JSX/TS syntax, +templates including interpolation and regex/division ambiguity need manual +review. When no supported match is found, the report includes an unknown +coverage row, never an absence or mitigation verdict. Spreads, duplicate/computed keys, dynamic options +and option expressions exceeding 4,096 tokens keep their shapes unknown. + +Source shares the existing 4 MiB/file, 100-file and 10,000-result budgets, with +an additional 200,000-token/file limit. Reports contain relative locations and +shape labels, without source snippets or source string contents. Work from +stable copies; ordinary file checks are not a filesystem sandbox. Selected +source files and their aliases remain protected from `--output --force`. +CSV/JSON report schema 1.1 adds `source_path`, `source_line`, `source_nesting`, +`source_require`, `source_run_argument` and `source_coverage`; HTML includes these +candidates in its evidence notes. Source candidates do not trigger the version +finding gate by themselves. ## Evidence and reports diff --git a/SHA256SUMS b/SHA256SUMS index e246ec1..f26df44 100644 --- a/SHA256SUMS +++ b/SHA256SUMS @@ -1 +1 @@ -0dc11d3fb2b1ff3bb5a723551513a05e0e835246be7bb2e0391dc2da9264cf57 vm2_nesting_check.py +c513513958376d2915b026a3f869d31211f798ad4c48c4d0a5e97ff6be3b0652 vm2_nesting_check.py diff --git a/docs/IMPLEMENTATION.md b/docs/IMPLEMENTATION.md index 7982de2..cde90a4 100644 --- a/docs/IMPLEMENTATION.md +++ b/docs/IMPLEMENTATION.md @@ -5,3 +5,7 @@ Implemented offline package-version evidence checker, with independent source/se Local verification: 13 tests, CLI help, documented synthetic inputs, checksum validation and whitespace checks. Hosted CI must pass for the exact final PR head before merge; a local pass is not a hosted result. The advisory metadata now describes the implemented rule and preserves its original disabled research state under research_origin. No live traffic, application execution, exploit verification or deployed-target assessment is claimed. Reported fixed versions do not attest installed patches; unknown evidence remains unknown. + +## Source candidate extension (2026-10-25) + +Implemented explicit bounded JS/TS source selection, literal vm2 import aliases, NodeVM construction and configuration shapes, relative locations and lexical run-argument association. Source evidence stays unknown, separate from version/operator observations. No AST, trust or runtime attestation is claimed. Templates, shadowing and dynamic syntax require manual review. Added source-specific synthetic tests and macOS CI; exact-head hosted checks remain a separate release gate. See README/REFERENCE for actual commands, schema 1.1 and bounds. Advisory thresholds and rule date are unchanged. diff --git a/docs/REFERENCE.md b/docs/REFERENCE.md index bc5afe4..e75c9dc 100644 --- a/docs/REFERENCE.md +++ b/docs/REFERENCE.md @@ -1,4 +1,4 @@ -# Evidence and CLI reference +# vm2-nesting-check Offline evidence checker for **CVE-2026-92935 — vm2 array-shaped require nesting escape**. Python 3.10+, standard library only. The executable can be copied alone. It never contacts websites, imports application code, runs a package manager, or executes exploit payloads. @@ -36,7 +36,42 @@ The reviewed fixed line is `3.11.x`; future lines remain unknown rather than ext | `require_configuration_is_array_shaped` | require configuration is array-shaped | | `attacker_supplied_javascript_executed` | attacker-supplied JavaScript executed | -Each observation is boolean or null, is unverified, and never changes the package-version result. No source search, taint analysis, reachability test, or runtime evaluation is performed. Absent observations do not establish mitigation. +Each observation is boolean or null, is unverified, and never changes the package-version result. Optional source inspection produces separate lexical candidates. No taint analysis, reachability test or runtime evaluation is performed. Absent observations do not establish mitigation. + +## Source review candidates + +```sh +python vm2_nesting_check.py --source examples/source.example.js --source-root examples --format json +python vm2_nesting_check.py --version 3.11.6 --source examples/source.example.js --source-root examples --format html +``` + +Select files explicitly with repeatable `--source`; `--source-root` is required +and all selected paths must resolve inside it. Nothing is traversed or executed. +The scanner recognizes simple literal `vm2` CommonJS/ES imports, including +destructuring aliases and namespace `.NodeVM` construction. For each `new` +candidate it records the relative path/line, literal `nesting`, array/object or +literal `require` shape, and a lexical association to `.run()` on a directly +assigned variable. A string argument is not proof of trusted input; a variable +argument is not proof of attacker control. Source rows always have status +`unknown`, exploitability `not_tested` and unfilled operator preconditions. +They never inherit a separately supplied version's assessment. + +This is a bounded lexical review aid, not an AST or binding/flow analysis. +Shadowing, reassignment, execution order, computed imports/options, JSX/TS syntax, +templates including interpolation and regex/division ambiguity need manual +review. When no supported match is found, the report includes an unknown +coverage row, never an absence or mitigation verdict. Spreads, duplicate/computed keys, dynamic options +and option expressions exceeding 4,096 tokens keep their shapes unknown. + +Source shares the existing 4 MiB/file, 100-file and 10,000-result budgets, with +an additional 200,000-token/file limit. Reports contain relative locations and +shape labels, without source snippets or source string contents. Work from +stable copies; ordinary file checks are not a filesystem sandbox. Selected +source files and their aliases remain protected from `--output --force`. +CSV/JSON report schema 1.1 adds `source_path`, `source_line`, `source_nesting`, +`source_require`, `source_run_argument` and `source_coverage`; HTML includes these +candidates in its evidence notes. Source candidates do not trigger the version +finding gate by themselves. ## Evidence and reports @@ -51,6 +86,10 @@ Exit 0: completed run; 1: potentially affected with `--fail-on-finding`; 2: argu - https://github.com/patriksimek/vm2/security/advisories/GHSA-8hr7-r645-pc6w - https://github.com/advisories/GHSA-8hr7-r645-pc6w -[Synthetic report](docs/example-report.html), [reference](docs/REFERENCE.md), [implementation status](docs/IMPLEMENTATION.md), [AGENTS](AGENTS.md), [contribution terms](CONTRIBUTING.md), [security policy](SECURITY.md), [license](LICENSE), [dual licensing](LICENSING.md). Bounded input and reporting helpers are bundled from the reviewed Node.js checker at `74aa57ba5df05c34d17ae67912cd26ec2335201b`, with package-specific range comparison and the mixed-whitespace CSV fix. No companion repository is needed at runtime. +[Synthetic report](example-report.html), [reference](REFERENCE.md), [implementation status](IMPLEMENTATION.md), [AGENTS](../AGENTS.md), [contribution terms](../CONTRIBUTING.md), [security policy](../SECURITY.md), [license](../LICENSE), [dual licensing](../LICENSING.md). Bounded input and reporting helpers are bundled from the reviewed Node.js checker at `74aa57ba5df05c34d17ae67912cd26ec2335201b`, with package-specific range comparison and the mixed-whitespace CSV fix. No companion repository is needed at runtime. CSV `record_type=result` rows are asset observations. A zero-result report has a `record_type=summary` row carrying completeness, schema, rule date, CVE and `not_tested`; it is not an asset finding. + +CSV rejects NUL characters before writing a report. An interruption after a complete report is published preserves that report and exits 130. + +If an interrupt leaves file publication indeterminate, the checker exits 130 without retrying. Inspect the output before retrying; the diagnostic does not establish whether publication succeeded. diff --git a/examples/source.example.js b/examples/source.example.js new file mode 100644 index 0000000..fa313e3 --- /dev/null +++ b/examples/source.example.js @@ -0,0 +1,4 @@ +// Synthetic review fixture. This file is read as text, never executed. +const { NodeVM: ReviewVM } = require('vm2'); +const sandbox = new ReviewVM({ nesting: true, require: [] }); +sandbox.run(operatorSuppliedCode); diff --git a/test_source.py b/test_source.py new file mode 100644 index 0000000..418f9c1 --- /dev/null +++ b/test_source.py @@ -0,0 +1,168 @@ +"""Synthetic source review cases; never execute JavaScript or contact targets.""" +import contextlib +import csv +import io +import json +import os +from pathlib import Path +import subprocess +import sys +import tempfile +import unittest +from unittest import mock + +import vm2_nesting_check as c + + +class SourceTests(unittest.TestCase): + def scan(self, code): + return c.scan_source_text(code, "src/service.ts") + + def cli(self, *args): + with contextlib.redirect_stdout(io.StringIO()) as out, contextlib.redirect_stderr(io.StringIO()) as err: + code = c.main(list(args)) + return code, out.getvalue(), err.getvalue() + + def test_import_bound_aliases_and_namespace_imports(self): + for binding, constructor in [ + ("const {NodeVM} = require('vm2');", "NodeVM"), + ("const {NodeVM: N} = require('vm2');", "N"), + ("const N = require('vm2').NodeVM;", "N"), + ("const vm = require('vm2');", "vm.NodeVM"), + ("import { NodeVM as N } from 'vm2';", "N"), + ("import { NodeVM as N, } from 'vm2';", "N"), + ("import * as vm from 'vm2';", "vm.NodeVM"), + ]: + with self.subTest(binding=binding): + rows = self.scan(binding + "\nconst sandbox = new " + constructor + "({nesting:true, require:[]});") + self.assertEqual(1, len(rows)) + row = rows[0] + self.assertEqual("lexical_source_candidate", row["evidence_type"]) + self.assertEqual(("literal_true", "array_candidate"), (row["source_nesting"], row["source_require"])) + self.assertEqual(2, row["source_line"]) + self.assertEqual("unknown", row["status"]) + self.assertEqual("not_reported", row["precondition_nodevm_nesting_enabled"]) + self.assertEqual("not_tested", row["exploitability"]) + + def test_off_defaults_require_shapes_and_dynamic_configuration(self): + cases = [ + ("", "not_specified", "not_specified"), + ("{}", "not_specified", "not_specified"), + ("{nesting:false, require:{builtin:[]}}", "literal_false", "object_candidate"), + ("{nesting:true, require:true}", "literal_true", "literal_true"), + ("{nesting:true, require:false}", "literal_true", "literal_false"), + ("{nesting:true, require:null}", "literal_true", "literal_null"), + ("{nesting:config.nesting, require:options}", "unknown", "unknown"), + ("{nesting:true, ...options, require:[]}", "unknown", "unknown"), + ("{nesting:true, nesting:false, require:[]}", "unknown", "unknown"), + ("{nesting:true, ['require']:[]}", "unknown", "unknown"), + ("options", "unknown", "unknown"), + ("{nesting:true, require:[] || []}", "literal_true", "unknown"), + ("{nesting:true, require:[]}, anotherOption", "unknown", "unknown"), + ] + for options, nesting, require in cases: + with self.subTest(options=options): + row = self.scan("import {NodeVM} from 'vm2'; new NodeVM(" + options + ");")[0] + self.assertEqual((nesting, require), (row["source_nesting"], row["source_require"])) + self.assertEqual("unknown", row["status"]) + + def test_comments_strings_templates_regex_and_unrelated_constructors(self): + code = r''' + import {NodeVM} from 'other'; + // new NodeVM({nesting:true, require:[]}); + /* const {NodeVM} = require('vm2'); new NodeVM({}); */ + const text = "const {NodeVM} = require('vm2'); new NodeVM({});"; + const template = `new NodeVM({nesting:true, require:[]})`; + const regex = /new NodeVM\(\{nesting:true, require:\[\]\}\)/; + new NodeVM({nesting:true, require:[]}); + ''' + rows = self.scan(code) + self.assertEqual(["source_coverage"], [r["evidence_type"] for r in rows]) + self.assertEqual("unknown", rows[0]["source_nesting"]) + # A genuine import does not turn text inside comments/strings into code. + self.assertEqual("source_coverage", self.scan("import {NodeVM} from 'vm2'; const s='new NodeVM({})';")[0]["evidence_type"]) + + def test_run_argument_shape_is_never_trust_or_taint(self): + prefix = "const {NodeVM} = require('vm2'); const sandbox = new NodeVM({nesting:true, require:[]});" + for expression, expected in [("'static text'", "literal_string"), ("request.body.code", "dynamic_or_unsupported"), ("trustedCode", "dynamic_or_unsupported"), ("`template`", "dynamic_or_unsupported")]: + row = self.scan(prefix + "sandbox.run(" + expression + ");")[0] + self.assertEqual(expected, row["source_run_argument"]) + self.assertEqual("not_reported", row["precondition_attacker_supplied_javascript_executed"]) + row = self.scan(prefix + "other.run(request.body.code);")[0] + self.assertEqual("not_observed", row["source_run_argument"]) + + def test_scopes_reassignment_and_same_name_remain_low_confidence_candidates(self): + row = self.scan("import {NodeVM} from 'vm2'; function f(NodeVM) { new NodeVM({nesting:true, require:[]}); }")[0] + self.assertEqual("unknown", row["status"]) + self.assertEqual("insufficient", row["evidence_confidence"]) + self.assertIn("shadowing", " ".join(row["notes"])) + + def test_malformed_and_token_limited_inputs_fail_closed(self): + for text in ["/* open", "'open", "`open", "({]", "const r=/open", "{"]: + with self.subTest(text=text), self.assertRaises(ValueError): + self.scan(text) + with self.assertRaises(ValueError): + self.scan(";" * 200001) + row = self.scan("import {NodeVM} from 'vm2'; new NodeVM({nesting:true, require:[" + "0," * 3000 + "]});")[0] + self.assertEqual(("unknown", "unknown"), (row["source_nesting"], row["source_require"])) + + def test_cli_relative_paths_separate_versions_and_output_parity(self): + with tempfile.TemporaryDirectory() as directory: + root = Path(directory) + path = root / "service.ts" + path.write_text("import {NodeVM} from 'vm2'; new NodeVM({nesting:true, require:[]});", encoding="utf-8") + args = ["--version", "3.11.7", "--source", str(path), "--source-root", str(root)] + code, out, err = self.cli(*args, "--format", "json", "--fail-on-finding") + self.assertEqual((0, ""), (code, err)) + rows = json.loads(out)["results"] + self.assertEqual(["fixed_version_reported", "unknown"], [r["status"] for r in rows]) + self.assertEqual("service.ts", rows[1]["source_path"]) + self.assertNotIn(str(root), out) + code, out, _ = self.cli(*args, "--format", "csv") + csv_rows = list(csv.DictReader(io.StringIO(out))) + self.assertEqual(rows[1]["source_require"], csv_rows[1]["source_require"]) + code, out, _ = self.cli(*args, "--format", "html") + self.assertIn("service.ts:1", out) + self.assertIn("array_candidate", out) + self.assertNotIn(str(root), out) + + def test_source_input_cannot_be_overwritten_even_with_force(self): + with tempfile.TemporaryDirectory() as directory: + path = Path(directory) / "input.js" + original = "const x=1;" + path.write_text(original, encoding="utf-8") + args = ["--source", str(path), "--source-root", directory] + self.assertEqual(2, self.cli(*args, "--output", str(path), "--force")[0]) + self.assertEqual(original, path.read_text(encoding="utf-8")) + if hasattr(os, "link"): + alias = Path(directory) / "alias.js" + os.link(path, alias) + self.assertEqual(2, self.cli(*args, "--output", str(alias), "--force")[0]) + + def test_source_root_bounds_file_bounds_and_no_execution(self): + with tempfile.TemporaryDirectory() as directory: + root = Path(directory) + path = root / "input.js" + path.write_text("process.exit(99);", encoding="utf-8") + with mock.patch.object(subprocess, "run", side_effect=AssertionError("must not execute")): + self.assertEqual(0, self.cli("--source", str(path), "--source-root", directory)[0]) + self.assertEqual(2, self.cli("--source", str(path))[0]) + child = root / "child" + child.mkdir() + self.assertEqual(2, self.cli("--source", str(path), "--source-root", str(child))[0]) + path.write_bytes(b" " * (c.MAX_INPUT_BYTES + 1)) + self.assertEqual(2, self.cli("--source", str(path), "--source-root", directory)[0]) + + def test_standalone_copy_retains_source_inspection(self): + with tempfile.TemporaryDirectory() as directory: + root = Path(directory) + checker = root / "checker.py" + checker.write_bytes(Path(c.__file__).read_bytes()) + source = root / "source.js" + source.write_text("import {NodeVM} from 'vm2'; new NodeVM({nesting:true,require:[]});", encoding="utf-8") + result = subprocess.run([sys.executable, str(checker), "--source", str(source), "--source-root", str(root), "--format", "json"], capture_output=True, text=True, check=True) + self.assertEqual("array_candidate", json.loads(result.stdout)["results"][0]["source_require"]) + + +if __name__ == "__main__": + unittest.main() diff --git a/vm2_nesting_check.py b/vm2_nesting_check.py index 798bbae..d6e5094 100644 --- a/vm2_nesting_check.py +++ b/vm2_nesting_check.py @@ -21,8 +21,8 @@ from pathlib import Path TOOL_NAME = "vm2-nesting-check" -TOOL_VERSION = "1.0.0" -REPORT_SCHEMA_VERSION = "1.0" +TOOL_VERSION = "1.1.0" +REPORT_SCHEMA_VERSION = "1.1" MAX_INPUT_BYTES = 4 * 1024 * 1024 MAX_ENTRIES = 10000 MAX_FIELD = 512 @@ -149,6 +149,8 @@ def assess_version(package_version="", *, version_candidates=None, build_source= CSV_COLUMNS = ["record_type", "input_label", "input_source", "package_version", "build_source", "status", "version_status", "fixed_version", "exploitability", "evidence_type", "evidence_confidence", "cve", "rules_as_of", *[f"precondition_{key}" for key in PRECONDITION_KEYS], "recommendation", "notes", "sources", "report_schema_version", "report_complete"] +SOURCE_COLUMNS = ["source_path", "source_line", "source_nesting", "source_require", "source_run_argument", "source_coverage"] +CSV_COLUMNS += SOURCE_COLUMNS STATUS_ORDER = {"potentially_affected": 0, "unknown": 2, "fixed_version_reported": 3} STATUS_LABELS = {"potentially_affected": "Potentially affected", "unknown": "Unknown", "fixed_version_reported": "Fixed version reported"} @@ -226,6 +228,244 @@ def _read_bounded(path): return raw.decode("utf-8-sig") +def _js_tokens(text): + """Bounded lexical hints, not a JavaScript parser. Never retain source strings.""" + tokens = [] + index, line = 0, 1 + while index < len(text): + start = index + char = text[index] + if char.isspace(): + line += char == "\n" + index += 1 + continue + if text.startswith("//", index): + end = text.find("\n", index) + index = len(text) if end < 0 else end + continue + if text.startswith("/*", index): + end = text.find("*/", index + 2) + if end < 0: + raise ValueError("Unterminated JavaScript comment") + line += text.count("\n", index, end + 2) + index = end + 2 + continue + token_line = line + if char in "\"'`": + index += 1 + while index < len(text): + if text[index] == "\\": + index += 2 + elif text[index] == char: + index += 1 + break + else: + index += 1 + else: + raise ValueError("Unterminated JavaScript string or template") + raw = text[start + 1:index - 1] + value = "@template" if char == "`" else "@" + raw if raw in {"vm2", "nesting", "require"} else "@string" + line += text.count("\n", start, index) + elif char == "/" and (not tokens or tokens[-1][0] in {"=", "(", "[", "{", ":", ",", ";", "return", "=>"}): + # Regex bodies are opaque. Templates (including interpolations) are + # also opaque; the report always states incomplete lexical coverage. + index += 1 + in_class = False + while index < len(text): + c = text[index] + if c == "\\": + index += 2 + continue + if c == "[": + in_class = True + elif c == "]": + in_class = False + elif c == "/" and not in_class: + index += 1 + break + elif c == "\n": + raise ValueError("Unterminated JavaScript regex candidate") + index += 1 + else: + raise ValueError("Unterminated JavaScript regex candidate") + value = "@regex" + elif char.isascii() and (char.isalpha() or char in "_$"): + index += 1 + while index < len(text) and text[index].isascii() and (text[index].isalnum() or text[index] in "_$"): + index += 1 + value = text[start:index] + elif text.startswith("...", index): + value, index = "...", index + 3 + else: + value, index = char, index + 1 + tokens.append((value, token_line)) + if len(tokens) > 200000: + raise ValueError("Source exceeds the 200,000 token limit") + return tokens + + +def _nodevm_bindings(values): + constructors, namespaces = set(), set() + identifier = r"[A-Za-z_$][A-Za-z0-9_$]*" + # Only literal vm2 imports in bounded, simple declarations are recognized. + # Shadowing, reassignment and execution order are not resolved: all matches + # remain candidates and never fill the operator-observation fields. + for index, value in enumerate(values): + if value not in {"const", "let", "var", "import"}: + continue + end = index + 1 + while end < min(len(values), index + 100) and values[end] != ";": + end += 1 + statement = " ".join(values[index:end]) + if value == "import": + match = re.match(r"import \{ (.*?) \} from @vm2(?: |$)", statement) + if match: + for member in re.split(r"\s*,\s*", match[1]): + m = re.fullmatch(r"NodeVM(?: as (" + identifier + r"))?", member) + if m: + constructors.add(m[1] or "NodeVM") + match = re.match(r"import \* as (" + identifier + r") from @vm2(?: |$)", statement) + if match: + namespaces.add(match[1]) + else: + match = re.match(r"(?:const|let|var) \{ (.*?) \} = require \( @vm2 \)", statement) + if match: + for member in re.split(r"\s*,\s*", match[1]): + m = re.fullmatch(r"NodeVM(?: : (" + identifier + r"))?", member) + if m: + constructors.add(m[1] or "NodeVM") + match = re.match(r"(?:const|let|var) (" + identifier + r") = require \( @vm2 \)(.*)", statement) + if match: + if re.match(r" \. NodeVM(?: |$)", match[2]): + constructors.add(match[1]) + elif not match[2].startswith(" ."): + namespaces.add(match[1]) + return constructors, namespaces + + +def _source_shapes(values, opening, closing, pairs): + nesting, require = "unknown", "unknown" + if closing - opening > 4096: + return nesting, require + first = opening + 1 + if first == closing: + return "not_specified", "not_specified" + if values[first] != "{" or pairs.get(first) != closing - 1: + return nesting, require + members, start = [], first + 1 + index = start + while index < closing - 1: + if values[index] == "...": + return "unknown", "unknown" + if values[index] in {"{", "[", "("} and index in pairs: + index = pairs[index] + 1 + continue + if values[index] == ",": + members.append(values[start:index]) + start = index + 1 + index += 1 + if start < closing - 1: + members.append(values[start:closing - 1]) + props = {} + for member in members: + if len(member) < 3 or member[1] != ":" or member[0].startswith("["): + return "unknown", "unknown" + key = member[0].removeprefix("@") + if key in props: + return "unknown", "unknown" + props[key] = member[2:] + n = props.get("nesting") + r = props.get("require") + nesting = "not_specified" if n is None else "literal_" + n[0] if n in (["true"], ["false"]) else "unknown" + if r is None: + require = "not_specified" + elif r[0] in {"[", "{"}: + depth, end = 0, None + for index, value in enumerate(r): + if value in {"[", "{", "("}: + depth += 1 + elif value in {"]", "}", ")"}: + depth -= 1 + if depth == 0: + end = index + break + if end == len(r) - 1: + require = "array_candidate" if r[0] == "[" else "object_candidate" + elif r in (["true"], ["false"], ["null"]): + require = "literal_" + r[0] + return nesting, require + + +def scan_source_text(text, relative_path): + """Return lexical review rows only, without assigning version or trust state.""" + tokens = _js_tokens(text) + values = [t[0] for t in tokens] + constructors, namespaces = _nodevm_bindings(values) + stack, pairs = [], {} + for index, value in enumerate(values): + if value in {"{", "[", "("}: + stack.append(index) + elif value in {"}", "]", ")"}: + if not stack or values[stack[-1]] != {"}": "{", "]": "[", ")": "("}[value]: + raise ValueError("Unbalanced JavaScript delimiters") + opening = stack.pop() + pairs[opening] = index + if stack: + raise ValueError("Unbalanced JavaScript delimiters") + runs = {} + for index in range(len(values) - 4): + if values[index + 1:index + 4] == [".", "run", "("]: + shape = "literal_string" if values[index + 4] == "@string" else "dynamic_or_unsupported" + runs.setdefault(values[index], set()).add(shape) + rows = [] + for index, value in enumerate(values[:-2]): + if value != "new": + continue + opening = None + if values[index + 1] in constructors and values[index + 2] == "(": + opening = index + 2 + elif (index + 4 < len(values) and values[index + 1] in namespaces + and values[index + 2:index + 5] == [".", "NodeVM", "("]): + opening = index + 4 + if opening is None or opening not in pairs: + continue + nesting, require = _source_shapes(values, opening, pairs[opening], pairs) + row = assess_entry(relative_path, "source", "") + row.update(evidence_type="lexical_source_candidate", source_path=relative_path, + source_line=tokens[index][1], source_nesting=nesting, source_require=require, + source_run_argument="not_observed", source_coverage="limited_lexical") + # Only direct variable assignment and direct calls on that spelling are + # associated. A lexical association is not a proven object or taint flow. + receiver = values[index - 2] if index >= 2 and values[index - 1] == "=" else None + argument_shapes = runs.get(receiver, set()) + if argument_shapes: + row["source_run_argument"] = next(iter(argument_shapes)) if len(argument_shapes) == 1 else "mixed" + row["notes"].append( + f"Source candidate {relative_path}:{tokens[index][1]}: nesting={nesting}; require={require}; " + f"run_argument={row['source_run_argument']}. This is not runtime configuration, trusted-input or taint evidence. " + "Aliases, shadowing, reassignment, dynamic syntax, templates and execution order need manual review; no match never means absent.") + rows.append(row) + if len(rows) > MAX_ENTRIES: + raise ValueError("Too many source candidates") + if not rows: + row = assess_entry(relative_path, "source", "") + row.update(evidence_type="source_coverage", source_path=relative_path, source_line="", + source_nesting="unknown", source_require="unknown", source_run_argument="not_observed", + source_coverage="limited_lexical") + row["notes"].append("No supported import-bound NodeVM construction candidate found; configuration, dependency presence and input trust remain unknown.") + rows.append(row) + return rows + + +def load_source(path, root, budget, out): + budget.add_file() + relative = Path(path).resolve().relative_to(Path(root).resolve()).as_posix() + _bounded_text(relative, "Source relative path") + rows = scan_source_text(_read_bounded(path), relative) + budget.add_entries(len(rows)) + out.extend(rows) + + class Budget: """Counts entries and files while loading, so limits hold before rows pile up.""" @@ -520,10 +760,19 @@ def _validate_arguments(args): _bounded_text(version, "--version") if len(args.package_version) > MAX_ENTRIES: raise ValueError(f"A run is limited to {MAX_ENTRIES:,} inputs") - if len(args.inventory) + len(args.csv_list) > MAX_FILES: + if len(args.inventory) + len(args.csv_list) + len(args.source) > MAX_FILES: raise ValueError(f"A run is limited to {MAX_FILES} input files") - for path in (*args.inventory, *args.csv_list): + inputs = (*args.inventory, *args.csv_list, *args.source) + if args.source and args.source_root is None: + raise ValueError("--source requires --source-root for relative evidence paths") + if args.source_root is not None and not args.source_root.is_dir(): + raise ValueError("--source-root must be a directory") + for path in inputs: _require_regular_file(path) + for path in args.source: + if path.suffix.lower() not in {".js", ".cjs", ".mjs", ".ts", ".cts", ".mts", ".jsx", ".tsx"}: + raise ValueError("Source must be an explicitly selected JS/TS file") + path.resolve().relative_to(args.source_root.resolve()) if args.output is not None: output = args.output parent = output.parent @@ -536,10 +785,10 @@ def _validate_arguments(args): raise ValueError("Output is a dangling or looping symbolic link") if output.is_dir() or (output.exists() and not stat.S_ISREG(os.stat(output).st_mode)): raise ValueError("Output must be a regular file path") - for path in (*args.inventory, *args.csv_list): + for path in inputs: if os.path.samefile(output, path): raise ValueError("--output must differ from every input file, even with --force") - for path in (*args.inventory, *args.csv_list): + for path in inputs: if os.path.realpath(output) == os.path.realpath(path): raise ValueError("--output must differ from every input file, even with --force") @@ -562,6 +811,10 @@ def main(argv=None): help="JSON object or array of entries (see docs/REFERENCE.md); repeatable") parser.add_argument("--csv-list", action="append", default=[], type=Path, metavar="FILE", help="CSV with a package_version column and optional label, build_source and precondition columns; repeatable") + parser.add_argument("--source", action="append", default=[], type=Path, metavar="FILE", + help="Explicit JS/TS file for lexical NodeVM candidates; repeatable, never executed") + parser.add_argument("--source-root", type=Path, metavar="DIR", + help="Required with --source; evidence paths are relative to this directory") parser.add_argument("--format", choices=("csv", "json", "html"), default="csv", help="Output format (default: csv)") parser.add_argument("--output", type=Path, help="Save report to a new file; default: stdout") parser.add_argument("--force", action="store_true", help="Replace an existing output file explicitly") @@ -569,8 +822,8 @@ def main(argv=None): parser.add_argument("--fail-on-finding", action="store_true", help="Exit 1 for potentially_affected results (errors still exit 2)") args = parser.parse_args(argv) - if not (args.package_version or args.inventory or args.csv_list): - parser.error("provide --version, --inventory or --csv-list") + if not (args.package_version or args.inventory or args.csv_list or args.source): + parser.error("provide --version, --inventory, --csv-list or --source") rows = [] state = {"validated": False, "published": False, "stdout_started": False} options = {"force": args.force, "format": args.format, "brand": args.brand, "state": state} @@ -587,6 +840,8 @@ def main(argv=None): load_inventory(path, budget, rows) for path in args.csv_list: load_csv_list(path, budget, rows) + for path in args.source: + load_source(path, args.source_root, budget, rows) save_report(args.output, rows, complete=True, **options) except KeyboardInterrupt: if not state["validated"]: