Open-source Grok Bot alternative with a virtual machine that bots can use
TypeScript ai-agentsclaude-codecodexcomputer-usedockerelectrongrokgrok-botgrok-bot-alternativeself-hostedtypescript
Add teammates on other servers: saved Bot API keys and a client (#7014 step 1)
Bugfixer 2a70ebd130cad
diff --git a/server/index.ts b/server/index.tsindex 50384d56ba..2061f2088b 100644--- a/server/index.ts+++ b/server/index.ts@@ -640,6 +640,7 @@ import { createDevsReports } from "./host/devs-reports.ts"; import { createSettiimport { createCardRequester, linePersonKey } from "./host/thread-person.ts"; import { selfThreadRefusal } from "./host/self-threads.ts"; import { lookedAfterBy } from "./host/looked-after.ts"; import { createActingPeople, HANDED_PEOPLE_FILE, HandedPeople, type HandedRun, keptPrivate, privateHandBack, withPerson } from "./host/acting-person.ts"; import { createTurnCallSignals } from "./host/turn-call-signals.ts";import { createThreadRoutes } from "./routes/threads.ts";import { createWebhookRoutes } from "./routes/webhooks.ts";+import { createRemoteTeammateRoutes } from "./routes/remote-teammates.ts"; import { RemoteTeammates } from "./remote-teammates.ts";import { withScopeHint } from "./connector-scope-hint.ts"; import { accountsByApp, withAccountHint } from "./connector-account-hint.ts";import { connectorFileDeps, connectorFileScope, prepareConnectorFiles, withMissingFileHint } from "./connector-files.ts";import { createConnectorCards } from "./host/connector-cards.ts";@@ -9385,6 +9386,7 @@ const webhookIngressStatus = () => ({...(webhookIngressError ? { error: webhookIngressError } : {}),});ROUTES.push(createTeamFilesRoutes({ files: teamFilesHost.files, actor: (auth) => auth.kind === "session" && auth.session.email ? { person: personKey(auth.session), admin: auth.scopes.includes("admin") } : null, personName: (person) => teamHost.personName(person), botName: (botId) => store.bot(botId)?.name })); ROUTES.push(createWebhookRoutes({ webhooks, ingress: webhookIngressStatus, visible: (auth) => visibleTo(viewerFor(auth)) }), botApi.routes);+ROUTES.push(createRemoteTeammateRoutes({ teammates: new RemoteTeammates() }));const RUNTIME_KEEP_MS = 30 * 24 * 60 * 60_000;let runtimePrunedAt = 0;diff --git a/server/remote-teammates.test.ts b/server/remote-teammates.test.tsnew file mode 100644index 0000000000..aaf49cafa6--- /dev/null+++ b/server/remote-teammates.test.ts@@ -0,0 +1,271 @@+import { mkdtempSync, readFileSync, rmSync, statSync, writeFileSync } from "node:fs";+import { createServer, type IncomingMessage, type Server, type ServerResponse } from "node:http";+import { tmpdir } from "node:os";+import { dirname, join } from "node:path";+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 type { RequestAuth } from "./request-auth.ts";+import { createRemoteTeammateRoutes } from "./routes/remote-teammates.ts";+import { dispatchRoutes } from "./routes/table.ts";+import type { Message } from "./store.ts";+import { createWebhookIngressHandler } from "./webhook-ingress.ts";+import type { WebhookManager } from "./webhooks.ts";++const KEY = `bak_${"k".repeat(43)}`;+const dirs: string[] = [];+const servers: Server[] = [];+afterEach(async () => {+ for (const server of servers.splice(0)) {+ server.closeAllConnections();+ await new Promise((resolve) => server.close(resolve));+ }+ for (const dir of dirs.splice(0)) rmSync(dir, { recursive: true, force: true });+});++function tempFile(): string {+ const dir = mkdtempSync(join(tmpdir(), "omb-remote-teammates-"));+ dirs.push(dir);+ return join(dir, "remote-teammates.json");+}++async function listen(handler: (req: IncomingMessage, res: ServerResponse) => void): Promise<string> {+ const server = createServer(handler);+ servers.push(server);+ await new Promise<void>((resolve) => server.listen(0, "127.0.0.1", resolve));+ return `http://127.0.0.1:${(server.address() as { port: number }).port}`;+}++function teammate(base: string, key = KEY): RemoteTeammate {+ return { id: "00000000-0000-4000-8000-000000000001", name: "Far", base, botId: "b1", key, createdAt: 1 };+}++describe("remoteAddress", () => {+ it("takes https anywhere and plain http only on a private network", () => {+ expect(remoteAddress("https://maus.example.com/", "b1")).toEqual({ base: "https://maus.example.com", botId: "b1" });+ expect(remoteAddress("http://100.101.2.3:8799", "b1").base).toBe("http://100.101.2.3:8799");+ expect(remoteAddress("http://box.tail1234.ts.net:8799", "b1").base).toBe("http://box.tail1234.ts.net:8799");+ expect(remoteAddress("http://192.168.1.20:8799", "b1").base).toBe("http://192.168.1.20:8799");+ expect(() => remoteAddress("http://maus.example.com", "b1")).toThrow(/open internet/);+ expect(() => remoteAddress("ftp://maus.example.com", "b1")).toThrow(/https/);+ expect(() => remoteAddress("https://me:[email protected]", "b1")).toThrow(/without a sign-in/);+ expect(() => remoteAddress("maus", "b1")).toThrow(/not a server address/);+ });++ it("refuses link-local and cloud metadata hosts, and an address too long to keep", () => {+ expect(() => remoteAddress("http://169.254.169.254", "b1")).toThrow(/link-local/);+ expect(() => remoteAddress("http://2852039166", "b1")).toThrow(/link-local/);+ expect(() => remoteAddress("http://[fe80::1]:8799", "b1")).toThrow(/link-local/);+ expect(() => remoteAddress("http://[fd00:ec2::254]", "b1")).toThrow(/link-local/);+ expect(() => remoteAddress(`https://maus.example.com/${"p".repeat(300)}`, "b1")).toThrow(/too long/);+ });++ it("reads the bot from a pasted Bot API address and keeps a path the server is served under", () => {+ expect(remoteAddress("https://maus.example.com/hooks/api/bots/scout-1/messages")).toEqual({ base: "https://maus.example.com", botId: "scout-1" });+ expect(remoteAddress("https://example.com/omb/hooks/api/bots/b2/messages", "b2")).toEqual({ base: "https://example.com/omb", botId: "b2" });+ expect(() => remoteAddress("https://maus.example.com/hooks/api/bots/b2/messages", "b3")).toThrow(/different bot/);+ expect(() => remoteAddress("https://maus.example.com")).toThrow(/bot's id/);+ });+});++describe("RemoteTeammates", () => {+ it("keeps the key only in its own file and never lists it", () => {+ const file = tempFile();+ const store = new RemoteTeammates({ file, now: () => 5 });+ const added = store.add({ name: " Far ", address: "https://maus.example.com/hooks/api/bots/b1/messages", key: KEY });+ expect(added).toEqual({ id: expect.any(String), name: "Far", base: "https://maus.example.com", botId: "b1", createdAt: 5 });+ expect(JSON.stringify(store.list())).not.toContain(KEY);+ expect(store.get(added.id)?.key).toBe(KEY);+ if (process.platform !== "win32") expect(statSync(file).mode & 0o777).toBe(0o600);+ expect(new RemoteTeammates({ file }).list()).toEqual([added]);+ });++ it("refuses a duplicate, a key of the wrong shape, and removes by id", () => {+ const store = new RemoteTeammates({ file: tempFile() });+ const added = store.add({ name: "Far", address: "https://maus.example.com", botId: "b1", key: KEY });+ expect(() => store.add({ name: "Again", address: "https://maus.example.com/", botId: "b1", key: KEY })).toThrow(/already a teammate/);+ expect(() => store.add({ name: "Bad", address: "https://maus.example.com", botId: "b2", key: "Bearer x\r\nX-Evil: 1" })).toThrow(/bak_/);+ expect(store.remove(added.id)).toBe(true);+ expect(store.remove(added.id)).toBe(false);+ expect(store.list()).toEqual([]);+ });++ it("never overwrites a saved file it could not read", () => {+ const file = tempFile();+ writeFileSync(file, "{not json");+ const store = new RemoteTeammates({ file });+ expect(store.list()).toEqual([]);+ expect(() => store.add({ name: "Far", address: "https://maus.example.com", botId: "b1", key: KEY })).toThrow(/could not be read/);+ expect(readFileSync(file, "utf8")).toBe("{not json");+ });++ it("keeps its list as the file has it when a save fails", () => {+ const dir = dirname(tempFile());+ const store = new RemoteTeammates({ file: join(dir, "blocked", "remote-teammates.json") });+ writeFileSync(join(dir, "blocked"), "a file where the folder should be");+ expect(() => store.add({ name: "Far", address: "https://maus.example.com", botId: "b1", key: KEY })).toThrow();+ expect(store.list()).toEqual([]);+ });+});++describe("calling a teammate's Bot API", () => {+ it("maps each answer the Bot API gives, and refuses answers of any other shape", async () => {+ const seen: Array<{ method?: string; url?: string; auth?: string; body: string }> = [];+ let next: { status: number; body: string; headers?: Record<string, string> } = { status: 200, body: JSON.stringify({ reply: "hi", thread: "t1" }) };+ const base = await listen((req, res) => {+ let body = "";+ req.on("data", (chunk) => { body += chunk; });+ req.on("end", () => {+ seen.push({ method: req.method, url: req.url, auth: req.headers.authorization, body });+ res.writeHead(next.status, { "content-type": "application/json", ...next.headers });+ res.end(next.body);+ });+ });+ const far = teammate(base);+ expect(await sendToRemote(far, { message: "hello", wait: 1 })).toEqual({ ok: true, answer: { reply: "hi", thread: "t1" } });+ expect(seen[0]).toMatchObject({ method: "POST", url: "/hooks/api/bots/b1/messages", auth: `Bearer ${KEY}` });+ expect(JSON.parse(seen[0]!.body)).toEqual({ message: "hello", wait: 1 });++ next = { status: 202, body: JSON.stringify({ thread: "t1", status: "needs_approval" }) };+ expect(await readRemote(far, "t1")).toEqual({ ok: true, answer: { thread: "t1", status: "needs_approval" } });+ expect(seen[1]).toMatchObject({ method: "GET", url: "/hooks/api/bots/b1/messages?thread=t1" });++ next = { status: 429, body: JSON.stringify({ error: "Too many calls" }), headers: { "retry-after": "12" } };+ expect(await sendToRemote(far, { message: "again", thread: "t1" })).toEqual({ ok: false, problem: "rate_limited", status: 429, detail: "Too many calls", retryAfterSeconds: 12 });+ next = { status: 401, body: JSON.stringify({ error: "Invalid key" }) };+ expect(await sendToRemote(far, { message: "x" })).toMatchObject({ ok: false, problem: "wrong_key", status: 401 });+ next = { status: 200, body: "<html>proxy login</html>" };+ expect(await sendToRemote(far, { message: "x" })).toEqual({ ok: false, problem: "bad_answer", status: 200 });+ next = { status: 200, body: JSON.stringify({ reply: "no thread" }) };+ expect(await sendToRemote(far, { message: "x" })).toEqual({ ok: false, problem: "bad_answer", status: 200 });+ next = { status: 200, body: JSON.stringify({ reply: "x".repeat(1_100_000), thread: "t1" }) };+ expect(await sendToRemote(far, { message: "x" })).toEqual({ ok: false, problem: "bad_answer", status: 200 });+ next = { status: 502, body: JSON.stringify({ error: "could not answer" }) };+ expect(await readRemote(far, "t1")).toMatchObject({ ok: false, problem: "failed", status: 502 });+ expect(await readRemote(far, "../etc")).toEqual({ ok: false, problem: "no_thread" });++ next = { status: 404, body: JSON.stringify({ error: "no such thread" }) };+ expect(await checkRemote(far)).toEqual({ ok: true });+ next = { status: 404, body: JSON.stringify({ error: "Not found" }) };+ expect(await checkRemote(far)).toEqual({ ok: false, problem: "bad_answer", status: 404, detail: "Not found" });+ next = { status: 404, body: "<html>no page</html>" };+ expect(await checkRemote(far)).toEqual({ ok: false, problem: "bad_answer", status: 404 });+ });++ 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("{}"); });+ const base = await listen((_req, res) => { res.writeHead(307, { location: `${other}/hooks/api/bots/b1/messages` }); res.end(); });+ expect(await sendToRemote(teammate(base), { message: "x" })).toMatchObject({ ok: false, problem: "unreachable" });+ expect(elsewhere).toEqual([]);+ });++ it("says unreachable when nothing answers", async () => {+ const base = await listen(() => {});+ const closed = servers.pop()!;+ await new Promise((resolve) => closed.close(resolve));+ expect(await checkRemote(teammate(base))).toMatchObject({ ok: false, problem: "unreachable" });+ });+});++type Task = { threadId: string; title: string; busy: boolean; botApi?: true };++/** A real Bot API door on a loopback port, with the slice of the store it reads and writes in memory. */+async function realBotApi(): Promise<{ base: string; key: string; manager: BotApiManager }> {+ const bots = new Map<string, { id: string; name: string; tasks: Task[] }>([["b1", { id: "b1", name: "Scout", tasks: [] }]]);+ const messages = new Map<string, Message[]>();+ let ids = 0;+ const store = {+ bot: (id: string) => bots.get(id),+ taskByThread: (botId: string, threadId: string) => bots.get(botId)?.tasks.find((task) => task.threadId === threadId),+ createTask: (botId: string, title?: string) => {+ const task: Task = { threadId: `t${++ids}`, title: title ?? "New thread", busy: false };+ bots.get(botId)!.tasks.push(task);+ messages.set(task.threadId, []);+ return task;+ },+ patchTask: (botId: string, threadId: string, patch: Partial<Task>) => {+ const task = bots.get(botId)?.tasks.find((candidate) => candidate.threadId === threadId);+ if (task) Object.assign(task, patch);+ return task ?? null;+ },+ appendMessage: (threadId: string, message: Omit<Message, "id" | "at">) => {+ const line = { ...message, id: `m${++ids}`, at: Date.now() } as Message;+ messages.set(threadId, [...(messages.get(threadId) ?? []), line]);+ return line;+ },+ messagesFor: (threadId: string) => messages.get(threadId) ?? [],+ activeLeaf: (threadId: string) => messages.get(threadId)?.at(-1)?.id ?? null,+ setActiveLeaf: (_threadId: string, messageId: string) => messageId,+ onChange: () => () => {},+ } as unknown as BotApiHostDeps["store"];+ const manager = new BotApiManager({ file: join(dirname(tempFile()), "bot-api.json") });+ const host = createBotApiHost({+ store, manager, waitMs: 5_000,+ startTurn: async (_botId, prompt, opts) => {+ store.appendMessage(opts.threadId, { role: "bot", kind: "text", text: `got ${prompt.includes("ping") ? "ping" : "?"}` } as never);+ opts.onSettled({ ok: true, text: "" });+ },+ threadBusy: () => false, canStart: () => true, canConfine: () => true, discard: () => {},+ hooksBaseUrl: () => "https://unused.example.test", manageRefusal: () => null,+ });+ const handle = createWebhookIngressHandler({ authorize: () => false, recordUnauthorized: () => null } as unknown as WebhookManager, undefined, host.door);+ const base = await listen((req, res) => { void handle(req, res); });+ return { base, key: manager.enable("b1").key, manager };+}++describe("against a real Bot API door", () => {+ it("checks the key without starting anything, then sends and gets the reply", async () => {+ const remote = await realBotApi();+ expect(await checkRemote(teammate(remote.base, remote.key))).toEqual({ ok: true });+ expect(await checkRemote(teammate(remote.base))).toMatchObject({ ok: false, problem: "wrong_key", status: 401 });+ expect(remote.manager.status("b1").callCount).toBe(0);+ const sent = await sendToRemote(teammate(remote.base, remote.key), { message: "ping", wait: 5 });+ expect(sent).toEqual({ ok: true, answer: { reply: "got ping", thread: expect.any(String) } });+ remote.manager.disable("b1");+ expect(await checkRemote(teammate(remote.base, remote.key))).toMatchObject({ ok: false, problem: "refused", status: 403 });+ });+});++describe("/api/remote-teammates", () => {+ async function app() {+ const teammates = new RemoteTeammates({ file: tempFile() });+ const remote = await realBotApi();+ const routes = [createRemoteTeammateRoutes({ teammates })];+ const base = await listen(async (req, res) => {+ const url = new URL(req.url ?? "/", "http://localhost");+ const auth = { kind: "loopback", scopes: ["admin", "client"] } as RequestAuth;+ if (!await dispatchRoutes(routes, { req, res, url, path: url.pathname, method: req.method ?? "GET", auth, json, readBody })) json(res, 404, { from: "no route" });+ });+ const call = async (method: string, path: string, body?: unknown): Promise<[number, any]> => {+ const response = await fetch(base + path, { method, ...(body === undefined ? {} : { body: JSON.stringify(body), headers: { "content-type": "application/json" } }) });+ return [response.status, await response.json()];+ };+ return { call, remote };+ }++ it("adds, lists without the key, checks and removes a teammate", async () => {+ const { call, remote } = await app();+ const [status, added] = await call("POST", "/api/remote-teammates", { name: "Far", address: `${remote.base}/hooks/api/bots/b1/messages`, key: remote.key });+ expect(status).toBe(201);+ expect(added.teammate).toMatchObject({ name: "Far", base: remote.base, botId: "b1" });+ const [, listed] = await call("GET", "/api/remote-teammates");+ expect(listed.teammates).toEqual([added.teammate]);+ expect(JSON.stringify(listed)).not.toContain(remote.key);+ expect(await call("POST", `/api/remote-teammates/${added.teammate.id}/check`)).toEqual([200, { ok: true }]);+ expect(await call("DELETE", `/api/remote-teammates/${added.teammate.id}`)).toEqual([200, { removed: true }]);+ expect(await call("DELETE", `/api/remote-teammates/${added.teammate.id}`)).toEqual([404, { error: "no such teammate" }]);+ expect((await call("GET", "/api/remote-teammates"))[1]).toEqual({ teammates: [] });+ });++ it("answers a bad teammate with 400 and leaves other paths to the next route", async () => {+ const { call } = await app();+ const [status, body] = await call("POST", "/api/remote-teammates", { name: "Far", address: "http://maus.example.com", botId: "b1", key: KEY });+ expect(status).toBe(400);+ expect(body.error).toMatch(/open internet/);+ expect(await call("GET", "/api/remote-teammates-other")).toEqual([404, { from: "no route" }]);+ });+});diff --git a/server/remote-teammates.ts b/server/remote-teammates.tsnew file mode 100644index 0000000000..e543d91324--- /dev/null+++ b/server/remote-teammates.ts@@ -0,0 +1,270 @@+// Teammates on other servers: a bot that another OpenMausBot server runs, reached through that server's Bot API+// (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 { mkdirSync, readFileSync } from "node:fs";+import { dirname, join } from "node:path";+import { z } from "zod";++import { allowedServerOrigin } from "../electron/server-address.mjs";+import { botApiEndpoint, type BotApiReply } from "../shared/bot-api.ts";+import { writeFileAtomic } from "./atomic.ts";+import { DATA_DIR } from "./config.ts";+import { clip } from "./host/text-clip.ts";+import { parseJson } from "./schema.ts";++export const MAX_REMOTE_TEAMMATES = 50;+/** The Bot API's wait is at most 300 s; past that plus this margin the other server isn't answering. */+const CALL_MARGIN_MS = 15_000;+const CHECK_TIMEOUT_MS = 15_000;+const MAX_ANSWER_BYTES = 1_000_000;+const DETAIL_CHARS = 300;++const BOT_ID = /^[\w-]{1,128}$/;+const THREAD_ID = /^[\w-]{1,128}$/;+/** The shape of a key the Bot API card makes; anything else would only be refused by the other server. */+const KEY = /^bak_[\w-]{16,200}$/;+const ENDPOINT_PATH = /^(.*?)\/hooks\/api\/bots\/([^/]+)\/messages\/?$/;+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;++const recordSchema = z.object({+ id: z.string().uuid(),+ name: z.string().min(1).max(80),+ /** Where the other server's `/hooks` receiver lives: an origin, with a path only if that server is served under one. */+ base: z.string().min(1).max(MAX_BASE_CHARS),+ botId: z.string().regex(BOT_ID),+ key: z.string().regex(KEY),+ createdAt: z.number().finite().nonnegative(),+});+const fileSchema = z.object({ version: z.literal(1), teammates: z.array(recordSchema) });++export type RemoteTeammate = z.output<typeof recordSchema>;+/** What the app may see: never the key. */+export type RemoteTeammateView = Omit<RemoteTeammate, "key">;++export const remoteTeammateInputSchema = z.object({+ name: z.string().trim().min(1).max(80),+ /** The other server's address, or the whole Bot API address its card shows. */+ address: z.string().trim().min(1).max(500),+ /** May be left out when the address is the Bot API address, which names the bot. */+ botId: z.string().trim().regex(BOT_ID).optional(),+ key: z.string().trim().regex(KEY, "paste the key the other server's Bot API card showed (it starts with bak_)"),+}).strict();++export class RemoteTeammateError extends Error {+ readonly status: number;+ constructor(message: string, status: number) {+ super(message);+ this.status = status;+ }+}++/** The base and bot a typed address names. https anywhere; plain http only on this computer or a private network+ * (a LAN address, Tailscale's 100.x or `*.ts.net`, `*.local`), as for the command line's --url. */+export function remoteAddress(address: string, botId?: string): { base: string; botId: string } {+ let url: URL;+ try {+ url = new URL(address);+ } catch {+ throw new RemoteTeammateError("that is not a server address; give it like https://maus.example.com", 400);+ }+ if (url.username || url.password || url.search || url.hash) throw new RemoteTeammateError("give the server's address without a sign-in, ? or #", 400);+ if (!allowedServerOrigin(url.origin)) {+ throw new RemoteTeammateError(url.protocol === "http:" ? `http://${url.host} is on the open internet and plain http isn't encrypted; use its https:// address` : "the address must start with https:// (or http:// on a private network)", 400);+ }+ if (LINK_LOCAL.test(url.hostname)) throw new RemoteTeammateError(`${url.hostname} is a link-local address, not another server`, 400);+ const endpoint = ENDPOINT_PATH.exec(url.pathname);+ const path = (endpoint ? endpoint[1]! : url.pathname).replace(/\/+$/, "");+ // A bot id is only word characters and dashes, so it never needs %-decoding.+ const named = endpoint?.[2];+ if (named !== undefined && !BOT_ID.test(named)) throw new RemoteTeammateError("the bot id in that address isn't valid", 400);+ if (named !== undefined && botId !== undefined && named !== botId) throw new RemoteTeammateError("the address names a different bot than the bot id given", 400);+ const bot = botId ?? named;+ if (!bot) throw new RemoteTeammateError("give the other bot's id, or paste the whole Bot API address from its card", 400);+ const base = `${url.origin}${path}`;+ if (base.length > MAX_BASE_CHARS) throw new RemoteTeammateError("that server address is too long", 400);+ return { base, botId: bot };+}++export interface RemoteTeammatesOptions {+ file?: string;+ now?: () => number;+}++export class RemoteTeammates {+ private readonly file: string;+ private readonly now: () => number;+ private teammates: RemoteTeammate[] = [];+ /** Saves are refused while set, so an empty list never overwrites a file that couldn't be read. */+ private unreadable = false;++ constructor(options: RemoteTeammatesOptions = {}) {+ this.file = options.file ?? join(DATA_DIR, "remote-teammates.json");+ this.now = options.now ?? Date.now;+ try {+ const parsed = fileSchema.safeParse(parseJson(readFileSync(this.file, "utf8")));+ if (!parsed.success) throw parsed.error;+ this.teammates = parsed.data.teammates;+ } catch (error) {+ if ((error as NodeJS.ErrnoException).code !== "ENOENT") {+ this.unreadable = true;+ console.error(`remote teammates: ignoring unreadable ${this.file}: ${error instanceof SyntaxError ? "invalid JSON" : error instanceof Error ? error.message : "unable to read"}`);+ }+ }+ }++ list(): RemoteTeammateView[] {+ return this.teammates.map(view);+ }++ /** With its key: for calling it, never for showing. */+ get(id: string): RemoteTeammate | undefined {+ return this.teammates.find((teammate) => teammate.id === id);+ }++ add(input: z.input<typeof remoteTeammateInputSchema>): RemoteTeammateView {+ this.assertWritable();+ const parsed = remoteTeammateInputSchema.safeParse(input);+ if (!parsed.success) throw new RemoteTeammateError(parsed.error.issues[0]?.message ?? "invalid teammate", 400);+ const { base, botId } = remoteAddress(parsed.data.address, parsed.data.botId);+ if (this.teammates.some((teammate) => teammate.base === base && teammate.botId === botId)) throw new RemoteTeammateError("that bot is already a teammate", 409);+ if (this.teammates.length >= MAX_REMOTE_TEAMMATES) throw new RemoteTeammateError(`at most ${MAX_REMOTE_TEAMMATES} teammates on other servers`, 400);+ const record: RemoteTeammate = { id: randomUUID(), name: parsed.data.name, base, botId, key: parsed.data.key, createdAt: this.now() };+ this.save([...this.teammates, record]);+ return view(record);+ }++ remove(id: string): boolean {+ this.assertWritable();+ const rest = this.teammates.filter((teammate) => teammate.id !== id);+ if (rest.length === this.teammates.length) return false;+ this.save(rest);+ return true;+ }++ private assertWritable(): void {+ if (this.unreadable) throw new RemoteTeammateError("The saved teammates on other servers could not be read. Repair remote-teammates.json before changing them.", 503);+ }++ /** Writes `teammates` and only then keeps them, so a failed write leaves the list as the file has it. */+ private save(teammates: RemoteTeammate[]): void {+ mkdirSync(dirname(this.file), { recursive: true });+ writeFileAtomic(this.file, JSON.stringify({ version: 1, teammates }, null, 2), { mode: 0o600 });+ this.teammates = teammates;+ }+}++function view({ key: _key, ...rest }: RemoteTeammate): RemoteTeammateView {+ return rest;+}++/** Why a call to the other server got no answer to use. `status` is its HTTP status when it gave one. */+export type RemoteProblem =+ | "unreachable" | "bad_answer" | "bad_request" | "wrong_key" | "refused" | "no_thread" | "busy" | "rate_limited" | "failed";++export type RemoteResult =+ | { ok: true; answer: BotApiReply }+ | { ok: false; problem: RemoteProblem; status?: number; detail?: string; retryAfterSeconds?: number };++export interface RemoteCallOptions {+ fetch?: typeof fetch;+ signal?: AbortSignal;+}++/** Sends the other bot a message, as any Bot API caller would; `thread` goes on in a thread an earlier answer gave. */+export function sendToRemote(teammate: RemoteTeammate, call: { message: string; thread?: string; wait?: number }, options: RemoteCallOptions = {}): Promise<RemoteResult> {+ const wait = Number.isFinite(call.wait) ? Math.min(300, Math.max(0, call.wait!)) : 50;+ return callRemote(teammate, "", {+ method: "POST",+ headers: { "content-type": "application/json" },+ body: JSON.stringify({ message: call.message, ...(call.thread !== undefined ? { thread: call.thread } : {}), wait }),+ }, wait * 1000 + CALL_MARGIN_MS, options);+}++/** Reads a thread an earlier answer gave: its reply once the other bot is done, or what it is doing now. */+export function readRemote(teammate: RemoteTeammate, thread: string, options: RemoteCallOptions = {}): Promise<RemoteResult> {+ if (!THREAD_ID.test(thread)) return Promise.resolve({ ok: false, problem: "no_thread" });+ return callRemote(teammate, `?thread=${encodeURIComponent(thread)}`, { method: "GET" }, CHECK_TIMEOUT_MS, options);+}++/** Whether the other server takes this key, without starting anything there: a read of a thread that can't exist is+ * answered 404 "no such thread" only after the key was accepted. Any other 404 (a proxy, a path with no Bot API) isn't. */+export async function checkRemote(teammate: RemoteTeammate, options: RemoteCallOptions = {}): Promise<{ ok: true } | Extract<RemoteResult, { ok: false }>> {+ const result = await callRemote(teammate, `?thread=omb-check-${randomUUID()}`, { method: "GET" }, CHECK_TIMEOUT_MS, options);+ if (!result.ok) {+ if (result.problem !== "no_thread") return result;+ return result.detail === "no such thread" ? { ok: true } : { ok: false, problem: "bad_answer", status: 404, ...(result.detail ? { detail: result.detail } : {}) };+ }+ return { ok: false, problem: "bad_answer", status: 200 };+}++async function callRemote(teammate: RemoteTeammate, query: string, init: RequestInit, timeoutMs: number, options: RemoteCallOptions): Promise<RemoteResult> {+ const timeout = AbortSignal.timeout(timeoutMs);+ const signal = options.signal ? AbortSignal.any([options.signal, timeout]) : timeout;+ let 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}`, {+ ...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 };+ }+ let body: unknown;+ try {+ body = JSON.parse(await boundedText(response, signal));+ } 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 };+ }+ if (response.status === 200 || response.status === 202) {+ const answer = parseAnswer(body, response.status);+ return answer ? { ok: true, answer } : { ok: false, problem: "bad_answer", status: response.status };+ }+ const detail = typeof (body as { error?: unknown })?.error === "string" ? clip((body as { error: string }).error, DETAIL_CHARS) : undefined;+ const retryAfter = Number(response.headers.get("retry-after"));+ return {+ ok: false, problem: PROBLEM_BY_STATUS[response.status] ?? (response.status >= 500 ? "failed" : "bad_answer"), status: response.status,+ ...(detail ? { detail } : {}),+ ...(Number.isFinite(retryAfter) && retryAfter > 0 ? { retryAfterSeconds: Math.ceil(retryAfter) } : {}),+ };+}++const PROBLEM_BY_STATUS: Record<number, RemoteProblem> = {+ 400: "bad_request", 401: "wrong_key", 403: "refused", 404: "no_thread", 409: "busy", 413: "bad_request", 415: "bad_request", 429: "rate_limited",+};++/** Only the two shapes docs/bot-api.md promises; a proxy's page or anything else is not an answer. */+function parseAnswer(body: unknown, status: number): BotApiReply | null {+ if (!body || typeof body !== "object") return null;+ const { reply, thread, status: state } = body as Record<string, unknown>;+ if (typeof thread !== "string" || !THREAD_ID.test(thread)) return null;+ if (status === 200) return typeof reply === "string" ? { reply, thread } : null;+ return state === "working" || state === "needs_approval" ? { thread, status: state } : null;+}++async function boundedText(response: Response, signal: AbortSignal): Promise<string> {+ if (!response.body) return "";+ const reader = response.body.getReader();+ const chunks: Uint8Array[] = [];+ let bytes = 0;+ try {+ for (;;) {+ signal.throwIfAborted();+ const { done, value } = await reader.read();+ if (done) break;+ bytes += value.byteLength;+ if (bytes > MAX_ANSWER_BYTES) throw new Error("answer too large");+ chunks.push(value);+ }+ } finally {+ reader.cancel().catch(() => {});+ }+ return Buffer.concat(chunks).toString("utf8");+}diff --git a/server/routes/remote-teammates.ts b/server/routes/remote-teammates.tsnew file mode 100644index 0000000000..76a3d604ae--- /dev/null+++ b/server/routes/remote-teammates.ts@@ -0,0 +1,48 @@+// Teammates on other servers (server/remote-teammates.ts): list, add, check and remove.+//+// Security: none of these paths is in CLIENT_ALLOW (server/request-auth.ts), so only the owner and admins reach them. A+// saved key lets this server call a bot elsewhere, and no answer ever carries it back.+import { checkRemote, RemoteTeammateError, type RemoteCallOptions, type RemoteTeammates } from "../remote-teammates.ts";+import { PASS, type RouteHandler } from "./table.ts";++export interface RemoteTeammateRouteDeps {+ teammates: RemoteTeammates;+ fetch?: RemoteCallOptions["fetch"];+}++const ONE = /^\/api\/remote-teammates\/([0-9a-f-]{36})(\/check)?$/;++export function createRemoteTeammateRoutes(deps: RemoteTeammateRouteDeps): RouteHandler {+ return async ({ req, res, path, method, json, readBody }) => {+ if (path === "/api/remote-teammates") {+ if (method === "GET") return json(res, 200, { teammates: deps.teammates.list() });+ if (method !== "POST") return json(res, 405, { error: "use GET or POST" });+ try {+ return json(res, 201, { teammate: deps.teammates.add(await readBody(req, 16_000)) });+ } catch (error) {+ return refused(res, json, error);+ }+ }+ const match = ONE.exec(path);+ if (!match) return PASS;+ if (match[2]) {+ if (method !== "POST") return json(res, 405, { error: "use POST" });+ const teammate = deps.teammates.get(match[1]!);+ if (!teammate) return json(res, 404, { error: "no such teammate" });+ return json(res, 200, await checkRemote(teammate, { fetch: deps.fetch }));+ }+ if (method !== "DELETE") return json(res, 405, { error: "use DELETE" });+ try {+ return deps.teammates.remove(match[1]!) ? json(res, 200, { removed: true }) : json(res, 404, { error: "no such teammate" });+ } catch (error) {+ return refused(res, json, error);+ }+ };+}++function refused(res: Parameters<RouteHandler>[0]["res"], json: Parameters<RouteHandler>[0]["json"], error: unknown): void {+ if (error instanceof RemoteTeammateError) return json(res, error.status, { error: error.message });+ const status = (error as { status?: unknown })?.status;+ if (typeof status === "number" && status >= 400 && status < 500) return json(res, status, { error: error instanceof Error ? error.message : "bad request" });+ throw error;+}