front.test.ts

15.2 KB · raw

1import type { Database } from "bun:sqlite";2import { beforeAll, describe, expect, test } from "bun:test";3import { mkdir, mkdtemp, unlink, 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 { openMirror } from "../src/mirror/store.ts";10import { createApp } from "../src/server/app.ts";11import { openKeprDb } from "../src/server/db.ts";12import { Browser, PASSWORD } from "./browser.ts";13import { makeRepos } from "./fixture.ts";1415let app: Hono;16let kepr: Database;17let dataDir: string;18let alphaSaves: { id: string; message: string; is_checkpoint: boolean }[];19let vaultSave: string;20const body = async (path: string) => (await app.request(path)).text();2122// alpha (public): a save, a checkpoint holding a draft no real save keeps, then a second save.23// vault (private): one save whose message, category, language and ID must never show.24beforeAll(async () => {25	const repos = await makeRepos(["alpha", "vault"]);26	const root = join(repos.bucketDir, "..");27	await writeFile(join(root, "work/alpha/draft.txt"), "a draft only a checkpoint holds\n");28	repos.koh("alpha", "checkpoint", "checkpoint message never shown");29	await unlink(join(root, "work/alpha/draft.txt"));30	await writeFile(join(root, "work/alpha/README.md"), "# alpha\n\nThe alpha project, grown.\n");31	await writeFile(join(root, "work/alpha/main.ts"), "export const a = 1;\n");32	repos.koh("alpha", "save", "grow alpha");33	// HEAD is a checkpoint adding a new language: none of it may reach a public stat.34	await writeFile(join(root, "work/alpha/tool.py"), "print(1)\n");35	repos.koh("alpha", "checkpoint", "checkpoint at head adds python");36	repos.koh("alpha", "offer");37	await writeFile(join(root, "work/vault/main.zig"), "const x = 1;\n");38	repos.koh("vault", "save", "vault message");39	alphaSaves = JSON.parse(repos.koh("alpha", "view", "--json")).saves;40	vaultSave = JSON.parse(repos.koh("vault", "view", "--json")).head_id;4142	dataDir = await mkdtemp(join(tmpdir(), "kepr-front-"));43	kepr = openKeprDb(dataDir);44	const bucket = openBucket({ kind: "folder", path: repos.bucketDir });45	await syncAll({46		bucket,47		kepr,48		mirrorDir: join(dataDir, "mirror"),49	});50	kepr.run("UPDATE repos SET public = 1, category = 'tools' WHERE name = 'alpha'");51	kepr.run("UPDATE repos SET category = 'secretcat' WHERE name = 'vault'");52	for (const [key, value] of [53		["handle", "ada"],54		["tagline", "A library of small tools."],55		["bio", "Writes small tools."],56		["location", "Lisbon"],57		["link", "https://ada.example"],58		["building_since", "may 2026"],59	]) {60		kepr.query("INSERT INTO settings (key, value) VALUES (?, ?)").run(key, value);61	}62	kepr.run(63		`INSERT INTO issues (repo, number, title, body, type, filed_at, hidden) VALUES64		('alpha', 1, 'a', 'b', 'bug', 1, 0), ('alpha', 2, 'c', 'd', 'bug', 1, 1),65		('vault', 1, 'e', 'f', 'bug', 1, 0)`,66	);67	kepr.run(68		`INSERT INTO downloads (repo, version, platform, count) VALUES69		('alpha', '1.0.0', 'linux-x86_64', 7), ('alpha', '0.9.0', 'linux-x86_64', 100),70		('vault', '1.0.0', 'linux-x86_64', 1000)`,71	);72	kepr.run("INSERT INTO release_settings (repo, version, hidden) VALUES ('alpha', '0.9.0', 1)");73	app = createApp(74		{75			domain: "kepr.example",76			dataDir,77			adminPasswordHash: await Bun.password.hash(PASSWORD, "argon2id"),78			bucket: { kind: "folder", path: repos.bucketDir },79		},80		kepr,81	);82});8384const checkpoints = () => alphaSaves.filter((save) => save.is_checkpoint).map((save) => save.id);85const realSaves = () => alphaSaves.filter((save) => !save.is_checkpoint);8687test("only a live operator session can see and open private repo cards", async () => {88	const operator = new Browser(app);89	const visitor = new Browser(app);90	const listings = ["/", "/browse", "/@ada"];91	const card = 'class="repo-card" href="/vault"';92	visitor.cookies.set("kepr_editor", "1");93	kepr.run(94		"INSERT INTO settings (key, value) VALUES ('umami_src', 'https://stats.example/s.js'), ('umami_id', 'test')",95	);96	kepr.run("INSERT INTO renamed (old, new) VALUES ('oldvault', 'vault')");97	try {98		for (const path of listings) {99			const response = await visitor.get(path);100			expect(response.headers.get("vary")).toContain("Cookie");101			const markup = await response.text();102			expect(markup).not.toContain(card);103			expect(markup).toContain("https://stats.example/s.js");104		}105		expect((await operator.signIn()).status).toBe(303);106		for (const path of listings) {107			const response = await operator.get(path);108			expect(response.headers.get("cache-control")).toBe("no-store");109			const markup = await response.text();110			expect(markup).toContain(card);111			expect(markup).not.toContain("https://stats.example/s.js");112			expect(await (await visitor.get(path)).text()).not.toContain(card);113		}114		for (const path of [115			"/vault",116			"/vault/timeline",117			"/vault/atlas/saves",118			"/vault/atlas/panel?path=main.zig",119			`/vault/saves/${vaultSave}`,120			"/vault/files/main.zig",121			`/vault/raw/main.zig?at=${vaultSave}`,122		]) {123			const response = await operator.get(path);124			expect([path, response.status]).toEqual([path, 200]);125			expect(response.headers.get("cache-control")).toBe("no-store");126			expect(await response.text()).not.toContain("https://stats.example/s.js");127			expect((await visitor.get(path)).status).toBe(404);128		}129		for (const path of [130			"/oldvault",131			"/vault/issues",132			"/vault/releases/latest.json",133			"/vault/koh/head",134		]) {135			expect((await visitor.get(path)).status).toBe(404);136			expect((await operator.get(path)).status).toBe(404);137		}138		const prefix = await operator.get(`/vault/saves/${vaultSave.slice(0, 7)}`);139		expect(prefix.status).toBe(302);140		expect(prefix.headers.get("cache-control")).toBe("no-store");141		const token = operator.cookies.get("kepr_session") ?? "";142		expect((await operator.post("/admin/sign-out", {})).status).toBe(303);143		operator.cookies.set("kepr_session", token);144		for (const path of listings)145			expect(await (await operator.get(path)).text()).not.toContain(card);146		expect((await operator.get("/vault")).status).toBe(404);147	} finally {148		kepr.run("DELETE FROM settings WHERE key IN ('umami_src', 'umami_id')");149		kepr.run("DELETE FROM renamed WHERE old = 'oldvault'");150	}151});152153describe("front page", () => {154	test("counts distinct objects of public repos' real saves only", async () => {155		// alpha's real saves hold .kohignore, two READMEs and main.ts; its mirror also holds the156		// draft and tool.py only checkpoints kept, and the private repo's objects are elsewhere.157		const mirror = openMirror(join(dataDir, "mirror"), "alpha");158		expect(mirror.query("SELECT COUNT(*) AS n FROM objects").get()).toEqual({ n: 6 });159		expect(await body("/")).toContain("The library knows<br>4 things.");160	});161162	test("the ticker, cloud and cards show public saves, never checkpoints or private repos", async () => {163		const html = await body("/");164		expect(html).toContain('<div class="ticker" aria-hidden="true">');165		expect(html).toContain("<span>grow alpha</span>");166		expect(html).toContain("<span>release alpha</span>");167		expect(html).toContain('class="tc-tag tc-5">tools<');168		expect(html).toContain('class="tc-tag tc-5">TypeScript<');169		expect(html).toContain('<span class="repo-card-saves mono">2 saves</span>');170		expect(html).toContain("The alpha project, grown.");171		expect(html).toContain("A library of small tools.");172		expect(html).toContain('href="/docs">run your own library →</a>');173		for (const secret of [174			"checkpoint message",175			"vault",176			"secretcat",177			"Zig",178			...checkpoints(),179			vaultSave,180		]) {181			expect(html).not.toContain(secret);182		}183	});184185	test("a checkpoint at head adds nothing to the public stats", async () => {186		const mirror = openMirror(join(dataDir, "mirror"), "alpha");187		const state = (key: string) => mirror.query("SELECT value FROM state WHERE key = ?").get(key);188		expect(checkpoints()).toContain((state("head") as { value: string }).value);189		// Lines and languages are counted at the newest real save, so tool.py is in neither.190		expect(state("stats_save")).toEqual({ value: realSaves()[0]?.id });191		for (const path of ["/", "/@ada", "/alpha"]) {192			const html = await body(path);193			expect(html).toContain("TypeScript");194			expect(html).not.toContain("Python");195		}196		expect(await body("/browse")).not.toContain("Python");197	});198199	test("the nav has browse, docs, support and log in, as Kepr 2's", async () => {200		const html = await body("/");201		expect(html).toContain(202			'<a href="/browse">browse</a><a href="/docs">docs</a><a href="/support">support</a><a href="/sign-in?next=/">log in</a>',203		);204	});205206	test("browse lists public repos as Kepr 2's cards: name, saves, description, category", async () => {207		const html = await body("/browse");208		expect(html).toContain('<a class="repo-card" href="/alpha">');209		expect(html).toContain(`${realSaves().length} saves</span>`);210		expect(html).toContain('<p class="repo-card-cat">tools</p>');211		expect(html).not.toContain("vault");212	});213});214215describe("profile", () => {216	test("a handle that isn't the configured one is a 404", async () => {217		expect((await app.request("/@ada")).status).toBe(200);218		expect((await app.request("/@someone")).status).toBe(404);219		expect((await app.request("/@")).status).toBe(404);220	});221222	test("stats leave out private repos, checkpoints, hidden issues and hidden releases", async () => {223		const numbers = [...(await body("/@ada")).matchAll(/profile-stat-number">([^<]*)</g)].map(224			(m) => m[1],225		);226		// repos, saves, issues, downloads227		expect(numbers).toEqual(["1", String(realSaves().length), "1", "7"]);228	});229230	test("recent activity and the hex backdrop use real public saves only", async () => {231		const html = await body("/@ada");232		expect(html).toContain('class="profile-timeline" tabindex="0"');233		expect(html).toContain('role="region" aria-label="recent activity"');234		for (const save of realSaves()) {235			expect(html).toContain(`<span class="hex-id">${save.id}</span>`);236			expect(html).toContain(`href="/alpha/saves/${save.id}">${save.message}</a>`);237		}238		const groups = [...html.matchAll(/<span class="hex-group">([\s\S]*?)<\/span><\/span>/g)];239		expect(groups).toHaveLength(96);240		for (let i = 0; i < groups.length; i += 2) {241			expect(groups[i]?.[1]).toBe(groups[i + 1]?.[1]);242			expect(groups[i]?.[1].match(/class="hex-id"/g)).toHaveLength(4);243		}244		for (const id of checkpoints()) expect(html).not.toContain(id);245		expect(html).not.toContain(vaultSave);246		expect(html).not.toContain("vault");247		expect(html).not.toContain("Zig");248	});249250	test("shows the settings, the handle in the signature font, and the language bar", async () => {251		const html = await body("/@ada");252		expect(html).toContain('<h1 class="profile-username">ada</h1>');253		expect(html).toContain("building since may 2026");254		expect(html).toContain("◈ operator");255		expect(html).toContain("Writes small tools.");256		expect(html).toContain("Lisbon");257		expect(html).toContain('href="https://ada.example"');258		expect(html).toContain('<span class="profile-lang-label">TypeScript</span>');259		expect(html).toContain('<meta property="og:title" content="@ada — kepr">');260	});261262	test("an uploaded signature is served from data/assets and replaces the handle", async () => {263		await mkdir(join(dataDir, "assets"), { recursive: true });264		await writeFile(join(dataDir, "assets/sig.svg"), "<svg xmlns='http://www.w3.org/2000/svg'/>");265		kepr.run("INSERT INTO settings (key, value) VALUES ('signature', 'sig.svg')");266		try {267			expect(await body("/@ada")).toContain(268				'<img class="profile-signature" src="/static/assets/sig.svg" alt="ada">',269			);270			const asset = await app.request("/static/assets/sig.svg");271			expect(asset.status).toBe(200);272			expect(asset.headers.get("content-type")).toContain("image/svg+xml");273			// The tag is the file's size, mtime and path; asking again costs no body.274			const etag = asset.headers.get("etag") ?? "";275			expect(etag).not.toBe("");276			const again = await app.request("/static/assets/sig.svg", {277				headers: { "If-None-Match": etag },278			});279			expect(again.status).toBe(304);280			expect(await again.text()).toBe("");281			await mkdir(join(dataDir, "assets/logos"));282			await writeFile(join(dataDir, "assets/logos/mark.svg"), "<svg/>");283			expect((await app.request("/static/assets/logos/mark.svg")).status).toBe(200);284			// `..` spelled so the URL parser leaves it for the route, and a backslash; kepr.db sits285			// right above assets/, so any of these reaching the disk would serve it.286			for (const path of [287				"/static/assets/../kepr.db",288				"/static/assets/..%2Fkepr.db",289				"/static/assets/%2e%2e%2fkepr.db",290				"/static/assets/..%5Ckepr.db",291				"/static/assets%2F..%2Fkepr.db",292				"/static/%00",293				"/static/assets/%00",294				"/static/css/%01kepr.css",295			]) {296				expect((await app.request(path)).status).toBe(404);297			}298		} finally {299			kepr.run("DELETE FROM settings WHERE key = 'signature'");300		}301	});302303	test("with no handle set there is no profile", async () => {304		kepr.run("UPDATE settings SET value = '' WHERE key = 'handle'");305		try {306			expect((await app.request("/@ada")).status).toBe(404);307		} finally {308			kepr.run("UPDATE settings SET value = 'ada' WHERE key = 'handle'");309		}310	});311});312313describe("docs and support", () => {314	test("docs show the running Kepr version", async () => {315		const { version } = (await Bun.file(join(import.meta.dir, "../package.json")).json()) as {316			version: string;317		};318		expect(await body("/docs")).toContain(`<p class="mono muted">Running Kepr v${version}</p>`);319		expect(await body("/support")).not.toContain("Running Kepr v");320	});321322	test("render the repo's Markdown, links left as written", async () => {323		const docs = await body("/docs");324		expect(docs).toContain("<h1>Your work, in public</h1>");325		expect(docs).toContain("<code>/setup</code>");326		const support = await body("/support");327		expect(support).toContain('<a href="/docs">self-hosting docs</a>');328		expect(support).toContain('<meta name="description" content="Found a bug');329	});330});331332test("motion stops under prefers-reduced-motion", async () => {333	const css = await Bun.file(join(import.meta.dir, "../public/css/kepr.css")).text();334	const blocks = [...css.matchAll(/@media \(prefers-reduced-motion: reduce\) \{([\s\S]*?)\n\}/g)]335		.map((m) => m[1] as string)336		.join("\n");337	for (const selector of [".ticker-row", ".ticker-track", ".hex-col", ".tri-outer"]) {338		expect(blocks).toContain(selector);339	}340	expect(blocks).toContain("animation: none;");341});342343test("a file two public repos share is one thing the library knows", async () => {344	const repos = await makeRepos(["one", "two"]);345	for (const repo of ["one", "two"]) {346		await writeFile(join(repos.bucketDir, "..", "work", repo, "LICENSE"), "the same licence\n");347		repos.koh(repo, "save", "add the licence");348		repos.koh(repo, "offer");349	}350	const dir = await mkdtemp(join(tmpdir(), "kepr-front-"));351	const db = openKeprDb(dir);352	const bucket = openBucket({ kind: "folder", path: repos.bucketDir });353	await syncAll({ bucket, kepr: db, mirrorDir: join(dir, "mirror") });354	db.run("UPDATE repos SET public = 1");355	const shared = createApp(356		{357			domain: "kepr.example",358			dataDir: dir,359			adminPasswordHash: "$argon2id$x",360			bucket: { kind: "folder", path: repos.bucketDir },361		},362		db,363	);364	// Two READMEs that differ; koh's default .kohignore and the licence, each shared by both.365	expect(await (await shared.request("/")).text()).toContain("The library knows<br>4 things.");366});