mirror of
https://github.com/morluto/rea.git
synced 2026-11-18 20:53:00 +00:00
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 <cursoragent@cursor.com> Co-authored-by: morluto <morluto@users.noreply.github.com>
This commit is contained in:
7 files changed
+188
-5
No files matched your search
@@ -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
|
||||
|
||||
@@ -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");
|
||||
|
||||
@@ -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);
|
||||
|
||||
@@ -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<string, t.Identifier>();
|
||||
|
||||
@@ -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
|
||||
? []
|
||||
: [
|
||||
|
||||
@@ -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;",
|
||||
|
||||
@@ -29,6 +29,7 @@ export const javaScriptStaticCoverageSchema = z.strictObject({
|
||||
"returned-reference-widening",
|
||||
"type-only-module-side-effect",
|
||||
"conditional-loader",
|
||||
"commonjs-wrapper-redeclaration",
|
||||
]),
|
||||
),
|
||||
}),
|
||||
|
||||
Reference in new issue
Block a user