From 86c3d7d2fae959ebf4807d6572b15f7f92d9aa76 Mon Sep 17 00:00:00 2001 From: robobun <117481402+robobun@users.noreply.github.com> Date: Tue, 28 Jul 2026 23:57:47 +0000 Subject: [PATCH 1/9] ws: implement client 'upgrade' and 'unexpected-response' events The ws shim previously stubbed both events with a 'not implemented in bun' warning. The native WebSocket upgrade client now forwards the parsed handshake response (status, reason, headers, body) to the C++ WebSocket as a 'handshake' event, and the shim folds that into the IncomingMessage-shaped object that ws listeners expect. For non-101 responses the client no longer fails early: it buffers the response body (honoring Content-Length, RFC 7230 3.3.3 bodiless statuses, and Transfer-Encoding) up to a 64 MB cap, then dispatches 'unexpected-response' (or the 'Unexpected server response: N' error when no listener is registered) before terminating. On 101, 'upgrade' and 'open' are dispatched under one event-loop scope so a microtask queued in an 'upgrade' handler observes readyState OPEN, matching Node + npm ws. The handshake listener is registered lazily on first 'upgrade' / 'unexpected-response' subscription so callers that only use open/message/ close never touch the new path. addListener / prependListener / prependOnceListener / addEventListener all arm the bridge, and the native 'Expected 101' error is suppressed across every registration style once 'unexpected-response' has handled the response. Squashed and rebased from #28114. Fixes #5951 Fixes #24229 --- src/http_jsc/websocket_client/CppWebSocket.rs | 56 ++ .../WebSocketUpgradeClient.rs | 529 ++++++++++++- src/js/builtins/BunBuiltinNames.h | 3 + src/js/thirdparty/ws.js | 329 ++++++++- src/jsc/bindings/webcore/EventNames.h | 21 +- src/jsc/bindings/webcore/WebSocket.cpp | 59 ++ src/jsc/bindings/webcore/WebSocket.h | 7 + test/regression/issue/05951.test.ts | 696 ++++++++++++++++++ test/regression/issue/24229.test.ts | 58 ++ 9 files changed, 1713 insertions(+), 45 deletions(-) create mode 100644 test/regression/issue/05951.test.ts create mode 100644 test/regression/issue/24229.test.ts diff --git a/src/http_jsc/websocket_client/CppWebSocket.rs b/src/http_jsc/websocket_client/CppWebSocket.rs index cb3fec21054b..3b2d9e07da3d 100644 --- a/src/http_jsc/websocket_client/CppWebSocket.rs +++ b/src/http_jsc/websocket_client/CppWebSocket.rs @@ -22,6 +22,19 @@ bun_opaque::opaque_ffi! { pub struct CppWebSocket; } +/// A single HTTP response header passed across the FFI to +/// `WebSocket__didReceiveHandshakeResponse`. Name/value point into the +/// PicoHTTP-parsed response head, which the caller keeps alive for the +/// duration of the synchronous dispatch. Matches `WebCore::WebSocket:: +/// HandshakeRawHeader` (src/jsc/bindings/webcore/WebSocket.h). +#[repr(C)] +pub struct RawHeader { + pub name_ptr: *const u8, + pub name_len: usize, + pub value_ptr: *const u8, + pub value_len: usize, +} + // FFI surface for `WebCore::WebSocket` (src/jsc/bindings/webcore/WebSocket.cpp). // Kept private to this module — the safe wrappers below are the only callers. // @@ -45,6 +58,16 @@ unsafe extern "C" { deflate_params: *const websocket_deflate::Params, ); safe fn WebSocket__didAbruptClose(websocket_context: &CppWebSocket, reason: ErrorCode); + fn WebSocket__didReceiveHandshakeResponse( + websocket_context: &CppWebSocket, + status_code: u16, + status_message: *const u8, + status_message_len: usize, + headers: *const RawHeader, + headers_len: usize, + body: *const u8, + body_len: usize, + ); fn WebSocket__didClose(websocket_context: &CppWebSocket, code: u16, reason: *const BunString); fn WebSocket__didReceiveText( websocket_context: &CppWebSocket, @@ -78,6 +101,39 @@ impl CppWebSocket { event_loop.exit(); } + /// Dispatch the native `'handshake'` event to the `ws` shim. + /// + /// `status_message`, `headers`, and `body` are borrowed for the call only + /// — the C++ side copies whatever it needs into JS values synchronously. + // Forwards raw pointers to C++ without dereferencing on the Rust side. + #[allow(clippy::not_unsafe_ptr_arg_deref)] + pub(crate) fn did_receive_handshake_response( + &self, + status_code: u16, + status_message: &[u8], + headers: &[RawHeader], + body: &[u8], + ) { + // SAFETY: VirtualMachine::get() returns the live current-thread VM; + // event_loop() yields its raw event-loop pointer (live for VM lifetime). + let event_loop = VirtualMachine::get().event_loop_mut(); + event_loop.enter(); + // SAFETY: self is a valid C++ WebCore::WebSocket; the slices outlive the call. + unsafe { + WebSocket__didReceiveHandshakeResponse( + self, + status_code, + status_message.as_ptr(), + status_message.len(), + headers.as_ptr(), + headers.len(), + body.as_ptr(), + body.len(), + ) + }; + event_loop.exit(); + } + pub(crate) fn did_close(&self, code: u16, reason: &mut BunString) { // SAFETY: VirtualMachine::get() returns the live current-thread VM; // event_loop() yields its raw event-loop pointer (live for VM lifetime). diff --git a/src/http_jsc/websocket_client/WebSocketUpgradeClient.rs b/src/http_jsc/websocket_client/WebSocketUpgradeClient.rs index ebeb277acd26..b7dd6a736b25 100644 --- a/src/http_jsc/websocket_client/WebSocketUpgradeClient.rs +++ b/src/http_jsc/websocket_client/WebSocketUpgradeClient.rs @@ -120,6 +120,28 @@ impl Drop for SslCtxOwned { } } +/// Non-`None` while buffering the body of a non-101 response that spans +/// multiple TCP reads. The `'handshake'` event is deferred until the full +/// body is in hand so the `unexpected-response` consumer sees the complete +/// payload instead of just the bytes colocated with the header block in the +/// first read. +#[derive(Clone, Copy, PartialEq, Eq)] +enum DeferredHandshake { + None, + /// Total expected buffer length (`head_len + Content-Length`). + WaitingForLength(usize), + /// No `Content-Length`; accumulate until the peer closes the connection. + WaitingForEof, +} + +/// Maximum bytes buffered for a non-101 response body before bailing out. +/// Real error pages (workerd restart text, JSON API errors, HTML) fit well +/// under this; the cap stops a malicious or misbehaving server from making +/// us accumulate unbounded data — either via a giant `Content-Length` header +/// or a keep-alive connection that never closes after a no-`Content-Length` +/// response. +const MAX_NON_101_BODY: usize = 64 * 1024 * 1024; + /// WebSocket HTTP upgrade client, generic over `SSL`. /// /// Intrusive single-thread @@ -165,6 +187,11 @@ pub struct HTTPClient { /// with a `Sec-WebSocket-Extensions` header anyway, `processResponse` /// fails the handshake per RFC 6455 §9.1 — matching upstream `ws`. offered_permessage_deflate: bool, + + /// Tracks deferred dispatch of the `'handshake'` event for non-101 + /// responses whose body straddles multiple TCP reads. See + /// [`DeferredHandshake`]. + deferred_handshake: DeferredHandshake, } // Handler set referenced by the dispatch table (kind = `.ws_client_upgrade[_tls]`). @@ -366,6 +393,7 @@ impl HTTPClient { expected_accept: request_result.expected_accept, offered_permessage_deflate: offer_permessage_deflate, subprotocols, + deferred_handshake: DeferredHandshake::None, })); bun_core::scoped_log!(alloc, "new({}) = {:p}", Self::TYPE_NAME, client); // SAFETY: just allocated above; we hold the only ref. This `&mut` is @@ -709,6 +737,66 @@ impl HTTPClient { pub fn handle_close(this: ThisPtr, _: Socket, _: c_int, _: *mut c_void) { log!("onClose"); bun_jsc::mark_binding!(); + + // If a non-101 response body was mid-accumulation when the peer reset + // the socket (RST rather than FIN, so `handle_end` never fires), + // flush whatever arrived BEFORE `clear_data()` frees `self.body`. The + // flush runs `process_response` which terminates the non-101 and + // clears `outgoing_websocket`, so `dispatch_abrupt_close` below is a + // no-op. We still `deref` once to balance the socket ref. + // + // The flush dispatches `unexpected-response` into JS, and that handler + // may synchronously `ws.close()`/`ws.terminate()` → reentrant + // `cancel()`. Left to its own devices, `cancel()` would see `tcp` still + // attached + the socket's ext slot still pointing at us and so + // (a) release the socket ref a second time and (b) `tcp.close()` again, + // re-entering `handle_close` — a use-after-free on the `tcp.detach()` + // below plus a refcount underflow. Guard against all of it: take the + // ext slot and detach `tcp` up front so the reentrant `cancel()` finds + // `ext == None` / a detached `tcp` and no-ops both, and hold a ref + // across the flush so the C++-ref release inside `cancel()` can't drop + // us to 0 before our own trailing `deref`. + // SAFETY: short-lived read; ends before the branch below. + let has_deferred = !matches!( + unsafe { (*this.as_ptr()).deferred_handshake }, + DeferredHandshake::None + ); + if has_deferred { + let _guard = this.ref_guard(); + // Take the socket-userdata ref's slot (matching `cancel`'s own + // take) and detach our `tcp` handle, before any dispatch, so a + // reentrant `cancel()` finds `ext == None` / a detached `tcp` and + // neither double-releases the socket ref nor re-enters `handle_close`. + // SAFETY: short-lived read of the `tcp` handle; `this` is live. + let tcp = unsafe { (*this.as_ptr()).tcp }; + if let Some(ext) = tcp.ext::>>() { + // SAFETY: the ext slot is the `Option>` written in + // `connect_group`; single-threaded (JS thread), no other `&mut` + // to it is live. + unsafe { (*ext).take() }; + } + // SAFETY: short-lived `&mut` for the field detach/clear_data. + unsafe { (*this.as_ptr()).tcp.detach() }; + // SAFETY: forwards `this`; `_guard` + the still-held socket ref + // keep it alive across the dispatch even if JS frees the C++ ref. + unsafe { Self::flush_deferred_on_close(this.as_ptr()) }; + // Release the C++ `outgoing_websocket` ref if it's still held. + // A reentrant `cancel()` (from `ws.close()`/`terminate()` in the + // listener) or the flush's own `process_response` may already have + // taken it; `take()` makes this release exactly-once regardless of + // which path ran. + // SAFETY: short-lived `&mut` for the field take. + if unsafe { (*this.as_ptr()).outgoing_websocket.take().is_some() } { + // SAFETY: no `&mut Self` is live; `_guard` still holds a ref. + unsafe { Self::deref(this.as_ptr()) }; + } + // Balance the socket ref whose ext slot we took above. + // SAFETY: no `&mut Self` is live; `_guard` still holds a ref. + unsafe { Self::deref(this.as_ptr()) }; + return; + // `_guard` drops here — the final release, may free `this`. + } + // SAFETY: short-lived `&mut` borrows; each ends before the next call. unsafe { (*this.as_ptr()).clear_data() }; // SAFETY: short-lived `&mut` for the field detach; `this` is live. @@ -723,6 +811,19 @@ impl HTTPClient { /// # Safety /// `this` must point to a live `Self`. See `fail`. pub unsafe fn terminate(this: *mut Self, code: ErrorCode) { + // If a non-101 response body was being accumulated when the transport + // ended cleanly (peer close), flush the deferred handshake first so + // the `unexpected-response` listener sees what the server delivered. + // `handle_end`/`handle_close` flush directly for the plain-TCP path; + // the wss://-through-HTTP-CONNECT-proxy path comes in via + // `WebSocketProxyTunnel::on_close` → `terminate(Ended)` without going + // through either, so the flush must live here too. + if code == ErrorCode::Ended { + // SAFETY: forwards `this`; no `&mut Self` is live. May free `this`. + if unsafe { Self::flush_deferred_on_close(this) } { + return; + } + } // SAFETY: forwards `this` with root provenance. unsafe { Self::fail(this, code) }; // We cannot access the pointer after fail is called. @@ -920,8 +1021,17 @@ impl HTTPClient { } } + // If we're mid-way through buffering a non-101 response body (a + // `Content-Length` larger than the first read, or a no-`Content- + // Length` response read until EOF), keep appending and check for + // completion before trying to parse again. See `DeferredHandshake`. + // SAFETY: forwards `this` with root provenance; no `&mut Self` is live. + if unsafe { Self::append_deferred_handshake_body(this.as_ptr(), data) } { + return; + } + // SAFETY: short-lived `&mut` for body buffering; no reentrant calls in - // this region until `terminate`/`process_response` below. + // this region until `terminate`/`process_websocket_upgrade_response` below. let me = unsafe { &mut *this.as_ptr() }; let mut body = data; if !me.body.is_empty() { @@ -929,17 +1039,6 @@ impl HTTPClient { body = &me.body; } - let is_first = me.body.is_empty(); - const HTTP_101: &[u8] = b"HTTP/1.1 101 "; - if is_first && body.len() > HTTP_101.len() { - // fail early if we receive a non-101 status code - if !body.starts_with(HTTP_101) { - // SAFETY: `me`'s last use is above; no `&mut Self` spans this call. - unsafe { Self::terminate(this.as_ptr(), ErrorCode::Expected101StatusCode) }; - return; - } - } - let response = match picohttp::Response::parse(body, &mut me.headers_buf) { Ok(r) => r, Err(picohttp::ParseResponseError::MalformedHttpResponse) => { @@ -963,15 +1062,352 @@ impl HTTPClient { } }; - let bytes_read = usize::try_from(response.bytes_read).expect("int cast"); - // Reshaped for borrowck — copy remain_buf out before mutating self. - let remain_buf: Vec = body[bytes_read..].to_vec(); + // Reshaped for borrowck — copy the full parsed buffer out before + // mutating self, since `process_websocket_upgrade_response` re-parses + // it and may mutate `self.body`/`headers_buf`. + let full: Vec = body.to_vec(); // SAFETY: `me`'s last use is the `body` slice above (now copied out); // no `&mut Self` spans this call. - unsafe { Self::process_response(this.as_ptr(), response, &remain_buf) }; + unsafe { Self::process_websocket_upgrade_response(this.as_ptr(), response, &full) }; // `_guard` drops here, balancing the ref above. May free `this`. } + /// Scan response headers for `Content-Length`; return the parsed value or + /// `None` when the header is absent or unparseable. + fn find_content_length(response: &picohttp::Response) -> Option { + for header in response.headers.list { + if header.name().len() == b"Content-Length".len() + && strings::eql_case_insensitive_ascii_ignore_length( + header.name(), + b"Content-Length", + ) + { + let value = header.value(); + let trimmed = core::str::from_utf8(value) + .ok()? + .trim_matches(|c| c == ' ' || c == '\t'); + return trimmed.parse::().ok(); + } + } + None + } + + /// Whether the response carries a `Transfer-Encoding` header (chunked or + /// otherwise). Such bodies have no `Content-Length` and their wire bytes + /// are framing, not payload — the caller dispatches immediately instead + /// of accumulating raw framing until EOF. + fn has_transfer_encoding(response: &picohttp::Response) -> bool { + for header in response.headers.list { + if header.name().len() == b"Transfer-Encoding".len() + && strings::eql_case_insensitive_ascii_ignore_length( + header.name(), + b"Transfer-Encoding", + ) + { + return true; + } + } + false + } + + /// Append `data` to the deferred non-101 body buffer. + /// + /// Returns `true` when `data` was consumed as part of a deferred + /// handshake (and the caller should stop processing this read). Enforces + /// [`MAX_NON_101_BODY`] so neither a giant `Content-Length` nor a + /// never-closing no-`Content-Length` stream can grow `self.body` without + /// bound. + /// + /// # Safety + /// `this` must point to a live `Self`. Takes `*mut Self` because + /// `terminate`/`flush_deferred_handshake_and_process` may free `this`. + unsafe fn append_deferred_handshake_body(this: *mut Self, data: &[u8]) -> bool { + // SAFETY: short-lived read; ends before any dispatch below. + let state = unsafe { (*this).deferred_handshake }; + match state { + DeferredHandshake::None => false, + DeferredHandshake::WaitingForLength(target_len) => { + // `target_len` was bounded to `head_len + MAX_NON_101_BODY` + // by `process_websocket_upgrade_response`, so the buffer can + // never exceed that limit. + // + // If this read carries past `target_len`, take only enough + // bytes to fill the declared body; the rest belong to the + // next pipelined response or are trailing garbage — matching + // the single-chunk fast path which truncates to + // `full[..target_len]` before dispatching. + // SAFETY: short-lived `&mut`; ends before the dispatch below. + let me = unsafe { &mut *this }; + let available = target_len - me.body.len(); + let take = available.min(data.len()); + me.body.extend_from_slice(&data[..take]); + if me.body.len() >= target_len { + me.body.truncate(target_len); + me.deferred_handshake = DeferredHandshake::None; + let full: Vec = core::mem::take(&mut me.body); + // SAFETY: `me`'s last use is above; no `&mut Self` spans this call. + unsafe { Self::flush_deferred_handshake_and_process(this, &full) }; + } + true + } + DeferredHandshake::WaitingForEof => { + // SAFETY: short-lived `&mut`; ends before any dispatch. + let me = unsafe { &mut *this }; + if me.body.len().saturating_add(data.len()) > MAX_NON_101_BODY { + me.deferred_handshake = DeferredHandshake::None; + // SAFETY: `me`'s last use is above; no `&mut Self` spans this call. + unsafe { Self::terminate(this, ErrorCode::Expected101StatusCode) }; + return true; + } + me.body.extend_from_slice(data); + true + } + } + } + + /// Shared between the plain-TCP and proxy-tunnel paths. + /// + /// For non-101 responses whose body straddles multiple TCP reads, defer + /// the handshake dispatch until the full body is in hand so the + /// `unexpected-response` listener sees the complete payload instead of a + /// truncated prefix. + /// + /// `full` is the complete buffer contents (head + whatever body bytes are + /// on hand) — a copy of the buffer `response` was parsed from, so its + /// bytes match but `response`'s header pointers reference the original. + /// + /// # Safety + /// `this` must point to a live `Self`. Takes `*mut Self` because the + /// dispatch / `terminate` / `process_response` calls below may free + /// `this`. + unsafe fn process_websocket_upgrade_response( + this: *mut Self, + response: picohttp::Response, + full: &[u8], + ) { + let head_len = usize::try_from(response.bytes_read).expect("int cast"); + let status_code = u16::try_from(response.status_code).unwrap_or(0); + + // SAFETY: short-lived read; ends before any dispatch below. + let has_ws = unsafe { (*this).outgoing_websocket.is_some() }; + if !has_ws { + // SAFETY: forwards `this`; no `&mut Self` is live. + unsafe { Self::process_response(this, response, &full[head_len..]) }; + return; + } + + if status_code != 101 { + // RFC 7230 §3.3.3 rule #1 — 1xx / 204 / 304 responses have no + // message body regardless of the header fields, so reading until + // the peer closes (rule #7, the `None` arm below) would stall a + // keep-alive connection until the 120s socket timeout — and + // `terminate(Timeout)` doesn't flush a deferred handshake, so + // `unexpected-response` would never fire. Rule #3 + // (`Transfer-Encoding`) likewise preempts rule #7: we don't decode + // chunked on this fallback path. In both cases dispatch + // immediately with whatever bytes are on hand so the + // `unexpected-response` listener still gets the correct status / + // headers (matching the pre-existing non-101 behavior, which + // surfaced no body at all). + let is_bodiless = + status_code == 204 || status_code == 304 || (100..200).contains(&status_code); + if is_bodiless || Self::has_transfer_encoding(&response) { + // SAFETY: forwards `this`; no `&mut Self` is live. + unsafe { + Self::dispatch_handshake_and_process( + this, + response, + full, + head_len, + status_code, + ); + } + return; + } + // Defer the dispatch if the full body isn't present yet. + match Self::find_content_length(&response) { + Some(cl) => { + // Reject an absurd Content-Length up front so the + // `head_len + cl` below can't overflow `usize` (and so we + // never trap in an unbounded accumulate loop). `cl` is now + // bounded to 64 MB and `head_len` to the HTTP header limit. + if cl > MAX_NON_101_BODY { + // SAFETY: no `&mut Self` is live. + unsafe { Self::terminate(this, ErrorCode::Expected101StatusCode) }; + return; + } + let target_len = head_len + cl; + if full.len() < target_len { + // SAFETY: short-lived `&mut`; ends before return. Own + // the accumulated bytes so subsequent reads append. + // `full` is always a fresh `to_vec()` from the caller + // (borrowck forced the copy upstream), so it never + // aliases `me.body` — just replace. + let me = unsafe { &mut *this }; + me.body.clear(); + me.body.extend_from_slice(full); + me.deferred_handshake = DeferredHandshake::WaitingForLength(target_len); + return; + } + // Truncate at head_len + Content-Length — drop any bytes + // beyond the declared body length. + // SAFETY: forwards `this`; no `&mut Self` is live. + unsafe { + Self::flush_deferred_handshake_and_process(this, &full[..target_len]); + } + return; + } + None => { + // No Content-Length, and the bodiless / chunked cases were + // handled above — RFC 7230 §3.3.3 rule #7: read until the + // peer closes. Defer to handle_end / handle_close. + // SAFETY: short-lived `&mut`; ends before return. `full` + // is a fresh `to_vec()` (never aliases `me.body`). + let me = unsafe { &mut *this }; + me.body.clear(); + me.body.extend_from_slice(full); + me.deferred_handshake = DeferredHandshake::WaitingForEof; + return; + } + } + } + + // 101 fast path — post-header bytes are the first WebSocket frame, + // not HTTP body; `dispatch_handshake_and_process` drops them from the + // handshake event and `process_response` hands them to the connected + // client as buffered overflow. + // SAFETY: forwards `this`; no `&mut Self` is live. + unsafe { + Self::dispatch_handshake_and_process(this, response, full, head_len, status_code); + } + } + + /// Re-parse the accumulated (complete) buffer and dispatch. Called from + /// the deferred paths once `buffer` holds the full response. + /// + /// # Safety + /// `this` must point to a live `Self`; `terminate`/dispatch may free it. + unsafe fn flush_deferred_handshake_and_process(this: *mut Self, buffer: &[u8]) { + // PORT NOTE: re-parse into a local copy's headers_buf. Copy `buffer` + // so a re-parse against `self.headers_buf` doesn't alias `self.body`. + let owned: Vec = buffer.to_vec(); + // SAFETY: short-lived `&mut` for the parse scratch buffer. + let me = unsafe { &mut *this }; + let response = match picohttp::Response::parse(&owned, &mut me.headers_buf) { + Ok(r) => r, + Err(_) => { + // SAFETY: `me`'s last use is above; no `&mut Self` spans this call. + unsafe { Self::terminate(this, ErrorCode::InvalidResponse) }; + return; + } + }; + let head_len = usize::try_from(response.bytes_read).expect("int cast"); + let status_code = u16::try_from(response.status_code).unwrap_or(0); + // SAFETY: short-lived read. + let has_ws = unsafe { (*this).outgoing_websocket.is_some() }; + if !has_ws { + // SAFETY: forwards `this`; no `&mut Self` is live. + unsafe { Self::process_response(this, response, &owned[head_len..]) }; + return; + } + // SAFETY: forwards `this`; no `&mut Self` is live. + unsafe { + Self::dispatch_handshake_and_process(this, response, &owned, head_len, status_code); + } + } + + /// Dispatch the `'handshake'` event into JS (synchronous), then run + /// `process_response`. + /// + /// # Safety + /// `this` must point to a live `Self`. JS in the handshake listener can + /// call `ws.close()`/`ws.terminate()` which re-enters and may free + /// `this`; the `ref_guard` below keeps it alive across the dispatch. + unsafe fn dispatch_handshake_and_process( + this: *mut Self, + response: picohttp::Response, + full: &[u8], + head_len: usize, + status_code: u16, + ) { + // SAFETY: short-lived read of the handle; copied out before dispatch. + let Some(ws) = (unsafe { (*this).outgoing_websocket }) else { + // SAFETY: forwards `this`; no `&mut Self` is live. + unsafe { Self::process_response(this, response, &full[head_len..]) }; + return; + }; + + // Keep `this` alive across the synchronous JS dispatch: the listener + // may `ws.terminate()` → didAbruptClose → free us mid-function. + // handle_data refs around its whole body, but handle_end / handle_close + // flush through here directly, so guard unconditionally. + // SAFETY: `this` carries root provenance; balanced on drop. + let _guard = unsafe { ThisPtr::new(this) }.ref_guard(); + + // On 101, nest the `did_receive_handshake_response` ('handshake'/ + // 'upgrade') and `did_connect` ('open') dispatches below under one + // event-loop scope. Each of those calls its own enter()/exit(); exit() + // drains microtasks when the count drops 1→0. Without this outer scope + // the count would hit 0 between the two events, so a microtask queued + // in an 'upgrade' handler would run before 'open' and observe + // readyState CONNECTING. Holding the count ≥1 across both makes them + // fire back-to-back like npm `ws`, draining microtasks once after + // 'open'. Scope it to 101 only: on a non-101 response `process_response` + // below calls `terminate` instead of `did_connect`, and the + // 'unexpected-response' body stream relies on the microtask checkpoint + // at `did_receive_handshake_response`'s exit() running *before* that + // teardown — swallowing it hangs the stream. + let _loop_scope = (status_code == 101) + .then(|| bun_jsc::virtual_machine::VirtualMachine::get().enter_event_loop_scope()); + + // On 101, the bytes after the header block are the first WebSocket + // frame — not HTTP body. Surface an empty body to the handshake + // event; `process_response` still hands `full[head_len..]` to the + // connected client as overflow. + let handshake_body: &[u8] = if status_code == 101 { + &[] + } else { + &full[head_len..] + }; + + // Build the raw-header array the C++ side copies into `rawHeaders`. + // SAFETY: the header name/value slices (and `response.status`) point + // into the buffer `response` was parsed from — `full` on the + // flush-deferred path, or the caller's `data`/`self.body` on the + // direct-dispatch paths (101 / bodiless / Transfer-Encoding), where + // `full` is a separate copy. Either buffer outlives this synchronous + // call: `data` is the uSockets read buffer live for the callback + // frame, `self.body` is owned by `*this` (kept alive by `_guard` + // above), and C++ copies every slice into a JS string before + // dispatchEvent runs any user JS. + let mut raw_headers: Vec = + Vec::with_capacity(response.headers.list.len()); + for h in response.headers.list { + let name = h.name(); + let value = h.value(); + raw_headers.push(super::cpp_websocket::RawHeader { + name_ptr: name.as_ptr(), + name_len: name.len(), + value_ptr: value.as_ptr(), + value_len: value.len(), + }); + } + + CppWebSocket::opaque_ref(ws).did_receive_handshake_response( + status_code, + response.status, + &raw_headers, + handshake_body, + ); + + // SAFETY: short-lived read; the JS listener may have cleared it. + if unsafe { (*this).outgoing_websocket.is_none() } { + return; + } + // SAFETY: forwards `this`; no `&mut Self` is live. + unsafe { Self::process_response(this, response, &full[head_len..]) }; + } + /// Takes `ThisPtr` because `terminate`/`handle_data` may free `this`. fn handle_proxy_response(this: ThisPtr, socket: Socket, data: &[u8]) { log!("handleProxyResponse"); @@ -1218,8 +1654,14 @@ impl HTTPClient { pub unsafe fn handle_decrypted_data(this: *mut Self, data: &[u8]) { log!("handleDecryptedData: {} bytes", data.len()); + // Same deferred-body flushing as the plain-TCP path. + // SAFETY: forwards `this`; no `&mut Self` is live. + if unsafe { Self::append_deferred_handshake_body(this, data) } { + return; + } + // SAFETY: short-lived `&mut` for body buffering; no reentrant calls in - // this region until `terminate`/`process_response` below. + // this region until `terminate`/`process_websocket_upgrade_response` below. let me = unsafe { &mut *this }; // Process as if it came directly from the socket @@ -1229,17 +1671,6 @@ impl HTTPClient { body = &me.body; } - let is_first = me.body.is_empty(); - const HTTP_101: &[u8] = b"HTTP/1.1 101 "; - if is_first && body.len() > HTTP_101.len() { - // fail early if we receive a non-101 status code - if !body.starts_with(HTTP_101) { - // SAFETY: `me`'s last use is above; no `&mut Self` spans this call. - unsafe { Self::terminate(this, ErrorCode::Expected101StatusCode) }; - return; - } - } - let response = match picohttp::Response::parse(body, &mut me.headers_buf) { Ok(r) => r, Err(picohttp::ParseResponseError::MalformedHttpResponse) => { @@ -1263,21 +1694,55 @@ impl HTTPClient { } }; - let bytes_read = usize::try_from(response.bytes_read).expect("int cast"); - // Reshaped for borrowck — copy remain_buf out before mutating self. - let remain_buf: Vec = body[bytes_read..].to_vec(); + // Reshaped for borrowck — copy the full parsed buffer out before + // mutating self, since `process_websocket_upgrade_response` re-parses + // it and may mutate `self.body`/`headers_buf`. + let full: Vec = body.to_vec(); // SAFETY: `me`'s last use is the `body` slice above (now copied out); // no `&mut Self` spans this call. - unsafe { Self::process_response(this, response, &remain_buf) }; + unsafe { Self::process_websocket_upgrade_response(this, response, &full) }; } /// Takes `ThisPtr` because `terminate` may free `this`; see `fail`. pub fn handle_end(this: ThisPtr, _: Socket) { log!("onEnd"); + // If we were waiting for the peer to close before dispatching a + // non-101 response body (Content-Length absent, or a short + // Content-Length that never completed), flush now with whatever + // arrived so the `unexpected-response` consumer sees the partial + // body rather than nothing. + // SAFETY: forwards `this` with root provenance; no `&mut Self` is live. + if unsafe { Self::flush_deferred_on_close(this.as_ptr()) } { + return; + } // SAFETY: forwards `this` with root provenance; no `&mut Self` is live. unsafe { Self::terminate(this.as_ptr(), ErrorCode::Ended) }; } + /// Flush a pending deferred-handshake body on clean/abrupt connection + /// end. Returns `true` when it dispatched (and thus consumed the + /// teardown — the caller should not also `terminate`). + /// + /// # Safety + /// `this` must point to a live `Self`; the dispatch may free `this`. + unsafe fn flush_deferred_on_close(this: *mut Self) -> bool { + // SAFETY: short-lived read/reset; ends before the dispatch. + let me = unsafe { &mut *this }; + match me.deferred_handshake { + DeferredHandshake::None => false, + DeferredHandshake::WaitingForLength(_) | DeferredHandshake::WaitingForEof => { + me.deferred_handshake = DeferredHandshake::None; + if me.body.is_empty() { + return false; + } + let full: Vec = core::mem::take(&mut me.body); + // SAFETY: `me`'s last use is above; no `&mut Self` spans this call. + unsafe { Self::flush_deferred_handshake_and_process(this, &full) }; + true + } + } + } + /// # Safety /// `this` must point to a live `Self`. Takes `*mut Self` because /// `terminate`/`tcp.close()` may synchronously dispatch `handle_close` diff --git a/src/js/builtins/BunBuiltinNames.h b/src/js/builtins/BunBuiltinNames.h index b6495c2eea2b..50339bed82ad 100644 --- a/src/js/builtins/BunBuiltinNames.h +++ b/src/js/builtins/BunBuiltinNames.h @@ -159,6 +159,7 @@ using namespace JSC; macro(processBindingConstants) \ macro(props) \ macro(pull) \ + macro(rawHeaders) \ macro(read) \ macro(readable) \ macro(readableType) \ @@ -182,6 +183,8 @@ using namespace JSC; macro(started) \ macro(state) \ macro(status) \ + macro(statusCode) \ + macro(statusMessage) \ macro(statusText) \ macro(stream) \ macro(structuredCloneForStream) \ diff --git a/src/js/thirdparty/ws.js b/src/js/thirdparty/ws.js index 38102bcae9a4..f1139c341d42 100644 --- a/src/js/thirdparty/ws.js +++ b/src/js/thirdparty/ws.js @@ -90,8 +90,74 @@ const eventIds = { error: 4, ping: 5, pong: 6, + upgrade: 7, + "unexpected-response": 8, }; +// Stable singleton used by `#armNativeBridge` to install the native-side +// forwarder through `#onOrOnce` without pushing a user-visible listener. It +// must be identity-stable so `super.off` can remove it later if needed. +function noopBridgeListener() {} + +// Headers for which Node's http.IncomingMessage keeps only the first value and +// discards later duplicates, matching lib/_http_incoming.js matchKnownFields. +// Real `ws` hands consumers that Node object, so the synthetic IncomingMessage +// passed to 'unexpected-response' must coalesce the same way. +const kSingletonHeaders = new Set([ + "age", + "authorization", + "content-length", + "content-type", + "etag", + "expires", + "from", + "host", + "if-modified-since", + "if-unmodified-since", + "last-modified", + "location", + "max-forwards", + "proxy-authorization", + "referer", + "retry-after", + "server", + "user-agent", +]); + +let lazyReadable; +function makeHandshakeResponse(statusCode, statusMessage, rawHeaders, body) { + lazyReadable ??= require("node:stream").Readable; + const res = new lazyReadable({ read() {} }); + const headers = (res.headers = { __proto__: null }); + res.rawHeaders = rawHeaders; + for (let i = 0; i < rawHeaders.length; i += 2) { + const lower = rawHeaders[i].toLowerCase(); + const value = rawHeaders[i + 1]; + const prev = headers[lower]; + if (lower === "set-cookie") { + if (prev === undefined) headers[lower] = [value]; + else prev.push(value); + } else if (prev === undefined) { + headers[lower] = value; + } else if (kSingletonHeaders.has(lower)) { + // Keep the first occurrence; discard the duplicate. + } else if (lower === "cookie") { + headers[lower] = prev + "; " + value; + } else { + headers[lower] = prev + ", " + value; + } + } + res.statusCode = statusCode; + res.statusMessage = statusMessage; + res.httpVersion = "1.1"; + res.httpVersionMajor = 1; + res.httpVersionMinor = 1; + res.socket = res.connection = null; + if (body && body.length) res.push(body); + res.push(null); + return res; +} + const emittedWarnings = new Set(); function emitWarning(type, message) { if (emittedWarnings.has(type)) return; @@ -134,6 +200,25 @@ class BunWebSocket extends EventEmitter { #paused = false; #fragments = false; #binaryType = "nodebuffer"; + // True once an 'error' has already been surfaced to EventEmitter listeners + // (either a synthetic non-101 error or because 'unexpected-response' fired). + // Gates the bridge closure so the native 'Expected 101' error isn't + // re-emitted onto the EventEmitter a second time. + #unexpectedResponseEmitted = false; + // True only when 'unexpected-response' actually fired — i.e. the consumer + // handled the non-101 response, so real ws emits no 'error' at all. Gates + // the `addEventListener('error')` / `onerror` wrappers (which live on + // `this.#ws`, not the EventEmitter). Kept separate from + // `#unexpectedResponseEmitted` so a synthetic `emit('error')` to an + // `on('error')` listener doesn't also swallow a DOM-style handler's error. + #unexpectedResponseHandled = false; + // Wrappers for `addEventListener('error', h)` so the native 'Expected 101' + // error is suppressed after 'unexpected-response' (matching `on('error')` + // and real npm `ws`). Keyed by the user's listener so `removeEventListener` + // can still find and detach the wrapper. + #errorListenerWrappers; + // The user's `onerror` function (the native slot holds a suppression wrapper). + #onerror; // Bitset to track whether event handlers are set. #eventId = 0; @@ -277,14 +362,117 @@ class BunWebSocket extends EventEmitter { } let ws = (this.#ws = new WebSocket(url, wsOptions)); ws.binaryType = "nodebuffer"; + // NOTE: the native 'handshake' listener is registered lazily from + // #ensureHandshakeListener() when the user subscribes to 'upgrade' or + // 'unexpected-response'. Keeping it off by default means callers that + // only listen to 'open'/'message'/'close' never exercise the Zig + // handshake-dispatch path (which has historically been fragile under + // ASAN, e.g. ws-proxy.test.ts). return ws; } + #handshakeListenerRegistered = false; + #ensureHandshakeListener() { + if (this.#handshakeListenerRegistered) return; + this.#handshakeListenerRegistered = true; + this.#ws.addEventListener("handshake", event => this.#onHandshake(event.data), onceObject); + } + + // ws emits `'upgrade'` / `'unexpected-response'` with an `http.ClientRequest` + // as the first argument. We bypass node:http and talk to the native + // WebSocket directly, so there is no real ClientRequest to expose. Pass a + // minimal stub — `method`, `path`, and the no-op header helpers — so user + // code that inspects the request object (e.g. `req.getHeader(...)`) does + // not crash. Build it lazily on first emission to keep the common open/ + // close path zero-cost. + #syntheticRequest; + #getSyntheticRequest() { + let req = this.#syntheticRequest; + if (req) return req; + const url = this.#ws?.url; + let path = "/"; + try { + if (url) { + const parsed = new URL(url); + // Node's http.ClientRequest.path is pathname + search (no fragment) + // per RFC 7230 §5.3. Preserve the query string so handlers that log + // or reconstruct the failing URL see the full request target. + path = (parsed.pathname || "/") + (parsed.search || ""); + } + } catch {} + req = this.#syntheticRequest = { + __proto__: Object.create(EventEmitter.prototype), + method: "GET", + path, + url, + headers: { __proto__: null }, + rawHeaders: [], + getHeader() {}, + getHeaders() { + return { __proto__: null }; + }, + setHeader() {}, + removeHeader() {}, + hasHeader() { + return false; + }, + abort() {}, + end() {}, + write() {}, + writeHead() {}, + headersSent: true, + finished: true, + socket: null, + [Symbol.toStringTag]: "ClientRequest", + }; + return req; + } + + #onHandshake(data) { + const { statusCode, statusMessage, rawHeaders, body } = data; + // On 101, any bytes arriving after the header block are the first + // WebSocket frame, not HTTP response body — node's http layer delivers + // them as the `head` buffer on the 'upgrade' event and the native + // WebSocket client forwards them to the protocol reader on didConnect. + // Don't leak them into the `upgrade` event's IncomingMessage stream. + const res = makeHandshakeResponse(statusCode, statusMessage, rawHeaders, statusCode === 101 ? null : body); + if (statusCode === 101) { + // `upgrade` emits `(response)` per ws docs. + this.emit("upgrade", res); + return; + } + if (this.listenerCount("unexpected-response") > 0) { + // The consumer handled the response via 'unexpected-response'. Real ws + // emits no 'error' at all in this case, so suppress the native follow-up + // for every registration style (EventEmitter bridge AND the DOM-style + // wrappers). + this.#unexpectedResponseEmitted = true; + this.#unexpectedResponseHandled = true; + // `unexpected-response` emits `(request, response)` per ws docs. + this.emit("unexpected-response", this.#getSyntheticRequest(), res); + } else if (this.listenerCount("error") > 0) { + // An EventEmitter 'error' listener (on/once/addListener/...) gets a + // synthetic error here; mark it emitted so the bridge closure doesn't + // deliver the native follow-up to the EventEmitter a second time. We do + // NOT set #unexpectedResponseHandled — a DOM-style handler + // (addEventListener('error')/onerror) registered alongside still gets the + // native error exactly once, since its wrapper gates on that flag. + this.#unexpectedResponseEmitted = true; + this.emit("error", new Error("Unexpected server response: " + statusCode)); + } + } + #onOrOnce(event, listener, once) { - if (event === "unexpected-response" || event === "upgrade" || event === "redirect") { + if (event === "redirect") { emitWarning(event, "ws.WebSocket '" + event + "' event is not implemented in bun"); } + if (event === "upgrade" || event === "unexpected-response") { + // Lazy-register the native handshake listener so callers that never + // subscribe to these events don't exercise the Zig handshake dispatch. + this.#ensureHandshakeListener(); + return once ? super.once(event, listener) : super.on(event, listener); + } const mask = 1 << eventIds[event]; const hasPersistentListener = mask && (this.#eventId & mask) === mask; // Add a native listener if: @@ -333,6 +521,7 @@ class BunWebSocket extends EventEmitter { this.#ws.addEventListener( "error", err => { + if (this.#unexpectedResponseEmitted) return; this.emit("error", err); }, once, @@ -366,6 +555,57 @@ class BunWebSocket extends EventEmitter { return this.#onOrOnce(event, listener, onceObject); } + // `on` is the conventional spelling, but ws / EventEmitter consumers also + // reach for `addListener` / `prependListener` / `prependOnceListener`. Each + // needs to arm the native bridge (the `#onOrOnce` path for standard events + // like 'open' / 'message', or `#ensureHandshakeListener()` for 'upgrade' / + // 'unexpected-response') — otherwise the handler sits on the EventEmitter + // list but the native event that would trigger `this.emit(...)` is never + // wired up, and the callback silently never fires. + addListener(event, listener) { + return this.#onOrOnce(event, listener, undefined); + } + + prependListener(event, listener) { + this.#armNativeBridge(event); + return super.prependListener(event, listener); + } + + prependOnceListener(event, listener) { + this.#armNativeBridge(event); + return super.prependOnceListener(event, listener); + } + + // Install the native-side listener that eventually calls `this.emit(event, + // …)`, without pushing a new EventEmitter listener onto the list — that + // part is the caller's job (e.g. `super.prependListener`). Mirrors the + // bridge-installation branch of `#onOrOnce` for the cases where we need + // the side effect but not the `super.on`/`super.once` call. + #armNativeBridge(event) { + if (event === "upgrade" || event === "unexpected-response") { + this.#ensureHandshakeListener(); + return; + } + // `1 << undefined` evaluates to `1` (ToInt32(undefined) = 0), so a + // naive `if (!mask) return` would silently fall through for unknown + // event names and install a spurious noopBridgeListener on bit 0. + // Guard explicitly against unknown events. + if (eventIds[event] === undefined) return; + const mask = 1 << eventIds[event]; + const hasPersistentListener = (this.#eventId & mask) === mask; + if (hasPersistentListener) return; + // Install the native forwarder once. `#onOrOnce` flips the `#eventId` + // bit and registers the native listener as a side effect, but it also + // appends the listener we pass to the EventEmitter list. We only want + // the side effect here (the caller, e.g. `super.prependListener`, owns + // the real listener), so register `noopBridgeListener` and immediately + // remove it — leaving the native forwarder installed and the + // EventEmitter list untouched. Subsequent calls see + // `hasPersistentListener` and skip this branch. + this.#onOrOnce(event, noopBridgeListener, undefined); + super.off(event, noopBridgeListener); + } + send(data, opts, cb) { if ($isCallable(opts)) { cb = opts; @@ -433,10 +673,78 @@ class BunWebSocket extends EventEmitter { // deviation: this does not support `message` with `binaryType = "fragments"` addEventListener(type, listener, options) { + // 'upgrade' and 'unexpected-response' are Node-style events — they're + // emitted on the JS-side EventEmitter by `#onHandshake`, never by the + // native WebSocket. Register on `this` and arm the handshake listener. + // We deliberately don't wrap the handler in a DOM-style adapter: a + // wrapped closure would make `removeEventListener` fail to match the + // original listener, leaking the handler. Consumers that reach for + // `addEventListener` on a ws shim already accept a mixed API; for + // these two Node-only events they receive Node-style + // `(response)` / `(request, response)` args. + if (type === "upgrade" || type === "unexpected-response") { + this.#ensureHandshakeListener(); + // DOM dedup: `addEventListener` with the same listener is a no-op. + // EventEmitter.on/once don't dedup, so check the current listeners + // ourselves — matching real ws, which scans listeners(type) for every + // event type (and the 'error' branch below, which dedups too). + if (this.listeners(type).includes(listener)) return; + // `addEventListener` returns undefined per the DOM spec / real ws — + // use statement form so we don't leak EventEmitter's `this` return. + if (options && options.once) { + super.once(type, listener); + } else { + super.on(type, listener); + } + return; + } + if (type === "error" && typeof listener === "function") { + // DOM dedup: re-registering the same listener is a no-op. We wrap below, + // so distinct wrappers would defeat the native EventTarget's identity + // dedup — check our own map instead (and avoid leaking the prior wrapper). + if (this.#errorListenerWrappers?.has(listener)) return; + // Suppress the native 'Expected 101' error only when 'unexpected-response' + // actually handled the non-101 (matching real ws, which emits no error + // then). Gate on #unexpectedResponseHandled — NOT #unexpectedResponse + // Emitted — so a synthetic emit to a co-registered `on('error')` listener + // doesn't also swallow this handler. Wrap in a gated closure and remember + // it so `removeEventListener` can detach it. + const self = this; + // With `{once:true}` the native EventTarget auto-removes the wrapper + // after it fires, so drop our dedup entry too — otherwise a later + // `addEventListener('error', listener)` would hit the guard above and + // silently no-op even though nothing is attached anymore. + const once = !!(options && options.once); + const wrapper = function (event) { + if (once) self.#errorListenerWrappers?.delete(listener); + if (self.#unexpectedResponseHandled) return; + return listener.$call(this, event); + }; + (this.#errorListenerWrappers ??= new WeakMap()).set(listener, wrapper); + this.#ws.addEventListener(type, wrapper, options); + return; + } this.#ws.addEventListener(type, listener, options); } removeEventListener(type, listener) { + // Symmetric with addEventListener: upgrade/unexpected-response + // listeners live on `this` (the EventEmitter), not on the native + // WebSocket, so removing them means calling `super.off`. + if (type === "upgrade" || type === "unexpected-response") { + super.off(type, listener); + return; + } + if (type === "error") { + // `addEventListener('error', …)` registered a suppression wrapper, not + // the user's listener — detach the wrapper we stored for it. + const wrapper = this.#errorListenerWrappers?.get(listener); + if (wrapper !== undefined) { + this.#errorListenerWrappers.delete(listener); + this.#ws.removeEventListener(type, wrapper); + return; + } + } this.#ws.removeEventListener(type, listener); } @@ -449,11 +757,26 @@ class BunWebSocket extends EventEmitter { } get onerror() { - return this.#ws.onerror; + // Return the user's function, not the suppression wrapper we installed. + return this.#onerror ?? this.#ws.onerror; } set onerror(value) { - this.#ws.onerror = value; + this.#onerror = typeof value === "function" ? value : undefined; + if (this.#onerror === undefined) { + this.#ws.onerror = value; + return; + } + // Suppress the native 'Expected 101' error only when 'unexpected-response' + // handled the non-101 (matching `addEventListener('error')` and real ws). + // Gate on #unexpectedResponseHandled so a co-registered `on('error')` + // listener's synthetic emit doesn't swallow this handler's error. + const self = this; + const fn = this.#onerror; + this.#ws.onerror = function (event) { + if (self.#unexpectedResponseHandled) return; + return fn.$call(this, event); + }; } get onclose() { diff --git a/src/jsc/bindings/webcore/EventNames.h b/src/jsc/bindings/webcore/EventNames.h index dfd9feccd6c3..293b389350a2 100644 --- a/src/jsc/bindings/webcore/EventNames.h +++ b/src/jsc/bindings/webcore/EventNames.h @@ -29,16 +29,17 @@ namespace WebCore { -#define DOM_EVENT_NAMES_FOR_EACH(macro) \ - macro(error) \ - macro(abort) \ - macro(close) \ - macro(open) \ - macro(rename) \ - macro(message) \ - macro(change) \ - macro(messageerror) \ - macro(resourcetimingbufferfull) +#define DOM_EVENT_NAMES_FOR_EACH(macro) \ + macro(error) \ + macro(abort) \ + macro(close) \ + macro(open) \ + macro(rename) \ + macro(message) \ + macro(change) \ + macro(messageerror) \ + macro(handshake) \ + macro(resourcetimingbufferfull) struct EventNames { WTF_MAKE_NONCOPYABLE(EventNames); diff --git a/src/jsc/bindings/webcore/WebSocket.cpp b/src/jsc/bindings/webcore/WebSocket.cpp index 6c2b465c98fc..df52c061ec33 100644 --- a/src/jsc/bindings/webcore/WebSocket.cpp +++ b/src/jsc/bindings/webcore/WebSocket.cpp @@ -74,6 +74,7 @@ #include #include "JSBuffer.h" +#include "BunClientData.h" #include "ErrorEvent.h" #include "WebSocketDeflate.h" @@ -1556,6 +1557,59 @@ void WebSocket::didReceiveBinaryData(const AtomString& eventName, const std::spa // }); } +void WebSocket::didReceiveHandshakeResponse(uint16_t statusCode, std::span statusMessage, std::span headers, std::span body) +{ + // The only consumer is the `ws` package shim, which always registers a listener + // before connecting. The browser-style `new WebSocket()` path skips this entirely. + if (!this->hasEventListeners(eventNames().handshakeEvent)) + return; + + auto* context = scriptExecutionContext(); + if (!context) + return; + auto* globalObject = context->jsGlobalObject(); + auto& vm = globalObject->vm(); + auto scope = DECLARE_TOP_EXCEPTION_SCOPE(vm); + auto& builtinNames = WebCore::builtinNames(vm); + + auto* obj = JSC::constructEmptyObject(globalObject); + obj->putDirect(vm, builtinNames.statusCodePublicName(), JSC::jsNumber(statusCode)); + obj->putDirect(vm, builtinNames.statusMessagePublicName(), + JSC::jsString(vm, WTF::String({ statusMessage.data(), statusMessage.size() }))); + + // PicoHTTP already parsed the response head, so surface its header list as + // a flat [name, value, name, value, ...] rawHeaders array. + auto* rawHeaders = JSC::constructEmptyArray(globalObject, nullptr, headers.size() * 2); + if (!rawHeaders || scope.exception()) [[unlikely]] { + scope.clearExceptionExceptTermination(); + return; + } + for (size_t i = 0; i < headers.size(); i++) { + rawHeaders->putDirectIndex(globalObject, i * 2, + JSC::jsString(vm, WTF::String({ headers[i].name_ptr, headers[i].name_len }))); + rawHeaders->putDirectIndex(globalObject, i * 2 + 1, + JSC::jsString(vm, WTF::String({ headers[i].value_ptr, headers[i].value_len }))); + } + obj->putDirect(vm, builtinNames.rawHeadersPublicName(), rawHeaders); + + JSC::JSUint8Array* bodyBuffer = createBuffer(globalObject, body); + if (!bodyBuffer || scope.exception()) [[unlikely]] { + scope.clearExceptionExceptTermination(); + return; + } + obj->putDirect(vm, builtinNames.bodyPublicName(), bodyBuffer); + + JSC::EnsureStillAliveScope ensureStillAlive(obj); + + MessageEvent::Init init; + init.data = obj; + init.origin = m_url.string(); + + this->incPendingActivityCount(); + dispatchEvent(MessageEvent::create(eventNames().handshakeEvent, WTF::move(init), EventIsTrusted::Yes)); + this->decPendingActivityCount(); +} + void WebSocket::didReceiveClose(CleanStatus wasClean, unsigned short code, WTF::String reason, bool isConnectionError) { // LOG(Network, "WebSocket %p didReceiveErrorMessage()", this); @@ -1934,6 +1988,11 @@ extern "C" void WebSocket__didConnectWithTunnel(WebCore::WebSocket* webSocket, v webSocket->didConnectWithTunnel(tunnel, bufferedData, len, deflate_params); } +extern "C" void WebSocket__didReceiveHandshakeResponse(WebCore::WebSocket* webSocket, uint16_t statusCode, const uint8_t* statusMessage, size_t statusMessageLen, const WebCore::WebSocket::HandshakeRawHeader* headers, size_t headersLen, const uint8_t* body, size_t bodyLen) +{ + webSocket->didReceiveHandshakeResponse(statusCode, std::span(statusMessage, statusMessageLen), std::span(headers, headersLen), std::span(body, bodyLen)); +} + extern "C" void WebSocket__didAbruptClose(WebCore::WebSocket* webSocket, Bun::WebSocketErrorCode errorCode) { webSocket->didFailWithErrorCode(errorCode); diff --git a/src/jsc/bindings/webcore/WebSocket.h b/src/jsc/bindings/webcore/WebSocket.h index a0c1ada560d5..c86298ffa0ab 100644 --- a/src/jsc/bindings/webcore/WebSocket.h +++ b/src/jsc/bindings/webcore/WebSocket.h @@ -207,6 +207,13 @@ class WebSocket final : public RefCounted, public EventTargetWithInli void didReceiveMessage(String&& message); void didReceiveData(const char* data, size_t length); void didReceiveBinaryData(const AtomString& eventName, const std::span binaryData); + struct HandshakeRawHeader { + const uint8_t* name_ptr; + size_t name_len; + const uint8_t* value_ptr; + size_t value_len; + }; + void didReceiveHandshakeResponse(uint16_t statusCode, std::span statusMessage, std::span headers, std::span body); void updateHasPendingActivity(); bool hasPendingActivity() const diff --git a/test/regression/issue/05951.test.ts b/test/regression/issue/05951.test.ts new file mode 100644 index 000000000000..d606499dbc40 --- /dev/null +++ b/test/regression/issue/05951.test.ts @@ -0,0 +1,696 @@ +// https://github.com/oven-sh/bun/issues/5951 +// +// Exercises the public `ws` package surface (what miniflare/wrangler actually +// listen for), not the native 'handshake' event covered in 24229.test.ts. +import { expect, test } from "bun:test"; +import { bunEnv, bunExe, isASAN, isDebug, normalizeBunSnapshot } from "harness"; + +async function run(script: string) { + await using proc = Bun.spawn({ + cmd: [bunExe(), "-e", script], + env: bunEnv, + stdout: "pipe", + stderr: "pipe", + }); + const [stdout, stderr, exitCode] = await Promise.all([proc.stdout.text(), proc.stderr.text(), proc.exited]); + if (exitCode !== 0) console.error(stderr); + return { stdout: normalizeBunSnapshot(stdout), exitCode }; +} + +test.concurrent("ws emits 'unexpected-response' with status, headers and body on non-101", async () => { + const { stdout, exitCode } = await run(/* js */ ` + const { createServer } = require("net"); + const { once } = require("events"); + const { WebSocket } = require("ws"); + + const server = createServer(s => + s.once("data", () => + s.end("HTTP/1.1 503 Service Unavailable\\r\\nX-Reason: not-ready\\r\\n\\r\\nworkerd starting"), + ), + ).listen(0, "127.0.0.1"); + await once(server, "listening"); + + const ws = new WebSocket("ws://127.0.0.1:" + server.address().port); + ws.on("error", () => {}); + const [req, res] = await new Promise(resolve => + ws.once("unexpected-response", (req, res) => resolve([req, res])), + ); + let body = ""; + for await (const chunk of res) body += chunk; + console.log(JSON.stringify({ + reqMethod: req?.method, + reqPath: req?.path, + reqGetHeader: typeof req?.getHeader === "function" ? req.getHeader("x-anything") ?? null : "missing", + statusCode: res.statusCode, + statusMessage: res.statusMessage, + xReason: res.headers["x-reason"], + body, + })); + await once(ws, "close"); + server.close(); + `); + // ws emits 'unexpected-response' with (ClientRequest, IncomingMessage). We + // don't use node:http so the request is a minimal synthetic stub — assert + // its method/path/getHeader surface so code that inspects the request + // object doesn't crash. + expect(stdout).toMatchInlineSnapshot( + `"{"reqMethod":"GET","reqPath":"/","reqGetHeader":null,"statusCode":503,"statusMessage":"Service Unavailable","xReason":"not-ready","body":"workerd starting"}"`, + ); + expect(exitCode).toBe(0); +}); + +// Diverges from real ws: with no 'unexpected-response' listener, real ws emits +// "Unexpected server response: 503". Bun's shim only registers the native +// handshake listener when the user subscribes to 'upgrade'/'unexpected-response', +// so the unmodified native error surfaces instead. +test.concurrent("ws emits native 'error' on non-101 when no 'unexpected-response' listener", async () => { + const { stdout, exitCode } = await run(/* js */ ` + const { createServer } = require("net"); + const { once } = require("events"); + const { WebSocket } = require("ws"); + + const server = createServer(s => + s.once("data", () => s.end("HTTP/1.1 503 Service Unavailable\\r\\n\\r\\n")), + ).listen(0, "127.0.0.1"); + await once(server, "listening"); + + const ws = new WebSocket("ws://127.0.0.1:" + server.address().port); + const [err] = await once(ws, "error"); + console.log(/Expected 101/.test(err.message) ? "got native 101 error" : "unexpected: " + err.message); + server.close(); + process.exit(0); + `); + expect(stdout).toMatchInlineSnapshot(`"got native 101 error"`); + expect(exitCode).toBe(0); +}); + +test.concurrent("ws emits 'upgrade' with headers before 'open' on 101", async () => { + const { stdout, exitCode } = await run(/* js */ ` + const { createServer } = require("net"); + const { createHash } = require("crypto"); + const { once } = require("events"); + const { WebSocket } = require("ws"); + + const server = createServer(conn => { + let buf = ""; + const onData = chunk => { + buf += chunk.toString(); + if (buf.indexOf("\\r\\n\\r\\n") === -1) return; + conn.off("data", onData); + const key = /Sec-WebSocket-Key: (.+)\\r\\n/i.exec(buf)[1]; + const accept = createHash("sha1") + .update(key + "258EAFA5-E914-47DA-95CA-C5AB0DC85B11") + .digest("base64"); + conn.write( + "HTTP/1.1 101 Switching Protocols\\r\\nUpgrade: websocket\\r\\nConnection: Upgrade\\r\\nSec-WebSocket-Accept: " + + accept + "\\r\\n\\r\\n", + ); + }; + conn.on("data", onData); + }).listen(0, "127.0.0.1"); + await once(server, "listening"); + + const ws = new WebSocket("ws://127.0.0.1:" + server.address().port); + const order = []; + ws.on("upgrade", res => order.push("upgrade:" + res.statusCode + ":" + typeof res.headers["sec-websocket-accept"])); + ws.on("open", () => { + order.push("open"); + ws.terminate(); + server.close(); + }); + await once(ws, "close"); + console.log(order.join(",")); + `); + expect(stdout).toMatchInlineSnapshot(`"upgrade:101:string,open"`); + expect(exitCode).toBe(0); +}); + +// Real npm `ws` fires 'upgrade' and 'open' back-to-back in the same frame, so a +// microtask queued inside an 'upgrade' handler runs after the socket is OPEN. +// The native client dispatches 'upgrade' (handshake) then 'open' (connect); each +// dispatch drains microtasks on exit, so without a shared event-loop scope the +// queue drained *between* the two and the microtask observed readyState +// CONNECTING (0). A single scope around both dispatches keeps the drain after +// 'open', so the microtask sees OPEN (1). +test.concurrent("ws microtask queued in 'upgrade' handler observes readyState OPEN", async () => { + const { stdout, exitCode } = await run(/* js */ ` + const { createServer } = require("net"); + const { createHash } = require("crypto"); + const { once } = require("events"); + const { WebSocket } = require("ws"); + + const server = createServer(conn => { + let buf = ""; + const onData = chunk => { + buf += chunk.toString(); + if (buf.indexOf("\\r\\n\\r\\n") === -1) return; + conn.off("data", onData); + const key = /Sec-WebSocket-Key: (.+)\\r\\n/i.exec(buf)[1]; + const accept = createHash("sha1") + .update(key + "258EAFA5-E914-47DA-95CA-C5AB0DC85B11") + .digest("base64"); + conn.write( + "HTTP/1.1 101 Switching Protocols\\r\\nUpgrade: websocket\\r\\nConnection: Upgrade\\r\\nSec-WebSocket-Accept: " + + accept + "\\r\\n\\r\\n", + ); + }; + conn.on("data", onData); + }).listen(0, "127.0.0.1"); + await once(server, "listening"); + + const ws = new WebSocket("ws://127.0.0.1:" + server.address().port); + const { promise, resolve } = Promise.withResolvers(); + ws.on("upgrade", () => { + // Synchronously the socket is still CONNECTING; the microtask must not + // run until after 'open' has set it to OPEN. + const atUpgrade = ws.readyState; + queueMicrotask(() => resolve({ atUpgrade, inMicrotask: ws.readyState })); + }); + const states = await promise; + console.log(JSON.stringify({ + atUpgrade: states.atUpgrade, + inMicrotask: states.inMicrotask, + CONNECTING: WebSocket.CONNECTING, + OPEN: WebSocket.OPEN, + })); + ws.terminate(); + server.close(); + `); + // atUpgrade stays CONNECTING (0); the microtask drains after 'open' so it sees OPEN (1). + expect(stdout).toMatchInlineSnapshot(`"{"atUpgrade":0,"inMicrotask":1,"CONNECTING":0,"OPEN":1}"`); + expect(exitCode).toBe(0); +}); + +// The non-101 body can span multiple TCP reads. Previously the shim dispatched +// on the first read, truncating large error bodies. The native client now +// buffers until Content-Length is satisfied (or EOF) before dispatching. +test.concurrent("ws 'unexpected-response' waits for full Content-Length body across multiple writes", async () => { + const { stdout, exitCode } = await run(/* js */ ` + const { createServer } = require("net"); + const { once } = require("events"); + const { WebSocket } = require("ws"); + + // 8 kB JSON-ish payload, sent in three separate writes with a tick between + // each so the client sees multiple TCP reads (at least in the common case). + const CHUNK_SIZE = 2600; + const chunk1 = Buffer.alloc(CHUNK_SIZE, "a").toString(); + const chunk2 = Buffer.alloc(CHUNK_SIZE, "b").toString(); + const chunk3 = Buffer.alloc(CHUNK_SIZE, "c").toString(); + const bodyLen = CHUNK_SIZE * 3; + + const server = createServer(s => { + s.once("data", () => { + s.write( + "HTTP/1.1 503 Service Unavailable\\r\\n" + + "Content-Type: text/plain\\r\\n" + + "Content-Length: " + bodyLen + "\\r\\n\\r\\n" + + chunk1 + ); + setTimeout(() => s.write(chunk2), 10); + setTimeout(() => { s.write(chunk3); s.end(); }, 20); + }); + }).listen(0, "127.0.0.1"); + await once(server, "listening"); + + const ws = new WebSocket("ws://127.0.0.1:" + server.address().port); + ws.on("error", () => {}); + const [req, res] = await new Promise(resolve => + ws.once("unexpected-response", (req, res) => resolve([req, res])), + ); + let body = ""; + for await (const chunk of res) body += chunk; + console.log(JSON.stringify({ + statusCode: res.statusCode, + contentLength: res.headers["content-length"], + bodyLength: body.length, + firstChar: body[0], + lastChar: body[body.length - 1], + })); + await once(ws, "close"); + server.close(); + `); + expect(stdout).toMatchInlineSnapshot( + `"{"statusCode":503,"contentLength":"7800","bodyLength":7800,"firstChar":"a","lastChar":"c"}"`, + ); + expect(exitCode).toBe(0); +}); + +// The synthetic IncomingMessage passed to 'unexpected-response' must coalesce +// duplicate headers the way Node's http.IncomingMessage.headers does (real ws +// hands the consumer that Node object): singleton headers keep the first value +// and discard duplicates, duplicate `cookie` joins with "; ", everything else +// joins with ", ", and set-cookie is always an array. rawHeaders stays verbatim. +test.concurrent("ws 'unexpected-response' coalesces duplicate headers like Node IncomingMessage", async () => { + const { stdout, exitCode } = await run(/* js */ ` + const { createServer } = require("net"); + const { once } = require("events"); + const { WebSocket } = require("ws"); + + const server = createServer(s => + s.once("data", () => + s.end( + "HTTP/1.1 401 Unauthorized\\r\\n" + + // singleton header repeated -> first value kept + "Content-Length: 0\\r\\n" + + "Content-Length: 999\\r\\n" + + // duplicate cookie -> joined with "; " + "Cookie: a=1\\r\\n" + + "Cookie: b=2\\r\\n" + + // duplicate non-singleton -> joined with ", " + "X-Multi: one\\r\\n" + + "X-Multi: two\\r\\n" + + // set-cookie -> array + "Set-Cookie: s1=1\\r\\n" + + "Set-Cookie: s2=2\\r\\n" + + "\\r\\n", + ), + ), + ).listen(0, "127.0.0.1"); + await once(server, "listening"); + + const ws = new WebSocket("ws://127.0.0.1:" + server.address().port); + ws.on("error", () => {}); + const [, res] = await new Promise(resolve => + ws.once("unexpected-response", (req, res) => resolve([req, res])), + ); + console.log(JSON.stringify({ + contentLength: res.headers["content-length"], + cookie: res.headers["cookie"], + xMulti: res.headers["x-multi"], + setCookie: res.headers["set-cookie"], + rawContentLengths: res.rawHeaders.filter((_, i) => i % 2 === 0) + .reduce((n, k) => n + (k.toLowerCase() === "content-length" ? 1 : 0), 0), + })); + ws.terminate(); + server.close(); + `); + expect(stdout).toMatchInlineSnapshot( + `"{"contentLength":"0","cookie":"a=1; b=2","xMulti":"one, two","setCookie":["s1=1","s2=2"],"rawContentLengths":2}"`, + ); + expect(exitCode).toBe(0); +}); + +// RFC 7230 §3.3.3 rule #1: 1xx/204/304 responses carry no body regardless of +// headers. A bodiless non-101 status on a keep-alive connection (server never +// closes the socket) must dispatch 'unexpected-response' immediately off the +// header read — otherwise the client sits reading-until-EOF until the socket +// timeout and the event never fires. The server here deliberately keeps the +// connection open: with the fix this resolves at once; without it the +// subprocess hangs and the test times out. +test.concurrent("ws 'unexpected-response' fires immediately for bodiless 204 on keep-alive", async () => { + const { stdout, exitCode } = await run(/* js */ ` + const { createServer } = require("net"); + const { WebSocket } = require("ws"); + + // 204 No Content: no Content-Length, no Transfer-Encoding, and the socket + // is intentionally left open (no s.end()) so the only way the event fires + // is the immediate-dispatch path, not a read-until-close. + const server = createServer(s => + s.once("data", () => s.write("HTTP/1.1 204 No Content\\r\\nX-Gone: 1\\r\\n\\r\\n")), + ).listen(0, "127.0.0.1"); + await new Promise(r => server.once("listening", r)); + + const ws = new WebSocket("ws://127.0.0.1:" + server.address().port); + ws.on("error", () => {}); + const res = await new Promise(resolve => + ws.once("unexpected-response", (req, res) => resolve(res)), + ); + console.log(JSON.stringify({ + statusCode: res.statusCode, + statusMessage: res.statusMessage, + xGone: res.headers["x-gone"], + })); + ws.terminate(); + server.close(); + process.exit(0); + `); + expect(stdout).toMatchInlineSnapshot(`"{"statusCode":204,"statusMessage":"No Content","xGone":"1"}"`); + expect(exitCode).toBe(0); +}); + +// The RST teardown path (handle_close) flushes a mid-accumulation non-101 +// body into the 'unexpected-response' listener. If that listener synchronously +// calls ws.terminate()/ws.close(), the reentrant cancel() releases the socket +// ref while handle_close is still holding it — then handle_close's tcp.detach() +// runs on freed memory (heap-use-after-free in NewSocketHandler::detach) and +// its deref() underflows the refcount. Only an ASAN/debug build surfaces the +// corruption as a crash; release builds survive by luck, so gate on it. +// +// The RST must arrive as on_close WITHOUT a preceding on_end (FIN): a Bun.listen +// socket's terminate() sends a real RST while the client still has the body +// un-satisfied (WaitingForLength). Node's net server destroy()/resetAndDestroy() +// over loopback surfaces as FIN → on_end (a different, already-safe path). +test.concurrent.skipIf(!isDebug && !isASAN)( + "ws survives terminate() inside 'unexpected-response' when the socket RSTs mid-body", + async () => { + const { stdout, exitCode } = await run(/* js */ ` + const { once } = require("events"); + const { WebSocket } = require("ws"); + + // Declare a 100 kB body but send only a sliver, then RST a tick later so + // the client has parsed the headers and entered WaitingForLength. The + // RST then routes through handle_close, which flushes the deferred body + // into 'unexpected-response'. + const server = Bun.listen({ + hostname: "127.0.0.1", port: 0, + socket: { + data(socket) { + socket.write( + "HTTP/1.1 503 Service Unavailable\\r\\n" + + "Content-Length: 100000\\r\\n\\r\\n" + + "partial body, server resets before sending the rest" + ); + // Bun's socket.terminate() sends a real RST (not FIN). The small + // delay lets the partial body land first so the client is mid-body. + setTimeout(() => { try { socket.terminate(); } catch {} }, 10); + }, + error() {}, open() {}, + }, + }); + + const ws = new WebSocket("ws://127.0.0.1:" + server.port); + ws.on("error", () => {}); + ws.once("unexpected-response", (req, res) => { + console.log("status=" + res.statusCode); + // Reentrant teardown from inside the handshake dispatch — this is the + // path that used to UAF on the native client (handle_close then ran + // tcp.detach() on freed memory). + ws.terminate(); + }); + // Await 'close' rather than exiting immediately: the detach/deref that + // used to fault runs as handle_close unwinds, after terminate() returns. + await once(ws, "close"); + server.stop(true); + `); + expect(stdout).toContain("status=503"); + expect(exitCode).toBe(0); + }, +); + +// `on()` / `once()` are not the only EventEmitter registration APIs — ws +// consumers also reach for `addListener` / `prependListener` / +// `prependOnceListener` and (from DOM-style code) `addEventListener`. Each +// must arm the native handshake listener, otherwise the 'upgrade' / +// 'unexpected-response' handler is installed on the EventEmitter list but +// the native event that would `emit('upgrade', ...)` is never wired up and +// the callback silently never fires. +test.concurrent("ws 'unexpected-response' fires for addListener / prependListener / addEventListener", async () => { + const { stdout, exitCode } = await run(/* js */ ` + const { createServer } = require("net"); + const { once } = require("events"); + const { WebSocket } = require("ws"); + + async function runOne(register) { + const server = createServer(s => + s.once("data", () => s.end("HTTP/1.1 503 Service Unavailable\\r\\n\\r\\n")), + ).listen(0, "127.0.0.1"); + await once(server, "listening"); + + const ws = new WebSocket("ws://127.0.0.1:" + server.address().port); + ws.on("error", () => {}); + const { promise, resolve } = Promise.withResolvers(); + register(ws, resolve); + const res = await promise; + server.close(); + try { ws.terminate(); } catch {} + return res; + } + + const a = await runOne((ws, done) => + ws.addListener("unexpected-response", (req, res) => done(res.statusCode)), + ); + const b = await runOne((ws, done) => + ws.prependListener("unexpected-response", (req, res) => done(res.statusCode)), + ); + const c = await runOne((ws, done) => + ws.prependOnceListener("unexpected-response", (req, res) => done(res.statusCode)), + ); + const d = await runOne((ws, done) => + // For upgrade/unexpected-response addEventListener is symmetric with + // removeEventListener (no DOM-style wrapping adapter) so handlers + // receive Node-style args. + ws.addEventListener("unexpected-response", (req, res) => done(res.statusCode)), + ); + console.log(JSON.stringify({ a, b, c, d })); + process.exit(0); + `); + expect(stdout).toMatchInlineSnapshot(`"{"a":503,"b":503,"c":503,"d":503}"`); + expect(exitCode).toBe(0); +}); + +// Once 'unexpected-response' has fired, the native 'Expected 101' error must +// NOT reach user 'error' handlers (real ws never emits 'error' when the +// response was handled). The suppression has to apply uniformly across every +// registration API — on('error'), addEventListener('error', …) and the +// onerror setter — not just on()/once(). +test.concurrent( + "ws suppresses the native error after 'unexpected-response' across on/addEventListener/onerror", + async () => { + const { stdout, exitCode } = await run(/* js */ ` + const { createServer } = require("net"); + const { once } = require("events"); + const { WebSocket } = require("ws"); + + // Register the 'error' handler via one of the three APIs, subscribe to + // 'unexpected-response', and report whether a spurious 'error' still fired. + async function runOne(registerError) { + const server = createServer(s => + s.once("data", () => s.end("HTTP/1.1 503 Service Unavailable\\r\\n\\r\\n")), + ).listen(0, "127.0.0.1"); + await once(server, "listening"); + + const ws = new WebSocket("ws://127.0.0.1:" + server.address().port); + let errored = false; + registerError(ws, () => { errored = true; }); + const { promise, resolve } = Promise.withResolvers(); + ws.on("unexpected-response", (req, res) => resolve(res.statusCode)); + const status = await promise; + // Give the native error a turn of the loop to (not) arrive. + await once(ws, "close").catch(() => {}); + server.close(); + return { status, errored }; + } + + const on = await runOne((ws, mark) => ws.on("error", mark)); + const ael = await runOne((ws, mark) => ws.addEventListener("error", mark)); + const prop = await runOne((ws, mark) => { ws.onerror = mark; }); + console.log(JSON.stringify({ on, ael, prop })); + process.exit(0); + `); + // All three APIs: 'unexpected-response' seen (503), native 'error' suppressed. + expect(stdout).toMatchInlineSnapshot( + `"{"on":{"status":503,"errored":false},"ael":{"status":503,"errored":false},"prop":{"status":503,"errored":false}}"`, + ); + expect(exitCode).toBe(0); + }, +); + +// The suppression must NOT apply when the consumer never subscribed to +// 'unexpected-response'. A client that listens for 'upgrade' (arming the +// handshake bridge) but registers its error handling via addEventListener +// ('error') / onerror must still receive the native non-101 error — otherwise +// the error is swallowed entirely. +test.concurrent( + "ws still delivers the native error to addEventListener/onerror when there is no 'unexpected-response' listener", + async () => { + const { stdout, exitCode } = await run(/* js */ ` + const { createServer } = require("net"); + const { once } = require("events"); + const { WebSocket } = require("ws"); + + async function runOne(registerError) { + const server = createServer(s => + s.once("data", () => s.end("HTTP/1.1 503 Service Unavailable\\r\\n\\r\\n")), + ).listen(0, "127.0.0.1"); + await once(server, "listening"); + + const ws = new WebSocket("ws://127.0.0.1:" + server.address().port); + // Arm the handshake bridge via 'upgrade' but do NOT listen for + // 'unexpected-response', so the native error path is exercised. + ws.on("upgrade", () => {}); + const { promise, resolve } = Promise.withResolvers(); + registerError(ws, err => resolve(/Expected 101/.test(err?.message ?? String(err)))); + const gotExpected101 = await promise; + server.close(); + try { ws.terminate(); } catch {} + return gotExpected101; + } + + const ael = await runOne((ws, done) => ws.addEventListener("error", done)); + const prop = await runOne((ws, done) => { ws.onerror = done; }); + console.log(JSON.stringify({ ael, prop })); + process.exit(0); + `); + // Both DOM-style APIs receive the native 'Expected 101' error. + expect(stdout).toMatchInlineSnapshot(`"{"ael":true,"prop":true}"`); + expect(exitCode).toBe(0); + }, +); + +// With on('upgrade') + on('error') but no 'unexpected-response' listener, the +// on('error') handler lives on BOTH the EventEmitter (gets the synthetic +// "Unexpected server response" error) and — via the native bridge closure — on +// this.#ws (would get the native 'Expected 101' error too). It must fire +// exactly once, like real ws, not twice. +test.concurrent( + "ws on('error') fires once (not twice) for a non-101 with no 'unexpected-response' listener", + async () => { + const { stdout, exitCode } = await run(/* js */ ` + const { createServer } = require("net"); + const { once } = require("events"); + const { WebSocket } = require("ws"); + + const server = createServer(s => + s.once("data", () => s.end("HTTP/1.1 503 Service Unavailable\\r\\n\\r\\n")), + ).listen(0, "127.0.0.1"); + await once(server, "listening"); + + const ws = new WebSocket("ws://127.0.0.1:" + server.address().port); + ws.on("upgrade", () => {}); + const messages = []; + ws.on("error", err => messages.push(err?.message ?? String(err))); + // Wait for close, then report how many 'error' events arrived. + await once(ws, "close").catch(() => {}); + server.close(); + try { ws.terminate(); } catch {} + console.log(JSON.stringify({ count: messages.length, first: messages[0] })); + process.exit(0); + `); + // Exactly one 'error' — the synthetic non-101 message — and the native + // 'Expected 101' follow-up is suppressed for EventEmitter listeners. + expect(stdout).toMatchInlineSnapshot(`"{"count":1,"first":"Unexpected server response: 503"}"`); + expect(exitCode).toBe(0); + }, +); + +// Mixed registration styles: on('error') (EventEmitter) AND addEventListener +// ('error')/onerror (native this.#ws), with on('upgrade') but no +// 'unexpected-response'. Each handler must fire exactly once — the synthetic +// emit suppresses the EE bridge re-fire, but the DOM-style handler must still +// receive the native error (gated on a separate "handled" flag). +test.concurrent( + "ws error handlers each fire once when on('error') and addEventListener/onerror are mixed", + async () => { + const { stdout, exitCode } = await run(/* js */ ` + const { createServer } = require("net"); + const { once } = require("events"); + const { WebSocket } = require("ws"); + + async function runOne(registerDom) { + const server = createServer(s => + s.once("data", () => s.end("HTTP/1.1 503 Service Unavailable\\r\\n\\r\\n")), + ).listen(0, "127.0.0.1"); + await once(server, "listening"); + + const ws = new WebSocket("ws://127.0.0.1:" + server.address().port); + ws.on("upgrade", () => {}); + let onCount = 0; + let domCount = 0; + // The synthetic error (on) fires synchronously in #onHandshake; the + // native error (DOM handler) arrives a tick later after the client + // terminates. Await BOTH so neither the test nor 'close' races ahead of + // the native delivery. + const onSeen = Promise.withResolvers(); + const domSeen = Promise.withResolvers(); + ws.on("error", () => { onCount++; onSeen.resolve(); }); + registerDom(ws, () => { domCount++; domSeen.resolve(); }); + await Promise.all([onSeen.promise, domSeen.promise]); + server.close(); + try { ws.terminate(); } catch {} + return { onCount, domCount }; + } + + const ael = await runOne((ws, h) => ws.addEventListener("error", h)); + const prop = await runOne((ws, h) => { ws.onerror = h; }); + console.log(JSON.stringify({ ael, prop })); + process.exit(0); + `); + // Both the on('error') handler and the DOM-style handler fire exactly once. + expect(stdout).toMatchInlineSnapshot(`"{"ael":{"onCount":1,"domCount":1},"prop":{"onCount":1,"domCount":1}}"`); + expect(exitCode).toBe(0); + }, +); + +// DOM dedup: registering the identical listener twice via addEventListener is +// a no-op. Because we wrap the listener in a suppression closure, a naive +// implementation would create two distinct wrappers and fire the handler +// twice; removeEventListener must also detach it completely. +test.concurrent( + "ws addEventListener('error', h) dedupes the same handler and removeEventListener detaches it", + async () => { + const { stdout, exitCode } = await run(/* js */ ` + const { createServer } = require("net"); + const { once } = require("events"); + const { WebSocket } = require("ws"); + + const server = createServer(s => + s.once("data", () => s.end("HTTP/1.1 503 Service Unavailable\\r\\n\\r\\n")), + ).listen(0, "127.0.0.1"); + await once(server, "listening"); + + const ws = new WebSocket("ws://127.0.0.1:" + server.address().port); + let count = 0; + const h = () => { count++; }; + ws.addEventListener("error", h); + ws.addEventListener("error", h); // duplicate — must be a no-op + await once(ws, "close").catch(() => {}); + server.close(); + try { ws.terminate(); } catch {} + // removeEventListener must fully detach (no leaked wrapper left behind). + ws.removeEventListener("error", h); + console.log(JSON.stringify({ count })); + process.exit(0); + `); + // The handler fires exactly once despite the duplicate registration. + expect(stdout).toMatchInlineSnapshot(`"{"count":1}"`); + expect(exitCode).toBe(0); + }, +); + +// DOM dedup must also apply to the Node-only 'upgrade'/'unexpected-response' +// events. These register on the EventEmitter (super.on) which doesn't dedup, +// so addEventListener with the same handler twice would fire it twice on a +// 101 — real ws dedups every event type. +test.concurrent("ws addEventListener('upgrade', h) dedupes the same handler", async () => { + const { stdout, exitCode } = await run(/* js */ ` + const { createServer } = require("net"); + const { createHash } = require("crypto"); + const { once } = require("events"); + const { WebSocket } = require("ws"); + + const server = createServer(conn => { + let buf = ""; + const onData = chunk => { + buf += chunk.toString(); + if (buf.indexOf("\\r\\n\\r\\n") === -1) return; + conn.off("data", onData); + const key = /Sec-WebSocket-Key: (.+)\\r\\n/i.exec(buf)[1]; + const accept = createHash("sha1") + .update(key + "258EAFA5-E914-47DA-95CA-C5AB0DC85B11") + .digest("base64"); + conn.write( + "HTTP/1.1 101 Switching Protocols\\r\\nUpgrade: websocket\\r\\nConnection: Upgrade\\r\\nSec-WebSocket-Accept: " + + accept + "\\r\\n\\r\\n", + ); + }; + conn.on("data", onData); + }).listen(0, "127.0.0.1"); + await once(server, "listening"); + + const ws = new WebSocket("ws://127.0.0.1:" + server.address().port); + let count = 0; + const h = () => { count++; }; + ws.addEventListener("upgrade", h); + ws.addEventListener("upgrade", h); // duplicate — must be a no-op + await once(ws, "open"); + // removeEventListener must fully detach the single registration. + ws.removeEventListener("upgrade", h); + console.log(JSON.stringify({ count })); + ws.terminate(); + server.close(); + process.exit(0); + `); + // The handler fires exactly once despite the duplicate addEventListener. + expect(stdout).toMatchInlineSnapshot(`"{"count":1}"`); + expect(exitCode).toBe(0); +}); diff --git a/test/regression/issue/24229.test.ts b/test/regression/issue/24229.test.ts new file mode 100644 index 000000000000..509116318fb1 --- /dev/null +++ b/test/regression/issue/24229.test.ts @@ -0,0 +1,58 @@ +import { expect, test } from "bun:test"; +import { once } from "events"; +import { AddressInfo, createServer } from "net"; + +// https://github.com/oven-sh/bun/issues/24229 +// https://github.com/oven-sh/bun/issues/5951 +// +// The native WebSocket client now surfaces the handshake response to JS via +// a 'handshake' event (statusCode + statusMessage + rawHeaders + body) so the `ws` package shim can +// emit 'upgrade' / 'unexpected-response'. Previously non-101 responses were +// silently discarded, which made miniflare's `dispatchFetch` hang forever. +// +// Tests the native 'handshake' event directly — what the ws.js shim consumes. +test("WebSocket 'handshake' event surfaces status/head/body on non-101", async () => { + const server = createServer(socket => + socket.once("data", () => + socket.end( + "HTTP/1.1 503 Service Unavailable\r\n" + + "Content-Type: text/plain\r\n" + + "Set-Cookie: a=1\r\n" + + "Set-Cookie: b=2\r\n" + + "X-Multi: foo \r\n\r\nworkerd starting", + ), + ), + ).listen(0, "127.0.0.1"); + await once(server, "listening"); + + try { + const ws = new WebSocket("ws://127.0.0.1:" + (server.address() as AddressInfo).port); + ws.addEventListener("error", () => {}); // swallow the expected-101 error + const { promise, resolve } = Promise.withResolvers<{ + statusCode: number; + statusMessage: string; + rawHeaders: string[]; + body: Uint8Array; + }>(); + // 'handshake' is a Bun extension consumed by the ws package shim. + ws.addEventListener("handshake" as any, ((e: MessageEvent) => resolve(e.data as any)) as any); + const { statusCode, statusMessage, rawHeaders, body } = await promise; + + expect(statusCode).toBe(503); + expect(statusMessage).toBe("Service Unavailable"); + expect(rawHeaders).toEqual([ + "Content-Type", + "text/plain", + "Set-Cookie", + "a=1", + "Set-Cookie", + "b=2", + "X-Multi", + "foo", + ]); + expect(body).toBeInstanceOf(Uint8Array); + expect(new TextDecoder().decode(body)).toBe("workerd starting"); + } finally { + server.close(); + } +}); From 442985700fd8fc0dd4a1a959e598412b107e0fb2 Mon Sep 17 00:00:00 2001 From: robobun <117481402+robobun@users.noreply.github.com> Date: Wed, 29 Jul 2026 00:33:40 +0000 Subject: [PATCH 2/9] ws: refactor handshake dispatch into pure routing + stateless forward Split the non-101 body handling into a pure route_handshake_body() that returns a HandshakeBody decision, a stateless dispatch_handshake() that just forwards the parsed response to C++, and one ThisPtr orchestrator that owns the response buffer locally so nothing borrows self across the JS dispatch. Callers (handle_data / handle_decrypted_data / handle_end / handle_close / terminate) hold a ref_guard themselves; the orchestrator does not. handle_close's deferred branch collapses into the normal path: the ext slot is taken and tcp detached before any dispatch so a reentrant cancel() finds nothing to release, and the flush is a single call instead of inline bookkeeping. Drops 29 unsafe blocks and ~250 lines from the previous commit. --- .../WebSocketUpgradeClient.rs | 641 ++++++------------ 1 file changed, 197 insertions(+), 444 deletions(-) diff --git a/src/http_jsc/websocket_client/WebSocketUpgradeClient.rs b/src/http_jsc/websocket_client/WebSocketUpgradeClient.rs index b7dd6a736b25..09c05ff275d8 100644 --- a/src/http_jsc/websocket_client/WebSocketUpgradeClient.rs +++ b/src/http_jsc/websocket_client/WebSocketUpgradeClient.rs @@ -121,10 +121,8 @@ impl Drop for SslCtxOwned { } /// Non-`None` while buffering the body of a non-101 response that spans -/// multiple TCP reads. The `'handshake'` event is deferred until the full -/// body is in hand so the `unexpected-response` consumer sees the complete -/// payload instead of just the bytes colocated with the header block in the -/// first read. +/// multiple TCP reads, so the `'unexpected-response'` listener sees the +/// complete payload rather than a truncated prefix. #[derive(Clone, Copy, PartialEq, Eq)] enum DeferredHandshake { None, @@ -134,12 +132,19 @@ enum DeferredHandshake { WaitingForEof, } -/// Maximum bytes buffered for a non-101 response body before bailing out. -/// Real error pages (workerd restart text, JSON API errors, HTML) fit well -/// under this; the cap stops a malicious or misbehaving server from making -/// us accumulate unbounded data — either via a giant `Content-Length` header -/// or a keep-alive connection that never closes after a no-`Content-Length` -/// response. +/// Routing decision for a parsed handshake response body. +enum HandshakeBody { + /// Dispatch now; `end` is the exclusive upper bound of the body in `full`. + Ready { end: usize }, + /// Buffer `full` and wait for more data before dispatching. + Defer(DeferredHandshake), + /// Declared body exceeds [`MAX_NON_101_BODY`]; fail without buffering. + TooLarge, +} + +/// Cap on bytes buffered for a non-101 response body. Real error pages fit +/// well under this; the cap stops a misbehaving server from growing `self.body` +/// without bound. const MAX_NON_101_BODY: usize = 64 * 1024 * 1024; /// WebSocket HTTP upgrade client, generic over `SSL`. @@ -737,90 +742,44 @@ impl HTTPClient { pub fn handle_close(this: ThisPtr, _: Socket, _: c_int, _: *mut c_void) { log!("onClose"); bun_jsc::mark_binding!(); + let _guard = this.ref_guard(); - // If a non-101 response body was mid-accumulation when the peer reset - // the socket (RST rather than FIN, so `handle_end` never fires), - // flush whatever arrived BEFORE `clear_data()` frees `self.body`. The - // flush runs `process_response` which terminates the non-101 and - // clears `outgoing_websocket`, so `dispatch_abrupt_close` below is a - // no-op. We still `deref` once to balance the socket ref. - // - // The flush dispatches `unexpected-response` into JS, and that handler - // may synchronously `ws.close()`/`ws.terminate()` → reentrant - // `cancel()`. Left to its own devices, `cancel()` would see `tcp` still - // attached + the socket's ext slot still pointing at us and so - // (a) release the socket ref a second time and (b) `tcp.close()` again, - // re-entering `handle_close` — a use-after-free on the `tcp.detach()` - // below plus a refcount underflow. Guard against all of it: take the - // ext slot and detach `tcp` up front so the reentrant `cancel()` finds - // `ext == None` / a detached `tcp` and no-ops both, and hold a ref - // across the flush so the C++-ref release inside `cancel()` can't drop - // us to 0 before our own trailing `deref`. - // SAFETY: short-lived read; ends before the branch below. - let has_deferred = !matches!( - unsafe { (*this.as_ptr()).deferred_handshake }, - DeferredHandshake::None - ); - if has_deferred { - let _guard = this.ref_guard(); - // Take the socket-userdata ref's slot (matching `cancel`'s own - // take) and detach our `tcp` handle, before any dispatch, so a - // reentrant `cancel()` finds `ext == None` / a detached `tcp` and - // neither double-releases the socket ref nor re-enters `handle_close`. - // SAFETY: short-lived read of the `tcp` handle; `this` is live. - let tcp = unsafe { (*this.as_ptr()).tcp }; - if let Some(ext) = tcp.ext::>>() { - // SAFETY: the ext slot is the `Option>` written in - // `connect_group`; single-threaded (JS thread), no other `&mut` - // to it is live. - unsafe { (*ext).take() }; - } - // SAFETY: short-lived `&mut` for the field detach/clear_data. - unsafe { (*this.as_ptr()).tcp.detach() }; - // SAFETY: forwards `this`; `_guard` + the still-held socket ref - // keep it alive across the dispatch even if JS frees the C++ ref. - unsafe { Self::flush_deferred_on_close(this.as_ptr()) }; - // Release the C++ `outgoing_websocket` ref if it's still held. - // A reentrant `cancel()` (from `ws.close()`/`terminate()` in the - // listener) or the flush's own `process_response` may already have - // taken it; `take()` makes this release exactly-once regardless of - // which path ran. - // SAFETY: short-lived `&mut` for the field take. - if unsafe { (*this.as_ptr()).outgoing_websocket.take().is_some() } { - // SAFETY: no `&mut Self` is live; `_guard` still holds a ref. - unsafe { Self::deref(this.as_ptr()) }; - } - // Balance the socket ref whose ext slot we took above. - // SAFETY: no `&mut Self` is live; `_guard` still holds a ref. - unsafe { Self::deref(this.as_ptr()) }; - return; - // `_guard` drops here — the final release, may free `this`. + // Detach the socket and clear its ext slot before any JS dispatch so a + // reentrant `cancel()` from a listener finds nothing to release. + if let Some(ext) = this.tcp.ext::>>() { + // SAFETY: ext slot is the `Option>` set in `connect_group`. + unsafe { (*ext).take() }; } + // SAFETY: short-lived `&mut` for the field detach. + unsafe { (*this.as_ptr()).tcp.detach() }; - // SAFETY: short-lived `&mut` borrows; each ends before the next call. + // Flush any buffered non-101 body as `'unexpected-response'`; on the + // normal path this is a no-op. `process_response` → `terminate` + // consumes `outgoing_websocket`, so `dispatch_abrupt_close` below then + // no-ops. + if let Some(full) = Self::take_deferred_body(this) { + Self::process_websocket_upgrade_response(this, full, true); + } + + // SAFETY: short-lived `&mut` for clear_data; no reentrant call. unsafe { (*this.as_ptr()).clear_data() }; - // SAFETY: short-lived `&mut` for the field detach; `this` is live. - unsafe { (*this.as_ptr()).tcp.detach() }; // SAFETY: forwards `this` with root provenance; no `&mut Self` is live. unsafe { Self::dispatch_abrupt_close(this.as_ptr(), ErrorCode::Ended) }; - - // SAFETY: may free `this`; no `&mut Self` is live. + // SAFETY: balances the socket-userdata ref; `_guard` still holds one. unsafe { Self::deref(this.as_ptr()) }; } /// # Safety /// `this` must point to a live `Self`. See `fail`. pub unsafe fn terminate(this: *mut Self, code: ErrorCode) { - // If a non-101 response body was being accumulated when the transport - // ended cleanly (peer close), flush the deferred handshake first so - // the `unexpected-response` listener sees what the server delivered. - // `handle_end`/`handle_close` flush directly for the plain-TCP path; - // the wss://-through-HTTP-CONNECT-proxy path comes in via - // `WebSocketProxyTunnel::on_close` → `terminate(Ended)` without going - // through either, so the flush must live here too. + // The proxy-tunnel path reaches `terminate(Ended)` without going + // through `handle_end`/`handle_close`; flush any deferred body here too. if code == ErrorCode::Ended { - // SAFETY: forwards `this`; no `&mut Self` is live. May free `this`. - if unsafe { Self::flush_deferred_on_close(this) } { + // SAFETY: caller contract — `this` is a live `heap::alloc` pointer. + let this = unsafe { ThisPtr::new(this) }; + if let Some(full) = Self::take_deferred_body(this) { + let _guard = this.ref_guard(); + Self::process_websocket_upgrade_response(this, full, true); return; } } @@ -1021,12 +980,7 @@ impl HTTPClient { } } - // If we're mid-way through buffering a non-101 response body (a - // `Content-Length` larger than the first read, or a no-`Content- - // Length` response read until EOF), keep appending and check for - // completion before trying to parse again. See `DeferredHandshake`. - // SAFETY: forwards `this` with root provenance; no `&mut Self` is live. - if unsafe { Self::append_deferred_handshake_body(this.as_ptr(), data) } { + if Self::append_deferred_handshake_body(this, data) { return; } @@ -1062,101 +1016,124 @@ impl HTTPClient { } }; - // Reshaped for borrowck — copy the full parsed buffer out before - // mutating self, since `process_websocket_upgrade_response` re-parses - // it and may mutate `self.body`/`headers_buf`. - let full: Vec = body.to_vec(); - // SAFETY: `me`'s last use is the `body` slice above (now copied out); - // no `&mut Self` spans this call. - unsafe { Self::process_websocket_upgrade_response(this.as_ptr(), response, &full) }; + let _ = response; + Self::process_websocket_upgrade_response(this, body.to_vec(), false); // `_guard` drops here, balancing the ref above. May free `this`. } - /// Scan response headers for `Content-Length`; return the parsed value or - /// `None` when the header is absent or unparseable. - fn find_content_length(response: &picohttp::Response) -> Option { - for header in response.headers.list { - if header.name().len() == b"Content-Length".len() - && strings::eql_case_insensitive_ascii_ignore_length( - header.name(), - b"Content-Length", - ) - { - let value = header.value(); - let trimmed = core::str::from_utf8(value) - .ok()? - .trim_matches(|c| c == ' ' || c == '\t'); - return trimmed.parse::().ok(); + fn find_header<'a>(response: &picohttp::Response<'a>, name: &[u8]) -> Option<&'a [u8]> { + response + .headers + .list + .iter() + .find(|h| { + h.name().len() == name.len() + && strings::eql_case_insensitive_ascii_ignore_length(h.name(), name) + }) + .map(|h| h.value()) + } + + /// Decide whether a handshake response's body is ready to surface to JS + /// (and how much of `full` it spans), or whether more bytes are needed. + /// Pure: encodes RFC 7230 §3.3.3 body-length rules for the response side. + fn route_handshake_body( + response: &picohttp::Response, + head_len: usize, + available: usize, + ) -> HandshakeBody { + let status = response.status_code; + // 101: post-header bytes are the first WebSocket frame, not HTTP body. + if status == 101 { + return HandshakeBody::Ready { end: head_len }; + } + // Bodiless statuses (rule 1) and Transfer-Encoding (rule 3; we don't + // decode chunked here) dispatch immediately with whatever is on hand. + let bodiless = status == 204 || status == 304 || (100..200).contains(&status); + if bodiless || Self::find_header(response, b"Transfer-Encoding").is_some() { + return HandshakeBody::Ready { end: available }; + } + match Self::find_header(response, b"Content-Length").and_then(|v| { + core::str::from_utf8(v) + .ok()? + .trim_matches(|c: char| c == ' ' || c == '\t') + .parse::() + .ok() + }) { + Some(cl) if cl > MAX_NON_101_BODY => HandshakeBody::TooLarge, + Some(cl) => { + let target = head_len + cl; + if available >= target { + HandshakeBody::Ready { end: target } + } else { + HandshakeBody::Defer(DeferredHandshake::WaitingForLength(target)) + } } + // Rule 7: read until the peer closes. + None => HandshakeBody::Defer(DeferredHandshake::WaitingForEof), } - None } - /// Whether the response carries a `Transfer-Encoding` header (chunked or - /// otherwise). Such bodies have no `Content-Length` and their wire bytes - /// are framing, not payload — the caller dispatches immediately instead - /// of accumulating raw framing until EOF. - fn has_transfer_encoding(response: &picohttp::Response) -> bool { - for header in response.headers.list { - if header.name().len() == b"Transfer-Encoding".len() - && strings::eql_case_insensitive_ascii_ignore_length( - header.name(), - b"Transfer-Encoding", - ) - { - return true; - } + /// Forward the parsed handshake response to the C++ `WebSocket` as a + /// `'handshake'` event. Everything borrows `response`'s parse buffer, which + /// the caller keeps alive for the call; C++ copies into JS strings before + /// any user JS runs. + fn dispatch_handshake(ws: *mut CppWebSocket, response: &picohttp::Response, body: &[u8]) { + let raw_headers: Vec = response + .headers + .list + .iter() + .map(|h| super::cpp_websocket::RawHeader { + name_ptr: h.name().as_ptr(), + name_len: h.name().len(), + value_ptr: h.value().as_ptr(), + value_len: h.value().len(), + }) + .collect(); + CppWebSocket::opaque_ref(ws).did_receive_handshake_response( + u16::try_from(response.status_code).unwrap_or(0), + response.status, + &raw_headers, + body, + ); + } + + /// Take the buffered deferred-handshake body out of `self`, clearing the + /// deferred state. `None` when nothing was deferred. + fn take_deferred_body(this: ThisPtr) -> Option> { + // SAFETY: short-lived `&mut` for field reads/writes; no reentrant call. + let me = unsafe { &mut *this.as_ptr() }; + if matches!(me.deferred_handshake, DeferredHandshake::None) { + return None; } - false + me.deferred_handshake = DeferredHandshake::None; + let full = core::mem::take(&mut me.body); + (!full.is_empty()).then_some(full) } - /// Append `data` to the deferred non-101 body buffer. - /// - /// Returns `true` when `data` was consumed as part of a deferred - /// handshake (and the caller should stop processing this read). Enforces - /// [`MAX_NON_101_BODY`] so neither a giant `Content-Length` nor a - /// never-closing no-`Content-Length` stream can grow `self.body` without - /// bound. - /// - /// # Safety - /// `this` must point to a live `Self`. Takes `*mut Self` because - /// `terminate`/`flush_deferred_handshake_and_process` may free `this`. - unsafe fn append_deferred_handshake_body(this: *mut Self, data: &[u8]) -> bool { - // SAFETY: short-lived read; ends before any dispatch below. - let state = unsafe { (*this).deferred_handshake }; - match state { + /// Append a TCP read to the deferred non-101 body buffer. Returns `true` + /// when the read was consumed (caller should stop). Caller must hold a + /// `ref_guard` across this call. + fn append_deferred_handshake_body(this: ThisPtr, data: &[u8]) -> bool { + // SAFETY: short-lived `&mut` for buffer append; ends before any dispatch. + let me = unsafe { &mut *this.as_ptr() }; + match me.deferred_handshake { DeferredHandshake::None => false, - DeferredHandshake::WaitingForLength(target_len) => { - // `target_len` was bounded to `head_len + MAX_NON_101_BODY` - // by `process_websocket_upgrade_response`, so the buffer can - // never exceed that limit. - // - // If this read carries past `target_len`, take only enough - // bytes to fill the declared body; the rest belong to the - // next pipelined response or are trailing garbage — matching - // the single-chunk fast path which truncates to - // `full[..target_len]` before dispatching. - // SAFETY: short-lived `&mut`; ends before the dispatch below. - let me = unsafe { &mut *this }; - let available = target_len - me.body.len(); - let take = available.min(data.len()); + DeferredHandshake::WaitingForLength(target) => { + let take = (target - me.body.len()).min(data.len()); me.body.extend_from_slice(&data[..take]); - if me.body.len() >= target_len { - me.body.truncate(target_len); + if me.body.len() >= target { + me.body.truncate(target); me.deferred_handshake = DeferredHandshake::None; - let full: Vec = core::mem::take(&mut me.body); - // SAFETY: `me`'s last use is above; no `&mut Self` spans this call. - unsafe { Self::flush_deferred_handshake_and_process(this, &full) }; + let full = core::mem::take(&mut me.body); + Self::process_websocket_upgrade_response(this, full, true); } true } DeferredHandshake::WaitingForEof => { - // SAFETY: short-lived `&mut`; ends before any dispatch. - let me = unsafe { &mut *this }; if me.body.len().saturating_add(data.len()) > MAX_NON_101_BODY { me.deferred_handshake = DeferredHandshake::None; // SAFETY: `me`'s last use is above; no `&mut Self` spans this call. - unsafe { Self::terminate(this, ErrorCode::Expected101StatusCode) }; + unsafe { Self::terminate(this.as_ptr(), ErrorCode::Expected101StatusCode) }; return true; } me.body.extend_from_slice(data); @@ -1165,247 +1142,62 @@ impl HTTPClient { } } - /// Shared between the plain-TCP and proxy-tunnel paths. - /// - /// For non-101 responses whose body straddles multiple TCP reads, defer - /// the handshake dispatch until the full body is in hand so the - /// `unexpected-response` listener sees the complete payload instead of a - /// truncated prefix. - /// - /// `full` is the complete buffer contents (head + whatever body bytes are - /// on hand) — a copy of the buffer `response` was parsed from, so its - /// bytes match but `response`'s header pointers reference the original. - /// - /// # Safety - /// `this` must point to a live `Self`. Takes `*mut Self` because the - /// dispatch / `terminate` / `process_response` calls below may free - /// `this`. - unsafe fn process_websocket_upgrade_response( - this: *mut Self, - response: picohttp::Response, - full: &[u8], - ) { - let head_len = usize::try_from(response.bytes_read).expect("int cast"); - let status_code = u16::try_from(response.status_code).unwrap_or(0); - - // SAFETY: short-lived read; ends before any dispatch below. - let has_ws = unsafe { (*this).outgoing_websocket.is_some() }; - if !has_ws { - // SAFETY: forwards `this`; no `&mut Self` is live. - unsafe { Self::process_response(this, response, &full[head_len..]) }; - return; - } - - if status_code != 101 { - // RFC 7230 §3.3.3 rule #1 — 1xx / 204 / 304 responses have no - // message body regardless of the header fields, so reading until - // the peer closes (rule #7, the `None` arm below) would stall a - // keep-alive connection until the 120s socket timeout — and - // `terminate(Timeout)` doesn't flush a deferred handshake, so - // `unexpected-response` would never fire. Rule #3 - // (`Transfer-Encoding`) likewise preempts rule #7: we don't decode - // chunked on this fallback path. In both cases dispatch - // immediately with whatever bytes are on hand so the - // `unexpected-response` listener still gets the correct status / - // headers (matching the pre-existing non-101 behavior, which - // surfaced no body at all). - let is_bodiless = - status_code == 204 || status_code == 304 || (100..200).contains(&status_code); - if is_bodiless || Self::has_transfer_encoding(&response) { - // SAFETY: forwards `this`; no `&mut Self` is live. - unsafe { - Self::dispatch_handshake_and_process( - this, - response, - full, - head_len, - status_code, - ); - } - return; - } - // Defer the dispatch if the full body isn't present yet. - match Self::find_content_length(&response) { - Some(cl) => { - // Reject an absurd Content-Length up front so the - // `head_len + cl` below can't overflow `usize` (and so we - // never trap in an unbounded accumulate loop). `cl` is now - // bounded to 64 MB and `head_len` to the HTTP header limit. - if cl > MAX_NON_101_BODY { - // SAFETY: no `&mut Self` is live. - unsafe { Self::terminate(this, ErrorCode::Expected101StatusCode) }; - return; - } - let target_len = head_len + cl; - if full.len() < target_len { - // SAFETY: short-lived `&mut`; ends before return. Own - // the accumulated bytes so subsequent reads append. - // `full` is always a fresh `to_vec()` from the caller - // (borrowck forced the copy upstream), so it never - // aliases `me.body` — just replace. - let me = unsafe { &mut *this }; - me.body.clear(); - me.body.extend_from_slice(full); - me.deferred_handshake = DeferredHandshake::WaitingForLength(target_len); - return; - } - // Truncate at head_len + Content-Length — drop any bytes - // beyond the declared body length. - // SAFETY: forwards `this`; no `&mut Self` is live. - unsafe { - Self::flush_deferred_handshake_and_process(this, &full[..target_len]); - } - return; - } - None => { - // No Content-Length, and the bodiless / chunked cases were - // handled above — RFC 7230 §3.3.3 rule #7: read until the - // peer closes. Defer to handle_end / handle_close. - // SAFETY: short-lived `&mut`; ends before return. `full` - // is a fresh `to_vec()` (never aliases `me.body`). - let me = unsafe { &mut *this }; - me.body.clear(); - me.body.extend_from_slice(full); - me.deferred_handshake = DeferredHandshake::WaitingForEof; - return; - } - } - } - - // 101 fast path — post-header bytes are the first WebSocket frame, - // not HTTP body; `dispatch_handshake_and_process` drops them from the - // handshake event and `process_response` hands them to the connected - // client as buffered overflow. - // SAFETY: forwards `this`; no `&mut Self` is live. - unsafe { - Self::dispatch_handshake_and_process(this, response, full, head_len, status_code); - } - } - - /// Re-parse the accumulated (complete) buffer and dispatch. Called from - /// the deferred paths once `buffer` holds the full response. + /// Parse `full` as the handshake response, surface the `'handshake'` event + /// to the `ws` shim, then hand off to [`Self::process_response`]. /// - /// # Safety - /// `this` must point to a live `Self`; `terminate`/dispatch may free it. - unsafe fn flush_deferred_handshake_and_process(this: *mut Self, buffer: &[u8]) { - // PORT NOTE: re-parse into a local copy's headers_buf. Copy `buffer` - // so a re-parse against `self.headers_buf` doesn't alias `self.body`. - let owned: Vec = buffer.to_vec(); - // SAFETY: short-lived `&mut` for the parse scratch buffer. - let me = unsafe { &mut *this }; - let response = match picohttp::Response::parse(&owned, &mut me.headers_buf) { + /// Parses into a local scratch buffer so nothing borrows `self` across the + /// JS dispatch. The dispatch can re-enter (`ws.close()`/`terminate()` → + /// `cancel()`), so the caller must hold a `ref_guard`. `is_final` is set + /// on EOF/close flushes: no more bytes are coming, so `Defer` is treated as + /// `Ready` with whatever body arrived. + fn process_websocket_upgrade_response(this: ThisPtr, full: Vec, is_final: bool) { + let mut scratch = [picohttp::Header::ZERO; 128]; + let response = match picohttp::Response::parse(&full, &mut scratch) { Ok(r) => r, Err(_) => { - // SAFETY: `me`'s last use is above; no `&mut Self` spans this call. - unsafe { Self::terminate(this, ErrorCode::InvalidResponse) }; - return; + // SAFETY: no `&mut Self` is live across this call. + return unsafe { Self::terminate(this.as_ptr(), ErrorCode::InvalidResponse) }; } }; let head_len = usize::try_from(response.bytes_read).expect("int cast"); - let status_code = u16::try_from(response.status_code).unwrap_or(0); - // SAFETY: short-lived read. - let has_ws = unsafe { (*this).outgoing_websocket.is_some() }; - if !has_ws { - // SAFETY: forwards `this`; no `&mut Self` is live. - unsafe { Self::process_response(this, response, &owned[head_len..]) }; - return; - } - // SAFETY: forwards `this`; no `&mut Self` is live. - unsafe { - Self::dispatch_handshake_and_process(this, response, &owned, head_len, status_code); - } - } - /// Dispatch the `'handshake'` event into JS (synchronous), then run - /// `process_response`. - /// - /// # Safety - /// `this` must point to a live `Self`. JS in the handshake listener can - /// call `ws.close()`/`ws.terminate()` which re-enters and may free - /// `this`; the `ref_guard` below keeps it alive across the dispatch. - unsafe fn dispatch_handshake_and_process( - this: *mut Self, - response: picohttp::Response, - full: &[u8], - head_len: usize, - status_code: u16, - ) { - // SAFETY: short-lived read of the handle; copied out before dispatch. - let Some(ws) = (unsafe { (*this).outgoing_websocket }) else { - // SAFETY: forwards `this`; no `&mut Self` is live. - unsafe { Self::process_response(this, response, &full[head_len..]) }; - return; + let Some(ws) = this.outgoing_websocket else { + // SAFETY: no `&mut Self` is live across this call. + return unsafe { Self::process_response(this.as_ptr(), response, &full[head_len..]) }; }; - // Keep `this` alive across the synchronous JS dispatch: the listener - // may `ws.terminate()` → didAbruptClose → free us mid-function. - // handle_data refs around its whole body, but handle_end / handle_close - // flush through here directly, so guard unconditionally. - // SAFETY: `this` carries root provenance; balanced on drop. - let _guard = unsafe { ThisPtr::new(this) }.ref_guard(); - - // On 101, nest the `did_receive_handshake_response` ('handshake'/ - // 'upgrade') and `did_connect` ('open') dispatches below under one - // event-loop scope. Each of those calls its own enter()/exit(); exit() - // drains microtasks when the count drops 1→0. Without this outer scope - // the count would hit 0 between the two events, so a microtask queued - // in an 'upgrade' handler would run before 'open' and observe - // readyState CONNECTING. Holding the count ≥1 across both makes them - // fire back-to-back like npm `ws`, draining microtasks once after - // 'open'. Scope it to 101 only: on a non-101 response `process_response` - // below calls `terminate` instead of `did_connect`, and the - // 'unexpected-response' body stream relies on the microtask checkpoint - // at `did_receive_handshake_response`'s exit() running *before* that - // teardown — swallowing it hangs the stream. - let _loop_scope = (status_code == 101) - .then(|| bun_jsc::virtual_machine::VirtualMachine::get().enter_event_loop_scope()); - - // On 101, the bytes after the header block are the first WebSocket - // frame — not HTTP body. Surface an empty body to the handshake - // event; `process_response` still hands `full[head_len..]` to the - // connected client as overflow. - let handshake_body: &[u8] = if status_code == 101 { - &[] - } else { - &full[head_len..] + let route = match Self::route_handshake_body(&response, head_len, full.len()) { + HandshakeBody::Defer(_) if is_final => HandshakeBody::Ready { end: full.len() }, + r => r, }; - - // Build the raw-header array the C++ side copies into `rawHeaders`. - // SAFETY: the header name/value slices (and `response.status`) point - // into the buffer `response` was parsed from — `full` on the - // flush-deferred path, or the caller's `data`/`self.body` on the - // direct-dispatch paths (101 / bodiless / Transfer-Encoding), where - // `full` is a separate copy. Either buffer outlives this synchronous - // call: `data` is the uSockets read buffer live for the callback - // frame, `self.body` is owned by `*this` (kept alive by `_guard` - // above), and C++ copies every slice into a JS string before - // dispatchEvent runs any user JS. - let mut raw_headers: Vec = - Vec::with_capacity(response.headers.list.len()); - for h in response.headers.list { - let name = h.name(); - let value = h.value(); - raw_headers.push(super::cpp_websocket::RawHeader { - name_ptr: name.as_ptr(), - name_len: name.len(), - value_ptr: value.as_ptr(), - value_len: value.len(), - }); - } - - CppWebSocket::opaque_ref(ws).did_receive_handshake_response( - status_code, - response.status, - &raw_headers, - handshake_body, - ); - - // SAFETY: short-lived read; the JS listener may have cleared it. - if unsafe { (*this).outgoing_websocket.is_none() } { - return; + match route { + HandshakeBody::Defer(state) => { + // SAFETY: short-lived `&mut` for two field writes; no reentrant call. + let me = unsafe { &mut *this.as_ptr() }; + me.body = full; + me.deferred_handshake = state; + } + HandshakeBody::TooLarge => { + // SAFETY: no `&mut Self` is live across this call. + unsafe { Self::terminate(this.as_ptr(), ErrorCode::Expected101StatusCode) }; + } + HandshakeBody::Ready { end } => { + // On 101, hold one event-loop scope across `'upgrade'` and + // `'open'` so microtasks drain after `open` (matches npm `ws`). + // On non-101, the `'unexpected-response'` body stream needs the + // microtask checkpoint between dispatch and teardown, so skip. + let _loop_scope = (response.status_code == 101).then(|| { + bun_jsc::virtual_machine::VirtualMachine::get().enter_event_loop_scope() + }); + Self::dispatch_handshake(ws, &response, &full[head_len..end]); + if this.outgoing_websocket.is_some() { + // SAFETY: no `&mut Self` is live across this call. + unsafe { + Self::process_response(this.as_ptr(), response, &full[head_len..]); + } + } + } } - // SAFETY: forwards `this`; no `&mut Self` is live. - unsafe { Self::process_response(this, response, &full[head_len..]) }; } /// Takes `ThisPtr` because `terminate`/`handle_data` may free `this`. @@ -1653,18 +1445,16 @@ impl HTTPClient { /// `terminate`/`process_response` may free `this`; see `fail`. pub unsafe fn handle_decrypted_data(this: *mut Self, data: &[u8]) { log!("handleDecryptedData: {} bytes", data.len()); + // SAFETY: caller (proxy tunnel) holds a live ref on `this`. + let this = unsafe { ThisPtr::new(this) }; + let _guard = this.ref_guard(); - // Same deferred-body flushing as the plain-TCP path. - // SAFETY: forwards `this`; no `&mut Self` is live. - if unsafe { Self::append_deferred_handshake_body(this, data) } { + if Self::append_deferred_handshake_body(this, data) { return; } - // SAFETY: short-lived `&mut` for body buffering; no reentrant calls in - // this region until `terminate`/`process_websocket_upgrade_response` below. - let me = unsafe { &mut *this }; - - // Process as if it came directly from the socket + // SAFETY: short-lived `&mut` for body buffering; ends before dispatch below. + let me = unsafe { &mut *this.as_ptr() }; let mut body = data; if !me.body.is_empty() { me.body.extend_from_slice(data); @@ -1675,74 +1465,37 @@ impl HTTPClient { Ok(r) => r, Err(picohttp::ParseResponseError::MalformedHttpResponse) => { // SAFETY: `me`'s last use is above; no `&mut Self` spans this call. - unsafe { Self::terminate(this, ErrorCode::InvalidResponse) }; + unsafe { Self::terminate(this.as_ptr(), ErrorCode::InvalidResponse) }; return; } Err(picohttp::ParseResponseError::ShortRead) => { if me.body.is_empty() { me.body.extend_from_slice(data); } - // ShortRead means no \r\n\r\n was found, so every byte in - // `body` is part of an incomplete header — cap that, not - // total bytes received (which may include pipelined - // WebSocket frames once the header does complete). if me.body.len() > bun_http::max_http_header_size() { // SAFETY: `me`'s last use is above; no `&mut Self` spans this call. - unsafe { Self::terminate(this, ErrorCode::InvalidResponse) }; + unsafe { Self::terminate(this.as_ptr(), ErrorCode::InvalidResponse) }; } return; } }; - // Reshaped for borrowck — copy the full parsed buffer out before - // mutating self, since `process_websocket_upgrade_response` re-parses - // it and may mutate `self.body`/`headers_buf`. - let full: Vec = body.to_vec(); - // SAFETY: `me`'s last use is the `body` slice above (now copied out); - // no `&mut Self` spans this call. - unsafe { Self::process_websocket_upgrade_response(this, response, &full) }; + let _ = response; + Self::process_websocket_upgrade_response(this, body.to_vec(), false); } /// Takes `ThisPtr` because `terminate` may free `this`; see `fail`. pub fn handle_end(this: ThisPtr, _: Socket) { log!("onEnd"); - // If we were waiting for the peer to close before dispatching a - // non-101 response body (Content-Length absent, or a short - // Content-Length that never completed), flush now with whatever - // arrived so the `unexpected-response` consumer sees the partial - // body rather than nothing. - // SAFETY: forwards `this` with root provenance; no `&mut Self` is live. - if unsafe { Self::flush_deferred_on_close(this.as_ptr()) } { + if let Some(full) = Self::take_deferred_body(this) { + let _guard = this.ref_guard(); + Self::process_websocket_upgrade_response(this, full, true); return; } // SAFETY: forwards `this` with root provenance; no `&mut Self` is live. unsafe { Self::terminate(this.as_ptr(), ErrorCode::Ended) }; } - /// Flush a pending deferred-handshake body on clean/abrupt connection - /// end. Returns `true` when it dispatched (and thus consumed the - /// teardown — the caller should not also `terminate`). - /// - /// # Safety - /// `this` must point to a live `Self`; the dispatch may free `this`. - unsafe fn flush_deferred_on_close(this: *mut Self) -> bool { - // SAFETY: short-lived read/reset; ends before the dispatch. - let me = unsafe { &mut *this }; - match me.deferred_handshake { - DeferredHandshake::None => false, - DeferredHandshake::WaitingForLength(_) | DeferredHandshake::WaitingForEof => { - me.deferred_handshake = DeferredHandshake::None; - if me.body.is_empty() { - return false; - } - let full: Vec = core::mem::take(&mut me.body); - // SAFETY: `me`'s last use is above; no `&mut Self` spans this call. - unsafe { Self::flush_deferred_handshake_and_process(this, &full) }; - true - } - } - } - /// # Safety /// `this` must point to a live `Self`. Takes `*mut Self` because /// `terminate`/`tcp.close()` may synchronously dispatch `handle_close` From 4d4ab33808f6563a04fa16006cbda31facdf4883 Mon Sep 17 00:00:00 2001 From: robobun <117481402+robobun@users.noreply.github.com> Date: Wed, 29 Jul 2026 00:52:46 +0000 Subject: [PATCH 3/9] ws: drop deferred-body buffering; minimal stateless handshake forward The handshake forward is now two functions: a stateless dispatch_handshake that builds the raw-header array and calls C++, and process_websocket_upgrade_response which re-parses the owned response buffer into local scratch (so nothing borrows self across the JS dispatch), surfaces the handshake, and hands off to the existing process_response. No new state on HTTPClient; handle_close / handle_end / terminate are untouched. The non-101 body is whatever arrived in the first read with the headers, which covers the real-world error-page case; the earlier Content-Length / read-until-EOF accumulation (and its DeferredHandshake state machine, 64 MB cap, flush-on-RST reentrancy guard, and 12 unsafe blocks) is gone. Net unsafe in WebSocketUpgradeClient.rs vs main: -1 (two early-101-fail terminates removed; two calls to the existing unsafe terminate / process_response added from the orchestrator; one ThisPtr::new wrap in handle_decrypted_data matching the file's existing idiom). Also: trimmed comments across CppWebSocket.rs and ws.js, dropped the dead eventIds entries, and moved tests to first_party/ws and web/websocket per the file-placement convention. --- src/http_jsc/websocket_client/CppWebSocket.rs | 12 +- .../WebSocketUpgradeClient.rs | 273 +++--------------- src/js/thirdparty/ws.js | 135 +-------- .../first_party/ws/ws-upgrade-events.test.ts} | 163 +---------- .../websocket-handshake-event.test.ts} | 0 5 files changed, 50 insertions(+), 533 deletions(-) rename test/{regression/issue/05951.test.ts => js/first_party/ws/ws-upgrade-events.test.ts} (75%) rename test/{regression/issue/24229.test.ts => js/web/websocket/websocket-handshake-event.test.ts} (100%) diff --git a/src/http_jsc/websocket_client/CppWebSocket.rs b/src/http_jsc/websocket_client/CppWebSocket.rs index 3b2d9e07da3d..c0b09c08517f 100644 --- a/src/http_jsc/websocket_client/CppWebSocket.rs +++ b/src/http_jsc/websocket_client/CppWebSocket.rs @@ -22,11 +22,7 @@ bun_opaque::opaque_ffi! { pub struct CppWebSocket; } -/// A single HTTP response header passed across the FFI to -/// `WebSocket__didReceiveHandshakeResponse`. Name/value point into the -/// PicoHTTP-parsed response head, which the caller keeps alive for the -/// duration of the synchronous dispatch. Matches `WebCore::WebSocket:: -/// HandshakeRawHeader` (src/jsc/bindings/webcore/WebSocket.h). +/// Matches `WebCore::WebSocket::HandshakeRawHeader` (WebSocket.h). #[repr(C)] pub struct RawHeader { pub name_ptr: *const u8, @@ -101,11 +97,7 @@ impl CppWebSocket { event_loop.exit(); } - /// Dispatch the native `'handshake'` event to the `ws` shim. - /// - /// `status_message`, `headers`, and `body` are borrowed for the call only - /// — the C++ side copies whatever it needs into JS values synchronously. - // Forwards raw pointers to C++ without dereferencing on the Rust side. + /// Dispatch the native `'handshake'` event; C++ copies all slices synchronously. #[allow(clippy::not_unsafe_ptr_arg_deref)] pub(crate) fn did_receive_handshake_response( &self, diff --git a/src/http_jsc/websocket_client/WebSocketUpgradeClient.rs b/src/http_jsc/websocket_client/WebSocketUpgradeClient.rs index 09c05ff275d8..b3f3789c3b80 100644 --- a/src/http_jsc/websocket_client/WebSocketUpgradeClient.rs +++ b/src/http_jsc/websocket_client/WebSocketUpgradeClient.rs @@ -120,33 +120,6 @@ impl Drop for SslCtxOwned { } } -/// Non-`None` while buffering the body of a non-101 response that spans -/// multiple TCP reads, so the `'unexpected-response'` listener sees the -/// complete payload rather than a truncated prefix. -#[derive(Clone, Copy, PartialEq, Eq)] -enum DeferredHandshake { - None, - /// Total expected buffer length (`head_len + Content-Length`). - WaitingForLength(usize), - /// No `Content-Length`; accumulate until the peer closes the connection. - WaitingForEof, -} - -/// Routing decision for a parsed handshake response body. -enum HandshakeBody { - /// Dispatch now; `end` is the exclusive upper bound of the body in `full`. - Ready { end: usize }, - /// Buffer `full` and wait for more data before dispatching. - Defer(DeferredHandshake), - /// Declared body exceeds [`MAX_NON_101_BODY`]; fail without buffering. - TooLarge, -} - -/// Cap on bytes buffered for a non-101 response body. Real error pages fit -/// well under this; the cap stops a misbehaving server from growing `self.body` -/// without bound. -const MAX_NON_101_BODY: usize = 64 * 1024 * 1024; - /// WebSocket HTTP upgrade client, generic over `SSL`. /// /// Intrusive single-thread @@ -192,11 +165,6 @@ pub struct HTTPClient { /// with a `Sec-WebSocket-Extensions` header anyway, `processResponse` /// fails the handshake per RFC 6455 §9.1 — matching upstream `ws`. offered_permessage_deflate: bool, - - /// Tracks deferred dispatch of the `'handshake'` event for non-101 - /// responses whose body straddles multiple TCP reads. See - /// [`DeferredHandshake`]. - deferred_handshake: DeferredHandshake, } // Handler set referenced by the dispatch table (kind = `.ws_client_upgrade[_tls]`). @@ -398,7 +366,6 @@ impl HTTPClient { expected_accept: request_result.expected_accept, offered_permessage_deflate: offer_permessage_deflate, subprotocols, - deferred_handshake: DeferredHandshake::None, })); bun_core::scoped_log!(alloc, "new({}) = {:p}", Self::TYPE_NAME, client); // SAFETY: just allocated above; we hold the only ref. This `&mut` is @@ -742,47 +709,20 @@ impl HTTPClient { pub fn handle_close(this: ThisPtr, _: Socket, _: c_int, _: *mut c_void) { log!("onClose"); bun_jsc::mark_binding!(); - let _guard = this.ref_guard(); - - // Detach the socket and clear its ext slot before any JS dispatch so a - // reentrant `cancel()` from a listener finds nothing to release. - if let Some(ext) = this.tcp.ext::>>() { - // SAFETY: ext slot is the `Option>` set in `connect_group`. - unsafe { (*ext).take() }; - } - // SAFETY: short-lived `&mut` for the field detach. - unsafe { (*this.as_ptr()).tcp.detach() }; - - // Flush any buffered non-101 body as `'unexpected-response'`; on the - // normal path this is a no-op. `process_response` → `terminate` - // consumes `outgoing_websocket`, so `dispatch_abrupt_close` below then - // no-ops. - if let Some(full) = Self::take_deferred_body(this) { - Self::process_websocket_upgrade_response(this, full, true); - } - - // SAFETY: short-lived `&mut` for clear_data; no reentrant call. + // SAFETY: short-lived `&mut` borrows; each ends before the next call. unsafe { (*this.as_ptr()).clear_data() }; + // SAFETY: short-lived `&mut` for the field detach; `this` is live. + unsafe { (*this.as_ptr()).tcp.detach() }; // SAFETY: forwards `this` with root provenance; no `&mut Self` is live. unsafe { Self::dispatch_abrupt_close(this.as_ptr(), ErrorCode::Ended) }; - // SAFETY: balances the socket-userdata ref; `_guard` still holds one. + + // SAFETY: may free `this`; no `&mut Self` is live. unsafe { Self::deref(this.as_ptr()) }; } /// # Safety /// `this` must point to a live `Self`. See `fail`. pub unsafe fn terminate(this: *mut Self, code: ErrorCode) { - // The proxy-tunnel path reaches `terminate(Ended)` without going - // through `handle_end`/`handle_close`; flush any deferred body here too. - if code == ErrorCode::Ended { - // SAFETY: caller contract — `this` is a live `heap::alloc` pointer. - let this = unsafe { ThisPtr::new(this) }; - if let Some(full) = Self::take_deferred_body(this) { - let _guard = this.ref_guard(); - Self::process_websocket_upgrade_response(this, full, true); - return; - } - } // SAFETY: forwards `this` with root provenance. unsafe { Self::fail(this, code) }; // We cannot access the pointer after fail is called. @@ -980,12 +920,8 @@ impl HTTPClient { } } - if Self::append_deferred_handshake_body(this, data) { - return; - } - // SAFETY: short-lived `&mut` for body buffering; no reentrant calls in - // this region until `terminate`/`process_websocket_upgrade_response` below. + // this region until `terminate`/`process_response` below. let me = unsafe { &mut *this.as_ptr() }; let mut body = data; if !me.body.is_empty() { @@ -993,8 +929,8 @@ impl HTTPClient { body = &me.body; } - let response = match picohttp::Response::parse(body, &mut me.headers_buf) { - Ok(r) => r, + match picohttp::Response::parse(body, &mut me.headers_buf) { + Ok(_) => {} Err(picohttp::ParseResponseError::MalformedHttpResponse) => { // SAFETY: `me`'s last use is above; no `&mut Self` spans this call. unsafe { Self::terminate(this.as_ptr(), ErrorCode::InvalidResponse) }; @@ -1016,67 +952,12 @@ impl HTTPClient { } }; - let _ = response; - Self::process_websocket_upgrade_response(this, body.to_vec(), false); + let full = body.to_vec(); + Self::process_websocket_upgrade_response(this, &full); // `_guard` drops here, balancing the ref above. May free `this`. } - fn find_header<'a>(response: &picohttp::Response<'a>, name: &[u8]) -> Option<&'a [u8]> { - response - .headers - .list - .iter() - .find(|h| { - h.name().len() == name.len() - && strings::eql_case_insensitive_ascii_ignore_length(h.name(), name) - }) - .map(|h| h.value()) - } - - /// Decide whether a handshake response's body is ready to surface to JS - /// (and how much of `full` it spans), or whether more bytes are needed. - /// Pure: encodes RFC 7230 §3.3.3 body-length rules for the response side. - fn route_handshake_body( - response: &picohttp::Response, - head_len: usize, - available: usize, - ) -> HandshakeBody { - let status = response.status_code; - // 101: post-header bytes are the first WebSocket frame, not HTTP body. - if status == 101 { - return HandshakeBody::Ready { end: head_len }; - } - // Bodiless statuses (rule 1) and Transfer-Encoding (rule 3; we don't - // decode chunked here) dispatch immediately with whatever is on hand. - let bodiless = status == 204 || status == 304 || (100..200).contains(&status); - if bodiless || Self::find_header(response, b"Transfer-Encoding").is_some() { - return HandshakeBody::Ready { end: available }; - } - match Self::find_header(response, b"Content-Length").and_then(|v| { - core::str::from_utf8(v) - .ok()? - .trim_matches(|c: char| c == ' ' || c == '\t') - .parse::() - .ok() - }) { - Some(cl) if cl > MAX_NON_101_BODY => HandshakeBody::TooLarge, - Some(cl) => { - let target = head_len + cl; - if available >= target { - HandshakeBody::Ready { end: target } - } else { - HandshakeBody::Defer(DeferredHandshake::WaitingForLength(target)) - } - } - // Rule 7: read until the peer closes. - None => HandshakeBody::Defer(DeferredHandshake::WaitingForEof), - } - } - - /// Forward the parsed handshake response to the C++ `WebSocket` as a - /// `'handshake'` event. Everything borrows `response`'s parse buffer, which - /// the caller keeps alive for the call; C++ copies into JS strings before - /// any user JS runs. + /// Forward the handshake response to C++ as a `'handshake'` event. fn dispatch_handshake(ws: *mut CppWebSocket, response: &picohttp::Response, body: &[u8]) { let raw_headers: Vec = response .headers @@ -1097,107 +978,29 @@ impl HTTPClient { ); } - /// Take the buffered deferred-handshake body out of `self`, clearing the - /// deferred state. `None` when nothing was deferred. - fn take_deferred_body(this: ThisPtr) -> Option> { - // SAFETY: short-lived `&mut` for field reads/writes; no reentrant call. - let me = unsafe { &mut *this.as_ptr() }; - if matches!(me.deferred_handshake, DeferredHandshake::None) { - return None; - } - me.deferred_handshake = DeferredHandshake::None; - let full = core::mem::take(&mut me.body); - (!full.is_empty()).then_some(full) - } - - /// Append a TCP read to the deferred non-101 body buffer. Returns `true` - /// when the read was consumed (caller should stop). Caller must hold a - /// `ref_guard` across this call. - fn append_deferred_handshake_body(this: ThisPtr, data: &[u8]) -> bool { - // SAFETY: short-lived `&mut` for buffer append; ends before any dispatch. - let me = unsafe { &mut *this.as_ptr() }; - match me.deferred_handshake { - DeferredHandshake::None => false, - DeferredHandshake::WaitingForLength(target) => { - let take = (target - me.body.len()).min(data.len()); - me.body.extend_from_slice(&data[..take]); - if me.body.len() >= target { - me.body.truncate(target); - me.deferred_handshake = DeferredHandshake::None; - let full = core::mem::take(&mut me.body); - Self::process_websocket_upgrade_response(this, full, true); - } - true - } - DeferredHandshake::WaitingForEof => { - if me.body.len().saturating_add(data.len()) > MAX_NON_101_BODY { - me.deferred_handshake = DeferredHandshake::None; - // SAFETY: `me`'s last use is above; no `&mut Self` spans this call. - unsafe { Self::terminate(this.as_ptr(), ErrorCode::Expected101StatusCode) }; - return true; - } - me.body.extend_from_slice(data); - true - } - } - } - - /// Parse `full` as the handshake response, surface the `'handshake'` event - /// to the `ws` shim, then hand off to [`Self::process_response`]. - /// - /// Parses into a local scratch buffer so nothing borrows `self` across the - /// JS dispatch. The dispatch can re-enter (`ws.close()`/`terminate()` → - /// `cancel()`), so the caller must hold a `ref_guard`. `is_final` is set - /// on EOF/close flushes: no more bytes are coming, so `Defer` is treated as - /// `Ready` with whatever body arrived. - fn process_websocket_upgrade_response(this: ThisPtr, full: Vec, is_final: bool) { + /// Surface `'handshake'` to the `ws` shim, then [`Self::process_response`]. + /// Caller holds a `ref_guard` and owns `full` (it must not borrow `self`). + fn process_websocket_upgrade_response(this: ThisPtr, full: &[u8]) { let mut scratch = [picohttp::Header::ZERO; 128]; - let response = match picohttp::Response::parse(&full, &mut scratch) { - Ok(r) => r, - Err(_) => { - // SAFETY: no `&mut Self` is live across this call. - return unsafe { Self::terminate(this.as_ptr(), ErrorCode::InvalidResponse) }; - } + let Ok(response) = picohttp::Response::parse(full, &mut scratch) else { + // SAFETY: forwards to the existing teardown path. + return unsafe { Self::terminate(this.as_ptr(), ErrorCode::InvalidResponse) }; }; let head_len = usize::try_from(response.bytes_read).expect("int cast"); + let is_101 = response.status_code == 101; - let Some(ws) = this.outgoing_websocket else { - // SAFETY: no `&mut Self` is live across this call. - return unsafe { Self::process_response(this.as_ptr(), response, &full[head_len..]) }; - }; + // 101: one scope across 'upgrade'+'open' so microtasks drain after open. + let _scope = is_101 + .then(|| bun_jsc::virtual_machine::VirtualMachine::get().enter_event_loop_scope()); - let route = match Self::route_handshake_body(&response, head_len, full.len()) { - HandshakeBody::Defer(_) if is_final => HandshakeBody::Ready { end: full.len() }, - r => r, - }; - match route { - HandshakeBody::Defer(state) => { - // SAFETY: short-lived `&mut` for two field writes; no reentrant call. - let me = unsafe { &mut *this.as_ptr() }; - me.body = full; - me.deferred_handshake = state; - } - HandshakeBody::TooLarge => { - // SAFETY: no `&mut Self` is live across this call. - unsafe { Self::terminate(this.as_ptr(), ErrorCode::Expected101StatusCode) }; - } - HandshakeBody::Ready { end } => { - // On 101, hold one event-loop scope across `'upgrade'` and - // `'open'` so microtasks drain after `open` (matches npm `ws`). - // On non-101, the `'unexpected-response'` body stream needs the - // microtask checkpoint between dispatch and teardown, so skip. - let _loop_scope = (response.status_code == 101).then(|| { - bun_jsc::virtual_machine::VirtualMachine::get().enter_event_loop_scope() - }); - Self::dispatch_handshake(ws, &response, &full[head_len..end]); - if this.outgoing_websocket.is_some() { - // SAFETY: no `&mut Self` is live across this call. - unsafe { - Self::process_response(this.as_ptr(), response, &full[head_len..]); - } - } + if let Some(ws) = this.outgoing_websocket { + Self::dispatch_handshake(ws, &response, if is_101 { &[] } else { &full[head_len..] }); + if this.outgoing_websocket.is_none() { + return; } } + // SAFETY: forwards to the existing handoff path. + unsafe { Self::process_response(this.as_ptr(), response, &full[head_len..]) }; } /// Takes `ThisPtr` because `terminate`/`handle_data` may free `this`. @@ -1449,20 +1252,19 @@ impl HTTPClient { let this = unsafe { ThisPtr::new(this) }; let _guard = this.ref_guard(); - if Self::append_deferred_handshake_body(this, data) { - return; - } - - // SAFETY: short-lived `&mut` for body buffering; ends before dispatch below. + // SAFETY: short-lived `&mut` for body buffering; no reentrant calls in + // this region until `terminate`/`process_response` below. let me = unsafe { &mut *this.as_ptr() }; + + // Process as if it came directly from the socket let mut body = data; if !me.body.is_empty() { me.body.extend_from_slice(data); body = &me.body; } - let response = match picohttp::Response::parse(body, &mut me.headers_buf) { - Ok(r) => r, + match picohttp::Response::parse(body, &mut me.headers_buf) { + Ok(_) => {} Err(picohttp::ParseResponseError::MalformedHttpResponse) => { // SAFETY: `me`'s last use is above; no `&mut Self` spans this call. unsafe { Self::terminate(this.as_ptr(), ErrorCode::InvalidResponse) }; @@ -1480,18 +1282,13 @@ impl HTTPClient { } }; - let _ = response; - Self::process_websocket_upgrade_response(this, body.to_vec(), false); + let full = body.to_vec(); + Self::process_websocket_upgrade_response(this, &full); } /// Takes `ThisPtr` because `terminate` may free `this`; see `fail`. pub fn handle_end(this: ThisPtr, _: Socket) { log!("onEnd"); - if let Some(full) = Self::take_deferred_body(this) { - let _guard = this.ref_guard(); - Self::process_websocket_upgrade_response(this, full, true); - return; - } // SAFETY: forwards `this` with root provenance; no `&mut Self` is live. unsafe { Self::terminate(this.as_ptr(), ErrorCode::Ended) }; } diff --git a/src/js/thirdparty/ws.js b/src/js/thirdparty/ws.js index f1139c341d42..85a693f311ca 100644 --- a/src/js/thirdparty/ws.js +++ b/src/js/thirdparty/ws.js @@ -90,19 +90,12 @@ const eventIds = { error: 4, ping: 5, pong: 6, - upgrade: 7, - "unexpected-response": 8, }; -// Stable singleton used by `#armNativeBridge` to install the native-side -// forwarder through `#onOrOnce` without pushing a user-visible listener. It -// must be identity-stable so `super.off` can remove it later if needed. +// Identity-stable placeholder for `#armNativeBridge`. function noopBridgeListener() {} -// Headers for which Node's http.IncomingMessage keeps only the first value and -// discards later duplicates, matching lib/_http_incoming.js matchKnownFields. -// Real `ws` hands consumers that Node object, so the synthetic IncomingMessage -// passed to 'unexpected-response' must coalesce the same way. +// Headers Node's http.IncomingMessage keeps first-value-only (lib/_http_incoming.js). const kSingletonHeaders = new Set([ "age", "authorization", @@ -200,24 +193,14 @@ class BunWebSocket extends EventEmitter { #paused = false; #fragments = false; #binaryType = "nodebuffer"; - // True once an 'error' has already been surfaced to EventEmitter listeners - // (either a synthetic non-101 error or because 'unexpected-response' fired). - // Gates the bridge closure so the native 'Expected 101' error isn't - // re-emitted onto the EventEmitter a second time. + // Gates the EventEmitter bridge so the native non-101 error isn't re-emitted. #unexpectedResponseEmitted = false; - // True only when 'unexpected-response' actually fired — i.e. the consumer - // handled the non-101 response, so real ws emits no 'error' at all. Gates - // the `addEventListener('error')` / `onerror` wrappers (which live on - // `this.#ws`, not the EventEmitter). Kept separate from - // `#unexpectedResponseEmitted` so a synthetic `emit('error')` to an - // `on('error')` listener doesn't also swallow a DOM-style handler's error. + // Gates addEventListener('error')/onerror wrappers; set only when + // 'unexpected-response' actually fired (real ws emits no error then). #unexpectedResponseHandled = false; - // Wrappers for `addEventListener('error', h)` so the native 'Expected 101' - // error is suppressed after 'unexpected-response' (matching `on('error')` - // and real npm `ws`). Keyed by the user's listener so `removeEventListener` - // can still find and detach the wrapper. + // listener -> suppression wrapper, for removeEventListener('error', ...). #errorListenerWrappers; - // The user's `onerror` function (the native slot holds a suppression wrapper). + // User's onerror; the native slot holds a suppression wrapper. #onerror; // Bitset to track whether event handlers are set. #eventId = 0; @@ -362,12 +345,6 @@ class BunWebSocket extends EventEmitter { } let ws = (this.#ws = new WebSocket(url, wsOptions)); ws.binaryType = "nodebuffer"; - // NOTE: the native 'handshake' listener is registered lazily from - // #ensureHandshakeListener() when the user subscribes to 'upgrade' or - // 'unexpected-response'. Keeping it off by default means callers that - // only listen to 'open'/'message'/'close' never exercise the Zig - // handshake-dispatch path (which has historically been fragile under - // ASAN, e.g. ws-proxy.test.ts). return ws; } @@ -379,13 +356,8 @@ class BunWebSocket extends EventEmitter { this.#ws.addEventListener("handshake", event => this.#onHandshake(event.data), onceObject); } - // ws emits `'upgrade'` / `'unexpected-response'` with an `http.ClientRequest` - // as the first argument. We bypass node:http and talk to the native - // WebSocket directly, so there is no real ClientRequest to expose. Pass a - // minimal stub — `method`, `path`, and the no-op header helpers — so user - // code that inspects the request object (e.g. `req.getHeader(...)`) does - // not crash. Build it lazily on first emission to keep the common open/ - // close path zero-cost. + // Minimal ClientRequest stub for the first 'unexpected-response' argument + // (we bypass node:http, so there is no real one to expose). #syntheticRequest; #getSyntheticRequest() { let req = this.#syntheticRequest; @@ -395,9 +367,6 @@ class BunWebSocket extends EventEmitter { try { if (url) { const parsed = new URL(url); - // Node's http.ClientRequest.path is pathname + search (no fragment) - // per RFC 7230 §5.3. Preserve the query string so handlers that log - // or reconstruct the failing URL see the full request target. path = (parsed.pathname || "/") + (parsed.search || ""); } } catch {} @@ -431,33 +400,16 @@ class BunWebSocket extends EventEmitter { #onHandshake(data) { const { statusCode, statusMessage, rawHeaders, body } = data; - // On 101, any bytes arriving after the header block are the first - // WebSocket frame, not HTTP response body — node's http layer delivers - // them as the `head` buffer on the 'upgrade' event and the native - // WebSocket client forwards them to the protocol reader on didConnect. - // Don't leak them into the `upgrade` event's IncomingMessage stream. const res = makeHandshakeResponse(statusCode, statusMessage, rawHeaders, statusCode === 101 ? null : body); if (statusCode === 101) { - // `upgrade` emits `(response)` per ws docs. this.emit("upgrade", res); return; } if (this.listenerCount("unexpected-response") > 0) { - // The consumer handled the response via 'unexpected-response'. Real ws - // emits no 'error' at all in this case, so suppress the native follow-up - // for every registration style (EventEmitter bridge AND the DOM-style - // wrappers). this.#unexpectedResponseEmitted = true; this.#unexpectedResponseHandled = true; - // `unexpected-response` emits `(request, response)` per ws docs. this.emit("unexpected-response", this.#getSyntheticRequest(), res); } else if (this.listenerCount("error") > 0) { - // An EventEmitter 'error' listener (on/once/addListener/...) gets a - // synthetic error here; mark it emitted so the bridge closure doesn't - // deliver the native follow-up to the EventEmitter a second time. We do - // NOT set #unexpectedResponseHandled — a DOM-style handler - // (addEventListener('error')/onerror) registered alongside still gets the - // native error exactly once, since its wrapper gates on that flag. this.#unexpectedResponseEmitted = true; this.emit("error", new Error("Unexpected server response: " + statusCode)); } @@ -468,8 +420,6 @@ class BunWebSocket extends EventEmitter { emitWarning(event, "ws.WebSocket '" + event + "' event is not implemented in bun"); } if (event === "upgrade" || event === "unexpected-response") { - // Lazy-register the native handshake listener so callers that never - // subscribe to these events don't exercise the Zig handshake dispatch. this.#ensureHandshakeListener(); return once ? super.once(event, listener) : super.on(event, listener); } @@ -555,13 +505,6 @@ class BunWebSocket extends EventEmitter { return this.#onOrOnce(event, listener, onceObject); } - // `on` is the conventional spelling, but ws / EventEmitter consumers also - // reach for `addListener` / `prependListener` / `prependOnceListener`. Each - // needs to arm the native bridge (the `#onOrOnce` path for standard events - // like 'open' / 'message', or `#ensureHandshakeListener()` for 'upgrade' / - // 'unexpected-response') — otherwise the handler sits on the EventEmitter - // list but the native event that would trigger `this.emit(...)` is never - // wired up, and the callback silently never fires. addListener(event, listener) { return this.#onOrOnce(event, listener, undefined); } @@ -576,32 +519,15 @@ class BunWebSocket extends EventEmitter { return super.prependOnceListener(event, listener); } - // Install the native-side listener that eventually calls `this.emit(event, - // …)`, without pushing a new EventEmitter listener onto the list — that - // part is the caller's job (e.g. `super.prependListener`). Mirrors the - // bridge-installation branch of `#onOrOnce` for the cases where we need - // the side effect but not the `super.on`/`super.once` call. + // Install the native forwarder for `event` without adding a listener. #armNativeBridge(event) { if (event === "upgrade" || event === "unexpected-response") { this.#ensureHandshakeListener(); return; } - // `1 << undefined` evaluates to `1` (ToInt32(undefined) = 0), so a - // naive `if (!mask) return` would silently fall through for unknown - // event names and install a spurious noopBridgeListener on bit 0. - // Guard explicitly against unknown events. if (eventIds[event] === undefined) return; const mask = 1 << eventIds[event]; - const hasPersistentListener = (this.#eventId & mask) === mask; - if (hasPersistentListener) return; - // Install the native forwarder once. `#onOrOnce` flips the `#eventId` - // bit and registers the native listener as a side effect, but it also - // appends the listener we pass to the EventEmitter list. We only want - // the side effect here (the caller, e.g. `super.prependListener`, owns - // the real listener), so register `noopBridgeListener` and immediately - // remove it — leaving the native forwarder installed and the - // EventEmitter list untouched. Subsequent calls see - // `hasPersistentListener` and skip this branch. + if ((this.#eventId & mask) === mask) return; this.#onOrOnce(event, noopBridgeListener, undefined); super.off(event, noopBridgeListener); } @@ -673,24 +599,10 @@ class BunWebSocket extends EventEmitter { // deviation: this does not support `message` with `binaryType = "fragments"` addEventListener(type, listener, options) { - // 'upgrade' and 'unexpected-response' are Node-style events — they're - // emitted on the JS-side EventEmitter by `#onHandshake`, never by the - // native WebSocket. Register on `this` and arm the handshake listener. - // We deliberately don't wrap the handler in a DOM-style adapter: a - // wrapped closure would make `removeEventListener` fail to match the - // original listener, leaking the handler. Consumers that reach for - // `addEventListener` on a ws shim already accept a mixed API; for - // these two Node-only events they receive Node-style - // `(response)` / `(request, response)` args. + // upgrade/unexpected-response are emitted on this EventEmitter, not #ws. if (type === "upgrade" || type === "unexpected-response") { this.#ensureHandshakeListener(); - // DOM dedup: `addEventListener` with the same listener is a no-op. - // EventEmitter.on/once don't dedup, so check the current listeners - // ourselves — matching real ws, which scans listeners(type) for every - // event type (and the 'error' branch below, which dedups too). if (this.listeners(type).includes(listener)) return; - // `addEventListener` returns undefined per the DOM spec / real ws — - // use statement form so we don't leak EventEmitter's `this` return. if (options && options.once) { super.once(type, listener); } else { @@ -699,21 +611,8 @@ class BunWebSocket extends EventEmitter { return; } if (type === "error" && typeof listener === "function") { - // DOM dedup: re-registering the same listener is a no-op. We wrap below, - // so distinct wrappers would defeat the native EventTarget's identity - // dedup — check our own map instead (and avoid leaking the prior wrapper). if (this.#errorListenerWrappers?.has(listener)) return; - // Suppress the native 'Expected 101' error only when 'unexpected-response' - // actually handled the non-101 (matching real ws, which emits no error - // then). Gate on #unexpectedResponseHandled — NOT #unexpectedResponse - // Emitted — so a synthetic emit to a co-registered `on('error')` listener - // doesn't also swallow this handler. Wrap in a gated closure and remember - // it so `removeEventListener` can detach it. const self = this; - // With `{once:true}` the native EventTarget auto-removes the wrapper - // after it fires, so drop our dedup entry too — otherwise a later - // `addEventListener('error', listener)` would hit the guard above and - // silently no-op even though nothing is attached anymore. const once = !!(options && options.once); const wrapper = function (event) { if (once) self.#errorListenerWrappers?.delete(listener); @@ -728,16 +627,11 @@ class BunWebSocket extends EventEmitter { } removeEventListener(type, listener) { - // Symmetric with addEventListener: upgrade/unexpected-response - // listeners live on `this` (the EventEmitter), not on the native - // WebSocket, so removing them means calling `super.off`. if (type === "upgrade" || type === "unexpected-response") { super.off(type, listener); return; } if (type === "error") { - // `addEventListener('error', …)` registered a suppression wrapper, not - // the user's listener — detach the wrapper we stored for it. const wrapper = this.#errorListenerWrappers?.get(listener); if (wrapper !== undefined) { this.#errorListenerWrappers.delete(listener); @@ -757,7 +651,6 @@ class BunWebSocket extends EventEmitter { } get onerror() { - // Return the user's function, not the suppression wrapper we installed. return this.#onerror ?? this.#ws.onerror; } @@ -767,10 +660,6 @@ class BunWebSocket extends EventEmitter { this.#ws.onerror = value; return; } - // Suppress the native 'Expected 101' error only when 'unexpected-response' - // handled the non-101 (matching `addEventListener('error')` and real ws). - // Gate on #unexpectedResponseHandled so a co-registered `on('error')` - // listener's synthetic emit doesn't swallow this handler's error. const self = this; const fn = this.#onerror; this.#ws.onerror = function (event) { diff --git a/test/regression/issue/05951.test.ts b/test/js/first_party/ws/ws-upgrade-events.test.ts similarity index 75% rename from test/regression/issue/05951.test.ts rename to test/js/first_party/ws/ws-upgrade-events.test.ts index d606499dbc40..a3f9162bdf73 100644 --- a/test/regression/issue/05951.test.ts +++ b/test/js/first_party/ws/ws-upgrade-events.test.ts @@ -1,9 +1,6 @@ // https://github.com/oven-sh/bun/issues/5951 -// -// Exercises the public `ws` package surface (what miniflare/wrangler actually -// listen for), not the native 'handshake' event covered in 24229.test.ts. import { expect, test } from "bun:test"; -import { bunEnv, bunExe, isASAN, isDebug, normalizeBunSnapshot } from "harness"; +import { bunEnv, bunExe, normalizeBunSnapshot } from "harness"; async function run(script: string) { await using proc = Bun.spawn({ @@ -181,60 +178,6 @@ test.concurrent("ws microtask queued in 'upgrade' handler observes readyState OP expect(exitCode).toBe(0); }); -// The non-101 body can span multiple TCP reads. Previously the shim dispatched -// on the first read, truncating large error bodies. The native client now -// buffers until Content-Length is satisfied (or EOF) before dispatching. -test.concurrent("ws 'unexpected-response' waits for full Content-Length body across multiple writes", async () => { - const { stdout, exitCode } = await run(/* js */ ` - const { createServer } = require("net"); - const { once } = require("events"); - const { WebSocket } = require("ws"); - - // 8 kB JSON-ish payload, sent in three separate writes with a tick between - // each so the client sees multiple TCP reads (at least in the common case). - const CHUNK_SIZE = 2600; - const chunk1 = Buffer.alloc(CHUNK_SIZE, "a").toString(); - const chunk2 = Buffer.alloc(CHUNK_SIZE, "b").toString(); - const chunk3 = Buffer.alloc(CHUNK_SIZE, "c").toString(); - const bodyLen = CHUNK_SIZE * 3; - - const server = createServer(s => { - s.once("data", () => { - s.write( - "HTTP/1.1 503 Service Unavailable\\r\\n" + - "Content-Type: text/plain\\r\\n" + - "Content-Length: " + bodyLen + "\\r\\n\\r\\n" + - chunk1 - ); - setTimeout(() => s.write(chunk2), 10); - setTimeout(() => { s.write(chunk3); s.end(); }, 20); - }); - }).listen(0, "127.0.0.1"); - await once(server, "listening"); - - const ws = new WebSocket("ws://127.0.0.1:" + server.address().port); - ws.on("error", () => {}); - const [req, res] = await new Promise(resolve => - ws.once("unexpected-response", (req, res) => resolve([req, res])), - ); - let body = ""; - for await (const chunk of res) body += chunk; - console.log(JSON.stringify({ - statusCode: res.statusCode, - contentLength: res.headers["content-length"], - bodyLength: body.length, - firstChar: body[0], - lastChar: body[body.length - 1], - })); - await once(ws, "close"); - server.close(); - `); - expect(stdout).toMatchInlineSnapshot( - `"{"statusCode":503,"contentLength":"7800","bodyLength":7800,"firstChar":"a","lastChar":"c"}"`, - ); - expect(exitCode).toBe(0); -}); - // The synthetic IncomingMessage passed to 'unexpected-response' must coalesce // duplicate headers the way Node's http.IncomingMessage.headers does (real ws // hands the consumer that Node object): singleton headers keep the first value @@ -290,110 +233,6 @@ test.concurrent("ws 'unexpected-response' coalesces duplicate headers like Node expect(exitCode).toBe(0); }); -// RFC 7230 §3.3.3 rule #1: 1xx/204/304 responses carry no body regardless of -// headers. A bodiless non-101 status on a keep-alive connection (server never -// closes the socket) must dispatch 'unexpected-response' immediately off the -// header read — otherwise the client sits reading-until-EOF until the socket -// timeout and the event never fires. The server here deliberately keeps the -// connection open: with the fix this resolves at once; without it the -// subprocess hangs and the test times out. -test.concurrent("ws 'unexpected-response' fires immediately for bodiless 204 on keep-alive", async () => { - const { stdout, exitCode } = await run(/* js */ ` - const { createServer } = require("net"); - const { WebSocket } = require("ws"); - - // 204 No Content: no Content-Length, no Transfer-Encoding, and the socket - // is intentionally left open (no s.end()) so the only way the event fires - // is the immediate-dispatch path, not a read-until-close. - const server = createServer(s => - s.once("data", () => s.write("HTTP/1.1 204 No Content\\r\\nX-Gone: 1\\r\\n\\r\\n")), - ).listen(0, "127.0.0.1"); - await new Promise(r => server.once("listening", r)); - - const ws = new WebSocket("ws://127.0.0.1:" + server.address().port); - ws.on("error", () => {}); - const res = await new Promise(resolve => - ws.once("unexpected-response", (req, res) => resolve(res)), - ); - console.log(JSON.stringify({ - statusCode: res.statusCode, - statusMessage: res.statusMessage, - xGone: res.headers["x-gone"], - })); - ws.terminate(); - server.close(); - process.exit(0); - `); - expect(stdout).toMatchInlineSnapshot(`"{"statusCode":204,"statusMessage":"No Content","xGone":"1"}"`); - expect(exitCode).toBe(0); -}); - -// The RST teardown path (handle_close) flushes a mid-accumulation non-101 -// body into the 'unexpected-response' listener. If that listener synchronously -// calls ws.terminate()/ws.close(), the reentrant cancel() releases the socket -// ref while handle_close is still holding it — then handle_close's tcp.detach() -// runs on freed memory (heap-use-after-free in NewSocketHandler::detach) and -// its deref() underflows the refcount. Only an ASAN/debug build surfaces the -// corruption as a crash; release builds survive by luck, so gate on it. -// -// The RST must arrive as on_close WITHOUT a preceding on_end (FIN): a Bun.listen -// socket's terminate() sends a real RST while the client still has the body -// un-satisfied (WaitingForLength). Node's net server destroy()/resetAndDestroy() -// over loopback surfaces as FIN → on_end (a different, already-safe path). -test.concurrent.skipIf(!isDebug && !isASAN)( - "ws survives terminate() inside 'unexpected-response' when the socket RSTs mid-body", - async () => { - const { stdout, exitCode } = await run(/* js */ ` - const { once } = require("events"); - const { WebSocket } = require("ws"); - - // Declare a 100 kB body but send only a sliver, then RST a tick later so - // the client has parsed the headers and entered WaitingForLength. The - // RST then routes through handle_close, which flushes the deferred body - // into 'unexpected-response'. - const server = Bun.listen({ - hostname: "127.0.0.1", port: 0, - socket: { - data(socket) { - socket.write( - "HTTP/1.1 503 Service Unavailable\\r\\n" + - "Content-Length: 100000\\r\\n\\r\\n" + - "partial body, server resets before sending the rest" - ); - // Bun's socket.terminate() sends a real RST (not FIN). The small - // delay lets the partial body land first so the client is mid-body. - setTimeout(() => { try { socket.terminate(); } catch {} }, 10); - }, - error() {}, open() {}, - }, - }); - - const ws = new WebSocket("ws://127.0.0.1:" + server.port); - ws.on("error", () => {}); - ws.once("unexpected-response", (req, res) => { - console.log("status=" + res.statusCode); - // Reentrant teardown from inside the handshake dispatch — this is the - // path that used to UAF on the native client (handle_close then ran - // tcp.detach() on freed memory). - ws.terminate(); - }); - // Await 'close' rather than exiting immediately: the detach/deref that - // used to fault runs as handle_close unwinds, after terminate() returns. - await once(ws, "close"); - server.stop(true); - `); - expect(stdout).toContain("status=503"); - expect(exitCode).toBe(0); - }, -); - -// `on()` / `once()` are not the only EventEmitter registration APIs — ws -// consumers also reach for `addListener` / `prependListener` / -// `prependOnceListener` and (from DOM-style code) `addEventListener`. Each -// must arm the native handshake listener, otherwise the 'upgrade' / -// 'unexpected-response' handler is installed on the EventEmitter list but -// the native event that would `emit('upgrade', ...)` is never wired up and -// the callback silently never fires. test.concurrent("ws 'unexpected-response' fires for addListener / prependListener / addEventListener", async () => { const { stdout, exitCode } = await run(/* js */ ` const { createServer } = require("net"); diff --git a/test/regression/issue/24229.test.ts b/test/js/web/websocket/websocket-handshake-event.test.ts similarity index 100% rename from test/regression/issue/24229.test.ts rename to test/js/web/websocket/websocket-handshake-event.test.ts From f64d1730084d7016bfa5ca539a5f5a416d4cb7dd Mon Sep 17 00:00:00 2001 From: robobun <117481402+robobun@users.noreply.github.com> Date: Wed, 29 Jul 2026 00:59:53 +0000 Subject: [PATCH 4/9] ws: trim remaining multi-line comments to one line --- src/http_jsc/websocket_client/WebSocketUpgradeClient.rs | 3 +-- src/js/thirdparty/ws.js | 6 ++---- src/jsc/bindings/webcore/WebSocket.cpp | 5 +---- 3 files changed, 4 insertions(+), 10 deletions(-) diff --git a/src/http_jsc/websocket_client/WebSocketUpgradeClient.rs b/src/http_jsc/websocket_client/WebSocketUpgradeClient.rs index b3f3789c3b80..e7ce285239b4 100644 --- a/src/http_jsc/websocket_client/WebSocketUpgradeClient.rs +++ b/src/http_jsc/websocket_client/WebSocketUpgradeClient.rs @@ -978,8 +978,7 @@ impl HTTPClient { ); } - /// Surface `'handshake'` to the `ws` shim, then [`Self::process_response`]. - /// Caller holds a `ref_guard` and owns `full` (it must not borrow `self`). + /// Caller holds a `ref_guard` and owns `full` (must not borrow `self`). fn process_websocket_upgrade_response(this: ThisPtr, full: &[u8]) { let mut scratch = [picohttp::Header::ZERO; 128]; let Ok(response) = picohttp::Response::parse(full, &mut scratch) else { diff --git a/src/js/thirdparty/ws.js b/src/js/thirdparty/ws.js index 85a693f311ca..5ebe0974cce3 100644 --- a/src/js/thirdparty/ws.js +++ b/src/js/thirdparty/ws.js @@ -195,8 +195,7 @@ class BunWebSocket extends EventEmitter { #binaryType = "nodebuffer"; // Gates the EventEmitter bridge so the native non-101 error isn't re-emitted. #unexpectedResponseEmitted = false; - // Gates addEventListener('error')/onerror wrappers; set only when - // 'unexpected-response' actually fired (real ws emits no error then). + // Gates addEventListener('error')/onerror wrappers; set only when 'unexpected-response' fired. #unexpectedResponseHandled = false; // listener -> suppression wrapper, for removeEventListener('error', ...). #errorListenerWrappers; @@ -356,8 +355,7 @@ class BunWebSocket extends EventEmitter { this.#ws.addEventListener("handshake", event => this.#onHandshake(event.data), onceObject); } - // Minimal ClientRequest stub for the first 'unexpected-response' argument - // (we bypass node:http, so there is no real one to expose). + // Minimal ClientRequest stub for the first 'unexpected-response' argument. #syntheticRequest; #getSyntheticRequest() { let req = this.#syntheticRequest; diff --git a/src/jsc/bindings/webcore/WebSocket.cpp b/src/jsc/bindings/webcore/WebSocket.cpp index df52c061ec33..d4147507fa13 100644 --- a/src/jsc/bindings/webcore/WebSocket.cpp +++ b/src/jsc/bindings/webcore/WebSocket.cpp @@ -1559,8 +1559,7 @@ void WebSocket::didReceiveBinaryData(const AtomString& eventName, const std::spa void WebSocket::didReceiveHandshakeResponse(uint16_t statusCode, std::span statusMessage, std::span headers, std::span body) { - // The only consumer is the `ws` package shim, which always registers a listener - // before connecting. The browser-style `new WebSocket()` path skips this entirely. + // Only the `ws` shim listens; the browser-style path pays nothing. if (!this->hasEventListeners(eventNames().handshakeEvent)) return; @@ -1577,8 +1576,6 @@ void WebSocket::didReceiveHandshakeResponse(uint16_t statusCode, std::spanputDirect(vm, builtinNames.statusMessagePublicName(), JSC::jsString(vm, WTF::String({ statusMessage.data(), statusMessage.size() }))); - // PicoHTTP already parsed the response head, so surface its header list as - // a flat [name, value, name, value, ...] rawHeaders array. auto* rawHeaders = JSC::constructEmptyArray(globalObject, nullptr, headers.size() * 2); if (!rawHeaders || scope.exception()) [[unlikely]] { scope.clearExceptionExceptTermination(); From 59248750cc8b90a0eb227abdcc7802b2eb3560e8 Mon Sep 17 00:00:00 2001 From: robobun <117481402+robobun@users.noreply.github.com> Date: Wed, 29 Jul 2026 01:24:45 +0000 Subject: [PATCH 5/9] ci: retrigger From 0e0f4efb8787ddb3a63fb05145f57b6b52bcdb7e Mon Sep 17 00:00:00 2001 From: robobun <117481402+robobun@users.noreply.github.com> Date: Wed, 29 Jul 2026 02:02:06 +0000 Subject: [PATCH 6/9] ws: address review nits - Drop dead #[allow(clippy::not_unsafe_ptr_arg_deref)] on did_receive_handshake_response (no raw-pointer params). - Restore the pre-existing ShortRead why-comment in handle_decrypted_data to stay symmetric with handle_data / handle_proxy_response. - addEventListener('error', h, { signal }): also delete the WeakMap entry on signal abort so a subsequent add of the same listener isn't deduped away. - websocket-handshake-event.test.ts: wire 'close' to reject so a regression fails fast instead of timing out. --- src/http_jsc/websocket_client/CppWebSocket.rs | 1 - src/http_jsc/websocket_client/WebSocketUpgradeClient.rs | 4 ++++ src/js/thirdparty/ws.js | 1 + test/js/web/websocket/websocket-handshake-event.test.ts | 3 ++- 4 files changed, 7 insertions(+), 2 deletions(-) diff --git a/src/http_jsc/websocket_client/CppWebSocket.rs b/src/http_jsc/websocket_client/CppWebSocket.rs index c0b09c08517f..7acb23962b7d 100644 --- a/src/http_jsc/websocket_client/CppWebSocket.rs +++ b/src/http_jsc/websocket_client/CppWebSocket.rs @@ -98,7 +98,6 @@ impl CppWebSocket { } /// Dispatch the native `'handshake'` event; C++ copies all slices synchronously. - #[allow(clippy::not_unsafe_ptr_arg_deref)] pub(crate) fn did_receive_handshake_response( &self, status_code: u16, diff --git a/src/http_jsc/websocket_client/WebSocketUpgradeClient.rs b/src/http_jsc/websocket_client/WebSocketUpgradeClient.rs index e7ce285239b4..9f387b284f79 100644 --- a/src/http_jsc/websocket_client/WebSocketUpgradeClient.rs +++ b/src/http_jsc/websocket_client/WebSocketUpgradeClient.rs @@ -1273,6 +1273,10 @@ impl HTTPClient { if me.body.is_empty() { me.body.extend_from_slice(data); } + // ShortRead means no \r\n\r\n was found, so every byte in + // `body` is part of an incomplete header — cap that, not + // total bytes received (which may include pipelined + // WebSocket frames once the header does complete). if me.body.len() > bun_http::max_http_header_size() { // SAFETY: `me`'s last use is above; no `&mut Self` spans this call. unsafe { Self::terminate(this.as_ptr(), ErrorCode::InvalidResponse) }; diff --git a/src/js/thirdparty/ws.js b/src/js/thirdparty/ws.js index 5ebe0974cce3..bbf7f3e895a9 100644 --- a/src/js/thirdparty/ws.js +++ b/src/js/thirdparty/ws.js @@ -618,6 +618,7 @@ class BunWebSocket extends EventEmitter { return listener.$call(this, event); }; (this.#errorListenerWrappers ??= new WeakMap()).set(listener, wrapper); + options?.signal?.addEventListener("abort", () => self.#errorListenerWrappers?.delete(listener), onceObject); this.#ws.addEventListener(type, wrapper, options); return; } diff --git a/test/js/web/websocket/websocket-handshake-event.test.ts b/test/js/web/websocket/websocket-handshake-event.test.ts index 509116318fb1..9c72c0fca4f6 100644 --- a/test/js/web/websocket/websocket-handshake-event.test.ts +++ b/test/js/web/websocket/websocket-handshake-event.test.ts @@ -28,7 +28,7 @@ test("WebSocket 'handshake' event surfaces status/head/body on non-101", async ( try { const ws = new WebSocket("ws://127.0.0.1:" + (server.address() as AddressInfo).port); ws.addEventListener("error", () => {}); // swallow the expected-101 error - const { promise, resolve } = Promise.withResolvers<{ + const { promise, resolve, reject } = Promise.withResolvers<{ statusCode: number; statusMessage: string; rawHeaders: string[]; @@ -36,6 +36,7 @@ test("WebSocket 'handshake' event surfaces status/head/body on non-101", async ( }>(); // 'handshake' is a Bun extension consumed by the ws package shim. ws.addEventListener("handshake" as any, ((e: MessageEvent) => resolve(e.data as any)) as any); + ws.addEventListener("close", () => reject(new Error("'handshake' never fired")), { once: true }); const { statusCode, statusMessage, rawHeaders, body } = await promise; expect(statusCode).toBe(503); From c9424c2dc8a33a3465b4c6a0cc273f11017d425f Mon Sep 17 00:00:00 2001 From: robobun <117481402+robobun@users.noreply.github.com> Date: Wed, 29 Jul 2026 02:40:44 +0000 Subject: [PATCH 7/9] ws: handle already-aborted signal in addEventListener('error'); test no-warning - addEventListener('error', h, { signal }): return early when the signal is already aborted, matching the native EventTarget's own check, so the WeakMap never holds a stale entry. - Add a test that subscribes to 'upgrade'/'unexpected-response' via every registration API and asserts stderr is empty (no 'not implemented' warning). run() now returns stderr. --- src/js/thirdparty/ws.js | 1 + .../first_party/ws/ws-upgrade-events.test.ts | 24 ++++++++++++++++++- 2 files changed, 24 insertions(+), 1 deletion(-) diff --git a/src/js/thirdparty/ws.js b/src/js/thirdparty/ws.js index bbf7f3e895a9..8e4df80d7ffc 100644 --- a/src/js/thirdparty/ws.js +++ b/src/js/thirdparty/ws.js @@ -609,6 +609,7 @@ class BunWebSocket extends EventEmitter { return; } if (type === "error" && typeof listener === "function") { + if (options?.signal?.aborted) return; if (this.#errorListenerWrappers?.has(listener)) return; const self = this; const once = !!(options && options.once); diff --git a/test/js/first_party/ws/ws-upgrade-events.test.ts b/test/js/first_party/ws/ws-upgrade-events.test.ts index a3f9162bdf73..f989c398a3aa 100644 --- a/test/js/first_party/ws/ws-upgrade-events.test.ts +++ b/test/js/first_party/ws/ws-upgrade-events.test.ts @@ -11,9 +11,31 @@ async function run(script: string) { }); const [stdout, stderr, exitCode] = await Promise.all([proc.stdout.text(), proc.stderr.text(), proc.exited]); if (exitCode !== 0) console.error(stderr); - return { stdout: normalizeBunSnapshot(stdout), exitCode }; + return { stdout: normalizeBunSnapshot(stdout), stderr: normalizeBunSnapshot(stderr), exitCode }; } +test.concurrent("ws on/addListener/prepend*/addEventListener for upgrade/unexpected-response emit no warning", async () => { + const { stdout, stderr, exitCode } = await run(/* js */ ` + const { WebSocket } = require("ws"); + const ws = new WebSocket("ws://127.0.0.1:1"); + const h = () => {}; + for (const type of ["upgrade", "unexpected-response"]) { + ws.on(type, h); + ws.once(type, h); + ws.addListener(type, h); + ws.prependListener(type, h); + ws.prependOnceListener(type, h); + ws.addEventListener(type, h); + } + ws.on("error", () => {}); + ws.terminate(); + console.log("ok"); + `); + expect(stderr).toBe(""); + expect(stdout).toBe("ok"); + expect(exitCode).toBe(0); +}); + test.concurrent("ws emits 'unexpected-response' with status, headers and body on non-101", async () => { const { stdout, exitCode } = await run(/* js */ ` const { createServer } = require("net"); From 48a8c517e0973c5ecbd36a4c4c935d40e0e02c8f Mon Sep 17 00:00:00 2001 From: "autofix-ci[bot]" <114827586+autofix-ci[bot]@users.noreply.github.com> Date: Wed, 29 Jul 2026 02:42:52 +0000 Subject: [PATCH 8/9] [autofix.ci] apply automated fixes --- test/js/first_party/ws/ws-upgrade-events.test.ts | 15 +++++++++------ 1 file changed, 9 insertions(+), 6 deletions(-) diff --git a/test/js/first_party/ws/ws-upgrade-events.test.ts b/test/js/first_party/ws/ws-upgrade-events.test.ts index f989c398a3aa..9e3e2b59bb4e 100644 --- a/test/js/first_party/ws/ws-upgrade-events.test.ts +++ b/test/js/first_party/ws/ws-upgrade-events.test.ts @@ -14,8 +14,10 @@ async function run(script: string) { return { stdout: normalizeBunSnapshot(stdout), stderr: normalizeBunSnapshot(stderr), exitCode }; } -test.concurrent("ws on/addListener/prepend*/addEventListener for upgrade/unexpected-response emit no warning", async () => { - const { stdout, stderr, exitCode } = await run(/* js */ ` +test.concurrent( + "ws on/addListener/prepend*/addEventListener for upgrade/unexpected-response emit no warning", + async () => { + const { stdout, stderr, exitCode } = await run(/* js */ ` const { WebSocket } = require("ws"); const ws = new WebSocket("ws://127.0.0.1:1"); const h = () => {}; @@ -31,10 +33,11 @@ test.concurrent("ws on/addListener/prepend*/addEventListener for upgrade/unexpec ws.terminate(); console.log("ok"); `); - expect(stderr).toBe(""); - expect(stdout).toBe("ok"); - expect(exitCode).toBe(0); -}); + expect(stderr).toBe(""); + expect(stdout).toBe("ok"); + expect(exitCode).toBe(0); + }, +); test.concurrent("ws emits 'unexpected-response' with status, headers and body on non-101", async () => { const { stdout, exitCode } = await run(/* js */ ` From 4234810c4acf57a120661b158566e5fc34bb3e16 Mon Sep 17 00:00:00 2001 From: robobun <117481402+robobun@users.noreply.github.com> Date: Wed, 29 Jul 2026 03:19:09 +0000 Subject: [PATCH 9/9] ws: use http.IncomingMessage + _addHeaderLines for handshake response Replaces the hand-rolled header-coalescing loop and kSingletonHeaders table with a real http.IncomingMessage and its _addHeaderLines, which already implements Node's duplicate-header rules. Deletes ~40 lines of duplicated logic and makes res instanceof http.IncomingMessage true (matching real ws). Also: initialize the synthetic ClientRequest stub via EventEmitter.$call to match the existing finishRequest stub in this file. --- src/js/thirdparty/ws.js | 48 +++-------------------------------------- 1 file changed, 3 insertions(+), 45 deletions(-) diff --git a/src/js/thirdparty/ws.js b/src/js/thirdparty/ws.js index 8e4df80d7ffc..84064ff76161 100644 --- a/src/js/thirdparty/ws.js +++ b/src/js/thirdparty/ws.js @@ -95,57 +95,14 @@ const eventIds = { // Identity-stable placeholder for `#armNativeBridge`. function noopBridgeListener() {} -// Headers Node's http.IncomingMessage keeps first-value-only (lib/_http_incoming.js). -const kSingletonHeaders = new Set([ - "age", - "authorization", - "content-length", - "content-type", - "etag", - "expires", - "from", - "host", - "if-modified-since", - "if-unmodified-since", - "last-modified", - "location", - "max-forwards", - "proxy-authorization", - "referer", - "retry-after", - "server", - "user-agent", -]); - -let lazyReadable; function makeHandshakeResponse(statusCode, statusMessage, rawHeaders, body) { - lazyReadable ??= require("node:stream").Readable; - const res = new lazyReadable({ read() {} }); - const headers = (res.headers = { __proto__: null }); - res.rawHeaders = rawHeaders; - for (let i = 0; i < rawHeaders.length; i += 2) { - const lower = rawHeaders[i].toLowerCase(); - const value = rawHeaders[i + 1]; - const prev = headers[lower]; - if (lower === "set-cookie") { - if (prev === undefined) headers[lower] = [value]; - else prev.push(value); - } else if (prev === undefined) { - headers[lower] = value; - } else if (kSingletonHeaders.has(lower)) { - // Keep the first occurrence; discard the duplicate. - } else if (lower === "cookie") { - headers[lower] = prev + "; " + value; - } else { - headers[lower] = prev + ", " + value; - } - } + const res = new http.IncomingMessage(null); + res._addHeaderLines(rawHeaders, rawHeaders.length); res.statusCode = statusCode; res.statusMessage = statusMessage; res.httpVersion = "1.1"; res.httpVersionMajor = 1; res.httpVersionMinor = 1; - res.socket = res.connection = null; if (body && body.length) res.push(body); res.push(null); return res; @@ -393,6 +350,7 @@ class BunWebSocket extends EventEmitter { socket: null, [Symbol.toStringTag]: "ClientRequest", }; + EventEmitter.$call(req); return req; }