1import type { Database } from "bun:sqlite";2import { afterAll, beforeAll, describe, expect, setSystemTime, test } from "bun:test";3import { mkdtemp } from "node:fs/promises";4import { tmpdir } from "node:os";5import { join } from "node:path";6import type { Hono } from "hono";7import { openBucket } from "../src/bucket/reader.ts";8import { syncAll } from "../src/bucket/sync.ts";9import {10 addEntry,11 blockReporter,12 fileIssue,13 filingsSince,14 findIssue,15 isBlocked,16 issueCounts,17 listIssues,18 type NewIssue,19 threadEntries,20 unblockReporter,21} from "../src/issues/store.ts";22import { createApp } from "../src/server/app.ts";23import { openKeprDb } from "../src/server/db.ts";24import { makeRepos, writeRelease } from "./fixture.ts";2526const newIssue = (repo: string, title: string, filedAt = 1000): NewIssue => ({27 repo,28 title,29 body: "It broke.",30 type: "bug",31 version: "1.0.0",32 reporterName: "",33 contactEmail: "[email protected]",34 ipHash: "ip-a",35 filedAt,36});3738describe("issue data layer", async () => {39 const db = openKeprDb(await mkdtemp(join(tmpdir(), "kepr-issues-")));4041 test("numbers are per repo and continue after an imported number", () => {42 expect(fileIssue(db, newIssue("app", "one")).number).toBe(1);43 expect(fileIssue(db, newIssue("app", "two")).number).toBe(2);44 expect(fileIssue(db, newIssue("lib", "first")).number).toBe(1);45 db.run(46 "INSERT INTO issues (repo, number, title, body, type, filed_at) VALUES ('lib', 41, 'from kepr 2', 'x', 'idea', 5)",47 );48 expect(fileIssue(db, newIssue("lib", "next")).number).toBe(42);49 });5051 test("refuses a child row whose parent issue is missing", () => {52 expect(() =>53 db.run(54 "INSERT INTO issue_entries (issue_id, author, body, created_at) VALUES (9999, 'reporter', 'x', 0)",55 ),56 ).toThrow();57 });5859 test("public reads leave out contact and IP", () => {60 const issue = findIssue(db, "app", fileIssue(db, newIssue("app", "secret")).number);61 expect(Object.keys(issue ?? {})).not.toContain("contact_email");62 expect(Object.keys(issue ?? {})).not.toContain("ip_hash");63 });6465 test("hidden issues vanish from lists, counts and lookups but still count against the IP", () => {66 const before = filingsSince(db, "ip-a", 0);67 const { number } = fileIssue(db, newIssue("app", "spam"));68 db.run("UPDATE issues SET hidden = 1 WHERE repo = 'app' AND number = ?", [number]);69 expect(findIssue(db, "app", number)).toBeNull();70 expect(listIssues(db, "app", "open").map((i) => i.title)).not.toContain("spam");71 expect(issueCounts(db, "app")).toEqual({ open: 3, closed: 0 });72 expect(filingsSince(db, "ip-a", 0)).toBe(before + 1);73 expect(filingsSince(db, "ip-a", 1000)).toBe(0);74 });7576 test("the thread keeps replies in order with their author, name and the reply they answer", () => {77 const issue = findIssue(db, "app", 1);78 if (!issue) throw new Error("issue 1 missing");79 const first = addEntry(db, issue.id, {80 author: "reporter",81 name: "Bo",82 body: "More.",83 at: 2000,84 });85 addEntry(db, issue.id, { author: "operator", body: "Thanks.", at: 3000, replyTo: first });86 expect(threadEntries(db, issue.id).map((e) => [e.author, e.name, e.body, e.reply_to])).toEqual([87 ["reporter", "Bo", "More.", null],88 ["operator", "", "Thanks.", first],89 ]);90 expect(listIssues(db, "app", "open").find((i) => i.number === 1)?.replies).toBe(2);91 });9293 test("a block from a reply takes that reply's address, and only a reply of that issue", () => {94 const [one, two] = [findIssue(db, "app", 1), findIssue(db, "app", 2)];95 if (!one || !two) throw new Error("issues missing");96 const at = 4000;97 const reply = addEntry(db, one.id, { author: "reporter", body: "x", at, ipHash: "ip-r" });98 expect(blockReporter(db, two.id, at, reply)).toBeNull();99 const block = blockReporter(db, one.id, at, reply) as number;100 expect(isBlocked(db, "ip-r")).toBe(true);101 expect(isBlocked(db, "ip-a")).toBe(false);102 unblockReporter(db, block);103 });104});105106describe("issues end to end over HTTP", () => {107 let app: Hono;108 let kepr: Database;109 let save: string;110 let clock = Date.parse("2026-09-26T12:00:00Z");111 const tick = (seconds: number) => {112 clock += seconds * 1000;113 setSystemTime(new Date(clock));114 };115 116 type Session = { cookie: string; stamp: string };117 const openForm = async (path = "/app/issues/new", cookie = ""): Promise<Session> => {118 const response = await app.request(path, { headers: cookie ? { cookie } : {} });119 const set = response.headers.get("set-cookie")?.split(";")[0] ?? cookie;120 const stamp = /name="stamp" value="([^"]+)"/.exec(await response.text())?.[1] ?? "";121 return { cookie: set, stamp };122 };123 const post = (124 path: string,125 session: Session,126 fields: Record<string, string>,127 peer = "203.0.113.9",128 forwardedFor = "",129 ) =>130 app.request(131 path,132 {133 method: "POST",134 headers: {135 cookie: session.cookie,136 ...(forwardedFor && { "x-forwarded-for": forwardedFor }),137 },138 body: new URLSearchParams({ stamp: session.stamp, website: "", ...fields }),139 },140 141 { requestIP: () => ({ address: peer }) },142 );143 const issue = {144 title: "Crash on <start>",145 body: "It <b>crashed</b>.",146 type: "bug",147 version: "1.2.0",148 };149 const page = async (path: string) => (await app.request(path)).text();150 const postFiles = (path: string, session: Session, body: string, files: File[]) => {151 const form = new FormData();152 form.append("stamp", session.stamp);153 form.append("website", "");154 form.append("body", body);155 for (const file of files) form.append("files", file);156 return app.request(157 path,158 { method: "POST", headers: { cookie: session.cookie }, body: form },159 { requestIP: () => ({ address: "203.0.113.9" }) },160 );161 };162163 beforeAll(async () => {164 setSystemTime(new Date(clock));165 const repos = await makeRepos(["app", "secret"]);166 save = repos.saves.app as string;167 await writeRelease(repos.bucketDir, "app", {168 version: "1.2.0",169 save,170 files: [{ platform: "linux-x86_64", name: "app", bytes: new Uint8Array([1]) }],171 });172 const dataDir = await mkdtemp(join(tmpdir(), "kepr-issues-e2e-"));173 kepr = openKeprDb(dataDir);174 const bucket = { kind: "folder" as const, path: repos.bucketDir };175 await syncAll({176 bucket: openBucket(bucket),177 kepr,178 mirrorDir: join(dataDir, "mirror"),179 });180 kepr.run("UPDATE repos SET public = 1 WHERE name = 'app'");181 app = createApp(182 { domain: "kepr.example", dataDir, adminPasswordHash: "$argon2id$x", bucket },183 kepr,184 );185 });186 afterAll(() => setSystemTime());187188 test("the form prefills the newest release, sets a strict same-site cookie and is never cached", async () => {189 const response = await app.request("/app/issues/new");190 expect(response.status).toBe(200);191 expect(response.headers.get("cache-control")).toBe("no-store");192 expect(response.headers.get("set-cookie")).toContain("SameSite=Strict");193 const text = await response.text();194 expect(text).toContain('name="version" maxlength="200" value="1.2.0"');195 expect(text).toContain('name="website"');196 });197198 test("refuses a too-fast, honeypot or cross-site submission", async () => {199 const session = await openForm();200 expect((await post("/app/issues/new", session, issue)).status).toBe(400);201 tick(3);202 expect((await post("/app/issues/new", session, { ...issue, website: "x" })).status).toBe(400);203 expect((await post("/app/issues/new", { ...session, cookie: "" }, issue)).status).toBe(403);204 const other = await openForm();205 expect(206 (await post("/app/issues/new", { ...session, cookie: other.cookie }, issue)).status,207 ).toBe(403);208 expect((await page("/app/issues")).includes("Crash")).toBe(false);209 });210211 test("refuses a field over 20,000 characters and keeps what was typed", async () => {212 const session = await openForm();213 tick(5);214 const response = await post("/app/issues/new", session, { ...issue, body: "x".repeat(20_001) });215 expect(response.status).toBe(400);216 expect(await response.text()).toContain("x".repeat(100));217 });218219 test("filing goes straight to the new issue", async () => {220 const session = await openForm();221 tick(4);222 const response = await post("/app/issues/new", session, {223 ...issue,224 name: "Ada",225 email: "[email protected]",226 });227 expect(response.status).toBe(303);228 expect(response.headers.get("location")).toBe("/app/issues/1");229 });230231 test("the list and thread show the issue escaped, with its name and never its email", async () => {232 const list = await page("/app/issues");233 expect(list).toContain("Crash on <start>");234 expect(list).toContain("#1 · bug · v1.2.0");235 expect(list).toContain('name="q"');236 expect(list).toContain('name="type"');237 expect(list).toContain("Ada");238 expect(await page("/app/issues?q=missing")).not.toContain('href="/app/issues/1"');239 expect(await page("/app/issues?type=question")).not.toContain('href="/app/issues/1"');240 expect(await page("/app/issues?q=CRASH&type=bug")).toContain('href="/app/issues/1"');241 expect(list).not.toContain("[email protected]");242 const response = await app.request("/app/issues/1");243 expect(response.headers.get("referrer-policy")).toBe("no-referrer");244 expect(response.headers.get("cache-control")).toBe("no-store");245 const thread = await response.text();246 expect(thread).toContain("It <b>crashed</b>.");247 expect(thread).toContain('<span class="issue-author">Ada</span>');248 expect(thread).not.toContain("[email protected]");249 expect(thread).toContain('href="/app/issues">back to issues</a>');250 expect(thread).toContain('<form class="issue-composer" id="reply"');251 });252253 let bobsReply = 0;254255 test("anyone can reply, in Markdown with raw HTML escaped and links marked as theirs", async () => {256 const session = await openForm("/app/issues/1");257 tick(3);258 const body =259 "Still <broken>.\n```\nlog line\n```\n**worse** [site](https://example.com) [x](javascript:alert(1))";260 const response = await post("/app/issues/1", session, { body, name: "Bob" }, "198.51.100.30");261 expect(response.status).toBe(303);262 const entry = /^\/app\/issues\/1#entry-(\d+)$/.exec(response.headers.get("location") ?? "");263 bobsReply = Number(entry?.[1]);264 expect(bobsReply).toBeGreaterThan(0);265 const thread = await page("/app/issues/1");266 expect(thread).toContain("Still <broken>.");267 expect(thread).toContain("<pre><code>log line");268 expect(thread).toContain("<strong>worse</strong>");269 expect(thread).toContain('<a href="https://example.com" rel="nofollow ugc noopener">site</a>');270 expect(thread).not.toContain('href="javascript:');271 expect(thread).toContain('<span class="issue-author">Bob</span>');272 expect(await page("/app/issues")).toContain("· 1 reply");273 });274275 test("a picture in a reply shows its words, never a request for the image", async () => {276 const session = await openForm("/app/issues/1");277 tick(3);278 const body =279 "\n" +280 "\n" +281 "[docs](https://example.com)";282 expect((await post("/app/issues/1", session, { body, name: "Cy" })).status).toBe(303);283 const thread = await page("/app/issues/1");284 expect(thread).not.toContain("<img");285 expect(thread).not.toContain('src="https://elsewhere.example/chart.png"');286 expect(thread).toContain("chart");287 expect(thread).toContain(288 '<a href="https://elsewhere.example/blank.png" rel="nofollow ugc noopener">https://elsewhere.example/blank.png</a>',289 );290 expect(thread).toContain('<a href="https://example.com" rel="nofollow ugc noopener">docs</a>');291 });292293 test("quote starts a reply with the post quoted, and the reply shows what it answers", async () => {294 const quoted = await page(`/app/issues/1?quote=${bobsReply}`);295 expect(quoted).toContain(`name="reply_to" value="${bobsReply}"`);296 expect(quoted).toContain("> Still <broken>.\n> ```");297 expect(await page("/app/issues/1?quote=0")).toContain("> It <b>crashed");298 expect(await page("/app/issues/1?reply=999999")).toContain('name="reply_to" value=""');299 const session = await openForm("/app/issues/1");300 tick(3);301 const reply = { body: "Same here.", reply_to: String(bobsReply) };302 expect((await post("/app/issues/1", session, reply)).status).toBe(303);303 const thread = await page("/app/issues/1");304 expect(thread).toContain(`replying to\n<a href="#entry-${bobsReply}">Bob</a>`);305 expect(thread).toContain('<span class="issue-author">anonymous</span>');306 });307308 test("pictures and logs attach to a reply, are judged by their bytes, and hide with it", async () => {309 const session = await openForm("/app/issues/1");310 tick(3);311 const png = new Uint8Array([0x89, 0x50, 0x4e, 0x47, 0x0d, 0x0a, 0x1a, 0x0a, 1, 2, 3]);312 const disguised = new File(["<svg onload=alert(1)>"], "shot.png", { type: "image/png" });313 expect((await postFiles("/app/issues/1", session, "x", [disguised])).status).toBe(400);314 const five = Array.from({ length: 5 }, (_, i) => new File([png], `${i}.png`));315 expect((await postFiles("/app/issues/1", session, "x", five)).status).toBe(400);316 const files = [317 new File([png], "shot.png"),318 new File([png], "report.html"),319 new File(["one\nline <two>\n"], "crash.log"),320 ];321 expect((await postFiles("/app/issues/1", session, "See attached.", files)).status).toBe(303);322 const thread = await page("/app/issues/1");323 expect(thread).toContain("line <two>");324 const shots = [...thread.matchAll(/src="(\/app\/issues\/1\/files\/\d+\.png)"/g)].map(325 (m) => m[1] ?? "",326 );327 expect(shots).toHaveLength(2);328 const shot = shots[0] ?? "";329 330 expect((await app.request(shots[1] ?? "")).headers.get("content-disposition")).toContain(331 "report.png",332 );333 const log = /href="(\/app\/issues\/1\/files\/\d+\.txt)"/.exec(thread)?.[1] ?? "";334 const image = await app.request(shot);335 expect(image.headers.get("content-type")).toBe("image/png");336 expect(image.headers.get("content-security-policy")).toContain("sandbox");337 expect(new Uint8Array(await image.arrayBuffer())).toEqual(png);338 expect((await app.request(log)).headers.get("content-type")).toBe("text/plain; charset=utf-8");339 expect((await app.request(shot.replace(".png", ".gif"))).status).toBe(404);340 kepr.run("UPDATE issue_entries SET hidden = 1 WHERE body = 'See attached.'");341 expect((await app.request(shot)).status).toBe(404);342 expect(await page("/app/issues/1")).not.toContain(shot);343 });344345 test("a refused reply keeps what was typed", async () => {346 const session = await openForm("/app/issues/1");347 tick(3);348 const response = await post("/app/issues/1", session, { body: "y".repeat(20_001), name: "Cy" });349 expect(response.status).toBe(400);350 const text = await response.text();351 expect(text).toContain("y".repeat(100));352 expect(text).toContain('value="Cy"');353 expect((await post("/app/issues/1", session, { body: " " })).status).toBe(400);354 });355356 test("twenty replies an hour per address", async () => {357 const session = await openForm("/app/issues/1");358 tick(3);359 const from = (peer: string) => post("/app/issues/1", session, { body: "more" }, peer);360 for (let i = 0; i < 20; i++) expect((await from("198.51.100.50")).status).toBe(303);361 expect((await from("198.51.100.50")).status).toBe(429);362 expect((await from("198.51.100.51")).status).toBe(303);363 kepr.run("UPDATE issue_entries SET hidden = 1 WHERE body = 'more'");364 });365366 test("five filings an hour per peer address, and a forged X-Forwarded-For does not help", async () => {367 const session = await openForm();368 tick(3);369 const from = (peer: string, forwardedFor = "") =>370 post("/app/issues/new", session, issue, peer, forwardedFor);371 for (let i = 0; i < 5; i++) {372 expect((await from("198.51.100.7", `192.0.2.${i}`)).status).toBe(303);373 }374 expect((await from("198.51.100.7", "192.0.2.99")).status).toBe(429);375 expect((await from("198.51.100.8")).status).toBe(303);376 tick(3601);377 expect((await from("198.51.100.7")).status).toBe(303);378 379 const plain = new Bun.CryptoHasher("sha256").update("198.51.100.7").digest("hex");380 const stored = kepr381 .query<{ ip_hash: string }, []>("SELECT ip_hash FROM issues WHERE ip_hash != ''")382 .all()383 .map((row) => row.ip_hash);384 expect(stored.every((hash) => /^[0-9a-f]{64}$/.test(hash) && hash !== plain)).toBe(true);385 });386387 test("behind a proxy on loopback, the rightmost X-Forwarded-For entry is the client", async () => {388 const session = await openForm();389 tick(3);390 const via = (peer: string, forwardedFor: string) =>391 post("/app/issues/new", session, issue, peer, forwardedFor);392 393 for (let i = 0; i < 5; i++) {394 expect((await via("127.0.0.1", `10.9.9.${i}, 198.51.100.20`)).status).toBe(303);395 }396 expect((await via("::1", "198.51.100.20")).status).toBe(429);397 expect((await via("::ffff:127.0.0.1", "10.9.9.9, 198.51.100.20")).status).toBe(429);398 expect((await via("127.0.0.1", "198.51.100.20, 198.51.100.21")).status).toBe(303);399 });400401 test("an operator reply and a close show on the thread, which then takes no replies", async () => {402 const found = findIssue(kepr, "app", 1);403 if (!found) throw new Error("issue 1 missing");404 const session = await openForm("/app/issues/1");405 addEntry(kepr, found.id, { author: "operator", body: "Fixed, thanks.", at: clock / 1000 });406 kepr.run("UPDATE issues SET status = 'closed', closed_at = 1, fixed_in = ? WHERE id = ?", [407 save,408 found.id,409 ]);410 const thread = await page("/app/issues/1");411 expect(thread).toContain('<article class="issue-post issue-post--operator"');412 expect(thread).toContain('<span class="issue-badge">operator</span>');413 expect(thread).toContain("Fixed, thanks.");414 expect(thread).toContain("◈ closed");415 expect(thread).toContain('href="/app/issues?status=closed">back to issues</a>');416 expect(thread).toContain(` · fixed in <a class="history-id" href="/app/saves/${save}">`);417 expect(thread).not.toContain('id="reply"');418 expect(thread).toContain("takes no new replies");419 tick(3);420 expect((await post("/app/issues/1", session, { body: "Late." })).status).toBe(403);421 expect(await page("/app/issues")).not.toContain('href="/app/issues/1"');422 expect(await page("/app/issues?status=closed")).toContain('href="/app/issues/1"');423 });424425 test("hidden issues and every issue route of a private repo are 404", async () => {426 kepr.run("UPDATE issues SET hidden = 1 WHERE repo = 'app' AND number = 2");427 expect((await app.request("/app/issues/2")).status).toBe(404);428 expect((await app.request("/app/issues/999")).status).toBe(404);429 kepr.run(430 "INSERT INTO issues (repo, number, title, body, type, filed_at) VALUES ('secret', 1, 't', 'b', 'bug', 1)",431 );432 for (const path of ["/secret/issues", "/secret/issues/new", "/secret/issues/1"]) {433 expect((await app.request(path)).status).toBe(404);434 }435 const session = await openForm();436 for (const path of ["/secret/issues/new", "/secret/issues/1"]) {437 expect((await post(path, session, { ...issue, body: "x" })).status).toBe(404);438 }439 });440441 test("a blocked address can neither file nor reply, until it is unblocked", async () => {442 const first = findIssue(kepr, "app", 1);443 if (!first) throw new Error("issue 1 missing");444 const block = blockReporter(kepr, first.id, 1) as number;445 const filing = await openForm();446 const thread = await openForm("/app/issues/3", filing.cookie);447 tick(4);448 const refused = await post("/app/issues/new", filing, issue);449 expect(refused.status).toBe(403);450 expect(await refused.text()).toContain("This address can't post here.");451 const reply = { body: "Blocked words." };452 expect((await post("/app/issues/3", thread, reply)).status).toBe(403);453 expect((await post("/app/issues/new", filing, issue, "198.51.100.8")).status).toBe(303);454 unblockReporter(kepr, block);455 expect((await post("/app/issues/3", thread, reply)).status).toBe(303);456 });457});