fix(javascript): resolve bundled exports by binding identity

Identify the factory exports parameter through the existing semantic binding owner, including renamed and minified Webpack parameters. Reject nested targets, bare alias rebinding, and shadowed identifiers. Prune the duplicated source happy path after validating the public CLI workflow.

Validation: public analyze-javascript-application CLI acceptance and focused semantic traversal/module-index tests.

Fixes #2171
This commit is contained in:
morluto
2026-10-13 04:12:14 +08:00
parent 921bb95755
commit 5ab0cbb48e
5 changed files with 150 additions and 25 deletions
@@ -10,6 +10,10 @@ import {
semanticStaticPropertyKey, semanticStaticPropertyKey,
} from "./javascriptAstValues.js"; } from "./javascriptAstValues.js";
import { stringValue } from "./javascriptStaticAnalysisHelpers.js"; import { stringValue } from "./javascriptStaticAnalysisHelpers.js";
import {
resolveSemanticBindingState,
type JavaScriptSemanticAnalysisState,
} from "./javascriptSemanticState.js";
/** Static CommonJS export names. */ /** Static CommonJS export names. */
export interface StaticExports { export interface StaticExports {
@@ -29,13 +33,41 @@ export const fingerprintJavaScriptAst = (node: t.Node): string => {
}; };
/** Collect statically declared CommonJS/bundler export names from one factory. */ /** Collect statically declared CommonJS/bundler export names from one factory. */
export const collectJavaScriptExports = (node: t.Node): StaticExports => { export const collectJavaScriptExports = (
node: t.Node,
bindings?: JavaScriptSemanticAnalysisState,
): StaticExports => {
const exports = new Set<string>(); const exports = new Set<string>();
const factoryExports =
bindings !== undefined &&
t.isFunction(node) &&
t.isIdentifier(node.params[1])
? resolveSemanticBindingState(
bindings,
node.params[1],
node.params[1].name,
)?.bindingId
: undefined;
const isExportsAlias = (reference: t.Node | null): boolean => {
if (!t.isIdentifier(reference)) return false;
if (factoryExports === undefined) return reference.name === "exports";
return (
bindings !== undefined &&
resolveSemanticBindingState(bindings, reference, reference.name)
?.bindingId === factoryExports
);
};
traverseJavaScriptAst(node, { traverseJavaScriptAst(node, {
enter: (current) => { enter: (current) => {
if (t.isAssignmentExpression(current)) if (t.isAssignmentExpression(current))
collectAssignmentExports(current.left, current.right, exports); collectAssignmentExports(
if (t.isCallExpression(current)) collectCallExports(current, exports); current.left,
current.right,
exports,
isExportsAlias,
);
if (t.isCallExpression(current))
collectCallExports(current, exports, isExportsAlias);
return undefined; return undefined;
}, },
}); });
@@ -72,17 +104,19 @@ const collectAssignmentExports = (
left: t.LVal | t.OptionalMemberExpression, left: t.LVal | t.OptionalMemberExpression,
right: t.Expression, right: t.Expression,
output: Set<string>, output: Set<string>,
isExportsAlias: (root: t.Node | null) => boolean,
): void => { ): void => {
const path = memberPath(left); const path = memberPath(left);
if (path === null) return; if (path === null) return;
const root = memberRoot(left);
const exportsAlias = isExportsAlias(root);
// Rebinding the CommonJS alias does not replace module.exports. // Rebinding the CommonJS alias does not replace module.exports.
if (path.length === 1 && path[0] === "exports") return; if (path.length === 1 && exportsAlias) return;
const exportOffset = const exportOffset = exportsAlias
path[0] === "exports" ? 1
? 1 : path[0] === "module" && path[1] === "exports"
: path[0] === "module" && path[1] === "exports" ? 2
? 2 : null;
: null;
if (exportOffset === null) return; if (exportOffset === null) return;
if (path.length === exportOffset) { if (path.length === exportOffset) {
if (t.isObjectExpression(right)) collectObjectKeys(right, output); if (t.isObjectExpression(right)) collectObjectKeys(right, output);
@@ -98,6 +132,7 @@ const collectAssignmentExports = (
const collectCallExports = ( const collectCallExports = (
call: t.CallExpression, call: t.CallExpression,
output: Set<string>, output: Set<string>,
isExportsAlias: (root: t.Node | null) => boolean,
): void => { ): void => {
const callee = memberPath(call.callee); const callee = memberPath(call.callee);
if (callee === null) return; if (callee === null) return;
@@ -107,13 +142,14 @@ const collectCallExports = (
callee[1] === "defineProperty"; callee[1] === "defineProperty";
const declarationCall = callee.length >= 2 && callee.at(-1) === "d"; const declarationCall = callee.length >= 2 && callee.at(-1) === "d";
if (!definePropertyCall && !declarationCall) return; if (!definePropertyCall && !declarationCall) return;
const target = memberPath(call.arguments[0]); const targetNode = call.arguments[0];
const target = memberPath(targetNode);
const exportTarget = const exportTarget =
target !== null && isExportsAlias(targetNode ?? null) ||
((target.length === 1 && target[0] === "exports") || (target !== null &&
(target.length === 2 && target.length === 2 &&
target[0] === "module" && target[0] === "module" &&
target[1] === "exports")); target[1] === "exports");
if (!exportTarget) return; if (!exportTarget) return;
if (definePropertyCall) { if (definePropertyCall) {
const name = stringValue(call.arguments[1]); const name = stringValue(call.arguments[1]);
@@ -125,6 +161,17 @@ const collectCallExports = (
collectObjectKeys(declarations, output); collectObjectKeys(declarations, output);
}; };
const memberRoot = (node: t.Node | null | undefined): t.Node | null => {
let current = node;
while (
current !== null &&
current !== undefined &&
(t.isMemberExpression(current) || t.isOptionalMemberExpression(current))
)
current = current.object;
return current ?? null;
};
const collectObjectKeys = ( const collectObjectKeys = (
object: t.ObjectExpression, object: t.ObjectExpression,
output: Set<string>, output: Set<string>,
@@ -232,8 +232,8 @@ const inspectNode = (
inspectElectronStaticNode(node, findings); inspectElectronStaticNode(node, findings);
if (t.isCallExpression(node)) { if (t.isCallExpression(node)) {
inspectBundlerBootstrap(source, node, accumulator, bindings); inspectBundlerBootstrap(source, node, accumulator, bindings);
inspectBundlerRegistration(source, node, accumulator); inspectBundlerRegistration(source, node, accumulator, bindings);
inspectEsbuildWrapper(source, node, accumulator); inspectEsbuildWrapper(source, node, accumulator, bindings);
inspectCall(source, node, findings); inspectCall(source, node, findings);
} else if (t.isOptionalCallExpression(node)) { } else if (t.isOptionalCallExpression(node)) {
inspectCall(source, node, findings); inspectCall(source, node, findings);
@@ -37,6 +37,7 @@ export const inspectBundlerRegistration = (
source: string, source: string,
call: t.CallExpression, call: t.CallExpression,
accumulator: AnalysisAccumulator, accumulator: AnalysisAccumulator,
bindings: JavaScriptSemanticAnalysisState,
): void => { ): void => {
const runtime = chunkRuntime(call); const runtime = chunkRuntime(call);
const entry = call.arguments[0]; const entry = call.arguments[0];
@@ -45,7 +46,10 @@ export const inspectBundlerRegistration = (
const table = entry.elements[1]; const table = entry.elements[1];
const runtimeValue = runtimeMetadata(entry.elements[2]); const runtimeValue = runtimeMetadata(entry.elements[2]);
if (!t.isArrayExpression(chunkIds) || !t.isObjectExpression(table)) return; if (!t.isArrayExpression(chunkIds) || !t.isObjectExpression(table)) return;
const recovered = recoverBundlerModules(source, table, runtime, accumulator); const recovered = recoverBundlerModules(source, table, accumulator, {
runtime,
bindings,
});
const chunkKeys = staticArrayValues(chunkIds); const chunkKeys = staticArrayValues(chunkIds);
accumulator.unknownFindings += chunkKeys.unknown; accumulator.unknownFindings += chunkKeys.unknown;
accumulator.unknownFindings += accumulator.unknownFindings +=
@@ -98,8 +102,8 @@ export const inspectBundlerBootstrap = (
const recovered = recoverBundlerModules( const recovered = recoverBundlerModules(
source, source,
bootstrap.table, bootstrap.table,
runtime,
accumulator, accumulator,
{ runtime, bindings },
); );
const entries: string[] = []; const entries: string[] = [];
let unknownEntries = 0; let unknownEntries = 0;
@@ -148,6 +152,7 @@ export const inspectEsbuildWrapper = (
source: string, source: string,
call: t.CallExpression, call: t.CallExpression,
accumulator: AnalysisAccumulator, accumulator: AnalysisAccumulator,
bindings: JavaScriptSemanticAnalysisState,
): void => { ): void => {
const name = calleeName(call.callee); const name = calleeName(call.callee);
const wrapperKind = const wrapperKind =
@@ -159,7 +164,10 @@ export const inspectEsbuildWrapper = (
const table = call.arguments[0]; const table = call.arguments[0];
if (wrapperKind === null || !t.isObjectExpression(table)) return; if (wrapperKind === null || !t.isObjectExpression(table)) return;
const runtime = `esbuild-${wrapperKind}`; const runtime = `esbuild-${wrapperKind}`;
const recovered = recoverBundlerModules(source, table, runtime, accumulator); const recovered = recoverBundlerModules(source, table, accumulator, {
runtime,
bindings,
});
if (recovered.modules.length === 0) return; if (recovered.modules.length === 0) return;
accumulator.unknownFindings += recovered.unknownAsyncChunkKeys; accumulator.unknownFindings += recovered.unknownAsyncChunkKeys;
const registration: JavaScriptBundlerRegistration = { const registration: JavaScriptBundlerRegistration = {
@@ -191,11 +199,16 @@ interface RecoveredBundlerModules {
readonly unknownAsyncChunkKeys: number; readonly unknownAsyncChunkKeys: number;
} }
interface BundlerRecoveryContext {
readonly runtime: string;
readonly bindings: JavaScriptSemanticAnalysisState;
}
const recoverBundlerModules = ( const recoverBundlerModules = (
source: string, source: string,
table: t.ObjectExpression, table: t.ObjectExpression,
runtime: string,
accumulator: AnalysisAccumulator, accumulator: AnalysisAccumulator,
context: BundlerRecoveryContext,
): RecoveredBundlerModules => { ): RecoveredBundlerModules => {
const modules: JavaScriptBundlerModule[] = []; const modules: JavaScriptBundlerModule[] = [];
const asyncChunkKeys: string[] = []; const asyncChunkKeys: string[] = [];
@@ -204,8 +217,8 @@ const recoverBundlerModules = (
const recovered = recoverBundlerModule( const recovered = recoverBundlerModule(
source, source,
property, property,
runtime,
accumulator, accumulator,
context,
); );
if (recovered === null) continue; if (recovered === null) continue;
modules.push(recovered.module); modules.push(recovered.module);
@@ -222,20 +235,21 @@ const recoverBundlerModules = (
const recoverBundlerModule = ( const recoverBundlerModule = (
source: string, source: string,
property: t.ObjectMethod | t.ObjectProperty | t.SpreadElement, property: t.ObjectMethod | t.ObjectProperty | t.SpreadElement,
runtime: string,
accumulator: AnalysisAccumulator, accumulator: AnalysisAccumulator,
context: BundlerRecoveryContext,
): { ): {
readonly module: JavaScriptBundlerModule; readonly module: JavaScriptBundlerModule;
readonly asyncChunkKeys: readonly string[]; readonly asyncChunkKeys: readonly string[];
readonly unknownAsyncChunkKeys: number; readonly unknownAsyncChunkKeys: number;
} | null => { } | null => {
const { runtime, bindings } = context;
const factory = moduleFactory(property); const factory = moduleFactory(property);
if (factory === undefined) return null; if (factory === undefined) return null;
const key = modulePropertyName(property); const key = modulePropertyName(property);
if (key.startsWith("[computed@") || key.startsWith("[unknown@")) if (key.startsWith("[computed@") || key.startsWith("[unknown@"))
accumulator.unknownFindings += 1; accumulator.unknownFindings += 1;
const fingerprint = fingerprintJavaScriptAst(factory); const fingerprint = fingerprintJavaScriptAst(factory);
const exportsValue = collectJavaScriptExports(factory); const exportsValue = collectJavaScriptExports(factory, bindings);
const requireName = factoryRequireName(factory); const requireName = factoryRequireName(factory);
const asyncChunks = collectBundlerAsyncChunkKeys(factory, requireName); const asyncChunks = collectBundlerAsyncChunkKeys(factory, requireName);
if (typeof factory.start === "number" && typeof factory.end === "number") { if (typeof factory.start === "number" && typeof factory.end === "number") {
@@ -50,6 +50,18 @@ it("does not infer a bootstrap from a function table without a matching loader",
expect(analysis.bundler_registrations).toEqual([]); expect(analysis.bundler_registrations).toEqual([]);
}); });
it("does not treat a same-named shadow as the factory exports parameter", () => {
const analysis =
analyzeJavaScriptStaticSource(`globalThis.webpackChunkApp.push([[1], {
first(module, e, require) {
{ const e = {}; require.d(e, { shadowed: () => 1 }); e.other = 2; }
}
}]);`);
expect(analysis.bundler_registrations[0]?.modules).toMatchObject([
{ module_key: "first", exports: [] },
]);
});
it("does not confuse a shadowed dispatch table with the outer module table", () => { it("does not confuse a shadowed dispatch table with the outer module table", () => {
const analysis = analyzeJavaScriptStaticSource(`(() => { const analysis = analyzeJavaScriptStaticSource(`(() => {
const modules = { 17(module) { module.exports = require("electron"); } }; const modules = { 17(module) { module.exports = require("electron"); } };
@@ -0,0 +1,52 @@
import { mkdir, writeFile } from "node:fs/promises";
import { join } from "node:path";
import { expect } from "vitest";
import { parseEvidence } from "../../../src/domain/evidence.js";
import { javascriptApplicationAnalysisResultSchema } from "../../../src/domain/javascript/javascriptApplicationAnalysis.js";
import { createTestTempDirectory } from "../../fixtures/temporaryDirectory.js";
import { cliTest } from "../../support/cli/cliFixture.js";
cliTest(
"reports Webpack exports attached to renamed factory parameters",
async ({ cli }) => {
const root = await createTestTempDirectory("rea-webpack-renamed-exports-");
await mkdir(join(root, "src"));
await writeFile(
join(root, "src", "chunk.js"),
`globalThis.webpackChunkApp.push([[1], {
17(module, __webpack_exports__, __webpack_require__) {
__webpack_require__.d(__webpack_exports__, { alpha: () => 1, "beta.gamma": () => 2 });
Object.defineProperty(__webpack_exports__, "delta", { enumerable: true, get() { return 3; } });
__webpack_require__.d(__webpack_exports__.nested, { nested_target: () => 0 });
__webpack_exports__ = { rebound: () => 0 };
__webpack_require__.d({}, { unrelated: () => 0 });
{ const exports = {}; __webpack_require__.d(exports, { shadowed_exports: () => 5 }); }
},
23(m, e, r) { r.d(e, { alpha: () => 1 }); }
}]);`,
);
const response = await cli.run({
arguments: ["analyze-javascript-application", root, "--format", "json"],
environment: { REA_LOG_LEVEL: "silent" },
});
expect(response.exitCode).toBe(0);
const result = javascriptApplicationAnalysisResultSchema.parse(
parseEvidence(response.json).normalized_result,
);
const modules = result.graph.nodes
.filter(({ kind }) => kind === "javascript-module")
.map(({ observations }) => observations[0]?.properties);
expect(modules).toEqual(
expect.arrayContaining([
expect.objectContaining({
module_key: "17",
exports: ["alpha", "beta.gamma", "delta"],
}),
expect.objectContaining({ module_key: "23", exports: ["alpha"] }),
]),
);
expect(result.graph.coverage.status).toBe("complete");
},
);