WebSockets
Introduction
@plinthjs/websockets is a WebSocket server written for Plinth with no dependencies. It performs the RFC 6455 handshake and frame encoding itself on top of node:http, and speaks the Pusher channel protocol, so Pusher-compatible browser clients can connect, subscribe to channels and receive the events you broadcast.
Use it as the delivery half of Broadcasting: your application announces an event, and this server pushes it to every browser subscribed to the channel.
pnpm add @plinthjs/websocketsINFO
The server implements the core of the protocol: connecting, subscribing, unsubscribing, ping and pong, and client events between members of a channel. It does not verify private channel signatures on its own (you supply that check, see Authenticating private and presence channels) and its presence support is the member list and join/leave events described below. Its behaviour was verified in-process against fake sockets, not against a browser client.
Running the server
Create a WebSocketServer (also exported as WebSocketServer) and attach it to a node:http server. It listens for the upgrade event, completes the handshake, and manages each connection from then on. A request with a bad handshake has its socket destroyed.
import { createServer } from 'node:http'
import { WebSocketServer } from '@plinthjs/websockets'
const websockets = new WebSocketServer()
const http = createServer()
websockets.attach(http)
http.listen(8080)The server can share an HTTP server that also serves your application, because attach only handles upgrade requests. From anywhere in your code, push an event to every subscriber of a channel. broadcast returns how many connections received it.
const delivered = websockets.broadcast('orders', 'OrderShipped', { id: 42 })
// => number of subscribers that received itTo connect it to your broadcasting events, see Delivering through the WebSocket server.
The channel protocol
Every message is JSON with an event name and optionally a channel and data. When a client connects, the server first sends a pusher:connection_established event whose data contains the connection's socket_id. The client then sends these events:
| Client event | What the server does |
|---|---|
pusher:subscribe | Adds the connection to data.channel and replies pusher_internal:subscription_succeeded |
pusher:unsubscribe | Removes the connection from data.channel |
pusher:ping | Replies pusher:pong |
client-* | Relays the event to the other members of the named channel |
A subscribe message looks like this:
{ "event": "pusher:subscribe", "data": { "channel": "orders" } }and the server's acknowledgement is:
{ "event": "pusher_internal:subscription_succeeded", "channel": "orders", "data": "{}" }Client events (those starting with client-) are only relayed when the sender has joined the channel they name, and the sender does not receive its own event back. Unknown events and malformed JSON are ignored. WebSocket-level ping frames are answered with pong frames, a close frame removes the connection, and closing the socket unsubscribes it from every channel.
Events you send from the server with broadcast(channel, event, data) arrive as { event, channel, data }, with data exactly as you passed it.
Authenticating private and presence channels
By default every subscription is accepted. To gate channels, pass authorizeSubscription when you create the server. It runs on every pusher:subscribe and receives the connection, the channel name and the auth string the client sent. It may be synchronous or async (look the user up, check a database), and a rejected promise counts as a refusal. Return false and the client receives a pusher:error event with code 4009 and the subscription is refused.
The client obtains its auth string from your application's authorization route, which signs socketId:channelName with your app secret (see The authorization route). The server recomputes the signature and compares:
import { createHmac, timingSafeEqual } from 'node:crypto'
import { WebSocketServer } from '@plinthjs/websockets'
const APP_KEY = 'app-key'
const APP_SECRET = 'app-secret'
function sign(socketId: string, channel: string): string {
const hmac = createHmac('sha256', APP_SECRET).update(`${socketId}:${channel}`).digest('hex')
return `${APP_KEY}:${hmac}`
}
const websockets = new WebSocketServer({
authorizeSubscription(connection, channel, auth) {
const isProtected = channel.startsWith('private-') || channel.startsWith('presence-')
if (!isProtected) return true
if (auth === undefined) return false
const expected = sign(connection.id, channel)
return (
auth.length === expected.length && timingSafeEqual(Buffer.from(auth), Buffer.from(expected))
)
},
})The hook does not receive the signed-in user, which is why the signature does the work: only your HTTP application, having authorized the user, can produce a valid one.
Presence channels
A channel whose name starts with presence- tracks its members. Who a member is comes from, in order: an object returned by authorizeSubscription ({ user_id, user_info }, the safe choice because your server decides), the channel_data the client sent with its subscribe ({ user_id, user_info } as JSON, as Pusher clients do), or the connection's socket id when neither is present. Prefer returning the member from the hook; client-supplied channel_data is only as trustworthy as your signature check, which for presence channels in the Pusher scheme also signs the channel data.
const websockets = new WebSocketServer({
async authorizeSubscription(connection, channel, auth) {
if (!channel.startsWith('presence-')) return true
const user = await userForSignature(connection.id, channel, auth)
return user === undefined ? false : { user_id: user.id, user_info: { name: user.name } }
},
})When a client joins a presence channel:
- Its
pusher_internal:subscription_succeededdata carries the current members:{ "presence": { "count", "ids", "hash" }, "members": [{ "user_id", "user_info" }] }. Thepresenceobject is the shape Pusher clients read,membersis the same list as an array. Non-presence channels still receive{}. - Every other member receives
pusher_internal:member_addedwith{ "user_id", "user_info" }asdata. - When a member unsubscribes or disconnects, the remaining members receive
pusher_internal:member_removedwith{ "user_id" }.
A user with several connections (two tabs) is one member: member_added fires for the first connection and member_removed after the last one leaves. websockets.members(channel) returns the current members from the server side.
Messages sent in several WebSocket frames (a text or binary frame followed by continuation frames) are reassembled before they are parsed, and control frames such as pings may arrive between the fragments.
Connections and channels
The server exposes what it is tracking.
websockets.connections.size // open connections, keyed by socket id
websockets.connections.get('328207309.343694922') // a Connection
websockets.channels.count('orders') // => subscriber count
websockets.channels.members('orders') // Set of Connection (a copy)
websockets.channels.channelNames() // every channel with at least one memberA Connection has an id, the set of channels it has joined, and methods to talk to that one client: send(text), sendJson(payload), sendBinary(data), ping(), pong(payload?) and close(code?, reason?). isClosed reports whether it has been closed.
for (const connection of websockets.channels.members('orders')) {
connection.sendJson({ event: 'Ping', channel: 'orders', data: {} })
}Low-level pieces
The handshake and frame codec are exported separately, which is useful for tests and for building your own transport.
import { computeAcceptKey, decodeFrames, encodeFrame, OPCODES, upgrade } from '@plinthjs/websockets'
computeAcceptKey('dGhlIHNhbXBsZSBub25jZQ==') // => 's3pPLMBiTxaQ9kYGzzhZRbK+xOo='
const frame = encodeFrame(OPCODES.text, 'hello') // an unmasked server-to-client frame
const clientFrame = encodeFrame(OPCODES.text, 'hello', { mask: true }) // as a browser sends it
const { frames, rest } = decodeFrames(frame)
frames[0]?.payload.toString() // => 'hello'
// rest is any trailing partial frame, to prepend to the next chunkupgrade(req, socket) writes the 101 Switching Protocols response for a raw upgrade request, and throws HandshakeError when Upgrade: websocket or Sec-WebSocket-Key is missing. closeFrame, pingFrame and pongFrame build control frames. Fragmented messages are not reassembled: continuation frames are ignored.
Testing without a network
You do not need to bind a port. handleConnection(socket) adopts any object with write, end and on, so a fake socket stands in for the network. Feed it masked frames to play the client, and decode what it wrote.
import {
decodeFrames,
encodeFrame,
OPCODES,
WebSocketServer,
type SocketLike,
} from '@plinthjs/websockets'
class FakeSocket implements SocketLike {
written: Buffer[] = []
private listeners = new Map<string, Array<(...args: never[]) => void>>()
write(buffer: Buffer) {
this.written.push(buffer)
}
end() {}
on(event: string, listener: (...args: never[]) => void) {
this.listeners.set(event, [...(this.listeners.get(event) ?? []), listener])
}
// Play the client: send a JSON message in a masked frame.
send(message: unknown) {
const chunk = encodeFrame(OPCODES.text, JSON.stringify(message), { mask: true })
for (const listener of this.listeners.get('data') ?? [])
(listener as (c: Buffer) => void)(chunk)
}
// Decode every JSON message the server wrote.
messages() {
const { frames } = decodeFrames(Buffer.concat(this.written))
return frames.map((f) => JSON.parse(f.payload.toString('utf8')))
}
}
const websockets = new WebSocketServer()
const socket = new FakeSocket()
websockets.handleConnection(socket)
socket.send({ event: 'pusher:subscribe', data: { channel: 'orders' } })
websockets.channels.count('orders') // => 1
websockets.broadcast('orders', 'OrderShipped', { id: 42 })
socket.messages().at(-1)
// => { event: 'OrderShipped', channel: 'orders', data: { id: 42 } }To exercise the HTTP wiring without listening on a port, call attach on a node:http server you never listen on, and emit its upgrade event with a request carrying Upgrade: websocket and a Sec-WebSocket-Key header and your fake socket.
import { createServer } from 'node:http'
const http = createServer()
websockets.attach(http)
http.emit(
'upgrade',
{ headers: { upgrade: 'websocket', 'sec-websocket-key': 'dGhlIHNhbXBsZSBub25jZQ==' } },
socket,
)
// socket.written[0] is the '101 Switching Protocols' response