Open-source Grok Bot alternative with a virtual machine that bots can use
TypeScript ai-agentsclaude-codecodexcomputer-usedockerelectrongrokgrok-botgrok-bot-alternativeself-hostedtypescript
Keep an error status whose body isn't JSON; refuse names that resolve to link-local
Bugfixer 256c031050d9e
diff --git a/server/remote-teammates.test.ts b/server/remote-teammates.test.tsindex 4dac0e58c9..cf47f7ae87 100644--- a/server/remote-teammates.test.ts+++ b/server/remote-teammates.test.ts@@ -1,5 +1,6 @@import { mkdtempSync, readFileSync, rmSync, statSync, writeFileSync } from "node:fs";import { createServer, type IncomingMessage, type Server, type ServerResponse } from "node:http";+import type { LookupFunction } from "node:net";import { tmpdir } from "node:os";import { dirname, join } from "node:path";import { afterEach, describe, expect, it } from "vitest";@@ -7,7 +8,7 @@ import { afterEach, describe, expect, it } from "vitest";import { BotApiManager } from "./bot-api.ts";import { createBotApiHost, type BotApiHostDeps } from "./bot-api-host.ts";import { json, readBody } from "./harness/http.ts";-import { checkRemote, readRemote, remoteAddress, RemoteTeammates, sendToRemote, type RemoteTeammate } from "./remote-teammates.ts";+import { checkRemote, linkLocalAddress, linkLocalRefusingLookup, readRemote, remoteAddress, RemoteTeammates, sendToRemote, type RemoteTeammate } from "./remote-teammates.ts";import type { RequestAuth } from "./request-auth.ts";import { createRemoteTeammateRoutes } from "./routes/remote-teammates.ts";import { dispatchRoutes } from "./routes/table.ts";@@ -158,6 +159,41 @@ describe("calling a teammate's Bot API", () => {expect(await checkRemote(far)).toEqual({ ok: false, problem: "bad_answer", status: 404 });});+ it("keeps an error status whose body isn't JSON, so a proxy's 502 or a plain-text 429 can be read again", async () => {+ let next: { status: number; body: string; headers?: Record<string, string> } = { status: 502, body: "<html>Bad Gateway</html>" };+ const base = await listen((_req, res) => { res.writeHead(next.status, { "content-type": "text/html", ...next.headers }); res.end(next.body); });+ const far = teammate(base);+ expect(await readRemote(far, "t1")).toEqual({ ok: false, problem: "failed", status: 502 });+ next = { status: 429, body: "slow down", headers: { "retry-after": "7" } };+ expect(await readRemote(far, "t1")).toEqual({ ok: false, problem: "rate_limited", status: 429, retryAfterSeconds: 7 });+ next = { status: 202, body: "<html>proxy</html>" };+ expect(await readRemote(far, "t1")).toEqual({ ok: false, problem: "bad_answer", status: 202 });+ });++ it("never connects to a name that resolves to a link-local or metadata address", async () => {+ for (const address of ["169.254.169.254", "fe80::1", "fd00:ec2::254", "::ffff:169.254.169.254"]) expect(linkLocalAddress(address)).toBe(true);+ for (const address of ["127.0.0.1", "100.64.1.2", "192.168.1.5", "::1", "not an address"]) expect(linkLocalAddress(address)).toBe(false);+ const lookupWith = (answer: Array<{ address: string; family: number }>) => {+ const resolve = ((_host: string, options: { all?: boolean }, callback: (...args: unknown[]) => void) => {+ if (options.all) callback(null, answer);+ else callback(null, answer[0]!.address, answer[0]!.family);+ }) as unknown as LookupFunction;+ const lookup = linkLocalRefusingLookup(resolve);+ return (all: boolean) => new Promise<{ error: NodeJS.ErrnoException | null; address: unknown }>((done) => {+ lookup("far.example.com", { all }, (error, address) => done({ error, address }));+ });+ };+ const metadata = await lookupWith([{ address: "169.254.169.254", family: 4 }])(false);+ expect(metadata.error).toMatchObject({ code: "ELINKLOCAL", message: "far.example.com resolves to 169.254.169.254, a link-local address, not another server" });+ expect((await lookupWith([{ address: "100.64.1.2", family: 4 }, { address: "fe80::1", family: 6 }])(true)).error).toMatchObject({ code: "ELINKLOCAL" });+ expect(await lookupWith([{ address: "100.64.1.2", family: 4 }])(false)).toEqual({ error: null, address: "100.64.1.2" });+ });++ it("calls a teammate saved by name through the checked lookup", async () => {+ const base = await listen((_req, res) => { res.writeHead(200, { "content-type": "application/json" }); res.end(JSON.stringify({ reply: "hi", thread: "t1" })); });+ expect(await sendToRemote(teammate(base.replace("127.0.0.1", "localhost")), { message: "x", wait: 0 })).toEqual({ ok: true, answer: { reply: "hi", thread: "t1" } });+ });+it("never follows a redirect, so the key reaches only the saved address", async () => {const elsewhere: string[] = [];const other = await listen((req, res) => { elsewhere.push(req.headers.authorization ?? ""); res.end("{}"); });diff --git a/server/remote-teammates.ts b/server/remote-teammates.tsindex cc033342cf..a7d92a611c 100644--- a/server/remote-teammates.ts+++ b/server/remote-teammates.ts@@ -2,8 +2,11 @@// (docs/bot-api.md) with the key its owner made there. The key is kept in this file alone (mode 600): it is never listed,// logged or sent anywhere but the Bot API address it was saved with.import { randomUUID } from "node:crypto";+import { lookup as dnsLookup } from "node:dns";import { mkdirSync, readFileSync } from "node:fs";+import { BlockList, isIP, type LookupFunction } from "node:net";import { dirname, join } from "node:path";+import type { Agent } from "undici";import { z } from "zod";import { allowedServerOrigin } from "../electron/server-address.mjs";@@ -29,6 +32,35 @@ const MAX_BASE_CHARS = 300;/** Link-local hosts (169.254/16, fe80::/10) and the cloud metadata service: never another OpenMausBot server, and a key* must not open a way from this server to them. */const LINK_LOCAL = /^(?:169\.254\.|\[fe[89ab][0-9a-f]:|\[::ffff:a9fe:|\[fd00:ec2::254\]$)/i;+/** The same ranges as addresses, for what a name resolves to when a call connects. */+const LINK_LOCAL_ADDRESSES = new BlockList();+LINK_LOCAL_ADDRESSES.addSubnet("169.254.0.0", 16, "ipv4");+LINK_LOCAL_ADDRESSES.addSubnet("fe80::", 10, "ipv6");+LINK_LOCAL_ADDRESSES.addAddress("fd00:ec2::254", "ipv6");++export function linkLocalAddress(address: string): boolean {+ const family = isIP(address);+ return family !== 0 && LINK_LOCAL_ADDRESSES.check(address, family === 6 ? "ipv6" : "ipv4");+}++/** Resolves a name as the system does, then refuses it when any address it gives is link-local or the metadata service,+ * so a DNS name can't carry a teammate key where a typed address may not go. Runs for every connection a call makes. */+export function linkLocalRefusingLookup(resolve: LookupFunction = dnsLookup as LookupFunction): LookupFunction {+ return (hostname, options, callback) => resolve(hostname, options, (error, address, family) => {+ const found = typeof address === "string" ? [address] : (address ?? []).map((entry) => entry.address);+ const refused = error ? undefined : found.find(linkLocalAddress);+ if (refused === undefined) return (callback as (...args: unknown[]) => void)(error, address, family);+ callback(Object.assign(new Error(`${hostname} resolves to ${refused}, a link-local address, not another server`), { code: "ELINKLOCAL" }), "", 0);+ });+}++let teammateAgent: Agent | undefined;+/** fetch whose every connection goes through {@link linkLocalRefusingLookup}. */+async function teammateFetch(url: string, init: RequestInit): Promise<Response> {+ const { Agent: UndiciAgent, fetch: undiciFetch } = await import("undici");+ teammateAgent ??= new UndiciAgent({ connect: { lookup: linkLocalRefusingLookup() } });+ return undiciFetch(url, { ...init, dispatcher: teammateAgent } as Parameters<typeof undiciFetch>[1]) as unknown as Promise<Response>;+}const recordSchema = z.object({id: z.string().uuid(),@@ -207,13 +239,15 @@ async function callRemote(teammate: RemoteTeammate, query: string, init: Requestlet response: Response;try {// A redirect would carry the key to an address nobody saved.- response = await (options.fetch ?? fetch)(`${botApiEndpoint(teammate.base, teammate.botId)}${query}`, {+ response = await (options.fetch ?? teammateFetch)(`${botApiEndpoint(teammate.base, teammate.botId)}${query}`, {...init, redirect: "error", signal,headers: { ...(init.headers as Record<string, string> | undefined), authorization: `Bearer ${teammate.key}` },});} catch (error) {options.signal?.throwIfAborted();- return { ok: false, problem: "unreachable", detail: timeout.aborted ? "no answer in time" : error instanceof Error ? clip(error.message, DETAIL_CHARS) : undefined };+ // fetch says only "fetch failed"; why it failed (refused, no such name, a link-local address) is its cause.+ const reason = error instanceof Error ? (error.cause instanceof Error ? error.cause.message : error.message) : undefined;+ return { ok: false, problem: "unreachable", detail: timeout.aborted ? "no answer in time" : reason === undefined ? undefined : clip(reason, DETAIL_CHARS) };}let body: unknown;try {@@ -221,7 +255,9 @@ async function callRemote(teammate: RemoteTeammate, query: string, init: Request} catch {options.signal?.throwIfAborted();if (timeout.aborted) return { ok: false, problem: "unreachable", detail: "no answer in time" };- return { ok: false, problem: "bad_answer", status: response.status };+ // Only a 200 or 202 must be the Bot API's JSON. A proxy's 502 page or a plain-text 429 is still that status.+ if (response.status === 200 || response.status === 202) return { ok: false, problem: "bad_answer", status: response.status };+ body = undefined;}if (response.status === 200 || response.status === 202) {const answer = parseAnswer(body, response.status);