Repository navigation
Conversation
JSC's JSGlobalObjectInspectorController has a single DebuggerAgent, RuntimeAgent and InjectedScript, and FrontendRouter broadcasts every response and event to every attached FrontendChannel. With two clients attached to one inspector.open() server, client B could flip client A's breakpointsActive / pauseOnExceptions, Debugger.disable A, delete A's breakpoints, receive A's Debugger.paused / consoleAPICalled events without ever enabling those domains, and read or release A's RemoteObject handles by id. Node gives each WebSocket its own V8InspectorSession and is per-session on all of these. The CDP adapter already sits between each WebSocket and the shared backend, so do the per-session scoping there: - Per-adapter backend command-id ranges so a broadcast response only matches the sender's pending map. - Per-adapter debuggerEnabled / runtimeEnabled gating of broadcast events, and refcounted Debugger/Runtime/Console enable so one client's disable does not tear the shared agent down under another. - Per-adapter breakpointsActive / pauseOnExceptions with an aggregate written to the backend only on change, and per-adapter breakpoint ownership so removeBreakpoint cannot delete another client's. - Every outbound RemoteObject.objectId is tagged with the adapter's session id; inbound ids without this adapter's tag are rejected with V8's 'Could not find object with given id'. - dispose() on connection close removes the session's breakpoints and contribution to the aggregates.
WalkthroughThe CDP adapter now isolates debugger and runtime state across inspector clients, remaps object handles, filters session-specific events, aggregates shared backend settings, and disposes adapters during connection teardown. A two-client integration test covers these behaviors. ChangesInspector session isolation
Possibly related PRs
Suggested reviewers: 🚥 Pre-merge checks | ✅ 4✅ Passed checks (4 passed)
Comment |
|
Found 1 issue this PR may fix:
🤖 Generated with Claude Code |
|
Updated 11:05 PM PT - Jul 25th, 2026
❌ @robobun, your commit 72a2623 has 1 failures in
🧪 To try this PR locally: bunx bun-pr 35752That installs a local version of the PR into your bun-35752 --bun |
|
This PR may be a duplicate of:
🤖 Generated with Claude Code |
A foreign-session or untagged objectId in Runtime.callFunctionOn arguments[] was forwarded to JSC unchanged (InjectedScriptSource.js ignores extra JSON fields), so client B could still read client A's RemoteObject via that path. Reject the whole request the same way the target objectId / getProperties / releaseObject paths already do, and cover it in the test. Also drain the debuggee's stderr in the test and include it in the waitForStdout failure message, matching the sibling tests in this file.
There was a problem hiding this comment.
Additional findings (outside current diff — PR may have been updated during review):
-
🟡
src/js/internal/inspector/cdp.ts:384-390— The raw pass-through at cdp.ts:719-724 still forwardsConsole.disablestraight to the shared backend with noanyRuntimeEnabled()guard, so B sending{method:"Console.disable"}stopsConsole.messageAddedfor every FrontendChannel — silencing A'sRuntime.consoleAPICalledstream, the exact failure this PR fixes forRuntime.disable. The V8Consoledomain is deprecated so real DevTools/vscode-js-debug won't send it, but the PR's threat model is explicitly a buggy/adversarial second client; the sameif (anyRuntimeEnabled()) { reply {}; return; }guard belongs on theConsole.disablecase (or drop the deprecatedConsole.*pass-through entirely).Extended reasoning...
What the bug is
The PR adds a refcount guard on
Runtime.disable(cdp.ts:384-390) so that when client B disables Runtime, the adapter checksanyRuntimeEnabled()and — if client A still has Runtime enabled — replies{}locally instead of sendingRuntime.disable/Console.disableto the single shared JSC backend. But the pre-existing raw pass-through further down in the same switch is left untouched:case "Console.enable": case "Console.disable": case "Console.clearMessages": case "Inspector.enable": this.#sendToBackend(method, undefined, id, method); return;
So client B can send
{method:"Console.disable"}directly and it goes straight to JSC'sInspectorConsoleAgent::disablewith no per-session gate.The specific code path
JSC's
JSGlobalObjectInspectorControllerowns exactly oneInspectorConsoleAgent(the PR description itself states this: "a single InspectorDebuggerAgent / InspectorRuntimeAgent"), and its enable state is a boolean, not a refcount. OneConsole.disablefrom any FrontendChannel flips it off, and the agent stops emittingConsole.messageAddedto every channel. In#translateBackendEvent,Console.messageAddedis the sole producer ofRuntime.consoleAPICalled— there is no other source. So once the backend Console agent is disabled, A stops receivingRuntime.consoleAPICalledeven thoughA.#flags.runtimeEnabledis stilltrue.Why existing code doesn't prevent it
The new adapter-side event gate in
#translateBackendEvent(if (!this.#flags.runtimeEnabled) return) filters events arriving from the backend per session; it can't help when the backend has stopped emitting them entirely. TheanyRuntimeEnabled()refcount was added precisely to keep the backend Console agent alive while any session wants it — but only on theRuntime.disablepath, not on the directConsole.disablesibling that reaches the same backend agent.Step-by-step proof
- Client A connects → adapter A,
sessionId=1,#flags.runtimeEnabled=false. - Client B connects → adapter B,
sessionId=2,#flags.runtimeEnabled=false. - A sends
Runtime.enable→ A's adapter setsA.#flags.runtimeEnabled=trueand sendsRuntime.enable+Console.enableto the backend. JSC's ConsoleAgent is now enabled. - Debuggee runs
console.log("x")→ backend emitsConsole.messageAddedto both FrontendChannels → A's#translateBackendEventseesruntimeEnabled=true, translates toRuntime.consoleAPICalled, A receives it. ✅ - B sends
{id:1, method:"Console.disable"}→ B's adapter hitscase "Console.disable":at line 720 →this.#sendToBackend("Console.disable", undefined, 1, "Console.disable")— noanyRuntimeEnabled()check. JSC's ConsoleAgent flips to disabled. - Debuggee runs
console.log("y")→ ConsoleAgent is disabled → noConsole.messageAddedis emitted to any channel. - A's
#translateBackendEventnever runs; A never receivesRuntime.consoleAPICalledfor "y". A's#flags.runtimeEnabledis stilltrue, so the adapter-side filter is irrelevant — the events simply stopped arriving.
This is exactly the failure the PR description lists ("B's Runtime.disable silences A's console stream") reachable via a sibling entry point the fix left unguarded.
Impact
The V8 CDP
Consoledomain is deprecated and Chrome DevTools / vscode-js-debug do not sendConsole.disable, so this won't fire in normal multi-client use. But the PR's stated threat model is per-session isolation regardless of what B sends — it already defends against B guessing raw backend objectIds (FOREIGN_OBJECT_ID_ERROR) and B callingDebugger.disable/removeBreakpointwithout ever having enabled Debugger. A one-message bypass of the console-stream isolation via a documented (if deprecated) method leaves the class incompletely fixed. REVIEW.md: "Fix the whole class in the same PR — grep for every sibling site sharing the pattern."How to fix
Either add the same guard the
Runtime.disablecase has:case "Console.disable": if (anyRuntimeEnabled()) { this.#replyToClient(id, {}); return; } this.#sendToBackend(method, undefined, id, method); return;
or, since
Runtime.enable/Runtime.disablealready manage the backend Console agent's lifecycle and no CDP client relies on the deprecatedConsoledomain, drop theConsole.enable/Console.disablepass-through cases entirely and reply{}locally (leavingConsole.clearMessagesas the only one that still needs to reach the backend, if at all). - Client A connects → adapter A,
…isolation gaps
- Backend command ids: replace per-session 1e9 stride with a single shared
counter. JSC's BackendDispatcher reads the request id via
JSON::Value::asInteger() into a 32-bit int, so session 3 at id 3e9
overflowed and every command from the third+ connection hung with no
reply.
- tagObjectIds: skip RemoteObject.value (arbitrary user JSON under
returnByValue:true) and only rewrite strings with JSC's fixed
{"injectedScriptId": prefix, so a user property named objectId is
not mutated.
- objectGroup names are prefixed per session so one client's
Runtime.releaseObjectGroup cannot free another's handles.
- The deprecated Console.enable/disable are acknowledged locally instead
of reaching the shared ConsoleAgent.
- Debugger.pause/resume/step*/continueToLocation/getScriptSource and
evaluateOnCallFrame are rejected with 'Debugger agent is not enabled'
when this session has not enabled Debugger.
- Debugger.breakpointResolved and Debugger.paused.hitBreakpoints are
filtered to the breakpoint's owning session.
- Test: wire ws close/error and proc.exited to reject pending sends;
add coverage for callFunctionOn arguments, releaseObjectGroup,
Console.disable, evaluateOnCallFrame gating, and returnByValue
round-trip of user objectId properties.
|
On the bot suggestions:
CI on 1330ddd failed only on |
…per-session enable; preserve omitted objectGroup A never-enabled session could still set a breakpoint on the shared agent (enabled by another session), have it recorded as owner, then never see the pause and leave it orphaned on disconnect since teardownDebuggerState early-returns when debuggerEnabled is false. Reject these with V8's 'Debugger agent is not enabled' like the already-gated sibling commands. sessionObjectGroup now returns undefined for a non-string name so JSON.stringify omits the key and JSC keeps its 'not in any group' semantics for evaluations that omit objectGroup.
There was a problem hiding this comment.
Actionable comments posted: 7
🤖 Prompt for all review comments with AI agents
Verify each finding against current code. Fix only still-valid issues, skip the
rest with a brief reason, keep changes minimal, and validate.
Inline comments:
In `@src/js/internal/debugger.ts`:
- Around line 609-615: Update `#error` to fully tear down the connection state
after logging the error: dispose the adapter, close or terminate the
websocket/backend, and clear data.adapter and data.backend so later frames
cannot reach handleClientMessage on the disposed session.
In `@src/js/internal/inspector/cdp.ts`:
- Around line 618-630: Gate the `Debugger.setBreakpointsActive` and
`Debugger.setPauseOnExceptions` cases on `debuggerEnabled` before mutating flags
or syncing the backend aggregate. When the domain is disabled, reject with the
existing “Debugger agent is not enabled” response path; otherwise preserve the
current state updates and successful replies.
- Around line 632-643: Update the Debugger.removeBreakpoint handling to forward
removal requests to the backend only when breakpointOwner.$get(breakpointId)
equals this.#sessionId. Treat both undefined owners and foreign owners as no-ops
by replying with an empty result and returning, while preserving deletion and
forwarding for breakpoints owned by the current session.
In `@test/js/node/inspector/inspector.test.ts`:
- Around line 1171-1188: Capture the responses from B.send calls for
Debugger.setBreakpointsActive, Debugger.setPauseOnExceptions,
Debugger.removeBreakpoint, and Debugger.disable, then assert each response
reports the adapter’s “Debugger agent is not enabled” error semantics, matching
the existing bEval assertion. Keep the existing pause-count and event assertions
unchanged.
- Around line 1258-1264: Update the test cleanup around proc.exited and
stderrDrained so stderr is always drained before evaluating the child’s exit
result. Await stderrDrained first, then assert the exit code together with the
collected stderr using the test’s combined failure output, preserving the
existing timeout and shutdown flow.
- Around line 1092-1093: Update the inspector startup wait in the URL extraction
flow to wait for the complete URL line, including its terminating newline,
before matching with the existing URL regex. Keep the wsUrl extraction unchanged
after waitForStdout has confirmed the full line is available.
- Around line 1137-1139: Update the WebSocket handlers in the attach flow to
track whether the socket has opened; when onclose fires before onopen,
explicitly reject the attach promise with a diagnostic error before abandoning
the client, while preserving the existing post-open abandon behavior and error
handling.
🪄 Autofix (Beta)
Fix all unresolved CodeRabbit comments on this PR:
- Push a commit to this branch (recommended)
- Create a new PR with the fixes
ℹ️ Review info
⚙️ Run configuration
Configuration used: Path: .coderabbit.yaml
Review profile: ASSERTIVE
Plan: Pro
Run ID: f3996111-ffb5-474f-89bc-cae74dacf6d5
📒 Files selected for processing (3)
src/js/internal/debugger.tssrc/js/internal/inspector/cdp.tstest/js/node/inspector/inspector.test.ts
…removeBreakpoint owner check, clear connection data on error/close; test diagnostics - setBreakpointsActive / setPauseOnExceptions / removeBreakpoint now reject with 'Debugger agent is not enabled' when the session has not enabled Debugger, matching the already-gated sibling commands. removeBreakpoint only forwards ids this session owns. - debugger.ts #close / #error clear data.adapter / data.backend after disposing so a later frame on the same socket cannot dispatch to a disposed session. - Test: wait for the full URL line before matching; reject the attach promise if the socket closes before open; assert B's Debugger config commands are rejected; await stderr drain before asserting the exit code and include stderr in the failure diff.
There was a problem hiding this comment.
Additional findings (outside current diff — PR may have been updated during review):
-
🟡
src/js/internal/inspector/cdp.ts:924-928— The new owner filter at line 926 hides A's breakpoint id from B'shitBreakpoints, but three lines abovecdpParamsis built withdatapassed through — and forreason: "Breakpoint"JSC'sdatais exactly{breakpointId: <id>}, so B still receives A's id viaparams.data.breakpointId. V8 doesn't populatedatafor breakpoint pauses at all, so settingcdpParams.data = undefinedin the"Breakpoint"arm both closes the leak and improves CDP fidelity. Impact is minimal (B can't act on the id —removeBreakpointis owner-gated), so nit.Extended reasoning...
What the gap is
Commit 1e1f3d9 added per-session ownership filtering to
Debugger.pausedin response to the earlier review comment ("gate breakpoint events onbreakpointOwner.$get(id) === this.#sessionId"):case "Breakpoint": { const hitId = data?.breakpointId; if (hitId && breakpointOwner.$get(hitId) === this.#sessionId) cdpParams.hitBreakpoints = [hitId]; break; }
but three lines above this,
cdpParamsis initialized as:const { data, asyncStackTrace } = params; const cdpParams: AnyObject = { callFrames, reason: "other", data };
For
reason: "Breakpoint", JSC's raw pause payloaddatais exactly{breakpointId: <id>}(that's why line 925 readsdata?.breakpointId). The owner check only governs whether thehitBreakpointskey is added; it never strips thedatafield. So the same datum the filter was added to hide is still emitted one property over.Step-by-step proof
- Client A:
Debugger.enable,setBreakpointByUrl→breakpointOwner.$set(bpId, A.#sessionId). - Client B:
Debugger.enable→B.#flags.debuggerEnabled = true. - Debuggee hits A's breakpoint. JSC broadcasts
Debugger.pausedwith{reason: "Breakpoint", data: {breakpointId: bpId}, callFrames: [...]}to every FrontendChannel. - B's adapter enters
#translateBackendEvent. Line 869 gate passes (B.#flags.debuggerEnabled === true). - Line 916:
cdpParams = { callFrames, reason: "other", data: {breakpointId: bpId} }. - Line 924–927:
hitId = bpId;breakpointOwner.$get(bpId) === A.#sessionId ≠ B.#sessionId→hitBreakpointsis not added. ✓ - Line 931: B receives
{method: "Debugger.paused", params: {callFrames, reason: "other", data: {breakpointId: bpId}}}— A's id is inparams.data.breakpointId.
Why existing code doesn't prevent it
The
datapassthrough at line 916 is pre-existing and untouched by the diff; the ownership check at line 926 only adds/omits a sibling key;tagObjectIds(line 901) doesn't touchbreakpointId(only keys namedobjectId). Nothing else in the"Breakpoint"arm reads or clearscdpParams.data.Impact — why nit
B cannot act on the leaked id:
Debugger.removeBreakpointis owner-gated at cdp.ts:632–636, and real CDP clients (Chrome DevTools, vscode-js-debug) correlate onhitBreakpoints[], not the non-standarddatafield. The scenario also requires B to haveDebuggerenabled, in which case B legitimately shares the pause and receives the fullcallFramesanyway. So this is an opaque-string information leak with no functional consequence — but it is the same class as thehitBreakpoints/breakpointResolvedfiltering this PR added in this exact switch arm (REVIEW.md: "Fix the whole class in the same PR … parallel switch arms"), and V8 does not populatedatafor plain breakpoint pauses, so it's also a minor Node-compat divergence.Fix
In the
"Breakpoint"arm, dropdata(matches V8):case "Breakpoint": { const hitId = data?.breakpointId; if (hitId && breakpointOwner.$get(hitId) === this.#sessionId) cdpParams.hitBreakpoints = [hitId]; cdpParams.data = undefined; break; }
or, minimally, only when the owner check fails.
- Client A:
…se, drop paused.data for breakpoint pauses
- setAsyncCallStackDepth is stored per session and the max across
debugger-enabled sessions is written to the backend, matching the
breakpointsActive / pauseOnExceptions aggregates and V8's per-agent
max.
- dispose() releases every session-prefixed objectGroup the adapter
issued so a closed client's wrapped values are not pinned in the
shared InjectedScript while another client remains attached.
- Debugger.paused for reason Breakpoint drops the JSC data:{breakpointId}
field; V8 does not populate data for breakpoint pauses and the
owner-filtered hitBreakpoints already carries the id for the owning
session.
There was a problem hiding this comment.
Additional findings (outside current diff — PR may have been updated during review):
-
🟡
src/js/internal/inspector/cdp.ts:776-781—Console.clearMessagesis still forwarded verbatim to the shared backend, unlike the siblingConsole.enable/Console.disablearms this PR just converted to local no-ops ("forwarding disable here would let one client tear the shared ConsoleAgent down under another"). JSC'sInspectorConsoleAgent::clearMessages()callsm_injectedScriptManager.releaseObjectGroup("console"), which frees the raw backend ids that were session-tagged and delivered to A viaRuntime.consoleAPICalled— so B (never enabled Runtime) can invalidate A's console-argument RemoteObjects, bypassing thereleaseObject/releaseObjectGroupisolation. The CDP equivalentRuntime.discardConsoleEntriesis already a local no-op below; moveConsole.clearMessagesinto the same local-ack block two lines up.Extended reasoning...
What the gap is
This PR split the fall-through group at cdp.ts:776-783: before,
Console.enable/Console.disable/Console.clearMessages/Inspector.enableall forwarded to the backend together. The PR movedConsole.enable/Console.disableinto a local-ack block with the comment "forwarding disable here would let one client tear the shared ConsoleAgent down under another", but leftConsole.clearMessagesin the forwarding arm with no per-session gate:case "Console.enable": case "Console.disable": this.#replyToClient(id, {}); return; case "Console.clearMessages": // ← still forwarded ungated case "Inspector.enable": this.#sendToBackend(method, undefined, id, method); return;
WebKit's
InspectorConsoleAgent::clearMessages()clearsm_consoleMessagesand callsm_injectedScriptManager.releaseObjectGroup("console"_s). Every object argument toconsole.logis wrapped byConsoleMessage::addToFrontendviainjectedScript.wrapObject(arg, "console"_s, ...)— the raw, unprefixed group name — before the resultingConsole.messageAddedis broadcast to every FrontendChannel. SoclearMessagesreleases exactly the backend ids that A received (session-tagged) inRuntime.consoleAPICalled.args[].objectId.Why existing code doesn't prevent it
The PR's
releaseObjectguard checks thebunSessionIdtag on inboundobjectIds, andreleaseObjectGroupprefixes the client-supplied group name withbun-session-<N>:. Neither touches this route:Console.clearMessagestakes noobjectIdand noobjectGroupparameter — the"console"group name is hard-coded on the JSC side, and#sessionObjectGroup()only rewrites client-supplied group names on inboundevaluate/callFunctionOn/releaseObjectGroup; it cannot rewrite what JSC uses internally when wrapping console-message arguments. There is noruntimeEnabledgate on this arm either, so B need never have enabled anything.Step-by-step proof
- A sends
Runtime.enable. Debuggee runsconsole.log({secret:1}). JSC'sConsoleMessage::addToFrontendwraps the argument in objectGroup"console", minting raw id{"injectedScriptId":1,"id":N}, and broadcastsConsole.messageAddedto every FrontendChannel. - A's adapter (
#translateBackendEvent→Console.messageAddedarm) callstagObjectIds(params, A.#sessionId)and emitsRuntime.consoleAPICalledwithargs[0].objectId = '{"bunSessionId":<A>,"injectedScriptId":1,"id":N}'. A now holds a valid session-tagged handle whose backing entry lives in the process-global InjectedScript under group"console". - B (never enabled Runtime, never enabled Debugger) sends
{"method":"Console.clearMessages"}. TheConsole.clearMessagesarm at cdp.ts:781 forwards it verbatim to the shared backend.InspectorConsoleAgent::clearMessages()runsreleaseObjectGroup("console"), freeing raw id N. - A sends
Runtime.getProperties({objectId}).untagObjectIdstrips A'sbunSessionIdtag →{"injectedScriptId":1,"id":N}, which is forwarded to JSC. JSC replies with an error (object not found). B has invalidated A's RemoteObject via a route the PR'sreleaseObject/releaseObjectGroupisolation doesn't cover.
Impact and severity
This is exactly the "one client tears down another's shared-agent state" class the adjacent
Console.disablechange and thereleaseObject/releaseObjectGrouprewriting exist to prevent, and REVIEW.md explicitly names "parallel switch arms" as same-class sites to fix in the same PR. That said, exposure is narrow: the CDPConsoledomain is deprecated (V8 documentsConsole.clearMessagesas "Does nothing"), and real clients (Chrome DevTools, vscode-js-debug) sendRuntime.discardConsoleEntriesinstead — which is already stubbed as a local no-op at cdp.ts:796. Impact is limited to console-argument handles, and comparable same-class gaps in this PR (setAsyncCallStackDepth, dispose-time object groups) are already tracked at nit.Fix
Move the case up two lines into the local-ack block:
case "Console.enable": case "Console.disable": case "Console.clearMessages": this.#replyToClient(id, {}); return; case "Inspector.enable": this.#sendToBackend(method, undefined, id, method); return;
This matches the treatment of
Runtime.discardConsoleEntries(its non-deprecated CDP equivalent) 15 lines below. - A sends
-
🟡
src/js/internal/inspector/cdp.ts:825-833—#forwardBreakpointResultrecordsbreakpointOwner.$set(breakpointId, this.#sessionId)unconditionally, so asetBreakpoint*response that arrives after this session has already run#teardownDebuggerState()(pipelinedDebugger.disableor WS close mid-flight, while another client keeps Debugger enabled) records ownership for a dead session — the laterdispose()early-returns on!debuggerEnabledand never sweeps it, leaving the surviving client paused on a breakpoint it can neither remove (owner check fails) nor re-set (JSC's "already exists"). Guard here on!this.#flags.debuggerEnabled || !liveAdapters.$has(this.#sessionId)and sendDebugger.removeBreakpoint({breakpointId})to the backend instead of recording ownership.Extended reasoning...
What the bug is
#forwardBreakpointResult(cdp.ts:825–833) is theonResultcallback forDebugger.setBreakpointByUrl/Debugger.setBreakpoint. On a successful backend response it does:if (typeof breakpointId === "string") breakpointOwner.$set(breakpointId, this.#sessionId);
with no check that the session is still debugger-enabled or still in
liveAdapters. Backend dispatch is cross-thread async (BunDebugger.cpp:sendMessageToInspectorFromDebuggerThreadqueues to the inspected thread viapostTaskConcurrently; the response returns via a posted task on the debugger thread), so a client that pipelines two frames —setBreakpointByUrlfollowed immediately byDebugger.disable— or whose socket closes between send and response, will have#teardownDebuggerState()run before the setBreakpoint response lands. When it later lands, ownership is recorded for a session whose teardown has already run and will never run again for this breakpoint.Step-by-step trace
Two sessions A and B both
Debugger.enable. A sendssetBreakpointByUrland, without awaiting, immediately sendsDebugger.disable(or A's WebSocket closes right after the send). On the debugger thread:setBreakpointByUrlhandler runs →#sendToBackend(..., onResult=#forwardBreakpointResult); entry queued in A's#pending. The command is posted to the inspected thread.Debugger.disablehandler (or#close→dispose()) runs →#teardownDebuggerState(). It iteratesbreakpointOwner— X is not there yet (response still pending) — removes nothing, setsA.#flags.debuggerEnabled = false.anyDebuggerEnabled()is still true (B is enabled), soDebugger.disableis NOT sent to the backend (cdp.ts:337).- The backend response for
setBreakpointByUrlarrives →handleBackendMessagefinds A's#pendingentry →#forwardBreakpointResult→breakpointOwner[X] = A.#sessionId. (In the WS-close variant,data.adapteris nowundefinedso no more client frames reach A, but thereceiveclosure indebugger.ts #opencapturedadapterby local — the callback still fires.) - A's WebSocket closes →
dispose()→#teardownDebuggerState()early-returns at cdp.ts:324 because!this.#flags.debuggerEnabled. ThensessionFlags.$delete(A),liveAdapters.$delete(A)—breakpointOwner[X]survives, keyed to a monotonic session id no future adapter can ever match.
Why nothing catches it
#teardownDebuggerState()sweepsbreakpointOwneronly for entries that already exist and only whendebuggerEnabledis still true — neither holds after step 2.dispose()does no unconditionalbreakpointOwnersweep and does not clear#pending, so lateonResultcallbacks still run.Debugger.removeBreakpoint(cdp.ts:643) now requiresbreakpointOwner.$get(breakpointId) === this.#sessionId, so B's remove is a silent no-op.- B's own
setBreakpointByUrlat that location fails with JSC's "Breakpoint at specified location already exists". Debugger.pausedon X reaches B (B is debugger-enabled) withhitBreakpointsomitted (owner ≠ B at cdp.ts:937), so B doesn't even know which breakpoint is stopping it.
Impact
The debuggee pauses on an unremovable breakpoint every time X's location is hit until every debugger-enabled client disconnects (only then does the last
#teardownDebuggerState()sendDebugger.disableto the backend, which JSC clears). This is a regression window opened by the ownership map: pre-PR,Debugger.disableforwarded straight to JSC (clearing all breakpoints) andremoveBreakpointhad no owner gate, so either path would have reclaimed X. Node avoids this becauseV8DebuggerAgentImpl::disable()clears that session's breakpoints synchronously per-session.The trigger is narrow — well-behaved DevTools/vscode-js-debug await responses, so it takes a client that pipelines set+disable or crashes/closes mid-flight while another debugger-enabled client is attached — hence nit rather than blocking. But it's a genuine gap in the new state machine and directly in scope for this PR's isolation contract (REVIEW.md: every error/abort path actively completes the operation).
Fix
At the top of
#forwardBreakpointResult's success branch:const { breakpointId } = result; if (typeof breakpointId === "string") { if (!this.#flags.debuggerEnabled || !liveAdapters.$has(this.#sessionId)) { // Session tore down while this setBreakpoint was in flight; the shared // backend was not disabled (another session holds it), so remove the // breakpoint we just armed instead of orphaning it under a dead owner. this.#sendToBackend("Debugger.removeBreakpoint", { breakpointId }); return; } breakpointOwner.$set(breakpointId, this.#sessionId); }
Alternatively (or additionally), have
dispose()unconditionally sweepbreakpointOwnerforowner === this.#sessionIdregardless ofdebuggerEnabled, and clear#pendingso lateonResultcallbacks don't run.
…give child-spawning tests ASAN headroom - Console.clearMessages releases JSC's internal "console" objectGroup (the raw backend ids A received as console-argument handles), so acknowledge it locally alongside Console.enable/disable instead of forwarding to the shared agent. Matches Runtime.discardConsoleEntries. - A setBreakpoint* response that arrives after this session already tore down Debugger (pipelined disable or socket close while another session keeps the backend enabled) would record a dead owner the teardown path can no longer sweep; remove the breakpoint from the backend instead. - The existing child-spawning tests in this file run 3-5s on an ASAN build and flake at the 5s default under load; give them the same 20s headroom as the first test's 30s.
|
CI status across the four builds on this branch:
All three reported to main-break triage. The diff is green on everything it touches; needs a maintainer to merge. |
…xceptions states A 1e400 maxDepth parses to Infinity and would poison the max-aggregate (JSON.stringify emits depth:null, JSC rejects it silently, and the cached backendAggregate.asyncCallStackDepth stays at Infinity so no later depth ever re-syncs). Number.isFinite + |0 matches V8's integer parameter. An off-enum pauseOnExceptions state now replies -32602 as JSC/V8 did before the value moved into adapter storage.
…th-enabled aggregate/ownership The torn-down guard returned without settling the client's setBreakpoint request id. Reply with the translated result before returning. Test: after the never-enabled block, B enables Debugger and sends setBreakpointsActive(false) and removeBreakpoint on A's id, then A's breakpoint still fires. This exercises aggregateBreakpointsActive with two enabled sessions and the removeBreakpoint owner-mismatch branch.
There was a problem hiding this comment.
No further issues found after 72a2623 — all six earlier findings (asyncCallStackDepth aggregation, dispose() object-group release, late setBreakpoint result guard + reply, maxDepth/state validation, both-enabled test coverage) are addressed. Deferring to a human because this adds ~440 lines of new stateful per-session emulation to cdp.ts (module-level sessionFlags/breakpointOwner/backendAggregate, refcounted enable/disable, recursive tagObjectIds with a RemoteObject heuristic) and that design choice — scoping sessions at the JS adapter layer rather than in the backend — is worth a maintainer's sign-off.
What was reviewed:
tagObjectIdsskippingRemoteObject.valuesoreturnByValueuser JSON round-trips — covered by test; thetypeof obj.type === "string"heuristic matches JSC's RemoteObject shape.dispose()ordering vsbackend.close()indebugger.ts#close/#error — dispose runs first while#writeToBackendis still live, so the removeBreakpoint/releaseObjectGroup sends land.Debugger.enableunconditionally forcingbackendAggregate.breakpointsActive = true— correct, since the enabling session's default istrueand the aggregate is OR.Runtime.disablefrom a never-enabled session — flag was already false,anyRuntimeEnabled()sees the other session, backend Console stays up.
Extended reasoning...
Overview
Three files: src/js/internal/inspector/cdp.ts (+~440 lines: module-level session registry, per-adapter SessionFlags, three aggregate functions, tagObjectIds/untagObjectId, #sessionObjectGroup, dispose()/#teardownDebuggerState()/#syncBackendAggregate(), #forwardBreakpointResult, and per-command debuggerEnabled gates), src/js/internal/debugger.ts (+12: call adapter.dispose() before backend.close() on WS close/error and on the in-process Session control-channel close/disconnect), and test/js/node/inspector/inspector.test.ts (+276: one large multi-client end-to-end test plus timeout bumps on existing subprocess tests).
Security risks
The PR closes a cross-session information leak (client B reading client A's RemoteObject handles / paused frames). The objectId session tag is not a security boundary in the cryptographic sense — a client can still forge {"bunSessionId":N,...} for any N — but that matches Node/V8, where objectIds are opaque per-session but not authenticated across sessions on the same process; the isolation here is against accidental cross-talk from well-behaved DevTools clients, not adversarial ones on the same debug port. No new network-facing surface; the WS server, Host/Origin checks, and upgrade path are unchanged.
Level of scrutiny
Medium-high. This is developer-tooling (node:inspector), not a production hot path, and the failure mode is a degraded debugging experience rather than data corruption. But the change is large, introduces module-level mutable state whose correctness rests on the "all adapters run on the one debugger thread" invariant, and the tagObjectIds recursive walker mutates backend payloads in place using typeof obj.type === "string" as the RemoteObject heuristic to avoid descending into user returnByValue JSON. Both are well-commented and tested, but they're the kind of thing a maintainer familiar with the JSC inspector plumbing should confirm.
Other factors
The PR has been through five fix commits addressing every prior automated finding, all threads are resolved, CI on the previous commit was green except an unrelated flaky, and the mechgate evidence shows the new test fails on main and passes on the branch under both debug/ASAN and release. The remaining reason to defer is scope/design, not any known defect.
|
Closing this PR because it has been inactive for more than 90 days. |
|
The stale sweep closed this PR. No maintainer reviewed it. I do not plan to reopen it. A design review of the alternatives found that this PR puts the fix in the wrong layer. The PR also leaves a common case broken. What this PR does not fix
The two probes ran on the release build at 367d939. The inspector sources on main (179664e) differ from that build only in type annotations. I did not run this PR's branch against the first probe. That statement comes from the code path above. Probe// bun probe.mjs (or: node probe.mjs)
import { spawn } from "node:child_process";
import { mkdtempSync, writeFileSync } from "node:fs";
import { tmpdir } from "node:os";
import { join } from "node:path";
const src = ['// debuggee','import inspector from "node:inspector";','inspector.open(0, "127.0.0.1");',
'process.stdout.write("URL " + inspector.url() + "\\n");','globalThis.secretStore = { alpha: "objA-secret" };',
'globalThis.hitme = function hitme(x) {',' const local = "frame-local-" + x;',' return local;','};',
'let n = 0;','setInterval(() => { globalThis.hitme(++n); }, 200);'].join("\n");
const dir = mkdtempSync(join(tmpdir(), "cdpidle-"));
writeFileSync(join(dir, "debuggee3350.mjs"), src);
const child = spawn(process.execPath, [join(dir, "debuggee3350.mjs")], { stdio: ["ignore", "pipe", "ignore"] });
let out = ""; child.stdout.on("data", d => (out += d));
const url = await new Promise(r => { const iv = setInterval(() => { const m = /URL (\S+)/.exec(out); if (m) { clearInterval(iv); r(m[1]); } }, 20); });
const sleep = ms => new Promise(r => setTimeout(r, ms));
let pauses = 0;
const attach = () => new Promise(res => { const ws = new WebSocket(url); const c = { ws, byId: new Map() };
ws.onmessage = e => { const m = JSON.parse(String(e.data));
if (m.id !== undefined) c.byId.set(m.id, m);
else if (m.method === "Debugger.paused") { pauses++; ws.send(JSON.stringify({ id: 100000 + pauses, method: "Debugger.resume" })); } };
ws.onopen = () => res(c); });
const cmd = async (c, id, method, params = {}) => { c.ws.send(JSON.stringify({ id, method, params }));
for (let i = 0; i < 300; i++) { if (c.byId.has(id)) return c.byId.get(id); await sleep(10); } return { timeout: true }; };
const A = await attach();
await cmd(A, 1, "Debugger.enable");
await cmd(A, 2, "Debugger.setBreakpointByUrl", { lineNumber: 6, urlRegex: "debuggee3350\\.mjs$" });
pauses = 0; await sleep(1500); const before = pauses;
const B = await attach(); B.ws.close(); await sleep(300);
pauses = 0; await sleep(1500); const after = pauses;
console.log(`A's breakpoint pauses in 1.5s before B: ${before}; after B attached and closed without sending anything: ${after}`);
child.kill("SIGKILL");
process.exit(0);Where the fix can liveThe sizes are estimates from the review. No option is built yet.
The review picked option 1. Node works this way: one Decision needed from a maintainerWill the oven-sh/WebKit fork take a per-frontend inspector session? The change adds session files. It edits the controller,
Notes
|
With two clients attached to one
inspector.open()server, client B can silently hijack or blind client A: B'sDebugger.setBreakpointsActive{active:false}orDebugger.disablestops A's breakpoints, B'sRuntime.disablesilences A's console stream, B receives A'sDebugger.paused/Runtime.consoleAPICalledwithout ever enabling those domains, and B can read orreleaseObjectA'sRuntime.RemoteObjecthandles by id. Node gives each WebSocket its ownV8InspectorSessionand is per-session on every cell of that matrix.Repro
Cause
Every WebSocket client is a
FrontendChannelon the one per-processJSGlobalObjectInspectorController, which owns a singleInspectorDebuggerAgent/InspectorRuntimeAgent/InjectedScript.FrontendRouter::sendResponse/sendEventbroadcast to every channel (the// FIXME: send responses to the appropriate frontendinInspectorFrontendRouter.cpp), anddispatchMessageFromRemotecarries no sender identity, so every agent's enable flags, breakpoints,breakpointsActive,pauseOnExceptionsand RemoteObject id table are process-global across clients.Fix
The CDP adapter already sits between each WebSocket and the shared JSC backend, so do the per-session scoping there (no WebKit changes):
#pendingmap and ids stay withinBackendDispatcher's 32-bit int. (Same approach as node:inspector: route CDP responses to the right client when multiple are attached #35701, which this PR subsumes.)debuggerEnabled/runtimeEnabledgating of broadcast events and of inbound Debugger commands (pause/resume/step*/evaluateOnCallFramereplyDebugger agent is not enabled), and refcountedDebugger/Runtime/Consoleenable so one client'sdisabledoes not tear the shared agent down under another. The deprecatedConsole.enable/disableare acknowledged locally.breakpointsActive/pauseOnExceptionswith an aggregate written to the backend only on change; per-adapter breakpoint ownership soremoveBreakpointcannot delete another client's, andbreakpointResolved/Debugger.paused.hitBreakpointsare filtered to the owner.objectIds: every outboundRemoteObject.objectIdgets abunSessionIdfield (skippingRemoteObject.value, which is user JSON underreturnByValue); inbound ids without this adapter's tag are rejected with V8'sCould not find object with given id, includingcallFunctionOnarguments[].objectId.objectGroupnames are likewise prefixed per session soreleaseObjectGroupcannot free another client's handles.dispose()on connection close removes the session's breakpoints and contribution to the aggregates.Verification
New test
two inspector.open() clients have isolated Debugger/Runtime session statedrives A's breakpoint before and after B'ssetBreakpointsActive(false)/removeBreakpoint/Debugger.disable, checks B can't read or release A'sobjectIdviagetProperties/callFunctionOn(target orarguments[]) /releaseObject/releaseObjectGroup, checks B'sRuntime.disable/Console.disabledoesn't silence A, checks B'sevaluateOnCallFrameis rejected, and checksreturnByValueuser JSON with anobjectIdproperty round-trips unchanged. Fails on main at the second pause count (Expected: 2, Received: 1), passes with the fix. Fulltest/js/node/inspector/inspector.test.ts24/24.[review] gate passed · iteration 2 · 3 files touched
fails on main (without fix)
passes on PR (with fix)
diff hotspot
gate history · 4 passed · 1 rejected · iteration 2
evidence per changed file