1import type { 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 { timelineSaves, timelineSvg } from "../src/pages/timeline.ts";12import { createApp } from "../src/server/app.ts";13import { openKeprDb } from "../src/server/db.ts";14import { type Fixture, KOH_BIN, makeKohBucket } from "./fixture.ts";1516let fx: Fixture;17let app: Hono;18let kepr: Database;19let mirrorDir: string;20let tailSaves: string[];21const get = (path: string) => app.request(path);22const body = async (path: string) => (await get(path)).text();2324const historyIds = (page: string) => {25 const list = /data-list="history">(.*?)<\/div>/s.exec(page)?.[1] ?? "";26 return [...list.matchAll(/class="history-id">([0-9a-f]+)</g)].map((m) => m[1]);27};2829beforeAll(async () => {30 fx = await makeKohBucket();31 const secretRepo = await makeKohBucket("hidden");32 const large = await makeKohBucket("large");33 34 await writeFile(35 join(large.repoDir, "big.txt"),36 `${"a".repeat(1024 * 1024 - 1)}é${"b".repeat(1000)}\n`,37 );38 await writeFile(join(large.repoDir, "big.bin"), new Uint8Array(1024 * 1024 + 500).fill(0xff));39 Bun.spawnSync([KOH_BIN, "save", "add large files"], {40 cwd: large.repoDir,41 env: { PATH: process.env.PATH, HOME: join(large.repoDir, "../../home"), NO_COLOR: "1" },42 });43 44 const tail = await makeKohBucket("tail");45 const tailEnv = { PATH: process.env.PATH, HOME: join(tail.repoDir, "../../home"), NO_COLOR: "1" };46 for (const [text, message] of [47 ["a\nb", "add tail"],48 ["a\nb\n", "end tail with a newline"],49 ["a\nb", "drop the newline"],50 ] as const) {51 await writeFile(join(tail.repoDir, "tail.txt"), text);52 Bun.spawnSync([KOH_BIN, "save", message], { cwd: tail.repoDir, env: tailEnv });53 }54 tailSaves = JSON.parse(55 Bun.spawnSync([KOH_BIN, "view", "--json"], {56 cwd: tail.repoDir,57 env: tailEnv,58 }).stdout.toString(),59 ).saves.map((save: { id: string }) => save.id);60 const dataDir = await mkdtemp(join(tmpdir(), "kepr-pages-"));61 await mkdir(join(dataDir, "assets"));62 await writeFile(join(dataDir, "assets", "plain.txt"), "asset\n");63 kepr = openKeprDb(dataDir);64 mirrorDir = join(dataDir, "mirror");65 for (const bucketDir of [fx.bucketDir, secretRepo.bucketDir, large.bucketDir, tail.bucketDir]) {66 const bucket = openBucket({ kind: "folder", path: bucketDir });67 await syncAll({ bucket, kepr, mirrorDir });68 }69 kepr.run("UPDATE repos SET public = 1, homepage = 'https://demo.example' WHERE name = 'demo'");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).not.toContain('class="install-line"');114 expect(page.match(/<circle 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("the issues tab counts only this repo's visible open issues and hides zero", async () => {122 kepr.run("BEGIN");123 try {124 kepr.run(`INSERT INTO issues (repo, number, title, body, type, filed_at, hidden, status) VALUES125('demo', 1, 'one', 'body', 'bug', 1, 0, 'open'),126('demo', 2, 'two', 'body', 'bug', 1, 0, 'open'),127('demo', 3, 'three', 'body', 'bug', 1, 0, 'open'),128('demo', 4, 'hidden', 'body', 'bug', 1, 1, 'open'),129('demo', 5, 'closed', 'body', 'bug', 1, 0, 'closed'),130('large', 1, 'another repo', 'body', 'bug', 1, 0, 'open')`);131 expect(await body("/demo")).toContain(132 '<span class="repo-issue-count" aria-label="3 open issues">3</span>',133 );134 kepr.run("UPDATE issues SET status = 'closed' WHERE repo = 'demo' AND number = 1");135 expect(await body("/demo")).toContain(136 '<span class="repo-issue-count" aria-label="2 open issues">2</span>',137 );138 kepr.run("UPDATE issues SET status = 'closed' WHERE repo = 'demo' AND number = 2");139 expect(await body("/demo")).toContain(140 '<span class="repo-issue-count" aria-label="1 open issue">1</span>',141 );142 kepr.run("UPDATE issues SET status = 'closed' WHERE repo = 'demo'");143 expect(await body("/demo")).not.toContain('class="repo-issue-count"');144 } finally {145 kepr.run("ROLLBACK");146 }147 });148149 test("a page past the last, or too large to bind, is page 1", async () => {150 for (const query of ["?page=2", `?page=${"9".repeat(400)}`, "?page=1e999", "?page=x"]) {151 const response = await get(`/demo${query}`);152 expect([query, response.status]).toEqual([query, 200]);153 expect(historyIds(await response.text()).length).toBe(3);154 }155 });156157 test("checkpoints never appear", async () => {158 expect(await body("/demo")).not.toContain(fx.saveIds[1] as string);159 });160161 test("the README points relative links and images at raw files and drops unsafe links", async () => {162 const page = await body("/demo");163 expect(page).toContain('<a href="/demo/raw/docs/guide.md">the guide</a>');164 expect(page).toContain('<img src="/demo/raw/docs/logo.png" alt="logo">');165 expect(page).toContain('<a href="https://example.com">the site</a>');166 expect(page).not.toContain('href="javascript:');167 expect(page).toContain("<script>alert");168 expect(page).not.toContain("<script>alert");169 });170});171172describe("the timeline", () => {173 174 const saves = [300, 100, 500, 200].map(175 (created_at, i): Save => ({176 id: `00000000000${i}`,177 parent: "",178 message: "m",179 created_at: created_at * 86400,180 machine: "m",181 agent: "",182 session: "",183 is_checkpoint: false,184 }),185 );186187 test("span from the earliest to the latest save, whatever the line's order", () => {188 const dots = [...timelineSvg("demo", saves).value.matchAll(/cx="([\d.]+)%"/g)].map((m) => m[1]);189 expect(dots).toEqual(["50.000", "1.000", "99.000", "25.500"]);190 });191192 test("a dot's neighbours are counted within a fractional reach exactly", () => {193 194 const at = (created_at: number) => ({ ...(saves[0] as Save), created_at });195 const svg = timelineSvg("demo", [at(0), at(3601), at(144001)]).value;196 expect(svg.match(/class="dot d(\d)"/g)).toEqual([197 'class="dot d0"',198 'class="dot d0"',199 'class="dot d0"',200 ]);201 });202203 test("a dot's tooltip keeps a long message's first 120 characters", () => {204 const long = { ...(saves[0] as Save), message: `${"x".repeat(150)}\nsecond line` };205 expect(timelineSaves([long])[0]?.message).toBe(`${"x".repeat(119)}…`);206 });207208 test("the page carries plain dots; their words come from /<repo>/timeline", async () => {209 const page = await (await get("/demo")).text();210 expect(page).toContain('data-src="/demo/timeline"');211 expect(/<svg class="timeline"[\s\S]*?<\/svg>/.exec(page)?.[0]).not.toContain("<title>");212 const response = await get("/demo/timeline");213 expect(response.headers.get("cache-control")).toBe("public, max-age=60");214 const saves = (await response.json()) as { id: string; message: string }[];215 expect(saves.map((save) => save.message)).toContain("say hello");216 expect(saves.length).toBe(3);217 expect((await get("/nope/timeline")).status).toBe(404);218 });219});220221describe("the file viewer", () => {222 test("shows a file at HEAD and at an old save, with line anchors", async () => {223 const now = await get("/demo/files/src/main.ts");224 expect(now.headers.get("cache-control")).toBe("public, max-age=60");225 const nowPage = await now.text();226 expect(nowPage).toContain("hello");227 expect(nowPage).toContain(228 '<span class="line" id="L2"><a class="ln" href="#L2">2</a><span class="lc">',229 );230 expect(nowPage).toContain('class="tk-');231232 const then = await get(`/demo/files/src/main.ts?at=${second().slice(0, 6)}`);233 expect(then.headers.get("cache-control")).toBe("private, max-age=31536000");234 const thenPage = await then.text();235 expect(thenPage).toContain("'hi'");236 expect(thenPage).not.toContain("hello");237 expect(thenPage).toContain(`/demo/raw/src/main.ts?at=${second()}`);238 });239240 test("a file absent at that save, a bad save or an unsafe path is a 404", async () => {241 expect((await get(`/demo/files/src/main.ts?at=${first()}`)).status).toBe(404);242 expect((await get("/demo/files/src/main.ts?at=zzzzzz")).status).toBe(404);243 expect((await get("/demo/files/src/main.ts?at=abc")).status).toBe(404);244 expect((await get("/demo/files/src%2F..%2FREADME.md")).status).toBe(404);245 expect((await get("/demo/files/nothing.txt")).status).toBe(404);246 });247248 test("Markdown renders, with a source toggle", async () => {249 const rendered = await body("/demo/files/docs/guide.md");250 expect(rendered).toContain("<h1>Guide</h1>");251 const source = await body("/demo/files/docs/guide.md?view=source");252 expect(source).toContain('id="L1"');253 expect(source).not.toContain("<h1>Guide</h1>");254 });255256 test("an image displays inline from its raw file", async () => {257 expect(await body("/demo/files/docs/logo.png")).toContain('<img src="/demo/raw/docs/logo.png"');258 });259});260261describe("files over 1 MB", () => {262 test("text shows its first 1 MB with a raw link, even with a character cut at the mark", async () => {263 const page = await body("/large/files/big.txt");264 expect(page).toContain("showing the first 1 MB");265 expect(page).toContain('href="/large/raw/big.txt"');266 expect(page).not.toContain("bbb");267 const raw = await get("/large/raw/big.txt");268 expect(raw.headers.get("content-type")).toBe("text/plain; charset=utf-8");269 });270271 test("invalid UTF-8 without a NUL is binary, not text", async () => {272 const page = await body("/large/files/big.bin");273 expect(page).toContain("binary file");274 expect(page).not.toContain('class="code"');275 const raw = await get("/large/raw/big.bin");276 expect(raw.headers.get("content-type")).toBe("application/octet-stream");277 });278});279280describe("raw ranges and the heavy-route budget", () => {281 test("one byte range is served with 206 and exactly those bytes", async () => {282 const whole = new Uint8Array(await (await get("/demo/raw/src/main.ts")).arrayBuffer());283 const ranged = await app.request("/demo/raw/src/main.ts", {284 headers: { Range: "bytes=2-5" },285 });286 expect(ranged.status).toBe(206);287 expect(ranged.headers.get("content-range")).toBe(`bytes 2-5/${whole.length}`);288 expect(new Uint8Array(await ranged.arrayBuffer())).toEqual(whole.slice(2, 6));289 const open = await app.request("/demo/raw/src/main.ts", { headers: { Range: "bytes=30-" } });290 expect(open.status).toBe(206);291 expect(new Uint8Array(await open.arrayBuffer())).toEqual(whole.slice(30));292 const past = await app.request("/demo/raw/src/main.ts", {293 headers: { Range: `bytes=${whole.length + 10}-` },294 });295 expect(past.status).toBe(416);296 expect(past.headers.get("content-range")).toBe(`bytes */${whole.length}`);297 });298299 test("the heavy routes answer 429 past the per-address budget; HEAD and pages are free", async () => {300 const address = "198.51.100.200";301 const ask = (path = "/demo/raw/src/main.ts", init: RequestInit = {}) =>302 app.request(path, init, { requestIP: () => ({ address }) });303 let refused: Response | null = null;304 for (let i = 0; i < 200 && refused === null; i++) {305 const response = await ask();306 if (response.status === 429) refused = response;307 }308 expect(refused).not.toBeNull();309 expect(Number(refused?.headers.get("retry-after"))).toBeGreaterThan(0);310 expect((await ask("/demo/raw/src/main.ts", { method: "HEAD" })).status).toBe(200);311 expect((await ask("/")).status).toBe(200);312 });313});314315describe("the Atlas", () => {316 317 const panelOf = (path: string, at?: string) =>318 body(`/demo/atlas/panel?${new URLSearchParams(at ? { path, at } : { path })}`);319 const rowOf = (page: string, name: string) =>320 new RegExp(`data-name="${name}"[^>]*>(.*?)</a>`, "s").exec(page)?.[1] ?? "";321322 test("sits between the timeline and History", async () => {323 const page = await body("/demo");324 const atlas = page.indexOf('id="atlas"');325 expect(page.indexOf('class="timeline"')).toBeLessThan(atlas);326 expect(atlas).toBeLessThan(page.indexOf('id="history"'));327 });328329 test("is a folder tree, folders first, then files, alphabetical", async () => {330 const names = [...(await body("/demo")).matchAll(/class="atlas-name">([^<]*)</g)].map(331 (m) => m[1],332 );333 expect(names).toEqual([334 "docs/",335 "guide.md",336 "logo.png",337 "src/",338 "lib/",339 "deep/",340 "util.ts",341 "main.ts",342 "vendor/",343 "big.c",344 "README.md",345 "secret.txt",346 ]);347 });348349 test("rows carry the first sentence of the file's own comment, rendered, and link to the file", async () => {350 const page = await body("/demo");351 expect(rowOf(page, "util.ts")).toContain(352 '<span class="atlas-desc">The <em>one</em> helper.</span>',353 );354 expect(rowOf(page, "main.ts")).toContain("Entry point.");355 expect(rowOf(page, "guide.md")).toContain('<span class="atlas-desc">Read me.</span>');356 expect(rowOf(page, "secret.txt")).toContain('<span class="atlas-desc"></span>');357 expect(page).toContain(358 '<a class="atlas-row atlas-file" href="/demo/files/src/main.ts" data-name="main.ts" data-path="src/main.ts">',359 );360 const util = await panelOf("src/lib/deep/util.ts");361 expect(util).toContain("<p>The <em>one</em> helper. Deep down.</p>");362 expect(util).toContain("<dt>exports</dt><dd>one</dd>");363 expect(await panelOf("src/main.ts")).not.toContain("atlas-map");364 });365366 test("the panel counts only real saves, crediting a checkpoint's change to the next save", async () => {367 const page = await body("/demo");368 const main = await panelOf("src/main.ts");369 expect(main).toContain("<dt>lines</dt><dd>2</dd>");370 expect(main).toContain("<dt>saves</dt><dd>2</dd>");371 expect(main).toContain(`<dt>first save</dt><dd><a href="/demo/saves/${second()}">`);372 expect(main).toContain(`<dt>last save</dt><dd><a href="/demo/saves/${head()}">`);373 const guide = await panelOf("docs/guide.md");374 expect(guide).toContain("<dt>saves</dt><dd>2</dd>");375 expect(guide).toContain(`<dt>last save</dt><dd><a href="/demo/saves/${head()}">`);376 expect(await panelOf("docs/logo.png")).toContain("<dt>lines</dt><dd>binary</dd>");377 expect(page).not.toContain(fx.saveIds[1] as string);378 });379380 test("a folder's panel sums its files and counts the saves that touched anything under it", async () => {381 const docs = await panelOf("docs/");382 expect(docs).toContain('<p class="atlas-info-path mono">docs</p>');383 expect(docs).toContain("<dt>lines</dt><dd>3</dd>");384 expect(docs).toContain("<dt>files</dt><dd>2</dd>");385 expect(docs).toContain("<dt>saves</dt><dd>2</dd>");386 expect(docs).toContain(`<dt>first save</dt><dd><a href="/demo/saves/${first()}">`);387 expect(docs).toContain(`<dt>last save</dt><dd><a href="/demo/saves/${head()}">`);388 const src = await panelOf("src/");389 expect(src).toContain("<dt>saves</dt><dd>3</dd>");390 });391392 test("can be viewed at an older save, and an unknown save is a 404", async () => {393 const page = await body(`/demo?at=${second().slice(0, 8)}`);394 expect(page).toContain(`title="explore through time">${second()}</summary>`);395 const picker = await body(`/demo/atlas/saves?at=${second()}`);396 expect(picker).toContain(397 `<a class="atlas-picker-row active" href="/demo?at=${second()}#atlas"`,398 );399 expect(picker).toContain(`<a class="atlas-picker-row" href="/demo?at=${head()}#atlas"`);400 expect(page).toContain('<a class="atlas-head-link mono" href="/demo#atlas">back to HEAD</a>');401 expect(page).toContain(`href="/demo/files/src/main.ts?at=${second()}"`);402 const main = await panelOf("src/main.ts", second().slice(0, 8));403 expect(main).toContain("<dt>saves</dt><dd>1</dd>");404 expect(main).not.toContain(head());405 const oldest = await body(`/demo?at=${first()}`);406 expect(oldest).not.toContain('data-name="main.ts"');407 expect((await get("/demo?at=abcdef")).status).toBe(404);408 expect((await get("/demo?at=../x")).status).toBe(404);409 });410411 test("the page carries no panels; each is fetched alone, and anything unknown is a 404", async () => {412 const page = await body("/demo");413 expect(page).not.toContain("<template>");414 expect(page).not.toContain('class="atlas-picker-row" href="/demo?at=');415 expect(page).toContain('data-src="/demo/atlas/saves"');416 expect((await get("/demo/atlas/saves?at=abcdef")).status).toBe(404);417 expect((await get("/nobody/atlas/saves")).status).toBe(404);418 const panel = await get("/demo/atlas/panel?path=src/main.ts");419 expect(panel.status).toBe(200);420 expect(panel.headers.get("content-type")).toContain("text/html");421 for (const query of [422 "path=nope.ts",423 "path=src/main.ts&at=abcdef",424 "path=../secret.txt",425 "path=",426 "",427 "path=nope/",428 ]) {429 expect(`${query} ${(await get(`/demo/atlas/panel?${query}`)).status}`).toBe(`${query} 404`);430 }431 expect((await get("/nobody/atlas/panel?path=README.md")).status).toBe(404);432 });433});434435describe("the save page", () => {436 test("shows the save's facts and diffs against the previous real save, skipping the checkpoint", async () => {437 const response = await get(`/demo/saves/${head()}`);438 expect(response.status).toBe(200);439 expect(response.headers.get("cache-control")).toBe("public, max-age=60");440 const page = await response.text();441 expect(page).toContain('<h1 class="save-message-head">say hello</h1>');442 expect(page).toContain(443 `<dt>parent</dt><dd><a href="/demo/saves/${second()}">${second()}</a></dd>`,444 );445 expect(page).not.toContain(fx.saveIds[1] as string);446 expect(page).not.toContain("save-flag");447 448 const rows = [449 ...page.matchAll(450 /class="change-row change-(\w+)" href="#diff-\d"><span class="change-path">([^<]+)</g,451 ),452 ];453 expect(rows.map((m) => [m[1], m[2]])).toEqual([454 ["modified", "docs/guide.md"],455 ["modified", "src/main.ts"],456 ]);457 expect(page).toContain('<span class="diff-add">+1</span> <span class="diff-del">−1</span>');458 expect(page).toContain('<span class="dh">@@ -1,2 +1,2 @@</span>');459 expect(page).toContain(460 '<span class="dl dl-del"><span class="ln">2</span><span class="ln"></span><span class="ds">-</span>',461 );462 expect(page).toContain('class="tk-');463 expect(page).toContain(`href="/demo/archive/${head()}.tar.gz"`);464 expect(page).toContain(`href="/demo?at=${head()}#atlas"`);465 });466467 test("the first save diffs against nothing, notes binaries, and shows its flag and agent", async () => {468 const page = await body(`/demo/saves/${first()}`);469 expect(page).toContain('<span class="save-flag-label mono">flagged</span> holds a secret');470 expect(page).toContain("<dt>parent</dt><dd>none, the first save</dd>");471 expect(page).toContain(472 'change-added" href="#diff-2"><span class="change-path">docs/logo.png</span><span class="change-stat mono"><span class="diff-note">binary</span>',473 );474 expect(page).toContain("binary file, not shown");475 expect(page).toContain('<span class="dh">@@ -0,0 +1 @@</span>');476 const second_ = await body(`/demo/saves/${second()}`);477 expect(second_).toContain("<dt>agent</dt><dd>test-agent</dd><dt>session</dt><dd>fixture</dd>");478 expect(second_).not.toContain("save-flag");479 });480481 test("a change to the final newline alone is a changed last line, marked as in GNU diff", async () => {482 const marker = '<span class="dh">\\ No newline at end of file</span>';483 const row = (kind: string, a: string, b: string, sign: string) =>484 `<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>`;485 const gained = await body(`/tail/saves/${tailSaves[1]}`);486 expect(gained).toContain('<span class="diff-add">+1</span> <span class="diff-del">−1</span>');487 expect(gained).toContain(`${row("del", "2", "", "-")}${marker}${row("add", "", "2", "+")}<`);488 const lost = await body(`/tail/saves/${tailSaves[0]}`);489 expect(lost).toContain(`${row("del", "2", "", "-")}${row("add", "", "2", "+")}${marker}`);490 });491492 test("a prefix redirects, and a checkpoint, an unknown or a private save is a 404", async () => {493 const short = await get(`/demo/saves/${head().slice(0, 6)}`);494 expect(short.status).toBe(302);495 expect(short.headers.get("location")).toBe(`/demo/saves/${head()}`);496 expect((await get(`/demo/saves/${fx.saveIds[1]}`)).status).toBe(404);497 expect((await get("/demo/saves/abcdef")).status).toBe(404);498 expect((await get("/demo/saves/abc")).status).toBe(404);499 expect((await get(`/hidden/saves/${head()}`)).status).toBe(404);500 });501});502503describe("raw files", () => {504 test("are the exact object bytes, text as text/plain", async () => {505 const mirror = openMirror(mirrorDir, "demo");506 for (const [path, type] of [507 ["src/main.ts", "text/plain; charset=utf-8"],508 ["docs/logo.png", "image/png"],509 ["README.md", "text/plain; charset=utf-8"],510 ] as const) {511 const response = await get(`/demo/raw/${path}`);512 const file = fileAt(mirror, head(), path);513 expect(response.headers.get("content-type")).toBe(type);514 expect(new Uint8Array(await response.arrayBuffer())).toEqual(515 objectBytes(mirror, file?.hash as string) as Uint8Array<ArrayBuffer>,516 );517 }518 expect(await (await get(`/demo/raw/src/main.ts?at=${second()}`)).text()).toContain("'hi'");519 });520});521522test("static assets and raw files carry route-based sandboxing", async () => {523 const css = await get("/static/css/kepr.css");524 expect(css.status).toBe(200);525 expect(css.headers.get("content-type")).toContain("text/css");526 const raw = await get("/demo/raw/README.md");527 expect(raw.headers.get("content-security-policy")).toContain("sandbox");528 const asset = await get("/static/assets/plain.txt");529 expect(asset.headers.get("content-security-policy")).toContain("sandbox");530 const favicon = await get("/favicon.svg");531 expect(favicon.headers.get("content-type")).toBe("image/svg+xml");532 expect(favicon.headers.get("content-security-policy")).not.toContain("sandbox");533 expect((await get("/static/../package.json")).status).toBe(404);534 const csp = (await get("/demo")).headers.get("content-security-policy") ?? "";535 expect(csp).toContain("style-src 'self';");536 expect(csp).toContain("font-src 'self';");537 expect(csp).not.toContain("unsafe-inline");538});539540describe("housekeeping routes", () => {541 test("robots.txt points at the sitemap, which lists public repos only", async () => {542 expect(await body("/robots.txt")).toBe(543 "User-agent: *\nAllow: /\n\nSitemap: https://kepr.example/sitemap.xml\n",544 );545 const sitemap = await get("/sitemap.xml");546 expect(sitemap.headers.get("Content-Type")).toBe("application/xml; charset=UTF-8");547 const xml = await sitemap.text();548 expect(xml).toStartWith('<?xml version="1.0" encoding="UTF-8"?>\n<urlset');549 for (const repo of ["demo", "large", "tail"]) {550 expect(xml).toContain(`<loc>https://kepr.example/${repo}</loc>`);551 }552 expect(xml).not.toContain("hidden");553 });554555 test("favicon.svg is Kepr 2's mark, and every page links it", async () => {556 const res = await get("/favicon.svg");557 expect(res.headers.get("Content-Type")).toBe("image/svg+xml");558 expect(await res.text()).toContain('<polygon points="16,3 27,23 5,23"');559 expect(await body("/demo")).toContain(560 '<link rel="icon" href="/favicon.svg" type="image/svg+xml">',561 );562 });563});564565test("pages are prefetched on hover, never a link whose GET does something", async () => {566 const page = await get("/demo");567 expect(page.headers.get("speculation-rules")).toBe('"/speculation.json"');568 const rules = await get("/speculation.json");569 expect(rules.headers.get("content-type")).toBe("application/speculationrules+json");570 const text = await rules.text();571 for (const pattern of [572 "/*/archive/*",573 "/*/raw/*",574 "/*/releases/*",575 "/*/koh/*",576 "/api/*",577 "/admin/backup*",578 "/admin/notifications/*",579 "/*/issues/*",580 "/sign-in*",581 "/connect*",582 ]) {583 expect(text).toContain(JSON.stringify(pattern));584 }585});