Skip to content

feat: add net.WebSocket - #51593

Merged
jkleinsc merged 5 commits into
mainfrom
feat/net-websocket
May 20, 2026
Merged

jkleinsc merged 5 commits into
mainfrom
feat/net-websocket

Conversation

@MarshallOfSound

@MarshallOfSound MarshallOfSound commented May 12, 2026 •

Copy link
Copy Markdown
Member

Description of Change

Adds net.WebSocket, a WHATWG-compatible WebSocket client for the main process backed by Chromium's network stack, via network.mojom.NetworkContext::CreateWebSocket(). No Chromium patches required.

Closes #44987

This gives main-process code a drop-in replacement for the browser/Node global WebSocket that:

  • Uses the system or session proxy configuration (PAC, WPAD, authenticated proxies).
  • Validates TLS against the platform trust store and the session's certificate verification policy.
  • Honors session-level configuration (custom CAs, host resolution rules, etc.).
  • Can send the session's cookies (when useSessionCookies is enabled).
const { app, net } = require('electron')

app.whenReady().then(() => {
  const ws = new net.WebSocket('wss://echo.websocket.events')
  ws.onopen = () => ws.send('hello')
  ws.onmessage = (event) => console.log(event.data)
})

The class implements the standard WebSocket interface (an EventTarget): addEventListener/on{open,message,error,close}, readyState, bufferedAmount, protocol, extensions, binaryType, send(), close(), and the CONNECTING/OPEN/CLOSING/CLOSED constants. It also accepts an Electron-specific options bag as the second constructor argument:

new net.WebSocket(url, {
  protocols, headers, origin, useSessionCookies, session, partition
})

Implementation

  • shell/browser/api/electron_api_web_socket.{h,cc} — a gin_helper::Wrappable + EventEmitterMixin object (mirroring SimpleURLLoaderWrapper) that implements network::mojom::{WebSocketHandshakeClient, WebSocketClient, WebSocketAuthenticationHandler}, drives the mojo data pipes with back-pressure loops on both sides, reassembles fragmented frames into messages, tracks bufferedAmount, and queues outbound writes.
  • lib/browser/api/net-websocket.ts — class WebSocket extends EventTarget, with WHATWG-spec URL/protocol/close validation (SyntaxError/InvalidAccessError/InvalidStateError DOMExceptions) and a CloseEvent polyfill (Node has Event and MessageEvent globals but not CloseEvent).

Notable behavior decisions

  • binaryType defaults to 'nodebuffer' (returns Buffer); 'arraybuffer' and 'blob' are also supported. This is the one intentional deviation from pure WHATWG.
  • useSessionCookies defaults to false, matching net.request().
  • The Origin header defaults to the http(s)-equivalent origin of the WebSocket URL (e.g. wss://api.example.com → Origin: https://api.example.com). With an opaque/null origin, Chromium computes a CROSS_SITE SameSite context for HTTP subresources (net/cookies/cookie_util.cc:ComputeSameSiteContext) and Lax cookies are silently dropped, so this default is required for useSessionCookies to work. Override with the origin option.

Known limitations / follow-ups

  • Main process only. Utility-process support would need a URLLoaderBundle-style mojo plumb-through for CreateWebSocket.
  • webRequest interception is not wired up yet — this would route through ProxyingWebSocket like ElectronBrowserClient::WillInterceptWebSocket() does.
  • The generated electron.d.ts declares extends EventTarget but the docs-parser can't express per-event-type addEventListener overloads, so addEventListener('message', (e: MessageEvent) => ...) requires a cast under strictFunctionTypes. The onmessage/etc. handler properties work without one.
  • Proxy auth challenges are wired up internally but not surfaced (per WHATWG-only surface).

Checklist

  • PR description included and stakeholders cc'd
  • npm test passes (spec/api-net-websocket-spec.ts — 27 tests, 10 consecutive clean runs)
  • tests are added or updated
  • relevant documentation is changed or added
  • PR title follows semantic commit guidelines

Release Notes

Notes: Added net.WebSocket, a WHATWG-compatible WebSocket client for the main process that routes through Chromium's network stack.

Add a WHATWG-compatible WebSocket client to the net module, backed by
Chromium's network stack via NetworkContext::CreateWebSocket(). This
gives main-process code a WebSocket that goes through the session's
proxy configuration, certificate verification, and cookie store, with
the same drop-in API shape as the browser/Node global WebSocket.

The implementation has two pieces:

- shell/browser/api/electron_api_web_socket.{h,cc}: a gin-wrapped object
  that implements network.mojom.{WebSocketHandshakeClient, WebSocketClient,
  WebSocketAuthenticationHandler}, drives the mojo data pipes with
  back-pressure on both sides, reassembles fragmented frames, tracks
  bufferedAmount, and emits low-level events.
- lib/browser/api/net-websocket.ts: a class WebSocket extends EventTarget
  that implements the WHATWG surface (addEventListener, on{open,message,
  error,close}, readyState, bufferedAmount, protocol, extensions,
  binaryType, send(), close(), CONNECTING/OPEN/CLOSING/CLOSED) plus
  Electron-specific options (headers, origin, useSessionCookies, session,
  partition).

binaryType supports 'nodebuffer' (default), 'arraybuffer', and 'blob'.
useSessionCookies defaults to false, matching net.request(). The Origin
header defaults to the http(s) equivalent of the WebSocket URL's origin
so that the connection looks first-party for SameSite cookie purposes;
it can be overridden with the origin option.

Main process only for now; webRequest interception is a known follow-up.
@electron-cation electron-cation Bot added the new-pr 🌱 PR opened recently label May 12, 2026
@MarshallOfSound MarshallOfSound added the semver/minor backwards-compatible functionality label May 12, 2026
…ppable

Migrate WebSocketWrapper from gin_helper::DeprecatedWrappable to
gin::Wrappable (cppgc-based, #47922):

- Add kElectronWebSocket wrappable pointer tag.
- Replace Pin()/Unpin() with gin_helper::SelfKeepAlive, cleared on teardown.
- Replace base::WeakPtrFactory with gin::WeakCellFactory + gin::WrapPersistent
  for callbacks; add Trace() to visit the weak cell.
- Annotate mojo::Receiver/Remote fields with GC_PLUGIN_IGNORE (browser process
  doesn't need execution-context tracking), matching UtilityProcessWrapper.
- Public constructor for cppgc::MakeGarbageCollected; Create() returns T*.

Spec and correctness fixes:

- Drop the unused WebSocketAuthenticationHandler. The 'login' event it emitted
  was never bridged to the WHATWG-only TS surface, leaving the mojo
  OnAuthRequired callback orphaned and the connection hung on a 401/407
  challenge until V8 GC. Pass NullRemote() so the network service fails the
  challenge fast (matching WebSocketConnectorImpl). Drop the 'authenticated
  proxies' claim from the docs.
- Serialize the send queue so a Blob send (which must read asynchronously)
  doesn't let a later string/ArrayBuffer send overtake it on the wire.
- Set readyState to CLOSED before dispatching the 'error' event, per the
  WebSocket spec ordering rules.
- Stop nulling the wrapper on close so bufferedAmount reflects untransmitted
  bytes (it must not reset to zero) and continues to count post-close sends.
- Use WebIDL [Clamp] semantics for the close() code argument.
- Disable permessage-deflate on the test ws server; it isn't the subject under
  test and ws@7's deflate close path can race a server-initiated close.

@deepak1556 deepak1556 left a comment

Copy link
Copy Markdown
Member

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

LGTM, just some minor followups

Comment thread lib/browser/api/net-websocket.ts Resolved
- Track all bytes queued in the JS send chain (not just Blob reads) so
  bufferedAmount is accurate while a non-Blob send is waiting behind an
  asynchronous Blob read.
- Surface the network failure message and net error in CloseEvent.reason
  for connection failures (the WHATWG 'error' Event has no payload). Failure
  reasons from the network service already embed the net error name; only
  append it for internally-generated failures.
- Emit a Node Buffer from the C++ side via electron::Buffer::Copy() instead
  of a raw ArrayBuffer, avoiding a TS-side wrap on the default 'nodebuffer'
  path.
- Drop the redundant disconnect handler on the WebSocket remote; the
  WebSocketClient receiver and the remote terminate at the same WebSocketImpl
  in the network process.
@MarshallOfSound
MarshallOfSound requested a review from a team as a code owner May 13, 2026 20:34

@deepak1556 deepak1556 left a comment

Copy link
Copy Markdown
Member

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

LGTM, thanks!

@nmggithub nmggithub left a comment

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Seems pretty good! Just some minor logic nits.

Comment thread lib/browser/api/net-websocket.ts Resolved

@erickzhao erickzhao left a comment

Copy link
Copy Markdown
Member

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

API LGTM

@jkleinsc jkleinsc left a comment

Copy link
Copy Markdown
Member

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

API LGTM

@jkleinsc
jkleinsc merged commit cdf7ac5 into main May 20, 2026
124 of 127 checks passed
@jkleinsc
jkleinsc deleted the feat/net-websocket branch May 20, 2026 14:03
@release-clerk

release-clerk Bot commented May 20, 2026

Copy link
Copy Markdown

Release Notes Persisted

Added net.WebSocket, a WHATWG-compatible WebSocket client for the main process that routes through Chromium's network stack.

@MarshallOfSound

Copy link
Copy Markdown
Member Author

/trop run backport-to 43-x-y

@trop

trop Bot commented Jul 14, 2026

Copy link
Copy Markdown
Contributor

The backport process for this PR has been manually initiated - sending your PR to 43-x-y!

@trop trop Bot mentioned this pull request Jul 14, 2026
@trop

trop Bot commented Jul 14, 2026

Copy link
Copy Markdown
Contributor

I have automatically backported this PR to "43-x-y", please check out #52344

@MarshallOfSound

Copy link
Copy Markdown
Member Author

/trop run backport-to 42-x-y

@trop

trop Bot commented Jul 14, 2026

Copy link
Copy Markdown
Contributor

The backport process for this PR has been manually initiated - sending your PR to 42-x-y!

@trop trop Bot mentioned this pull request Jul 14, 2026
@trop

trop Bot commented Jul 14, 2026

Copy link
Copy Markdown
Contributor

I have automatically backported this PR to "42-x-y", please check out #52345

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Labels

44-x-y api-review/approved ✅ merged/42-x-y PR was merged to the "42-x-y" branch. merged/43-x-y PR was merged to the "43-x-y" branch. no-backport semver/minor backwards-compatible functionality

Projects

No open projects
Status: No status

Development

Successfully merging this pull request may close these issues.

net.WebSocket

6 participants