Open-source Grok Bot alternative with a virtual machine that bots can use
TypeScript ai-agentsclaude-codecodexcomputer-usedockerelectrongrokgrok-botgrok-bot-alternativeself-hostedtypescript
feat(companion): carry the full web server over the desktop's encrypted route (#5665 step 3d-4)
Bugfixer 22ce14c749c78
diff --git a/companion/src/proxy.ts b/companion/src/proxy.tsindex 12b717ffc5..342558b622 100644--- a/companion/src/proxy.ts+++ b/companion/src/proxy.ts@@ -23,6 +23,7 @@ import {} from "./routes.ts";import { createJsonScrubber } from "./json-scrub.ts";import { acceptsGzip, gzipCandidate, sendTunnelJson, varyOnEncoding } from "./tunnel-gzip.ts";+import { forwardWebSession, forwardWebSessionUpgrade, webSessionPeer, type WebSessionTarget } from "./session-route.ts";import { CompanionViewerRelay, requestTarget } from "./viewer-relay.ts";import { createSseScrubber, isJson, scrub } from "./wire.ts";@@ -383,6 +384,8 @@ function harnessControlCheck(options: ProxyOptions) {}export function createProxyHandler(options: ProxyOptions) {+ const webSessionTarget = (req: IncomingMessage): WebSessionTarget =>+ ({ harnessPort: options.harnessPort, headersTimeoutMs: proxyHeadersTimeoutMs(req.url ?? "", options.headersTimeoutMs) });const viewers = new CompanionViewerRelay({ checkControl: harnessControlCheck(options) });const capabilityStreams = new Map<string, Set<() => void>>();/** Each device's open `/api/events` streams, for the events the sidecar itself sends. */@@ -407,6 +410,8 @@ export function createProxyHandler(options: ProxyOptions) {const token = bearerToken(req.headers.authorization);const device = options.authenticate(token);const e2e = e2eContextOf(req.socket);+ const webPeer = webSessionPeer(e2e, req);+ if (webPeer) return forwardWebSession(webSessionTarget(req), webPeer, req, res);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 });@@ -801,6 +806,8 @@ export function createProxyHandler(options: ProxyOptions) {const token = bearerToken(req.headers.authorization);const device = options.authenticate(token);const e2e = e2eContextOf(req.socket);+ const webPeer = webSessionPeer(e2e, req);+ if (webPeer) return forwardWebSessionUpgrade(webSessionTarget(req), webPeer, req, socket, head);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;diff --git a/companion/src/session-route.ts b/companion/src/session-route.tsnew file mode 100644index 0000000000..edd489dc1e--- /dev/null+++ b/companion/src/session-route.ts@@ -0,0 +1,130 @@+// The full web app over the desktop's encrypted connection. A paired device that also holds a session of the web server+// (`omb_sess_…`, issued by the server's own pairing) reaches every route that session may use, not only the phone app's.+// The server decides what the session may do; the companion only carries the request, as a remote one.+import { request as httpRequest, type IncomingMessage, type ServerResponse } from "node:http";+import type { Duplex } from "node:stream";++import { bearerToken } from "./devices.ts";+import type { E2EContext } from "./e2e/registry.ts";++/** What a page sends to sign in with the server's pairing code; the reply is the session token it uses from then on. */+const SERVER_PAIRING = "POST /api/auth/pair";+/** Never forwarded: hop-by-hop headers, and everything that names a client or carries this machine's trust. */+const DROPPED = new Set([+ "host", "origin", "cookie", "connection", "keep-alive", "proxy-authorization", "proxy-connection", "te", "trailer",+ "transfer-encoding", "upgrade",+ "x-forwarded-for", "x-forwarded-proto", "x-forwarded-host", "forwarded", "x-real-ip", "cf-connecting-ip",+ "true-client-ip", "x-client-ip",+]);+const HOST = "companion-relay.invalid";++/** The device whose request goes to the web server as a remote one, or null: the companion's own surface answers it. */+export function webSessionPeer(context: E2EContext | null, req: IncomingMessage): string | null {+ if (context?.peer.kind !== "device") return null;+ const token = bearerToken(req.headers.authorization);+ if (token) return token.startsWith("omb_sess_") ? context.peer.id : null;+ return `${req.method ?? "GET"} ${(req.url ?? "/").split("?")[0]}` === SERVER_PAIRING ? context.peer.id : null;+}++/** Security: the harness trusts a loopback request as the owner, so this one is marked as proxied (the server then needs+ * its session) and keeps nothing the device wrote that names a client, a cookie or the desktop's own credentials. */+export function webSessionHeaders(req: IncomingMessage, deviceId: string, upgrade = false): Record<string, string | string[]> {+ const out: Record<string, string | string[]> = {};+ for (const [name, value] of Object.entries(req.headers)) {+ if (value === undefined || DROPPED.has(name) || name.startsWith("x-openmausbot-")) continue;+ out[name] = value;+ }+ out.host = HOST;+ out["x-forwarded-for"] = `relay-${deviceId.slice(0, 48)}`;+ if (upgrade && req.headers.upgrade) Object.assign(out, { connection: "Upgrade", upgrade: String(req.headers.upgrade) });+ return out;+}++/** `http.request` has no deadline of its own for the headers phase. */+function headersDeadline(upstream: ReturnType<typeof httpRequest>, ms: number) {+ let fired = false;+ const deadline = setTimeout(() => {+ fired = true;+ upstream.destroy(new Error("the harness sent no response headers"));+ }, ms);+ deadline.unref?.();+ return { deadline, timedOut: () => fired };+}++const reply = (res: ServerResponse, status: number, error: string) => {+ const body = JSON.stringify({ error });+ res.writeHead(status, { "content-type": "application/json; charset=utf-8", "content-length": Buffer.byteLength(body) }).end(body);+};++/** Where the harness listens, and how long it may take to answer (the proxy's own deadline for that path). */+export type WebSessionTarget = { harnessPort: number; headersTimeoutMs: number };++export function forwardWebSession(target: WebSessionTarget, deviceId: string, req: IncomingMessage, res: ServerResponse): void {+ const upstream = httpRequest(+ { hostname: "127.0.0.1", port: target.harnessPort, path: req.url, method: req.method, headers: webSessionHeaders(req, deviceId) },+ (harness) => {+ clearTimeout(deadline);+ const { connection: _connection, "keep-alive": _keepAlive, ...headers } = harness.headers;+ res.writeHead(harness.statusCode ?? 502, harness.statusMessage, headers);+ harness.pipe(res);+ },+ );+ const { deadline, timedOut } = headersDeadline(upstream, target.headersTimeoutMs);+ upstream.once("error", () => {+ clearTimeout(deadline);+ if (res.headersSent) res.destroy();+ else if (timedOut()) reply(res, 504, "OpenMausBot did not respond");+ else reply(res, 502, "OpenMausBot is not running on this computer");+ });+ // Also before the reply starts: a device that leaves must not keep a stream open on the server.+ res.once("close", () => upstream.destroy());+ req.pipe(upstream);+}++/** A raw response head; `skip` names headers (lower case) left out. */+function responseHead(status: number, message: string, rawHeaders: string[], skip: ReadonlySet<string> = new Set(), extra = ""): string {+ const lines = [`HTTP/1.1 ${status} ${message}`];+ for (let index = 0; index < rawHeaders.length; index += 2) {+ if (!skip.has(rawHeaders[index].toLowerCase())) lines.push(`${rawHeaders[index]}: ${rawHeaders[index + 1]}`);+ }+ if (extra) lines.push(extra);+ return `${lines.join("\r\n")}\r\n\r\n`;+}+const REFUSED_UPGRADE_SKIP = new Set(["connection", "transfer-encoding", "keep-alive"]);++export function forwardWebSessionUpgrade(target: WebSessionTarget, deviceId: string, req: IncomingMessage, socket: Duplex, head: Buffer): void {+ const upstream = httpRequest({ hostname: "127.0.0.1", port: target.harnessPort, path: req.url, method: req.method, headers: webSessionHeaders(req, deviceId, true) });+ const { deadline, timedOut } = headersDeadline(upstream, target.headersTimeoutMs);+ let answered = false;+ upstream.once("upgrade", (harness, harnessSocket, harnessHead) => {+ clearTimeout(deadline);+ answered = true;+ if (socket.destroyed) return harnessSocket.destroy();+ socket.write(responseHead(harness.statusCode ?? 101, harness.statusMessage ?? "Switching Protocols", harness.rawHeaders));+ if (harnessHead.length) socket.write(harnessHead);+ if (head.length) harnessSocket.write(head);+ harnessSocket.pipe(socket).pipe(harnessSocket);+ const close = () => {+ harnessSocket.destroy();+ socket.destroy();+ };+ harnessSocket.once("close", close);+ socket.once("close", close);+ harnessSocket.once("error", close);+ socket.once("error", close);+ });+ upstream.once("response", (harness) => {+ clearTimeout(deadline);+ answered = true;+ // Refused: the body is read to its end, then the socket closes (no chunked framing is passed on).+ socket.write(responseHead(harness.statusCode ?? 502, harness.statusMessage ?? "", harness.rawHeaders, REFUSED_UPGRADE_SKIP, "connection: close"));+ harness.pipe(socket);+ });+ upstream.once("error", () => {+ clearTimeout(deadline);+ if (!answered && socket.writable) socket.end(responseHead(timedOut() ? 504 : 502, timedOut() ? "Gateway Timeout" : "Bad Gateway", [], undefined, "connection: close"));+ else socket.destroy();+ });+ socket.once("close", () => upstream.destroy());+ upstream.end();+}diff --git a/companion/test/session-route.test.ts b/companion/test/session-route.test.tsnew file mode 100644index 0000000000..51ec99774f--- /dev/null+++ b/companion/test/session-route.test.ts@@ -0,0 +1,179 @@+import { createServer, request, type IncomingHttpHeaders, type Server } from "node:http";+import { once } from "node:events";+import type { Duplex } from "node:stream";+import { afterEach, expect, it } from "vitest";+import { WebSocket, WebSocketServer } from "ws";+import { createE2EOrigin } from "../src/e2e/origin.ts";+import type { E2EContext } from "../src/e2e/registry.ts";+import { createProxyHandler } from "../src/proxy.ts";++const servers: Server[] = [];+const closers: (() => void)[] = [];+async function listen(server: Server): Promise<number> {+ servers.push(server);+ server.listen(0, "127.0.0.1");+ await once(server, "listening");+ const address = server.address();+ if (!address || typeof address === "string") throw new Error("no test port");+ return address.port;+}+afterEach(async () => {+ for (const close of closers.splice(0)) close();+ for (const server of servers.splice(0).reverse()) {+ server.closeAllConnections();+ await new Promise<void>((resolve) => server.close(() => resolve()));+ }+});++const DEVICE: E2EContext = { peer: { kind: "device", id: "web-1" }, route: "relay" };+const PAIRING: E2EContext = { peer: { kind: "pairing", admHash: "adm" }, route: "relay" };++async function closedPort(): Promise<number> {+ const server = createServer();+ server.listen(0, "127.0.0.1");+ await once(server, "listening");+ const { port } = server.address() as { port: number };+ await new Promise<void>((resolve) => server.close(() => resolve()));+ return port;+}++async function rig(harnessPortOverride?: number) {+ const received: { method?: string; url?: string; headers: IncomingHttpHeaders; body: string }[] = [];+ let hungClosed!: () => void;+ const hung = new Promise<void>((resolve) => { hungClosed = resolve; });+ const harness = createServer(async (req, res) => {+ if (req.url === "/api/hang") {+ req.socket.once("close", hungClosed);+ return received.push({ method: req.method, url: req.url, headers: req.headers, body: "" });+ }+ let body = "";+ for await (const chunk of req) body += chunk;+ received.push({ method: req.method, url: req.url, headers: req.headers, body });+ res.writeHead(200, { "content-type": "application/json", "x-from": "server" }).end(JSON.stringify({ ok: req.url }));+ });+ const wss = new WebSocketServer({ noServer: true });+ harness.on("upgrade", (req, socket, head) => {+ received.push({ method: req.method, url: req.url, headers: req.headers, body: "" });+ wss.handleUpgrade(req, socket, head, (ws) => ws.on("message", (data) => ws.send(`echo:${data}`)));+ });+ closers.push(() => wss.close());+ const harnessPort = harnessPortOverride ?? await listen(harness);+ const proxy = createProxyHandler({+ harnessPort, mutationToken: () => "private-relay-secret",+ authenticate: (token) => token === "phone-token" ? { id: "web-1", cloudDesktopAccess: false, browserControlAccess: false } : null,+ redeem: () => ({ error: "not pairing", code: "pairing_code_wrong" }), serverName: () => "Fixture",+ });+ const deviceSockets: Duplex[] = [];+ const origin = createE2EOrigin((req, res) => {+ deviceSockets.push(req.socket);+ proxy(req, res);+ }, (req, socket, head) => proxy.upgrade(req, socket, head));+ closers.push(() => origin.close());+ const lanPort = await listen(createServer((req, res) => proxy(req, res, "lan")));+ return { received, origin, lanPort, hung, deviceSockets };+}++function send(stream: Duplex | null, port: number | null, method: string, path: string, headers: Record<string, string>, body?: string) {+ return new Promise<{ status: number; headers: IncomingHttpHeaders; body: string }>((resolve, reject) => {+ const req = request({+ method, path, headers,+ ...(stream ? { createConnection: () => stream as never } : { host: "127.0.0.1", port: port!, agent: false }),+ }, async (res) => {+ let text = "";+ for await (const chunk of res) text += chunk;+ resolve({ status: res.statusCode ?? 0, headers: res.headers, body: text });+ });+ req.once("error", reject);+ req.end(body);+ });+}++const FORGED = {+ cookie: "omb_session=owner-cookie",+ "x-openmausbot-companion-auth": "forged",+ "x-openmausbot-desktop-owner": "forged-owner",+ "x-forwarded-for": "127.0.0.1",+ "x-real-ip": "127.0.0.1",+ forwarded: "for=127.0.0.1",+};++it("carries a web server session over the encrypted route as a remote request, to any route the server allows", async () => {+ const { received, origin } = await rig();+ const res = await send(await origin.connect(DEVICE), null, "PUT", "/api/config?x=1", {+ authorization: "Bearer omb_sess_abc", "content-type": "application/json", ...FORGED,+ }, "{\"a\":1}");+ expect(res.status).toBe(200);+ expect(res.headers["x-from"]).toBe("server");+ expect(received).toHaveLength(1);+ const [seen] = received;+ expect(seen).toMatchObject({ method: "PUT", url: "/api/config?x=1", body: "{\"a\":1}" });+ expect(seen.headers.authorization).toBe("Bearer omb_sess_abc");+ expect(seen.headers.host).toBe("companion-relay.invalid");+ expect(seen.headers["x-forwarded-for"]).toBe("relay-web-1");+ for (const name of ["cookie", "origin", "x-real-ip", "forwarded", "x-openmausbot-companion-auth", "x-openmausbot-desktop-owner", "x-openmausbot-companion-device"]) {+ expect(seen.headers[name], name).toBeUndefined();+ }+});++it("lets a paired device sign in to the web server with its pairing code", async () => {+ const { received, origin } = await rig();+ const res = await send(await origin.connect(DEVICE), null, "POST", "/api/auth/pair", { "content-type": "application/json" }, "{\"code\":\"123456\"}");+ expect(res.status).toBe(200);+ expect(received[0]).toMatchObject({ url: "/api/auth/pair", body: "{\"code\":\"123456\"}" });+ expect(received[0].headers["x-forwarded-for"]).toBe("relay-web-1");+});++it("keeps the phone app's surface for everyone else", async () => {+ const { received, origin, lanPort } = await rig();+ // Not yet admitted: the pairing peer never reaches the web server.+ expect((await send(await origin.connect(PAIRING), null, "PUT", "/api/config", { authorization: "Bearer omb_sess_abc" })).status).not.toBe(200);+ // Not over the encrypted route: a session token on the LAN listener gets no pass-through.+ expect((await send(null, lanPort, "PUT", "/api/config", { authorization: "Bearer omb_sess_abc" })).status).toBe(401);+ // Other routes and other tokens keep the allowlist.+ expect((await send(await origin.connect(DEVICE), null, "PUT", "/api/config", { authorization: "Bearer phone-token" })).status).toBe(403);+ expect((await send(await origin.connect(DEVICE), null, "POST", "/api/auth/pair", { authorization: "Bearer phone-token" })).status).not.toBe(200);+ expect(received).toHaveLength(0);+ // The phone app's own allowed route still gets the companion's capability, never the session route's marking.+ await send(await origin.connect(DEVICE), null, "POST", "/api/bots/b/read", { authorization: "Bearer phone-token" });+ expect(received).toHaveLength(1);+ expect(received[0].headers["x-openmausbot-companion-auth"]).toBe("private-relay-secret");+ expect(received[0].headers["x-forwarded-for"]).toBeUndefined();+});++it("carries the web server's live socket for a session", async () => {+ const { received, origin } = await rig();+ const stream = await origin.connect(DEVICE);+ const ws = new WebSocket("ws://desktop.invalid/api/events", {+ headers: { authorization: "Bearer omb_sess_abc", cookie: "omb_session=owner-cookie", "x-forwarded-for": "127.0.0.1" },+ createConnection: () => stream as never,+ });+ await once(ws, "open");+ ws.send("hi");+ const [reply] = await once(ws, "message");+ expect(String(reply)).toBe("echo:hi");+ ws.close();+ expect(received[0].headers).toMatchObject({ authorization: "Bearer omb_sess_abc", host: "companion-relay.invalid", "x-forwarded-for": "relay-web-1" });+ expect(received[0].headers.cookie).toBeUndefined();+});++it("closes the server's request when the device leaves before the reply", async () => {+ const { received, origin, hung, deviceSockets } = await rig();+ const stream = await origin.connect(DEVICE);+ const pending = send(stream, null, "GET", "/api/hang", { authorization: "Bearer omb_sess_abc" }).catch(() => null);+ await expect.poll(() => received.length).toBe(1);+ deviceSockets[0].destroy(); // the connection to the device is gone+ await hung;+ await pending;+});++it("says so when OpenMausBot is not running, for requests and live sockets", async () => {+ const { origin } = await rig(await closedPort());+ const res = await send(await origin.connect(DEVICE), null, "GET", "/api/bots", { authorization: "Bearer omb_sess_abc" });+ expect(res.status).toBe(502);+ expect(JSON.parse(res.body)).toEqual({ error: "OpenMausBot is not running on this computer" });+ const stream = await origin.connect(DEVICE);+ const ws = new WebSocket("ws://desktop.invalid/api/events", { headers: { authorization: "Bearer omb_sess_abc" }, createConnection: () => stream as never });+ ws.once("error", () => {});+ const [, refused] = await once(ws, "unexpected-response");+ expect((refused as { statusCode: number }).statusCode).toBe(502);+});diff --git a/server/request-auth.test.ts b/server/request-auth.test.tsindex 69d5d45859..c3b4d66855 100644--- a/server/request-auth.test.ts+++ b/server/request-auth.test.ts@@ -30,6 +30,7 @@ import {sessionCookieName,} from "./request-auth.ts";import { SESSION_TTL_MS, SessionRegistry } from "./sessions.ts";+import { webSessionHeaders } from "../companion/src/session-route.ts";function request(headers: Record<string, string>, method = "GET"): IncomingMessage {// SAFETY: the resolver reads only headers and method; a bare object is the whole contract here@@ -288,6 +289,19 @@ describe("resolveRequestAuth", () => {});afterEach(() => rmSync(dir, { recursive: true, force: true }));+ it("treats a request the companion carries for a web session as remote: only its own session counts", () => {+ // The companion's real headers (companion/src/session-route.ts), however the device dressed the request.+ const carried = (headers: Record<string, string>) =>+ webSessionHeaders(request({ host: "127.0.0.1:8799", ...headers }), "web-1") as Record<string, string>;+ const forged = { "x-forwarded-for": "127.0.0.1", "x-real-ip": "127.0.0.1", cookie: `${cookieName}=stolen`, origin: "http://127.0.0.1:8799" };+ expect(resolve(carried(forged)).auth).toBeNull();+ expect(resolve(carried({ ...forged, authorization: "Bearer omb_sess_wrong" })).auth).toBeNull();+ const { token } = sessions.issue({ label: "web", scopes: ["admin", "client"] });+ expect(resolve(carried({ ...forged, authorization: `Bearer ${token}` })).auth?.kind).toBe("session");+ // From the companion on this machine, the lockout counts this device, never every device as one.+ expect(requestSource({ headers: carried(forged), socket: { remoteAddress: "127.0.0.1" } } as unknown as IncomingMessage)).toBe("relay-web-1");+ });+it("accepts authenticated relay mutations without exposing the desktop owner capability", () => {const headers = {host: "127.0.0.1:8799",