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(/<span>private<\/span>/g)?.length).toBe(2);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("bad settings are refused and change nothing", async () => {85 for (const fields of <Record<string, string>[]>[86 { homepage: "javascript:alert(1)" },87 { sort_order: "first" },88 { install1: "one\ntwo" },89 { category: "x".repeat(501) },90 ]) {91 expect((await publish("app", { public: "1", ...fields })).status).toBe(400);92 }93 expect((await inst.app.request("/app")).status).toBe(404);94 expect((await browser.post("/admin/repos/nowhere", { public: "1" })).status).toBe(404);95 });9697 test("publishing opens every public surface, with the settings shown", async () => {98 await publish("other", { public: "1" });99 const response = await publish("app", {100 public: "1",101 category: "tools",102 homepage: "https://app.example",103 install1: "nix profile add app",104 });105 expect(response.status).toBe(303);106 const lines = await statuses();107 expect(lines.filter((line) => line.endsWith(" 404"))).toEqual([]);108 expect(await text("/app")).toContain("https://app.example");109 expect(await text("/app")).toContain("nix profile add app");110 expect(await text("/")).toContain('href="/app"');111 expect(await text("/browse")).toContain('href="/app"');112 expect(await text("/@june")).toContain('href="/app"');113 expect(await text("/sitemap.xml")).toContain("/app</loc>");114 });115116 test("flipping a repo private 404s every surface and drops it from lists and counts", async () => {117 const stat = async () =>118 [...(await text("/@june")).matchAll(/profile-stat-number">([^<]*)</g)].map((m) => m[1]);119 120 expect(await stat()).toEqual(["2", "2", "1", "2"]);121 await publish("app", { category: "tools" });122 expect((await statuses()).filter((line) => !line.endsWith(" 404"))).toEqual([]);123 for (const path of ["/", "/browse", "/@june"]) expect(await text(path)).not.toContain("/app");124 expect(await text("/sitemap.xml")).not.toContain("/app<");125 expect(await text("/")).not.toContain("tools");126 expect(await stat()).toEqual(["1", "1", "0", "0"]);127 128 expect(await (await browser.get("/admin/repos")).text()).toContain('value="tools"');129 });130131 test("sync now reads the bucket at once and records the time", async () => {132 await writeRelease(bucketDir, "other", {133 version: "2.0.0",134 save: save,135 files: [{ platform: "linux-x86_64", name: "other", bytes: new Uint8Array([2]) }],136 });137 tick(60);138 expect((await inst.app.request("/other/releases/latest/version.txt")).status).toBe(404);139 const response = await browser.post("/admin/sync", {});140 expect(response.status).toBe(303);141 expect(await text("/other/releases/latest/version.txt")).toBe("2.0.0");142 expect(await (await browser.get("/admin/repos")).text()).toContain(143 "last sync 2026-09-26 12:01 UTC",144 );145 });146});147148describe("issues: filed, answered and closed end to end through real routes", () => {149 let inst: Instance;150 let operator: Browser;151 let save: string;152 const text = async (path: string) => (await inst.app.request(path)).text();153 const act = (fields: Record<string, string>) => operator.post("/admin/issues/app/1", fields);154155 beforeAll(async () => {156 setSystemTime(new Date(clock));157 const repos = await makeRepos(["app", "hush"]);158 save = repos.saves.app as string;159 inst = await instance(repos.bucketDir);160 operator = new Browser(inst.app);161 await operator.signIn();162 await operator.post("/admin/repos/app", { public: "1", sort_order: "0" });163 164 const reporter = new Browser(inst.app, "198.51.100.40");165 const form = await (await reporter.request("/app/issues/new")).text();166 const stamp = /name="stamp" value="([^"]+)"/.exec(form)?.[1] ?? "";167 tick(4);168 const filed = await reporter.request("/app/issues/new", {169 method: "POST",170 body: new URLSearchParams({171 stamp,172 website: "",173 title: "Crash <on> start",174 body: "It crashed.",175 type: "bug",176 version: "",177 name: "Ada",178 email: "[email protected]",179 }),180 });181 expect(filed.status).toBe(200);182 fileIssueDirect(inst, "hush");183 });184 afterAll(() => setSystemTime());185186 test("the console lists issues across repos, private ones too, with the contact detail", async () => {187 const list = await (await operator.get("/admin/issues")).text();188 expect(list).toContain('href="/admin/issues/app/1"');189 expect(list).toContain('href="/admin/issues/hush/1"');190 expect(list).toContain("Crash <on> start");191 const page = await (await operator.get("/admin/issues/app/1")).text();192 expect(page).toContain("contact: [email protected]");193 expect(await text("/app/issues/1")).not.toContain("[email protected]");194 });195196 test("an operator reply shows on the public thread, marked", async () => {197 expect((await act({ action: "reply", body: "Fixed <soon>." })).status).toBe(303);198 expect((await act({ action: "reply", body: " " })).status).toBe(400);199 const thread = await text("/app/issues/1");200 expect(thread).toContain('<span class="issue-badge">operator</span>');201 expect(thread).toContain("Fixed <soon>.");202 });203204 test("close with a fixed-in save prefix, then reopen", async () => {205 expect((await act({ action: "close", fixed_in: "zzzzzz" })).status).toBe(400);206 expect((await act({ action: "close", fixed_in: "0123456789ab" })).status).toBe(400);207 expect((await act({ action: "close", fixed_in: save.slice(0, 6) })).status).toBe(303);208 const thread = await text("/app/issues/1");209 expect(thread).toContain("◈ closed");210 expect(thread).toContain(`fixed in <a class="history-id" href="/app/saves/${save}">`);211 expect(await text("/app/issues?status=closed")).toContain('href="/app/issues/1"');212 expect(await (await operator.get("/admin/issues?filter=closed")).text()).toContain(213 'href="/admin/issues/app/1"',214 );215 expect((await act({ action: "reopen" })).status).toBe(303);216 expect(await text("/app/issues/1")).toContain("◉ open");217 expect(await text("/app/issues/1")).not.toContain("fixed in");218 });219220 test("set type, and hide for spam: gone publicly, kept in the console", async () => {221 expect((await act({ action: "type", type: "nonsense" })).status).toBe(400);222 expect((await act({ action: "type", type: "idea" })).status).toBe(303);223 expect(await text("/app/issues")).toContain("#1 · idea");224 expect((await act({ action: "hide" })).status).toBe(303);225 expect((await inst.app.request("/app/issues/1")).status).toBe(404);226 expect(await (await operator.get("/admin/issues")).text()).not.toContain("/admin/issues/app/1");227 expect(await (await operator.get("/admin/issues?filter=hidden")).text()).toContain(228 'href="/admin/issues/app/1"',229 );230 expect((await act({ action: "unhide" })).status).toBe(303);231 expect((await inst.app.request("/app/issues/1")).status).toBe(200);232 expect((await act({ action: "delete" })).status).toBe(400);233 expect((await operator.post("/admin/issues/app/9", { action: "reopen" })).status).toBe(404);234 });235});236237function fileIssueDirect(inst: Instance, repo: string): void {238 fileIssue(inst.kepr, {239 repo,240 title: `A ${repo} issue`,241 body: "b",242 type: "bug",243 version: "",244 reporterName: "",245 contactEmail: "",246 ipHash: "x",247 filedAt: 1,248 });249}250251describe("releases: counts, displayed notes and hiding", () => {252 let inst: Instance;253 let operator: Browser;254 const text = async (path: string) => (await inst.app.request(path)).text();255 const edit = (version: string, fields: Record<string, string>) =>256 operator.post(`/admin/releases/app/${version}`, fields);257258 beforeAll(async () => {259 const repos = await makeRepos(["app"]);260 const save = repos.saves.app as string;261 for (const version of ["1.0.0", "1.1.0"]) {262 await writeRelease(repos.bucketDir, "app", {263 version,264 save,265 notes: `notes for ${version}`,266 files: [{ platform: "linux-x86_64", name: "app", bytes: new Uint8Array([1]) }],267 });268 }269 inst = await instance(repos.bucketDir);270 operator = new Browser(inst.app);271 await operator.signIn();272 await operator.post("/admin/repos/app", { public: "1", sort_order: "0" });273 await inst.app.request("/app/releases/1.1.0/linux-x86_64");274 });275276 test("every version is listed with its download counts and notes", async () => {277 const page = await (await operator.get("/admin/releases")).text();278 expect(page).toContain('id="app-1.1.0"');279 expect(page).toContain('id="app-1.0.0"');280 expect(page.indexOf('id="app-1.1.0"')).toBeLessThan(page.indexOf('id="app-1.0.0"'));281 expect(page).toContain('<span>1 download</span><span class="muted">linux-x86_64 1</span>');282 expect(page).toContain(">notes for 1.1.0</textarea>");283 });284285 test("edited notes replace the record's everywhere; the record's own text clears the edit", async () => {286 expect((await edit("1.1.0", { notes: "Better <notes>." })).status).toBe(303);287 expect(JSON.parse(await text("/api/app/releases/latest")).notes).toBe("Better <notes>.");288 expect(await text("/app/releases")).toContain("Better <notes>.");289 expect(await (await operator.get("/admin/releases")).text()).toContain("(edited)");290 expect((await edit("1.1.0", { notes: "notes for 1.1.0" })).status).toBe(303);291 const row = inst.kepr.query("SELECT notes FROM release_settings WHERE version = '1.1.0'").get();292 expect(row).toEqual({ notes: null });293 expect((await edit("1.1.0", { notes: "x".repeat(20_001) })).status).toBe(400);294 });295296 test("a hidden version leaves pages, latest and every feed, and stays in the console", async () => {297 expect((await edit("1.1.0", { notes: "notes for 1.1.0", hidden: "1" })).status).toBe(303);298 expect(await text("/app/releases/latest/version.txt")).toBe("1.0.0");299 expect(JSON.parse(await text("/api/app/releases/latest")).version).toBe("1.0.0");300 expect(await text("/api/app/releases/history")).not.toContain("1.1.0");301 expect(await text("/app/releases")).not.toContain("1.1.0");302 expect((await inst.app.request("/app/releases/1.1.0/linux-x86_64")).status).toBe(404);303 const page = await (await operator.get("/admin/releases")).text();304 expect(page).toContain('id="app-1.1.0"');305 expect(page).toContain('value="1" checked> hidden');306 expect((await edit("1.1.0", { notes: "notes for 1.1.0" })).status).toBe(303);307 expect(await text("/app/releases/latest/version.txt")).toBe("1.1.0");308 expect((await edit("9.9.9", { notes: "" })).status).toBe(404);309 expect((await operator.post("/admin/releases/nowhere/1.0.0", { notes: "" })).status).toBe(404);310 });311});312313describe("site and profile settings, and the signature upload", () => {314 let inst: Instance;315 let operator: Browser;316 const PNG = Uint8Array.from(317 atob(318 "iVBORw0KGgoAAAANSUhEUgAAAAEAAAABCAYAAAAfFcSJAAAADUlEQVR42mNk+M9QDwADhgGAWjR9awAAAABJRU5ErkJggg==",319 ),320 (ch) => ch.charCodeAt(0),321 );322 const settings = {323 site_name: "ada's library",324 tagline: "Small <tools>.",325 branding: "by ada",326 handle: "ada",327 bio: "Writes code.",328 location: "Lisbon",329 link: "https://ada.example",330 building_since: "june 2026",331 };332 const text = async (path: string) => (await inst.app.request(path)).text();333 const upload = (bytes: Uint8Array | string, name: string, type: string, extra = {}) => {334 const form = new FormData();335 for (const [key, value] of Object.entries({ ...settings, ...extra })) form.set(key, value);336 form.set("signature", new File([bytes], name, { type }));337 return operator.post("/admin/site", form);338 };339 const signature = () =>340 inst.kepr.query("SELECT value FROM settings WHERE key = 'signature'").get();341342 beforeAll(async () => {343 const repos = await makeRepos(["app"]);344 inst = await instance(repos.bucketDir);345 operator = new Browser(inst.app);346 await operator.signIn();347 });348349 test("settings are saved and every public page reads them", async () => {350 expect((await operator.post("/admin/site", settings)).status).toBe(303);351 const front = await text("/");352 expect(front).toContain("<title>ada's library</title>");353 expect(front).toContain("Small <tools>.");354 expect(front).toContain('<span class="wordmark-by">by ada</span>');355 const profile = await text("/@ada");356 for (const value of [357 "Writes code.",358 "Lisbon",359 'href="https://ada.example"',360 "building since june 2026",361 ]) {362 expect(profile).toContain(value);363 }364 expect(await (await operator.get("/admin/site")).text()).toContain('value="Lisbon"');365 366 expect((await operator.post("/admin/site", { ...settings, site_name: "" })).status).toBe(303);367 expect(await text("/")).toContain("<title>kepr</title>");368 });369370 test("a bad handle, link or overlong field is refused", async () => {371 for (const bad of [372 { handle: "a/b" },373 { link: "javascript:alert(1)" },374 { bio: "x".repeat(2001) },375 ]) {376 expect((await operator.post("/admin/site", { ...settings, ...bad })).status).toBe(400);377 }378 expect((await inst.app.request("/@ada")).status).toBe(200);379 });380381 test("a PNG signature is stored in data/assets and shown on the profile", async () => {382 expect((await upload(PNG, "sig.png", "image/png")).status).toBe(303);383 const name = (signature() as { value: string }).value;384 expect(name).toMatch(/^signature-[0-9a-f]{16}\.png$/);385 expect(await Bun.file(join(inst.dataDir, "assets", name)).exists()).toBe(true);386 expect(await text("/@ada")).toContain(387 `<img class="profile-signature" src="/static/assets/${name}"`,388 );389 const served = await inst.app.request(`/static/assets/${name}`);390 expect(served.headers.get("content-type")).toBe("image/png");391 expect(new Uint8Array(await served.arrayBuffer())).toEqual(PNG);392 });393394 test("SVG, or anything whose bytes are not PNG, JPEG or WebP, is refused whatever it claims", async () => {395 const before = signature();396 const svg = '<svg xmlns="http://www.w3.org/2000/svg"><script>alert(1)</script></svg>';397 expect((await upload(svg, "sig.svg", "image/svg+xml")).status).toBe(400);398 expect((await upload(svg, "sig.png", "image/png")).status).toBe(400);399 expect((await upload("GIF89a", "sig.gif", "image/gif")).status).toBe(400);400 expect(signature()).toEqual(before);401 expect((await upload(new Uint8Array(70 * 1024), "big.png", "image/png")).status).toBe(413);402 403 const png = (size: number) => {404 const bytes = new Uint8Array(size);405 bytes.set(PNG);406 return bytes;407 };408 const over = await upload(png(60 * 1024 + 1), "big.png", "image/png");409 expect(over.status).toBe(400);410 expect(await over.text()).toContain("The signature must be under 60 KB.");411 expect(signature()).toEqual(before);412 expect((await upload(png(60 * 1024), "edge.png", "image/png")).status).toBe(303);413 });414415 test("a new signature replaces the old file; removing it brings the handle back", async () => {416 const old = (signature() as { value: string }).value;417 const webp = new Uint8Array([0x52, 0x49, 0x46, 0x46, 0, 0, 0, 0, 0x57, 0x45, 0x42, 0x50, 1]);418 expect((await upload(webp, "sig.webp", "image/webp")).status).toBe(303);419 const name = (signature() as { value: string }).value;420 expect(name).toMatch(/\.webp$/);421 expect(await Bun.file(join(inst.dataDir, "assets", old)).exists()).toBe(false);422 expect(423 (await operator.post("/admin/site", { ...settings, remove_signature: "1" })).status,424 ).toBe(303);425 expect(signature()).toBeNull();426 expect(await Bun.file(join(inst.dataDir, "assets", name)).exists()).toBe(false);427 expect(await text("/@ada")).toContain('<h1 class="profile-username">ada</h1>');428 });429});