console.test.ts

27.0 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('id="repo-app"');81		expect(page).toContain('id="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('id="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#repo-editor");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="app-1.1.0"');290		expect(page).toContain('id="app-1.0.0"');291		expect(page.indexOf('id="app-1.1.0"')).toBeLessThan(page.indexOf('id="app-1.0.0"'));292		expect(page).toContain('<span>1 download</span><span class="muted">linux-x86_64 1</span>');293		expect(page).toContain(">notes for 1.1.0</textarea>");294	});295296	test("edited notes replace the record's everywhere; the record's own text clears the edit", async () => {297		const saved = await edit("1.1.0", { notes: "Better <notes>." });298		expect(saved.headers.get("location")).toBe("/admin/repos?repo=app&saved=1#app-1.1.0");299		expect(JSON.parse(await text("/api/app/releases/latest")).notes).toBe("Better <notes>.");300		expect(await text("/app/releases")).toContain("Better &lt;notes&gt;.");301		expect(await (await operator.get("/admin/repos?repo=app")).text()).toContain("(edited)");302		expect((await edit("1.1.0", { notes: "notes for 1.1.0" })).status).toBe(303);303		const row = inst.kepr.query("SELECT notes FROM release_settings WHERE version = '1.1.0'").get();304		expect(row).toEqual({ notes: null });305		expect((await edit("1.1.0", { notes: "x".repeat(20_001) })).status).toBe(400);306	});307308	test("a hidden version leaves pages, latest and every feed, and stays in the console", async () => {309		expect((await edit("1.1.0", { notes: "notes for 1.1.0", hidden: "1" })).status).toBe(303);310		expect(await text("/app/releases/latest/version.txt")).toBe("1.0.0");311		expect(JSON.parse(await text("/api/app/releases/latest")).version).toBe("1.0.0");312		expect(await text("/api/app/releases/history")).not.toContain("1.1.0");313		expect(await text("/app/releases")).not.toContain("1.1.0");314		expect((await inst.app.request("/app/releases/1.1.0/linux-x86_64")).status).toBe(404);315		const page = await (await operator.get("/admin/repos?repo=app")).text();316		expect(page).toContain('id="app-1.1.0"');317		expect(page).toContain('value="1" checked> hidden');318		expect((await edit("1.1.0", { notes: "notes for 1.1.0" })).status).toBe(303);319		expect(await text("/app/releases/latest/version.txt")).toBe("1.1.0");320		expect((await edit("9.9.9", { notes: "" })).status).toBe(404);321		expect((await operator.post("/admin/releases/nowhere/1.0.0", { notes: "" })).status).toBe(404);322	});323});324325describe("deleting a build from the bucket", () => {326	let inst: Instance;327	let operator: Browser;328	let bucketDir: string;329	const text = async (path: string) => (await inst.app.request(path)).text();330	const remove = (version: string, fields: Record<string, string> = { confirm: "1" }) =>331		operator.post(`/admin/releases/app/${version}/delete`, fields);332333	beforeAll(async () => {334		const repos = await makeRepos(["app"]);335		bucketDir = repos.bucketDir;336		for (const version of ["1.0.0", "1.1.0"]) {337			await writeRelease(bucketDir, "app", {338				version,339				save: repos.saves.app as string,340				files: [{ platform: "linux-x86_64", name: "app", bytes: new Uint8Array([1]) }],341			});342		}343		inst = await instance(bucketDir);344		operator = new Browser(inst.app);345		await operator.signIn();346		await operator.post("/admin/repos/app", { public: "1" });347		await inst.app.request("/app/releases/1.1.0/linux-x86_64");348	});349350	test("needs its confirmation, and an unknown version is a 404", async () => {351		expect((await remove("1.1.0", {})).status).toBe(400);352		expect(await Bun.file(join(bucketDir, "app/releases/1.1.0/release.json")).exists()).toBe(true);353		expect((await remove("9.9.9")).status).toBe(404);354	});355356	test("the newest build goes, latest falls back, and a sync does not bring it back", async () => {357		const response = await remove("1.1.0");358		expect(response.headers.get("location")).toBe("/admin/repos?repo=app&saved=1#builds");359		expect(await Bun.file(join(bucketDir, "app/releases/1.1.0/release.json")).exists()).toBe(false);360		expect(await Bun.file(join(bucketDir, "app/releases/1.1.0/linux-x86_64/app")).exists()).toBe(361			false,362		);363		expect(await Bun.file(join(bucketDir, "app/releases/latest")).text()).toBe("1.0.0");364		expect(JSON.parse(await text("/api/app/releases/latest")).version).toBe("1.0.0");365		expect(inst.kepr.query("SELECT * FROM downloads WHERE version = '1.1.0'").all()).toEqual([]);366		await operator.post("/admin/sync", {});367		const page = await (await operator.get("/admin/repos?repo=app")).text();368		expect(page).not.toContain('id="app-1.1.0"');369		expect(page).toContain('id="app-1.0.0"');370	});371372	test("the last build goes, and latest with it", async () => {373		expect((await remove("1.0.0")).status).toBe(303);374		expect(await Bun.file(join(bucketDir, "app/releases/latest")).exists()).toBe(false);375		expect((await inst.app.request("/app/releases/latest/version.txt")).status).toBe(404);376	});377});378379describe("deleting one file of a build", () => {380	let inst: Instance;381	let operator: Browser;382	let bucketDir: string;383	const record = async () =>384		JSON.parse(await Bun.file(join(bucketDir, "app/releases/1.0.0/release.json")).text());385	const removeFile = (platform: string, fields: Record<string, string> = { confirm: "1" }) =>386		operator.post(`/admin/releases/app/1.0.0/${platform}/delete`, fields);387388	beforeAll(async () => {389		const repos = await makeRepos(["app"]);390		bucketDir = repos.bucketDir;391		await writeRelease(bucketDir, "app", {392			version: "1.0.0",393			save: repos.saves.app as string,394			files: [395				{ platform: "linux-x86_64", name: "app", bytes: new Uint8Array([1]) },396				{ platform: "macos-aarch64", name: "app", bytes: new Uint8Array([2]) },397			],398		});399		inst = await instance(bucketDir);400		operator = new Browser(inst.app);401		await operator.signIn();402		await operator.post("/admin/repos/app", { public: "1" });403		await inst.app.request("/app/releases/1.0.0/macos-aarch64");404	});405406	test("needs its confirmation, and an unknown platform is a 404", async () => {407		expect((await removeFile("macos-aarch64", {})).status).toBe(400);408		expect((await removeFile("windows-x86_64")).status).toBe(404);409		expect((await record()).files).toHaveLength(2);410	});411412	test("the file leaves the record, the bucket, the counts and the public routes", async () => {413		const response = await removeFile("macos-aarch64");414		expect(response.headers.get("location")).toBe("/admin/repos?repo=app&saved=1#app-1.0.0");415		const files = (await record()).files.map((file: { platform: string }) => file.platform);416		expect(files).toEqual(["linux-x86_64"]);417		const gone = join(bucketDir, "app/releases/1.0.0/macos-aarch64/app");418		expect(await Bun.file(gone).exists()).toBe(false);419		expect(420			inst.kepr.query("SELECT * FROM downloads WHERE platform = 'macos-aarch64'").all(),421		).toEqual([]);422		expect((await inst.app.request("/app/releases/1.0.0/macos-aarch64")).status).toBe(404);423		expect((await inst.app.request("/app/releases/1.0.0/linux-x86_64")).status).toBe(302);424	});425426	test("the last file can't go alone", async () => {427		expect((await removeFile("linux-x86_64")).status).toBe(400);428		expect((await record()).files).toHaveLength(1);429	});430});431432describe("deleting builds when a step fails or two run at once", () => {433	let inst: Instance;434	let bucketDir: string;435	const folder = () => openBucket({ kind: "folder", path: bucketDir });436	const mirror = () => openMirror(join(inst.dataDir, "mirror"), "app");437	const versions = () => operatorReleases(inst.kepr, mirror(), "app").map((r) => r.version);438	const latest = () => Bun.file(join(bucketDir, "app/releases/latest")).text();439440	beforeAll(async () => {441		const repos = await makeRepos(["app"]);442		bucketDir = repos.bucketDir;443		for (const version of ["1.0.0", "2.0.0", "3.0.0", "4.0.0"]) {444			await writeRelease(bucketDir, "app", {445				version,446				save: repos.saves.app as string,447				files: [{ platform: "linux-x86_64", name: "app", bytes: new Uint8Array([1]) }],448			});449		}450		inst = await instance(bucketDir);451	});452453	test("a failed file delete leaves the build whole, and deleting it again finishes", async () => {454		const failing: Bucket = {455			...folder(),456			async remove(key) {457				if (key.endsWith("/app")) throw new Error("network down");458				return folder().remove(key);459			},460		};461		await expect(deleteRelease(failing, inst.kepr, mirror(), "app", "4.0.0")).rejects.toThrow(462			"network down",463		);464		expect(await Bun.file(join(bucketDir, "app/releases/4.0.0/release.json")).exists()).toBe(true);465		expect(versions()).toContain("4.0.0");466		expect(await latest()).toBe("3.0.0");467		await deleteRelease(folder(), inst.kepr, mirror(), "app", "4.0.0");468		expect(await Bun.file(join(bucketDir, "app/releases/4.0.0/release.json")).exists()).toBe(false);469		expect(versions()).not.toContain("4.0.0");470	});471472	test("two deletes at once leave latest naming a build that still exists", async () => {473		await Promise.all([474			deleteRelease(folder(), inst.kepr, mirror(), "app", "3.0.0"),475			deleteRelease(folder(), inst.kepr, mirror(), "app", "2.0.0"),476		]);477		expect(await latest()).toBe("1.0.0");478		expect(versions()).toEqual(["1.0.0"]);479	});480});481482describe("site and profile settings, and the signature upload", () => {483	let inst: Instance;484	let operator: Browser;485	const PNG = Uint8Array.from(486		atob(487			"iVBORw0KGgoAAAANSUhEUgAAAAEAAAABCAYAAAAfFcSJAAAADUlEQVR42mNk+M9QDwADhgGAWjR9awAAAABJRU5ErkJggg==",488		),489		(ch) => ch.charCodeAt(0),490	);491	const settings = {492		site_name: "ada's library",493		tagline: "Small <tools>.",494		branding: "by ada",495		handle: "ada",496		bio: "Writes code.",497		location: "Lisbon",498		link: "https://ada.example",499		building_since: "june 2026",500		support: "1",501	};502	const text = async (path: string) => (await inst.app.request(path)).text();503	const upload = (bytes: Uint8Array | string, name: string, type: string, extra = {}) => {504		const form = new FormData();505		for (const [key, value] of Object.entries({ ...settings, ...extra })) form.set(key, value);506		form.set("signature", new File([bytes], name, { type }));507		return operator.post("/admin/site", form);508	};509	const signature = () =>510		inst.kepr.query("SELECT value FROM settings WHERE key = 'signature'").get();511512	beforeAll(async () => {513		const repos = await makeRepos(["app"]);514		inst = await instance(repos.bucketDir);515		operator = new Browser(inst.app);516		await operator.signIn();517	});518519	test("settings are saved and every public page reads them", async () => {520		expect((await operator.post("/admin/site", settings)).status).toBe(303);521		const front = await text("/");522		expect(front).toContain("<title>ada&#39;s library</title>");523		expect(front).toContain("Small &lt;tools&gt;.");524		expect(front).toContain('<span class="wordmark-by">by ada</span>');525		const profile = await text("/@ada");526		for (const value of [527			"Writes code.",528			"Lisbon",529			'href="https://ada.example"',530			"building since june 2026",531		]) {532			expect(profile).toContain(value);533		}534		expect(await (await operator.get("/admin/site?section=profile")).text()).toContain(535			'value="Lisbon"',536		);537		// Emptying a field removes the setting, so its default comes back.538		expect((await operator.post("/admin/site", { ...settings, site_name: "" })).status).toBe(303);539		expect(await text("/")).toContain("<title>kepr</title>");540	});541542	test("profile and site forms preserve each other's settings and retain invalid input", async () => {543		await operator.post("/admin/site", settings);544		const profile = await (await operator.get("/admin/site?section=profile")).text();545		expect(profile).toContain('aria-label="operator workspace"');546		expect(profile).toContain('href="/@ada"');547		expect(profile).not.toContain('name="site_name"');548		expect(profile).not.toContain('name="signature"');549		expect(profile).not.toContain('name="remove_signature"');550		expect(551			(552				await operator.post("/admin/site", {553					section: "profile",554					handle: "ada",555					bio: "New bio",556					link: "https://ada.example",557				})558			).status,559		).toBe(303);560		expect(await text("/")).toContain("Small &lt;tools&gt;.");561		await operator.post("/admin/site", { section: "site", site_name: "New site", support: "1" });562		expect(await text("/@ada")).toContain("New bio");563		const bad = await operator.post("/admin/site", {564			section: "profile",565			handle: "a/b",566			bio: "Keep my draft",567		});568		expect(bad.status).toBe(400);569		expect(await bad.text()).toContain("Keep my draft");570		expect(await text("/@ada")).toContain("New bio");571	});572573	test("the support page is the operator's to write, and to switch off", async () => {574		// Until written, the shipped words show, and the console's box starts from them.575		const shipped = await text("/support");576		expect(await (await operator.get("/admin/site")).text()).toContain("show the support page");577		const own = { ...settings, support_page: "## Help\n\nMail **me**." };578		expect((await operator.post("/admin/site", own)).status).toBe(303);579		const support = await text("/support");580		expect(support).toContain('<h2 id="help">Help</h2>\n<p>Mail <strong>me</strong>.</p>');581		expect(support).not.toBe(shipped);582		const { support: _, ...off } = own;583		expect((await operator.post("/admin/site", off)).status).toBe(303);584		expect((await inst.app.request("/support")).status).toBe(404);585		expect(await text("/")).not.toContain('href="/support"');586		expect((await operator.post("/admin/site", own)).status).toBe(303);587		expect(await text("/")).toContain('<a href="/support">support</a>');588	});589590	test("a bad handle, link or overlong field is refused", async () => {591		for (const bad of [592			{ handle: "a/b" },593			{ link: "javascript:alert(1)" },594			{ bio: "x".repeat(2001) },595		]) {596			expect((await operator.post("/admin/site", { ...settings, ...bad })).status).toBe(400);597		}598		expect((await inst.app.request("/@ada")).status).toBe(200);599	});600601	test("a PNG signature is stored in data/assets and shown on the profile", async () => {602		expect((await upload(PNG, "sig.png", "image/png")).status).toBe(303);603		const name = (signature() as { value: string }).value;604		expect(name).toMatch(/^signature-[0-9a-f]{16}\.png$/);605		expect(await Bun.file(join(inst.dataDir, "assets", name)).exists()).toBe(true);606		expect(await text("/@ada")).toContain(607			`<img class="profile-signature" src="/static/assets/${name}"`,608		);609		const served = await inst.app.request(`/static/assets/${name}`);610		expect(served.headers.get("content-type")).toBe("image/png");611		expect(new Uint8Array(await served.arrayBuffer())).toEqual(PNG);612	});613614	test("SVG, or anything whose bytes are not PNG, JPEG or WebP, is refused whatever it claims", async () => {615		const before = signature();616		const svg = '<svg xmlns="http://www.w3.org/2000/svg"><script>alert(1)</script></svg>';617		expect((await upload(svg, "sig.svg", "image/svg+xml")).status).toBe(400);618		expect((await upload(svg, "sig.png", "image/png")).status).toBe(400);619		expect((await upload("GIF89a", "sig.gif", "image/gif")).status).toBe(400);620		expect(signature()).toEqual(before);621		expect((await upload(new Uint8Array(70 * 1024), "big.png", "image/png")).status).toBe(413);622		// Between the 60 KB limit and the 64 KiB body cap, the limit answers.623		const png = (size: number) => {624			const bytes = new Uint8Array(size);625			bytes.set(PNG);626			return bytes;627		};628		const over = await upload(png(60 * 1024 + 1), "big.png", "image/png");629		expect(over.status).toBe(400);630		expect(await over.text()).toContain("The signature must be under 60 KB.");631		expect(signature()).toEqual(before);632		expect((await upload(png(60 * 1024), "edge.png", "image/png")).status).toBe(303);633	});634635	test("a new signature replaces the old file; removing it brings the handle back", async () => {636		const old = (signature() as { value: string }).value;637		const webp = new Uint8Array([0x52, 0x49, 0x46, 0x46, 0, 0, 0, 0, 0x57, 0x45, 0x42, 0x50, 1]);638		expect((await upload(webp, "sig.webp", "image/webp")).status).toBe(303);639		const name = (signature() as { value: string }).value;640		expect(name).toMatch(/\.webp$/);641		expect(await Bun.file(join(inst.dataDir, "assets", old)).exists()).toBe(false);642		expect(643			(await operator.post("/admin/site", { ...settings, remove_signature: "1" })).status,644		).toBe(303);645		expect(signature()).toBeNull();646		expect(await Bun.file(join(inst.dataDir, "assets", name)).exists()).toBe(false);647		expect(await text("/@ada")).toContain('<h1 class="profile-username">ada</h1>');648	});649});