Skip to content

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

Phone web app session: handshake deadline from ready, bounded early records, no pong timeout after the socket closed

Bugfixer 26f50a18cb156
diff --git a/src/lib/e2e/session-handshake.test.ts b/src/lib/e2e/session-handshake.test.ts
new file mode 100644
index 0000000000..eaecb7ae73
--- /dev/null
+++ b/src/lib/e2e/session-handshake.test.ts
@@ -0,0 +1,122 @@
+import { afterEach, beforeEach, describe, expect, it, vi } from "vitest";
+
+import type { Bytes } from "./bytes.ts";
+import type { SessionKeys } from "./noise.ts";
+
+// The computer's side of the handshake is replaced, so these tests drive only dial()'s timing and queueing.
+vi.mock("./noise.ts", async (importOriginal) => ({ ...(await importOriginal<typeof import("./noise.ts")>()), phoneHello: vi.fn() }));
+
+const { phoneHello } = await import("./noise.ts");
+const { dial, SessionClosed } = await import("./session.ts");
+
+class FakeSocket {
+ static last: FakeSocket;
+ binaryType = "blob";
+ bufferedAmount = 0;
+ sent: unknown[] = [];
+ closes: Array<number | undefined> = [];
+ onopen: (() => void) | null = null;
+ onmessage: ((event: MessageEvent) => void) | null = null;
+ onclose: ((event: CloseEvent) => void) | null = null;
+ onerror: (() => void) | null = null;
+ constructor() {
+ FakeSocket.last = this;
+ }
+ send(data: unknown) {
+ this.sent.push(data);
+ }
+ close(code?: number) {
+ this.closes.push(code);
+ }
+ message(data: string | Uint8Array) {
+ this.onmessage!({ data: typeof data === "string" ? data : data.slice().buffer } as MessageEvent);
+ }
+}
+
+const keys = {
+ send: { seal: async (plaintext: Bytes) => plaintext },
+ receive: { open: async (record: Bytes) => record },
+} as unknown as SessionKeys;
+const base = { remoteStatic: new Uint8Array(65), psk: new Uint8Array(32), app: "web-test/1" };
+/** Ping {SYN} 7 from the computer. */
+const PING = Uint8Array.of(0, 2, 0, 1, 0, 0, 0, 0, 0, 0, 0, 7);
+
+let finishKeys: ((keys: SessionKeys) => void) | undefined;
+
+beforeEach(() => {
+ finishKeys = undefined;
+ vi.stubGlobal("WebSocket", FakeSocket);
+ vi.mocked(phoneHello).mockResolvedValue({
+ message1: Uint8Array.of(1),
+ finish: () => new Promise<SessionKeys>((resolve) => (finishKeys = resolve)),
+ } as unknown as Awaited<ReturnType<typeof phoneHello>>);
+});
+
+afterEach(() => {
+ vi.useRealTimers();
+ vi.unstubAllGlobals();
+});
+
+const settled = (promise: Promise<unknown>) => {
+ const state: { error?: unknown; done: boolean } = { done: false };
+ promise.then(
+ () => (state.done = true),
+ (error: unknown) => Object.assign(state, { done: true, error }),
+ );
+ return state;
+};
+
+/** Opens the socket and hands dial() a message 2 to check; the check waits for finishKeys. */
+async function atMessage2(options: Partial<Parameters<typeof dial>[0]> = {}) {
+ const attempt = dial({ ...base, url: "wss://computer.test/e2e", pingIntervalMs: 60_000, ...options });
+ const socket = FakeSocket.last;
+ socket.onopen!();
+ await vi.waitFor(() => expect(socket.sent).toHaveLength(1));
+ socket.message(new Uint8Array(96));
+ return { attempt, socket };
+}
+
+describe("dial: the handshake deadline", () => {
+ it("gives the handshake its own 10 s from the relay's ready, inside the attempt's 20 s", async () => {
+ vi.useFakeTimers();
+ const relay = { hostId: new Uint8Array(16), adm: new Uint8Array(16) };
+ const attempt = settled(dial({ ...base, url: "wss://relay.test/v1/phone", relay }));
+ const socket = FakeSocket.last;
+ socket.onopen!();
+ // A slow node: ready comes 8 s in.
+ await vi.advanceTimersByTimeAsync(8_000);
+ socket.message(JSON.stringify({ t: "ready" }));
+ await vi.advanceTimersByTimeAsync(9_900);
+ expect(attempt.done).toBe(false);
+ expect(socket.sent).toHaveLength(2);
+ await vi.advanceTimersByTimeAsync(200);
+ expect(attempt.error).toBeInstanceOf(SessionClosed);
+ expect(attempt.error).toMatchObject({ code: 4002 });
+ expect(socket.closes).toEqual([4002]);
+ });
+});
+
+describe("dial: records that arrive while message 2 is checked", () => {
+ it("replays a few in order once message 2 checks out", async () => {
+ const { attempt, socket } = await atMessage2();
+ for (let i = 0; i < 3; i++) socket.message(PING);
+ await vi.waitFor(() => expect(finishKeys).toBeDefined());
+ finishKeys!(keys);
+ const session = await attempt;
+ // Message 1, then an ACK for each ping.
+ await vi.waitFor(() => expect(socket.sent).toHaveLength(4));
+ session.close(1000);
+ });
+
+ it("refuses the session, holding nothing, when more arrive than a session's start can need", async () => {
+ const { attempt, socket } = await atMessage2();
+ const state = settled(attempt);
+ for (let i = 0; i < 65; i++) socket.message(PING);
+ await vi.waitFor(() => expect(finishKeys).toBeDefined());
+ finishKeys!(keys);
+ await vi.waitFor(() => expect(state.done).toBe(true));
+ expect(state.error).toMatchObject({ code: 4000 });
+ expect(socket.closes).toEqual([4000]);
+ expect(socket.sent).toHaveLength(1);
+ });
+});
diff --git a/src/lib/e2e/session.test.ts b/src/lib/e2e/session.test.ts
index dec454d255..3b6f0624d8 100644
--- a/src/lib/e2e/session.test.ts
+++ b/src/lib/e2e/session.test.ts
@@ -400,6 +400,38 @@ const GO_AWAY_PROTOCOL = [0, 3, 0, 0, 0, 0, 0, 0, 0, 0, 0, 1];
const COMPUTER_OPEN = [0, 1, 0, 1, 0, 0, 0, 2, 0, 0, 0, 0];
describe("PhoneSession records and closes", () => {
+ it("keeps a GoAway(3) still being opened when the socket closes 4001 and the pong deadline passes meanwhile", async () => {
+ let release!: () => void;
+ let opened = 0;
+ const socket = {
+ bufferedAmount: 0,
+ send: () => {},
+ close: () => {},
+ onmessage: null as ((event: MessageEvent) => void) | null,
+ onclose: null as ((event: CloseEvent) => void) | null,
+ };
+ const keys = {
+ send: { seal: async (plaintext: Bytes) => plaintext },
+ receive: {
+ open: (record: Bytes) => {
+ opened += 1;
+ return new Promise<Bytes>((resolve) => (release = () => resolve(record)));
+ },
+ },
+ } as unknown as SessionKeys;
+ const session = new PhoneSession(socket as unknown as WebSocket, keys, { pingIntervalMs: 10, pingTimeoutMs: 20 });
+ // The ping is out and its deadline is running when the removal record and the close arrive.
+ await new Promise((resolve) => setTimeout(resolve, 15));
+ session.receive({ data: Uint8Array.from(GO_AWAY_REMOVED).buffer } as MessageEvent);
+ socket.onclose!({ code: 4001 } as CloseEvent);
+ await new Promise((resolve) => setTimeout(resolve, 60));
+ expect(session.state).toBe("open");
+ expect(opened).toBe(1);
+ release();
+ expect(await session.closed).toBe(4001);
+ expect(session.removed).toBe(true);
+ });
+
it("reads a GoAway(3) still being opened before the 4001 close behind it ends the session", async () => {
const { session, record, remoteClose } = fakeSession();
record(...GO_AWAY_REMOVED);
diff --git a/src/lib/e2e/session.ts b/src/lib/e2e/session.ts
index 797793ecaa..1dda2a037e 100644
--- a/src/lib/e2e/session.ts
+++ b/src/lib/e2e/session.ts
@@ -1,5 +1,5 @@
import { b64u, type Bytes } from "./bytes.ts";
-import { encodePayload1, newConn, NoiseError, phoneHello, TRANSPORT_DIRECT, TRANSPORT_RELAY, type SessionKeys } from "./noise.ts";
+import { encodePayload1, MAX_RECORD_BYTES, 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";
@@ -27,6 +27,9 @@ const DRAIN_POLL_MS = 5;
const READ_HIGH_WATER = 256 * 1024;
/** The longest wait a 4503 can ask for. */
const MAX_RETRY_MS = 60_000;
+/** Records held while message 2 is checked: control frames only, since no stream is open yet. */
+const MAX_EARLY_RECORDS = 64;
+const MAX_EARLY_BYTES = MAX_RECORD_BYTES;
export class SessionClosed extends Error {
readonly code: number;
@@ -101,12 +104,16 @@ export async function dial(options: DialOptions): Promise<PhoneSession> {
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[] = [];
+ let earlyBytes = 0;
+ /** More arrived than a session's start can need; the queue is dropped and the session refused once verified. */
+ let overflowed = false;
/** 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: CloseEvent | null = null;
const fail = (error: Error, code?: number) => {
if (stage === "done") return;
stage = "done";
clearTimeout(timer);
+ clearTimeout(noiseTimer);
reject(error);
if (code !== undefined) closeSocket(socket, code);
};
@@ -114,8 +121,11 @@ export async function dial(options: DialOptions): Promise<PhoneSession> {
() => fail(new SessionClosed(CLOSE.deadline), CLOSE.deadline),
options.timeoutMs ?? HANDSHAKE_DEADLINE_MS + (relay ? RELAY_EXTRA_MS : 0),
);
+ let noiseTimer: ReturnType<typeof setTimeout> | undefined;
const sendMessage1 = () => {
stage = "message2";
+ // The handshake's own 10 s run from the socket opening, or from the relay's ready (README section 5).
+ noiseTimer = setTimeout(() => fail(new SessionClosed(CLOSE.deadline), CLOSE.deadline), HANDSHAKE_DEADLINE_MS);
hello.then(
(started) => {
if (stage === "message2") socket.send(started.message1);
@@ -134,7 +144,16 @@ export async function dial(options: DialOptions): Promise<PhoneSession> {
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 === "finishing") {
+ // Before the session exists the phone has opened no stream, so only a few control records can be due. Too many
+ // is a protocol error, reported after the check so that a message 2 that fails to verify still stops hard.
+ if (overflowed) return;
+ earlyBytes += typeof event.data === "string" ? event.data.length : (event.data as ArrayBuffer).byteLength;
+ if (early.length < MAX_EARLY_RECORDS && earlyBytes <= MAX_EARLY_BYTES) return void early.push(event);
+ overflowed = true;
+ early.length = 0;
+ return;
+ }
if (stage !== "message2" || typeof event.data === "string") return fail(new SessionClosed(CLOSE.protocol), CLOSE.protocol);
stage = "finishing";
hello
@@ -142,8 +161,10 @@ export async function dial(options: DialOptions): Promise<PhoneSession> {
.then(
(keys) => {
if (stage !== "finishing") return;
+ if (overflowed) return fail(new SessionClosed(CLOSE.protocol), CLOSE.protocol);
stage = "done";
clearTimeout(timer);
+ clearTimeout(noiseTimer);
const session = new PhoneSession(socket, keys, options);
for (const message of early) session.receive(message);
if (!closedWhileFinishing) return resolve(session);
@@ -376,8 +397,10 @@ export class PhoneSession {
socket.onmessage = (event: MessageEvent) => this.receive(event);
// A record already received, such as GoAway(3) just before a 4001, is read before the close ends the session.
socket.onclose = (event: CloseEvent) => {
- if (this.#opening === 0) this.#end(event.code);
- else this.#closedMeanwhile = event.code;
+ if (this.#opening === 0) return this.#end(event.code);
+ // The socket is gone, so no pong can come: only the records already in may still settle the session.
+ this.#closedMeanwhile = event.code;
+ this.#stopLiveness();
};
const pingTimeoutMs = timers.pingTimeoutMs ?? PING_TIMEOUT_MS;
this.#pingTimer = setInterval(() => this.#ping(pingTimeoutMs), timers.pingIntervalMs ?? PING_INTERVAL_MS);
@@ -473,8 +496,7 @@ export class PhoneSession {
#end(code: number): void {
if (this.#state === "closed") return;
this.#state = "closed";
- clearInterval(this.#pingTimer);
- if (this.#pongTimer) clearTimeout(this.#pongTimer);
+ this.#stopLiveness();
// 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();
@@ -482,6 +504,12 @@ export class PhoneSession {
this.#settleClosed(code);
}
+ #stopLiveness(): void {
+ clearInterval(this.#pingTimer);
+ if (this.#pongTimer) clearTimeout(this.#pongTimer);
+ this.#awaitingPong = null;
+ }
+
#ping(timeoutMs: number): void {
if (this.#awaitingPong !== null || this.#state !== "open") return;
this.#pingCounter = (this.#pingCounter + 1) >>> 0;