console.test.ts

28.5 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(200);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("site and profile settings, and the signature upload", () => {487	let inst: Instance;488	let operator: Browser;489	const PNG = Uint8Array.from(490		atob(491			"iVBORw0KGgoAAAANSUhEUgAAAAEAAAABCAYAAAAfFcSJAAAADUlEQVR42mNk+M9QDwADhgGAWjR9awAAAABJRU5ErkJggg==",492		),493		(ch) => ch.charCodeAt(0),494	);495	const settings = {496		site_name: "ada's library",497		tagline: "Small <tools>.",498		branding: "by ada",499		handle: "ada",500		bio: "Writes code.",501		location: "Lisbon",502		link: "https://ada.example",503		building_since: "june 2026",504		support: "1",505	};506	const text = async (path: string) => (await inst.app.request(path)).text();507	const upload = (bytes: Uint8Array | string, name: string, type: string, extra = {}) => {508		const form = new FormData();509		for (const [key, value] of Object.entries({ ...settings, ...extra })) form.set(key, value);510		form.set("signature", new File([bytes], name, { type }));511		return operator.post("/admin/site", form);512	};513	const signature = () =>514		inst.kepr.query("SELECT value FROM settings WHERE key = 'signature'").get();515516	beforeAll(async () => {517		const repos = await makeRepos(["app"]);518		inst = await instance(repos.bucketDir);519		operator = new Browser(inst.app);520		await operator.signIn();521	});522523	test("settings are saved and every public page reads them", async () => {524		expect((await operator.post("/admin/site", settings)).status).toBe(303);525		const front = await text("/");526		expect(front).toContain("<title>ada&#39;s library</title>");527		expect(front).toContain("Small &lt;tools&gt;.");528		expect(front).toContain('<span class="wordmark-by">by ada</span>');529		const profile = await text("/@ada");530		for (const value of [531			"Writes code.",532			"Lisbon",533			'href="https://ada.example"',534			"building since june 2026",535		]) {536			expect(profile).toContain(value);537		}538		expect(await (await operator.get("/admin/site?section=profile")).text()).toContain(539			'value="Lisbon"',540		);541		// Emptying a field removes the setting, so its default comes back.542		expect((await operator.post("/admin/site", { ...settings, site_name: "" })).status).toBe(303);543		expect(await text("/")).toContain("<title>kepr</title>");544	});545546	test("profile and site forms preserve each other's settings and retain invalid input", async () => {547		await operator.post("/admin/site", settings);548		const profile = await (await operator.get("/admin/site?section=profile")).text();549		expect(profile).toContain('aria-label="operator workspace"');550		expect(profile).toContain('href="/@ada"');551		expect(profile).not.toContain('name="site_name"');552		expect(profile).not.toContain('name="signature"');553		expect(profile).not.toContain('name="remove_signature"');554		expect(555			(556				await operator.post("/admin/site", {557					section: "profile",558					handle: "ada",559					bio: "New bio",560					link: "https://ada.example",561				})562			).status,563		).toBe(303);564		expect(await text("/")).toContain("Small &lt;tools&gt;.");565		await operator.post("/admin/site", { section: "site", site_name: "New site", support: "1" });566		expect(await text("/@ada")).toContain("New bio");567		const bad = await operator.post("/admin/site", {568			section: "profile",569			handle: "a/b",570			bio: "Keep my draft",571		});572		expect(bad.status).toBe(400);573		expect(await bad.text()).toContain("Keep my draft");574		expect(await text("/@ada")).toContain("New bio");575	});576577	test("the support page is the operator's to write, and to switch off", async () => {578		// Until written, the shipped words show, and the console's box starts from them.579		const shipped = await text("/support");580		expect(await (await operator.get("/admin/site")).text()).toContain("show the support page");581		const own = { ...settings, support_page: "## Help\n\nMail **me**." };582		expect((await operator.post("/admin/site", own)).status).toBe(303);583		const support = await text("/support");584		expect(support).toContain('<h2 id="help">Help</h2>\n<p>Mail <strong>me</strong>.</p>');585		expect(support).not.toBe(shipped);586		const { support: _, ...off } = own;587		expect((await operator.post("/admin/site", off)).status).toBe(303);588		expect((await inst.app.request("/support")).status).toBe(404);589		expect(await text("/")).not.toContain('href="/support"');590		expect((await operator.post("/admin/site", own)).status).toBe(303);591		expect(await text("/")).toContain('<a href="/support">support</a>');592	});593594	test("an Umami tracking code loads on public pages, allowed by the CSP", async () => {595		const id = "94db1cb1-74f4-4a40-ad6c-962362670409";596		const tracking = `<script defer src="https://stats.example/script.js" data-website-id="${id}"></script>`;597		expect((await operator.post("/admin/site", { ...settings, tracking })).status).toBe(303);598		const front = await inst.app.request("/");599		expect(await front.text()).toContain(tracking);600		const policy = front.headers.get("Content-Security-Policy") ?? "";601		expect(policy).toContain("script-src 'self' https://stats.example");602		expect(policy).toContain("connect-src 'self' https://stats.example");603		const admin = await (await operator.get("/admin/site")).text();604		expect(admin).not.toContain('<script defer src="https://stats.example');605		expect(admin).toContain(`data-website-id=&quot;${id}&quot;`);606		for (const bad of [607			'<script src="http://stats.example/script.js" data-website-id="x"></script>',608			'<script src="https://%" data-website-id="94db1cb1-74f4-4a40-ad6c-962362670409"></script>',609			`<script src="https://stats.example/script.js"></script>`,610			"<script>alert(1)</script>",611		]) {612			expect((await operator.post("/admin/site", { ...settings, tracking: bad })).status).toBe(400);613		}614		expect((await operator.post("/admin/site", settings)).status).toBe(303);615		expect(await text("/")).not.toContain("stats.example");616	});617618	test("a bad handle, link or overlong field is refused", async () => {619		for (const bad of [620			{ handle: "a/b" },621			{ link: "javascript:alert(1)" },622			{ bio: "x".repeat(2001) },623		]) {624			expect((await operator.post("/admin/site", { ...settings, ...bad })).status).toBe(400);625		}626		expect((await inst.app.request("/@ada")).status).toBe(200);627	});628629	test("a PNG signature is stored in data/assets and shown on the profile", async () => {630		expect((await upload(PNG, "sig.png", "image/png")).status).toBe(303);631		const name = (signature() as { value: string }).value;632		expect(name).toMatch(/^signature-[0-9a-f]{16}\.png$/);633		expect(await Bun.file(join(inst.dataDir, "assets", name)).exists()).toBe(true);634		expect(await text("/@ada")).toContain(635			`<img class="profile-signature" src="/static/assets/${name}"`,636		);637		const served = await inst.app.request(`/static/assets/${name}`);638		expect(served.headers.get("content-type")).toBe("image/png");639		expect(new Uint8Array(await served.arrayBuffer())).toEqual(PNG);640	});641642	test("SVG, or anything whose bytes are not PNG, JPEG or WebP, is refused whatever it claims", async () => {643		const before = signature();644		const svg = '<svg xmlns="http://www.w3.org/2000/svg"><script>alert(1)</script></svg>';645		expect((await upload(svg, "sig.svg", "image/svg+xml")).status).toBe(400);646		expect((await upload(svg, "sig.png", "image/png")).status).toBe(400);647		expect((await upload("GIF89a", "sig.gif", "image/gif")).status).toBe(400);648		expect(signature()).toEqual(before);649		expect((await upload(new Uint8Array(70 * 1024), "big.png", "image/png")).status).toBe(413);650		// Between the 60 KB limit and the 64 KiB body cap, the limit answers.651		const png = (size: number) => {652			const bytes = new Uint8Array(size);653			bytes.set(PNG);654			return bytes;655		};656		const over = await upload(png(60 * 1024 + 1), "big.png", "image/png");657		expect(over.status).toBe(400);658		expect(await over.text()).toContain("The signature must be under 60 KB.");659		expect(signature()).toEqual(before);660		expect((await upload(png(60 * 1024), "edge.png", "image/png")).status).toBe(303);661	});662663	test("a new signature replaces the old file; removing it brings the handle back", async () => {664		const old = (signature() as { value: string }).value;665		const webp = new Uint8Array([0x52, 0x49, 0x46, 0x46, 0, 0, 0, 0, 0x57, 0x45, 0x42, 0x50, 1]);666		expect((await upload(webp, "sig.webp", "image/webp")).status).toBe(303);667		const name = (signature() as { value: string }).value;668		expect(name).toMatch(/\.webp$/);669		expect(await Bun.file(join(inst.dataDir, "assets", old)).exists()).toBe(false);670		expect(671			(await operator.post("/admin/site", { ...settings, remove_signature: "1" })).status,672		).toBe(303);673		expect(signature()).toBeNull();674		expect(await Bun.file(join(inst.dataDir, "assets", name)).exists()).toBe(false);675		expect(await text("/@ada")).toContain('<h1 class="profile-username">ada</h1>');676	});677});