Skip to content

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

12.6 KB
Raw Blame
// How an owner-only page opens. No reusable secret ever sits in an address bar:
// - The page's address is its stable link, /api/published-pages/<id>/. It answers only the owner: a request the sign-in
//   gate vouches for (an admin session, or this computer's own app), or a browser holding the page's own cookie.
// - That cookie comes from a one-time code. The owner's app asks for one (POST .../open) and opens the stable link with
//   `?omb_page_code=` in a browser; the code is spent on first use, two minutes at most, and the answer moves the browser to the
//   link without it. The cookie is HttpOnly, scoped to that page's path, and answers only while the page is still
//   owner-only and the session that asked for it is still signed in.
// - The page runs in an opaque-origin sandbox, which sends no cookie with its own files, so its relative URLs resolve to
//   a token folder (/api/owner-page-files/<token>/) through a <base> written ahead of the page. That token lives only in
//   the page's markup: opening a token URL as a page moves the browser back to the stable link, and the files answer
//   cross-origin reads only to the sandbox's own (null) origin.
import { randomBytes } from "node:crypto";
import type { IncomingMessage, ServerResponse } from "node:http";
import { extname } from "node:path";
import { stripDocumentPreamble } from "../../shared/app-frame/document.ts";
import { BOT_HTML_CSP } from "../../shared/app-frame/csp.ts";
import { PAGE_FILE_TYPES } from "../../shared/published-page.ts";
import { pageFilePath } from "../page-files.ts";
import { requestOrigin } from "../request-auth.ts";
import type { PublishedPageFiles } from "./owner-files.ts";

export const OWNER_PAGE_FILES_PREFIX = "/api/owner-page-files/";
export const OWNER_PAGE_PREFIX = "/api/published-pages/";
export const OWNER_PAGE_COOKIE = "omb_owner_page";
/** The one-time code's query name: one a page is unlikely to use for itself. */
export const OWNER_PAGE_CODE = "omb_page_code";
const OWNER_PAGE_PATH = /^\/api\/published-pages\/([a-z0-9]{20,63})(\/.*)?$/;
const TOKEN = /^[A-Za-z0-9_-]{43}$/;
const DAY_MS = 24 * 60 * 60_000;
const CODE_MS = 2 * 60_000;
const MAX_TOKENS = 2_000;
const MAX_CODES = 200;

/** An owner-only page opened directly: its own files load, inline code runs, and it stays in an opaque origin, so it can
 * reach neither the app's cookies nor its API. */
export function ownerPageCsp(origin: string): string {
  return BOT_HTML_CSP.split("; ").map((directive) => {
    if (/^(script|style|font|img|media|connect|worker)-src /.test(directive)) return `${directive} ${origin}`;
    // The page's relative URLs resolve to its token folder through the <base> written ahead of it.
    if (directive === "base-uri 'none'") return `base-uri ${origin}${OWNER_PAGE_FILES_PREFIX}`;
    return directive === "default-src 'none'" ? `default-src ${origin}` : directive;
  }).join("; ").concat("; sandbox allow-scripts allow-forms allow-modals allow-downloads allow-top-navigation-by-user-activation");
}

/** Who a page was opened for: `key` names them, and `allowed()` is asked again on every request. */
export interface OwnerPageViewer {
  key: string;
  allowed(): boolean;
}

type Grant = { pageId: string; viewer: string; allowed: () => boolean; used: number };

function cookieValue(req: IncomingMessage, name: string): string | undefined {
  const header = req.headers.cookie;
  if (!header) return undefined;
  for (const part of header.split(";")) {
    const at = part.indexOf("=");
    if (at > 0 && part.slice(0, at).trim() === name) return part.slice(at + 1).trim();
  }
  return undefined;
}

const escapeAttribute = (value: string) => value.replace(/&/g, "&amp;").replace(/"/g, "&quot;").replace(/</g, "&lt;").replace(/>/g, "&gt;");

export function createOwnerPageLinks(deps: {
  files: Pick<PublishedPageFiles, "read">;
  /** True while the page is still an owner-only page this server keeps. */
  ownerPage(pageId: string): boolean;
  /** The address this server answers at, for the link an open code is sent with; a path alone when null. */
  pageOrigin?(): string | null;
  now?(): number;
}) {
  const now = deps.now ?? Date.now;
  /** Token folders the page's files load from, and the page cookies; both keyed by a random 32-byte token. */
  const folders = new Map<string, Grant>(), cookies = new Map<string, Grant>(), codes = new Map<string, Grant>();
  const byViewer = new Map<string, string>();
  const keyOf = (pageId: string, viewer: string) => `${pageId}\n${viewer}`;
  const token = () => randomBytes(32).toString("base64url");
  const live = (grant: Grant | undefined, pageId: string | undefined, ttl: number): grant is Grant =>
    Boolean(grant) && grant!.pageId === (pageId ?? grant!.pageId) && now() - grant!.used <= ttl && grant!.allowed() && deps.ownerPage(grant!.pageId);
  const sweep = (map: Map<string, Grant>, ttl: number, max: number) => {
    const at = now();
    for (const [key, grant] of map) if (at - grant.used > ttl) {
      map.delete(key);
      if (map === folders) byViewer.delete(keyOf(grant.pageId, grant.viewer));
    }
    while (map.size >= max) {
      const oldest = map.keys().next().value!;
      const grant = map.get(oldest)!;
      map.delete(oldest);
      if (map === folders) byViewer.delete(keyOf(grant.pageId, grant.viewer));
    }
  };
  const answer = (res: ServerResponse, status: number, text: string, headers: Record<string, string> = {}) => {
    res.writeHead(status, { "content-type": "text/plain; charset=utf-8", "cache-control": "private, no-store", "x-content-type-options": "nosniff", ...headers });
    res.end(text);
  };
  const redirect = (res: ServerResponse, status: number, location: string, headers: Record<string, string> = {}) => {
    res.writeHead(status, { location, "cache-control": "private, no-store", "referrer-policy": "no-referrer", ...headers });
    res.end();
  };

  /** The token folder this viewer's copy of the page loads its files from; the same token while it is in use. */
  function folder(pageId: string, viewer: OwnerPageViewer): string {
    const existing = byViewer.get(keyOf(pageId, viewer.key));
    const known = existing ? folders.get(existing) : undefined;
    if (existing && known) {
      known.used = now();
      known.allowed = viewer.allowed;
      return `${OWNER_PAGE_FILES_PREFIX}${existing}/`;
    }
    sweep(folders, DAY_MS, MAX_TOKENS);
    const minted = token();
    folders.set(minted, { pageId, viewer: viewer.key, allowed: viewer.allowed, used: now() });
    byViewer.set(keyOf(pageId, viewer.key), minted);
    return `${OWNER_PAGE_FILES_PREFIX}${minted}/`;
  }

  /** One file of the page at its stable link. An HTML file's relative URLs resolve to the viewer's token folder. */
  function servePage(req: IncomingMessage, res: ServerResponse, method: string, pageId: string, rest: string | undefined, search: string, viewer: OwnerPageViewer): void {
    const base = `${OWNER_PAGE_PREFIX}${pageId}`;
    if (rest === undefined) return redirect(res, 308, `${base}/${search}`);
    const raw = rest.slice(1);
    const file = pageFilePath(raw === "" || raw.endsWith("/") ? `${raw}index.html` : raw);
    if (file === null) return answer(res, 400, "Not a file of this page.");
    const body = deps.files.read(pageId, file);
    if (!body) return answer(res, 404, "Not found.");
    const extension = extname(file).slice(1).toLowerCase();
    const headers = {
      "content-security-policy": ownerPageCsp(requestOrigin(req) ?? "http://127.0.0.1"),
      "x-content-type-options": "nosniff",
      "referrer-policy": "no-referrer",
      "cache-control": "private, no-store",
    };
    let sent = body;
    if (extension === "html" || extension === "htm") {
      const dir = file.includes("/") ? `${file.slice(0, file.lastIndexOf("/")).split("/").map(encodeURIComponent).join("/")}/` : "";
      sent = Buffer.from(`<!DOCTYPE html><base href="${escapeAttribute(`${folder(pageId, viewer)}${dir}`)}">${stripDocumentPreamble(body.toString("utf8"))}`);
    }
    res.writeHead(200, { ...headers, "content-type": PAGE_FILE_TYPES[extension] ?? "application/octet-stream", "content-length": String(sent.byteLength) });
    res.end(method === "HEAD" ? undefined : sent);
  }

  return {
    folder,
    servePage,

    /** A one-time code that opens the page in a browser: spent on first use, and good for two minutes. */
    openUrl(pageId: string, viewer: OwnerPageViewer): string {
      sweep(codes, CODE_MS, MAX_CODES);
      const code = token();
      codes.set(code, { pageId, viewer: viewer.key, allowed: viewer.allowed, used: now() });
      return `${(deps.pageOrigin?.() ?? "").replace(/\/+$/, "")}${OWNER_PAGE_PREFIX}${pageId}/?${OWNER_PAGE_CODE}=${code}`;
    },

    /** Ahead of the sign-in gate: the token folders, a code being spent, and the stable link for a browser holding the
     * page's cookie. False leaves the request to the gate and the route (a signed-in owner). */
    serve(req: IncomingMessage, res: ServerResponse, path: string, method: string): boolean {
      const search = (() => { const at = req.url?.indexOf("?") ?? -1; return at >= 0 ? req.url!.slice(at) : ""; })();
      if (path.startsWith(OWNER_PAGE_FILES_PREFIX)) {
        const rest = path.slice(OWNER_PAGE_FILES_PREFIX.length), slash = rest.indexOf("/");
        const key = slash === -1 ? rest : rest.slice(0, slash);
        if (method !== "GET" && method !== "HEAD") {
          answer(res, 405, "Read only.");
          return true;
        }
        const grant = TOKEN.test(key) ? folders.get(key) : undefined;
        if (!live(grant, undefined, DAY_MS) || slash === -1) {
          answer(res, 404, "Not found.");
          return true;
        }
        // Opened as a page (a link the page followed, or a pasted URL): back to the stable link, which asks who it is.
        if (req.headers["sec-fetch-mode"] === "navigate" && req.headers["sec-fetch-dest"] === "document") {
          redirect(res, 303, `${OWNER_PAGE_PREFIX}${grant.pageId}/${rest.slice(slash + 1)}${search}`);
          return true;
        }
        grant.used = now();
        const file = pageFilePath(rest.slice(slash + 1));
        if (file === null) {
          answer(res, 400, "Not a file of this page.");
          return true;
        }
        const body = deps.files.read(grant.pageId, file);
        if (!body) {
          answer(res, 404, "Not found.");
          return true;
        }
        // Only the page's own sandbox (an opaque, "null" origin) may read a file across origins, never any site.
        const sandboxed = req.headers.origin === "null";
        res.writeHead(200, {
          "content-type": PAGE_FILE_TYPES[extname(file).slice(1).toLowerCase()] ?? "application/octet-stream",
          "content-length": String(body.byteLength),
          "content-security-policy": ownerPageCsp(requestOrigin(req) ?? "http://127.0.0.1"),
          "x-content-type-options": "nosniff",
          "referrer-policy": "no-referrer",
          "cache-control": "private, no-store",
          vary: "origin",
          ...(sandboxed ? { "access-control-allow-origin": "null" } : {}),
        });
        res.end(method === "HEAD" ? undefined : body);
        return true;
      }
      const page = OWNER_PAGE_PATH.exec(path);
      if (!page || (method !== "GET" && method !== "HEAD") || !deps.ownerPage(page[1]!)) return false;
      const pageId = page[1]!;
      const params = new URLSearchParams(search);
      const code = params.get(OWNER_PAGE_CODE);
      const granted = code === null ? undefined : codes.get(code);
      if (code !== null) codes.delete(code);
      // A spent or unknown code is ignored: the page's cookie, or the owner's sign-in at the gate, may still open it.
      if (code !== null && live(granted, pageId, CODE_MS)) {
        const grant = granted;
        sweep(cookies, DAY_MS, MAX_TOKENS);
        const cookie = token();
        cookies.set(cookie, { ...grant, used: now() });
        params.delete(OWNER_PAGE_CODE);
        const rest = params.toString();
        const secure = requestOrigin(req)?.startsWith("https://") === true;
        redirect(res, 303, `${OWNER_PAGE_PREFIX}${pageId}${page[2] ?? "/"}${rest ? `?${rest}` : ""}`, {
          "set-cookie": [`${OWNER_PAGE_COOKIE}=${cookie}`, `Path=${OWNER_PAGE_PREFIX}${pageId}/`, "HttpOnly", "SameSite=Lax", `Max-Age=${DAY_MS / 1000}`, ...(secure ? ["Secure"] : [])].join("; "),
        });
        return true;
      }
      const held = cookieValue(req, OWNER_PAGE_COOKIE);
      const grant = held && TOKEN.test(held) ? cookies.get(held) : undefined;
      if (!live(grant, pageId, DAY_MS)) return false;
      grant.used = now();
      servePage(req, res, method, pageId, page[2], search, { key: `cookie:${held}`, allowed: () => live(cookies.get(held!), pageId, DAY_MS) });
      return true;
    },
  };
}
export type OwnerPageLinks = ReturnType<typeof createOwnerPageLinks>;