Open-source Grok Bot alternative with a virtual machine that bots can use
TypeScript ai-agentsclaude-codecodexcomputer-usedockerelectrongrokgrok-botgrok-bot-alternativeself-hostedtypescript
companion: serve the end-to-end connection on Wi-Fi, Tailscale and the relay
milind-soniedc506e10e15
diff --git a/companion/src/control.ts b/companion/src/control.tsindex 69bfe100ef..828f4a4d83 100644--- a/companion/src/control.ts+++ b/companion/src/control.ts@@ -6,6 +6,7 @@ import { randomBytes, timingSafeEqual } from "node:crypto";import { createServer, type Server, type ServerResponse } from "node:http";import type { DeviceRegistry, DeviceRoutes } from "./devices.ts";+import type { E2EDescriptor } from "./e2e/descriptor.ts";import type { LiveRoute } from "./e2e/registry.ts";import { companionEndpointCandidates, hostedCompanionUrl } from "./endpoints.ts";import { lanAddresses, lanInterfaces, tailnetName, tailscaleAddress } from "./listener.ts";@@ -48,6 +49,8 @@ export interface E2EStatus {enabled: boolean;relay: "connected" | "connecting" | "off";node: string | null;+ /** What the pairing QR carries as `e2e`. */+ descriptor: E2EDescriptor | null;}/** A bracketed IPv6 literal has colons of its own. A malformed authority comes@@ -214,7 +217,7 @@ export function companionState(options: Omit<ControlOptions, "controlToken">) {...(secretPublicKey ? { secretPublicKey } : {}),pairing: pairing ? { code: pairing.code, token: pairing.token, expiresAt: pairing.expiresAt } : null,devices: options.devices.list().map((device) => ({ ...device, route: options.liveRoutes?.()[device.id] ?? null })),- e2e: options.e2e?.() ?? { enabled: false, relay: "off", node: null },+ e2e: options.e2e?.() ?? { enabled: false, relay: "off", node: null, descriptor: null },// An empty list from an unreadable file must not read as "nothing paired"....(options.devices.devicesUnreadable() ? { devicesUnreadable: true } : {}),connectedDeviceIds: options.connectedDeviceIds?.() ?? [],diff --git a/companion/src/e2e/registry.ts b/companion/src/e2e/registry.tsindex 13e7de2ec0..c12e802a24 100644--- a/companion/src/e2e/registry.ts+++ b/companion/src/e2e/registry.ts@@ -9,7 +9,8 @@ import { CLOSE, TRANSPORT_RELAY, type KeyPair, type PskCandidate, type Transportimport { E2ESession, type RecordTransport } from "./session.ts";export type LiveRoute = "wifi" | "tailscale" | "relay";-export type Peer = { kind: "device"; id: string } | { kind: "pairing" };+/** A pairing peer carries the admission value its window had, so a relay session stays admitted after pairing. */+export type Peer = { kind: "device"; id: string } | { kind: "pairing"; admHash: string | null };/** Shared by every stream of one session, so a pairing session becomes that device's once it has paired. */export interface E2EContext {@@ -25,6 +26,9 @@ export interface RelayIdentity {interface Live {session: E2ESession<Peer>;context: E2EContext;+ /** A relay session opened with a pairing token: kept in the admission set until it ends, or redeeming the window+ * would make the relay close the very session that paired. */+ pairingAdmission: string | null;}const ROUTE_RANK: Record<LiveRoute, number> = { wifi: 0, tailscale: 1, relay: 2 };@@ -39,11 +43,17 @@ export class E2ERegistry {#key: KeyPair | null = null;#relay: RelayIdentity | null = null;#pending = 0;+ readonly #admissionListeners = new Set<() => void>();constructor(devices: DeviceRegistry) {this.#devices = devices;}+ /** The admission set may have changed for a reason the device registry doesn't see. */+ onAdmissionChange(listener: () => void): void {+ this.#admissionListeners.add(listener);+ }+get enabled(): boolean {return this.#key !== null;}@@ -71,7 +81,11 @@ export class E2ERegistry {const hash = credentialHashFromHex(device.tokenHash);if (hash) out.push({ id: { kind: "device", id: device.id }, psk: psk(hash, id) });}- for (const window of this.#devices.pairingWindows()) out.push({ id: { kind: "pairing" }, psk: psk(credentialHash(window.token), id) });+ for (const window of this.#devices.pairingWindows()) {+ const hash = credentialHash(window.token);+ const admHash = this.#relay ? admissionHash(admission(hash, this.#relay.hostId)) : null;+ out.push({ id: { kind: "pairing", admHash }, psk: psk(hash, id) });+ }return out;}@@ -86,7 +100,8 @@ export class E2ERegistry {if (hash) out.push(admissionHash(admission(hash, hostId)));}for (const window of this.#devices.pairingWindows()) out.push(admissionHash(admission(credentialHash(window.token), hostId)));- return out.sort();+ for (const live of this.#live) if (live.pairingAdmission) out.push(live.pairingAdmission);+ return [...new Set(out)].sort();}/** For one device (null: a phone that is pairing now). A restricted device never learns the relay. */@@ -110,7 +125,7 @@ export class E2ERegistry {return null;}this.#pending += 1;- const live: Live = { context: { peer: { kind: "pairing" }, route }, session: null as unknown as E2ESession<Peer> };+ const live: Live = { context: { peer: { kind: "pairing", admHash: null }, route }, session: null as unknown as E2ESession<Peer>, pairingAdmission: null };live.session = E2ESession.computer<Peer>({transport,transportByte,@@ -121,6 +136,7 @@ export class E2ERegistry {live.context.peer = peer;this.#live.add(live);if (peer.kind === "device") return this.#devices.markE2E(peer.id);+ if (transportByte === TRANSPORT_RELAY) live.pairingAdmission = peer.admHash;const timer = setTimeout(() => {if (live.context.peer.kind === "pairing") live.session.close(CLOSE.rejected);}, PAIRING_SESSION_MS);@@ -138,6 +154,7 @@ export class E2ERegistry {void live.session.closed.then(() => {settle();this.#live.delete(live);+ if (live.pairingAdmission) for (const listener of this.#admissionListeners) listener();});return live.session;}diff --git a/companion/src/index.ts b/companion/src/index.tsindex d38ddf1211..50527fe280 100755--- a/companion/src/index.ts+++ b/companion/src/index.ts@@ -198,6 +198,7 @@ function configureE2E(message: Record<string, unknown>): void {}devices.onChange(() => relay?.refreshAdmission());+e2e.onAdmissionChange(() => relay?.refreshAdmission());const control = createControlServer({devices,@@ -222,7 +223,7 @@ const control = createControlServer({void notifyDeviceRevoked({ harnessPort: HARNESS_PORT, deviceId, mutationToken: mutationToken ?? undefined });},refreshTailscale: () => refreshTailnetName(),- e2e: () => ({ enabled: e2e.enabled, relay: relay?.status ?? "off", node: relay?.node ?? null }),+ e2e: () => ({ enabled: e2e.enabled, relay: relay?.status ?? "off", node: relay?.node ?? null, descriptor: e2e.descriptor(null) }),liveRoutes: () => e2e.routes(),routesChanged: (deviceId, routes) => {relay?.refreshAdmission();diff --git a/companion/test/e2e/fake-harness.ts b/companion/test/e2e/fake-harness.tsnew file mode 100644index 0000000000..e21b1cb174--- /dev/null+++ b/companion/test/e2e/fake-harness.ts@@ -0,0 +1,96 @@+// A harness for the sidecar to front in tests: health, an event stream with resume, uploads, a Range download and a+// long wait before headers.+import { createHash } from "node:crypto";+import { createServer, type ServerResponse } from "node:http";+import type { AddressInfo } from "node:net";++export interface FakeHarness {+ port: number;+ /** Appends an event to the log; every open stream gets it. Returns its id. */+ emit(data: unknown): number;+ /** How long the secret-card `provide` route waits before answering. */+ provideWaitMs: number;+ keepaliveMs: number;+ close(): Promise<void>;+}++export const ATTACHMENT_BYTES = 1024 * 1024;+export const attachmentByte = (index: number) => (index * 7) % 256;++export async function startFakeHarness(): Promise<FakeHarness> {+ const log: Array<{ id: number; text: string }> = [];+ const streams = new Set<ServerResponse>();+ const state = { provideWaitMs: 0, keepaliveMs: 200 };+ const write = (res: ServerResponse, event: { id: number; text: string }) => res.write(`id: ${event.id}\ndata: ${event.text}\n\n`);++ const server = createServer((req, res) => {+ const url = new URL(req.url ?? "/", "http://harness");+ const path = url.pathname;+ if (path === "/api/health") return void res.writeHead(200, { "content-type": "application/json" }).end('{"app":"openmausbot"}');+ if (path === "/api/config") return void res.writeHead(200, { "content-type": "application/json" }).end('{"computerName":"Test Mac"}');+ if (path === "/api/events") {+ const since = Number(req.headers["last-event-id"] ?? url.searchParams.get("since") ?? 0) || 0;+ res.writeHead(200, { "content-type": "text/event-stream", "cache-control": "no-cache" });+ for (const event of log) if (event.id > since) write(res, event);+ streams.add(res);+ const keepalive = setInterval(() => res.write(": keepalive\n\n"), state.keepaliveMs);+ res.on("close", () => {+ clearInterval(keepalive);+ streams.delete(res);+ });+ return;+ }+ if (req.method === "POST" && path === "/api/files") {+ const hash = createHash("sha256");+ let bytes = 0;+ req.on("data", (chunk: Buffer) => {+ bytes += chunk.length;+ hash.update(chunk);+ });+ req.on("end", () => res.writeHead(201, { "content-type": "application/json" }).end(JSON.stringify({ bytes, sha256: hash.digest("hex") })));+ return;+ }+ 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 ?? ""));+ if (!range) return void res.writeHead(200, { "content-type": "audio/mpeg", "content-length": body.length }).end(body);+ const [start, end] = [Number(range[1]), Number(range[2])];+ return void res+ .writeHead(206, { "content-type": "audio/mpeg", "content-range": `bytes ${start}-${end}/${body.length}`, "content-length": end - start + 1 })+ .end(body.subarray(start, end + 1));+ }+ if (req.method === "POST" && /\/secret-cards\/[\w-]+\/provide$/.test(path)) {+ req.resume();+ const timer = setTimeout(() => res.writeHead(200, { "content-type": "application/json" }).end('{"provided":true}'), state.provideWaitMs);+ return void res.on("close", () => clearTimeout(timer));+ }+ res.writeHead(404, { "content-type": "application/json" }).end('{"error":"not found"}');+ });++ await new Promise<void>((resolve) => server.listen(0, "127.0.0.1", resolve));+ return {+ port: (server.address() as AddressInfo).port,+ emit(data) {+ const event = { id: log.length + 1, text: JSON.stringify(data) };+ log.push(event);+ for (const res of streams) write(res, event);+ return event.id;+ },+ get provideWaitMs() {+ return state.provideWaitMs;+ },+ set provideWaitMs(value: number) {+ state.provideWaitMs = value;+ },+ get keepaliveMs() {+ return state.keepaliveMs;+ },+ set keepaliveMs(value: number) {+ state.keepaliveMs = value;+ },+ async close() {+ server.closeAllConnections();+ await new Promise<void>((resolve) => server.close(() => resolve()));+ },+ };+}diff --git a/companion/test/e2e/fake-relay.ts b/companion/test/e2e/fake-relay.tsnew file mode 100644index 0000000000..959c25f3e4--- /dev/null+++ b/companion/test/e2e/fake-relay.ts@@ -0,0 +1,186 @@+// A relay for tests, following README section 9: host control and data sockets, phone sockets, admission sets,+// splicing, and the close codes. `tamper` lets a test play a malicious relay on spliced bytes.+import { createHash, randomBytes } from "node:crypto";+import { createServer, type IncomingMessage } from "node:http";+import type { AddressInfo } from "node:net";+import type { Duplex } from "node:stream";+import { WebSocket, WebSocketServer, type RawData } from "ws";++import { b64u, fromB64u, verifyRelayToken } from "../../src/e2e/credentials.ts";++export type Direction = "toHost" | "toPhone";++interface Host {+ control: WebSocket;+ set: Set<string>;+ pending: Map<string, { phone: WebSocket; admHash: string; timer: ReturnType<typeof setTimeout> }>;+ sessions: Set<{ phone: WebSocket; data: WebSocket; admHash: string }>;+}++export interface FakeRelayOptions {+ keys: Map<string, Uint8Array>;+ port?: number;+ /** Return the bytes to pass on, or null to drop them. */+ tamper?: (direction: Direction, data: Buffer, index: number) => Buffer | null;+}++export interface FakeRelay {+ port: number;+ url: string;+ hosts: Map<string, Host>;+ /** Close codes sent, in order, for assertions. */+ closes: Array<{ kind: string; code: number }>;+ admitted(hid: string): Set<string>;+ restart(): void;+ /** Drops every socket without a close frame, as a crashed process would. */+ kill(): Promise<void>;+ close(): Promise<void>;+}++const PROTOCOL = "omb-relay.v1";+const toBuffer = (data: RawData): Buffer => (Array.isArray(data) ? Buffer.concat(data) : Buffer.from(data as ArrayBuffer));++export async function startFakeRelay(options: FakeRelayOptions): Promise<FakeRelay> {+ const hosts = new Map<string, Host>();+ const closes: FakeRelay["closes"] = [];+ const server = createServer((_req, res) => res.writeHead(404).end());+ const wss = new WebSocketServer({+ noServer: true,+ maxPayload: 70_000,+ handleProtocols: (protocols) => (protocols.has(PROTOCOL) ? PROTOCOL : false),+ });+ const close = (socket: WebSocket, kind: string, code: number, reason = "") => {+ closes.push({ kind, code });+ if (socket.readyState === WebSocket.OPEN) socket.close(code, reason);+ };+ const now = () => Math.floor(Date.now() / 1000);++ const splice = (host: Host, phone: WebSocket, data: WebSocket, admHash: string) => {+ const session = { phone, data, admHash };+ host.sessions.add(session);+ let toHost = 0;+ let toPhone = 0;+ phone.on("message", (raw, isBinary) => {+ if (!isBinary) return close(phone, "phone", 4400);+ const out = options.tamper ? options.tamper("toHost", toBuffer(raw), toHost++) : toBuffer(raw);+ if (out && data.readyState === WebSocket.OPEN) data.send(out);+ });+ data.on("message", (raw, isBinary) => {+ if (!isBinary) return close(data, "data", 4400);+ const out = options.tamper ? options.tamper("toPhone", toBuffer(raw), toPhone++) : toBuffer(raw);+ if (out && phone.readyState === WebSocket.OPEN) phone.send(out);+ });+ const end = (other: WebSocket) => (code: number) => {+ host.sessions.delete(session);+ if (other.readyState === WebSocket.OPEN) other.close(code >= 3000 && code <= 4999 ? code : 1000);+ };+ phone.on("close", end(data));+ data.on("close", end(phone));+ phone.send(JSON.stringify({ t: "ready" }));+ };++ const onFirst = (socket: WebSocket, kind: string, handle: (message: Record<string, unknown>) => void) => {+ const timer = setTimeout(() => close(socket, kind, 4400), 5_000);+ socket.once("message", (raw, isBinary) => {+ clearTimeout(timer);+ if (isBinary || toBuffer(raw).length > 4096) return close(socket, kind, 4400);+ try {+ handle(JSON.parse(toBuffer(raw).toString("utf8")) as Record<string, unknown>);+ } catch {+ close(socket, kind, 4400);+ }+ });+ };++ const hostControl = (socket: WebSocket) =>+ onFirst(socket, "host", (message) => {+ if (message.t !== "auth" || typeof message.token !== "string") return close(socket, "host", 4400);+ const verified = verifyRelayToken(message.token, options.keys, now());+ if (!verified.ok) return close(socket, "host", 4401);+ const hid = verified.claims.hid;+ const previous = hosts.get(hid);+ if (previous) close(previous.control, "host", 4409);+ const host: Host = { control: socket, set: new Set(), pending: new Map(), sessions: previous?.sessions ?? new Set() };+ hosts.set(hid, host);+ socket.send(JSON.stringify({ t: "hello", v: 1, node: "relay1", sessionsMax: 16 }));+ socket.on("message", (raw, isBinary) => {+ if (isBinary) return close(socket, "host", 4400);+ const next = JSON.parse(toBuffer(raw).toString("utf8")) as Record<string, unknown>;+ if (next.t === "auth") {+ const refreshed = typeof next.token === "string" ? verifyRelayToken(next.token, options.keys, now(), hid) : null;+ if (!refreshed?.ok) close(socket, "host", 4401);+ } else if (next.t === "admit" && Array.isArray(next.set) && next.set.length <= 32) {+ host.set = new Set(next.set as string[]);+ for (const session of host.sessions) {+ if (!host.set.has(session.admHash)) close(session.phone, "phone", 4404);+ }+ } else {+ close(socket, "host", 4400);+ }+ });+ socket.on("close", () => {+ if (hosts.get(hid) === host) hosts.delete(hid);+ });+ });++ const hostData = (socket: WebSocket) =>+ onFirst(socket, "data", (message) => {+ const verified = typeof message.token === "string" ? verifyRelayToken(message.token, options.keys, now()) : null;+ if (message.t !== "data" || !verified?.ok || typeof message.sid !== "string") return close(socket, "data", 4401);+ const host = hosts.get(verified.claims.hid);+ const pending = host?.pending.get(message.sid);+ if (!host || !pending) return close(socket, "data", 4404);+ host.pending.delete(message.sid);+ clearTimeout(pending.timer);+ splice(host, pending.phone, socket, pending.admHash);+ });++ const phoneSocket = (socket: WebSocket) =>+ onFirst(socket, "phone", (message) => {+ const adm = typeof message.adm === "string" ? fromB64u(message.adm) : null;+ const host = typeof message.hid === "string" ? hosts.get(message.hid) : undefined;+ const admHash = adm ? b64u(createHash("sha256").update(adm).digest()) : "";+ if (message.t !== "phone" || message.v !== 1 || !host || !host.set.has(admHash)) return close(socket, "phone", 4404);+ const sid = b64u(randomBytes(16));+ const timer = setTimeout(() => {+ host.pending.delete(sid);+ close(socket, "phone", 4408);+ }, 10_000);+ host.pending.set(sid, { phone: socket, admHash, timer });+ socket.on("message", (_raw, isBinary) => {+ if (host.pending.has(sid) && isBinary) close(socket, "phone", 4400);+ });+ host.control.send(JSON.stringify({ t: "open", sid }));+ });++ server.on("upgrade", (req: IncomingMessage, socket: Duplex, head: Buffer) => {+ const path = new URL(req.url ?? "/", "http://relay").pathname;+ const handler = { "/v1/host": hostControl, "/v1/host/data": hostData, "/v1/phone": phoneSocket }[path];+ if (!handler) return void socket.destroy();+ wss.handleUpgrade(req, socket, head, (ws) => handler(ws));+ });++ await new Promise<void>((resolve) => server.listen(options.port ?? 0, "127.0.0.1", resolve));+ const port = (server.address() as AddressInfo).port;+ return {+ port,+ url: `ws://127.0.0.1:${port}`,+ hosts,+ closes,+ admitted: (hid) => hosts.get(hid)?.set ?? new Set(),+ restart() {+ for (const host of hosts.values()) host.control.send(JSON.stringify({ t: "restarting", reconnectInMs: 0, tryForMs: 200 }));+ },+ async kill() {+ for (const client of wss.clients) client.terminate();+ hosts.clear();+ server.closeAllConnections();+ await new Promise<void>((resolve) => server.close(() => resolve()));+ },+ async close() {+ for (const client of wss.clients) client.terminate();+ server.closeAllConnections();+ await new Promise<void>((resolve) => server.close(() => resolve()));+ },+ };+}diff --git a/companion/test/e2e/sidecar.test.ts b/companion/test/e2e/sidecar.test.tsnew file mode 100644index 0000000000..db8973d238--- /dev/null+++ b/companion/test/e2e/sidecar.test.ts@@ -0,0 +1,327 @@+// 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";+import { afterAll, beforeAll, describe, expect, it } from "vitest";++import { admission, admissionHash, 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 { 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";++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;+}++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"],+ });+ 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 });+});++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>;++/** 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", () => {+ 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();+ });++ 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 stream = events(session, deviceToken);+ const big = "x".repeat(4 * 1024 * 1024 - 1024);+ const id = 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);+ const stored = await http(session, "POST", "/api/files", { token: deviceToken, body: upload, headers: { "content-type": "application/octet-stream" } });+ expect(json(stored)).toEqual({ bytes: upload.length, sha256: createHash("sha256").update(upload).digest("hex") });+ 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);+ 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(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);+ 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`, {+ method: "POST",+ headers: { "content-type": "application/json" },+ body: JSON.stringify({ credential: state.token, deviceName: "Other" }),+ });+ const otherToken = ((await other.json()) as { token: string }).token;+ const session = await direct(state, 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);+ 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;+ }, 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);+ const before = events(first, deviceToken);+ const ids = [harness.emit({ n: 1 }), harness.emit({ n: 2 })];+ await waitFor(() => before.seen.some((event) => event.id === ids[1]));+ const port = relay.port;+ await relay.kill();+ 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 after = events(second, deviceToken, before.seen.at(-1)!.id);+ const next = 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);++ 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" });+ 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 endpoints = json(await http(session, "GET", "/api/companion/endpoints", { token: deviceToken }));+ expect(endpoints.e2e).toEqual({ v: 1, k: state.e2e.descriptor!.k });+ session.shutdown();+ await control("PUT", `/devices/${deviceId}/routes`, { routes: "any" });+ await waitFor(() => relay.admitted(hid).has(adm));+ });++ 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);+ const started = Date.now();+ await control("DELETE", `/devices/${deviceId}`);+ expect(await session.closed).toBe(4001);+ expect(Date.now() - started).toBeLessThan(1_000);+ await expect(direct(state, deviceToken)).rejects.toEqual(new SessionClosed(4001));+ });+});