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 (direct and relay), WIP
milind-soni549cc82709f6
diff --git a/companion/README.md b/companion/README.mdindex 06ec47f1b8..4d42499f6a 100644--- a/companion/README.md+++ b/companion/README.md@@ -123,6 +123,9 @@ it is switched on, so the opt-in is never implicit.| `OMB_CONTROL_TOKEN` | random | that token (43 base64url characters), for a script that starts the sidecar; the desktop app ignores it || `OMB_COMPANION_DIR` | `~/.openmausbot-companion` | paired devices live here || `OMB_COMPANION_NAME` | your name, from the harness | what the phone calls this computer |+| `OMB_COMPANION_E2E` | off | `1` turns on the end-to-end encrypted connection when standing alone (the desktop app turns it on itself); the transport key is kept in `e2e-key.json` beside the devices |+| `OMB_COMPANION_BONJOUR` | on | `0` keeps a test rig off the network's Bonjour |+| `OMB_COMPANION_RELAY_URL` | none | test rigs only: a `ws://127.0.0.1:<port>` relay in place of `wss://relayN.openmausbot.com` |`OMB_COMPANION_NAME` overrides a name the sidecar otherwise asks the harnessfor: the computer name set in Settings → Remote access, else the profile fromdiff --git a/companion/src/control.ts b/companion/src/control.tsindex 3e95b70ade..69bfe100ef 100644--- a/companion/src/control.ts+++ b/companion/src/control.ts@@ -5,7 +5,8 @@import { randomBytes, timingSafeEqual } from "node:crypto";import { createServer, type Server, type ServerResponse } from "node:http";-import type { DeviceRegistry } from "./devices.ts";+import type { DeviceRegistry, DeviceRoutes } from "./devices.ts";+import type { LiveRoute } from "./e2e/registry.ts";import { companionEndpointCandidates, hostedCompanionUrl } from "./endpoints.ts";import { lanAddresses, lanInterfaces, tailnetName, tailscaleAddress } from "./listener.ts";import { defaultHostName } from "./mdns.ts";@@ -33,6 +34,20 @@ export interface ControlOptions {revoked?: (deviceId: string) => void;refreshTailscale?: () => Promise<void>;publicNetworks?: () => ReadonlySet<string>;+ /** End-to-end status; absent or `enabled: false` while it is off. */+ e2e?: () => E2EStatus;+ /** The best live encrypted route of each connected device. */+ liveRoutes?: () => Record<string, LiveRoute>;+ /** After a device's allowed routes change: the relay admission set and its relay sessions follow. */+ routesChanged?: (deviceId: string, routes: DeviceRoutes) => void;+ /** A standalone sidecar's relay identity and token (`PUT /e2e/relay`); false when refused. */+ setRelay?: (body: unknown) => boolean;+}++export interface E2EStatus {+ enabled: boolean;+ relay: "connected" | "connecting" | "off";+ node: string | null;}/** A bracketed IPv6 literal has colons of its own. A malformed authority comes@@ -124,6 +139,28 @@ const readHostedEndpoint = (});});+/** A small JSON body of any shape, for the caller to validate. */+const readSmallJson = (req: import("node:http").IncomingMessage): Promise<unknown> =>+ new Promise((resolve, reject) => {+ let text = "";+ req.setEncoding("utf8");+ req.on("data", (chunk: string) => {+ text += chunk;+ if (text.length > 4096) {+ reject(new Error("body too large"));+ req.destroy();+ }+ });+ req.on("error", reject);+ req.on("end", () => {+ try {+ resolve(JSON.parse(text));+ } catch {+ reject(new Error("invalid JSON body"));+ }+ });+ });+const currentHostedUrl = (options: Pick<ControlOptions, "hostedUrl">): string | null =>options.hostedUrl?.() ?? null;@@ -176,7 +213,8 @@ 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(),+ devices: options.devices.list().map((device) => ({ ...device, route: options.liveRoutes?.()[device.id] ?? null })),+ e2e: options.e2e?.() ?? { enabled: false, relay: "off", node: null },// An empty list from an unreadable file must not read as "nothing paired"....(options.devices.devicesUnreadable() ? { devicesUnreadable: true } : {}),connectedDeviceIds: options.connectedDeviceIds?.() ?? [],@@ -235,6 +273,18 @@ export function createControlServer(options: ControlOptions): Server {token: window.token,});}+ const setRelay = options.setRelay;+ if (method === "PUT" && path === "/e2e/relay" && setRelay) {+ readSmallJson(req).then(+ (body) => (setRelay(body) ? json(res, 200, companionState(options)) : json(res, 400, { error: "invalid relay configuration" })),+ (error: Error) => json(res, 400, { error: error.message }),+ );+ return;+ }+ if (method === "POST" && path === "/pairing/renew") {+ const window = options.devices.renewPairing();+ return json(res, 201, { ...companionState(options), code: window.code, token: window.token });+ }if (method === "DELETE" && path === "/pairing") {const expectedToken = requestUrl.searchParams.get("expectedToken") ?? undefined;options.devices.closePairing(expectedToken);@@ -281,6 +331,24 @@ export function createControlServer(options: ControlOptions): Server {options.disconnectDevice?.(browserControl[1]);return json(res, 200, companionState(options));}+ const routes = path.match(/^\/devices\/([\w-]+)\/routes$/);+ if (routes && method === "PUT") {+ readSmallJson(req).then(+ (body) => {+ const next = (body as { routes?: unknown } | null)?.routes;+ if (next !== "any" && next !== "local") return json(res, 400, { error: 'routes must be "any" or "local"' });+ try {+ if (!options.devices.setRoutes(routes[1], next)) return json(res, 404, { error: "no such device" });+ } catch {+ return json(res, 500, { error: "could not save where this device connects from" });+ }+ options.routesChanged?.(routes[1], next);+ return json(res, 200, companionState(options));+ },+ (error: Error) => json(res, 400, { error: error.message }),+ );+ return;+ }const revoke = path.match(/^\/devices\/([\w-]+)$/);if (revoke && method === "DELETE") {try {diff --git a/companion/src/devices.ts b/companion/src/devices.tsindex 2a303e5865..7f7746b908 100644--- a/companion/src/devices.ts+++ b/companion/src/devices.ts@@ -20,8 +20,14 @@ export interface DeviceRecord {* person's real accounts is a different risk from a disposable VM. Off on* every new and migrated device until the computer owner enables it. */browserControlAccess: boolean;+ /** "local": Wi-Fi and Tailscale only. The relay never admits it and its psk is never tried there. */+ routes: DeviceRoutes;+ /** First end-to-end encrypted session. From then on its token is refused on the plain listener. */+ e2eAt?: number;}+export type DeviceRoutes = "any" | "local";+export type PublicDevice = Omit<DeviceRecord, "tokenHash">;/** `token` rides in the QR, has enough entropy to stand alone and is never@@ -96,17 +102,37 @@ function normalizeDevice(record: Partial<DeviceRecord> & { id: string; tokenHashlastSeenAt: timestamp(record.lastSeenAt, createdAt),cloudDesktopAccess: record.cloudDesktopAccess === true,browserControlAccess: record.browserControlAccess === true,+ routes: record.routes === "local" ? "local" : "any",+ ...(typeof record.e2eAt === "number" && record.e2eAt > 0 ? { e2eAt: record.e2eAt } : {}),};}export class DeviceRegistry {private devices: DeviceRecord[] = [];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;private replay: PairingReplay | null = null;private replayExpiryTimer: ReturnType<typeof setTimeout> | null = null;private lastSeenWrites = new Map<string, number>();/** devices.json exists but could not be read: "no devices" is a guess. */private unreadable = false;+ private changeListeners = new Set<() => void>();++ /** Pairing, removal, a route restriction, or a pairing window opening or closing. */+ onChange(listener: () => void): () => void {+ this.changeListeners.add(listener);+ return () => this.changeListeners.delete(listener);+ }++ private changed(): void {+ for (const listener of this.changeListeners) listener();+ }++ /** Records, token hashes included: the E2E layer derives each psk and admission value from them. */+ records(): readonly DeviceRecord[] {+ return this.devices;+ }/** Only `id` and `tokenHash` make a record a device; the rest is display and* gets defaults. */@@ -150,28 +176,71 @@ export class DeviceRegistry {return this.devices.length;}- /** Expiry is evaluated on read. */+ /** The newest window. Expiry is evaluated on read. */pairing(): PairingWindow | null {- if (this.window && this.window.expiresAt <= Date.now()) this.window = null;- return this.window;+ return this.pairingWindows()[0] ?? null;+ }++ /** Newest first: at most the current window and the one a renewal replaced. */+ pairingWindows(): PairingWindow[] {+ const now = Date.now();+ let expired = false;+ if (this.previousWindow && this.previousWindow.expiresAt <= now) {+ this.previousWindow = null;+ expired = true;+ }+ if (this.window && this.window.expiresAt <= now) {+ this.window = this.previousWindow;+ this.previousWindow = null;+ expired = true;+ }+ if (expired) this.changed();+ return [this.window, this.previousWindow].filter((window): window is PairingWindow => window !== null);+ }++ /** A fresh code while the pairing screen stays open; the one before keeps its remaining time. */+ renewPairing(): PairingWindow {+ const current = this.pairing();+ const next = this.newWindow();+ this.previousWindow = current;+ this.window = next;+ this.changed();+ return next;}/** `randomInt`, not `Math.random`: the code is a credential. */- openPairing(): PairingWindow {- this.clearReplay();- this.window = {+ private newWindow(): PairingWindow {+ return {code: String(randomInt(0, 1_000_000)).padStart(6, "0"),token: `omb_pair_${randomBytes(32).toString("base64url")}`,expiresAt: Date.now() + PAIRING_TTL_MS,attemptsLeft: MAX_PAIRING_ATTEMPTS,};+ }++ /** Replaces any open window. */+ openPairing(): PairingWindow {+ this.clearReplay();+ this.previousWindow = null;+ this.window = this.newWindow();+ this.changed();return this.window;}+ /** With a token: the newest window's closes both; the replaced one's closes only that one. */closePairing(expectedToken?: string): boolean {- if (expectedToken !== undefined && this.pairing()?.token !== expectedToken) return false;+ const [newest, previous] = this.pairingWindows();+ if (expectedToken !== undefined && newest?.token !== expectedToken) {+ if (!previous || previous.token !== expectedToken) return false;+ this.previousWindow = null;+ this.changed();+ return true;+ }+ const wasOpen = newest !== undefined;this.window = null;+ this.previousWindow = null;this.clearReplay();+ if (wasOpen) this.changed();return true;}@@ -206,12 +275,13 @@ export class DeviceRegistry {return this.replay.result;}- const window = this.pairing();- if (!window) return { error: "no pairing is in progress — open Phone settings on your computer" };- if (!sameCredential(window.code, presented) && !sameCredential(window.token, presented)) {- window.attemptsLeft -= 1;- // Without burning the window, six digits is seconds of guessing.- if (window.attemptsLeft <= 0) {+ const windows = this.pairingWindows();+ const window = windows.find((candidate) => sameCredential(candidate.code, presented) || sameCredential(candidate.token, presented));+ if (windows.length === 0) return { error: "no pairing is in progress — open Phone settings on your computer" };+ if (!window) {+ // Every open window pays for a wrong guess: without burning them, six digits is seconds of guessing.+ for (const open of windows) open.attemptsLeft -= 1;+ if (windows.some((open) => open.attemptsLeft <= 0)) {this.closePairing();return { error: "too many incorrect codes — start pairing again" };}@@ -220,8 +290,9 @@ export class DeviceRegistry {// After the code check: a full fleet must not answer wrong guesses, which// would leak state and cost no attempts.if (this.devices.length >= MAX_DEVICES) return { error: "too many paired devices — remove one first" };- // Consume the window without clearing a replay; `closePairing` clears both.+ // Consume every open window without clearing a replay; `closePairing` clears both.this.window = null;+ this.previousWindow = null;const token = `omb_${randomBytes(32).toString("base64url")}`;const device: DeviceRecord = {@@ -232,6 +303,7 @@ export class DeviceRegistry {lastSeenAt: Date.now(),cloudDesktopAccess: false,browserControlAccess: false,+ routes: "any",};this.devices.push(device);// Unlike lastSeenAt, a failed write rolls the registration back: a device@@ -242,6 +314,7 @@ export class DeviceRegistry {this.devices.pop();return { error: `could not save the pairing: ${(e as Error).message}` };}+ this.changed();const { tokenHash: _tokenHash, ...pub } = device;const result = { device: pub, token };if (requestId) {@@ -290,9 +363,37 @@ export class DeviceRegistry {throw error;}this.lastSeenWrites.delete(id);+ this.changed();return true;}+ setRoutes(id: string, routes: DeviceRoutes): boolean {+ const device = this.devices.find((candidate) => candidate.id === id);+ if (!device) return false;+ const previous = device.routes;+ device.routes = routes;+ try {+ this.persist();+ } catch (error) {+ device.routes = previous;+ throw error;+ }+ this.changed();+ return true;+ }++ /** Once: the first end-to-end session ratchets this device off the plain listener for good. */+ markE2E(id: string): void {+ const device = this.devices.find((candidate) => candidate.id === id);+ if (!device || device.e2eAt) return;+ device.e2eAt = Date.now();+ try {+ this.persist();+ } catch {+ // Kept in memory; the next successful write saves it.+ }+ }+/** Per device, so one phone does not inherit another's permission. */setCloudDesktopAccess(id: string, allowed: boolean): boolean {const device = this.devices.find((candidate) => candidate.id === id);diff --git a/companion/src/e2e/config.ts b/companion/src/e2e/config.tsnew file mode 100644index 0000000000..4bd9585f8e--- /dev/null+++ b/companion/src/e2e/config.ts@@ -0,0 +1,78 @@+// What turns end-to-end on: the transport key, and the relay identity once the computer holds a relay token. The+// desktop app sends both over its private port; a standalone sidecar keeps its own key file.+import { existsSync, readFileSync } from "node:fs";+import { join } from "node:path";++import { fromB64u, HOST_ID_BYTES, RELAY_TOKEN_MAX_CHARS } from "./credentials.ts";+import { RELAY_HOST } from "./descriptor.ts";+import { generateKeyPair, keyPairFromPrivate, type KeyPair } from "./noise.ts";+import { DATA_DIR, ensureDataDir, writeFileAtomic } from "../state.ts";++export interface RelayConfig {+ hostId: Buffer;+ nodes: string[];+ token: string;+}++export interface E2EConfig {+ /** Null turns end-to-end off. */+ transportKey: KeyPair | null;+ relay: RelayConfig | null;+}++const TOKEN = /^[A-Za-z0-9_-]+\.[A-Za-z0-9_-]+$/;++/** Exact: anything malformed is refused whole, so a bad relay field can never half-apply. */+export function parseRelayConfig(value: unknown): RelayConfig | null | "invalid" {+ if (value === null || value === undefined) return null;+ if (typeof value !== "object" || Array.isArray(value)) return "invalid";+ const { hostId, nodes, relayToken } = value as Record<string, unknown>;+ const id = typeof hostId === "string" ? fromB64u(hostId) : null;+ if (!id || id.length !== HOST_ID_BYTES) return "invalid";+ if (!Array.isArray(nodes) || nodes.length < 1 || nodes.length > 4) return "invalid";+ if (!nodes.every((node): node is string => typeof node === "string" && RELAY_HOST.test(node))) return "invalid";+ if (typeof relayToken !== "string" || relayToken.length > RELAY_TOKEN_MAX_CHARS || !TOKEN.test(relayToken)) return "invalid";+ return { hostId: id, nodes: [...nodes], token: relayToken };+}++/** The desktop app's `openmausbot:companion-e2e` message: `{transportKey, relay}`, the key as b64u of the 32-byte+ * private scalar. */+export function parseE2EMessage(message: Record<string, unknown>): E2EConfig | null {+ let transportKey: KeyPair | null = null;+ if (message.transportKey !== null) {+ const raw = typeof message.transportKey === "string" ? fromB64u(message.transportKey) : null;+ if (!raw || raw.length !== 32) return null;+ try {+ transportKey = keyPairFromPrivate(raw);+ } catch {+ return null;+ }+ }+ const relay = parseRelayConfig(message.relay);+ if (relay === "invalid" || (relay && !transportKey)) return null;+ return { transportKey, relay };+}++const KEY_FILE = () => join(DATA_DIR, "e2e-key.json");++/** A standalone sidecar's transport key, created once with mode 0600 beside devices.json. */+export function standaloneTransportKey(): KeyPair {+ const file = KEY_FILE();+ if (existsSync(file)) {+ const parsed = JSON.parse(readFileSync(file, "utf8")) as { v?: unknown; privateKey?: unknown };+ const raw = parsed.v === 1 && typeof parsed.privateKey === "string" ? fromB64u(parsed.privateKey) : null;+ if (!raw || raw.length !== 32) throw new Error(`${file} is not a transport key`);+ return keyPairFromPrivate(raw);+ }+ const key = generateKeyPair();+ ensureDataDir();+ writeFileAtomic(file, JSON.stringify({ v: 1, privateKey: key.privateKey.toString("base64url") }));+ return key;+}++/** Test-only: dial `ws://127.0.0.1:<port>` instead of `wss://<node>`. Loopback or TLS only. */+export function relayBaseUrlOverride(value: string | undefined): ((node: string) => string) | undefined {+ if (!value) return undefined;+ if (!/^(wss:\/\/[a-z0-9.-]+(:\d+)?|ws:\/\/(127\.0\.0\.1|localhost)(:\d+)?)$/.test(value)) return undefined;+ return () => value;+}diff --git a/companion/src/e2e/direct.ts b/companion/src/e2e/direct.tsnew file mode 100644index 0000000000..94769c285a--- /dev/null+++ b/companion/src/e2e/direct.ts@@ -0,0 +1,37 @@+// Wi-Fi and Tailscale: the phone dials ws://<host>:8810/v1/e2e on the device listener.+import { isIP } from "node:net";+import type { IncomingMessage } from "node:http";+import type { Duplex } from "node:stream";++import { MAX_RECORD_BYTES, TRANSPORT_DIRECT } from "./noise.ts";+import type { E2EOrigin } from "./origin.ts";+import type { E2ERegistry, LiveRoute } from "./registry.ts";+import { acceptWebSocket } from "./ws-server.ts";++export const E2E_PATH = "/v1/e2e";+export const E2E_PROTOCOL = "omb-e2e.v1";++/** Tailscale's CGNAT range 100.64.0.0/10 and its IPv6 prefix fd7a:115c:a1e0::/48. */+export function routeFor(remoteAddress: string | undefined): LiveRoute {+ const address = (remoteAddress ?? "").replace(/^::ffff:/i, "").toLowerCase();+ if (isIP(address) === 4) {+ const [first, second] = address.split(".").map(Number);+ return first === 100 && second >= 64 && second <= 127 ? "tailscale" : "wifi";+ }+ return address.startsWith("fd7a:115c:a1e0:") ? "tailscale" : "wifi";+}++export const isE2EUpgrade = (req: IncomingMessage): boolean => (req.url ?? "").split("?")[0] === E2E_PATH;++/** Refused outright while end-to-end is off, so a phone keeps to the routes it has. */+export function handleDirectUpgrade(req: IncomingMessage, socket: Duplex, head: Buffer, registry: E2ERegistry, origin: E2EOrigin): void {+ if (!registry.enabled) return void socket.destroy();+ const route = routeFor(req.socket.remoteAddress);+ acceptWebSocket(req, socket, head, { protocol: E2E_PROTOCOL, maxPayload: MAX_RECORD_BYTES }, (connection) => {+ const session = registry.accept(connection, TRANSPORT_DIRECT, route, (context) => origin.connect(context));+ return {+ message: (data, binary) => session?.receive(data, binary),+ close: (code) => session?.transportClosed(code),+ };+ });+}diff --git a/companion/src/e2e/origin.ts b/companion/src/e2e/origin.tsnew file mode 100644index 0000000000..aea254ad41--- /dev/null+++ b/companion/src/e2e/origin.ts@@ -0,0 +1,64 @@+// Where each encrypted stream lands: the same proxy handler as every other listener (allowlist, device-token auth,+// gzip, WebSocket upgrades), reached in memory. Nothing listens on a port or a path, so nothing else can connect.+import { createServer, type IncomingMessage, type ServerResponse } from "node:http";+import { duplexPair, type Duplex } from "node:stream";++import { gzipTunnelReplies } from "../tunnel-gzip.ts";+import type { E2EContext } from "./registry.ts";++const contexts = new WeakMap<object, E2EContext>();++/** The session a request arrived through, or null for any other listener. */+export const e2eContextOf = (socket: object | null | undefined): E2EContext | null => (socket ? contexts.get(socket) ?? null : null);++/** The parts of net.Socket an http.Server and the proxy call. Idle time counts reads, which is what the server's+ * keep-alive timeout waits on. */+function socketLike(socket: Duplex): Duplex {+ let idleMs = 0;+ let timer: ReturnType<typeof setTimeout> | null = null;+ const arm = () => {+ if (timer) clearTimeout(timer);+ timer = idleMs > 0 ? setTimeout(() => socket.emit("timeout"), idleMs) : null;+ timer?.unref?.();+ };+ socket.on("data", arm);+ socket.on("close", () => {+ if (timer) clearTimeout(timer);+ });+ return Object.assign(socket, {+ setTimeout(ms: number, listener?: () => void) {+ idleMs = ms;+ if (listener) socket.once("timeout", listener);+ arm();+ return socket;+ },+ setNoDelay: () => socket,+ setKeepAlive: () => socket,+ });+}++export interface E2EOrigin {+ connect(context: E2EContext): Promise<Duplex>;+ close(): void;+}++export function createE2EOrigin(+ handle: (req: IncomingMessage, res: ServerResponse) => void,+ upgrade: (req: IncomingMessage, socket: Duplex, head: Buffer) => void,+): E2EOrigin {+ // Gzipped like the tunnel listener: the relay hop is the person's home upload too.+ const server = createServer(gzipTunnelReplies(handle));+ server.on("upgrade", upgrade);+ return {+ connect(context) {+ const [near, far] = duplexPair();+ const serverSide = socketLike(far);+ contexts.set(serverSide, context);+ server.emit("connection", serverSide);+ return Promise.resolve(near);+ },+ close() {+ server.closeAllConnections();+ },+ };+}diff --git a/companion/src/e2e/phone.ts b/companion/src/e2e/phone.tsindex 1fc1f52997..8a93a7f80d 100644--- a/companion/src/e2e/phone.ts+++ b/companion/src/e2e/phone.ts@@ -27,7 +27,8 @@ export interface DialOptions {/** Codes a WebSocket client may send; any other closes without one. */const sendable = (code: number) => code === 1000 || (code >= 3000 && code <= 4999);-function transportFor(socket: WebSocket): RecordTransport {+/** A built-in WebSocket client as a record transport. */+export function webSocketTransport(socket: WebSocket): RecordTransport {return {send: (message) => socket.send(message),close: (code, reason) => (sendable(code) ? socket.close(code, reason) : socket.close()),@@ -51,7 +52,7 @@ export function dial(options: DialOptions): Promise<E2ESession<never>> {if (relayed && options.transportByte !== TRANSPORT_RELAY) throw new Error("the relay route uses the relay prologue");const socket = new WebSocket(options.url, [relayed ? RELAY_PROTOCOL : DIRECT_PROTOCOL]);socket.binaryType = "arraybuffer";- const transport = transportFor(socket);+ const transport = webSocketTransport(socket);return new Promise((resolve, reject) => {let session: E2ESession<never> | null = null;const timer = setTimeout(() => {diff --git a/companion/src/e2e/registry.ts b/companion/src/e2e/registry.tsnew file mode 100644index 0000000000..13e7de2ec0--- /dev/null+++ b/companion/src/e2e/registry.ts@@ -0,0 +1,177 @@+// The sidecar's end-to-end state: the transport key, the relay identity, the psk and admission value of every paired+// device and the open pairing window, and which device holds which live session over which route.+import type { Duplex } from "node:stream";++import type { DeviceRegistry } from "../devices.ts";+import { admission, admissionHash, credentialHash, credentialHashFromHex, keyId, psk } from "./credentials.ts";+import { descriptorFor, type E2EDescriptor } from "./descriptor.ts";+import { CLOSE, TRANSPORT_RELAY, type KeyPair, type PskCandidate, type TransportByte } from "./noise.ts";+import { E2ESession, type RecordTransport } from "./session.ts";++export type LiveRoute = "wifi" | "tailscale" | "relay";+export type Peer = { kind: "device"; id: string } | { kind: "pairing" };++/** Shared by every stream of one session, so a pairing session becomes that device's once it has paired. */+export interface E2EContext {+ peer: Peer;+ route: LiveRoute;+}++export interface RelayIdentity {+ hostId: Buffer;+ nodes: string[];+}++interface Live {+ session: E2ESession<Peer>;+ context: E2EContext;+}++const ROUTE_RANK: Record<LiveRoute, number> = { wifi: 0, tailscale: 1, relay: 2 };+/** A session keyed by the pairing token may only pair; one that hasn't by then is closed. */+export const PAIRING_SESSION_MS = 150_000;+/** Handshakes in progress at once; more are refused until one finishes. */+export const MAX_PENDING_HANDSHAKES = 16;++export class E2ERegistry {+ readonly #devices: DeviceRegistry;+ readonly #live = new Set<Live>();+ #key: KeyPair | null = null;+ #relay: RelayIdentity | null = null;+ #pending = 0;++ constructor(devices: DeviceRegistry) {+ this.#devices = devices;+ }++ get enabled(): boolean {+ return this.#key !== null;+ }++ get relay(): RelayIdentity | null {+ return this.#relay;+ }++ setKey(key: KeyPair | null): void {+ this.#key = key;+ if (!key) this.closeAll(CLOSE.normal);+ }++ setRelay(relay: RelayIdentity | null): void {+ this.#relay = relay && relay.nodes.length > 0 ? relay : null;+ }++ /** Every device allowed on this transport, plus each open pairing window (at most 22). */+ candidates(transport: TransportByte): PskCandidate<Peer>[] {+ if (!this.#key) return [];+ const id = keyId(this.#key.publicKey);+ const out: PskCandidate<Peer>[] = [];+ for (const device of this.#devices.records()) {+ if (transport === TRANSPORT_RELAY && device.routes === "local") continue;+ 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) });+ return out;+ }++ /** What the relay may admit: every device not restricted to Wi-Fi and Tailscale, and each open pairing window. */+ admissionSet(): string[] {+ if (!this.#relay) return [];+ const hostId = this.#relay.hostId;+ const out: string[] = [];+ for (const device of this.#devices.records()) {+ if (device.routes === "local") continue;+ const hash = credentialHashFromHex(device.tokenHash);+ 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 one device (null: a phone that is pairing now). A restricted device never learns the relay. */+ descriptor(deviceId: string | null): E2EDescriptor | null {+ if (!this.#key) return null;+ const device = deviceId ? this.#devices.records().find((candidate) => candidate.id === deviceId) : null;+ const relay = this.#relay && device?.routes !== "local" ? this.#relay : undefined;+ return descriptorFor(this.#key.publicKey, relay);+ }++ /** One WebSocket that just opened, on a direct route or a relay data socket. Null when refused. */+ accept(+ transport: RecordTransport,+ transportByte: TransportByte,+ route: LiveRoute,+ connectOrigin: (context: E2EContext) => Promise<Duplex>,+ ): E2ESession<Peer> | null {+ const key = this.#key;+ if (!key || this.#pending >= MAX_PENDING_HANDSHAKES) {+ transport.close(CLOSE.rejected);+ return null;+ }+ this.#pending += 1;+ const live: Live = { context: { peer: { kind: "pairing" }, route }, session: null as unknown as E2ESession<Peer> };+ live.session = E2ESession.computer<Peer>({+ transport,+ transportByte,+ staticKey: key,+ candidates: () => this.candidates(transportByte),+ connectOrigin: () => connectOrigin(live.context),+ opened: (peer) => {+ live.context.peer = peer;+ this.#live.add(live);+ if (peer.kind === "device") return this.#devices.markE2E(peer.id);+ const timer = setTimeout(() => {+ if (live.context.peer.kind === "pairing") live.session.close(CLOSE.rejected);+ }, PAIRING_SESSION_MS);+ timer.unref?.();+ void live.session.closed.then(() => clearTimeout(timer));+ },+ });+ let counted = true;+ const settle = () => {+ if (!counted) return;+ counted = false;+ this.#pending -= 1;+ };+ live.session.ready.then(settle, settle);+ void live.session.closed.then(() => {+ settle();+ this.#live.delete(live);+ });+ return live.session;+ }++ /** A pairing session that redeemed the window now speaks for the new device. */+ paired(context: E2EContext, deviceId: string): void {+ context.peer = { kind: "device", id: deviceId };+ this.#devices.markE2E(deviceId);+ }++ /** Removal: the phone hears 4001 ("removed from your computer"). A narrowed route closes only relay sessions. */+ closeDevice(deviceId: string, code: number = CLOSE.rejected, onlyRoute?: LiveRoute): void {+ 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);+ }+ }++ /** The best live route per device, for "Connected · Wi-Fi". */+ routes(): Record<string, LiveRoute> {+ const out: Record<string, LiveRoute> = {};+ for (const live of this.#live) {+ if (live.context.peer.kind !== "device" || live.session.state !== "open") continue;+ const current = out[live.context.peer.id];+ if (!current || ROUTE_RANK[live.context.route] < ROUTE_RANK[current]) out[live.context.peer.id] = live.context.route;+ }+ return out;+ }++ closeAll(code: number = CLOSE.normal): void {+ for (const live of this.#live) {+ if (code === CLOSE.normal) live.session.shutdown();+ else live.session.close(code);+ }+ }+}diff --git a/companion/src/e2e/relay-client.ts b/companion/src/e2e/relay-client.tsnew file mode 100644index 0000000000..8ac1cc01fe--- /dev/null+++ b/companion/src/e2e/relay-client.ts@@ -0,0 +1,286 @@+// The computer's side of MausBot Relay: one outbound control socket, and one data socket per phone session. The relay+// splices sealed bytes and can't open them; everything here is outside the encryption. Wire spec: README section 9.+import { webSocketTransport } from "./phone.ts";+import type { RecordTransport } from "./session.ts";++export const RELAY_PROTOCOL = "omb-relay.v1";+export type RelayStatus = "connected" | "connecting" | "off";++const BACKOFF_MS = [0, 1_000, 2_000, 4_000, 8_000, 16_000, 32_000, 60_000];+const DEFAULT_TIMING = {+ /** While on a later node, how often to try the first one again (± a fifth). */+ firstNodeRetryMs: 10 * 60_000,+ sleepCheckMs: 2_000,+ sleepJumpMs: 5_000,+ /** The pairing window expires on its own; the admission set is rechecked this often. */+ admissionCheckMs: 5_000,+};++export interface SessionSink {+ receive(data: Uint8Array, binary: boolean): void;+ transportClosed(code: number): void;+}++export interface RelayClientOptions {+ /** Hostnames in the order to try. */+ nodes: string[];+ token: string;+ admissionSet(): string[];+ /** A data socket is spliced: run the computer's session on it. */+ accept(transport: RecordTransport): SessionSink | null;+ /** 4401: the token is invalid or expired. The caller fetches one and calls setToken. */+ tokenRejected(): void;+ statusChanged?(status: RelayStatus, node: string | null): void;+ /** Test-only: `ws://127.0.0.1:<port>` in place of `wss://<node>`. */+ baseUrl?: (node: string) => string;+ random?: () => number;+ timing?: Partial<typeof DEFAULT_TIMING>;+}++interface ControlMessage {+ t?: unknown;+ sid?: unknown;+ node?: unknown;+ reconnectInMs?: unknown;+ tryForMs?: unknown;+}++const jitter = (ms: number, random: () => number) => Math.round(ms * (0.8 + 0.4 * random()));++export class RelayClient {+ readonly #options: RelayClientOptions;+ readonly #timing: typeof DEFAULT_TIMING;+ readonly #random: () => number;+ #nodes: string[];+ #token: string;+ #control: WebSocket | null = null;+ #controlNode = 0;+ #probe: WebSocket | null = null;+ #status: RelayStatus = "off";+ #attempt = 0;+ #stopped = true;+ #awaitingToken = false;+ #lastAdmit = "";+ #retryTimer: ReturnType<typeof setTimeout> | null = null;+ #firstNodeTimer: ReturnType<typeof setTimeout> | null = null;+ #intervals: Array<ReturnType<typeof setInterval>> = [];++ constructor(options: RelayClientOptions) {+ this.#options = options;+ this.#timing = { ...DEFAULT_TIMING, ...options.timing };+ this.#random = options.random ?? Math.random;+ this.#nodes = [...options.nodes];+ this.#token = options.token;+ }++ get status(): RelayStatus {+ return this.#status;+ }++ get node(): string | null {+ return this.#status === "connected" ? this.#nodes[this.#controlNode] ?? null : null;+ }++ start(): void {+ if (!this.#stopped) return;+ this.#stopped = false;+ this.#setStatus("connecting");+ this.#connect(0);+ let wall = Date.now();+ let mono = performance.now();+ this.#intervals.push(+ setInterval(() => {+ const nowWall = Date.now();+ const nowMono = performance.now();+ // A wall-clock jump the monotonic clock didn't see: the computer slept.+ const jumped = Math.abs(nowWall - wall - (nowMono - mono)) > this.#timing.sleepJumpMs;+ wall = nowWall;+ mono = nowMono;+ if (jumped) this.redial();+ }, this.#timing.sleepCheckMs),+ setInterval(() => this.refreshAdmission(), this.#timing.admissionCheckMs),+ );+ for (const interval of this.#intervals) interval.unref?.();+ }++ /** Data sockets already spliced keep running; their sessions end on their own. */+ stop(): void {+ this.#stopped = true;+ this.#clearTimers();+ for (const interval of this.#intervals) clearInterval(interval);+ this.#intervals = [];+ for (const socket of [this.#control, this.#probe]) socket?.close(1000);+ this.#control = null;+ this.#probe = null;+ this.#setStatus("off");+ }++ /** A refreshed token goes to the relay on the same socket; a refused one reconnects. */+ setToken(token: string, nodes?: string[]): void {+ this.#token = token;+ if (nodes && nodes.join(",") !== this.#nodes.join(",")) {+ this.#nodes = [...nodes];+ return this.redial();+ }+ if (this.#awaitingToken) {+ this.#awaitingToken = false;+ return this.#connect(this.#controlNode);+ }+ if (this.#status === "connected") this.#control?.send(JSON.stringify({ t: "auth", v: 1, token }));+ }++ /** After sleep, a network change or a resume: drop the control socket and dial the first node now. */+ redial(): void {+ if (this.#stopped) return;+ this.#clearTimers();+ const old = this.#control;+ this.#control = null;+ old?.close(1000);+ this.#attempt = 0;+ this.#setStatus("connecting");+ this.#connect(0);+ }++ /** Sends the full set whenever it differs from the last one sent. */+ refreshAdmission(force = false): void {+ if (this.#status !== "connected" || !this.#control) return;+ const set = this.#options.admissionSet();+ const text = JSON.stringify(set);+ if (!force && text === this.#lastAdmit) return;+ this.#lastAdmit = text;+ this.#control.send(JSON.stringify({ t: "admit", set }));+ }++ #url(node: string, path: string): string {+ return `${this.#options.baseUrl ? this.#options.baseUrl(node) : `wss://${node}`}${path}`;+ }++ #setStatus(status: RelayStatus): void {+ if (status === this.#status && status !== "connected") return;+ this.#status = status;+ this.#options.statusChanged?.(status, this.node);+ }++ #clearTimers(): void {+ for (const timer of [this.#retryTimer, this.#firstNodeTimer]) if (timer) clearTimeout(timer);+ this.#retryTimer = null;+ this.#firstNodeTimer = null;+ }++ #connect(index: number, probe = false): void {+ if (this.#stopped || this.#nodes.length === 0) return;+ const nodeIndex = index % this.#nodes.length;+ const socket = new WebSocket(this.#url(this.#nodes[nodeIndex], "/v1/host"), [RELAY_PROTOCOL]);+ if (probe) this.#probe = socket;+ else this.#control = socket;+ socket.onopen = () => socket.send(JSON.stringify({ t: "auth", v: 1, token: this.#token }));+ socket.onmessage = (event: MessageEvent) => {+ if (typeof event.data !== "string") return;+ let message: ControlMessage;+ try {+ message = JSON.parse(event.data) as ControlMessage;+ } catch {+ return;+ }+ this.#onControlMessage(socket, nodeIndex, message);+ };+ socket.onclose = (event: CloseEvent) => this.#onControlClose(socket, nodeIndex, event.code, event.reason);+ socket.onerror = () => {};+ }++ #onControlMessage(socket: WebSocket, nodeIndex: number, message: ControlMessage): void {+ if (message.t === "hello") {+ if (socket === this.#probe) {+ // Back on the first node: the new socket first, then the old one goes.+ this.#probe = null;+ const old = this.#control;+ this.#control = socket;+ old?.close(1000);+ }+ if (socket !== this.#control) return;+ this.#controlNode = nodeIndex;+ this.#attempt = 0;+ this.#lastAdmit = "";+ this.#setStatus("connected");+ this.refreshAdmission(true);+ this.#scheduleFirstNode();+ return;+ }+ if (socket !== this.#control) return;+ if (message.t === "open" && typeof message.sid === "string" && /^[A-Za-z0-9_-]{22}$/.test(message.sid)) {+ return this.#openData(nodeIndex, message.sid);+ }+ if (message.t === "restarting") {+ const wait = (Number(message.reconnectInMs) || 0) + this.#random() * (Number(message.tryForMs) || 15_000);+ this.#control = null;+ socket.close(1000);+ this.#retry(nodeIndex + 1, Math.min(wait, 60_000));+ }+ }++ #onControlClose(socket: WebSocket, nodeIndex: number, code: number, reason: string): void {+ if (socket === this.#probe) {+ this.#probe = null;+ return this.#scheduleFirstNode();+ }+ if (socket !== this.#control || this.#stopped) return;+ this.#control = null;+ if (code === 4409) return this.stop();+ const wasConnected = this.#status === "connected";+ this.#setStatus("connecting");+ if (code === 4401) {+ this.#awaitingToken = true;+ this.#controlNode = nodeIndex;+ return this.#options.tokenRejected();+ }+ if (code === 4503) {+ let retryInMs = 5_000;+ try {+ retryInMs = Number((JSON.parse(reason) as { retryInMs?: unknown }).retryInMs) || retryInMs;+ } catch {+ // The default stands.+ }+ return this.#retry(nodeIndex + 1, Math.min(retryInMs, 60_000) + this.#random() * 1_000);+ }+ const delay = jitter(BACKOFF_MS[Math.min(this.#attempt, BACKOFF_MS.length - 1)], this.#random);+ this.#attempt += 1;+ this.#retry(wasConnected ? nodeIndex : nodeIndex + 1, delay);+ }++ #retry(index: number, delayMs: number): void {+ if (this.#stopped) return;+ if (this.#retryTimer) clearTimeout(this.#retryTimer);+ this.#retryTimer = setTimeout(() => {+ this.#retryTimer = null;+ this.#connect(index);+ }, delayMs);+ this.#retryTimer.unref?.();+ }++ #scheduleFirstNode(): void {+ if (this.#firstNodeTimer) clearTimeout(this.#firstNodeTimer);+ this.#firstNodeTimer = null;+ if (this.#controlNode === 0 || this.#stopped) return;+ this.#firstNodeTimer = setTimeout(() => {+ this.#firstNodeTimer = null;+ if (!this.#probe && this.#controlNode !== 0) this.#connect(0, true);+ }, jitter(this.#timing.firstNodeRetryMs, this.#random));+ this.#firstNodeTimer.unref?.();+ }++ #openData(nodeIndex: number, sid: string): void {+ const socket = new WebSocket(this.#url(this.#nodes[nodeIndex], "/v1/host/data"), [RELAY_PROTOCOL]);+ socket.binaryType = "arraybuffer";+ let sink: SessionSink | null = null;+ socket.onopen = () => {+ socket.send(JSON.stringify({ t: "data", v: 1, sid, token: this.#token }));+ sink = this.#options.accept(webSocketTransport(socket));+ };+ socket.onmessage = (event: MessageEvent) => {+ const binary = typeof event.data !== "string";+ sink?.receive(binary ? new Uint8Array(event.data as ArrayBuffer) : Buffer.from(event.data as string, "utf8"), binary);+ };+ socket.onclose = (event: CloseEvent) => sink?.transportClosed(event.code);+ socket.onerror = () => {};+ }+}diff --git a/companion/src/index.ts b/companion/src/index.tsindex e50749eaa2..d38ddf1211 100755--- a/companion/src/index.ts+++ b/companion/src/index.ts@@ -23,6 +23,13 @@ import {} from "./mdns.ts";import { notifyDeviceRevoked } from "./harness-notice.ts";import { createProxyHandler } from "./proxy.ts";+import { parseE2EMessage, parseRelayConfig, relayBaseUrlOverride, standaloneTransportKey, type RelayConfig } from "./e2e/config.ts";+import { b64u } from "./e2e/credentials.ts";+import { handleDirectUpgrade, isE2EUpgrade } from "./e2e/direct.ts";+import { CLOSE, TRANSPORT_RELAY } from "./e2e/noise.ts";+import { createE2EOrigin } from "./e2e/origin.ts";+import { E2ERegistry } from "./e2e/registry.ts";+import { RelayClient } from "./e2e/relay-client.ts";import { companionOriginSocket, listenCompanionOrigin } from "./origin.ts";import { gzipTunnelReplies } from "./tunnel-gzip.ts";import { normalizedPhoneSecretPublicKey } from "./phone-secret-key.ts";@@ -30,7 +37,10 @@ import { machineNameFromConfig } from "./machine-name.ts";// Only Electron supplies this port; Electron children fail closed until initialized.const parentPort = (process as NodeJS.Process & {- parentPort?: { on(event: "message", listener: (event: { data?: unknown }) => void): void };+ parentPort?: {+ on(event: "message", listener: (event: { data?: unknown }) => void): void;+ postMessage(message: unknown): void;+ };}).parentPort;let mutationToken: string | null = null;let controlToken = initialControlToken(process.env, Boolean(parentPort));@@ -39,6 +49,8 @@ const controlReady = controlToken ? Promise.resolve() : new Promise<void>((resolparentPort?.on("message", ({ data }) => {if (!data || typeof data !== "object") return;const message = data as Record<string, unknown>;+ if (message.type === "openmausbot:companion-e2e") return void configureE2E(message);+ if (message.type === "openmausbot:companion-e2e-redial") return void relay?.redial();if (message.type !== "openmausbot:companion-mutation-token") return;if (typeof message.token === "string" && /^[A-Za-z0-9_-]{43}$/.test(message.token)) {mutationToken = message.token;@@ -107,6 +119,9 @@ let stopping = false;const devices = new DeviceRegistry();const mdns = new MdnsResponder();+const e2e = new E2ERegistry(devices);+let relay: RelayClient | null = null;+const relayBaseUrl = relayBaseUrlOverride(process.env.OMB_COMPANION_RELAY_URL);/** Advertise when a network appears, re-advertise when DHCP moves us, withdraw* when it goes. */@@ -138,14 +153,51 @@ const proxy = createProxyHandler({hosts: () => hostCandidates(),endpoints: () => companionEndpointCandidates(COMPANION_PORT, undefined, undefined, hostedUrl),connected: connectedDevices.open,+ e2eDescriptor: (deviceId) => e2e.descriptor(deviceId),+ e2ePaired: (context, deviceId) => e2e.paired(context, deviceId),});-const companion = createServer(proxy);-// `createServer(proxy)` handles plain HTTP only; noVNC's WebSocket arrives as-// Node's separate `upgrade` event.-companion.on("upgrade", proxy.upgrade);+const e2eOrigin = createE2EOrigin((req, res) => proxy(req, res), (req, socket, head) => proxy.upgrade(req, socket, head));+const companion = createServer((req, res) => proxy(req, res, "lan"));+// `createServer` handles plain HTTP only; noVNC's WebSocket and /v1/e2e arrive as Node's separate `upgrade` event.+companion.on("upgrade", (req, socket, head) =>+ isE2EUpgrade(req) ? handleDirectUpgrade(req, socket, head, e2e, e2eOrigin) : proxy.upgrade(req, socket, head, "lan"));// Large JSON replies go gzipped here: this is the only listener whose replies go up the home connection to Cloudflare.-const managedOrigin = PRIVATE_ORIGIN ? createServer(gzipTunnelReplies(proxy)) : null;-managedOrigin?.on("upgrade", proxy.upgrade);+const managedOrigin = PRIVATE_ORIGIN ? createServer(gzipTunnelReplies((req, res) => proxy(req, res, "origin"))) : null;+managedOrigin?.on("upgrade", (req, socket, head) => proxy.upgrade(req, socket, head, "origin"));++function applyRelay(config: RelayConfig | null): void {+ const sameHost = relay && config && e2e.relay?.hostId.equals(config.hostId);+ if (!config || !e2e.enabled || !sameHost) {+ relay?.stop();+ relay = null;+ }+ e2e.setRelay(config && e2e.enabled ? { hostId: config.hostId, nodes: config.nodes } : null);+ if (!config || !e2e.enabled) return;+ if (relay) return relay.setToken(config.token, config.nodes);+ relay = new RelayClient({+ nodes: config.nodes,+ token: config.token,+ admissionSet: () => e2e.admissionSet(),+ accept: (transport) => {+ const session = e2e.accept(transport, TRANSPORT_RELAY, "relay", (context) => e2eOrigin.connect(context));+ return session && { receive: (data, binary) => session.receive(data, binary), transportClosed: (code) => session.transportClosed(code) };+ },+ tokenRejected: () => parentPort?.postMessage({ type: "openmausbot:companion-e2e-token-rejected" }),+ statusChanged: (status, node) => console.log(`e2e: relay ${status}${node ? ` via ${node}` : ""}`),+ baseUrl: relayBaseUrl,+ });+ relay.start();+}++/** The desktop app's message; a malformed one changes nothing. */+function configureE2E(message: Record<string, unknown>): void {+ const config = parseE2EMessage(message);+ if (!config) return void console.warn("e2e: ignored a malformed configuration");+ e2e.setKey(config.transportKey);+ applyRelay(config.relay);+}++devices.onChange(() => relay?.refreshAdmission());const control = createControlServer({devices,@@ -165,10 +217,23 @@ const control = createControlServer({// The harness hears a phone as this computer, so only the sidecar can tell// it the phone lost access and end the Live call that phone holds.revoked: (deviceId) => {+ e2e.closeDevice(deviceId);if (parentPort && !mutationToken) return;void notifyDeviceRevoked({ harnessPort: HARNESS_PORT, deviceId, mutationToken: mutationToken ?? undefined });},refreshTailscale: () => refreshTailnetName(),+ e2e: () => ({ enabled: e2e.enabled, relay: relay?.status ?? "off", node: relay?.node ?? null }),+ liveRoutes: () => e2e.routes(),+ routesChanged: (deviceId, routes) => {+ relay?.refreshAdmission();+ if (routes === "local") e2e.closeDevice(deviceId, CLOSE.normal, "relay");+ },+ setRelay: (body) => {+ const config = parseRelayConfig(body);+ if (config === "invalid" || !e2e.enabled) return false;+ applyRelay(config);+ return true;+ },});const listen = (server: ReturnType<typeof createServer>, port: number, host: string): Promise<void> =>@@ -212,6 +277,12 @@ async function main(): Promise<void> {}await controlReady;+ // Standing alone, end-to-end is opt-in and keeps its own key; the desktop app sends its key over its port.+ if (!parentPort && process.env.OMB_COMPANION_E2E === "1") {+ const key = standaloneTransportKey();+ e2e.setKey(key);+ console.log(`e2e: on, transport key ${b64u(key.publicKey).slice(0, 8)}…`);+ }await listen(control, CONTROL_PORT, "127.0.0.1");await listen(companion, COMPANION_PORT, "0.0.0.0");if (managedOrigin && PRIVATE_ORIGIN) {@@ -226,8 +297,10 @@ async function main(): Promise<void> {// Through the watcher: a laptop may have no addresses yet, and they change// under a running sidecar. Discovery failing is never fatal.- await watcher.check();- watcher.start();+ if (process.env.OMB_COMPANION_BONJOUR !== "0") {+ await watcher.check();+ watcher.start();+ }// A rename in Settings reaches the phone within one tick: the watcher re-advertises when the name moves.nameTimer = setInterval(() => void refreshMachineName().then((changed) => (changed && !stopping ? watcher.check() : undefined)), 30_000);nameTimer.unref?.();@@ -252,6 +325,9 @@ const shutdown = async (signal: string): Promise<void> => {if (nameTimer) clearInterval(nameTimer);await mdns.stop().catch(() => {});// close() waits for open connections, and an SSE stream never ends on its own.+ relay?.stop();+ e2e.closeAll();+ e2eOrigin.close();proxy.closeViewers();companion.closeAllConnections?.();control.closeAllConnections?.();diff --git a/companion/src/proxy.ts b/companion/src/proxy.tsindex e34c2420df..f03374e585 100644--- a/companion/src/proxy.ts+++ b/companion/src/proxy.ts@@ -5,6 +5,9 @@ import { request as httpRequest, type IncomingMessage, type ServerResponse } froimport type { Duplex } from "node:stream";import { bearerToken } from "./devices.ts";+import type { E2EDescriptor } from "./e2e/descriptor.ts";+import { e2eContextOf } from "./e2e/origin.ts";+import type { E2EContext } from "./e2e/registry.ts";import {COMPANION_ENDPOINT_KINDS,MAX_COMPANION_ENDPOINTS,@@ -26,7 +29,7 @@ export interface ProxyOptions {mutationToken?: () => string | null;authenticate: (token: string | undefined,- ) => { id?: string; cloudDesktopAccess: boolean; browserControlAccess: boolean } | null;+ ) => { id?: string; cloudDesktopAccess: boolean; browserControlAccess: boolean; e2eAt?: number } | null;/** Pairing is handled here and never forwarded: the harness has no such route. */redeem: (code: string,@@ -43,6 +46,25 @@ export interface ProxyOptions {* it synchronously on revoke; the returned disposer is called exactly once. */connected?: (deviceId: string, disconnect: () => void) => () => void;headersTimeoutMs?: number;+ /** The `e2e` descriptor for one device (null: the phone pairing now); null when end-to-end is off. */+ e2eDescriptor?: (deviceId: string | null) => E2EDescriptor | null;+ /** A phone paired through an encrypted session keyed by the pairing token: the session is now that device's. */+ e2ePaired?: (context: E2EContext, deviceId: string) => void;+}++/** Which listener a request reached. Only `lan` (port 8810, plain HTTP) refuses a device that has gone end-to-end;+ * requests arriving through an encrypted stream are recognised by their socket, whatever this says. */+export type ProxyListener = "lan" | "origin";++/** §11 rule 4 of the wire spec: a phone that has used the encrypted connection never goes back to plain HTTP. */+const UPDATE_APP = { error: "update_app" } as const;++const PAIRING_SESSION_PATHS = new Set(["POST /api/pair", "GET /api/health"]);++/** A token presented inside a session must belong to the device whose psk opened it. */+function e2eRefusal(context: E2EContext, method: string, path: string, deviceId: string | undefined): string | null {+ if (context.peer.kind === "pairing") return PAIRING_SESSION_PATHS.has(`${method} ${path}`) ? null : "pair this phone first";+ return deviceId && deviceId !== context.peer.id ? "this connection belongs to another device" : null;}export interface CompanionEndpointSnapshot {@@ -264,7 +286,7 @@ function harnessControlCheck(options: ProxyOptions) {export function createProxyHandler(options: ProxyOptions) {const viewers = new CompanionViewerRelay({ checkControl: harnessControlCheck(options) });const capabilityStreams = new Map<string, Set<() => void>>();- const handle = function handle(req: IncomingMessage, res: ServerResponse): void {+ 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" });const path = (req.url ?? "/").split("?")[0];@@ -278,6 +300,10 @@ export function createProxyHandler(options: ProxyOptions) {const token = bearerToken(req.headers.authorization);const device = options.authenticate(token);+ const e2e = e2eContextOf(req.socket);+ if (!e2e && listener === "lan" && device?.e2eAt && path !== "/api/health") return sendJson(res, 426, UPDATE_APP);+ const e2eDenial = e2e ? e2eRefusal(e2e, method, path, device?.id) : null;+ if (e2eDenial) return sendJson(res, 401, { error: e2eDenial });const browserRequest = isBrowserControlAccess(method, path);const browserRefusal = () => {if (!browserRequest) return null;@@ -332,18 +358,23 @@ export function createProxyHandler(options: ProxyOptions) {body.pairRequestId,);if ("error" in result) return sendJson(res, 401, { error: result.error });+ const pairedId = (result.device as { id?: unknown } | null)?.id;+ if (e2e && typeof pairedId === "string") options.e2ePaired?.(e2e, pairedId);const hosts = options.hosts?.() ?? [];const endpoints = options.endpoints?.() ?? [];+ const descriptor = options.e2eDescriptor?.(typeof pairedId === "string" ? pairedId : null) ?? null;const response: typeof result & {serverName: string;hosts?: string[];endpoints?: CompanionEndpoint[];+ e2e?: E2EDescriptor;} = {...result,serverName: options.serverName(),};if (hosts.length) response.hosts = hosts;if (endpoints.length) response.endpoints = endpoints;+ if (descriptor) response.e2e = descriptor;return sendJson(res, 201, response);},(error: Error) => sendJson(res, 400, { error: error.message }),@@ -357,7 +388,8 @@ 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") {- return sendJson(res, 200, endpointSnapshot(options));+ const descriptor = options.e2eDescriptor?.(device?.id ?? null) ?? null;+ return sendJson(res, 200, { ...endpointSnapshot(options), ...(descriptor ? { e2e: descriptor } : {}) });}const mutationToken = device ? options.mutationToken?.() : undefined;@@ -634,13 +666,22 @@ export function createProxyHandler(options: ProxyOptions) {req.pipe(upstream);};- handle.upgrade = (req: IncomingMessage, socket: Duplex, head: Buffer): void => {+ handle.upgrade = (req: IncomingMessage, socket: Duplex, head: Buffer, listener: ProxyListener = "lan"): void => {if (req.headers.origin) {socket.destroy();return;}const token = bearerToken(req.headers.authorization);const device = options.authenticate(token);+ const e2e = e2eContextOf(req.socket);+ if (!e2e && listener === "lan" && device?.e2eAt) {+ socket.end("HTTP/1.1 426 Upgrade Required\r\nConnection: close\r\nContent-Length: 0\r\n\r\n");+ return;+ }+ if (e2e && e2eRefusal(e2e, req.method ?? "GET", (req.url ?? "/").split("?")[0], device?.id)) {+ socket.destroy();+ return;+ }viewers.handleUpgrade(req, socket, head, device);};handle.closeViewers = (): void => viewers.closeAll();