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 notFound,8 openPublicRepo,9 type PageContext,10 type PublicRepo,11 page,12 relativeTime,13} from "../pages/layout.ts";14import { visibleReleases } from "../releases/releases.ts";15import { checkStamp, FILINGS_PER_HOUR, formStamp, ipHash, MAX_CHARS } from "./spam.ts";16import {17 addEntry,18 fileIssue,19 filingsSince,20 findIssue,21 hashToken,22 ISSUE_TYPES,23 type Issue,24 type IssueType,25 issueCounts,26 listIssues,27 threadEntries,28} from "./store.ts";2930type Fields = Record<string, string>;31type Notice = { error?: string; draft?: string };3233const TOKEN = /^[0-9a-f]{64}$/;34const FORM_FIELDS = ["title", "body", "type", "version", "name", "email", "website", "stamp"];35const unixNow = () => Math.floor(Date.now() / 1000);363738export function registerIssuePages(app: Hono, ctx: PageContext): void {39 app.get("/:repo/issues", (c) => {40 const repo = openPublicRepo(ctx, c.req.param("repo"));41 if (!repo) return notFound(c, ctx);42 const status = c.req.query("status") === "closed" ? "closed" : "open";43 cacheFor(c, false);44 return c.html(listPage(ctx, repo, status, c.req.query("q") ?? "", c.req.query("type") ?? ""));45 });4647 app.get("/:repo/issues/new", (c) => {48 const repo = openPublicRepo(ctx, c.req.param("repo"));49 if (!repo) return notFound(c, ctx);50 const version = visibleReleases(ctx.kepr, repo.mirror, repo.settings.name)[0]?.version ?? "";51 return formPage(c, ctx, repo, { type: "bug", version }, "", 200);52 });5354 app.post("/:repo/issues/new", async (c) => {55 const repo = openPublicRepo(ctx, c.req.param("repo"));56 if (!repo) return notFound(c, ctx);57 if (repo.settings.issuesPaused) return formPage(c, ctx, repo, {}, "", 403);58 const fields = await readFields(c, FORM_FIELDS);59 const now = unixNow();60 const refuse = (message: string, status: 400 | 403 | 429) =>61 formPage(c, ctx, repo, fields, message, status);62 63 if (fields.website !== "") return refuse("This issue could not be filed.", 400);64 const stamp = checkStamp(ctx.kepr, c, fields.stamp ?? "", now);65 if (stamp === "invalid") return refuse("This form expired. Please send it again.", 403);66 if (stamp === "too-fast") return refuse("That was quick. Please send it again.", 400);67 const title = fields.title?.trim() ?? "";68 const body = fields.body?.trim() ?? "";69 if (title === "" || body === "") return refuse("A title and what happened are needed.", 400);70 if (!ISSUE_TYPES.includes(fields.type as IssueType)) return refuse("Pick a type.", 400);71 if (Object.values(fields).some((value) => value.length > MAX_CHARS)) {72 return refuse(73 `Please keep each field under ${MAX_CHARS.toLocaleString("en-US")} characters.`,74 400,75 );76 }77 const hash = ipHash(ctx.kepr, c);78 if (filingsSince(ctx.kepr, hash, now - 3600) >= FILINGS_PER_HOUR) {79 return refuse("Too many issues from here this hour. Please try again later.", 429);80 }81 const name = repo.settings.name;82 const filed = fileIssue(ctx.kepr, {83 repo: name,84 title,85 body,86 type: fields.type as IssueType,87 version: fields.version?.trim() ?? "",88 reporterName: fields.name?.trim() ?? "",89 contactEmail: fields.email?.trim() ?? "",90 ipHash: hash,91 filedAt: now,92 });93 const link = `https://${ctx.domain}/${name}/issues/${filed.number}?token=${filed.token}`;94 privatePage(c);95 return c.html(96 page(ctx, {97 title: `issue #${filed.number} filed · ${name}`,98 description: "",99 path: c.req.path,100 body: html`${crumbs(name)}101<h1 class="file-page-title">Filed as102<a href="/${name}/issues/${filed.number}">#${filed.number}</a></h1>103<p>This is your private link for adding to the issue later. It is shown only this once,104so keep it; anyone who has it can post as you.</p>105<p class="issue-link mono"><a href="${link}">${link}</a></p>`,106 }),107 );108 });109110 app.get("/:repo/issues/:n{[0-9]{1,9}}", (c) => {111 const repo = openPublicRepo(ctx, c.req.param("repo"));112 const issue = repo && findIssue(ctx.kepr, repo.settings.name, Number(c.req.param("n")));113 if (!repo || !issue) return notFound(c, ctx);114 const token = c.req.query("token");115 if (token === undefined) {116 cacheFor(c, false);117 return c.html(threadPage(c, ctx, repo, issue, null, {}));118 }119 privatePage(c);120 return c.html(threadPage(c, ctx, repo, issue, token, {}));121 });122123 app.post("/:repo/issues/:n{[0-9]{1,9}}", async (c) => {124 const repo = openPublicRepo(ctx, c.req.param("repo"));125 const issue = repo && findIssue(ctx.kepr, repo.settings.name, Number(c.req.param("n")));126 if (!repo || !issue) return notFound(c, ctx);127 const { token = "", body = "", stamp = "" } = await readFields(c, ["token", "body", "stamp"]);128 privatePage(c);129 const refuse = (error: string, status: 400 | 403) =>130 c.html(threadPage(c, ctx, repo, issue, token, { error, draft: body }), status);131 if (!ownsIssue(issue, token))132 return refuse("This follow-up link does not match the issue.", 403);133 const check = checkStamp(ctx.kepr, c, stamp, unixNow());134 if (check === "invalid") return refuse("This form expired. Please send it again.", 403);135 if (check === "too-fast") return refuse("That was quick. Please send it again.", 400);136 const text = body.trim();137 if (text === "") return refuse("Write something to add.", 400);138 if (text.length > MAX_CHARS) {139 return refuse(`Please keep it under ${MAX_CHARS.toLocaleString("en-US")} characters.`, 400);140 }141 const entry = addEntry(ctx.kepr, issue.id, "reporter", text, unixNow());142 return c.redirect(143 `/${repo.settings.name}/issues/${issue.number}?token=${token}#entry-${entry}`,144 303,145 );146 });147}148149async function readFields(c: Context, names: string[]): Promise<Fields> {150 const form = await c.req.parseBody();151 const fields: Fields = {};152 for (const name of names) {153 const value = form[name];154 fields[name] = typeof value === "string" ? value : "";155 }156 return fields;157}158159function ownsIssue(issue: Issue, token: string): boolean {160 return TOKEN.test(token) && issue.token_hash === hashToken(token);161}162163164function privatePage(c: Context): void {165 c.header("Cache-Control", "no-store");166 c.header("Referrer-Policy", "no-referrer");167}168169function crumbs(repo: string): Html {170 return html`<p class="breadcrumb mono">171<a href="/${repo}">${repo}</a> / <a href="/${repo}/issues">issues</a></p>`;172}173174function listPage(175 ctx: PageContext,176 repo: PublicRepo,177 status: "open" | "closed",178 query: string,179 type: string,180): string {181 const name = repo.settings.name;182 const counts = issueCounts(ctx.kepr, name);183 const filter = ISSUE_TYPES.includes(type as IssueType) ? type : "";184 const issues = listIssues(ctx.kepr, name, status).filter(185 (issue) =>186 (!filter || issue.type === filter) &&187 issue.title.toLowerCase().includes(query.trim().toLowerCase()),188 );189 const tab = (which: "open" | "closed") =>190 html`<a class="issues-tab${which === status ? " active" : ""}"191 href="/${name}/issues${which === "closed" ? "?status=closed" : ""}">192${which} <span class="muted">${counts[which]}</span></a>`;193 return page(ctx, {194 title: `issues · ${name}`,195 description: `Issues filed against ${name}.`,196 path: `/${name}/issues`,197 body: html`<p class="breadcrumb mono"><a href="/${name}">${name}</a></p>198<h1 class="file-page-title">issues</h1>199<p class="issues-bar mono">${tab("open")}${tab("closed")}200${!repo.settings.issuesPaused && html`<a class="issues-new" href="/${name}/issues/new">report an issue →</a>`}</p>201<form class="issues-filter" method="get" action="/${name}/issues">202<input type="hidden" name="status" value="${status}">203<input class="issues-input" name="q" type="search" aria-label="search issue titles"204placeholder="search issues" value="${query}">205<select class="issues-input" name="type" aria-label="issue type">206<option value="">all types</option>207${ISSUE_TYPES.map(208 (value) =>209 html`<option value="${value}"${filter === value ? html` selected` : ""}>${value}</option>`,210)}211</select><button class="issues-submit" type="submit">filter</button></form>212<section class="repo-section">213${214 issues.length > 0215 ? issues.map(216 (issue) =>217 html`<a class="issue-row" href="/${name}/issues/${issue.number}">218<span class="issue-symbol issue-symbol--${issue.status}">219${issue.status === "open" ? "◉" : "◈"}</span>220<span class="issue-title">${issue.title}</span>221${ ""}<span class="issue-meta mono">#${issue.number} · ${issue.type}${issue.version && ` · v${issue.version}`} · ${relativeTime(issue.filed_at)}</span>222<span class="issue-reporter mono">${issue.reporter_name || "anonymous"}</span>223</a>`,224 )225 : html`<p class="muted mono save-empty">${query || filter ? "no matching issues" : `no ${status} issues`}</p>`226}227</section>`,228 });229}230231function formPage(232 c: Context,233 ctx: PageContext,234 repo: PublicRepo,235 values: Fields,236 error: string,237 status: 200 | 400 | 403 | 429,238): Response {239 const name = repo.settings.name;240 privatePage(c);241 const typeOption = (type: string) =>242 html`<option value="${type}"${values.type === type ? html` selected` : ""}>${type}</option>`;243 const body = repo.settings.issuesPaused244 ? html`${crumbs(name)}245<h1 class="file-page-title">report an issue</h1>246<p>${name} is not taking new issues right now.</p>247<p><a href="/${name}/issues">see the existing issues →</a></p>`248 : html`${crumbs(name)}249<h1 class="file-page-title">report an issue</h1>250${error && html`<p class="issues-error mono" role="alert">${error}</p>`}251<form class="issues-form" method="post" action="/${name}/issues/new">252<input type="hidden" name="stamp" value="${formStamp(ctx.kepr, c, unixNow())}">253<label class="issues-hp" aria-hidden="true">leave this empty254<input name="website" tabindex="-1" autocomplete="off"></label>255<label class="issues-label" for="issue-title">title</label>256<input class="issues-input" id="issue-title" name="title" required maxlength="${MAX_CHARS}" value="${values.title ?? ""}">257<label class="issues-label" for="issue-body">what happened</label>258<textarea class="issues-textarea" id="issue-body" name="body" rows="8" required259maxlength="${MAX_CHARS}">${values.body ?? ""}</textarea>260<label class="issues-label" for="issue-type">type</label>261<select class="issues-input" id="issue-type" name="type">${ISSUE_TYPES.map(typeOption)}</select>262<label class="issues-label" for="issue-version">version you're on</label>263<input class="issues-input" id="issue-version" name="version" maxlength="200" value="${values.version ?? ""}">264<label class="issues-label" for="issue-name">name to show265<span class="muted">(optional)</span></label>266<input class="issues-input" id="issue-name" name="name" maxlength="200" value="${values.name ?? ""}">267<label class="issues-label" for="issue-email">contact email268<span class="muted">(optional, only the operator sees it)</span></label>269<input class="issues-input" id="issue-email" name="email" type="email" maxlength="320" value="${values.email ?? ""}">270<p class="issues-actions"><button class="issues-submit" type="submit">file issue</button>271<a class="issues-cancel mono" href="/${name}/issues">cancel</a></p>272</form>`;273 return c.html(274 page(ctx, {275 title: `report an issue · ${name}`,276 description: `File an issue against ${name}.`,277 path: `/${name}/issues/new`,278 body,279 }),280 status,281 );282}283284function threadPage(285 c: Context,286 ctx: PageContext,287 repo: PublicRepo,288 issue: Issue,289 token: string | null,290 notice: Notice,291): string {292 const name = repo.settings.name;293 const reporter = issue.reporter_name || "anonymous";294 const post = (id: string, operator: boolean, at: number, text: string) =>295 html`<article class="issue-post${operator ? " issue-post--operator" : ""}" id="${id}">296<p class="issue-post-head mono">${297 operator298 ? html`<span class="issue-badge">operator</span>`299 : html`<span class="issue-author">${reporter}</span>`300 }<span class="history-when">${formatDate(at)}</span></p>301<div class="issue-text">${text}</div>302</article>`;303 const owner = token !== null && ownsIssue(issue, token);304 return page(ctx, {305 title: `#${issue.number} ${issue.title} · ${name}`,306 description: issue.title,307 path: `/${name}/issues/${issue.number}`,308 body: html`${crumbs(name)}309<h1 class="file-page-title">${issue.title} <span class="muted">#${issue.number}</span></h1>310<p class="issue-meta mono">311<span class="issue-symbol issue-symbol--${issue.status}">312${issue.status === "open" ? "◉ open" : "◈ closed"}</span>313${issue.type}${issue.version && ` · v${issue.version}`} · filed ${relativeTime(issue.filed_at)}314${issue.status === "closed" && fixedIn(repo, issue)}</p>315${post("issue", false, issue.filed_at, issue.body)}316${threadEntries(ctx.kepr, issue.id).map((entry) =>317 post(`entry-${entry.id}`, entry.author === "operator", entry.created_at, entry.body),318)}319${notice.error && html`<p class="issues-error mono" role="alert">${notice.error}</p>`}320${321 token !== null &&322 !owner &&323 !notice.error &&324 html`<p class="issues-error mono">This follow-up link does not match the issue.</p>`325}326${327 owner &&328 html`<form class="issues-form" method="post" action="/${name}/issues/${issue.number}">329<p class="muted">This is your private follow-up link; anyone who has it can post as you.</p>330<input type="hidden" name="token" value="${token}">331<input type="hidden" name="stamp" value="${formStamp(ctx.kepr, c, unixNow())}">332<label class="issues-label" for="follow-up">add to this issue</label>333<textarea class="issues-textarea" id="follow-up" name="body" rows="5" required334maxlength="${MAX_CHARS}">${notice.draft ?? ""}</textarea>335<button class="issues-submit" type="submit">post</button>336</form>`337}`,338 });339}340341function fixedIn(repo: PublicRepo, issue: Issue): Html | "" {342 if (issue.fixed_in === "") return "";343 const save = saveByPrefix(repo.mirror, issue.fixed_in);344 345 const id =346 save && !save.is_checkpoint347 ? html`<a class="history-id" href="/${repo.settings.name}/saves/${save.id}">${save.id}</a>`348 : html`<span class="history-id">${issue.fixed_in}</span>`;349 return html` · fixed in ${id}`;350}