From 7bedbcb6f6a9c6f556ed581047d48898cecfcc2c Mon Sep 17 00:00:00 2001 From: gongfpp <1360187968@qq.com> Date: Tue, 1 Dec 2026 00:30:59 +0800 Subject: [PATCH] fix(javascript): scope the missing-listener rule to proven Node emitters (#8663) * fix(javascript): scope the missing-listener rule to proven Node emitters A listener method called without a listener argument passes `undefined` to Node's `checkListener`, which throws before anything is registered or removed, so no event operation exists. That rule currently applies to every receiver, including objects that only look like an emitter. Restrict it to a receiver whose stable initializer is `new EventEmitter()` resolved through a proven `events` load, or a call Node's own `child_process` factories answer with a `ChildProcess`. The proof is withdrawn when `Function.prototype.call` was replaced, when the class reference or its prototype object escaped to a call, when any member of the shared `events` module was written, or when the selected method, the receiver's own prototype or an earlier escape of the instance may have replaced it. An effect that runs after the call cannot change whether it threw. Any other receiver keeps its operation as an unresolved candidate, as it did before the missing argument was considered. Those include EventEmitter-style APIs that define a one-argument form, such as Socket.IO's `socket.off("x")`, which removes every listener for the event. * fix(javascript): verify native emitter constructor and prototype ownership * fix(javascript): retain escaped prototype constructor aliases * fix(javascript): track acquired builtin module mutations * fix(javascript): charge module acquisition to phase allowance * fix(javascript): recognize computed builtin getter keys --------- Co-authored-by: gongfpp <22683417+gongfpp@users.noreply.github.com> Co-authored-by: Vincent Koc --- .../javascript-application-workflows.md | 5 + ...Analysis.missing_listener_receiver.test.ts | 279 ++++++++++++++++++ .../javascriptSemanticAsyncEffects.ts | 154 +++++++++- .../javascript/javascriptSemanticEffectLog.ts | 40 +++ .../javascriptSemanticMemberMutations.ts | 21 ++ .../javascriptSemanticRequireOrigin.ts | 186 +++++++++--- .../javascriptSemanticWorkAllowance.test.ts | 62 +++- .../javascriptThisEmitters.test.ts | 65 ++++ 8 files changed, 772 insertions(+), 40 deletions(-) create mode 100644 src/domain/javascript/javascriptSemanticAnalysis.missing_listener_receiver.test.ts diff --git a/docs/guides/javascript/javascript-application-workflows.md b/docs/guides/javascript/javascript-application-workflows.md index 4335e1aeb10..9c4ddd603f5 100644 --- a/docs/guides/javascript/javascript-application-workflows.md +++ b/docs/guides/javascript/javascript-application-workflows.md @@ -254,6 +254,11 @@ registrations/removals and dispatch, Node timers and cancellation handles, async `node:child_process` creation and ownership, configuration sources and direct defaults, request construction and response consumers, parse/coercion/ validation boundaries, and built-in resource acquisition/release. +Calls without a listener are omitted only for a proven native Node.js +EventEmitter receiver with an unchanged listener contract. Replaced methods, +escaped constructors and changes through shared module exports retain a +candidate operation instead. An unawaited dynamic import is a Promise, not a +module namespace. For `fs/promises.open`, a binding receiving the Promise is distinct from one receiving the awaited FileHandle. Awaiting the Promise later does not replace the original binding, but `h = await h` can replace it with the FileHandle. diff --git a/src/domain/javascript/javascriptSemanticAnalysis.missing_listener_receiver.test.ts b/src/domain/javascript/javascriptSemanticAnalysis.missing_listener_receiver.test.ts new file mode 100644 index 00000000000..06d52931507 --- /dev/null +++ b/src/domain/javascript/javascriptSemanticAnalysis.missing_listener_receiver.test.ts @@ -0,0 +1,279 @@ +import { describe, expect, it } from "vitest"; + +import { + analyzeJavaScriptSemantics, + analyzeParsedJavaScriptSemantics, +} from "./javascriptSemanticAnalysis.js"; +import { parseJavaScriptSource } from "./javascriptSourceParser.js"; + +const operations = (source: string) => + analyzeJavaScriptSemantics(source).eventOperations.map( + ({ kind, method, eventName }) => ({ kind, method, eventName }), + ); + +const esm = 'import { EventEmitter } from "node:events";\n'; + +it.each([ + ["./custom", 1], + ["node:events", 0], +])( + "requires the native module identity in CommonJS: %s", + (specifier, count) => { + const file = parseJavaScriptSource( + ` + const {EventEmitter} = require("${specifier}"); + const emitter = new EventEmitter(); + emitter.on("ready"); + `, + "fixture.cjs", + ); + if (file === null) throw new Error("CommonJS fixture did not parse"); + expect(analyzeParsedJavaScriptSemantics(file).eventOperations).toHaveLength( + count, + ); + }, +); + +it.each([ + ["./custom", 1], + ["node:events", 0], +])( + "checks the module of inline CommonJS constructors: %s", + (specifier, count) => { + const file = parseJavaScriptSource( + ` + const emitter = new (require("${specifier}").EventEmitter)(); + emitter.on("ready"); + `, + "fixture.cjs", + ); + if (file === null) throw new Error("CommonJS fixture did not parse"); + expect(analyzeParsedJavaScriptSemantics(file).eventOperations).toHaveLength( + count, + ); + }, +); + +it("retains an operation after a namespace constructor escapes", () => { + expect( + operations(` + import * as events from "node:events"; + configure(events.EventEmitter); + const emitter = new events.EventEmitter(); + emitter.on("ready"); + `), + ).toHaveLength(1); +}); + +it("retains an operation after the ChildProcess prototype changes", () => { + expect( + operations(` + import {spawn, ChildProcess} from "node:child_process"; + ChildProcess.prototype.on = function(event, listener = () => {}) {}; + const child = spawn("worker"); + child.on("exit"); + `), + ).toHaveLength(1); +}); + +it.each([ + `${esm}configure(EventEmitter.prototype.constructor); + const emitter = new EventEmitter(); emitter.on("ready");`, + `${esm}configure(EventEmitter.init); + const emitter = new EventEmitter(); emitter.on("ready");`, + `${esm}configure(EventEmitter.init.prototype.constructor); + const emitter = new EventEmitter(); emitter.on("ready");`, + `import {spawn, ChildProcess} from "node:child_process"; + configure(ChildProcess.prototype.constructor); + const child = spawn("worker"); child.on("exit");`, +])("retains operations after a prototype constructor escapes: %s", (source) => { + expect(operations(source)).toHaveLength(1); +}); + +it("retains a local emitter operation after outer dynamic code", () => { + expect( + operations(`${esm} + eval('EventEmitter.prototype.on = function(event, listener = () => {}) {}'); + function run() { const emitter = new EventEmitter(); emitter.on("ready"); } + run(); + `), + ).toHaveLength(1); +}); + +it.each([ + 'process.getBuiltinModule("events").EventEmitter.prototype.on = replacement;', + 'process[`getBuiltinModule`]("events").EventEmitter.prototype.on = replacement;', + 'const {[`getBuiltinModule`]: get} = process; get("events").EventEmitter.prototype.on = replacement;', + '(await import("node:events")).EventEmitter.prototype.on = replacement;', + 'const pending = import("node:events"); const ns = await pending; ns.EventEmitter.init = replacement;', + 'const {getBuiltinModule} = process; getBuiltinModule("events").EventEmitter.prototype.on = replacement;', + 'process.getBuiltinModule.call(null, "events").EventEmitter.prototype.on = replacement;', + 'const proc = process; const get = proc.getBuiltinModule; get("events").EventEmitter.prototype.on = replacement;', + 'import {getBuiltinModule as get} from "node:process"; get("events").EventEmitter.prototype.on = replacement;', + 'const {pending} = {pending: import("node:events")}; const ns = await pending; ns.EventEmitter.prototype.on = replacement;', +])( + "retains operations after a shared-module acquisition writes the method: %s", + (write) => { + expect( + operations(`${esm} + import replacement from "./replacement.js"; + ${write} + const emitter = new EventEmitter(); emitter.on("ready"); + `), + ).toHaveLength(1); + }, +); + +it.each([ + 'const pending = import("node:events"); pending.EventEmitter = replacement;', + 'const box = await {pending: import("node:events")}; box.pending.EventEmitter = replacement;', + 'const process = {getBuiltinModule() {return {};}}; process.getBuiltinModule("events").EventEmitter = replacement;', + 'process.getBuiltinModule("fs").EventEmitter = replacement;', + 'const process = {[`getBuiltinModule`]() {return {};}}; process[`getBuiltinModule`]("events").EventEmitter = replacement;', +])( + "does not confuse unrelated values with an acquired events namespace: %s", + (write) => { + expect( + operations(`${esm} + import replacement from "./replacement.js"; + ${write} + const emitter = new EventEmitter(); emitter.on("ready"); + `), + ).toEqual([]); + }, +); + +/** + * Node's `EventEmitter` validates argument 1 with `checkListener` before it + * registers or removes anything, so a call that passes no listener throws and + * produces no event operation. Only that class is bound by the rule: an + * EventEmitter-style API may define a one-argument form, such as Socket.IO's + * `socket.off("x")`, which removes every listener for the event. A receiver that + * is not proven to be Node's class therefore keeps its operation as an + * unresolved candidate, as it did before the missing argument was considered. + */ +describe("missing listener argument", () => { + it.each([ + ["a named import", 'import { EventEmitter } from "node:events";'], + ["a default import", 'import EventEmitter from "node:events";'], + ["the node: prefix", 'import { EventEmitter } from "events";'], + ])( + "drops the operation for a receiver built from %s", + (_label, importLine) => { + expect( + operations(`${importLine} +const emitter = new EventEmitter(); +emitter.on("ready");`), + ).toEqual([]); + }, + ); + + it("drops the operation for a namespace member construction", () => { + expect( + operations(`import * as events from "node:events"; +const emitter = new events.EventEmitter(); +emitter.off("ready");`), + ).toEqual([]); + }); + + it("drops the operation inside a later activation", () => { + expect( + operations(`${esm}const emitter = new EventEmitter(); +function start() { + emitter.once("ready"); +}`), + ).toEqual([]); + }); + + it("drops the operation for a child process Node creates", () => { + expect( + operations(`import { spawn } from "node:child_process"; +const child = spawn("worker"); +child.on("exit");`), + ).toEqual([]); + }); + + it.each([ + [ + "an unknown receiver", + 'function forward(target) {\n target.on("ready");\n}', + ], + [ + "an object that defines its own listener method", + 'const target = { on(event) {\n return event;\n} };\ntarget.on("ready");', + ], + [ + "a Socket.IO style removal", + 'function clear(socket) {\n socket.off("ready");\n}', + ], + [ + "a commonjs member require", + 'const { EventEmitter } = require("events");\nconst emitter = new EventEmitter();\nemitter.on("ready");', + ], + ])("keeps the operation for %s", (_label, source) => { + expect(operations(source)).toHaveLength(1); + }); + + it.each([ + [ + "the receiver method is replaced", + `${esm}const emitter = new EventEmitter(); +emitter.on = function listen() {}; +emitter.on("ready");`, + ], + [ + "the shared prototype method is replaced", + `${esm}EventEmitter.prototype.on = function listen() {}; +const emitter = new EventEmitter(); +emitter.on("ready");`, + ], + [ + "the constructor init hook is replaced", + `${esm}EventEmitter.init = replacement; +const emitter = new EventEmitter(); +emitter.on("ready");`, + ], + [ + "the class is handed to another call", + `${esm}configure(EventEmitter); +const emitter = new EventEmitter(); +emitter.on("ready");`, + ], + [ + "the prototype is handed to another call", + `${esm}configure(EventEmitter.prototype); +const emitter = new EventEmitter(); +emitter.on("ready");`, + ], + [ + "the receiver is handed to an earlier call", + `${esm}const emitter = new EventEmitter(); +configure(emitter); +emitter.on("ready");`, + ], + [ + "spread arguments may still supply a listener", + `${esm}const emitter = new EventEmitter(); +const arguments_ = ["ready", listen]; +emitter.on(...arguments_);`, + ], + ])("keeps the operation when %s", (_label, source) => { + expect(operations(source)).toHaveLength(1); + }); + + it("drops the operation when only the method value is handed out", () => { + expect( + operations(`${esm}configure(EventEmitter.prototype.on); +const emitter = new EventEmitter(); +emitter.on("ready");`), + ).toEqual([]); + }); + + it("drops the operation when the receiver escapes after the call", () => { + expect( + operations(`${esm}const emitter = new EventEmitter(); +emitter.on("ready"); +configure(emitter);`), + ).toEqual([]); + }); +}); diff --git a/src/domain/javascript/javascriptSemanticAsyncEffects.ts b/src/domain/javascript/javascriptSemanticAsyncEffects.ts index 837d3ea1fd0..5375111c458 100644 --- a/src/domain/javascript/javascriptSemanticAsyncEffects.ts +++ b/src/domain/javascript/javascriptSemanticAsyncEffects.ts @@ -17,6 +17,7 @@ import { import { resolveSemanticBindingState, semanticResolutionBlocked, + semanticStableInitializer, type JavaScriptSemanticAnalysisState, } from "./javascriptSemanticState.js"; import { semanticBindingAtRead } from "./javascriptSemanticMutationInitializers.js"; @@ -25,10 +26,18 @@ import { isIntrinsicGlobalReference, isUnmodifiedGlobalReference, } from "./javascriptSemanticGlobalReference.js"; -import { opaqueCodeMayChangeGlobalRead } from "./javascriptSemanticEffectLog.js"; +import { + ambientPathMayHaveChanged, + bindingMethodMayHaveChanged, + bindingObjectEscapedOutside, + opaqueCodeMayChangeGlobalRead, + requiredModuleSurfaceTouched, +} from "./javascriptSemanticEffectLog.js"; import { createGlobalReferenceReader } from "./javascriptSemanticAmbientWrites.js"; +import { semanticGlobalCodeSites } from "./javascriptSemanticEffectRecord.js"; import { range } from "./javascriptStaticAnalysisHelpers.js"; import { + builtinDataEffectCallablePath, builtinDataEffectIdentity, dataEffectArgumentBindingId, dataEffectLiteralString, @@ -199,6 +208,132 @@ export const rejectsSemanticEventListener = ( ); }; +/** Node builtin calls whose result is an `EventEmitter`. */ +const NODE_EMITTER_FACTORIES = ["spawn", "exec", "execFile", "fork"] as const; + +/** + * The construction whose class resolves to Node's `EventEmitter`, or `null` + * when the initializer is something else. A default import and the + * `EventEmitter` member both name that class; only a proven host loader + * establishes the builtin identity, because a bundled or shimmed `events` + * module is not bound by Node's `checkListener`. + */ +const nodeEventEmitterConstruction = ( + node: t.Node, + state: JavaScriptSemanticAnalysisState, +): t.Node | null => { + const value = unwrapJavaScriptExpression(node).node; + // Node's own factories return a `ChildProcess`, which inherits the listener + // methods and their `checkListener` contract. The analyzer already proves + // these calls, so the receiver does not have to be a constructor call. + if (t.isCallExpression(value)) { + const factory = builtinDataEffectCallablePath(value.callee, state, [ + "child_process", + "node:child_process", + ]); + return factory !== null && + factory.length === 1 && + NODE_EMITTER_FACTORIES.some((name) => name === factory[0]) + ? value + : null; + } + if (!t.isNewExpression(value)) return null; + const path = builtinDataEffectCallablePath(value.callee, state, [ + "events", + "node:events", + ]); + if (path === null) return null; + if (path.length === 0) return value; + if (path.length !== 1) return null; + const selected = path[0]; + return selected === "EventEmitter" || selected === "default" ? value : null; +}; + +/** + * Whether the class reference a construction uses was handed to another call, + * which may replace a member of it before this receiver exists. Building the + * receiver is not such an escape. + */ +const nodeEventEmitterClassEscaped = ( + construction: t.NewExpression, + state: JavaScriptSemanticAnalysisState, +): boolean => { + const { callee } = construction; + if (!t.isIdentifier(callee)) return false; + const binding = resolveSemanticBindingState(state, callee, callee.name); + return ( + binding !== undefined && bindingObjectEscapedOutside(binding, construction) + ); +}; + +/** + * Whether the receiver is a value this module constructs from Node's + * `EventEmitter` and still calls the native listener method. Only that class + * validates the listener argument with `checkListener`; other EventEmitter-style + * APIs define one-argument forms, such as Socket.IO's `socket.off("x")`, which + * removes every listener for the event. Any receiver whose selected method may + * have been replaced keeps its operation as an unresolved candidate. + */ +const provenNativeEventEmitterReceiver = ( + receiver: t.Expression | t.Super, + method: string, + call: t.Node, + state: JavaScriptSemanticAnalysisState, +): boolean => { + if (semanticGlobalCodeSites(state).length > 0) return false; + if (!t.isIdentifier(receiver)) return false; + const binding = resolveSemanticBindingState(state, receiver, receiver.name); + if (binding === undefined) return false; + const initializer = semanticStableInitializer(binding, state); + if (initializer === undefined || initializer.projection.length !== 0) + return false; + const construction = nodeEventEmitterConstruction(initializer.node, state); + if (construction === null) return false; + // Node allocates through `EventEmitter.init.call(this, opts)`. The inherited + // call slot is shared by every function, so replacing it changes the + // allocation even when no `events` binding was written or exposed. + if ( + ambientPathMayHaveChanged( + state, + ["global", "Function", "prototype", "call"], + "contents", + ) + ) + return false; + if ( + t.isNewExpression(construction) && + nodeEventEmitterClassEscaped(construction, state) + ) + return false; + // The events module is shared by every receiver built from it, so a write to + // any of its members, or an escape of its prototype object, replaces what the + // method call selects. + if ( + requiredModuleSurfaceTouched(state, "events", [ + "EventEmitter", + "default", + "init", + ]) + ) + return false; + if ( + t.isCallExpression(construction) && + requiredModuleSurfaceTouched(state, "child_process", ["ChildProcess"]) + ) + return false; + // Passing the instance to another call lets that call replace the method + // first. Writing the selected method or replacing the receiver's own prototype + // selects a different contract the same way. A call that runs after this one + // cannot change whether it threw. + return !bindingMethodMayHaveChanged(binding, method, call, state, { + fresh: true, + inherited: true, + definingPrototypeDepth: undefined, + isolatedNativeCloses: false, + targets: () => true, + }); +}; + const collectEvent = ( node: t.CallExpression | t.OptionalCallExpression, ownerCallableId: string | null, @@ -216,15 +351,26 @@ const collectEvent = ( if (method === undefined) return; const kind = eventKind(method); const eventArgument = node.arguments[0]; - const listenerArgument = EVENT_LISTENER_METHODS.includes(method) - ? node.arguments[1] - : undefined; + const listenerMethod = EVENT_LISTENER_METHODS.includes(method); + const listenerArgument = listenerMethod ? node.arguments[1] : undefined; + // A listener method called without a listener argument passes `undefined` to + // Node's `checkListener`, which throws before it registers or removes + // anything. Only a spread argument can still reach that position, and only a + // receiver proven to be Node's `EventEmitter` is held to that contract. + if ( + listenerMethod && + listenerArgument === undefined && + !node.arguments.some((argument) => t.isSpreadElement(argument)) && + provenNativeEventEmitterReceiver(member.object, method, node, state) + ) + return; // A leading spread shifts the runtime argument positions, so argument 1 is not // provably the listener: `e.on(...["x", fn], 1)` registers `fn` and ignores the // trailing `1`. if ( EVENT_LISTENER_METHODS.includes(method) && !t.isSpreadElement(eventArgument) && + listenerArgument !== undefined && rejectsSemanticEventListener(listenerArgument) ) return; diff --git a/src/domain/javascript/javascriptSemanticEffectLog.ts b/src/domain/javascript/javascriptSemanticEffectLog.ts index 709c0edabce..6c630c28da2 100644 --- a/src/domain/javascript/javascriptSemanticEffectLog.ts +++ b/src/domain/javascript/javascriptSemanticEffectLog.ts @@ -780,6 +780,46 @@ export const bindingMethodMayHaveChanged = ( ); }; +/** + * Whether a member of the required module `specifier` was written anywhere in + * the source, or its exported object or selected mutable entry was handed to a + * call that may write one. + * The module is shared by every value built from it, so these effects are not + * ordered against a read. + */ +export const requiredModuleSurfaceTouched = ( + state: JavaScriptSemanticAnalysisState, + specifier: string, + mutableEntries: readonly string[], +): boolean => + (state.requiredModuleEffects.get(specifier) ?? []).some( + ({ path, kind }) => + kind === "write" || + // A null or unresolved key may select the exported object; only a + // definite other member keeps the surface untouched. + path.every( + (key, index) => + typeof key !== "string" || + key === "prototype" || + // The prototype's constructor is another reference to the class. + (key === "constructor" && path[index - 1] === "prototype") || + mutableEntries.includes(key), + ), + ); + +/** + * Whether `binding`'s object itself, rather than one of its members, was handed + * to code at a site other than `except`. A member handed out cannot gain or lose + * siblings, but the object handed out can replace its own members. + */ +export const bindingObjectEscapedOutside = ( + binding: JavaScriptSemanticBindingState, + except: t.Node | undefined, +): boolean => + binding.escapedPaths.some( + (effect) => effect.path.length === 0 && effect.node !== except, + ); + /** Whether a member write to `binding`'s object is recorded. */ export const bindingHasMemberWrites = ( binding: JavaScriptSemanticBindingState, diff --git a/src/domain/javascript/javascriptSemanticMemberMutations.ts b/src/domain/javascript/javascriptSemanticMemberMutations.ts index 5c8110fb7ec..6916b42d13c 100644 --- a/src/domain/javascript/javascriptSemanticMemberMutations.ts +++ b/src/domain/javascript/javascriptSemanticMemberMutations.ts @@ -22,6 +22,7 @@ import { semanticRequireExportsIdentity, semanticRequireOrigin, semanticRequireOriginCandidate, + semanticAcquiredModuleSources, semanticRequireLoaderAt, hasSemanticCreateRequireFactoryOrigin, } from "./javascriptSemanticRequireOrigin.js"; @@ -946,6 +947,26 @@ export function* collectSemanticMemberMutationsSteps( definiteReceiver = true, selection?: MutationSelectionContext, ): void => { + // This query owns its alias traversal; run it once per source rather than + // repeating the same walk for every intermediate binding below. + for (const source of semanticAcquiredModuleSources( + node, + state, + originAt, + () => work.charge(), + )) { + const shared = semanticMutableBuiltinOrigin( + { + specifier: source.specifier, + resolutionMode: source.resolutionMode, + importedPath: [], + }, + [...source.path, ...path], + effect === "escape", + ); + if (shared !== undefined) + recordRequiredEffect(shared.specifier, shared.path, effect, mutation); + } type JoinedProjection = { readonly path: PropertyPath; readonly definiteReceiver: boolean; diff --git a/src/domain/javascript/javascriptSemanticRequireOrigin.ts b/src/domain/javascript/javascriptSemanticRequireOrigin.ts index d5ac977ef26..ef583422a4e 100644 --- a/src/domain/javascript/javascriptSemanticRequireOrigin.ts +++ b/src/domain/javascript/javascriptSemanticRequireOrigin.ts @@ -10,6 +10,7 @@ import { import * as t from "@babel/types"; import { createGlobalPathReader, + createAmbientPathResolver, type GlobalReferenceRead, } from "./javascriptSemanticAmbientWrites.js"; import { @@ -89,6 +90,7 @@ import { isUnmodifiedImportMetaUrl, } from "./javascriptSemanticGlobalReference.js"; import { semanticConsumerMemo } from "./javascriptSemanticConsumer.js"; +import { evaluateSemanticExpressionProvenance } from "./javascriptSemanticValues.js"; const possibleCommonJsDelegateWriteStates = new WeakSet(); @@ -1322,13 +1324,7 @@ const hasCommonJsModuleSource = ( ): ModuleSourceMatch => { if (!programMayNameCommonJsLoader(state.program)) return "no-match"; if (!state.memberMutationFactsComplete) - return walkCommonJsModuleSource( - node, - state, - includeUnknown, - target, - readAt, - ); + return walkModuleSources(node, state, includeUnknown, target, readAt); const queries = semanticModuleSourceQueries(state, node); let byOptions = queries.get(readAt); if (byOptions === undefined) { @@ -1343,13 +1339,7 @@ const hasCommonJsModuleSource = ( return cached.match; } const before = new Set(state.observations.valueResourceLimits); - const match = walkCommonJsModuleSource( - node, - state, - includeUnknown, - target, - readAt, - ); + const match = walkModuleSources(node, state, includeUnknown, target, readAt); // The walk can clear this state's queries; retain the answer only if the // same generation still owns them. if (semanticModuleSourceQueries(state, node) === queries) @@ -1362,17 +1352,25 @@ const hasCommonJsModuleSource = ( return match; }; -const walkCommonJsModuleSource = ( +const walkModuleSources = ( node: t.Node, state: JavaScriptSemanticAnalysisState, includeUnknown: boolean, - target: "module" | "delegate", + target: "module" | "delegate" | "exports", readAt?: t.Node, + terminal?: ( + node: t.Node, + path: SemanticAliasSelectionPath, + awaited: boolean, + ) => boolean, + onSchedule?: () => void, ): ModuleSourceMatch => { + let incomplete = false; type Work = ModuleObjectSource & { /** Await occurs after this many requested outer property selections. */ readonly awaitDepths: readonly number[]; }; + onSchedule?.(); const pending: Work[] = [{ node, path: [], readAt, awaitDepths: [] }]; // Keep depths separate and join finite key alternatives at each source read. const selections = new SemanticAliasSelections(() => { @@ -1453,24 +1451,23 @@ const walkCommonJsModuleSource = ( depths: readonly number[], ...sources: ModuleObjectSource[] ) => { - pending.push( - ...inheritLoaderSourceContext(next, sources) - // These leaves cannot contribute a module source and the walker - // would discard them without expanding their selected paths. - .filter((source) => { - const value = unwrapJavaScriptExpression(source.node).node; - return ( - !t.isNumericLiteral(value) && - !t.isBooleanLiteral(value) && - !t.isNullLiteral(value) - ); - }) - .map((source) => ({ ...source, awaitDepths: depths })), - ); + for (const source of inheritLoaderSourceContext(next, sources)) { + // These leaves cannot contribute a module source. + const value = unwrapJavaScriptExpression(source.node).node; + if ( + t.isNumericLiteral(value) || + t.isBooleanLiteral(value) || + t.isNullLiteral(value) + ) + continue; + onSchedule?.(); + pending.push({ ...source, awaitDepths: depths }); + } }; const enqueue = (...sources: ModuleObjectSource[]) => { enqueueAt(awaitDepths, ...sources); }; + if (terminal?.(value, path, awaitDepths.includes(path.length))) continue; if (t.isAwaitExpression(value)) { enqueueAt( [...new Set([...awaitDepths, path.length])].sort( @@ -1535,7 +1532,10 @@ const walkCommonJsModuleSource = ( value.callee, t.isNewExpression(value) ? undefined : value, ); - if (returnedResult.unresolvedInvocation) return "possible"; + if (returnedResult.unresolvedInvocation) { + if (target !== "exports") return "possible"; + incomplete = true; + } enqueue( ...returnedResult.references.map((source) => ({ node: source.node, @@ -1551,6 +1551,7 @@ const walkCommonJsModuleSource = ( if (!t.isIdentifier(value)) continue; const binding = resolveSemanticBindingState(state, value, value.name); const processMainModulePath = + target !== "exports" && semanticGlobalProcessOrigin(value, state) !== undefined && path.length === (target === "module" ? 1 : 2) && semanticAliasSelectionChoices(path[0]!).some( @@ -1564,6 +1565,7 @@ const walkCommonJsModuleSource = ( )); if (processMainModulePath) return "possible"; const mainModulePath = + target !== "exports" && value.name === "require" && state.program.sourceType === "script" && path.length === (target === "module" ? 1 : 2) && @@ -1593,7 +1595,11 @@ const walkCommonJsModuleSource = ( capture.ownEnumerable && !semanticCommonJsRequireOwnEnumerableAt(capture.at, state), ); - if (value.name === "module" && binding === undefined) { + if ( + target !== "exports" && + value.name === "module" && + binding === undefined + ) { if ( copyAdmitsModuleDelegate && (target === "module" @@ -1628,6 +1634,7 @@ const walkCommonJsModuleSource = ( ) return "possible"; if ( + target !== "exports" && value.name === "module" && copyAdmitsModuleDelegate && (target === "module" @@ -1666,7 +1673,8 @@ const walkCommonJsModuleSource = ( ) : facts?.sources; if (sources === undefined) { - if (target !== "delegate") return "possible"; + if (target === "exports") incomplete = true; + else if (target !== "delegate") return "possible"; // An opaque member effect can obscure a selected native delegate, but // cannot make every escaped callable a possible Node loader. Keep its // receiver's retained sources as the eligibility boundary for that gap. @@ -1678,7 +1686,10 @@ const walkCommonJsModuleSource = ( next.readAt ?? value, next.capturedSelections, ); - if (sources === undefined) return "possible"; + if (sources === undefined) { + if (target !== "exports") return "possible"; + continue; + } eligibility = true; } enqueue( @@ -1687,7 +1698,111 @@ const walkCommonJsModuleSource = ( ), ); } - return "no-match"; + return incomplete ? "incomplete" : "no-match"; +}; + +/** A module export source retained for writes, never proof of a read value. */ +export interface SemanticAcquiredModuleSource { + readonly specifier: string; + readonly path: readonly (string | number | null)[]; + readonly resolutionMode: "import" | "require"; +} + +const moduleAcquisitionSyntax = new WeakMap(); + +/** Skip export-source walks in programs that contain no additional acquisition syntax. */ +const hasModuleAcquisitionSyntax = ( + state: JavaScriptSemanticAnalysisState, +): boolean => { + const cached = moduleAcquisitionSyntax.get(state.program); + if (cached !== undefined) return cached; + let found = false; + traverseJavaScriptValueAst(state.program, state.erasedSyntaxNodes, { + enter: (node) => { + if ( + t.isImportExpression(node) || + semanticStaticPropertyKey(node, false) === "getBuiltinModule" + ) + found = true; + }, + }); + moduleAcquisitionSyntax.set(state.program, found); + return found; +}; + +/** + * Follow the shared captured-source and await traversal to module namespaces. + * These are possible mutation targets; they do not promote loader uncertainty + * into an exact callable or runtime module value. + */ +export const semanticAcquiredModuleSources = ( + node: t.Node, + state: JavaScriptSemanticAnalysisState, + readAt?: t.Node, + onSchedule?: () => void, +): readonly SemanticAcquiredModuleSource[] => { + if (!hasModuleAcquisitionSyntax(state)) return []; + const sources = new Map(); + const ambient = createAmbientPathResolver(state, true); + const interop = semanticModuleInteropWithAmbientWrites(state); + walkModuleSources( + node, + state, + false, + "exports", + readAt, + (value, path, awaited) => { + let specifier: string | undefined; + let resolutionMode: "import" | "require" = "require"; + if (t.isImportExpression(value)) { + // import() returns a Promise. Awaiting its containing object is not + // equivalent to awaiting this selected value. + if (!awaited) return true; + specifier = stringValue(value.source); + resolutionMode = "import"; + } else if ( + t.isCallExpression(value) || + t.isOptionalCallExpression(value) + ) { + const invocation = interop.intrinsicInvocation(value, (callee) => { + const paths = ambient(callee, value).paths; + const globalGetter = paths.some( + (selected) => + selected.length === 3 && + selected[0] === "global" && + selected[1] === "process" && + selected[2] === "getBuiltinModule", + ); + const importedGetter = + !globalGetter && + evaluateSemanticExpressionProvenance(callee, state).origins.some( + (origin) => + origin.specifier.replace(/^node:/u, "") === "process" && + origin.importedPath.length === 1 && + origin.importedPath[0] === "getBuiltinModule", + ); + return globalGetter || importedGetter + ? ["builtin-module-loader"] + : interop.intrinsicPath(callee); + }); + if (invocation?.path[0] !== "builtin-module-loader") return false; + specifier = stringValue(invocation.arguments?.[0]); + } else return false; + if (specifier !== undefined) { + const source = { + specifier, + resolutionMode, + path: path.map((key) => + typeof key === "string" || typeof key === "number" ? key : null, + ), + }; + sources.set(JSON.stringify(source), source); + } + return true; + }, + onSchedule, + ); + return [...sources.values()]; }; /** Select an unchecked member-loader receiver before its identity is examined. */ @@ -2177,6 +2292,7 @@ export const semanticMutableBuiltinOrigin = ( path[0] === "FileReadStream" || path[0] === "FileWriteStream")) || (specifier === "buffer" && path[0] === "Buffer") || + (specifier === "child_process" && path[0] === "ChildProcess") || // `Stream` is the ancestor both fs stream classes extend, so a member installed // through a named `Stream` import reaches them. Measured on Node 24.22.1, the // named-import form constructs a handle from `{start:-1}` exactly like the diff --git a/src/domain/javascript/javascriptSemanticWorkAllowance.test.ts b/src/domain/javascript/javascriptSemanticWorkAllowance.test.ts index 4b7e2967739..4d3645e42e5 100644 --- a/src/domain/javascript/javascriptSemanticWorkAllowance.test.ts +++ b/src/domain/javascript/javascriptSemanticWorkAllowance.test.ts @@ -4,11 +4,18 @@ import { DEFAULT_JAVASCRIPT_MEMBER_MUTATION_ALIAS_STATES, MAXIMUM_JAVASCRIPT_MEMBER_MUTATION_ALIAS_STATES, } from "../analysisResourceLimits.js"; -import { analyzeJavaScriptSemantics } from "./javascriptSemanticAnalysis.js"; +import { + analyzeJavaScriptSemantics, + indexJavaScriptBindingsWithReceiversSteps, +} from "./javascriptSemanticAnalysis.js"; +import { semanticAcquiredModuleSources } from "./javascriptSemanticRequireOrigin.js"; +import { completeSemanticSteps } from "./javascriptSemanticTraversal.js"; +import { parseJavaScriptSource } from "./javascriptSourceParser.js"; import { DEFAULT_JAVASCRIPT_MEMBER_MUTATION_ALLOWANCE, JAVASCRIPT_MEMBER_MUTATION_WORK_LIMIT, javaScriptMemberMutationRefusal, + JavaScriptSemanticWorkMeter, } from "./javascriptSemanticWorkAllowance.js"; /** @@ -37,6 +44,59 @@ const refusalOf = (run: () => unknown): AnalysisResourceConstraintError => { throw new Error("Expected a work allowance refusal"); }; +it("charges module-acquisition aliases to the selected phase allowance", () => { + const file = parseJavaScriptSource( + ` + const pending = import("node:events"); + const ns = await pending; + ns.EventEmitter; + `, + "fixture.mjs", + ); + if (file === null) throw new Error("Module fixture did not parse"); + const selected = file.program.body.at(-1); + if (selected?.type !== "ExpressionStatement") + throw new Error("Missing module selection"); + const { bindings } = completeSemanticSteps( + indexJavaScriptBindingsWithReceiversSteps(file.program), + ); + const small = new JavaScriptSemanticWorkMeter({ + aliasStates: 1, + source: "runtime", + }); + const refusal = refusalOf(() => + semanticAcquiredModuleSources( + selected.expression, + bindings, + undefined, + () => small.charge(), + ), + ); + expect(refusal.limit).toMatchObject({ + setting: "javascript.member_mutation_alias_states", + effective_value: 1, + source: "runtime", + }); + const raised = new JavaScriptSemanticWorkMeter({ + aliasStates: 50, + source: "runtime", + }); + expect( + semanticAcquiredModuleSources( + selected.expression, + bindings, + undefined, + () => raised.charge(), + ), + ).toEqual([ + { + specifier: "node:events", + path: ["EventEmitter"], + resolutionMode: "import", + }, + ]); +}); + it.each([8, 32])( "answers %i self-selections conservatively instead of refusing the source", (count) => { diff --git a/tests/acceptance/applications/javascriptThisEmitters.test.ts b/tests/acceptance/applications/javascriptThisEmitters.test.ts index 5a280c4a7ed..fdde0a61f64 100644 --- a/tests/acceptance/applications/javascriptThisEmitters.test.ts +++ b/tests/acceptance/applications/javascriptThisEmitters.test.ts @@ -7,6 +7,7 @@ import { javascriptApplicationAnalysisResultSchema } from "../../../src/domain/j import { connectLocalToolsMcp } from "../../fixtures/localToolsMcp.js"; import { createTestTempDirectory } from "../../fixtures/temporaryDirectory.js"; import { cliTest } from "../../support/cli/cliFixture.js"; +import { analyzeJavaScriptDirectory } from "../../support/cli/javascriptApplication.js"; const fixtureSource = ` class Base { @@ -39,6 +40,70 @@ const fixtureSource = ` } `; +for (const [label, target] of [ + ["intact native emitter", null], + [ + "builtin module getter", + 'process.getBuiltinModule("events").EventEmitter.prototype.on', + ], + [ + "computed builtin module getter", + 'process[`getBuiltinModule`]("events").EventEmitter.prototype.on', + ], + [ + "awaited module import", + '(await import("node:events")).EventEmitter.prototype.on', + ], +] as const) { + cliTest( + `preserves missing-listener certainty for ${label} through CLI and stdio MCP`, + async ({ cli }) => { + const root = await createTestTempDirectory("rea-native-emitter-"); + await writeFile( + join(root, "main.mjs"), + ` + import {EventEmitter} from "node:events"; + ${ + target === null + ? "" + : ` + const nativeOn = EventEmitter.prototype.on; + function replacement(name, listener = () => {}) { + return nativeOn.call(this, name, listener); + } + ${target} = replacement; + ` + } + const emitter = new EventEmitter(); + emitter.on("ready"); + `, + ); + for (const surface of ["CLI", "stdio MCP"] as const) { + const { semantic_graph: graph } = await analyzeJavaScriptDirectory( + surface, + cli, + root, + ); + const events = graph.nodes.filter( + (node) => + node.kind === "event" && node.properties.event_name === "ready", + ); + expect(events).toHaveLength(target === null ? 0 : 1); + if (target !== null) { + expect( + graph.relations.some( + (relation) => + relation.relation === "registers-listener" && + (relation.source_node_id === events[0]?.node_id || + relation.target_node_id === events[0]?.node_id), + ), + ).toBe(true); + } + } + }, + ); +} + type SemanticGraph = ReturnType< typeof javascriptApplicationAnalysisResultSchema.parse >["semantic_graph"];