Repository navigation
fix(javascript): follow Electron through Webpack bootstrap externals - #2948
UnknownHacker1 wants to merge 4 commits into
Conversation
|
There was a problem hiding this comment.
💡 Codex Review
Here are some automated review suggestions for this pull request.
Reviewed commit: e1c408a391
ℹ️ About Codex in GitHub
Your team has set up Codex to review pull requests in this repo. Reviews are triggered when you
- Open a pull request for review
- Mark a draft as ready
- Comment "@codex review".
If Codex has suggestions, it will comment; otherwise it will react with 👍.
Codex can also answer questions or update the PR. Try commenting "@codex address that feedback".
| loaderBindingIds.add(bindingId); | ||
| } | ||
| const key = modulePropertyName(property); | ||
| const specifier = externalSpecifier(factory, state); |
There was a problem hiding this comment.
Invalidate rewritten bootstrap module slots
When a recognized table is later changed through an alias—e.g. const alias = modules; alias[45840] = fake or delete alias[45840]—this still records the factory from the initializer, although it is no longer the slot dispatched by the loader. JavaScriptSymbolicBindings.#invalidateBootstrapTable already makes these writes unknown, but direct Electron identity bypasses that invalidation, so a consumer can now produce bogus BrowserWindow/IPC findings; consult visible slot mutations before adding the specifier.
AGENTS.md reference: AGENTS.md:L19-L19
Useful? React with 👍 / 👎.
| call: t.CallExpression, | ||
| state: JavaScriptSemanticAnalysisState, | ||
| ): BootstrapExternals | null => { | ||
| const bootstrap = javascriptBootstrapAt(call, state); |
There was a problem hiding this comment.
Require the loader to return dispatched exports
javascriptBootstrapAt proves only that a loader body contains a matching table[id](module, module.exports, loader) dispatch; it does not prove that the loader returns those exports. For an otherwise matching IIFE whose loader invokes the external factory and then return fake, this treats the loader as a require origin anyway, so load(45840).BrowserWindow is attributed to Electron even though its runtime receiver is fake. Require a synchronous return/cache relation to the dispatched module exports before exposing this origin.
AGENTS.md reference: AGENTS.md:L19-L19
Useful? React with 👍 / 👎.
| factory: t.FunctionExpression | t.ArrowFunctionExpression | t.ObjectMethod, | ||
| state: JavaScriptSemanticAnalysisState, | ||
| ): string | undefined => { | ||
| const moduleParameter = factory.params[0]; | ||
| if (!t.isIdentifier(moduleParameter)) return undefined; |
There was a problem hiding this comment.
Reject non-eager external module factories
externalSpecifier assumes that any factory node with this body executes it when the dispatch calls the table slot. A valid object-literal entry such as 45840: function* (module) { module.exports = require("electron") } only creates a generator, leaving module.exports unchanged, while a setter ObjectMethod is not callable at all; both shapes can reach this check and assign Electron identity to consumers. Restrict accepted entries to ordinary, non-generator callable factories before inspecting the assignment.
AGENTS.md reference: AGENTS.md:L19-L19
Useful? React with 👍 / 👎.
Codex Review SummaryThis comment shows the latest Codex review activity on this pull request.
ℹ️ About Codex in GitHubYour team has set up Codex to review pull requests in this repo. Reviews are triggered when you
Codex reacts with 👀 while any review is running, comments if it has suggestions, and reacts with 👍 once all reviews finish with no findings. |
e1c408a to
039e70e
Compare
There was a problem hiding this comment.
💡 Codex Review
Here are some automated review suggestions for this pull request.
Reviewed commit: 039e70eafe
ℹ️ About Codex in GitHub
Your team has set up Codex to review pull requests in this repo. Reviews are triggered when you
- Open a pull request for review
- Mark a draft as ready
- Comment "@codex review".
If Codex has suggestions, it will comment; otherwise it will react with 👍.
Codex can also answer questions or update the PR. Try commenting "@codex address that feedback".
| const initializer = semanticStableInitializer(binding, state); | ||
| if (initializer === undefined) return undefined; | ||
| const origin = semanticRequireOrigin(initializer.node, state)?.origin; | ||
| const origin = electronRequireOrigin(initializer.node, state)?.origin; |
There was a problem hiding this comment.
Propagate bundled origins through stable aliases
When a proven loader result crosses even one stable alias, for example const loaded = n(45840); const electron = loaded; new electron.BrowserWindow({}), this immediate-initializer lookup sees only the identifier loaded and returns no origin. electronExport then falls back to evaluateSemanticProvenance, whose provenanceForExpression still recognizes only semanticRequireOrigin, so BrowserWindow/IPC findings disappear; the same ownership gap affects the existing module-interop paths around bundled loads. Feed the bundled origin into the shared provenance/interop owner rather than recognizing it only at this leaf.
AGENTS.md reference: AGENTS.md:L19-L19
Useful? React with 👍 / 👎.
| ) | ||
| loaderBindingIds.add(bindingId); | ||
| } | ||
| const key = modulePropertyName(property); |
There was a problem hiding this comment.
Invalidate externals shadowed by unknown table keys
When a later table property has a nonliteral computed key, such as {45840: external, [externalId]: local} with externalId === 45840, modulePropertyName assigns that property a synthetic marker, so this map leaves the earlier 45840 external intact. At runtime the computed property overwrites that slot before the loader runs, but n(45840) is still attributed to Electron and produces bogus findings. A later unresolved key must leave every earlier slot it could shadow unknown (or be resolved) rather than being treated as a disjoint key.
AGENTS.md reference: AGENTS.md:L21-L21
Useful? React with 👍 / 👎.
039e70e to
d22374e
Compare
d22374e to
305818b
Compare
|
thanks, these were all real. pushed a fix in 305818b (squashed, rebased on the current main):
each one has a test in two things i left on purpose:
also noticed while testing: the existing wrapper-substitution path on main still reports ipc for most of these tampered shapes (generator external, replaced loader, etc). not from this PR so i didnt touch it, the new tests just make sure nothing direct comes out of the new path. i can open a separate issue for that if its useful |
There was a problem hiding this comment.
💡 Codex Review
Here are some automated review suggestions for this pull request.
Reviewed commit: 305818b2d1
ℹ️ About Codex in GitHub
Your team has set up Codex to review pull requests in this repo. Reviews are triggered when you
- Open a pull request for review
- Mark a draft as ready
- Comment "@codex review".
If Codex has suggestions, it will comment; otherwise it will react with 👍.
Codex can also answer questions or update the PR. Try commenting "@codex address that feedback".
| ) | ||
| return null; | ||
| const cacheId = keyedSlot(value.left, parameterId, state); | ||
| return cacheId === undefined ? null : { cacheId, site: value.left }; |
There was a problem hiding this comment.
Reject pre-populated module caches
When a bootstrap initializes its cache as c={45840:{exports:local}}, the normal early-cache return yields local and never dispatches the Electron external. moduleCache accepts the later c[t]={...} assignment as sufficient cache proof without checking c's initializer, so n(45840) is still given Electron identity and can produce bogus BrowserWindow or IPC findings.
AGENTS.md reference: AGENTS.md:L21-L21
Useful? React with 👍 / 👎.
| const value = t.isSequenceExpression(argument) | ||
| ? argument.expressions.at(-1) | ||
| : argument; |
There was a problem hiding this comment.
Reject exports rewritten after dispatch
When the loader returns m[t](o,o.exports,n),o.exports=local,o.exports, runtime returns local, not the external's exports. Although a direct return fake is now rejected, the new returnsModuleExports implementation provides fresh evidence of the same proof gap because it discards every sequence element except the last, so this rewrite still assigns Electron identity to n(45840).
AGENTS.md reference: AGENTS.md:L21-L21
Useful? React with 👍 / 👎.
| const role = id === undefined ? undefined : tracked.get(id); | ||
| if (role === undefined) return; | ||
| const use: Use = { node, parent, ancestors, shape, loaderIds, state }; | ||
| if (role === "loader") exposedSlotWrite(use, replacedKeys); |
There was a problem hiding this comment.
Reject aliases of exposed module tables
With the supported exposure n.m=m, code can do const a=n.m; a[45840]=local; n(100), replacing the external before its consumer loads it. The direct-table alias case is now rejected, but this revision's role === "loader" branch only calls exposedSlotWrite and never rejects an unrecognized loader-property read, so the alias mutation leaves replacedKeys empty and yields bogus Electron findings.
AGENTS.md reference: AGENTS.md:L21-L21
Useful? React with 👍 / 👎.
Bundled Electron main processes load Electron through a Webpack external
(`45840: e => { e.exports = require("electron") }`) and the bootstrap
loader (`n(45840)`) instead of a direct require, so Electron identity
missed BrowserWindow, IPC and contextBridge calls made on that module.
A loader call now counts as a require origin only when the bootstrap is
proven intact: the loader is never reassigned and returns only the
dispatched module's exports or its own cache entry, the table has only
literal keys and is touched only by the dispatch or the runtime's
loader.m/loader.c exposure, literal-key writes through that exposure
drop their slot, and the external factory is an ordinary function whose
whole body is `module.exports = require(specifier)`.
Refs morluto#2932
305818b to
88bfa85
Compare
There was a problem hiding this comment.
💡 Codex Review
Here are some automated review suggestions for this pull request.
Reviewed commit: 88bfa85deb
ℹ️ About Codex in GitHub
Your team has set up Codex to review pull requests in this repo. Reviews are triggered when you
- Open a pull request for review
- Mark a draft as ready
- Comment "@codex review".
If Codex has suggestions, it will comment; otherwise it will react with 👍.
Codex can also answer questions or update the PR. Try commenting "@codex address that feedback".
| if (parameterId === undefined || loader.async || loader.generator) | ||
| return undefined; |
There was a problem hiding this comment.
Reject rewritten bootstrap module keys
When the loader rewrites its module-ID parameter, for example with if (t === 45840) t = 1, this check still accepts m[t](...), while semanticBundledRequireOrigin indexes the caller's original literal 45840. An entry at key 100 can therefore run normally, but its n(45840) dispatches a local module at key 1 while the analyzer attributes Electron's factory at 45840 and emits bogus BrowserWindow/IPC findings; require the key parameter to have a single unmodified binding before accepting the proof.
AGENTS.md reference: AGENTS.md:L21-L21
Useful? React with 👍 / 👎.
| const dispatch = tableDispatch(node, tableId, parameterId, state); | ||
| if (dispatch === undefined) return; | ||
| dispatches.add(dispatch.table); |
There was a problem hiding this comment.
Require dispatch on every uncached loader path
The new returns.every check still accepts a dispatch that appears only under a guard, because this traversal records the call without its control-flow context. For example, if (t === 100) m[t](o, o.exports, n); return o.exports lets the entry module run, but n(45840) never invokes the Electron external and returns the initial exports object; calls through that result are nevertheless labeled Electron. Require the dispatch to dominate every non-cache return path, or leave the origin unknown.
AGENTS.md reference: AGENTS.md:L21-L21
Useful? React with 👍 / 👎.
| if ( | ||
| moduleBinding === undefined || | ||
| target?.bindingId !== moduleBinding.bindingId | ||
| ) |
There was a problem hiding this comment.
Reject duplicate module-parameter bindings
For a valid sloppy-mode factory such as function (e, e, n) { e.exports = require("electron") }, the first parameter and the body target resolve to the same semantic binding, so this comparison succeeds. At runtime the duplicate binding contains the second argument (module.exports), so the assignment adds an exports property to that object instead of replacing the loader module's exports; n(45840).BrowserWindow is still attributed to Electron even though it is absent. Require the first parameter's binding to have exactly one parameter definition.
AGENTS.md reference: AGENTS.md:L21-L21
Useful? React with 👍 / 👎.
| const value = initializer.node; | ||
| if (t.isObjectExpression(value)) return undefined; |
There was a problem hiding this comment.
Prove ordinary storage for module exports
Accepting every fresh object literal allows a loader module object to define an exports getter and a setter that discards writes. The external's module.exports = require("electron") then executes without changing the getter's returned local value, while the syntactic return o.exports still passes the proof and consumers are labeled Electron. Reject accessor/prototype-intercepted exports properties unless ordinary writable data-property behavior is proven.
AGENTS.md reference: AGENTS.md:L21-L21
Useful? React with 👍 / 👎.
- the loader's key parameter can't be reassigned, and the dispatch has to run unconditionally before any return of the module's exports - the module object is a plain literal (no accessors, computed keys or __proto__) and is only touched by the dispatch, returned exports reads and writes to members other than exports - the cache has to start as an empty literal - loader.m / loader.c can only be assigned or indexed directly, and writing a member of an indexed entry drops the proof - factories with duplicate parameter names are rejected
|
second round in 4b7e2d6, all of these were fair:
tests for each are in the two "tampered" blocks in one honest side effect: discord goes back to unresolved. its bundle ships require-in-the-middle (from its error reporting sdk), which reads the whole module cache through |
There was a problem hiding this comment.
💡 Codex Review
Here are some automated review suggestions for this pull request.
Reviewed commit: 4b7e2d601a
ℹ️ About Codex in GitHub
Your team has set up Codex to review pull requests in this repo. Reviews are triggered when you
- Open a pull request for review
- Mark a draft as ready
- Comment "@codex review".
If Codex has suggestions, it will comment; otherwise it will react with 👍.
Codex can also answer questions or update the PR. Try commenting "@codex address that feedback".
| return returns.every((argument) => | ||
| returnsModuleExports(argument, shape, state), | ||
| ) |
There was a problem hiding this comment.
Require a nonempty set of loader returns
Fresh evidence after adding return validation is that returns.every(...) is vacuously true for a loader with no return. For function n(t){var o={exports:{}};m[t](o,o.exports,n)}, entry modules execute, but n(45840) evaluates to undefined; bindingOrigin nevertheless assigns Electron identity to that result and can report calls on it. Require at least one proven return in addition to validating each return.
AGENTS.md reference: AGENTS.md:L21-L21
Useful? React with 👍 / 👎.
| return ( | ||
| binding?.definitions.length === 1 && | ||
| initializer?.projection.length === 0 && | ||
| t.isObjectExpression(initializer.node) && | ||
| initializer.node.properties.length === 0 |
There was a problem hiding this comment.
Reject caches mutated outside the bootstrap
Fresh evidence after adding startsEmpty is that it trusts an empty initializer without proving the cache is owned by the bootstrap. In var c={}; c[45840]={exports:local}; (()=>{/* loader closes over c */})(), the member write does not add a binding definition and lies outside the call subtree scanned later, so this function returns true and the cache hit is mislabeled as the external. Require the cache declaration and references to be contained by the bootstrap, or incorporate out-of-subtree member mutations.
AGENTS.md reference: AGENTS.md:L21-L21
Useful? React with 👍 / 👎.
| if (role !== "loader") contained = containedUse(role, use); | ||
| else if (exposedTableUse(use) === "escaped") contained = false; | ||
| else exposedSlotWrite(use, replacedKeys); |
There was a problem hiding this comment.
The loader branch treats every use other than a recognized .m/.c escape as safe. Thus n.m=m; mutate(n); n(100), where mutate(x) writes x.m[45840]=local, leaves both the loader argument and the alias's mutation untracked and still attributes the consumer to Electron. Reject or track loader values that are passed, stored, or returned rather than silently accepting them.
AGENTS.md reference: AGENTS.md:L21-L21
Useful? React with 👍 / 👎.
| ((t.isAssignmentExpression(target) && target.left === member) || | ||
| t.isUpdateExpression(target) || | ||
| t.isUnaryExpression(target, { operator: "delete" })); | ||
| return entryWritten ? "escaped" : "contained"; |
There was a problem hiding this comment.
Reject aliases of indexed cache entries
Fresh evidence after the whole-table alias fix is that an indexed entry can still escape: with n.c=c; n(45840); const entry=n.c[45840]; entry.exports=local; n(100), this branch calls the initializer contained, and the later write contains no tracked loader or cache identifier. The consumer's n(45840) therefore returns local, but the proof still assigns Electron identity and can emit bogus findings; treat stored, returned, or passed entries as escaped.
AGENTS.md reference: AGENTS.md:L21-L21
Useful? React with 👍 / 👎.
| const key = slot.computed | ||
| ? argumentValue(slot.property) | ||
| : semanticStaticPropertyKey(slot.property, false); | ||
| if (key !== undefined && key !== null) replacedKeys.add(key); |
There was a problem hiding this comment.
Invalidate externals after unresolved slot writes
Fresh evidence after computed initializer keys were rejected is that post-initialization writes through the exposure still drop an unresolved key. For const id=45840; n.m=m; n.m[id]=local; n(100), argumentValue(id) is undefined, so this code records no replacement even though runtime overwrites external slot 45840; the consumer is then falsely attributed to Electron. Resolve stable keys or invalidate all possibly matching externals on unknown writes.
AGENTS.md reference: AGENTS.md:L21-L21
Useful? React with 👍 / 👎.
Track module writes and escapes at their owner, preserve capture and reassignment ordering, and share CommonJS/default namespace identity without erasing parent-slot changes. Carry write sites into ambient alias resolution and use parsed write targets across consumers. Deduplicate returned-reference work with cycle context; retain unchanged temporal selection identity so provenance memoization stays effective. Reviewed fixes include #2041, #2465, #2830, #2881, and #2948. Remove superseded mutation representations and the ineffective per-markValue dedup layer. Validation: 380 focused JavaScript tests passed under a 384 MiB heap cap, including the previously aborting 30-level/128-call alias regression. Six public CLI/MCP builtin tests passed. Exact pdf.js completed-workflow performance remains unmeasured.
…t keys - the loader must return the dispatched module's exports somewhere; a cache-only early return is not enough, since a first load would fall off the end and yield undefined - a slot write through a constant key (`const id = 45840; n.m[id] = x`) resolves to the declared slot and drops it
|
pushed two more from the latest codex round:
@morluto question on where you want the bar for this one. the remaining codex findings are things like an outside function mutating the loader ( so i see two options:
im leaning 1 but its your call, happy to do either |
|
Codex usage limits have been reached for code reviews. Please check with the admins of this repo to increase the limits by adding credits. |
# Conflicts: # src/domain/javascript/electronBundledRequireIdentity.test.ts # src/domain/javascript/electronWrappedCallPaths.test.ts # src/domain/javascript/javascriptBootstrapIntegrity.ts # src/domain/javascript/javascriptBundledRequireOrigin.ts # src/domain/javascript/javascriptSemanticAnalysis.ts # src/domain/javascript/javascriptSemanticRequireOrigin.ts
|
Merged latest |
|
Thanks @UnknownHacker1. Closing this PR as superseded by 04672f2b9 on The current PR head has no remaining diff from its merge base with main. This is an unmerged closure: it does not label this PR as merged or remove contributor history/credit. The decision uses the current source diff and existing validation record; no new local test or provider run is claimed. |
Summary
Refs #2932. if an electron app's main process is bundled with webpack, electron gets loaded through the bundle's module table (
45840: e => { e.exports = require("electron") }) and thenn(45840)everywhere, never a directrequire("electron"). electron identity only knew the direct require so it just saw nothing. BrowserWindow, webPreferences, ipc handlers on the module, all 0.this lets a loader call count as the require it re-exports, but only when the bootstrap can be proven intact.
Problem and expected behavior
smallest case (normal webpack 5
target: "electron-main"shape):main gives
browser_windows: []. should be one window withpreload_path: "./preload.js"plus theget-connectionshandler, which is what you get now.Change and scope
new
semanticBundledRequireOriginreusesjavascriptBootstrapAtfor the bootstrap shape, andproveJavaScriptBootstrapIntegritychecks the rest.n(KEY)only resolves when all of this holds:nis the bootstrap loader (never reassigned) or a factory's 3rd param that the bootstrap passes the loader asreturnin the loader is the dispatched module's.exports(after the dispatch) or the cache entry the loader made for it.exportsreads and writes to other members{}n.m = tableexposure. same for the cache withn.c.n.m/n.ccan only be assigned or indexed, a literal key write through them drops that slot, and writing into an entry drops the proofKEYis a plain function (not generator/async/getter, no duplicate params) whose whole body ismodule.exports = require("x")only electron identity uses it (
rootExportandbindingOrigin). othersemanticRequireOriginusers are unchanged. the member chain walk moved intosemanticMemberChainso both resolvers share it.not in here:
n.n()default interop getter form (a = n.n(n(45840)); a().ipcMain). separate follow upn.m[k]are left alone. thats chunk install adding its own ids, refusing those would turn this off for pretty much every chunked bundleContract and boundary impact
Semantic owner and earliest changed stage: electron identity in
indexJavaScriptElectronIdentitySteps. bootstrap shape still owned byjavascriptBootstrapAtContribution scope fit and linked maintainer decision: not applicable, static analysis fix
CLI and MCP/tool-catalog contract: none, same fields just more findings
Provider, bridge, target-format, or platform compatibility: none
Evidence, artifact, provenance, or reconstruction contract: calls through a proven loader are direct observations now. one existing test that reached
electronthroughload(2)gets noresolution_basisinstead of"wrapper-substitution"(same api key, members, world). thats what the same call throughrequire("electron")gives tooTarget selection, authority, upstream behavior, and cleanup details: not applicable
Generated metadata, package, or installation impact: none
Read existing files or captured data.
Launch or attach to a process.
Inject instrumentation or run scripts/code.
Change process memory, registers, files, or configuration.
Contact network services.
Recover protected code or work around protections.
Documentation or usability only; no target interaction.
Not sure yet; investigation or maintainer guidance needed.
Evidence and regression coverage
Tests added or updated:
electronBundledRequireIdentity.test.ts. 3 positive shapes, 4 real world loader shapes that have to keep working (try/finally cache delete like compass,n.c = cache, chunk install throughn.m,module.loaded = !0before the return), and 24 tampered or wrong shapes that have to stay unresolved (replaced loader, generator/async factory, loader returning something else, table slot replaced directly / through an alias / throughn.m, planted cache entry, computed table keys, shadowed require, etc).electronWrappedCallPaths.test.tshas the one updated expectation aboveBase reproduction: the positive cases fail on main. the tamper cases fail on the earlier pushes of this PR and pass now
fixture repo with a one command repro: https://github.com/UnknownHacker1/rea-groundtruth (
python scripts/run_repro.py <rea>)real apps, installed windows builds,
--integrity-policy record-and-continue, same base commit with and without this:Discord is unresolved on purpose: it ships require-in-the-middle, which reads the whole module cache through
__webpack_require__.cand writes into entries with runtime keys, so whatn(91288)returns cant be provenRemaining proof gaps:
explicit_web_preferences: 0because its window options are built before the call (new s.BrowserWindow(u)), separate thingObserved, derived, and inferred claims remain distinguishable.
Artifact identity, source provenance, and failed attempts remain preserved.
Unsupported, incomplete, unavailable, or uncertain outcomes remain visible.
Validation performed
npm run test:local -- <all 57 files in src/domain/javascript/*.test.ts>: 1313 passednpx tsc --noEmit: passnpm run lint: 0 errors, no warnings in touched filesnpm run verify:test-discovery: all test files discovered oncenpm run buildthennode scripts/rea.mjs analyze-javascript-application ...on the fixtures, Discord and Compass (numbers above). single cold runs, timing looked the same within noise. didnt measure memory or tokensCompatibility, safety, and release
native/windows/build, not committed. no native provider involvedBefore merge
type(scope): outcome.