diff --git a/src/domain/javascript/electronBundledRequireIdentity.test.ts b/src/domain/javascript/electronBundledRequireIdentity.test.ts index 307b49b3ff..15f3fea848 100644 --- a/src/domain/javascript/electronBundledRequireIdentity.test.ts +++ b/src/domain/javascript/electronBundledRequireIdentity.test.ts @@ -1,7 +1,11 @@ import { describe, expect, it } from "vitest"; import { runInNewContext } from "node:vm"; -import { analyzeJavaScriptStaticSource as analyzeUnknownHostSource } from "../../../tests/fixtures/javascriptStaticAnalysis.js"; +import { + analyzeJavaScriptStaticSource as analyzeUnknownHostSource, + analyzeParsedJavaScriptStaticSource, +} from "../../../tests/fixtures/javascriptStaticAnalysis.js"; +import { parseJavaScriptSource } from "./javascriptSourceParser.js"; import { analyzeCommonJsStaticFixture as analyzeJavaScriptStaticSource } from "../../../tests/fixtures/javascriptCommonJsAnalysis.js"; // Webpack 5 standalone bootstrap with an Electron external, as emitted for @@ -337,6 +341,68 @@ it("reports the alias budget when a destructured external alias chain exceeds it }); }); +describe("exhausted CommonJS delegate-write receiver selections", () => { + const writes = "while(flag)receiver=receiver[key];receiver[key]=0;"; + + it.each([ + ["a closed local cycle", `let receiver={};${writes}`, 1], + [ + "a Module stored in a property", + `let receiver={host:module};${writes}`, + 0, + ], + [ + "a Module installed through a prior member write", + `let receiver={};receiver.host=module;${writes}`, + 0, + ], + [ + "an opaque parameter", + `function mutate(receiver){${writes}}mutate(module);`, + 0, + ], + [ + "a mutated prototype", + `Object.prototype.host=module;let receiver={};${writes}`, + 0, + ], + [ + "indirect eval that can change inherited members", + `(0, eval)(code);let receiver={};${writes}`, + 0, + ], + [ + "constructed code that can change inherited members", + `Function(code)();let receiver={};${writes}`, + 0, + ], + [ + "an unfinished source closure", + `let receiver=[${Array(24).fill("0").join(",")}];${writes}`, + 0, + ], + ] as const)( + "preserves the receiver proof for %s", + (_name, sideEffect, expected) => { + const source = bootstrap(EXTERNAL, CONSUMER, `${sideEffect}n(100);`); + const parsed = parseJavaScriptSource(source, "main.cjs"); + if (parsed === null) throw new Error("Expected a parsed Webpack fixture"); + const analysis = analyzeParsedJavaScriptStaticSource(source, parsed, { + alias_selections: 16, + }); + expect( + analysis.analysis_coverage.examination.semantic_resource_limits, + ).toContain("alias-selections"); + expect(analysis.electron.browser_windows).toHaveLength(expected); + expect( + analysis.electron.ipc.filter( + ({ resolution_basis }) => resolution_basis !== "wrapper-substitution", + ), + ).toHaveLength(expected); + }, + ); +}); + describe("Webpack externals with a tampered runtime", () => { it.each([ [ diff --git a/src/domain/javascript/javascriptSemanticEffectLog.ts b/src/domain/javascript/javascriptSemanticEffectLog.ts index 280d2fb036..d0d97e7319 100644 --- a/src/domain/javascript/javascriptSemanticEffectLog.ts +++ b/src/domain/javascript/javascriptSemanticEffectLog.ts @@ -1030,6 +1030,28 @@ const opaqueCodeMayReachBindingReference = ( ): boolean => semanticBindingMayHaveOpaqueEffect(binding, state, capturePoint, "reference"); +/** Whether a binding can acquire members outside its retained assignment sources. */ +export const bindingHasUnmodeledMemberValues = ( + binding: JavaScriptSemanticBindingState, + write: t.Node, + state: JavaScriptSemanticAnalysisState, +): boolean => { + if (opaqueCodeMayReachBindingReference(binding, state, undefined)) + return true; + if ( + binding.memberWrites.some((effect) => effect.assignedSources === undefined) + ) + return true; + // The queried store itself can mark its selected slot escaped. Its retained + // RHS still participates in the source proof. + const storeIsModeled = binding.memberWrites.some( + (effect) => effect.node === write, + ); + return binding.escapedPaths.some( + (effect) => effect.node !== write || !storeIsModeled, + ); +}; + const inactiveMemberWriteNodes = new WeakMap< JavaScriptSemanticAnalysisState, WeakSet diff --git a/src/domain/javascript/javascriptSemanticRequireOrigin.ts b/src/domain/javascript/javascriptSemanticRequireOrigin.ts index 9f824c728c..5b066cfd3f 100644 --- a/src/domain/javascript/javascriptSemanticRequireOrigin.ts +++ b/src/domain/javascript/javascriptSemanticRequireOrigin.ts @@ -20,6 +20,7 @@ import type { JavaScriptModuleOrigin } from "./javascriptSemanticIr.js"; import { resolveSemanticBindingState, semanticResolutionBlocked, + semanticPrototypeOwners, semanticStableInitializer, type JavaScriptSemanticAnalysisState, type JavaScriptBindingIndex, @@ -31,6 +32,7 @@ import { semanticBindingHasPriorValueWrite, } from "./javascriptSemanticMutationInitializers.js"; import { + readExactJavaScriptLiteral, semanticStaticPropertyKey, semanticMemberChain, semanticWriteSiteTarget, @@ -49,12 +51,18 @@ import { import { ambientBindingMayObserveWriteAt, ambientPathMayObserveAt, + ambientPathOrMemberMayHaveChanged, + bindingHasUnmodeledMemberValues, + opaqueCodeMayRebindBinding, semanticEffectMayPrecede, + semanticMemberWriteSources, } from "./javascriptSemanticEffectLog.js"; +import { semanticGlobalCodeSites } from "./javascriptSemanticEffectRecord.js"; import { createSemanticReturnedReferences } from "./javascriptSemanticReturnedReferences.js"; import { semanticIterationSources } from "./javascriptSemanticIterationSources.js"; import { semanticCommonJsRequireOwnEnumerableAt, + semanticReferenceIterationUnknown, semanticReferenceSourcesInactive, } from "./javascriptSemanticReferenceSources.js"; import { @@ -128,7 +136,7 @@ const commonJsDelegateChangedAt = ( state: JavaScriptSemanticAnalysisState, ): boolean => writesModuleRequire(state).some((write) => - semanticEffectMayPrecede(state, node, write.node), + semanticEffectMayPrecede(state, node, write), ); const commonJsLoaderAt = ( @@ -982,13 +990,9 @@ const isWrapperRequireInitializerCall = ( }; type ModuleSourceMatch = "possible" | "no-match" | "incomplete"; -type ModuleRequireWrite = { - readonly node: t.Node; - readonly resolution: "possible" | "incomplete"; -}; const moduleRequireWrites = new WeakMap< JavaScriptSemanticAnalysisState, - readonly ModuleRequireWrite[] + readonly t.Node[] >(); const moduleReturnedReferences = new WeakMap< JavaScriptSemanticAnalysisState, @@ -1554,21 +1558,125 @@ export const semanticModuleRequireCallAt = ( ); }; +/** + * An exhausted selector walk can still exclude the host on a closed graph of + * local values. Follow every retained source and member-write RHS without + * expanding selector paths. Opaque inputs and an unfinished graph stay unknown. + */ +const hasClosedLocalReceiverSources = ( + root: t.Node, + write: t.Node, + state: JavaScriptSemanticAnalysisState, +): boolean => { + if ( + !state.memberMutationFactsComplete || + // The closure follows inherited members without selecting a read time. + semanticGlobalCodeSites(state).length > 0 || + semanticPrototypeOwners.some((owner) => + ambientPathOrMemberMayHaveChanged(state, ["global", owner]), + ) + ) + return false; + const pending: t.Node[] = []; + const scheduled = new Set(); + const enqueue = (source: t.Node): boolean => { + const node = unwrapJavaScriptExpression(source).node; + if (scheduled.has(node)) return true; + if (scheduled.size >= state.precision.alias_selections) return false; + scheduled.add(node); + pending.push(node); + return true; + }; + if (!enqueue(root)) return false; + const bindings = new Set(); + while (pending.length > 0) { + const node = pending.pop()!; + if (t.isIdentifier(node)) { + const binding = resolveSemanticBindingState(state, node, node.name); + if ( + binding === undefined || + semanticResolutionBlocked(state, node, node.name) || + commonJsWrapperBindingDeclaration(node, node.name, state) !== + undefined || + binding.definitions.some( + ({ kind }) => kind === "parameter" || kind === "catch", + ) || + binding.directOrigins.length !== 0 || + binding.initializers.length === 0 || + bindingHasUnmodeledMemberValues(binding, write, state) || + opaqueCodeMayRebindBinding(binding, state, node) + ) + return false; + if (bindings.has(binding.bindingId)) continue; + bindings.add(binding.bindingId); + for (const sources of [ + binding.initializers, + binding.referenceInitializers, + semanticMemberWriteSources(binding), + ]) + for (const source of sources) { + if (semanticReferenceIterationUnknown(source, state)) return false; + if ( + !semanticReferenceSourcesInactive(source, state) && + !enqueue(source.node) + ) + return false; + } + } else if ( + t.isMemberExpression(node) || + t.isOptionalMemberExpression(node) + ) { + if (!enqueue(node.object)) return false; + } else if (t.isObjectExpression(node)) { + for (const property of node.properties) { + if ( + !t.isObjectProperty(property) || + semanticStaticPropertyKey(property.key, property.computed) === + "__proto__" + ) + return false; + if (!enqueue(property.value)) return false; + } + } else if (t.isArrayExpression(node)) { + for (const element of node.elements) { + if (t.isSpreadElement(element)) return false; + if (element !== null && !enqueue(element)) return false; + } + } else if (t.isConditionalExpression(node) || t.isLogicalExpression(node)) { + const [left, right] = t.isConditionalExpression(node) + ? [node.consequent, node.alternate] + : [node.left, node.right]; + if (!enqueue(left) || !enqueue(right)) return false; + } else if (!readExactJavaScriptLiteral(node).found) { + return false; + } + } + return true; +}; + const writesModuleRequire = ( state: JavaScriptSemanticAnalysisState, -): readonly ModuleRequireWrite[] => { +): readonly t.Node[] => { const cached = moduleRequireWrites.get(state); if (cached !== undefined) return cached; // Interop invocation resolution may ask for require provenance while this // index is being built. Publish a temporary empty result to break that cycle. moduleRequireWrites.set(state, []); - const writes: ModuleRequireWrite[] = []; + const writes: t.Node[] = []; const interop = createSemanticModuleInterop(state); - const isModuleObject = (node: t.Node): ModuleSourceMatch => - hasCommonJsModuleSource(node, state, false, "module"); const record = (node: t.Node, receiver: t.Node): void => { - const resolution = isModuleObject(receiver); - if (resolution !== "no-match") writes.push({ node, resolution }); + const resolution = hasCommonJsModuleSource( + receiver, + state, + false, + "module", + ); + if ( + resolution === "possible" || + (resolution === "incomplete" && + !hasClosedLocalReceiverSources(receiver, node, state)) + ) + writes.push(node); }; traverseJavaScriptValueAst(state.program, state.erasedSyntaxNodes, { enter: (node) => { diff --git a/tests/boundary/cli/javascriptApplicationCoverage.test.ts b/tests/boundary/cli/javascriptApplicationCoverage.test.ts index a441e9013a..3bb21d6101 100644 --- a/tests/boundary/cli/javascriptApplicationCoverage.test.ts +++ b/tests/boundary/cli/javascriptApplicationCoverage.test.ts @@ -39,6 +39,56 @@ cliTest( ); for (const surface of ["CLI", "stdio MCP"] as const) { + cliTest( + `counts proven Electron facts beside exhausted receiver selections through ${surface}`, + async ({ cli }) => { + const root = await createTestTempDirectory("rea-js-alias-coverage-"); + await writeFixtureFiles(root, { + "main.cjs": ` + (() => { + const table = { + 1: module => { module.exports = require("electron"); }, + 2: (module, exports, load) => { + const electron = load(1); + new electron.BrowserWindow({ webPreferences: { sandbox: true } }); + electron.ipcMain.handle("ready", () => 1); + } + }; + const cache = {}; + function load(id) { + const cached = cache[id]; + if (cached) return cached.exports; + const module = cache[id] = { exports: {} }; + table[id](module, module.exports, load); + return module.exports; + } + let receiver = {}; + while (flag) receiver = receiver[key]; + receiver[key] = 0; + load(2); + })(); + `, + }); + const application = await analyzeJavaScriptDirectory(surface, cli, root); + + expect(application.summary).toMatchObject({ + electron_semantics: "partial", + browser_windows: 1, + explicit_web_preferences: 1, + ipc: { operations: 1, main_handlers: 1 }, + }); + expect(application.graph.coverage).toMatchObject({ + status: "partial", + limits: expect.arrayContaining([ + expect.objectContaining({ + name: "javascript_semantic_alias_selections", + value: 512, + }), + ]), + }); + }, + ); + cliTest( `retains inherited loader uncertainty through ${surface}`, async ({ cli }) => {