Skip to content

fix(ext/node): improve module hooks (registerHooks + register) - #33859

Closed
bartlomieju wants to merge 10 commits into
mainfrom
fix/module-hooks-improvements
Closed

bartlomieju wants to merge 10 commits into
mainfrom
fix/module-hooks-improvements

Conversation

@bartlomieju

Copy link
Copy Markdown
Member

Summary

Fixes multiple issues with module.registerHooks() and module.register() to
pass 10 more Node.js compatibility tests (25 -> 35 out of 62 test-module-hooks
tests).

Changes

deno_core: pump event loop during module loading

  • load_main_es_module and load_side_es_module now interleave event loop
    ticks with module load polling, preventing deadlocks when module.register()
    load hooks are active. Previously, the Rust module loader would push load
    requests to the JS hook queue but the event loop wasn't running to process
    them.

Resolve hook deduplication

  • deno_core calls resolve() twice for each dynamic import (fast-path cache
    check + RecursiveModuleLoad). Added in-flight tracking in
    LoaderHookRegistry so hooks are invoked exactly once per
    specifier+referrer pair.

ESM load hook chain fixes

  • nextLoad in executeEsmLoadHookChain is now synchronous (was async),
    fixing sync hooks from registerHooks() that got a Promise instead of the
    return value.
  • End-of-chain nextLoad now reads the file from disk instead of returning
    { source: null }, so hooks can transform the source.

Builtin module handling

  • Module._load now detects bare builtin names (e.g. 'zlib') in addition
    to 'node:zlib', so load hooks can intercept builtins.
  • Resolve hooks returning node: URLs now strip the prefix for builtins in
    _resolveFilename, matching Node.js behavior for require.resolve().

Error propagation for register()

  • Rejected hook module load promises are re-thrown instead of silently
    swallowed, so loader errors cause non-zero exit codes.

--experimental-loader translation

  • node_shim now translates --experimental-loader to
    --preload=data:...,import{register}from"node:module";register("URL"),
    enabling Node.js compat tests that spawn child processes with loader flags.

Test plan

  • ./x test-compat test-module-hooks — 35/62 passing (was 25/62)
  • ./x test-compat test-async-loader — 3/48 passing (was 4/48, -1 net due to
    removing false positives that passed without actually loading hooks)
  • Updated tests/node_compat/config.jsonc with newly passing tests and removed
    false positives

- Deduplicate ESM resolve hook calls: deno_core calls resolve twice for
  dynamic imports (fast-path check + RecursiveModuleLoad). Track
  in-flight requests in LoaderHookRegistry and fulfill piggybacking
  waiters from the first response, so hooks are invoked exactly once.

- Fix ESM load hook chain: make nextLoad synchronous so sync hooks
  (from registerHooks) get the return value directly instead of a
  Promise. Read file from disk at end-of-chain instead of returning
  null, matching the CJS load hook behavior.

- Fix builtin detection in Module._load: detect bare builtin names
  (e.g. 'zlib') in addition to 'node:zlib', so load hooks can
  intercept builtins even when _resolveFilename returns the bare name.

- Propagate register() loader errors: re-throw rejected hook module
  load promises so they surface as unhandled rejections instead of
  being silently swallowed.

- Translate --experimental-loader to --preload with module.register()
  in node_shim, so Node.js compat tests that spawn child processes
  with --experimental-loader work correctly.
…lock

When module.register() activates load hooks, subsequent module loading
via load_main_es_module/load_side_es_module would deadlock because the
Rust module loader pushes load requests to a queue that requires the
JS event loop to process (via op_module_hooks_poll_load), but the
event loop wasn't running during module loading.

Fix by interleaving event loop ticks with module load polling in
load_main_es_module and load_side_es_module. Uses raw isolate pointers
(same pattern as poll_event_loop) to avoid borrow conflicts between
the module load future and the event loop pump.
Add 10 newly passing tests, remove 4 false positives that only
passed because --experimental-loader was silently ignored.
When a resolve hook returns a node: URL (e.g. 'node:zlib'),
_resolveFilename should strip the prefix for builtin modules so that
require.resolve() returns the bare name (e.g. 'zlib'), matching
Node.js behavior.
Make nextResolve in executeEsmResolveHookChain synchronous (was async)
so sync hooks from registerHooks() get the return value directly.
Resolve specifiers at end-of-chain using URL resolution for relative
paths and Module._resolveFilename for bare specifiers, so hooks can
inspect the resolved URL.

@fibibot fibibot left a comment

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.

Substantial follow-up to #33849 with several real improvements: error-swallowing in register() rejection handler is now throw err (this was my prior concern at df440a13 — ✓), sync nextResolve/nextLoad correctly preserve sync semantics for registerHooks() consumers, end-of-chain nextLoad reads from disk so hooks can transform source, and resolve hook deduplication via resolve_waiters correctly handles deno_core's double-resolve pattern.

One CI blocker, three substantive concerns inline.

CI

3 fail, 57 pass, 27 pending.

  • lint debug linux-x86_64 fails with [1m[91merror[0m: 'allow' attribute without specifying a reason at ext/node/ops/module_hooks.rs:58:3 — the new #[allow(clippy::type_complexity)] on resolve_waiters needs reason = "..." to satisfy the project's allow_attribute_without_reason lint. Trivial: #[allow(clippy::type_complexity, reason = "map of compound key to vec of senders")].
  • The other 27 are pending.

Substantive concerns

Three things worth a closer look — all inline. The most load-bearing is the unsafe raw-pointer borrow split in jsruntime.rs:2900-2939; that's the kind of pattern where a subtle error doesn't show up in CI but breaks under specific event-loop reentrance scenarios. The --experimental-loader data URL has a small JS-injection surface for URLs containing ", and the resolve dedup has a subtle invariant about user-driven concurrency.

Nice work overall — the surface improvement here (10 more test-module-hooks passing) is meaningful for Node-compat parity.

// pattern as poll_event_loop). These never overlap temporally.
let isolate_ptr = self.v8_isolate_ptr();
let self_ptr = self as *const Self;
let isolate_raw: *mut v8::OwnedIsolate = &mut *self.inner.v8_isolate;

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.

The SAFETY comment claims the load future and event-loop pump "never overlap temporally" within each poll_fn iteration. That's plausible but worth a closer audit because the failure mode is the kind that doesn't show up in CI but blows up under specific reentrance:

  • poll_event_loop_inner runs ops via OpDriver::poll_ready_ops, which can resolve a pending future that was waiting on V8 (e.g., a microtask scheduled inside a previously-loaded module).
  • The load_fut (calling load_main_es_module_from_code) borrows &mut isolate_raw and walks the dependency graph; the on_module callback hits the v8 isolate during the synchronous portion of its poll.
  • If poll_event_loop_inner runs an op that re-enters JsRuntime::load_*_es_module (e.g., a userland resolve hook that itself imports a side module), we get nested &mut Isolate borrows through different raw pointers — UB.

The "same pattern as poll_event_loop" framing skips a non-trivial audit step: poll_event_loop in production code never has a sibling load future polling the same isolate. This is a new shape.

Minimum I'd want before merge: a runtime invariant or assertion (e.g., a thread-local recursion-counter on load_*_es_module) that prevents nested module-load entry, plus a comment example of when this could fire and why it's safe. Even a debug_assert! would surface the bug if it ever happens.

Comment thread libs/node_shim/lib.rs
deno_args.push(format!(
"--preload=data:text/javascript,import%7Bregister%7Dfrom%22node:module%22;register(%22{}%22)",
escaped
));

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.

JS-injection surface here: the loader URL is interpolated into a JS string literal inside a data URL. The escaping handles % and # but not ":

let escaped = loader.replace('%', "%25").replace('#', "%23");
// ...
format!("--preload=data:text/javascript,import%7Bregister%7Dfrom%22node:module%22;register(%22{}%22)", escaped)

A loader URL containing " (legal in some URL contexts via percent-encoding, or any user-controlled input that could pass through here) would break out of the JS string and execute attacker-controlled code with the same permissions as the spawned Deno process.

File URLs in practice don't contain raw ", but the function takes &env_opts.userland_loaders which could in principle be any string. Defense-in-depth: percent-encode " as %22 too, or — better — use base64-encode the entire register('URL') JS payload so the URL never appears in interpretable text:

let payload = format!("import{{register}}from\"node:module\";register({})", json_string_quote(loader));
let b64 = base64::encode(&payload);
format!("--preload=data:text/javascript;base64,{}", b64)

Low severity in practice (loaders come from CLI args, not network input), but the JS-injection shape itself is something we'd flag if it appeared in any other context.

.borrow_mut()
.get_mut(&key)
.unwrap()
.push(sender);

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.

Subtle invariant in the resolve-dedup logic: resolve_waiters.contains_key(&key) collapses ALL concurrent calls with the same (specifier, referrer) into a single hook invocation, fulfilling all of them with the first response.

The doc-comment explains this is for deno_core's double-resolve case (fast-path + RecursiveModuleLoad). But the code doesn't check WHO the second caller is — any user-driven concurrent dynamic-import of the same (specifier, referrer) pair will also get deduplicated.

This is probably fine because the resolution should be deterministic for a given input pair, but two concerns:

  1. A hook with side effects (e.g., logging, metrics, non-deterministic timestamps) will fire once for two semantically-distinct user calls. Surprising behavior, though arguably the user shouldn't have side-effecting resolve hooks.
  2. A hook that returns a result that's consumed by mutation (e.g., a Result<&mut Foo, _>) is shared across waiters. Looking at result.clone() — it's Result<Option<String>, String> so cloning is fine. Just want to confirm this remains the type.

Optional: distinguish deno_core's internal double-call from user concurrency. The internal pattern has a known temporal shape (both calls come in within the same V8 tick before any await yields), so a fast-path TTL on the dedup entry would scope it correctly. Not blocking — just want this on the radar.

- ESM resolve hook nextResolve now provides default resolution at
  end-of-chain (URL resolution for relative paths, Module._resolveFilename
  for bare specifiers with re-entry guard), so hooks can inspect the
  resolved URL.
- Invalidate relativeResolveCache when hooks are registered/deregistered,
  preventing stale cached resolutions from bypassing hooks.
When a load hook returns format "commonjs" or the specifier is detected
as CJS (via file extension or package.json), fall through to the default
module loader which handles CJS-to-ESM translation. Previously, CJS
source was always evaluated as ESM, causing "exports is not defined"
errors.

Also pass format from JS load loop to Rust via op_module_hooks_respond_load
so the Rust side can make format-aware decisions.
@bartlomieju

Copy link
Copy Markdown
Member Author

Superseded by #33906 which includes the worker-thread architecture for register() hooks.

@bartlomieju bartlomieju closed this May 7, 2026
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Labels

None yet

Projects

None yet

Development

Successfully merging this pull request may close these issues.

2 participants