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="/new"'); const signed = await (await api("/", {}, as("u5", "erin"))).text(); expect(signed).toContain("Your vault is empty"); expect(signed).toContain("erin"); expect(signed).toContain("/__forge/signout"); expect(signed).toContain('action="/welcome"'); }); test("a form post writes as the person and lands on the note; a guest is sent to sign in", async () => { const form = new FormData(); form.set("title", "From a form"); const refused = await api("/new", { 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("/new", { method: "POST", body: form, redirect: "manual" }, alice); expect(posted.status).toBe(303); const at = posted.headers.get("location")!; expect(at).toMatch(/^\/n\/\d+$/); const page = await (await api(at, {}, alice)).text(); expect(page).toContain('value="From a form"'); expect(page).toContain("From a form · "); // The vault opens on the note last written. const home = await api("/", { redirect: "manual" }, alice); expect(home.headers.get("location")).toBe(at); // Saving without JavaScript: the form posts the whole note. const save = new FormData(); save.set("title", "From a form"); save.set("body", "Now with [[Words]] and #tags"); expect((await api(at, { method: "POST", body: save, redirect: "manual" }, alice)).status).toBe(303); const saved = await (await api(at, {}, alice)).text(); expect(saved).toContain('class="wikilink unresolved"'); expect(saved).toContain('href="/search?q=%23tags"'); // Another person's note is not theirs to open. const peek = await api(at, { redirect: "manual" }, bob); expect(peek.status).toBe(303); expect(peek.headers.get("location")).toBe("/"); }); test("a link to a note not written yet offers to write it", async () => { const page = await (await api("/open?title=Someday", {}, alice)).text(); expect(page).toContain("doesn't exist yet"); const form = new FormData(); form.set("title", "Someday"); const made = await api("/open", { method: "POST", body: form, redirect: "manual" }, alice); expect(made.headers.get("location")).toMatch(/^\/n\/\d+$/); const again = await api("/open?title=someday", { redirect: "manual" }, alice); expect(again.headers.get("location")).toBe(made.headers.get("location")); }); test("the JSON API is the same actions with the same identity", async () => { const created = await api( "/api/notes", { method: "POST", ...jsonBody({ title: "Over the API", body: "hello #api" }) }, alice, ); expect(created.status).toBe(201); const note = (await created.json()) as { id: number; author_name: string; title: string }; expect(note.author_name).toBe("alice"); const listed = (await (await api("/api/notes", {}, alice)).json()) as { id: number }[]; expect(listed.map((n) => n.id)).toContain(note.id); const found = (await (await api("/api/notes?q=%23api", {}, alice)).json()) as { id: number }[]; expect(found.map((n) => n.id)).toEqual([note.id]); expect(((await (await api("/api/notes", {}, bob)).json()) as unknown[]).length).toBe(0); const renamed = await api( `/api/notes/${note.id}`, { method: "PATCH", ...jsonBody({ title: "Renamed", pinned: true }) }, alice, ); expect(renamed.status).toBe(200); expect(((await renamed.json()) as { pinned: number }).pinned).toBe(1); expect((await api("/api/notes", { method: "POST", ...jsonBody({ title: "anon" }) })).status).toBe(401); expect((await api(`/api/notes/${note.id}`, {}, bob)).status).toBe(403); expect((await api(`/api/notes/${note.id}`, { method: "DELETE" }, bob)).status).toBe(403); const raw = await api(`/n/${note.id}/raw`, {}, alice); expect(raw.headers.get("content-type")).toContain("text/markdown"); expect(await raw.text()).toBe("hello #api"); const dump = (await (await api("/export", {}, alice)).json()) as { notes: { title: string }[] }; expect(dump.notes.map((n) => n.title)).toContain("Renamed"); 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({ title: "a|b" }) }, 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", "search_notes", "read_note", "create_note", "update_note", "append_to_note", "delete_note", ]); const call = (name: string, args: unknown, who = {}) => rpc({ jsonrpc: "2.0", id: 3, method: "tools/call", params: { name, arguments: args } }, who); expect((await call("create_note", { title: "as nobody" })).result.isError).toBe(true); expect((await call("list_notes", {})).result.isError).toBe(true); const added = await call("create_note", { title: "Over MCP", body: "first" }, root); expect(added.result.isError).toBeUndefined(); const note = JSON.parse(added.result.content[0].text); expect(note.author_name).toBe("root"); await call("append_to_note", { title: "Over MCP", text: "second" }, root); const read = JSON.parse((await call("read_note", { title: "over mcp" }, root)).result.content[0].text); expect(read.body).toBe("first\n\nsecond\n"); const titles = JSON.parse((await call("list_notes", {}, root)).result.content[0].text); expect(titles.map((n: { id: number }) => n.id)).toContain(note.id); expect(JSON.parse((await call("search_notes", { q: "second" }, root)).result.content[0].text)[0].id).toBe(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 its author's event stream only, and a late client hears what it missed", async () => { const read = (stream: Response) => { const reader = stream.body!.getReader(); let buffer = ""; return { reader, next: async (): Promise<{ id: string; type: string; data: any }> => { for (;;) { const frame = /id: (\d+)\ndata: (.*)\n\n/.exec(buffer); if (frame) { buffer = buffer.slice(frame.index + frame[0].length); const { type, data } = JSON.parse(frame[2]!); return { id: frame[1]!, type, data }; } const { value, done } = await reader.read(); if (done) throw new Error("the stream ended"); buffer += new TextDecoder().decode(value); } }, }; }; const mine = read(await api("/events", {}, alice)); const stranger = read(await fetch(base + "/events")); expect((await fetch(base + "/events")).headers.get("content-type")).toBe("text/event-stream"); await api("/api/notes", { method: "POST", ...jsonBody({ title: "Live one", body: "private words" }) }, alice); // A new stream first replays what this person missed; read to the new note. let heard = await mine.next(); while (heard.data?.title !== "Live one") heard = await mine.next(); expect(heard.type).toBe("note.added"); expect(heard.data.title).toBe("Live one"); // Nobody else's stream hears it — not even that it happened. const nothing = await Promise.race([ stranger.next().then( () => "heard", () => "silence", ), Bun.sleep(300).then(() => "silence"), ]); expect(nothing).toBe("silence"); await mine.reader.cancel(); await stranger.reader.cancel(); const late = await api("/events", { headers: { "last-event-id": String(Number(heard.id) - 1) } }, alice); const replay = new TextDecoder().decode((await late.body!.getReader().read()).value); expect(replay).toContain(`id: ${heard.id}\n`); expect(replay).toContain("note.added"); expect(JSON.stringify(heard)).not.toContain("private words"); }); test("someone with no forge account signs up, gets their own vault, and logs out", async () => { const form = (fields: Record<string, string>) => { const f = new FormData(); for (const [k, v] of Object.entries(fields)) f.set(k, v); return { method: "POST", body: f, redirect: "manual" as const }; }; const landing = await (await fetch(base + "/")).text(); expect(landing).toContain('href="/signup"'); expect(landing).toContain('href="/login"'); const made = await fetch(base + "/signup", form({ email: "pat@example.com", password: "a long password", name: "Pat" })); expect(made.status).toBe(303); const set = made.headers.getSetCookie().find((c) => c.startsWith("sid="))!; expect(set).toContain("HttpOnly"); expect(set).toContain("SameSite=Lax"); const sid = { cookie: set.split(";")[0]! }; // Signed in by the cookie alone: an empty vault, theirs. const home = await (await api("/", {}, sid)).text(); expect(home).toContain("Your vault is empty"); expect(home).toContain('action="/logout"'); const note = await api("/api/notes", { method: "POST", ...jsonBody({ title: "Pat's secret" }) }, sid); expect(note.status).toBe(201); const id = ((await note.json()) as { id: number }).id; // Not alice's, not a stranger's. expect((await api(`/api/notes/${id}`, {}, alice)).status).toBe(403); expect((await fetch(`${base}/api/notes/${id}`)).status).toBe(401); expect(((await (await api("/api/notes", {}, alice)).json()) as { title: string }[]).map((n) => n.title)).not.toContain("Pat's secret"); // The same email can't sign up twice; the wrong password doesn't log in. expect((await fetch(base + "/signup", form({ email: "PAT@example.com", password: "another password" }))).status).toBe(422); expect((await fetch(base + "/login", form({ email: "pat@example.com", password: "wrong password" }))).status).toBe(401); // A session cookie made up is nobody. expect((await api("/api/notes", {}, { cookie: `sid=${"A".repeat(43)}` })).status).toBe(401); // Log out ends it; log in again finds the same vault. const out = await api("/logout", { method: "POST", redirect: "manual" }, sid); expect(out.headers.getSetCookie().some((c) => c.startsWith("sid=;") && c.includes("Max-Age=0"))).toBe(true); expect((await api("/api/notes", {}, sid)).status).toBe(401); const back = await fetch(base + "/login", form({ email: "Pat@Example.com", password: "a long password" })); expect(back.status).toBe(303); const again = { cookie: back.headers.getSetCookie().find((c) => c.startsWith("sid="))!.split(";")[0]! }; const notes = (await (await api("/api/notes", {}, again)).json()) as { id: number }[]; expect(notes.map((n) => n.id)).toEqual([id]); expect(await (await api("/account", {}, again)).text()).toContain("pat@example.com"); // A cross-site page can't log someone in or out. expect( (await fetch(base + "/login", { ...form({ email: "pat@example.com", password: "a long password" }), headers: { "sec-fetch-site": "cross-site" } })).status, ).toBe(403); }); 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( "/new", { method: "POST", headers: { "content-type": "application/x-www-form-urlencoded" }, body: "title=" + "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("title", "from another site"); const posted = await api( "/new", { 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<string, unknown>; 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(), ); } });