1import { afterAll, beforeAll, describe, expect, setSystemTime, test } from "bun:test";2import { join } from "node:path";3import { fileIssue } from "../src/issues/store.ts";4import { Browser, type Instance, instance } from "./browser.ts";5import { makeRepos, writeRelease } from "./fixture.ts";67let clock = Date.parse("2026-09-26T12:00:00Z");8const tick = (seconds: number) => {9 clock += seconds * 1000;10 setSystemTime(new Date(clock));11};1213describe("repos and visibility", () => {14 let inst: Instance;15 let browser: Browser;16 let bucketDir: string;17 let save: string;18 const publicPaths = () => [19 "/app",20 "/app/files/README.md",21 "/app/raw/README.md",22 `/app/saves/${save}`,23 `/app/archive/${save}.tar.gz`,24 "/app/archive/HEAD.tar.gz",25 "/app/archives",26 "/app/releases",27 "/app/releases/latest",28 "/app/releases/latest.json",29 "/app/releases/history.json",30 "/app/releases/latest/version.txt",31 "/app/releases/latest/linux-x86_64",32 "/app/releases/1.0.0/checksums.txt",33 "/app/releases/1.0.0/linux-x86_64",34 "/app/install.sh",35 "/api/app/releases/latest",36 "/api/app/releases/history",37 "/app/update-info",38 "/app/meta",39 "/app/issues",40 "/app/issues/new",41 "/app/issues/1",42 "/app?panel=issues",43 "/app/file?path=README.md",44 "/app/bundle",45 "/app/bundle.blake3",46 "/app/releases/1.0.0",47 ];48 const statuses = async () => {49 const out: string[] = [];50 for (const path of publicPaths()) out.push(`${path} ${(await inst.app.request(path)).status}`);51 return out;52 };53 const text = async (path: string) => (await inst.app.request(path)).text();54 const publish = (repo: string, fields: Record<string, string>) =>55 browser.post(`/admin/repos/${repo}`, { sort_order: "0", ...fields });5657 beforeAll(async () => {58 setSystemTime(new Date(clock));59 const repos = await makeRepos(["app", "other"]);60 bucketDir = repos.bucketDir;61 save = repos.saves.app as string;62 await writeRelease(bucketDir, "app", {63 version: "1.0.0",64 save,65 files: [{ platform: "linux-x86_64", name: "app", bytes: new Uint8Array([1]) }],66 });67 inst = await instance(bucketDir);68 inst.kepr.run("INSERT INTO settings (key, value) VALUES ('handle', 'june')");69 fileIssueDirect(inst, "app");70 browser = new Browser(inst.app);71 await browser.signIn();72 });73 afterAll(() => setSystemTime());7475 test("every repo the sync found is listed, private, with its last sync", async () => {76 const page = await (await browser.get("/admin/repos")).text();77 expect(page).toContain('id="repo-app"');78 expect(page).toContain('id="repo-other"');79 expect(page.match(/action="\/admin\/repos\//g)?.length).toBe(1);80 expect(page).toContain("last sync 2026-09-26 12:00 UTC");81 expect((await statuses()).every((line) => line.endsWith(" 404"))).toBe(true);82 });8384 test("repo search focuses one settings form and links back to the selected repo after saving", async () => {85 const page = await (await browser.get("/admin/repos?q=other")).text();86 expect(page).toContain('action="/admin/repos/other"');87 expect(page).not.toContain('id="repo-app"');88 const saved = await publish("other", {});89 expect(saved.headers.get("location")).toBe("/admin/repos?repo=other&saved=1#repo-editor");90 expect(await (await browser.get("/admin/repos?repo=other&saved=1")).text()).toContain(91 "Changes saved.",92 );93 });9495 test("bad settings are refused and change nothing", async () => {96 for (const fields of <Record<string, string>[]>[97 { homepage: "javascript:alert(1)" },98 { sort_order: "first" },99 { install1: "one\ntwo" },100 { category: "x".repeat(501) },101 ]) {102 expect((await publish("app", { public: "1", ...fields })).status).toBe(400);103 }104 expect((await inst.app.request("/app")).status).toBe(404);105 expect((await browser.post("/admin/repos/nowhere", { public: "1" })).status).toBe(404);106 });107108 test("publishing opens every public surface, with the settings shown", async () => {109 await publish("other", { public: "1" });110 const response = await publish("app", {111 public: "1",112 category: "tools",113 homepage: "https://app.example",114 install1: "nix profile add app",115 });116 expect(response.status).toBe(303);117 const lines = await statuses();118 expect(lines.filter((line) => line.endsWith(" 404"))).toEqual([]);119 expect(await text("/app")).toContain("https://app.example");120 expect(await text("/app")).toContain("nix profile add app");121 expect(await text("/")).toContain('href="/app"');122 expect(await text("/browse")).toContain('href="/app"');123 expect(await text("/@june")).toContain('href="/app"');124 expect(await text("/sitemap.xml")).toContain("/app</loc>");125 });126127 test("flipping a repo private 404s every surface and drops it from lists and counts", async () => {128 const stat = async () =>129 [...(await text("/@june")).matchAll(/profile-stat-number">([^<]*)</g)].map((m) => m[1]);130 131 expect(await stat()).toEqual(["2", "2", "1", "2"]);132 await publish("app", { category: "tools" });133 expect((await statuses()).filter((line) => !line.endsWith(" 404"))).toEqual([]);134 for (const path of ["/", "/browse", "/@june"]) expect(await text(path)).not.toContain("/app");135 expect(await text("/sitemap.xml")).not.toContain("/app<");136 expect(await text("/")).not.toContain("tools");137 expect(await stat()).toEqual(["1", "1", "0", "0"]);138 139 expect(await (await browser.get("/admin/repos")).text()).toContain('value="tools"');140 });141142 test("sync now reads the bucket at once and records the time", async () => {143 await writeRelease(bucketDir, "other", {144 version: "2.0.0",145 save: save,146 files: [{ platform: "linux-x86_64", name: "other", bytes: new Uint8Array([2]) }],147 });148 tick(60);149 expect((await inst.app.request("/other/releases/latest/version.txt")).status).toBe(404);150 const response = await browser.post("/admin/sync", {});151 expect(response.status).toBe(303);152 expect(await text("/other/releases/latest/version.txt")).toBe("2.0.0");153 expect(await (await browser.get("/admin/repos")).text()).toContain(154 "last sync 2026-09-26 12:01 UTC",155 );156 });157});158159describe("issues: filed, answered and closed end to end through real routes", () => {160 let inst: Instance;161 let operator: Browser;162 let save: string;163 const text = async (path: string) => (await inst.app.request(path)).text();164 const act = (fields: Record<string, string>) => operator.post("/admin/issues/app/1", fields);165166 beforeAll(async () => {167 setSystemTime(new Date(clock));168 const repos = await makeRepos(["app", "hush"]);169 save = repos.saves.app as string;170 inst = await instance(repos.bucketDir);171 operator = new Browser(inst.app);172 await operator.signIn();173 await operator.post("/admin/repos/app", { public: "1", sort_order: "0" });174 175 const reporter = new Browser(inst.app, "198.51.100.40");176 const form = await (await reporter.request("/app/issues/new")).text();177 const stamp = /name="stamp" value="([^"]+)"/.exec(form)?.[1] ?? "";178 tick(4);179 const filed = await reporter.request("/app/issues/new", {180 method: "POST",181 body: new URLSearchParams({182 stamp,183 website: "",184 title: "Crash <on> start",185 body: "It crashed.",186 type: "bug",187 version: "",188 name: "Ada",189 email: "[email protected]",190 }),191 });192 expect(filed.status).toBe(200);193 fileIssueDirect(inst, "hush");194 });195 afterAll(() => setSystemTime());196197 test("the console lists issues across repos, private ones too, with the contact detail", async () => {198 const list = await (await operator.get("/admin/issues")).text();199 expect(list).toContain('href="/admin/issues/app/1"');200 expect(list).toContain('href="/admin/issues/hush/1"');201 expect(list).toContain("Crash <on> start");202 const page = await (await operator.get("/admin/issues/app/1")).text();203 expect(page).toContain("contact: [email protected]");204 expect(await text("/app/issues/1")).not.toContain("[email protected]");205 });206207 test("an operator reply shows on the public thread, marked", async () => {208 expect((await act({ action: "reply", body: "Fixed <soon>." })).status).toBe(303);209 expect((await act({ action: "reply", body: " " })).status).toBe(400);210 const thread = await text("/app/issues/1");211 expect(thread).toContain('<span class="issue-badge">operator</span>');212 expect(thread).toContain("Fixed <soon>.");213 });214215 test("close with a fixed-in save prefix, then reopen", async () => {216 expect((await act({ action: "close", fixed_in: "zzzzzz" })).status).toBe(400);217 expect((await act({ action: "close", fixed_in: "0123456789ab" })).status).toBe(400);218 expect((await act({ action: "close", fixed_in: save.slice(0, 6) })).status).toBe(303);219 const thread = await text("/app/issues/1");220 expect(thread).toContain("◈ closed");221 expect(thread).toContain(`fixed in <a class="history-id" href="/app/saves/${save}">`);222 expect(await text("/app/issues?status=closed")).toContain('href="/app/issues/1"');223 expect(await (await operator.get("/admin/issues?filter=closed")).text()).toContain(224 'href="/admin/issues/app/1"',225 );226 expect((await act({ action: "reopen" })).status).toBe(303);227 expect(await text("/app/issues/1")).toContain("◉ open");228 expect(await text("/app/issues/1")).not.toContain("fixed in");229 });230231 test("set type, and hide for spam: gone publicly, kept in the console", async () => {232 expect((await act({ action: "type", type: "nonsense" })).status).toBe(400);233 expect((await act({ action: "type", type: "idea" })).status).toBe(303);234 expect(await text("/app/issues")).toContain("#1 · idea");235 expect((await act({ action: "hide" })).status).toBe(303);236 expect((await inst.app.request("/app/issues/1")).status).toBe(404);237 expect(await (await operator.get("/admin/issues")).text()).not.toContain("/admin/issues/app/1");238 expect(await (await operator.get("/admin/issues?filter=hidden")).text()).toContain(239 'href="/admin/issues/app/1"',240 );241 expect((await act({ action: "unhide" })).status).toBe(303);242 expect((await inst.app.request("/app/issues/1")).status).toBe(200);243 expect((await act({ action: "delete" })).status).toBe(400);244 expect((await operator.post("/admin/issues/app/9", { action: "reopen" })).status).toBe(404);245 });246});247248function fileIssueDirect(inst: Instance, repo: string): void {249 fileIssue(inst.kepr, {250 repo,251 title: `A ${repo} issue`,252 body: "b",253 type: "bug",254 version: "",255 reporterName: "",256 contactEmail: "",257 ipHash: "x",258 filedAt: 1,259 });260}261262describe("releases: counts, displayed notes and hiding", () => {263 let inst: Instance;264 let operator: Browser;265 const text = async (path: string) => (await inst.app.request(path)).text();266 const edit = (version: string, fields: Record<string, string>) =>267 operator.post(`/admin/releases/app/${version}`, fields);268269 beforeAll(async () => {270 const repos = await makeRepos(["app"]);271 const save = repos.saves.app as string;272 for (const version of ["1.0.0", "1.1.0"]) {273 await writeRelease(repos.bucketDir, "app", {274 version,275 save,276 notes: `notes for ${version}`,277 files: [{ platform: "linux-x86_64", name: "app", bytes: new Uint8Array([1]) }],278 });279 }280 inst = await instance(repos.bucketDir);281 operator = new Browser(inst.app);282 await operator.signIn();283 await operator.post("/admin/repos/app", { public: "1", sort_order: "0" });284 await inst.app.request("/app/releases/1.1.0/linux-x86_64");285 });286287 test("every version is listed with its download counts and notes", async () => {288 const page = await (await operator.get("/admin/releases")).text();289 expect(page).toContain('id="app-1.1.0"');290 expect(page).toContain('id="app-1.0.0"');291 expect(page.indexOf('id="app-1.1.0"')).toBeLessThan(page.indexOf('id="app-1.0.0"'));292 expect(page).toContain('<span>1 download</span><span class="muted">linux-x86_64 1</span>');293 expect(page).toContain(">notes for 1.1.0</textarea>");294 });295296 test("edited notes replace the record's everywhere; the record's own text clears the edit", async () => {297 expect((await edit("1.1.0", { notes: "Better <notes>." })).status).toBe(303);298 expect(JSON.parse(await text("/api/app/releases/latest")).notes).toBe("Better <notes>.");299 expect(await text("/app/releases")).toContain("Better <notes>.");300 expect(await (await operator.get("/admin/releases")).text()).toContain("(edited)");301 expect((await edit("1.1.0", { notes: "notes for 1.1.0" })).status).toBe(303);302 const row = inst.kepr.query("SELECT notes FROM release_settings WHERE version = '1.1.0'").get();303 expect(row).toEqual({ notes: null });304 expect((await edit("1.1.0", { notes: "x".repeat(20_001) })).status).toBe(400);305 });306307 test("a hidden version leaves pages, latest and every feed, and stays in the console", async () => {308 expect((await edit("1.1.0", { notes: "notes for 1.1.0", hidden: "1" })).status).toBe(303);309 expect(await text("/app/releases/latest/version.txt")).toBe("1.0.0");310 expect(JSON.parse(await text("/api/app/releases/latest")).version).toBe("1.0.0");311 expect(await text("/api/app/releases/history")).not.toContain("1.1.0");312 expect(await text("/app/releases")).not.toContain("1.1.0");313 expect((await inst.app.request("/app/releases/1.1.0/linux-x86_64")).status).toBe(404);314 const page = await (await operator.get("/admin/releases")).text();315 expect(page).toContain('id="app-1.1.0"');316 expect(page).toContain('value="1" checked> hidden');317 expect((await edit("1.1.0", { notes: "notes for 1.1.0" })).status).toBe(303);318 expect(await text("/app/releases/latest/version.txt")).toBe("1.1.0");319 expect((await edit("9.9.9", { notes: "" })).status).toBe(404);320 expect((await operator.post("/admin/releases/nowhere/1.0.0", { notes: "" })).status).toBe(404);321 });322});323324describe("site and profile settings, and the signature upload", () => {325 let inst: Instance;326 let operator: Browser;327 const PNG = Uint8Array.from(328 atob(329 "iVBORw0KGgoAAAANSUhEUgAAAAEAAAABCAYAAAAfFcSJAAAADUlEQVR42mNk+M9QDwADhgGAWjR9awAAAABJRU5ErkJggg==",330 ),331 (ch) => ch.charCodeAt(0),332 );333 const settings = {334 site_name: "ada's library",335 tagline: "Small <tools>.",336 branding: "by ada",337 handle: "ada",338 bio: "Writes code.",339 location: "Lisbon",340 link: "https://ada.example",341 building_since: "june 2026",342 support: "1",343 };344 const text = async (path: string) => (await inst.app.request(path)).text();345 const upload = (bytes: Uint8Array | string, name: string, type: string, extra = {}) => {346 const form = new FormData();347 for (const [key, value] of Object.entries({ ...settings, ...extra })) form.set(key, value);348 form.set("signature", new File([bytes], name, { type }));349 return operator.post("/admin/site", form);350 };351 const signature = () =>352 inst.kepr.query("SELECT value FROM settings WHERE key = 'signature'").get();353354 beforeAll(async () => {355 const repos = await makeRepos(["app"]);356 inst = await instance(repos.bucketDir);357 operator = new Browser(inst.app);358 await operator.signIn();359 });360361 test("settings are saved and every public page reads them", async () => {362 expect((await operator.post("/admin/site", settings)).status).toBe(303);363 const front = await text("/");364 expect(front).toContain("<title>ada's library</title>");365 expect(front).toContain("Small <tools>.");366 expect(front).toContain('<span class="wordmark-by">by ada</span>');367 const profile = await text("/@ada");368 for (const value of [369 "Writes code.",370 "Lisbon",371 'href="https://ada.example"',372 "building since june 2026",373 ]) {374 expect(profile).toContain(value);375 }376 expect(await (await operator.get("/admin/site?section=profile")).text()).toContain(377 'value="Lisbon"',378 );379 380 expect((await operator.post("/admin/site", { ...settings, site_name: "" })).status).toBe(303);381 expect(await text("/")).toContain("<title>kepr</title>");382 });383384 test("profile and site forms preserve each other's settings and retain invalid input", async () => {385 await operator.post("/admin/site", settings);386 const profile = await (await operator.get("/admin/site?section=profile")).text();387 expect(profile).toContain('aria-label="operator workspace"');388 expect(profile).toContain('href="/@ada"');389 expect(profile).not.toContain('name="site_name"');390 expect(391 (392 await operator.post("/admin/site", {393 section: "profile",394 handle: "ada",395 bio: "New bio",396 link: "https://ada.example",397 })398 ).status,399 ).toBe(303);400 expect(await text("/")).toContain("Small <tools>.");401 await operator.post("/admin/site", { section: "site", site_name: "New site", support: "1" });402 expect(await text("/@ada")).toContain("New bio");403 const bad = await operator.post("/admin/site", {404 section: "profile",405 handle: "a/b",406 bio: "Keep my draft",407 });408 expect(bad.status).toBe(400);409 expect(await bad.text()).toContain("Keep my draft");410 expect(await text("/@ada")).toContain("New bio");411 });412413 test("the support page is the operator's to write, and to switch off", async () => {414 415 const shipped = await text("/support");416 expect(await (await operator.get("/admin/site")).text()).toContain("show the support page");417 const own = { ...settings, support_page: "## Help\n\nMail **me**." };418 expect((await operator.post("/admin/site", own)).status).toBe(303);419 const support = await text("/support");420 expect(support).toContain('<h2 id="help">Help</h2>\n<p>Mail <strong>me</strong>.</p>');421 expect(support).not.toBe(shipped);422 const { support: _, ...off } = own;423 expect((await operator.post("/admin/site", off)).status).toBe(303);424 expect((await inst.app.request("/support")).status).toBe(404);425 expect(await text("/")).not.toContain('href="/support"');426 expect((await operator.post("/admin/site", own)).status).toBe(303);427 expect(await text("/")).toContain('<a href="/support">support</a>');428 });429430 test("a bad handle, link or overlong field is refused", async () => {431 for (const bad of [432 { handle: "a/b" },433 { link: "javascript:alert(1)" },434 { bio: "x".repeat(2001) },435 ]) {436 expect((await operator.post("/admin/site", { ...settings, ...bad })).status).toBe(400);437 }438 expect((await inst.app.request("/@ada")).status).toBe(200);439 });440441 test("a PNG signature is stored in data/assets and shown on the profile", async () => {442 expect((await upload(PNG, "sig.png", "image/png")).status).toBe(303);443 const name = (signature() as { value: string }).value;444 expect(name).toMatch(/^signature-[0-9a-f]{16}\.png$/);445 expect(await Bun.file(join(inst.dataDir, "assets", name)).exists()).toBe(true);446 expect(await text("/@ada")).toContain(447 `<img class="profile-signature" src="/static/assets/${name}"`,448 );449 const served = await inst.app.request(`/static/assets/${name}`);450 expect(served.headers.get("content-type")).toBe("image/png");451 expect(new Uint8Array(await served.arrayBuffer())).toEqual(PNG);452 });453454 test("SVG, or anything whose bytes are not PNG, JPEG or WebP, is refused whatever it claims", async () => {455 const before = signature();456 const svg = '<svg xmlns="http://www.w3.org/2000/svg"><script>alert(1)</script></svg>';457 expect((await upload(svg, "sig.svg", "image/svg+xml")).status).toBe(400);458 expect((await upload(svg, "sig.png", "image/png")).status).toBe(400);459 expect((await upload("GIF89a", "sig.gif", "image/gif")).status).toBe(400);460 expect(signature()).toEqual(before);461 expect((await upload(new Uint8Array(70 * 1024), "big.png", "image/png")).status).toBe(413);462 463 const png = (size: number) => {464 const bytes = new Uint8Array(size);465 bytes.set(PNG);466 return bytes;467 };468 const over = await upload(png(60 * 1024 + 1), "big.png", "image/png");469 expect(over.status).toBe(400);470 expect(await over.text()).toContain("The signature must be under 60 KB.");471 expect(signature()).toEqual(before);472 expect((await upload(png(60 * 1024), "edge.png", "image/png")).status).toBe(303);473 });474475 test("a new signature replaces the old file; removing it brings the handle back", async () => {476 const old = (signature() as { value: string }).value;477 const webp = new Uint8Array([0x52, 0x49, 0x46, 0x46, 0, 0, 0, 0, 0x57, 0x45, 0x42, 0x50, 1]);478 expect((await upload(webp, "sig.webp", "image/webp")).status).toBe(303);479 const name = (signature() as { value: string }).value;480 expect(name).toMatch(/\.webp$/);481 expect(await Bun.file(join(inst.dataDir, "assets", old)).exists()).toBe(false);482 expect(483 (await operator.post("/admin/site", { ...settings, remove_signature: "1" })).status,484 ).toBe(303);485 expect(signature()).toBeNull();486 expect(await Bun.file(join(inst.dataDir, "assets", name)).exists()).toBe(false);487 expect(await text("/@ada")).toContain('<h1 class="profile-username">ada</h1>');488 });489});