import { afterAll, expect, test } from "bun:test"; import { mkdtempSync } from "node:fs"; import { tmpdir } from "node:os"; import { join } from "node:path"; import { env } from "./env.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, ); 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).not.toContain('action="/notes"'); const signed = await (await api("/", {}, alice)).text(); expect(signed).toContain("alice"); expect(signed).toContain("/__forge/signout"); expect(signed).toContain('action="/notes"'); }); test("a form post adds as the person; a guest is sent to sign in", async () => { const form = new FormData(); form.set("body", "hello from a form"); const refused = await api("/notes", { 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"); expect(await (await fetch(base + "/")).text()).not.toContain( "hello from a form", ); const posted = await api( "/notes", { method: "POST", body: form, redirect: "manual" }, alice, ); expect(posted.status).toBe(303); expect(posted.headers.get("set-cookie")).toBeNull(); const page = await (await api("/", {}, alice)).text(); expect(page).toContain("hello from a form"); expect(page).toContain("alice ยท"); }); test("the JSON API is the same actions with the same identity", async () => { const created = await api( "/api/notes", { method: "POST", ...jsonBody({ body: "over the api" }) }, alice, ); expect(created.status).toBe(201); const note = (await created.json()) as { id: number; author_name: string }; expect(note.author_name).toBe("alice"); const listed = (await (await fetch(base + "/api/notes")).json()) as { id: number; }[]; expect(listed.map((n) => n.id)).toContain(note.id); expect( (await api("/api/notes", { method: "POST", ...jsonBody({ body: "anon" }) })) .status, ).toBe(401); expect( (await api(`/api/notes/${note.id}`, { method: "DELETE" }, bob)).status, ).toBe(403); expect( (await api(`/api/notes/${note.id}`, { method: "DELETE" }, alice)).status, ).toBe(200); expect( (await api(`/api/notes/${note.id}`, { method: "DELETE" }, alice)).status, ).toBe(404); expect( ( await api( "/api/notes", { method: "POST", ...jsonBody({ body: "" }) }, alice, ) ).status, ).toBe(422); }); 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([ "list_notes", "add_note", "delete_note", ]); 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("add_note", { body: "as nobody" }); expect(refused.result.isError).toBe(true); const added = await call("add_note", { body: "over mcp" }, root); expect(added.result.isError).toBeUndefined(); const note = JSON.parse(added.result.content[0].text); expect(note.author_name).toBe("root"); const notes = JSON.parse( (await call("list_notes", {})).result.content[0].text, ); expect(notes.map((n: { id: number }) => n.id)).toContain(note.id); expect( (await call("delete_note", { id: note.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/notes", { method: "POST", ...jsonBody({ body: "live" }) }, alice, ); const heard = await next(); expect(heard.type).toBe("note.added"); await reader.cancel(); 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("note.added"); }); test("writes are rationed per person", async () => { const flood = as("u9", "flood"); const answers = await Promise.all( Array.from({ length: 40 }, () => api( "/api/notes", { method: "POST", ...jsonBody({ body: "again" }) }, flood, ), ), ); const codes = answers.map((r) => r.status); expect(codes).toContain(201); 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/notes")).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( "/notes", { method: "POST", headers: { "content-type": "application/x-www-form-urlencoded" }, body: "body=" + "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("body", "from another site"); const posted = await api( "/notes", { 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(), ); } });