console.test.ts

30.2 KB · raw

1import { afterAll, beforeAll, describe, expect, setSystemTime, test } from "bun:test";2import { join } from "node:path";3import { type Bucket, openBucket } from "../src/bucket/reader.ts";4import { fileIssue } from "../src/issues/store.ts";5import { openMirror } from "../src/mirror/store.ts";6import { deleteRelease, operatorReleases } from "../src/releases/releases.ts";7import { Browser, type Instance, instance } from "./browser.ts";8import { makeRepos, writeRelease } from "./fixture.ts";910let clock = Date.parse("2026-09-26T12:00:00Z");11const tick = (seconds: number) => {12	clock += seconds * 1000;13	setSystemTime(new Date(clock));14};1516describe("repos and visibility", () => {17	let inst: Instance;18	let browser: Browser;19	let bucketDir: string;20	let save: string;21	const publicPaths = () => [22		"/app",23		"/app/files/README.md",24		"/app/raw/README.md",25		`/app/saves/${save}`,26		`/app/archive/${save}.tar.gz`,27		"/app/archive/HEAD.tar.gz",28		"/app/archives",29		"/app/releases",30		"/app/releases/latest",31		"/app/releases/latest.json",32		"/app/releases/history.json",33		"/app/releases/latest/version.txt",34		"/app/releases/latest/linux-x86_64",35		"/app/releases/1.0.0/checksums.txt",36		"/app/releases/1.0.0/linux-x86_64",37		"/app/install.sh",38		"/api/app/releases/latest",39		"/api/app/releases/history",40		"/app/update-info",41		"/app/meta",42		"/app/issues",43		"/app/issues/new",44		"/app/issues/1",45		"/app?panel=issues",46		"/app/file?path=README.md",47		"/app/bundle",48		"/app/bundle.blake3",49		"/app/releases/1.0.0",50	];51	const statuses = async () => {52		const out: string[] = [];53		for (const path of publicPaths()) out.push(`${path} ${(await inst.app.request(path)).status}`);54		return out;55	};56	const text = async (path: string) => (await inst.app.request(path)).text();57	const publish = (repo: string, fields: Record<string, string>) =>58		browser.post(`/admin/repos/${repo}`, fields);5960	beforeAll(async () => {61		setSystemTime(new Date(clock));62		const repos = await makeRepos(["app", "other"]);63		bucketDir = repos.bucketDir;64		save = repos.saves.app as string;65		await writeRelease(bucketDir, "app", {66			version: "1.0.0",67			save,68			files: [{ platform: "linux-x86_64", name: "app", bytes: new Uint8Array([1]) }],69		});70		inst = await instance(bucketDir);71		inst.kepr.run("INSERT INTO settings (key, value) VALUES ('handle', 'june')");72		fileIssueDirect(inst, "app");73		browser = new Browser(inst.app);74		await browser.signIn();75	});76	afterAll(() => setSystemTime());7778	test("every repo the sync found is listed, private, with its last sync", async () => {79		const page = await (await browser.get("/admin/repos")).text();80		expect(page).toContain('href="/admin/repos?repo=app"');81		expect(page).toContain('href="/admin/repos?repo=other"');82		expect(page.match(/action="\/admin\/repos\/[^/"]+"/g)?.length).toBe(1);83		expect(page).toContain("last sync 2026-09-26 12:00 UTC");84		expect((await statuses()).every((line) => line.endsWith(" 404"))).toBe(true);85	});8687	test("repo selection focuses one settings form without a search form", async () => {88		const page = await (await browser.get("/admin/repos?repo=other")).text();89		expect(page).toContain('action="/admin/repos/other"');90		expect(page).toContain('href="/admin/repos?repo=app"');91		expect(page).not.toContain('type="search"');92		const saved = await publish("other", {});93		expect(saved.headers.get("location")).toBe("/admin/repos?repo=other&saved=1");94		expect(await (await browser.get("/admin/repos?repo=other&saved=1")).text()).toContain(95			"Changes saved.",96		);97	});9899	test("bad settings are refused and change nothing", async () => {100		for (const fields of <Record<string, string>[]>[101			{ homepage: "javascript:alert(1)" },102			{ category: "x".repeat(501) },103		]) {104			expect((await publish("app", { public: "1", ...fields })).status).toBe(400);105		}106		expect((await inst.app.request("/app")).status).toBe(404);107		expect((await browser.post("/admin/repos/nowhere", { public: "1" })).status).toBe(404);108	});109110	test("publishing opens every public surface, with the settings shown", async () => {111		await publish("other", { public: "1" });112		const response = await publish("app", {113			public: "1",114			category: "tools",115			homepage: "https://app.example",116		});117		expect(response.status).toBe(303);118		const lines = await statuses();119		expect(lines.filter((line) => line.endsWith(" 404"))).toEqual([]);120		expect(await text("/app")).toContain("https://app.example");121		expect(await text("/")).toContain('href="/app"');122		expect(await text("/browse")).toContain('href="/app"');123		expect(await text("/@june")).toContain('href="/app"');124		expect(await text("/sitemap.xml")).toContain("/app</loc>");125	});126127	test("flipping a repo private 404s every surface and drops it from lists and counts", async () => {128		const stat = async () =>129			[...(await text("/@june")).matchAll(/profile-stat-number">([^<]*)</g)].map((m) => m[1]);130		// Both download routes above counted; the issue is the repo's one.131		expect(await stat()).toEqual(["2", "2", "1", "2"]);132		await publish("app", { category: "tools" });133		expect((await statuses()).filter((line) => !line.endsWith(" 404"))).toEqual([]);134		for (const path of ["/", "/browse", "/@june"]) expect(await text(path)).not.toContain("/app");135		expect(await text("/sitemap.xml")).not.toContain("/app<");136		expect(await text("/")).not.toContain("tools");137		expect(await stat()).toEqual(["1", "1", "0", "0"]);138		// Settings survive the flip.139		expect(await (await browser.get("/admin/repos")).text()).toContain('value="tools"');140	});141142	test("sync now reads the bucket at once and records the time", async () => {143		await writeRelease(bucketDir, "other", {144			version: "2.0.0",145			save: save,146			files: [{ platform: "linux-x86_64", name: "other", bytes: new Uint8Array([2]) }],147		});148		tick(60);149		expect((await inst.app.request("/other/releases/latest/version.txt")).status).toBe(404);150		const response = await browser.post("/admin/sync", {});151		expect(response.status).toBe(303);152		expect(await text("/other/releases/latest/version.txt")).toBe("2.0.0");153		expect(await (await browser.get("/admin/repos")).text()).toContain(154			"last sync 2026-09-26 12:01 UTC",155		);156	});157});158159describe("issues: filed, answered and closed end to end through real routes", () => {160	let inst: Instance;161	let operator: Browser;162	let save: string;163	const text = async (path: string) => (await inst.app.request(path)).text();164	const act = (fields: Record<string, string>) => operator.post("/admin/issues/app/1", fields);165166	beforeAll(async () => {167		setSystemTime(new Date(clock));168		const repos = await makeRepos(["app", "hush"]);169		save = repos.saves.app as string;170		inst = await instance(repos.bucketDir);171		operator = new Browser(inst.app);172		await operator.signIn();173		await operator.post("/admin/repos/app", { public: "1" });174		// A reporter files through the public form, as a browser would.175		const reporter = new Browser(inst.app, "198.51.100.40");176		const form = await (await reporter.request("/app/issues/new")).text();177		const stamp = /name="stamp" value="([^"]+)"/.exec(form)?.[1] ?? "";178		tick(4);179		const filed = await reporter.request("/app/issues/new", {180			method: "POST",181			body: new URLSearchParams({182				stamp,183				website: "",184				title: "Crash <on> start",185				body: "It crashed.",186				type: "bug",187				version: "",188				name: "Ada",189				email: "[email protected]",190			}),191		});192		expect(filed.status).toBe(303);193		fileIssueDirect(inst, "hush");194	});195	afterAll(() => setSystemTime());196197	test("the console lists issues across repos, private ones too, with the contact detail", async () => {198		const list = await (await operator.get("/admin/issues")).text();199		expect(list).toContain('href="/admin/issues/app/1"');200		expect(list).toContain('href="/admin/issues/hush/1"');201		expect(list).toContain("Crash &lt;on&gt; start");202		const page = await (await operator.get("/admin/issues/app/1")).text();203		expect(page).toContain("contact: [email protected]");204		expect(await text("/app/issues/1")).not.toContain("[email protected]");205	});206207	test("an operator reply shows on the public thread, marked", async () => {208		expect((await act({ action: "reply", body: "Fixed <soon>." })).status).toBe(303);209		expect((await act({ action: "reply", body: "  " })).status).toBe(400);210		const thread = await text("/app/issues/1");211		expect(thread).toContain('<span class="issue-badge">operator</span>');212		expect(thread).toContain("Fixed &lt;soon&gt;.");213	});214215	test("close with a fixed-in save prefix, then reopen", async () => {216		expect((await act({ action: "close", fixed_in: "zzzzzz" })).status).toBe(400);217		expect((await act({ action: "close", fixed_in: "0123456789ab" })).status).toBe(400);218		expect((await act({ action: "close", fixed_in: save.slice(0, 6) })).status).toBe(303);219		const thread = await text("/app/issues/1");220		expect(thread).toContain("◈ closed");221		expect(thread).toContain(`fixed in <a class="history-id" href="/app/saves/${save}">`);222		expect(await text("/app/issues?status=closed")).toContain('href="/app/issues/1"');223		expect(await (await operator.get("/admin/issues?filter=closed")).text()).toContain(224			'href="/admin/issues/app/1"',225		);226		expect((await act({ action: "reopen" })).status).toBe(303);227		expect(await text("/app/issues/1")).toContain("◉ open");228		expect(await text("/app/issues/1")).not.toContain("fixed in");229	});230231	test("set type, and hide for spam: gone publicly, kept in the console", async () => {232		expect((await act({ action: "type", type: "nonsense" })).status).toBe(400);233		expect((await act({ action: "type", type: "idea" })).status).toBe(303);234		expect(await text("/app/issues")).toContain("#1 · idea");235		expect((await act({ action: "hide" })).status).toBe(303);236		expect((await inst.app.request("/app/issues/1")).status).toBe(404);237		expect(await (await operator.get("/admin/issues")).text()).not.toContain("/admin/issues/app/1");238		expect(await (await operator.get("/admin/issues?filter=hidden")).text()).toContain(239			'href="/admin/issues/app/1"',240		);241		expect((await act({ action: "unhide" })).status).toBe(303);242		expect((await inst.app.request("/app/issues/1")).status).toBe(200);243		expect((await act({ action: "delete" })).status).toBe(400);244		expect((await operator.post("/admin/issues/app/9", { action: "reopen" })).status).toBe(404);245	});246});247248function fileIssueDirect(inst: Instance, repo: string): void {249	fileIssue(inst.kepr, {250		repo,251		title: `A ${repo} issue`,252		body: "b",253		type: "bug",254		version: "",255		reporterName: "",256		contactEmail: "",257		ipHash: "x",258		filedAt: 1,259	});260}261262describe("releases: counts, displayed notes and hiding", () => {263	let inst: Instance;264	let operator: Browser;265	const text = async (path: string) => (await inst.app.request(path)).text();266	const edit = (version: string, fields: Record<string, string>) =>267		operator.post(`/admin/releases/app/${version}`, fields);268269	beforeAll(async () => {270		const repos = await makeRepos(["app"]);271		const save = repos.saves.app as string;272		for (const version of ["1.0.0", "1.1.0"]) {273			await writeRelease(repos.bucketDir, "app", {274				version,275				save,276				notes: `notes for ${version}`,277				files: [{ platform: "linux-x86_64", name: "app", bytes: new Uint8Array([1]) }],278			});279		}280		inst = await instance(repos.bucketDir);281		operator = new Browser(inst.app);282		await operator.signIn();283		await operator.post("/admin/repos/app", { public: "1" });284		await inst.app.request("/app/releases/1.1.0/linux-x86_64");285	});286287	test("every version is listed with its download counts and notes", async () => {288		const page = await (await operator.get("/admin/repos?repo=app")).text();289		expect(page).toContain('id="release-app-1.1.0"');290		expect(page).toContain('id="release-app-1.0.0"');291		expect(page.indexOf('id="release-app-1.1.0"')).toBeLessThan(292			page.indexOf('id="release-app-1.0.0"'),293		);294		expect(page).toContain('<span>1 download</span><span class="muted">linux-x86_64 1</span>');295		expect(page).toContain(">notes for 1.1.0</textarea>");296	});297298	test("edited notes replace the record's everywhere; the record's own text clears the edit", async () => {299		const saved = await edit("1.1.0", { notes: "Better <notes>." });300		expect(saved.headers.get("location")).toBe("/admin/repos?repo=app&saved=1#release-app-1.1.0");301		expect(JSON.parse(await text("/api/app/releases/latest")).notes).toBe("Better <notes>.");302		expect(await text("/app/releases")).toContain("Better &lt;notes&gt;.");303		expect(await (await operator.get("/admin/repos?repo=app")).text()).toContain("(edited)");304		expect((await edit("1.1.0", { notes: "notes for 1.1.0" })).status).toBe(303);305		const row = inst.kepr.query("SELECT notes FROM release_settings WHERE version = '1.1.0'").get();306		expect(row).toEqual({ notes: null });307		expect((await edit("1.1.0", { notes: "x".repeat(20_001) })).status).toBe(400);308	});309310	test("a hidden version leaves pages, latest and every feed, and stays in the console", async () => {311		expect((await edit("1.1.0", { notes: "notes for 1.1.0", hidden: "1" })).status).toBe(303);312		expect(await text("/app/releases/latest/version.txt")).toBe("1.0.0");313		expect(JSON.parse(await text("/api/app/releases/latest")).version).toBe("1.0.0");314		expect(await text("/api/app/releases/history")).not.toContain("1.1.0");315		expect(await text("/app/releases")).not.toContain("1.1.0");316		expect((await inst.app.request("/app/releases/1.1.0/linux-x86_64")).status).toBe(404);317		const page = await (await operator.get("/admin/repos?repo=app")).text();318		expect(page).toContain('id="release-app-1.1.0"');319		expect(page).toContain('value="1" checked> hidden');320		expect((await edit("1.1.0", { notes: "notes for 1.1.0" })).status).toBe(303);321		expect(await text("/app/releases/latest/version.txt")).toBe("1.1.0");322		expect((await edit("9.9.9", { notes: "" })).status).toBe(404);323		expect((await operator.post("/admin/releases/nowhere/1.0.0", { notes: "" })).status).toBe(404);324	});325});326327describe("deleting a build from the bucket", () => {328	let inst: Instance;329	let operator: Browser;330	let bucketDir: string;331	const text = async (path: string) => (await inst.app.request(path)).text();332	const remove = (version: string, fields: Record<string, string> = { confirm: "1" }) =>333		operator.post(`/admin/releases/app/${version}/delete`, fields);334335	beforeAll(async () => {336		const repos = await makeRepos(["app"]);337		bucketDir = repos.bucketDir;338		for (const version of ["1.0.0", "1.1.0"]) {339			await writeRelease(bucketDir, "app", {340				version,341				save: repos.saves.app as string,342				files: [{ platform: "linux-x86_64", name: "app", bytes: new Uint8Array([1]) }],343			});344		}345		inst = await instance(bucketDir);346		operator = new Browser(inst.app);347		await operator.signIn();348		await operator.post("/admin/repos/app", { public: "1" });349		await inst.app.request("/app/releases/1.1.0/linux-x86_64");350	});351352	test("needs its confirmation, and an unknown version is a 404", async () => {353		expect((await remove("1.1.0", {})).status).toBe(400);354		expect(await Bun.file(join(bucketDir, "app/releases/1.1.0/release.json")).exists()).toBe(true);355		expect((await remove("9.9.9")).status).toBe(404);356	});357358	test("the newest build goes, latest falls back, and a sync does not bring it back", async () => {359		const response = await remove("1.1.0");360		expect(response.headers.get("location")).toBe("/admin/repos?repo=app&saved=1#builds");361		expect(await Bun.file(join(bucketDir, "app/releases/1.1.0/release.json")).exists()).toBe(false);362		expect(await Bun.file(join(bucketDir, "app/releases/1.1.0/linux-x86_64/app")).exists()).toBe(363			false,364		);365		expect(await Bun.file(join(bucketDir, "app/releases/latest")).text()).toBe("1.0.0");366		expect(JSON.parse(await text("/api/app/releases/latest")).version).toBe("1.0.0");367		expect(inst.kepr.query("SELECT * FROM downloads WHERE version = '1.1.0'").all()).toEqual([]);368		await operator.post("/admin/sync", {});369		const page = await (await operator.get("/admin/repos?repo=app")).text();370		expect(page).not.toContain('id="release-app-1.1.0"');371		expect(page).toContain('id="release-app-1.0.0"');372	});373374	test("the last build goes, and latest with it", async () => {375		expect((await remove("1.0.0")).status).toBe(303);376		expect(await Bun.file(join(bucketDir, "app/releases/latest")).exists()).toBe(false);377		expect((await inst.app.request("/app/releases/latest/version.txt")).status).toBe(404);378	});379});380381describe("deleting one file of a build", () => {382	let inst: Instance;383	let operator: Browser;384	let bucketDir: string;385	const record = async () =>386		JSON.parse(await Bun.file(join(bucketDir, "app/releases/1.0.0/release.json")).text());387	const removeFile = (platform: string, fields: Record<string, string> = { confirm: "1" }) =>388		operator.post(`/admin/releases/app/1.0.0/${platform}/delete`, fields);389390	beforeAll(async () => {391		const repos = await makeRepos(["app"]);392		bucketDir = repos.bucketDir;393		await writeRelease(bucketDir, "app", {394			version: "1.0.0",395			save: repos.saves.app as string,396			files: [397				{ platform: "linux-x86_64", name: "app", bytes: new Uint8Array([1]) },398				{ platform: "macos-aarch64", name: "app", bytes: new Uint8Array([2]) },399			],400		});401		inst = await instance(bucketDir);402		operator = new Browser(inst.app);403		await operator.signIn();404		await operator.post("/admin/repos/app", { public: "1" });405		await inst.app.request("/app/releases/1.0.0/macos-aarch64");406	});407408	test("needs its confirmation, and an unknown platform is a 404", async () => {409		expect((await removeFile("macos-aarch64", {})).status).toBe(400);410		expect((await removeFile("windows-x86_64")).status).toBe(404);411		expect((await record()).files).toHaveLength(2);412	});413414	test("the file leaves the record, the bucket, the counts and the public routes", async () => {415		const response = await removeFile("macos-aarch64");416		expect(response.headers.get("location")).toBe(417			"/admin/repos?repo=app&saved=1#release-app-1.0.0",418		);419		const files = (await record()).files.map((file: { platform: string }) => file.platform);420		expect(files).toEqual(["linux-x86_64"]);421		const gone = join(bucketDir, "app/releases/1.0.0/macos-aarch64/app");422		expect(await Bun.file(gone).exists()).toBe(false);423		expect(424			inst.kepr.query("SELECT * FROM downloads WHERE platform = 'macos-aarch64'").all(),425		).toEqual([]);426		expect((await inst.app.request("/app/releases/1.0.0/macos-aarch64")).status).toBe(404);427		expect((await inst.app.request("/app/releases/1.0.0/linux-x86_64")).status).toBe(302);428	});429430	test("the last file can't go alone", async () => {431		expect((await removeFile("linux-x86_64")).status).toBe(400);432		expect((await record()).files).toHaveLength(1);433	});434});435436describe("deleting builds when a step fails or two run at once", () => {437	let inst: Instance;438	let bucketDir: string;439	const folder = () => openBucket({ kind: "folder", path: bucketDir });440	const mirror = () => openMirror(join(inst.dataDir, "mirror"), "app");441	const versions = () => operatorReleases(inst.kepr, mirror(), "app").map((r) => r.version);442	const latest = () => Bun.file(join(bucketDir, "app/releases/latest")).text();443444	beforeAll(async () => {445		const repos = await makeRepos(["app"]);446		bucketDir = repos.bucketDir;447		for (const version of ["1.0.0", "2.0.0", "3.0.0", "4.0.0"]) {448			await writeRelease(bucketDir, "app", {449				version,450				save: repos.saves.app as string,451				files: [{ platform: "linux-x86_64", name: "app", bytes: new Uint8Array([1]) }],452			});453		}454		inst = await instance(bucketDir);455	});456457	test("a failed file delete leaves the build whole, and deleting it again finishes", async () => {458		const failing: Bucket = {459			...folder(),460			async remove(key) {461				if (key.endsWith("/app")) throw new Error("network down");462				return folder().remove(key);463			},464		};465		await expect(deleteRelease(failing, inst.kepr, mirror(), "app", "4.0.0")).rejects.toThrow(466			"network down",467		);468		expect(await Bun.file(join(bucketDir, "app/releases/4.0.0/release.json")).exists()).toBe(true);469		expect(versions()).toContain("4.0.0");470		expect(await latest()).toBe("3.0.0");471		await deleteRelease(folder(), inst.kepr, mirror(), "app", "4.0.0");472		expect(await Bun.file(join(bucketDir, "app/releases/4.0.0/release.json")).exists()).toBe(false);473		expect(versions()).not.toContain("4.0.0");474	});475476	test("two deletes at once leave latest naming a build that still exists", async () => {477		await Promise.all([478			deleteRelease(folder(), inst.kepr, mirror(), "app", "3.0.0"),479			deleteRelease(folder(), inst.kepr, mirror(), "app", "2.0.0"),480		]);481		expect(await latest()).toBe("1.0.0");482		expect(versions()).toEqual(["1.0.0"]);483	});484});485486describe("a publish landing while a build is deleted", () => {487	let inst: Instance;488	let bucketDir: string;489	let save: string;490	const folder = () => openBucket({ kind: "folder", path: bucketDir });491	const mirror = () => openMirror(join(inst.dataDir, "mirror"), "app");492	const latest = () => Bun.file(join(bucketDir, "app/releases/latest")).text();493	let moves = 0;494495	// A `koh offer` of 3.0.0 lands between the delete's read of `latest` and its write, as it can.496	const publishing = (): Bucket => ({497		...folder(),498		async putIfTag(key, bytes, type, tag) {499			moves += 1;500			await writeRelease(bucketDir, "app", {501				version: "3.0.0",502				save,503				files: [{ platform: "linux-x86_64", name: "app", bytes: new Uint8Array([1]) }],504			});505			return folder().putIfTag(key, bytes, type, tag);506		},507	});508509	beforeAll(async () => {510		const repos = await makeRepos(["app"]);511		bucketDir = repos.bucketDir;512		save = repos.saves.app as string;513		for (const version of ["1.0.0", "2.0.0"]) {514			await writeRelease(bucketDir, "app", {515				version,516				save,517				files: [{ platform: "linux-x86_64", name: "app", bytes: new Uint8Array([1]) }],518			});519		}520		inst = await instance(bucketDir);521	});522523	test("the published version keeps latest, and the deleted build still goes", async () => {524		await deleteRelease(publishing(), inst.kepr, mirror(), "app", "2.0.0");525		expect(await latest()).toBe("3.0.0");526		expect(await Bun.file(join(bucketDir, "app/releases/3.0.0/release.json")).exists()).toBe(true);527		expect(await Bun.file(join(bucketDir, "app/releases/2.0.0/release.json")).exists()).toBe(false);528		// One conditional write was refused; the retry read 3.0.0 and left it alone.529		expect(moves).toBe(1);530	});531});532533describe("site and profile settings, and the signature upload", () => {534	let inst: Instance;535	let operator: Browser;536	const PNG = Uint8Array.from(537		atob(538			"iVBORw0KGgoAAAANSUhEUgAAAAEAAAABCAYAAAAfFcSJAAAADUlEQVR42mNk+M9QDwADhgGAWjR9awAAAABJRU5ErkJggg==",539		),540		(ch) => ch.charCodeAt(0),541	);542	const settings = {543		site_name: "ada's library",544		tagline: "Small <tools>.",545		branding: "by ada",546		handle: "ada",547		bio: "Writes code.",548		location: "Lisbon",549		link: "https://ada.example",550		building_since: "june 2026",551		support: "1",552	};553	const text = async (path: string) => (await inst.app.request(path)).text();554	const upload = (bytes: Uint8Array | string, name: string, type: string, extra = {}) => {555		const form = new FormData();556		for (const [key, value] of Object.entries({ ...settings, ...extra })) form.set(key, value);557		form.set("signature", new File([bytes], name, { type }));558		return operator.post("/admin/site", form);559	};560	const signature = () =>561		inst.kepr.query("SELECT value FROM settings WHERE key = 'signature'").get();562563	beforeAll(async () => {564		const repos = await makeRepos(["app"]);565		inst = await instance(repos.bucketDir);566		operator = new Browser(inst.app);567		await operator.signIn();568	});569570	test("settings are saved and every public page reads them", async () => {571		expect((await operator.post("/admin/site", settings)).status).toBe(303);572		const front = await text("/");573		expect(front).toContain("<title>ada&#39;s library</title>");574		expect(front).toContain("Small &lt;tools&gt;.");575		expect(front).toContain('<span class="wordmark-by">by ada</span>');576		const profile = await text("/@ada");577		for (const value of [578			"Writes code.",579			"Lisbon",580			'href="https://ada.example"',581			"building since june 2026",582		]) {583			expect(profile).toContain(value);584		}585		expect(await (await operator.get("/admin/site?section=profile")).text()).toContain(586			'value="Lisbon"',587		);588		// Emptying a field removes the setting, so its default comes back.589		expect((await operator.post("/admin/site", { ...settings, site_name: "" })).status).toBe(303);590		expect(await text("/")).toContain("<title>kepr</title>");591	});592593	test("profile and site forms preserve each other's settings and retain invalid input", async () => {594		await operator.post("/admin/site", settings);595		const profile = await (await operator.get("/admin/site?section=profile")).text();596		expect(profile).toContain('aria-label="operator workspace"');597		expect(profile).toContain('href="/@ada"');598		expect(profile).not.toContain('name="site_name"');599		expect(profile).not.toContain('name="signature"');600		expect(profile).not.toContain('name="remove_signature"');601		expect(602			(603				await operator.post("/admin/site", {604					section: "profile",605					handle: "ada",606					bio: "New bio",607					link: "https://ada.example",608				})609			).status,610		).toBe(303);611		expect(await text("/")).toContain("Small &lt;tools&gt;.");612		await operator.post("/admin/site", { section: "site", site_name: "New site", support: "1" });613		expect(await text("/@ada")).toContain("New bio");614		const bad = await operator.post("/admin/site", {615			section: "profile",616			handle: "a/b",617			bio: "Keep my draft",618		});619		expect(bad.status).toBe(400);620		expect(await bad.text()).toContain("Keep my draft");621		expect(await text("/@ada")).toContain("New bio");622	});623624	test("the support page is the operator's to write, and to switch off", async () => {625		// Until written, the shipped words show, and the console's box starts from them.626		const shipped = await text("/support");627		expect(await (await operator.get("/admin/site")).text()).toContain("show the support page");628		const own = { ...settings, support_page: "## Help\n\nMail **me**." };629		expect((await operator.post("/admin/site", own)).status).toBe(303);630		const support = await text("/support");631		expect(support).toContain('<h2 id="help">Help</h2>\n<p>Mail <strong>me</strong>.</p>');632		expect(support).not.toBe(shipped);633		const { support: _, ...off } = own;634		expect((await operator.post("/admin/site", off)).status).toBe(303);635		expect((await inst.app.request("/support")).status).toBe(404);636		expect(await text("/")).not.toContain('href="/support"');637		expect((await operator.post("/admin/site", own)).status).toBe(303);638		expect(await text("/")).toContain('<a href="/support">support</a>');639	});640641	test("an Umami tracking code loads on public pages, allowed by the CSP", async () => {642		const id = "94db1cb1-74f4-4a40-ad6c-962362670409";643		const tracking = `<script defer src="https://stats.example/script.js" data-website-id="${id}"></script>`;644		expect((await operator.post("/admin/site", { ...settings, tracking })).status).toBe(303);645		const front = await inst.app.request("/");646		expect(await front.text()).toContain(tracking);647		const policy = front.headers.get("Content-Security-Policy") ?? "";648		expect(policy).toContain("script-src 'self' https://stats.example");649		expect(policy).toContain("connect-src 'self' https://stats.example");650		const admin = await (await operator.get("/admin/site")).text();651		expect(admin).not.toContain('<script defer src="https://stats.example');652		expect(admin).toContain(`data-website-id=&quot;${id}&quot;`);653		for (const bad of [654			'<script src="http://stats.example/script.js" data-website-id="x"></script>',655			'<script src="https://%" data-website-id="94db1cb1-74f4-4a40-ad6c-962362670409"></script>',656			`<script src="https://stats.example/script.js"></script>`,657			"<script>alert(1)</script>",658		]) {659			expect((await operator.post("/admin/site", { ...settings, tracking: bad })).status).toBe(400);660		}661		expect((await operator.post("/admin/site", settings)).status).toBe(303);662		expect(await text("/")).not.toContain("stats.example");663	});664665	test("a bad handle, link or overlong field is refused", async () => {666		for (const bad of [667			{ handle: "a/b" },668			{ link: "javascript:alert(1)" },669			{ bio: "x".repeat(2001) },670		]) {671			expect((await operator.post("/admin/site", { ...settings, ...bad })).status).toBe(400);672		}673		expect((await inst.app.request("/@ada")).status).toBe(200);674	});675676	test("a PNG signature is stored in data/assets and shown on the profile", async () => {677		expect((await upload(PNG, "sig.png", "image/png")).status).toBe(303);678		const name = (signature() as { value: string }).value;679		expect(name).toMatch(/^signature-[0-9a-f]{16}\.png$/);680		expect(await Bun.file(join(inst.dataDir, "assets", name)).exists()).toBe(true);681		expect(await text("/@ada")).toContain(682			`<img class="profile-signature" src="/static/assets/${name}"`,683		);684		const served = await inst.app.request(`/static/assets/${name}`);685		expect(served.headers.get("content-type")).toBe("image/png");686		expect(new Uint8Array(await served.arrayBuffer())).toEqual(PNG);687	});688689	test("SVG, or anything whose bytes are not PNG, JPEG or WebP, is refused whatever it claims", async () => {690		const before = signature();691		const svg = '<svg xmlns="http://www.w3.org/2000/svg"><script>alert(1)</script></svg>';692		expect((await upload(svg, "sig.svg", "image/svg+xml")).status).toBe(400);693		expect((await upload(svg, "sig.png", "image/png")).status).toBe(400);694		expect((await upload("GIF89a", "sig.gif", "image/gif")).status).toBe(400);695		expect(signature()).toEqual(before);696		expect((await upload(new Uint8Array(70 * 1024), "big.png", "image/png")).status).toBe(413);697		// Between the 60 KB limit and the 64 KiB body cap, the limit answers.698		const png = (size: number) => {699			const bytes = new Uint8Array(size);700			bytes.set(PNG);701			return bytes;702		};703		const over = await upload(png(60 * 1024 + 1), "big.png", "image/png");704		expect(over.status).toBe(400);705		expect(await over.text()).toContain("The signature must be under 60 KB.");706		expect(signature()).toEqual(before);707		expect((await upload(png(60 * 1024), "edge.png", "image/png")).status).toBe(303);708	});709710	test("a new signature replaces the old file; removing it brings the handle back", async () => {711		const old = (signature() as { value: string }).value;712		const webp = new Uint8Array([0x52, 0x49, 0x46, 0x46, 0, 0, 0, 0, 0x57, 0x45, 0x42, 0x50, 1]);713		expect((await upload(webp, "sig.webp", "image/webp")).status).toBe(303);714		const name = (signature() as { value: string }).value;715		expect(name).toMatch(/\.webp$/);716		expect(await Bun.file(join(inst.dataDir, "assets", old)).exists()).toBe(false);717		expect(718			(await operator.post("/admin/site", { ...settings, remove_signature: "1" })).status,719		).toBe(303);720		expect(signature()).toBeNull();721		expect(await Bun.file(join(inst.dataDir, "assets", name)).exists()).toBe(false);722		expect(await text("/@ada")).toContain('<h1 class="profile-username">ada</h1>');723	});724});