Skip to content

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

Phone web app: browser E2E session client over the relay or a direct route

Bugfixer 27728b900c5fb
diff --git a/src/lib/e2e/session.test.ts b/src/lib/e2e/session.test.ts
new file mode 100644
index 0000000000..fcc45c9506
--- /dev/null
+++ b/src/lib/e2e/session.test.ts
@@ -0,0 +1,275 @@
+import { spawn, type ChildProcess } from "node:child_process";
+import { createHash } from "node:crypto";
+import { createServer } from "node:http";
+import type { AddressInfo } from "node:net";
+import { fileURLToPath } from "node:url";
+import { afterAll, beforeAll, describe, expect, it } from "vitest";
+import { WebSocket as NodeWebSocket, WebSocketServer, type RawData } from "ws";
+
+import { b64u, concat, fromB64u, utf8, type Bytes } from "./bytes.ts";
+import { admission, credentialHash, keyId, psk } from "./credentials.ts";
+import { dial, dialRelay, RELAY_PROTOCOL, SessionClosed, type E2EStream, type PhoneSession } from "./session.ts";
+
+const SERVER = fileURLToPath(new URL("../../../companion/src/e2e/interop-server.ts", import.meta.url));
+const BOUND_MS = 10_000;
+const HOST_ID = Uint8Array.from({ length: 16 }, (_, i) => i + 1);
+
+interface Ready {
+ direct: string;
+ relayTransport: string;
+ wrongKey: string;
+ k: string;
+ deviceToken: string;
+ pairingToken: string;
+}
+
+let child: ChildProcess;
+let ready: Ready;
+let remoteStatic: Bytes;
+
+/** A relay node for tests, phone side of README section 9 only: one text message first, then 4404 unless it names the
+ * test host with an admitted `adm`; otherwise it dials the computer, answers ready, and splices binary both ways. */
+interface RelayNode {
+ url: string;
+ /** What phones sent before ready. */
+ firstMessages: unknown[];
+ /** Codes this node closed phones with, in order. */
+ closes: number[];
+ admitted: Set<string>;
+ /** Refuse every phone with this code, as a full (4503) or rate-limiting (4429) node would. */
+ refuseWith: number | null;
+ /** Answer ready but never splice, so the handshake deadline passes. */
+ stall: boolean;
+ /** Drop everything the computer sends from now on, as a dead path would. */
+ mute: boolean;
+ close(): Promise<void>;
+}
+
+const nodes: RelayNode[] = [];
+
+async function startNode(): Promise<RelayNode> {
+ const server = createServer((_req, res) => res.writeHead(404).end());
+ const wss = new WebSocketServer({ server, maxPayload: 70_000, handleProtocols: (offered) => (offered.has(RELAY_PROTOCOL) ? RELAY_PROTOCOL : false) });
+ const node: RelayNode = {
+ url: "",
+ firstMessages: [],
+ closes: [],
+ admitted: new Set(),
+ refuseWith: null,
+ stall: false,
+ mute: false,
+ close: () =>
+ new Promise((resolve) => {
+ for (const client of wss.clients) client.terminate();
+ wss.close();
+ server.close(() => resolve());
+ }),
+ };
+ const refuse = (socket: NodeWebSocket, code: number) => {
+ node.closes.push(code);
+ socket.close(code);
+ };
+ wss.on("connection", (phone) => {
+ if (node.refuseWith !== null) return refuse(phone, node.refuseWith);
+ phone.once("message", (raw: RawData, isBinary: boolean) => {
+ if (isBinary) return refuse(phone, 4400);
+ let first: { t?: unknown; v?: unknown; hid?: unknown; adm?: unknown };
+ try {
+ first = JSON.parse(String(raw)) as typeof first;
+ } catch {
+ return refuse(phone, 4400);
+ }
+ node.firstMessages.push(first);
+ if (first.t !== "phone" || first.v !== 1) return refuse(phone, 4400);
+ if (first.hid !== b64u(HOST_ID) || !node.admitted.has(String(first.adm))) return refuse(phone, 4404);
+ if (node.stall) return void phone.send(JSON.stringify({ t: "ready" }));
+ const data = new NodeWebSocket(ready.relayTransport, "omb-e2e.v1");
+ data.on("open", () => {
+ phone.send(JSON.stringify({ t: "ready" }));
+ phone.on("message", (bytes: RawData, binary: boolean) => (binary ? data.send(bytes as Buffer) : refuse(phone, 4400)));
+ data.on("message", (bytes: RawData) => {
+ if (!node.mute && phone.readyState === NodeWebSocket.OPEN) phone.send(bytes as Buffer);
+ });
+ });
+ // Close codes pass through, as the real relay's splice does.
+ const passClose = (to: NodeWebSocket) => (code: number) => {
+ if (to.readyState === NodeWebSocket.OPEN) to.close(code >= 3000 ? code : 1000);
+ };
+ data.on("close", passClose(phone));
+ phone.on("close", passClose(data));
+ data.on("error", () => phone.terminate());
+ });
+ });
+ await new Promise<void>((resolve) => server.listen(0, "127.0.0.1", () => resolve()));
+ node.url = `ws://127.0.0.1:${(server.address() as AddressInfo).port}/v1/phone`;
+ nodes.push(node);
+ return node;
+}
+
+beforeAll(async () => {
+ child = spawn(process.execPath, [SERVER, "--port", "0", "--exit-with-stdin"], { stdio: ["pipe", "pipe", "ignore"] });
+ ready = await new Promise<Ready>((resolve, reject) => {
+ const timer = setTimeout(() => reject(new Error("interop server did not say ready in 10 s")), BOUND_MS);
+ 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) as Ready);
+ }
+ });
+ child.once("error", reject);
+ child.once("exit", (code) => reject(new Error(`interop server exited ${code}`)));
+ });
+ remoteStatic = fromB64u(ready.k)!;
+});
+
+afterAll(async () => {
+ await Promise.all(nodes.map((node) => node.close()));
+ child?.kill("SIGTERM");
+});
+
+async function credentials(token: string) {
+ const credHash = await credentialHash(token);
+ return { psk: await psk(credHash, await keyId(remoteStatic)), adm: await admission(credHash, HOST_ID) };
+}
+
+/** A node that admits the pairing token, and what a phone paired with that token dials it with. */
+async function admittingNode() {
+ const node = await startNode();
+ const { psk: key, adm } = await credentials(ready.pairingToken);
+ node.admitted.add(b64u(adm));
+ return { node, options: { hostId: HOST_ID, adm, remoteStatic, psk: key, app: "web-test/1" } };
+}
+
+async function readAll(stream: E2EStream): Promise<Bytes> {
+ const chunks: Uint8Array[] = [];
+ const reader = stream.readable.getReader();
+ for (;;) {
+ const { done, value } = await reader.read();
+ if (done) return concat(...chunks);
+ chunks.push(value);
+ }
+}
+
+/** Like an HTTP client: no half close while the reply comes (Node's HTTP server cuts a reply short on one). */
+async function request(session: PhoneSession, head: string, body?: Bytes): Promise<Bytes> {
+ const stream = session.open();
+ await stream.write(utf8(head));
+ if (body) await stream.write(body);
+ const reply = await readAll(stream);
+ stream.end();
+ return reply;
+}
+
+const text = (bytes: Uint8Array) => new TextDecoder().decode(bytes);
+const health = async (session: PhoneSession) => text(await request(session, "GET /api/health HTTP/1.1\r\nHost: companion\r\nConnection: close\r\n\r\n"));
+
+describe("dialRelay: the browser phone through a relay node", () => {
+ it("sends the pre-auth message, waits for ready, handshakes with the relay prologue and carries requests", async () => {
+ const { node, options } = await admittingNode();
+ const adm = b64u(options.adm);
+ const dialing = dialRelay({ ...options, urls: [node.url] });
+ options.adm.fill(0);
+ const session = await dialing;
+ expect(node.firstMessages).toEqual([{ t: "phone", v: 1, hid: b64u(HOST_ID), adm }]);
+ for (const reply of await Promise.all([health(session), health(session)])) {
+ expect(reply.startsWith("HTTP/1.1 200")).toBe(true);
+ expect(reply).toContain('{"ok":true}');
+ }
+ expect(session.state).toBe("open");
+ session.shutdown();
+ expect(await session.closed).toBe(1000);
+ });
+
+ it("moves more than a stream window each way", async () => {
+ const { node, options } = await admittingNode();
+ const session = await dialRelay({ ...options, urls: [node.url] });
+ const body = new Uint8Array(5 * 1024 * 1024 + 7);
+ for (let offset = 0; offset < body.length; offset += 65_536) crypto.getRandomValues(body.subarray(offset, offset + 65_536));
+ const sha256 = createHash("sha256").update(body).digest("hex");
+ const [upload, download] = await Promise.all([
+ request(session, `POST /upload HTTP/1.1\r\nHost: companion\r\nContent-Length: ${body.length}\r\nConnection: close\r\n\r\n`, body),
+ request(session, `GET /bytes?n=${body.length} HTTP/1.1\r\nHost: companion\r\nConnection: close\r\n\r\n`),
+ ]);
+ expect(text(upload)).toContain(JSON.stringify({ bytes: body.length, sha256 }));
+ expect(text(download.subarray(0, 12))).toBe("HTTP/1.1 200");
+ expect(download.length).toBeGreaterThan(body.length);
+ session.shutdown();
+ });
+
+ it("tries the next node on 4503 and on 4404, and keeps the last code when every node refuses", async () => {
+ const full = await startNode();
+ full.refuseWith = 4503;
+ const stranger = await startNode();
+ const { node, options } = await admittingNode();
+ const session = await dialRelay({ ...options, urls: [full.url, stranger.url, node.url] });
+ expect(full.closes).toEqual([4503]);
+ expect(stranger.closes).toEqual([4404]);
+ expect((await health(session)).startsWith("HTTP/1.1 200")).toBe(true);
+ session.shutdown();
+
+ const failure = dialRelay({ ...options, urls: [full.url, stranger.url] });
+ await expect(failure).rejects.toBeInstanceOf(SessionClosed);
+ await expect(failure).rejects.toMatchObject({ code: 4404 });
+ });
+
+ it("does not try another node after any other code", async () => {
+ const strict = await startNode();
+ strict.refuseWith = 4429;
+ const { node, options } = await admittingNode();
+ await expect(dialRelay({ ...options, urls: [strict.url, node.url] })).rejects.toMatchObject({ code: 4429 });
+ expect(node.firstMessages).toEqual([]);
+ });
+
+ it("is refused with 4001 when the computer does not know the token", async () => {
+ const { node, options } = await admittingNode();
+ const wrong = await credentials("not-a-token-the-computer-knows");
+ await expect(dialRelay({ ...options, psk: wrong.psk, urls: [node.url] })).rejects.toMatchObject({ code: 4001 });
+ });
+
+ it("gives up with 4002 when the handshake does not finish in time", async () => {
+ const { node, options } = await admittingNode();
+ node.stall = true;
+ await expect(dialRelay({ ...options, urls: [node.url], timeoutMs: 200 })).rejects.toMatchObject({ code: 4002 });
+ });
+
+ it("closes the session with 1001 when a ping goes unanswered", async () => {
+ const { node, options } = await admittingNode();
+ const session = await dialRelay({ ...options, urls: [node.url], pingIntervalMs: 20, pingTimeoutMs: 100 });
+ // Pings are answered while the path is alive.
+ await new Promise((resolve) => setTimeout(resolve, 200));
+ expect(session.state).toBe("open");
+ node.mute = true;
+ expect(await session.closed).toBe(1001);
+ });
+});
+
+describe("dial: the direct route", () => {
+ it("handshakes with the direct prologue and no pre-auth message", async () => {
+ const { psk: key } = await credentials(ready.deviceToken);
+ const session = await dial({ url: ready.direct, remoteStatic, psk: key, app: "web-test/1" });
+ expect((await health(session)).startsWith("HTTP/1.1 200")).toBe(true);
+ session.close(1000);
+ expect(await session.closed).toBe(1000);
+ });
+
+ it("stops hard on a message 2 from a party without the key", async () => {
+ const { psk: key } = await credentials(ready.deviceToken);
+ await expect(dial({ url: ready.wrongKey, remoteStatic, psk: key, app: "web-test/1" })).rejects.toThrow("e2e: aead");
+ });
+
+ it("resets open streams when the session closes, and opens no more", async () => {
+ const { psk: key } = await credentials(ready.deviceToken);
+ const session = await dial({ url: ready.direct, remoteStatic, psk: key, app: "web-test/1" });
+ const stream = session.open();
+ const reader = stream.readable.getReader();
+ await stream.write(utf8("GET /hang HTTP/1.1\r\nHost: companion\r\n\r\n"));
+ expect(text((await reader.read()).value!)).toContain("data: start");
+ session.close(1000);
+ await expect(reader.read()).rejects.toThrow("stream reset");
+ await expect(stream.write(utf8("more"))).rejects.toThrow("stream reset");
+ expect(() => session.open()).toThrow(SessionClosed);
+ });
+});
diff --git a/src/lib/e2e/session.ts b/src/lib/e2e/session.ts
new file mode 100644
index 0000000000..2de710ce6d
--- /dev/null
+++ b/src/lib/e2e/session.ts
@@ -0,0 +1,451 @@
+// The phone side of one encrypted session in the browser (companion/src/e2e/README.md sections 6-12): the WebSocket to
+// a relay node or a direct route, the handshake, then records carrying yamux frames. Each stream is a raw byte pipe to
+// the computer's origin; the HTTP on top comes later.
+import { b64u, type Bytes } from "./bytes.ts";
+import { encodePayload1, newConn, NoiseError, phoneHello, TRANSPORT_DIRECT, TRANSPORT_RELAY, type SessionKeys } from "./noise.ts";
+import { decodeFrame, encodeFrame, GO_AWAY, Mux, PING_INTERVAL_MS, PING_TIMEOUT_MS, YamuxError, type Frame } from "./yamux.ts";
+
+export const DIRECT_PROTOCOL = "omb-e2e.v1";
+export const RELAY_PROTOCOL = "omb-relay.v1";
+
+export const CLOSE = {
+ normal: 1000,
+ goingAway: 1001,
+ protocol: 4000,
+ rejected: 4001,
+ deadline: 4002,
+ relayBadMessage: 4400,
+ relayNotHere: 4404,
+ relayBusy: 4503,
+} as const;
+
+export const HANDSHAKE_DEADLINE_MS = 10_000;
+/** The relay adds a hop and the host's data socket: its attempt gets this much more. */
+const RELAY_EXTRA_MS = 10_000;
+/** A sender stops writing records while the socket holds more than this. */
+export const SEND_BUFFER_HIGH = 1024 * 1024;
+/** The browser WebSocket has no drain event, so a congested writer checks this often. */
+const DRAIN_POLL_MS = 5;
+/** The readable side holds this much before the computer is told to wait. */
+const READ_HIGH_WATER = 256 * 1024;
+
+export class SessionClosed extends Error {
+ readonly code: number;
+ constructor(code: number) {
+ super(`e2e session closed (${code})`);
+ this.code = code;
+ }
+}
+
+/** Codes a browser may send; any other closes without one. */
+const sendable = (code: number) => code === 1000 || (code >= 3000 && code <= 4999);
+const closeSocket = (socket: WebSocket, code: number) => (sendable(code) ? socket.close(code) : socket.close());
+
+interface Timers {
+ pingIntervalMs?: number;
+ pingTimeoutMs?: number;
+}
+
+export interface DialOptions extends Timers {
+ /** `ws://host:port/v1/e2e` for Wi-Fi and Tailscale, `wss://relayN.openmausbot.com/v1/phone` for the relay. */
+ url: string;
+ /** The pinned transport key `T.pub`. */
+ remoteStatic: Bytes;
+ psk: Bytes;
+ app: string;
+ /** The relay route: sent before the handshake, which then uses the relay prologue. */
+ relay?: { hostId: Bytes; adm: Bytes };
+ /** The whole attempt, handshake included: 10 s direct, 20 s through the relay. */
+ timeoutMs?: number;
+}
+
+export interface RelayDialOptions extends Omit<DialOptions, "url" | "relay"> {
+ /** The relay nodes' phone URLs, best first. */
+ urls: readonly string[];
+ hostId: Bytes;
+ adm: Bytes;
+}
+
+/** One stream: the computer's origin answers what is written. */
+export interface E2EStream {
+ readonly id: number;
+ /** Errors with "stream reset" on RST or when the session closes. Cancelling it resets the stream. */
+ readonly readable: ReadableStream<Uint8Array>;
+ /** Resolves once every byte is handed to the session; rejects if the stream is reset first. */
+ write(bytes: Uint8Array): Promise<void>;
+ /** No more writes: FIN after what is already written. */
+ end(): void;
+ reset(): void;
+}
+
+/** Rejects with SessionClosed (the close code) or a NoiseError (a hard stop: the computer could not be verified). */
+export function dial(options: DialOptions): Promise<PhoneSession> {
+ const { relay } = options;
+ const hello = phoneHello(
+ { remoteStatic: options.remoteStatic, psk: options.psk, transport: relay ? TRANSPORT_RELAY : TRANSPORT_DIRECT },
+ encodePayload1(newConn(), options.app),
+ );
+ // A bad key or psk is reported when message 1 is due; until then the rejection is held here.
+ hello.catch(() => {});
+ // Read at the call, like every other option, so later changes to the caller's bytes don't reach the wire.
+ const preAuth = relay && JSON.stringify({ t: "phone", v: 1, hid: b64u(relay.hostId), adm: b64u(relay.adm) });
+ const socket = new WebSocket(options.url, [relay ? RELAY_PROTOCOL : DIRECT_PROTOCOL]);
+ socket.binaryType = "arraybuffer";
+ return new Promise((resolve, reject) => {
+ let stage: "connecting" | "relay" | "message2" | "finishing" | "done" = "connecting";
+ /** Records that arrive while message 2 is checked go to the session in order. */
+ const early: MessageEvent[] = [];
+ const fail = (error: Error, code?: number) => {
+ if (stage === "done") return;
+ stage = "done";
+ clearTimeout(timer);
+ reject(error);
+ if (code !== undefined) closeSocket(socket, code);
+ };
+ const timer = setTimeout(
+ () => fail(new SessionClosed(CLOSE.deadline), CLOSE.deadline),
+ options.timeoutMs ?? HANDSHAKE_DEADLINE_MS + (relay ? RELAY_EXTRA_MS : 0),
+ );
+ const sendMessage1 = () => {
+ stage = "message2";
+ hello.then(
+ (started) => {
+ if (stage === "message2") socket.send(started.message1);
+ },
+ (error: Error) => fail(error, CLOSE.normal),
+ );
+ };
+ socket.onopen = () => {
+ if (!preAuth) return sendMessage1();
+ stage = "relay";
+ socket.send(preAuth);
+ };
+ socket.onmessage = (event: MessageEvent) => {
+ if (stage === "relay") {
+ // Before the handshake, only the relay's ready.
+ if (typeof event.data === "string" && isReady(event.data)) return sendMessage1();
+ return fail(new SessionClosed(CLOSE.relayBadMessage), CLOSE.normal);
+ }
+ if (stage === "finishing") return void early.push(event);
+ if (stage !== "message2" || typeof event.data === "string") return fail(new SessionClosed(CLOSE.protocol), CLOSE.protocol);
+ stage = "finishing";
+ hello
+ .then((started) => started.finish(new Uint8Array(event.data as ArrayBuffer)))
+ .then(
+ (keys) => {
+ if (stage !== "finishing") return;
+ stage = "done";
+ clearTimeout(timer);
+ const session = new PhoneSession(socket, keys, options);
+ for (const message of early) session.receive(message);
+ resolve(session);
+ },
+ (error: Error) => fail(error, CLOSE.protocol),
+ );
+ };
+ socket.onclose = (event: CloseEvent) => fail(new SessionClosed(event.code));
+ socket.onerror = () => {};
+ });
+}
+
+function isReady(text: string): boolean {
+ try {
+ return (JSON.parse(text) as { t?: unknown } | null)?.t === "ready";
+ } catch {
+ return false;
+ }
+}
+
+/** Tries each node in order. 4404 (not connected or not admitted here) and 4503 (full or restarting) move on to the
+ * next; any other failure, or the last node's, is the caller's to back off from. */
+export async function dialRelay(options: RelayDialOptions): Promise<PhoneSession> {
+ const { urls, hostId, adm, ...rest } = options;
+ let last: unknown = new SessionClosed(CLOSE.relayNotHere);
+ for (const url of urls) {
+ try {
+ return await dial({ ...rest, url, relay: { hostId, adm } });
+ } catch (error) {
+ if (!(error instanceof SessionClosed) || (error.code !== CLOSE.relayNotHere && error.code !== CLOSE.relayBusy)) throw error;
+ last = error;
+ }
+ }
+ throw last;
+}
+
+interface PendingWrite {
+ bytes: Uint8Array;
+ resolve(): void;
+ reject(error: Error): void;
+}
+
+class Stream implements E2EStream {
+ readonly id: number;
+ readonly readable: ReadableStream<Uint8Array>;
+ readonly #session: PhoneSession;
+ #controller!: ReadableStreamDefaultController<Uint8Array>;
+ #writes: PendingWrite[] = [];
+ #ending = false;
+ #finSent = false;
+ #remoteEnded = false;
+ #done = false;
+ /** Delivered but not yet granted back, because the reader is behind. */
+ #ungranted = 0;
+
+ constructor(session: PhoneSession, id: number) {
+ this.#session = session;
+ this.id = id;
+ this.readable = new ReadableStream<Uint8Array>(
+ {
+ start: (controller) => {
+ this.#controller = controller;
+ },
+ pull: () => {
+ if (this.#ungranted === 0) return;
+ const bytes = this.#ungranted;
+ this.#ungranted = 0;
+ this.#session.mux?.consumed(this.id, bytes);
+ },
+ cancel: () => this.reset(),
+ },
+ { highWaterMark: READ_HIGH_WATER, size: (chunk) => chunk.byteLength },
+ );
+ }
+
+ write(bytes: Uint8Array): Promise<void> {
+ if (this.#done || this.#ending) return Promise.reject(new Error(this.#done ? "stream reset" : "stream ended"));
+ return new Promise((resolve, reject) => {
+ this.#writes.push({ bytes: bytes.slice(), resolve, reject });
+ this.flush();
+ });
+ }
+
+ end(): void {
+ if (this.#done || this.#ending) return;
+ this.#ending = true;
+ this.flush();
+ }
+
+ reset(): void {
+ const mux = this.#session.mux;
+ if (mux?.has(this.id)) mux.reset(this.id);
+ this.remoteReset();
+ }
+
+ /** Granted back as the reader takes it, so a slow reader slows the computer. */
+ deliver(data: Uint8Array): void {
+ if (this.#done) return;
+ this.#controller.enqueue(data.slice());
+ if ((this.#controller.desiredSize ?? 0) > 0) this.#session.mux?.consumed(this.id, data.length);
+ else this.#ungranted += data.length;
+ }
+
+ remoteEnded(): void {
+ if (this.#done) return;
+ this.#remoteEnded = true;
+ this.#controller.close();
+ this.#forgetIfDone();
+ }
+
+ /** Both FINs seen: the mux has dropped the stream without an event, so the session drops it too. */
+ #forgetIfDone(): void {
+ if (!this.#finSent || !this.#remoteEnded) return;
+ this.#done = true;
+ this.#session.forget(this.id);
+ }
+
+ remoteReset(): void {
+ if (this.#done) return;
+ this.#done = true;
+ this.#session.forget(this.id);
+ const error = new Error("stream reset");
+ try {
+ this.#controller.error(error);
+ } catch {
+ // Already closed by the computer's FIN: nothing more to read either way.
+ }
+ for (const pending of this.#writes.splice(0)) pending.reject(error);
+ }
+
+ flush(): void {
+ const mux = this.#session.mux;
+ while (!this.#done && this.#writes.length > 0) {
+ if (!mux?.has(this.id)) return this.remoteReset();
+ if (this.#session.congested) return this.#session.whenDrained(() => this.flush());
+ const head = this.#writes[0];
+ const taken = mux.write(this.id, head.bytes);
+ if (taken === 0 && head.bytes.length > 0) return;
+ head.bytes = head.bytes.subarray(taken);
+ if (head.bytes.length > 0) continue;
+ this.#writes.shift();
+ head.resolve();
+ }
+ if (!this.#done && this.#ending && this.#writes.length === 0 && mux?.has(this.id)) {
+ this.#ending = false;
+ this.#finSent = true;
+ mux.finish(this.id);
+ this.#forgetIfDone();
+ }
+ }
+}
+
+type State = "open" | "closed";
+
+/** An open session. Built by dial() once message 2 checks out. */
+export class PhoneSession {
+ readonly #socket: WebSocket;
+ readonly #keys: SessionKeys;
+ readonly #mux: Mux;
+ readonly #streams = new Map<number, Stream>();
+ #state: State = "open";
+ /** Records not yet sealed, which the socket's buffered amount does not count yet. */
+ #unsealed = 0;
+ #sending: Promise<void> = Promise.resolve();
+ #pingTimer: ReturnType<typeof setInterval>;
+ #pongTimer: ReturnType<typeof setTimeout> | null = null;
+ #awaitingPong: number | null = null;
+ #pingCounter = 0;
+ #drainWaiters: Array<() => void> = [];
+ #removed = false;
+ #settleClosed!: (code: number) => void;
+ readonly closed: Promise<number>;
+
+ constructor(socket: WebSocket, keys: SessionKeys, timers: Timers = {}) {
+ this.#socket = socket;
+ this.#keys = keys;
+ this.closed = new Promise((resolve) => {
+ this.#settleClosed = resolve;
+ });
+ this.#mux = new Mux("phone", {
+ send: (frame) => this.#send(frame),
+ data: (streamId, data) => this.#streams.get(streamId)?.deliver(data),
+ ended: (streamId) => this.#streams.get(streamId)?.remoteEnded(),
+ reset: (streamId) => this.#streams.get(streamId)?.remoteReset(),
+ writable: (streamId) => this.#streams.get(streamId)?.flush(),
+ goAway: (code) => {
+ if (code === GO_AWAY.removed) this.#removed = true;
+ else if (code !== GO_AWAY.normal) this.close(CLOSE.protocol);
+ },
+ pong: (value) => {
+ if (value !== this.#awaitingPong) return;
+ this.#awaitingPong = null;
+ if (this.#pongTimer) clearTimeout(this.#pongTimer);
+ },
+ });
+ socket.onmessage = (event: MessageEvent) => this.receive(event);
+ socket.onclose = (event: CloseEvent) => this.#end(event.code);
+ const pingTimeoutMs = timers.pingTimeoutMs ?? PING_TIMEOUT_MS;
+ this.#pingTimer = setInterval(() => this.#ping(pingTimeoutMs), timers.pingIntervalMs ?? PING_INTERVAL_MS);
+ }
+
+ get mux(): Mux | null {
+ return this.#state === "open" ? this.#mux : null;
+ }
+
+ get state(): State {
+ return this.#state;
+ }
+
+ /** The computer said, inside the encryption, that this device was removed (GoAway 3). Only this, or a 4001 on a
+ * direct route, means "pair again"; a bare 4001 through the relay may be the relay's own. */
+ get removed(): boolean {
+ return this.#removed;
+ }
+
+ get congested(): boolean {
+ return this.#socket.bufferedAmount + this.#unsealed > SEND_BUFFER_HIGH;
+ }
+
+ whenDrained(listener: () => void): void {
+ this.#drainWaiters.push(listener);
+ if (this.#drainWaiters.length > 1) return;
+ const check = () => {
+ if (this.#state === "open" && this.#socket.bufferedAmount + this.#unsealed > SEND_BUFFER_HIGH / 4) return void setTimeout(check, DRAIN_POLL_MS);
+ for (const waiter of this.#drainWaiters.splice(0)) waiter();
+ };
+ setTimeout(check, DRAIN_POLL_MS);
+ }
+
+ forget(streamId: number): void {
+ this.#streams.delete(streamId);
+ }
+
+ open(): E2EStream {
+ if (this.#state !== "open") throw new SessionClosed(CLOSE.normal);
+ const stream = new Stream(this, this.#mux.open());
+ this.#streams.set(stream.id, stream);
+ return stream;
+ }
+
+ /** Every message after message 2, in order. */
+ receive(event: MessageEvent): void {
+ if (this.#state !== "open") return;
+ if (typeof event.data === "string") return this.close(CLOSE.protocol);
+ // Opens settle one at a time in call order, so frames reach the mux in wire order.
+ this.#keys.receive.open(new Uint8Array(event.data as ArrayBuffer)).then(
+ (plaintext) => {
+ if (this.#state !== "open") return;
+ try {
+ this.#mux.receive(decodeFrame(plaintext));
+ } catch (error) {
+ if (!(error instanceof YamuxError)) throw error;
+ this.#mux.protocolError();
+ this.close(CLOSE.protocol);
+ }
+ },
+ () => this.close(CLOSE.protocol),
+ );
+ }
+
+ /** A planned close: GoAway first, so the computer knows it isn't an error. */
+ shutdown(): void {
+ if (this.#state === "open") this.#mux.goAway(GO_AWAY.normal);
+ this.#sending.then(() => this.close(CLOSE.normal));
+ }
+
+ close(code: number): void {
+ if (this.#state === "closed") return;
+ closeSocket(this.#socket, code);
+ this.#end(code);
+ }
+
+ #end(code: number): void {
+ if (this.#state === "closed") return;
+ this.#state = "closed";
+ clearInterval(this.#pingTimer);
+ if (this.#pongTimer) clearTimeout(this.#pongTimer);
+ // Each reset forgets its stream; a Map may drop the entry being visited.
+ for (const stream of this.#streams.values()) stream.remoteReset();
+ this.#mux.closeAll();
+ for (const waiter of this.#drainWaiters.splice(0)) waiter();
+ this.#settleClosed(code);
+ }
+
+ #ping(timeoutMs: number): void {
+ if (this.#awaitingPong !== null || this.#state !== "open") return;
+ this.#pingCounter = (this.#pingCounter + 1) >>> 0;
+ this.#awaitingPong = this.#pingCounter;
+ this.#mux.ping(this.#pingCounter);
+ this.#pongTimer = setTimeout(() => this.close(CLOSE.goingAway), timeoutMs);
+ }
+
+ /** Seals start now, in frame order, so each takes the next nonce; sends wait for every earlier record. */
+ #send(frame: Frame): void {
+ if (this.#state !== "open") return;
+ const plaintext = encodeFrame(frame);
+ this.#unsealed += plaintext.length;
+ const sealed = this.#keys.send.seal(plaintext);
+ this.#sending = this.#sending.then(() =>
+ sealed.then(
+ (record) => {
+ this.#unsealed -= plaintext.length;
+ if (this.#state === "open") this.#socket.send(record);
+ },
+ (error: unknown) => {
+ this.#unsealed -= plaintext.length;
+ // The counter ran out: close before it could repeat; the phone reconnects.
+ this.close(error instanceof NoiseError ? CLOSE.normal : CLOSE.protocol);
+ },
+ ),
+ );
+ }
+}
diff --git a/src/lib/e2e/vectors.test.ts b/src/lib/e2e/vectors.test.ts
index f977c5e5f6..79741674c0 100644
--- a/src/lib/e2e/vectors.test.ts
+++ b/src/lib/e2e/vectors.test.ts
@@ -45,7 +45,7 @@ describe("the shared vectors", () => {
});
describe("the browser modules", () => {
- it.each(["bytes.ts", "credentials.ts", "noise.ts", "yamux.ts"])("%s uses no Node-only API", (name) => {
+ it.each(["bytes.ts", "credentials.ts", "noise.ts", "session.ts", "yamux.ts"])("%s uses no Node-only API", (name) => {
const source = readFileSync(new URL(name, import.meta.url), "utf8");
expect(source).not.toMatch(/from "node:|\bBuffer\b|\bprocess\./);
});