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