Files
ShuaixinHuang e9fc8fb30c fix(javascript): preserve runtime path bytes and Electron ownership (#4941)
* fix(javascript): preserve literal percent runtime paths

* fix(javascript): ignore resolve prefixes before the final anchor

* fix(electron): retain application roots for loadFile declarations

* fix(electron): resolve loadFile from enclosing application package

* fix(electron): retain outer application root across package scopes

* fix(electron): derive application ownership from inventoried packages

* fix(electron): retain resolved package entrypoint ownership

* fix(electron): preserve competing application ownership

* fix(electron): retain invalid and omitted runtime ownership

* fix(electron): preserve omitted module ownership and runtime paths

* fix(electron): preserve proven roots before confining page paths

* fix(electron): retain possible owners behind missing imports

* fix(electron): distinguish absent imports and owned page candidates

* fix(electron): keep unavailable JSON out of owner gaps

* fix(electron): retain exact loader formats and default entry status

* fix(electron): retain unavailable entrypoint ownership candidates

* test(ghidra): preserve Windows Node probe prerequisites

* test(ghidra): assert cancellation during profile shutdown

* fix(electron): separate examined imports from frontend ownership

* fix(electron): retain unavailable directory entrypoint owners

* test(jeb): retain Linux ownership prerequisite in isolation

* fix(javascript): retain unchecked loader ownership and literal main paths

* fix(javascript): preserve runtime paths and call-site module aliases

* fix(javascript): bound module alias traversal and preserve projections

* fix(javascript): retain host module and nested artifact path boundaries

* fix(javascript): preserve ESM and archive module loader provenance

* test(javascript): distinguish unmapped containers from missing exports

* fix: retain default module aliases and Electron builtin imports

* fix: preserve host file URL and inward ASAR ownership

* fix: preserve CommonJS file URL classification in CI fixtures

* fix: retain bound module loaders and Windows entrypoint uncertainty

* fix: retain ASAR uncertainty and invalidate changed Electron app roots

* fix(javascript): retain ownership uncertainty across loader boundaries

* fix(javascript): preserve loader sources and bound alias queries

* fix(javascript): retain destructured loader sources

* fix(javascript): preserve loader uncertainty at resolution boundaries

* fix(javascript): preserve callable and package launch ownership

* fix(javascript): preserve captured values across member reads

* test(process): assert tagged filesystem cancellation failures

* fix(javascript): preserve inventory bases and invocation read timing

* fix(javascript): preserve ownership across indirect and unread loads

* test(javascript): order fixture directory creation on Windows

* test(javascript): share ordered filesystem fixture writer

* fix(javascript): unify loader provenance and package validation

* fix(javascript): preserve captured Node require loader values

* fix(javascript): preserve loader invocation authority

* fix(javascript): verify generic loader invocation authority

* fix(javascript): preserve conditional loader method alternatives

* fix(javascript): require proven factories for source association

* fix(javascript): honor replaced Electron app path setters

* fix(javascript): prove path and assignment source ownership

* fix(javascript): retain native delegate eligibility through shared writes

* fix(process): settle stale baseline errors after confirmed absence

* fix(javascript): preserve assignment and path boundary evidence

* fix(javascript): prove source-directory resolve anchors

* fix: preserve application path provenance and portable schemas

* fix(javascript): retain CommonJS exported setter effects

* fix: isolate Linux identity observations and retain native module exports

* fix(javascript): preserve published app and helper provenance

* fix(javascript): normalize typed stores and native path fixtures
2026-10-20 17:25:19 +08:00

145 lines
6.3 KiB
TypeScript

import { mkdir, readFile, writeFile } from "node:fs/promises";
import { dirname, join, relative } from "node:path";
import { fileURLToPath, pathToFileURL } from "node:url";
import { parseExpression } from "@babel/parser";
import { describe, expect, it } from "vitest";
import { createTestTempDirectory } from "../../../fixtures/temporaryDirectory.js";
import { javascriptApplicationAnalysisResultSchema } from "../../../../src/domain/javascript/javascriptApplicationAnalysis.js";
import { staticPath } from "../../../../src/domain/javascript/javascriptStaticAnalysisHelpers.js";
import { analyzeJavaScriptStaticSource } from "../../../../src/domain/javascript/javascriptStaticAnalysis.js";
import { analyzeJavaScriptApplication } from "../../../support/javascriptApplicationScope.js";
const urlCases = [
["./preload%20name.cjs", "preload name.cjs", "main.mjs"],
["./preload%252Fname.cjs", "preload%2Fname.cjs", "main.mjs"],
["./pr%C3%A9load.cjs", "préload.cjs", "main.mjs"],
["./preload%3F%23.cjs", "preload?#.cjs", "main.mjs"],
["./preload.cjs?cache=1#v2", "preload.cjs", "main.mjs"],
["../preload.cjs?cache=1", "preload.cjs", "src/main.mjs"],
["./sub/../preload.cjs", "preload.cjs", "main.mjs"],
["./preload.cjs", "preload.cjs", "main.mjs"],
] as const;
const unknownExpressions = [
'fileURLToPath("file:///app/%2Fpreload.cjs")',
'fileURLToPath("file:///app/%5Cpreload.cjs")',
'fileURLToPath("file:///app/%")',
'fileURLToPath("file:///C:/app/preload.cjs")',
'fileURLToPath("file://remote/share/preload.cjs")',
'fileURLToPath("file:///app/preload.cjs", { windows: selectedPlatform })',
'fileURLToPath(new URL("./invalid%.cjs", import.meta.url))',
'fileURLToPath(new URL("./preload%2fname.cjs", import.meta.url))',
'fileURLToPath(new URL("./preload%5cname.cjs", import.meta.url))',
'fileURLToPath(new URL("./%2e/preload.cjs", import.meta.url))',
'fileURLToPath(new URL("https://example.test/preload.cjs", import.meta.url))',
'fileURLToPath(new URL("//example.test/preload.cjs", import.meta.url))',
'fileURLToPath(new URL("#fragment", import.meta.url))',
'fileURLToPath(new URL("?cache=1", import.meta.url))',
'fileURLToPath(new URL("./preload.cjs", runtimeBase))',
"fileURLToPath(new URL(runtimePath, import.meta.url))",
'convertFileURLToPath(new URL("./preload.cjs", import.meta.url))',
];
describe("JavaScript file URL paths", () => {
it.each(urlCases)(
"resolves %s to the file read by Node",
async (reference, target, sourcePath) => {
const root = await createTestTempDirectory("rea-file-url-path-");
const sourceFile = join(root, sourcePath);
await mkdir(dirname(sourceFile), { recursive: true });
await writeFile(join(root, target), 'module.exports = "real preload";\n');
if (reference.includes("%") && sourcePath === "main.mjs")
await writeFile(
join(root, reference),
'module.exports = "encoded-name decoy";\n',
);
const nativePath = fileURLToPath(
new URL(reference, pathToFileURL(sourceFile)),
);
expect(relative(root, nativePath)).toBe(target);
expect(await readFile(nativePath, "utf8")).toContain("real preload");
await writeFile(
sourceFile,
`import { fileURLToPath } from "node:url";\nimport { BrowserWindow } from "electron";\nnew BrowserWindow({ webPreferences: { preload: fileURLToPath(new URL(${JSON.stringify(reference)}, import.meta.url)) } });\n`,
);
const result = await analyzeJavaScriptApplication({
input_path: root,
format: "directory",
});
if (!result.ok) throw result.error;
const { graph } = javascriptApplicationAnalysisResultSchema.parse(
result.value.normalized_result,
);
const preloads = graph.nodes.filter(
({ kind }) => kind === "electron-preload",
);
expect(preloads).toHaveLength(1);
expect(preloads[0]?.observations).not.toHaveLength(0);
for (const observation of preloads[0]?.observations ?? [])
expect(observation.properties).toMatchObject({
resolved_path: target,
resolution_status: "resolved",
resolution_context: "filesystem-expression",
});
},
);
it("keeps a decoded absolute file URL unmapped without host ownership", async () => {
const root = await createTestTempDirectory("rea-literal-file-url-");
await mkdir(join(root, "app"), { recursive: true });
await writeFile(
join(root, "app", "preload name.cjs"),
'module.exports = "literal file URL preload";\n',
);
await writeFile(
join(root, "main.mjs"),
`import { fileURLToPath } from "node:url";\nimport { BrowserWindow } from "electron";\nnew BrowserWindow({ webPreferences: { preload: fileURLToPath("file:///app/preload%20name.cjs") } });\n`,
);
const result = await analyzeJavaScriptApplication({
input_path: root,
format: "directory",
});
if (!result.ok) throw result.error;
const { graph } = javascriptApplicationAnalysisResultSchema.parse(
result.value.normalized_result,
);
const preload = graph.nodes.find(({ kind }) => kind === "electron-preload");
expect(preload?.observations).not.toHaveLength(0);
for (const observation of preload?.observations ?? [])
expect(observation.properties).toMatchObject({
resolved_path: null,
resolution_status: "unavailable",
resolution_context: "filesystem-expression",
});
expect(
graph.edges.filter(
({ source_node_id, relation }) =>
source_node_id === preload?.node_id && relation === "maps_to",
),
).toEqual([]);
});
it.each(unknownExpressions)("leaves unsupported %s unknown", (expression) => {
expect(
staticPath(parseExpression(expression, { sourceType: "module" })),
).toBeUndefined();
});
it("does not URL-decode literal filesystem punctuation", () => {
const analysis = analyzeJavaScriptStaticSource(`
const path = require('node:path');
const {BrowserWindow} = require('electron');
new BrowserWindow({webPreferences:{preload:path.join(__dirname,"preload%20?#.cjs")}});
`);
expect(analysis.parse_error_count).toBe(0);
expect(analysis.electron.browser_windows).toHaveLength(1);
expect(analysis.electron.browser_windows[0]?.preload_path).toBe(
"preload%20?#.cjs",
);
});
});