From ffae857c20d3f6beec46d2578774fe6cfba8d92d Mon Sep 17 00:00:00 2001 From: morluto <76467478+morluto@users.noreply.github.com> Date: Thu, 19 Nov 2026 01:59:16 +0800 Subject: [PATCH] fix(javascript): keep CommonJS wrapper redeclarations from inventing application owners (#12084) fix(javascript): keep wrapper redeclarations from inventing application owners A top-level lexical declaration that reuses a CommonJS wrapper parameter cannot evaluate, and its recovered syntax is complete. Counting that diagnostic as dropped syntax marked the entrypoint as an unexamined loader and erased another package's proven loadFile root. Co-authored-by: Cursor Agent Co-authored-by: morluto --- .../javascript-artifact-reconstruction.md | 5 +- ...criptArtifactGraphElectronCoverage.test.ts | 122 ++++++++++++++++++ .../javascript/javascriptSemanticAnalysis.ts | 3 +- .../javascript/javascriptSourceParser.ts | 13 ++ .../javascript/javascriptStaticAnalysis.ts | 25 +++- .../javascriptStaticCoverage.test.ts | 24 ++++ .../javascript/javascriptStaticCoverage.ts | 1 + 7 files changed, 188 insertions(+), 5 deletions(-) diff --git a/docs/guides/javascript/javascript-artifact-reconstruction.md b/docs/guides/javascript/javascript-artifact-reconstruction.md index 8b5e603f36..4dde2aa4bf 100644 --- a/docs/guides/javascript/javascript-artifact-reconstruction.md +++ b/docs/guides/javascript/javascript-artifact-reconstruction.md @@ -230,7 +230,10 @@ unknown findings and typed uncertainty, including returned-reference widening and unavailable type-only compiler options. `conditional-loader` records a BOM/hashbang source recovered with an uncertain package mode or loader invocation. Its overall `parse_status` stays partial without inventing a syntax -error. Dependency and worker Evidence retains the loader limitation. +error. `commonjs-wrapper-redeclaration` records a top-level lexical declaration +that redeclares a CommonJS wrapper parameter. Node cannot evaluate that module, +and the recovered syntax stays complete because the diagnostic does not drop +statements. Dependency and worker Evidence retains the loader limitation. `examination` reports static semantic resource limits and Electron wrapper expansion limits independently. A completed pass does not establish complete runtime semantics. Route examination and result diff --git a/src/application/javascript/JavaScriptArtifactGraphElectronCoverage.test.ts b/src/application/javascript/JavaScriptArtifactGraphElectronCoverage.test.ts index 379720cc78..3d6bbd91cb 100644 --- a/src/application/javascript/JavaScriptArtifactGraphElectronCoverage.test.ts +++ b/src/application/javascript/JavaScriptArtifactGraphElectronCoverage.test.ts @@ -1,3 +1,4 @@ +import { createHash } from "node:crypto"; import { describe, expect, it } from "vitest"; import type { ArtifactInventorySnapshot } from "../../domain/artifactInventorySnapshot.js"; @@ -423,6 +424,127 @@ it("reports partial coverage when a successful static pass stopped at a limit", ); }); +it("does not treat a CommonJS wrapper redeclaration as another application owner", async () => { + const digest = (value: string) => + createHash("sha256").update(value).digest("hex"); + const textFile = ( + path: string, + source: string, + kind: JavaScriptArtifactFile["kind"], + ): JavaScriptArtifactFile => ({ + path, + container_sha256: SHA256, + sha256: digest(path + source), + bytes: source.length, + inventory_artifact_id: `art_${digest(path)}`, + kind, + unpacked: false, + text: { included: true, value: source }, + }); + const files = [ + textFile( + "a/package.json", + JSON.stringify({ main: "main.cjs" }), + "package-json", + ), + textFile( + "a/main.cjs", + "const require={main:{require(){}}};require.main.require('../shared/window.cjs');", + "javascript", + ), + textFile("b/package.json", '{"main":"main.cjs"}', "package-json"), + textFile("b/main.cjs", "require('../shared/window.cjs');", "javascript"), + textFile( + "shared/window.cjs", + "const {BrowserWindow}=require('electron');new BrowserWindow().loadFile('index.html');", + "javascript", + ), + textFile("a/index.html", "possible page", "html"), + textFile("b/index.html", "proven page", "html"), + textFile("shared/index.html", "source-relative decoy", "html"), + textFile("index.html", "artifact-root decoy", "html"), + ]; + const analyzed = await Promise.all( + files + .filter((file) => file.kind === "javascript") + .map((file) => + analyzedEntry( + file.text.included ? file.text.value : "", + file.path, + ).then((entry) => ({ ...entry, file })), + ), + ); + const local = analyzed.find((entry) => entry.file.path === "a/main.cjs"); + expect(local?.javascript).toMatchObject({ + parse_status: "complete", + parse_error_count: 0, + references: [], + analysis_coverage: { + syntax: { status: "complete", error_count: 0 }, + semantics: { uncertainty: ["commonjs-wrapper-redeclaration"] }, + }, + }); + const packageObservation = (path: string, main: string) => ({ + path, + sha256: digest(path), + status: "included" as const, + name: null, + version: null, + main, + main_status: "declared" as const, + main_entrypoint: main, + renderer_declarations: {}, + renderer_entrypoint: null, + limitation: null, + }); + const analysis: JavaScriptArtifactAnalysis = { + jsonDocuments: new JavaScriptJsonDocuments(), + files: analyzed, + packages: [ + packageObservation("a/package.json", "main.cjs"), + packageObservation("b/package.json", "main.cjs"), + ], + json_modules: [], + html_scripts: [], + html_inline_scripts: [], + source_maps: [], + visited_ast_nodes: 0, + findings: 0, + modules: 0, + parse_failures: 0, + limitations: [], + }; + const steps = buildGraph( + snapshot, + { + files, + unavailable_relevant_files: [], + containers: [], + text_bytes_read: files.reduce((total, file) => total + file.bytes, 0), + invalid_utf8_files: 0, + }, + analysis, + ); + let next = steps.next(); + while (next.done !== true) next = steps.next(); + const roles = next.value.graph.nodes.filter( + (node) => node.kind === "electron-renderer", + ); + expect(roles).toHaveLength(1); + expect(roles[0]?.observations).toEqual( + expect.arrayContaining([ + expect.objectContaining({ + properties: expect.objectContaining({ + declared_path: "index.html", + resolution_status: "resolved", + resolved_path: "b/index.html", + limitations: [], + }), + }), + ]), + ); +}); + it("keeps recovered Electron facts partial after syntax recovery", async () => { const source = `import { BrowserWindow } from "electron"; new BrowserWindow({webPreferences: {sandbox: true}}); const duplicate = 1; const duplicate = 2;`; const entry = await analyzedEntry(source, "main.mjs"); diff --git a/src/domain/javascript/javascriptSemanticAnalysis.ts b/src/domain/javascript/javascriptSemanticAnalysis.ts index d8dc8b986f..c8e5ec99dd 100644 --- a/src/domain/javascript/javascriptSemanticAnalysis.ts +++ b/src/domain/javascript/javascriptSemanticAnalysis.ts @@ -133,6 +133,7 @@ import { javaScriptSourceLoaderCondition, javaScriptStrictnessAt, parseJavaScriptSource, + recoveredJavaScriptSyntaxErrorCount, type ParsedJavaScriptSource, } from "./javascriptSourceParser.js"; @@ -311,7 +312,7 @@ export function* analyzeParsedJavaScriptSemanticsSteps( }); yield; const references = yield* collectSemanticReferencesSteps(file.program, state); - const parserPartial = file.errors.length > 0; + const parserPartial = recoveredJavaScriptSyntaxErrorCount(file.errors) > 0; const bindings = immutableSemanticBindings(state); yield; const callables = collectSemanticReturns(state, parserPartial); diff --git a/src/domain/javascript/javascriptSourceParser.ts b/src/domain/javascript/javascriptSourceParser.ts index 25d382261f..e1bba22bd3 100644 --- a/src/domain/javascript/javascriptSourceParser.ts +++ b/src/domain/javascript/javascriptSourceParser.ts @@ -179,6 +179,19 @@ const COMMONJS_WRAPPER_PARAMETERS = new Set([ "__dirname", ]); +/** Token recovery drops syntax. A wrapper redeclaration does not. */ +export const recoveredJavaScriptSyntaxErrorCount = ( + errors: readonly ParsedJavaScriptSource["errors"][number][], +): number => + errors.filter((error) => !(error instanceof JavaScriptLoaderSyntaxError)) + .length; + +/** Top-level lexical names that collide with Node's CommonJS parameters. */ +export const commonJsWrapperRedeclarationCount = ( + errors: readonly ParsedJavaScriptSource["errors"][number][], +): number => + errors.filter((error) => error instanceof JavaScriptLoaderSyntaxError).length; + /** Only top-level lexical bindings conflict with the wrapper's parameters. */ const lexicalWrapperBindings = (program: t.Program): t.Identifier[] => { const bindings = new Map(); diff --git a/src/domain/javascript/javascriptStaticAnalysis.ts b/src/domain/javascript/javascriptStaticAnalysis.ts index 0e818ec783..d8db46a393 100644 --- a/src/domain/javascript/javascriptStaticAnalysis.ts +++ b/src/domain/javascript/javascriptStaticAnalysis.ts @@ -74,7 +74,9 @@ import { indexJavaScriptBindingsWithReceiversSteps, } from "./javascriptSemanticAnalysis.js"; import { + commonJsWrapperRedeclarationCount, javaScriptSourceLoaderCondition, + recoveredJavaScriptSyntaxErrorCount, type ParsedJavaScriptSource, } from "./javascriptSourceParser.js"; @@ -101,7 +103,8 @@ export const memberMutationRefusedJavaScriptStaticAnalysis = ( file: ParsedJavaScriptSource, refusal: AnalysisResourceConstraintError, ): JavaScriptStaticAnalysis => { - const parserErrors = file.errors.length; + const parserErrors = recoveredJavaScriptSyntaxErrorCount(file.errors); + const wrapperRedeclarations = commonJsWrapperRedeclarationCount(file.errors); const loaderCondition = javaScriptSourceLoaderCondition(file.program); const accumulator = createJavaScriptAnalysisAccumulator(source.length); addSourceMapDirectives(source, file.comments ?? [], accumulator); @@ -113,7 +116,14 @@ export const memberMutationRefusedJavaScriptStaticAnalysis = ( : { status: "recovered", error_count: parserErrors }, semantics: { unknown_findings: null, - uncertainty: loaderCondition === undefined ? [] : ["conditional-loader"], + uncertainty: [ + ...(loaderCondition === undefined + ? [] + : ["conditional-loader" as const]), + ...(wrapperRedeclarations === 0 + ? [] + : ["commonjs-wrapper-redeclaration" as const]), + ], }, examination: { status: "not-examined", @@ -255,7 +265,8 @@ const finalizeStaticAnalysis = ( bindings: JavaScriptSemanticAnalysisState, routes: JavaScriptRouteSourceFacts, ): JavaScriptStaticAnalysis => { - const parserErrors = file.errors.length; + const parserErrors = recoveredJavaScriptSyntaxErrorCount(file.errors); + const wrapperRedeclarations = commonJsWrapperRedeclarationCount(file.errors); const typeOnlySideEffect = hasUncertainTypeOnlyModuleSideEffect(file.program); // A `worker` or `service-worker` reference records a URL relative to the // importing source, so `new Worker(new URL("electron", import.meta.url))` is @@ -310,6 +321,9 @@ const finalizeStaticAnalysis = ( ...(typeOnlySideEffect ? ["type-only-module-side-effect" as const] : []), + ...(wrapperRedeclarations === 0 + ? [] + : ["commonjs-wrapper-redeclaration" as const]), ], }, examination: { @@ -352,6 +366,11 @@ const finalizeStaticAnalysis = ( : [ "The parser recovered from syntax errors; affected facts are partial.", ]), + ...(wrapperRedeclarations === 0 + ? [] + : [ + "A top-level lexical declaration redeclares a CommonJS wrapper parameter, so this module cannot evaluate. Recovered syntax was examined completely.", + ]), ...(accumulator.unknownFindings === 0 ? [] : [ diff --git a/src/domain/javascript/javascriptStaticCoverage.test.ts b/src/domain/javascript/javascriptStaticCoverage.test.ts index 214b4a31d2..aa1c54c282 100644 --- a/src/domain/javascript/javascriptStaticCoverage.test.ts +++ b/src/domain/javascript/javascriptStaticCoverage.test.ts @@ -160,6 +160,30 @@ it("retains typed examination limits alongside successfully parsed source", () = }); }); +it("keeps a CommonJS wrapper redeclaration out of recovered-syntax coverage", () => { + const source = + "const require={main:{require(){}}};require.main.require('../shared/window.cjs');"; + const file = parseJavaScriptSource(source, "a/main.cjs"); + expect(file).not.toBeNull(); + expect(file!.errors).toEqual([ + expect.objectContaining({ + reasonCode: "CommonJsWrapperLexicalDeclaration", + }), + ]); + const result = analyzeParsedJavaScriptStaticSource(source, file!); + expect(result.parse_status).toBe("complete"); + expect(result.parse_error_count).toBe(0); + expect(result.references).toEqual([]); + expect(result.analysis_coverage).toMatchObject({ + syntax: { status: "complete", error_count: 0 }, + semantics: { + unknown_findings: 0, + uncertainty: ["commonjs-wrapper-redeclaration"], + }, + examination: { status: "complete" }, + }); +}); + it("preserves the legacy summary responsibility without relabeling independent limitations", () => { const base = analyzeJavaScriptStaticSource( "export const value = 1;", diff --git a/src/domain/javascript/javascriptStaticCoverage.ts b/src/domain/javascript/javascriptStaticCoverage.ts index 040625e98e..cfed674efe 100644 --- a/src/domain/javascript/javascriptStaticCoverage.ts +++ b/src/domain/javascript/javascriptStaticCoverage.ts @@ -29,6 +29,7 @@ export const javaScriptStaticCoverageSchema = z.strictObject({ "returned-reference-widening", "type-only-module-side-effect", "conditional-loader", + "commonjs-wrapper-redeclaration", ]), ), }),