Skip to content

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

5.9 KB
Raw Blame
// The one place a Boat API call gets its bearer. A pasted key and the plan's included token are sent as they are; a
// "Sign in with Boat" connection gives a current access token (renewed by one caller at a time, server/boat-sign-in.ts),
// and what Boat refuses a sign-in for is put in the person's words here, so no caller reads it as a rejected API key.
import { BOAT_SIGN_IN_MARK } from "../shared/boat-sign-in.ts";
import { relayPath } from "./boat-relay.ts";
import { BOAT_SIGN_IN_PROBLEM, BoatSignInError, type BoatScope } from "./boat-sign-in.ts";
import { boatSignIn } from "./boat-sign-in-use.ts";
import { boatProviderApi, type ServiceCredential } from "./included-services.ts";

const SETTINGS = "Settings → AI → Other services";
const AGAIN = `Sign in to Boat again in ${SETTINGS} and keep it ticked, or paste an API key there`;

/** What each scope the app asks for is used for (the PR lists why each is needed). */
export const BOAT_SCOPE_USE: Record<BoatScope, string> = {
  "account.read": "show which Boat account is signed in",
  "sandbox.read": "see your cloud computers",
  "sandbox.create": "create a cloud computer",
  "sandbox.resume": "wake a cloud computer",
  "sandbox.stop": "stop a cloud computer",
  "sandbox.update": "name a cloud computer and set when it stops by itself",
  "sandbox.delete": "delete a cloud computer",
  exec: "run commands on a cloud computer",
  "file.read": "read files and the screen of a cloud computer",
  "file.write": "copy files to a cloud computer",
  desktop: "show a cloud computer's desktop",
};

export const boatScopeRefusal = (scope: BoatScope): string =>
  `Your Boat account sign-in does not let this app ${BOAT_SCOPE_USE[scope]}: "${scope}" was not allowed. ${AGAIN}`;

const refusal = (status: number, error: string, message: string): Response =>
  new Response(JSON.stringify({ ok: false, error, message, boatSignIn: true }), { status, headers: { "content-type": "application/json" } });

function words(status: number, code: string, method: string, scope: BoatScope | null): string | null {
  if (status === 400) {
    return code === "org_required"
      ? `Your Boat account sign-in covers several organizations and none of them is your default. Sign in to Boat again in ${SETTINGS} and tick one organization only on that screen, or set a default organization in boat.dev`
      : null;
  }
  if (status === 401) return BOAT_SIGN_IN_PROBLEM["needs-sign-in"];
  if (code === "api_key_sandbox_forbidden") {
    return `Your Boat account sign-in does not reach this cloud computer: its organization or environment was not ticked when you signed in. Sign in to Boat again in ${SETTINGS} and tick it, or paste an API key there`;
  }
  if (method === "DELETE") {
    return `boat.dev did not let your Boat account sign-in delete this cloud computer. Sign in to Boat again in ${SETTINGS} and keep "sandbox.delete" ticked, or delete it in boat.dev`;
  }
  if (scope) return boatScopeRefusal(scope);
  return `boat.dev refused this for your Boat account sign-in. ${AGAIN}`;
}

/** Boat's refusal of a sign-in, with the same status and body plus `message` in plain words and `boatSignIn: true`. */
async function explained(response: Response, method: string, path: string): Promise<Response> {
  let body: any = null;
  try { body = await response.json(); } catch { /* no JSON: read by its status */ }
  const found = typeof body?.error === "string" ? body.error : body?.error?.code ?? body?.code;
  const code = typeof found === "string" ? found : "";
  const message = words(response.status, code, method, boatSignIn()?.scopeOf(method, path) ?? null);
  const next = message ? { ...(body && typeof body === "object" ? body : {}), message, boatSignIn: true } : body;
  return new Response(JSON.stringify(next), { status: response.status, statusText: response.statusText, headers: { "content-type": "application/json" } });
}

/** The words for a refused sign-in call, when `body` is one; else null and the caller's own words apply. */
export const boatSignInWords = (body: any): string | null =>
  body?.boatSignIn === true && typeof body.message === "string" ? body.message : null;

/** An own token goes to Boat; Cloud Pro's included token only to its relay. */
export async function boatCall(account: ServiceCredential | null, path: string, opts: RequestInit = {}): Promise<Response> {
  const url = `${account?.api ?? boatProviderApi()}${relayPath(account, path)}`;
  const send = (bearer: string | undefined) => fetch(url, {
    ...opts,
    headers: { authorization: `Bearer ${bearer}`, "content-type": "application/json", ...opts.headers },
  });
  if (account?.token !== BOAT_SIGN_IN_MARK) return send(account?.token);

  const signIn = boatSignIn();
  if (!signIn) return refusal(401, "boat_sign_in_ended", BOAT_SIGN_IN_PROBLEM["signed-out"]);
  const method = (opts.method ?? "GET").toUpperCase();
  const missing = signIn.missingScope(method, path);
  // Not sent: Boat would refuse it, and the person is told which permission is missing.
  if (missing) return refusal(403, "api_key_action_forbidden", boatScopeRefusal(missing));
  let bearer: string;
  try {
    bearer = await signIn.accessToken();
  } catch (error) {
    if (error instanceof BoatSignInError && (error.problem === "needs-sign-in" || error.problem === "signed-out")) {
      return refusal(401, "boat_sign_in_ended", error.message);
    }
    // Not reached or not saved: like a network failure, the call did not happen and may be tried again.
    throw error instanceof BoatSignInError ? new Error(error.message) : error;
  }
  let response = await send(bearer);
  if (response.status === 401 && (opts.body === undefined || opts.body === null || typeof opts.body === "string")) {
    const renewed = await signIn.afterRefusal(bearer);
    if (renewed) {
      void response.body?.cancel().catch(() => undefined);
      response = await send(renewed);
    }
  }
  return response.status === 400 || response.status === 401 || response.status === 403 ? explained(response, method, path) : response;
}