Open-source Grok Bot alternative with a virtual machine that bots can use
TypeScript ai-agentsclaude-codecodexcomputer-usedockerelectrongrokgrok-botgrok-bot-alternativeself-hostedtypescript
// Archive work is mocked so revocation can be held at a deterministic boundary.
import { randomUUID } from "node:crypto";
import { existsSync, mkdirSync, mkdtempSync, readdirSync, rmSync, utimesSync, writeFileSync } from "node:fs";
import { createServer, request, type IncomingMessage, type Server } from "node:http";
import { tmpdir } from "node:os";
import { join } from "node:path";
import { afterEach, beforeEach, expect, it, vi } from "vitest";
import type { WorkspaceBackupSummary } from "../shared/workspace-backup.ts";
import { resolveRequestAuth } from "./request-auth.ts";
import { SessionRegistry } from "./sessions.ts";
import { WorkspaceBackupMaintenance } from "./workspace-backup-maintenance.ts";
import { userError, userErrorThrown } from "./user-errors.ts";
const archive = vi.hoisted(() => ({ create: vi.fn(), stage: vi.fn(), commit: vi.fn(), remove: vi.fn() }));
vi.mock("./workspace-backup.ts", async (original) => ({
...await original<typeof import("./workspace-backup.ts")>(),
createWorkspaceBackup: archive.create, stageWorkspaceBackup: archive.stage,
commitPendingWorkspaceRestore: archive.commit, removeWorkspaceBackupJob: archive.remove,
}));
import { createWorkspaceBackupRoutes, isWorkspaceBackupSessionControl } from "./workspace-backup-http.ts";
const PASSWORD = "fixture password 123";
let dataDir: string;
let server: Server;
let url: string;
let sessions: SessionRegistry;
let maintenance: WorkspaceBackupMaintenance;
let admin: ReturnType<SessionRegistry["issue"]>;
function fakeArchive() {
const id = randomUUID();
const directory = join(dataDir, ".backups", id);
mkdirSync(directory, { recursive: true, mode: 0o700 });
const path = join(directory, "workspace.ombbackup");
writeFileSync(path, "fixture encrypted bytes", { mode: 0o600 });
const summary: WorkspaceBackupSummary = { format: "openmaus.workspace-backup", version: 1, id, createdAt: "2026-09-11T00:00:00Z", appVersion: "0.1.71", files: 1, directories: 0, bytes: 23, bots: 0, groups: 0, threads: 0, messages: 0, exclusions: [], warnings: [] };
return { id, path, summary };
}
beforeEach(async () => {
vi.resetAllMocks();
dataDir = mkdtempSync(join(tmpdir(), "omb-backup-http-"));
maintenance = new WorkspaceBackupMaintenance();
sessions = new SessionRegistry({ file: join(dataDir, "sessions.json") });
admin = sessions.issue({ label: "Fixture admin", scopes: ["admin", "client"] });
archive.create.mockImplementation(async () => fakeArchive());
archive.stage.mockImplementation(async () => fakeArchive());
archive.commit.mockImplementation((_dataDir: string, id: string) => ({ id, restartRequired: true }));
archive.remove.mockImplementation((_dataDir: string, id: string) => rmSync(join(dataDir, ".backups", id), { recursive: true, force: true }));
await listen();
});
/** Serves the backup routes; `extra` adds options such as a launcher restart. */
async function listen(extra: Partial<Parameters<typeof createWorkspaceBackupRoutes>[0]> = {}) {
const authenticate = (req: IncomingMessage) => resolveRequestAuth(req, { sessions, cookieName: "fixture", streamPath: "/api/events", url: new URL(req.url!, url) });
const routes = createWorkspaceBackupRoutes({
dataDir, appVersion: "0.1.71", restored: {},
readBody: async (req, limit = 1_000_000) => {
const chunks: Buffer[] = [];
let bytes = 0;
for await (const chunk of req.iterator({ destroyOnReturn: false })) {
bytes += chunk.length;
if (bytes > limit) throw Object.assign(new Error("body too large"), { status: 413 });
chunks.push(chunk);
}
return JSON.parse(Buffer.concat(chunks).toString() || "{}");
},
authorized: (req, original) => {
const current = authenticate(req).auth;
return Boolean(current?.scopes.includes("admin") && current.kind === original.kind &&
(current.kind !== "session" || (original.kind === "session" && current.session.id === original.session.id)));
},
status: () => ({ busy: maintenance.active, pendingRestore: maintenance.pendingRestore }),
exclusive: (work, keepLocked) => maintenance.run(work, { idle: () => true, pause: () => {}, resume: () => {}, flush: async () => {} }, keepLocked),
...extra,
});
server = createServer(async (req, res) => {
const path = new URL(req.url!, url).pathname;
const method = req.method!;
const json = (status: number, body: unknown) => { res.writeHead(status, { "content-type": "application/json" }); res.end(JSON.stringify(body)); };
let release: (() => void) | undefined;
try {
const gate = authenticate(req);
if (!gate.auth) return json(gate.status, { error: gate.error });
if (await routes(req, res, path, gate.auth)) return;
if (!isWorkspaceBackupSessionControl(method, path)) release = maintenance.request();
if (method === "GET" && path === "/api/auth/sessions") return json(200, { sessions: sessions.list() });
if (method === "POST" && path === "/api/auth/logout") {
if (gate.auth.kind === "session") sessions.revoke(gate.auth.session.id);
return json(200, { ok: true });
}
if (method === "DELETE" && /^\/api\/auth\/sessions\/[\w-]+$/.test(path)) return json(200, { ok: sessions.revoke(path.split("/").at(-1)!) });
json(404, { error: "Fixture route not found" });
} catch (error) { json((error as { status?: number }).status ?? 500, { error: error instanceof Error ? error.message : String(error) }); }
finally { release?.(); }
});
await new Promise<void>((resolve) => server.listen(0, "127.0.0.1", resolve));
const address = server.address();
if (!address || typeof address === "string") throw new Error("Fixture did not listen");
url = `http://127.0.0.1:${address.port}`;
}
afterEach(async () => {
server?.closeAllConnections();
if (server) await new Promise<void>((resolve) => server.close(() => resolve()));
rmSync(dataDir, { recursive: true, force: true });
});
function post(path: string, body: unknown, token = admin.token) {
return fetch(`${url}${path}`, { method: "POST", headers: { "content-type": "application/json", authorization: `Bearer ${token}` }, body: JSON.stringify(body) });
}
function get(path: string, token = admin.token) {
return fetch(`${url}${path}`, { headers: { authorization: `Bearer ${token}` } });
}
it("finds the original export after a lost response and allows only its own session to download it", async () => {
const path = `/api/workspace-backup/export-jobs/${randomUUID()}`;
let release!: () => void;
let started!: () => void;
const held = new Promise<void>((resolve) => { release = resolve; });
const starting = new Promise<void>((resolve) => { started = resolve; });
const artifact = fakeArchive();
archive.create.mockImplementationOnce(async () => {
started();
await held;
return artifact;
});
const body = JSON.stringify({ password: PASSWORD });
const connection = request(`${url}${path}`, { method: "POST", headers: {
authorization: `Bearer ${admin.token}`, "content-type": "application/json", "content-length": Buffer.byteLength(body),
} });
const closed = new Promise<void>((resolve) => connection.once("close", resolve));
connection.on("error", () => {});
connection.end(body);
const other = sessions.issue({ label: "Another admin session", scopes: ["admin", "client"] });
try {
await starting;
connection.destroy();
await closed;
const retry = await post(path, { password: PASSWORD });
expect(retry.status).toBe(202);
expect(await retry.json()).toEqual({ state: "running" });
expect(await (await get(path)).json()).toEqual({ state: "running" });
expect((await get(path, other.token)).status).toBe(404);
expect((await post(`/api/workspace-backup/export-jobs/${randomUUID()}`, { password: PASSWORD })).status).toBe(409);
expect((await post("/api/workspace-backup/export", { password: PASSWORD })).status).toBe(409);
expect(maintenance.active).toBe(true);
} finally { release(); }
const ready = { state: "ready", id: artifact.id, filename: "OpenMausBot-2026-09-11.ombbackup" };
await expect.poll(async () => (await get(path)).json()).toMatchObject(ready);
expect(await (await post(path, { password: PASSWORD })).json()).toMatchObject(ready);
expect(archive.create).toHaveBeenCalledOnce();
const download = `/api/workspace-backup/download/${artifact.id}`;
expect(await (await get(download)).text()).toBe("fixture encrypted bytes");
expect((await get(download, other.token)).status).toBe(404);
});
it("cleans up a completed asynchronous export if the initiating session was revoked", async () => {
let release!: () => void;
const held = new Promise<void>((resolve) => { release = resolve; });
const artifact = fakeArchive();
archive.create.mockImplementationOnce(async () => { await held; return artifact; });
const path = `/api/workspace-backup/export-jobs/${randomUUID()}`;
try {
expect((await post(path, { password: PASSWORD })).status).toBe(202);
expect((await post("/api/auth/logout", {})).status).toBe(200);
} finally { release(); }
await vi.waitFor(() => expect(archive.remove).toHaveBeenCalledWith(dataDir, artifact.id));
expect(existsSync(artifact.path)).toBe(false);
expect((await get(path)).status).toBe(401);
expect((await get(`/api/workspace-backup/download/${artifact.id}`)).status).toBe(401);
});
it("reports a failed job when polled and accepts a new explicit export", async () => {
const path = `/api/workspace-backup/export-jobs/${randomUUID()}`;
archive.create.mockRejectedValueOnce(new Error("Fixture archive failed"));
expect((await post(path, { password: PASSWORD })).status).toBe(202);
await expect.poll(async () => (await get(path)).json()).toEqual({ state: "failed", error: "Fixture archive failed" });
expect(await (await post(path, { password: PASSWORD })).json()).toEqual({ state: "failed", error: "Fixture archive failed" });
expect(archive.create).toHaveBeenCalledOnce();
const retry = `/api/workspace-backup/export-jobs/${randomUUID()}`;
expect((await post(retry, { password: PASSWORD })).status).toBe(202);
await expect.poll(async () => (await get(retry)).json()).toMatchObject({ state: "ready", expiresInMs: expect.any(Number) });
expect(archive.create).toHaveBeenCalledTimes(2);
});
it("retains each successful async archive for one hour from completion", async () => {
const first = `/api/workspace-backup/export-jobs/${randomUUID()}`;
const artifact = fakeArchive();
archive.create.mockResolvedValueOnce(artifact);
expect((await post(first, { password: PASSWORD })).status).toBe(202);
await expect.poll(async () => (await get(first)).json()).toMatchObject({ state: "ready" });
const { expiresInMs } = await (await get(first)).json() as { expiresInMs: number };
expect(expiresInMs).toBeGreaterThan(59 * 60_000);
expect((await post("/api/workspace-backup/export", { password: PASSWORD })).status).toBe(200);
const download = `/api/workspace-backup/download/${artifact.id}`;
expect((await get(download)).status).toBe(200);
const clock = vi.spyOn(Date, "now").mockReturnValue(Date.now() + expiresInMs);
try {
expect((await get(first)).status).toBe(404);
expect((await get(download)).status).toBe(404);
expect(existsSync(artifact.path)).toBe(false);
} finally { clock.mockRestore(); }
});
it("schedules cleanup for an interrupted export that left a snapshot but no archive", async () => {
server.closeAllConnections();
await new Promise<void>((resolve) => server.close(() => resolve()));
const id = randomUUID();
const directory = join(dataDir, ".backups", id);
mkdirSync(join(directory, "snapshot"), { recursive: true });
const createdAt = new Date(Date.now() - 60 * 60_000 + 5_000);
utimesSync(directory, createdAt, createdAt);
vi.useFakeTimers({ toFake: ["setTimeout", "clearTimeout"] });
try {
await listen();
expect(existsSync(directory)).toBe(true);
await vi.advanceTimersByTimeAsync(5_001);
expect(archive.remove).toHaveBeenCalledWith(dataDir, id);
expect(existsSync(directory)).toBe(false);
} finally { vi.useRealTimers(); }
});
it("carries a fixed backup refusal and its redacted string path to the client", async () => {
const params = { path: "workspaces/ws/project/loop" };
archive.create.mockRejectedValueOnce(userErrorThrown("serverError.backup.recursiveLink", params));
const response = await post("/api/workspace-backup/export", { password: PASSWORD });
expect(response.status).toBe(400);
expect(await response.json()).toEqual(userError("serverError.backup.recursiveLink", params));
});
it.each(["revoke", "logout"])("keeps session controls authenticated and usable during a held export (%s)", async (action) => {
let started!: () => void;
let release!: () => void;
const starting = new Promise<void>((resolve) => { started = resolve; });
const held = new Promise<void>((resolve) => { release = resolve; });
const output = fakeArchive();
archive.create.mockImplementationOnce(async () => { started(); await held; return output; });
const exporting = post("/api/workspace-backup/export", { password: PASSWORD });
try {
await starting;
expect(maintenance.active).toBe(true);
const member = sessions.issue({ label: "Fixture member", scopes: ["client"] });
expect((await fetch(`${url}/api/auth/sessions`, { headers: { authorization: `Bearer ${member.token}` } })).status).toBe(403);
expect((await fetch(`${url}/api/auth/sessions`)).status).toBe(200);
expect((await fetch(`${url}/api/bots`)).status).toBe(503);
const response = action === "logout"
? await post("/api/auth/logout", {})
: await fetch(`${url}/api/auth/sessions/${admin.session.id}`, { method: "DELETE" });
expect(response.status).toBe(200);
} finally { release(); }
expect((await exporting).status).toBe(403);
expect(archive.remove).toHaveBeenCalledWith(dataDir, output.id);
expect(existsSync(join(dataDir, ".backups", output.id))).toBe(false);
expect(maintenance.active).toBe(false);
});
it("does not broaden maintenance exemptions beyond the three exact session routes", () => {
for (const [method, path] of [["GET", "/api/auth/sessions"], ["POST", "/api/auth/logout"], ["DELETE", "/api/auth/sessions/fixture-id"]]) expect(isWorkspaceBackupSessionControl(method, path)).toBe(true);
for (const [method, path] of [["POST", "/api/auth/sessions"], ["GET", "/api/auth/logout"], ["DELETE", "/api/auth/sessions"], ["DELETE", "/api/auth/sessions/id/extra"], ["GET", "/api/auth/sessions/"], ["POST", "/api/auth/pairing"], ["PATCH", "/api/settings"]]) expect(isWorkspaceBackupSessionControl(method, path)).toBe(false);
});
it("keeps a validated stage after rejecting a malformed or oversized upload", async () => {
const uploaded = await fetch(`${url}/api/workspace-backup/upload`, { method: "POST", headers: { authorization: `Bearer ${admin.token}` }, body: "fixture bytes" }).then((response) => response.json()) as { id: string };
const preview = await post("/api/workspace-backup/preview", { id: uploaded.id, password: PASSWORD }).then((response) => response.json()) as { id: string };
for (const length of ["0", String(11 * 1024 ** 3)]) {
const status = await new Promise<number>((resolve, reject) => {
const upload = request(`${url}/api/workspace-backup/upload`, { method: "POST", headers: { authorization: `Bearer ${admin.token}`, "content-length": length }, signal: AbortSignal.timeout(5000) }, (response) => { response.resume(); resolve(response.statusCode!); });
upload.on("error", reject);
upload.end();
});
expect(status).toBe(413);
expect(existsSync(join(dataDir, ".backups", preview.id))).toBe(true);
}
expect((await post("/api/workspace-backup/restore", { id: preview.id, confirmation: "REPLACE" })).status).toBe(200);
expect(archive.commit).toHaveBeenCalledWith(dataDir, preview.id);
});
it("accepts drafts between 1 and 2 MiB and enforces the preference cap in UTF-8 bytes", async () => {
const clientState = { "omb-drafts": "a".repeat(1536 * 1024) };
expect((await post("/api/workspace-backup/export", { password: PASSWORD, clientState })).status).toBe(200);
expect(archive.create.mock.calls[0][1].clientState).toEqual(clientState);
// Fits the request framing allowance but exceeds the preference byte cap; string.length alone would accept it.
const tooLarge = { "omb-drafts": "é".repeat(1024 ** 2) };
const rejected = await post("/api/workspace-backup/export", { password: PASSWORD, clientState: tooLarge });
expect(rejected.status).toBe(413);
expect((await rejected.json() as { error: string }).error).toContain("2 MB backup preference limit");
expect(archive.create).toHaveBeenCalledOnce();
expect(readdirSync(join(dataDir, ".backups"))).toHaveLength(1);
});
async function stagedRestore() {
const uploaded = await fetch(`${url}/api/workspace-backup/upload`, { method: "POST", headers: { authorization: `Bearer ${admin.token}` }, body: "fixture bytes" }).then((response) => response.json()) as { id: string };
return await post("/api/workspace-backup/preview", { id: uploaded.id, password: PASSWORD }).then((response) => response.json()) as { id: string };
}
function status() {
return fetch(`${url}/api/workspace-backup/status`, { headers: { authorization: `Bearer ${admin.token}` } }).then((response) => response.json()) as Promise<Record<string, unknown>>;
}
it("restarts a server its launcher starts again (My Cloud) once a restore commits, after answering", async () => {
server.closeAllConnections();
await new Promise<void>((resolve) => server.close(() => resolve()));
const restart = vi.fn();
await listen({ restart });
expect(await status()).toMatchObject({ restarts: true, pendingRestore: false });
const preview = await stagedRestore();
expect(restart).not.toHaveBeenCalled();
const restored = await post("/api/workspace-backup/restore", { id: preview.id, confirmation: "REPLACE" });
expect(restored.status).toBe(200);
expect(await restored.json()).toMatchObject({ restarting: true, restoreId: preview.id });
await vi.waitFor(() => expect(restart).toHaveBeenCalledTimes(1));
expect(await status()).toMatchObject({ restarts: true, pendingRestore: true });
});
it("leaves the restart to the person where no launcher restarts the server", async () => {
expect(await status()).not.toHaveProperty("restarts");
const preview = await stagedRestore();
const restored = await post("/api/workspace-backup/restore", { id: preview.id, confirmation: "REPLACE" });
expect(restored.status).toBe(200);
expect(await restored.json()).not.toHaveProperty("restarting");
expect(await status()).toMatchObject({ pendingRestore: true });
expect((await post(`/api/workspace-backup/export-jobs/${randomUUID()}`, { password: PASSWORD })).status).toBe(409);
expect(archive.create).not.toHaveBeenCalled();
});