Skip to content

Open-source Grok Bot alternative with a virtual machine that bots can use

31.2 KB
Raw Blame
import { spawn, type ChildProcess } from "node:child_process";
import { once } from "node:events";
import { request } from "node:http";
import { mkdirSync, mkdtempSync, writeFileSync } from "node:fs";
import { tmpdir } from "node:os";
import { dirname, join } from "node:path";
import { fileURLToPath } from "node:url";
import { afterAll, beforeAll, describe, expect, it } from "vitest";
import { WebSocket } from "ws";

import { PAIRING_LOCKOUT } from "./sessions.ts";
import { removeTempDir, waitForExit } from "./testing/cleanup.ts";
import { openSse } from "./testing/sse.ts";
import { workerPort } from "./testing/worker-port.ts";

const SERVER_DIR = dirname(fileURLToPath(import.meta.url));
const ROOT = join(SERVER_DIR, "..");
const PORT = workerPort(18800, 10_000);
const WEBHOOK_PORT = workerPort(39000, 10_000);
const BASE = `http://127.0.0.1:${PORT}`;
const REMOTE_HOST = "mini.tail1234.ts.net:8799";
const PUBLIC_URL = "https://mini.tail1234.ts.net";

let home: string;
let child: ChildProcess;
let stderr = "";

/** A non-loopback Host and a distinct forwarded source, so the pairing lockout is exercised only on purpose. */
const remote = (source: string, extra: Record<string, string> = {}) => ({ host: REMOTE_HOST, "x-forwarded-for": source, ...extra });

/** Plain node:http: fetch silently drops a custom Host header. */
function call(
  path: string,
  init: { method?: string; headers?: Record<string, string>; body?: string } = {},
): Promise<{ status: number; body: any; headers: Record<string, string | string[] | undefined> }> {
  return new Promise((resolve, reject) => {
    const req = request(
      { host: "127.0.0.1", port: PORT, path, method: init.method ?? "GET", headers: { "content-type": "application/json", ...init.headers } },
      (res) => {
        let raw = "";
        res.setEncoding("utf8");
        res.on("data", (chunk) => (raw += chunk));
        res.on("end", () => {
          let body: any = {};
          try {
            body = raw ? JSON.parse(raw) : {};
          } catch {
            body = { raw };
          }
          resolve({ status: res.statusCode ?? 0, body, headers: res.headers });
        });
      },
    );
    req.on("error", reject);
    if (init.body) req.write(init.body);
    req.end();
  });
}

/** Holds the body after the server accepted its headers, so a test can revoke the session before the route commits. */
function delayedCall(
  path: string,
  init: { headers: Record<string, string>; body: unknown },
): Promise<{
  finish: () => Promise<{ status: number; body: any }>;
  close: () => void;
}> {
  const raw = JSON.stringify(init.body);
  const req = request(
    {
      host: "127.0.0.1",
      port: PORT,
      path,
      method: "POST",
      headers: {
        "content-type": "application/json",
        "content-length": Buffer.byteLength(raw),
        expect: "100-continue",
        ...init.headers,
      },
    },
  );
  const response = new Promise<{ status: number; body: any }>((resolve, reject) => {
    req.on("error", reject);
    req.on("response", (res) => {
      let data = "";
      res.setEncoding("utf8");
      res.on("data", (chunk) => (data += chunk));
      res.on("error", reject);
      res.on("end", () => {
        try {
          resolve({ status: res.statusCode ?? 0, body: data ? JSON.parse(data) : {} });
        } catch (error) {
          reject(error);
        }
      });
    });
  });
  void response.catch(() => {});
  const accepted = new Promise<void>((resolve) => req.once("continue", resolve));
  req.flushHeaders();
  return accepted.then(() => ({
    finish: () => {
      req.end(raw);
      return response;
    },
    close: () => req.destroy(),
  }));
}

const header = (headers: Record<string, string | string[] | undefined>, name: string): string => {
  const v = headers[name];
  return Array.isArray(v) ? v.join("\n") : (v ?? "");
};

async function refusedFeed(headers: Record<string, string>): Promise<number> {
  const ws = new WebSocket(`${BASE}/api/events`, { headers });
  try {
    const result = await Promise.race([
      once(ws, "unexpected-response").then(([, res]) => { res.resume(); return res.statusCode as number; }),
      once(ws, "open").then(() => { throw new Error("unexpectedly subscribed"); }),
    ]);
    return result;
  } finally { ws.on("error", () => {}); ws.terminate(); }
}
async function pairingCode(scopes?: string[]): Promise<{ code: string; credential: string; url: string | null; inviteUrl: string | null; serverName: string; hint: string | null }> {
  const opened = await call("/api/auth/pairing", { method: "POST", body: JSON.stringify(scopes ? { scopes } : {}) });
  expect(opened.status).toBe(200);
  return opened.body;
}

it("admits only a same-origin paired browser to the event socket", async () => {
  const source = "10.0.0.88";
  const origin = `http://${REMOTE_HOST}`;
  const opened = await pairingCode(["client"]);
  const paired = await call("/api/auth/pair", { method: "POST", headers: remote(source), body: JSON.stringify({ code: opened.code, cookie: true }) });
  expect(paired.status).toBe(200);
  const cookie = header(paired.headers, "set-cookie").split(";")[0]!;
  expect(await refusedFeed(remote(source, { origin }))).toBe(403);
  expect(await refusedFeed({ origin: BASE })).toBe(401);
  expect(await refusedFeed({})).toBe(403);
  expect(await refusedFeed(remote(source, { cookie }))).toBe(403);
  expect(await refusedFeed(remote(source, { cookie, origin: "https://another.example" }))).toBe(403);
  const ws = new WebSocket(`${BASE}/api/events`, { headers: remote(source, { cookie, origin }) });
  try {
    const message = once(ws, "message");
    const ended = once(ws, "close");
    const [first] = await message;
    expect(JSON.parse(first.toString()).frame.kind).toBe("hello");
    ws.send("not a command channel");
    await ended;
  } finally { ws.terminate(); }
});

beforeAll(async () => {
  home = mkdtempSync(join(tmpdir(), "omb-remote-test-"));
  const staticDir = join(home, "static");
  mkdirSync(join(home, ".openmausbot"), { recursive: true });
  mkdirSync(join(staticDir, "assets"), { recursive: true });
  writeFileSync(join(staticDir, "index.html"), "<!doctype html><title>Served UI</title>");
  // Avoid probing whatever agent CLIs the test machine has installed.
  writeFileSync(join(home, ".openmausbot", "config.json"), JSON.stringify({
    instances: { fixture: { driver: "remote-session-test-shadow" } },
    profile: { name: "Security fixture", email: "[email protected]" },
    vps: { sshAlias: "fixture-private-host" },
    vpsServers: [{ name: "Fixture lab", sshAlias: "fixture-private-lab" }],
    browserProfiles: [{ id: "fixture", name: "Fixture browser", partitionId: "fixture-private-partition" }],
  }));
  child = spawn(process.execPath, [join(SERVER_DIR, "index.ts")], {
    cwd: ROOT,
    env: {
      ...(process.env.PATH ? { PATH: process.env.PATH } : {}),
      ...(process.env.SystemRoot ? { SystemRoot: process.env.SystemRoot } : {}),
      HOME: home,
      USERPROFILE: home,
      OMB_PORT: String(PORT),
      OMB_WEBHOOK_PORT: String(WEBHOOK_PORT),
      OMB_STATIC_DIR: staticDir,
      OMB_PUBLIC_URL: `${PUBLIC_URL}/`,
      OMB_APP_VERSION: "9.9.9-test",
      OMB_ENVIRONMENT_LABEL: "cab mini",
      OMB_BROWSER_CONNECTION: join(home, "browser-test-connection.json"),
      // Slow heartbeat: the revocation test must prove the revoke itself ends the stream.
      OMB_SSE_HEARTBEAT_MS: "4000",
    },
    stdio: ["ignore", "pipe", "pipe"],
  });
  child.stderr?.on("data", (chunk) => (stderr += String(chunk)));
  const deadline = Date.now() + 20_000;
  while (Date.now() < deadline) {
    try {
      const res = await fetch(`${BASE}/api/health`);
      if (res.ok) return;
    } catch {
    }
    await new Promise((r) => setTimeout(r, 100));
  }
  throw new Error(`server did not start:\n${stderr}`);
}, 30_000);

afterAll(async () => {
  await waitForExit(child, { signal: "SIGTERM" });
  await removeTempDir(home);
});

describe("before pairing", () => {
  it.each(["//%5B", "//[", "http://["])("rejects malformed request target %s and stays healthy", async (path) => {
    const response = await call(path, { headers: remote("10.0.0.1") });
    expect(response.status).toBe(400);
    expect(response.body).toEqual({ error: "invalid request URL" });
    const health = await call("/api/health");
    expect(health.status).toBe(200);
    expect(health.body).toMatchObject({ app: "openmausbot", pid: child.pid });
    expect(child.exitCode).toBeNull();
  });

  it("describes itself to anyone, but serves nothing else off-machine", async () => {
    const descriptor = await call("/.well-known/openmausbot/environment", { headers: remote("10.0.0.1") });
    expect(descriptor.status).toBe(200);
    expect(descriptor.body.environmentId).toMatch(/^[0-9a-f-]{36}$/);
    expect(descriptor.body.label).toBe("cab mini");
    expect(descriptor.body.version).toBe("9.9.9-test");
    // Exact, so a new pre-pairing field has to be added here on purpose.
    expect(descriptor.body.capabilities).toEqual({
      remoteSessions: true,
      selfUpdate: "operator",
      // How it was installed, so a client's update note offers the command that fits.
      install: expect.any(String),
      emailSignIn: false,
      jobs: true,
      // A server nobody else signs in to can be its owner's bots' home: it takes their move once they pair.
      move: 1,
    });
    const refused = await call("/api/bots", { headers: remote("10.0.0.1") });
    expect(refused.status).toBe(403);
    expect(refused.body.error).toMatch(/pair this device/);
  });

  it("serves the UI shell to a remote browser so it can reach the pair page", async () => {
    const res = await call("/pair", { headers: remote("10.0.0.1") });
    expect(res.status).toBe(200);
    expect(res.body.raw).toContain("Served UI");
  });

  it("keeps the owner's loopback path untouched", async () => {
    expect((await call("/api/bots")).status).toBe(200);
    const me = await call("/api/auth/session");
    expect(me.body).toMatchObject({ kind: "loopback", scopes: ["admin", "client"] });
    const ticket = await call("/api/auth/stream-ticket", { method: "POST" });
    expect(ticket.body.ticket).toBeNull();
  });
});

describe("pairing", () => {
  it("mints a code on the server with a link built from the public address", async () => {
    const opened = await pairingCode();
    expect(opened.code).toMatch(/^[A-Z2-9]{4}-[A-Z2-9]{4}-[A-Z2-9]{4}$/);
    expect(opened.url).toBe(`${PUBLIC_URL}/pair#code=${opened.code}`);
    expect(opened.hint).toBeNull();
    const listed = await call("/api/auth/pairing");
    expect(listed.body.pairings.length).toBeGreaterThanOrEqual(1);
    expect(listed.body.publicUrl).toBe(PUBLIC_URL);
  });

  it("refuses to mint or list codes from a client-only session", async () => {
    const opened = await pairingCode(["client"]);
    const paired = await call("/api/auth/pair", { method: "POST", headers: remote("10.0.0.2"), body: JSON.stringify({ code: opened.code, label: "viewer" }) });
    expect(paired.status).toBe(200);
    const denied = await call("/api/auth/pairing", { method: "POST", headers: remote("10.0.0.2", { authorization: `Bearer ${paired.body.token}` }), body: "{}" });
    expect(denied.status).toBe(403);
    expect(denied.body.error).toContain("lacks the admin scope");
    expect((await call("/api/bots", { headers: remote("10.0.0.2", { authorization: `Bearer ${paired.body.token}` }) })).status).toBe(200);
  });

  it("rechecks an admin session after a slow pairing body before minting a code", async () => {
    const opened = await pairingCode();
    const paired = await call("/api/auth/pair", {
      method: "POST",
      headers: remote("10.0.0.22"),
      body: JSON.stringify({ code: opened.code, label: "revoked admin" }),
    });
    expect(paired.status).toBe(200);
    const held = await delayedCall("/api/auth/pairing", {
      headers: remote("10.0.0.22", { authorization: `Bearer ${paired.body.token}` }),
      body: { label: "must not be minted after revocation", scopes: ["admin", "client"] },
    });
    try {
      const revoked = await call(`/api/auth/sessions/${paired.body.session.id}`, { method: "DELETE" });
      expect(revoked.status).toBe(200);
      expect((await call("/api/auth/session", {
        headers: remote("10.0.0.22", { authorization: `Bearer ${paired.body.token}` }),
      })).status).toBe(401);

      const late = await held.finish();
      expect(late.status).toBe(401);
      expect(late.body.error).toMatch(/session ended/i);
      const remaining = await call("/api/auth/pairing");
      expect(remaining.body.pairings).not.toEqual(expect.arrayContaining([
        expect.objectContaining({ label: "must not be minted after revocation" }),
      ]));
    } finally {
      held.close();
    }
  });

  it("exchanges a code exactly once, with a bearer token for native clients", async () => {
    const opened = await pairingCode();
    const wrong = await call("/api/auth/pair", { method: "POST", headers: remote("10.0.0.3"), body: JSON.stringify({ code: "AAAA-AAAA-AAAA" }) });
    expect(wrong.status).toBe(401);
    expect(wrong.body.error).toMatch(/wrong or has expired/);
    const paired = await call("/api/auth/pair", {
      method: "POST",
      headers: remote("10.0.0.3", { "user-agent": "Mozilla/5.0 (Macintosh; Intel Mac OS X 14_0) Safari/605.1" }),
      body: JSON.stringify({ code: opened.code.toLowerCase() }),
    });
    expect(paired.status).toBe(200);
    expect(paired.body.token).toMatch(/^omb_sess_/);
    expect(paired.body.session.label).toBe("Safari on Mac");
    expect(paired.body.environment.label).toBe("cab mini");
    const again = await call("/api/auth/pair", { method: "POST", headers: remote("10.0.0.3"), body: JSON.stringify({ code: opened.code }) });
    expect(again.status).toBe(401);

    const bearer = remote("10.0.0.3", { authorization: `Bearer ${paired.body.token}` });
    expect((await call("/api/bots", { headers: bearer })).status).toBe(200);
    const me = await call("/api/auth/session", { headers: bearer });
    expect(me.body).toMatchObject({ kind: "session", via: "bearer", label: "Safari on Mac", scopes: ["admin", "client"] });

    const ticket = await call("/api/auth/stream-ticket", { method: "POST", headers: bearer });
    expect(ticket.body.ticket).toMatch(/^omb_tick_/);
    const stream = await openSse(`${BASE}/api/events?ticket=${ticket.body.ticket}`, { host: REMOTE_HOST });
    try {
      const hello = await stream.until((f) => f.kind === "hello", 5_000);
      expect(hello.kind).toBe("hello");
    } finally {
      stream.close();
    }
    const reused = await call(`/api/events?ticket=${ticket.body.ticket}`, { headers: remote("10.0.0.3") });
    expect(reused.status).toBe(401);

    const sessionsList = await call("/api/auth/sessions");
    const mine = sessionsList.body.sessions.find((s: { id: string }) => s.id === me.body.id);
    expect(mine.label).toBe("Safari on Mac");
    expect(JSON.stringify(sessionsList.body)).not.toContain(paired.body.token);
    const revoked = await call(`/api/auth/sessions/${me.body.id}`, { method: "DELETE" });
    expect(revoked.status).toBe(200);
    const after = await call("/api/bots", { headers: bearer });
    expect(after.status).toBe(401);
    expect(after.body.error).toMatch(/pair this device again/);
  });

  it("gives a browser a cookie that only works same-origin", async () => {
    const opened = await pairingCode();
    const res = await call("/api/auth/pair", {
      method: "POST",
      headers: remote("10.0.0.4", { "x-forwarded-proto": "https" }),
      body: JSON.stringify({ code: opened.code, label: "iPad in the kitchen", cookie: true }),
    });
    expect(res.status).toBe(200);
    expect(res.body.token).toBeUndefined();
    const setCookie = header(res.headers, "set-cookie");
    expect(setCookie).toMatch(new RegExp(`^omb_session_${PORT}_[a-f0-9]{12}=omb_sess_`));
    expect(setCookie).toContain("HttpOnly");
    expect(setCookie).toContain("SameSite=Lax");
    expect(setCookie).toContain("Secure");
    const cookie = setCookie.split(";")[0];

    const sameOrigin = await call("/api/bots", { headers: remote("10.0.0.4", { cookie, origin: `http://${REMOTE_HOST}` }) });
    expect(sameOrigin.status).toBe(200);
    const refreshed = header(sameOrigin.headers, "set-cookie");
    expect(refreshed.split(";")[0]).toBe(cookie);
    expect(refreshed).toMatch(/Max-Age=\d+/);
    expect(refreshed).toContain("HttpOnly");
    const stranger = await call("/api/bots", { headers: remote("10.0.0.4", { cookie: `${cookie.split("=")[0]}=omb_sess_nope`, origin: `http://${REMOTE_HOST}` }) });
    expect(stranger.status).toBe(401);
    expect(header(stranger.headers, "set-cookie")).toBe("");
    const noOrigin = await call("/api/auth/session", { headers: remote("10.0.0.4", { cookie }) });
    expect(noOrigin.body).toMatchObject({ kind: "session", via: "cookie", label: "iPad in the kitchen" });
    const csrf = await call("/api/bots", { method: "POST", headers: remote("10.0.0.4", { cookie, origin: "https://evil.example" }), body: "{}" });
    expect(csrf.status).toBe(403);
    expect(csrf.body.error).toBe("forbidden: cross-origin request");

    const logout = await call("/api/auth/logout", { method: "POST", headers: remote("10.0.0.4", { cookie }) });
    expect(header(logout.headers, "set-cookie")).toContain("Max-Age=0");
    expect((await call("/api/bots", { headers: remote("10.0.0.4", { cookie }) })).status).toBe(401);
  });

  it("pairs a native companion app on its own route, with the body shape it sends", async () => {
    const opened = await pairingCode(["client"]);
    expect(opened.credential).toMatch(/^omb_pair_[A-Za-z0-9_-]{43}$/);

    const paired = await call("/api/pair", {
      method: "POST",
      headers: remote("10.0.0.31"),
      body: JSON.stringify({ credential: opened.credential, deviceName: "Pixel 9", pairRequestId: "11111111-2222-4333-8444-555555555555" }),
    });
    expect(paired.status).toBe(200);
    // Exactly the fields android/core's PairResponseSerializer requires.
    expect(typeof paired.body.token).toBe("string");
    expect(paired.body.token.startsWith("omb_sess_")).toBe(true);
    expect(paired.body.serverName).toBe(opened.serverName);
    expect(paired.body.device.name).toBe("Pixel 9");
    expect(typeof paired.body.device.id).toBe("string");
    expect(typeof paired.body.device.createdAt).toBe("number");
    expect(typeof paired.body.device.lastSeenAt).toBe("number");

    const used = await call("/api/bots", { headers: remote("10.0.0.31", { authorization: `Bearer ${paired.body.token}` }) });
    expect(used.status).toBe(200);
    const listed = await call("/api/auth/sessions");
    expect(listed.body.sessions.some((s: { label: string }) => s.label === "Pixel 9")).toBe(true);

    const again = await call("/api/pair", {
      method: "POST",
      headers: remote("10.0.0.32"),
      body: JSON.stringify({ credential: opened.credential, deviceName: "Pixel 9" }),
    });
    expect(again.status).toBe(401);
    const byCode = await call("/api/auth/pair", {
      method: "POST",
      headers: remote("10.0.0.32"),
      body: JSON.stringify({ code: opened.code, label: "same window" }),
    });
    expect(byCode.status).toBe(401);
  });

  it("offers the app-scheme invite the Android scanner can read", async () => {
    const opened = await pairingCode(["client"]);
    expect(opened.inviteUrl).not.toBeNull();
    const invite = new URL(opened.inviteUrl!);
    // Android's PairingInvite.parse accepts only this exact scheme and host (android/core Connection.kt).
    expect(invite.protocol).toBe("openmausbot:");
    expect(invite.host).toBe("pair");
    expect(invite.searchParams.get("address")).toBe(PUBLIC_URL);
    expect(invite.searchParams.get("token")).toBe(opened.credential);
    expect(invite.searchParams.get("name")).toBe(opened.serverName);
    expect(opened.url).toBe(`${PUBLIC_URL}/pair#code=${opened.code}`);
  });

  it("refuses a native pairing body that is not JSON", async () => {
    const opened = await pairingCode(["client"]);
    const refused = await call("/api/pair", {
      method: "POST",
      headers: remote("10.0.0.33", { "content-type": "text/plain" }),
      body: opened.credential,
    });
    expect(refused.status).toBe(415);
  });

  it("only accepts JSON for the exchange, and replays a lost response by attempt id", async () => {
    const opened = await pairingCode();
    const form = await call("/api/auth/pair", { method: "POST", headers: { ...remote("10.0.0.20"), "content-type": "application/x-www-form-urlencoded" }, body: `code=${opened.code}` });
    expect(form.status).toBe(415);
    const first = await call("/api/auth/pair", { method: "POST", headers: remote("10.0.0.20"), body: JSON.stringify({ code: opened.code, attemptId: "attempt-first-0001" }) });
    expect(first.status).toBe(200);
    const replay = await call("/api/auth/pair", { method: "POST", headers: remote("10.0.0.21"), body: JSON.stringify({ code: opened.code, attemptId: "attempt-first-0001" }) });
    expect(replay.status).toBe(200);
    expect(replay.body.token).toBe(first.body.token);
    const other = await call("/api/auth/pair", { method: "POST", headers: remote("10.0.0.20"), body: JSON.stringify({ code: opened.code, attemptId: "attempt-other-0002" }) });
    expect(other.status).toBe(401);
  });

  it("ends a live event stream the moment its session is revoked", async () => {
    const opened = await pairingCode();
    const paired = await call("/api/auth/pair", { method: "POST", headers: remote("10.0.0.30"), body: JSON.stringify({ code: opened.code, label: "stream" }) });
    const bearer = remote("10.0.0.30", { authorization: `Bearer ${paired.body.token}` });
    const ticket = await call("/api/auth/stream-ticket", { method: "POST", headers: bearer });
    const ended = new Promise<{ hello: boolean; endedMs: number }>((resolve, reject) => {
      const startedAt = Date.now();
      let hello = false;
      const req = request({ host: "127.0.0.1", port: PORT, path: `/api/events?ticket=${ticket.body.ticket}`, method: "GET", headers: { accept: "text/event-stream", ...remote("10.0.0.30") } }, (res) => {
        res.setEncoding("utf8");
        res.on("data", (chunk: string) => {
          if (chunk.includes('"kind":"hello"')) {
            hello = true;
            void call(`/api/auth/sessions/${paired.body.session.id}`, { method: "DELETE" }).then((r) => {
              if (r.status !== 200) reject(new Error(`revoke returned ${r.status}`));
            });
          }
        });
        res.on("end", () => resolve({ hello, endedMs: Date.now() - startedAt }));
        res.on("error", reject);
      });
      req.on("error", reject);
      req.end();
      setTimeout(() => reject(new Error("stream did not end after revocation")), 8_000).unref();
    });
    const outcome = await ended;
    expect(outcome.hello).toBe(true);
    // well under the 4 s heartbeat: the revoke closed it, not the heartbeat
    expect(outcome.endedMs).toBeLessThan(2_500);
  });

  it("gives a client-scope session chat but not the machine: allow-list, display-only edits, stripped config", async () => {
    const opened = await pairingCode(["client"]);
    const paired = await call("/api/auth/pair", { method: "POST", headers: remote("10.0.0.40"), body: JSON.stringify({ code: opened.code, label: "viewer" }) });
    expect(paired.status).toBe(200);
    const h = (extra: Record<string, string> = {}) => remote("10.0.0.40", { authorization: `Bearer ${paired.body.token}`, ...extra });
    expect((await call("/api/bots", { headers: h() })).status).toBe(200);
    for (const [method, path] of [["POST", "/api/cli-test"], ["POST", "/api/webhooks"], ["GET", "/api/mcp/servers"], ["POST", "/api/local-computer/run"]] as const) {
      const r = await call(path, { method, headers: h(), body: method === "POST" ? "{}" : undefined });
      expect(r.status, `${method} ${path}`).toBe(403);
      expect(r.body.error, `${method} ${path}`).toContain("admin scope");
    }
    // The engine list, for picking a model and steering: names, models and capabilities, no accounts or paths.
    const engines = await call("/api/instances", { headers: h() });
    expect(engines.status).toBe(200);
    for (const instance of engines.body.instances as Array<Record<string, unknown>>) {
      expect(Object.keys(instance).filter((key) => !["instanceId", "driverKind", "displayName", "readOnly", "icon", "access", "models", "capabilities", "snapshot"].includes(key))).toEqual([]);
      expect(Object.keys(instance.snapshot as object).filter((key) => key !== "state" && key !== "authenticated")).toEqual([]);
    }
    const created = await call("/api/bots", { method: "POST", body: JSON.stringify({ name: "Scoped" }) });
    const botId = created.body?.id ?? created.body?.bot?.id;
    if (botId) {
      const cosmetic = await call(`/api/bots/${botId}`, { method: "PATCH", headers: h(), body: JSON.stringify({ unread: true }) });
      expect(cosmetic.status).toBe(200);
      const smuggled = await call(`/api/bots/${botId}`, { method: "PATCH", headers: h(), body: JSON.stringify({ unread: true, autoApprove: true }) });
      expect(smuggled.status).toBe(403);
      expect(smuggled.body.error).toContain('"autoApprove"');
    }
    const avatarUrl = "/api/attachments/5f0c2b1e-8a43-4c1d-9e7a-2b6f1d3c4e5a.webp";
    expect((await call("/api/config", { method: "PUT", body: JSON.stringify({ profile: { email: "[email protected]", avatarUrl } }) })).status).toBe(200);
    const config = await call("/api/config", { headers: h() });
    expect(config.status).toBe(200);
    expect(config.body.vps.sshAlias).toBe("");
    expect(config.body.profile.email).toBe("");
    // The sidebar picture is the attachment address only, the same thing a bot's picture is.
    expect(config.body.profile.avatarUrl).toBe(avatarUrl);
    expect(JSON.stringify(config.body)).not.toContain("partitionId");
    expect((await call("/api/config", { method: "PUT", body: JSON.stringify({ profile: { email: "", avatarUrl: "" } }) })).status).toBe(200);
    expect((await call("/api/config", { headers: h() })).body.profile.avatarUrl).toBeUndefined();
  });

  it("projects client config consistently for REST, live events, and replay without stripping admin events", async () => {
    async function pair(scopes: string[], source: string) {
      const opened = await pairingCode(scopes);
      const paired = await call("/api/auth/pair", {
        method: "POST", headers: remote(source), body: JSON.stringify({ code: opened.code }),
      });
      expect(paired.status).toBe(200);
      return remote(source, { authorization: `Bearer ${paired.body.token}` });
    }
    const clientHeaders = await pair(["client"], "10.0.0.41");
    const adminHeaders = await pair(["admin", "client"], "10.0.0.42");
    const streams: Awaited<ReturnType<typeof openSse>>[] = [];
    async function stream(headers: Record<string, string>, cursor?: string) {
      const opened = await openSse(`${BASE}/api/events${cursor ? `?since=${encodeURIComponent(cursor)}` : ""}`, headers);
      streams.push(opened);
      return opened;
    }
    expect((await call("/api/config", { method: "PUT", body: JSON.stringify({ opencodeGo: { providerKeys: { VENICE_API_KEY: "venice-fixture-key" } } }) })).status).toBe(200);
    expect((await call("/api/config", { method: "PUT", body: JSON.stringify({ openai: { key: "sk-proj-fixture-hint-a1b2" }, live: { key: "sk-proj-fixture-live-b2c3" } }) })).status).toBe(200);
    function expectClientConfig(config: any) {
      expect(config.openai).toEqual({ configured: true });
      expect(config.savedKeys.openaiLiveKey).toEqual({ configured: true });
      expect(JSON.stringify(config)).not.toContain("last4");
      expect(config.opencodeGo).toEqual({ configured: false, providerKeys: [] });
      expect(config.profile).toEqual({ name: "Updated fixture", email: "" });
      expect(config.vps).toEqual({ configured: true, sshAlias: "", servers: [], memoryGb: 4, cpus: 2 });
      expect(JSON.stringify(config)).not.toContain("fixture-private-lab");
      expect(config.browserProfiles).toEqual([{ id: "fixture", name: "Fixture browser" }]);
    }
    function expectAdminConfig(config: any) {
      expect(config.openai).toEqual({ configured: true, last4: "a1b2" });
      expect(config.savedKeys.openaiLiveKey).toEqual({ configured: true, last4: "b2c3" });
      expect(config.opencodeGo).toEqual({ configured: false, providerKeys: ["VENICE_API_KEY"] });
      expect(config.profile).toEqual({ name: "Updated fixture", email: "[email protected]", aboutMe: "" });
      expect(config.vps).toEqual({ configured: true, sshAlias: "fixture-private-host", servers: [{ name: "Fixture lab", sshAlias: "fixture-private-lab" }], memoryGb: 4, cpus: 2 });
      expect(config.browserProfiles).toEqual([{ id: "fixture", name: "Fixture browser", partitionId: "fixture-private-partition" }]);
    }
    try {
      // Connect the client first, so a mutation of the shared payload would also corrupt the live event and replay buffer.
      const client = await stream(clientHeaders);
      const hello = await client.until((frame) => frame.kind === "hello");
      const admin = await stream(adminHeaders);
      await admin.until((frame) => frame.kind === "hello");
      const changed = await call("/api/config", {
        method: "PATCH", headers: adminHeaders,
        body: JSON.stringify({ profile: { name: "Updated fixture", email: "[email protected]" } }),
      });
      expect(changed.status).toBe(200);
      expectAdminConfig(changed.body);
      const clientFrame = await client.until((frame) => frame.kind === "config");
      const adminFrame = await admin.until((frame) => frame.kind === "config");
      expectClientConfig(clientFrame);
      expectAdminConfig(adminFrame);
      expect(clientFrame.seq).toBe(adminFrame.seq);
      client.close();
      admin.close();

      const clientReplay = await stream(clientHeaders, hello.cursor);
      expect((await clientReplay.until((frame) => frame.kind === "hello")).resumed).toBe(true);
      expectClientConfig(await clientReplay.until((frame) => frame.kind === "config"));
      const adminReplay = await stream(adminHeaders, hello.cursor);
      expect((await adminReplay.until((frame) => frame.kind === "hello")).resumed).toBe(true);
      expectAdminConfig(await adminReplay.until((frame) => frame.kind === "config"));

      const clientRest = await call("/api/config", { headers: clientHeaders });
      const adminRest = await call("/api/config", { headers: adminHeaders });
      const ownerRest = await call("/api/config");
      expect(clientRest.status).toBe(200);
      expect(adminRest.status).toBe(200);
      expect(ownerRest.status).toBe(200);
      expectClientConfig(clientRest.body);
      expectAdminConfig(adminRest.body);
      expectAdminConfig(ownerRest.body);
    } finally {
      for (const opened of streams) opened.close();
    }
  });

  it("locks a source out after repeated bad codes and says how long", async () => {
    for (let i = 0; i < PAIRING_LOCKOUT.failures; i++) {
      const r = await call("/api/auth/pair", { method: "POST", headers: remote("10.0.0.99"), body: JSON.stringify({ code: `BAD${i}-BADB-ADBA` }) });
      expect(r.status).toBe(401);
    }
    const opened = await pairingCode();
    const locked = await call("/api/auth/pair", { method: "POST", headers: remote("10.0.0.99"), body: JSON.stringify({ code: opened.code }) });
    expect(locked.status).toBe(429);
    expect(locked.body.error).toMatch(/^Too many wrong codes\. Try again at \d{2}:\d{2} UTC\.$/);
    expect((await call("/api/auth/pair", { method: "POST", headers: remote("10.0.0.100"), body: JSON.stringify({ code: opened.code }) })).status).toBe(200);
    expect(stderr).toMatch(/pairing refused from 10\.0\.0\.99/);
  });
});