Open-source Grok Bot alternative with a virtual machine that bots can use
TypeScript ai-agentsclaude-codecodexcomputer-usedockerelectrongrokgrok-botgrok-bot-alternativeself-hostedtypescript
Phones hear a routes change inside their session before the relay acts (#4695)
Milind Soni27b57eff9fc8
diff --git a/companion/src/devices.ts b/companion/src/devices.tsindex 7f7746b908..7c00817fcb 100644--- a/companion/src/devices.ts+++ b/companion/src/devices.ts@@ -107,8 +107,14 @@ function normalizeDevice(record: Partial<DeviceRecord> & { id: string; tokenHash};}+/** A device saved at pairing whose token was never used: the phone never got its reply, or lost it. Dropped after this. */+export const UNCONFIRMED_DEVICE_MS = 5 * 60_000;+export class DeviceRegistry {private devices: DeviceRecord[] = [];+ /** Paired in this run and not yet used; a restart forgets these, and such a device then stays until removed. */+ private unconfirmed = new Map<string, ReturnType<typeof setTimeout>>();+ private droppedListeners = new Set<(id: string) => void>();private window: PairingWindow | null = null;/** The window a renewal replaced: still valid until its own expiry, so a phone mid-scan never misses. */private previousWindow: PairingWindow | null = null;@@ -125,6 +131,19 @@ export class DeviceRegistry {return () => this.changeListeners.delete(listener);}+ /** A device dropped because its phone never used it. */+ onDropped(listener: (id: string) => void): void {+ this.droppedListeners.add(listener);+ }++ /** The phone holds the token: it authenticated with it, or opened an encrypted session keyed by it. */+ confirm(id: string): void {+ const timer = this.unconfirmed.get(id);+ if (!timer) return;+ clearTimeout(timer);+ this.unconfirmed.delete(id);+ }+private changed(): void {for (const listener of this.changeListeners) listener();}@@ -315,6 +334,17 @@ export class DeviceRegistry {return { error: `could not save the pairing: ${(e as Error).message}` };}this.changed();+ const unconfirmed = setTimeout(() => {+ this.unconfirmed.delete(device.id);+ try {+ if (!this.revoke(device.id)) return;+ } catch {+ return;+ }+ for (const listener of this.droppedListeners) listener(device.id);+ }, UNCONFIRMED_DEVICE_MS);+ unconfirmed.unref?.();+ this.unconfirmed.set(device.id, unconfirmed);const { tokenHash: _tokenHash, ...pub } = device;const result = { device: pub, token };if (requestId) {@@ -338,6 +368,7 @@ export class DeviceRegistry {const hash = sha256(token);const device = this.devices.find((d) => sameDigest(d.tokenHash, hash));if (!device) return null;+ this.confirm(device.id);const now = Date.now();if (now - (this.lastSeenWrites.get(device.id) ?? 0) > LAST_SEEN_WRITE_MS) {device.lastSeenAt = now;@@ -363,6 +394,7 @@ export class DeviceRegistry {throw error;}this.lastSeenWrites.delete(id);+ this.confirm(id);this.changed();return true;}diff --git a/companion/src/e2e/README.md b/companion/src/e2e/README.mdindex 05483d7406..e768053cf0 100644--- a/companion/src/e2e/README.md+++ b/companion/src/e2e/README.md@@ -57,13 +57,15 @@ reveals nothing about `psk`: the two are separate HMAC outputs under different l- **Field rules:**- `v` MUST be 1.- `k` is required.- - `h` and `r` are present only when the computer has a relay token (signed in, relay enabled, and the device isn't restricted to "Wi-Fi and- Tailscale only").+ - `h` and `r` are present only when the computer has a relay token (signed in, relay enabled). A device restricted to "Wi-Fi and+ Tailscale only" still gets them: they admit nothing by themselves, and they let a restricted phone away from home probe the relay+ now and then (4404 until it is allowed again).- `r` lists 1 to 4 hostnames in the order to try. Each MUST match `^relay[1-9][0-9]?\.openmausbot\.com$`.- `routes` is optional, `"any"` or `"local"`. `"local"` means the computer restricted this device to Wi-Fi and- Tailscale; it never comes with `h` or `r`. Absent means `"any"`, so a descriptor without `h` and `r` and without- `"local"` only says the computer has no relay right now (signed out, or outside the rollout). The QR never carries- `"local"`: a restriction is set per phone after pairing, and reaches it through the endpoint list.+ Tailscale; it may come with `h` and `r` (an older computer sends it without them). Absent means `"any"`, so a+ descriptor without `h` and `r` and without `"local"` only says the computer has no relay right now (signed out, or+ outside the rollout). The QR never carries `"local"`: a restriction is set per phone after pairing, and reaches it+ through the endpoint list and the `companion.endpoints` event.- The encoded value is at most 1,024 bytes.- **Phone parsing rules:**- A malformed `e2e` rejects the whole invite. That includes bad base64, bad JSON, a bad point, `h` without `r` or `r` without `h`, and a host@@ -74,7 +76,12 @@ reveals nothing about `psk`: the two are separate HMAC outputs under different l`http://H:P` into `ws://H:P/v1/e2e`. A `hosted` URL is never used for E2E.- **Pair response.** `POST /api/pair` returns 200 with `{token, device, serverName, hosts?, endpoints?}` plus `"e2e": {…same object…}`.- **Endpoint list.** `GET /api/companion/endpoints` returns `{serverName, hosts?, endpoints[]}` plus `"e2e": {…}`. The response is built for- the device that asks: `h` and `r` are left out if that device is restricted.+ the device that asks: a restricted device's `e2e` says `"routes":"local"`.+- **Endpoint event.** When a device's routes change, the sidecar writes the same body plus `"kind":"companion.endpoints"` as one event+ (`data:` only, no `id:` and no `seq`, never replayed) on every `/api/events` stream that device holds, so the phone hears it inside its+ session. Narrowing to `"local"`: the event first, then the relay keeps the device admitted 300 ms more so the event lands, then the+ set shrinks (the relay closes its relay sessions with 4404) and the computer closes its own; direct sessions stay. Widening to+ `"any"`: admitted first, then the event.- **Pinning:**- A phone that holds a QR-pinned `k` MUST NEVER replace it from a network response.- A phone paired before this feature (no `k`) accepts `k` once from `/api/companion/endpoints`, over the route it already trusts (trust on@@ -353,7 +360,9 @@ These make the sections above exact where an implementation could otherwise choo- `v` must be an integer. `v > 1` means "update the app" whatever the other fields hold; `v < 1`, a string, or a missing`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.+- `routes`, when present, must be the string `"any"` or `"local"`. `"local"` may carry `h` and `r` (vector+ `routes_local_with_relay`); a restricted phone dials only its direct routes, and probes the relay on a slow backoff only+ when they fail.**Removal**- A close code travels outside the encryption, and over the relay the relay writes it. When a device is removed, thediff --git a/companion/src/e2e/descriptor.ts b/companion/src/e2e/descriptor.tsindex 35f47bb3d7..50d9e59643 100644--- a/companion/src/e2e/descriptor.ts+++ b/companion/src/e2e/descriptor.ts@@ -18,8 +18,9 @@ export interface E2EDescriptor {h?: string;/** relay hostnames in the order to try */r?: string[];- /** "local": the computer restricted this device to Wi-Fi and Tailscale, so it never has `h` or `r`. Absent means- * "any"; then a missing relay only means the computer has none (signed out, or outside the rollout). */+ /** "local": the computer restricted this device to Wi-Fi and Tailscale. It may still carry `h` and `r`, so a phone away+ * from home can probe the relay now and then and learn when it is allowed again; the relay refuses it (4404) until+ * then. Absent means "any"; then a missing relay only means the computer has none (signed out, or outside the rollout). */routes?: DescriptorRoutes;}@@ -29,16 +30,16 @@ export function encodeDescriptor(descriptor: E2EDescriptor): string {return b64u(Buffer.from(json, "utf8"));}-/** A restricted device's descriptor says so and never carries the relay. */+/** A restricted device's descriptor says so; it keeps the relay identity, which admits nothing by itself. */export function descriptorFor(transportPublicKey: Uint8Array,relay?: { hostId: Uint8Array; nodes: readonly string[] },routes?: DescriptorRoutes,): E2EDescriptor {- if (routes === "local") return { v: 1, k: b64u(transportPublicKey), routes: "local" };- return relay && relay.nodes.length > 0- ? { v: 1, k: b64u(transportPublicKey), h: b64u(relay.hostId), r: [...relay.nodes] }- : { v: 1, k: b64u(transportPublicKey) };+ const base = relay && relay.nodes.length > 0+ ? { v: 1 as const, k: b64u(transportPublicKey), h: b64u(relay.hostId), r: [...relay.nodes] }+ : { v: 1 as const, k: b64u(transportPublicKey) };+ return routes === "local" ? { ...base, routes: "local" } : base;}/** `update` means a newer version: the phone says "Update the MausBot app" and never falls back to plain pairing.@@ -73,7 +74,6 @@ export function parseDescriptor(input: unknown): DescriptorParse {if (hasHost !== hasRelays) return reject("relay_pair");if (fields.routes !== undefined && fields.routes !== "any" && fields.routes !== "local") return reject("routes");const routes = fields.routes === undefined ? {} : { routes: fields.routes as DescriptorRoutes };- if (routes.routes === "local" && hasHost) return reject("local_with_relay");if (!hasHost) return { outcome: "ok", descriptor: { v: 1, k: fields.k as string, ...routes }, transportKey, hostId: null };const hostId = typeof fields.h === "string" ? fromB64u(fields.h) : null;if (!hostId || hostId.length !== HOST_ID_BYTES) return reject("host_id");diff --git a/companion/src/e2e/gen-vectors.ts b/companion/src/e2e/gen-vectors.tsindex 9d671fba36..ce61b8ea9a 100644--- a/companion/src/e2e/gen-vectors.ts+++ b/companion/src/e2e/gen-vectors.ts@@ -524,6 +524,7 @@ function v7() {{ name: "routes_local", value: encodeDescriptor({ v: 1, k, routes: "local" }) },{ name: "routes_any_with_relay", value: encodeDescriptor({ v: 1, k, h, r, routes: "any" }) },{ name: "routes_any_without_relay", value: raw({ v: 1, k, routes: "any" }) },+ { name: "routes_local_with_relay", value: encodeDescriptor({ v: 1, k, h, r, routes: "local" }) },];const offCurve = b64u(flip(T.publicKey, 64));const invalid = [@@ -551,7 +552,6 @@ function v7() {{ name: "json_array", value: raw([1]) },{ name: "routes_unknown", value: raw({ v: 1, k, routes: "wifi" }) },{ name: "routes_not_a_string", value: raw({ v: 1, k, routes: 1 }) },- { name: "routes_local_with_relay", value: raw({ v: 1, k, h, r, routes: "local" }) },{ name: "v2", value: raw({ v: 2, k }) },{ name: "v2_unknown_shape", value: raw({ v: 2, keys: [1, 2, 3] }) },];diff --git a/companion/src/e2e/registry.ts b/companion/src/e2e/registry.tsindex c1ffeb8e5e..3d6fdd85d6 100644--- a/companion/src/e2e/registry.ts+++ b/companion/src/e2e/registry.ts@@ -44,6 +44,9 @@ export class E2ERegistry {#relay: RelayIdentity | null = null;#pending = 0;readonly #admissionListeners = new Set<() => void>();+ /** Admission hashes kept a moment after their device lost the relay, so what the computer says inside the session+ * reaches the phone before the relay closes it. */+ readonly #held = new Map<string, number>();constructor(devices: DeviceRegistry) {this.#devices = devices;@@ -101,10 +104,30 @@ export class E2ERegistry {}for (const window of this.#devices.pairingWindows()) out.push(admissionHash(admission(credentialHash(window.token), hostId)));for (const live of this.#live) if (live.pairingAdmission) out.push(live.pairingAdmission);+ out.push(...this.#held.keys());return [...new Set(out)].sort();}- /** For one device (null: a phone that is pairing now). A restricted device never learns the relay. */+ /** Keeps this device admitted at the relay for `ms` whatever its routes now say, then lets the set shrink. */+ holdAdmission(deviceId: string, ms: number): Promise<void> {+ const device = this.#devices.records().find((candidate) => candidate.id === deviceId);+ const hash = device && this.#relay ? credentialHashFromHex(device.tokenHash) : null;+ if (!hash || !this.#relay) return Promise.resolve();+ const held = admissionHash(admission(hash, this.#relay.hostId));+ this.#held.set(held, (this.#held.get(held) ?? 0) + 1);+ return new Promise((resolve) => {+ setTimeout(() => {+ const count = (this.#held.get(held) ?? 1) - 1;+ if (count > 0) this.#held.set(held, count);+ else this.#held.delete(held);+ for (const listener of this.#admissionListeners) listener();+ resolve();+ }, ms).unref?.();+ });+ }++ /** For one device (null: a phone that is pairing now). A restricted device is told so, with the relay identity, which+ * admits nothing by itself: the relay refuses it until the device is allowed again. */descriptor(deviceId: string | null): E2EDescriptor | null {if (!this.#key) return null;const device = deviceId ? this.#devices.records().find((candidate) => candidate.id === deviceId) : null;@@ -134,7 +157,10 @@ export class E2ERegistry {opened: (peer) => {live.context.peer = peer;this.#live.add(live);- if (peer.kind === "device") return this.#devices.markE2E(peer.id);+ if (peer.kind === "device") {+ this.#devices.confirm(peer.id);+ 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);diff --git a/companion/src/e2e/vectors/v1.json b/companion/src/e2e/vectors/v1.jsonindex fd91a31768..ea1c50c470 100644--- a/companion/src/e2e/vectors/v1.json+++ b/companion/src/e2e/vectors/v1.json@@ -2205,6 +2205,21 @@"k": "BJiFmi3bzpQUayMJErl6eqt24mUOvHEUR6uzutPTHfundIgyZxs3bSzUMydGOfgbWdwQshIyzzlMWqxMkNHnmd0","routes": "any"}+ },+ {+ "name": "routes_local_with_relay",+ "value": "eyJ2IjoxLCJrIjoiQkppRm1pM2J6cFFVYXlNSkVybDZlcXQyNG1VT3ZIRVVSNnV6dXRQVEhmdW5kSWd5WnhzM2JTelVNeWRHT2ZnYldkd1FzaEl5enpsTVdxeE1rTkhubWQwIiwiaCI6Imx6ODFpc0IzQnVOVjZySGdZZ0czV2ciLCJyIjpbInJlbGF5MS5vcGVubWF1c2JvdC5jb20iLCJyZWxheTIub3Blbm1hdXNib3QuY29tIl0sInJvdXRlcyI6ImxvY2FsIn0",+ "chars": 271,+ "parsed": {+ "v": 1,+ "k": "BJiFmi3bzpQUayMJErl6eqt24mUOvHEUR6uzutPTHfundIgyZxs3bSzUMydGOfgbWdwQshIyzzlMWqxMkNHnmd0",+ "h": "lz81isB3BuNV6rHgYgG3Wg",+ "r": [+ "relay1.openmausbot.com",+ "relay2.openmausbot.com"+ ],+ "routes": "local"+ }}],"invalid": [@@ -2352,12 +2367,6 @@"chars": 150,"outcome": "reject"},- {- "name": "routes_local_with_relay",- "value": "eyJ2IjoxLCJrIjoiQkppRm1pM2J6cFFVYXlNSkVybDZlcXQyNG1VT3ZIRVVSNnV6dXRQVEhmdW5kSWd5WnhzM2JTelVNeWRHT2ZnYldkd1FzaEl5enpsTVdxeE1rTkhubWQwIiwiaCI6Imx6ODFpc0IzQnVOVjZySGdZZ0czV2ciLCJyIjpbInJlbGF5MS5vcGVubWF1c2JvdC5jb20iLCJyZWxheTIub3Blbm1hdXNib3QuY29tIl0sInJvdXRlcyI6ImxvY2FsIn0",- "chars": 271,- "outcome": "reject"- },{"name": "v2","value": "eyJ2IjoyLCJrIjoiQkppRm1pM2J6cFFVYXlNSkVybDZlcXQyNG1VT3ZIRVVSNnV6dXRQVEhmdW5kSWd5WnhzM2JTelVNeWRHT2ZnYldkd1FzaEl5enpsTVdxeE1rTkhubWQwIn0",diff --git a/companion/src/e2e/vectors/v1.sha256 b/companion/src/e2e/vectors/v1.sha256index 792eb45b2d..b67029265d 100644--- a/companion/src/e2e/vectors/v1.sha256+++ b/companion/src/e2e/vectors/v1.sha256@@ -1 +1 @@-525279254e73d3a953957a9b8dd7b044051fa2d10ce349f409535022a5fbe30a v1.json+5471a0070ddbb69dca34dee6da550de4581e8e1a40e22e0f97873d539793bf4e v1.jsondiff --git a/companion/src/index.ts b/companion/src/index.tsindex c4ea0c9b36..549c7ad46f 100755--- a/companion/src/index.ts+++ b/companion/src/index.ts@@ -202,6 +202,10 @@ function configureE2E(message: Record<string, unknown>): void {const ADMISSION_SETTLE_MS = 300;devices.onChange(() => setTimeout(() => relay?.refreshAdmission(), ADMISSION_SETTLE_MS).unref());e2e.onAdmissionChange(() => relay?.refreshAdmission());+devices.onDropped((deviceId) => {+ e2e.closeDevice(deviceId);+ console.log("companion: dropped a paired device its phone never used");+});const control = createControlServer({devices,@@ -228,9 +232,17 @@ const control = createControlServer({refreshTailscale: () => refreshTailnetName(),e2e: () => ({ enabled: e2e.enabled, relay: relay?.status ?? "off", node: relay?.node ?? null, descriptor: e2e.descriptor(null) }),liveRoutes: () => e2e.routes(),+ // The phone hears where it may connect from inside its session first. Narrowed, the relay keeps it a moment so that+ // lands, then refuses it (4404) and its relay sessions close; direct ones stay. Widened, it is admitted before it hears.routesChanged: (deviceId, routes) => {- relay?.refreshAdmission();- if (routes === "local") e2e.closeDevice(deviceId, CLOSE.normal, "relay");+ if (routes === "any") {+ relay?.refreshAdmission();+ proxy.sendEndpoints(deviceId);+ return;+ }+ const held = e2e.holdAdmission(deviceId, ADMISSION_SETTLE_MS);+ proxy.sendEndpoints(deviceId);+ void held.then(() => e2e.closeDevice(deviceId, CLOSE.normal, "relay"));},setRelay: (body) => {const config = parseRelayConfig(body);diff --git a/companion/src/proxy.ts b/companion/src/proxy.tsindex f03374e585..ccb5031eae 100644--- a/companion/src/proxy.ts+++ b/companion/src/proxy.ts@@ -286,6 +286,12 @@ function harnessControlCheck(options: ProxyOptions) {export function createProxyHandler(options: ProxyOptions) {const viewers = new CompanionViewerRelay({ checkControl: harnessControlCheck(options) });const capabilityStreams = new Map<string, Set<() => void>>();+ /** Each device's open `/api/events` streams, for the events the sidecar itself sends. */+ const eventStreams = new Map<string, Set<(event: string) => void>>();+ const endpointsFor = (deviceId: string | null) => {+ const descriptor = options.e2eDescriptor?.(deviceId) ?? null;+ return { ...endpointSnapshot(options), ...(descriptor ? { e2e: descriptor } : {}) };+ };const handle = function handle(req: IncomingMessage, res: ServerResponse, listener: ProxyListener = "lan"): void {const target = requestTarget(req.url);if (!target) return sendJson(res, 400, { error: "invalid request target" });@@ -388,8 +394,7 @@ export function createProxyHandler(options: ProxyOptions) {// Sidecar-owned state: answered here after the bearer and default-deny// checks, never sent to the harness.if (method === "GET" && path === "/api/companion/endpoints") {- const descriptor = options.e2eDescriptor?.(device?.id ?? null) ?? null;- return sendJson(res, 200, { ...endpointSnapshot(options), ...(descriptor ? { e2e: descriptor } : {}) });+ return sendJson(res, 200, endpointsFor(device?.id ?? null));}const mutationToken = device ? options.mutationToken?.() : undefined;@@ -491,9 +496,24 @@ export function createProxyHandler(options: ProxyOptions) {open.add(disconnect);capabilityStreams.set(capabilityOwner, open);}+ // The scrubber hands on whole events only, so an event written here never splits one of the harness's.+ const pushTo = tracksDeviceConnection && currentDevice?.id ? currentDevice.id : undefined;+ const push = (event: string) => {+ if (!res.destroyed && !res.writableEnded) res.write(event);+ };+ if (pushTo) {+ const open = eventStreams.get(pushTo) ?? new Set<(event: string) => void>();+ open.add(push);+ eventStreams.set(pushTo, open);+ }const release = () => {releaseConnection?.();releaseConnection = null;+ if (pushTo) {+ const open = eventStreams.get(pushTo);+ open?.delete(push);+ if (open && open.size === 0) eventStreams.delete(pushTo);+ }if (capabilityOwner) {const open = capabilityStreams.get(capabilityOwner);open?.delete(disconnect);@@ -685,6 +705,15 @@ export function createProxyHandler(options: ProxyOptions) {viewers.handleUpgrade(req, socket, head, device);};handle.closeViewers = (): void => viewers.closeAll();+ /** The endpoint list again, as an event on every event stream the device holds: a phone hears a change of where it+ * may connect from inside its session, before the relay acts on it. No `id:`, so the replay cursor stays put. */+ handle.sendEndpoints = (deviceId: string): number => {+ const open = eventStreams.get(deviceId);+ if (!open) return 0;+ const event = `data: ${JSON.stringify({ kind: "companion.endpoints", ...endpointsFor(deviceId) })}\n\n`;+ for (const push of open) push(event);+ return open.size;+ };handle.disconnectDevice = (deviceId: string): void => {viewers.closeDevice(deviceId);// Revoking a capability closes the streams it already granted.diff --git a/companion/test/devices.test.ts b/companion/test/devices.test.tsindex 8e8566a491..05e352d399 100644--- a/companion/test/devices.test.ts+++ b/companion/test/devices.test.ts@@ -9,6 +9,7 @@ import {DeviceRegistry,MAX_PAIRING_ATTEMPTS,PAIRING_TTL_MS,+ UNCONFIRMED_DEVICE_MS,} from "../src/devices.ts";const pair = (registry: DeviceRegistry, name = "iPhone") => {@@ -49,6 +50,28 @@ describe("DeviceRegistry", () => {expect(registry.pairing()).toBeNull();});+ it("drops a paired device its phone never used, and keeps one it did", () => {+ vi.useFakeTimers();+ try {+ const registry = new DeviceRegistry();+ const dropped: string[] = [];+ registry.onDropped((id) => dropped.push(id));+ const unused = pair(registry, "Lost reply");+ const used = pair(registry, "Used");+ const viaSession = pair(registry, "Encrypted");+ expect(registry.authenticate(used.token)?.id).toBe(used.device.id);+ registry.confirm(viaSession.device.id);+ vi.advanceTimersByTime(UNCONFIRMED_DEVICE_MS - 1);+ expect(registry.list()).toHaveLength(3);+ vi.advanceTimersByTime(1);+ expect(dropped).toEqual([unused.device.id]);+ expect(registry.list().map((device) => device.name)).toEqual(["Used", "Encrypted"]);+ expect(registry.authenticate(unused.token)).toBeNull();+ } finally {+ vi.useRealTimers();+ }+ });+it("survives a restart", () => {const { token } = pair(new DeviceRegistry());expect(new DeviceRegistry().authenticate(token)).not.toBeNull();diff --git a/companion/test/e2e/registry.test.ts b/companion/test/e2e/registry.test.tsnew file mode 100644index 0000000000..5ca3d5b5e2--- /dev/null+++ b/companion/test/e2e/registry.test.ts@@ -0,0 +1,48 @@+import { rmSync } from "node:fs";+import { randomBytes } from "node:crypto";+import { beforeEach, describe, expect, it, vi } from "vitest";++import { DeviceRegistry } from "../../src/devices.ts";+import { admission, admissionHash, credentialHash } from "../../src/e2e/credentials.ts";+import { generateKeyPair } from "../../src/e2e/noise.ts";+import { E2ERegistry } from "../../src/e2e/registry.ts";+import { DATA_DIR } from "../../src/state.ts";++describe("E2ERegistry admission", () => {+ beforeEach(() => {+ rmSync(DATA_DIR, { recursive: true, force: true });+ });++ it("keeps a just-restricted device admitted for the hold, then lets the set shrink and says so", async () => {+ vi.useFakeTimers();+ try {+ const devices = new DeviceRegistry();+ const registry = new E2ERegistry(devices);+ const hostId = randomBytes(16);+ registry.setKey(generateKeyPair());+ registry.setRelay({ hostId, nodes: ["relay1.openmausbot.com"] });+ const { code } = devices.openPairing();+ const paired = devices.redeem(code, "Phone");+ if ("error" in paired) throw new Error(paired.error);+ devices.closePairing();+ const hash = admissionHash(admission(credentialHash(paired.token), hostId));+ expect(registry.admissionSet()).toEqual([hash]);+ let changes = 0;+ registry.onAdmissionChange(() => (changes += 1));++ devices.setRoutes(paired.device.id, "local");+ const held = registry.holdAdmission(paired.device.id, 300);+ expect(registry.admissionSet()).toEqual([hash]);+ vi.advanceTimersByTime(299);+ expect(registry.admissionSet()).toEqual([hash]);+ expect(changes).toBe(0);+ vi.advanceTimersByTime(1);+ await held;+ expect(registry.admissionSet()).toEqual([]);+ expect(changes).toBe(1);+ expect(registry.descriptor(paired.device.id)).toMatchObject({ h: expect.any(String), r: ["relay1.openmausbot.com"], routes: "local" });+ } finally {+ vi.useRealTimers();+ }+ });+});diff --git a/companion/test/e2e/rig.ts b/companion/test/e2e/rig.tsindex d003d7721f..015b8a0cb7 100644--- a/companion/test/e2e/rig.ts+++ b/companion/test/e2e/rig.ts@@ -225,6 +225,8 @@ export const json = (reply: Reply) => JSON.parse(reply.body.toString("utf8")) as/** 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 }> = [];+ /** Events with no `id:`: the ones the sidecar itself sends. */+ const pushed: Array<{ at: number; data: Record<string, unknown> }> = [];let buffer = "";let abort = () => {};const done = new Promise<void>((resolve) => {@@ -246,6 +248,7 @@ export function events(session: E2ESession<never>, token: string, lastEventId?: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]) });+ else if (data) pushed.push({ at: Date.now(), data: JSON.parse(data[1]) });}});res.on("close", resolve);@@ -255,7 +258,7 @@ export function events(session: E2ESession<never>, token: string, lastEventId?:abort = () => req.destroy();req.end();});- return { seen, done, abort: () => abort() };+ return { seen, pushed, done, abort: () => abort() };}/** Pairs a phone through the relay with a fresh pairing window; returns its device token and id. */diff --git a/companion/test/e2e/sidecar.test.ts b/companion/test/e2e/sidecar.test.tsindex 6445707144..5da1ea0914 100644--- a/companion/test/e2e/sidecar.test.ts+++ b/companion/test/e2e/sidecar.test.ts@@ -112,21 +112,46 @@ describe("the sidecar's end-to-end connection, through the real relay", () => {second.shutdown();}, 40_000);- it("drops a device restricted to Wi-Fi and Tailscale from the relay at once: the relay answers 4404, direct still works", async () => {+ it("tells a phone it is restricted to Wi-Fi and Tailscale inside its sessions, then the relay drops it (4404); direct stays", async () => {const current = await state();const relayed = await rig.viaRelay(current, deviceToken);+ const direct = await rig.direct(current, deviceToken);+ const marker = rig.harness.emit({ n: "routes" });+ const relayedEvents = events(relayed, deviceToken, marker - 1);+ const directEvents = events(direct, deviceToken, marker - 1);+ await waitFor(() => [relayedEvents, directEvents].every((stream) => stream.seen.some((event) => event.id === marker)));+ let closedAt = 0;+ const closed = relayed.closed.then((code) => ((closedAt = Date.now()), code));await rig.control("PUT", `/devices/${deviceId}/routes`, { routes: "local" });- expect(await relayed.closed).toBeGreaterThan(0);+ expect(await closed).toBeGreaterThan(0);+ const local = { v: 1, k: current.e2e.descriptor!.k, h: rig.hid, r: ["relay1.openmausbot.com"], routes: "local" };+ // Heard inside the relayed session itself, well before the relay closed it.+ expect(relayedEvents.pushed.map((event) => event.data)).toEqual([expect.objectContaining({ kind: "companion.endpoints", serverName: "Test Mac", e2e: local })]);+ expect(closedAt - relayedEvents.pushed[0].at).toBeGreaterThanOrEqual(200);+ await waitFor(() => directEvents.pushed.length === 1);+ expect(directEvents.pushed[0].data).toEqual(expect.objectContaining({ kind: "companion.endpoints", e2e: local }));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: current.e2e.descriptor!.k, routes: "local" });- session.shutdown();+ expect(direct.state).toBe("open");+ const endpoints = json(await http(direct, "GET", "/api/companion/endpoints", { token: deviceToken }));+ expect(endpoints.e2e).toEqual(local);++ // Allowed again: admitted first, then told, on the session that stayed.await rig.control("PUT", `/devices/${deviceId}/routes`, { routes: "any" });+ await waitFor(() => directEvents.pushed.length === 2);+ expect(directEvents.pushed[1].data).toEqual(expect.objectContaining({ kind: "companion.endpoints", e2e: { v: 1, k: current.e2e.descriptor!.k, h: rig.hid, r: ["relay1.openmausbot.com"] } }));+ const back = await waitFor(() => rig.viaRelay(current, deviceToken).catch(() => null), 5_000);+ expect((await http(back, "GET", "/api/health", { token: deviceToken })).status).toBe(200);+ // The harness's own stream is untouched: no id was spent and its events still arrive.+ const after = rig.harness.emit({ n: 5 });+ await waitFor(() => directEvents.seen.some((event) => event.id === after));+ back.shutdown();+ directEvents.abort();+ relayedEvents.abort();+ direct.shutdown();});it("tells a removed phone so inside the encryption, then closes with 4001, through the relay and directly", async () => {diff --git a/relay/test/token.test.ts b/relay/test/token.test.tsindex 057d2a6c6f..dc5501368d 100644--- a/relay/test/token.test.ts+++ b/relay/test/token.test.ts@@ -6,7 +6,7 @@ import { parseTokenKeys, verifyToken } from "../src/token.ts";import { keysJson, mintToken, testKey } from "./helpers.ts";/** The SHA-256 the wire spec pins for vectors/v1.json; a stale copy here fails. */-const PINNED_VECTORS = "525279254e73d3a953957a9b8dd7b044051fa2d10ce349f409535022a5fbe30a";+const PINNED_VECTORS = "5471a0070ddbb69dca34dee6da550de4581e8e1a40e22e0f97873d539793bf4e";const vectorsText = readFileSync(new URL("./vectors/e2e-v1.json", import.meta.url));const vectors = JSON.parse(vectorsText.toString("utf8"));const V8 = vectors.V8;diff --git a/relay/test/vectors/e2e-v1.json b/relay/test/vectors/e2e-v1.jsonindex fd91a31768..ea1c50c470 100644--- a/relay/test/vectors/e2e-v1.json+++ b/relay/test/vectors/e2e-v1.json@@ -2205,6 +2205,21 @@"k": "BJiFmi3bzpQUayMJErl6eqt24mUOvHEUR6uzutPTHfundIgyZxs3bSzUMydGOfgbWdwQshIyzzlMWqxMkNHnmd0","routes": "any"}+ },+ {+ "name": "routes_local_with_relay",+ "value": "eyJ2IjoxLCJrIjoiQkppRm1pM2J6cFFVYXlNSkVybDZlcXQyNG1VT3ZIRVVSNnV6dXRQVEhmdW5kSWd5WnhzM2JTelVNeWRHT2ZnYldkd1FzaEl5enpsTVdxeE1rTkhubWQwIiwiaCI6Imx6ODFpc0IzQnVOVjZySGdZZ0czV2ciLCJyIjpbInJlbGF5MS5vcGVubWF1c2JvdC5jb20iLCJyZWxheTIub3Blbm1hdXNib3QuY29tIl0sInJvdXRlcyI6ImxvY2FsIn0",+ "chars": 271,+ "parsed": {+ "v": 1,+ "k": "BJiFmi3bzpQUayMJErl6eqt24mUOvHEUR6uzutPTHfundIgyZxs3bSzUMydGOfgbWdwQshIyzzlMWqxMkNHnmd0",+ "h": "lz81isB3BuNV6rHgYgG3Wg",+ "r": [+ "relay1.openmausbot.com",+ "relay2.openmausbot.com"+ ],+ "routes": "local"+ }}],"invalid": [@@ -2352,12 +2367,6 @@"chars": 150,"outcome": "reject"},- {- "name": "routes_local_with_relay",- "value": "eyJ2IjoxLCJrIjoiQkppRm1pM2J6cFFVYXlNSkVybDZlcXQyNG1VT3ZIRVVSNnV6dXRQVEhmdW5kSWd5WnhzM2JTelVNeWRHT2ZnYldkd1FzaEl5enpsTVdxeE1rTkhubWQwIiwiaCI6Imx6ODFpc0IzQnVOVjZySGdZZ0czV2ciLCJyIjpbInJlbGF5MS5vcGVubWF1c2JvdC5jb20iLCJyZWxheTIub3Blbm1hdXNib3QuY29tIl0sInJvdXRlcyI6ImxvY2FsIn0",- "chars": 271,- "outcome": "reject"- },{"name": "v2","value": "eyJ2IjoyLCJrIjoiQkppRm1pM2J6cFFVYXlNSkVybDZlcXQyNG1VT3ZIRVVSNnV6dXRQVEhmdW5kSWd5WnhzM2JTelVNeWRHT2ZnYldkd1FzaEl5enpsTVdxeE1rTkhubWQwIn0",