Skip to content

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

8.8 KB
Raw Blame
// 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[], apiKeys: 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/box/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/box/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);
      // A pasted API key of the same account: every action.
      if (apiKeys.includes(bearer)) return json(res, 200, url.pathname === "/api/v1/me" ? { ok: true, user: { login: "maya-shah" } } : { ok: true, sandboxes: [] });
      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" : req.method === "DELETE" ? "sandbox.delete" : "sandbox.read";
      // A grant with only "sandbox.delete-own" deletes what it created; the fake has no such computer, so it refuses.
      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/box/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()); }),
  };
}