nish/net/websocket

RFC 6455 WebSocket framing and both sides of the opening handshake, sans-IO: bytes in, events and bytes out.

import {
  WS_CLOSE,
  WS_CLOSE_GOING_AWAY,
  WS_CLOSE_INTERNAL_ERROR,
  WS_CLOSE_INVALID_DATA,
  WS_CLOSE_NORMAL,
  WS_CLOSE_NO_STATUS,
  WS_CLOSE_POLICY,
  WS_CLOSE_PROTOCOL_ERROR,
  WS_CLOSE_TOO_BIG,
  WS_CLOSE_UNSUPPORTED,
  WS_ERROR,
  WS_GUID,
  WS_HS_ACCEPT,
  WS_HS_CONNECTION,
  WS_HS_EXTENSION,
  WS_HS_OK,
  WS_HS_PROTOCOL,
  WS_HS_STATUS,
  WS_HS_UPGRADE,
  WS_HS_VERSION,
  WS_MAX_CONTROL,
  WS_MESSAGE,
  WS_NEED_MORE,
  WS_NO_ROOM,
  WS_OP_BINARY,
  WS_OP_CLOSE,
  WS_OP_CONTINUATION,
  WS_OP_PING,
  WS_OP_PONG,
  WS_OP_TEXT,
  WS_PING,
  WS_PONG,
  WS_REFUSED,
  WsAcceptKey,
  WsDecoder,
  WsHandshake,
  websocketAcceptKey,
  websocketCheckResponse,
  websocketClientKey,
  websocketClosePayload,
  websocketFrame,
  websocketFrameSize,
  websocketIsUtf8,
  websocketKeyIsValid,
  websocketOfferedProtocols,
  websocketOriginAllowed,
  websocketRequestKey,
  websocketRequestKeyField,
  websocketUpgradeRequest,
  websocketUpgradeResponse,
  websocketWriteFrame,
  websocketWriteUpgradeResponse,
} from "nish/net/websocket";
const d = new WsDecoder(true, maxMessage); // a server: frames must be masked
d.feed(received, 0, n);
let event: i32 = d.next();
while (event !== WS_NEED_MORE) {
  // WS_MESSAGE: d.opcode is WS_OP_TEXT or WS_OP_BINARY, the message
  //   is d.data[0 .. d.dataLen), valid until the next call
  // WS_PING / WS_PONG: the payload, the same way
  // WS_CLOSE: d.closeCode and d.closeReason; answer with a close
  // WS_ERROR: fail the connection, sending a close with d.closeCode
  event = d.next();
}
The server's handshake

nish/net/http1-codec reads the client's request; websocketRequestKey(parser) answers its Sec-WebSocket-Key when the head is a valid opening handshake (§4.2.1), websocketOfferedProtocols(parser) the subprotocols it offers, and websocketUpgradeResponse(key, protocol) writes the 101 that accepts it, with Sec-WebSocket-Accept from websocketAcceptKey (§4.2.2): the base64 of the SHA-1 of the key and a fixed GUID. websocketOriginAllowed(parser, allowed) is the opt-in check of Origin a server makes first, against a page on another site. A server that accepts handshake after handshake keeps a WsAcceptKey and writes the 101 into its output with websocketRequestKeyField and websocketWriteUpgradeResponse, allocating nothing per handshake, as Http1Connection.acceptWebSocket does. What HTTP1_UPGRADE's upgradeBytes() answers is the first input for the decoder.

The client's handshake

The client's handshake (§4.1). websocketClientKey(nonce) spells 16 random bytes as the key, websocketUpgradeRequest(host, target, key, protocols) writes the GET that asks to upgrade, and websocketCheckResponse(parser, key, offered) reads the server's answer, parsed by nish/net/http1-client-codec after expectUpgrade(): it answers the negotiated subprotocol, or which rule of §4.1 the response broke. What HTTP1_UPGRADE's tunnelBytes() answers is the first input for WsDecoder(false, …). This module draws no randomness: the nonce and every frame's mask key are the caller's, from crypto.getRandomValues.

The decoder

The decoder is a push-pull machine like Http1Parser: feed any slice, then call next() until it answers WS_NEED_MORE.

Fragments are joined: WS_MESSAGE comes once, with the whole message, and control frames between the fragments of a message come out in their place (§5.4). WS_CLOSE and WS_ERROR are final and repeat on every later call; input after them is dropped.

What it refuses (WS_ERROR, and the status code to close with):

  • 1002, a protocol error: a reserved bit set, since no extension is negotiated (§5.2); a reserved opcode; a control frame that is fragmented or longer than 125 bytes (§5.5); a frame masked when the decoder expects it not to be, or the reverse (§5.1); a length not in its minimal form, or a 64-bit length with its top bit set (§5.2); a continuation with no message to continue, or a new message while one is unfinished (§5.4); a close frame with a one-byte payload, or a status code that may not be sent (§5.5.1, §7.4).
  • 1007: a text message, or a close reason, that is not UTF-8 (§8.1). A text message is checked as its bytes arrive, inside a frame as well as across fragments, so a bad byte is refused without waiting for the rest of the frame. The message buffer grows with the bytes received, not the length a frame header declares.
  • 1009: a message longer than maxMessage (§7.4.1), refused from the frame header that would pass it, before its payload arrives.
The encoder

The encoder is websocketFrame, which writes one frame with the mask a client supplies (the mask key is randomness, so it is an argument here), and websocketClosePayload for a close frame's code and reason. Both refuse (null) what the decoder would.

Private helpers share the importing program's flat symbol namespace (docs/wp26-stdlib.md §3e), which is why each one carries the module's name.

Written from RFC 6455, not ported from another implementation.

Functions

websocketAcceptKey

Sec-WebSocket-Accept for the client's Sec-WebSocket-Key (§4.2.2 item 5.4): the SHA-1 of the key and WS_GUID, in padded standard base64.

const websocketAcceptKey: (key: string) => string
keystringrequired

The key as the client sent it; it is not checked here, so check it with websocketKeyIsValid first.

returnsstring

The 28-character accept value.

websocketCheckResponse

Reads the server's answer to websocketUpgradeRequest(…, key, offered) (§4.1, the client's checks of the response): call it at the parser's HTTP1_HEAD.

It fails closed, and the connection is closed on any failure: a status other than 101 (WS_HS_STATUS; a redirect is not followed), a version other than HTTP/1.1, Upgrade absent, repeated or not websocket, no Connection listing upgrade, Sec-WebSocket-Accept absent, repeated or not websocketAcceptKey(key) (a forged or replayed answer, or any answer when key is not a valid key), any Sec-WebSocket-Extensions (this client offers none, so none may be in use), and a Sec-WebSocket-Protocol that is present when nothing was offered, repeated, a list, or not one of offered.

On WS_HS_OK the parser's next events are HTTP1_END and HTTP1_UPGRADE; its tunnelBytes() go to WsDecoder(false, …), and every frame the client sends is masked with a fresh mask key from crypto.getRandomValues (§5.3).

const websocketCheckResponse: (
  response: Http1ResponseParser,
  key: string,
  offered: string[],
) => WsHandshake
responseHttp1ResponseParserrequired

The client's parser, at the HTTP1_HEAD of the response.

keystringrequired

The key the request sent, from websocketClientKey.

offeredstring[]required

The subprotocols the request offered, as passed to websocketUpgradeRequest.

returnsWsHandshake

WS_HS_OK and the chosen subprotocol, or the first WS_HS_* rule the response broke.

websocketClientKey

The Sec-WebSocket-Key for a client's opening handshake (§4.1 item 7): the 16-byte nonce in padded standard base64, 24 characters. Answers null for a nonce of any other length. The nonce is the caller's, drawn from crypto.getRandomValues and fresh for every connection: a key that repeats or can be guessed lets a cache or an intermediary replay an old handshake's answer. This module draws no randomness itself.

const websocketClientKey: (nonce: u8[]) => string | null
nonceu8[]required

16 fresh random bytes; the caller keeps the returned key to check the response with.

returnsstring | null

The 24-character key, or null when nonce is not 16 bytes.

websocketClosePayload

The payload of a close frame (§5.5.1): code in two bytes, then reason. Answers null for a code that may not be sent (1005, 1006 and 1015 among them; §7.4), a reason that is not UTF-8, and one longer than 123 bytes, which would take the frame past 125.

const websocketClosePayload: (
  code: i32,
  reason: string,
) => u8[] | null
codei32required

The close status code, such as 1000 for a normal closure.

reasonstringrequired

Why the connection closes, for a person to read; "" for no reason.

returnsu8[] | null

The payload for a WS_OP_CLOSE frame, the code big-endian and then the reason's bytes, or null when refused.

websocketFrame

One frame, as websocketWriteFrame writes it, in an array of its own; the same refusals answer null. A window outside payload panics.

const websocketFrame: (
  fin: boolean,
  opcode: i32,
  payload: u8[],
  off: i32,
  len: i32,
  mask: u8[] | null,
) => u8[] | null
finbooleanrequired

Whether this is the message's last frame; a control frame must set it.

opcodei32required

The frame's opcode, such as WS_OP_TEXT or WS_OP_PING.

payloadu8[]required

The array holding the payload; it is not changed, even when masked.

offi32required

Where the payload starts in payload.

leni32required

The payload's length in bytes.

masku8[] | nullrequired

The 4-byte mask key for a client's frame, or null for a server's.

returnsu8[] | null

The whole frame, websocketFrameSize(len, mask !== null) bytes, or null for a frame websocketWriteFrame refuses.

websocketFrameSize

How many bytes a frame of len payload bytes takes, its header included, so a caller can size the buffer websocketWriteFrame writes into.

const websocketFrameSize: (len: i32, masked: boolean) => i32
leni32required

The payload's length in bytes, at least 0.

maskedbooleanrequired

Whether the frame carries a 4-byte mask key, as every frame a client sends does.

returnsi32

The frame's size in bytes: 2 to 14 bytes of header, then len.

websocketIsUtf8

Whether buf[off .. off + len) is well-formed UTF-8: what a whole text message's payload, or a close frame's reason, must be (§8.1). A window outside buf panics.

const websocketIsUtf8: (
  buf: u8[],
  off: i32,
  len: i32,
) => boolean
bufu8[]required

The array holding the bytes.

offi32required

Where the bytes start in buf.

leni32required

How many bytes to check; 0 is valid UTF-8.

returnsboolean

True when the bytes are UTF-8 with no overlong form, surrogate or code point past U+10FFFF, and no character cut short at the end.

websocketKeyIsValid

Whether key is a valid Sec-WebSocket-Key (§4.2.1 item 5): padded standard base64 that decodes to exactly 16 bytes, in its one canonical spelling.

const websocketKeyIsValid: (key: string) => boolean
keystringrequired

The field's value, as the client sent it.

returnsboolean

True for a 24-character key ending in == whose other characters decode to 16 bytes.

websocketOfferedProtocols

The subprotocols the opening handshake p has just read offers, in the order offered (§4.2.1 item 8, §11.3.4): every Sec-WebSocket-Protocol field's comma-separated list, joined, each element trimmed of OWS and the empty ones dropped (RFC 9110 §5.6.1). Answers [] when there is no such field, and null when an element is not a token: a server picks one of these, or none, for websocketUpgradeResponse.

const websocketOfferedProtocols: (
  p: Http1Parser,
) => string[] | null
pHttp1Parserrequired

The server's parser, at the HTTP1_HEAD of the request.

returnsstring[] | null

The offered subprotocols in order, [] when none are offered, or null when one is not a token.

websocketOriginAllowed

Whether the request's Origin is one of allowed: the check a server makes before acceptWebSocket so that a page on another site cannot open a WebSocket that rides the user's cookies (cross-site WebSocket hijacking, RFC 6455 §10.2). A browser always sends Origin on the opening handshake and a page cannot change it; the handshake itself is not refused without one, because a client that is not a browser need not send it, so the check is the program's to opt into.

An origin is compared whole, in any ASCII case, as the browser serializes it: https://example.com, or https://example.com:8443 for a port that is not the scheme's default, with no path and no trailing slash. Answers false for a request with no Origin or with more than one, so a program that also serves clients that are not browsers lets those through itself. Allocates nothing.

const websocketOriginAllowed: (
  p: Http1Parser,
  allowed: string[],
) => boolean
pHttp1Parserrequired

the parser holding the request's head, as Http1Connection.parser does at H1_REQUEST

allowedstring[]required

the origins to accept, each written as a browser sends it; "null" accepts an opaque origin, which any sandboxed page can send

returnsboolean

true when exactly one Origin field is present and its value is one of allowed

websocketRequestKey

The client's key when the head p has just read is a valid opening handshake (§4.2.1), as websocketRequestKeyField judges it. Otherwise null, and the server answers 400 (or 426 with Sec-WebSocket-Version: 13 when only the version is wrong, §4.4).

const websocketRequestKey: (p: Http1Parser) => string | null
pHttp1Parserrequired

The server's parser, at the HTTP1_HEAD of the request.

returnsstring | null

The Sec-WebSocket-Key to pass to websocketUpgradeResponse, or null when the request is not a valid handshake.

websocketRequestKeyField

Which field of the head p has just read holds the client's key, when that head is a valid opening handshake (§4.2.1): a GET in HTTP/1.1, asking to upgrade to websocket (alone, in any case), at version 13, with a valid first Sec-WebSocket-Key. Otherwise -1. Nothing is allocated: the key is p.head[p.spans[4 * i + 2] .. p.spans[4 * i + 3]), for WsAcceptKey.

const websocketRequestKeyField: (p: Http1Parser) => i32
pHttp1Parserrequired

The server's parser, at the HTTP1_HEAD of the request.

returnsi32

The key's field index, or -1 when the request is not a valid handshake.

websocketUpgradeRequest

A client's opening handshake (§4.1 items 1 to 10): GET target HTTP/1.1 with Host, Sec-WebSocket-Key, Sec-WebSocket-Version: 13, the offered protocols in one Sec-WebSocket-Protocol field when there are any, and Upgrade: websocket and Connection: Upgrade, written by nish/net/http1-client-codec's http1UpgradeRequestHead. Answers null for a key websocketKeyIsValid refuses, a protocol that is not a token (an empty one, or one holding a comma, a space, CR or LF), a protocol offered twice, an empty host, and everything the request writer refuses (CR, LF or another control byte in host, a target that is not a request target).

const websocketUpgradeRequest: (
  host: string,
  target: string,
  key: string,
  protocols: string[],
) => u8[] | null
hoststringrequired

The Host field's value: the server's host, and its port when it is not the scheme's default.

targetstringrequired

The request target, such as /chat?room=1.

keystringrequired

The client's key, from websocketClientKey.

protocolsstring[]required

The subprotocols the client offers, in order of preference; [] for none.

returnsu8[] | null

The whole request head, ending in the empty line, or null when refused.

websocketUpgradeResponse

The server's 101 response to an opening handshake (§4.2.2): Upgrade, Connection, Sec-WebSocket-Accept, and Sec-WebSocket-Protocol when protocol is not empty (the caller picks it from the client's list). Answers null for an invalid key or a protocol that is not a token. A server answering handshake after handshake writes the same bytes with WsAcceptKey and websocketWriteUpgradeResponse instead, allocating nothing.

const websocketUpgradeResponse: (
  key: string,
  protocol: string,
) => u8[] | null
keystringrequired

The client's Sec-WebSocket-Key, as websocketRequestKey gave it.

protocolstringrequired

The subprotocol the server chose from websocketOfferedProtocols, or "" for none.

returnsu8[] | null

The whole response head, ending in the empty line, or null when refused.

websocketWriteFrame

Writes one frame (§5.2) into out at at: FIN, the opcode, the payload payload[off .. off + len) and, when mask is not null, masked with that 4-byte key. A client masks every frame with a fresh key from crypto.getRandomValues (§5.3); a server passes null. The length takes the shortest of its three forms.

Answers where the frame ends, WS_NO_ROOM when it does not fit, or WS_REFUSED for an opcode RFC 6455 does not define, a control frame that is not FIN or is longer than 125 bytes, and a mask that is not 4 bytes; on either refusal out is untouched. A window outside payload panics, and so does a payload longer than 2^31 - 15 bytes. A text frame's payload is not checked here, because a fragment may end inside a character; websocketIsUtf8 checks a whole message.

const websocketWriteFrame: (
  out: u8[],
  at: i32,
  fin: boolean,
  opcode: i32,
  payload: u8[],
  off: i32,
  len: i32,
  mask: u8[] | null,
) => i32
outu8[]required

The buffer the frame is written into.

ati32required

The index in out the frame starts at; one outside out answers WS_NO_ROOM.

finbooleanrequired

Whether this is the message's last frame; a control frame must set it.

opcodei32required

The frame's opcode, such as WS_OP_TEXT or WS_OP_PING.

payloadu8[]required

The array holding the payload; it is not changed, even when masked.

offi32required

Where the payload starts in payload.

leni32required

The payload's length in bytes.

masku8[] | nullrequired

The 4-byte mask key for a client's frame, or null for a server's.

returnsi32

The index in out just past the frame, or WS_NO_ROOM or WS_REFUSED.

websocketWriteUpgradeResponse

Writes the server's 101 response to an opening handshake (§4.2.2) into out from at, allocating nothing: Upgrade, Connection, Sec-WebSocket-Accept with the 28 bytes accept holds, and Sec-WebSocket-Protocol when protocol is not empty. The bytes are those of websocketUpgradeResponse.

const websocketWriteUpgradeResponse: (
  out: u8[],
  at: i32,
  accept: u8[],
  protocol: string,
) => i32
outu8[]required

The buffer the head is written into.

ati32required

Where in out it starts.

acceptu8[]required

The accept value, its 28 characters one a byte: a WsAcceptKey's value.

protocolstringrequired

The subprotocol the server chose from websocketOfferedProtocols, or "" for none.

returnsi32

The index just past the head, HTTP1_REFUSED when protocol is not a token or accept is not 28 bytes, or HTTP1_NO_ROOM when the head does not fit, out unchanged either way.

Classes

WsAcceptKey

The accept key of one handshake after another, in storage the caller keeps: a server builds one per connection and computes every handshake's Sec-WebSocket-Accept into it, allocating nothing after it is built (the fix for H1-3 in docs/security/http1-codec.md).

const accept = new WsAcceptKey();
if (accept.compute(p.head, start, end)) {
  // accept.value[0 .. 28) is the field's value
}
class WsAcceptKey
Member
new WsAcceptKey() Storage for one accept value, its hasher and buffers allocated.
digest: u8[] The SHA-1 of input.
hasher: Sha1 The hasher, its state kept from one handshake to the next.
input: u8[] The key followed by WS_GUID: what is hashed (§4.2.2 item 5.4).
value: u8[] The accept value's 28 characters, one a byte, once compute answers true.
compute(text: u8[], start: i32, end: i32): boolean Computes into value the accept value of the key in text[start .. end) (§4.2.2 item 5.4), when that is a valid key.

WsDecoder

One connection's frame decoder. expectMasked is true on a server, whose client must mask every frame, and false on a client, whose server must mask none (§5.1). maxMessage bounds a message, all its fragments together.

class WsDecoder
Member
new WsDecoder(expectMasked: boolean, maxMessage: i32) A decoder with nothing fed yet.
closeCode: i32 The peer's status code after WS_CLOSE (WS_CLOSE_NO_STATUS when it sent none), or the one to send after WS_ERROR.
closeReason: string The peer's close reason after WS_CLOSE, or what was wrong after WS_ERROR.
data: u8[] The last event's payload is data[0 .. dataLen), valid until the next next().
dataLen: i32 How many bytes of data the last event filled.
expectMasked: boolean Whether every frame must be masked, as a server requires of a client.
maxMessage: i32 The longest message accepted, in bytes; a longer one is refused with 1009.
opcode: i32 The last event's opcode: WS_OP_TEXT or WS_OP_BINARY for a message, the control opcode otherwise.
feed(data: u8[], off: i32, len: i32): void Appends data[off .. off + len) to the input. A window outside data panics; after WS_CLOSE or WS_ERROR the input is dropped.
next(): i32 The next event the input holds; see the module comment.
reset(): void Puts the decoder back as the constructor left it, for the next connection, keeping the buffers it has grown: a slot that is reused allocates nothing to start over.

WsHandshake

websocketCheckResponse's answer: error is a WS_HS_* code; protocol is set when it is WS_HS_OK.

class WsHandshake
Member
new WsHandshake(error: i32, protocol: string) The answer to one handshake check.
error: i32 WS_HS_OK, or the WS_HS_* rule the response broke.
protocol: string The subprotocol the server chose, or "" when it chose none.

Limits

125

WS_MAX_CONTROL: i32

The longest payload a control frame may carry (§5.5).

Constants

4

WS_CLOSE: i32

From now on: the peer closed, with closeCode and closeReason.

1,001

WS_CLOSE_GOING_AWAY: i32

The endpoint is going away: a server shutting down, or a page closed.

1,011

WS_CLOSE_INTERNAL_ERROR: i32

The endpoint met a condition it could not handle.

1,007

WS_CLOSE_INVALID_DATA: i32

A message's data did not fit its type, such as a text message that is not UTF-8.

1,000

WS_CLOSE_NORMAL: i32

The purpose of the connection is fulfilled.

1,005

WS_CLOSE_NO_STATUS: i32

Reported for a close frame with no status; never sent.

1,008

WS_CLOSE_POLICY: i32

A message broke the endpoint's policy, when no other code fits.

1,002

WS_CLOSE_PROTOCOL_ERROR: i32

The peer broke the framing rules.

1,009

WS_CLOSE_TOO_BIG: i32

A message was longer than the endpoint takes.

1,003

WS_CLOSE_UNSUPPORTED: i32

The peer sent a kind of data the endpoint cannot take.

5

WS_ERROR: i32

From now on: the input is refused; close with closeCode.

"258​EAFA5-E914-47​DA-95​CA-C5​AB0​DC85​B11"

WS_GUID: string

The GUID RFC 6455 §1.3 appends to the client's key before hashing it.

5

WS_HS_ACCEPT: i32

Sec-WebSocket-Accept is absent, repeated, or not the key's accept value.

4

WS_HS_CONNECTION: i32

No Connection field lists upgrade.

6

WS_HS_EXTENSION: i32

A Sec-WebSocket-Extensions field, when the client offered none.

0

WS_HS_OK: i32

The server accepted the handshake; protocol is the subprotocol it chose.

7

WS_HS_PROTOCOL: i32

A Sec-WebSocket-Protocol that is repeated, a list, or not one the client offered.

1

WS_HS_STATUS: i32

The status is not 101; the parser's status says what it is. No redirect is followed.

3

WS_HS_UPGRADE: i32

Upgrade is absent, repeated, or not websocket in any case.

2

WS_HS_VERSION: i32

The response is not HTTP/1.1.

1

WS_MESSAGE: i32

A whole text or binary message is in data[0 .. dataLen).

0

WS_NEED_MORE: i32

The input so far holds no further event; feed more.

-1

WS_NO_ROOM: i32

websocketWriteFrame: the frame does not fit at at.

2

WS_OP_BINARY: i32

A binary message.

8

WS_OP_CLOSE: i32

A close frame: an optional status code, then an optional UTF-8 reason.

0

WS_OP_CONTINUATION: i32

A frame that continues the message before it.

9

WS_OP_PING: i32

A ping, which the peer answers with a pong carrying the same payload.

10

WS_OP_PONG: i32

A pong, the answer to a ping or an unasked heartbeat.

1

WS_OP_TEXT: i32

A text message, UTF-8.

2

WS_PING: i32

A ping, its payload in data[0 .. dataLen); answer with a pong carrying it.

3

WS_PONG: i32

A pong, its payload in data[0 .. dataLen).

-2

WS_REFUSED: i32

websocketWriteFrame: a frame the encoder refuses to write.