Open-source Grok Bot alternative with a virtual machine that bots can use
TypeScript ai-agentsclaude-codecodexcomputer-usedockerelectrongrokgrok-botgrok-bot-alternativeself-hostedtypescript
companion: authenticated removal, the real relay in the integration tests, and an opt-in soak
milind-soni30a131b535f3
diff --git a/companion/src/e2e/README.md b/companion/src/e2e/README.mdindex 1b5e1de28c..05483d7406 100644--- a/companion/src/e2e/README.md+++ b/companion/src/e2e/README.md@@ -179,7 +179,7 @@ This uses the yamux wire format (`hashicorp/yamux` spec): a 12-byte header of `v| Concurrent streams per session | 64, counting un-ACKed opens. The 65th is answered with RST || Half close | FIN on Data or WindowUpdate. A stream ends when both FINs are seen, or on RST || Keepalive | Each side sends Ping {SYN, length = opaque u32} every 20 s. The peer answers Ping {ACK, same value}. No answer within 10 s closes the session (1001) |-| GoAway | StreamId 0, `length` = 0 normal, 1 protocol error, 2 internal error. Sent before a planned close (quit, sleep, restart) |+| GoAway | StreamId 0, `length` = 0 normal, 1 protocol error, 2 internal error, 3 removed. 0 is sent before a planned close (quit, sleep, restart). 3 goes only from the computer to the phone, when the person removed this device, right before the 4001 close || Session flow | No session-wide window. Backpressure comes from the WebSocket: a sender stops writing records while the socket's buffered amount is above 1 MiB || Stream ID ceiling | At `streamId > 2^31 − 1` the phone opens a new session |@@ -249,7 +249,7 @@ own the `sid`, and a `sid` is single-use with a 10 s life. The relay then splice| 4429 | relay | Rate, size or byte limit | Back off, at least 30 s || 4503 | relay | Restarting or full. Reason is JSON `{"retryInMs":N}` | Wait N plus jitter, then try the next node || 4000 | either end | E2E protocol error (AEAD, framing, window) | Hard stop for this session; reconnect with backoff |-| 4001 | computer | Handshake rejected (no psk matched) | Phone: "This phone was removed from your computer. Pair again." Stop retrying the relay |+| 4001 | computer | Handshake rejected (no psk matched), or the device was removed (after GoAway(3)) | Phone: on a direct route, or after GoAway(3), "This phone was removed from your computer. Pair again." Through the relay without GoAway(3), the relay may have written it: retry with backoff || 4002 | either end | Handshake deadline passed | Retry with backoff |**Relay token** (minted by the control plane, checked by the relay offline):@@ -310,7 +310,8 @@ own the `sid`, and a `sid` is single-use with a 10 s life. The relay then splice| Direct routes failed and the relay couldn't be reached | "Can't reach MausBot Relay right now. Trying again…" || Restricted device, not on the home Wi-Fi or the tailnet | "This phone is set to Wi-Fi and Tailscale only." || Message 2 failed / pin mismatch | "Couldn't verify your computer. Pair again from your computer's Settings." |-| 4001 | "This phone was removed from your computer. Pair again." |+| GoAway(3) inside the session, or close 4001 on a direct route | "This phone was removed from your computer. Pair again." |+| Close 4001 through the relay with no GoAway(3) before it | Nothing yet: a relay can forge close codes, so keep retrying with backoff. It reads as "removed" only if a direct route also answers 4001 || `e2e.v > 1` or 426 | "Update the MausBot app to connect to this computer." || 4429 / 4503 lasting more than 30 s | "MausBot Relay is busy. Trying again…" |@@ -353,6 +354,13 @@ These make the sections above exact where an implementation could otherwise choo`v` rejects.- Unknown fields are ignored. Field order is free.- `routes`, when present, must be the string `"any"` or `"local"`, and `"local"` with `h` or `r` rejects.++**Removal**+- A close code travels outside the encryption, and over the relay the relay writes it. When a device is removed, the+ computer first sends GoAway with `length` 3 inside the session, then closes with 4001. The phone treats only that+ GoAway(3), or a 4001 on a direct route, as removed. A 4001 from the relay without it (including at the handshake, where+ no session exists yet) means "couldn't confirm": retry with backoff and try a direct route. The computer refuses a+ GoAway(3) from the phone as a protocol error.- base64url is strict everywhere (descriptor, keys, `h`, `conn`, tokens): the URL-safe alphabet only, no padding, andcanonical (unused low bits of the last character are zero). Decode, re-encode and compare is enough.diff --git a/companion/src/e2e/gen-vectors.ts b/companion/src/e2e/gen-vectors.tsindex d7b6dbc28c..9d671fba36 100644--- a/companion/src/e2e/gen-vectors.ts+++ b/companion/src/e2e/gen-vectors.ts@@ -246,6 +246,7 @@ function v5() {["go_away_0", goAwayFrame(0), "GoAway normal"],["go_away_1", goAwayFrame(1), "GoAway protocol error"],["go_away_2", goAwayFrame(2), "GoAway internal error"],+ ["go_away_3", goAwayFrame(3), "GoAway removed: only from the computer, before it closes with 4001"],["stream_3", openFrame(3), "the next stream the phone opens"],];return frames.map(([name, frame, about]) => {@@ -475,6 +476,7 @@ function v6Sessions() {steps: [{ in: openFrame(1) }, ...fill(1, 1024 * 1024), { consume: { stream: 1, bytes: 1024 * 1024 - 1 } }, { consume: { stream: 1, bytes: 1 } }],},{ name: "phone_open_ids", about: "the phone opens 1, 3, 5", role: "phone", steps: [{ open: true }, { open: true }, { open: true }] },+ { name: "phone_hears_removed", about: "GoAway removed is no protocol error at the phone; it sends nothing back", role: "phone", steps: [{ open: true }, { in: goAwayFrame(3) }] },];return scripts.map((script) => {const result = runScript(script);diff --git a/companion/src/e2e/registry.ts b/companion/src/e2e/registry.tsindex 369177a344..c1ffeb8e5e 100644--- a/companion/src/e2e/registry.ts+++ b/companion/src/e2e/registry.ts@@ -169,7 +169,8 @@ export class E2ERegistry {for (const live of this.#live) {if (live.context.peer.kind !== "device" || live.context.peer.id !== deviceId) continue;if (onlyRoute && live.context.route !== onlyRoute) continue;- live.session.close(code);+ if (code === CLOSE.rejected) live.session.remove();+ else live.session.close(code);}}diff --git a/companion/src/e2e/session.ts b/companion/src/e2e/session.tsindex 308a98b5cd..ae6535f9b5 100644--- a/companion/src/e2e/session.ts+++ b/companion/src/e2e/session.ts@@ -164,6 +164,7 @@ export class E2ESession<Id> {#settleReady!: (error?: Error) => void;#settleClosed!: (code: number) => void;#connectOrigin: (() => Promise<Duplex>) | null = null;+ #removed = false;/** The computer side: which device (or pairing window) this is. */peer: Id | null = null;readonly ready: Promise<void>;@@ -230,10 +231,21 @@ export class E2ESession<Id> {return this.#mux;}+ /** The phone side: the computer said, inside the encryption, that this device was removed. Only this, or a 4001 on+ * a direct route, means "pair again"; a bare 4001 through the relay may be the relay's own and means "keep trying". */+ get removed(): boolean {+ return this.#removed;+ }+get state(): State {return this.#state;}+ /** Records each way so far, for diagnostics. */+ get records(): { sent: number; received: number } {+ return { sent: this.#keys?.send.nonce ?? 0, received: this.#keys?.receive.nonce ?? 0 };+ }+get congested(): boolean {return this.#transport.bufferedAmount > SEND_BUFFER_HIGH;}@@ -290,6 +302,12 @@ export class E2ESession<Id> {return stream;}+ /** The computer side: the device was removed. The phone hears it authenticated, then the 4001 close. */+ remove(): void {+ if (this.#state === "open") this.#mux?.goAway(GO_AWAY.removed);+ this.close(CLOSE.rejected);+ }+/** A planned close (quit, sleep, restart): GoAway first, so the peer knows it isn't an error. */shutdown(): void {if (this.#state === "open") this.#mux?.goAway(GO_AWAY.normal);@@ -339,7 +357,8 @@ export class E2ESession<Id> {},writable: (streamId) => this.#streams.get(streamId)?.flush(),goAway: (code) => {- if (code !== GO_AWAY.normal) this.close(CLOSE.protocol);+ if (code === GO_AWAY.removed && this.role === "phone") this.#removed = true;+ else if (code !== GO_AWAY.normal) this.close(CLOSE.protocol);},pong: (value) => {if (value !== this.#awaitingPong) return;diff --git a/companion/src/e2e/vectors/v1.json b/companion/src/e2e/vectors/v1.jsonindex f1e46cc34f..fd91a31768 100644--- a/companion/src/e2e/vectors/v1.json+++ b/companion/src/e2e/vectors/v1.json@@ -425,6 +425,15 @@"length": 2,"hex": "000300000000000000000002"},+ {+ "name": "go_away_3",+ "about": "GoAway removed: only from the computer, before it closes with 4001",+ "type": 3,+ "flags": 0,+ "streamId": 0,+ "length": 3,+ "hex": "000300000000000000000003"+ },{"name": "stream_3","about": "the next stream the phone opens",@@ -2070,6 +2079,26 @@"0001000100000005001c0000"]}+ },+ {+ "name": "phone_hears_removed",+ "about": "GoAway removed is no protocol error at the phone; it sends nothing back",+ "role": "phone",+ "steps": [+ {+ "open": true+ },+ {+ "in": {+ "header": "000300000000000000000003"+ }+ }+ ],+ "expect": {+ "sent": [+ "0001000100000001001c0000"+ ]+ }}]},diff --git a/companion/src/e2e/vectors/v1.sha256 b/companion/src/e2e/vectors/v1.sha256index 489b193b30..792eb45b2d 100644--- a/companion/src/e2e/vectors/v1.sha256+++ b/companion/src/e2e/vectors/v1.sha256@@ -1 +1 @@-734415cc7b8aa2f57de6788a72b058c2eb48a11fcfb20d0fab489cf46668ed00 v1.json+525279254e73d3a953957a9b8dd7b044051fa2d10ce349f409535022a5fbe30a v1.jsondiff --git a/companion/src/e2e/yamux.ts b/companion/src/e2e/yamux.tsindex 78712cb0fb..a167662de1 100644--- a/companion/src/e2e/yamux.ts+++ b/companion/src/e2e/yamux.ts@@ -5,7 +5,9 @@ export const VERSION = 0;export const TYPE = { data: 0, windowUpdate: 1, ping: 2, goAway: 3 } as const;export const FLAG = { syn: 0x1, ack: 0x2, fin: 0x4, rst: 0x8 } as const;const KNOWN_FLAGS = 0xf;-export const GO_AWAY = { normal: 0, protocol: 1, internal: 2 } as const;+/** `removed` goes only from the computer to the phone: this device was removed, and the close that follows is 4001. It+ * is inside the encryption, so unlike a bare 4001 close code a relay can't forge it. */+export const GO_AWAY = { normal: 0, protocol: 1, internal: 2, removed: 3 } as const;export const HEADER_BYTES = 12;export const MAX_DATA_PAYLOAD = 65_507;diff --git a/companion/src/index.ts b/companion/src/index.tsindex 50527fe280..c4ea0c9b36 100755--- a/companion/src/index.ts+++ b/companion/src/index.ts@@ -197,7 +197,10 @@ function configureE2E(message: Record<string, unknown>): void {applyRelay(config.relay);}-devices.onChange(() => relay?.refreshAdmission());+/** A removal closes the device's sessions with an authenticated GoAway(3) first; the relay drops a session whose+ * admission leaves the set at once (4404), so the smaller set follows a moment later. */+const ADMISSION_SETTLE_MS = 300;+devices.onChange(() => setTimeout(() => relay?.refreshAdmission(), ADMISSION_SETTLE_MS).unref());e2e.onAdmissionChange(() => relay?.refreshAdmission());const control = createControlServer({diff --git a/companion/test/e2e/fake-harness.ts b/companion/test/e2e/fake-harness.tsindex e21b1cb174..1677954ae9 100644--- a/companion/test/e2e/fake-harness.ts+++ b/companion/test/e2e/fake-harness.ts@@ -50,6 +50,25 @@ export async function startFakeHarness(): Promise<FakeHarness> {req.on("end", () => res.writeHead(201, { "content-type": "application/json" }).end(JSON.stringify({ bytes, sha256: hash.digest("hex") })));return;}+ const soak = /^\/api\/attachments\/soak-(\d+)\.mp3$/.exec(path);+ if (soak) {+ // A long screen stream in small frames: `total` bytes in 12 KiB writes, byte i = i % 251.+ const total = Number(soak[1]);+ const frame = Buffer.from(Array.from({ length: 12 * 1024 * 251 }, (_, index) => index % 251));+ res.writeHead(200, { "content-type": "audio/mpeg", "content-length": total });+ let sent = 0;+ const pump = () => {+ while (sent < total) {+ const size = Math.min(12 * 1024, total - sent);+ const offset = sent % 251;+ const more = res.write(frame.subarray(offset, offset + size));+ sent += size;+ if (!more) return void res.once("drain", pump);+ }+ res.end();+ };+ return pump();+ }if (path.startsWith("/api/attachments/")) {const body = Buffer.from(Array.from({ length: ATTACHMENT_BYTES }, (_, index) => attachmentByte(index)));const range = /^bytes=(\d+)-(\d+)$/.exec(String(req.headers.range ?? ""));diff --git a/companion/test/e2e/fake-relay.ts b/companion/test/e2e/fake-relay.tsindex eb44e3aba7..8facdaa96e 100644--- a/companion/test/e2e/fake-relay.ts+++ b/companion/test/e2e/fake-relay.ts@@ -36,6 +36,8 @@ export interface FakeRelay {tamper: FakeRelayOptions["tamper"] | null;admitted(hid: string): Set<string>;restart(): void;+ /** Closes every spliced phone socket with `code`, as a malicious relay would, outside the encryption. */+ forgeClose(code: number): void;/** Drops every socket without a close frame, as a crashed process would. */kill(): Promise<void>;close(): Promise<void>;@@ -177,6 +179,9 @@ export async function startFakeRelay(options: FakeRelayOptions): Promise<FakeRelrestart() {for (const host of hosts.values()) host.control.send(JSON.stringify({ t: "restarting", reconnectInMs: 0, tryForMs: 200 }));},+ forgeClose(code: number) {+ for (const host of hosts.values()) for (const session of host.sessions) session.phone.close(code);+ },async kill() {for (const client of wss.clients) client.terminate();hosts.clear();diff --git a/companion/test/e2e/malicious-relay.test.ts b/companion/test/e2e/malicious-relay.test.tsnew file mode 100644index 0000000000..5682c9b813--- /dev/null+++ b/companion/test/e2e/malicious-relay.test.ts@@ -0,0 +1,113 @@+// DESIGN §6.3: a relay that tampers with what it splices. Every attack must end in a closed session or a refused+// pairing, never in data delivered.+import { randomBytes } from "node:crypto";+import { afterAll, beforeAll, describe, expect, it } from "vitest";++import { b64u } from "../../src/e2e/credentials.ts";+import { generateKeyPair, NoiseError, phoneHello, TRANSPORT_RELAY } from "../../src/e2e/noise.ts";+import { fromB64u } from "../../src/e2e/credentials.ts";+import { startFakeRelay, type FakeRelay } from "./fake-relay.ts";+import { http, pairViaRelay, startRig, type Rig } from "./rig.ts";++let rig: Rig;+let relay: FakeRelay;+let deviceToken = "";++beforeAll(async () => {+ rig = await startRig(async (publicKey) => {+ relay = await startFakeRelay({ keys: new Map([["k1", publicKey]]) });+ return relay.url;+ });+ const paired = await pairViaRelay(rig);+ deviceToken = paired.token;+ paired.session.shutdown();+}, 30_000);++afterAll(async () => {+ await rig?.stop();+ await relay?.close();+});++const state = () => rig.control("GET", "/state");+const flip = (data: Buffer) => {+ const out = Buffer.from(data);+ out[out.length - 1] ^= 1;+ return out;+};++/** One 300 KB upload through a tampered relay: it must never reach the harness. */+async function attempt(tamper: NonNullable<FakeRelay["tamper"]>): Promise<"refused" | "delivered"> {+ relay.tamper = tamper;+ try {+ const session = await rig.viaRelay(await state(), deviceToken);+ const reply = await http(session, "POST", "/api/files", { token: deviceToken, body: randomBytes(300_000), headers: { "content-type": "application/octet-stream" } });+ session.shutdown();+ return reply.status === 201 ? "delivered" : "refused";+ } catch {+ return "refused";+ } finally {+ relay.tamper = null;+ }+}++describe("a malicious relay", () => {+ it("can't swap the computer's key: a message 2 it wrote is a hard stop", async () => {+ relay.tamper = (direction, data, index) =>+ direction === "toPhone" && index === 0 && data.length > 81 ? Buffer.concat([generateKeyPair().publicKey, randomBytes(data.length - 65)]) : data;+ await expect(rig.viaRelay(await state(), deviceToken)).rejects.toBeInstanceOf(NoiseError);+ relay.tamper = null;+ });++ it("can't pose as the phone: a message 1 without the psk is refused", async () => {+ const forged = phoneHello(+ { remoteStatic: fromB64u((await state()).e2e.descriptor!.k)!, psk: randomBytes(32), transport: TRANSPORT_RELAY },+ Buffer.from(JSON.stringify({ v: 1, conn: b64u(randomBytes(16)) })),+ "",+ ).message1;+ expect(await attempt((direction, data, index) => (direction === "toHost" && index === 0 ? forged : data))).toBe("refused");+ });++ it("can't replay, drop, truncate or flip a record", async () => {+ let previous: Buffer | null = null;+ expect(await attempt((direction, data, index) => {+ if (direction !== "toHost" || index < 1) return data;+ const out = index === 3 && previous ? previous : data;+ previous = data;+ return out;+ })).toBe("refused");+ expect(await attempt((direction, data, index) => (direction === "toHost" && index === 2 ? null : data))).toBe("refused");+ expect(await attempt((direction, data, index) => (direction === "toHost" && index === 2 ? data.subarray(0, data.length - 1) : data))).toBe("refused");+ expect(await attempt((direction, data, index) => (direction === "toHost" && index === 2 ? flip(data) : data))).toBe("refused");+ });++ it("can't reflect the computer's own record back to it", async () => {+ let fromComputer: Buffer | null = null;+ let reflected = false;+ expect(await attempt((direction, data, index) => {+ if (direction === "toPhone" && index >= 1) fromComputer ??= data;+ if (direction !== "toHost" || index < 2 || !fromComputer || reflected) return data;+ reflected = true;+ return fromComputer;+ })).toBe("refused");+ });++ it("can't pass off a message 2 from an earlier session", async () => {+ let old: Buffer | null = null;+ relay.tamper = (direction, data, index) => {+ if (direction === "toPhone" && index === 0) old = data;+ return data;+ };+ (await rig.viaRelay(await state(), deviceToken)).shutdown();+ relay.tamper = (direction, data, index) => (direction === "toPhone" && index === 0 && old ? old : data);+ await expect(rig.viaRelay(await state(), deviceToken)).rejects.toBeInstanceOf(NoiseError);+ relay.tamper = null;+ });++ it("can close the session with 4001, but the phone doesn't take it for a removal", async () => {+ const session = await rig.viaRelay(await state(), deviceToken);+ relay.forgeClose(4001);+ expect(await session.closed).toBe(4001);+ expect(session.removed).toBe(false);+ expect((await state()).devices).toHaveLength(1);+ });+});diff --git a/companion/test/e2e/rig.ts b/companion/test/e2e/rig.tsnew file mode 100644index 0000000000..d003d7721f--- /dev/null+++ b/companion/test/e2e/rig.ts@@ -0,0 +1,272 @@+// The real sidecar process in front of a fake harness, reached through a relay (the real relay process, or the fake+// one for attacks), driven by the reference phone.+import { spawn, type ChildProcess } from "node:child_process";+import { generateKeyPairSync, randomBytes } from "node:crypto";+import { mkdtempSync, rmSync } from "node:fs";+import { request } from "node:http";+import { createServer, type AddressInfo } from "node:net";+import { tmpdir } from "node:os";+import { join } from "node:path";+import { fileURLToPath } from "node:url";++import { admission, b64u, credentialHash, ed25519RawPublicKey, fromB64u, keyId, mintRelayToken, psk } from "../../src/e2e/credentials.ts";+import { TRANSPORT_DIRECT, TRANSPORT_RELAY } from "../../src/e2e/noise.ts";+import { dial } from "../../src/e2e/phone.ts";+import type { E2ESession } from "../../src/e2e/session.ts";+import { startFakeHarness, type FakeHarness } from "./fake-harness.ts";++const ENTRY = fileURLToPath(new URL("../../src/index.ts", import.meta.url));+const RELAY_MAIN = fileURLToPath(new URL("../../../relay/src/main.ts", import.meta.url));++/** Distinct ports: each is held until all are found, so two calls can't hand back the same one. */+export async function freePorts(count: number): Promise<number[]> {+ const servers = await Promise.all(Array.from({ length: count }, () => new Promise<ReturnType<typeof createServer>>((resolve) => {+ const server = createServer();+ server.listen(0, "127.0.0.1", () => resolve(server));+ })));+ const ports = servers.map((server) => (server.address() as AddressInfo).port);+ await Promise.all(servers.map((server) => new Promise((resolve) => server.close(resolve))));+ return ports;+}++export const freePort = async () => (await freePorts(1))[0];++export const waitFor = async <T>(check: () => Promise<T | null | undefined | false> | T | null | undefined | false, ms = 5_000): Promise<T> => {+ const deadline = Date.now() + ms;+ for (;;) {+ const value = await check();+ if (value) return value;+ if (Date.now() > deadline) throw new Error("timed out waiting");+ await new Promise((resolve) => setTimeout(resolve, 25));+ }+};++export interface RelayProcess {+ url: string;+ port: number;+ pid: number;+ stop(): Promise<void>;+}++/** `relay/src/main.ts` as a child process, as on the boxes, holding only the public token key. */+export async function spawnRelay(publicKey: Buffer, port: number): Promise<RelayProcess> {+ const child = spawn(process.execPath, ["--disable-warning=ExperimentalWarning", RELAY_MAIN], {+ env: { PATH: process.env.PATH ?? "", RELAY_HOST: "127.0.0.1", RELAY_PORT: String(port), RELAY_NODE: "relay1", RELAY_TOKEN_KEYS: JSON.stringify({ k1: b64u(publicKey) }) },+ stdio: ["ignore", "pipe", "pipe"],+ });+ let err = "";+ child.stderr!.on("data", (chunk: Buffer) => (err += chunk));+ await new Promise<void>((resolve, reject) => {+ let out = "";+ child.stdout!.on("data", (chunk: Buffer) => {+ out += chunk;+ if (out.split("\n").some((line) => line.includes('"ev":"start"'))) resolve();+ });+ child.once("exit", (code) => reject(new Error(`relay exited ${code}: ${err}`)));+ });+ const exited = new Promise<void>((resolve) => child.once("exit", () => resolve()));+ return {+ url: `ws://127.0.0.1:${port}`,+ port,+ pid: child.pid ?? 0,+ async stop() {+ if (child.exitCode === null) child.kill("SIGKILL");+ await exited;+ },+ };+}++export interface State {+ devices: Array<{ id: string; route: string | null; routes: string; e2eAt?: number }>;+ e2e: { enabled: boolean; relay: string; descriptor: { k: string; h?: string; r?: string[] } | null };+ token?: string;+}++export interface Reply {+ status: number;+ headers: Record<string, string | string[] | undefined>;+ body: Buffer;+}++export interface Rig {+ harness: FakeHarness;+ companionPort: number;+ sidecarPid: number;+ hostId: Buffer;+ hid: string;+ signingPublicKey: Buffer;+ control(method: string, path: string, body?: unknown): Promise<State>;+ relayToken(): string;+ viaRelay(state: State, token: string): Promise<E2ESession<never>>;+ direct(state: State, token: string): Promise<E2ESession<never>>;+ stop(): Promise<void>;+}++/** `relayUrl` is where the sidecar's relay client dials, for every node. */+export async function startRig(relayUrl: (signingPublicKey: Buffer) => Promise<string>): Promise<Rig> {+ const harness = await startFakeHarness();+ const signingKey = generateKeyPairSync("ed25519").privateKey;+ const signingPublicKey = ed25519RawPublicKey(signingKey);+ const url = await relayUrl(signingPublicKey);+ const hostId = randomBytes(16);+ const hid = b64u(hostId);+ const controlToken = randomBytes(32).toString("base64url");+ const [companionPort, controlPort, webhookPort] = await freePorts(3);+ const dir = mkdtempSync(join(tmpdir(), "omb-e2e-sidecar-"));+ const sidecar: ChildProcess = spawn(process.execPath, [ENTRY], {+ env: {+ PATH: process.env.PATH,+ HOME: dir,+ OMB_PORT: String(harness.port),+ OMB_WEBHOOK_PORT: String(webhookPort),+ OMB_COMPANION_PORT: String(companionPort),+ OMB_CONTROL_PORT: String(controlPort),+ OMB_CONTROL_TOKEN: controlToken,+ OMB_COMPANION_DIR: dir,+ OMB_COMPANION_NAME: "Test Mac",+ OMB_COMPANION_E2E: "1",+ OMB_COMPANION_BONJOUR: "0",+ OMB_COMPANION_RELAY_URL: url,+ },+ stdio: ["ignore", "pipe", "pipe"],+ });+ if (process.env.OMB_E2E_DEBUG) for (const stream of [sidecar.stdout!, sidecar.stderr!]) stream.on("data", (chunk: Buffer) => process.stderr.write(`[sidecar] ${chunk}`));+ await new Promise<void>((resolve, reject) => {+ let out = "";+ sidecar.stdout!.on("data", (chunk: Buffer) => {+ out += chunk.toString();+ if (out.includes("companion http://")) resolve();+ });+ sidecar.stderr!.on("data", (chunk: Buffer) => (out += chunk.toString()));+ sidecar.once("exit", (code) => reject(new Error(`sidecar exited ${code}: ${out}`)));+ });+ const relayToken = () => {+ const iat = Math.floor(Date.now() / 1000);+ return mintRelayToken({ v: 1, kid: "k1", hid, iid: "test-install", iat, exp: iat + 12 * 3600 }, signingKey);+ };+ const control = async (method: string, path: string, body?: unknown): Promise<State> => {+ const res = await fetch(`http://127.0.0.1:${controlPort}${path}`, {+ method,+ headers: { "x-openmausbot-control-token": controlToken, ...(body ? { "content-type": "application/json" } : {}) },+ body: body ? JSON.stringify(body) : undefined,+ });+ if (!res.ok) throw new Error(`${method} ${path}: ${res.status} ${await res.text()}`);+ return (await res.json()) as State;+ };+ await control("PUT", "/e2e/relay", { hostId: hid, nodes: ["relay1.openmausbot.com"], relayToken: relayToken() });+ await waitFor(async () => (await control("GET", "/state")).e2e.relay === "connected", 10_000);+ const transportKey = (state: State) => fromB64u(state.e2e.descriptor!.k)!;+ return {+ harness,+ companionPort,+ sidecarPid: sidecar.pid ?? 0,+ hostId,+ hid,+ signingPublicKey,+ control,+ relayToken,+ viaRelay: (state, token) => {+ const k = transportKey(state);+ return dial({+ url: `${url}/v1/phone`,+ transportByte: TRANSPORT_RELAY,+ remoteStatic: k,+ psk: psk(credentialHash(token), keyId(k)),+ app: "test/1",+ relay: { hostId, adm: admission(credentialHash(token), hostId) },+ });+ },+ direct: (state, token) => {+ const k = transportKey(state);+ return dial({ url: `ws://127.0.0.1:${companionPort}/v1/e2e`, transportByte: TRANSPORT_DIRECT, remoteStatic: k, psk: psk(credentialHash(token), keyId(k)), app: "test/1" });+ },+ async stop() {+ sidecar.kill("SIGTERM");+ await harness.close();+ rmSync(dir, { recursive: true, force: true });+ },+ };+}++export function http(+ session: E2ESession<never>,+ method: string,+ path: string,+ options: { token?: string; body?: Buffer | string; headers?: Record<string, string> } = {},+): Promise<Reply> {+ const body = typeof options.body === "string" ? Buffer.from(options.body) : options.body;+ return new Promise((resolve, reject) => {+ const req = request(+ {+ method,+ path,+ host: "companion",+ headers: {+ ...options.headers,+ ...(options.token ? { authorization: `Bearer ${options.token}` } : {}),+ ...(body ? { "content-length": String(body.length) } : {}),+ },+ createConnection: () => session.openStream(),+ },+ (res) => {+ const chunks: Buffer[] = [];+ res.on("data", (chunk: Buffer) => chunks.push(chunk));+ res.on("end", () => resolve({ status: res.statusCode ?? 0, headers: res.headers, body: Buffer.concat(chunks) }));+ res.on("error", reject);+ },+ );+ req.on("error", reject);+ req.end(body);+ });+}++export const json = (reply: Reply) => JSON.parse(reply.body.toString("utf8")) as Record<string, unknown>;++/** Opens the event stream and collects events as they come. */+export function events(session: E2ESession<never>, token: string, lastEventId?: number) {+ const seen: Array<{ id: number; data: unknown }> = [];+ let buffer = "";+ let abort = () => {};+ const done = new Promise<void>((resolve) => {+ const req = request(+ {+ path: "/api/events",+ host: "companion",+ headers: { authorization: `Bearer ${token}`, ...(lastEventId ? { "last-event-id": String(lastEventId) } : {}) },+ createConnection: () => session.openStream(),+ },+ (res) => {+ res.setEncoding("utf8");+ res.on("data", (chunk: string) => {+ buffer += chunk;+ let end: number;+ while ((end = buffer.indexOf("\n\n")) >= 0) {+ const event = buffer.slice(0, end);+ buffer = buffer.slice(end + 2);+ const id = /^id: (\d+)$/m.exec(event);+ const data = /^data: (.*)$/m.exec(event);+ if (id && data) seen.push({ id: Number(id[1]), data: JSON.parse(data[1]) });+ }+ });+ res.on("close", resolve);+ },+ );+ req.on("error", () => resolve());+ abort = () => req.destroy();+ req.end();+ });+ return { seen, done, abort: () => abort() };+}++/** Pairs a phone through the relay with a fresh pairing window; returns its device token and id. */+export async function pairViaRelay(rig: Rig): Promise<{ token: string; id: string; session: E2ESession<never> }> {+ const state = await rig.control("POST", "/pairing");+ const pairingToken = state.token!;+ const session = await waitFor(() => rig.viaRelay(state, pairingToken).catch(() => null), 5_000);+ const paired = await http(session, "POST", "/api/pair", { body: JSON.stringify({ credential: pairingToken, deviceName: "Test Phone" }), headers: { "content-type": "application/json" } });+ if (paired.status !== 201) throw new Error(`pairing failed: ${paired.status} ${paired.body}`);+ const body = json(paired) as { token: string; device: { id: string } };+ // The relay admits the new device a moment after pairing.+ await waitFor(() => rig.viaRelay(state, body.token).then((check) => (check.shutdown(), true), () => null), 5_000);+ return { token: body.token, id: body.device.id, session };+}diff --git a/companion/test/e2e/sidecar.test.ts b/companion/test/e2e/sidecar.test.tsindex 4fa42ae74b..6445707144 100644--- a/companion/test/e2e/sidecar.test.ts+++ b/companion/test/e2e/sidecar.test.ts@@ -1,236 +1,52 @@-// The real sidecar process, a fake harness and a fake relay, driven by the reference phone.-import { spawn, type ChildProcess } from "node:child_process";-import { createHash, generateKeyPairSync, randomBytes } from "node:crypto";-import { mkdtempSync, rmSync } from "node:fs";-import { request } from "node:http";-import { createServer, type AddressInfo } from "node:net";-import { tmpdir } from "node:os";-import { join } from "node:path";-import { fileURLToPath } from "node:url";+// The real sidecar process and the real relay process, with a fake harness, driven by the reference phone.+import { createHash, randomBytes } from "node:crypto";import { afterAll, beforeAll, describe, expect, it } from "vitest";-import { admission, admissionHash, b64u, credentialHash, ed25519RawPublicKey, fromB64u, keyId, mintRelayToken, psk } from "../../src/e2e/credentials.ts";-import { generateKeyPair, NoiseError, TRANSPORT_DIRECT, TRANSPORT_RELAY } from "../../src/e2e/noise.ts";-import { dial } from "../../src/e2e/phone.ts";-import { SessionClosed, type E2ESession } from "../../src/e2e/session.ts";-import { ATTACHMENT_BYTES, attachmentByte, startFakeHarness, type FakeHarness } from "./fake-harness.ts";-import { startFakeRelay, type FakeRelay } from "./fake-relay.ts";+import { SessionClosed } from "../../src/e2e/session.ts";+import { attachmentByte } from "./fake-harness.ts";+import { events, freePort, http, json, pairViaRelay, spawnRelay, startRig, waitFor, type RelayProcess, type Rig } from "./rig.ts";-const ENTRY = fileURLToPath(new URL("../../src/index.ts", import.meta.url));-const CONTROL_TOKEN = randomBytes(32).toString("base64url");const LONG = process.env.OMB_E2E_LONG === "1";--const freePort = () =>- new Promise<number>((resolve) => {- const server = createServer();- server.listen(0, "127.0.0.1", () => {- const { port } = server.address() as AddressInfo;- server.close(() => resolve(port));- });- });--const waitFor = async <T>(check: () => Promise<T | null | undefined | false> | T | null | undefined | false, ms = 5_000): Promise<T> => {- const deadline = Date.now() + ms;- for (;;) {- const value = await check();- if (value) return value;- if (Date.now() > deadline) throw new Error("timed out waiting");- await new Promise((resolve) => setTimeout(resolve, 25));- }-};--let harness: FakeHarness;-let relay: FakeRelay;-let sidecar: ChildProcess;-let dir: string;-let companionPort: number;-let controlPort: number;-const signingKey = generateKeyPairSync("ed25519").privateKey;-const keys = new Map([["k1", ed25519RawPublicKey(signingKey)]]);-const hostId = randomBytes(16);-const hid = b64u(hostId);-const relayToken = () => {- const iat = Math.floor(Date.now() / 1000);- return mintRelayToken({ v: 1, kid: "k1", hid, iid: "test-install", iat, exp: iat + 12 * 3600 }, signingKey);-};--interface State {- devices: Array<{ id: string; route: string | null; routes: string; e2eAt?: number }>;- e2e: { enabled: boolean; relay: string; descriptor: { k: string; h?: string; r?: string[] } | null };- token?: string;-}--async function control(method: string, path: string, body?: unknown): Promise<State> {- const res = await fetch(`http://127.0.0.1:${controlPort}${path}`, {- method,- headers: { "x-openmausbot-control-token": CONTROL_TOKEN, ...(body ? { "content-type": "application/json" } : {}) },- body: body ? JSON.stringify(body) : undefined,- });- if (!res.ok) throw new Error(`${method} ${path}: ${res.status} ${await res.text()}`);- return (await res.json()) as State;-}+let rig: Rig;+let relay: RelayProcess;+let relayPort: number;+let deviceToken = "";+let deviceId = "";beforeAll(async () => {- harness = await startFakeHarness();- relay = await startFakeRelay({ keys });- [companionPort, controlPort] = [await freePort(), await freePort()];- dir = mkdtempSync(join(tmpdir(), "omb-e2e-sidecar-"));- sidecar = spawn(process.execPath, [ENTRY], {- env: {- PATH: process.env.PATH,- HOME: dir,- OMB_PORT: String(harness.port),- OMB_COMPANION_PORT: String(companionPort),- OMB_CONTROL_PORT: String(controlPort),- OMB_CONTROL_TOKEN: CONTROL_TOKEN,- OMB_COMPANION_DIR: dir,- OMB_COMPANION_NAME: "Test Mac",- OMB_COMPANION_E2E: "1",- OMB_COMPANION_BONJOUR: "0",- OMB_COMPANION_RELAY_URL: relay.url,- },- stdio: ["ignore", "pipe", "pipe"],+ relayPort = await freePort();+ rig = await startRig(async (publicKey) => {+ relay = await spawnRelay(publicKey, relayPort);+ return relay.url;});- if (process.env.OMB_E2E_DEBUG) sidecar.stderr!.on("data", (chunk: Buffer) => process.stderr.write(`[sidecar] ${chunk}`));- if (process.env.OMB_E2E_DEBUG) sidecar.stdout!.on("data", (chunk: Buffer) => process.stderr.write(`[sidecar] ${chunk}`));- await new Promise<void>((resolve, reject) => {- let out = "";- sidecar.stdout!.on("data", (chunk: Buffer) => {- out += chunk.toString();- if (out.includes("companion http://")) resolve();- });- sidecar.once("exit", (code) => reject(new Error(`sidecar exited ${code}: ${out}`)));- });- await control("PUT", "/e2e/relay", { hostId: hid, nodes: ["relay1.openmausbot.com"], relayToken: relayToken() });- await waitFor(async () => (await control("GET", "/state")).e2e.relay === "connected");}, 30_000);afterAll(async () => {- sidecar?.kill("SIGTERM");- await relay?.close();- await harness?.close();- if (dir) rmSync(dir, { recursive: true, force: true });+ await rig?.stop();+ await relay?.stop();});-const transportKey = (state: State) => fromB64u(state.e2e.descriptor!.k)!;--function viaRelay(state: State, token: string) {- const k = transportKey(state);- return dial({- url: `${relay.url}/v1/phone`,- transportByte: TRANSPORT_RELAY,- remoteStatic: k,- psk: psk(credentialHash(token), keyId(k)),- app: "test/1",- relay: { hostId, adm: admission(credentialHash(token), hostId) },- });-}--function direct(state: State, token: string) {- const k = transportKey(state);- return dial({ url: `ws://127.0.0.1:${companionPort}/v1/e2e`, transportByte: TRANSPORT_DIRECT, remoteStatic: k, psk: psk(credentialHash(token), keyId(k)), app: "test/1" });-}--interface Reply {- status: number;- headers: Record<string, string | string[] | undefined>;- body: Buffer;-}--function http(session: E2ESession<never>, method: string, path: string, options: { token?: string; body?: Buffer | string; headers?: Record<string, string> } = {}): Promise<Reply> {- const body = typeof options.body === "string" ? Buffer.from(options.body) : options.body;- return new Promise((resolve, reject) => {- const req = request(- {- method,- path,- host: "companion",- headers: {- ...options.headers,- ...(options.token ? { authorization: `Bearer ${options.token}` } : {}),- ...(body ? { "content-length": String(body.length) } : {}),- },- createConnection: () => session.openStream(),- },- (res) => {- const chunks: Buffer[] = [];- res.on("data", (chunk: Buffer) => chunks.push(chunk));- res.on("end", () => resolve({ status: res.statusCode ?? 0, headers: res.headers, body: Buffer.concat(chunks) }));- res.on("error", reject);- },- );- req.on("error", reject);- req.end(body);- });-}--const json = (reply: Reply) => JSON.parse(reply.body.toString("utf8")) as Record<string, unknown>;+const state = () => rig.control("GET", "/state");-/** Opens the event stream and collects events until `until` says stop. */-function events(session: E2ESession<never>, token: string, lastEventId?: number) {- const seen: Array<{ id: number; data: unknown }> = [];- let buffer = "";- let abort = () => {};- const done = new Promise<void>((resolve) => {- const req = request(- {- path: "/api/events",- host: "companion",- headers: { authorization: `Bearer ${token}`, ...(lastEventId ? { "last-event-id": String(lastEventId) } : {}) },- createConnection: () => session.openStream(),- },- (res) => {- res.setEncoding("utf8");- res.on("data", (chunk: string) => {- buffer += chunk;- let end: number;- while ((end = buffer.indexOf("\n\n")) >= 0) {- const event = buffer.slice(0, end);- buffer = buffer.slice(end + 2);- const id = /^id: (\d+)$/m.exec(event);- const data = /^data: (.*)$/m.exec(event);- if (id && data) seen.push({ id: Number(id[1]), data: JSON.parse(data[1]) });- }- });- res.on("close", resolve);- },- );- req.on("error", () => resolve());- abort = () => req.destroy();- req.end();- });- return { seen, done, abort: () => abort() };-}--let deviceToken = "";-let deviceId = "";--describe("the sidecar's end-to-end connection", () => {+describe("the sidecar's end-to-end connection, through the real relay", () => {it("pairs through the relay with the pairing token, then serves the new device in the same session", async () => {- const state = await control("POST", "/pairing");- const pairingToken = state.token!;- expect(state.e2e.descriptor).toEqual({ v: 1, k: expect.any(String), h: hid, r: ["relay1.openmausbot.com"] });- const adm = admissionHash(admission(credentialHash(pairingToken), hostId));- await waitFor(() => relay.admitted(hid).has(adm));- const session = await viaRelay(state, pairingToken);- expect((await http(session, "GET", "/api/threads/t1/messages")).status).toBe(401);- const paired = await http(session, "POST", "/api/pair", { body: JSON.stringify({ credential: pairingToken, deviceName: "Test Phone" }), headers: { "content-type": "application/json" } });- expect(paired.status).toBe(201);- const body = json(paired) as { token: string; device: { id: string }; e2e: unknown };- expect(body.e2e).toEqual(state.e2e.descriptor);- deviceToken = body.token;- deviceId = body.device.id;- expect(json(await http(session, "GET", "/api/health", { token: deviceToken }))).toEqual({ app: "openmausbot" });- const after = await control("GET", "/state");- expect(after.devices).toEqual([expect.objectContaining({ id: deviceId, route: "relay", routes: "any", e2eAt: expect.any(Number) })]);- session.shutdown();+ const before = await rig.control("POST", "/pairing");+ expect(before.e2e.descriptor).toEqual({ v: 1, k: expect.any(String), h: rig.hid, r: ["relay1.openmausbot.com"] });+ await rig.control("DELETE", "/pairing");+ const paired = await pairViaRelay(rig);+ deviceToken = paired.token;+ deviceId = paired.id;+ expect((await http(paired.session, "GET", "/api/threads/t1/messages", { token: "omb_other" })).status).toBe(401);+ expect(json(await http(paired.session, "GET", "/api/health", { token: deviceToken }))).toEqual({ app: "openmausbot" });+ expect((await state()).devices).toEqual([expect.objectContaining({ id: deviceId, route: "relay", routes: "any", e2eAt: expect.any(Number) })]);+ paired.session.shutdown();});it("carries a 4 MiB event, a 25 MiB upload and a Range read through the relay", async () => {- const session = await viaRelay(await control("GET", "/state"), deviceToken);+ const session = await rig.viaRelay(await state(), deviceToken);const stream = events(session, deviceToken);const big = "x".repeat(4 * 1024 * 1024 - 1024);- const id = harness.emit({ type: "shot", blob: big });+ const id = rig.harness.emit({ type: "shot", blob: big });await waitFor(() => stream.seen.find((event) => event.id === id), 15_000);expect((stream.seen.find((event) => event.id === id)!.data as { blob: string }).blob.length).toBe(big.length);const upload = randomBytes(25 * 1024 * 1024);@@ -239,164 +55,92 @@ describe("the sidecar's end-to-end connection", () => {const ranged = await http(session, "GET", "/api/attachments/voice.mp3", { token: deviceToken, headers: { range: "bytes=1000-1999" } });expect(ranged.status).toBe(206);expect(ranged.body.equals(Buffer.from(Array.from({ length: 1000 }, (_, index) => attachmentByte(1000 + index))))).toBe(true);- expect(ATTACHMENT_BYTES).toBeGreaterThan(1999);stream.abort();session.shutdown();}, 60_000);it("is reached directly on /v1/e2e, labelled Wi-Fi, and the plain listener then refuses the device", async () => {- const session = await direct(await control("GET", "/state"), deviceToken);+ const session = await rig.direct(await state(), deviceToken);expect((await http(session, "GET", "/api/health", { token: deviceToken })).status).toBe(200);- expect((await control("GET", "/state")).devices[0].route).toBe("wifi");- const plain = await fetch(`http://127.0.0.1:${companionPort}/api/threads/t1/messages`, { headers: { authorization: `Bearer ${deviceToken}` } });+ expect((await state()).devices[0].route).toBe("wifi");+ const plain = await fetch(`http://127.0.0.1:${rig.companionPort}/api/threads/t1/messages`, { headers: { authorization: `Bearer ${deviceToken}` } });expect(plain.status).toBe(426);expect(await plain.json()).toEqual({ error: "update_app" });- expect((await fetch(`http://127.0.0.1:${companionPort}/api/health`, { headers: { authorization: `Bearer ${deviceToken}` } })).status).toBe(200);+ expect((await fetch(`http://127.0.0.1:${rig.companionPort}/api/health`, { headers: { authorization: `Bearer ${deviceToken}` } })).status).toBe(200);session.shutdown();});it("refuses another device's token inside a session", async () => {- const state = await control("POST", "/pairing");- const other = await fetch(`http://127.0.0.1:${companionPort}/api/pair`, {+ const pairing = await rig.control("POST", "/pairing");+ const other = await fetch(`http://127.0.0.1:${rig.companionPort}/api/pair`, {method: "POST",headers: { "content-type": "application/json" },- body: JSON.stringify({ credential: state.token, deviceName: "Other" }),+ body: JSON.stringify({ credential: pairing.token, deviceName: "Other" }),});const otherToken = ((await other.json()) as { token: string }).token;- const session = await direct(state, deviceToken);+ const session = await rig.direct(pairing, deviceToken);expect((await http(session, "GET", "/api/health", { token: otherToken })).status).toBe(401);session.shutdown();});it(`waits ${LONG ? 105 : 35} s for headers without a deadline of its own`, async () => {- harness.provideWaitMs = LONG ? 104_000 : 35_000;- const session = await viaRelay(await control("GET", "/state"), deviceToken);+ rig.harness.provideWaitMs = LONG ? 104_000 : 35_000;+ const session = await rig.viaRelay(await state(), deviceToken);const reply = await http(session, "POST", "/api/bots/b1/secret-cards/c1/provide", { token: deviceToken, body: "{}", headers: { "content-type": "application/json" } });expect(json(reply)).toEqual({ provided: true });session.shutdown();- harness.provideWaitMs = 0;+ rig.harness.provideWaitMs = 0;}, 120_000);- it("resumes the event stream from its cursor after the relay dies, with no loss and no duplicates", async () => {- const first = await viaRelay(await control("GET", "/state"), deviceToken);+ it("resumes the event stream from its cursor after the relay process dies, with no loss and no duplicates", async () => {+ const first = await rig.viaRelay(await state(), deviceToken);const before = events(first, deviceToken);- const ids = [harness.emit({ n: 1 }), harness.emit({ n: 2 })];+ const ids = [rig.harness.emit({ n: 1 }), rig.harness.emit({ n: 2 })];await waitFor(() => before.seen.some((event) => event.id === ids[1]));- const port = relay.port;- await relay.kill();+ await relay.stop();expect(await first.closed).not.toBe(1000);- const missed = harness.emit({ n: 3 });- relay = await startFakeRelay({ keys, port });- await waitFor(async () => (await control("GET", "/state")).e2e.relay === "connected", 10_000);- await waitFor(() => relay.admitted(hid).size > 0);- const second = await viaRelay(await control("GET", "/state"), deviceToken);+ const missed = rig.harness.emit({ n: 3 });+ relay = await spawnRelay(rig.signingPublicKey, relayPort);+ await waitFor(async () => (await state()).e2e.relay === "connected", 15_000);+ const second = await waitFor(async () => rig.viaRelay(await state(), deviceToken).catch(() => null), 10_000);const after = events(second, deviceToken, before.seen.at(-1)!.id);- const next = harness.emit({ n: 4 });+ const next = rig.harness.emit({ n: 4 });await waitFor(() => after.seen.some((event) => event.id === next));const all = [...before.seen, ...after.seen].map((event) => event.id).filter((id) => id >= ids[0]);expect(all).toEqual([ids[0], ids[1], missed, next]);after.abort();second.shutdown();- }, 30_000);+ }, 40_000);- it("drops a device restricted to Wi-Fi and Tailscale from the relay at once, and keeps it direct", async () => {- const state = await control("GET", "/state");- const relayed = await viaRelay(state, deviceToken);- const adm = admissionHash(admission(credentialHash(deviceToken), hostId));- await control("PUT", `/devices/${deviceId}/routes`, { routes: "local" });+ it("drops a device restricted to Wi-Fi and Tailscale from the relay at once: the relay answers 4404, direct still works", async () => {+ const current = await state();+ const relayed = await rig.viaRelay(current, deviceToken);+ await rig.control("PUT", `/devices/${deviceId}/routes`, { routes: "local" });expect(await relayed.closed).toBeGreaterThan(0);- await waitFor(() => !relay.admitted(hid).has(adm));- await expect(viaRelay(state, deviceToken)).rejects.toEqual(new SessionClosed(4404));- const session = await direct(state, deviceToken);+ const refused = await waitFor(async () => {+ const outcome = await rig.viaRelay(current, deviceToken).then((session) => (session.shutdown(), null), (error: unknown) => error);+ return outcome instanceof SessionClosed && outcome.code === 4404 ? outcome : null;+ }, 5_000);+ expect(refused.code).toBe(4404);+ const session = await rig.direct(current, deviceToken);const endpoints = json(await http(session, "GET", "/api/companion/endpoints", { token: deviceToken }));- expect(endpoints.e2e).toEqual({ v: 1, k: state.e2e.descriptor!.k, routes: "local" });+ expect(endpoints.e2e).toEqual({ v: 1, k: current.e2e.descriptor!.k, routes: "local" });session.shutdown();- await control("PUT", `/devices/${deviceId}/routes`, { routes: "any" });- await waitFor(() => relay.admitted(hid).has(adm));- });-- describe("against a malicious relay, every attack ends in a closed session and nothing delivered", () => {- const flip = (data: Buffer) => {- const out = Buffer.from(data);- out[out.length - 1] ^= 1;- return out;- };- /** One upload through a tampered relay: it must never reach the harness. */- async function attempt(tamper: NonNullable<FakeRelay["tamper"]>): Promise<"refused" | "delivered"> {- relay.tamper = tamper;- try {- const session = await viaRelay(await control("GET", "/state"), deviceToken);- const reply = await http(session, "POST", "/api/files", { token: deviceToken, body: randomBytes(300_000), headers: { "content-type": "application/octet-stream" } });- session.shutdown();- return reply.status === 201 ? "delivered" : "refused";- } catch {- return "refused";- } finally {- relay.tamper = null;- }- }-- it("key swap: a message 2 the computer didn't write is a hard stop", async () => {- relay.tamper = (direction, data, index) =>- direction === "toPhone" && index === 0 ? Buffer.concat([generateKeyPair().publicKey, randomBytes(data.length - 65)]) : data;- await expect(viaRelay(await control("GET", "/state"), deviceToken)).rejects.toBeInstanceOf(NoiseError);- relay.tamper = null;- });-- it("posing as the phone: a message 1 without the psk is refused with 4001", async () => {- const forged = (await import("../../src/e2e/noise.ts")).phoneHello(- { remoteStatic: transportKey(await control("GET", "/state")), psk: randomBytes(32), transport: TRANSPORT_RELAY },- Buffer.from(JSON.stringify({ v: 1, conn: b64u(randomBytes(16)) })),- "",- ).message1;- expect(await attempt((direction, data, index) => (direction === "toHost" && index === 0 ? forged : data))).toBe("refused");- });-- it("replaying, dropping, truncating or flipping a record", async () => {- let previous: Buffer | null = null;- const replay: NonNullable<FakeRelay["tamper"]> = (direction, data, index) => {- if (direction !== "toHost" || index < 1) return data;- const out = index === 3 && previous ? previous : data;- previous = data;- return out;- };- expect(await attempt(replay)).toBe("refused");- expect(await attempt((direction, data, index) => (direction === "toHost" && index === 2 ? null : data))).toBe("refused");- expect(await attempt((direction, data, index) => (direction === "toHost" && index === 2 ? data.subarray(0, data.length - 1) : data))).toBe("refused");- expect(await attempt((direction, data, index) => (direction === "toHost" && index === 2 ? flip(data) : data))).toBe("refused");- });-- it("reflection: the computer's own record sent back to it", async () => {- let fromComputer: Buffer | null = null;- let reflected = false;- expect(await attempt((direction, data, index) => {- if (direction === "toPhone" && index >= 1) fromComputer ??= data;- if (direction !== "toHost" || index < 2 || !fromComputer || reflected) return data;- reflected = true;- return fromComputer;- })).toBe("refused");- });-- it("a stale message 2 from an earlier session", async () => {- let old: Buffer | null = null;- relay.tamper = (direction, data, index) => {- if (direction === "toPhone" && index === 0) old = data;- return data;- };- (await viaRelay(await control("GET", "/state"), deviceToken)).shutdown();- relay.tamper = (direction, data, index) => (direction === "toPhone" && index === 0 && old ? old : data);- await expect(viaRelay(await control("GET", "/state"), deviceToken)).rejects.toBeInstanceOf(NoiseError);- relay.tamper = null;- });+ await rig.control("PUT", `/devices/${deviceId}/routes`, { routes: "any" });});- it("closes a removed device's sessions within a second, with 4001", async () => {- const state = await control("GET", "/state");- const session = await direct(state, deviceToken);+ it("tells a removed phone so inside the encryption, then closes with 4001, through the relay and directly", async () => {+ const current = await state();+ const relayed = await waitFor(() => rig.viaRelay(current, deviceToken).catch(() => null), 5_000);+ const direct = await rig.direct(current, deviceToken);const started = Date.now();- await control("DELETE", `/devices/${deviceId}`);- expect(await session.closed).toBe(4001);+ await rig.control("DELETE", `/devices/${deviceId}`);+ expect(await direct.closed).toBe(4001);+ await relayed.closed;expect(Date.now() - started).toBeLessThan(1_000);- await expect(direct(state, deviceToken)).rejects.toEqual(new SessionClosed(4001));+ expect(direct.removed).toBe(true);+ // Through the relay only the authenticated GoAway counts; the close code is whatever the relay sends.+ expect(relayed.removed).toBe(true);+ await expect(rig.direct(current, deviceToken)).rejects.toEqual(new SessionClosed(4001));});});diff --git a/companion/test/e2e/soak.test.ts b/companion/test/e2e/soak.test.tsnew file mode 100644index 0000000000..5db3fc944d--- /dev/null+++ b/companion/test/e2e/soak.test.ts@@ -0,0 +1,83 @@+// An 8-hour Local VM screen stream, compressed: about 10 GB in 12 KiB frames (some 870k records) through the real+// sidecar and the real relay, with a relay token refresh and a control-socket replacement mid-run. Opt-in like the+// nightly fuzz: OMB_E2E_SOAK=1 (OMB_E2E_SOAK_BYTES to change the size). Run it through the heavy-run lock.+import { execFileSync } from "node:child_process";+import { request } from "node:http";+import { afterAll, beforeAll, describe, expect, it } from "vitest";++import { freePort, pairViaRelay, spawnRelay, startRig, waitFor, type RelayProcess, type Rig } from "./rig.ts";++const ENABLED = process.env.OMB_E2E_SOAK === "1";+const TOTAL = Number(process.env.OMB_E2E_SOAK_BYTES) || 10 * 1024 ** 3;+const rssMb = (pid: number) => Number(execFileSync("ps", ["-o", "rss=", "-p", String(pid)], { encoding: "utf8" }).trim()) / 1024;++let rig: Rig;+let relay: RelayProcess;++describe.skipIf(!ENABLED)("a long screen stream through the relay", () => {+ beforeAll(async () => {+ const port = await freePort();+ rig = await startRig(async (publicKey) => {+ relay = await spawnRelay(publicKey, port);+ return relay.url;+ });+ }, 30_000);++ afterAll(async () => {+ await rig?.stop();+ await relay?.stop();+ });++ it("keeps the data socket through a token refresh and a control-socket replacement, with flat memory", async () => {+ const { token, session } = await pairViaRelay(rig);+ const samples: Array<{ at: number; sidecar: number; relay: number; phone: number }> = [];+ let received = 0;+ let mismatches = 0;+ let refreshed = false;+ let replaced = false;+ const started = Date.now();+ await new Promise<void>((resolve, reject) => {+ const req = request(+ { path: `/api/attachments/soak-${TOTAL}.mp3`, host: "companion", headers: { authorization: `Bearer ${token}` }, createConnection: () => session.openStream() },+ (res) => {+ res.on("data", (chunk: Buffer) => {+ if (chunk[0] !== received % 251) mismatches += 1;+ received += chunk.length;+ const fraction = received / TOTAL;+ if (samples.length < Math.floor(fraction * 20) + 1) {+ samples.push({ at: received, sidecar: rssMb(rig.sidecarPid), relay: rssMb(relay.pid), phone: process.memoryUsage().rss / 1024 ** 2 });+ }+ if (!refreshed && fraction > 0.3) {+ refreshed = true;+ void rig.control("PUT", "/e2e/relay", { hostId: rig.hid, nodes: ["relay1.openmausbot.com"], relayToken: rig.relayToken() });+ }+ if (!replaced && fraction > 0.6) {+ replaced = true;+ // A different node list makes the sidecar redial: a new control socket replaces the old one.+ void rig.control("PUT", "/e2e/relay", { hostId: rig.hid, nodes: ["relay1.openmausbot.com", "relay2.openmausbot.com"], relayToken: rig.relayToken() });+ }+ });+ res.on("end", resolve);+ res.on("error", reject);+ },+ );+ req.on("error", reject);+ req.end();+ });+ const seconds = (Date.now() - started) / 1000;+ const records = session.records.received;+ console.log(JSON.stringify({ bytes: received, records, seconds, mbPerSecond: Math.round(received / 1024 ** 2 / seconds), samples }));+ expect(received).toBe(TOTAL);+ expect(mismatches).toBe(0);+ expect(refreshed && replaced).toBe(true);+ expect(session.state).toBe("open");+ await waitFor(async () => (await rig.control("GET", "/state")).e2e.relay === "connected", 10_000);+ // Flat: after the first tenth, no process grows by more than 64 MB.+ const settled = samples.filter((sample) => sample.at > TOTAL / 10);+ for (const key of ["sidecar", "relay", "phone"] as const) {+ const values = settled.map((sample) => sample[key]);+ expect(Math.max(...values) - values[0], key).toBeLessThan(64);+ }+ session.shutdown();+ }, 60 * 60_000);+});