Skip to content

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

2.3 KB
Raw Blame
// "Sign in with Boat" as the page sees it: a status from the server's config and three requests. The page never holds a
// token and never calls Boat; it only opens Boat's own sign-in page in the person's browser.
import { BOAT_SIGN_IN_PORTS, type BoatSignInStatus } from "../../shared/boat-sign-in";
import { openExternalLink } from "@/lib/app-links";
import { api } from "@/state/api";
import type { ConfigStatus } from "@/state/store";

const LOCAL_HOSTS = ["127.0.0.1", "localhost"];

/** Offered only on the desktop app's own page (one of its three local ports) and only where the server offers it; a
 * hosted Cloud, a self-hosted server and a page reached from another device show the key field alone. */
export function boatSignInShown(
  config: Pick<ConfigStatus, "box"> | null | undefined,
  page: Pick<Location, "hostname" | "port"> | undefined = typeof window === "undefined" ? undefined : window.location,
): BoatSignInStatus | null {
  const status = config?.box?.signIn;
  // No page (a server-side render): nothing is offered.
  if (!page || !status?.available || config?.box?.included) return null;
  return LOCAL_HOSTS.includes(page.hostname) && BOAT_SIGN_IN_PORTS.includes(Number(page.port)) ? status : null;
}

/** Only Boat's own authorize page is ever opened (a loopback stand-in in development): anything else the server says is not. */
export function isBoatSignInUrl(value: unknown): value is string {
  if (typeof value !== "string") return false;
  let url: URL;
  try { url = new URL(value); } catch { return false; }
  const boat = url.protocol === "https:" && url.hostname === "boat.dev" && url.port === "";
  const standIn = url.protocol === "http:" && LOCAL_HOSTS.includes(url.hostname);
  return (boat || standIn) && url.username === "" && url.password === "" && url.pathname === "/api/box/oauth2/authorize" && url.hash === "";
}

export async function startBoatSignIn(): Promise<void> {
  const answer = await api<{ url?: unknown }>("/api/boat/sign-in/start", { method: "POST" });
  if (!isBoatSignInUrl(answer.url)) throw new Error("not the sign-in page");
  await openExternalLink(answer.url);
}

export const cancelBoatSignIn = (): Promise<unknown> => api("/api/boat/sign-in/cancel", { method: "POST" });

export const disconnectBoat = (): Promise<unknown> => api("/api/boat/sign-in", { method: "DELETE" });