Skip to content

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

7.7 KB
Raw Blame
// "Sign in with Boat" on this server: where it is offered, its three routes, the public callback Boat sends the browser
// back to, and what Settings is told. Offered only by the desktop app's own local server on one of the three ports
// registered with Boat, and never where cloud computers are included with a plan; everywhere else nothing here answers
// and a pasted API key is the only way, exactly as before.
import type { IncomingMessage, ServerResponse } from "node:http";

import { BOAT_SIGN_IN_MARK, type BoatSignInStatus } from "../shared/boat-sign-in.ts";
import { boatAccountChangeRefusal } from "./boat-account-change.ts";
import * as boat from "./boat.ts";
import { BOAT_SIGN_IN_CALLBACK_PATH, BOAT_SIGN_IN_PORTS, BoatSignIn } from "./boat-sign-in.ts";
import { createBoatSignInStore, type BoatSignInStoreRequest } from "./boat-sign-in-store.ts";
import { setBoatSignIn } from "./boat-sign-in-use.ts";
import type { AppConfig } from "./config.ts";
import { boatProviderApi } from "./included-services.ts";
import { fromPairedDevice, type RequestAuth } from "./request-auth.ts";
import { PASS, type RouteHandler } from "./routes/table.ts";

export interface BoatSignInHostDeps {
  /** The desktop app started this server (OMB_DESKTOP_PARENT). */
  desktop: boolean;
  /** A Cloud home or hosted workspace: cloud computers come with the plan, and the key field is hidden too. */
  hosted: boolean;
  /** The port this server really listens on. */
  port: number;
  dataDir: string;
  cfg: AppConfig;
  /** Reads the config again (the sign-in may now be, or no longer be, the credential in use) and tells every page. */
  refresh(): void;
  managedBoatOwners(): boat.ManagedBoatOwner[];
  /** A cloud computer operation is under way: its words, or null. */
  operationConflict(): string | null;
  /** Holds "box" while the Boat credential in use changes, so no cloud computer operation starts meanwhile. */
  transitions: Pick<Set<"box" | "vps">, "add" | "delete" | "has">;
  post(message: BoatSignInStoreRequest): boolean;
  env?: NodeJS.ProcessEnv;
}

export interface BoatSignInHost {
  signIn: BoatSignIn;
  /** For configStatus `box`, only where sign-in is offered: whether a key is saved, and the sign-in's state. Elsewhere
   * nothing, so that status is exactly what it was. */
  statusPart(): { keySaved?: boolean; signIn?: BoatSignInStatus };
  /** Answers Boat's redirect; false when the request is not that. Runs before the sign-in gate: the state is the credential. */
  callback(req: IncomingMessage, res: ServerResponse, url: URL): Promise<boolean>;
  routes: RouteHandler;
  receive(message: unknown): boolean;
}

const escapeHtml = (text: string) => text.replace(/[&<>"']/g, (char) => `&#${char.charCodeAt(0)};`);

/** A small fixed page: no script, no link, nothing from the request, and never the code or a token. */
function page(title: string, text: string): string {
  return `<!doctype html><html lang="en"><head><meta charset="utf-8"><meta name="viewport" content="width=device-width, initial-scale=1"><title>${escapeHtml(title)}</title>`
    + `<style>body{font:16px/1.5 system-ui,sans-serif;margin:15vh auto;max-width:28rem;padding:0 1.5rem;color:#1a1a1a;background:#fff}h1{font-size:1.25rem;margin:0 0 .5rem}p{margin:0;color:#555}@media(prefers-color-scheme:dark){body{color:#eee;background:#151515}p{color:#aaa}}</style>`
    + `</head><body><h1>${escapeHtml(title)}</h1><p>${escapeHtml(text)}</p></body></html>`;
}

const localOwner = (req: IncomingMessage, auth: RequestAuth): boolean =>
  auth.kind === "loopback" && auth.trust !== "service" && !fromPairedDevice(req, auth);

export function createBoatSignInHost(deps: BoatSignInHostDeps): BoatSignInHost {
  const enabled = deps.desktop && !deps.hosted && BOAT_SIGN_IN_PORTS.includes(deps.port);
  const store = createBoatSignInStore({ dataDir: deps.dataDir, post: deps.post, ...(deps.env ? { env: deps.env } : {}) });
  const keySaved = () => Boolean(deps.cfg.box?.token?.trim());
  const inUse = (): AppConfig | null => (boat.boatConfigured(deps.cfg) ? { box: { ...deps.cfg.box } } : null);

  const BUSY = "another change to the Boat account is under way — try again in a moment";
  /** The check and nothing else: the caller makes the change right after it. */
  const checked = async (check: () => Promise<string | null>): Promise<string | null> => {
    if (deps.transitions.has("box")) return BUSY;
    const conflict = deps.operationConflict();
    if (conflict) return conflict;
    deps.transitions.add("box");
    try {
      return await check();
    } finally {
      deps.transitions.delete("box");
    }
  };

  const signIn = new BoatSignIn({
    enabled,
    persistence: store.persistence,
    api: () => boatProviderApi(),
    onChange: () => deps.refresh(),
    // A raw bearer names the account being connected: it is checked like a replacement key, before anything is saved.
    beforeConnect: (bearer) => checked(() => boatAccountChangeRefusal(inUse(), { box: { token: bearer } }, deps.managedBoatOwners())),
  });
  setBoatSignIn(enabled ? signIn : null);

  return {
    signIn,
    statusPart: () => (enabled ? { keySaved: keySaved(), signIn: signIn.status(keySaved()) } : {}),
    receive: (message) => store.receive(message),
    async callback(req, res, url) {
      if (url.pathname !== BOAT_SIGN_IN_CALLBACK_PATH) return false;
      const headers = { "cache-control": "no-store", "referrer-policy": "no-referrer", "x-content-type-options": "nosniff", "content-security-policy": "default-src 'none'; style-src 'unsafe-inline'" };
      const answer = !enabled ? { status: 404, title: "Not found", text: "Nothing is here." }
        : req.method !== "GET" ? { status: 405, title: "Sign-in link not valid", text: "This sign-in link is not valid. Return to the app and start again." }
          : await signIn.callback(req.headers.host, url.search);
      res.writeHead(answer.status, { ...headers, "content-type": "text/html; charset=utf-8", ...(answer.status === 405 ? { allow: "GET" } : {}) });
      res.end(page(answer.title, answer.text));
      return true;
    },
    routes: async ({ req, res, path, method, auth, json }) => {
      if (!path.startsWith("/api/boat/sign-in")) return PASS;
      if (!enabled || !localOwner(req, auth)) return json(res, 403, { error: "Sign in with your Boat account from the desktop app on this computer; elsewhere, paste a Boat API key." });
      if (method === "POST" && path === "/api/boat/sign-in/start") {
        try {
          return json(res, 200, { url: signIn.start("owner", deps.port).url });
        } catch {
          return json(res, 503, { error: "Sign-in with a Boat account is not available here." });
        }
      }
      if (method === "POST" && path === "/api/boat/sign-in/cancel") {
        signIn.cancel("owner");
        return json(res, 200, { ok: true });
      }
      if (method === "DELETE" && path === "/api/boat/sign-in") {
        // Disconnecting changes the credential in use only when the sign-in is that credential.
        // A sign-in Boat has ended reaches nothing: it is only forgotten here, with nothing to check or revoke.
        const refusal = signIn.used(keySaved()) && signIn.status(keySaved()).state === "connected"
          ? await checked(() => boatAccountChangeRefusal({ box: { token: BOAT_SIGN_IN_MARK } }, keySaved() ? { box: { token: deps.cfg.box?.token } } : null, deps.managedBoatOwners()))
          : null;
        if (refusal) return json(res, 409, { error: refusal });
        try {
          const { revoked } = await signIn.signOut();
          return json(res, 200, { ok: true, revoked });
        } catch {
          return json(res, 503, { error: "The Boat account sign-in could not be removed from this computer. Try again." });
        }
      }
      return json(res, 404, { error: "not found" });
    },
  };
}