Open-source Grok Bot alternative with a virtual machine that bots can use
TypeScript ai-agentsclaude-codecodexcomputer-usedockerelectrongrokgrok-botgrok-bot-alternativeself-hostedtypescript
Phone web app session: read records before a close in the handshake; pong deadline from when the ping leaves
Bugfixer 2c603ce08ec51
diff --git a/companion/src/e2e/interop-server.ts b/companion/src/e2e/interop-server.tsindex 03bd4852cb..919bb2356d 100644--- a/companion/src/e2e/interop-server.ts+++ b/companion/src/e2e/interop-server.ts@@ -6,6 +6,7 @@// /v1/e2e direct transport (0x02), the normal case// /test/relay-transport the relay prologue (0x01) without a relay// /test/wrong-key a key swap: any message 1 gets a well-formed message 2 that can't verify (a hard stop)+// /test/removed the relay prologue; right after message 2 the device is removed: GoAway(3), then 4001// Origin paths, over any stream:// GET /api/health {"ok":true}// POST /upload {"bytes":N,"sha256":"<hex>"} of the body@@ -140,6 +141,7 @@ const routes: Record<string, TransportByte | "impostor"> = {"/v1/e2e": TRANSPORT_DIRECT,"/test/relay-transport": TRANSPORT_RELAY,"/test/wrong-key": "impostor",+ "/test/removed": TRANSPORT_RELAY,};/** What a relay holding no key can do: answer with a fresh point and bytes of the right length. */@@ -148,7 +150,8 @@ const impostorMessage2 = () => Buffer.concat([generateKeyPair().publicKey, randoconst pingIntervalMs = arg("ping-interval-ms") ? Number(arg("ping-interval-ms")) : undefined;const server = createServer((_req, res) => res.writeHead(404).end());server.on("upgrade", (req: IncomingMessage, socket: Duplex, head: Buffer) => {- const route = routes[new URL(req.url ?? "/", "http://interop").pathname];+ const path = new URL(req.url ?? "/", "http://interop").pathname;+ const route = routes[path];if (!route) return void socket.destroy();if (route === "impostor") {acceptWebSocket(req, socket, head, { protocol: "omb-e2e.v1", maxPayload: MAX_RECORD_BYTES }, (connection) => ({@@ -170,7 +173,10 @@ server.on("upgrade", (req: IncomingMessage, socket: Duplex, head: Buffer) => {const originSocket = connect({ host: "127.0.0.1", port, allowHalfOpen: true }, () => resolve(originSocket));originSocket.once("error", reject);}),- opened: (id, payload1) => console.error(`session ${req.url} ${id} ${payload1.app ?? ""}`),+ opened: (id, payload1) => {+ console.error(`session ${req.url} ${id} ${payload1.app ?? ""}`);+ if (path === "/test/removed") session?.remove();+ },pingIntervalMs,});return {@@ -194,6 +200,7 @@ console.log(direct: `${base}/v1/e2e`,relayTransport: `${base}/test/relay-transport`,wrongKey: `${base}/test/wrong-key`,+ removed: `${base}/test/removed`,k: b64u(T.publicKey),deviceToken: tokens.device,pairingToken: tokens.pairing,diff --git a/src/lib/e2e/session.test.ts b/src/lib/e2e/session.test.tsindex 7327b71f93..dec454d255 100644--- a/src/lib/e2e/session.test.ts+++ b/src/lib/e2e/session.test.ts@@ -3,7 +3,7 @@ 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 { afterAll, beforeAll, describe, expect, it, vi } from "vitest";import { WebSocket as NodeWebSocket, WebSocketServer, type RawData } from "ws";import { b64u, concat, fromB64u, utf8, type Bytes } from "./bytes.ts";@@ -19,6 +19,7 @@ interface Ready {direct: string;relayTransport: string;wrongKey: string;+ removed: string;k: string;deviceToken: string;pairingToken: string;@@ -34,6 +35,8 @@ interface RelayNode {url: string;/** What phones sent before ready. */firstMessages: unknown[];+ /** When each phone connected, by Date.now(). */+ connectedAt: number[];/** Codes this node closed phones with, in order. */closes: number[];admitted: Set<string>;@@ -60,6 +63,7 @@ async function startNode(): Promise<RelayNode> {const node: RelayNode = {url: "",firstMessages: [],+ connectedAt: [],closes: [],admitted: new Set(),refuseWith: null,@@ -80,6 +84,7 @@ async function startNode(): Promise<RelayNode> {socket.close(code, reason);};wss.on("connection", (phone) => {+ node.connectedAt.push(Date.now());if (node.refuseWith !== null) return refuse(phone, node.refuseWith, node.refuseReason);phone.once("message", (raw: RawData, isBinary: boolean) => {if (isBinary) return refuse(phone, 4400);@@ -176,6 +181,17 @@ async function request(session: PhoneSession, head: string, body?: Bytes): Promi}const text = (bytes: Uint8Array) => new TextDecoder().decode(bytes);++/** Reads until `want` has arrived whole: chunk edges need not match SSE events. */+async function readUntil(reader: ReadableStreamDefaultReader<Uint8Array>, want: string): Promise<string> {+ let seen = "";+ while (!seen.includes(want)) {+ const { done, value } = await reader.read();+ if (done) throw new Error(`stream ended before ${JSON.stringify(want)}`);+ seen += text(value);+ }+ return seen;+}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", () => {@@ -242,10 +258,30 @@ describe("dialRelay: the browser phone through a relay node", () => {full.refuseWith = 4503;full.refuseReason = JSON.stringify({ retryInMs: 400 });const { node, options } = await admittingNode();- const started = Date.now();- const session = await dialRelay({ ...options, urls: [full.url, node.url] });- expect(Date.now() - started).toBeGreaterThanOrEqual(400);- session.shutdown();+ // Jitter fixed at 10%: the wait is exactly 440 ms.+ const random = vi.spyOn(Math, "random").mockReturnValue(0.5);+ try {+ const session = await dialRelay({ ...options, urls: [full.url, node.url] });+ // Measured between the two nodes, so only the wait lies between the refusal and the next attempt.+ const waited = node.connectedAt[0] - full.connectedAt[0];+ expect(waited).toBeGreaterThanOrEqual(440);+ expect(waited).toBeLessThan(440 + 500);+ session.shutdown();+ } finally {+ random.mockRestore();+ }+ });++ it("reads a GoAway(3) that comes with message 2 before the 4001 behind it, and says the device was removed", async () => {+ const { node, options } = await admittingNode();+ node.computer = ready.removed;+ await expect(dialRelay({ ...options, urls: [node.url] })).rejects.toMatchObject({ code: 4001, removed: true });+ });++ it("keeps a bare 4001 right after message 2 as not removed: through the relay it may be the relay's own", async () => {+ const { node, options } = await admittingNode();+ node.closeAfterFirst = 4001;+ await expect(dialRelay({ ...options, urls: [node.url] })).rejects.toMatchObject({ code: 4001, removed: false });});it("stops hard on a message 2 that fails to verify, even when the node closes 4404 meanwhile", async () => {@@ -297,6 +333,13 @@ describe("dial: the direct route", () => {expect(await session.closed).toBe(1000);});+ it("rejects, rather than throws, when message 1 can't be built", async () => {+ const { psk: key } = await credentials(ready.deviceToken);+ let attempt: Promise<PhoneSession> | undefined;+ expect(() => (attempt = dial({ url: ready.direct, remoteStatic, psk: key, app: "a".repeat(41) }))).not.toThrow();+ await expect(attempt).rejects.toThrow("app_too_long");+ });+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");@@ -308,7 +351,7 @@ describe("dial: the direct route", () => {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");+ await readUntil(reader, "data: start\n\n");session.close(1000);await expect(reader.read()).rejects.toThrow("stream reset");await expect(stream.write(utf8("more"))).rejects.toThrow("stream reset");@@ -321,7 +364,7 @@ describe("dial: the direct route", () => {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");+ await readUntil(reader, "data: start\n\n");stream.end();await expect(stream.write(utf8("more"))).rejects.toThrow("stream ended");session.close(1000);@@ -335,6 +378,7 @@ function fakeSession() {const sent: Bytes[] = [];const closes: Array<number | undefined> = [];+ /** bufferedAmount stays where a test sets it: what send() adds counts as gone out at once. */const socket = {bufferedAmount: 0,send: (record: Bytes) => sent.push(record.slice()),@@ -346,7 +390,7 @@ function fakeSession(const session = new PhoneSession(socket as unknown as WebSocket, keys, timers);const record = (...bytes: number[]) => session.receive({ data: Uint8Array.from(bytes).buffer } as MessageEvent);const remoteClose = (code: number) => socket.onclose!({ code } as CloseEvent);- return { session, sent, closes, record, remoteClose };+ return { session, socket, sent, closes, record, remoteClose };}const GO_AWAY_REMOVED = [0, 3, 0, 0, 0, 0, 0, 0, 0, 0, 0, 3];@@ -393,6 +437,39 @@ describe("PhoneSession records and closes", () => {expect(closes).toEqual([1000]);});+ it("starts the pong deadline once the ping has left the socket, not while it waits behind an upload", async () => {+ vi.useFakeTimers();+ try {+ const { session, socket } = fakeSession(undefined, { pingIntervalMs: 10, pingTimeoutMs: 40 });+ // An upload ahead of the ping, leaving at 1,000 bytes a ms: the ping goes out at about 100 ms.+ socket.bufferedAmount = 100_000;+ const drain = setInterval(() => (socket.bufferedAmount = Math.max(0, socket.bufferedAmount - 1_000)), 1);+ await vi.advanceTimersByTimeAsync(129);+ expect(session.state).toBe("open");+ await vi.advanceTimersByTimeAsync(30);+ expect(session.state).toBe("closed");+ expect(await session.closed).toBe(1001);+ clearInterval(drain);+ } finally {+ vi.useRealTimers();+ }+ });++ it("closes 1001 when the socket sends nothing for the ping timeout", async () => {+ vi.useFakeTimers();+ try {+ const { session, socket } = fakeSession(undefined, { pingIntervalMs: 10, pingTimeoutMs: 40 });+ socket.bufferedAmount = 100_000;+ await vi.advanceTimersByTimeAsync(45);+ expect(session.state).toBe("open");+ await vi.advanceTimersByTimeAsync(20);+ expect(session.state).toBe("closed");+ expect(await session.closed).toBe(1001);+ } finally {+ vi.useRealTimers();+ }+ });+it("handles a seal that fails while an earlier one is pending, and keeps send order", async () => {const unhandled: unknown[] = [];const onUnhandled = (reason: unknown) => unhandled.push(reason);diff --git a/src/lib/e2e/session.ts b/src/lib/e2e/session.tsindex 95799b26c0..797793ecaa 100644--- a/src/lib/e2e/session.ts+++ b/src/lib/e2e/session.ts@@ -32,10 +32,13 @@ export class SessionClosed extends Error {readonly code: number;/** A 4503's `{"retryInMs":N}`. */readonly retryInMs?: number;- constructor(code: number, retryInMs?: number) {+ /** The computer said, inside the encryption, that this device was removed (GoAway 3) just before the close. */+ readonly removed: boolean;+ constructor(code: number, retryInMs?: number, removed = false) {super(`e2e session closed (${code})`);this.code = code;this.retryInMs = retryInMs;+ this.removed = removed;}}@@ -82,7 +85,7 @@ export interface E2EStream {}/** 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> {+export async function dial(options: DialOptions): Promise<PhoneSession> {const { relay } = options;const hello = phoneHello({ remoteStatic: options.remoteStatic, psk: options.psk, transport: relay ? TRANSPORT_RELAY : TRANSPORT_DIRECT },@@ -99,7 +102,7 @@ export function dial(options: DialOptions): Promise<PhoneSession> {/** Records that arrive while message 2 is checked go to the session in order. */const early: MessageEvent[] = [];/** A close while message 2 is checked: a failed check wins over it, since a node's 4404 must not hide a hard stop. */- let closedWhileFinishing: SessionClosed | null = null;+ let closedWhileFinishing: CloseEvent | null = null;const fail = (error: Error, code?: number) => {if (stage === "done") return;stage = "done";@@ -139,25 +142,31 @@ export function dial(options: DialOptions): Promise<PhoneSession> {.then((keys) => {if (stage !== "finishing") return;- if (closedWhileFinishing) return fail(closedWhileFinishing);stage = "done";clearTimeout(timer);const session = new PhoneSession(socket, keys, options);for (const message of early) session.receive(message);- resolve(session);+ if (!closedWhileFinishing) return resolve(session);+ // Closed already: the records before the close are read first, so a GoAway(3) among them is told apart+ // from a bare 4001 the relay may have sent on its own.+ const event = closedWhileFinishing;+ socket.onclose?.call(socket, event);+ void session.closed.then(() => reject(closedBy(event, session.removed)));},(error: Error) => fail(error, CLOSE.protocol),);};socket.onclose = (event: CloseEvent) => {- const closed = new SessionClosed(event.code, event.code === CLOSE.relayBusy ? retryDelay(event.reason) : undefined);- if (stage === "finishing") closedWhileFinishing = closed;- else fail(closed);+ if (stage === "finishing") closedWhileFinishing = event;+ else fail(closedBy(event));};socket.onerror = () => {};});}+const closedBy = (event: CloseEvent, removed = false) =>+ new SessionClosed(event.code, event.code === CLOSE.relayBusy ? retryDelay(event.reason) : undefined, removed);+/** `{"retryInMs":N}` with N a whole number of ms, at most a minute; anything else asks for no wait. */function retryDelay(reason: string): number | undefined {try {@@ -328,6 +337,8 @@ export class PhoneSession {/** Records not yet sealed, which the socket's buffered amount does not count yet. */#unsealed = 0;#sending: Promise<void> = Promise.resolve();+ /** Bytes handed to the socket so far; less its buffered amount, what has gone out. */+ #handed = 0;#pingTimer: ReturnType<typeof setInterval>;#pongTimer: ReturnType<typeof setTimeout> | null = null;#awaitingPong: number | null = null;@@ -476,7 +487,23 @@ export class PhoneSession {this.#pingCounter = (this.#pingCounter + 1) >>> 0;this.#awaitingPong = this.#pingCounter;this.#mux.ping(this.#pingCounter);- this.#pongTimer = setTimeout(() => this.close(CLOSE.goingAway), timeoutMs);+ // The deadline is for the computer's answer, so it starts once the ping has gone out, not while the ping waits+ // behind an upload. A socket that sends nothing for as long is stalled, and closes the same way.+ const ping = this.#awaitingPong;+ void this.#sending.then(() => {+ const pingSent = this.#handed;+ let gone = -Infinity;+ let since = Date.now();+ const check = () => {+ if (this.#state !== "open" || this.#awaitingPong !== ping) return;+ const now = this.#handed - this.#socket.bufferedAmount;+ if (now >= pingSent) return void (this.#pongTimer = setTimeout(() => this.close(CLOSE.goingAway), timeoutMs));+ if (now > gone) [gone, since] = [now, Date.now()];+ else if (Date.now() - since >= timeoutMs) return this.close(CLOSE.goingAway);+ this.#pongTimer = setTimeout(check, DRAIN_POLL_MS);+ };+ check();+ });}/** Seals start now, in frame order, so each takes the next nonce; sends wait for every earlier record. A seal's@@ -494,7 +521,9 @@ export class PhoneSession {this.#unsealed -= plaintext.length;// The counter ran out: close before it could repeat; the phone reconnects.if ("error" in result) return this.close(result.error instanceof NoiseError ? CLOSE.normal : CLOSE.protocol);- if (this.#state !== "closed") this.#socket.send(result.record);+ if (this.#state === "closed") return;+ this.#socket.send(result.record);+ this.#handed += result.record.length;});}}