diff --git a/docs/guides/javascript/javascript-artifact-reconstruction.md b/docs/guides/javascript/javascript-artifact-reconstruction.md index 3963f8bb96e..be3cde8c36b 100644 --- a/docs/guides/javascript/javascript-artifact-reconstruction.md +++ b/docs/guides/javascript/javascript-artifact-reconstruction.md @@ -533,6 +533,16 @@ covers direct BrowserWindow instances, stable local aliases, and their `webContents`; other receiver-producing APIs remain unmodeled. Complete AST traversal does not imply complete API-model coverage. +Path values and source-directory or source-file anchors held in a single +`const`, such as `const preload = path.join(__dirname, "preload.js")` or +`const __dirname = path.dirname(fileURLToPath(import.meta.url))`, stand for +their initializers when the shared lexical index proves that the initializer +runs before every evaluation of the read. The timing rules described below for +constant options apply. Each constant is read at most once per path +expression, so repeated reads such as `const twice = once + once` stay +unknown. `let` and `var` bindings, reassigned or destructured constants, reads +that may run before initialization, and `URL` objects keep their expressions. + Artifact bytes and AST syntax are observations. Entrypoint resolution, imports, loads, calls, and persistence relationships are static inferences and explicitly say that syntax does not prove runtime execution. A malformed or unavailable diff --git a/src/domain/javascript/javascriptStaticAnalysisHelpers.ts b/src/domain/javascript/javascriptStaticAnalysisHelpers.ts index 209b3eacdd2..b10ed133e77 100644 --- a/src/domain/javascript/javascriptStaticAnalysisHelpers.ts +++ b/src/domain/javascript/javascriptStaticAnalysisHelpers.ts @@ -169,22 +169,55 @@ export const staticArrayValues = ( }; }; +type JavaScriptStaticPathIntrinsicFact = + | "resolve" + | "join" + | "file-url-to-path" + | "source-url" + | "source-directory"; + /** Classify whether inert path syntax is a module specifier or file expression. */ -export type JavaScriptStaticPathIntrinsicQuery = ( - node: t.Node, - fact?: - | "resolve" - | "join" - | "file-url-to-path" - | "source-url" - | "source-directory", -) => boolean; +export interface JavaScriptStaticPathIntrinsicQuery { + (node: t.Node, fact?: JavaScriptStaticPathIntrinsicFact): boolean; + /** + * Return the initializer of a single `const` binding when it runs before + * every evaluation of this read. Other reads remain unknown. + */ + readonly constantInitializer?: (read: t.Identifier) => t.Node | undefined; +} + +/** + * Substitute each constant at most once while interpreting one expression. + * Repeated reads such as `const twice = once + once` stay unknown, so + * substitution cannot expand syntax or spelling beyond the source text. + */ +const substitutingConstantsOnce = ( + pathIntrinsics: JavaScriptStaticPathIntrinsicQuery | undefined, +): JavaScriptStaticPathIntrinsicQuery | undefined => { + const constantInitializer = pathIntrinsics?.constantInitializer; + if (pathIntrinsics === undefined || constantInitializer === undefined) + return pathIntrinsics; + const substituted = new Set(); + return Object.assign( + (node: t.Node, fact?: JavaScriptStaticPathIntrinsicFact) => + pathIntrinsics(node, fact), + { + constantInitializer: (read: t.Identifier) => { + const initializer = constantInitializer(read); + if (initializer === undefined || substituted.has(initializer)) + return undefined; + substituted.add(initializer); + return initializer; + }, + }, + ); +}; export const staticPathResolutionContext = ( node: t.Node, pathIntrinsics?: JavaScriptStaticPathIntrinsicQuery, ): JavaScriptStaticPathContext => - isFilesystemPathExpression(node, pathIntrinsics) + isFilesystemPathExpression(node, substitutingConstantsOnce(pathIntrinsics)) ? "filesystem-expression" : "module-specifier"; @@ -197,7 +230,8 @@ interface StaticPathFact { export const staticPath = ( node: t.Node, pathIntrinsics?: JavaScriptStaticPathIntrinsicQuery, -): string | undefined => staticPathFact(node, pathIntrinsics)?.path; +): string | undefined => + staticPathFact(node, substitutingConstantsOnce(pathIntrinsics))?.path; /** Parse spelling and its source-directory provenance together at the owning boundary. */ const staticPathFact = ( @@ -207,6 +241,13 @@ const staticPathFact = ( const node = unwrapJavaScriptExpression(raw).node; const value = stringValue(node); if (value !== undefined) return { path: value, base: "literal-path" }; + if (t.isIdentifier(node)) { + // The initializer keeps its own syntax, so a source-directory base survives. + const initializer = pathIntrinsics?.constantInitializer?.(node); + return initializer === undefined + ? undefined + : staticPathFact(initializer, pathIntrinsics); + } if (t.isBinaryExpression(node, { operator: "+" })) return staticConcatenation(node, pathIntrinsics); if (t.isCallExpression(node) || t.isNewExpression(node)) @@ -224,7 +265,7 @@ export const staticFileExpressionPath = ( readonly base: "source-directory" | "literal-path"; } | undefined => { - const fact = staticPathFact(node, pathIntrinsics); + const fact = staticPathFact(node, substitutingConstantsOnce(pathIntrinsics)); return fact === undefined || fact.base === "unknown" ? undefined : { path: fact.path, base: fact.base }; @@ -326,7 +367,7 @@ const staticFileUrlPathFact = ( ? undefined : { path: resolved.path, base: "source-directory" }; } - const value = staticPath(argument, pathIntrinsics); + const value = staticPathFact(argument, pathIntrinsics)?.path; const rawPath = value?.split(/[?#]/u, 1)[0] ?? ""; if ( value === undefined || @@ -432,6 +473,13 @@ const isFilesystemPathExpression = ( if (value !== undefined) return value.startsWith("/"); if (isFileIdentity(node) || isDirectoryPath(node, pathIntrinsics)) return true; + if (t.isIdentifier(node)) { + const initializer = pathIntrinsics?.constantInitializer?.(node); + return ( + initializer !== undefined && + isFilesystemPathExpression(initializer, pathIntrinsics) + ); + } if (t.isBinaryExpression(node, { operator: "+" })) return ( isFilesystemPathExpression(node.left, pathIntrinsics) || diff --git a/src/domain/javascript/javascriptStaticPathConstants.test.ts b/src/domain/javascript/javascriptStaticPathConstants.test.ts new file mode 100644 index 00000000000..5c387e90dad --- /dev/null +++ b/src/domain/javascript/javascriptStaticPathConstants.test.ts @@ -0,0 +1,300 @@ +import { posix } from "node:path"; +import { runInNewContext } from "node:vm"; + +import { describe, expect, it } from "vitest"; + +import { analyzeParsedJavaScriptStaticSource } from "./javascriptStaticAnalysis.js"; +import { parseJavaScriptSource } from "./javascriptSourceParser.js"; + +const COMMONJS_HEADER = [ + 'const path = require("node:path");', + 'const { BrowserWindow, utilityProcess } = require("electron");', +].join("\n"); +const MODULE_HEADER = [ + 'import path from "node:path";', + 'import { fileURLToPath } from "node:url";', + 'import { BrowserWindow, utilityProcess } from "electron";', +].join("\n"); + +const analyze = (filename: string, source: string) => { + const parsed = parseJavaScriptSource(source, filename); + if (parsed === null) throw new Error(`${filename} could not be parsed`); + return analyzeParsedJavaScriptStaticSource(source, parsed); +}; + +const consumers = (expression: string) => + [ + `new BrowserWindow({ webPreferences: { preload: ${expression} } });`, + `utilityProcess.fork(${expression});`, + ].join("\n"); + +/** Preload and utility-process paths, which share one path owner. */ +const pathFacts = (analysis: ReturnType) => ({ + preloads: analysis.electron.browser_windows.map( + ({ preload_path, preload_resolution_context }) => ({ + path: preload_path, + context: preload_resolution_context, + }), + ), + utilities: analysis.electron.utility_processes.map( + ({ module_path, module_resolution_context }) => ({ + path: module_path, + context: module_resolution_context, + }), + ), +}); + +const resolved = (path: string, context: string) => ({ + preloads: [{ path, context }], + utilities: [{ path, context }], +}); +const UNKNOWN = { + preloads: [{ path: null, context: null }], + utilities: [{ path: null, context: null }], +}; + +/** Inert Electron and path modules for checking initialization order. */ +const runtime = () => ({ + __dirname: "/app", + require: (specifier: string) => + specifier === "electron" + ? { BrowserWindow: class {}, utilityProcess: { fork: () => undefined } } + : posix, +}); + +describe("constant path bindings", () => { + it.each([ + { + name: "a joined source path", + declarations: 'const PRELOAD = path.join(__dirname, "preload.js");', + expression: "PRELOAD", + path: "preload.js", + context: "filesystem-expression", + }, + { + name: "a literal specifier", + declarations: 'const PRELOAD = "./preload.js";', + expression: "PRELOAD", + path: "./preload.js", + context: "module-specifier", + }, + { + name: "a constant alias", + declarations: + 'const FIRST = path.resolve(__dirname, "preload.js"); const PRELOAD = FIRST;', + expression: "PRELOAD", + path: "preload.js", + context: "filesystem-expression", + }, + { + name: "nested directory constants", + declarations: + 'const ROOT = path.join(__dirname, ".."); const DIST = path.join(ROOT, "dist");', + expression: 'path.join(DIST, "preload.js")', + path: "../dist/preload.js", + context: "filesystem-expression", + }, + { + name: "a constant file name", + declarations: 'const NAME = "preload.js";', + expression: "path.join(__dirname, NAME)", + path: "preload.js", + context: "filesystem-expression", + }, + { + name: "a source directory alias", + declarations: "const DIRECTORY = __dirname;", + expression: 'DIRECTORY + "/preload.js"', + path: "preload.js", + context: "filesystem-expression", + }, + { + name: "a source file alias", + declarations: "const FILE = __filename;", + expression: 'path.join(path.dirname(FILE), "preload.js")', + path: "preload.js", + context: "filesystem-expression", + }, + ])( + "resolves $name like the inline path", + ({ declarations, expression, path, context }) => { + const analysis = analyze( + "main.cjs", + `${COMMONJS_HEADER}\n${declarations}\n${consumers(expression)}`, + ); + expect(pathFacts(analysis)).toEqual(resolved(path, context)); + }, + ); + + it.each([ + "const __dirname = path.dirname(fileURLToPath(import.meta.url));", + "const __filename = fileURLToPath(import.meta.url); const __dirname = path.dirname(__filename);", + ])("anchors module paths at a constant module directory: %s", (body) => { + const analysis = analyze( + "main.mjs", + `${MODULE_HEADER}\n${body}\n${consumers('path.join(__dirname, "preload.mjs")')}`, + ); + expect(pathFacts(analysis)).toEqual( + resolved("preload.mjs", "filesystem-expression"), + ); + }); + + it("resolves constant renderer files and utility-process service names", () => { + const analysis = analyze( + "main.cjs", + [ + COMMONJS_HEADER, + 'const PAGE = path.join(__dirname, "index.html");', + 'const SERVICE = path.join(__dirname, "service.js");', + 'const NAME = "Example service";', + "new BrowserWindow().loadFile(PAGE);", + "utilityProcess.fork(SERVICE, [], { serviceName: NAME });", + ].join("\n"), + ); + expect(analysis.role_paths).toEqual([ + expect.objectContaining({ + role: "renderer", + path: "index.html", + path_base: "source-directory", + resolution_context: "filesystem-expression", + }), + ]); + expect(analysis.electron.utility_processes).toEqual([ + expect.objectContaining({ + module_path: "service.js", + module_resolution_context: "filesystem-expression", + service_name: "Example service", + }), + ]); + }); +}); + +describe("constant path ownership and initialization", () => { + it.each([ + { declarations: 'let PRELOAD = path.join(__dirname, "preload.js");' }, + { declarations: 'var PRELOAD = path.join(__dirname, "preload.js");' }, + { + declarations: + 'const PRELOAD = path.join(__dirname, "preload.js"); PRELOAD = "./other.js";', + }, + { + declarations: + 'const { PRELOAD } = { PRELOAD: path.join(__dirname, "preload.js") };', + }, + { + declarations: + 'const PRELOAD = runtimeFlag ? "./first.js" : "./second.js";', + }, + { + declarations: + 'const PRELOAD = path.join(__dirname, "preload.js"); { const PRELOAD = runtimePath;', + after: "}", + }, + { + declarations: + 'const PRELOAD = path.join(__dirname, "preload.js"); function open(PRELOAD) {', + after: "} open(runtimePath);", + }, + ])( + "keeps a binding that is not one definite constant unknown: $declarations", + ({ declarations, after = "" }) => { + const analysis = analyze( + "main.cjs", + `${COMMONJS_HEADER}\n${declarations}\n${consumers("PRELOAD")}\n${after}`, + ); + expect(pathFacts(analysis)).toEqual(UNKNOWN); + }, + ); + + it.each([ + { + label: "a read before the declaration", + source: [ + COMMONJS_HEADER, + consumers("PRELOAD"), + 'const PRELOAD = path.join(__dirname, "preload.js");', + ], + }, + { + label: "a hoisted function called before initialization", + source: [ + COMMONJS_HEADER, + `function open() {\n${consumers("PRELOAD")}\n}`, + "open();", + 'const PRELOAD = path.join(__dirname, "preload.js");', + ], + }, + ])("keeps $label unknown", ({ source }) => { + const text = source.join("\n"); + expect(() => runInNewContext(text, runtime())).toThrow( + /before initialization/, + ); + expect(pathFacts(analyze("main.cjs", text))).toEqual(UNKNOWN); + }); + + it("resolves a module constant read by a function called after initialization", () => { + const text = [ + COMMONJS_HEADER, + `function open() {\n${consumers("PRELOAD")}\n}`, + 'const PRELOAD = path.join(__dirname, "preload.js");', + "open();", + ].join("\n"); + expect(() => runInNewContext(text, runtime())).not.toThrow(); + expect(pathFacts(analyze("main.cjs", text))).toEqual( + resolved("preload.js", "filesystem-expression"), + ); + }); + + it.each([ + { + label: "an exported function another module can call first", + body: `export function open() {\n${consumers("PRELOAD")}\n}\nconst PRELOAD = path.join(path.dirname(fileURLToPath(import.meta.url)), "preload.mjs");`, + }, + { + label: "a URL object, which can change after construction", + body: `const PRELOAD_URL = new URL("./preload.mjs", import.meta.url);\n${consumers("fileURLToPath(PRELOAD_URL)")}`, + }, + ])("keeps $label unknown", ({ body }) => { + expect(pathFacts(analyze("main.mjs", `${MODULE_HEADER}\n${body}`))).toEqual( + UNKNOWN, + ); + }); +}); + +describe("constant substitution bound", () => { + it.each([ + { + declarations: 'const ONCE = "./once"; const TWICE = ONCE + ONCE;', + expression: "TWICE", + }, + { + declarations: 'const PART = "part";', + expression: "path.join(__dirname, PART, PART)", + }, + ])( + "reads each constant at most once per expression: $expression", + ({ declarations, expression }) => { + const analysis = analyze( + "main.cjs", + `${COMMONJS_HEADER}\n${declarations}\n${consumers(expression)}`, + ); + expect(pathFacts(analysis)).toEqual(UNKNOWN); + }, + ); + + it("does not expand a doubling constant chain beyond the source", () => { + const declarations = [ + 'const level0 = "x";', + ...Array.from( + { length: 64 }, + (_, index) => + `const level${String(index + 1)} = level${String(index)} + level${String(index)};`, + ), + ]; + const analysis = analyze( + "main.cjs", + `${COMMONJS_HEADER}\n${declarations.join("\n")}\n${consumers("level64")}`, + ); + expect(pathFacts(analysis)).toEqual(UNKNOWN); + }); +}); diff --git a/src/domain/javascript/javascriptStaticPathIntrinsics.ts b/src/domain/javascript/javascriptStaticPathIntrinsics.ts index bc363bb4d0b..56774ab8f1e 100644 --- a/src/domain/javascript/javascriptStaticPathIntrinsics.ts +++ b/src/domain/javascript/javascriptStaticPathIntrinsics.ts @@ -1,7 +1,11 @@ import * as t from "@babel/types"; import { builtinDataEffectCallablePath } from "./javascriptSemanticDataEffectHelpers.js"; -import type { JavaScriptBindingIndex } from "./javascriptSemanticState.js"; +import { semanticBindingAtRead } from "./javascriptSemanticMutationInitializers.js"; +import { + semanticStableInitializer, + type JavaScriptBindingIndex, +} from "./javascriptSemanticState.js"; import { completeSemanticSteps } from "./javascriptSemanticTraversal.js"; import { evaluateSemanticExpressionProvenance } from "./javascriptSemanticValues.js"; import { @@ -42,9 +46,41 @@ export const createStaticPathIntrinsicQuery = ( path[1] === method)) ); }; + // A read before initialization throws, so only a definite initializer counts. + const constantInitializer = (read: t.Identifier): t.Node | undefined => { + const binding = index.bindingForReferenceAt(read); + const initializer = semanticStableInitializer(binding, index.bindings); + if ( + binding === undefined || + binding.mutable || + binding.declarationKinds.size !== 1 || + !binding.declarationKinds.has("const") || + initializer === undefined || + initializer.projection.length !== 0 + ) + return undefined; + // Ordering a read in a function against its activations uses member effects. + completeSemanticSteps(index.indexMemberMutationFactsSteps()); + return semanticBindingAtRead(binding, read, index.bindings) + .hasDefiniteInitializer + ? initializer.node + : undefined; + }; + /** Follow constant aliases to the syntax whose identity is proven. */ + const constantTarget = (input: t.Node): t.Node => { + let node = unwrapJavaScriptExpression(input).node; + const seen = new Set(); + while (t.isIdentifier(node) && !seen.has(node)) { + seen.add(node); + const initializer = constantInitializer(node); + if (initializer === undefined) break; + node = unwrapJavaScriptExpression(initializer).node; + } + return node; + }; const sourceFile = (node: t.Node | undefined): boolean => { if (node === undefined) return false; - node = unwrapJavaScriptExpression(node).node; + node = constantTarget(node); if (t.isIdentifier(node, { name: "__filename" })) return isUnmodifiedGlobalReference(node, index.bindings, "__filename"); return ( @@ -54,9 +90,9 @@ export const createStaticPathIntrinsicQuery = ( isUnmodifiedImportMetaUrl(node.arguments[0], index.bindings) ); }; - return (callee, fact) => { + const query: JavaScriptStaticPathIntrinsicQuery = (callee, fact) => { if (fact === "source-directory") { - callee = unwrapJavaScriptExpression(callee).node; + callee = constantTarget(callee); return t.isIdentifier(callee, { name: "__dirname" }) ? isUnmodifiedGlobalReference(callee, index.bindings, "__dirname") : t.isCallExpression(callee) && @@ -85,4 +121,5 @@ export const createStaticPathIntrinsicQuery = ( entry.set(kind, proven); return proven; }; + return Object.assign(query, { constantInitializer }); }; diff --git a/tests/acceptance/applications/electronConstantPathsCli.test.ts b/tests/acceptance/applications/electronConstantPathsCli.test.ts new file mode 100644 index 00000000000..5328f2d4674 --- /dev/null +++ b/tests/acceptance/applications/electronConstantPathsCli.test.ts @@ -0,0 +1,115 @@ +import { expect } from "vitest"; + +import { createTestTempDirectory } from "../../fixtures/temporaryDirectory.js"; +import { cliTest } from "../../support/cli/cliFixture.js"; +import { analyzeJavaScriptDirectory } from "../../support/cli/javascriptApplication.js"; +import { writeFixtureFiles } from "../../support/javascriptApplicationFixture.js"; + +const MAIN = [ + 'const path = require("node:path");', + 'const { BrowserWindow, utilityProcess } = require("electron");', + 'const PRELOAD = path.join(__dirname, "preload.js");', + 'const SERVICE = path.join(__dirname, "service.js");', + 'const PAGE = path.join(__dirname, "page.html");', + 'let RUNTIME_PRELOAD = path.join(__dirname, "runtime.js");', + "new BrowserWindow({ webPreferences: { preload: PRELOAD } }).loadFile(PAGE);", + "new BrowserWindow({ webPreferences: { preload: RUNTIME_PRELOAD } });", + "new BrowserWindow({ webPreferences: { preload: EARLY_PRELOAD } });", + 'const EARLY_PRELOAD = path.join(__dirname, "early.js");', + "utilityProcess.fork(SERVICE);", +]; +const INERT = "throw new Error('Static fixture must never execute');\n"; + +cliTest.for(["CLI", "stdio MCP"] as const)( + "links constant Electron paths through %s", + async (surface, { cli }) => { + const root = await createTestTempDirectory("rea-electron-constant-paths-"); + await writeFixtureFiles(root, { + "package.json": JSON.stringify({ main: "main.cjs" }), + "main.cjs": `${MAIN.join("\n")}\n`, + "preload.js": INERT, + "runtime.js": INERT, + "early.js": INERT, + "service.js": INERT, + "page.html": "page\n", + }); + const { graph, statistics } = await analyzeJavaScriptDirectory( + surface, + cli, + root, + ); + expect(statistics.parse_failures).toBe(0); + + const preloads = graph.nodes + .filter(({ kind }) => kind === "browser-window") + .map((window) => { + const [observation] = window.observations; + const location = observation?.evidence.location; + const association = graph.edges.find( + ({ source_node_id, evidence }) => + source_node_id === window.node_id && + evidence.extractor.operation === "associate-browser-window-preload", + ); + return { + line: + location?.available === true && + location.value.kind === "source-range" + ? location.value.start.line + : null, + preload_path: observation?.properties.preload_path, + resolved_path: association?.properties.resolved_path ?? null, + }; + }) + .sort((left, right) => (left.line ?? 0) - (right.line ?? 0)); + // Mutable and possibly uninitialized bindings keep their expressions. + expect(preloads).toEqual([ + { line: 7, preload_path: "preload.js", resolved_path: "preload.js" }, + { line: 8, preload_path: null, resolved_path: null }, + { line: 9, preload_path: null, resolved_path: null }, + ]); + const runtimeWindow = graph.nodes.find( + ({ kind, observations }) => + kind === "browser-window" && + observations[0]?.evidence.location.available === true && + observations[0].evidence.location.value.kind === "source-range" && + observations[0].evidence.location.value.start.line === 8, + ); + expect(runtimeWindow?.observations[0]?.properties.web_preferences).toEqual([ + { + name: "preload", + value: { + status: "dynamic", + value: null, + expression: "RUNTIME_PRELOAD", + }, + }, + ]); + + expect( + graph.nodes + .filter(({ kind }) => kind === "electron-renderer") + .flatMap(({ observations }) => + observations.map(({ properties }) => properties.resolved_path), + ), + ).toEqual(["page.html"]); + expect( + graph.nodes + .filter(({ kind }) => kind === "electron-utility") + .map(({ observations }) => + observations.map(({ properties }) => properties), + ), + ).toEqual([ + [ + expect.objectContaining({ + module_path: "service.js", + module_resolution_context: "filesystem-expression", + module_expression: null, + }), + expect.objectContaining({ + resolved_path: "service.js", + resolution_status: "resolved", + }), + ], + ]); + }, +);