Skip to content

Open-source Grok Bot alternative with a virtual machine that bots can use

e2e: WebSocket client over one E2E stream (step 3c-2 of #5665)

Bugfixer 2b17af0ce3d5f
diff --git a/src/lib/e2e/http.ts b/src/lib/e2e/http.ts
index 0dbbcb8875..d66fc32004 100644
--- a/src/lib/e2e/http.ts
+++ b/src/lib/e2e/http.ts
@@ -6,12 +6,12 @@ import type { E2EStream } from "./session.ts";
/** Status line plus headers of one reply, the same ceiling Node's HTTP server puts on a request head. */
export const MAX_HEAD = 16 * 1024;
const MAX_CHUNK_LINE = 1024;
-const TOKEN = /^[!#$%&'*+.^_`|~0-9A-Za-z-]+$/;
+export const TOKEN = /^[!#$%&'*+.^_`|~0-9A-Za-z-]+$/;
/** Framing and connection headers this client writes itself; a caller's own would contradict them. */
const OWN = new Set(["host", "connection", "content-length", "transfer-encoding", "upgrade", "keep-alive", "te", "trailer", "accept-encoding"]);
/** Statuses whose Response must have a null body. */
const NULL_BODY = new Set([204, 205, 304]);
-const CRLF2 = [13, 10, 13, 10];
+export const CRLF2 = [13, 10, 13, 10];
export class HttpError extends Error {
constructor(message: string) {
@@ -30,22 +30,28 @@ export interface StreamRequest {
signal?: AbortSignal;
}
-/** The request head, refused before anything is sent when a part could split or reframe the request. */
-export function requestHead(method: string, path: string, headers: Headers, length: number | null): string {
+/** The request line, Host and the caller's headers, refused before anything is sent when a part could split or reframe
+ * the request. The caller adds its own framing and connection lines and the blank line. */
+export function headStart(method: string, path: string, headers: Headers): string {
if (!TOKEN.test(method)) throw new TypeError(`e2e http: bad method ${JSON.stringify(method)}`);
if (!path.startsWith("/") || [...path].some((char) => char <= " " || char === "\x7f")) throw new TypeError("e2e http: path must be origin-form with no spaces or controls");
let head = `${method} ${path} HTTP/1.1\r\nHost: companion\r\n`;
// Headers already refuses names that are not tokens and values with CR, LF or NUL.
for (const [name, value] of headers) {
- if (OWN.has(name)) throw new TypeError(`e2e http: ${name} is set by the stream client`);
+ if (OWN.has(name) || name.startsWith("sec-websocket-")) throw new TypeError(`e2e http: ${name} is set by the stream client`);
head += `${name}: ${value}\r\n`;
}
- if (length !== null) head += `Content-Length: ${length}\r\n`;
- return `${head}Connection: close\r\n\r\n`;
+ return head;
+}
+
+/** The whole head of a plain request. */
+export function requestHead(method: string, path: string, headers: Headers, length: number | null): string {
+ const head = headStart(method, path, headers);
+ return `${head}${length !== null ? `Content-Length: ${length}\r\n` : ""}Connection: close\r\n\r\n`;
}
/** Reads a stream's bytes with the leftover of the last read kept for the next parse. */
-class ByteReader {
+export class ByteReader {
readonly #reader: ReadableStreamDefaultReader<Uint8Array>;
#held: Uint8Array = new Uint8Array(0);
@@ -85,6 +91,14 @@ class ByteReader {
return part;
}
+ /** Exactly `count` bytes as a copy, or null when the stream ends first. */
+ async exact(count: number): Promise<Uint8Array | null> {
+ while (this.#held.length < count) if (!(await this.#more())) return null;
+ const part = this.#held.slice(0, count);
+ this.#held = this.#held.subarray(count);
+ return part;
+ }
+
release(): void {
this.#reader.releaseLock();
}
@@ -105,13 +119,13 @@ const byteString = (bytes: Uint8Array): string => {
return text;
};
-interface Head {
+export interface Head {
status: number;
statusText: string;
headers: Headers;
}
-function parseHead(bytes: Uint8Array): Head {
+export function parseHead(bytes: Uint8Array): Head {
const [statusLine, ...lines] = byteString(bytes).split("\r\n");
const status = /^HTTP\/1\.[01] ([1-5]\d\d)(?: ([^\r\n]*))?$/.exec(statusLine);
if (!status) throw new HttpError("bad status line");
diff --git a/src/lib/e2e/websocket.test.ts b/src/lib/e2e/websocket.test.ts
new file mode 100644
index 0000000000..956f51691a
--- /dev/null
+++ b/src/lib/e2e/websocket.test.ts
@@ -0,0 +1,335 @@
+import { spawn, type ChildProcess } from "node:child_process";
+import { createHash } from "node:crypto";
+import { fileURLToPath } from "node:url";
+import { afterAll, beforeAll, describe, expect, it, vi } from "vitest";
+
+import { concat, fromB64u, utf8 } from "./bytes.ts";
+import { credentialHash, keyId, psk } from "./credentials.ts";
+import { HttpError } from "./http.ts";
+import { dial, type E2EStream, type PhoneSession } from "./session.ts";
+import { streamWebSocket, type StreamSocketClose, type StreamSocketOptions } from "./websocket.ts";
+
+const SERVER = fileURLToPath(new URL("../../../companion/src/e2e/interop-server.ts", import.meta.url));
+
+/** What a socket handed its page: whole messages and the one close. */
+function listener() {
+ const messages: (string | Uint8Array)[] = [];
+ const closes: StreamSocketClose[] = [];
+ return { messages, closes, onMessage: (data: string | Uint8Array) => void messages.push(data), onClose: (event: StreamSocketClose) => void closes.push(event) };
+}
+
+/** A stream the test plays the computer on: reply bytes pushed in by hand, the client's frames read back unmasked. */
+function fakeComputer() {
+ const written: Uint8Array[] = [];
+ const state = { ended: false, reset: false };
+ let source!: ReadableStreamDefaultController<Uint8Array>;
+ const stream: E2EStream = {
+ id: 1,
+ readable: new ReadableStream<Uint8Array>({
+ start(controller) {
+ source = controller;
+ },
+ }),
+ write: async (bytes) => {
+ if (state.ended || state.reset) throw new Error("stream reset");
+ written.push(Uint8Array.from(bytes));
+ },
+ end: () => void (state.ended = true),
+ reset: () => {
+ state.reset = true;
+ try {
+ source.error(new Error("stream reset"));
+ } catch {
+ /* already closed */
+ }
+ },
+ };
+ return {
+ open: () => stream,
+ state,
+ written,
+ push: (bytes: string | Uint8Array) => source.enqueue(typeof bytes === "string" ? utf8(bytes) : bytes),
+ finish: () => source.close(),
+ /** The client's frames after the upgrade request. */
+ frames: () => written.slice(1).map(readClientFrame),
+ };
+}
+
+type Fake = ReturnType<typeof fakeComputer>;
+
+function serverFrame(op: number, payload: Uint8Array | string = new Uint8Array(0), { fin = true, mask = false, rsv = 0 } = {}): Uint8Array {
+ const body = typeof payload === "string" ? utf8(payload) : payload;
+ const size = body.length;
+ const head = size < 126 ? [size] : size < 65_536 ? [126, size >> 8, size & 0xff] : [127, 0, 0, 0, 0, (size >>> 24) & 0xff, (size >> 16) & 0xff, (size >> 8) & 0xff, size & 0xff];
+ head[0] |= mask ? 0x80 : 0;
+ return concat(Uint8Array.of((fin ? 0x80 : 0) | rsv | op, ...head), mask ? Uint8Array.of(0, 0, 0, 0) : new Uint8Array(0), body);
+}
+
+function readClientFrame(bytes: Uint8Array) {
+ const fin = (bytes[0] & 0x80) !== 0;
+ const op = bytes[0] & 0x0f;
+ const masked = (bytes[1] & 0x80) !== 0;
+ let length = bytes[1] & 0x7f;
+ let at = 2;
+ const view = new DataView(bytes.buffer, bytes.byteOffset, bytes.byteLength);
+ if (length === 126) [length, at] = [view.getUint16(2), 4];
+ else if (length === 127) [length, at] = [Number(view.getBigUint64(2)), 10];
+ const mask = bytes.subarray(at, at + 4);
+ const payload = bytes.slice(at + 4, at + 4 + length).map((byte, i) => byte ^ mask[i & 3]);
+ expect(at + 4 + length).toBe(bytes.length);
+ return { fin, op, masked, payload };
+}
+
+const closeCode = (payload: Uint8Array) => (payload[0] << 8) | payload[1];
+
+/** The upgrade request the client wrote, once it is written. */
+async function request(fake: Fake): Promise<{ text: string; key: string }> {
+ await vi.waitFor(() => expect(fake.written.length).toBeGreaterThan(0));
+ const text = new TextDecoder().decode(fake.written[0]);
+ return { text, key: /\r\nSec-WebSocket-Key: (\S+)\r\n/.exec(text)![1] };
+}
+
+const acceptFor = (key: string) => createHash("sha1").update(`${key}258EAFA5-E914-47DA-95CA-C5AB0DC85B11`).digest("base64");
+
+async function switched(fake: Fake, options: Partial<StreamSocketOptions> = {}, extra = "") {
+ const page = listener();
+ const opening = streamWebSocket(fake.open, { path: "/ws", ...page, ...options });
+ const { key } = await request(fake);
+ fake.push(`HTTP/1.1 101 Switching Protocols\r\nUpgrade: websocket\r\nConnection: Upgrade\r\nSec-WebSocket-Accept: ${acceptFor(key)}\r\n${extra}\r\n`);
+ return { socket: await opening, page };
+}
+
+describe("streamWebSocket handshake", () => {
+ it("sends an RFC 6455 upgrade and opens on a matching 101", async () => {
+ const fake = fakeComputer();
+ const page = listener();
+ const opening = streamWebSocket(fake.open, { path: "/ws?x=1", headers: { authorization: "Bearer t" }, protocols: ["a", "b"], ...page });
+ const { text, key } = await request(fake);
+ expect(text).toMatch(/^GET \/ws\?x=1 HTTP\/1\.1\r\nHost: companion\r\nauthorization: Bearer t\r\n/);
+ expect(text).toContain("\r\nConnection: Upgrade\r\nUpgrade: websocket\r\nSec-WebSocket-Version: 13\r\n");
+ expect(text).toContain("\r\nSec-WebSocket-Protocol: a, b\r\n");
+ expect(text.endsWith("\r\n\r\n")).toBe(true);
+ expect(atob(key)).toHaveLength(16);
+ fake.push(`HTTP/1.1 101 Switching Protocols\r\nUpgrade: WebSocket\r\nConnection: keep-alive, Upgrade\r\nSec-WebSocket-Accept: ${acceptFor(key)}\r\nSec-WebSocket-Protocol: b\r\n\r\n`);
+ const socket = await opening;
+ expect(socket.protocol).toBe("b");
+ expect(socket.readyState).toBe("open");
+ expect(fake.state).toEqual({ ended: false, reset: false });
+ });
+
+ it.each([
+ ["a wrong Sec-WebSocket-Accept", (key: string) => `HTTP/1.1 101 x\r\nUpgrade: websocket\r\nConnection: Upgrade\r\nSec-WebSocket-Accept: ${acceptFor(key + "x")}\r\n\r\n`, /Sec-WebSocket-Accept/],
+ ["a plain reply", () => "HTTP/1.1 404 Not Found\r\nContent-Length: 0\r\n\r\n", /answered 404/],
+ ["a switch to something else", (key: string) => `HTTP/1.1 101 x\r\nUpgrade: h2c\r\nConnection: Upgrade\r\nSec-WebSocket-Accept: ${acceptFor(key)}\r\n\r\n`, /not to WebSocket/],
+ ["an extension nobody offered", (key: string) => `HTTP/1.1 101 x\r\nUpgrade: websocket\r\nConnection: Upgrade\r\nSec-WebSocket-Accept: ${acceptFor(key)}\r\nSec-WebSocket-Extensions: permessage-deflate\r\n\r\n`, /extension/],
+ ["a subprotocol nobody offered", (key: string) => `HTTP/1.1 101 x\r\nUpgrade: websocket\r\nConnection: Upgrade\r\nSec-WebSocket-Accept: ${acceptFor(key)}\r\nSec-WebSocket-Protocol: z\r\n\r\n`, /subprotocol "z"/],
+ ])("refuses %s and resets the stream", async (_what, reply, message) => {
+ const fake = fakeComputer();
+ const opening = streamWebSocket(fake.open, { path: "/ws", ...listener() });
+ fake.push(reply((await request(fake)).key));
+ const error = await opening.catch((caught: unknown) => caught);
+ expect(error).toBeInstanceOf(HttpError);
+ expect((error as Error).message).toMatch(message);
+ expect(fake.state.reset).toBe(true);
+ });
+
+ it("refuses a caller's own upgrade headers and bad subprotocols before opening a stream", async () => {
+ const open = vi.fn(() => fakeComputer().open());
+ await expect(streamWebSocket(open, { path: "/ws", headers: { "Sec-WebSocket-Key": "x" }, ...listener() })).rejects.toThrow(TypeError);
+ await expect(streamWebSocket(open, { path: "/ws", protocols: ["a b"], ...listener() })).rejects.toThrow(TypeError);
+ await expect(streamWebSocket(open, { path: "/ws", protocols: ["a", "a"], ...listener() })).rejects.toThrow(TypeError);
+ expect(open).not.toHaveBeenCalled();
+ });
+
+ it("resets the stream and rejects with the reason when aborted during the handshake", async () => {
+ const fake = fakeComputer();
+ const abort = new AbortController();
+ const opening = streamWebSocket(fake.open, { path: "/ws", signal: abort.signal, ...listener() });
+ await request(fake);
+ abort.abort(new Error("gave up"));
+ await expect(opening).rejects.toThrow("gave up");
+ expect(fake.state.reset).toBe(true);
+ });
+});
+
+describe("StreamWebSocket frames", () => {
+ it("masks every client frame and uses the shortest length form", async () => {
+ const fake = fakeComputer();
+ const { socket } = await switched(fake);
+ await socket.send("héllo");
+ await socket.send(new Uint8Array(200).fill(7));
+ await socket.send(new Uint8Array(70_000).fill(9));
+ const frames = fake.frames();
+ expect(frames.map(({ fin, op, masked }) => [fin, op, masked])).toEqual([
+ [true, 1, true],
+ [true, 2, true],
+ [true, 2, true],
+ ]);
+ expect(new TextDecoder().decode(frames[0].payload)).toBe("héllo");
+ expect(fake.written[2][1] & 0x7f).toBe(126);
+ expect(fake.written[3][1] & 0x7f).toBe(127);
+ expect(frames[2].payload.every((byte) => byte === 9)).toBe(true);
+ });
+
+ it("puts fragments back together, answers a ping in between and reads bytes that came with the 101", async () => {
+ const fake = fakeComputer();
+ const page = listener();
+ const opening = streamWebSocket(fake.open, { path: "/ws", ...page });
+ const { key } = await request(fake);
+ const accept = utf8(`HTTP/1.1 101 x\r\nUpgrade: websocket\r\nConnection: Upgrade\r\nSec-WebSocket-Accept: ${acceptFor(key)}\r\n\r\n`);
+ fake.push(concat(accept, serverFrame(2, Uint8Array.of(1, 2, 3))));
+ await opening;
+ // "é" split across two fragments, with a ping between them.
+ const text = utf8("café");
+ fake.push(concat(serverFrame(1, text.subarray(0, 4), { fin: false }), serverFrame(9, "p?"), serverFrame(0, text.subarray(4))));
+ await vi.waitFor(() => expect(page.messages).toHaveLength(2));
+ expect(page.messages).toEqual([Uint8Array.of(1, 2, 3), "café"]);
+ await vi.waitFor(() => expect(fake.frames()).toHaveLength(1));
+ const [pong] = fake.frames();
+ expect(pong.op).toBe(10);
+ expect(new TextDecoder().decode(pong.payload)).toBe("p?");
+ });
+
+ it.each([
+ ["invalid UTF-8 in a text message", serverFrame(1, Uint8Array.of(0xc3, 0x28)), 1007],
+ ["a masked frame from the computer", serverFrame(2, "x", { mask: true }), 1002],
+ ["reserved bits", serverFrame(2, "x", { rsv: 0x40 }), 1002],
+ ["an unknown opcode", serverFrame(3, "x"), 1002],
+ ["a fragmented ping", serverFrame(9, "x", { fin: false }), 1002],
+ ["a continuation with no message", serverFrame(0, "x"), 1002],
+ ["a message over maxMessage", serverFrame(2, new Uint8Array(11)), 1009],
+ ["a close code that may not be sent", serverFrame(8, Uint8Array.of(0x03, 0xed)), 1002],
+ ])("fails the socket on %s: close frame, then FIN, and 1006 for the page", async (_what, frame, code) => {
+ const fake = fakeComputer();
+ const { socket, page } = await switched(fake, { maxMessage: 10 });
+ fake.push(frame);
+ await vi.waitFor(() => expect(page.closes).toHaveLength(1));
+ expect(page.closes[0]).toEqual({ code: 1006, reason: "", wasClean: false });
+ expect(page.messages).toEqual([]);
+ await vi.waitFor(() => expect(fake.state.ended).toBe(true));
+ const frames = fake.frames();
+ expect(frames).toHaveLength(1);
+ expect(frames[0].op).toBe(8);
+ expect(closeCode(frames[0].payload)).toBe(code);
+ expect(socket.readyState).toBe("closed");
+ await expect(socket.send("late")).rejects.toThrow(/closed/);
+ });
+
+ it("answers the computer's close with its code, then ends the stream", async () => {
+ const fake = fakeComputer();
+ const { socket, page } = await switched(fake);
+ fake.push(serverFrame(8, concat(Uint8Array.of(0x03, 0xe9), utf8("going away"))));
+ await vi.waitFor(() => expect(page.closes).toEqual([{ code: 1001, reason: "going away", wasClean: true }]));
+ await vi.waitFor(() => expect(fake.state.ended).toBe(true));
+ expect(fake.frames().map(({ op, payload }) => [op, closeCode(payload), payload.length])).toEqual([[8, 1001, 2]]);
+ expect(socket.readyState).toBe("closed");
+ expect(fake.state.reset).toBe(false);
+ });
+
+ it("reports 1005 for a close frame with no code", async () => {
+ const fake = fakeComputer();
+ const { page } = await switched(fake);
+ fake.push(serverFrame(8));
+ await vi.waitFor(() => expect(page.closes).toEqual([{ code: 1005, reason: "", wasClean: true }]));
+ await vi.waitFor(() => expect(fake.frames().map(({ op, payload }) => [op, payload.length])).toEqual([[8, 0]]));
+ });
+
+ it("close() sends one close frame, refuses later sends and finishes on the computer's answer", async () => {
+ const fake = fakeComputer();
+ const { socket, page } = await switched(fake);
+ socket.close(4000, "done");
+ socket.close(1000);
+ expect(socket.readyState).toBe("closing");
+ await expect(socket.send("late")).rejects.toThrow(/closing/);
+ await vi.waitFor(() => expect(fake.frames()).toHaveLength(1));
+ const [frame] = fake.frames();
+ expect([frame.op, closeCode(frame.payload), new TextDecoder().decode(frame.payload.subarray(2))]).toEqual([8, 4000, "done"]);
+ expect(fake.state.ended).toBe(false);
+ fake.push(serverFrame(8, Uint8Array.of(0x0f, 0xa0)));
+ await vi.waitFor(() => expect(page.closes).toEqual([{ code: 4000, reason: "", wasClean: true }]));
+ await vi.waitFor(() => expect(fake.state.ended).toBe(true));
+ expect(fake.frames()).toHaveLength(1);
+ });
+
+ it("close() refuses codes and reasons a browser refuses", async () => {
+ const { socket } = await switched(fakeComputer());
+ expect(() => socket.close(1001)).toThrow(TypeError);
+ expect(() => socket.close(5000)).toThrow(TypeError);
+ expect(() => socket.close(undefined, "why")).toThrow(TypeError);
+ expect(() => socket.close(1000, "x".repeat(124))).toThrow(TypeError);
+ expect(socket.readyState).toBe("open");
+ });
+
+ it("reports 1006 and resets when the stream ends without a closing handshake", async () => {
+ const fake = fakeComputer();
+ const { socket, page } = await switched(fake);
+ fake.push(serverFrame(2, Uint8Array.of(1)).subarray(0, 2));
+ fake.finish();
+ await vi.waitFor(() => expect(page.closes).toEqual([{ code: 1006, reason: "", wasClean: false }]));
+ expect(fake.state.reset).toBe(true);
+ expect(socket.readyState).toBe("closed");
+ });
+});
+
+describe("streamWebSocket over a real session (interop computer)", () => {
+ let child: ChildProcess;
+ let session: PhoneSession;
+
+ beforeAll(async () => {
+ child = spawn(process.execPath, [SERVER, "--port", "0", "--exit-with-stdin"], { stdio: ["pipe", "pipe", "ignore"] });
+ const ready = await new Promise<{ direct: string; k: string; deviceToken: string }>((resolve, reject) => {
+ const timer = setTimeout(() => reject(new Error("interop server did not say ready in 10 s")), 10_000);
+ let out = "";
+ child.stdout!.on("data", (chunk: Buffer) => {
+ out += chunk.toString();
+ const line = out.split("\n").slice(0, -1).find((candidate) => candidate.startsWith("{"));
+ if (line) {
+ clearTimeout(timer);
+ resolve(JSON.parse(line));
+ }
+ });
+ child.once("error", reject);
+ child.once("exit", (code) => reject(new Error(`interop server exited ${code}`)));
+ });
+ const remoteStatic = fromB64u(ready.k)!;
+ const key = await psk(await credentialHash(ready.deviceToken), await keyId(remoteStatic));
+ session = await dial({ url: ready.direct, remoteStatic, psk: key, app: "web-test/1" });
+ });
+
+ afterAll(() => {
+ session?.close(1000);
+ child?.kill("SIGTERM");
+ });
+
+ it("echoes messages in order, a large one included, and closes cleanly", async () => {
+ const page = listener();
+ const socket = await streamWebSocket(() => session.open(), { path: "/ws", ...page });
+ const big = Uint8Array.from({ length: 1024 * 1024 }, (_, i) => i % 251);
+ await socket.send("hello");
+ await socket.send(Uint8Array.of(0, 1, 2));
+ await socket.send(big);
+ await vi.waitFor(() => expect(page.messages).toHaveLength(3), { timeout: 10_000 });
+ // The interop origin echoes every message as binary.
+ expect(new TextDecoder().decode(page.messages[0] as Uint8Array)).toBe("hello");
+ expect(page.messages[1]).toEqual(Uint8Array.of(0, 1, 2));
+ expect((page.messages[2] as Uint8Array).length).toBe(big.length);
+ expect(page.messages[2]).toEqual(big);
+ socket.close(1000);
+ await vi.waitFor(() => expect(page.closes).toEqual([{ code: 1000, reason: "", wasClean: true }]));
+ });
+
+ it("refuses a path the origin does not upgrade", async () => {
+ await expect(streamWebSocket(() => session.open(), { path: "/nope", ...listener() })).rejects.toThrow(HttpError);
+ });
+
+ it("keeps the session usable for other sockets after one closes", async () => {
+ for (let round = 0; round < 3; round++) {
+ const page = listener();
+ const socket = await streamWebSocket(() => session.open(), { path: "/ws", ...page });
+ await socket.send(`round ${round}`);
+ await vi.waitFor(() => expect(page.messages).toHaveLength(1));
+ socket.close();
+ await vi.waitFor(() => expect(page.closes).toEqual([{ code: 1005, reason: "", wasClean: true }]));
+ }
+ });
+});
diff --git a/src/lib/e2e/websocket.ts b/src/lib/e2e/websocket.ts
new file mode 100644
index 0000000000..3c6be5af48
--- /dev/null
+++ b/src/lib/e2e/websocket.ts
@@ -0,0 +1,271 @@
+// A WebSocket client (RFC 6455) over one E2E stream. The app's live sockets reach the computer's origin the same way its
+// HTTP requests do: the upgrade request and the frames are plain stream bytes (README section 8), so the browser's own
+// WebSocket, which can only dial a URL, cannot be used here.
+import { concat, utf8 } from "./bytes.ts";
+import { ByteReader, CRLF2, HttpError, MAX_HEAD, TOKEN, headStart, parseHead } from "./http.ts";
+import type { E2EStream } from "./session.ts";
+
+const GUID = "258EAFA5-E914-47DA-95CA-C5AB0DC85B11";
+/** Largest message put together when the caller sets no maxMessage. */
+export const MAX_MESSAGE = 16 * 1024 * 1024;
+const OP = { continuation: 0, text: 1, binary: 2, close: 8, ping: 9, pong: 10 } as const;
+const OPCODES = new Set<number>(Object.values(OP));
+const EMPTY = new Uint8Array(0);
+
+export interface StreamSocketClose {
+ /** 1005 when the computer's close frame had no code, 1006 when the socket ended without a closing handshake. */
+ code: number;
+ reason: string;
+ wasClean: boolean;
+}
+
+export interface StreamSocketOptions {
+ /** Origin form: "/ws?x=1". */
+ path: string;
+ headers?: HeadersInit;
+ protocols?: readonly string[];
+ /** Aborts the opening handshake; close() ends an open socket. */
+ signal?: AbortSignal;
+ maxMessage?: number;
+ /** Each whole message: text as a string, binary as bytes. Given up front so no message can arrive before it is set. */
+ onMessage(data: string | Uint8Array): void;
+ /** Called once, however the socket ends. */
+ onClose(event: StreamSocketClose): void;
+}
+
+/** A protocol error from the computer: the socket is failed with this close code. */
+class Failure extends Error {
+ constructor(
+ readonly code: number,
+ message: string,
+ ) {
+ super(message);
+ }
+}
+
+const base64 = (bytes: Uint8Array): string => btoa(String.fromCharCode(...bytes));
+
+/** The close codes a peer may put on the wire (RFC 6455 section 7.4). */
+const wireCode = (code: number): boolean => (code >= 1000 && code <= 1014 && code !== 1004 && code !== 1005 && code !== 1006) || (code >= 3000 && code <= 4999);
+
+/** One masked, unfragmented client frame. */
+export function clientFrame(op: number, payload: Uint8Array): Uint8Array {
+ const size = payload.length;
+ const extra = size < 126 ? 0 : size < 65_536 ? 2 : 8;
+ const out = new Uint8Array(2 + extra + 4 + size);
+ out[0] = 0x80 | op;
+ out[1] = 0x80 | (extra === 0 ? size : extra === 2 ? 126 : 127);
+ const view = new DataView(out.buffer);
+ if (extra === 2) view.setUint16(2, size);
+ if (extra === 8) view.setBigUint64(2, BigInt(size));
+ const mask = crypto.getRandomValues(new Uint8Array(4));
+ out.set(mask, 2 + extra);
+ const start = 2 + extra + 4;
+ for (let i = 0; i < size; i++) out[start + i] = payload[i] ^ mask[i & 3];
+ return out;
+}
+
+const closePayload = (code: number, reason: Uint8Array): Uint8Array => concat(Uint8Array.of(code >> 8, code & 0xff), reason);
+
+const strict = new TextDecoder("utf-8", { fatal: true, ignoreBOM: true });
+
+const decodeText = (bytes: Uint8Array, what: string): string => {
+ try {
+ return strict.decode(bytes);
+ } catch {
+ throw new Failure(1007, `${what} is not UTF-8`);
+ }
+};
+
+export class StreamWebSocket {
+ readonly protocol: string;
+ readonly #stream: E2EStream;
+ readonly #reader: ByteReader;
+ readonly #options: StreamSocketOptions;
+ readonly #maxMessage: number;
+ #state: "open" | "closing" | "closed" = "open";
+ #sending: Promise<void> = Promise.resolve();
+
+ constructor(stream: E2EStream, reader: ByteReader, protocol: string, options: StreamSocketOptions) {
+ this.#stream = stream;
+ this.#reader = reader;
+ this.protocol = protocol;
+ this.#options = options;
+ this.#maxMessage = options.maxMessage ?? MAX_MESSAGE;
+ void this.#read();
+ }
+
+ get readyState(): "open" | "closing" | "closed" {
+ return this.#state;
+ }
+
+ /** Resolves once the frame is handed to the session. Refused once close() was called or the socket ended. */
+ send(data: string | Uint8Array): Promise<void> {
+ if (this.#state !== "open") return Promise.reject(new Error(`e2e websocket: the socket is ${this.#state}`));
+ return typeof data === "string" ? this.#send(OP.text, utf8(data)) : this.#send(OP.binary, data);
+ }
+
+ /** Starts the closing handshake, as the browser's close(): no code, 1000 or 3000-4999, reason up to 123 bytes. */
+ close(code?: number, reason = ""): void {
+ if (code !== undefined && code !== 1000 && !(Number.isInteger(code) && code >= 3000 && code <= 4999)) throw new TypeError(`e2e websocket: close code ${code} cannot be sent`);
+ const why = utf8(reason);
+ if (why.length > 123) throw new TypeError("e2e websocket: close reason is over 123 bytes");
+ if (why.length && code === undefined) throw new TypeError("e2e websocket: a close reason needs a code");
+ if (this.#state !== "open") return;
+ this.#state = "closing";
+ this.#control(OP.close, code === undefined ? EMPTY : closePayload(code, why));
+ }
+
+ /** Frames go out in call order; a failed write leaves the chain rejected, so later sends fail too. */
+ #send(op: number, payload: Uint8Array): Promise<void> {
+ const frame = clientFrame(op, payload);
+ this.#sending = this.#sending.then(() => this.#stream.write(frame));
+ return this.#sending;
+ }
+
+ /** A frame nobody waits on: a failed write shows up as the stream's end instead. */
+ #control(op: number, payload: Uint8Array): void {
+ this.#send(op, payload).catch(() => {});
+ }
+
+ async #read(): Promise<void> {
+ try {
+ await this.#frames();
+ } catch (error) {
+ if (!(error instanceof Failure)) {
+ this.#stream.reset();
+ return this.#finish({ code: 1006, reason: "", wasClean: false });
+ }
+ // Fail the connection: tell the computer why, then end the stream. The page sees 1006, as a browser reports it.
+ if (this.#state === "open") this.#control(OP.close, closePayload(error.code, utf8(error.message.slice(0, 123))));
+ this.#end();
+ this.#finish({ code: 1006, reason: "", wasClean: false });
+ }
+ // Read on to the end of the stream so it is not reset under the computer.
+ try {
+ while (await this.#reader.some(64 * 1024)) { /* after the close frame */ }
+ } catch {
+ /* the stream ended either way */
+ }
+ }
+
+ /** FIN once every queued frame is handed to the session, so the closing frame goes before it. */
+ #end(): void {
+ void this.#sending.then(
+ () => this.#stream.end(),
+ () => this.#stream.reset(),
+ );
+ }
+
+ /** Reads frames until the closing handshake; throws a Failure for a protocol error, anything else when the stream ends. */
+ async #frames(): Promise<void> {
+ let kind: number = OP.continuation;
+ let parts: Uint8Array[] = [];
+ let size = 0;
+ for (;;) {
+ const head = await this.#need(2);
+ const fin = (head[0] & 0x80) !== 0;
+ const op = head[0] & 0x0f;
+ if (head[0] & 0x70) throw new Failure(1002, "reserved bits are set");
+ if (head[1] & 0x80) throw new Failure(1002, "the computer masked a frame");
+ if (!OPCODES.has(op)) throw new Failure(1002, `unknown opcode ${op}`);
+ let length = head[1] & 0x7f;
+ if (length === 126) {
+ length = new DataView((await this.#need(2)).buffer).getUint16(0);
+ if (length < 126) throw new Failure(1002, "a length that is not in its shortest form");
+ } else if (length === 127) {
+ const long = new DataView((await this.#need(8)).buffer).getBigUint64(0);
+ if (long < 65_536n || long > BigInt(Number.MAX_SAFE_INTEGER)) throw new Failure(1002, "a length that is not in its shortest form or too large");
+ length = Number(long);
+ }
+ const control = op >= OP.close;
+ if (control && (!fin || length > 125)) throw new Failure(1002, "a control frame that is fragmented or over 125 bytes");
+ if (!control && size + length > this.#maxMessage) throw new Failure(1009, `a message over ${this.#maxMessage} bytes`);
+ const payload = length ? await this.#need(length) : EMPTY;
+
+ if (op === OP.ping) {
+ if (this.#state === "open") this.#control(OP.pong, payload);
+ continue;
+ }
+ if (op === OP.pong) continue;
+ if (op === OP.close) return this.#closeFrame(payload);
+
+ if (op === OP.continuation ? kind === OP.continuation : kind !== OP.continuation) throw new Failure(1002, op === OP.continuation ? "a continuation with no message" : "a new message inside a fragmented one");
+ if (op !== OP.continuation) kind = op;
+ parts.push(payload);
+ size += length;
+ if (!fin) continue;
+ const whole = parts.length === 1 ? parts[0] : concat(...parts);
+ const message = kind === OP.text ? decodeText(whole, "a text message") : whole;
+ kind = OP.continuation;
+ parts = [];
+ size = 0;
+ try {
+ this.#options.onMessage(message);
+ } catch (error) {
+ // A throwing handler is the page's bug, not the computer's: report it and keep the socket, as a browser does.
+ queueMicrotask(() => {
+ throw error;
+ });
+ }
+ }
+ }
+
+ async #need(count: number): Promise<Uint8Array> {
+ const bytes = await this.#reader.exact(count);
+ if (!bytes) throw new Error("the stream ended without a closing handshake");
+ return bytes;
+ }
+
+ #closeFrame(payload: Uint8Array): void {
+ if (payload.length === 1) throw new Failure(1002, "a close frame with a one-byte body");
+ const code = payload.length ? (payload[0] << 8) | payload[1] : 1005;
+ if (payload.length && !wireCode(code)) throw new Failure(1002, `close code ${code} is not allowed on the wire`);
+ const reason = decodeText(payload.subarray(2), "the close reason");
+ // Answer the computer's close with its code, unless this side already sent one.
+ if (this.#state === "open") this.#control(OP.close, payload.length ? closePayload(code, EMPTY) : EMPTY);
+ this.#end();
+ this.#finish({ code, reason, wasClean: true });
+ }
+
+ #finish(event: StreamSocketClose): void {
+ if (this.#state === "closed") return;
+ this.#state = "closed";
+ this.#options.onClose(event);
+ }
+}
+
+/** Opens a WebSocket on a fresh stream from `open`. Resolves once the computer switched protocols. */
+export async function streamWebSocket(open: () => E2EStream, options: StreamSocketOptions): Promise<StreamWebSocket> {
+ const protocols = options.protocols ?? [];
+ if (protocols.some((protocol) => !TOKEN.test(protocol)) || new Set(protocols).size !== protocols.length) throw new TypeError("e2e websocket: bad subprotocol list");
+ const key = base64(crypto.getRandomValues(new Uint8Array(16)));
+ let head = headStart("GET", options.path, new Headers(options.headers));
+ head += `Connection: Upgrade\r\nUpgrade: websocket\r\nSec-WebSocket-Version: 13\r\nSec-WebSocket-Key: ${key}\r\n`;
+ if (protocols.length) head += `Sec-WebSocket-Protocol: ${protocols.join(", ")}\r\n`;
+ head += "\r\n";
+ const accept = base64(new Uint8Array(await crypto.subtle.digest("SHA-1", utf8(key + GUID))));
+ const signal = options.signal;
+ signal?.throwIfAborted();
+
+ const stream = open();
+ const reader = new ByteReader(stream.readable);
+ const abort = () => stream.reset();
+ signal?.addEventListener("abort", abort, { once: true });
+ try {
+ const [, reply] = await Promise.all([stream.write(utf8(head)), reader.until(CRLF2, MAX_HEAD, "reply head").then(parseHead)]);
+ if (reply.status !== 101) throw new HttpError(`the computer answered ${reply.status} instead of switching to WebSocket`);
+ const connection = (reply.headers.get("connection") ?? "").toLowerCase().split(",");
+ if (reply.headers.get("upgrade")?.toLowerCase() !== "websocket" || !connection.some((token) => token.trim() === "upgrade")) throw new HttpError("the switch is not to WebSocket");
+ if (reply.headers.get("sec-websocket-accept") !== accept) throw new HttpError("wrong Sec-WebSocket-Accept");
+ if (reply.headers.has("sec-websocket-extensions")) throw new HttpError("the computer chose an extension that was not offered");
+ const chosen = reply.headers.get("sec-websocket-protocol");
+ if (chosen !== null && !protocols.includes(chosen)) throw new HttpError(`the computer chose subprotocol ${JSON.stringify(chosen)}, which was not offered`);
+ return new StreamWebSocket(stream, reader, chosen ?? "", options);
+ } catch (error) {
+ stream.reset();
+ throw signal?.aborted ? signal.reason : error;
+ } finally {
+ signal?.removeEventListener("abort", abort);
+ }
+}