Skip to content

inspector: CDP on --inspect, node announce lines, Session, Profiler adapter, Network, exit handshake, async stacks (+9 tests, inspector 11%→22%) - #34719

Open
cirospaciari wants to merge 196 commits into
mainfrom
claude/inspector-cdp-on-cli
Open

cirospaciari wants to merge 196 commits into
mainfrom
claude/inspector-cdp-on-cli

Conversation

@cirospaciari

@cirospaciari cirospaciari commented Jul 19, 2026 •

Copy link
Copy Markdown
Member

Serves node's Chrome DevTools Protocol endpoint additively on bun --inspect*, so node inspector clients and the vendored upstream inspector tests can attach. The JSC protocol path (debug.bun.sh, VS Code extension) is untouched — both banners print, driven end-to-end to verify. Adds 9 vendored upstream tests (a larger set was staged and then held back pending exception-validator work; only in-tree files are counted, per the vendor-only-passing policy).

Stacked on #31823.

What changed

  • CDP endpoint on the same port: /json/list, /json/version, NodeRuntime domain, node's announce lines (Debugger listening on ws://... / For help, see...).
  • node:inspector Session (connect/post/disconnect, in-process backend), plus the CDP adapter: breakpoints with re-resolution and Debugger.breakpointResolved on pre-parse re-set, callFunctionOn, evaluateOnCallFrame, async stack traces, script positions.
  • Profiler domain adapter (Profiler.start/stop → real .cpuprofile payloads) and Network domain events for fetch.
  • Exit handshake: NodeRuntime.waitingForDebugger / Runtime.runIfWaitingForDebugger, so --inspect-brk and --inspect-wait interoperate with node's test helper.
  • Remote and in-process frontends coexist: disjoint backend-id ranges, deferred in-process detach when the last remote frontend leaves.
  • Two prerequisites: the Sec-WebSocket-Key length gate is relaxed only for the internal debugger server (uWS routes short keys away from the upgrade path; a plain Bun.serve still refuses them — verified both ways), and the inspector additively binds the loopback family the primary listener didn't take, because node's helper dials IPv4.

Verification

The 30 common/inspector-helper.js tests went from 21 hangs to zero; converted files run verbatim, 3x each, tamper-checked. inspector.test.ts, the CDP suites, and the profiler suites pass; children of exempted tests strip the exception-validator env, and the two intentional-leak shapes are in leaksan.supp with symbolized stacks recorded.

Compat impact (upstream node v26.3.0 test files vendored, in-tree = passing)

  • node:inspector: 11% → 22% (8 → 17 of 76)

[review] gate passed · iteration 39 · 35 files touched

fails on main (without fix)
ASAN without fix: 18 FAILED
$ BUN_DEBUG_QUIET_LOGS=1 bun scripts/build.ts --profile=debug --quiet test "--reporter=junit" "--reporter-outfile=/tmp/mechgate.xml" test/js/node/inspector/inspector-profiler.test.ts test/js/node/inspector/inspector.test.ts
bun test v1.4.1 (4448a2e21)

test/js/node/inspector/inspector-profiler.test.ts:
(pass) node:inspector > Session > Session is a constructor [15.18ms]
(pass) node:inspector > Session > Session extends EventEmitter [2.77ms]
(pass) node:inspector > Session > connect() establishes connection [6.07ms]
(pass) node:inspector > Session > connect() throws if already connected [4.08ms]
(pass) node:inspector > Session > connectToMainThread() throws ERR_INSPECTOR_NOT_WORKER on the main thread [4.78ms]
(pass) node:inspector > Session > disconnect() closes connection cleanly [2.83ms]
(pass) node:inspector > Session > disconnect() is a no-op if not connected [2.36ms]
(pass) node:inspector > Session > post() throws if not connected [9.25ms]
214 |     });
215 | 
216 |     test("post() with callback throws synchronously if not connected", async () => {
217 |       // Node throws ERR_INSPECTOR_NOT_CONNECTED synchronously and never calls the callback.
218 |       let
... (truncated)

release without fix: 18 FAILED
bun test v1.4.0-canary.1 (4448a2e21)

test/js/node/inspector/inspector-profiler.test.ts:
(pass) node:inspector > Session > Session is a constructor [0.25ms]
(pass) node:inspector > Session > Session extends EventEmitter [0.04ms]
(pass) node:inspector > Session > connect() establishes connection [0.11ms]
(pass) node:inspector > Session > connect() throws if already connected [0.09ms]
(pass) node:inspector > Session > connectToMainThread() throws ERR_INSPECTOR_NOT_WORKER on the main thread [0.08ms]
(pass) node:inspector > Session > disconnect() closes connection cleanly [0.04ms]
(pass) node:inspector > Session > disconnect() is a no-op if not connected [0.02ms]
(pass) node:inspector > Session > post() throws if not connected [0.15ms]
214 |     });
215 | 
216 |     test("post() with callback throws synchronously if not connected", async () => {
217 |       // Node throws ERR_INSPECTOR_NOT_CONNECTED synchronously and never calls the callback.
218 |       let called = false;
219 |       expect(() => session.post("Profiler.enable", () => (called = true))).toThrow("not connected");
                                                                                 ^
error: ex
... (truncated)
passes on PR (with fix)
ASAN with fix: all passed
$ BUN_DEBUG_QUIET_LOGS=1 bun scripts/build.ts --profile=debug --quiet test "--reporter=junit" "--reporter-outfile=/tmp/mechgate.xml" test/js/node/inspector/inspector-profiler.test.ts test/js/node/inspector/inspector.test.ts
bun test v1.4.1 (4448a2e21)

test/js/node/inspector/inspector-profiler.test.ts:
(pass) node:inspector > Session > Session is a constructor [16.31ms]
(pass) node:inspector > Session > Session extends EventEmitter [2.76ms]
(pass) node:inspector > Session > connect() establishes connection [5.92ms]
(pass) node:inspector > Session > connect() throws if already connected [4.36ms]
(pass) node:inspector > Session > connectToMainThread() throws ERR_INSPECTOR_NOT_WORKER on the main thread [5.18ms]
(pass) node:inspector > Session > disconnect() closes connection cleanly [2.84ms]
(pass) node:inspector > Session > disconnect() is a no-op if not connected [2.54ms]
(pass) node:inspector > Session > post() throws if not connected [7.64ms]
(pass) node:inspector > Session > post() with callback throws synchronously if not connected [13.82ms]
(pass) node:inspector > Profiler > Profiler.enable succeeds [32.40ms]
(pass) node:inspector > Profiler > Profiler.disable s
... (truncated)

release with fix: all passed
$ bun scripts/build.ts --profile=release
[configured] bun-profile → bun (stripped)
  target       linux-x64-gnu
  build type   Release
  build dir    ./build/release
  revision     be14532db5
  features     baseline

23 deps, 129 codegen, 1172 objects in 1343ms

ninja: Entering directory `/workspace/bun/build/release'
[1/1244] gen bindgenv2
[2/1244] gen ErrorCode+*.h
[3/1244] gen bake.{client,server,error}.js
-> bake.client.js, bake.server.js, bake.error.js
[4/1244] gen .bind.ts → GeneratedBindings.cpp
[5/1244] gen JSBuffer.lut.h
Generating /workspace/bun/build/release/codegen/JSBuffer.lut.h from /workspace/bun/src/jsc/bindings/JSBuffer.cpp
[6/1244] fetch zlib
[zlib] up to date
[7/1244] fetch tinycc
[tinycc] up to date
[8/1243] gen ZigGeneratedClasses.{cpp,h,rs}
Found 2 classes from /workspace/bun/src/jsc/resolve_message.classes.ts
  - ResolveMessage (15 fields)
  - BuildMessage (10 fields)
Found 1 classes from /workspace/bun/src/runtime/api/Archive.classes.ts
  - Archive (4 fields, 1 class fields)
Found 2 classes from /workspace/bun/src/runtime/api/BunObject.classes.ts
  - ResourceUsage (8 fields)
  - Subprocess (20 fields)
Found 1 classes from /workspace/bun/s
... (truncated)
diff hotspot
.gitignore                                         |    1 +
 packages/bun-uws/src/App.h                         |    3 +-
 src/js/internal/debugger.ts                        |  293 ++++--
 src/js/internal/inspector/cdp.ts                   | 1058 ++++++++++++++++---
 src/js/node/inspector.promises.ts                  |    4 +-
 src/js/node/inspector.ts                           | 1065 ++++++++++++++++----
 src/jsc/Debugger.rs                                |   98 +-
 src/jsc/VirtualMachine.rs                          |    2 +
 src/jsc/bindings/BunDebugger.cpp                   |  552 ++++++++--
 src/jsc/bindings/BunDebugger.h                     |    3 +
 src/jsc/bindings/BunProcess.cpp                    |   13 +-
 src/jsc/bindings/NodeVM.cpp                        |    4 +-
 src/runtime/server/WebSocketServerContext.rs       |    5 +
 src/runtime/server/server_body.rs                  |    9 +-
 src/uws_sys/WebSocket.rs                           |    3 +
 src/uws_sys/_libusockets.h                         |    1 +
 src/uws_sys/libuwsockets.cpp                       |    2 +
 test/js/node/inspector/inspector-profiler.test.ts  |  202 ++--
 test/js/node/inspector/inspector.test.ts           |  713 ++++++++++++-
 test/js/node/test/common/debugger.js               |   31 +-
 .../node/test/parallel/test-debugger-backtrace.js  |    2 +-
 test/js/node/test/parallel/test-debugger-exec.js   |    2 +-
 .../test/parallel/test-debugger-invalid-json.mjs   |    4 +-
 .../node/test/parallel/test-debugger-low-level.js  |    2 +-
 .../test/parallel/test-debugger-repeat-last.js     |    4 +-
 .../test/parallel/test-debugger-restart-message.js |   12 +-
 .../parallel/test-inspector-console-top-frame.js   |   31 +
 .../node/test/parallel/test-inspector-heapdump.js  |   29 +
 .../test/parallel/test-inspector-host-warning.js   |   16 +
 .../parallel/test-inspector-invalid-protocol.js    |   40 +
 .../test/parallel/test-inspector-ip-detection.js   |   46 +
 .../parallel/t
... (truncated)

gate history · 38 passed · 5 rejected · iteration 39

evidence per changed file
file                                          reads  edits  tests
.gitignore                                        0      0      0
packages/bun-uws/src/App.h                        1      0      0
src/js/internal/debugger.ts                      11     10      0
src/js/internal/inspector/cdp.ts                 24     20      0
src/js/node/inspector.promises.ts                 0      0      0
src/js/node/inspector.ts                         25     21      0
src/jsc/Debugger.rs                               7      5      0
src/jsc/VirtualMachine.rs                         0      0      0
src/jsc/bindings/BunDebugger.cpp                 19     20      0
src/jsc/bindings/BunDebugger.h                    0      0      0
src/jsc/bindings/BunProcess.cpp                   2      1      0
src/jsc/bindings/NodeVM.cpp                       0      0      0
src/runtime/server/WebSocketServerContext.rs      1      1      0
src/runtime/server/server_body.rs                 1      0      0
src/uws_sys/WebSocket.rs                          0      0      0
src/uws_sys/_libusockets.h                        0      0      0
(+ 19 more files)

cirospaciari and others added 30 commits June 29, 2026 15:36
…spector tests

Bun has no V8/CDP inspector: node:inspector is a stub (Profiler API only)
and there is no CDP endpoint, but process.features.inspector claimed true.
That sent feature-detecting code (and node's test suite) down a path that
hangs or throws. Report false so consumers take the no-inspector path,
matching a node build compiled --without-inspector.

- BunProcess.cpp: features.inspector -> false
- run_command.rs: emit node's "inspector is disabled, coverage could not
  be collected" warning when NODE_V8_COVERAGE is set instead of silently
  ignoring it
- inspector.ts: implement Runtime.enable/disable and emit
  Runtime.consoleAPICalled notifications to in-process Sessions while the
  Runtime domain is enabled (console hooks, node-shaped RemoteObjects)
- port all 77 missing test-*inspector* tests (74 parallel + 3 sequential)
  from node v26.3.0 plus fixtures; sync common/inspector-helper.js; add
  common/repl.js and common.skipIfSQLiteMissing
- adapt test-inspector-has-inspector-false to the public no-inspector
  surface (bun does not expose internal/util/inspector), skip
  test-repl-preview-without-inspector (REPLServer unimplemented), fix the
  overwrite-config Flags path for the vendored tree layout

All 84 inspector parallel+sequential tests pass; the 11 other tests using
skipIfInspectorDisabled and bun's node:inspector unit tests still pass.

Co-Authored-By: Claude Opus 4.8 <noreply@anthropic.com>
Review follow-ups: a Runtime.consoleAPICalled listener that itself logs
re-entered the console hook and recursed to stack overflow (Node is
immune because V8 dispatches notifications via the message pump); and
the notification object was shared across sessions, so one listener
mutating it contaminated the next session's payload. Console calls from
inside a listener now run the original method without re-emitting, and
each session gets a fresh message. Adds unit tests for both.

Co-Authored-By: Claude Opus 4.8 <noreply@anthropic.com>
…nment

A throwing consoleAPICalled listener propagated out of console.log (the
emit runs before the original method), suppressing the output and
starving later sessions; listener exceptions now surface as process
warnings, matching how Node reports them. removeConsoleHooks() also
restored its saved original unconditionally, clobbering a console
method user code reassigned while the Runtime domain was enabled; it
now only restores slots that still hold the hook. Unit tests for both.

Co-Authored-By: Claude Opus 4.8 <noreply@anthropic.com>
toRemoteObject reads user-controlled toString (a revoked Proxy throws on
Object.prototype.toString), and the message construction sat outside the
per-session try/catch, so a throwing argument still escaped through
console.log. Message construction now lives inside the guard. The
throwing-listener test also now asserts the process warning is actually
delivered (async) instead of capturing it without asserting; adds a
revoked-Proxy argument test.

Co-Authored-By: Claude Opus 4.8 <noreply@anthropic.com>
test-coverage-with-inspector-disabled.js spawns
fixtures/v8-coverage/subprocess, but the fixture was not included when
the test was ported, so the child exited 1 on every platform. Add the
file verbatim from Node v26.3.0 (the fixtures/v8-coverage directory is
gitignored for sync tooling, so the file is force-added).
If a consoleAPICalled listener throws a value for which instanceof or
String() itself throws (e.g. a revoked Proxy), the catch block meant to
isolate listener exceptions would rethrow, making console.log throw.
Fall back to a generic Error when the thrown value cannot be coerced.
Node's Session#onMessage emits the method event first, then the generic
inspectorNotification; ours was reversed, which flips listener firing
order and which event's throwing listener suppresses the other. Swap to
match and assert the order in a test.
…--coverage) (#32476)

**Stacked on #31823** (base branch is
`claude/port-node-inspector-tests`); only the last commit is new.
Retarget to `main` once #31823 lands.

`Profiler.startPreciseCoverage`, `Profiler.takePreciseCoverage`,
`Profiler.stopPreciseCoverage`, and `Profiler.getBestEffortCoverage` on
the in-process `node:inspector` Session now return real V8-format
`ScriptCoverage` data instead of `"Coverage APIs are not supported"`.
This is the API `@vitest/coverage-v8` drives, so `vitest --run
--coverage` (v8 provider) now works under Bun.

Verified end to end against real Node on the same vitest project
(sources with classes, arrows, async functions, switch/loops, partially
covered functions): Bun's coverage report is identical to Node's,
including per-file statement/branch/function/line percentages and the
uncovered line numbers.

```
            Node 26                      Bun (this PR)
math.ts     50 | 75 | 66.66 | 55.55      50 | 75 | 66.66 | 55.55   uncovered 7,15-18
shapes.ts   84.61 | 66.66 | 83.33 | 83.33  same                    uncovered 9,28
```

- `Profiler.startPreciseCoverage` enables JSC's control flow profiler
(the same machinery `bun test --coverage` uses), so everything compiled
afterwards is instrumented. This matches the V8 contract that coverage
collection begins at `startPreciseCoverage` — which is also why
already-compiled scripts don't appear (V8 re-instruments them; JSC
cannot). vitest starts coverage before loading test/source files, so
this does not affect it.
- `Profiler.takePreciseCoverage` (new
`jsFunction_collectPreciseCoverage` in `JSInspectorProfiler.cpp`) walks
the heap for live script executables to enumerate scripts, then reads
basic-block execution counts (`ControlFlowProfiler`) and function ranges
(`FunctionHasExecutedCache`) per source ID.
- The JS layer (`src/js/node/inspector.ts`) reshapes that into V8
`ScriptCoverage`: a whole-script entry, one entry per function whose
first range carries the call count (the function's entry-block count),
block sub-ranges so untaken branches show up as count 0, and a single
count-0 range with `isBlockCoverage: false` for never-executed
functions. `callCount: false` clamps counts to 0/1 and `detailed: false`
drops block granularity.
- URLs match V8's observed behavior: filesystem paths are reported as
`file://` URLs (Node does this even for `vm` scripts whose `filename` is
a plain path — verified against Node 26) and a `//# sourceURL` directive
overrides the script name.
- Error contract checked against Node:
`startPreciseCoverage`/`stopPreciseCoverage` without `Profiler.enable` →
"Profiler is not enabled"; `takePreciseCoverage` without start →
"Precise coverage has not been started." (plain `Error`s, consistent
with the rest of this module; not `ERR_INSPECTOR_COMMAND` since Bun has
no inspector protocol transport here.)
- `Session.disconnect()` stops precise coverage if that session started
it, balancing JSC's enable/disable refcount.

- `inspector.open()` / `--inspect-brk` under vitest still throw
`ERR_NOT_IMPLEMENTED`; a V8-CDP websocket server is a separate, much
larger project.
- Functions whose enclosing module was compiled before
`startPreciseCoverage` are not reported (see above).
- `functionName` is always `""` — JSC's coverage caches don't carry
names. Coverage consumers (ast-v8-to-istanbul, v8-to-istanbul) take
names from the AST, so reports are unaffected.

`test/js/node/inspector/inspector-profiler.test.ts`:
- replaces the "coverage APIs throw not supported" test with the new
error-contract tests
- spawned fixtures asserting call counts (3× called function),
untaken-branch ranges with count 0, never-called functions,
`callCount`/`detailed` flag handling, `file://` URLs for imported
modules, and the vm-script path vitest uses (via
`node:inspector/promises`)

All fail with `USE_SYSTEM_BUN=1` and pass with the debug build (55/55 in
`test/js/node/inspector/`); `test/cli/test/coverage.test.ts` (bun's own
lcov coverage, which shares the control flow profiler) still passes.
Runs the real vitest CLI under Bun against a small fixture project: a plain
--run pass and a --coverage run whose per-file report is asserted against the
numbers the same project produces under Node.js. The coverage provider drives
node:inspector's Profiler precise-coverage API end to end.

Bumps the test workspace's vitest from 0.32.2 to 4.1.9 and adds
@vitest/coverage-v8; the bun:test interop tests that import from vitest
(fake-timers, mock-fn) pass with the new version.
…en(), use ERR_INSPECTOR_* codes

- inspector.waitForDebugger() now blocks until a client sends
  Runtime.runIfWaitingForDebugger even when inspector.open() was called
  without wait, matching Node. The wait resolves through
  BunJSGlobalObjectDebuggable's unpause hook, so Bun__ensureDebugger now
  replaces the default JSGlobalObject controller/debuggable unless a
  frontend is already connected (recreating it then would orphan the
  connection).
- inspector.close() followed by inspector.open() starts a new server
  instead of throwing; the debugger thread handles an "open" control
  message and the resolved-wait flag is reset for the new server.
- The already-activated / not-active errors now carry Node's
  ERR_INSPECTOR_ALREADY_ACTIVATED / ERR_INSPECTOR_NOT_ACTIVE codes.
- The port range error message matches Node's validatePort wording.
- /json/list builds webSocketDebuggerUrl from the request's Host header
  when present, so clients behind a tunnel or port-forward get a usable
  URL.
Plain `vitest --run` trips a pre-existing unchecked exception after
constructEmptyArray when the spawned process inherits
BUN_JSC_validateExceptionChecks=1, so the suite produced no output on the
ASAN CI job. Also assert a combined exitCode/stderr/stdout object first so
a failed vitest run shows its stderr in the diff.
Node's inspector rejects other hostnames on its discovery endpoints, so
reflecting an arbitrary Host header would both diverge from Node and let a
request inject content into the response. Other hostnames now fall back to
the bind address.
src/jsc/ErrorCode.rs mirrors ErrorCode.ts by index, so inserting
ERR_INSPECTOR_ALREADY_ACTIVATED / ERR_INSPECTOR_NOT_ACTIVE in the middle of
the list shifted every later code's discriminant and made Rust-thrown errors
resolve to the wrong constructor and code (seen as widespread unrelated test
failures on CI). The new codes now go at the end of both tables, like other
recently added codes, leaving existing discriminants unchanged.
V8's Profiler agent stops precise coverage when the domain is disabled;
without this the control-flow profiler kept instrumenting newly-compiled
code and the session's coverage flag stayed set.
A failed first open() (port in use) never registered the debugger thread's
control callback, so every later open() threw ERR_INSPECTOR_ALREADY_ACTIVATED
with no way to recover. The callback is now registered on the failure path
too, letting a later open() start a new server on the same debugger thread.
With BUN_DESTRUCT_VM_ON_EXIT=1 the spawned vitest process trips a
pre-existing leak in NAPI env teardown: NapiEnv::addCleanupHook leaks the
cleanup-hook set's bucket array when a NAPI module registers an env cleanup
hook, and vitest loads @rollup/rollup-linux-x64-gnu which does. The leak is
unrelated to the inspector changes in this branch.
The features.inspector comment and the inspector.ts header still described
node:inspector as a Profiler-only stub with no CDP endpoint; describe the
implemented surface and the actual reason the feature flag stays false
(breakpoint pausing is not supported yet).
…ugger

Debugger.setBreakpointsActive triggers Debugger::setBreakpointsActivated →
recompileAllJSFunctions → vm.deleteAllCode, which iterates each
ScriptExecutable subspace's clearableCodeSet and calls clearCode. For
ModuleProgramExecutable, clearCode drops m_unlinkedCodeBlock and
m_moduleEnvironmentSymbolTable; the next executeModuleProgram (a
top-level-await resume, or a linked-but-not-yet-evaluated module)
regenerates the unlinked code block under the now-different
CodeGenerationMode::Debugger, whose module-environment / generator-frame
layout no longer matches the live JSModuleEnvironment, and the next
op_put_to_scope writes past it (debug builds assert isValidScopeOffset in
JSLexicalEnvironment::variableAt; release builds corrupt memory). This is
the invariant documented in JSC's UnlinkedModuleProgramCodeBlock.h.

Module bodies execute once, so dropping their unlinked code block here
cannot recover debug hooks for the body anyway — inner functions are
recompiled independently via Heap::deleteAllUnlinkedCodeBlocks. Bun now
removes every module executable from the heap's clearableCodeSet before
dispatching each batch of inspector messages (via vm.whenIdle so it runs
ahead of any deferred deleteAllCode regardless of whether dispatch
happens with a VMEntryScope on the stack), which makes
deleteAllCodeBlocks skip them and keeps the original bytecode in place.
JSModuleRecord::evaluate drops the executable once the body finishes, so
the unlinked code block is still reclaimed via GC.

With that in place the CDP adapter activates breakpoints and pause-on-
debugger-statements when Debugger.enable arrives (matching V8's defaults),
so DevTools-protocol clients pause without an extra round-trip. New tests
cover both the bun --inspect (JSC protocol) and inspector.open() (CDP)
paths end to end: attach at runtime, activate breakpoints, import a module
containing `debugger;`, pause/resume, and assert the importer's TLA
resume completes with the right values. The process.features.inspector
comment is reworded now that breakpoint pausing works.
Satisfies the bun/no-duplicate-conditional-property-access oxlint rule
(main grew the rule since this branch was last green); no behaviour
change.
…tale comment

Adds the dotted form to the bracketed-IPv6 alternative so e.g.
[::ffff:127.0.0.1] is reflected like Node (whose IsIPAddress validates
via uv_inet_pton(AF_INET6, ...)); covered by a new assertion in the
discovery-endpoint test. Also drops the now-stale 'Breakpoint pausing is
not supported yet' from the node:inspector module header.
…aitPromise, delta coverage

- Gate every node:inspector request (WS upgrade + /json) on the Host header,
  matching Node's inspector_socket.cc IsAllowedHost / DNS-rebinding guard.
- Add ERR_INSPECTOR_{ALREADY,NOT}_CONNECTED / NOT_WORKER / CLOSED / COMMAND
  and ERR_WORKER_UNSUPPORTED_OPERATION to ErrorCode; use them throughout
  inspector.Session (connect, connectToMainThread, disconnect, post, dispatch).
- post(): validate method/params/callback types (ERR_INVALID_ARG_TYPE).
- Runtime.evaluate over CDP: forward contextId + userGesture, and emulate
  awaitPromise by chaining JSC's Runtime.awaitPromise (DevTools TLA).
- Profiler.takePreciseCoverage: report delta since the previous take (CDP
  contract) via a per-Session baseline; JSC has no counter reset.
- Runtime.consoleAPICalled: encode -0 as unserializableValue like Node.
- Session#disconnect(): release forwarded Debugger.* state on the debugger
  thread (refcounted per Session) so breakpoints don't outlive the session.
- process.features.inspector: report true again; gate the vendored Node
  inspector suite per-file in test/common (allowlist of tests that pass).
- BunDebugger: wrap NodeInspectorState in NeverDestroyed (~Strong at exit()
  touched a live foreign HandleSet); drop the 30s startup timeout since
  debugger.ts's try/catch reports on every path and a timeout left state
  half-set with no recovery.
- JSInspectorProfiler / inspector.ts: fix comments to state actual JSC vs V8
  semantics (no always-on counters, GC-collected scripts drop, transpiled
  offsets, generator entry-block heuristic, no recompile on start).
- Debugger.rs: document that transpiler debug state persists past close().

Adds coverage for the Host gate (/json + WS upgrade), awaitPromise, -0/NaN/
Infinity/bigint RemoteObject shapes, Session error codes + arg validation,
delta coverage semantics, best-effort empty without start, and connectToMain-
Thread on the main thread.
…RAGE warning, log-and-return on open() bind failure

- Profiler.{start,take}PreciseCoverage timestamp: performance.now()/1000 (monotonic
  seconds per CDP) instead of Date.now()/1000.
- Remove the NODE_V8_COVERAGE 'inspector is disabled' warning: process.features.inspector
  is true, so the warning contradicts observable state (Node only emits it on
  --without-inspector builds).
- inspector.open() on a busy port now prints Node's one-line stderr diagnostic
  ('Starting inspector on HOST:PORT failed: address already in use') and returns
  instead of throwing with a stack trace, so callers can retry with another port.
  Drop the redundant console.error in the Debugger constructor (every caller has
  its own catch) and map EADDRINUSE/EACCES to the libuv strings on the debugger
  thread.
…vendored test

- Debugger__abandonNodeInspectorWait: on the C++ throw path (Bun.serve on the
  debugger thread reported EADDRINUSE / no URL), undo create()'s poll_ref.ref_()
  and clear wait state so the process can exit. Previously open(port, host, true)
  on a busy port printed the diagnostic but then hung forever on the leaked
  event-loop ref.
- inspector.open() error trim: derive the slice length from the prefix instead
  of hardcoding 27.
- Drop test-inspector-reported-host.js from bunInspectorPassing: it spawns via
  --inspect-brk=0 (Bun's JSC-protocol path, no 'Debugger listening on ws://'
  banner, no /json), so inspector-helper's portPromise never resolves and it
  hangs to timeout on every CI target. The Host-reflection contract is already
  covered by inspector.test.ts.
Conflicts:
- src/jsc/bindings/ErrorCode.ts, src/jsc/ErrorCode.rs: both sides appended
  error codes. Kept main's TRACE_EVENTS_* at 329-330, renumbered this
  branch's INSPECTOR_* to 331-337, COUNT=338.
- src/js/internal/debugger.ts: both sides added a Host-header gate. Kept
  main's isHostAllowed + isOriginAllowed (hardening #33072) which subsumes
  this branch's node-inspector-only isAllowedHostHeader regex; dropped the
  now-dead helper.
… waitForDebugger()

- BunDebugger.cpp: gate controller install on a one-shot static instead of
  \!hasFrontends(); a connect→disconnect→waitForDebugger() sequence would
  otherwise makeUnique<> over a once-connected controller and hit the
  CheckedPtr ordering crash the exit path already leaks around.
- Debugger.rs: drop the NODE_INSPECTOR_WAIT_RESOLVED early-return and the
  now-dead reset export — Node blocks on every waitForDebugger() for a fresh
  Runtime.runIfWaitingForDebugger, so Bun does too.
- inspector.ts: only treat params as the callback when no third argument was
  passed, so post(method, fn, fn) throws ERR_INVALID_ARG_TYPE for params like
  Node instead of silently discarding the callback.
- util.ts: pass the operation name (not the full sentence) to
  ERR_WORKER_UNSUPPORTED_OPERATION now that ErrorCode.cpp appends the suffix.
- cdp.ts: read remote.objectId once (oxlint bun/no-repeated-prop-access).

Adds a test that connects, resumes, disconnects, then hits a second
waitForDebugger() and resumes again; and a post(method, fn, fn) validation
case.
…skip

- start_node_inspector_server now calls Bun__ensureDebugger unconditionally so
  a client cannot connectFrontend to JSC's default controller before Bun's is
  installed (the wait path's later call is a bunControllerInstalled no-op).
- test-repl-preview-without-inspector.js: remove the Bun skip that
  process.features.inspector already made unreachable, restoring the file to
  upstream-verbatim.
Resolved:
- src/jsc/ErrorCode.rs: main moved the error-code table to codegen
  (include! of ErrorCode.generated.rs). Took main's file; the ERR_INSPECTOR_*
  entries now come from the ErrorCode.ts source of truth this branch already
  edits, so the hand-written constants are no longer needed.
- test/no-validate-exceptions.txt, test/no-validate-leaksan.txt: append-only
  exclusion lists; kept both sides' entries.
The previous approach vendored 77 Node inspector tests and skipped the ones
Bun cannot pass yet through a hardcoded filename allowlist inside
skipIfInspectorDisabled(). That helper is shared: because Bun reports
process.features.inspector === true, the allowlist also silently skipped 17
tests that already run and pass on main (test-worker-name.js,
test-debugger-*.js, test-trace-events-*.js and others), and it made the
helper skip for reasons that have nothing to do with the inspector being
disabled.

Keep the 5 tests that actually pass and delete the rest, so the tree contains
no test that is present but never executed:

  test-inspector-connect-to-main-thread.js
  test-inspector-open.js
  test-inspector-open-coverage.js
  test-inspector-open-port-integer-overflow.js
  test-inspector-open-dispose.mjs

common/index.js and common/inspector-helper.js go back to their upstream
content, and test-inspector-has-inspector-false.js keeps upstream's version
instead of being rewritten into a Bun-specific test that asserted the
opposite of its own filename. Fixtures and helpers whose only consumers were
deleted go with them (common/repl.js, the dom-storage and
inspector-network-resource fixtures, and the v8-coverage subprocess fixture
whose only consumer skips).

@claude claude Bot 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.

I reviewed this PR and didn't find any bugs this pass; every prior finding is resolved. Given the scope — ~3k lines across the C++ in-process inspector channel and pause-loop reentrancy (BunDebugger.cpp), cross-thread atomics and the exit-handshake pump in Debugger.rs/VirtualMachine.rs, the uWS Sec-WebSocket-Key gate relaxation, and new public node:inspector surface (Network/DOMStorage) — a human sign-off is still warranted.

What was reviewed:

  • allowAnySecWebSocketKey is threaded end-to-end and only set by the internal debugger server; a plain Bun.serve still rejects short keys (uWS gate also requires behavior.upgrade).
  • The exit-handshake pump snapshots CDP-only preventShutdown sessions under the lock and reuses pausedWait; the accept gate is cleared only on successful reopen.
  • InProcessInspectorChannel defers detach on dispatchDepth/inPauseLoop/hasRemoteFrontend, and the JS-side inProcessAdapters.size === 0 guard prevents zombie posts from re-arming a discarding channel.
Extended reasoning...

Overview

This PR adds a Chrome DevTools Protocol endpoint alongside Bun's existing JSC-protocol inspector on --inspect*, plus an in-process node:inspector Session backend. It touches 35 files: ~550 lines of new C++ in BunDebugger.cpp (an InProcessInspectorChannel frontend, a same-thread pause loop, an exit-handshake pump loop, deferred-detach machinery), ~100 lines of Rust in Debugger.rs (cross-thread WAITING_FOR_DEBUGGER_CONTEXT atomic, wait_for_debugger_to_disconnect), ~1000 lines each in inspector.ts and cdp.ts (Network/DOMStorage domains, source-map VLQ decoding, pre-parse breakpoint re-resolution, Profiler adapter), a uWS allowAnySecWebSocketKey flag threaded through App.h → libuwsockets.cpp → WebSocket.rs → server_body.rs, a hook into VirtualMachine::on_exit, and 15+ test files including 9 vendored upstream Node inspector tests.

Security risks

The Sec-WebSocket-Key length gate relaxation is the security-adjacent change. It is scoped: the uWS check requires both behavior.allowAnySecWebSocketKey and a non-null behavior.upgrade handler and a non-empty key; the Rust-side server.upgrade() re-check in server_body.rs also requires allow_any_sec_websocket_key on the config. Only internal/debugger.ts sets internalAllowAnySecWebSocketKey: true, and the property is read via JSValue::get() (which routes through prototype-pollution mitigation). The inspector's Origin check and random-UUID pathname remain unchanged. The inspector.open() SecurityWarning for non-loopback hosts mirrors Node's. I did not find a way for a plain Bun.serve user to trip the relaxed gate.

Level of scrutiny

High. This is a large feature PR in a subsystem with cross-thread state (JS thread ↔ debugger thread), a new blocking pump loop on the process-exit path, reentrancy between JSC's inspector controller and user JS listeners (disconnect-from-paused-listener), and a security-gate change in vendored uWS. The PR has been through 36 iterations with dozens of resolved review threads covering exactly those hazards (deferred-detach reentrancy, atomic ordering, stale-breakpoint auto-resume suppression, tamper-resistance in built-in JS). That history is reassuring but does not substitute for a maintainer look at the overall design — particularly the InProcessInspectorChannel lifetime (NeverDestroyed process-global with Weak<JSObject> callback), the runWhilePausedCallback = inProcessRunWhilePaused install/reset ordering, and whether the exit-handshake pump on on_exit interacts correctly with process.exit() from inside a Runtime.evaluate.

Other factors

All 121 of my prior findings are resolved (0 unresolved threads). Test coverage is substantial: end-to-end WebSocket CDP tests in inspector.test.ts covering pre-parse breakpoints, source-mapped positions, the exit handshake, stepOver-from-paused-listener, and disconnect-from-paused-listener; plus 9 vendored upstream Node tests. The PR description records ASAN+debug and release passes. Nothing here is simple or mechanical enough to bypass human review.

Comment thread src/js/node/inspector.ts Resolved
…led the domain

JSC has one agent set and broadcasts every event to every frontend, so
all in-process Sessions (and all remote clients) received each other's
Debugger.* and console events. The adapter now tracks per-session
Debugger/Runtime enables and gates the event emits on them, matching
V8's per-session agents; script and breakpoint bookkeeping still runs so
console and profiler position translation keep working. The flags are
set before the backend send because the in-process dispatch delivers the
enable-time replay synchronously. When a server is up, node:inspector
forwards Debugger.enable past the adapter, so that path records the
enable on the adapter explicitly. Also stops a remote client's
Console.enable from duplicating in-process sessions' console events,
which node:inspector already delivers through its own hook.
Comment thread src/js/internal/inspector/cdp.ts Resolved
…on-cli

# Conflicts:
#	src/js/node/inspector.ts
Comment thread src/js/node/inspector.ts Resolved
… consumed

Forwarding by itself delivers no events; the flag matters once the
session's in-process channel has connected through a kInProcess post.
Comment thread src/js/node/inspector.ts Resolved
Comment thread src/js/node/inspector.ts Resolved
robobun and others added 3 commits August 21, 2026 05:55
… payloads

Validation ran once and the same request/response/initiator/storageId
objects were handed to every enabled session, so a listener mutating
its event leaked into the next session. Copy the first-level objects per
session, as emitConsoleAPICalled already does; bookkeeping keeps reading
the validated originals.
…on-cli

# Conflicts:
#	src/jsc/Debugger.rs
#	src/jsc/bindings/BunDebugger.cpp

@claude claude Bot 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.

I reviewed this PR and the automated bug hunt found no new issues at this revision. Given the size (~3,000 lines across 35 files) and the surfaces it touches — the JSC inspector controller lifecycle and pause loop in BunDebugger.cpp, the process-exit path in VirtualMachine::on_exit, cross-thread debugger state in Debugger.rs, and the Sec-WebSocket-Key relaxation threaded through uWS/Bun.serve — a human look is still warranted before merge.

What was reviewed

  • The InProcessInspectorChannel lifecycle (deferred detach vs. dispatchDepth/inPauseLoop, re-arm on zombie post) — the JS-side inProcessAdapters.size === 0 gate and the size-0 drain branch cover the cases raised in earlier rounds.
  • The allowAnySecWebSocketKey plumbing — confirmed it only reaches uWS when both the internal flag and an upgrade handler are present, and server.upgrade() still refuses an empty key; a plain Bun.serve without the flag keeps the 24-byte gate.
  • The exit-handshake wait loop and notAcceptingConnectionsContext — snapshot-then-pump ordering matches Node's, and _debugEnd/reopen clear the accept gate only on success.
  • Tamper-resistance in inspector.ts (ErrorObject, SafeMap/SafeSet, per-session payload copies) and the per-adapter domain-enable gates in cdp.ts.
Extended reasoning...

Overview

This PR adds a Chrome DevTools Protocol endpoint alongside Bun's existing JSC-protocol inspector on --inspect*, plus a full in-process node:inspector Session backend. The heavy lifting is in four files: src/js/internal/inspector/cdp.ts (+900 lines: CDP↔JSC translation, source-map re-resolution, pre-parse breakpoint reset, Profiler adapter, exit-handshake state machine), src/js/node/inspector.ts (+900 lines: in-process backend dispatch, Network/DOMStorage domains, console stack capture), src/jsc/bindings/BunDebugger.cpp (~+450 lines: InProcessInspectorChannel singleton, deferred detach, inProcessRunWhilePaused, waitForDebuggerToDisconnect pump loop), and src/jsc/Debugger.rs (WAITING_FOR_DEBUGGER_CONTEXT atomic, debug_ended gate, exit-handshake entry). It also threads an allowAnySecWebSocketKey flag through uWS → libuwsockets.cpp → WebSocketBehavior → WebSocketServerContext → server.upgrade(), adds a secondary loopback listener in debugger.ts, wires process._debugEnd, and hooks wait_for_debugger_to_disconnect into VirtualMachine::on_exit.

Security risks

Two security-adjacent changes: (1) the Sec-WebSocket-Key length gate is relaxed, but only when the server sets the undocumented internalAllowAnySecWebSocketKey handler flag and has a custom upgrade handler and the key is non-empty — a stock Bun.serve still 400s short keys, and server.upgrade() re-checks with allow_any_sec_websocket_key gated on the same config; (2) a secondary loopback bind on 127.0.0.1/::1 for the CDP endpoint. The existing isOriginAllowed browser-origin check and the random-UUID pathname are unchanged, and isLoopbackHost now emits Node's SecurityWarning on non-loopback inspector.open(). I don't see a new attack surface, but both are the kind of change a maintainer should sign off on.

Level of scrutiny

High. This is not a mechanical change: it introduces a new same-thread FrontendChannel on JSC's inspector controller with reentrancy guards (dispatchDepth, inPauseLoop, discarding) whose interaction with disconnectFrontend, runWhilePaused, and remote-frontend coexistence went through many review iterations here; it adds a blocking pump loop on the process-exit path; and it changes the --inspect banner and discovery endpoints that external tools depend on. The 37-iteration review history and the number of resolved inline threads reflect that complexity.

Other factors

Test coverage is substantial (77 in-tree inspector tests + 9 vendored upstream Node tests, ASAN+release verified in the gate evidence), and every prior inline finding on this PR is marked resolved with a corresponding fix commit. No unresolved reviewer threads remain. The remaining reason to defer is scope and architectural weight, not a specific known defect.

…on-cli

# Conflicts:
#	src/runtime/server/server_body.rs

@claude claude Bot 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.

I reviewed this PR and the automated bug-hunting pass found no new issues; all prior inline findings from earlier passes are resolved. Given the size (~3k LOC across 35 files) and the surface it touches — cross-thread C++ frontend-channel lifetime in BunDebugger.cpp, a new blocking exit-handshake in VirtualMachine::on_exit, and the Sec-WebSocket-Key gate relaxation plumbed through uWS/Bun.serve — a human sign-off is still warranted.

What was reviewed:

  • InProcessInspectorChannel reentrancy (dispatchDepth/inPauseLoop/discarding) and deferred detach vs. disconnectFrontend ordering — no UAF or missed detach found.
  • allowAnySecWebSocketKey: confirmed it defaults off through the Rust/C++/uWS chain and is only set by internal/debugger.ts; a plain Bun.serve still refuses short keys.
  • BunDebugger__waitForDebuggerToDisconnect pump loop: snapshot-under-lock then release, same shape as runWhilePaused; no lock held across JS callbacks.
  • CDP adapter source-map/breakpoint bookkeeping and per-session Network/DOMStorage fanout — the earlier cross-session mutation and stale-breakpoint nits are addressed at the tip.
Extended reasoning...

Overview

This PR adds a Chrome DevTools Protocol endpoint alongside Bun's existing JSC-protocol inspector on --inspect*, plus a full in-process node:inspector Session backend. It spans 35 files: ~1000 lines each in src/js/node/inspector.ts and src/js/internal/inspector/cdp.ts (CDP↔JSC translation, source-map remapping, pre-parse breakpoint re-resolution, Profiler/Network/DOMStorage domains), ~550 lines in src/jsc/bindings/BunDebugger.cpp (a new InProcessInspectorChannel singleton, exit handshake, deferred detach), Rust-side Debugger.rs/VirtualMachine.rs (waiting-for-debugger atomics, wait_for_debugger_to_disconnect on exit), and a Sec-WebSocket-Key length-check relaxation plumbed through uWS → Bun.serve → WebSocketServerContext. It vendors 9 upstream Node inspector tests and adds ~700 lines of new tests.

Security risks

The inspector is an RCE surface by design; two changes touch its perimeter. First, allowAnySecWebSocketKey relaxes the RFC 6455 24-byte key check in uWS's upgrade path. I traced the flag end-to-end: it defaults false in WebSocketBehavior, is only set true via the undocumented internalAllowAnySecWebSocketKey handler property (read via prototype-pollution-mitigated get), and is only supplied by the internal debugger server — public Bun.serve still 400s short keys, and even with the flag on the upgrade still requires a non-empty key and an upgrade handler. Second, the additive loopback bind (127.0.0.1/::1) and Host-header echo in /json were checked against the existing isOriginAllowed guard, which is unchanged. No new attack surface identified beyond what --inspect already exposes.

Level of scrutiny

High. This is a substantial feature, not a mechanical fix: it adds a NeverDestroyed C++ frontend channel with reentrant-dispatch bookkeeping and a deferred-detach state machine that must survive session.disconnect() from inside a Debugger.paused listener; a blocking pump loop on the process-exit path (on_exit → BunDebugger__waitForDebuggerToDisconnect) that snapshots connections under a lock and then waits indefinitely for CDP frontends to leave; and cross-thread atomics (WAITING_FOR_DEBUGGER_CONTEXT, notAcceptingConnectionsContext) coordinating main and debugger threads. The inProcessRunWhilePaused hook replaces JSC's runWhilePausedCallback and auto-continues when no remote frontend is attached. These are exactly the shapes REVIEW.md flags for careful ownership/thread-affinity review, and while nothing wrong surfaced, they warrant a maintainer's eye.

Other factors

The PR has been through 39 gated iterations; every one of the 100+ prior inline findings from earlier automated passes (deferred-detach cancellation, per-adapter domain-enable gating, cross-session payload mutation, tamper-resistance via ErrorObject, worker-thread open() messaging, dead isWorker param, etc.) is marked resolved and the fixes are visible in the diff. Test coverage is substantial and the fails-on-main/passes-on-PR evidence is attached. The remaining reason to defer is scope and architectural weight, not any specific unresolved concern.

…on-cli

# Conflicts:
#	src/jsc/bindings/BunDebugger.cpp
Comment thread src/jsc/Debugger.rs Resolved
The block's early return already guarantees the debugger is present, so
the re-lookup's None arm was unreachable; match wait_for_debugger_to_disconnect.
@steipete

Copy link
Copy Markdown
Collaborator

One gap in the new in-process HeapProfiler.disable arm: it returns {} but leaves the VM's retained heap-snapshot metadata in place. After v8.writeHeapSnapshot(), JSC's HeapProfiler keeps the snapshot and later collections keep pruning its node map. Node clears the isolate's heap object IDs on disable whether or not that Session enabled HeapProfiler first: V8HeapProfilerAgentImpl::disable() calls ClearObjectIds() unconditionally (v24.21.0).

#45025 fixes the disconnect half on current main. It exposes HeapProfiler::clearSnapshots() through the existing native inspector profiler bindings and calls it on local Session disconnect, only when the VM already has a profiler (so cleanup does not create one), and not for a worker Session connected to the main thread (which must not clear the worker's own VM). Its regression keeps a separate JSC inspector observer attached, writes a real snapshot, confirms Heap.getPreview resolves a marker, then expects No heap snapshot after the actor Session goes away. Keeping the observer attached matters; otherwise its own disconnect could do the cleanup and hide the bug.

The HeapProfiler.disable arm here could call the same binding. Main has no HeapProfiler commands yet, so #45025 only covers disconnect. On a downstream fork that has them, the same regression also covers disable with and without a preceding enable, and the callback form (openclaw/bun#141); that variant has not been run against this PR.

This branch has not been deployed

No deployments
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.

5 participants