Skip to content

fix(javascript): trace wrapped Electron IPC paths in large bundles - #1874

Merged
morluto merged 2 commits into
morluto:mainfrom
fengdwx:fix/electron-bundle-clipboard-paths
Oct 12, 2026
Merged

morluto merged 2 commits into
morluto:mainfrom
fengdwx:fix/electron-bundle-clipboard-paths

Conversation

@fengdwx

@fengdwx fengdwx commented Oct 11, 2026 •

Copy link
Copy Markdown
Contributor

Summary

Recover candidate feature paths through Electron wrapper functions and literal CommonJS module tables, and allow large bundles to retain their semantic graph within explicit caller-selected budgets.

An exposed member such as desktop.copy: sender("example:copy") currently loses its connection to ipcRenderer.send and the wrapped main-process callback. This change lets trace-application-feature follow that member through a unique literal IPC pairing to event.sender.copy(), preserving source locations, guards, and inferred authority.

Problem and expected behavior

The following pattern should produce a candidate cross-file path:

// preload.js
const e = require("electron");
const sender = channel => (...args) => e.ipcRenderer.send(channel, ...args);
e.contextBridge.exposeInMainWorld("desktop", { copy: sender("example:copy") });

// main.js
const e = require("electron");
function register(channel, handler) {
  e.ipcMain.addListener(channel, event => allowed(event) && handler(event));
}
register("example:copy", event => event.sender.copy());

Large bundles hit the fixed 20,000-node per-file semantic projection limit even when more heap is available. This PR adds explicit node budgets and bounded adaptive result transfer. A class/getter alias regression also incorrectly retains a literal after its shared object escapes through a loop.

These were found while testing publicly distributed Notion desktop JavaScript. This PR includes the reproduction directly; no separate issue was opened. Upstream integration: merged main at 6611bcf6e86630c775c24e6afa00d7239c64e70e, preserving #1857 and #1912 (the fix for #1909). The upstream intrinsic-invocation and module-interop owners and their regression tests are unchanged. Upstream source selection and cancellation behavior are retained.

Change and scope

  • Recognize literal standalone module-table bootstraps and substitute lexical exports, wrapper arguments, returned closures, object members/spreads, and IPC callback parameters without evaluating target code.
  • Emit contextual candidate paths with source ranges and guard expressions; join only unique compatible literal channels. Ambiguous handlers, reassigned bindings, unknown spreads, and unsupported values remain unresolved.
  • Prioritize discovered boundary paths during semantic projection. Add explicit total/per-file node controls while preserving the 100,000/20,000 defaults and independent worker/parent memory admission.
  • Use upstream main's sequential next-checkpoint reserve unchanged; remove this PR's superseded reserve helper. Scale streamed transfer capacity with parent admission while retaining the 8 MiB record limit and a 2 GiB file ceiling.
  • Preserve distinct class/getter origins during mutation-path pruning. Retain upstream's newer general alias-cycle termination logic.

Review fixes

  • Ambiguous handler selection: expand a handler only when its symbolic value contains exactly one function and no unresolved alternative. Keep an unresolved channel registration so it still prevents a false unique pairing with another handler.
  • Nullish short-circuiting: share right-operand selection across value substitution, callback traversal, and seed traversal. Known non-nullish values (including false, 0, and "") exclude the fallback; nullish values select it; unknown values retain a nullish guard.
  • Factory return alternatives: retain both branches of an unknown condition. Return collection tracks fallthrough separately, includes implicit undefined, and excludes statements after all branches definitely exit.
  • Added public CLI and stdio MCP checks for the resulting application graph, plus source cases for nested branches, definite exits, nullish guards, and handlers with an unresolved alternative. The new regression cases first reproduced 12 failures before the fixes.

Contract and boundary impact

  • Semantic owner and earliest changed stage: domain JavaScript bootstrap/binding analysis, then application graph projection and feature tracing.
  • CLI and MCP/tool-catalog contract: optional max_semantic_nodes and max_semantic_nodes_per_file (CLI: --max-semantic-nodes, --max-semantic-nodes-per-file), integers from 1 through 1,000,000. Explicit choices are retained in Evidence parameters; omitted choices remain absent.
  • Provider, bridge, target-format, or platform compatibility: static JavaScript/Electron analysis; no runtime provider or native bridge changes. Current Node/Bun platform-specific worker enforcement is preserved.
  • Evidence, artifact, provenance, or reconstruction contract: optional electron.call_paths, resolution_basis: "wrapper-substitution", and contextual javascript-expression graph nodes. New paths and IPC joins are inferred candidates; runtime execution and guard acceptance remain unverified. Resource exhaustion is reported in coverage.
  • Process execution, authorization, cleanup, or containment impact: existing isolated analysis worker, cancellation, and owned cleanup remain in use. Target JavaScript is never executed.
  • Generated metadata, package, or installation impact: owning documentation updated; ignored catalogs regenerated and checked locally. No dependency, package-version, or installation changes; no generated output committed.

Evidence and regression coverage

  • On base d3e9ee5505251f760666bb8e1e6c295b6d6aedb2, the wrapper and reference-lifetime regression files produced 5 failures / 115 passes: four missing wrapper-path behaviors and the getter escape case. The corresponding tests pass with this patch.

  • A compiled public CLI test runs analysis and then trace-application-feature using the complete returned Evidence and only the desktop.copy seed. It asserts the path, guards, inferred authority, and separation from desktop.cut; a competing untraced handler prevents pairing.

  • Additional coverage exercises bootstrap syntax, shadowing/overwrites, helper-name spoofing, definite throws/returns, explicit node limits across files, transfer admission, IPC provenance, cancellation, and MCP resource recovery.

  • Notion 7.37.1 macOS arm64: the two unchanged distributed bundles (.webpack/main/index.js and .webpack/renderer/tab_browser_view/preload.js) were analyzed with the public CLI, using a 6,144 MiB worker heap, 24,576 MiB parent old-space budget, 750,000 total nodes, and 700,000 nodes per file. No Notion binaries or source files are included in this PR.

  • Verified analysis result: 651,734 semantic nodes / 635,848 relations, both files parsed, zero parse failures, truncated: false, zero omitted nodes/relations, and no resource limits. Analysis exited successfully in 105.4 s. The 220,735 dynamic/ambiguous facts remain unknown; overall semantic coverage is still unknown.

  • Passing the complete returned Evidence to trace-application-feature with only the API seed __electronApi.copy and match: "contains" recovered all three candidate paths below (63.292 s, exit 0). The source hashes, every directed edge, guard evidence, and unique literal notion:copy join were independently checked against the saved CLI output.

Entry Terminal Nodes / edges
__electronApi.copy ipc-event.sender.copy 15 / 14
__electronApi.copyText navigator.clipboard.writeText 3 / 2
__electronApi.copyImage navigator.clipboard.write 5 / 4

Input SHA-256 digests (for reproducibility):

main/index.js: 9dda511b87214c82b06e90b232f5e10db07bd4581f8747251199dc3dd2a34aa0
tab_browser_view/preload.js: dee77f63b2f50333a36bbc711a8f54e416b121d96f8278f53627eb00ce9bac38
  • Remaining proof gaps: static candidates do not establish actual Notion UI/clipboard execution, accepted senders, OS implementation, or client reimplementation. Dynamic JavaScript unknowns remain explicitly reported.

  • 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

  • npm run test:focused -- … across 91 JavaScript/Electron source, filesystem, CLI, worker, MCP, and acceptance test files: 1,548 tests passed on macOS arm64, Node 24.18.0 / npm 11.16.0.
  • npm run check: passed, including typecheck, lint, formatting, knip, metadata, module boundaries, and architecture guards.
  • npm run docs:check: passed.
  • npm run verify:test-discovery: all 892 test files discovered exactly once.
  • git diff origin/main --check: passed. The committed tree exactly matches the tested tree; working tree is clean.
  • Real artifact analysis and feature trace: results above, performed through the compiled public CLI on the PR implementation.

Compatibility, safety, and release

  • Breaking changes or migration steps: no existing invocation needs migration. New optional fields and a new application-node kind are documented above. Existing resource defaults remain unchanged.
  • Real Hopper/Ghidra, browser, or OS coverage: not exercised; this changes static Electron/JavaScript analysis. Linux, Windows, Bun, and actual Notion UI behavior were not independently exercised locally.
  • Package or release metadata impact: none.
  • Security, privacy, process, or containment review: source is parsed inertly; IPC pairing remains inferred and guards are retained. No proprietary fixtures, credentials, local evaluation output, or build artifacts are committed.

Review checklist

  • This PR addresses a concrete problem or an agreed enhancement.
  • 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.

@chatgpt-codex-connector

chatgpt-codex-connector Bot commented Oct 11, 2026 •

Copy link
Copy Markdown

Codex Review Summary

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

Review Status Commit Review trigger
📝 Code Review ✅ Completed 2026-10-12T01:33:18.733389Z cfc32c4 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.

@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: 1017d61dbe

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

Comment on lines +142 to +144
const fn = symbolicVariants(
args[1] ?? symbolicUnknown("missing handler"),
).find((v): v is SymbolicFunction => v.kind === "function");

Copy link
Copy Markdown

Choose a reason for hiding this comment

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

P2 Badge Reject ambiguous IPC handler variants

When a wrapped registration receives a conditional or otherwise union-valued handler (for example, register("copy", flag ? copy : cut)), .find(...) silently chooses the first function variant. The analyzer then emits one literal handler finding and can classify the channel as uniquely paired, producing a caller-to-handler edge for only one of the possible callbacks instead of leaving the handler ambiguous. Require exactly one function variant (and no unresolved variants), or retain all variants as ambiguity.

AGENTS.md reference: AGENTS.md:L17-L17

Useful? React with 👍 / 👎.

Comment on lines +347 to +350
if (
(node.operator === "&&" && truth === false) ||
(node.operator === "||" && truth === true)
)

Copy link
Copy Markdown

Choose a reason for hiding this comment

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

P2 Badge Respect nullish coalescing before walking the right operand

When a handler contains a statically non-nullish left operand such as "ready" ?? event.sender.copy(), this short-circuit check handles only && and ||, so it walks the right side and emits an impossible terminal path. Unknown ?? operands are also annotated using truthiness rather than nullishness. Handle ?? using whether the symbolic literal is null/undefined, and leave genuinely unknown nullish state unresolved.

Useful? React with 👍 / 👎.

Comment on lines +457 to +458
const branch =
truth === false ? statement.alternate : statement.consequent;

Copy link
Copy Markdown

Choose a reason for hiding this comment

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

P2 Badge Evaluate both returns when a condition is unknown

When a wrapper uses if (flag) return first; else return second; and flag is symbolic/unknown, this expression always selects the consequent because truth !== false; the alternate is never evaluated. As a result, only first can be connected to an exposed bridge member and the valid second call path disappears without being represented as unknown. Union the return values from both branches when the condition cannot be resolved.

AGENTS.md reference: AGENTS.md:L17-L17

Useful? React with 👍 / 👎.

@morluto
morluto merged commit 87b9793 into morluto:main Oct 12, 2026
2 checks passed
@morluto

morluto commented Oct 12, 2026

Copy link
Copy Markdown
Owner

This is great work, thank you!

@github-actions github-actions Bot mentioned this pull request Oct 12, 2026
3 tasks done

@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: cfc32c4421

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

location,
};
if (existing)
existing.value.members.length === 0 &&

Copy link
Copy Markdown

Choose a reason for hiding this comment

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

P2 Badge Preserve direct empty bridge observations

For a direct exposeInMainWorld("desktop", {}) call, the syntax pass has already recorded an exact object-literal observation with zero members, but this length check treats it as unresolved and replaces it with the symbolic finding (api_status: "dynamic", resolution_basis: "wrapper-substitution"). The graph consequently downgrades observed source syntax to inferred evidence even though no wrapper was involved; only replace an existing finding when its status/unknown count actually indicates unresolved input.

AGENTS.md reference: AGENTS.md:L5-L5

Useful? React with 👍 / 👎.

Comment on lines +389 to +392
const initializer =
binding.initializers.length === 1 ? binding.initializers[0] : undefined;
if (!initializer)
return symbolicUnknown("missing or ambiguous initializer");

Copy link
Copy Markdown

Choose a reason for hiding this comment

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

P2 Badge Reject initializers that have not executed

When an exposed member reads a variable before its declaration, such as exposeInMainWorld("desktop", {copy}); const copy = () => e.ipcRenderer.send("copy"), this resolves the later initializer without considering the read/call position and emits a desktop.copy path. At runtime the const form throws in the TDZ (and var supplies undefined), so this is an impossible path rather than an execution-unverified candidate; require proof that non-hoisted initializers are available at the relevant invocation point, otherwise retain the member as unresolved.

AGENTS.md reference: AGENTS.md:L23-L23

Useful? React with 👍 / 👎.

Comment on lines +509 to +512
const modules = new Map<string, SymbolicValue>();
for (const property of bootstrap.table.properties) {
const factory = moduleFactory(property);
if (!factory) continue;

Copy link
Copy Markdown

Choose a reason for hiding this comment

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

P2 Badge Invalidate mutated bootstrap module tables

In a recognized bootstrap where modules[id] is overwritten before load(entry) runs, this snapshots every original literal factory into an independent modules map and never associates that map with writes to the actual table binding. For example, replacing the factory that exports Electron with a fake factory still lets consumer modules resolve the original require("electron"), producing bridge/IPC paths that cannot execute; reject or invalidate a bootstrap when its table or indexed slots are mutated.

AGENTS.md reference: AGENTS.md:L23-L23

Useful? React with 👍 / 👎.

Comment on lines +59 to +63
export const symbolicTruth = (value: SymbolicValue): boolean | undefined =>
value.kind === "literal"
? Boolean(value.value)
: ["function", "object", "namespace", "array"].includes(value.kind)
? true

Copy link
Copy Markdown

Choose a reason for hiding this comment

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

P2 Badge Treat symbolic records and loaders as truthy

Inside a recovered module factory, record represents the concrete module object and loader represents its loader function, so both are always truthy. Omitting them here makes expressions such as module || event.sender.copy() unresolved; the call-path walker then follows the right operand with a !(module) guard and emits an impossible terminal path. Include these known object/function kinds in the truthy set, as the nullish helper already does.

Useful? React with 👍 / 👎.

Comment on lines +347 to +351
return truth === undefined
? symbolicUnion([
this.evaluate(node.consequent, env),
this.evaluate(node.alternate, env),
])

Copy link
Copy Markdown

Choose a reason for hiding this comment

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

P2 Badge Retain predicates on symbolic branch unions

For an exposed member such as {action: flag ? copy : cut}, the new union now retains both callbacks, but it strips the selecting predicate from each variant. The bridge walker therefore emits both IPC paths with conditions: [], losing the guard that distinguishes flag from !flag; carry branch provenance into the variants (or leave the member unresolved) so feature traces preserve the condition attached to each candidate.

AGENTS.md reference: AGENTS.md:L17-L17

Useful? React with 👍 / 👎.

Comment on lines +60 to +63
Math.min(
MAX_TRANSFER_BYTES,
Math.max(TRANSFER_BYTES, Math.floor(resultBudgetBytes / 8)),
);

Copy link
Copy Markdown

Choose a reason for hiding this comment

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

P2 Badge Apply scaled transfer budget during module preflight

When parent admission permits a transfer above 512 MiB and the semantic module rows themselves exceed 512 MiB, this larger budget is only used by the final writer. measureJavaScriptModuleTransfer runs first and calls encodeTransferRecord with its unchanged 512 MiB default, so analysis fails before the advertised scaled (up to 2 GiB) transfer can be used; thread the same computed byte budget through module measurement.

AGENTS.md reference: AGENTS.md:L44-L44

Useful? React with 👍 / 👎.

@morluto morluto added bug Something isn't working area: native Native analysis and decompilation, including Ghidra, IDA, and Hopper analysis behavior labels Oct 14, 2026
@morluto morluto added the provider: electron Analysis provider / engine: electron label Nov 23, 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 provider: electron Analysis provider / engine: electron

Projects

None yet

Development

Successfully merging this pull request may close these issues.

2 participants