Skip to content

fix(javascript): keep strict module checks unproven when alias walks exhaust their budget - #9387

Merged
morluto merged 7 commits into
morluto:mainfrom
mvanhorn:fix/8201-require-origin-budget-exhaustion
Nov 9, 2026
Merged

morluto merged 7 commits into
morluto:mainfrom
mvanhorn:fix/8201-require-origin-budget-exhaustion

Conversation

@mvanhorn

@mvanhorn mvanhorn commented Nov 8, 2026 •

Copy link
Copy Markdown
Contributor

Summary

Fixes #8201.

analyze_javascript_application reports 0 BrowserWindows and 0 IPC operations on Electron main bundles that also contain a loop-aliased Object.defineProperty walk, which zod's error formatter has.

A strict "is this the CommonJS module object?" check treats a budget-exhausted alias walk as a proven module identity. writesModuleRequire then records an unrelated local object's defineProperty as a possible module.require write, revokes the host require, and the electron binding stops resolving.

After this change, a strict check that runs out of budget answers "not proven", so the Electron facts are recovered, and the alias-selections resource limit is still reported.

Problem and expected behavior

Smallest trigger, from the reproduction in the issue thread:

let h=require("electron");
function f(n,e){let r=n,i=0;for(;i<e.length;){let k=e[i];Object.prototype.hasOwnProperty.call(r,k)||Object.defineProperty(r,k,{value:{_errors:[]}});let s=r[k];r=s,i++}return r}
new h.BrowserWindow({webPreferences:{sandbox:!0}});h.ipcMain.handle(`x:y`,()=>1);

Violated invariant: hasCommonJsModuleSource(..., includeUnknown = false, ...) should return true only for a retained module identity. Both budget exits (selections.limited and the additionalStates > SEMANTIC_ALIAS_SELECTION_LIMIT branch) returned true whatever includeUnknown was. Running out of budget was treated as proof.

Expected: the window and the x:y main handler are reported, and the budget exhaustion stays visible as a resource limit.

Change and scope

Permissive callers (includeUnknown = true, the default for isCommonJsModuleObject and semanticModuleRequireCallAt) still return true at either budget exit and are unchanged.

A strict check that reaches a budget exit no longer returns. It stops following bindings and calls, keeps expanding finite expressions (sequences, conditionals, members, awaits, containers), and examines each queued source by its own selected keys rather than the limiter's widened ones. It returns false only if none of them is a retained module identity.

Review found the two earlier versions of this rule order-dependent: ending the walk outright missed (flag ? module : r), and a drain without finite expansion missed (flag ? (0, module) : r). Strict callers affected:

  • writesModuleRequire. This is the reported failure: an exhausted walk over an unrelated local object no longer revokes the host delegate.
  • semanticModuleRequireCallAt(node, bindings, false) in javascriptStaticAnalysisCalls.ts, and the interop isCommonJsRequireDelegate(..., false, ...) branch. Under exhaustion these no longer treat an unproven callee as a module-require delegate. That matches the contract the includeUnknown = false parameter already states. I did not add separate tests for these two sites.

Not included: the per-site budgets are unchanged. Also unchanged: #7253's canonicalWebpackInteropBindings site (same family, different site) is untouched. Contribution scope: an ordinary fix within existing boundaries; no maintainer scope decision is required.

Open policy question: a strict walk that exhausts the budget cannot be both precise and sound. This version still misses a module reached through a binding beside the exhausted alias, for example const m = module; (flag ? m : r).require = replacement, when r is explored first. Base behavior (revoke on exhaustion) is sound but suppresses Electron facts whenever an unrelated walk such as zod's exhausts the budget. See the PR conversation for the options.

Contract and boundary impact

  • Semantic owner and earliest changed stage: hasCommonJsModuleSource in src/domain/javascript/javascriptSemanticRequireOrigin.ts (semantic require-origin analysis). Consumers: writesModuleRequire, the strict require-call recognizer in javascriptStaticAnalysisCalls.ts, and the interop delegate branch of semanticModuleRequireCallAt.
  • Contribution scope fit and linked maintainer decision: not applicable; a bug fix within the existing analysis boundary.
  • CLI and MCP/tool-catalog contract: none. No schema or option changes.
  • Provider, bridge, target-format, or platform compatibility: none.
  • Evidence, artifact, provenance, or reconstruction contract: Electron graph counts change for affected bundles (from 0 to the recovered facts). semantic_resource_limits still lists alias-selections.
  • Target selection, authority, upstream behavior, and cleanup details: not applicable.
  • Generated metadata, package, or installation impact: none.

Expected effects:

  • 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, in src/domain/javascript/javascriptStaticAnalysisAssignedRequire.test.ts:

    • revokes the host delegate through %s after alias selections are exhausted: module, (0,module) and process.mainModule beside the exhausted alias revoke the loader in both branch orders.
    • keeps the host delegate through %s after alias selections are exhausted: process.foo beside the exhausted alias does not revoke, in both orders.
    • keeps electron facts when a loop-aliased defineProperty exhausts alias selections: the reduction above. It asserts 1 BrowserWindow, the x:y main handler, the electron require reference, and alias-selections in analysis_coverage.examination.semantic_resource_limits. It fails on 08637b0 without the source change (Tests 1 failed | 48 passed).
    • keeps electron facts for the same path walk without defineProperty: a control; passes before and after.
    • revokes the host delegate after a dynamic defineProperty on module: a control showing a real, proven module receiver with a dynamic key still revokes (specifier: null).
  • Base reproduction (executed). I built an Electron main entry that imports real [email protected] and calls z.formatError, bundled it with [email protected] (--format cjs --platform node --external electron --minify; 69,567 bytes), and ran rea analyze-javascript-application <app> --source-path dist/main.js from a source build:

    base 08637b0 this PR
    browser_windows 0 1
    explicit_web_preferences 0 1
    ipc.operations / main_handlers / literal_channels 0 / 0 / 0 1 / 1 / 1
    electron_semantics absent recovered
    semantic_resource_limits alias-selections alias-selections
  • User-visible CLI/MCP output: the graph summary counts above.

  • Remaining proof gaps: the binding case in the open policy question above is not covered. I did not run the Signal Desktop 8.33.0 or Wonder 0.2.220 bundles from the issue, and I did not check whether Signal reaches this exact site. The two other strict callers have no dedicated regression tests.

For evidence-bearing changes:

  • Observed, 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

  • Alias cutoff: the module-source search now distinguishes a possible source, a completed negative result, and an incomplete search. Possible or incomplete receiver writes remain indexed with their source and use existing effect timing; they make a potentially affected CommonJS loader unknown. Primitive leaves the walker would discard are pruned before consuming the remaining search allowance. Direct assignment, Object.defineProperty and Object.assign regressions fail on the previous head and pass here, including both branch orders and identifier alternatives.

  • npm run check:fast passed. The focused require/Electron source suites passed (457 tests, plus two added Object cases subsequently passed in the 67-test assigned-require suite). npm run test:focused -- tests/acceptance/applications/javascriptModuleResolutionSemantics.test.ts tests/boundary/filesystem/javascript-applications/electronApplicationAnalysis.test.ts tests/boundary/filesystem/javascriptArtifactSemanticUnknowns.test.ts passed (16 tests; CLI and stdio MCP included).

  • Precision limitation: when the bounded walk cannot rule out a write, including the Zod-like computed-property loop, the loader remains unknown and previously reported Electron facts are no longer inferred. Further precision requires proving that an unresolved receiver cannot alias the module; that refinement is not implemented.

  • npx vitest run src/domain/javascript/javascriptStaticAnalysisAssignedRequire.test.ts on base without the source change: 1 failed, 48 passed (the new regression).

  • npx vitest run src/domain/javascript/javascriptStaticAnalysisAssignedRequire.test.ts src/domain/javascript/electronBundledRequireIdentity.test.ts src/domain/javascript/javascriptSemanticRequireCaptures.test.ts: 3 files, 181 tests passed before the review follow-up; the assigned-require file now has 57 passing tests (includes "keeps a limited loader-alias walk unknown").

  • npx vitest run src/domain/javascript: 174 files, 5051 tests passed.

  • npm run check:fast (typecheck, lint): passed.

  • npm run verify:test-discovery: "Discovered all 3192 test files exactly once."

  • npm run check: typecheck and lint passed (0 errors). metadata:check failed under local Node 26.5.0 with ERR_INVALID_ARG_VALUE ... options.mode ... 'transform'; it fails the same way on unmodified base, below the repo's engines floor. Under Node 24.22.1, npm ci and npm run build:cached (which includes metadata:check) passed.

  • rea analyze-javascript-application before/after on the zod bundle: the table above, re-run on the final commit with the same result.

  • npx oxfmt --check on both changed files: correct format.

Compatibility, safety, and release

  • Breaking changes or migration steps: none.
  • Real Hopper/Ghidra, browser, or OS coverage: not applicable (static JavaScript analysis). macOS, Node 24.22.1 and 26.5.0.
  • Package or release metadata impact: none.
  • Security, privacy, process, or containment review: no target execution. The analysis may now report Electron facts it previously suppressed; it does not widen what is executed or read.

Author readiness

Human owner: @mvanhorn

  • I reviewed the final diff and relevant existing code, understand the change and its edge cases, and take responsibility for the complete PR, including AI-assisted work.
  • I checked the evidence above, confirmed it supports the current change, and recorded meaningful validation gaps.
  • I declare this PR ready for initial maintainer review.

Before merge

  • This PR addresses a concrete problem or an agreed enhancement.
  • Material scope and authority questions are resolved, and any required maintainer scope decision covers the final diff.
  • The PR has one focused outcome and the title follows type(scope): outcome.
  • Related issue is linked, or the reason for not linking one is stated above.
  • Tests cover changed observable behavior and meaningful failure paths.
  • Owning docs, contracts, and generated metadata are updated where needed.
  • User-visible CLI/MCP changes include representative output.
  • I checked the final diff for secrets, unrelated cleanup, and unsupported claims.

AI was used for assistance.

@chatgpt-codex-connector

chatgpt-codex-connector Bot commented Nov 8, 2026 •

Copy link
Copy Markdown
Codex Review Summary: ✅ Completed

This comment shows the latest Codex review activity on this pull request.

Review Status Commit Review trigger
📝 Code Review ✅ Completed 2026-11-09T12:56:14.257108Z 04b6b97 New commits
ℹ️ 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" or "@codex security review".

Codex reacts with 👀 while any review is running, comments if it has suggestions, and reacts with 👍 once all reviews finish with no findings.

@greptile-apps

greptile-apps Bot commented Nov 8, 2026 •

Copy link
Copy Markdown
Contributor

Confidence Score: 5/5 · The PR appears safe to merge, with the earlier non-blocking test weakness still present.RetriggerView in GreptileConfidence Score: 5/5

[Medium impact] The PR appears safe to merge, with the earlier non-blocking test weakness still present.

Findings

  1. P2 Helper masks broken write checks ▶
Fix with agent prompt
### Issue 1
src/domain/javascript/javascriptStaticAnalysisAssignedRequire.test.ts:217-218
`exhaustedWalkWrite` includes a loop-aliased `Object.defineProperty(r,k,...)` write that already makes the loader unknown, as the test at line 198 shows. The later tests therefore pass even if the added receiver assignment, `Object.defineProperty`, or `Object.assign` is never recorded.

Remove the helper's independent write and add a control without the tested write. That will let these tests catch a broken cutoff fix.

---

For each issue above, determine whether it is valid and should be fixed. If so, fix it directly.

Summary

The PR separates a possible module source, a completed negative search, and an incomplete search.

  • Strict alias checks stop treating unfinished searches as proof of module.

No new findings were accepted. Supersession could not be checked because GitHub access was unavailable.

Diagram

%%{init: {'theme': 'neutral'}}%%
flowchart TD
  A[Check a write receiver] --> B[Walk selected sources]
  B --> C{Search result}
  C -->|Possible module source| D[Record the write]
  C -->|Incomplete search| D
  C -->|Completed without a match| E[Do not record the write]
  D --> F[Apply existing write timing]
  F --> G[Keep affected loader unknown]
Loading

Reviews (8) · Last reviewed commit: "fix(javascript): retain uncertainty at a..." · Reviewed by Greptile

@chatgpt-codex-connector chatgpt-codex-connector Bot left a comment

Copy link
Copy Markdown

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

💡 Codex Review

Here are some automated review suggestions for this pull request.

Reviewed commit: 13608c7530

ℹ️ 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".

…hausts its budget

A strict check that exhausts the alias budget stopped the whole walk, so a module branch queued beside the growing alias was never examined. Stop expanding instead, and drain the queued sources.

@chatgpt-codex-connector chatgpt-codex-connector Bot left a comment

Copy link
Copy Markdown

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

💡 Codex Review

Here are some automated review suggestions for this pull request.

Reviewed commit: 63a951c0d8

ℹ️ 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".

depths: readonly number[],
...sources: ModuleObjectSource[]
) => {
if (exhausted) return;

Copy link
Copy Markdown

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

P1 Badge Resolve finite queued sources after alias-budget exhaustion

The new direct-module cases miss a finite queued wrapper: in the same growing-r loop, (flag ? (0, module) : r).require = replacement leaves the sequence pending while r exhausts the budget. When that sequence is popped, this new guard prevents it from enqueueing its final module expression, so the strict walk returns false, whereas reversing the branches returns true. This drops a possible native write from writesModuleRequire, letting commonJsLoaderAt label a subsequent require('electron') as commonjs-loader and expose concrete Electron facts despite a potentially replaced delegate. Preserve a bounded route for resolving finite pending alternatives rather than treating their native identities as absent.

AGENTS.md reference: AGENTS.md:L21-L21

Useful? React with 👍 / 👎.

Copy link
Copy Markdown
Contributor Author

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Confirmed on 63a951c: (flag ? (0, module) : r) kept require("electron") as a loader, and the reversed order revoked it. 5ad934f keeps expanding finite expressions (sequences, conditionals, members, awaits, containers) after exhaustion and stops only at bindings and calls, so both orders revoke. The binding form, const m = module; (flag ? m : r), is still order-dependent; I raised it as a policy question in the PR conversation.

…nite expressions

After exhaustion the limiter widens every key, so draining by normalized paths could match process.foo as mainModule. Keep each queued source's selected keys, expand finite expressions such as sequences and conditionals, and stop only at bindings and calls.
@mvanhorn
mvanhorn marked this pull request as draft November 8, 2026 17:49
@mvanhorn

mvanhorn commented Nov 8, 2026 •

Copy link
Copy Markdown
Contributor Author

One design question I could not settle from the code; the PR is reviewable as is.

When a strict hasCommonJsModuleSource walk exhausts the alias budget, it can't be both precise and sound. Here is what 5ad934f does after exhaustion: it stops following bindings and calls, keeps expanding finite expressions, and checks each queued source by its own selected keys. That covers module, (0, module) and process.mainModule beside an exhausted alias in both branch orders. It also keeps process.foo from revoking.

The remaining gap is a module reached through a binding, when the exhausted alias is explored first:

const m = module;
(flag ? m : r).require = replacement; // r is the loop-aliased walk

(flag ? r : m) revokes; (flag ? m : r) does not. The same holds for const q = process.mainModule.

Options as I see them:

  1. Keep this PR's behavior. It is precise for direct and structural sources, recovers the Electron facts in the zod case, and misses a binding-held module beside an exhausted alias.
  2. Keep base behavior (exhaustion proves a module). This is sound, but any unrelated walk that exhausts the budget, as zod's error formatter does, suppresses the app's Electron facts.
  3. Report a partial result. Keep the facts but mark the host loader as possibly revoked in coverage. This is a larger change across the result model.
  4. A variant of 1: on exhaustion, re-walk only the queued binding sources with a fresh, small budget. That narrows the gap but does not close it.

Which would you prefer? I'm happy to rework this toward 2, 3 or 4, or to close it if the current trade-off is intended.

@chatgpt-codex-connector chatgpt-codex-connector Bot left a comment

Copy link
Copy Markdown

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

💡 Codex Review

Here are some automated review suggestions for this pull request.

Reviewed commit: 5ad934f181

ℹ️ 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".

@mvanhorn
mvanhorn marked this pull request as ready for review November 8, 2026 19:19
… strict walks

An exhausted strict walk skipped every binding and call, so (flag ? m : r).require with const m = module lost the module branch when r was explored first. Drain the queue breadth first after exhaustion and follow bindings and calls under a second alias selection budget, so a growing alias cannot starve a sibling.

@chatgpt-codex-connector chatgpt-codex-connector Bot left a comment

Copy link
Copy Markdown

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

💡 Codex Review

Here are some automated review suggestions for this pull request.

Reviewed commit: 6103e26360

ℹ️ 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".

…tion

After the alias budget is exhausted, paths are no longer normalized, so a
cycle through containers or getters can keep growing its selected path
without crossing a binding or call. Count each new state against the
drain budget instead of only binding and call follow-ups.

@chatgpt-codex-connector chatgpt-codex-connector Bot left a comment

Copy link
Copy Markdown

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

💡 Codex Review

Here are some automated review suggestions for this pull request.

Reviewed commit: 078a19a49c

ℹ️ 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".

// expansion beyond the shared selector budget.
if (
if (exhausted) {
if (++drained > SEMANTIC_ALIAS_SELECTION_LIMIT) break;

Copy link
Copy Markdown

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

P1 Badge Preserve unresolved module sources at the final drain cutoff

With the growing r from exhaustedWalkWrite, use (flag ? [0, …, 0, module][key] : r) with 520 explicit zero elements. The new breadth-first drain queues module behind those finite elements, exhausts this second budget, and falls through to false while that native identity is still pending; reversing the branches returns true. Consequently, writesModuleRequire misses the possible native .require replacement and commonJsLoaderAt classifies the following require('electron') as a known loader, enabling unsupported Electron facts. Preserve an unresolved outcome, or inspect queued terminal identities, when this final cap is hit instead of treating the unfinished search as no module source.

AGENTS.md reference: AGENTS.md:L21-L21

Useful? React with 👍 / 👎.

@morluto

morluto commented Nov 9, 2026

Copy link
Copy Markdown
Owner

@mvanhorn Thanks for laying out the tradeoff. We chose the conservative behavior closest to option 2, but only after the bounded follow-up walk is exhausted: an unfinished receiver search is recorded as incomplete, so a potentially affected loader becomes unknown. It does not assert that the receiver is definitely module.

In 04b6b97, the search distinguishes a possible source, a completed negative result, and an incomplete search. It still examines queued sources and skips primitive leaves that cannot contribute a module source. The write index preserves the incomplete result and applies the existing effect-timing check.

Both branch orders for const m = module are covered, as are final-cutoff cases for direct assignment, Object.defineProperty, and Object.assign. The exact const q = process.mainModule binding variant was not tested separately. The Zod-like computed-property case and the process.foo/r controls now leave the loader unknown and omit Electron facts when the receiver remains unresolved; preserving those facts with a possible-revocation warning would require the larger result-model change in option 3.

Validation: npm run check:fast passed, along with the focused require/Electron source suites and 16 CLI/MCP and Electron boundary tests. The new cutoff regressions failed on the previous head and passed after the fix. Further precision would require proving that an unresolved receiver cannot alias the module; that refinement remains open. GitHub checks are pending.

@morluto
morluto merged commit 9108d9a into morluto:main Nov 9, 2026
4 of 8 checks passed
@morluto morluto mentioned this pull request Nov 11, 2026
3 tasks done
Comment on lines +217 to +218
const exhaustedWalkWrite = (receiver: string): string =>
`const m=module,g=()=>module;function f(n,e,flag){let r=n,i=0;for(;i<e.length;){let k=e[i];Object.prototype.hasOwnProperty.call(r,k)||Object.defineProperty(r,k,{value:{_errors:[]}});let s=r[k];r=s,i++}${receiver}.require=replacement;return r}let h=require("electron");new h.BrowserWindow({});`;

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

P2 Helper masks broken write checks

exhaustedWalkWrite includes a loop-aliased Object.defineProperty(r,k,...) write that already makes the loader unknown, as the test at line 198 shows. The later tests therefore pass even if the added receiver assignment, Object.defineProperty, or Object.assign is never recorded.

Remove the helper's independent write and add a control without the tested write. That will let these tests catch a broken cutoff fix.

Prompt To Fix With AI
This is a comment left during a code review.
Path: src/domain/javascript/javascriptStaticAnalysisAssignedRequire.test.ts
Line: 217-218

Comment:
**Helper masks broken write checks**

`exhaustedWalkWrite` includes a loop-aliased `Object.defineProperty(r,k,...)` write that already makes the loader unknown, as the test at line 198 shows. The later tests therefore pass even if the added receiver assignment, `Object.defineProperty`, or `Object.assign` is never recorded.

Remove the helper's independent write and add a control without the tested write. That will let these tests catch a broken cutoff fix.

---

For each issue above, determine whether it is valid and should be fixed. If so, fix it directly.

@morluto morluto added bug Something isn't working area: native Native analysis and decompilation, including Ghidra, IDA, and Hopper analysis behavior labels Nov 22, 2026
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Labels

area: native Native analysis and decompilation, including Ghidra, IDA, and Hopper analysis behavior bug Something isn't working

Projects

None yet

Development

Successfully merging this pull request may close these issues.

[Bug] Electron graph reports 0 IPC channels and 0 BrowserWindows on a real Rolldown bundle (Signal Desktop 8.33.0)

2 participants