Skip to content

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

9.7 KB
Raw Blame
import { join } from "node:path";
import { describe, expect, it, vi } from "vitest";
import type { PagePublisher } from "../pages/publisher.ts";
import type { RequestAuth } from "../request-auth.ts";
import { createPagesInternalRoutes, createPublishedPageRoutes, type OwnerPages, type PagesInternalContext } from "./published-pages.ts";
import { PASS, type RouteContext } from "./table.ts";

function fakePublisher() {
  return {
    publish: vi.fn(async () => ({ status: 200, text: "Published “Bake sale” at https://abcdefghijklmnopqrstuvwxyz.mausbot.page/" })),
    unpublish: vi.fn(async () => ({ status: 200, text: "Unpublished.", card: { state: "unpublished" as const, title: "Bake sale" } })),
    publishFiles: vi.fn(async () => ({ status: 200, text: "Published." })),
    refreshLive: vi.fn(async () => 0),
  } satisfies PagePublisher;
}

function sink() {
  const sent: { status?: number; body?: any } = {};
  const json = ((_res: unknown, status: number, body: unknown) => { sent.status = status; sent.body = body; }) as PagesInternalContext["json"];
  return { sent, json, res: {} as PagesInternalContext["res"] };
}

async function internal(handler: ReturnType<typeof createPagesInternalRoutes>, input: { path?: string; method?: string; body?: unknown; vmWorkspace?: string | null } = {}) {
  const { sent, json, res } = sink();
  const post = vi.fn(() => "message-1");
  const out = await handler({ method: input.method ?? "POST", path: input.path ?? "/api/internal/pages/publish", res, json, botId: "bot-1", threadId: "thread-1",
    readBody: async () => input.body ?? {}, folders: async () => ({ roots: ["/work/bot-1"], vmWorkspace: input.vmWorkspace ?? null }), post,
    requireActive: () => {}, signal: new AbortController().signal });
  return { out, post, ...sent };
}

describe("the page tools' internal routes", () => {
  it("passes requests that are not its own", async () => {
    const handler = createPagesInternalRoutes(fakePublisher());
    expect((await internal(handler, { path: "/api/internal/attach-file" })).out).toBe(PASS);
    expect((await internal(handler, { method: "GET" })).out).toBe(PASS);
  });

  it("publishes as the capability's own bot and conversation, from its own folders, whatever the body says", async () => {
    const publisher = fakePublisher(), handler = createPagesInternalRoutes(publisher);
    const answer = await internal(handler, { body: { path: "site", title: "Bake sale", page_id: "abcdefghijklmnopqrstuvwxyz", botId: "someone-else" } });
    expect(answer).toMatchObject({ status: 200, body: { ok: true, text: expect.stringContaining("Published") } });
    expect(publisher.publish).toHaveBeenCalledWith(expect.objectContaining({ botId: "bot-1", threadId: "thread-1", path: "site", title: "Bake sale",
      pageId: "abcdefghijklmnopqrstuvwxyz", roots: ["/work/bot-1"], call: expect.objectContaining({ assertActive: expect.any(Function) }) }));
  });

  it("passes live on, and only when the tool was given it", async () => {
    const publisher = fakePublisher(), handler = createPagesInternalRoutes(publisher);
    await internal(handler, { body: { path: "site", title: "Sales", live: true } });
    expect(publisher.publish).toHaveBeenLastCalledWith(expect.objectContaining({ live: true }));
    await internal(handler, { body: { path: "site", title: "Sales" } });
    expect(publisher.publish).toHaveBeenLastCalledWith(expect.not.objectContaining({ live: expect.anything() }));
    expect(await internal(handler, { body: { path: "site", title: "Sales", live: "yes" } })).toMatchObject({ status: 400 });
  });

  it("reads a path inside the bot's private desktop as the same file on this computer", async () => {
    const publisher = fakePublisher(), handler = createPagesInternalRoutes(publisher);
    await internal(handler, { body: { path: "/home/cua/workspace/site", title: "Site" }, vmWorkspace: "/vm/bot-1" });
    // The guest path becomes this computer's own path under the private desktop's folder (Windows joins with "\\").
    expect(publisher.publish).toHaveBeenCalledWith(expect.objectContaining({ path: join("/vm/bot-1", "site"), roots: ["/vm/bot-1", "/work/bot-1"] }));
  });

  it("refuses a body that isn't the tool's, and passes on a publisher's refusal as an error", async () => {
    const publisher = fakePublisher(), handler = createPagesInternalRoutes(publisher);
    expect(await internal(handler, { body: { path: 3, title: "x" } })).toMatchObject({ status: 400 });
    expect(publisher.publish).not.toHaveBeenCalled();
    publisher.publish.mockResolvedValueOnce({ status: 403, text: "Publishing a page needs a MausBot account." });
    expect(await internal(handler, { body: { path: "site", title: "x" } })).toMatchObject({ status: 403, body: { error: "Publishing a page needs a MausBot account." } });
  });

  it("unpublishes by page id or path, as the capability's bot", async () => {
    const publisher = fakePublisher(), handler = createPagesInternalRoutes(publisher);
    const answer = await internal(handler, { path: "/api/internal/pages/unpublish", body: { path: "site" } });
    expect(answer).toMatchObject({ status: 200, body: { ok: true, text: "Unpublished." } });
    expect(publisher.unpublish).toHaveBeenCalledWith({ path: "site", botId: "bot-1", roots: ["/work/bot-1"], call: expect.anything() });
  });
});

describe("the card's Unpublish", () => {
  const call = async (handler: ReturnType<typeof createPublishedPageRoutes>, path: string, method = "POST") => {
    const sent: { status?: number; body?: any } = {};
    const out = await handler({ path, method, res: {}, json: (_res: unknown, status: number, body: unknown) => { sent.status = status; sent.body = body; } } as unknown as RouteContext);
    return { out, ...sent };
  };

  it("unpublishes the page the path names and answers with its card", async () => {
    const publisher = fakePublisher(), handler = createPublishedPageRoutes(publisher);
    expect(await call(handler, "/api/published-pages/abcdefghijklmnopqrstuvwxyz/unpublish")).toMatchObject({ status: 200, body: { ok: true, card: { state: "unpublished" } } });
    expect(publisher.unpublish).toHaveBeenCalledWith({ pageId: "abcdefghijklmnopqrstuvwxyz" });
    expect((await call(handler, "/api/published-pages/abcdefghijklmnopqrstuvwxyz/unpublish", "GET")).out).toBe(PASS);
    expect((await call(handler, "/api/published-pages/short/unpublish")).out).toBe(PASS);
  });
});

describe("an owner-only page's stable link", () => {
  const PAGE = "abcdefghijklmnopqrstuvwxyz";
  const HOME: RequestAuth = { kind: "loopback", scopes: ["admin", "client"] };
  // The route reads only the kind and scopes through ownerOrAdmin; a real session record is the gate's business.
  const OWNER = { kind: "session", scopes: ["admin", "client"], via: "bearer", session: { id: "s1" } } as unknown as RequestAuth;
  const MEMBER = { kind: "session", scopes: ["client"], via: "bearer", session: { id: "s2" } } as unknown as RequestAuth;

  function ownerPage(only = true, sessionLive?: (id: string) => boolean) {
    const served: unknown[][] = [];
    const pages: OwnerPages & { served: unknown[][] } = { served, ownerOnly: () => only, sessionLive,
      servePage: (_req, _res, method, pageId, rest, search, viewer) => { served.push([method, pageId, rest, search, viewer.key, viewer.allowed()]); },
      openUrl: (pageId, viewer) => `https://cloud.example.test/api/published-pages/${pageId}/?code=for-${viewer.key}` };
    return pages;
  }

  function serve(ownerPages: OwnerPages | undefined, target = `/api/published-pages/${PAGE}/`, method = "GET", auth: RequestAuth = OWNER) {
    const sent: { status?: number; body?: any; out?: typeof PASS | void } = {};
    const url = new URL(target, "https://cloud.example.test");
    return createPublishedPageRoutes(fakePublisher(), undefined, ownerPages)({ req: {} as never, res: {} as never,
      url, path: url.pathname, method, auth,
      json: ((_res: unknown, status: number, body: unknown) => { sent.status = status; sent.body = body; }) as never,
      readBody: async () => ({}) } as RouteContext).then((out) => Object.assign(sent, { out }));
  }

  it("serves the owner any file of the page at its link, keeping the query string, never through a redirect", async () => {
    const pages = ownerPage();
    await serve(pages);
    await serve(pages, `/api/published-pages/${PAGE}/data.csv?period=2026-11`, "HEAD", HOME);
    await serve(pages, `/api/published-pages/${PAGE}`);
    expect(pages.served).toEqual([
      ["GET", PAGE, "/", "", "session:s1", true],
      ["HEAD", PAGE, "/data.csv", "?period=2026-11", "loopback", true],
      ["GET", PAGE, undefined, "", "session:s1", true],
    ]);
  });

  it("ties what it serves to the session that asked, so a signed-out session's copy stops", async () => {
    const pages = ownerPage(true, () => false);
    await serve(pages);
    expect(pages.served[0]?.[5]).toBe(false);
  });

  it("gives the owner a one-time link to open the page in a browser, and nobody else", async () => {
    expect(await serve(ownerPage(), `/api/published-pages/${PAGE}/open`, "POST")).toMatchObject({ status: 200,
      body: { url: `https://cloud.example.test/api/published-pages/${PAGE}/?code=for-session:s1` } });
    expect(await serve(ownerPage(), `/api/published-pages/${PAGE}/open`, "POST", MEMBER)).toMatchObject({ status: 404 });
  });

  it("refuses a viewer who is not the owner, and any page that is not owner-only", async () => {
    expect(await serve(ownerPage(), undefined, "GET", MEMBER)).toMatchObject({ status: 404, body: { error: "Not found." } });
    expect(await serve(ownerPage(), undefined, "GET", { kind: "loopback", scopes: ["client"], trust: "service" })).toMatchObject({ status: 404 });
    expect((await serve(ownerPage(false))).out).toBe(PASS);
    expect((await serve(ownerPage(false), `/api/published-pages/${PAGE}/open`, "POST")).out).toBe(PASS);
    expect((await serve(undefined)).out).toBe(PASS);
  });
});