import { afterAll, expect, test } from "bun:test"; import { mkdtempSync } from "node:fs"; import { tmpdir } from "node:os"; import { join } from "node:path"; import { setDrawer, settled } from "./draw.ts"; import { env } from "./env.ts"; import { GLOW, INK, PALETTES } from "./glyph.ts"; import { serve } from "./server.ts"; import { sign } from "./who.ts"; const KEY = "a-key-only-the-forge-holds"; const server = serve({ port: 0, dataDir: mkdtempSync(join(tmpdir(), "app-")), identityKey: KEY, }); const base = `http://${server.hostname}:${server.port}`; afterAll(() => server.stop(true)); /** The headers the forge sends for a signed-in person. */ const as = ( id: string, name: string, role: "user" | "admin" = "user", ): Record => { const identity = `${id}|${name}|${role}|${Date.now() + 60_000}`; return { "x-forge-identity": identity, "x-forge-signature": sign(identity, KEY), }; }; const alice = as("u1", "alice"); const bob = as("u2", "bob"); const root = as("u0", "root", "admin"); const jsonBody = (body: unknown): RequestInit => ({ headers: { "content-type": "application/json" }, body: JSON.stringify(body), }); const api = ( path: string, init: RequestInit = {}, who: Record = {}, ) => fetch(base + path, { ...init, headers: { ...(init.headers as Record), ...who }, }); const rpc = (message: unknown, who: Record = {}) => api("/mcp", { method: "POST", ...jsonBody(message) }, who).then( (r) => r.json() as Promise, ); /** The drawer every test here uses: Claude is never called. */ const SVG = `Test Mark`; setDrawer(async (prompt) => { if (prompt.includes("fail")) throw new Error("Claude had a bad day."); return [SVG, SVG]; }); test("the page knows who you are and offers the right door", async () => { const guest = await (await fetch(base + "/")).text(); expect(guest).toContain("

"); expect(guest).toContain("/__forge/signin?to=/"); expect(guest).toContain('href="/__forge/report"'); expect(guest).not.toContain('action="/drawings"'); const signed = await (await api("/", {}, alice)).text(); expect(signed).toContain("alice"); expect(signed).toContain("/__forge/signout"); expect(signed).toContain('action="/drawings"'); }); test("a form post draws as the person; a guest is sent to sign in; the board shows it", async () => { const form = new FormData(); form.set("prompt", "hello from a form"); form.set("kind", "icon"); const refused = await api("/drawings", { method: "POST", body: form, redirect: "manual", }); expect(refused.status).toBe(303); expect(refused.headers.get("set-cookie")).toContain("notice="); expect(refused.headers.get("set-cookie")).toContain("SameSite=Lax"); const posted = await api( "/drawings", { method: "POST", body: form, redirect: "manual" }, alice, ); expect(posted.status).toBe(303); expect(posted.headers.get("set-cookie")).toBeNull(); await settled(); const page = await (await api("/", {}, alice)).text(); expect(page).toContain("hello from a form"); expect(page).toContain("app icon"); expect(page).toContain('alt="Test Mark"'); expect(page).toContain("data:image/svg+xml,"); // Nobody else sees alice's drawing. expect(await (await api("/", {}, bob)).text()).not.toContain("hello from a form"); // A palette in the address is the palette the tiles are drawn in. const neon = await (await api("/?palette=neon", {}, alice)).text(); expect(neon).toContain('data-palette="neon" aria-current="true"'); expect(neon).toContain(encodeURIComponent(PALETTES.neon!.ink)); }); test("the JSON API is the same actions with the same identity", async () => { const created = await api( "/api/drawings", { method: "POST", ...jsonBody({ prompt: "over the api", kind: "badge" }) }, alice, ); expect(created.status).toBe(202); const drawing = (await created.json()) as { id: number; author_name: string; status: string; svgs: string[] }; expect(drawing.author_name).toBe("alice"); expect(drawing.status).toBe("drawing"); expect(drawing.svgs).toEqual([]); await settled(); const done = (await (await api(`/api/drawings/${drawing.id}`, {}, alice)).json()) as { status: string; svgs: string[] }; expect(done.status).toBe("done"); expect(done.svgs).toEqual([SVG, SVG]); const listed = (await (await api("/api/drawings", {}, alice)).json()) as { id: number }[]; expect(listed.map((n) => n.id)).toContain(drawing.id); expect((await (await api("/api/drawings", {}, bob)).json()) as unknown[]).toEqual([]); expect((await api(`/api/drawings/${drawing.id}`, {}, bob)).status).toBe(403); expect( (await api("/api/drawings", { method: "POST", ...jsonBody({ prompt: "anon" }) })).status, ).toBe(401); expect((await api(`/api/drawings/${drawing.id}`, { method: "DELETE" }, bob)).status).toBe(403); expect((await api(`/api/drawings/${drawing.id}`, { method: "DELETE" }, alice)).status).toBe(200); expect((await api(`/api/drawings/${drawing.id}`, { method: "DELETE" }, alice)).status).toBe(404); for (const body of [{ prompt: "" }, { prompt: "ok", kind: "poster" }]) expect( (await api("/api/drawings", { method: "POST", ...jsonBody(body) }, alice)).status, ).toBe(422); }); test("a failed drawing says why, and a busy person is asked to wait", async () => { const carol = as("u3", "carol"); let release = (): void => {}; setDrawer(() => new Promise((resolve) => (release = () => resolve([SVG])))); try { const first = await api("/api/drawings", { method: "POST", ...jsonBody({ prompt: "slow" }) }, carol); expect(first.status).toBe(202); const second = await api("/api/drawings", { method: "POST", ...jsonBody({ prompt: "again" }) }, carol); expect(second.status).toBe(429); expect(((await second.json()) as { error: string }).error).toBe("busy"); release(); await settled(); } finally { setDrawer(async (prompt) => { if (prompt.includes("fail")) throw new Error("Claude had a bad day."); return [SVG, SVG]; }); } const failed = (await ( await api("/api/drawings", { method: "POST", ...jsonBody({ prompt: "please fail" }) }, carol) ).json()) as { id: number }; await settled(); const row = (await (await api(`/api/drawings/${failed.id}`, {}, carol)).json()) as { status: string; error: string }; expect(row).toMatchObject({ status: "failed", error: "Claude had a bad day." }); expect(await (await api("/", {}, carol)).text()).toContain("Claude had a bad day."); }); test("a drawing saves as a file, in the palette asked for, and runs nothing", async () => { const made = (await ( await api("/api/drawings", { method: "POST", ...jsonBody({ prompt: "to save" }) }, alice) ).json()) as { id: number }; await settled(); const saved = await api(`/drawings/${made.id}/1.svg?palette=blueprint`, {}, alice); expect(saved.status).toBe(200); expect(saved.headers.get("content-type")).toContain("image/svg+xml"); expect(saved.headers.get("content-disposition")).toBe('attachment; filename="test-mark.svg"'); expect(saved.headers.get("content-security-policy")).toContain("sandbox"); const body = await saved.text(); expect(body).toContain(PALETTES.blueprint!.ink); expect(body).not.toContain(INK); expect((await api(`/drawings/${made.id}/0.svg`, {}, alice)).status).toBe(200); expect((await api(`/drawings/${made.id}/7.svg`, {}, alice)).status).toBe(404); expect((await api(`/drawings/${made.id}/0.svg`, {}, bob)).status).toBe(403); expect((await api(`/drawings/${made.id}/0.svg`)).status).toBe(401); }); test("the MCP server lists the tools and calls them as the caller", async () => { const hello = await rpc({ jsonrpc: "2.0", id: 1, method: "initialize", params: {}, }); expect(hello.result.capabilities).toEqual({ tools: {} }); const listed = await rpc({ jsonrpc: "2.0", id: 2, method: "tools/list" }); expect(listed.result.tools.map((t: { name: string }) => t.name)).toEqual([ "draw", "get_drawing", "list_drawings", "delete_drawing", ]); const call = (name: string, args: unknown, who = {}) => rpc( { jsonrpc: "2.0", id: 3, method: "tools/call", params: { name, arguments: args }, }, who, ); const refused = await call("draw", { prompt: "as nobody" }); expect(refused.result.isError).toBe(true); const added = await call("draw", { prompt: "over mcp" }, root); expect(added.result.isError).toBeUndefined(); const drawing = JSON.parse(added.result.content[0].text); expect(drawing.author_name).toBe("root"); await settled(); const got = JSON.parse((await call("get_drawing", { id: drawing.id }, root)).result.content[0].text); expect(got.svgs).toEqual([SVG, SVG]); const mine = JSON.parse((await call("list_drawings", {}, root)).result.content[0].text); expect(mine.map((n: { id: number }) => n.id)).toContain(drawing.id); expect((await call("delete_drawing", { id: drawing.id }, root)).result.isError).toBeUndefined(); expect( (await rpc({ jsonrpc: "2.0", id: 4, method: "nothing" })).error.code, ).toBe(-32601); const notified = await api("/mcp", { method: "POST", ...jsonBody({ jsonrpc: "2.0", method: "notifications/initialized" }), }); expect(notified.status).toBe(202); }); test("a change is on the event stream, and a late client hears what it missed", async () => { const stream = await fetch(base + "/events"); expect(stream.headers.get("content-type")).toBe("text/event-stream"); const reader = stream.body!.getReader(); const next = async (): Promise<{ id: string; type: string }> => { let buffer = ""; for (;;) { const { value } = await reader.read(); buffer += new TextDecoder().decode(value); const frame = /id: (\d+)\ndata: (.*)\n\n/.exec(buffer); if (frame) return { id: frame[1]!, type: JSON.parse(frame[2]!).type }; } }; await api( "/api/drawings", { method: "POST", ...jsonBody({ prompt: "live" }) }, as("u4", "dana"), ); const heard = await next(); expect(heard.type).toBe("drawing.added"); await reader.cancel(); await settled(); const late = await fetch(base + "/events", { headers: { "last-event-id": String(Number(heard.id) - 1) }, }); const replay = new TextDecoder().decode( (await late.body!.getReader().read()).value, ); expect(replay).toContain(`id: ${heard.id}\n`); expect(replay).toContain("drawing.added"); expect(replay).toContain("drawing.changed"); }); test("writes are rationed per person", async () => { const flood = as("u9", "flood"); const answers = await Promise.all( Array.from({ length: 40 }, () => api("/api/drawings/999999", { method: "DELETE" }, flood), ), ); const codes = answers.map((r) => r.status); expect(codes).toContain(404); expect(codes).toContain(429); }); test("stands on the security floor", async () => { const response = await fetch(base + "/"); expect(response.headers.get("content-security-policy")).toContain( "default-src 'self'", ); expect(response.headers.get("x-content-type-options")).toBe("nosniff"); expect( (await fetch(base + "/api/drawings")).headers.get("content-security-policy"), ).toContain("default-src"); }); test("a body is capped by the bytes read, whatever it claims", async () => { const response = await api( "/drawings", { method: "POST", headers: { "content-type": "application/x-www-form-urlencoded" }, body: "prompt=" + "x".repeat(1024 * 1024), }, alice, ); expect(response.status).toBe(413); }); test("HEAD sees the app up", async () => { const response = await fetch(base + "/", { method: "HEAD" }); expect(response.status).toBe(200); expect(await response.text()).toBe(""); }); test("refuses a cross-site post", async () => { const form = new FormData(); form.set("prompt", "from another site"); const posted = await api( "/drawings", { method: "POST", body: form, redirect: "manual", headers: { origin: "https://evil.example", "sec-fetch-site": "cross-site", }, }, alice, ); expect(posted.status).toBe(403); }); test("static files are cached for a year when linked by content", async () => { const page = await (await fetch(base + "/")).text(); const href = /href="(\/static\/app\.css\?v=[0-9a-f]{8})"/.exec(page)?.[1]; expect(href).toBeDefined(); const css = await fetch(base + href!); expect(css.headers.get("cache-control")).toContain("immutable"); expect( (await fetch(base + "/static/app.css")).headers.get("cache-control"), ).toBe("no-cache"); expect((await fetch(base + "/static/..%2Fpackage.json")).status).toBe(404); }); test("/healthz says up, apart from the page", async () => { const response = await fetch(base + "/healthz"); expect(response.status).toBe(200); expect(response.headers.get("cache-control")).toBe("no-store"); const health = (await response.json()) as Record; expect(health.ok).toBe(true); expect(health.version).toMatch(/^\d+\.\d+\.\d+/); expect(Number.isInteger(health.uptime)).toBe(true); expect((await fetch(base + "/healthz", { method: "HEAD" })).status).toBe(200); }); test("a link to the page unfurls: description, Open Graph, a card", async () => { const page = await (await fetch(base + "/")).text(); for (const meta of [ 'name="description"', 'property="og:title"', 'property="og:description"', 'property="og:url"', 'property="og:type" content="website"', 'name="twitter:card" content="summary"', 'name="theme-color"', ]) expect([meta, page.includes(meta)]).toEqual([meta, true]); }); test("the look is the tokens: /tokens.css is linked by content and cached for a year", async () => { const page = await (await fetch(base + "/")).text(); const href = /href="(\/tokens\.css\?v=[0-9a-f]{8})"/.exec(page)?.[1]; expect(href).toBeDefined(); const css = await fetch(base + href!); expect(css.headers.get("content-type")).toContain("text/css"); expect(css.headers.get("cache-control")).toContain("immutable"); expect(await css.text()).toContain("--color-bg:"); // The tokens come first, so every rule after them can use them. expect(page.indexOf("/tokens.css")).toBeLessThan( page.indexOf("/static/app.css"), ); }); test("what the web expects: robots.txt, and security.txt from the forge that runs us", async () => { // Production is read by crawlers, the API is not; anything else is a // draft and asks not to be indexed at all. const robots = await (await fetch(base + "/robots.txt")).text(); const noindex = (await fetch(base + "/")).headers.get("x-robots-tag"); if (env === "production") { expect(robots).toContain("Disallow: /api/\n"); expect(noindex).toBeNull(); } else { expect(robots).toBe("User-agent: *\nDisallow: /\n"); expect(noindex).toBe("noindex"); } const security = await fetch(base + "/.well-known/security.txt", { redirect: "manual", }); if (process.env.FORGE_URL === undefined) expect(security.status).toBe(404); else { expect(security.status).toBe(302); expect(security.headers.get("location")).toBe( new URL("/.well-known/security.txt", process.env.FORGE_URL).toString(), ); } }); test("another person's prompt and SVG never reach /events, live or replayed", async () => { const secret = "zq-private-prompt-7"; const live = await fetch(base + "/events", { headers: as("u2", "bob") }); const reader = live.body!.getReader(); let heard = ""; const pump = (async () => { for (;;) { const { value, done } = await reader.read(); if (done) return; heard += new TextDecoder().decode(value); } })(); await api( "/api/drawings", { method: "POST", ...jsonBody({ prompt: secret }) }, as("u1", "alice"), ); await settled(); await Bun.sleep(50); const replay = await (async () => { const late = await fetch(base + "/events?since=0", { headers: as("u2", "bob") }); const late_reader = late.body!.getReader(); const text = new TextDecoder().decode((await late_reader.read()).value); await late_reader.cancel(); return text; })(); await reader.cancel(); await pump; expect(heard).toContain("drawing.changed"); expect(replay).toContain("drawing.changed"); for (const text of [heard, replay]) { expect(text).not.toContain(secret); expect(text).not.toContain("