pages.ts

31.7 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		const wanted = Math.max(1, Number.parseInt(c.req.query("page") ?? "1", 10) || 1);122		cacheFor(c, false);123		return c.html(124			listPage(ctx, repo, status, c.req.query("q") ?? "", c.req.query("type") ?? "", wanted),125		);126	});127128	app.get("/:repo/issues/new", (c) => {129		const repo = openPublicRepo(ctx, c.req.param("repo"));130		if (!repo) return notFound(c, ctx);131		const version = visibleReleases(ctx.kepr, repo.mirror, repo.settings.name)[0]?.version ?? "";132		return formPage(c, ctx, repo, { type: "bug", version, follow: "1" }, "", 200, mail());133	});134135	app.post("/:repo/issues/new", async (c) => {136		const repo = openPublicRepo(ctx, c.req.param("repo"));137		if (!repo) return notFound(c, ctx);138		if (repo.settings.issuesPaused) return formPage(c, ctx, repo, {}, "", 403, mail());139		const now = unixNow();140		const hash = ipHash(ctx.kepr, c);141		// Answered before the body is read: a blocked or over-quota address is refused without142		// parsing the 34 MB a post may carry (§25).143		const early = (message: string, status: 400 | 403 | 429) =>144			formPage(c, ctx, repo, {}, message, status, mail());145		if (isBlocked(ctx.kepr, hash)) return early(BLOCKED, 403);146		if (filingsSince(ctx.kepr, hash, now - 3600) >= FILINGS_PER_HOUR) {147			return early("Too many issues from here this hour. Please try again later.", 429);148		}149		const { fields, files } = await readForm(c, FORM_FIELDS);150		const refuse = (message: string, status: 400 | 403 | 429) =>151			formPage(c, ctx, repo, fields, attachAgain(message, files), status, mail());152		// A bot that fills the hidden field learns nothing from the answer.153		if (fields.website !== "") return refuse("This issue could not be filed.", 400);154		const stamp = checkStamp(ctx.kepr, c, fields.stamp ?? "", now);155		if (stamp === "invalid") return refuse("This form expired. Please send it again.", 403);156		if (stamp === "too-fast") return refuse("That was quick. Please send it again.", 400);157		const title = fields.title?.trim() ?? "";158		const body = fields.body?.trim() ?? "";159		const email = fields.email?.trim() ?? "";160		if (title === "" || body === "") return refuse("A title and what happened are needed.", 400);161		if (!ISSUE_TYPES.includes(fields.type as IssueType)) return refuse("Pick a type.", 400);162		if (email !== "" && !isEmail(email)) return refuse(BAD_EMAIL, 400);163		if (Object.values(fields).some((value) => value.length > MAX_CHARS)) {164			return refuse(165				`Please keep each field under ${MAX_CHARS.toLocaleString("en-US")} characters.`,166				400,167			);168		}169		const uploads = await checkUploads(ctx, files, hash, now);170		if (!Array.isArray(uploads)) return refuse(uploads.error, uploads.status);171		const name = repo.settings.name;172		const filed = fileIssue(ctx.kepr, {173			repo: name,174			title,175			body,176			type: fields.type as IssueType,177			version: fields.version?.trim() ?? "",178			reporterName: fields.name?.trim() ?? "",179			contactEmail: email,180			ipHash: hash,181			filedAt: now,182		});183		attachFiles(ctx.kepr, filed.id, null, uploads, hash, now);184		notify(185			ctx.kepr,186			"issue_filed",187			`New issue ${name} #${filed.number}: ${title}`,188			`/admin/issues/${name}/${filed.number}`,189		);190		const issue = findIssue(ctx.kepr, name, filed.number);191		const asked =192			issue && mail() && fields.follow === "1" && email !== ""193				? follow(ctx.kepr, site(), name, issue, email, hash, now)194				: false;195		return c.redirect(`/${name}/issues/${filed.number}${asked ? "?notice=check" : ""}`, 303);196	});197198	app.get("/:repo/issues/:n{[0-9]{1,9}}/files/:file{[0-9]{1,9}\\.[a-z]{3,4}}", (c) => {199		const repo = openPublicRepo(ctx, c.req.param("repo"));200		const [id, ext] = c.req.param("file").split(".");201		const file =202			repo && visibleFile(ctx.kepr, repo.settings.name, Number(c.req.param("n")), Number(id));203		// One address per file: a name ending in another type's extension is as missing as no file.204		if (!repo || !file || FILE_EXTENSIONS[file.type] !== ext) return notFound(c, ctx);205		return c.body(file.data, 200, {206			"Content-Type": file.type === "text/plain" ? "text/plain; charset=utf-8" : file.type,207			"Content-Disposition": `inline; filename*=UTF-8''${encodeURIComponent(file.name)}`,208			// Short, so a file hidden as spam soon leaves shared caches too.209			"Cache-Control": "public, max-age=300",210		});211	});212213	app.get("/:repo/issues/:n{[0-9]{1,9}}", (c) => {214		const found = open(c);215		if (!found) return notFound(c, ctx);216		const { repo, issue } = found;217		const entries = threadEntries(ctx.kepr, issue.id);218		// `?reply=<id>` answers a reply; `?quote=<id>` also quotes it, and 0 is the issue itself.219		const quoting = c.req.query("quote");220		const asked = Number(quoting ?? c.req.query("reply"));221		const target = entries.find((entry) => entry.id === asked);222		const quoted = quoting === undefined ? null : asked === 0 ? issue.body : target?.body;223		privatePage(c);224		return c.html(225			threadPage(c, ctx, repo, issue, entries, {226				mail: mail(),227				notice: NOTICES[c.req.query("notice") ?? ""],228				replyTo: target?.id ?? null,229				body: quoted ? `${quoted.replace(/^/gm, "> ")}\n\n` : "",230			}),231		);232	});233234	app.post("/:repo/issues/:n{[0-9]{1,9}}", async (c) => {235		const found = open(c);236		if (!found) return notFound(c, ctx);237		const { repo, issue, base } = found;238		const entries = threadEntries(ctx.kepr, issue.id);239		const now = unixNow();240		privatePage(c);241		// Before the body is read: a closed issue, a blocked address and an over-quota one all242		// answer without parsing the uploads a reply may carry (§25).243		const hash = ipHash(ctx.kepr, c);244		const early = (error: string, status: 400 | 403 | 429) => {245			const view = { mail: mail(), refused: "reply" as const, error };246			return c.html(threadPage(c, ctx, repo, issue, entries, view), status);247		};248		if (issue.status === "closed") return early("This issue is closed to new replies.", 403);249		if (isBlocked(ctx.kepr, hash)) return early(BLOCKED, 403);250		const posted =251			repliesSince(ctx.kepr, hash, now - 3600) + followsSince(ctx.kepr, hash, now - 3600);252		if (posted >= REPLIES_PER_HOUR) {253			return early("Too many replies from here this hour. Please try again later.", 429);254		}255		const { fields, files } = await readForm(c, REPLY_FIELDS);256		const answering = entries.find((entry) => String(entry.id) === fields.reply_to);257		const body = fields.body?.trim() ?? "";258		const name = fields.name?.trim() ?? "";259		const email = fields.email?.trim() ?? "";260		const refuse = (message: string, status: 400 | 403 | 429) => {261			const view = {262				mail: mail(),263				refused: "reply" as const,264				error: attachAgain(message, files),265				body: fields.body,266				name,267				email,268				replyTo: answering?.id ?? null,269			};270			return c.html(threadPage(c, ctx, repo, issue, entries, view), status);271		};272		if (fields.website !== "") return refuse("This reply could not be posted.", 400);273		const stamp = checkStamp(ctx.kepr, c, fields.stamp ?? "", now);274		if (stamp === "invalid") return refuse("This form expired. Please send it again.", 403);275		if (stamp === "too-fast") return refuse("That was quick. Please send it again.", 400);276		if (body === "") return refuse("Write something to reply with.", 400);277		if (body.length > MAX_CHARS || name.length > NAME_CHARS) {278			return refuse(`Please keep it under ${MAX_CHARS.toLocaleString("en-US")} characters.`, 400);279		}280		if (email !== "" && !isEmail(email)) return refuse(BAD_EMAIL, 400);281		const uploads = await checkUploads(ctx, files, hash, now);282		if (!Array.isArray(uploads)) return refuse(uploads.error, uploads.status);283		const entry = addEntry(ctx.kepr, issue.id, {284			author: "reporter",285			name,286			body,287			at: now,288			ipHash: hash,289			replyTo: answering?.id ?? null,290		});291		attachFiles(ctx.kepr, issue.id, entry, uploads, hash, now);292		notify(293			ctx.kepr,294			"issue_followup",295			`Reply on ${repo.settings.name} #${issue.number}: ${issue.title}`,296			`/admin/issues/${repo.settings.name}/${issue.number}`,297		);298		const author = name || "anonymous";299		const to = answering300			? ` to ${answering.author === "operator" ? "the operator" : answering.name || "anonymous"}`301			: "";302		const extra = uploads.length > 0 ? `\n\n(${uploads.length} attached on the page)` : "";303		tellFollowers(304			ctx.kepr,305			site(),306			repo.settings.name,307			issue,308			{ text: `${author} replied${to}:\n\n${body}${extra}`, href: `${base}#entry-${entry}` },309			email,310		);311		const asked = mail() && email !== "";312		if (asked) follow(ctx.kepr, site(), repo.settings.name, issue, email, hash, now);313		// The same answer whether the address already followed, so a reply never says who follows314		// what; the follow form answers identically, for the same reason (§23).315		return c.redirect(`${base}${asked ? "?notice=check" : ""}#entry-${entry}`, 303);316	});317318	app.post("/:repo/issues/:n{[0-9]{1,9}}/follow", async (c) => {319		const found = open(c);320		if (!found || !mail()) return notFound(c, ctx);321		const { repo, issue, base } = found;322		const { fields } = await readForm(c, ["email", "website", "stamp"]);323		const email = fields.email?.trim() ?? "";324		const now = unixNow();325		privatePage(c);326		const refuse = (error: string, status: 400 | 403 | 429) => {327			const view = { mail: true, refused: "follow" as const, error, email };328			const entries = threadEntries(ctx.kepr, issue.id);329			return c.html(threadPage(c, ctx, repo, issue, entries, view), status);330		};331		if (fields.website !== "") return refuse("This address could not follow.", 400);332		const stamp = checkStamp(ctx.kepr, c, fields.stamp ?? "", now);333		if (stamp === "invalid") return refuse("This form expired. Please send it again.", 403);334		if (stamp === "too-fast") return refuse("That was quick. Please send it again.", 400);335		if (!isEmail(email)) return refuse(BAD_EMAIL, 400);336		const hash = ipHash(ctx.kepr, c);337		if (isBlocked(ctx.kepr, hash)) return refuse(BLOCKED, 403);338		const posted =339			repliesSince(ctx.kepr, hash, now - 3600) + followsSince(ctx.kepr, hash, now - 3600);340		if (posted >= REPLIES_PER_HOUR) {341			return refuse("Too many requests from here this hour. Please try again later.", 429);342		}343		follow(ctx.kepr, site(), repo.settings.name, issue, email, hash, now);344		// The same answer whether the address was new, so a page never says who follows what; it345		// opens at the top, where the notice is.346		return c.redirect(`${base}?notice=check`, 303);347	});348349	// The link in a confirmation email (§23); its token is the proof the inbox is theirs.350	app.get("/:repo/issues/:n{[0-9]{1,9}}/follow", (c) => {351		const found = open(c);352		if (!found) return notFound(c, ctx);353		const confirmed = confirmFollower(354			ctx.kepr,355			found.issue.id,356			Number(c.req.query("f")),357			c.req.query("t") ?? "",358		);359		privatePage(c);360		return c.redirect(`${found.base}?notice=${confirmed ? "following" : "expired"}`, 303);361	});362363	// A stop link asks first, so a mail scanner opening it changes nothing.364	app.get("/:repo/issues/:n{[0-9]{1,9}}/unfollow", (c) => {365		const found = open(c);366		if (!found) return notFound(c, ctx);367		const { repo, issue, base } = found;368		const id = Number(c.req.query("f"));369		const token = c.req.query("t") ?? "";370		privatePage(c);371		if (!followerLinkMatches(ctx.kepr, found.issue.id, id, token)) {372			return c.redirect(`${base}?notice=expired`, 303);373		}374		const query = new URLSearchParams({ f: String(id), t: token });375		return c.html(376			page(ctx, {377				title: `stop emails · #${issue.number} ${issue.title}`,378				description: "",379				path: `${base}/unfollow`,380				body: html`${crumbs(repo.settings.name)}381<h1 class="file-page-title">stop emails about #${issue.number}?</h1>382<p>You follow “${issue.title}” by email. Stopping takes effect at once.</p>383<form class="issues-actions" method="post" action="${base}/unfollow?${query.toString()}">384<button class="issues-submit" type="submit">stop emails</button>385<a class="issues-cancel mono" href="${base}">keep them</a></form>`,386			}),387		);388	});389390	// Both the page's button and an inbox's one-click unsubscribe (RFC 8058) post here.391	app.post("/:repo/issues/:n{[0-9]{1,9}}/unfollow", async (c) => {392		const found = open(c);393		if (!found) return notFound(c, ctx);394		const stopped = unfollow(395			ctx.kepr,396			found.issue.id,397			Number(c.req.query("f")),398			c.req.query("t") ?? "",399		);400		const form = await c.req.parseBody();401		if (form["List-Unsubscribe"] === "One-Click") {402			return c.text(stopped ? "Unsubscribed." : "Unknown link.", stopped ? 200 : 404);403		}404		return c.redirect(`${found.base}?notice=${stopped ? "stopped" : "expired"}`, 303);405	});406}407408async function readForm(c: Context, names: string[]): Promise<{ fields: Fields; files: File[] }> {409	const form = await c.req.parseBody({ all: true });410	const fields: Fields = {};411	for (const name of names) {412		const value = form[name];413		fields[name] = typeof value === "string" ? value : "";414	}415	// An empty file input still sends one nameless, empty part.416	const files = [form.files ?? []]417		.flat()418		.filter((file): file is File => file instanceof File && file.size > 0);419	return { fields, files };420}421422/** A post's files, checked last so the post's own refusals come first; or why they're refused. */423async function checkUploads(424	ctx: PageContext,425	files: File[],426	hash: string,427	now: number,428): Promise<Upload[] | { error: string; status: 400 | 429 }> {429	const uploads = await readUploads(files);430	if (typeof uploads === "string") return { error: uploads, status: 400 };431	const bytes = uploads.reduce((sum, upload) => sum + upload.data.length, 0);432	if (bytes > 0 && fileBytesSince(ctx.kepr, hash, now - 3600) + bytes > FILE_BYTES_PER_HOUR) {433		return {434			error: "Too many attachments from here this hour. Please try again later.",435			status: 429,436		};437	}438	// The site's day, not this address's hour: a botnet sharing one prefix still fills one bucket.439	if (bytes > 0 && attachmentBytesToday(now) + bytes > ATTACHMENT_BYTES_PER_DAY) {440		return { error: "Too many attachments today. Please try again tomorrow.", status: 429 };441	}442	return uploads;443}444445// A browser can't refill a file input, so a refused post says its files need choosing again.446function attachAgain(message: string, files: File[]): string {447	return files.length > 0 ? `${message} Please attach your files again.` : message;448}449450// A page carrying a form stamp or a follow link is never cached, nor sent on as a referrer.451function privatePage(c: Context): void {452	c.header("Cache-Control", "no-store");453	c.header("Referrer-Policy", "no-referrer");454}455456function crumbs(repo: string, closed = false): Html {457	return html`<p class="breadcrumb mono">458<a href="/${repo}">${repo}</a> /459<a href="/${repo}/issues${closed ? "?status=closed" : ""}">back to issues</a></p>`;460}461462// Fifty rows is a page a reader can scan, and keeps an old issue one link away.463const ISSUES_PER_PAGE = 50;464465function listPage(466	ctx: PageContext,467	repo: PublicRepo,468	status: "open" | "closed",469	query: string,470	type: string,471	requested: number,472): string {473	const name = repo.settings.name;474	const counts = issueCounts(ctx.kepr, name);475	const filter = ISSUE_TYPES.includes(type as IssueType) ? type : "";476	// ponytail: a repo's whole visible list is filtered then sliced in memory; push the filter and477	// LIMIT into SQL if one repo ever holds more issues than a request should read.478	const matched = listIssues(ctx.kepr, name, status).filter(479		(issue) =>480			(!filter || issue.type === filter) &&481			issue.title.toLowerCase().includes(query.trim().toLowerCase()),482	);483	const pages = Math.max(1, Math.ceil(matched.length / ISSUES_PER_PAGE));484	const current = Math.min(Math.max(1, requested), pages);485	const issues = matched.slice((current - 1) * ISSUES_PER_PAGE, current * ISSUES_PER_PAGE);486	// Page 1 keeps today's URL, so a short list reads exactly as it did.487	const pageHref = (n: number) => {488		const params = new URLSearchParams({ status, q: query, type: filter });489		if (n > 1) params.set("page", String(n));490		return `/${name}/issues?${params.toString()}`;491	};492	const tab = (which: "open" | "closed") =>493		html`<a class="issues-tab${which === status ? " active" : ""}"494			href="/${name}/issues${which === "closed" ? "?status=closed" : ""}">495${which} <span class="muted">${counts[which]}</span></a>`;496	return page(ctx, {497		title: `issues · ${name}`,498		description: `Issues filed against ${name}.`,499		path: `/${name}/issues`,500		body: html`<p class="breadcrumb mono"><a href="/${name}">${name}</a></p>501<h1 class="file-page-title">issues</h1>502<p class="issues-bar mono">${tab("open")}${tab("closed")}503${!repo.settings.issuesPaused && html`<a class="issues-new" href="/${name}/issues/new">report an issue →</a>`}</p>504<form class="issues-filter" method="get" action="/${name}/issues">505<input type="hidden" name="status" value="${status}">506<input class="issues-input issues-search" name="q" type="search" aria-label="search issue titles"507placeholder="search issues" value="${query}">508<select class="issues-input issues-type" name="type" aria-label="issue type">509<option value="">all types</option>510${ISSUE_TYPES.map(511	(value) =>512		html`<option value="${value}"${filter === value ? html` selected` : ""}>${value}</option>`,513)}514</select><button class="issues-submit" type="submit">filter</button></form>515<section class="repo-section">516${517	issues.length > 0518		? issues.map(519				(issue) =>520					html`<a class="issue-row" href="/${name}/issues/${issue.number}">521<span class="issue-symbol issue-symbol--${issue.status}">522${issue.status === "open" ? "◉" : "◈"}</span>523<span class="issue-title">${issue.title}</span>524${/* 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>525<span class="issue-reporter mono">${issue.reporter_name || "anonymous"}</span>526</a>`,527			)528		: html`<p class="muted mono save-empty">${query || filter ? "no matching issues" : `no ${status} issues`}</p>`529}530</section>531${532	pages > 1 &&533	html`<p class="pager mono">${current > 1 && html`<a href="${pageHref(current - 1)}">← newer</a>`}<span class="muted">page ${current} of ${pages}</span>${current < pages && html`<a class="pager-older" href="${pageHref(current + 1)}">older →</a>`}</p>`534}`,535	});536}537538// A refused post shows what was typed, never more than a field may hold: an issue post may be 34 MB539// (§25), so echoing that back escaped would answer one request with several times its size.540function kept(value: string | undefined): string {541	return (value ?? "").slice(0, MAX_CHARS);542}543544function formPage(545	c: Context,546	ctx: PageContext,547	repo: PublicRepo,548	values: Fields,549	error: string,550	status: 200 | 400 | 403 | 429,551	mail: boolean,552): Response {553	const name = repo.settings.name;554	privatePage(c);555	const typeOption = (type: string) =>556		html`<option value="${type}"${values.type === type ? html` selected` : ""}>${type}</option>`;557	const body = repo.settings.issuesPaused558		? html`${crumbs(name)}559<h1 class="file-page-title">report an issue</h1>560<p>${name} is not taking new issues right now.</p>561<p><a href="/${name}/issues">see the existing issues →</a></p>`562		: html`${crumbs(name)}563<h1 class="file-page-title">report an issue</h1>564${error && html`<p class="issues-error mono" role="alert">${error}</p>`}565<form class="issues-form" method="post" action="/${name}/issues/new"566enctype="multipart/form-data">567<input type="hidden" name="stamp" value="${formStamp(ctx.kepr, c, unixNow())}">568<label class="issues-hp" aria-hidden="true">leave this empty569<input name="website" tabindex="-1" autocomplete="off"></label>570<label class="issues-label" for="issue-title">title</label>571<input class="issues-input" id="issue-title" name="title" required maxlength="${MAX_CHARS}" value="${kept(values.title)}">572<label class="issues-label" for="issue-body">what happened</label>573<textarea class="issues-textarea" id="issue-body" name="body" rows="10" required574maxlength="${MAX_CHARS}">${kept(values.body)}</textarea>575${markdownHint}576${attachField("issue-files")}577<label class="issues-label" for="issue-type">type</label>578<select class="issues-input" id="issue-type" name="type">${ISSUE_TYPES.map(typeOption)}</select>579<label class="issues-label" for="issue-version">version you're on</label>580<input class="issues-input" id="issue-version" name="version" maxlength="200" value="${kept(values.version)}">581<label class="issues-label" for="issue-name">name to show582<span class="muted">(optional)</span></label>583<input class="issues-input" id="issue-name" name="name" maxlength="${NAME_CHARS}"584autocomplete="nickname" value="${kept(values.name)}">585<label class="issues-label" for="issue-email">contact email586<span class="muted">(optional, only the operator sees it)</span></label>587<input class="issues-input" id="issue-email" name="email" type="email" maxlength="254"588autocomplete="email" value="${kept(values.email)}">589${590	mail &&591	html`<label class="issues-label issues-check">592<input type="checkbox" name="follow" value="1"${values.follow === "1" ? html` checked` : ""}>593email me each reply, and when it's closed</label>`594}595<p class="issues-actions"><button class="issues-submit" type="submit">file issue</button>596<a class="issues-cancel mono" href="/${name}/issues">cancel</a></p>597</form>`;598	return c.html(599		page(ctx, {600			title: `report an issue · ${name}`,601			description: `File an issue against ${name}.`,602			path: `/${name}/issues/new`,603			body,604		}),605		status,606	);607}608609const markdownHint = html`<p class="issue-hint mono">Markdown works: **bold**, \`code\`,610\`\`\` around logs, &gt; to quote.</p>`;611612function attachField(id: string): Html {613	return html`<label class="issues-label" for="${id}">screenshots or logs614<span class="muted">(optional, up to ${FILES_PER_POST})</span></label>615<input class="issues-file" id="${id}" name="files" type="file" multiple616accept="image/png,image/jpeg,image/gif,image/webp,.txt,.log">617<ul class="issue-attached mono" aria-live="polite"></ul>618<p class="issue-hint mono">PNG, JPEG, GIF or WebP up to 8 MB; .txt or .log up to 2 MB.619Pictures can be pasted or dropped into the text box too.</p>`;620}621622/** A post's pictures side by side, and each log as its start with the whole file a link away. */623export function attachmentsHtml(base: string, files: Attachment[]): Html {624	const url = (file: Attachment) => `${base}/files/${file.id}.${FILE_EXTENSIONS[file.type]}`;625	const images = files.filter((file) => file.type !== "text/plain");626	const logs = files.filter((file) => file.type === "text/plain");627	return html`${628		images.length > 0 &&629		html`<div class="issue-shots">${images.map(630			(file) => html`<a class="issue-shot" href="${url(file)}" target="_blank" rel="noopener">631<img src="${url(file)}" alt="${file.name}" loading="lazy"></a>`,632		)}</div>`633	}${logs.map(634		(file) => html`<details class="issue-log">635<summary class="issue-log-name mono">${file.name}636<span class="muted">${formatSize(file.size)}</span></summary>637<pre><code>${new TextDecoder().decode(file.head ?? new Uint8Array())}</code></pre>638<p class="issue-log-foot mono">639<a class="issue-log-whole" href="${url(file)}">open the whole log</a>${640			file.size > (file.head?.length ?? 0) &&641			` · showing its first ${formatSize(file.head?.length ?? 0)}`642		}</p>643</details>`,644	)}`;645}646647function threadPage(648	c: Context,649	ctx: PageContext,650	repo: PublicRepo,651	issue: Issue,652	entries: Entry[],653	view: View,654): string {655	const name = repo.settings.name;656	const base = `/${name}/issues/${issue.number}`;657	const open = issue.status === "open";658	const who = (entry: Entry) =>659		entry.author === "operator" ? "operator" : entry.name || "anonymous";660	const byId = new Map(entries.map((entry) => [entry.id, entry]));661	const answering = view.replyTo ? byId.get(view.replyTo) : undefined;662	const files = issueAttachments(ctx.kepr, issue.id);663	const stamp = formStamp(ctx.kepr, c, unixNow());664	// The issue itself is post 0: quoting it quotes what was filed.665	const post = (key: number, author: string, operator: boolean, at: number, body: string) => {666		const id = key === 0 ? "issue" : `entry-${key}`;667		const answers = byId.get(byId.get(key)?.reply_to ?? -1);668		const attached = files.filter((file) => (file.entry_id ?? 0) === key);669		return html`<article class="issue-post${operator ? " issue-post--operator" : ""}" id="${id}"670data-entry="${key === 0 ? "" : String(key)}" data-author="${author}">671<p class="issue-post-head mono">${672			operator673				? html`<span class="issue-badge">operator</span>`674				: html`<span class="issue-author">${author}</span>`675		}${676			answers &&677			html`<span class="issue-replying">replying to678<a href="#entry-${answers.id}">${who(answers)}</a></span>`679		}<a class="history-when" href="#${id}" title="${formatDate(at)}">${relativeTime(at)}</a></p>680<div class="markdown issue-text">${renderComment(body)}</div>681${attached.length > 0 && attachmentsHtml(base, attached)}682${683	open &&684	html`<p class="issue-post-actions mono">685<a href="${base}?reply=${key}#reply" data-action="reply">reply</a>686<a href="${base}?quote=${key}#reply" data-action="quote">quote</a></p>`687}688</article>`;689	};690	const reporter = issue.reporter_name || "anonymous";691	const error = view.error && html`<p class="issues-error mono" role="alert">${view.error}</p>`;692	const honeypot = html`<input type="hidden" name="stamp" value="${stamp}">693<label class="issues-hp" aria-hidden="true">leave this empty694<input name="website" tabindex="-1" autocomplete="off"></label>`;695	return page(ctx, {696		title: `#${issue.number} ${issue.title} · ${name}`,697		description: issue.title,698		path: base,699		body: html`${crumbs(name, !open)}700<h1 class="file-page-title">${issue.title} <span class="muted">#${issue.number}</span></h1>701<p class="issue-meta mono">702<span class="issue-symbol issue-symbol--${issue.status}">${open ? "◉ open" : "◈ closed"}</span>703${issue.type}${issue.version && ` · v${issue.version}`}704· filed by ${reporter} ${relativeTime(issue.filed_at)}705${entries.length > 0 && ` · ${entries.length} ${entries.length === 1 ? "reply" : "replies"}`}706${!open && fixedIn(repo, issue)}</p>707${view.notice && html`<p class="issue-notice mono" role="status">${view.notice}</p>`}708<div class="issue-thread">709${post(0, reporter, false, issue.filed_at, issue.body)}710${entries.map((entry) =>711	post(entry.id, who(entry), entry.author === "operator", entry.created_at, entry.body),712)}713</div>714${715	open716		? html`<form class="issue-composer" id="reply" method="post" action="${base}"717enctype="multipart/form-data">718${honeypot}719<input type="hidden" name="reply_to" value="${answering ? String(answering.id) : ""}">720<p class="issue-composer-head mono"><label for="reply-body">add a reply</label>721<span class="issue-composer-to"${answering ? "" : html` hidden`}>replying to722<a class="issue-composer-name"723href="#entry-${answering ? String(answering.id) : ""}">${answering ? who(answering) : ""}</a>724<a class="issues-cancel" href="${base}#reply"725aria-label="reply to the issue instead">×</a></span></p>726${view.refused === "reply" && error}727<textarea class="issues-textarea" id="reply-body" name="body" rows="7" required728maxlength="${MAX_CHARS}" placeholder="More detail, another angle, what you tried…"729>${kept(view.body)}</textarea>730${markdownHint}731${attachField("reply-files")}732<div class="issue-composer-who">733<label class="issues-label" for="reply-name">name to show734<span class="muted">(optional)</span></label>735<input class="issues-input" id="reply-name" name="name" maxlength="${NAME_CHARS}"736autocomplete="nickname" value="${kept(view.name)}">737${738	view.mail &&739	html`<label class="issues-label" for="reply-email">email me new replies740<span class="muted">(optional, never shown)</span></label>741<input class="issues-input" id="reply-email" name="email" type="email" maxlength="254"742autocomplete="email" value="${view.refused === "reply" ? kept(view.email) : ""}">`743}744</div>745<p class="issues-actions"><button class="issues-submit" type="submit">post reply</button></p>746</form>`747		: html`${view.refused === "reply" && error}748<p class="issue-closed-note mono">This issue is closed, so it takes no new replies.</p>`749}750${751	view.mail &&752	html`<form class="issue-follow" id="follow" method="post" action="${base}/follow">753${honeypot}754<label class="issues-label" for="follow-email">follow by email755<span class="muted">(each reply, and when it closes; your address is never shown)</span></label>756${view.refused === "follow" && error}757<p class="issue-follow-row"><input class="issues-input" id="follow-email" name="email" type="email"758required maxlength="254" autocomplete="email" placeholder="[email protected]"759value="${view.refused === "follow" ? (view.email ?? "") : ""}">760<button class="issues-submit" type="submit">follow</button></p>761</form>`762}`,763	});764}765766function fixedIn(repo: PublicRepo, issue: Issue): Html | "" {767	if (issue.fixed_in === "") return "";768	const save = saveByPrefix(repo.mirror, issue.fixed_in);769	// Only a save with a page of its own is linked; a checkpoint or an unknown ID stays text.770	const id =771		save && !save.is_checkpoint772			? html`<a class="history-id" href="/${repo.settings.name}/saves/${save.id}">${save.id}</a>`773			: html`<span class="history-id">${issue.fixed_in}</span>`;774	return html` · fixed in ${id}`;775}