1import { beforeAll, describe, expect, test } from "bun:test";2import { 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 } from "../src/mirror/queries.ts";9import { openMirror } from "../src/mirror/store.ts";10import { createApp } from "../src/server/app.ts";11import { openKeprDb } from "../src/server/db.ts";12import { type Fixture, makeKohBucket } from "./fixture.ts";1314let fx: Fixture;15let app: Hono;16let mirrorDir: string;17let tailSaves: string[];18const get = (path: string) => app.request(path);19const body = async (path: string) => (await get(path)).text();2021beforeAll(async () => {22 fx = await makeKohBucket();23 const secretRepo = await makeKohBucket("hidden");24 const large = await makeKohBucket("large");25 26 await writeFile(27 join(large.repoDir, "big.txt"),28 `${"a".repeat(1024 * 1024 - 1)}é${"b".repeat(1000)}\n`,29 );30 await writeFile(join(large.repoDir, "big.bin"), new Uint8Array(1024 * 1024 + 500).fill(0xff));31 Bun.spawnSync(["koh3", "save", "add large files"], {32 cwd: large.repoDir,33 env: { PATH: process.env.PATH, HOME: join(large.repoDir, "../../home"), NO_COLOR: "1" },34 });35 36 const tail = await makeKohBucket("tail");37 const tailEnv = { PATH: process.env.PATH, HOME: join(tail.repoDir, "../../home"), NO_COLOR: "1" };38 for (const [text, message] of [39 ["a\nb", "add tail"],40 ["a\nb\n", "end tail with a newline"],41 ["a\nb", "drop the newline"],42 ] as const) {43 await writeFile(join(tail.repoDir, "tail.txt"), text);44 Bun.spawnSync(["koh3", "save", message], { cwd: tail.repoDir, env: tailEnv });45 }46 tailSaves = JSON.parse(47 Bun.spawnSync(["koh3", "log", "--json"], { cwd: tail.repoDir, env: tailEnv }).stdout.toString(),48 ).saves.map((save: { id: string }) => save.id);49 const dataDir = await mkdtemp(join(tmpdir(), "kepr-pages-"));50 mirrorDir = join(dataDir, "mirror");51 const kepr = openKeprDb(dataDir);52 for (const bucketDir of [fx.bucketDir, secretRepo.bucketDir, large.bucketDir, tail.bucketDir]) {53 const bucket = openBucket({ kind: "folder", path: bucketDir });54 await syncAll({ bucket, kepr, mirrorDir, tarballDir: join(dataDir, "tarballs") });55 }56 kepr.run(57 "UPDATE repos SET public = 1, install1 = 'nix profile add x', homepage = 'https://demo.example' WHERE name = 'demo'",58 );59 kepr.run("UPDATE repos SET public = 1 WHERE name IN ('large', 'tail')");60 app = createApp(61 {62 domain: "kepr.example",63 dataDir,64 adminPasswordHash: "$argon2id$x",65 bucket: { kind: "folder", path: fx.bucketDir },66 },67 kepr,68 );69});7071const [head, , second, first] = [0, 1, 2, 3].map((i) => () => fx.saveIds[i] as string);7273describe("the visibility gate", () => {74 test("a private repo and an unknown one are the same 404, everywhere", async () => {75 for (const suffix of ["", "/files/src/main.ts", "/raw/src/main.ts"]) {76 const hidden = await get(`/hidden${suffix}`);77 const missing = await get(`/nowhere${suffix}`);78 expect(hidden.status).toBe(404);79 expect(missing.status).toBe(404);80 expect((await hidden.text()).replaceAll("/hidden", "/nowhere")).toBe(await missing.text());81 }82 });83});8485describe("the repo page", () => {86 test("renders header, timeline, history and README at HEAD with a short cache", async () => {87 const response = await get("/demo");88 expect(response.status).toBe(200);89 expect(response.headers.get("cache-control")).toBe("public, max-age=60");90 const page = await response.text();91 expect(page).toContain('<h1 class="repo-name">demo</h1>');92 93 expect(/<div class="repo-desc"><p>(.*?)<\/p>/.exec(page)?.[1]).toBe(94 "A small repo for <strong>Kepr's</strong> tests.",95 );96 expect(page).toContain(97 '<meta property="og:description" content="A small repo for Kepr's tests.">',98 );99 expect(page).toContain('href="https://demo.example"');100 expect(page).toContain('<span class="lang-badge">TypeScript</span>');101 expect(page).toContain("3 saves");102 expect(page).toContain('data-copy="nix profile add x"');103 expect(page.match(/class="dot d\d"/g)?.length).toBe(3);104 expect(page).toContain("density = activity · position = time");105 const history = [...page.matchAll(/class="history-id">([0-9a-f]+)</g)].map((m) => m[1]);106 expect(history).toEqual([head(), second(), first()]);107 });108109 test("checkpoints never appear", async () => {110 expect(await body("/demo")).not.toContain(fx.saveIds[1] as string);111 });112113 test("the README points relative links and images at raw files and drops unsafe links", async () => {114 const page = await body("/demo");115 expect(page).toContain('<a href="/demo/raw/docs/guide.md">the guide</a>');116 expect(page).toContain('<img src="/demo/raw/docs/logo.png" alt="logo">');117 expect(page).toContain('<a href="https://example.com">the site</a>');118 expect(page).not.toContain('href="javascript:');119 expect(page).toContain("<script>alert");120 expect(page).not.toContain("<script>alert");121 });122});123124describe("the file viewer", () => {125 test("shows a file at HEAD and at an old save, with line anchors", async () => {126 const now = await get("/demo/files/src/main.ts");127 expect(now.headers.get("cache-control")).toBe("public, max-age=60");128 const nowPage = await now.text();129 expect(nowPage).toContain("hello");130 expect(nowPage).toContain(131 '<span class="line" id="L2"><a class="ln" href="#L2">2</a><span class="lc">',132 );133 expect(nowPage).toContain('class="tk-');134135 const then = await get(`/demo/files/src/main.ts?at=${second().slice(0, 6)}`);136 expect(then.headers.get("cache-control")).toBe("private, max-age=31536000");137 const thenPage = await then.text();138 expect(thenPage).toContain("'hi'");139 expect(thenPage).not.toContain("hello");140 expect(thenPage).toContain(`/demo/raw/src/main.ts?at=${second()}`);141 });142143 test("a file absent at that save, a bad save or an unsafe path is a 404", async () => {144 expect((await get(`/demo/files/src/main.ts?at=${first()}`)).status).toBe(404);145 expect((await get("/demo/files/src/main.ts?at=zzzzzz")).status).toBe(404);146 expect((await get("/demo/files/src/main.ts?at=abc")).status).toBe(404);147 expect((await get("/demo/files/src%2F..%2FREADME.md")).status).toBe(404);148 expect((await get("/demo/files/nothing.txt")).status).toBe(404);149 });150151 test("Markdown renders, with a source toggle", async () => {152 const rendered = await body("/demo/files/docs/guide.md");153 expect(rendered).toContain("<h1>Guide</h1>");154 const source = await body("/demo/files/docs/guide.md?view=source");155 expect(source).toContain('id="L1"');156 expect(source).not.toContain("<h1>Guide</h1>");157 });158159 test("an image displays inline from its raw file", async () => {160 expect(await body("/demo/files/docs/logo.png")).toContain('<img src="/demo/raw/docs/logo.png"');161 });162});163164describe("files over 1 MB", () => {165 test("text shows its first 1 MB with a raw link, even with a character cut at the mark", async () => {166 const page = await body("/large/files/big.txt");167 expect(page).toContain("showing the first 1 MB");168 expect(page).toContain('href="/large/raw/big.txt"');169 expect(page).not.toContain("bbb");170 const raw = await get("/large/raw/big.txt");171 expect(raw.headers.get("content-type")).toBe("text/plain; charset=utf-8");172 });173174 test("invalid UTF-8 without a NUL is binary, not text", async () => {175 const page = await body("/large/files/big.bin");176 expect(page).toContain("binary file");177 expect(page).not.toContain('class="code"');178 const raw = await get("/large/raw/big.bin");179 expect(raw.headers.get("content-type")).toBe("application/octet-stream");180 });181});182183describe("the Atlas", () => {184 185 const panelOf = (page: string, name: string) =>186 new RegExp(`data-name="${name}">.*?</a>\\n<template>(.*?)</template>`, "s").exec(page)?.[1] ??187 "";188 const rowOf = (page: string, name: string) =>189 new RegExp(`data-name="${name}">(.*?)</a>`, "s").exec(page)?.[1] ?? "";190191 test("sits between the timeline and History", async () => {192 const page = await body("/demo");193 const atlas = page.indexOf('id="atlas"');194 expect(page.indexOf('class="timeline"')).toBeLessThan(atlas);195 expect(atlas).toBeLessThan(page.indexOf('id="history"'));196 });197198 test("is a folder tree, folders first, then files, alphabetical", async () => {199 const names = [...(await body("/demo")).matchAll(/class="atlas-name">([^<]*)</g)].map(200 (m) => m[1],201 );202 expect(names).toEqual([203 "docs/",204 "guide.md",205 "logo.png",206 "src/",207 "lib/",208 "deep/",209 "util.ts",210 "main.ts",211 "vendor/",212 "big.c",213 ".kohignore",214 "README.md",215 "secret.txt",216 ]);217 });218219 test("rows carry the first sentence of the file's own comment, rendered, and link to the file", async () => {220 const page = await body("/demo");221 expect(rowOf(page, "util.ts")).toContain(222 '<span class="atlas-desc">The <em>one</em> helper.</span>',223 );224 expect(rowOf(page, "main.ts")).toContain("Entry point.");225 expect(rowOf(page, "guide.md")).toContain('<span class="atlas-desc">Read me.</span>');226 expect(rowOf(page, "secret.txt")).toContain('<span class="atlas-desc"></span>');227 expect(page).toContain(228 '<a class="atlas-row atlas-file" href="/demo/files/src/main.ts" data-name="main.ts">',229 );230 expect(panelOf(page, "util.ts")).toContain("<p>The <em>one</em> helper. Deep down.</p>");231 });232233 test("the panel counts only real saves, crediting a checkpoint's change to the next save", async () => {234 const page = await body("/demo");235 const main = panelOf(page, "main.ts");236 expect(main).toContain("<dt>lines</dt><dd>2</dd>");237 expect(main).toContain("<dt>saves</dt><dd>2</dd>");238 expect(main).toContain(`<dt>first save</dt><dd><a href="/demo/saves/${second()}">`);239 expect(main).toContain(`<dt>last save</dt><dd><a href="/demo/saves/${head()}">`);240 expect(main.indexOf(head())).toBeLessThan(main.lastIndexOf(second()));241 const guide = panelOf(page, "guide.md");242 expect(guide).toContain("<dt>saves</dt><dd>2</dd>");243 expect(guide).toContain(`<dt>last save</dt><dd><a href="/demo/saves/${head()}">`);244 expect(panelOf(page, "logo.png")).toContain("<dt>lines</dt><dd>binary</dd>");245 expect(page).not.toContain(fx.saveIds[1] as string);246 });247248 test("a folder's panel sums its files and counts the saves that touched anything under it", async () => {249 const page = await body("/demo");250 const folderPanel = (path: string) =>251 new RegExp(252 `data-path="${path}">\\n<summary.*?</summary>\\n<template>(.*?)</template>`,253 "s",254 ).exec(page)?.[1] ?? "";255 const docs = folderPanel("docs");256 expect(docs).toContain('<p class="atlas-info-path mono">docs</p>');257 expect(docs).toContain("<dt>lines</dt><dd>3</dd>");258 expect(docs).toContain("<dt>files</dt><dd>2</dd>");259 expect(docs).toContain("<dt>saves</dt><dd>2</dd>");260 expect(docs).toContain(`<dt>first save</dt><dd><a href="/demo/saves/${first()}">`);261 expect(docs).toContain(`<dt>last save</dt><dd><a href="/demo/saves/${head()}">`);262 const src = folderPanel("src");263 expect(src).toContain("<dt>saves</dt><dd>3</dd>");264 const recentIds = [265 ...(/<ul class="atlas-recent">(.*?)<\/ul>/s.exec(src)?.[1] ?? "").matchAll(266 /saves\/([0-9a-f]+)/g,267 ),268 ].map((m) => m[1]);269 expect(recentIds).toEqual([head(), second(), first()]);270 });271272 test("can be viewed at an older save, and an unknown save is a 404", async () => {273 const page = await body(`/demo?at=${second().slice(0, 8)}`);274 expect(page).toContain(`at <a href="/demo/saves/${second()}">${second()}</a>`);275 expect(page).toContain(`href="/demo/files/src/main.ts?at=${second()}"`);276 expect(panelOf(page, "main.ts")).toContain("<dt>saves</dt><dd>1</dd>");277 expect(panelOf(page, "main.ts")).not.toContain(head());278 const oldest = await body(`/demo?at=${first()}`);279 expect(oldest).not.toContain('data-name="main.ts"');280 expect((await get("/demo?at=abcdef")).status).toBe(404);281 expect((await get("/demo?at=../x")).status).toBe(404);282 });283});284285describe("the save page", () => {286 test("shows the save's facts and diffs against the previous real save, skipping the checkpoint", async () => {287 const response = await get(`/demo/saves/${head()}`);288 expect(response.status).toBe(200);289 expect(response.headers.get("cache-control")).toBe("public, max-age=60");290 const page = await response.text();291 expect(page).toContain('<h1 class="save-message-head">say hello</h1>');292 expect(page).toContain(293 `<dt>parent</dt><dd><a href="/demo/saves/${second()}">${second()}</a></dd>`,294 );295 expect(page).not.toContain(fx.saveIds[1] as string);296 expect(page).not.toContain("save-flag");297 298 const rows = [299 ...page.matchAll(300 /class="change-row change-(\w+)" href="#diff-\d"><span class="change-path">([^<]+)</g,301 ),302 ];303 expect(rows.map((m) => [m[1], m[2]])).toEqual([304 ["modified", "docs/guide.md"],305 ["modified", "src/main.ts"],306 ]);307 expect(page).toContain('<span class="diff-add">+1</span> <span class="diff-del">−1</span>');308 expect(page).toContain('<span class="dh">@@ -1,2 +1,2 @@</span>');309 expect(page).toContain(310 '<span class="dl dl-del"><span class="ln">2</span><span class="ln"></span><span class="ds">-</span>',311 );312 expect(page).toContain('class="tk-');313 expect(page).toContain(`href="/demo/archive/${head()}.tar.gz"`);314 expect(page).toContain(`href="/demo?at=${head()}#atlas"`);315 });316317 test("the first save diffs against nothing, notes binaries, and shows its flag and agent", async () => {318 const page = await body(`/demo/saves/${first()}`);319 expect(page).toContain('<span class="save-flag-label mono">flagged</span> holds a secret');320 expect(page).toContain("<dt>parent</dt><dd>none, the first save</dd>");321 expect(page).toContain(322 'change-added" href="#diff-2"><span class="change-path">docs/logo.png</span><span class="change-stat mono"><span class="diff-note">binary</span>',323 );324 expect(page).toContain("binary file, not shown");325 expect(page).toContain('<span class="dh">@@ -0,0 +1 @@</span>');326 const second_ = await body(`/demo/saves/${second()}`);327 expect(second_).toContain("<dt>agent</dt><dd>test-agent</dd><dt>session</dt><dd>fixture</dd>");328 expect(second_).not.toContain("save-flag");329 });330331 test("a change to the final newline alone is a changed last line, marked as in GNU diff", async () => {332 const marker = '<span class="dh">\\ No newline at end of file</span>';333 const row = (kind: string, a: string, b: string, sign: string) =>334 `<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>`;335 const gained = await body(`/tail/saves/${tailSaves[1]}`);336 expect(gained).toContain('<span class="diff-add">+1</span> <span class="diff-del">−1</span>');337 expect(gained).toContain(`${row("del", "2", "", "-")}${marker}${row("add", "", "2", "+")}<`);338 const lost = await body(`/tail/saves/${tailSaves[0]}`);339 expect(lost).toContain(`${row("del", "2", "", "-")}${row("add", "", "2", "+")}${marker}`);340 });341342 test("a prefix redirects, and a checkpoint, an unknown or a private save is a 404", async () => {343 const short = await get(`/demo/saves/${head().slice(0, 6)}`);344 expect(short.status).toBe(302);345 expect(short.headers.get("location")).toBe(`/demo/saves/${head()}`);346 expect((await get(`/demo/saves/${fx.saveIds[1]}`)).status).toBe(404);347 expect((await get("/demo/saves/abcdef")).status).toBe(404);348 expect((await get("/demo/saves/abc")).status).toBe(404);349 expect((await get(`/hidden/saves/${head()}`)).status).toBe(404);350 });351});352353describe("raw files", () => {354 test("are the exact object bytes, text as text/plain", async () => {355 const mirror = openMirror(mirrorDir, "demo");356 for (const [path, type] of [357 ["src/main.ts", "text/plain; charset=utf-8"],358 ["docs/logo.png", "image/png"],359 ["README.md", "text/plain; charset=utf-8"],360 ] as const) {361 const response = await get(`/demo/raw/${path}`);362 const file = fileAt(mirror, head(), path);363 expect(response.headers.get("content-type")).toBe(type);364 expect(new Uint8Array(await response.arrayBuffer())).toEqual(365 objectBytes(mirror, file?.hash as string) as Uint8Array<ArrayBuffer>,366 );367 }368 expect(await (await get(`/demo/raw/src/main.ts?at=${second()}`)).text()).toContain("'hi'");369 });370});371372test("static assets are served and the CSP allows Bunny Fonts but no inline script", async () => {373 const css = await get("/static/css/kepr.css");374 expect(css.status).toBe(200);375 expect(css.headers.get("content-type")).toContain("text/css");376 expect((await get("/static/../package.json")).status).toBe(404);377 const csp = (await get("/demo")).headers.get("content-security-policy") ?? "";378 expect(csp).toContain("style-src 'self' https://fonts.bunny.net");379 expect(csp).toContain("font-src https://fonts.bunny.net");380 expect(csp).not.toContain("unsafe-inline");381});382383describe("housekeeping routes", () => {384 test("robots.txt points at the sitemap, which lists public repos only", async () => {385 expect(await body("/robots.txt")).toBe(386 "User-agent: *\nAllow: /\n\nSitemap: https://kepr.example/sitemap.xml\n",387 );388 const sitemap = await get("/sitemap.xml");389 expect(sitemap.headers.get("Content-Type")).toBe("application/xml; charset=UTF-8");390 const xml = await sitemap.text();391 expect(xml).toStartWith('<?xml version="1.0" encoding="UTF-8"?>\n<urlset');392 for (const repo of ["demo", "large", "tail"]) {393 expect(xml).toContain(`<loc>https://kepr.example/${repo}</loc>`);394 }395 expect(xml).not.toContain("hidden");396 });397398 test("favicon.svg is Kepr 2's mark, and every page links it", async () => {399 const res = await get("/favicon.svg");400 expect(res.headers.get("Content-Type")).toBe("image/svg+xml");401 expect(await res.text()).toContain('<polygon points="16,3 27,23 5,23"');402 expect(await body("/demo")).toContain(403 '<link rel="icon" href="/favicon.svg" type="image/svg+xml">',404 );405 });406});