1import { Database } from "bun:sqlite";2import { beforeAll, describe, expect, test } from "bun:test";3import { mkdir, mkdtemp, writeFile } 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 { fileAt, objectBytes, type Save } from "../src/mirror/queries.ts";10import { openMirror } from "../src/mirror/store.ts";11import { repoCards } from "../src/pages/library.ts";12import { timelineSvg } from "../src/pages/timeline.ts";13import { createApp } from "../src/server/app.ts";14import { openKeprDb } from "../src/server/db.ts";15import { type Fixture, makeKohBucket } from "./fixture.ts";1617let fx: Fixture;18let app: Hono;19let mirrorDir: string;20let tailSaves: string[];21const get = (path: string) => app.request(path);22const body = async (path: string) => (await get(path)).text();2324beforeAll(async () => {25 fx = await makeKohBucket();26 const secretRepo = await makeKohBucket("hidden");27 const large = await makeKohBucket("large");28 29 await writeFile(30 join(large.repoDir, "big.txt"),31 `${"a".repeat(1024 * 1024 - 1)}é${"b".repeat(1000)}\n`,32 );33 await writeFile(join(large.repoDir, "big.bin"), new Uint8Array(1024 * 1024 + 500).fill(0xff));34 Bun.spawnSync(["koh3", "save", "add large files"], {35 cwd: large.repoDir,36 env: { PATH: process.env.PATH, HOME: join(large.repoDir, "../../home"), NO_COLOR: "1" },37 });38 39 const tail = await makeKohBucket("tail");40 const tailEnv = { PATH: process.env.PATH, HOME: join(tail.repoDir, "../../home"), NO_COLOR: "1" };41 for (const [text, message] of [42 ["a\nb", "add tail"],43 ["a\nb\n", "end tail with a newline"],44 ["a\nb", "drop the newline"],45 ] as const) {46 await writeFile(join(tail.repoDir, "tail.txt"), text);47 Bun.spawnSync(["koh3", "save", message], { cwd: tail.repoDir, env: tailEnv });48 }49 tailSaves = JSON.parse(50 Bun.spawnSync(["koh3", "view", "--json"], {51 cwd: tail.repoDir,52 env: tailEnv,53 }).stdout.toString(),54 ).saves.map((save: { id: string }) => save.id);55 const dataDir = await mkdtemp(join(tmpdir(), "kepr-pages-"));56 await mkdir(join(dataDir, "assets"));57 await writeFile(join(dataDir, "assets", "plain.txt"), "asset\n");58 const kepr = openKeprDb(dataDir);59 mirrorDir = join(dataDir, "mirror");60 for (const bucketDir of [fx.bucketDir, secretRepo.bucketDir, large.bucketDir, tail.bucketDir]) {61 const bucket = openBucket({ kind: "folder", path: bucketDir });62 await syncAll({ bucket, kepr, mirrorDir, tarballDir: join(dataDir, "tarballs") });63 }64 kepr.run(65 "UPDATE repos SET public = 1, install1 = 'nix profile add x', homepage = 'https://demo.example' WHERE name = 'demo'",66 );67 kepr.run("UPDATE repos SET public = 1 WHERE name IN ('large', 'tail')");68 app = createApp(69 {70 domain: "kepr.example",71 dataDir,72 adminPasswordHash: "$argon2id$x",73 bucket: { kind: "folder", path: fx.bucketDir },74 },75 kepr,76 );77});7879const [head, , second, first] = [0, 1, 2, 3].map((i) => () => fx.saveIds[i] as string);8081describe("the visibility gate", () => {82 test("a private repo and an unknown one are the same 404, everywhere", async () => {83 for (const suffix of ["", "/files/src/main.ts", "/raw/src/main.ts"]) {84 const hidden = await get(`/hidden${suffix}`);85 const missing = await get(`/nowhere${suffix}`);86 expect(hidden.status).toBe(404);87 expect(missing.status).toBe(404);88 expect((await hidden.text()).replaceAll("/hidden", "/nowhere")).toBe(await missing.text());89 }90 });91});9293describe("the repo page", () => {94 test("renders header, timeline, history and README at HEAD with a short cache", async () => {95 const response = await get("/demo");96 expect(response.status).toBe(200);97 expect(response.headers.get("cache-control")).toBe("public, max-age=60");98 const page = await response.text();99 expect(page).toContain('<h1 class="repo-name">demo</h1>');100 101 expect(/<div class="repo-desc"><p>(.*?)<\/p>/.exec(page)?.[1]).toBe(102 "A small repo for <strong>Kepr's</strong> tests.",103 );104 expect(page).toContain(105 '<meta property="og:description" content="A small repo for Kepr's tests.">',106 );107 expect(page).toContain('href="https://demo.example"');108 expect(page).toContain('<span class="lang-badge">TypeScript</span>');109 expect(page).toContain("3 saves");110 expect(page).toContain('data-copy="nix profile add x"');111 expect(page.match(/class="dot d\d"/g)?.length).toBe(3);112 expect(page).toContain("density = activity · position = time");113 const history = [...page.matchAll(/class="history-id">([0-9a-f]+)</g)].map((m) => m[1]);114 expect(history).toEqual([head(), second(), first()]);115 });116117 test("a page past the last, or too large to bind, is page 1", async () => {118 const history = (page: string) => [...page.matchAll(/class="history-id">([0-9a-f]+)</g)];119 for (const query of ["?page=2", `?page=${"9".repeat(400)}`, "?page=1e999", "?page=x"]) {120 const response = await get(`/demo${query}`);121 expect([query, response.status]).toEqual([query, 200]);122 expect(history(await response.text()).length).toBe(3);123 }124 });125126 test("checkpoints never appear", async () => {127 expect(await body("/demo")).not.toContain(fx.saveIds[1] as string);128 });129130 test("the README points relative links and images at raw files and drops unsafe links", async () => {131 const page = await body("/demo");132 expect(page).toContain('<a href="/demo/raw/docs/guide.md">the guide</a>');133 expect(page).toContain('<img src="/demo/raw/docs/logo.png" alt="logo">');134 expect(page).toContain('<a href="https://example.com">the site</a>');135 expect(page).not.toContain('href="javascript:');136 expect(page).toContain("<script>alert");137 expect(page).not.toContain("<script>alert");138 });139});140141describe("the timeline and card ticks", () => {142 143 const saves = [300, 100, 500, 200].map(144 (created_at, i): Save => ({145 id: `00000000000${i}`,146 parent: "",147 message: "m",148 created_at: created_at * 86400,149 machine: "m",150 agent: "",151 session: "",152 is_checkpoint: false,153 }),154 );155156 test("span from the earliest to the latest save, whatever the line's order", () => {157 const dots = [...timelineSvg("demo", saves).value.matchAll(/cx="([\d.]+)%"/g)].map((m) => m[1]);158 expect(dots).toEqual(["50.000", "1.000", "99.000", "25.500"]);159 const card = repoCards([160 {161 settings: { name: "demo", category: "", homepage: "", installLines: [] },162 mirror: new Database(":memory:"),163 stats: { saves: 4, lines: 0, language: "", updated: null },164 description: "",165 saves,166 },167 ]).value;168 const ticks = [...card.matchAll(/<line x1="([\d.]+)"/g)].map((m) => m[1]);169 expect(ticks).toEqual(["50.00", "1.00", "99.00", "25.50"]);170 });171});172173describe("the file viewer", () => {174 test("shows a file at HEAD and at an old save, with line anchors", async () => {175 const now = await get("/demo/files/src/main.ts");176 expect(now.headers.get("cache-control")).toBe("public, max-age=60");177 const nowPage = await now.text();178 expect(nowPage).toContain("hello");179 expect(nowPage).toContain(180 '<span class="line" id="L2"><a class="ln" href="#L2">2</a><span class="lc">',181 );182 expect(nowPage).toContain('class="tk-');183184 const then = await get(`/demo/files/src/main.ts?at=${second().slice(0, 6)}`);185 expect(then.headers.get("cache-control")).toBe("private, max-age=31536000");186 const thenPage = await then.text();187 expect(thenPage).toContain("'hi'");188 expect(thenPage).not.toContain("hello");189 expect(thenPage).toContain(`/demo/raw/src/main.ts?at=${second()}`);190 });191192 test("a file absent at that save, a bad save or an unsafe path is a 404", async () => {193 expect((await get(`/demo/files/src/main.ts?at=${first()}`)).status).toBe(404);194 expect((await get("/demo/files/src/main.ts?at=zzzzzz")).status).toBe(404);195 expect((await get("/demo/files/src/main.ts?at=abc")).status).toBe(404);196 expect((await get("/demo/files/src%2F..%2FREADME.md")).status).toBe(404);197 expect((await get("/demo/files/nothing.txt")).status).toBe(404);198 });199200 test("Markdown renders, with a source toggle", async () => {201 const rendered = await body("/demo/files/docs/guide.md");202 expect(rendered).toContain("<h1>Guide</h1>");203 const source = await body("/demo/files/docs/guide.md?view=source");204 expect(source).toContain('id="L1"');205 expect(source).not.toContain("<h1>Guide</h1>");206 });207208 test("an image displays inline from its raw file", async () => {209 expect(await body("/demo/files/docs/logo.png")).toContain('<img src="/demo/raw/docs/logo.png"');210 });211});212213describe("files over 1 MB", () => {214 test("text shows its first 1 MB with a raw link, even with a character cut at the mark", async () => {215 const page = await body("/large/files/big.txt");216 expect(page).toContain("showing the first 1 MB");217 expect(page).toContain('href="/large/raw/big.txt"');218 expect(page).not.toContain("bbb");219 const raw = await get("/large/raw/big.txt");220 expect(raw.headers.get("content-type")).toBe("text/plain; charset=utf-8");221 });222223 test("invalid UTF-8 without a NUL is binary, not text", async () => {224 const page = await body("/large/files/big.bin");225 expect(page).toContain("binary file");226 expect(page).not.toContain('class="code"');227 const raw = await get("/large/raw/big.bin");228 expect(raw.headers.get("content-type")).toBe("application/octet-stream");229 });230});231232describe("the Atlas", () => {233 234 const panelOf = (page: string, name: string) =>235 new RegExp(`data-name="${name}">.*?</a>\\n<template>(.*?)</template>`, "s").exec(page)?.[1] ??236 "";237 const rowOf = (page: string, name: string) =>238 new RegExp(`data-name="${name}">(.*?)</a>`, "s").exec(page)?.[1] ?? "";239240 test("sits between the timeline and History", async () => {241 const page = await body("/demo");242 const atlas = page.indexOf('id="atlas"');243 expect(page.indexOf('class="timeline"')).toBeLessThan(atlas);244 expect(atlas).toBeLessThan(page.indexOf('id="history"'));245 });246247 test("is a folder tree, folders first, then files, alphabetical", async () => {248 const names = [...(await body("/demo")).matchAll(/class="atlas-name">([^<]*)</g)].map(249 (m) => m[1],250 );251 expect(names).toEqual([252 "docs/",253 "guide.md",254 "logo.png",255 "src/",256 "lib/",257 "deep/",258 "util.ts",259 "main.ts",260 "vendor/",261 "big.c",262 ".kohignore",263 "README.md",264 "secret.txt",265 ]);266 });267268 test("rows carry the first sentence of the file's own comment, rendered, and link to the file", async () => {269 const page = await body("/demo");270 expect(rowOf(page, "util.ts")).toContain(271 '<span class="atlas-desc">The <em>one</em> helper.</span>',272 );273 expect(rowOf(page, "main.ts")).toContain("Entry point.");274 expect(rowOf(page, "guide.md")).toContain('<span class="atlas-desc">Read me.</span>');275 expect(rowOf(page, "secret.txt")).toContain('<span class="atlas-desc"></span>');276 expect(page).toContain(277 '<a class="atlas-row atlas-file" href="/demo/files/src/main.ts" data-name="main.ts">',278 );279 expect(panelOf(page, "util.ts")).toContain("<p>The <em>one</em> helper. Deep down.</p>");280 });281282 test("the panel counts only real saves, crediting a checkpoint's change to the next save", async () => {283 const page = await body("/demo");284 const main = panelOf(page, "main.ts");285 expect(main).toContain("<dt>lines</dt><dd>2</dd>");286 expect(main).toContain("<dt>saves</dt><dd>2</dd>");287 expect(main).toContain(`<dt>first save</dt><dd><a href="/demo/saves/${second()}">`);288 expect(main).toContain(`<dt>last save</dt><dd><a href="/demo/saves/${head()}">`);289 expect(main.indexOf(head())).toBeLessThan(main.lastIndexOf(second()));290 const guide = panelOf(page, "guide.md");291 expect(guide).toContain("<dt>saves</dt><dd>2</dd>");292 expect(guide).toContain(`<dt>last save</dt><dd><a href="/demo/saves/${head()}">`);293 expect(panelOf(page, "logo.png")).toContain("<dt>lines</dt><dd>binary</dd>");294 expect(page).not.toContain(fx.saveIds[1] as string);295 });296297 test("a folder's panel sums its files and counts the saves that touched anything under it", async () => {298 const page = await body("/demo");299 const folderPanel = (path: string) =>300 new RegExp(301 `data-path="${path}">\\n<summary.*?</summary>\\n<template>(.*?)</template>`,302 "s",303 ).exec(page)?.[1] ?? "";304 const docs = folderPanel("docs");305 expect(docs).toContain('<p class="atlas-info-path mono">docs</p>');306 expect(docs).toContain("<dt>lines</dt><dd>3</dd>");307 expect(docs).toContain("<dt>files</dt><dd>2</dd>");308 expect(docs).toContain("<dt>saves</dt><dd>2</dd>");309 expect(docs).toContain(`<dt>first save</dt><dd><a href="/demo/saves/${first()}">`);310 expect(docs).toContain(`<dt>last save</dt><dd><a href="/demo/saves/${head()}">`);311 const src = folderPanel("src");312 expect(src).toContain("<dt>saves</dt><dd>3</dd>");313 const recentIds = [314 ...(/<ul class="atlas-recent">(.*?)<\/ul>/s.exec(src)?.[1] ?? "").matchAll(315 /saves\/([0-9a-f]+)/g,316 ),317 ].map((m) => m[1]);318 expect(recentIds).toEqual([head(), second(), first()]);319 });320321 test("can be viewed at an older save, and an unknown save is a 404", async () => {322 const page = await body(`/demo?at=${second().slice(0, 8)}`);323 expect(page).toContain(`at <a href="/demo/saves/${second()}">${second()}</a>`);324 expect(page).toContain(`href="/demo/files/src/main.ts?at=${second()}"`);325 expect(panelOf(page, "main.ts")).toContain("<dt>saves</dt><dd>1</dd>");326 expect(panelOf(page, "main.ts")).not.toContain(head());327 const oldest = await body(`/demo?at=${first()}`);328 expect(oldest).not.toContain('data-name="main.ts"');329 expect((await get("/demo?at=abcdef")).status).toBe(404);330 expect((await get("/demo?at=../x")).status).toBe(404);331 });332});333334describe("the save page", () => {335 test("shows the save's facts and diffs against the previous real save, skipping the checkpoint", async () => {336 const response = await get(`/demo/saves/${head()}`);337 expect(response.status).toBe(200);338 expect(response.headers.get("cache-control")).toBe("public, max-age=60");339 const page = await response.text();340 expect(page).toContain('<h1 class="save-message-head">say hello</h1>');341 expect(page).toContain(342 `<dt>parent</dt><dd><a href="/demo/saves/${second()}">${second()}</a></dd>`,343 );344 expect(page).not.toContain(fx.saveIds[1] as string);345 expect(page).not.toContain("save-flag");346 347 const rows = [348 ...page.matchAll(349 /class="change-row change-(\w+)" href="#diff-\d"><span class="change-path">([^<]+)</g,350 ),351 ];352 expect(rows.map((m) => [m[1], m[2]])).toEqual([353 ["modified", "docs/guide.md"],354 ["modified", "src/main.ts"],355 ]);356 expect(page).toContain('<span class="diff-add">+1</span> <span class="diff-del">−1</span>');357 expect(page).toContain('<span class="dh">@@ -1,2 +1,2 @@</span>');358 expect(page).toContain(359 '<span class="dl dl-del"><span class="ln">2</span><span class="ln"></span><span class="ds">-</span>',360 );361 expect(page).toContain('class="tk-');362 expect(page).toContain(`href="/demo/archive/${head()}.tar.gz"`);363 expect(page).toContain(`href="/demo?at=${head()}#atlas"`);364 });365366 test("the first save diffs against nothing, notes binaries, and shows its flag and agent", async () => {367 const page = await body(`/demo/saves/${first()}`);368 expect(page).toContain('<span class="save-flag-label mono">flagged</span> holds a secret');369 expect(page).toContain("<dt>parent</dt><dd>none, the first save</dd>");370 expect(page).toContain(371 'change-added" href="#diff-2"><span class="change-path">docs/logo.png</span><span class="change-stat mono"><span class="diff-note">binary</span>',372 );373 expect(page).toContain("binary file, not shown");374 expect(page).toContain('<span class="dh">@@ -0,0 +1 @@</span>');375 const second_ = await body(`/demo/saves/${second()}`);376 expect(second_).toContain("<dt>agent</dt><dd>test-agent</dd><dt>session</dt><dd>fixture</dd>");377 expect(second_).not.toContain("save-flag");378 });379380 test("a change to the final newline alone is a changed last line, marked as in GNU diff", async () => {381 const marker = '<span class="dh">\\ No newline at end of file</span>';382 const row = (kind: string, a: string, b: string, sign: string) =>383 `<span class="dl dl-${kind}"><span class="ln">${a}</span><span class="ln">${b}</span><span class="ds">${sign}</span><span class="lc">b</span></span>`;384 const gained = await body(`/tail/saves/${tailSaves[1]}`);385 expect(gained).toContain('<span class="diff-add">+1</span> <span class="diff-del">−1</span>');386 expect(gained).toContain(`${row("del", "2", "", "-")}${marker}${row("add", "", "2", "+")}<`);387 const lost = await body(`/tail/saves/${tailSaves[0]}`);388 expect(lost).toContain(`${row("del", "2", "", "-")}${row("add", "", "2", "+")}${marker}`);389 });390391 test("a prefix redirects, and a checkpoint, an unknown or a private save is a 404", async () => {392 const short = await get(`/demo/saves/${head().slice(0, 6)}`);393 expect(short.status).toBe(302);394 expect(short.headers.get("location")).toBe(`/demo/saves/${head()}`);395 expect((await get(`/demo/saves/${fx.saveIds[1]}`)).status).toBe(404);396 expect((await get("/demo/saves/abcdef")).status).toBe(404);397 expect((await get("/demo/saves/abc")).status).toBe(404);398 expect((await get(`/hidden/saves/${head()}`)).status).toBe(404);399 });400});401402describe("raw files", () => {403 test("are the exact object bytes, text as text/plain", async () => {404 const mirror = openMirror(mirrorDir, "demo");405 for (const [path, type] of [406 ["src/main.ts", "text/plain; charset=utf-8"],407 ["docs/logo.png", "image/png"],408 ["README.md", "text/plain; charset=utf-8"],409 ] as const) {410 const response = await get(`/demo/raw/${path}`);411 const file = fileAt(mirror, head(), path);412 expect(response.headers.get("content-type")).toBe(type);413 expect(new Uint8Array(await response.arrayBuffer())).toEqual(414 objectBytes(mirror, file?.hash as string) as Uint8Array<ArrayBuffer>,415 );416 }417 expect(await (await get(`/demo/raw/src/main.ts?at=${second()}`)).text()).toContain("'hi'");418 });419});420421test("static assets and raw files carry route-based sandboxing", async () => {422 const css = await get("/static/css/kepr.css");423 expect(css.status).toBe(200);424 expect(css.headers.get("content-type")).toContain("text/css");425 const raw = await get("/demo/raw/README.md");426 expect(raw.headers.get("content-security-policy")).toContain("sandbox");427 const asset = await get("/static/assets/plain.txt");428 expect(asset.headers.get("content-security-policy")).toContain("sandbox");429 const favicon = await get("/favicon.svg");430 expect(favicon.headers.get("content-type")).toBe("image/svg+xml");431 expect(favicon.headers.get("content-security-policy")).not.toContain("sandbox");432 expect((await get("/static/../package.json")).status).toBe(404);433 const csp = (await get("/demo")).headers.get("content-security-policy") ?? "";434 expect(csp).toContain("style-src 'self' https://fonts.bunny.net");435 expect(csp).toContain("font-src https://fonts.bunny.net");436 expect(csp).not.toContain("unsafe-inline");437});438439describe("housekeeping routes", () => {440 test("robots.txt points at the sitemap, which lists public repos only", async () => {441 expect(await body("/robots.txt")).toBe(442 "User-agent: *\nAllow: /\n\nSitemap: https://kepr.example/sitemap.xml\n",443 );444 const sitemap = await get("/sitemap.xml");445 expect(sitemap.headers.get("Content-Type")).toBe("application/xml; charset=UTF-8");446 const xml = await sitemap.text();447 expect(xml).toStartWith('<?xml version="1.0" encoding="UTF-8"?>\n<urlset');448 for (const repo of ["demo", "large", "tail"]) {449 expect(xml).toContain(`<loc>https://kepr.example/${repo}</loc>`);450 }451 expect(xml).not.toContain("hidden");452 });453454 test("favicon.svg is Kepr 2's mark, and every page links it", async () => {455 const res = await get("/favicon.svg");456 expect(res.headers.get("Content-Type")).toBe("image/svg+xml");457 expect(await res.text()).toContain('<polygon points="16,3 27,23 5,23"');458 expect(await body("/demo")).toContain(459 '<link rel="icon" href="/favicon.svg" type="image/svg+xml">',460 );461 });462});