1import type { Context, Hono } from "hono";2import { BucketWriteError } from "../bucket/reader.ts";3import { isSafePath } from "../bucket/repo.ts";4import { MAX_CHARS } from "../issues/spam.ts";5import { operatorIssues } from "../issues/store.ts";6import { languageLines, repoStats } from "../mirror/queries.ts";7import { openMirror, quarantinedPaths } from "../mirror/store.ts";8import { type Html, html } from "../pages/html.ts";9import { formatDate, plural } from "../pages/layout.ts";10import {11 deleteRelease,12 deleteReleaseFile,13 LastReleaseFile,14 type OperatorRelease,15 operatorReleases,16 setRelease,17 visibleReleases,18} from "../releases/releases.ts";19import { type RepoText, repoText, setRepoText } from "../server/db.ts";20import { type Removal, removal, startRemoval } from "../server/remove.ts";21import { dropTarballs } from "../tarball/cache.ts";22import { type AdminContext, adminPage, formField, notice, textFields } from "./console.ts";23import { renameErrors, renameProblem, renameRepo, renames } from "./rename.ts";24import { type AdminRepo, allRepos, findRepo, type RepoEdit, updateRepo } from "./store.ts";25import { LIMITS } from "./text.ts";2627const MAX_FIELD = 500;28const HTTP_URL = /^https?:\/\/[^\s]+$/i;29const MAX_LANGUAGES = 5;30const MAX_LANGUAGE = 30;31const MAX_HIDDEN = 100;323334function languageNames(value: string): string[] {35 return value36 .split(",")37 .map((name) => name.trim())38 .filter((name) => name !== "");39}404142export function registerRepos(app: Hono, ctx: AdminContext): void {43 app.get("/admin/repos", (c) => {44 return c.html(reposPage(c, ctx, "", c.req.query("repo")));45 });4647 app.post("/admin/sync", async (c) => {48 49 await ctx.syncer.syncSoon();50 return c.redirect("/admin/repos", 303);51 });5253 app.post("/admin/repos/:repo", async (c) => {54 const repo = findRepo(ctx.kepr, c.req.param("repo"));55 if (!repo) return c.notFound();56 const fields = await textFields(c);57 const text = (name: string) => (fields[name] ?? "").trim();58 const languages = languageNames(fields.languages ?? "");59 const hidden = (fields.hidden_paths ?? "")60 .split(/\r?\n/)61 .map((path) => path.trim().replace(/\/+$/, ""))62 .filter((path) => path !== "");63 const edit: RepoEdit = {64 public: fields.public === "1" ? 1 : 0,65 category: text("category"),66 homepage: text("homepage"),67 68 languages: languages.join(", "),69 issues_paused: fields.issues_paused === "1" ? 1 : 0,70 hidden_paths: hidden.join("\n"),71 };72 const refuse = (error: string) =>73 c.html(reposPage(c, ctx, `${repo.name}: ${error}`, repo.name), 400);74 const texts = (["description", "details"] as const).map((field): [RepoText, string] => [75 field,76 (fields[field] ?? "").replace(/\r\n/g, "\n").trim(),77 ]);78 const long = texts.find(([field, value]) => value.length > LIMITS[field]);79 if (long) {80 const [field] = long;81 return refuse(`Keep the ${field} under ${LIMITS[field].toLocaleString("en-US")} characters.`);82 }83 if ([edit.category, edit.homepage, fields.languages ?? ""].some((v) => v.length > MAX_FIELD)) {84 return refuse(`keep each field under ${MAX_FIELD} characters.`);85 }86 if (edit.homepage !== "" && !HTTP_URL.test(edit.homepage)) {87 return refuse("the homepage must be an http or https address.");88 }89 if (languages.length > MAX_LANGUAGES) return refuse("up to five languages.");90 if (languages.some((name) => name.length > MAX_LANGUAGE)) {91 return refuse(`a language name is at most ${MAX_LANGUAGE} characters.`);92 }93 if (languages.some((name) => /\p{C}/u.test(name))) {94 return refuse("a language name is printable text.");95 }96 if (hidden.length > MAX_HIDDEN) return refuse(`up to ${MAX_HIDDEN} hidden paths.`);97 const unsafe = hidden.find((path) => path.length > MAX_FIELD || !isSafePath(path));98 if (unsafe !== undefined) return refuse(`"${unsafe}" is not a path in the repo.`);99 updateRepo(ctx.kepr, repo.name, edit);100 for (const [field, value] of texts) setRepoText(ctx.kepr, repo.name, field, value);101 102 if (edit.hidden_paths !== repo.hidden_paths) await ctx.syncer.applyHidden([repo.name]);103 return c.redirect(`/admin/repos?repo=${repo.name}&saved=1`, 303);104 });105106 107 app.post("/admin/releases/:repo/:version", async (c) => {108 const found = findRelease(ctx, c.req.param("repo"), c.req.param("version"));109 if (!found) return c.notFound();110 const { repo, release } = found;111 const fields = await textFields(c);112 const notes = (fields.notes ?? "").replace(/\r\n/g, "\n");113 if (notes.length > MAX_CHARS) {114 const limit = MAX_CHARS.toLocaleString("en-US");115 const error = `${repo.name} ${release.version}: notes are over ${limit} characters.`;116 return c.html(reposPage(c, ctx, error, repo.name), 400);117 }118 119 const override = notes === release.recordNotes ? null : notes;120 setRelease(ctx.kepr, repo.name, release.version, fields.hidden === "1", override);121 return c.redirect(122 `/admin/repos?repo=${repo.name}&saved=1#release-${repo.name}-${release.version}`,123 303,124 );125 });126127 app.post("/admin/repos/:repo/delete", async (c) => {128 const repo = findRepo(ctx.kepr, c.req.param("repo"));129 if (!repo) return c.notFound();130 const fields = await textFields(c);131 const typed = (fields.name ?? "").trim();132 if (fields.delete !== "on" || typed !== repo.name) {133 return c.html(134 reposPage(c, ctx, `Tick the box and type ${repo.name} to delete it.`, repo.name),135 400,136 );137 }138 if (!startRemoval(ctx.sync, repo.name)) {139 return c.html(140 reposPage(c, ctx, "A repo is already being deleted. Let it finish first.", repo.name),141 400,142 );143 }144 return c.redirect(`/admin/repos?repo=${encodeURIComponent(repo.name)}`, 303);145 });146147 app.post("/admin/repos/:repo/rename", async (c) => {148 const repo = findRepo(ctx.kepr, c.req.param("repo"));149 if (!repo) return c.notFound();150 const to = ((await textFields(c)).name ?? "").trim();151 const problem = await renameProblem(ctx, repo.name, to);152 if (problem) {153 return c.html(reposPage(c, ctx, `${repo.name}: ${problem}`, repo.name), 400);154 }155 renameRepo(ctx, repo.name, to);156 return c.redirect(`/admin/repos?repo=${repo.name}#settings`, 303);157 });158159 app.post("/admin/repos/:repo/tarballs/delete", async (c) => {160 const repo = findRepo(ctx.kepr, c.req.param("repo"));161 if (!repo) return c.notFound();162 try {163 await dropTarballs(ctx.sync.bucket, repo.name);164 } catch (error) {165 if (!(error instanceof BucketWriteError)) throw error;166 const message = `${repo.name}: ${error.message}`;167 return c.html(reposPage(c, ctx, message, repo.name), 503);168 }169 return c.redirect(`/admin/repos?repo=${repo.name}&saved=1#archives`, 303);170 });171172 app.post("/admin/releases/:repo/:version/delete", async (c) => {173 const found = findRelease(ctx, c.req.param("repo"), c.req.param("version"));174 if (!found) return c.notFound();175 const { repo, mirror, release } = found;176 const refuse = (status: 400 | 503, error: string) =>177 c.html(reposPage(c, ctx, `${repo.name} ${release.version}: ${error}`, repo.name), status);178 if ((await textFields(c)).confirm !== "1") return refuse(400, "tick the box to delete it.");179 try {180 await deleteRelease(ctx.sync.bucket, ctx.kepr, mirror, repo.name, release.version);181 } catch (error) {182 if (error instanceof BucketWriteError) return refuse(503, error.message);183 throw error;184 }185 return c.redirect(`/admin/repos?repo=${repo.name}&saved=1#builds`, 303);186 });187188 app.post("/admin/releases/:repo/:version/:platform/delete", async (c) => {189 const found = findRelease(ctx, c.req.param("repo"), c.req.param("version"));190 const platform = c.req.param("platform");191 if (!found?.release.downloads.some(([p]) => p === platform)) return c.notFound();192 const { repo, mirror, release } = found;193 const refuse = (status: 400 | 503, error: string) =>194 c.html(195 reposPage(c, ctx, `${repo.name} ${release.version} ${platform}: ${error}`, repo.name),196 status,197 );198 if ((await textFields(c)).confirm !== "1") return refuse(400, "tick the box to delete it.");199 try {200 await deleteReleaseFile(201 ctx.sync.bucket,202 ctx.kepr,203 mirror,204 repo.name,205 release.version,206 platform,207 );208 } catch (error) {209 if (error instanceof LastReleaseFile) return refuse(400, error.message);210 if (error instanceof BucketWriteError) return refuse(503, error.message);211 throw error;212 }213 return c.redirect(214 `/admin/repos?repo=${repo.name}&saved=1#release-${repo.name}-${release.version}`,215 303,216 );217 });218}219220221function findRelease(ctx: AdminContext, name: string, version: string) {222 const repo = findRepo(ctx.kepr, name);223 const mirror = repo && openMirror(ctx.mirrorDir, repo.name);224 const release =225 repo &&226 mirror &&227 operatorReleases(ctx.kepr, mirror, repo.name).find((r) => r.version === version);228 return repo && mirror && release ? { repo, mirror, release } : null;229}230231function reposPage(c: Context, ctx: AdminContext, error: string, chosen: string | undefined) {232 const repos = allRepos(ctx.kepr);233 const selected = repos.find((repo) => repo.name === chosen) ?? repos[0];234 235 const repoLink = (repo: AdminRepo) => {236 const current = repo.name === selected?.name;237 return html`<a class="admin-repo-link${current ? " active" : ""}" href="/admin/repos?repo=${repo.name}"${238 current ? html` aria-current="page"` : ""239 }>${repo.name}${repo.public ? "" : html` <span class="muted">private</span>`}${240 repo.last_sync_error ? html` <span class="issues-error">sync failed</span>` : ""241 }</a>`;242 };243 const body = html`${notice(error)}244<div class="admin-repos-layout">245<aside class="admin-repo-picker mono">246<nav aria-label="repositories">${repos.map(repoLink)}</nav>247<a href="/admin/site#global-hide">global hide ↗</a>248<form method="post" action="/admin/sync">249${formField(c)}<button class="issues-submit" type="submit">sync now</button></form>250</aside>251<div class="admin-repo-workspace">252${repos.length === 0 && html`<p class="muted mono save-empty">no repos found in the bucket yet</p>`}253${selected && repoWorkspace(c, ctx, selected)}254</div></div>`;255 return adminPage(c, ctx, "repos", body);256}257258259function workspace(ctx: AdminContext, repo: AdminRepo) {260 const mirror = openMirror(ctx.mirrorDir, repo.name);261 const stats = repoStats(mirror);262 const releases = operatorReleases(ctx.kepr, mirror, repo.name);263 const downloads = (release: (typeof releases)[number]) =>264 release.downloads.reduce((sum, [, count]) => sum + count, 0);265 const open = operatorIssues(ctx.kepr, "open").filter((issue) => issue.repo === repo.name);266 const vital = (label: string, value: string | number) =>267 html`<div><strong>${String(value)}</strong><span class="mono">${label}</span></div>`;268 return html`<div class="admin-vitals">269${vital("saves", stats.saves)}270${vital("lines", stats.lines)}271${vital("newest version", visibleReleases(ctx.kepr, mirror, repo.name)[0]?.version ?? "none")}272${vital("open issues", open.length)}273${vital(274 "downloads",275 releases.reduce((sum, release) => sum + downloads(release), 0),276)}277</div>278<p class="issue-meta mono">detected languages:279${languageLines(mirror).map(280 ([language, lines], i) =>281 html`${i > 0 ? " · " : " "}${language} <span class="muted">${plural(lines, "line")}</span>`,282)}</p>283`;284}285286function repoWorkspace(c: Context, ctx: AdminContext, repo: AdminRepo) {287 const synced =288 repo.last_sync_at === null ? "never synced" : `last sync ${formatDate(repo.last_sync_at)} UTC`;289 const section = (id: string, body: Html | Html[]) =>290 html`<section class="repo-section" id="${id}"><h2 class="section-label mono">${id}</h2>291${body}</section>`;292 return html`<article class="issue-post" id="repo-editor">293<p class="issue-post-head mono">294<span class="issue-author">295${repo.public ? html`<a href="/${repo.name}">${repo.name}</a>` : repo.name}</span>296<span>${repo.public ? "public" : "private"}</span><span class="history-when">${synced}</span></p>297${section("overview", overviewSection(ctx, repo))}298${section("settings", settingsSection(c, ctx, repo))}299${section("builds", buildsSection(c, ctx, repo))}300${section("archives", archivesSection(c, repo))}301${section("delete", deleteSection(c, ctx, repo))}302</article>`;303}304305306307308309function deleteSection(c: Context, ctx: AdminContext, repo: AdminRepo) {310 const under = removal(ctx.kepr);311 const state =312 under && under.repo === repo.name313 ? html`<p class="issues-error mono" role="status">${deleteProgress(under)}</p>`314 : "";315 return html`${state}316<form class="issues-form" method="post" action="/admin/repos/${repo.name}/delete">317${formField(c)}318<p>This deletes every key of <span class="mono">${repo.name}</span> in the bucket: its history,319releases, issues and counts. Then it drops Kepr's own copy of it. No other repo is touched, and320nothing here can undo it.</p>321<label class="issues-label">322<input type="checkbox" name="delete" value="on" required> delete ${repo.name} from the bucket</label>323<label class="issues-label" for="${repo.name}-delete-name">type ${repo.name} to confirm</label>324<input class="issues-input mono" id="${repo.name}-delete-name" name="name" autocomplete="off" required>325<button class="issues-submit" type="submit">delete ${repo.name}</button>326</form>`;327}328329function deleteProgress(under: Removal): string {330 const gone = `${String(under.done)} of ${String(under.total)} keys`;331 if (under.error !== "") {332 return `deleting ${under.repo} stopped after ${gone}: ${under.error}. Delete it again to finish the rest.`;333 }334 return `deleting ${under.repo}: ${gone} gone. Reload to follow it.`;335}336337function overviewSection(ctx: AdminContext, repo: AdminRepo) {338 const quarantined = quarantinedPaths(openMirror(ctx.mirrorDir, repo.name));339 return html`${workspace(ctx, repo)}340${341 repo.last_sync_error && html`<p class="issues-error mono">sync error: ${repo.last_sync_error}</p>`342}343${344 quarantined.length > 0 &&345 html`<p class="issues-error mono">${plural(quarantined.length, "path")} quarantined: ${quarantined.join(", ")}</p>`346}`;347}348349function settingsSection(c: Context, ctx: AdminContext, repo: AdminRepo) {350 const own = repoText(ctx.kepr, repo.name);351 const input = (name: keyof RepoEdit, label: string) =>352 html`<label class="issues-label" for="${repo.name}-${name}">${label}</label>353<input class="issues-input" id="${repo.name}-${name}" name="${name}" maxlength="${MAX_FIELD}" value="${String(repo[name])}">`;354 return html`<form class="issues-form" method="post" action="/admin/repos/${repo.name}">355${formField(c)}356<label class="issues-label">357<input type="checkbox" name="public" value="1"${repo.public ? html` checked` : ""}> public</label>358<label class="issues-label">359<input type="checkbox" name="issues_paused" value="1"${repo.issues_paused ? html` checked` : ""}>360pause new issues</label>361${input("category", "category")}362${input("homepage", "homepage")}363${input("languages", "shown languages")}364<p class="issue-meta mono">Up to five, separated by commas. Leave blank to show the detected one.</p>365${textArea(repo.name, "description", "description", 3, own.description)}366${textArea(repo.name, "details", "details", 12, own.details)}367<p class="issue-meta mono">Markdown. Leave either blank to use the README's.</p>368<label class="issues-label" for="${repo.name}-hidden_paths">hidden files and folders</label>369<textarea class="issues-textarea mono" id="${repo.name}-hidden_paths" name="hidden_paths"370rows="4">${repo.hidden_paths}</textarea>371<p class="issue-meta mono">One path per line, such as notes.md or docs/private. Hidden from every page,372the stats and tarballs, and passed to Koh for .kohignore.373For every repo, use <a href="/admin/site#global-hide">global hide</a>.</p>374<button class="issues-submit" type="submit">save ${repo.name}</button>375</form>376${renameForm(c, repo.name)}`;377}378379380function renameForm(c: Context, name: string) {381 const to = renames.get(name);382 if (to)383 return html`<p class="admin-intro">Renaming ${name} to ${to}. This page shows ${to} once it is done.</p>`;384 return html`${notice(renameErrors.get(name) ? `rename failed: ${renameErrors.get(name)}` : "")}385<form class="issues-form" method="post" action="/admin/repos/${name}/rename">386${formField(c)}387<label class="issues-label" for="${name}-rename">rename</label>388<input class="issues-input mono" id="${name}-rename" name="name" maxlength="100" required>389<p class="issue-meta mono">Moves its history to the new name in the bucket, with its settings, issues and390counts, and sends old links there. Your machines follow it on their next save or steal.</p>391<button class="issues-submit" type="submit">rename ${name}</button>392</form>`;393}394395function buildsSection(c: Context, ctx: AdminContext, repo: AdminRepo) {396 const releases = operatorReleases(ctx.kepr, openMirror(ctx.mirrorDir, repo.name), repo.name);397 return releases.length > 0398 ? releases.map((release) => releaseForm(c, repo.name, release))399 : html`<p class="muted mono save-empty">no builds yet</p>`;400}401402function archivesSection(c: Context, repo: AdminRepo) {403 return html`<form class="issues-form" method="post" action="/admin/repos/${repo.name}/tarballs/delete">404${formField(c)}405<p class="issue-meta mono">Tarballs are kept in the bucket once downloaded, and rebuilt on the next download.406Each one is listed under <a href="/admin/storage">storage</a>.</p>407<button class="issues-submit" type="submit">delete kept tarballs</button>408</form>`;409}410411function textArea(repo: string, name: RepoText, label: string, rows: number, value: string) {412 return html`<label class="issues-label" for="${repo}-${name}">${label}</label>413<textarea class="issues-textarea" id="${repo}-${name}" name="${name}" rows="${String(rows)}"414maxlength="${String(LIMITS[name])}">${value}</textarea>`;415}416417function releaseForm(c: Context, repo: string, release: OperatorRelease) {418 const total = release.downloads.reduce((sum, [, n]) => sum + n, 0);419 420 const id = `release-${repo}-${release.version}`;421 return html`<article class="issue-post" id="${id}">422<p class="issue-post-head mono">423${ ""}${html`<span class="repo-version">${release.version}</span>`}${html`<span>${release.hidden ? "hidden" : "shown"}</span>`}${html`<span>${plural(total, "download")}</span>`}${release.downloads.map(424 ([platform, n]) => html`<span class="muted">${platform} ${n}</span>`,425)}426</p>427<form class="issues-form" method="post" action="/admin/releases/${repo}/${release.version}">428${formField(c)}429<label class="issues-label" for="notes-${repo}-${release.version}">notes430${release.notes !== release.recordNotes ? html` <span class="muted">(edited)</span>` : ""}</label>431<textarea class="issues-textarea" id="notes-${repo}-${release.version}" name="notes" rows="3"432maxlength="${MAX_CHARS}">${release.notes}</textarea>433${434 435 436 ""437}<label class="issues-label">${html`<input type="checkbox"`}${html` name="hidden" value="1"`}${release.hidden ? html` checked` : ""}> hidden</label>438<button class="issues-submit" type="submit">save ${release.version}</button>439</form>440${441 release.downloads.length > 1 &&442 release.downloads.map(443 ([platform]) => html`<form class="issues-form" method="post"444action="/admin/releases/${repo}/${release.version}/${platform}/delete">445${formField(c)}446<label class="issues-label"><input type="checkbox" name="confirm" value="1" required>447delete the ${platform} file from the bucket</label>448<button class="issues-submit" type="submit">delete ${platform}</button>449</form>`,450 )451}452<form class="issues-form" method="post" action="/admin/releases/${repo}/${release.version}/delete">453${formField(c)}454<label class="issues-label"><input type="checkbox" name="confirm" value="1" required>455delete ${release.version} and its files from the bucket; this cannot be undone</label>456<button class="issues-submit" type="submit">delete ${release.version}</button>457</form>458</article>`;459}