Skip to content

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

Boat sign-in: tests against a local stand-in for Boat

milind-sonib71394a3b423
diff --git a/electron/boat-sign-in-store.node-test.mjs b/electron/boat-sign-in-store.node-test.mjs
new file mode 100644
index 0000000000..91111e0fe0
--- /dev/null
+++ b/electron/boat-sign-in-store.node-test.mjs
@@ -0,0 +1,61 @@
+import assert from "node:assert/strict";
+import test from "node:test";
+
+import { BOAT_SIGN_IN_CREDENTIAL, boatSignInEnv, createBoatSignInStore, decodeBoatSignInStoreRequest } from "./boat-sign-in-store.mjs";
+
+const REQUEST = "openmausbot:boat-sign-in-store";
+const settled = () => new Promise((done) => setImmediate(done));
+
+test("only a packaged app hands the connection to its server, and says so even when there is none", () => {
+ assert.deepEqual(boatSignInEnv({ [BOAT_SIGN_IN_CREDENTIAL]: "{\"v\":1}" }, true), { OMB_BOAT_SIGN_IN: "{\"v\":1}" });
+ assert.deepEqual(boatSignInEnv({}, true), { OMB_BOAT_SIGN_IN: "" });
+ assert.deepEqual(boatSignInEnv({ [BOAT_SIGN_IN_CREDENTIAL]: "{\"v\":1}" }, false), {});
+});
+
+test("a request is one read or one write of a bounded string, and nothing else", () => {
+ assert.deepEqual(decodeBoatSignInStoreRequest({ data: { type: REQUEST, requestId: "a1", op: "read" } }), { requestId: "a1", op: "read" });
+ assert.deepEqual(decodeBoatSignInStoreRequest({ type: REQUEST, requestId: "a1", op: "write", value: null }), { requestId: "a1", op: "write", value: null });
+ for (const bad of [null, {}, { type: "other", requestId: "a", op: "read" }, { type: REQUEST, requestId: "bad id", op: "read" }, { type: REQUEST, requestId: "a", op: "erase" },
+ { type: REQUEST, requestId: "a", op: "write" }, { type: REQUEST, requestId: "a", op: "write", value: "" }, { type: REQUEST, requestId: "a", op: "write", value: { v: 1 } },
+ { type: REQUEST, requestId: "a", op: "write", value: "x".repeat(16_385) }]) {
+ assert.equal(decodeBoatSignInStoreRequest(bad), null);
+ }
+});
+
+test("writes go through the app's one encrypted writer and are answered only after it; nothing secret is logged", async () => {
+ let document = { boxToken: "boat_key" };
+ const logged = [];
+ const posted = [];
+ const store = createBoatSignInStore({
+ packaged: true, read: () => document, log: (line) => logged.push(line),
+ update: async (derive) => { document = derive({ ...document }); },
+ });
+ const proc = { postMessage: (message) => posted.push(message) };
+ assert.equal(store.receive(proc, { type: "openmausbot:phone-secret-save" }), false);
+ assert.equal(store.receive(proc, { data: { type: REQUEST, requestId: "w1", op: "write", value: "{\"refresh\":\"boatrt_secret\"}" } }), true);
+ await settled();
+ assert.deepEqual(document, { boxToken: "boat_key", [BOAT_SIGN_IN_CREDENTIAL]: "{\"refresh\":\"boatrt_secret\"}" });
+ assert.deepEqual(posted.pop(), { type: "openmausbot:boat-sign-in-store-result", requestId: "w1", ok: true });
+ store.receive(proc, { type: REQUEST, requestId: "r1", op: "read" });
+ await settled();
+ assert.deepEqual(posted.pop(), { type: "openmausbot:boat-sign-in-store-result", requestId: "r1", ok: true, value: "{\"refresh\":\"boatrt_secret\"}" });
+ store.receive(proc, { type: REQUEST, requestId: "w2", op: "write", value: null });
+ await settled();
+ assert.deepEqual(document, { boxToken: "boat_key" });
+ assert.equal(posted.pop().ok, true);
+
+ const failing = createBoatSignInStore({ packaged: true, read: () => document, log: (line) => logged.push(line), update: async () => { throw new Error("The operating-system credential store is unavailable"); } });
+ failing.receive(proc, { type: REQUEST, requestId: "w3", op: "write", value: "{\"refresh\":\"boatrt_other\"}" });
+ await settled();
+ assert.deepEqual(posted.pop(), { type: "openmausbot:boat-sign-in-store-result", requestId: "w3", ok: false });
+ assert.equal(logged.length, 1);
+ assert.ok(!logged.join("\n").includes("boatrt_"));
+});
+
+test("an app run from source keeps nothing here: its server uses its own owner-only file", async () => {
+ const posted = [];
+ const store = createBoatSignInStore({ packaged: false, read: () => ({}), update: async () => { throw new Error("never"); }, log: () => {} });
+ store.receive({ postMessage: (message) => posted.push(message) }, { type: REQUEST, requestId: "w1", op: "write", value: "{}" });
+ await settled();
+ assert.deepEqual(posted, [{ type: "openmausbot:boat-sign-in-store-result", requestId: "w1", ok: false }]);
+});
diff --git a/server/boat-sign-in.test.ts b/server/boat-sign-in.test.ts
new file mode 100644
index 0000000000..eff15d5d11
--- /dev/null
+++ b/server/boat-sign-in.test.ts
@@ -0,0 +1,700 @@
+// "Sign in with Boat" against a local stand-in for Boat (server/testing/fake-boat-oauth.ts): nothing here reaches boat.dev.
+import { createServer, request, type IncomingMessage, type Server } from "node:http";
+import type { AddressInfo } from "node:net";
+import { mkdtempSync, readFileSync, statSync } from "node:fs";
+import { tmpdir } from "node:os";
+import { join } from "node:path";
+
+import { afterAll, afterEach, beforeAll, beforeEach, describe, expect, it, vi } from "vitest";
+
+import { BOAT_SIGN_IN_MARK } from "../shared/boat-sign-in.ts";
+import { boatFetch } from "./boat.ts";
+import { BOAT_SIGN_IN_CALLBACK_PATH, BOAT_SIGN_IN_CLIENT_ID, BOAT_SIGN_IN_PORTS, BOAT_SIGN_IN_SCOPES, BoatSignIn, boatScopeFor, type BoatSignInPersistence } from "./boat-sign-in.ts";
+import { createBoatSignInHost, type BoatSignInHost } from "./boat-sign-in-host.ts";
+import { BOAT_SIGN_IN_ENV, BOAT_SIGN_IN_FILE, createBoatSignInStore } from "./boat-sign-in-store.ts";
+import { setBoatSignIn } from "./boat-sign-in-use.ts";
+import { loadConfig, WORKSPACE_CREDENTIAL_ENV, type AppConfig } from "./config.ts";
+import { json } from "./harness/http.ts";
+import { redactSecretsInText } from "./redact.ts";
+import type { RequestAuth } from "./request-auth.ts";
+import { PASS } from "./routes/table.ts";
+import { removeTempDir } from "./testing/cleanup.ts";
+import { startFakeBoat, type FakeBoat } from "./testing/fake-boat-oauth.ts";
+import { excludedWorkspaceAuthPath } from "./workspace-backup-policy.ts";
+
+const PORT = 18799;
+const REDIRECTS = BOAT_SIGN_IN_PORTS.map((port) => `http://127.0.0.1:${port}${BOAT_SIGN_IN_CALLBACK_PATH}`);
+const SIGNED_IN: AppConfig = { box: { signIn: true } };
+const MINUTE = 60_000;
+
+let fake: FakeBoat;
+let clock = 1_800_000_000_000;
+const savedApi = process.env.OMB_BOAT_API;
+const savedKey = process.env.BOX_TOKEN;
+
+/** What was saved, in order, beside the bearers the fake saw: the order is the proof of "saved before used". */
+function memory(initial: string | null = null) {
+ const state = { value: initial, writes: [] as Array<string | null>, events: [] as string[], fail: false, boatCallsAtSave: [] as number[] };
+ const persistence: BoatSignInPersistence = {
+ read: () => state.value,
+ latest: async () => state.value,
+ async write(value) {
+ if (state.fail) throw new Error("disk full");
+ state.value = value;
+ state.writes.push(value);
+ state.events.push(`saved:${value ? JSON.parse(value).access : "nothing"}`);
+ state.boatCallsAtSave.push(fake.counts.api);
+ },
+ };
+ return { state, persistence };
+}
+
+function signInWith(persistence: BoatSignInPersistence, more: Partial<ConstructorParameters<typeof BoatSignIn>[0]> = {}) {
+ const signIn = new BoatSignIn({ persistence, api: () => fake.api, now: () => clock, pause: async () => {}, ...more });
+ setBoatSignIn(signIn);
+ return signIn;
+}
+
+async function connect(signIn: BoatSignIn, choice?: Parameters<FakeBoat["approve"]>[1], owner = "owner") {
+ const back = new URL(fake.approve(signIn.start(owner, PORT).url, choice));
+ const answer = await signIn.callback(back.host, back.search);
+ // What connecting itself asked Boat (the account's name) is not what a test counts.
+ fake.counts.api = 0;
+ fake.bearers.length = 0;
+ return { back, answer };
+}
+
+const advance = (ms: number) => { clock += ms; fake.advance(ms); };
+const tokensOf = (value: string | null) => JSON.parse(value ?? "{}") as { access: string; refresh: string };
+
+beforeAll(async () => {
+ fake = await startFakeBoat(BOAT_SIGN_IN_CLIENT_ID, REDIRECTS);
+ process.env.OMB_BOAT_API = fake.api;
+});
+afterAll(async () => {
+ await fake.close();
+ if (savedApi === undefined) delete process.env.OMB_BOAT_API; else process.env.OMB_BOAT_API = savedApi;
+ if (savedKey === undefined) delete process.env.BOX_TOKEN; else process.env.BOX_TOKEN = savedKey;
+});
+beforeEach(() => {
+ delete process.env.BOX_TOKEN;
+ fake.requireOrg(false);
+ for (const key of Object.keys(fake.counts) as Array<keyof FakeBoat["counts"]>) fake.counts[key] = 0;
+ fake.bearers.length = 0;
+});
+afterEach(() => {
+ setBoatSignIn(null);
+ vi.restoreAllMocks();
+});
+
+describe("signing in", () => {
+ it("asks Boat for the least it needs with PKCE, exchanges the code once and keeps the tokens to itself", async () => {
+ const { state, persistence } = memory();
+ const signIn = signInWith(persistence);
+ const started = new URL(signIn.start("owner", PORT).url);
+ expect(started.origin + started.pathname).toBe(`${fake.origin}/api/boat/oauth2/authorize`);
+ expect(Object.fromEntries(started.searchParams)).toMatchObject({
+ response_type: "code", client_id: BOAT_SIGN_IN_CLIENT_ID, redirect_uri: `http://127.0.0.1:${PORT}/api/boat/oauth/callback`,
+ scope: BOAT_SIGN_IN_SCOPES.join(" "), code_challenge_method: "S256",
+ });
+ for (const never of ["billing.write", "ssh", "environment.read", "environment.write", "environment.values.read", "sandbox.delete", "sandbox.fork", "agent.prompt", "host", "network.write", "snapshot.read", "snapshot.write"]) {
+ expect(BOAT_SIGN_IN_SCOPES as readonly string[]).not.toContain(never);
+ }
+ expect(signIn.status(false, "owner")).toMatchObject({ available: true, state: "none", pending: true });
+
+ const back = new URL(fake.approve(started.href));
+ const answer = await signIn.callback(back.host, back.search);
+ expect(answer).toMatchObject({ status: 200, title: "Signed in to Boat" });
+ const { access, refresh } = tokensOf(state.value);
+ expect(access).toMatch(/^boat_/);
+ expect(refresh).toMatch(/^boatrt_/);
+ expect(JSON.stringify(answer)).not.toContain(back.searchParams.get("code")!);
+ expect(fake.counts.token).toBe(1);
+
+ const status = signIn.status(false, "owner");
+ expect(status).toEqual({ available: true, state: "connected", account: "[email protected]", missingScopes: [], used: true, keySaved: false, last: { outcome: "connected" } });
+ expect(JSON.stringify(status)).not.toContain(access);
+ expect(JSON.stringify(status)).not.toContain(refresh);
+
+ const listed = await boatFetch(SIGNED_IN, "/sandboxes?limit=1");
+ expect(listed.status).toBe(200);
+ expect(fake.bearers.at(-1)).toBe(access);
+ });
+
+ it("refuses a callback whose state is not the one it sent, is repeated, comes for another address or comes too late", async () => {
+ const { state, persistence } = memory();
+ const signIn = signInWith(persistence);
+ expect((await signIn.callback(`127.0.0.1:${PORT}`, "?code=x&state=y")).status).toBe(400);
+
+ const good = new URL(fake.approve(signIn.start("owner", PORT).url));
+ const code = good.searchParams.get("code")!, sent = good.searchParams.get("state")!;
+ for (const search of [`?code=${code}&state=${sent}x`, `?code=${code}`, `?code=${code}&state=${sent}&state=${sent}`, `?code=${code}&state=`]) {
+ expect((await signIn.callback(good.host, search)).status, search).toBe(400);
+ }
+ expect((await signIn.callback("127.0.0.1:8799", good.search)).status).toBe(400);
+ expect((await signIn.callback("evil.example", good.search)).status).toBe(400);
+ expect(fake.counts.token).toBe(0);
+ expect(state.value).toBeNull();
+ // None of those spent the real one.
+ expect((await signIn.callback(good.host, good.search)).status).toBe(200);
+
+ const late = new URL(fake.approve(signIn.start("owner", PORT).url));
+ clock += 11 * MINUTE;
+ expect((await signIn.callback(late.host, late.search)).status).toBe(400);
+ });
+
+ it("a newer start makes the older link worthless", async () => {
+ const signIn = signInWith(memory().persistence);
+ const older = new URL(fake.approve(signIn.start("owner", PORT).url));
+ signIn.start("owner", PORT);
+ expect((await signIn.callback(older.host, older.search)).status).toBe(400);
+ expect(fake.counts.token).toBe(0);
+ });
+
+ it("a person who cancels on Boat's screen connects nothing and is told so", async () => {
+ const { state, persistence } = memory();
+ const signIn = signInWith(persistence);
+ const { answer } = await connect(signIn, { deny: true });
+ expect(answer).toMatchObject({ status: 200, title: "Sign-in cancelled" });
+ expect(state.value).toBeNull();
+ expect(fake.counts.token).toBe(0);
+ expect(signIn.status(false, "owner")).toEqual({ available: true, state: "none", keySaved: false, last: { outcome: "cancelled" } });
+ });
+
+ it("a callback link opened a second time exchanges nothing", async () => {
+ const signIn = signInWith(memory().persistence);
+ const { back, answer } = await connect(signIn);
+ expect(answer.status).toBe(200);
+ expect((await signIn.callback(back.host, back.search)).status).toBe(400);
+ expect(fake.counts.token).toBe(1);
+ expect(signIn.status(false).state).toBe("connected");
+ });
+
+ it("a code Boat no longer accepts ends as a plain failure, never a connection", async () => {
+ const { state, persistence } = memory();
+ const signIn = signInWith(persistence);
+ const first = new URL(fake.approve(signIn.start("owner", PORT).url));
+ const code = first.searchParams.get("code")!;
+ await signIn.callback(first.host, first.search);
+ await signIn.signOut();
+ // The same code again under a fresh state: Boat answers invalid_grant.
+ const again = new URL(signIn.start("owner", PORT).url);
+ const answer = await signIn.callback(first.host, `?code=${code}&state=${again.searchParams.get("state")}&iss=${encodeURIComponent(fake.origin)}`);
+ expect(answer.status).toBe(400);
+ expect(state.value).toBeNull();
+ expect(signIn.status(false, "owner").last).toEqual({ outcome: "failed" });
+ });
+
+ it("an answer that names another issuer is refused", async () => {
+ const signIn = signInWith(memory().persistence);
+ const back = new URL(fake.approve(signIn.start("owner", PORT).url));
+ back.searchParams.set("iss", "https://elsewhere.example");
+ expect((await signIn.callback(back.host, back.search)).status).toBe(400);
+ expect(fake.counts.token).toBe(0);
+ });
+
+ it("signing in again does not revoke: a revoke would end the new connection too", async () => {
+ const signIn = signInWith(memory().persistence);
+ await connect(signIn);
+ await connect(signIn);
+ expect(fake.counts.revoke).toBe(0);
+ expect((await boatFetch(SIGNED_IN, "/sandboxes")).status).toBe(200);
+ });
+});
+
+describe("renewing", () => {
+ it("saves the new refresh token before the new access token is used", async () => {
+ const { state, persistence } = memory();
+ const signIn = signInWith(persistence);
+ await connect(signIn);
+ const before = tokensOf(state.value);
+ state.events.length = 0;
+ state.boatCallsAtSave.length = 0;
+ advance(56 * MINUTE);
+ const response = await boatFetch(SIGNED_IN, "/sandboxes");
+ expect(response.status).toBe(200);
+ const after = tokensOf(state.value);
+ expect(after.refresh).not.toBe(before.refresh);
+ expect(after.access).not.toBe(before.access);
+ expect(fake.bearers).toEqual([after.access]);
+ expect(state.events).toEqual([`saved:${after.access}`]);
+ // Saved while no Boat call had yet been made with it.
+ expect(state.boatCallsAtSave).toEqual([0]);
+ expect(fake.counts.refresh).toBe(1);
+ });
+
+ it("ten callers at once cause one refresh", async () => {
+ const signIn = signInWith(memory().persistence);
+ await connect(signIn);
+ advance(58 * MINUTE);
+ const release = fake.holdRefreshes();
+ const calls = Array.from({ length: 10 }, () => boatFetch(SIGNED_IN, "/sandboxes"));
+ await vi.waitFor(() => expect(fake.counts.refresh).toBe(1));
+ release();
+ const answers = await Promise.all(calls);
+ expect(answers.map((answer) => answer.status)).toEqual(Array(10).fill(200));
+ expect(fake.counts.refresh).toBe(1);
+ expect(new Set(fake.bearers).size).toBe(1);
+ expect(fake.liveConnections()).toBeGreaterThan(0);
+ });
+
+ it("asks once more when the answer is lost, and gets the same new tokens", async () => {
+ const { state, persistence } = memory();
+ const signIn = signInWith(persistence);
+ await connect(signIn);
+ const before = tokensOf(state.value);
+ advance(58 * MINUTE);
+ fake.loseNextRefreshAnswer();
+ expect((await boatFetch(SIGNED_IN, "/sandboxes")).status).toBe(200);
+ expect(fake.counts.refresh).toBe(2);
+ expect(tokensOf(state.value).refresh).not.toBe(before.refresh);
+ expect(signIn.status(false).state).toBe("connected");
+ });
+
+ it("when Boat says invalid_grant it asks the person to sign in again and never tries again", async () => {
+ const { state, persistence } = memory();
+ const signIn = signInWith(persistence);
+ await connect(signIn);
+ const before = tokensOf(state.value);
+ advance(58 * MINUTE);
+ fake.disconnect();
+ const first = await boatFetch(SIGNED_IN, "/sandboxes");
+ expect(first.status).toBe(401);
+ expect(await first.json()).toMatchObject({ boatSignIn: true, message: expect.stringContaining("sign in to Boat again") });
+ expect(signIn.status(true)).toMatchObject({ state: "needs-sign-in", used: true, keySaved: true });
+ const stored = tokensOf(state.value);
+ expect(stored.refresh).toBe("");
+ expect(JSON.stringify(state.value)).not.toContain(before.refresh);
+ for (let i = 0; i < 3; i += 1) expect((await boatFetch(SIGNED_IN, "/sandboxes")).status).toBe(401);
+ expect(fake.counts.refresh).toBe(1);
+ // Never the pasted key in its place without being asked: nothing reached Boat at all.
+ expect(fake.counts.api).toBe(0);
+ // Signing in again is the way out.
+ expect((await connect(signIn)).answer.status).toBe(200);
+ expect((await boatFetch(SIGNED_IN, "/sandboxes")).status).toBe(200);
+ });
+
+ it("does not hand out a renewed token it could not save, and saves it before trying anything else", async () => {
+ const { state, persistence } = memory();
+ const signIn = signInWith(persistence);
+ await connect(signIn);
+ advance(58 * MINUTE);
+ state.fail = true;
+ await expect(boatFetch(SIGNED_IN, "/sandboxes")).rejects.toThrow(/could not be saved/);
+ expect(fake.counts.api).toBe(0);
+ await expect(boatFetch(SIGNED_IN, "/sandboxes")).rejects.toThrow(/could not be saved/);
+ expect(fake.counts.refresh).toBe(1);
+ state.fail = false;
+ expect((await boatFetch(SIGNED_IN, "/sandboxes")).status).toBe(200);
+ expect(fake.counts.refresh).toBe(1);
+ expect(fake.bearers).toEqual([tokensOf(state.value).access]);
+ });
+
+ it("keeps using a token that is still good while Boat cannot be reached, then says so; the connection is kept", async () => {
+ const { state, persistence } = memory();
+ let down = false;
+ const signIn = signInWith(persistence, { api: () => (down ? "http://127.0.0.1:9/api/v1" : fake.api) });
+ await connect(signIn);
+ advance(56 * MINUTE);
+ down = true;
+ expect(await signIn.accessToken()).toBe(tokensOf(state.value).access);
+ advance(5 * MINUTE);
+ await expect(signIn.accessToken()).rejects.toMatchObject({ problem: "unreachable" });
+ expect(signIn.status(false).state).toBe("connected");
+ down = false;
+ advance(MINUTE);
+ expect(await signIn.accessToken()).toBe(tokensOf(state.value).access);
+ expect(fake.counts.refresh).toBe(1);
+ });
+
+ it("a second server process on the same store takes the renewed tokens and never sends the spent one", async () => {
+ const { state, persistence } = memory();
+ const first = signInWith(persistence);
+ await connect(first);
+ const second = new BoatSignIn({ persistence, api: () => fake.api, now: () => clock, pause: async () => {} });
+ advance(58 * MINUTE);
+ const renewed = await first.accessToken();
+ expect(fake.counts.refresh).toBe(1);
+ expect(await second.accessToken()).toBe(renewed);
+ expect(fake.counts.refresh).toBe(1);
+ expect(tokensOf(state.value).access).toBe(renewed);
+ });
+
+ it("a token Boat refuses before its time is renewed once and the call repeated", async () => {
+ const { state, persistence } = memory();
+ const signIn = signInWith(persistence);
+ await connect(signIn);
+ const stale = tokensOf(state.value).access;
+ advance(2 * MINUTE);
+ // Something else renewed this connection moments ago (its tokens never reached this store): the access token here is dead.
+ const other = new BoatSignIn({ persistence: memory(state.value).persistence, api: () => fake.api, now: () => clock + 58 * MINUTE, pause: async () => {} });
+ const fresh = await other.accessToken();
+ setBoatSignIn(signIn);
+ const response = await boatFetch(SIGNED_IN, "/sandboxes");
+ expect(response.status).toBe(200);
+ expect(fake.bearers).toEqual([stale, fresh]);
+ expect(tokensOf(state.value).access).toBe(fresh);
+ });
+});
+
+describe("what the person allowed", () => {
+ it("a feature whose scope was unticked says so and is never sent; the rest works", async () => {
+ const signIn = signInWith(memory().persistence);
+ await connect(signIn, { scopes: BOAT_SIGN_IN_SCOPES.filter((scope) => scope !== "sandbox.create" && scope !== "exec") });
+ expect(signIn.status(false).missingScopes).toEqual(["sandbox.create", "exec"]);
+ expect((await boatFetch(SIGNED_IN, "/sandboxes?limit=1")).status).toBe(200);
+ const sent = fake.counts.api;
+ const created = await boatFetch(SIGNED_IN, "/sandboxes", { method: "POST", body: "{}" });
+ expect(created.status).toBe(403);
+ expect(await created.json()).toMatchObject({ error: "api_key_action_forbidden", boatSignIn: true, message: expect.stringMatching(/does not let this app create a cloud computer: "sandbox\.create" was not allowed/) });
+ const ran = await boatFetch(SIGNED_IN, "/sandboxes/bx_1/commands", { method: "POST", body: "{}" });
+ expect((await ran.json()).message).toContain("run commands on a cloud computer");
+ expect(fake.counts.api).toBe(sent);
+ });
+
+ it("without account.read it connects and shows no account", async () => {
+ const signIn = signInWith(memory().persistence);
+ await connect(signIn, { scopes: BOAT_SIGN_IN_SCOPES.filter((scope) => scope !== "account.read") });
+ const status = signIn.status(false);
+ expect(status).toMatchObject({ state: "connected", missingScopes: ["account.read"] });
+ expect(status.account).toBeUndefined();
+ });
+
+ it("sandbox.delete stands in for sandbox.delete-own", async () => {
+ const signIn = signInWith(memory().persistence);
+ await connect(signIn, { scopes: [...BOAT_SIGN_IN_SCOPES.filter((scope) => scope !== "sandbox.delete-own"), "sandbox.delete"] });
+ expect(signIn.status(false).missingScopes).toEqual([]);
+ });
+
+ it("Boat's own refusals of a sign-in are put in plain words, not called a rejected API key", async () => {
+ const signIn = signInWith(memory().persistence);
+ await connect(signIn);
+ fake.requireOrg(true);
+ const refused = await boatFetch(SIGNED_IN, "/sandboxes");
+ expect(refused.status).toBe(400);
+ expect(await refused.json()).toMatchObject({ error: "org_required", boatSignIn: true, message: expect.stringContaining("several organizations") });
+ });
+
+ it("knows which scope each call the app makes needs", () => {
+ expect([
+ boatScopeFor("GET", "/sandboxes?limit=1"), boatScopeFor("POST", "/sandboxes"), boatScopeFor("GET", "/sandboxes/bx_1"),
+ boatScopeFor("PATCH", "/sandboxes/bx_1"), boatScopeFor("DELETE", "/sandboxes/bx_1"), boatScopeFor("POST", "/sandboxes/bx_1/resume"),
+ boatScopeFor("POST", "/sandboxes/bx_1/stop"), boatScopeFor("POST", "/sandboxes/bx_1/commands"), boatScopeFor("GET", "/sandboxes/bx_1/commands/p1?tailBytes=1"),
+ boatScopeFor("POST", "/sandboxes/bx_1/desktop?vnc=1"), boatScopeFor("GET", "/sandboxes/bx_1/files?path=a"), boatScopeFor("PUT", "/sandboxes/bx_1/files"),
+ boatScopeFor("POST", "/sandboxes/bx_1/files/download-url"), boatScopeFor("POST", "/sandboxes/bx_1/files/upload-url"), boatScopeFor("GET", "/sandboxes/bx_1/artifacts?path=a"),
+ boatScopeFor("GET", "/me"), boatScopeFor("GET", "/deletion-operations/op_1"),
+ ]).toEqual(["sandbox.read", "sandbox.create", "sandbox.read", "sandbox.update", "sandbox.delete-own", "sandbox.resume", "sandbox.stop", "exec", "exec", "desktop",
+ "file.read", "file.write", "file.read", "file.write", "file.read", "account.read", null]);
+ });
+});
+
+describe("a pasted API key beside the sign-in", () => {
+ it("a key alone is sent as it always was", async () => {
+ setBoatSignIn(null);
+ await boatFetch({ box: { token: "boat_pasted_key_0001" } }, "/sandboxes");
+ expect(fake.bearers).toEqual(["boat_pasted_key_0001"]);
+ });
+
+ it("the one set last is used, the other stays, and removing one leaves the other", async () => {
+ const { state, persistence } = memory();
+ const signIn = signInWith(persistence);
+ process.env.BOX_TOKEN = "boat_pasted_key_0002";
+ expect(loadConfig().box).toEqual({ token: "boat_pasted_key_0002" });
+
+ // Signed in after the key: the sign-in is used.
+ await connect(signIn);
+ expect(signIn.status(true)).toMatchObject({ state: "connected", used: true, keySaved: true });
+ expect(loadConfig().box).toEqual({ token: "boat_pasted_key_0002", signIn: true });
+ await boatFetch(loadConfig(), "/sandboxes");
+ expect(fake.bearers.at(-1)).toBe(tokensOf(state.value).access);
+ // A credential named by its token is exactly that one, whatever is in use.
+ await boatFetch({ box: { token: "boat_pasted_key_0002" } }, "/sandboxes");
+ expect(fake.bearers.at(-1)).toBe("boat_pasted_key_0002");
+ await boatFetch({ box: { token: BOAT_SIGN_IN_MARK } }, "/sandboxes");
+ expect(fake.bearers.at(-1)).toBe(tokensOf(state.value).access);
+
+ // A key saved after the sign-in: the key is used, the sign-in stays connected.
+ await signIn.preferKey();
+ expect(signIn.status(true)).toMatchObject({ state: "connected", used: false });
+ expect(loadConfig().box).toEqual({ token: "boat_pasted_key_0002" });
+ await boatFetch(loadConfig(), "/sandboxes");
+ expect(fake.bearers.at(-1)).toBe("boat_pasted_key_0002");
+
+ // The key removed: the sign-in is what is left, and is used.
+ delete process.env.BOX_TOKEN;
+ expect(signIn.status(false)).toMatchObject({ state: "connected", used: true, keySaved: false });
+ expect(loadConfig().box).toEqual({ signIn: true });
+
+ // The sign-in removed: the key, saved again, is what is left.
+ process.env.BOX_TOKEN = "boat_pasted_key_0002";
+ expect(await signIn.signOut()).toEqual({ revoked: true });
+ expect(fake.counts.revoke).toBe(1);
+ expect(state.value).toBeNull();
+ expect(signIn.status(true)).toEqual({ available: true, state: "none", keySaved: true });
+ expect(loadConfig().box).toEqual({ token: "boat_pasted_key_0002" });
+ });
+
+ it("with sign-in not offered, nothing is read, started or used", async () => {
+ const { state, persistence } = memory(JSON.stringify({ v: 1, refresh: "boatrt_x", access: "boat_x", expiresAt: clock + 60 * MINUTE, scopes: [], prefer: "signIn", connectedAt: 1 }));
+ const signIn = signInWith(persistence, { enabled: false });
+ expect(signIn.status(true)).toEqual({ available: false, state: "none", keySaved: true });
+ expect(() => signIn.start("owner", PORT)).toThrow();
+ expect(signIn.used(false)).toBe(false);
+ expect((await signIn.callback(`127.0.0.1:${PORT}`, "?code=a&state=b")).status).toBe(400);
+ expect(state.writes).toEqual([]);
+ });
+
+ it("only the three registered ports are ever a return address", () => {
+ const signIn = signInWith(memory().persistence);
+ expect(() => signIn.start("owner", 5199)).toThrow();
+ expect(() => signIn.start("owner", 8800)).toThrow();
+ for (const port of BOAT_SIGN_IN_PORTS) expect(new URL(signIn.start("owner", port).url).searchParams.get("redirect_uri")).toBe(`http://127.0.0.1:${port}/api/boat/oauth/callback`);
+ });
+});
+
+describe("the tokens stay on the server", () => {
+ it("are masked in anything logged and never written by the sign-in itself", async () => {
+ const lines: string[] = [];
+ for (const level of ["log", "info", "warn", "error", "debug"] as const) vi.spyOn(console, level).mockImplementation((...args) => { lines.push(args.map(String).join(" ")); });
+ const { state, persistence } = memory();
+ const signIn = signInWith(persistence);
+ const { back } = await connect(signIn);
+ const first = tokensOf(state.value);
+ advance(58 * MINUTE);
+ await boatFetch(SIGNED_IN, "/sandboxes");
+ fake.disconnect();
+ advance(58 * MINUTE);
+ await boatFetch(SIGNED_IN, "/sandboxes");
+ const second = tokensOf(state.writes.at(-2) ?? null);
+ const all = lines.join("\n");
+ for (const secret of [first.access, first.refresh, second.access, second.refresh, back.searchParams.get("code")!]) {
+ if (secret) expect(all).not.toContain(secret);
+ }
+ await connect(signIn);
+ const held = tokensOf(state.value);
+ expect(redactSecretsInText(`curl -H "authorization: Bearer ${held.access}" and ${held.refresh}`)).not.toMatch(/boat_|boatrt_/);
+ });
+
+ it("the connection's environment name is stripped from everything a bot runs", () => {
+ expect(WORKSPACE_CREDENTIAL_ENV).toContain(BOAT_SIGN_IN_ENV);
+ });
+});
+
+describe("where the connection is kept", () => {
+ let dir: string;
+ beforeEach(() => { dir = mkdtempSync(join(tmpdir(), "omb-boat-sign-in-")); });
+ afterEach(async () => { await removeTempDir(dir); });
+
+ it("an app run from source keeps it in an owner-only file that no backup carries", async () => {
+ const store = createBoatSignInStore({ dataDir: dir, env: {}, post: () => false });
+ expect(store.persistence.read()).toBeNull();
+ await store.persistence.write("{\"v\":1}");
+ expect(readFileSync(join(dir, BOAT_SIGN_IN_FILE), "utf8")).toBe("{\"v\":1}");
+ if (process.platform !== "win32") expect(statSync(join(dir, BOAT_SIGN_IN_FILE)).mode & 0o777).toBe(0o600);
+ expect(await store.persistence.latest()).toBe("{\"v\":1}");
+ expect(excludedWorkspaceAuthPath(BOAT_SIGN_IN_FILE)).toBe(true);
+ await store.persistence.write(null);
+ expect(store.persistence.read()).toBeNull();
+ });
+
+ it("the packaged app's server reads it from its environment once, then asks the app to read and save", async () => {
+ const env: NodeJS.ProcessEnv = { [BOAT_SIGN_IN_ENV]: "{\"v\":1}" };
+ const kept = { value: "{\"v\":1}" as string | null };
+ let answering = true;
+ const store = createBoatSignInStore({
+ dataDir: dir, env,
+ post: (message) => {
+ if (!answering) return false;
+ if (message.op === "write") kept.value = message.value ?? null;
+ queueMicrotask(() => store.receive({ type: "openmausbot:boat-sign-in-store-result", requestId: message.requestId, ok: true, ...(message.op === "read" ? { value: kept.value } : {}) }));
+ return true;
+ },
+ });
+ expect(env[BOAT_SIGN_IN_ENV]).toBeUndefined();
+ expect(store.persistence.read()).toBe("{\"v\":1}");
+ await store.persistence.write("{\"v\":2}");
+ expect(kept.value).toBe("{\"v\":2}");
+ expect(await store.persistence.latest()).toBe("{\"v\":2}");
+ expect(() => statSync(join(dir, BOAT_SIGN_IN_FILE))).toThrow();
+ answering = false;
+ await expect(store.persistence.write("{\"v\":3}")).rejects.toThrow();
+ expect(store.receive({ type: "something-else" })).toBe(false);
+ });
+});
+
+describe("on the server", () => {
+ const owner: RequestAuth = { kind: "loopback", scopes: [] } as unknown as RequestAuth;
+ let dir: string;
+ let http: Server;
+ let origin: string;
+ let host: BoatSignInHost;
+ let cfg: AppConfig;
+ const transitions = new Set<"box" | "vps">();
+
+ const make = (more: Partial<Parameters<typeof createBoatSignInHost>[0]> = {}) => {
+ cfg = loadConfig();
+ host = createBoatSignInHost({
+ desktop: true, hosted: false, port: PORT, dataDir: dir, cfg, env: {}, refresh: () => { Object.assign(cfg, loadConfig()); },
+ managedBoatOwners: () => [], operationConflict: () => null, transitions, post: () => false, ...more,
+ });
+ // The clock of the host's own sign-in is the real one; nothing below waits on it.
+ return host;
+ };
+ const call = (method: string, path: string, auth: RequestAuth = owner, headers: Record<string, string> = {}) => new Promise<{ status: number; body: any }>((done, fail) => {
+ const req = { method, headers } as unknown as IncomingMessage;
+ const chunks: string[] = [];
+ const res = { headersSent: false, writableEnded: false, statusCode: 0, setHeader() {}, getHeader() { return undefined; },
+ writeHead(status: number) { this.statusCode = status; this.headersSent = true; return this; },
+ end(text?: string) { if (text) chunks.push(text); this.writableEnded = true; done({ status: this.statusCode, body: chunks.length ? JSON.parse(chunks.join("")) : null }); } };
+ void host.routes({ req, res: res as never, url: new URL(path, "http://127.0.0.1"), path, method, auth, json, readBody: (async () => ({})) as never })
+ .then((out) => { if (out === PASS) done({ status: 0, body: null }); }, fail);
+ });
+ const get = (path: string, method = "GET", headers: Record<string, string> = {}) => new Promise<{ status: number; headers: IncomingMessage["headers"]; text: string }>((done, fail) => {
+ const target = new URL(path, origin);
+ const req = request({ hostname: target.hostname, port: target.port, path: target.pathname + target.search, method, headers: { host: `127.0.0.1:${PORT}`, ...headers } }, (res) => {
+ let text = "";
+ res.on("data", (chunk) => { text += chunk; });
+ res.on("end", () => done({ status: res.statusCode ?? 0, headers: res.headers, text }));
+ });
+ req.on("error", fail);
+ req.end();
+ });
+
+ beforeEach(async () => {
+ dir = mkdtempSync(join(tmpdir(), "omb-boat-sign-in-host-"));
+ transitions.clear();
+ http = createServer((req, res) => {
+ void host.callback(req, res, new URL(req.url ?? "/", "http://127.0.0.1")).then((answered) => { if (!answered) res.writeHead(418).end(); });
+ });
+ await new Promise<void>((done) => http.listen(0, "127.0.0.1", done));
+ origin = `http://127.0.0.1:${(http.address() as AddressInfo).port}`;
+ });
+ afterEach(async () => {
+ await new Promise<void>((done) => { http.closeAllConnections(); http.close(() => done()); });
+ await removeTempDir(dir);
+ });
+
+ it("the whole way: start, Boat's redirect, connected, a Boat call, disconnect", async () => {
+ make();
+ expect(host.statusPart()).toEqual({ keySaved: false, signIn: { available: true, state: "none", keySaved: false } });
+ const started = await call("POST", "/api/boat/sign-in/start");
+ expect(started.status).toBe(200);
+ expect(Object.keys(started.body)).toEqual(["url"]);
+ const back = new URL(fake.approve(started.body.url));
+ const page = await get(back.pathname + back.search);
+ expect(page.status).toBe(200);
+ expect(page.headers["content-type"]).toBe("text/html; charset=utf-8");
+ expect(page.text).toContain("Signed in to Boat");
+ expect(page.text).toContain("You can close this tab");
+ const stored = tokensOf(readFileSync(join(dir, BOAT_SIGN_IN_FILE), "utf8"));
+ for (const secret of [back.searchParams.get("code")!, back.searchParams.get("state")!, stored.access, stored.refresh]) {
+ expect(page.text).not.toContain(secret);
+ expect(JSON.stringify(page.headers)).not.toContain(secret);
+ }
+ const status = host.statusPart();
+ expect(status.signIn).toMatchObject({ state: "connected", account: "[email protected]", used: true, missingScopes: [] });
+ expect(JSON.stringify(status)).not.toMatch(/boat_|boatrt_/);
+ // The live config now names the sign-in, and a Boat call made with it carries the sign-in's bearer.
+ expect(cfg.box?.signIn).toBe(true);
+ expect((await boatFetch(cfg, "/sandboxes?limit=1")).status).toBe(200);
+ expect(fake.bearers.at(-1)).toBe(stored.access);
+
+ const out = await call("DELETE", "/api/boat/sign-in");
+ expect(out).toEqual({ status: 200, body: { ok: true, revoked: true } });
+ expect(fake.counts.revoke).toBe(1);
+ expect(() => readFileSync(join(dir, BOAT_SIGN_IN_FILE))).toThrow();
+ expect(cfg.box?.signIn).toBeUndefined();
+ expect(host.statusPart().signIn).toEqual({ available: true, state: "none", keySaved: false });
+ });
+
+ it("the callback is a plain page for a browser's own navigation: GET only, no CORS, never a redirect", async () => {
+ make();
+ const started = await call("POST", "/api/boat/sign-in/start");
+ const back = new URL(fake.approve(started.body.url));
+ const posted = await get(back.pathname + back.search, "POST");
+ expect(posted.status).toBe(405);
+ for (const method of ["PUT", "DELETE", "OPTIONS", "HEAD"]) expect((await get(back.pathname + back.search, method)).status, method).toBe(405);
+ expect(fake.counts.token).toBe(0);
+
+ const tries = [
+ "?state=wrong&code=x", "?error=access_denied&state=wrong", "", "?redirect_uri=https://evil.example&next=https://evil.example&state=x&code=y",
+ `?code=x&state=${back.searchParams.get("state")}x&return_to=//evil.example`,
+ ];
+ for (const search of tries) {
+ const answer = await get(`${BOAT_SIGN_IN_CALLBACK_PATH}${search}`, "GET", { origin: "https://evil.example" });
+ expect(answer.status, search).toBe(400);
+ expect(answer.headers.location).toBeUndefined();
+ expect(Object.keys(answer.headers).filter((name) => name.startsWith("access-control-"))).toEqual([]);
+ expect(answer.text).not.toContain("evil.example");
+ expect(answer.headers["cache-control"]).toBe("no-store");
+ expect(answer.headers["content-security-policy"]).toContain("default-src 'none'");
+ }
+ // A site that guesses the path gets nothing done, and the real answer still works afterwards.
+ const real = await get(back.pathname + back.search, "GET", { origin: "https://evil.example" });
+ expect(real.status).toBe(200);
+ expect(real.headers.location).toBeUndefined();
+ expect(Object.keys(real.headers).filter((name) => name.startsWith("access-control-"))).toEqual([]);
+ expect((await get("/api/boat/oauth/callback/extra")).status).toBe(418);
+ });
+
+ it("only the desktop app's own page on this computer may start, cancel or disconnect", async () => {
+ make();
+ const strangers: Array<[string, RequestAuth, Record<string, string>]> = [
+ ["a shared server's local caller", { kind: "loopback", scopes: [], trust: "service" } as unknown as RequestAuth, {}],
+ ["a paired phone", { kind: "loopback", scopes: [], companionDevice: "phone-1" } as unknown as RequestAuth, {}],
+ ["a companion request", owner, { "x-openmausbot-companion": "1" }],
+ ["a signed-in session", { kind: "session", scopes: ["admin", "client"], session: {} } as unknown as RequestAuth, {}],
+ ];
+ for (const [who, auth, headers] of strangers) {
+ for (const [method, path] of [["POST", "/api/boat/sign-in/start"], ["POST", "/api/boat/sign-in/cancel"], ["DELETE", "/api/boat/sign-in"]]) {
+ expect((await call(method!, path!, auth, headers)).status, `${who} ${path}`).toBe(403);
+ }
+ }
+ expect((await call("GET", "/api/boat/sign-in/start")).status).toBe(404);
+ expect((await call("GET", "/api/config")).status).toBe(0);
+ });
+
+ it("is not offered on a self-hosted server, a hosted Cloud or any other port: paste a key only", async () => {
+ for (const more of [{ desktop: false }, { hosted: true }, { port: 5199 }, { port: 8800 }]) {
+ make(more);
+ expect(host.statusPart(), JSON.stringify(more)).toEqual({ keySaved: false });
+ expect((await call("POST", "/api/boat/sign-in/start")).status).toBe(403);
+ expect((await get(`${BOAT_SIGN_IN_CALLBACK_PATH}?code=a&state=b`)).status).toBe(404);
+ expect(host.signIn.used(false)).toBe(false);
+ }
+ for (const port of BOAT_SIGN_IN_PORTS) expect(make({ port }).statusPart().signIn?.available).toBe(true);
+ });
+
+ it("cancelling in the app spends the link", async () => {
+ make();
+ const started = await call("POST", "/api/boat/sign-in/start");
+ expect(host.statusPart().signIn?.pending).toBe(true);
+ expect((await call("POST", "/api/boat/sign-in/cancel")).status).toBe(200);
+ expect(host.statusPart().signIn?.pending).toBeUndefined();
+ const back = new URL(fake.approve(started.body.url));
+ expect((await get(back.pathname + back.search)).status).toBe(400);
+ });
+
+ it("does not connect while a cloud computer is busy or another account change is under way", async () => {
+ let conflict: string | null = "stop active bot work and computer control before changing the Boat account";
+ make({ operationConflict: () => conflict });
+ let back = new URL(fake.approve((await call("POST", "/api/boat/sign-in/start")).body.url));
+ let page = await get(back.pathname + back.search);
+ expect(page.status).toBe(400);
+ expect(page.text).toContain("stop active bot work");
+ expect(host.statusPart().signIn).toMatchObject({ state: "none", last: { outcome: "refused" } });
+ // What Boat issued for the refused sign-in was given back.
+ expect(fake.counts.revoke).toBe(1);
+
+ conflict = null;
+ transitions.add("box");
+ back = new URL(fake.approve((await call("POST", "/api/boat/sign-in/start")).body.url));
+ page = await get(back.pathname + back.search);
+ expect(page.status).toBe(400);
+ expect(transitions.has("box")).toBe(true);
+ transitions.clear();
+ back = new URL(fake.approve((await call("POST", "/api/boat/sign-in/start")).body.url));
+ expect((await get(back.pathname + back.search)).status).toBe(200);
+ expect(transitions.size).toBe(0);
+ });
+});
diff --git a/server/testing/fake-boat-oauth.ts b/server/testing/fake-boat-oauth.ts
new file mode 100644
index 0000000000..38e5f2d8f7
--- /dev/null
+++ b/server/testing/fake-boat-oauth.ts
@@ -0,0 +1,166 @@
+// A stand-in for Boat's OAuth and the few API routes the sign-in tests call, on a loopback port: authorization codes that
+// work once with PKCE, refresh tokens that rotate (the old access token dies at once, a lost answer is repeated for one
+// minute, an old refresh token seen after that ends the connection), revoke, scopes the person may untick, and
+// `org_required`. Time is the test's own clock. Nothing here talks to boat.dev.
+import { createHash, randomBytes } from "node:crypto";
+import { createServer, type IncomingMessage, type ServerResponse } from "node:http";
+import type { AddressInfo } from "node:net";
+
+interface Grant {
+ id: number;
+ scopes: string[];
+ refresh: string;
+ access: string;
+ /** The refresh token this one replaced, the answer given for it, and when. */
+ previous?: { refresh: string; answer: Record<string, unknown>; at: number };
+ ended: boolean;
+}
+
+export interface FakeBoat {
+ /** `…/api/v1`: what OMB_BOAT_API points at. */
+ api: string;
+ origin: string;
+ clientId: string;
+ /** What the person does on Boat's screen: the address Boat sends the browser back to. */
+ approve(authorizeUrl: string, choice?: { deny?: boolean; scopes?: string[] }): string;
+ advance(ms: number): void;
+ /** The next refresh rotates the tokens, then the answer is lost on the way back. */
+ loseNextRefreshAnswer(): void;
+ /** Refresh answers wait until the returned function is called. */
+ holdRefreshes(): () => void;
+ /** Every refresh fails as `invalid_grant` from now on, as after a disconnect in Boat's dashboard. */
+ disconnect(): void;
+ requireOrg(on: boolean): void;
+ counts: { token: number; refresh: number; revoke: number; api: number };
+ /** Every bearer the API routes were called with, in order. */
+ bearers: string[];
+ liveConnections(): number;
+ close(): Promise<void>;
+}
+
+const body = (req: IncomingMessage) => new Promise<string>((done) => {
+ let text = "";
+ req.on("data", (chunk) => { text += chunk; });
+ req.on("end", () => done(text));
+});
+
+export async function startFakeBoat(clientId: string, redirectUris: string[]): Promise<FakeBoat> {
+ let now = 0;
+ let nextId = 1;
+ const codes = new Map<string, { challenge: string; redirectUri: string; scopes: string[]; used: boolean }>();
+ const grants: Grant[] = [];
+ let loseNext = false;
+ let held: Promise<void> | null = null;
+ let orgRequired = false;
+ const counts = { token: 0, refresh: 0, revoke: 0, api: 0 };
+ const bearers: string[] = [];
+ const mint = (prefix: string) => `${prefix}${randomBytes(24).toString("base64url")}`;
+ const json = (res: ServerResponse, status: number, value: unknown) => {
+ res.writeHead(status, { "content-type": "application/json" });
+ res.end(JSON.stringify(value));
+ };
+ const answerFor = (grant: Grant) => ({ access_token: grant.access, token_type: "Bearer", expires_in: 3600, refresh_token: grant.refresh, scope: grant.scopes.join(" ") });
+
+ const server = createServer(async (req, res) => {
+ const url = new URL(req.url ?? "/", "http://fake");
+ if (req.method === "POST" && url.pathname === "/api/boat/oauth2/token") {
+ counts.token += 1;
+ const form = new URLSearchParams(await body(req));
+ if (form.get("client_id") !== clientId) return json(res, 401, { error: "invalid_client" });
+ if (form.get("grant_type") === "authorization_code") {
+ const code = codes.get(form.get("code") ?? "");
+ const verifier = form.get("code_verifier") ?? "";
+ if (!code || code.used || code.redirectUri !== form.get("redirect_uri") || createHash("sha256").update(verifier).digest("base64url") !== code.challenge) {
+ return json(res, 400, { error: "invalid_grant", error_description: "The code is wrong, expired or used." });
+ }
+ code.used = true;
+ const grant: Grant = { id: nextId++, scopes: code.scopes, refresh: mint("boatrt_"), access: mint("boat_"), ended: false };
+ grants.push(grant);
+ return json(res, 200, answerFor(grant));
+ }
+ if (form.get("grant_type") === "refresh_token") {
+ counts.refresh += 1;
+ if (held) await held;
+ const sent = form.get("refresh_token") ?? "";
+ const grant = grants.find((one) => one.refresh === sent || one.previous?.refresh === sent);
+ if (!grant || grant.ended) return json(res, 400, { error: "invalid_grant" });
+ if (grant.previous?.refresh === sent) {
+ // The lost answer, repeated within the minute; after it, the old token ends the connection.
+ if (now - grant.previous.at <= 60_000) return json(res, 200, grant.previous.answer);
+ grant.ended = true;
+ return json(res, 400, { error: "invalid_grant" });
+ }
+ const previous = grant.refresh;
+ grant.refresh = mint("boatrt_");
+ grant.access = mint("boat_");
+ const answer = answerFor(grant);
+ grant.previous = { refresh: previous, answer, at: now };
+ if (loseNext) {
+ loseNext = false;
+ res.destroy();
+ return;
+ }
+ return json(res, 200, answer);
+ }
+ return json(res, 400, { error: "unsupported_grant_type" });
+ }
+ if (req.method === "POST" && url.pathname === "/api/boat/oauth2/revoke") {
+ counts.revoke += 1;
+ const token = new URLSearchParams(await body(req)).get("token") ?? "";
+ const grant = grants.find((one) => one.refresh === token || one.access === token);
+ // Revoke gives up the product's access to the account: every connection of this client ends.
+ if (grant) for (const one of grants) one.ended = true;
+ return json(res, 200, {});
+ }
+ if (url.pathname.startsWith("/api/v1/")) {
+ counts.api += 1;
+ const bearer = /^Bearer (.+)$/.exec(req.headers.authorization ?? "")?.[1] ?? "";
+ bearers.push(bearer);
+ const grant = grants.find((one) => one.access === bearer && !one.ended);
+ if (!grant) return json(res, 401, { ok: false, error: "unauthorized", message: "Invalid token" });
+ const needs = url.pathname === "/api/v1/me" ? "account.read" : req.method === "POST" ? "sandbox.create" : "sandbox.read";
+ if (!grant.scopes.includes(needs)) return json(res, 403, { ok: false, error: "api_key_action_forbidden", message: "The action is not on the key" });
+ if (orgRequired && !url.searchParams.get("org") && !req.headers["x-boat-org"]) return json(res, 400, { ok: false, error: "org_required", message: "Name an organization" });
+ if (url.pathname === "/api/v1/me") return json(res, 200, { ok: true, type: "user.info", user: { login: "maya-shah", email: "[email protected]" } });
+ return json(res, 200, { ok: true, sandboxes: [] });
+ }
+ json(res, 404, { error: "not_found" });
+ });
+ await new Promise<void>((done) => server.listen(0, "127.0.0.1", done));
+ const origin = `http://127.0.0.1:${(server.address() as AddressInfo).port}`;
+
+ return {
+ api: `${origin}/api/v1`, origin, clientId, counts, bearers,
+ approve(authorizeUrl, choice = {}) {
+ const url = new URL(authorizeUrl);
+ const params = url.searchParams;
+ const redirectUri = params.get("redirect_uri") ?? "";
+ if (url.origin !== origin || url.pathname !== "/api/boat/oauth2/authorize" || params.get("response_type") !== "code" || params.get("client_id") !== clientId
+ || !redirectUris.includes(redirectUri) || params.get("code_challenge_method") !== "S256" || !params.get("code_challenge") || !params.get("state")) {
+ throw new Error("fake Boat: not an authorize address it accepts");
+ }
+ const back = new URL(redirectUri);
+ back.searchParams.set("state", params.get("state")!);
+ back.searchParams.set("iss", origin);
+ if (choice.deny) {
+ back.searchParams.set("error", "access_denied");
+ return back.href;
+ }
+ const code = randomBytes(16).toString("base64url");
+ codes.set(code, { challenge: params.get("code_challenge")!, redirectUri, scopes: choice.scopes ?? (params.get("scope") ?? "").split(" ").filter(Boolean), used: false });
+ back.searchParams.set("code", code);
+ return back.href;
+ },
+ advance(ms) { now += ms; },
+ loseNextRefreshAnswer() { loseNext = true; },
+ holdRefreshes() {
+ let release!: () => void;
+ held = new Promise<void>((done) => { release = done; });
+ return () => { held = null; release(); };
+ },
+ disconnect() { for (const grant of grants) grant.ended = true; },
+ requireOrg(on) { orgRequired = on; },
+ liveConnections: () => grants.filter((grant) => !grant.ended).length,
+ close: () => new Promise<void>((done) => { server.closeAllConnections(); server.close(() => done()); }),
+ };
+}