Open-source Grok Bot alternative with a virtual machine that bots can use
TypeScript ai-agentsclaude-codecodexcomputer-usedockerelectrongrokgrok-botgrok-bot-alternativeself-hostedtypescript
fix(relay): free streams of unread replies, relay the env descriptor, check upload size first
Bugfixer 2df1ec9c9fe7d
diff --git a/src/components/team-files/TeamFilesPage.test.ts b/src/components/team-files/TeamFilesPage.test.tsindex 2176793357..3f6c4b486a 100644--- a/src/components/team-files/TeamFilesPage.test.ts+++ b/src/components/team-files/TeamFilesPage.test.ts@@ -15,7 +15,7 @@ class FakeApiError extends Error {vi.mock("@/state/store", () => ({ useStore: () => ({ state: fixture.state, dispatch: fixture.dispatch }) }));vi.mock("@/state/api", () => ({ api: fixture.api, ApiError: FakeApiError }));-const { TeamFilesPage, changedLine, formatSize, refusalText } = await import("./TeamFilesPage");+const { TeamFilesPage, changedLine, formatSize, refusalText, uploadFile } = await import("./TeamFilesPage");const NOW = Date.parse("2026-11-17T12:00:00Z");const GB = 1024 ** 3;@@ -140,4 +140,13 @@ describe("its words", () => {expect(refusalText(new FakeApiError("x", 403, { code: "forbidden" }), limits)).toBe("Only an admin, or whoever uploaded it, can do that.");expect(refusalText(new Error("offline"), limits)).toBe("That didn't work. Try again.");});++ it("refuses a file over the upload limit before sending it, with the server's too-large words", async () => {+ const send = vi.spyOn(globalThis, "fetch");+ const big = new File(["x".repeat(11)], "big.bin");+ const refused = await uploadFile("", big, 10).catch((error: unknown) => error);+ expect(send).not.toHaveBeenCalled();+ expect(refusalText(refused, { uploadMax: 10 * 1024 ** 2, cap: 5 * GB })).toBe("A file may be at most 10 MB.");+ send.mockRestore();+ });});diff --git a/src/components/team-files/TeamFilesPage.tsx b/src/components/team-files/TeamFilesPage.tsxindex 9c4e1b201b..d36bf65682 100644--- a/src/components/team-files/TeamFilesPage.tsx+++ b/src/components/team-files/TeamFilesPage.tsx@@ -56,8 +56,10 @@ export function refusalText(error: unknown, limits: { uploadMax: number; cap: nureturn t((code && REFUSALS[code]) || "teamFiles.error.failed");}-/** One file up, the bytes as the request body. */-async function uploadFile(folder: string, file: File): Promise<void> {+/** One file up, the bytes as the request body. One over `uploadMax` is refused here, as the server would refuse it: over+ * a relay link the whole body is read into the page before it is sent. */+export async function uploadFile(folder: string, file: File, uploadMax: number): Promise<void> {+ if (file.size > uploadMax) throw new ApiError("413", 413, { code: "too_large" satisfies TeamFilesRefusal });const res = await serverFetch(`${BASE}/file?path=${encodeURIComponent(folder)}&name=${encodeURIComponent(file.name)}`, {method: "PUT", body: file, headers: { "content-type": "application/octet-stream" },});@@ -112,7 +114,7 @@ export function TeamFilesPage() {try {for (const file of files) {setUploading(file.name);- await uploadFile(folder, file);+ await uploadFile(folder, file, limits.uploadMax);}} finally {setUploading(null);diff --git a/src/lib/e2e/http.test.ts b/src/lib/e2e/http.test.tsindex 4cba4724d2..052007f3aa 100644--- a/src/lib/e2e/http.test.ts+++ b/src/lib/e2e/http.test.ts@@ -1,6 +1,6 @@import { spawn, type ChildProcess } from "node:child_process";import { fileURLToPath } from "node:url";-import { afterAll, beforeAll, describe, expect, it } from "vitest";+import { afterAll, beforeAll, describe, expect, it, vi } from "vitest";import { fromB64u, utf8 } from "./bytes.ts";import { credentialHash, keyId, psk } from "./credentials.ts";@@ -46,8 +46,10 @@ function fakeStream(reply: (string | Uint8Array)[], { endAfter = true } = {}) {const state = { ended: false, reset: false, written };const parts = reply.map((part) => (typeof part === "string" ? utf8(part) : part));let source!: ReadableStreamDefaultController<Uint8Array>;+ let fin!: () => void;const stream: E2EStream = {id: 1,+ ended: new Promise<void>((resolve) => (fin = resolve)),readable: new ReadableStream<Uint8Array>({start(controller) {source = controller;@@ -75,6 +77,8 @@ function fakeStream(reply: (string | Uint8Array)[], { endAfter = true } = {}) {state,/** Ends the reply now, for a fake made with endAfter false. */finish: () => source.close(),+ /** The computer's FIN arriving, whether or not the reply has been read. */+ fin: () => fin(),sent: () => new TextDecoder().decode(Uint8Array.from(written.flatMap((part) => [...part]))) };}@@ -135,6 +139,14 @@ describe("streamFetch over a real session (interop computer)", () => {await expect(pending).rejects.toThrow("left the page");expect((await fetchOver({ path: "/api/health" })).status).toBe(200);});++ it("frees the stream of every reply nobody reads, so 100 of them do not use up the session's 64", async () => {+ for (let i = 0; i < 100; i++) {+ // Each reply's head is in; its body (a chunked echo) is left unread, as a caller that only checks the status does.+ expect((await fetchOver({ method: "POST", path: "/echo", body: `read ${i}` })).status).toBe(200);+ }+ expect(await (await fetchOver({ method: "POST", path: "/echo", body: "last" })).text()).toBe("last");+ });});describe("streamFetch framing (fake computer)", () => {@@ -148,6 +160,15 @@ describe("streamFetch framing (fake computer)", () => {expect(fake.state.reset).toBe(false);});+ it("ends the request side once the computer's FIN is in, though nobody reads the reply", async () => {+ const fake = fakeStream(["HTTP/1.1 200 OK\r\nContent-Length: 2\r\n\r\nhi"]);+ await streamFetch(fake.open, { method: "POST", path: "/api/bots/b/read", body: "{}" });+ expect(fake.state.ended).toBe(false);+ fake.fin();+ await vi.waitFor(() => expect(fake.state.ended).toBe(true));+ expect(fake.state.reset).toBe(false);+ });+it("decodes chunks split at odd places, with extensions and trailers", async () => {const wire = "HTTP/1.1 200 OK\r\nTransfer-Encoding: chunked\r\n\r\n5;x=1\r\nhello\r\n1\r\n \r\nA\r\n0123456789\r\n0\r\nX-T: 1\r\n\r\n";const parts = wire.match(/[\s\S]{1,3}/g)!;diff --git a/src/lib/e2e/http.ts b/src/lib/e2e/http.tsindex 6948033b64..f1ef8b413d 100644--- a/src/lib/e2e/http.ts+++ b/src/lib/e2e/http.ts@@ -224,6 +224,9 @@ export async function streamFetch(open: () => E2EStream, request: StreamRequest)() => (uploaded = true),() => {},);+ // Once the computer's FIN is in, its reply is whole and the request side can end too: a reply nobody reads to the end+ // (a caller that only checks the status) still frees its stream, as both FINs drop it.+ void Promise.all([sent, stream.ended]).then(() => stream.end(), () => {});try {const received = (async () => {for (;;) {diff --git a/src/lib/e2e/session.ts b/src/lib/e2e/session.tsindex 781c84ab9d..f0a8825b34 100644--- a/src/lib/e2e/session.ts+++ b/src/lib/e2e/session.ts@@ -85,6 +85,8 @@ export interface E2EStream {/** No more writes: FIN after what is already written. */end(): void;reset(): void;+ /** Resolves on the computer's FIN: all it will send is in `readable`, read or not. */+ readonly ended: Promise<void>;}/** Rejects with SessionClosed (the close code) or a NoiseError (a hard stop: the computer could not be verified). */@@ -242,7 +244,9 @@ interface PendingWrite {class Stream implements E2EStream {readonly id: number;readonly readable: ReadableStream<Uint8Array>;+ readonly ended: Promise<void>;readonly #session: PhoneSession;+ #markEnded!: () => void;#controller!: ReadableStreamDefaultController<Uint8Array>;#writes: PendingWrite[] = [];#ending = false;@@ -255,6 +259,7 @@ class Stream implements E2EStream {constructor(session: PhoneSession, id: number) {this.#session = session;this.id = id;+ this.ended = new Promise((resolve) => (this.#markEnded = resolve));this.readable = new ReadableStream<Uint8Array>({start: (controller) => {@@ -304,6 +309,7 @@ class Stream implements E2EStream {if (this.#done) return;this.#remoteEnded = true;this.#controller.close();+ this.#markEnded();this.#forgetIfDone();}diff --git a/src/lib/e2e/websocket.test.ts b/src/lib/e2e/websocket.test.tsindex 43cfb0346a..e64d07cefb 100644--- a/src/lib/e2e/websocket.test.ts+++ b/src/lib/e2e/websocket.test.ts@@ -25,6 +25,7 @@ function fakeComputer() {let source!: ReadableStreamDefaultController<Uint8Array>;const stream: E2EStream = {id: 1,+ ended: new Promise<void>(() => {}),readable: new ReadableStream<Uint8Array>({start(controller) {source = controller;diff --git a/src/lib/relay-server-callers.test.ts b/src/lib/relay-server-callers.test.tsindex 80071eb40b..d9b0139923 100644--- a/src/lib/relay-server-callers.test.ts+++ b/src/lib/relay-server-callers.test.ts@@ -15,17 +15,28 @@ function appFiles(): string[] {.filter((file) => file !== "src/lib/relay-server.ts" && !file.endsWith("-preview.tsx"));}-/** A call to fetch, or fetch handed on as a value (`fetchImpl = fetch`, `run(fetch)`); not `.fetch(` or a `fetch:` key. */-const BARE_FETCH = /(?<![\w$.])fetch\(|[=(,:]\s*fetch\b(?![\w$.(]|\s*:)/;+/** A call to fetch, whitespace or a line break before its `(` too, or fetch handed on as a value (`fetchImpl = fetch`,+ * `run(fetch)`); not `.fetch(` or a `fetch:` key. */+const BARE_FETCH = /(?<![\w$.])fetch\s*\(|[=(,:]\s*fetch\b(?![\w$.(]|\s*[:(])/g;++/** The 1-based lines of `source` with a bare fetch, `//` comments left out. */+function bareFetchLines(source: string): number[] {+ const code = source.split("\n").map((line) => line.replace(/\/\/.*$/, "")).join("\n");+ const lines = [...code.matchAll(BARE_FETCH)].map((match) => code.slice(0, match.index).split("\n").length);+ return [...new Set(lines)];+}describe("app requests to its own server", () => {it("all go through serverFetch, never a bare fetch", () => {- const bare: string[] = [];- for (const file of appFiles()) {- readFileSync(new URL(file, ROOT), "utf8").split("\n").forEach((line, index) => {- if (BARE_FETCH.test(line.replace(/\/\/.*$/, ""))) bare.push(`${file}:${index + 1}`);- });- }+ const bare = appFiles().flatMap((file) => bareFetchLines(readFileSync(new URL(file, ROOT), "utf8")).map((line) => `${file}:${line}`));expect(bare).toEqual([]);});++ it("counts a bare fetch however it is spaced, and nothing that only looks like one", () => {+ expect(bareFetchLines('fetch("/api/bots");')).toEqual([1]);+ expect(bareFetchLines('void fetch ("/api/bots");')).toEqual([1]);+ expect(bareFetchLines('const a = 1;\nawait fetch\n ("/api/bots");')).toEqual([2]);+ expect(bareFetchLines("const run = fetch;\nuse(fetch)")).toEqual([1, 2]);+ expect(bareFetchLines('link.fetch("/api/bots");\nconst x = { fetch: go };\n// fetch("/api/bots")\nserverFetch("/api/bots");')).toEqual([]);+ });});diff --git a/src/lib/relay-server.test.ts b/src/lib/relay-server.test.tsindex 4dd4bd32c4..bda70c739c 100644--- a/src/lib/relay-server.test.ts+++ b/src/lib/relay-server.test.ts@@ -97,6 +97,18 @@ describe("serverFetch", () => {expect(text).toContain("hello");});+ it("sends the environment descriptor through the link too, as it describes the paired server", async () => {+ const plain = vi.fn();+ vi.stubGlobal("fetch", plain);+ const { link, sent } = fakeLink(() => Response.json({ environmentId: "env-1" }));+ setRelayLink(link);++ expect(await (await serverFetch("/.well-known/openmausbot/environment")).json()).toEqual({ environmentId: "env-1" });+ await serverFetch("/.well-known/openmausbot/environmental");+ expect(sent.map(({ path }) => path)).toEqual(["/.well-known/openmausbot/environment"]);+ expect(plain.mock.calls.map(([path]) => path)).toEqual(["/.well-known/openmausbot/environmental"]);+ });+it("forwards the normalized target: unsafe characters encoded, no fragment", async () => {const { link, sent } = fakeLink(() => new Response("{}"));setRelayLink(link);diff --git a/src/lib/relay-server.ts b/src/lib/relay-server.tsindex b923a3c61c..5d0052b35e 100644--- a/src/lib/relay-server.ts+++ b/src/lib/relay-server.ts@@ -32,10 +32,11 @@ export function relayLink(): ServerLink | null {return link;}-const API = /^\/api(?:[/?#]|$)/;+/** The server's own routes: `/api`, and the environment descriptor that says what this server is. */+const API = /^\/(?:api(?:[/?#]|$)|\.well-known\/openmausbot\/environment(?:[?#]|$))/;-/** `path` as a request to this page's own `/api` routes: a root path, or an absolute URL on this page's origin (some- * links are built from `location`); null for anything else. */+/** `path` as a request to this page's own server routes (API): a root path, or an absolute URL on this page's origin+ * (some links are built from `location`); null for anything else. */function ownApiPath(path: string): string | null {if (API.test(path)) return path;const origin = (globalThis as { location?: { origin?: string } }).location?.origin;