Open-source Grok Bot alternative with a virtual machine that bots can use
TypeScript ai-agentsclaude-codecodexcomputer-usedockerelectrongrokgrok-botgrok-bot-alternativeself-hostedtypescript
companion: E2E session, dependency-free WebSocket server, reference phone and interop server
milind-sonia7d300dd0c95
diff --git a/companion/src/e2e/interop-server.ts b/companion/src/e2e/interop-server.tsnew file mode 100644index 0000000000..03bd4852cb--- /dev/null+++ b/companion/src/e2e/interop-server.ts@@ -0,0 +1,213 @@+// A computer for other implementations to test against: `node companion/src/e2e/interop-server.ts [--port N]`.+// It holds the vector transport key and accepts the vector device and pairing tokens, so a client needs only+// vectors/v1.json. No dependencies: it runs from a plain checkout with Node 24 or later.+//+// Prints one JSON line when ready. Routes:+// /v1/e2e direct transport (0x02), the normal case+// /test/relay-transport the relay prologue (0x01) without a relay+// /test/wrong-key a key swap: any message 1 gets a well-formed message 2 that can't verify (a hard stop)+// Origin paths, over any stream:+// GET /api/health {"ok":true}+// POST /upload {"bytes":N,"sha256":"<hex>"} of the body+// POST /echo the body back, streamed+// GET /bytes?n=N N bytes, byte i = i % 251; one Range is honoured+// GET /sse?events=M&size=S&gapMs=G M events of S bytes each, a keepalive comment between, then `event: end`+// GET /wait?ms=N answers after N ms+// GET /hang headers and one event, then nothing+// GET /ws (Upgrade: websocket) echoes every message+import { createHash, randomBytes } from "node:crypto";+import { readFileSync } from "node:fs";+import { createServer, type IncomingMessage, type ServerResponse } from "node:http";+import { connect, type AddressInfo } from "node:net";+import type { Duplex } from "node:stream";++import { b64u, credentialHash, keyId, psk } from "./credentials.ts";+import { generateKeyPair, keyPairFromPrivate, MAX_RECORD_BYTES, TAG_BYTES, TRANSPORT_DIRECT, TRANSPORT_RELAY, type TransportByte } from "./noise.ts";+import { E2ESession } from "./session.ts";+import { acceptWebSocket } from "./ws-server.ts";++const vectors = JSON.parse(readFileSync(new URL("./vectors/v1.json", import.meta.url), "utf8")) as {+ inputs: { transportPrivate: string; deviceToken: string; pairingToken: string };+};++const arg = (name: string): string | undefined => {+ const index = process.argv.indexOf(`--${name}`);+ return index >= 0 ? process.argv[index + 1] : undefined;+};++const T = keyPairFromPrivate(Buffer.from(vectors.inputs.transportPrivate, "hex"));+const tokens = { device: vectors.inputs.deviceToken, pairing: vectors.inputs.pairingToken };+const candidates = Object.entries(tokens).map(([id, token]) => ({ id, psk: psk(credentialHash(token), keyId(T.publicKey)) }));++const pattern = (start: number, length: number): Buffer => {+ const out = Buffer.alloc(length);+ for (let index = 0; index < length; index += 1) out[index] = (start + index) % 251;+ return out;+};++function bytesRoute(req: IncomingMessage, res: ServerResponse, total: number): void {+ const range = /^bytes=(\d+)-(\d*)$/.exec(req.headers.range ?? "");+ let start = 0;+ let end = total - 1;+ if (req.headers.range) {+ if (!range || Number(range[1]) >= total) {+ res.writeHead(416, { "Content-Range": `bytes */${total}` }).end();+ return;+ }+ start = Number(range[1]);+ end = range[2] ? Math.min(Number(range[2]), total - 1) : total - 1;+ }+ const length = end - start + 1;+ res.writeHead(req.headers.range ? 206 : 200, {+ "Content-Type": "application/octet-stream",+ "Content-Length": length,+ "Accept-Ranges": "bytes",+ ...(req.headers.range ? { "Content-Range": `bytes ${start}-${end}/${total}` } : {}),+ });+ let offset = start;+ const pump = () => {+ while (offset <= end) {+ const size = Math.min(64 * 1024, end - offset + 1);+ const more = res.write(pattern(offset, size));+ offset += size;+ if (!more) return void res.once("drain", pump);+ }+ res.end();+ };+ pump();+}++function sseRoute(res: ServerResponse, events: number, size: number, gapMs: number): void {+ res.writeHead(200, { "Content-Type": "text/event-stream", "Cache-Control": "no-cache" });+ let sent = 0;+ const next = () => {+ if (res.destroyed) return;+ if (sent === events) return void res.end("event: end\ndata: {}\n\n");+ const data = Buffer.alloc(size, 0x61 + (sent % 26)).toString("latin1");+ sent += 1;+ const more = res.write(`id: ${sent}\ndata: ${data}\n\n`);+ const later = () => (gapMs > 0 ? setTimeout(() => (res.write(": keepalive\n\n"), next()), gapMs) : setImmediate(next));+ if (more) later();+ else res.once("drain", later);+ };+ next();+}++function origin(req: IncomingMessage, res: ServerResponse): void {+ const url = new URL(req.url ?? "/", "http://origin");+ const number = (name: string, fallback: number) => {+ const value = Number(url.searchParams.get(name));+ return Number.isSafeInteger(value) && value >= 0 ? value : fallback;+ };+ if (req.method === "GET" && url.pathname === "/api/health") return void res.writeHead(200, { "Content-Type": "application/json" }).end('{"ok":true}');+ if (req.method === "POST" && url.pathname === "/upload") {+ const hash = createHash("sha256");+ let bytes = 0;+ req.on("data", (chunk: Buffer) => {+ bytes += chunk.length;+ hash.update(chunk);+ });+ req.on("end", () => res.writeHead(200, { "Content-Type": "application/json" }).end(JSON.stringify({ bytes, sha256: hash.digest("hex") })));+ return;+ }+ if (req.method === "POST" && url.pathname === "/echo") {+ res.writeHead(200, { "Content-Type": "application/octet-stream" });+ return void req.pipe(res);+ }+ if (req.method === "GET" && url.pathname === "/bytes") return bytesRoute(req, res, number("n", 0));+ if (req.method === "GET" && url.pathname === "/sse") return sseRoute(res, number("events", 1), number("size", 1024), number("gapMs", 0));+ if (req.method === "GET" && url.pathname === "/wait") {+ const timer = setTimeout(() => res.writeHead(200, { "Content-Type": "application/json" }).end('{"waited":true}'), number("ms", 0));+ return void res.on("close", () => clearTimeout(timer));+ }+ if (req.method === "GET" && url.pathname === "/hang") {+ res.writeHead(200, { "Content-Type": "text/event-stream" });+ return void res.write("data: start\n\n");+ }+ res.writeHead(404).end();+}++const originServer = createServer(origin);+originServer.on("upgrade", (req: IncomingMessage, socket: Duplex, head: Buffer) => {+ if (new URL(req.url ?? "/", "http://origin").pathname !== "/ws") return void socket.destroy();+ acceptWebSocket(req, socket, head, { protocol: null, maxPayload: 16 * 1024 * 1024 }, (connection) => ({+ message: (data) => connection.send(data),+ close: () => {},+ }));+});++const routes: Record<string, TransportByte | "impostor"> = {+ "/v1/e2e": TRANSPORT_DIRECT,+ "/test/relay-transport": TRANSPORT_RELAY,+ "/test/wrong-key": "impostor",+};++/** What a relay holding no key can do: answer with a fresh point and bytes of the right length. */+const impostorMessage2 = () => Buffer.concat([generateKeyPair().publicKey, randomBytes(JSON.stringify({ v: 1, conn: "x".repeat(22) }).length + TAG_BYTES)]);++const pingIntervalMs = arg("ping-interval-ms") ? Number(arg("ping-interval-ms")) : undefined;+const server = createServer((_req, res) => res.writeHead(404).end());+server.on("upgrade", (req: IncomingMessage, socket: Duplex, head: Buffer) => {+ const route = routes[new URL(req.url ?? "/", "http://interop").pathname];+ if (!route) return void socket.destroy();+ if (route === "impostor") {+ acceptWebSocket(req, socket, head, { protocol: "omb-e2e.v1", maxPayload: MAX_RECORD_BYTES }, (connection) => ({+ message: () => connection.send(impostorMessage2()),+ close: () => {},+ }));+ return;+ }+ let session: E2ESession<string> | null = null;+ acceptWebSocket(req, socket, head, { protocol: "omb-e2e.v1", maxPayload: MAX_RECORD_BYTES }, (connection) => {+ session = E2ESession.computer({+ transport: connection,+ transportByte: route,+ staticKey: T,+ candidates: () => candidates,+ connectOrigin: () =>+ new Promise((resolve, reject) => {+ const port = (originServer.address() as AddressInfo).port;+ const originSocket = connect({ host: "127.0.0.1", port, allowHalfOpen: true }, () => resolve(originSocket));+ originSocket.once("error", reject);+ }),+ opened: (id, payload1) => console.error(`session ${req.url} ${id} ${payload1.app ?? ""}`),+ pingIntervalMs,+ });+ return {+ message: (data, binary) => session?.receive(data, binary),+ close: (code) => session?.transportClosed(code),+ };+ });+});++const listen = (target: ReturnType<typeof createServer>, port: number, host: string) =>+ new Promise<number>((resolve) => target.listen(port, host, () => resolve((target.address() as AddressInfo).port)));++const host = arg("host") ?? "127.0.0.1";+await listen(originServer, 0, "127.0.0.1");+const port = await listen(server, Number(arg("port") ?? 0), host);+const base = `ws://${host}:${port}`;+console.log(+ JSON.stringify({+ ready: true,+ port,+ direct: `${base}/v1/e2e`,+ relayTransport: `${base}/test/relay-transport`,+ wrongKey: `${base}/test/wrong-key`,+ k: b64u(T.publicKey),+ deviceToken: tokens.device,+ pairingToken: tokens.pairing,+ }),+);++const stop = () => {+ server.closeAllConnections();+ originServer.closeAllConnections();+ process.exit(0);+};+process.on("SIGINT", stop);+process.on("SIGTERM", stop);+if (process.argv.includes("--exit-with-stdin")) {+ process.stdin.on("end", stop);+ process.stdin.resume();+}diff --git a/companion/src/e2e/noise.ts b/companion/src/e2e/noise.tsindex 60bcb4bd22..97ad524663 100644--- a/companion/src/e2e/noise.ts+++ b/companion/src/e2e/noise.ts@@ -1,8 +1,8 @@// Noise_NKpsk0_P256_AESGCM_SHA256 (Noise Protocol Framework rev 34, with P-256 as the DH function) and the// transport records that follow it. Wire spec: companion/src/e2e/README.md, "Handshake" and "Transport messages".-import { createCipheriv, createDecipheriv, createECDH, randomBytes } from "node:crypto";+import { createCipheriv, createDecipheriv, createECDH, hkdfSync, randomBytes } from "node:crypto";-import { b64u, fromB64u, hmacSha256, sha256 } from "./credentials.ts";+import { b64u, fromB64u, sha256 } from "./credentials.ts";export const PROTOCOL_NAME = "Noise_NKpsk0_P256_AESGCM_SHA256";export const PUBLIC_KEY_BYTES = 65;@@ -89,16 +89,10 @@ export function isPublicKey(bytes: Uint8Array): boolean {}}-/** Noise HKDF over HMAC-SHA256. */+/** Noise's HKDF is RFC 5869 HKDF-SHA256 with the chaining key as salt and empty info. */export function hkdf(chainingKey: Uint8Array, ikm: Uint8Array, outputs: 2 | 3): Buffer[] {- const temp = hmacSha256(chainingKey, ikm);- const out: Buffer[] = [];- let previous: Buffer = Buffer.alloc(0);- for (let index = 1; index <= outputs; index += 1) {- previous = hmacSha256(temp, Buffer.concat([previous, Buffer.from([index])]));- out.push(previous);- }- return out;+ const out = Buffer.from(hkdfSync("sha256", ikm, chainingKey, Buffer.alloc(0), 32 * outputs));+ return Array.from({ length: outputs }, (_, index) => out.subarray(index * 32, index * 32 + 32));}export function nonceBytes(n: number): Buffer {diff --git a/companion/src/e2e/phone.ts b/companion/src/e2e/phone.tsnew file mode 100644index 0000000000..1fc1f52997--- /dev/null+++ b/companion/src/e2e/phone.ts@@ -0,0 +1,103 @@+// The reference phone: dials a route with Node's built-in WebSocket client and returns an open session. Used by the+// interop and integration tests, and by a desktop reaching another desktop.+import { b64u } from "./credentials.ts";+import { E2ESession, SEND_BUFFER_HIGH, SessionClosed, type RecordTransport } from "./session.ts";+import { HANDSHAKE_DEADLINE_MS, TRANSPORT_RELAY, type KeyPair, type TransportByte } from "./noise.ts";++export const DIRECT_PROTOCOL = "omb-e2e.v1";+export const RELAY_PROTOCOL = "omb-relay.v1";+const DRAIN_POLL_MS = 5;++export interface DialOptions {+ /** `ws://host:port/v1/e2e` for Wi-Fi and Tailscale, `wss://relayN.openmausbot.com/v1/phone` for the relay. */+ url: string;+ transportByte: TransportByte;+ remoteStatic: Uint8Array;+ psk: Uint8Array;+ app: string;+ /** On the relay: the hostId and this device's admission value, sent before the handshake. */+ relay?: { hostId: Uint8Array; adm: Uint8Array };+ timeoutMs?: number;+ /** Test-only. */+ ephemeral?: KeyPair;+ pingIntervalMs?: number;+ pingTimeoutMs?: number;+}++/** 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 {+ return {+ send: (message) => socket.send(message),+ close: (code, reason) => (sendable(code) ? socket.close(code, reason) : socket.close()),+ get bufferedAmount() {+ return socket.bufferedAmount;+ },+ // The built-in client has no drain event.+ onceDrained(listener) {+ const check = () => {+ if (socket.readyState !== WebSocket.OPEN || socket.bufferedAmount <= SEND_BUFFER_HIGH / 4) listener();+ else setTimeout(check, DRAIN_POLL_MS);+ };+ check();+ },+ };+}++/** Rejects with SessionClosed (the close code, e.g. 4001 or a relay 4404) or a NoiseError (a hard stop). */+export function dial(options: DialOptions): Promise<E2ESession<never>> {+ const relayed = Boolean(options.relay);+ 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);+ return new Promise((resolve, reject) => {+ let session: E2ESession<never> | null = null;+ const timer = setTimeout(() => {+ reject(new SessionClosed(4002));+ socket.close();+ }, (options.timeoutMs ?? HANDSHAKE_DEADLINE_MS) + (relayed ? 10_000 : 0));+ const start = () => {+ session = E2ESession.phone({ ...options, transport });+ session.ready.then(+ () => {+ clearTimeout(timer);+ resolve(session as E2ESession<never>);+ },+ (error: Error) => {+ clearTimeout(timer);+ reject(error);+ },+ );+ };+ socket.onopen = () => {+ if (!options.relay) return start();+ socket.send(JSON.stringify({ t: "phone", v: 1, hid: b64u(options.relay.hostId), adm: b64u(options.relay.adm) }));+ };+ socket.onmessage = (event: MessageEvent) => {+ const binary = typeof event.data !== "string";+ const data = binary ? new Uint8Array(event.data as ArrayBuffer) : Buffer.from(event.data as string, "utf8");+ if (session) return session.receive(data, binary);+ // Before the session: only the relay's ready.+ let ready = false;+ try {+ ready = !binary && (JSON.parse(String(event.data)) as { t?: unknown }).t === "ready";+ } catch {+ ready = false;+ }+ if (!ready) {+ clearTimeout(timer);+ reject(new SessionClosed(4400));+ return socket.close();+ }+ start();+ };+ socket.onclose = (event: CloseEvent) => {+ clearTimeout(timer);+ if (session) session.transportClosed(event.code);+ else reject(new SessionClosed(event.code));+ };+ socket.onerror = () => {};+ });+}diff --git a/companion/src/e2e/session.ts b/companion/src/e2e/session.tsnew file mode 100644index 0000000000..308a98b5cd--- /dev/null+++ b/companion/src/e2e/session.ts@@ -0,0 +1,398 @@+// One encrypted session over any message transport: the handshake, then records carrying yamux frames, each stream+// a Node Duplex. The computer pipes every stream to its own origin socket; the phone hands streams to an HTTP stack.+import { Duplex } from "node:stream";++import {+ CLOSE,+ computerAccept,+ encodePayload1,+ HANDSHAKE_DEADLINE_MS,+ newConn,+ NoiseError,+ NONCE_LIMIT,+ phoneHello,+ type KeyPair,+ type Payload1,+ type PhoneHello,+ type PskCandidate,+ type SessionKeys,+ type TransportByte,+} from "./noise.ts";+import { b64u } from "./credentials.ts";+import { decodeFrame, encodeFrame, GO_AWAY, Mux, PING_INTERVAL_MS, PING_TIMEOUT_MS, YamuxError, type Frame, type Role } from "./yamux.ts";++/** A sender stops writing records while the socket holds more than this. */+export const SEND_BUFFER_HIGH = 1024 * 1024;++/** A WebSocket, as the session needs it: binary messages out, a close, and backpressure. */+export interface RecordTransport {+ send(message: Uint8Array): void;+ close(code: number, reason?: string): void;+ readonly bufferedAmount: number;+ onceDrained(listener: () => void): void;+}++export class SessionClosed extends Error {+ readonly code: number;+ constructor(code: number) {+ super(`e2e session closed (${code})`);+ this.code = code;+ }+}++interface Timers {+ pingIntervalMs?: number;+ pingTimeoutMs?: number;+ handshakeDeadlineMs?: number;+}++export interface ComputerSessionOptions<Id> extends Timers {+ transport: RecordTransport;+ transportByte: TransportByte;+ staticKey: KeyPair;+ /** Read when message 1 arrives, so a revoke or a closed pairing window applies at once. */+ candidates(): ReadonlyArray<PskCandidate<Id>>;+ /** A fresh connection to the private origin listener, per stream. */+ connectOrigin(): Promise<Duplex>;+ opened?(id: Id, payload1: Payload1): void;+}++export interface PhoneSessionOptions extends Timers {+ transport: RecordTransport;+ transportByte: TransportByte;+ remoteStatic: Uint8Array;+ psk: Uint8Array;+ app: string;+ /** Test-only. */+ ephemeral?: KeyPair;+}++const noop = () => {};++export class MuxStream extends Duplex {+ readonly streamId: number;+ readonly #session: E2ESession<unknown>;+ #pending: Buffer | null = null;+ #pendingDone: ((error?: Error | null) => void) | null = null;+ #ungranted = 0;++ constructor(session: E2ESession<unknown>, streamId: number) {+ super({ allowHalfOpen: true, readableHighWaterMark: 256 * 1024 });+ this.#session = session;+ this.streamId = streamId;+ // A reset reaches whoever listens; without a listener it must not take the process down.+ this.on("error", noop);+ }++ override _write(chunk: Buffer, _encoding: BufferEncoding, done: (error?: Error | null) => void): void {+ this.#pending = chunk;+ this.#pendingDone = done;+ this.flush();+ }++ override _final(done: (error?: Error | null) => void): void {+ this.#session.mux?.finish(this.streamId);+ done();+ }++ override _read(): void {+ if (this.#ungranted === 0) return;+ const bytes = this.#ungranted;+ this.#ungranted = 0;+ this.#session.mux?.consumed(this.streamId, bytes);+ }++ override _destroy(error: Error | null, done: (error?: Error | null) => void): void {+ const mux = this.#session.mux;+ if (mux?.has(this.streamId)) mux.reset(this.streamId);+ this.#session.forget(this.streamId);+ const pendingDone = this.#pendingDone;+ this.#pending = null;+ this.#pendingDone = null;+ pendingDone?.(error ?? new Error("stream reset"));+ done(error);+ }++ /** Granted back as the reader takes it, so a slow reader slows the sender. */+ deliver(data: Buffer): void {+ if (this.push(data)) this.#session.mux?.consumed(this.streamId, data.length);+ else this.#ungranted += data.length;+ }++ remoteEnded(): void {+ this.push(null);+ }++ remoteReset(): void {+ if (!this.destroyed) this.destroy(new Error("stream reset"));+ }++ flush(): void {+ const mux = this.#session.mux;+ while (this.#pending && this.#pending.length > 0) {+ if (!mux || !mux.has(this.streamId)) return void this.destroy(new Error("stream reset"));+ if (this.#session.congested) return this.#session.whenDrained(() => this.flush());++ const taken = mux.write(this.streamId, this.#pending);+ if (taken === 0) return;+ this.#pending = this.#pending.subarray(taken);+ }+ const done = this.#pendingDone;+ this.#pending = null;+ this.#pendingDone = null;+ done?.();+ }+}++type State = "handshake" | "open" | "closed";++export class E2ESession<Id> {+ readonly role: Role;+ readonly #transport: RecordTransport;+ readonly #streams = new Map<number, MuxStream>();+ readonly #timers: Required<Timers>;+ #state: State = "handshake";+ #keys: SessionKeys | null = null;+ #mux: Mux | null = null;+ #accept: ((message: Buffer) => void) | null = null;+ #deadline: ReturnType<typeof setTimeout> | null = null;+ #pingTimer: ReturnType<typeof setInterval> | null = null;+ #pongTimer: ReturnType<typeof setTimeout> | null = null;+ #awaitingPong: number | null = null;+ #pingCounter = 0;+ #drainWaiters: Array<() => void> = [];+ #settleReady!: (error?: Error) => void;+ #settleClosed!: (code: number) => void;+ #connectOrigin: (() => Promise<Duplex>) | null = null;+ /** The computer side: which device (or pairing window) this is. */+ peer: Id | null = null;+ readonly ready: Promise<void>;+ readonly closed: Promise<number>;++ private constructor(role: Role, transport: RecordTransport, timers: Timers) {+ this.role = role;+ this.#transport = transport;+ this.#timers = {+ pingIntervalMs: timers.pingIntervalMs ?? PING_INTERVAL_MS,+ pingTimeoutMs: timers.pingTimeoutMs ?? PING_TIMEOUT_MS,+ handshakeDeadlineMs: timers.handshakeDeadlineMs ?? HANDSHAKE_DEADLINE_MS,+ };+ this.ready = new Promise((resolve, reject) => {+ this.#settleReady = (error) => (error ? reject(error) : resolve());+ });+ this.ready.catch(noop);+ this.closed = new Promise((resolve) => {+ this.#settleClosed = resolve;+ });+ this.#deadline = setTimeout(() => this.close(CLOSE.deadline), this.#timers.handshakeDeadlineMs);+ this.#deadline.unref?.();+ }++ /** Waits for message 1. Anything wrong with it closes 4001 and nothing else is sent. */+ static computer<Id>(options: ComputerSessionOptions<Id>): E2ESession<Id> {+ const session = new E2ESession<Id>("computer", options.transport, options);+ session.#connectOrigin = options.connectOrigin;+ session.#accept = (message) => {+ const accepted = computerAccept({ staticKey: options.staticKey, transport: options.transportByte, candidates: options.candidates() }, message);+ if (!accepted) return session.close(CLOSE.rejected);+ options.transport.send(accepted.message2);+ session.peer = accepted.id;+ session.#start(accepted.keys);+ options.opened?.(accepted.id, accepted.payload1);+ };+ return session;+ }++ /** Sends message 1 now. `ready` rejects with a NoiseError when the computer can't be verified: a hard stop. */+ static phone(options: PhoneSessionOptions): E2ESession<never> {+ const session = new E2ESession<never>("phone", options.transport, options);+ const conn = newConn();+ const hello: PhoneHello = phoneHello(+ { remoteStatic: options.remoteStatic, psk: options.psk, transport: options.transportByte, ephemeral: options.ephemeral },+ encodePayload1(conn, options.app),+ b64u(conn),+ );+ session.#accept = (message) => {+ let keys: SessionKeys;+ try {+ keys = hello.finish(message);+ } catch (error) {+ session.#settleReady(error as Error);+ return session.close(CLOSE.protocol);+ }+ session.#start(keys);+ };+ options.transport.send(hello.message1);+ return session;+ }++ get mux(): Mux | null {+ return this.#mux;+ }++ get state(): State {+ return this.#state;+ }++ get congested(): boolean {+ return this.#transport.bufferedAmount > SEND_BUFFER_HIGH;+ }++ get activeStreams(): number {+ return this.#streams.size;+ }++ whenDrained(listener: () => void): void {+ this.#drainWaiters.push(listener);+ if (this.#drainWaiters.length > 1) return;+ this.#transport.onceDrained(() => {+ const waiters = this.#drainWaiters;+ this.#drainWaiters = [];+ for (const waiter of waiters) waiter();+ });+ }++ forget(streamId: number): void {+ this.#streams.delete(streamId);+ }++ /** Every message the transport receives, in order. */+ receive(message: Uint8Array, binary: boolean): void {+ if (this.#state === "closed") return;+ if (this.#state === "handshake") {+ const accept = this.#accept;+ this.#accept = null;+ if (!binary || !accept) return this.close(this.role === "computer" ? CLOSE.rejected : CLOSE.protocol);+ return accept(Buffer.from(message));+ }+ if (!binary) return this.close(CLOSE.protocol);+ let plaintext: Buffer;+ try {+ plaintext = (this.#keys as SessionKeys).receive.open(message);+ } catch {+ return this.close(CLOSE.protocol);+ }+ try {+ (this.#mux as Mux).receive(decodeFrame(plaintext));+ } catch (error) {+ if (!(error instanceof YamuxError)) throw error;+ this.#mux?.protocolError();+ this.close(CLOSE.protocol);+ }+ }++ /** The phone side. */+ openStream(): MuxStream {+ if (this.#state !== "open" || !this.#mux) throw new SessionClosed(CLOSE.normal);+ const streamId = this.#mux.open();+ const stream = new MuxStream(this as E2ESession<unknown>, streamId);+ this.#streams.set(streamId, stream);+ return stream;+ }++ /** A planned close (quit, sleep, restart): GoAway first, so the peer knows it isn't an error. */+ shutdown(): void {+ if (this.#state === "open") this.#mux?.goAway(GO_AWAY.normal);+ this.close(CLOSE.normal);+ }++ close(code: number, reason?: string): void {+ if (this.#state === "closed") return;+ this.#transport.close(code, reason);+ this.#end(code);+ }++ /** The transport closed under us. */+ transportClosed(code: number): void {+ this.#end(code);+ }++ #end(code: number): void {+ if (this.#state === "closed") return;+ const wasHandshake = this.#state === "handshake";+ this.#state = "closed";+ for (const timer of [this.#deadline, this.#pongTimer]) if (timer) clearTimeout(timer);+ if (this.#pingTimer) clearInterval(this.#pingTimer);+ this.#mux?.closeAll();+ for (const stream of this.#streams.values()) stream.remoteReset();+ this.#streams.clear();+ const waiters = this.#drainWaiters;+ this.#drainWaiters = [];+ for (const waiter of waiters) waiter();+ if (wasHandshake) this.#settleReady(new SessionClosed(code));+ this.#settleClosed(code);+ }++ #start(keys: SessionKeys): void {+ if (this.#deadline) clearTimeout(this.#deadline);+ this.#keys = keys;+ this.#state = "open";+ this.#mux = new Mux(this.role, {+ send: (frame) => this.#send(frame),+ opened: (streamId) => this.#openOrigin(streamId),+ data: (streamId, data) => this.#streams.get(streamId)?.deliver(Buffer.from(data.buffer, data.byteOffset, data.byteLength)),+ ended: (streamId) => this.#streams.get(streamId)?.remoteEnded(),+ reset: (streamId) => {+ const stream = this.#streams.get(streamId);+ this.#streams.delete(streamId);+ stream?.remoteReset();+ },+ writable: (streamId) => this.#streams.get(streamId)?.flush(),+ goAway: (code) => {+ if (code !== GO_AWAY.normal) this.close(CLOSE.protocol);+ },+ pong: (value) => {+ if (value !== this.#awaitingPong) return;+ this.#awaitingPong = null;+ if (this.#pongTimer) clearTimeout(this.#pongTimer);+ },+ });+ this.#pingTimer = setInterval(() => this.#ping(), this.#timers.pingIntervalMs);+ this.#pingTimer.unref?.();+ this.#settleReady();+ }++ #ping(): void {+ if (this.#awaitingPong !== null || !this.#mux) return;+ this.#pingCounter = (this.#pingCounter + 1) >>> 0;+ this.#awaitingPong = this.#pingCounter;+ this.#mux.ping(this.#pingCounter);+ this.#pongTimer = setTimeout(() => this.close(CLOSE.goingAway), this.#timers.pingTimeoutMs);+ this.#pongTimer.unref?.();+ }++ #send(frame: Frame): void {+ if (this.#state !== "open" || !this.#keys) return;+ let record: Buffer;+ try {+ record = this.#keys.send.seal(encodeFrame(frame));+ } catch (error) {+ if (error instanceof NoiseError) return this.close(CLOSE.normal);+ throw error;+ }+ this.#transport.send(record);+ // Well before the counter could repeat; the phone reconnects.+ if (this.#keys.send.nonce >= NONCE_LIMIT - 1024) queueMicrotask(() => this.close(CLOSE.normal));+ }++ #openOrigin(streamId: number): void {+ const stream = new MuxStream(this as E2ESession<unknown>, streamId);+ this.#streams.set(streamId, stream);+ const connect = this.#connectOrigin;+ if (!connect) return void stream.destroy();+ connect().then(+ (socket) => {+ if (stream.destroyed || this.#state !== "open") return void socket.destroy();+ this.#mux?.accept(streamId);+ socket.on("error", () => stream.destroy());+ socket.on("close", () => {+ if (!socket.readableEnded) stream.destroy();+ });+ stream.on("close", () => socket.destroy());+ stream.pipe(socket);+ socket.pipe(stream);+ },+ () => stream.destroy(),+ );+ }+}diff --git a/companion/src/e2e/ws-server.ts b/companion/src/e2e/ws-server.tsnew file mode 100644index 0000000000..f565e3702a--- /dev/null+++ b/companion/src/e2e/ws-server.ts@@ -0,0 +1,199 @@+// The server half of RFC 6455, enough for /v1/e2e: one unfragmented message per frame, masked client frames,+// binary, text, ping, pong and close. No dependency: the sidecar builds and runs alone.+import { createHash } from "node:crypto";+import type { IncomingMessage } from "node:http";+import type { Duplex } from "node:stream";++const ACCEPT_GUID = "258EAFA5-E914-47DA-95CA-C5AB0DC85B11";+const OP = { continuation: 0x0, text: 0x1, binary: 0x2, close: 0x8, ping: 0x9, pong: 0xa } as const;+const CLOSE_WAIT_MS = 1_000;+/** RFC 6455 close codes this server sends on its own. */+export const WS_CLOSE = { protocol: 1002, unsupported: 1003, tooBig: 1009 } as const;++export interface WsHandlers {+ message(data: Buffer, binary: boolean): void;+ close(code: number): void;+}++export interface WsConnection {+ send(data: Uint8Array): void;+ close(code: number, reason?: string): void;+ readonly bufferedAmount: number;+ /** Runs once the kernel has taken what was buffered. */+ onceDrained(listener: () => void): void;+ ping(data?: Uint8Array): void;+}++export interface UpgradeOptions {+ /** Required subprotocol; null accepts a connection that asks for none. */+ protocol: string | null;+ maxPayload: number;+}++const refuse = (socket: Duplex, status: string): null => {+ socket.end(`HTTP/1.1 ${status}\r\nConnection: close\r\nContent-Length: 0\r\n\r\n`);+ return null;+};++function header(req: IncomingMessage, name: string): string {+ const value = req.headers[name];+ return Array.isArray(value) ? value.join(",") : value ?? "";+}++/** Null when refused; the socket is already answered. A request with an `Origin` header is a browser and is+ * refused before anything else, as on every other sidecar listener. */+export function acceptWebSocket(+ req: IncomingMessage,+ socket: Duplex,+ head: Buffer,+ options: UpgradeOptions,+ handlers: (connection: WsConnection) => WsHandlers,+): WsConnection | null {+ if (req.headers.origin !== undefined) return refuse(socket, "403 Forbidden");+ const key = header(req, "sec-websocket-key");+ const upgrade = header(req, "upgrade").toLowerCase();+ const connectionTokens = header(req, "connection").toLowerCase().split(",").map((token) => token.trim());+ if (req.method !== "GET" || upgrade !== "websocket" || !connectionTokens.includes("upgrade")) return refuse(socket, "400 Bad Request");+ if (header(req, "sec-websocket-version") !== "13") return refuse(socket, "426 Upgrade Required\r\nSec-WebSocket-Version: 13");+ if (!/^[A-Za-z0-9+/]{22}==$/.test(key)) return refuse(socket, "400 Bad Request");+ const offered = header(req, "sec-websocket-protocol").split(",").map((token) => token.trim()).filter(Boolean);+ if (options.protocol !== null && !offered.includes(options.protocol)) return refuse(socket, "400 Bad Request");+ const accept = createHash("sha1").update(key + ACCEPT_GUID).digest("base64");+ socket.write(+ "HTTP/1.1 101 Switching Protocols\r\nUpgrade: websocket\r\nConnection: Upgrade\r\n" ++ `Sec-WebSocket-Accept: ${accept}\r\n` ++ (options.protocol !== null ? `Sec-WebSocket-Protocol: ${options.protocol}\r\n` : "") ++ "\r\n",+ );+ return serveFrames(socket, head, options.maxPayload, handlers);+}++function frame(opcode: number, payload: Uint8Array): Buffer {+ const length = payload.length;+ const head = length < 126 ? Buffer.alloc(2) : length < 65_536 ? Buffer.alloc(4) : Buffer.alloc(10);+ head[0] = 0x80 | opcode;+ if (length < 126) head[1] = length;+ else if (length < 65_536) {+ head[1] = 126;+ head.writeUInt16BE(length, 2);+ } else {+ head[1] = 127;+ head.writeBigUInt64BE(BigInt(length), 2);+ }+ return Buffer.concat([head, payload]);+}++function closePayload(code: number, reason = ""): Buffer {+ const out = Buffer.alloc(2 + Buffer.byteLength(reason));+ out.writeUInt16BE(code, 0);+ out.write(reason, 2);+ return out.subarray(0, Math.min(out.length, 125));+}++function serveFrames(socket: Duplex, head: Buffer, maxPayload: number, handlers: (connection: WsConnection) => WsHandlers): WsConnection {+ let buffered: Buffer = head.length > 0 ? Buffer.from(head) : Buffer.alloc(0);+ let closing = false;+ let closed = false;+ let closeTimer: ReturnType<typeof setTimeout> | null = null;+ let reported = false;++ const finish = (code: number) => {+ if (closeTimer) clearTimeout(closeTimer);+ closed = true;+ socket.destroy();+ if (!reported) {+ reported = true;+ events.close(code);+ }+ };++ const connection: WsConnection = {+ send(data) {+ if (!closing && !closed) socket.write(frame(OP.binary, data));+ },+ close(code, reason) {+ if (closing || closed) return;+ closing = true;+ socket.write(frame(OP.close, closePayload(code, reason)));+ closeTimer = setTimeout(() => finish(code), CLOSE_WAIT_MS);+ closeTimer.unref?.();+ if (!reported) {+ reported = true;+ events.close(code);+ }+ },+ get bufferedAmount() {+ return socket.writableLength;+ },+ onceDrained(listener) {+ if (socket.writableLength === 0 || closed) queueMicrotask(listener);+ else socket.once("drain", listener);+ },+ ping(data = Buffer.alloc(0)) {+ if (!closing && !closed) socket.write(frame(OP.ping, data));+ },+ };+ const events = handlers(connection);++ const fail = (code: number) => {+ connection.close(code);+ };++ const parse = () => {+ while (!closed) {+ if (buffered.length < 2) return;+ const first = buffered[0];+ const second = buffered[1];+ const fin = (first & 0x80) !== 0;+ const opcode = first & 0x0f;+ if ((first & 0x70) !== 0) return fail(WS_CLOSE.protocol);+ if ((second & 0x80) === 0) return fail(WS_CLOSE.protocol);+ let length = second & 0x7f;+ let offset = 2;+ if (length === 126) {+ if (buffered.length < 4) return;+ length = buffered.readUInt16BE(2);+ offset = 4;+ } else if (length === 127) {+ if (buffered.length < 10) return;+ const big = buffered.readBigUInt64BE(2);+ if (big > BigInt(maxPayload)) return fail(WS_CLOSE.tooBig);+ length = Number(big);+ offset = 10;+ }+ const control = opcode >= 0x8;+ if (control && (length > 125 || !fin)) return fail(WS_CLOSE.protocol);+ if (!fin || opcode === OP.continuation) return fail(WS_CLOSE.unsupported);+ if (length > maxPayload) return fail(WS_CLOSE.tooBig);+ if (buffered.length < offset + 4 + length) return;+ const mask = buffered.subarray(offset, offset + 4);+ const payload = Buffer.from(buffered.subarray(offset + 4, offset + 4 + length));+ for (let index = 0; index < payload.length; index += 1) payload[index] ^= mask[index & 3];+ buffered = buffered.subarray(offset + 4 + length);+ if (opcode === OP.binary || opcode === OP.text) {+ if (!closing) events.message(payload, opcode === OP.binary);+ } else if (opcode === OP.ping) {+ if (!closing) socket.write(frame(OP.pong, payload));+ } else if (opcode === OP.close) {+ const code = payload.length >= 2 ? payload.readUInt16BE(0) : 1005;+ if (!closing) {+ closing = true;+ socket.write(frame(OP.close, payload.subarray(0, 2)));+ }+ socket.end();+ return finish(code);+ } else if (opcode !== OP.pong) {+ return fail(WS_CLOSE.protocol);+ }+ }+ };++ socket.on("data", (chunk: Buffer) => {+ buffered = buffered.length ? Buffer.concat([buffered, chunk]) : chunk;+ parse();+ });+ socket.on("error", () => finish(1006));+ socket.on("close", () => finish(1006));+ queueMicrotask(parse);+ return connection;+}diff --git a/companion/test/e2e/interop.test.ts b/companion/test/e2e/interop.test.tsnew file mode 100644index 0000000000..dc24d5680a--- /dev/null+++ b/companion/test/e2e/interop.test.ts@@ -0,0 +1,167 @@+import { spawn, type ChildProcess } from "node:child_process";+import { createHash, randomBytes } from "node:crypto";+import { request, type IncomingMessage } from "node:http";+import { fileURLToPath } from "node:url";+import type { Duplex } from "node:stream";+import { afterAll, beforeAll, describe, expect, it } from "vitest";++import { credentialHash, fromB64u, keyId, psk } from "../../src/e2e/credentials.ts";+import { NoiseError, TRANSPORT_DIRECT, TRANSPORT_RELAY, type TransportByte } from "../../src/e2e/noise.ts";+import { dial } from "../../src/e2e/phone.ts";+import { SessionClosed, type E2ESession } from "../../src/e2e/session.ts";++const SERVER = fileURLToPath(new URL("../../src/e2e/interop-server.ts", import.meta.url));++interface Ready {+ direct: string;+ relayTransport: string;+ wrongKey: string;+ k: string;+ deviceToken: string;+ pairingToken: string;+}++let child: ChildProcess;+let ready: Ready;++beforeAll(async () => {+ child = spawn(process.execPath, [SERVER, "--port", "0", "--ping-interval-ms", "200"], { stdio: ["pipe", "pipe", "ignore"] });+ ready = await new Promise<Ready>((resolve, reject) => {+ let out = "";+ child.stdout!.on("data", (chunk: Buffer) => {+ out += chunk.toString();+ const line = out.split("\n").find((candidate) => candidate.startsWith("{"));+ if (line && out.includes("\n")) resolve(JSON.parse(line) as Ready);+ });+ child.once("exit", (code) => reject(new Error(`interop server exited ${code}`)));+ });+});++afterAll(() => {+ child?.kill("SIGTERM");+});++const pskFor = (token: string) => psk(credentialHash(token), keyId(fromB64u(ready.k)!));++function connect(url = ready.direct, token = ready.deviceToken, transportByte: TransportByte = TRANSPORT_DIRECT) {+ return dial({ url, transportByte, remoteStatic: fromB64u(ready.k)!, psk: pskFor(token), app: "test/1", pingIntervalMs: 200, pingTimeoutMs: 1_000 });+}++interface Reply {+ status: number;+ headers: IncomingMessage["headers"];+ body: Buffer;+}++function http(session: E2ESession<never>, method: string, path: string, body?: Buffer, headers: Record<string, string> = {}): Promise<Reply> {+ return new Promise((resolve, reject) => {+ const req = request(+ { method, path, host: "companion", headers: { ...headers, ...(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 pattern = (start: number, length: number) => Buffer.from(Array.from({ length }, (_, index) => (start + index) % 251));++describe("a session with the interop server", () => {+ it("carries requests on several streams at once", async () => {+ const session = await connect();+ const health = await http(session, "GET", "/api/health");+ expect(health.status).toBe(200);+ expect(JSON.parse(health.body.toString())).toEqual({ ok: true });+ const replies = await Promise.all([1, 2, 3].map(() => http(session, "GET", "/bytes?n=1000000")));+ for (const reply of replies) expect(reply.body.equals(pattern(0, 1_000_000))).toBe(true);+ session.shutdown();+ });++ it("streams a 4 MiB event and keeps the session alive through idle pings", async () => {+ const session = await connect();+ const reply = await http(session, "GET", "/sse?events=1&size=4194304");+ expect(reply.body.length).toBeGreaterThan(4 * 1024 * 1024);+ expect(reply.body.toString("latin1").endsWith("event: end\ndata: {}\n\n")).toBe(true);+ await new Promise((resolve) => setTimeout(resolve, 700));+ expect(session.state).toBe("open");+ expect((await http(session, "GET", "/api/health")).status).toBe(200);+ session.shutdown();+ });++ it("uploads 25 MiB intact", async () => {+ const session = await connect();+ const body = randomBytes(25 * 1024 * 1024);+ const reply = await http(session, "POST", "/upload", body);+ expect(JSON.parse(reply.body.toString())).toEqual({ bytes: body.length, sha256: createHash("sha256").update(body).digest("hex") });+ session.shutdown();+ }, 60_000);++ it("honours Range", async () => {+ const session = await connect();+ const reply = await http(session, "GET", "/bytes?n=1000", undefined, { Range: "bytes=10-19" });+ expect(reply.status).toBe(206);+ expect(reply.headers["content-range"]).toBe("bytes 10-19/1000");+ expect(reply.body.equals(pattern(10, 10))).toBe(true);+ session.shutdown();+ });++ it("resets one stream mid-response and keeps the rest of the session", async () => {+ const session = await connect();+ await new Promise<void>((resolve) => {+ const req = request({ path: "/hang", host: "companion", createConnection: () => session.openStream() }, (res) => {+ res.once("data", () => {+ req.destroy();+ resolve();+ });+ });+ req.on("error", () => {});+ req.end();+ });+ await new Promise((resolve) => setTimeout(resolve, 50));+ expect(session.activeStreams).toBe(0);+ expect((await http(session, "GET", "/api/health")).status).toBe(200);+ session.shutdown();+ });++ it("carries a WebSocket upgrade inside a stream", async () => {+ const session = await connect();+ const socket = await new Promise<Duplex>((resolve, reject) => {+ const req = request({+ path: "/ws",+ host: "companion",+ headers: { Connection: "Upgrade", Upgrade: "websocket", "Sec-WebSocket-Version": "13", "Sec-WebSocket-Key": randomBytes(16).toString("base64") },+ createConnection: () => session.openStream(),+ });+ req.on("upgrade", (_res, upgraded: Duplex) => resolve(upgraded));+ req.on("error", reject);+ req.end();+ });+ const mask = randomBytes(4);+ const text = Buffer.from("hello viewer");+ const masked = Buffer.from(text.map((byte, index) => byte ^ mask[index % 4]));+ socket.write(Buffer.concat([Buffer.from([0x82, 0x80 | text.length]), mask, masked]));+ const echoed = await new Promise<Buffer>((resolve) => socket.once("data", (chunk: Buffer) => resolve(chunk)));+ expect(echoed.subarray(2).toString()).toBe("hello viewer");+ socket.destroy();+ session.shutdown();+ });++ it("pairs with the pairing token's psk, and uses the relay prologue when told to", async () => {+ (await connect(ready.direct, ready.pairingToken)).shutdown();+ (await connect(ready.relayTransport, ready.deviceToken, TRANSPORT_RELAY)).shutdown();+ });++ it("is refused with 4001 for an unknown token or the wrong transport", async () => {+ await expect(connect(ready.direct, "omb_not_paired")).rejects.toEqual(new SessionClosed(4001));+ await expect(connect(ready.relayTransport, ready.deviceToken, TRANSPORT_DIRECT)).rejects.toEqual(new SessionClosed(4001));+ });++ it("hard-stops when the computer holds a different key", async () => {+ await expect(connect(ready.wrongKey)).rejects.toBeInstanceOf(NoiseError);+ });+});diff --git a/companion/test/e2e/vectors.test.ts b/companion/test/e2e/vectors.test.tsindex 75a6a4b73c..9009f33f83 100644--- a/companion/test/e2e/vectors.test.ts+++ b/companion/test/e2e/vectors.test.ts@@ -1,4 +1,4 @@-import { createCipheriv, createECDH, createHash, createHmac, hkdfSync } from "node:crypto";+import { createCipheriv, createECDH, createHash, createHmac } from "node:crypto";import { readFileSync } from "node:fs";import { describe, expect, it } from "vitest";@@ -97,13 +97,16 @@ describe("V1 derivations", () => {});});-/** Every step written out from the spec text, with RFC 5869 HKDF (the same construction as Noise's) and no- * shared code, so the reference cannot agree with itself by accident. */+/** Every step written out from the spec text, with HKDF as Noise defines it (HMAC chains) rather than the+ * library HKDF the reference uses, and no shared code, so the reference cannot agree with itself by accident. */function straightLine(transport: number, pskBytes: Buffer) {const hash = (...parts: Uint8Array[]) => sha256(Buffer.concat(parts));+ const hmac = (key: Uint8Array, data: Uint8Array) => createHmac("sha256", key).update(data).digest();const hkdf = (ck: Buffer, ikm: Uint8Array, n: number) => {- const out = Buffer.from(hkdfSync("sha256", ikm, ck, Buffer.alloc(0), 32 * n));- return Array.from({ length: n }, (_, index) => out.subarray(index * 32, index * 32 + 32));+ const temp = hmac(ck, ikm);+ const out: Buffer[] = [];+ for (let index = 1; index <= n; index += 1) out.push(hmac(temp, Buffer.concat([out[index - 2] ?? Buffer.alloc(0), Buffer.from([index])])));+ return out;};const seal = (key: Buffer, ad: Buffer, plaintext: Buffer) => {const cipher = createCipheriv("aes-256-gcm", key, Buffer.alloc(12), { authTagLength: 16 });@@ -115,8 +118,8 @@ function straightLine(transport: number, pskBytes: Buffer) {curve.setPrivateKey(priv);return curve.computeSecret(pub);};- let h = Buffer.concat([Buffer.from("Noise_NKpsk0_P256_AESGCM_SHA256"), Buffer.alloc(1)]);- let ck = h;+ let h: Buffer = Buffer.concat([Buffer.from("Noise_NKpsk0_P256_AESGCM_SHA256"), Buffer.alloc(1)]);+ let ck: Buffer = h;let k: Buffer;h = hash(h, Buffer.from([...Buffer.from("omb-e2e/1"), 0, transport]));h = hash(h, T.publicKey);diff --git a/tsconfig.companion.build.json b/tsconfig.companion.build.jsonindex d128c00467..31bef084de 100644--- a/tsconfig.companion.build.json+++ b/tsconfig.companion.build.json@@ -12,6 +12,7 @@"companion/src"],"exclude": [- "companion/src/e2e/gen-vectors.ts"+ "companion/src/e2e/gen-vectors.ts",+ "companion/src/e2e/interop-server.ts"]}