Skip to content

websocket client: echo the received close code verbatim on the wire - #35529

Closed
robobun wants to merge 4 commits into
mainfrom
farm/bbc31fc3/websocket-close-echo
Closed

robobun wants to merge 4 commits into
mainfrom
farm/bbc31fc3/websocket-close-echo

Conversation

@robobun

@robobun robobun commented Jul 25, 2026 •

Copy link
Copy Markdown
Collaborator

Problem

When the client WebSocket receives a server-initiated Close frame, RFC 6455 section 5.5.1 says the echo it sends back "typically echoes the status code it received". Bun rewrote the echo in three cases:

  • a server Close frame with no status code (empty payload) was answered with an explicit 1000, so the peer could no longer tell "no status" from a deliberate normal closure. This is exactly what the reserved off-wire code 1005 exists to represent; putting 1000 on the wire hides it.
  • a received 1001 ("going away") was answered with 1000.
  • a Close frame whose 2-byte header and status-code bytes arrived in separate TCP reads was treated as bodyless (echoed bodyless, JS reported 1005) or, if exactly one code byte arrived with the header, failed as InvalidControlFrame.

Every other legal code already echoed verbatim. Node/undici echo bodyless → bodyless and 1001 → 1001.

The JS-visible CloseEvent.code was already correct for the first two cases (1005 for bodyless, 1001 for 1001); only the wire echo was wrong. The split-read case was wrong on both the wire and in JS.

Repro

// server sends a close frame, records what the client echoes back on the wire
import net from "node:net"; import crypto from "node:crypto";
const acc = k => crypto.createHash("sha1").update(k + "258EAFA5-E914-47DA-95CA-C5AB0DC85B11").digest("base64");
const cases = ["EMPTY", 1000, 1001, 1002, 3000]; let ci = -1;
const frame = c => c === "EMPTY" ? Buffer.from([0x88, 0]) : Buffer.from([0x88, 2, c >> 8, c & 0xff]);
const srv = net.createServer(sock => { let head = "", up = false, c = -1; sock.on("data", ch => {
  if (!up) { head += ch.toString("latin1"); if (!head.includes("\r\n\r\n")) return; up = true; c = ++ci;
    const key = /Sec-WebSocket-Key: (.+)\r\n/i.exec(head)[1].trim();
    sock.write(`HTTP/1.1 101 Switching Protocols\r\nUpgrade: websocket\r\nConnection: Upgrade\r\nSec-WebSocket-Accept: ${acc(key)}\r\n\r\n`);
    setTimeout(() => sock.write(frame(cases[c])), 60); return; }
  if ((ch[0] & 15) === 8) { const len = ch[1] & 127, k = ch.subarray(2, 6);
    const code = len >= 2 ? ((ch[6] ^ k[0]) << 8 | (ch[7] ^ k[1])) : "EMPTY";
    console.log(`server sent ${cases[c]} -> client echoed ${code}`); if (c === cases.length - 1) process.exit(0); }
}); }).listen(0, "127.0.0.1", () => { let i = 0;
  const next = () => { if (i >= cases.length) return; const ws = new WebSocket(`ws://127.0.0.1:${srv.address().port}`); i++; ws.onerror = () => {}; ws.onclose = () => setTimeout(next, 50); };
  next(); });
bun (before):  EMPTY -> 1000 | 1000 -> 1000 | 1001 -> 1000 | 1002 -> 1002 | 3000 -> 3000
node:          EMPTY -> EMPTY | 1000 -> 1000 | 1001 -> 1001 | 1002 -> 1002 | 3000 -> 3000
bun (after):   EMPTY -> EMPTY | 1000 -> 1000 | 1001 -> 1001 | 1002 -> 1002 | 3000 -> 3000

Cause

src/http_jsc/websocket_client.rs:

  • send_close() (the bodyless-Close echo path) called send_close_with_body(1000, Some(1005), &[]), and send_close_with_body had no way to emit a bodyless frame: it always wrote the 2-byte code.
  • received_close_codes() special-cased 1001: let echo = if dispatch == 1001 { 1000 } else { dispatch }.
  • recv_close() checked body_remain == 0 / == 1 on every entry. Once buffer_control_payload has started buffering a partial payload it repurposes body_remain to "bytes buffered so far", so on re-entry a Close whose header arrived alone (buffered = 0) hit the bodyless branch and one whose header arrived with a single code byte (buffered = 1) hit the InvalidControlFrame branch. recv_ping_or_pong already gated its size check on !control_frame_started; recv_close did not.

Fix

  • send_close_with_body now takes code: Option<u16>. None emits a bodyless Close frame (payload length 0, mask key still present). The JS dispatch code falls back to 1005 when both code and dispatch_code are None.
  • send_close() passes None for the wire code.
  • received_close_codes() is replaced by received_close_code() -> u16: with the 1001 -> 1000 rewrite gone, the wire echo and JS dispatch are always the same value.
  • recv_close() gates its length checks on !control_frame_started, matching recv_ping_or_pong.

The JS ws.close(code, reason) entrypoint passes Some(code) and is unchanged in behaviour.

Verification

New describe block in test/js/web/websocket/websocket-close-code.test.ts runs a raw TCP server that sends a Close frame (optionally split across writes) and unmasks the client's echo, asserting both the wire code and CloseEvent.code for EMPTY, 1000, 1001, 1002, 1003, 3000, 4999, and two split-read variants.

# USE_SYSTEM_BUN=1 (before)
(fail) server sends EMPTY > client echoes EMPTY ...                    # got wireCode 1000
(fail) server sends 1001  > client echoes 1001 ...                     # got wireCode 1000
(fail) Close header and code split across reads ...                    # got jsCode 1005
(fail) Close header and 1 payload byte split across reads ...          # ECONNRESET
5 pass, 4 fail

# bun bd (after)
33 pass, 0 fail   (whole file)

websocket.test.js -t close (22 tests), websocket-client.test.ts (34 tests), websocket-close-fragmented.test.ts, websocket-pong-fragmented.test.ts, and websocket-client-short-read.test.ts pass unchanged.

Not a duplicate of #33457: that PR fixes the user-initiated ws.close() (no arguments) path to send a bodyless frame; this one fixes the server-initiated echo path. They share the Option<u16> refactor of send_close_with_body so whichever lands second will need a small rebase there.


[review] gate passed · iteration 2 · 2 files touched

fails on main (without fix)
ASAN without fix: 4 FAILED
$ BUN_DEBUG_QUIET_LOGS=1 bun scripts/build.ts --profile=debug --quiet test "--reporter=junit" "--reporter-outfile=/tmp/mechgate.xml" test/js/web/websocket/websocket-close-code.test.ts
bun test v1.4.0 (a3aa9c5fd)

test/js/web/websocket/websocket-close-code.test.ts:
(pass) WebSocket close() argument validation > throws InvalidAccessError for close codes an endpoint must not send [172.61ms]
(pass) WebSocket close() argument validation > throws SyntaxError when the reason is longer than 123 UTF-8 bytes [163.26ms]
(pass) WebSocket close() argument validation > validates arguments even when the socket is already closed [134.63ms]
(pass) WebSocket close() argument validation > validates arguments while the socket is still connecting [125.82ms]
(pass) WebSocket close() argument validation > accepts a reason of exactly 123 UTF-8 bytes [177.23ms]
(pass) WebSocket close() argument validation > close(1000) is allowed > and the code and reason reach the server [95.95ms]
(pass) WebSocket close() argument validation > close(1001) is allowed > and the code and reason reach the server [84.86ms]
(pass) WebSocket close() argument validation > close(1002) is allowed > and the code and 
... (truncated)

release without fix: 4 FAILED
bun test v1.4.0-canary.1 (a3aa9c5fd)

test/js/web/websocket/websocket-close-code.test.ts:
(pass) WebSocket close() argument validation > throws InvalidAccessError for close codes an endpoint must not send [36.48ms]
(pass) WebSocket close() argument validation > throws SyntaxError when the reason is longer than 123 UTF-8 bytes [23.70ms]
(pass) WebSocket close() argument validation > validates arguments even when the socket is already closed [21.24ms]
(pass) WebSocket close() argument validation > validates arguments while the socket is still connecting [20.77ms]
(pass) WebSocket close() argument validation > accepts a reason of exactly 123 UTF-8 bytes [25.76ms]
(pass) WebSocket close() argument validation > close(1000) is allowed > and the code and reason reach the server [22.72ms]
(pass) WebSocket close() argument validation > close(1001) is allowed > and the code and reason reach the server [21.70ms]
(pass) WebSocket close() argument validation > close(1002) is allowed > and the code and reason reach the server [21.90ms]
(pass) WebSocket close() argument validation > close(1003) is allowed > and the code and reason reach the server [21.53ms]
(pass) WebSocket close(
... (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/web/websocket/websocket-close-code.test.ts
bun test v1.4.0 (a3aa9c5fd)

test/js/web/websocket/websocket-close-code.test.ts:
(pass) WebSocket close() argument validation > throws InvalidAccessError for close codes an endpoint must not send [196.31ms]
(pass) WebSocket close() argument validation > throws SyntaxError when the reason is longer than 123 UTF-8 bytes [180.21ms]
(pass) WebSocket close() argument validation > validates arguments even when the socket is already closed [146.27ms]
(pass) WebSocket close() argument validation > validates arguments while the socket is still connecting [137.80ms]
(pass) WebSocket close() argument validation > accepts a reason of exactly 123 UTF-8 bytes [197.70ms]
(pass) WebSocket close() argument validation > close(1000) is allowed > and the code and reason reach the server [115.57ms]
(pass) WebSocket close() argument validation > close(1001) is allowed > and the code and reason reach the server [104.47ms]
(pass) WebSocket close() argument validation > close(1002) is allowed > and the code an
... (truncated)

release with fix: all passed
$ bun scripts/build.ts --profile=release
[configured] bun-profile → bun (stripped) in 845ms (unchanged)
ninja: Entering directory `/workspace/bun/build/release'
[1/9] cc obj/src/jsc/bindings/node/http/llhttp/http.c.o
[2/9] cc obj/src/jsc/bindings/node/http/llhttp/api.c.o
[3/9] cc obj/src/jsc/bindings/node/http/llhttp/llhttp.c.o
[4/9] cxx obj/unified/UnifiedSource-src_jsc_bindings_node_http-0.cpp.o
[5/9] cxx obj/unified/UnifiedSource-src_jsc_bindings-3.cpp.o
[6/9] cxx obj/src/jsc/bindings/ZigGlobalObject.cpp.o
[6/9] link bun-profile
[7/9] bun-profile --revision
1.4.0-canary.1+a3aa9c5fd
[9/9] strip bun
[build] done
bun test v1.4.0-canary.1 (a3aa9c5fd)

test/js/web/websocket/websocket-close-code.test.ts:
(pass) WebSocket close() argument validation > throws InvalidAccessError for close codes an endpoint must not send [12.83ms]
(pass) WebSocket close() argument validation > throws SyntaxError when the reason is longer than 123 UTF-8 bytes [11.54ms]
(pass) WebSocket close() argument validation > validates arguments even when the socket is already closed [9.96ms]
(pass) WebSocket close() argument validation > validates arguments while the socket is still connecting [9.2
... (truncated)
diff hotspot
src/http_jsc/websocket_client.rs                   |  94 ++++++++--------
 test/js/web/websocket/websocket-close-code.test.ts | 119 +++++++++++++++++++++
 2 files changed, 170 insertions(+), 43 deletions(-)

gate history · 1 passed · 2 rejected · iteration 2

evidence per changed file
file                                                reads  edits  tests
src/http_jsc/websocket_client.rs                        9      6      0
test/js/web/websocket/websocket-close-code.test.ts      2      2      0

@robobun

robobun commented Jul 25, 2026 •

Copy link
Copy Markdown
Collaborator Author

Reproduced with the raw-TCP repro in the PR body: bodyless Close echoed as 1000, 1001 echoed as 1000, and a Close frame split at the header boundary reported 1005 / failed as InvalidControlFrame. With this change all three echo the received code verbatim; CloseEvent.code for the first two was already correct and is unchanged. PR: #35529

CI on build #80259 (final): 195 jobs passed with no websocket-client failures; the only hard failure is :package: binary-size (+~540 KB across all targets). This diff nets ~40 lines in one Rust file and cannot account for that; the size-check baseline is canary #79916 which predates the node:quic (#32602), node:repl (#31827) and node:inspector (#31823) merges this branch is rebased on top of. The handful of [flaky] annotations (inspect, webview-chrome, terminal-platform-gaps, no-orphans) passed on retry and are unrelated to the websocket client.

@coderabbitai

coderabbitai Bot commented Jul 25, 2026 •

Copy link
Copy Markdown
Contributor

Review Change Stack

Warning

Review limit reached

@robobun, you've reached your PR review limit, so we couldn't start this review.

Next review available in: 20 minutes

Enable usage-based reviews in Billing to review now. Otherwise, wait until the next included review is available.
You're only billed for reviews past your plan's rate limits ($0.25/file).

How can I continue?

After more reviews become available, a review can be triggered using the @coderabbitai review command as a PR comment. Alternatively, push new commits to this PR.

To avoid repeated limits, reduce automatic review volume by pausing incremental auto-reviews earlier, using label-based review opt-in, excluding WIP or generated PR titles, or requesting reviews manually when the PR is ready. If your team needs uninterrupted high-volume reviews, an organization admin can enable usage-based reviews.

How do review limits work?

CodeRabbit enforces per-developer PR review limits for each organization. Most developers receive the normal plan review availability.

For paid Pro and Pro+ PR reviews, CodeRabbit uses adaptive limits for sustained high-volume activity. When a developer's recent PR review activity reaches the 95th percentile or higher among CodeRabbit users, additional reviews become available more gradually as earlier reviews age out of the rolling window.

Please refer docs for additional details.

Review details
⚙️ Run configuration

Configuration used: Path: .coderabbit.yaml

Review profile: ASSERTIVE

Plan: Pro

Run ID: f9a234ce-28df-4ef3-9e9f-e84c4b0c140c

📥 Commits

Reviewing files that changed from the base of the PR and between fae8525 and e6255cc.

📒 Files selected for processing (1)
  • src/http_jsc/websocket_client.rs

Walkthrough

Changes

The WebSocket client now supports bodyless Close frames, preserves received status codes when echoing, and derives JavaScript close codes through optional payload handling. New TCP-level tests cover legal codes, bodyless closes, and Close frames split across reads.

WebSocket close handling

Layer / File(s) Summary
Close-frame parsing and response
src/http_jsc/websocket_client.rs
Close parsing handles bodyless frames and partial buffering, maps received codes, and builds optional-code Close responses with matching JavaScript dispatch codes.
Close-frame echo regression coverage
test/js/web/websocket/websocket-close-code.test.ts
TCP-level tests verify echoed wire codes and JavaScript CloseEvent.code values for legal, bodyless, and split Close frames.

Suggested reviewers: jarred-sumner

🚥 Pre-merge checks | ✅ 4
✅ Passed checks (4 passed)
Check name Status Explanation
Title check ✅ Passed The title accurately summarizes the main change: server-initiated WebSocket close codes are echoed verbatim on the wire.
Description check ✅ Passed It covers the problem, fix, reproduction, and verification details, though it uses different headings than the template.
Linked Issues check ✅ Passed Check skipped because no linked issues were found for this pull request.
Out of Scope Changes check ✅ Passed Check skipped because no linked issues were found for this pull request.

Comment @coderabbitai help to get the list of available commands.

@robobun

robobun commented Jul 25, 2026 •

Copy link
Copy Markdown
Collaborator Author
Updated 3:11 AM PT - Jul 25th, 2026

❌ @robobun, your commit e6255cc has 1 failures in Build #80259 (All Failures):

  • 📦 Binary size — 12 over 0.50 MB
  • targetthis build canary: main #79916
    sizeΔ
    ❌ bun-darwin-aarch6458.13 MB57.58 MB+564.9 KB
    ❌ bun-darwin-x6463.48 MB62.95 MB+544.5 KB
    ❌ bun-linux-aarch6470.98 MB70.42 MB+576.0 KB
    ❌ bun-linux-x6472.47 MB71.95 MB+528.0 KB
    ❌ bun-linux-aarch64-musl64.88 MB64.32 MB+576.0 KB
    ❌ bun-linux-x64-musl66.98 MB66.45 MB+544.0 KB
    ❌ bun-linux-aarch64-android78.47 MB77.97 MB+512.0 KB
    ❌ bun-linux-x64-android80.62 MB80.10 MB+529.2 KB
    ❌ bun-freebsd-x6483.07 MB82.56 MB+528.0 KB
    ❌ bun-freebsd-aarch6484.84 MB84.31 MB+544.0 KB
    ❌ bun-windows-x6480.26 MB79.70 MB+570.5 KB
    ❌ bun-windows-aarch6470.86 MB70.34 MB+533.0 KB

    Add [skip size check] to the commit message if this increase is intentional.


🧪   To try this PR locally:

bunx bun-pr 35529

That installs a local version of the PR into your bun-35529 executable, so you can run:

bun-35529 --bun

@github-actions

Copy link
Copy Markdown
Contributor

This PR may be a duplicate of:

  1. websocket: close() with no code sends an empty close payload #33457 - Both fix the bodyless-close-frame echo bug by changing send_close_with_body() code param from u16 to Option<u16> and modifying send_close() to send an empty payload instead of 1000, with tests in the same websocket-close-code.test.ts file.

🤖 Generated with Claude Code

@robobun

robobun commented Jul 25, 2026

Copy link
Copy Markdown
Collaborator Author

Not a duplicate of #33457. They share the send_close_with_body(Option<u16>, ...) refactor but fix different bugs:

  • websocket: close() with no code sends an empty close payload #33457 fixes the user-initiated ws.close() (no arguments) path: the C++ side now passes a 1005 sentinel so the client sends a bodyless frame instead of 1000.
  • This PR fixes the server-initiated echo path: when the server sends a Close and the client echoes it back, a bodyless Close now echoes bodyless (not 1000) and a received 1001 echoes 1001 (not 1000).

#33457's send_close() still passes Some(1000) for the echo and does not touch received_close_codes, so neither of the two cases in this PR's repro is fixed there. Whichever lands first will create a small merge conflict in send_close_with_body; happy to rebase on top of #33457 if it goes in first.

@robobun
robobun force-pushed the farm/bbc31fc3/websocket-close-echo branch from 75a4c3e to 2b32f3f Compare July 25, 2026 02:53

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

Additional findings (outside current diff — PR may have been updated during review):

  • 🟣 src/http_jsc/websocket_client.rs:900-907 — Pre-existing (not introduced by this PR), noting since it's the same "close code not echoed verbatim" class: recv_close's body_remain == 1 and body_remain == 0 checks aren't guarded by !self.control_frame_started.get(), unlike recv_ping_or_pong. Once buffer_control_payload has run once and returned None, body_remain is repurposed to "bytes buffered so far", so if a Close frame's 2-byte header arrives alone in one TCP read and the code bytes arrive in the next, re-entry hits the bodyless branch (echoes bodyless, JS sees 1005) and the server's actual code is discarded; header+1 payload byte re-enters into InvalidControlFrame. Guarding both checks with !self.control_frame_started.get() would fix it — happy to do as a follow-up.

    Extended reasoning...

    What this is

    recv_close() decides how to handle a received Close frame by inspecting cursor.body_remain:

    fn recv_close(&self, cursor: &mut RecvCursor<'_>) -> Step {
        if cursor.body_remain == 1 || cursor.body_remain > MAX_CONTROL_PAYLOAD {
            return self.recv_failed(ErrorCode::InvalidControlFrame);
        }
        if cursor.body_remain == 0 {
            self.close_received.set(true);
            self.send_close();
            return Step::Terminated;
        }
        let Some((payload, payload_len)) = self.buffer_control_payload(cursor) else {
            return Step::NeedMoreData;
        };
        ...
    }

    These two guards assume body_remain still means "declared payload length from the frame header". But buffer_control_payload()'s doc comment states: "While control_frame_started, cursor.body_remain counts bytes buffered so far, not bytes left." Once buffer_control_payload has run once and returned None (partial read), it has set control_frame_started = true and repurposed body_remain. handle_data_loop's epilogue then persists that repurposed value into self.receive_body_remain, and the next handle_data call restores it into cursor.body_remain before re-entering recv_close.

    recv_ping_or_pong handles this correctly — its size check is gated on !self.control_frame_started.get(). recv_close is not.

    Step-by-step trigger

    Server sends a Close frame with code 1000, but the TCP stack delivers it as two reads: first the 2-byte header [0x88, 0x02] alone, then the 2-byte code [0x03, 0xE8].

    Read 1 (data = [0x88, 0x02]):

    1. recv_frame_header consumes both bytes, sets state = Close, body_remain = 2, returns Continue with cursor.data empty.
    2. recv_close: body_remain = 2 → falls through to buffer_control_payload.
    3. buffer_control_payload: control_frame_started is false → sets ping_len = 2, body_remain = 0, control_frame_started = true. cursor.data is empty so nothing is copied. payload_len (2) > body_remain (0) → returns None.
    4. recv_close returns NeedMoreData. Loop epilogue persists receive_body_remain = 0, receive_state = Close.

    Read 2 (data = [0x03, 0xE8]):
    5. handle_data_loop restores cursor.body_remain = 0, cursor.state = Close.
    6. recv_close: body_remain == 0 → takes the bodyless branch → self.send_close() echoes a bodyless Close and dispatches 1005 to JS.

    The server's actual code (1000) is discarded and its bytes are never consumed.

    Variant: if exactly 1 payload byte arrives with the header ([0x88, 0x02, 0x03]), buffer_control_payload copies 1 byte and body_remain persists as 1. On re-entry recv_close sees body_remain == 1 → recv_failed(InvalidControlFrame) → abrupt close (JS sees 1002, not the server's code).

    Why nothing prevents it

    control_frame_started is a Cell<bool> on self, so it survives across handle_data calls. handle_data_loop unconditionally persists cursor.body_remain on NeedMoreData. The only defense would be gating the == 0 / == 1 checks on !self.control_frame_started.get() — which recv_ping_or_pong does for its > MAX_CONTROL_PAYLOAD check, but recv_close does not.

    The existing test websocket-close-fragmented.test.ts doesn't cover this: it sends the header plus 12 payload bytes together in the first segment (code + 10-byte reason), so on re-entry body_remain = 12 and both checks are bypassed.

    Impact and relationship to this PR

    This is pre-existing; the PR neither introduces nor worsens it. Before this PR, the body_remain == 0 misroute called send_close() which echoed 1000 on the wire and dispatched 1005 to JS; after this PR it echoes bodyless and still dispatches 1005 — JS-visible behavior is identical, and the wire echo is arguably less wrong now (bodyless is at least a legal echo shape). The body_remain == 1 misroute is byte-identical before and after.

    It's flagged here only because the PR touches recv_close / send_close directly and the failure mode — "server's close code is not echoed verbatim" — is exactly the class the PR title claims to address, so a follow-up in the same area seems worthwhile. The trigger is narrow (a 4-byte Close frame split at the exact header boundary by the TCP stack), so it shouldn't block this PR.

    Fix

    Mirror recv_ping_or_pong:

    fn recv_close(&self, cursor: &mut RecvCursor<'_>) -> Step {
        if !self.control_frame_started.get() {
            if cursor.body_remain == 1 || cursor.body_remain > MAX_CONTROL_PAYLOAD {
                return self.recv_failed(ErrorCode::InvalidControlFrame);
            }
            if cursor.body_remain == 0 {
                self.close_received.set(true);
                self.send_close();
                return Step::Terminated;
            }
        }
        let Some((payload, payload_len)) = self.buffer_control_payload(cursor) else { ... };
        ...
    }

Comment thread src/http_jsc/websocket_client.rs Resolved
@robobun

robobun commented Jul 25, 2026

Copy link
Copy Markdown
Collaborator Author

Addressed all three review points in 816d13c:

  • received_close_codes collapsed to received_close_code(u16) -> u16; the tuple was vestigial once the wire echo and JS dispatch can no longer differ.
  • recv_close now gates its body_remain == 0 / == 1 / > 125 checks on !control_frame_started, matching recv_ping_or_pong. Folded in here since it's the same function and the same "received code not echoed verbatim" failure mode. Two split-read test cases cover it (header alone, and header + 1 payload byte); both fail on the unfixed build.
  • Test helper's gotEcho now rejects on socket error/close so a missing echo surfaces as an assertion failure instead of a timeout.

Fail-before on stock bun: 4 fail (EMPTY, 1001, and the two split-read cases). With the fix: 33/33 pass.

@robobun
robobun force-pushed the farm/bbc31fc3/websocket-close-echo branch from 816d13c to a3aa9c5 Compare July 25, 2026 03:09
Jarred-Sumner pushed a commit that referenced this pull request Jul 25, 2026
…35534)

Adds a self-contained GitHub Action that scans `claude`-labeled PRs for
multi-line comment blocks added under `src/` and leaves a review line
comment on each one asking for it to be deleted (and the thread resolved
once done).

### Behavior

- Triggers on `pull_request_target` (`opened` / `synchronize` /
`reopened` / `labeled`), gated on `github.repository == 'oven-sh/bun'`
and the `claude` label being present. The `labeled` trigger covers the
normal case where `auto-label-claude-prs.yml` applies the label after
open.
- Fetches PR files via `pulls.listFiles` and parses the unified diff in
`actions/github-script`. No repo checkout.
- A group is **2+ consecutive added lines** that are pure comment lines
(`//`, `///`, `//!`, `/* ... */`, `* ` continuation) in `.rs` / `.c` /
`.cpp` / `.h` / `.ts` / `.js` and friends. Groups containing `SAFETY:`
are skipped.
- Posts one standalone review line comment per consecutive group via
`pulls.createReviewComment` (no review summary).
- Each comment carries `<!-- comment-cop:<path>:<sha12> -->` keyed on
the group's content hash, so reruns (new pushes, relabels) skip groups
that already have a marker.
- On each run, any existing comment-cop thread whose flagged block is no
longer present in the diff is auto-resolved via `resolveReviewThread`.

### Verification

Dry-ran the parser against the five most recent open `claude` PRs via
`gh api repos/oven-sh/bun/pulls/<n>/files`:

```
#35531  src/runtime/webcore/Blob.rs:5245-5246
#35529  src/http_jsc/websocket_client.rs:907-910
#35528  src/runtime/webcore/FileSink.rs:917-920
#35526  src/http_jsc/websocket_client.rs:2179-2182
#35532  (clean)
```

Cross-checked `#35531` line numbers against the fetched head ref;
`Blob.rs:5245` is the first line of the flagged block. `actionlint` and
prettier both pass.

<!-- robobun:evidence:begin -->

---

**no test proof** · iteration 0 · build/CI scripts only; test-proof not
applicable

<!-- robobun:evidence:end -->

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

Additional findings (outside current diff — PR may have been updated during review):

  • 🟣 src/http_jsc/websocket_client.rs:892-902 — Pre-existing (not introduced by this PR), but since you're in recv_close: its two cursor.body_remain guards are evaluated on every entry, yet after buffer_control_payload sets control_frame_started, body_remain has been repurposed from "declared payload length" to "bytes buffered so far". If a server's Close frame with a code arrives split so the first TCP read delivers only the 2-byte header (or header + 1 payload byte), the persisted body_remain is 0 (or 1) and the next entry short-circuits to send_close() (JS sees 1005) or recv_failed(InvalidControlFrame) (JS sees 1002) instead of resuming buffer_control_payload to read the real code. Fix: gate both checks on !self.control_frame_started.get(), mirroring recv_ping_or_pong.

    Extended reasoning...

    What the bug is

    recv_close opens with two guards that inspect cursor.body_remain:

    fn recv_close(&self, cursor: &mut RecvCursor<'_>) -> Step {
        if cursor.body_remain == 1 || cursor.body_remain > MAX_CONTROL_PAYLOAD {
            return self.recv_failed(ErrorCode::InvalidControlFrame);
        }
        if cursor.body_remain == 0 {
            self.close_received.set(true);
            self.send_close();
            return Step::Terminated;
        }
        let Some((payload, payload_len)) = self.buffer_control_payload(cursor) else {
            return Step::NeedMoreData;
        };
        ...

    These guards assume body_remain is the declared payload length from the frame header. That's true on first entry. But buffer_control_payload — per its own doc comment — repurposes body_remain while control_frame_started is set: "While control_frame_started, cursor.body_remain counts bytes buffered so far, not bytes left." On its first call it stashes the declared length into ping_len, sets body_remain = 0, sets control_frame_started = true, then accumulates bytes. When the payload spans TCP reads it returns None, recv_close returns NeedMoreData, and the loop epilogue persists the accumulator value into self.receive_body_remain. On the next read, recv_close re-runs both guards against the accumulator, not the declared length.

    The sibling recv_ping_or_pong guards its equivalent check with exactly this condition:

    if !self.control_frame_started.get() && cursor.body_remain > MAX_CONTROL_PAYLOAD {

    recv_close does not, so it mis-validates on re-entry.

    Step-by-step proof (header-only first read)

    Server sends Close code 3000, no reason: bytes [0x88, 0x02, 0x0B, 0xB8]. TCP delivers [0x88, 0x02] in the first read and [0x0B, 0xB8] in the second.

    First read [0x88, 0x02]:

    1. handle_data_loop inits cursor{state=NeedHeader, body_remain=0}.
    2. recv_frame_header consumes both bytes → state=Close, body_remain=2, data=[], returns Continue (its data.is_empty() early-return only fires for state==NeedBody).
    3. Loop iterates → recv_close. body_remain=2 passes both guards. buffer_control_payload: control_frame_started is false → sets ping_len=2, body_remain=0, control_frame_started=true; data is empty so nothing is copied; payload_len(2) > body_remain(0) → returns None. recv_close returns NeedMoreData.
    4. Loop epilogue (terminated=false) persists receive_state=Close, receive_body_remain=0. close_received is not set (only set after buffer_control_payload returns Some, or in the body_remain==0 branch which didn't fire).

    Second read [0x0B, 0xB8]:
    5. handle_data checks close_received → false → proceeds. handle_data_loop inits cursor{state=Close, body_remain=0}.
    6. recv_close re-entry: first guard body_remain==1 → false; second guard body_remain==0 → true → self.send_close() + Step::Terminated.

    Result: the client echoes a bodyless Close and JS sees CloseEvent.code == 1005. Correct behavior would resume buffer_control_payload (since control_frame_started is still true on self), copy the two payload bytes, reach the payload_len >= 2 branch, and dispatch code 3000.

    Step-by-step proof (header + 1 payload byte in first read)

    First read [0x88, 0x02, 0x0B]: step 3 copies 1 byte → body_remain=1, payload_len(2) > body_remain(1) → None → persisted receive_body_remain=1. Second read [0xB8]: recv_close re-entry hits the first guard body_remain==1 → recv_failed(InvalidControlFrame) → JS sees 1002 with wasClean=false and the socket is RST'd via terminate → fail → cancel(Failure).

    Why existing tests don't catch it

    websocket-close-fragmented.test.ts splits the Close frame after 12 payload bytes are already buffered (header + code + 10 reason bytes), so the persisted accumulator is never 0 or 1. This PR's new tests write each frame in one sock.write(), and websocket-client-short-read.test.ts doesn't cover a Close split at the header/payload boundary.

    Impact

    When a server's Close frame with a status code lands with a TCP read boundary at exactly byte 2 or byte 3 of the frame, the client reports the wrong CloseEvent.code (1005 or 1002 instead of the received code), and in the byte-3 case treats a valid frame as a protocol error and RSTs. This is timing-dependent and rare over loopback, but reachable on real networks — a 4-byte Close frame following a ≥MSS burst can straddle a segment boundary.

    Relation to this PR

    Pre-existing. The guards are untouched; the PR only wraps the send_close_with_body args at line 895 in Some() and changes what send_close() puts on the wire. The PR slightly changes the wire symptom of the body_remain==0 sub-case (bodyless echo instead of 1000), but the JS-visible wrong code (1005) and the root cause — validating the accumulator as if it were the declared length — are identical before and after. The PR neither introduces nor worsens the reachability. Flagging only because the author is in this exact function; not blocking.

    Fix

    Gate both checks on !self.control_frame_started.get(), matching recv_ping_or_pong:

    fn recv_close(&self, cursor: &mut RecvCursor<'_>) -> Step {
        if !self.control_frame_started.get() {
            if cursor.body_remain == 1 || cursor.body_remain > MAX_CONTROL_PAYLOAD {
                return self.recv_failed(ErrorCode::InvalidControlFrame);
            }
            if cursor.body_remain == 0 {
                self.close_received.set(true);
                self.send_close();
                return Step::Terminated;
            }
        }
        let Some((payload, payload_len)) = self.buffer_control_payload(cursor) else {
            return Step::NeedMoreData;
        };
        ...

@robobun

robobun commented Jul 25, 2026

Copy link
Copy Markdown
Collaborator Author

Already addressed in a3aa9c5 (the review ran against a pre-rebase snapshot): recv_close's length guards are now gated on !self.control_frame_started.get(), matching recv_ping_or_pong, and the two split-read cases (header alone → would report 1005; header + 1 payload byte → would fail as InvalidControlFrame) are covered by the new tests at the bottom of websocket-close-code.test.ts. Both fail on stock bun and pass on this branch.

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

LGTM — both prior review comments are addressed and the split-read fix now mirrors recv_ping_or_pong.

What was reviewed:

  • Traced the two split-read cases (header-only and header+1-byte) through recv_close → buffer_control_payload re-entry with the new !control_frame_started gate — both now reach send_close_with_body(Some(code), None, …) with the correct code.
  • Checked the bodyless echo path: Mask::fill_in_place still writes the 4-byte mask key into frame[2..6] before early-returning on the empty payload, so the 6-byte masked frame (0x88 0x80 <mask>) stays RFC-5.3-compliant.
  • Confirmed gotEcho.reject on sock.on('close') after resolve is a no-op, so the happy path isn't broken by the added rejection wiring.
Extended reasoning...

Overview

Three related fixes to the WebSocket client's server-initiated Close handling in src/http_jsc/websocket_client.rs:

  1. send_close_with_body now takes code: Option<u16> so None emits a genuine bodyless Close frame (payload length 0, mask key still present). send_close() passes None instead of 1000, so a received bodyless Close is echoed bodyless rather than as an explicit 1000.
  2. received_close_codes → received_close_code(u16) -> u16: the 1001 → 1000 wire-echo rewrite is removed, so 1001 echoes verbatim. With that gone, the wire echo and JS dispatch are always identical, so the tuple collapsed to a scalar (my earlier review comment).
  3. recv_close's body_remain == 0 / == 1 / > 125 guards are now gated on !control_frame_started, matching recv_ping_or_pong. Once buffer_control_payload has started, body_remain is repurposed to "bytes buffered so far", so re-entry with 0 or 1 buffered bytes was misfiring the bodyless / invalid branches.

The test file gains a new describe.concurrent block with a raw TCP server that unmasks the client's echo and asserts both the wire code and CloseEvent.code for 7 codes plus 2 split-read variants. gotEcho now rejects on socket error/close (my earlier review comment) so a regression that RSTs surfaces as an assertion failure instead of a timeout.

Security risks

None. This is RFC 6455 §5.5.1 wire-echo correctness. No new untrusted-input parsing was added; the existing received_close_code validation (which maps illegal codes to 1002) is unchanged. The bodyless-frame path writes a fixed 6-byte masked frame with no user-controlled length.

Level of scrutiny

Moderate. The Close-echo path is user-observable on the wire but not a hot path, and two of the three fixes (bodyless echo, 1001 rewrite) change only the wire echo — CloseEvent.code was already correct. The third (split-read gating) is a straightforward mirror of the existing recv_ping_or_pong pattern in the same file. I traced both split-read scenarios byte-by-byte through buffer_control_payload's re-entry semantics to confirm the fix.

Other factors

  • All prior review feedback (2 inline comments) is addressed and threads are resolved.
  • Strong test coverage: 9 new cases in the target file, verified fail-before (4 fail on stock bun) / pass-after per the PR description, plus the existing websocket.test.js -t close, websocket-client.test.ts, websocket-close-fragmented.test.ts, websocket-pong-fragmented.test.ts, and websocket-client-short-read.test.ts reported passing unchanged.
  • The 10ms setTimeout between segment writes is below the 50ms threshold and matches the established split-read pattern in websocket-close-fragmented / websocket-client-short-read (called out in the helper's comment).
  • The known overlap with #33457 (user-initiated ws.close() bodyless path) is acknowledged in the PR description with a rebase plan; the shared Option<u16> refactor is the only conflict surface.

robobun and others added 3 commits July 25, 2026 05:06
When the server sends a Close frame, the client's echo must mirror what
was received (RFC 6455 5.5.1). Two cases were being rewritten:

* a bodyless Close (no status code) was answered with an explicit 1000,
  so the peer could no longer tell "no status" from a deliberate normal
  closure (1005 is the reserved off-wire marker for exactly this case)
* a received 1001 (going away) was answered with 1000

Both now echo verbatim (bodyless -> bodyless, 1001 -> 1001), matching
Node/undici. The JS-visible CloseEvent.code was already correct (1005
and 1001 respectively) and is unchanged.

send_close_with_body() now takes Option<u16> for the wire code so it can
emit a bodyless frame; received_close_codes() drops the 1001->1000
special case.
…length checks on first entry, reject gotEcho on socket close

- received_close_codes -> received_close_code returning a single u16; the
  (echo, dispatch) tuple was vestigial once the 1001 rewrite was removed
- recv_close: body_remain == 0/1/>125 checks now gated on
  !control_frame_started, matching recv_ping_or_pong. Once
  buffer_control_payload has run, body_remain is repurposed to 'bytes
  buffered so far', so a Close whose header arrives in one read and code
  in the next no longer misroutes into the bodyless branch.
- test helper: gotEcho rejects on socket error/close so a missing echo
  fails the assertion instead of the harness timeout; two split-read
  cases cover the recv_close re-entry fix.
@robobun
robobun force-pushed the farm/bbc31fc3/websocket-close-echo branch from a3aa9c5 to fae8525 Compare July 25, 2026 06:08
Comment thread src/http_jsc/websocket_client.rs Resolved
Comment thread src/http_jsc/websocket_client.rs Resolved
Comment thread src/http_jsc/websocket_client.rs Resolved
Comment thread src/http_jsc/websocket_client.rs Resolved

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

Both earlier nits are addressed (tuple collapsed to received_close_code() -> u16; gotEcho now rejects on socket error/close). No further findings, but this touches the native WebSocket receive state machine so it's worth a human look before merge.

What was reviewed:

  • Traced the split-read fix through buffer_control_payload's body_remain repurposing for both header-alone and header+1-byte cases — the !control_frame_started gate matches recv_ping_or_pong and the persisted body_remain values (0 and 1) are correctly skipped on re-entry.
  • Verified the bodyless-echo path: payload_len = 0, mask key still written by Mask::fill_in_place before the empty-buf early return, frame_len = 6.
  • Checked all three send_close_with_body call sites for the Option<u16> signature; dispatch_code.or(code).unwrap_or(1005) produces the right JS-visible code on each.
  • The four comment-cop flags are RFC-section citations / invariant docs, not workaround justifications.
Extended reasoning...

Overview

Two files: src/http_jsc/websocket_client.rs (~50 lines net) and test/js/web/websocket/websocket-close-code.test.ts (+119 lines). The Rust change fixes three cases where the client's Close-frame echo diverged from what the server sent: bodyless→1000, 1001→1000, and a split-read bug in recv_close where the length guards ran against body_remain after buffer_control_payload had repurposed it as a bytes-buffered counter. send_close_with_body's wire code becomes Option<u16> so it can emit a true bodyless frame; received_close_codes collapses to a single-u16 received_close_code now that echo and dispatch never differ.

Security risks

None identified. All inputs are already bounds-checked upstream (MAX_CONTROL_PAYLOAD, the body_remain > 125 guard still runs on first entry). The bodyless path writes a 6-byte frame with a generated mask key and zero-length payload; no new user-controlled length reaches an allocation or index.

Level of scrutiny

Moderate. This is native protocol-state-machine code on a hot user-facing path. The change is small, mirrors the existing recv_ping_or_pong gating pattern, and ships with a raw-TCP test that unmasks the client's echo and asserts both wire and JS codes across seven values plus two split-read shapes. The PR body shows fail-before/pass-after under both debug+ASAN and release. Still, the body_remain dual-meaning is subtle enough that a maintainer glance is warranted.

Other factors

My two prior review comments (vestigial tuple, unrejectable gotEcho promise) were both addressed in fae8525. The four comment-cop bot flags on lines 879/910/1157/2131 target RFC §5.5.1/§7.1.5/§7.4 citations and an invariant note — these are the durable non-obvious content REVIEW.md asks for, not workaround justifications. The PR overlaps #33457's Option<u16> refactor of send_close_with_body (different bug, user-initiated vs. server-echo path); whichever lands second needs a small rebase there.

The recv_close guard comment restated buffer_control_payload's doc
comment (and recv_ping_or_pong has the same guard with no comment);
the rest are trimmed to keep the RFC refs and parameter contracts
without prose that restates the code.
Comment thread src/http_jsc/websocket_client.rs Resolved
Comment thread src/http_jsc/websocket_client.rs Resolved
Comment thread src/http_jsc/websocket_client.rs Resolved

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

LGTM — both prior review points (vestigial tuple, unreachable gotEcho reject path) are addressed and the split-read fix mirrors recv_ping_or_pong's existing !control_frame_started gate.

What was reviewed:

  • send_close_with_body(None, ...) produces a correctly-masked 6-byte bodyless frame (payload_len = 0, mask key still written by fill_in_place before its empty-buf early return); dispatch_code.or(code).unwrap_or(1005) preserves JS-visible codes for all three call sites.
  • recv_close re-entry semantics: on first entry body_remain is the declared length (0/1/>125 checks apply); after buffer_control_payload it becomes bytes-buffered-so-far and is persisted via receive_body_remain, so gating on control_frame_started is the correct discriminator — same as recv_ping_or_pong.
  • Test's sock.on('close', reject) fires after resolve(wireCode) in the happy path — harmless since the promise is already settled.
  • The two remaining comment-cop flags (3-line doc comments carrying RFC §refs) are false positives, not workaround justifications.
Extended reasoning...

Overview

Fixes three related bugs in the WebSocket client's Close-frame echo path (src/http_jsc/websocket_client.rs): bodyless server Close was echoed as explicit 1000; received 1001 was rewritten to 1000; and a Close frame whose header and payload arrived in separate TCP reads mis-fired the length guards because body_remain is repurposed to "bytes buffered so far" once buffer_control_payload starts. The fix makes send_close_with_body's wire code an Option<u16> (None → bodyless), collapses received_close_codes to a single u16 (the 1001 rewrite was the only divergence), and gates recv_close's length checks on !control_frame_started — the exact pattern recv_ping_or_pong already uses. New tests in websocket-close-code.test.ts assert both the on-wire echo (via a raw TCP server that unmasks the client's frame) and CloseEvent.code for EMPTY/1000/1001/1002/1003/3000/4999 plus two split-read variants.

Security risks

None. This is outbound Close-frame framing on the client side; no new parsing of untrusted input beyond what recv_close already did. The > MAX_CONTROL_PAYLOAD guard still runs on first entry (before control_frame_started is set), and on re-entry body_remain is bounded by ping_len ≤ 125 so gating the check is safe.

Level of scrutiny

Medium — protocol framing code, but the change is narrow and mechanical. The Option<u16> refactor touches one function with three call sites, all traced. The !control_frame_started gate copies the sibling recv_ping_or_pong verbatim. Fail-before/pass-after is demonstrated on both debug+ASAN and release in the PR evidence.

Other factors

Both of my earlier inline comments were addressed in fae8525: the vestigial (u16, u16) tuple is now a single u16, and the test helper rejects gotEcho on socket error/close so a missing echo fails the assertion instead of the harness timeout. The remaining unresolved comment-cop bot flags target 2–3 line doc comments carrying RFC 6455 section references — these are exactly the "durable non-obvious content" REVIEW.md asks for, not workaround justifications, and robobun's reply correctly notes they're at or below the length of the comments they replace on main. The overlap with #33457 (user-initiated ws.close() no-args path) is called out in the description; the shared Option<u16> refactor will need a small rebase for whichever lands second.

Jarred-Sumner pushed a commit that referenced this pull request Jul 27, 2026
…35534)

Adds a self-contained GitHub Action that scans `claude`-labeled PRs for
multi-line comment blocks added under `src/` and leaves a review line
comment on each one asking for it to be deleted (and the thread resolved
once done).

### Behavior

- Triggers on `pull_request_target` (`opened` / `synchronize` /
`reopened` / `labeled`), gated on `github.repository == 'oven-sh/bun'`
and the `claude` label being present. The `labeled` trigger covers the
normal case where `auto-label-claude-prs.yml` applies the label after
open.
- Fetches PR files via `pulls.listFiles` and parses the unified diff in
`actions/github-script`. No repo checkout.
- A group is **2+ consecutive added lines** that are pure comment lines
(`//`, `///`, `//!`, `/* ... */`, `* ` continuation) in `.rs` / `.c` /
`.cpp` / `.h` / `.ts` / `.js` and friends. Groups containing `SAFETY:`
are skipped.
- Posts one standalone review line comment per consecutive group via
`pulls.createReviewComment` (no review summary).
- Each comment carries `<!-- comment-cop:<path>:<sha12> -->` keyed on
the group's content hash, so reruns (new pushes, relabels) skip groups
that already have a marker.
- On each run, any existing comment-cop thread whose flagged block is no
longer present in the diff is auto-resolved via `resolveReviewThread`.

### Verification

Dry-ran the parser against the five most recent open `claude` PRs via
`gh api repos/oven-sh/bun/pulls/<n>/files`:

```
#35531  src/runtime/webcore/Blob.rs:5245-5246
#35529  src/http_jsc/websocket_client.rs:907-910
#35528  src/runtime/webcore/FileSink.rs:917-920
#35526  src/http_jsc/websocket_client.rs:2179-2182
#35532  (clean)
```

Cross-checked `#35531` line numbers against the fetched head ref;
`Blob.rs:5245` is the first line of the flagged block. `actionlint` and
prettier both pass.

<!-- robobun:evidence:begin -->

---

**no test proof** · iteration 0 · build/CI scripts only; test-proof not
applicable

<!-- robobun:evidence:end -->
@robobun

robobun commented Sep 12, 2026

Copy link
Copy Markdown
Collaborator Author

The recv_close guard from this PR (!control_frame_started around the length checks) is split out into #42511 with an every-cut-position test, so that the parser fix can land without the decision on the echoed close code. If #42511 merges first, a rebase of this PR drops that hunk. The two echo changes here are not part of #42511.

Jarred-Sumner pushed a commit that referenced this pull request Sep 12, 2026
…oss reads (#42511)

### Problem

- A server Close frame can span two TCP reads. If the first read ends
after the 2-byte header, the `close` event reports `1005 ""`, not the
real `4000 "bye"`. If it ends one byte later, the client fails with
`1002 "Protocol error - invalid control frame"`.
- `recv_close` (`src/http_jsc/websocket_client.rs:841`) tests
`cursor.body_remain == 0` (empty Close) and `== 1` (illegal payload) on
every entry. Once `buffer_control_payload` starts a frame,
`cursor.body_remain` counts the bytes buffered so far, not the declared
length. On the second read, 0 or 1 buffered bytes trip those tests.

### Fix

- `recv_close` runs its length checks only when
`!control_frame_started`, the first entry for a frame.
`recv_ping_or_pong` already has this guard, so Ping and Pong splits are
not affected.
- Correct because the declared length is checked once, while
`cursor.body_remain` still holds it.
- #35529 carries the same guard next to two changes to the echoed close
code. This PR splits the guard out so that it can land alone.
- Verified: a new block in
`test/js/web/websocket/websocket-close-fragmented.test.ts` cuts a 7-byte
Close frame at every position. Stock bun fails cuts 2 and 3. The other
close, ping and `ws` suites pass (list in Notes).

### Background

- A Close frame is a control frame: a 2-byte header, then an optional
payload of a 2-byte status code and a UTF-8 reason. A 1-byte payload is
illegal.
- `CloseEvent.code` is `1005` when the Close frame has no payload.
- `buffer_control_payload` collects a control payload that spans reads.
It parks the declared length in `ping_len` and sets
`control_frame_started` until the payload is complete.

<details><summary>Notes</summary>

Standalone repro (public APIs only). The server writes the first `cut`
bytes of a 7-byte Close frame (code 4000, reason "bye"), waits 5 ms,
then writes the rest.

```js
import net from "node:net";
import { createHash } from "node:crypto";
const close = Buffer.from([0x88, 0x05, 0x0f, 0xa0, 0x62, 0x79, 0x65]);
for (const cut of [7, 1, 2, 3, 4, 5, 6]) {
  const srv = net.createServer(s => {
    s.setNoDelay(true);
    s.once("data", d => {
      const key = /sec-websocket-key: *(.+)\r\n/i.exec(d.toString())[1];
      s.write("HTTP/1.1 101 Switching Protocols\r\nUpgrade: websocket\r\nConnection: Upgrade\r\nSec-WebSocket-Accept: " +
        createHash("sha1").update(key + "258EAFA5-E914-47DA-95CA-C5AB0DC85B11").digest("base64") + "\r\n\r\n");
      setTimeout(() => {
        s.write(close.subarray(0, cut));
        setTimeout(() => { if (cut < 7) s.write(close.subarray(cut)); setTimeout(() => s.end(), 30); }, 5);
      }, 5);
    });
    s.on("error", () => {});
  }).listen(0, "127.0.0.1");
  await new Promise(r => srv.once("listening", r));
  const ws = new WebSocket("ws://127.0.0.1:" + srv.address().port);
  const ev = await new Promise(r => { ws.onclose = r; });
  console.log(`close frame split at byte ${cut}/7 -> code=${ev.code} reason=${JSON.stringify(ev.reason)} wasClean=${ev.wasClean}`);
  srv.close();
}
```

Before (1.4.3-canary.1+6a92015fc, also reported on 1.4.0, 1.4.1 and
1.4.2):

```
close frame split at byte 7/7 -> code=4000 reason="bye" wasClean=true
close frame split at byte 1/7 -> code=4000 reason="bye" wasClean=true
close frame split at byte 2/7 -> code=1005 reason="" wasClean=true
close frame split at byte 3/7 -> code=1002 reason="Protocol error - invalid control frame" wasClean=false
close frame split at byte 4/7 -> code=4000 reason="bye" wasClean=true
close frame split at byte 5/7 -> code=4000 reason="bye" wasClean=true
close frame split at byte 6/7 -> code=4000 reason="bye" wasClean=true
```

After (this branch, debug build): all seven lines print `code=4000
reason="bye" wasClean=true`. Node v26.3.0 prints the same seven lines.

Trace of the two cuts that fail:

- Cut 2. Read 1 is the header. `recv_close` sees `body_remain == 5`,
`buffer_control_payload` parks 5 in `ping_len`, sets `body_remain = 0`
and waits. Read 2 enters `recv_close` with `body_remain == 0`, takes the
empty-Close branch and calls `send_close()`, which reports 1005.
- Cut 3. Read 1 is the header plus one payload byte.
`buffer_control_payload` copies that byte and leaves `body_remain == 1`.
Read 2 enters `recv_close` with `body_remain == 1` and fails with
`InvalidControlFrame`.

The `ws` package shim sits on the same native client, so it gets the
same fix.

Test design. The test uses no timers. The server writes an empty Ping
and the first part of the Close frame in one write. It writes the rest
only after it receives the Pong. The Pong proves that the client already
read the first part, so the two parts cannot arrive in one read. Each
case also checks that the client echoes `4000 "bye"` on the wire. On
stock bun the new block gives the same result in 25 of 25 runs: cuts 2
and 3 fail, cuts 1, 4, 5 and 6 pass.

Suites run with the debug build, all pass:

- `test/js/web/websocket/websocket-close-fragmented.test.ts` (7)
- `test/js/web/websocket/websocket-close-code.test.ts` (24)
- `test/js/web/websocket/websocket-pong-fragmented.test.ts` (4)
- `test/js/web/websocket/websocket-client-short-read.test.ts` (4)
- `test/js/web/websocket/websocket-close-async-dispatch.test.ts` (5)
- `test/js/web/websocket/websocket-close-connecting.test.ts` (4)
- `test/js/web/websocket/websocket-client.test.ts` (37)
- `test/js/web/websocket/websocket-buffered-amount.test.ts` (7)
- `test/js/web/websocket/websocket-permessage-deflate.test.ts` (10, 1
skip)
- `test/js/web/websocket/websocket.test.js -t close` (23)
- `test/js/first_party/ws/ws.test.ts` (65)

</details>

<!-- robobun:evidence:begin -->

---

**[human-review]** gate passed · iteration 0 · 2 files touched

<details><summary>fails on main (without fix)</summary>

```console
ASAN without fix: 2 FAILED
$ BUN_DEBUG_QUIET_LOGS=1 bun scripts/build.ts --profile=debug --quiet test "--reporter=junit" "--reporter-outfile=/tmp/pr_gate.xml" test/js/web/websocket/websocket-close-fragmented.test.ts
bun test v1.4.3 (6a92015)

test/js/web/websocket/websocket-close-fragmented.test.ts:
(pass) WebSocket > fragmented close frame [71.02ms]
211 |     const closed = Promise.withResolvers<{ code: number; reason: string; wasClean: boolean }>();
212 |     const ws = new WebSocket(`ws://${server.hostname}:${server.port}`);
213 |     ws.onclose = ev => closed.resolve({ code: ev.code, reason: ev.reason, wasClean: ev.wasClean });
214 | 
215 |     try {
216 |       expect(await closed.promise).toEqual({ code: 4000, reason: "bye", wasClean: true });
                                         ^
error: expect(received).toEqual(expected)

  {
-   "code": 4000,
-   "reason": "bye",
+   "code": 1005,
+   "reason": "",
    "wasClean": true,
  }

- Expected  - 2
+ Received  + 2

      at <anonymous> (/workspace/bun/test/js/web/websocket/websocket-close-fragmented.test.ts:216:36)
211 |     const closed = Promise.withResolvers<{ code: number; reason: string; wasClean: boolean }>();
212 |     const ws 
... (truncated)

release without fix: 2 FAILED
bun test v1.4.3-canary.1 (6a92015)

test/js/web/websocket/websocket-close-fragmented.test.ts:
(pass) WebSocket > fragmented close frame [11.55ms]
211 |     const closed = Promise.withResolvers<{ code: number; reason: string; wasClean: boolean }>();
212 |     const ws = new WebSocket(`ws://${server.hostname}:${server.port}`);
213 |     ws.onclose = ev => closed.resolve({ code: ev.code, reason: ev.reason, wasClean: ev.wasClean });
214 | 
215 |     try {
216 |       expect(await closed.promise).toEqual({ code: 4000, reason: "bye", wasClean: true });
                                         ^
error: expect(received).toEqual(expected)

  {
-   "code": 4000,
-   "reason": "bye",
+   "code": 1005,
+   "reason": "",
    "wasClean": true,
  }

- Expected  - 2
+ Received  + 2

      at <anonymous> (/workspace/bun/test/js/web/websocket/websocket-close-fragmented.test.ts:216:36)
211 |     const closed = Promise.withResolvers<{ code: number; reason: string; wasClean: boolean }>();
212 |     const ws = new WebSocket(`ws://${server.hostname}:${server.port}`);
213 |     ws.onclose = ev => closed.resolve({ code: ev.code, reason: ev.reason, wasClean: ev.wasClean });
214 | 
215 |   
... (truncated)
```

</details>

<details><summary>passes on PR (with fix)</summary>

```console
ASAN with fix: all passed
$ BUN_DEBUG_QUIET_LOGS=1 bun scripts/build.ts --profile=debug --quiet test "--reporter=junit" "--reporter-outfile=/tmp/pr_gate.xml" test/js/web/websocket/websocket-close-fragmented.test.ts
bun test v1.4.3 (6a92015)

test/js/web/websocket/websocket-close-fragmented.test.ts:
(pass) WebSocket > fragmented close frame [77.15ms]
(pass) WebSocket close frame split across two reads > after byte 1 of 7 [76.69ms]
(pass) WebSocket close frame split across two reads > after byte 2 of 7 [56.71ms]
(pass) WebSocket close frame split across two reads > after byte 3 of 7 [53.98ms]
(pass) WebSocket close frame split across two reads > after byte 4 of 7 [52.51ms]
(pass) WebSocket close frame split across two reads > after byte 5 of 7 [51.13ms]
(pass) WebSocket close frame split across two reads > after byte 6 of 7 [5.78ms]

 7 pass
 0 fail
 14 expect() calls
Ran 7 tests across 1 file. [2.88s]
__F:0:S:0

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     4b652ed
  features     baseline

23 deps, 131 codegen, 1172 objects in 768ms

ninja: Entering directory `/workspace/bun/build/release'
[1/1244] install /workspace/bun
bun install v1.4.3-canary.1 (6a92015)

Checked 22 installs across 61 packages (no changes) [8.00ms]
[2/1244] install /workspace/bun/packages/bun-error
bun install v1.4.3-canary.1 (6a92015)

Checked 1 install across 2 packages (no changes) [5.00ms]
[3/1244] install /workspace/bun/src/node-fallbacks
bun install v1.4.3-canary.1 (6a92015)

Checked 111 installs across 104 packages (no changes) [14.00ms]
[4/1244] gen ErrorCode+*.h
[5/1244] gen node-fallbacks/react-refresh.js
Bundled 1 module in 5ms

  react-refresh.js  4.81 KB  (entry point)

[6/1244] fetch tinycc
[tinycc] up to date
[7/1243] fetch zlib
[zlib] up to date
[8/1243] gen bindgenv2
[9/1243] fetch libjpeg-turbo
[libjpeg-turbo] up to date
[10/1216] gen .bind.ts → GeneratedBindings.cpp
[11/1216] gen bake.{client,server,error}.js
-> bake.client.js, bake.server
... (truncated)
```

</details>

<details><summary>diff hotspot</summary>

```
src/http_jsc/websocket_client.rs                   | 16 ++--
 .../websocket/websocket-close-fragmented.test.ts   | 96 ++++++++++++++++++++++
 2 files changed, 105 insertions(+), 7 deletions(-)
```

</details>

**gate history** · 1 passed · 0 rejected · iteration 0

<details><summary>evidence per changed file</summary>

```
file                                                      reads  edits  tests
src/http_jsc/websocket_client.rs                              2      1      9
test/js/web/websocket/websocket-close-fragmented.test.ts      1      1      8
```

</details>

<!-- robobun:evidence:end -->
@robobun

robobun commented Sep 13, 2026

Copy link
Copy Markdown
Collaborator Author

Closing as part of a cleanup of stale pull requests. This PR has had no new commits since 2026-07-25, it conflicts with main, and its last CI run failed. This is not a judgment on the fix itself. If the problem still reproduces on a current build, reopen this PR after a rebase or open a new one against main.

@robobun robobun closed this Sep 13, 2026
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Labels

Projects

None yet

Development

Successfully merging this pull request may close these issues.

2 participants