pages.ts

30.5 KB · raw

1import type { Context, Hono } from "hono";2import { saveByPrefix } from "../mirror/queries.ts";3import { type Html, html } from "../pages/html.ts";4import {5	cacheFor,6	formatDate,7	formatSize,8	notFound,9	openPublicRepo,10	type PageContext,11	type PublicRepo,12	page,13	relativeTime,14} from "../pages/layout.ts";15import { renderComment } from "../pages/markdown.ts";16import { visibleReleases } from "../releases/releases.ts";17import type { Config } from "../server/config.ts";18import { notify } from "../server/db.ts";19import {20	ATTACHMENT_BYTES_PER_DAY,21	type Attachment,22	attachFiles,23	attachmentBytesToday,24	FILE_BYTES_PER_HOUR,25	FILE_EXTENSIONS,26	FILES_PER_POST,27	fileBytesSince,28	issueAttachments,29	readUploads,30	type Upload,31	visibleFile,32} from "./files.ts";33import {34	confirmFollower,35	follow,36	followerLinkMatches,37	followsSince,38	isEmail,39	tellFollowers,40	unfollow,41} from "./followers.ts";42import {43	checkStamp,44	FILINGS_PER_HOUR,45	formStamp,46	ipHash,47	MAX_CHARS,48	REPLIES_PER_HOUR,49} from "./spam.ts";50import {51	addEntry,52	type Entry,53	fileIssue,54	filingsSince,55	findIssue,56	ISSUE_TYPES,57	type Issue,58	type IssueType,59	isBlocked,60	issueCounts,61	listIssues,62	repliesSince,63	threadEntries,64} from "./store.ts";6566type Fields = Record<string, string>;67// How a thread is shown: whether email is offered, a notice, and what a refused reply typed.68type View = {69	mail: boolean;70	notice?: string;71	/** Which form a refusal belongs to, so its error and what was typed show there. */72	refused?: "reply" | "follow";73	error?: string;74	body?: string;75	name?: string;76	email?: string;77	replyTo?: number | null;78};7980const FORM_FIELDS = [81	"title",82	"body",83	"type",84	"version",85	"name",86	"email",87	"follow",88	"website",89	"stamp",90];91const REPLY_FIELDS = ["body", "name", "email", "reply_to", "website", "stamp"];92const NAME_CHARS = 200;93const unixNow = () => Math.floor(Date.now() / 1000);94// The same words whatever the reason, so a blocked address learns nothing more.95const BLOCKED = "This address can't post here.";96const BAD_EMAIL = "That email address doesn't look right.";97// What a thread says after a follow form or link, named by `?notice=`.98const NOTICES: Record<string, string> = {99	check: "Check your inbox: one email asks you to confirm, and replies follow once you do.",100	following: "You'll get an email for each reply, and when the issue is closed or reopened.",101	stopped: "You won't get any more emails about this issue.",102	expired: "That link didn't work. You can follow again from this page.",103};104105/** §23: the list, the filing form, and the thread anyone can reply to and follow by email. */106export function registerIssuePages(app: Hono, ctx: PageContext, config: Config): void {107	const mail = () => config.smtp !== undefined;108	const site = () => `https://${ctx.domain}`;109	const open = (c: Context) => {110		const repo = openPublicRepo(ctx, c.req.param("repo") ?? "");111		const issue = repo && findIssue(ctx.kepr, repo.settings.name, Number(c.req.param("n")));112		return repo && issue113			? { repo, issue, base: `/${repo.settings.name}/issues/${issue.number}` }114			: null;115	};116117	app.get("/:repo/issues", (c) => {118		const repo = openPublicRepo(ctx, c.req.param("repo"));119		if (!repo) return notFound(c, ctx);120		const status = c.req.query("status") === "closed" ? "closed" : "open";121		cacheFor(c, false);122		return c.html(listPage(ctx, repo, status, c.req.query("q") ?? "", c.req.query("type") ?? ""));123	});124125	app.get("/:repo/issues/new", (c) => {126		const repo = openPublicRepo(ctx, c.req.param("repo"));127		if (!repo) return notFound(c, ctx);128		const version = visibleReleases(ctx.kepr, repo.mirror, repo.settings.name)[0]?.version ?? "";129		return formPage(c, ctx, repo, { type: "bug", version, follow: "1" }, "", 200, mail());130	});131132	app.post("/:repo/issues/new", async (c) => {133		const repo = openPublicRepo(ctx, c.req.param("repo"));134		if (!repo) return notFound(c, ctx);135		if (repo.settings.issuesPaused) return formPage(c, ctx, repo, {}, "", 403, mail());136		const now = unixNow();137		const hash = ipHash(ctx.kepr, c);138		// Answered before the body is read: a blocked or over-quota address is refused without139		// parsing the 34 MB a post may carry (§25).140		const early = (message: string, status: 400 | 403 | 429) =>141			formPage(c, ctx, repo, {}, message, status, mail());142		if (isBlocked(ctx.kepr, hash)) return early(BLOCKED, 403);143		if (filingsSince(ctx.kepr, hash, now - 3600) >= FILINGS_PER_HOUR) {144			return early("Too many issues from here this hour. Please try again later.", 429);145		}146		const { fields, files } = await readForm(c, FORM_FIELDS);147		const refuse = (message: string, status: 400 | 403 | 429) =>148			formPage(c, ctx, repo, fields, attachAgain(message, files), status, mail());149		// A bot that fills the hidden field learns nothing from the answer.150		if (fields.website !== "") return refuse("This issue could not be filed.", 400);151		const stamp = checkStamp(ctx.kepr, c, fields.stamp ?? "", now);152		if (stamp === "invalid") return refuse("This form expired. Please send it again.", 403);153		if (stamp === "too-fast") return refuse("That was quick. Please send it again.", 400);154		const title = fields.title?.trim() ?? "";155		const body = fields.body?.trim() ?? "";156		const email = fields.email?.trim() ?? "";157		if (title === "" || body === "") return refuse("A title and what happened are needed.", 400);158		if (!ISSUE_TYPES.includes(fields.type as IssueType)) return refuse("Pick a type.", 400);159		if (email !== "" && !isEmail(email)) return refuse(BAD_EMAIL, 400);160		if (Object.values(fields).some((value) => value.length > MAX_CHARS)) {161			return refuse(162				`Please keep each field under ${MAX_CHARS.toLocaleString("en-US")} characters.`,163				400,164			);165		}166		const uploads = await checkUploads(ctx, files, hash, now);167		if (!Array.isArray(uploads)) return refuse(uploads.error, uploads.status);168		const name = repo.settings.name;169		const filed = fileIssue(ctx.kepr, {170			repo: name,171			title,172			body,173			type: fields.type as IssueType,174			version: fields.version?.trim() ?? "",175			reporterName: fields.name?.trim() ?? "",176			contactEmail: email,177			ipHash: hash,178			filedAt: now,179		});180		attachFiles(ctx.kepr, filed.id, null, uploads, hash, now);181		notify(182			ctx.kepr,183			"issue_filed",184			`New issue ${name} #${filed.number}: ${title}`,185			`/admin/issues/${name}/${filed.number}`,186		);187		const issue = findIssue(ctx.kepr, name, filed.number);188		const asked =189			issue && mail() && fields.follow === "1" && email !== ""190				? follow(ctx.kepr, site(), name, issue, email, hash, now)191				: false;192		return c.redirect(`/${name}/issues/${filed.number}${asked ? "?notice=check" : ""}`, 303);193	});194195	app.get("/:repo/issues/:n{[0-9]{1,9}}/files/:file{[0-9]{1,9}\\.[a-z]{3,4}}", (c) => {196		const repo = openPublicRepo(ctx, c.req.param("repo"));197		const [id, ext] = c.req.param("file").split(".");198		const file =199			repo && visibleFile(ctx.kepr, repo.settings.name, Number(c.req.param("n")), Number(id));200		// One address per file: a name ending in another type's extension is as missing as no file.201		if (!repo || !file || FILE_EXTENSIONS[file.type] !== ext) return notFound(c, ctx);202		return c.body(file.data, 200, {203			"Content-Type": file.type === "text/plain" ? "text/plain; charset=utf-8" : file.type,204			"Content-Disposition": `inline; filename*=UTF-8''${encodeURIComponent(file.name)}`,205			// Short, so a file hidden as spam soon leaves shared caches too.206			"Cache-Control": "public, max-age=300",207		});208	});209210	app.get("/:repo/issues/:n{[0-9]{1,9}}", (c) => {211		const found = open(c);212		if (!found) return notFound(c, ctx);213		const { repo, issue } = found;214		const entries = threadEntries(ctx.kepr, issue.id);215		// `?reply=<id>` answers a reply; `?quote=<id>` also quotes it, and 0 is the issue itself.216		const quoting = c.req.query("quote");217		const asked = Number(quoting ?? c.req.query("reply"));218		const target = entries.find((entry) => entry.id === asked);219		const quoted = quoting === undefined ? null : asked === 0 ? issue.body : target?.body;220		privatePage(c);221		return c.html(222			threadPage(c, ctx, repo, issue, entries, {223				mail: mail(),224				notice: NOTICES[c.req.query("notice") ?? ""],225				replyTo: target?.id ?? null,226				body: quoted ? `${quoted.replace(/^/gm, "> ")}\n\n` : "",227			}),228		);229	});230231	app.post("/:repo/issues/:n{[0-9]{1,9}}", async (c) => {232		const found = open(c);233		if (!found) return notFound(c, ctx);234		const { repo, issue, base } = found;235		const entries = threadEntries(ctx.kepr, issue.id);236		const now = unixNow();237		privatePage(c);238		// Before the body is read: a closed issue, a blocked address and an over-quota one all239		// answer without parsing the uploads a reply may carry (§25).240		const hash = ipHash(ctx.kepr, c);241		const early = (error: string, status: 400 | 403 | 429) => {242			const view = { mail: mail(), refused: "reply" as const, error };243			return c.html(threadPage(c, ctx, repo, issue, entries, view), status);244		};245		if (issue.status === "closed") return early("This issue is closed to new replies.", 403);246		if (isBlocked(ctx.kepr, hash)) return early(BLOCKED, 403);247		const posted =248			repliesSince(ctx.kepr, hash, now - 3600) + followsSince(ctx.kepr, hash, now - 3600);249		if (posted >= REPLIES_PER_HOUR) {250			return early("Too many replies from here this hour. Please try again later.", 429);251		}252		const { fields, files } = await readForm(c, REPLY_FIELDS);253		const answering = entries.find((entry) => String(entry.id) === fields.reply_to);254		const body = fields.body?.trim() ?? "";255		const name = fields.name?.trim() ?? "";256		const email = fields.email?.trim() ?? "";257		const refuse = (message: string, status: 400 | 403 | 429) => {258			const view = {259				mail: mail(),260				refused: "reply" as const,261				error: attachAgain(message, files),262				body: fields.body,263				name,264				email,265				replyTo: answering?.id ?? null,266			};267			return c.html(threadPage(c, ctx, repo, issue, entries, view), status);268		};269		if (fields.website !== "") return refuse("This reply could not be posted.", 400);270		const stamp = checkStamp(ctx.kepr, c, fields.stamp ?? "", now);271		if (stamp === "invalid") return refuse("This form expired. Please send it again.", 403);272		if (stamp === "too-fast") return refuse("That was quick. Please send it again.", 400);273		if (body === "") return refuse("Write something to reply with.", 400);274		if (body.length > MAX_CHARS || name.length > NAME_CHARS) {275			return refuse(`Please keep it under ${MAX_CHARS.toLocaleString("en-US")} characters.`, 400);276		}277		if (email !== "" && !isEmail(email)) return refuse(BAD_EMAIL, 400);278		const uploads = await checkUploads(ctx, files, hash, now);279		if (!Array.isArray(uploads)) return refuse(uploads.error, uploads.status);280		const entry = addEntry(ctx.kepr, issue.id, {281			author: "reporter",282			name,283			body,284			at: now,285			ipHash: hash,286			replyTo: answering?.id ?? null,287		});288		attachFiles(ctx.kepr, issue.id, entry, uploads, hash, now);289		notify(290			ctx.kepr,291			"issue_followup",292			`Reply on ${repo.settings.name} #${issue.number}: ${issue.title}`,293			`/admin/issues/${repo.settings.name}/${issue.number}`,294		);295		const author = name || "anonymous";296		const to = answering297			? ` to ${answering.author === "operator" ? "the operator" : answering.name || "anonymous"}`298			: "";299		const extra = uploads.length > 0 ? `\n\n(${uploads.length} attached on the page)` : "";300		tellFollowers(301			ctx.kepr,302			site(),303			repo.settings.name,304			issue,305			{ text: `${author} replied${to}:\n\n${body}${extra}`, href: `${base}#entry-${entry}` },306			email,307		);308		const asked = mail() && email !== "";309		if (asked) follow(ctx.kepr, site(), repo.settings.name, issue, email, hash, now);310		// The same answer whether the address already followed, so a reply never says who follows311		// what; the follow form answers identically, for the same reason (§23).312		return c.redirect(`${base}${asked ? "?notice=check" : ""}#entry-${entry}`, 303);313	});314315	app.post("/:repo/issues/:n{[0-9]{1,9}}/follow", async (c) => {316		const found = open(c);317		if (!found || !mail()) return notFound(c, ctx);318		const { repo, issue, base } = found;319		const { fields } = await readForm(c, ["email", "website", "stamp"]);320		const email = fields.email?.trim() ?? "";321		const now = unixNow();322		privatePage(c);323		const refuse = (error: string, status: 400 | 403 | 429) => {324			const view = { mail: true, refused: "follow" as const, error, email };325			const entries = threadEntries(ctx.kepr, issue.id);326			return c.html(threadPage(c, ctx, repo, issue, entries, view), status);327		};328		if (fields.website !== "") return refuse("This address could not follow.", 400);329		const stamp = checkStamp(ctx.kepr, c, fields.stamp ?? "", now);330		if (stamp === "invalid") return refuse("This form expired. Please send it again.", 403);331		if (stamp === "too-fast") return refuse("That was quick. Please send it again.", 400);332		if (!isEmail(email)) return refuse(BAD_EMAIL, 400);333		const hash = ipHash(ctx.kepr, c);334		if (isBlocked(ctx.kepr, hash)) return refuse(BLOCKED, 403);335		const posted =336			repliesSince(ctx.kepr, hash, now - 3600) + followsSince(ctx.kepr, hash, now - 3600);337		if (posted >= REPLIES_PER_HOUR) {338			return refuse("Too many requests from here this hour. Please try again later.", 429);339		}340		follow(ctx.kepr, site(), repo.settings.name, issue, email, hash, now);341		// The same answer whether the address was new, so a page never says who follows what; it342		// opens at the top, where the notice is.343		return c.redirect(`${base}?notice=check`, 303);344	});345346	// The link in a confirmation email (§23); its token is the proof the inbox is theirs.347	app.get("/:repo/issues/:n{[0-9]{1,9}}/follow", (c) => {348		const found = open(c);349		if (!found) return notFound(c, ctx);350		const confirmed = confirmFollower(351			ctx.kepr,352			found.issue.id,353			Number(c.req.query("f")),354			c.req.query("t") ?? "",355		);356		privatePage(c);357		return c.redirect(`${found.base}?notice=${confirmed ? "following" : "expired"}`, 303);358	});359360	// A stop link asks first, so a mail scanner opening it changes nothing.361	app.get("/:repo/issues/:n{[0-9]{1,9}}/unfollow", (c) => {362		const found = open(c);363		if (!found) return notFound(c, ctx);364		const { repo, issue, base } = found;365		const id = Number(c.req.query("f"));366		const token = c.req.query("t") ?? "";367		privatePage(c);368		if (!followerLinkMatches(ctx.kepr, found.issue.id, id, token)) {369			return c.redirect(`${base}?notice=expired`, 303);370		}371		const query = new URLSearchParams({ f: String(id), t: token });372		return c.html(373			page(ctx, {374				title: `stop emails · #${issue.number} ${issue.title}`,375				description: "",376				path: `${base}/unfollow`,377				body: html`${crumbs(repo.settings.name)}378<h1 class="file-page-title">stop emails about #${issue.number}?</h1>379<p>You follow “${issue.title}” by email. Stopping takes effect at once.</p>380<form class="issues-actions" method="post" action="${base}/unfollow?${query.toString()}">381<button class="issues-submit" type="submit">stop emails</button>382<a class="issues-cancel mono" href="${base}">keep them</a></form>`,383			}),384		);385	});386387	// Both the page's button and an inbox's one-click unsubscribe (RFC 8058) post here.388	app.post("/:repo/issues/:n{[0-9]{1,9}}/unfollow", async (c) => {389		const found = open(c);390		if (!found) return notFound(c, ctx);391		const stopped = unfollow(392			ctx.kepr,393			found.issue.id,394			Number(c.req.query("f")),395			c.req.query("t") ?? "",396		);397		const form = await c.req.parseBody();398		if (form["List-Unsubscribe"] === "One-Click") {399			return c.text(stopped ? "Unsubscribed." : "Unknown link.", stopped ? 200 : 404);400		}401		return c.redirect(`${found.base}?notice=${stopped ? "stopped" : "expired"}`, 303);402	});403}404405async function readForm(c: Context, names: string[]): Promise<{ fields: Fields; files: File[] }> {406	const form = await c.req.parseBody({ all: true });407	const fields: Fields = {};408	for (const name of names) {409		const value = form[name];410		fields[name] = typeof value === "string" ? value : "";411	}412	// An empty file input still sends one nameless, empty part.413	const files = [form.files ?? []]414		.flat()415		.filter((file): file is File => file instanceof File && file.size > 0);416	return { fields, files };417}418419/** A post's files, checked last so the post's own refusals come first; or why they're refused. */420async function checkUploads(421	ctx: PageContext,422	files: File[],423	hash: string,424	now: number,425): Promise<Upload[] | { error: string; status: 400 | 429 }> {426	const uploads = await readUploads(files);427	if (typeof uploads === "string") return { error: uploads, status: 400 };428	const bytes = uploads.reduce((sum, upload) => sum + upload.data.length, 0);429	if (bytes > 0 && fileBytesSince(ctx.kepr, hash, now - 3600) + bytes > FILE_BYTES_PER_HOUR) {430		return {431			error: "Too many attachments from here this hour. Please try again later.",432			status: 429,433		};434	}435	// The site's day, not this address's hour: a botnet sharing one prefix still fills one bucket.436	if (bytes > 0 && attachmentBytesToday(now) + bytes > ATTACHMENT_BYTES_PER_DAY) {437		return { error: "Too many attachments today. Please try again tomorrow.", status: 429 };438	}439	return uploads;440}441442// A browser can't refill a file input, so a refused post says its files need choosing again.443function attachAgain(message: string, files: File[]): string {444	return files.length > 0 ? `${message} Please attach your files again.` : message;445}446447// A page carrying a form stamp or a follow link is never cached, nor sent on as a referrer.448function privatePage(c: Context): void {449	c.header("Cache-Control", "no-store");450	c.header("Referrer-Policy", "no-referrer");451}452453function crumbs(repo: string, closed = false): Html {454	return html`<p class="breadcrumb mono">455<a href="/${repo}">${repo}</a> /456<a href="/${repo}/issues${closed ? "?status=closed" : ""}">back to issues</a></p>`;457}458459function listPage(460	ctx: PageContext,461	repo: PublicRepo,462	status: "open" | "closed",463	query: string,464	type: string,465): string {466	const name = repo.settings.name;467	const counts = issueCounts(ctx.kepr, name);468	const filter = ISSUE_TYPES.includes(type as IssueType) ? type : "";469	const issues = listIssues(ctx.kepr, name, status).filter(470		(issue) =>471			(!filter || issue.type === filter) &&472			issue.title.toLowerCase().includes(query.trim().toLowerCase()),473	);474	const tab = (which: "open" | "closed") =>475		html`<a class="issues-tab${which === status ? " active" : ""}"476			href="/${name}/issues${which === "closed" ? "?status=closed" : ""}">477${which} <span class="muted">${counts[which]}</span></a>`;478	return page(ctx, {479		title: `issues · ${name}`,480		description: `Issues filed against ${name}.`,481		path: `/${name}/issues`,482		body: html`<p class="breadcrumb mono"><a href="/${name}">${name}</a></p>483<h1 class="file-page-title">issues</h1>484<p class="issues-bar mono">${tab("open")}${tab("closed")}485${!repo.settings.issuesPaused && html`<a class="issues-new" href="/${name}/issues/new">report an issue →</a>`}</p>486<form class="issues-filter" method="get" action="/${name}/issues">487<input type="hidden" name="status" value="${status}">488<input class="issues-input issues-search" name="q" type="search" aria-label="search issue titles"489placeholder="search issues" value="${query}">490<select class="issues-input issues-type" name="type" aria-label="issue type">491<option value="">all types</option>492${ISSUE_TYPES.map(493	(value) =>494		html`<option value="${value}"${filter === value ? html` selected` : ""}>${value}</option>`,495)}496</select><button class="issues-submit" type="submit">filter</button></form>497<section class="repo-section">498${499	issues.length > 0500		? issues.map(501				(issue) =>502					html`<a class="issue-row" href="/${name}/issues/${issue.number}">503<span class="issue-symbol issue-symbol--${issue.status}">504${issue.status === "open" ? "◉" : "◈"}</span>505<span class="issue-title">${issue.title}</span>506${/* this line stays whole: splitting it changes the text tests/issues.test.ts asserts */ ""}<span class="issue-meta mono">#${issue.number} · ${issue.type}${issue.version && ` · v${issue.version}`} · ${relativeTime(issue.filed_at)}${issue.replies > 0 && ` · ${issue.replies} ${issue.replies === 1 ? "reply" : "replies"}`}</span>507<span class="issue-reporter mono">${issue.reporter_name || "anonymous"}</span>508</a>`,509			)510		: html`<p class="muted mono save-empty">${query || filter ? "no matching issues" : `no ${status} issues`}</p>`511}512</section>`,513	});514}515516// A refused post shows what was typed, never more than a field may hold: an issue post may be 34 MB517// (§25), so echoing that back escaped would answer one request with several times its size.518function kept(value: string | undefined): string {519	return (value ?? "").slice(0, MAX_CHARS);520}521522function formPage(523	c: Context,524	ctx: PageContext,525	repo: PublicRepo,526	values: Fields,527	error: string,528	status: 200 | 400 | 403 | 429,529	mail: boolean,530): Response {531	const name = repo.settings.name;532	privatePage(c);533	const typeOption = (type: string) =>534		html`<option value="${type}"${values.type === type ? html` selected` : ""}>${type}</option>`;535	const body = repo.settings.issuesPaused536		? html`${crumbs(name)}537<h1 class="file-page-title">report an issue</h1>538<p>${name} is not taking new issues right now.</p>539<p><a href="/${name}/issues">see the existing issues →</a></p>`540		: html`${crumbs(name)}541<h1 class="file-page-title">report an issue</h1>542${error && html`<p class="issues-error mono" role="alert">${error}</p>`}543<form class="issues-form" method="post" action="/${name}/issues/new"544enctype="multipart/form-data">545<input type="hidden" name="stamp" value="${formStamp(ctx.kepr, c, unixNow())}">546<label class="issues-hp" aria-hidden="true">leave this empty547<input name="website" tabindex="-1" autocomplete="off"></label>548<label class="issues-label" for="issue-title">title</label>549<input class="issues-input" id="issue-title" name="title" required maxlength="${MAX_CHARS}" value="${kept(values.title)}">550<label class="issues-label" for="issue-body">what happened</label>551<textarea class="issues-textarea" id="issue-body" name="body" rows="10" required552maxlength="${MAX_CHARS}">${kept(values.body)}</textarea>553${markdownHint}554${attachField("issue-files")}555<label class="issues-label" for="issue-type">type</label>556<select class="issues-input" id="issue-type" name="type">${ISSUE_TYPES.map(typeOption)}</select>557<label class="issues-label" for="issue-version">version you're on</label>558<input class="issues-input" id="issue-version" name="version" maxlength="200" value="${kept(values.version)}">559<label class="issues-label" for="issue-name">name to show560<span class="muted">(optional)</span></label>561<input class="issues-input" id="issue-name" name="name" maxlength="${NAME_CHARS}"562autocomplete="nickname" value="${kept(values.name)}">563<label class="issues-label" for="issue-email">contact email564<span class="muted">(optional, only the operator sees it)</span></label>565<input class="issues-input" id="issue-email" name="email" type="email" maxlength="254"566autocomplete="email" value="${kept(values.email)}">567${568	mail &&569	html`<label class="issues-label issues-check">570<input type="checkbox" name="follow" value="1"${values.follow === "1" ? html` checked` : ""}>571email me each reply, and when it's closed</label>`572}573<p class="issues-actions"><button class="issues-submit" type="submit">file issue</button>574<a class="issues-cancel mono" href="/${name}/issues">cancel</a></p>575</form>`;576	return c.html(577		page(ctx, {578			title: `report an issue · ${name}`,579			description: `File an issue against ${name}.`,580			path: `/${name}/issues/new`,581			body,582		}),583		status,584	);585}586587const markdownHint = html`<p class="issue-hint mono">Markdown works: **bold**, \`code\`,588\`\`\` around logs, &gt; to quote.</p>`;589590function attachField(id: string): Html {591	return html`<label class="issues-label" for="${id}">screenshots or logs592<span class="muted">(optional, up to ${FILES_PER_POST})</span></label>593<input class="issues-file" id="${id}" name="files" type="file" multiple594accept="image/png,image/jpeg,image/gif,image/webp,.txt,.log">595<ul class="issue-attached mono" aria-live="polite"></ul>596<p class="issue-hint mono">PNG, JPEG, GIF or WebP up to 8 MB; .txt or .log up to 2 MB.597Pictures can be pasted or dropped into the text box too.</p>`;598}599600/** A post's pictures side by side, and each log as its start with the whole file a link away. */601export function attachmentsHtml(base: string, files: Attachment[]): Html {602	const url = (file: Attachment) => `${base}/files/${file.id}.${FILE_EXTENSIONS[file.type]}`;603	const images = files.filter((file) => file.type !== "text/plain");604	const logs = files.filter((file) => file.type === "text/plain");605	return html`${606		images.length > 0 &&607		html`<div class="issue-shots">${images.map(608			(file) => html`<a class="issue-shot" href="${url(file)}" target="_blank" rel="noopener">609<img src="${url(file)}" alt="${file.name}" loading="lazy"></a>`,610		)}</div>`611	}${logs.map(612		(file) => html`<details class="issue-log">613<summary class="issue-log-name mono">${file.name}614<span class="muted">${formatSize(file.size)}</span></summary>615<pre><code>${new TextDecoder().decode(file.head ?? new Uint8Array())}</code></pre>616<p class="issue-log-foot mono">617<a class="issue-log-whole" href="${url(file)}">open the whole log</a>${618			file.size > (file.head?.length ?? 0) &&619			` · showing its first ${formatSize(file.head?.length ?? 0)}`620		}</p>621</details>`,622	)}`;623}624625function threadPage(626	c: Context,627	ctx: PageContext,628	repo: PublicRepo,629	issue: Issue,630	entries: Entry[],631	view: View,632): string {633	const name = repo.settings.name;634	const base = `/${name}/issues/${issue.number}`;635	const open = issue.status === "open";636	const who = (entry: Entry) =>637		entry.author === "operator" ? "operator" : entry.name || "anonymous";638	const byId = new Map(entries.map((entry) => [entry.id, entry]));639	const answering = view.replyTo ? byId.get(view.replyTo) : undefined;640	const files = issueAttachments(ctx.kepr, issue.id);641	const stamp = formStamp(ctx.kepr, c, unixNow());642	// The issue itself is post 0: quoting it quotes what was filed.643	const post = (key: number, author: string, operator: boolean, at: number, body: string) => {644		const id = key === 0 ? "issue" : `entry-${key}`;645		const answers = byId.get(byId.get(key)?.reply_to ?? -1);646		const attached = files.filter((file) => (file.entry_id ?? 0) === key);647		return html`<article class="issue-post${operator ? " issue-post--operator" : ""}" id="${id}"648data-entry="${key === 0 ? "" : String(key)}" data-author="${author}">649<p class="issue-post-head mono">${650			operator651				? html`<span class="issue-badge">operator</span>`652				: html`<span class="issue-author">${author}</span>`653		}${654			answers &&655			html`<span class="issue-replying">replying to656<a href="#entry-${answers.id}">${who(answers)}</a></span>`657		}<a class="history-when" href="#${id}" title="${formatDate(at)}">${relativeTime(at)}</a></p>658<div class="markdown issue-text">${renderComment(body)}</div>659${attached.length > 0 && attachmentsHtml(base, attached)}660${661	open &&662	html`<p class="issue-post-actions mono">663<a href="${base}?reply=${key}#reply" data-action="reply">reply</a>664<a href="${base}?quote=${key}#reply" data-action="quote">quote</a></p>`665}666</article>`;667	};668	const reporter = issue.reporter_name || "anonymous";669	const error = view.error && html`<p class="issues-error mono" role="alert">${view.error}</p>`;670	const honeypot = html`<input type="hidden" name="stamp" value="${stamp}">671<label class="issues-hp" aria-hidden="true">leave this empty672<input name="website" tabindex="-1" autocomplete="off"></label>`;673	return page(ctx, {674		title: `#${issue.number} ${issue.title} · ${name}`,675		description: issue.title,676		path: base,677		body: html`${crumbs(name, !open)}678<h1 class="file-page-title">${issue.title} <span class="muted">#${issue.number}</span></h1>679<p class="issue-meta mono">680<span class="issue-symbol issue-symbol--${issue.status}">${open ? "◉ open" : "◈ closed"}</span>681${issue.type}${issue.version && ` · v${issue.version}`}682· filed by ${reporter} ${relativeTime(issue.filed_at)}683${entries.length > 0 && ` · ${entries.length} ${entries.length === 1 ? "reply" : "replies"}`}684${!open && fixedIn(repo, issue)}</p>685${view.notice && html`<p class="issue-notice mono" role="status">${view.notice}</p>`}686<div class="issue-thread">687${post(0, reporter, false, issue.filed_at, issue.body)}688${entries.map((entry) =>689	post(entry.id, who(entry), entry.author === "operator", entry.created_at, entry.body),690)}691</div>692${693	open694		? html`<form class="issue-composer" id="reply" method="post" action="${base}"695enctype="multipart/form-data">696${honeypot}697<input type="hidden" name="reply_to" value="${answering ? String(answering.id) : ""}">698<p class="issue-composer-head mono"><label for="reply-body">add a reply</label>699<span class="issue-composer-to"${answering ? "" : html` hidden`}>replying to700<a class="issue-composer-name"701href="#entry-${answering ? String(answering.id) : ""}">${answering ? who(answering) : ""}</a>702<a class="issues-cancel" href="${base}#reply"703aria-label="reply to the issue instead">×</a></span></p>704${view.refused === "reply" && error}705<textarea class="issues-textarea" id="reply-body" name="body" rows="7" required706maxlength="${MAX_CHARS}" placeholder="More detail, another angle, what you tried…"707>${kept(view.body)}</textarea>708${markdownHint}709${attachField("reply-files")}710<div class="issue-composer-who">711<label class="issues-label" for="reply-name">name to show712<span class="muted">(optional)</span></label>713<input class="issues-input" id="reply-name" name="name" maxlength="${NAME_CHARS}"714autocomplete="nickname" value="${kept(view.name)}">715${716	view.mail &&717	html`<label class="issues-label" for="reply-email">email me new replies718<span class="muted">(optional, never shown)</span></label>719<input class="issues-input" id="reply-email" name="email" type="email" maxlength="254"720autocomplete="email" value="${view.refused === "reply" ? kept(view.email) : ""}">`721}722</div>723<p class="issues-actions"><button class="issues-submit" type="submit">post reply</button></p>724</form>`725		: html`${view.refused === "reply" && error}726<p class="issue-closed-note mono">This issue is closed, so it takes no new replies.</p>`727}728${729	view.mail &&730	html`<form class="issue-follow" id="follow" method="post" action="${base}/follow">731${honeypot}732<label class="issues-label" for="follow-email">follow by email733<span class="muted">(each reply, and when it closes; your address is never shown)</span></label>734${view.refused === "follow" && error}735<p class="issue-follow-row"><input class="issues-input" id="follow-email" name="email" type="email"736required maxlength="254" autocomplete="email" placeholder="[email protected]"737value="${view.refused === "follow" ? (view.email ?? "") : ""}">738<button class="issues-submit" type="submit">follow</button></p>739</form>`740}`,741	});742}743744function fixedIn(repo: PublicRepo, issue: Issue): Html | "" {745	if (issue.fixed_in === "") return "";746	const save = saveByPrefix(repo.mirror, issue.fixed_in);747	// Only a save with a page of its own is linked; a checkpoint or an unknown ID stays text.748	const id =749		save && !save.is_checkpoint750			? html`<a class="history-id" href="/${repo.settings.name}/saves/${save.id}">${save.id}</a>`751			: html`<span class="history-id">${issue.fixed_in}</span>`;752	return html` · fixed in ${id}`;753}