Skip to content

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

9.8 KB
Raw Blame
import type { IncomingMessage, ServerResponse } from "node:http";
import { mkdtempSync, rmSync } from "node:fs";
import { tmpdir } from "node:os";
import { join } from "node:path";
import { afterEach, beforeEach, describe, expect, it } from "vitest";
import { PublishedPageFiles } from "./owner-files.ts";
import { createOwnerPageLinks, OWNER_PAGE_CODE, OWNER_PAGE_COOKIE } from "./owner-links.ts";

const PAGE = "abcdefghijklmnopqrstuvwxyz";
const STABLE = `/api/published-pages/${PAGE}/`;
let dir: string;
let files: PublishedPageFiles;

beforeEach(() => {
  dir = mkdtempSync(join(tmpdir(), "omb-owner-links-"));
  files = new PublishedPageFiles(join(dir, "owner-pages"));
  files.save(PAGE, [
    { path: "index.html", data: Buffer.from("<!doctype html><h1>Traffic</h1><a href=\"more/notes.html\">notes</a>") },
    { path: "data.csv", data: Buffer.from("a,1") },
    { path: "more/notes.html", data: Buffer.from("<p>notes</p>") },
  ]);
});
afterEach(() => rmSync(dir, { recursive: true, force: true }));

function request(url = "/", headers: Record<string, string> = {}): IncomingMessage {
  // SAFETY: the routes read only the URL and headers.
  return { url, headers } as unknown as IncomingMessage;
}

function response() {
  const sent: { status?: number; headers?: Record<string, string>; body?: unknown } = {};
  const res = {
    writeHead: (status: number, headers: Record<string, string>) => { sent.status = status; sent.headers = headers; },
    end: (body?: unknown) => { sent.body = body; },
  } as unknown as ServerResponse;
  return { res, sent };
}

const OWNER = { key: "session:s1", allowed: () => true };
const linksFor = (options: { ownerPage?: () => boolean; now?: () => number } = {}) =>
  createOwnerPageLinks({ files, ownerPage: options.ownerPage ?? (() => true), pageOrigin: () => "https://cloud.example.test",
    ...(options.now ? { now: options.now } : {}) });

/** The stable link answered for a signed-in owner, as the route does after the sign-in gate. */
function page(links: ReturnType<typeof linksFor>, target = STABLE, viewer = OWNER, method = "GET") {
  const out = response();
  const url = new URL(target, "https://cloud.example.test");
  const rest = url.pathname.slice(`/api/published-pages/${PAGE}`.length);
  links.servePage(request(target, { host: "cloud.example.test", "x-forwarded-proto": "https" }), out.res, method, PAGE, rest === "" ? undefined : rest, url.search, viewer);
  return out.sent;
}

/** A request ahead of the sign-in gate: true when the links answered it. */
function early(links: ReturnType<typeof linksFor>, target: string, headers: Record<string, string> = {}, method = "GET") {
  const out = response();
  const handled = links.serve(request(target, headers), out.res, new URL(target, "http://x").pathname, method);
  return { handled, ...out.sent };
}

const baseOf = (html: unknown) => /<base href="([^"]+)">/.exec(String(html))?.[1];

describe("an owner-only page's stable link", () => {
  it("serves the page itself at its link, sandboxed and uncached, with its relative URLs on a token folder no address bar shows", () => {
    const sent = page(linksFor());
    expect(sent).toMatchObject({ status: 200, headers: { "content-type": "text/html; charset=utf-8", "cache-control": "private, no-store",
      "x-content-type-options": "nosniff", "referrer-policy": "no-referrer" } });
    expect(sent.headers).not.toHaveProperty("access-control-allow-origin");
    expect(String(sent.headers!["content-security-policy"])).toContain("sandbox allow-scripts");
    expect(String(sent.headers!["content-security-policy"])).toContain("https://cloud.example.test");
    expect(String(sent.headers!["content-security-policy"])).toContain("base-uri https://cloud.example.test/api/owner-page-files/;");
    expect(baseOf(sent.body)).toMatch(/^\/api\/owner-page-files\/[A-Za-z0-9_-]{43}\/$/);
    expect(String(sent.body)).toContain("<h1>Traffic</h1>");
    expect(String(sent.body)).not.toContain("<!doctype html><h1>");
    expect(baseOf(page(linksFor(), `${STABLE}more/notes.html`).body)).toMatch(/\/more\/$/);
  });

  it("moves a link without its trailing slash to the folder its files are relative to, keeping the query string", () => {
    expect(page(linksFor(), `/api/published-pages/${PAGE}?period=2026-11`)).toMatchObject({ status: 308,
      headers: { location: `${STABLE}?period=2026-11` } });
  });

  it("refuses a path a page cannot hold, and a missing file", () => {
    expect(page(linksFor(), `${STABLE}..%2Fsecret.txt`)).toMatchObject({ status: 400 });
    expect(page(linksFor(), `${STABLE}missing.css`)).toMatchObject({ status: 404 });
  });
});

describe("an owner-only page's token folder", () => {
  it("serves the page's files to its own sandbox only: the null origin may read them, no other origin is named", () => {
    const links = linksFor(), folder = baseOf(page(links).body)!;
    const sandbox = early(links, `${folder}data.csv`, { origin: "null", "sec-fetch-dest": "empty", "sec-fetch-mode": "cors" });
    expect(sandbox).toMatchObject({ handled: true, status: 200, headers: { "content-type": "text/csv; charset=utf-8", "access-control-allow-origin": "null", vary: "origin" } });
    expect(String(sandbox.body)).toBe("a,1");
    const site = early(links, `${folder}data.csv`, { origin: "https://evil.example" });
    expect(site.headers).not.toHaveProperty("access-control-allow-origin");
    expect(Object.values(site.headers!)).not.toContain("*");
  });

  it("sends a token URL opened as a page back to the stable link, so the token never stays in an address bar", () => {
    const links = linksFor(), folder = baseOf(page(links).body)!;
    expect(early(links, `${folder}more/notes.html?x=1`, { "sec-fetch-mode": "navigate", "sec-fetch-dest": "document" }))
      .toMatchObject({ handled: true, status: 303, headers: { location: `${STABLE}more/notes.html?x=1` } });
  });

  it("refuses a token whose page is gone, whose viewer may no longer see it, or that was never minted", () => {
    let allowed = true, owner = true;
    const links = linksFor({ ownerPage: () => owner });
    const folder = baseOf(page(links, STABLE, { key: "session:s1", allowed: () => allowed }).body)!;
    allowed = false;
    expect(early(links, `${folder}data.csv`)).toMatchObject({ status: 404 });
    allowed = true;
    expect(early(links, "/api/owner-page-files/not-a-token/index.html")).toMatchObject({ status: 404 });
    owner = false;
    expect(early(links, `${folder}data.csv`)).toMatchObject({ status: 404 });
    owner = true;
    expect(early(links, `${folder}..%2Fsecret.txt`)).toMatchObject({ status: 400 });
  });

  it("gives one viewer the same folder while it is in use, another its own, and forgets them after a day unused", () => {
    let now = 1_000;
    const links = linksFor({ now: () => now });
    const first = baseOf(page(links).body);
    expect(baseOf(page(links).body)).toBe(first);
    expect(baseOf(page(links, STABLE, { key: "session:s2", allowed: () => true }).body)).not.toBe(first);
    now += 24 * 60 * 60_000 + 1;
    expect(early(links, `${first}data.csv`)).toMatchObject({ status: 404, body: "Not found." });
  });
});

describe("opening an owner-only page in a browser that is not signed in", () => {
  const codeOf = (url: string) => new URL(url).searchParams.get(OWNER_PAGE_CODE)!;

  it("spends a one-time code for a page cookie, and moves the browser to the link without the code", () => {
    const links = linksFor();
    const url = links.openUrl(PAGE, OWNER);
    expect(url).toMatch(new RegExp(`^https://cloud\\.example\\.test${STABLE}\\?${OWNER_PAGE_CODE}=[A-Za-z0-9_-]{43}$`));
    const spent = early(links, `${STABLE}?${OWNER_PAGE_CODE}=${codeOf(url)}&period=2026-11`, { host: "cloud.example.test", "x-forwarded-proto": "https" });
    expect(spent).toMatchObject({ handled: true, status: 303, headers: { location: `${STABLE}?period=2026-11` } });
    const cookie = String(spent.headers!["set-cookie"]);
    expect(cookie).toMatch(new RegExp(`^${OWNER_PAGE_COOKIE}=[A-Za-z0-9_-]{43}; Path=${STABLE}; HttpOnly; SameSite=Lax; Max-Age=86400; Secure$`));
    expect(early(links, `${STABLE}?${OWNER_PAGE_CODE}=${codeOf(url)}`).handled, "a spent code leaves the request to the gate").toBe(false);

    const held = cookie.split(";")[0]!;
    const opened = early(links, STABLE, { cookie: `other=1; ${held}`, host: "cloud.example.test" });
    expect(opened).toMatchObject({ handled: true, status: 200 });
    expect(baseOf(opened.body)).toMatch(/^\/api\/owner-page-files\//);
  });

  it("leaves the gate to answer a browser with no code and no cookie, a cookie for nothing, or a page's own code query", () => {
    const links = linksFor();
    expect(early(links, STABLE).handled).toBe(false);
    expect(early(links, `${STABLE}?code=abc`).handled).toBe(false);
    expect(early(links, STABLE, { cookie: `${OWNER_PAGE_COOKIE}=${"a".repeat(43)}` }).handled).toBe(false);
  });

  it("expires an unspent code after two minutes, and a cookie when the session that asked for it ends", () => {
    let now = 1_000, live = true;
    const links = linksFor({ now: () => now });
    const stale = links.openUrl(PAGE, OWNER);
    now += 2 * 60_000 + 1;
    expect(early(links, `${STABLE}?${OWNER_PAGE_CODE}=${codeOf(stale)}`).handled).toBe(false);
    const fresh = links.openUrl(PAGE, { key: "session:s1", allowed: () => live });
    const cookie = String(early(links, `${STABLE}?${OWNER_PAGE_CODE}=${codeOf(fresh)}`).headers!["set-cookie"]).split(";")[0]!;
    expect(early(links, STABLE, { cookie }).handled).toBe(true);
    live = false;
    expect(early(links, STABLE, { cookie }).handled).toBe(false);
  });

  it("stops answering a cookie once the page is no longer owner-only", () => {
    let owner = true;
    const links = linksFor({ ownerPage: () => owner });
    const cookie = String(early(links, `${STABLE}?${OWNER_PAGE_CODE}=${codeOf(links.openUrl(PAGE, OWNER))}`).headers!["set-cookie"]).split(";")[0]!;
    owner = false;
    expect(early(links, STABLE, { cookie }).handled).toBe(false);
  });
});