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 { 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 { dropTarballs } from "../tarball/cache.ts";21import { type AdminContext, adminPage, formField, notice, textFields } from "./console.ts";22import { renameErrors, renameProblem, renameRepo, renames } from "./rename.ts";23import { type AdminRepo, allRepos, findRepo, type RepoEdit, updateRepo } from "./store.ts";24import { LIMITS } from "./text.ts";2526const MAX_FIELD = 500;27const HTTP_URL = /^https?:\/\/[^\s]+$/i;28const MAX_LANGUAGES = 5;29const MAX_LANGUAGE = 30;30const MAX_HIDDEN = 100;31const TABS = ["overview", "settings", "builds", "archives"] as const;32type Tab = (typeof TABS)[number];333435function languageNames(value: string): string[] {36 return value37 .split(",")38 .map((name) => name.trim())39 .filter((name) => name !== "");40}414243export function registerRepos(app: Hono, ctx: AdminContext): void {44 app.get("/admin/repos", (c) => {45 const tab = TABS.find((t) => t === c.req.query("tab")) ?? "overview";46 return c.html(reposPage(c, ctx, "", c.req.query("repo"), tab));47 });4849 app.post("/admin/sync", async (c) => {50 await ctx.syncer.syncAll();51 return c.redirect("/admin/repos", 303);52 });5354 app.post("/admin/repos/:repo", async (c) => {55 const repo = findRepo(ctx.kepr, c.req.param("repo"));56 if (!repo) return c.notFound();57 const fields = await textFields(c);58 const text = (name: string) => (fields[name] ?? "").trim();59 const languages = languageNames(fields.languages ?? "");60 const hidden = (fields.hidden_paths ?? "")61 .split(/\r?\n/)62 .map((path) => path.trim().replace(/\/+$/, ""))63 .filter((path) => path !== "");64 const edit: RepoEdit = {65 public: fields.public === "1" ? 1 : 0,66 category: text("category"),67 homepage: text("homepage"),68 69 languages: languages.join(", "),70 issues_paused: fields.issues_paused === "1" ? 1 : 0,71 hidden_paths: hidden.join("\n"),72 };73 const refuse = (error: string) =>74 c.html(reposPage(c, ctx, `${repo.name}: ${error}`, repo.name, "settings"), 400);75 const texts = (["description", "details"] as const).map((field): [RepoText, string] => [76 field,77 (fields[field] ?? "").replace(/\r\n/g, "\n").trim(),78 ]);79 const long = texts.find(([field, value]) => value.length > LIMITS[field]);80 if (long) {81 const [field] = long;82 return refuse(`Keep the ${field} under ${LIMITS[field].toLocaleString("en-US")} characters.`);83 }84 if ([edit.category, edit.homepage, fields.languages ?? ""].some((v) => v.length > MAX_FIELD)) {85 return refuse(`keep each field under ${MAX_FIELD} characters.`);86 }87 if (edit.homepage !== "" && !HTTP_URL.test(edit.homepage)) {88 return refuse("the homepage must be an http or https address.");89 }90 if (languages.length > MAX_LANGUAGES) return refuse("up to five languages.");91 if (languages.some((name) => name.length > MAX_LANGUAGE)) {92 return refuse(`a language name is at most ${MAX_LANGUAGE} characters.`);93 }94 if (languages.some((name) => /\p{C}/u.test(name))) {95 return refuse("a language name is printable text.");96 }97 if (hidden.length > MAX_HIDDEN) return refuse(`up to ${MAX_HIDDEN} hidden paths.`);98 const unsafe = hidden.find((path) => path.length > MAX_FIELD || !isSafePath(path));99 if (unsafe !== undefined) return refuse(`"${unsafe}" is not a path in the repo.`);100 updateRepo(ctx.kepr, repo.name, edit);101 for (const [field, value] of texts) setRepoText(ctx.kepr, repo.name, field, value);102 103 if (edit.hidden_paths !== repo.hidden_paths) await ctx.syncer.applyHidden([repo.name]);104 return c.redirect(`/admin/repos?repo=${repo.name}&tab=settings&saved=1`, 303);105 });106107 108 app.post("/admin/releases/:repo/:version", async (c) => {109 const found = findRelease(ctx, c.req.param("repo"), c.req.param("version"));110 if (!found) return c.notFound();111 const { repo, release } = found;112 const fields = await textFields(c);113 const notes = (fields.notes ?? "").replace(/\r\n/g, "\n");114 if (notes.length > MAX_CHARS) {115 const limit = MAX_CHARS.toLocaleString("en-US");116 const error = `${repo.name} ${release.version}: notes are over ${limit} characters.`;117 return c.html(reposPage(c, ctx, error, repo.name, "builds"), 400);118 }119 120 const override = notes === release.recordNotes ? null : notes;121 setRelease(ctx.kepr, repo.name, release.version, fields.hidden === "1", override);122 return c.redirect(123 `/admin/repos?repo=${repo.name}&tab=builds&saved=1#${repo.name}-${release.version}`,124 303,125 );126 });127128 app.post("/admin/repos/:repo/rename", async (c) => {129 const repo = findRepo(ctx.kepr, c.req.param("repo"));130 if (!repo) return c.notFound();131 const to = ((await textFields(c)).name ?? "").trim();132 const problem = await renameProblem(ctx, repo.name, to);133 if (problem) {134 return c.html(reposPage(c, ctx, `${repo.name}: ${problem}`, repo.name, "settings"), 400);135 }136 renameRepo(ctx, repo.name, to);137 return c.redirect(`/admin/repos?repo=${repo.name}&tab=settings`, 303);138 });139140 app.post("/admin/repos/:repo/tarballs/delete", async (c) => {141 const repo = findRepo(ctx.kepr, c.req.param("repo"));142 if (!repo) return c.notFound();143 try {144 await dropTarballs(ctx.sync.bucket, repo.name);145 } catch (error) {146 if (!(error instanceof BucketWriteError)) throw error;147 const message = `${repo.name}: ${error.message}`;148 return c.html(reposPage(c, ctx, message, repo.name, "archives"), 503);149 }150 return c.redirect(`/admin/repos?repo=${repo.name}&tab=archives&saved=1`, 303);151 });152153 app.post("/admin/releases/:repo/:version/delete", async (c) => {154 const found = findRelease(ctx, c.req.param("repo"), c.req.param("version"));155 if (!found) return c.notFound();156 const { repo, mirror, release } = found;157 const refuse = (status: 400 | 503, error: string) =>158 c.html(159 reposPage(c, ctx, `${repo.name} ${release.version}: ${error}`, repo.name, "builds"),160 status,161 );162 if ((await textFields(c)).confirm !== "1") return refuse(400, "tick the box to delete it.");163 try {164 await deleteRelease(ctx.sync.bucket, ctx.kepr, mirror, repo.name, release.version);165 } catch (error) {166 if (error instanceof BucketWriteError) return refuse(503, error.message);167 throw error;168 }169 return c.redirect(`/admin/repos?repo=${repo.name}&tab=builds&saved=1`, 303);170 });171172 app.post("/admin/releases/:repo/:version/:platform/delete", async (c) => {173 const found = findRelease(ctx, c.req.param("repo"), c.req.param("version"));174 const platform = c.req.param("platform");175 if (!found?.release.downloads.some(([p]) => p === platform)) return c.notFound();176 const { repo, mirror, release } = found;177 const refuse = (status: 400 | 503, error: string) =>178 c.html(179 reposPage(180 c,181 ctx,182 `${repo.name} ${release.version} ${platform}: ${error}`,183 repo.name,184 "builds",185 ),186 status,187 );188 if ((await textFields(c)).confirm !== "1") return refuse(400, "tick the box to delete it.");189 try {190 await deleteReleaseFile(191 ctx.sync.bucket,192 ctx.kepr,193 mirror,194 repo.name,195 release.version,196 platform,197 );198 } catch (error) {199 if (error instanceof LastReleaseFile) return refuse(400, error.message);200 if (error instanceof BucketWriteError) return refuse(503, error.message);201 throw error;202 }203 return c.redirect(204 `/admin/repos?repo=${repo.name}&tab=builds&saved=1#${repo.name}-${release.version}`,205 303,206 );207 });208}209210211function findRelease(ctx: AdminContext, name: string, version: string) {212 const repo = findRepo(ctx.kepr, name);213 const mirror = repo && openMirror(ctx.mirrorDir, repo.name);214 const release =215 repo &&216 mirror &&217 operatorReleases(ctx.kepr, mirror, repo.name).find((r) => r.version === version);218 return repo && mirror && release ? { repo, mirror, release } : null;219}220221function reposPage(222 c: Context,223 ctx: AdminContext,224 error: string,225 chosen: string | undefined,226 tab: Tab,227) {228 const repos = allRepos(ctx.kepr);229 const selected = repos.find((repo) => repo.name === chosen) ?? repos[0];230 const body = html`${notice(error)}231<p class="admin-intro">Choose a repository to manage its visibility and public page.</p>232<form method="post" action="/admin/sync">233${formField(c)}<button class="issues-submit" type="submit">sync now</button></form>234${repos.length === 0 && html`<p class="muted mono save-empty">no repos found in the bucket yet</p>`}235<div class="admin-repos">236<nav aria-label="repositories">237${repos.map(238 (repo) => html`<a class="issue-row" id="repo-${repo.name}"239href="/admin/repos?repo=${repo.name}#repo-editor"${selected?.name === repo.name ? html` aria-current="page"` : ""}>240<span>${repo.name}</span><span>${repo.public ? "public" : "private"}</span>241<span class="issue-meta mono">${repo.last_sync_at === null ? "never synced" : `last sync ${formatDate(repo.last_sync_at)} UTC`}</span>242${repo.last_sync_error && html`<span class="issues-error">${repo.last_sync_error}</span>`}</a>`,243)}244</nav>245${selected && repoForm(c, ctx, selected, tab)}246</div>`;247 return adminPage(c, ctx, "repos", body);248}249250251function workspace(ctx: AdminContext, repo: AdminRepo) {252 const mirror = openMirror(ctx.mirrorDir, repo.name);253 const stats = repoStats(mirror);254 const releases = operatorReleases(ctx.kepr, mirror, repo.name);255 const downloads = (release: (typeof releases)[number]) =>256 release.downloads.reduce((sum, [, count]) => sum + count, 0);257 const open = operatorIssues(ctx.kepr, "open").filter((issue) => issue.repo === repo.name);258 const vital = (label: string, value: string | number) =>259 html`<div><strong>${String(value)}</strong><span class="mono">${label}</span></div>`;260 return html`<div class="admin-vitals">261${vital("saves", stats.saves)}262${vital("lines", stats.lines)}263${vital("newest version", visibleReleases(ctx.kepr, mirror, repo.name)[0]?.version ?? "none")}264${vital("open issues", open.length)}265${vital(266 "downloads",267 releases.reduce((sum, release) => sum + downloads(release), 0),268)}269</div>270<p class="issue-meta mono">detected languages:271${languageLines(mirror).map(272 ([language, lines], i) =>273 html`${i > 0 ? " · " : " "}${language} <span class="muted">${plural(lines, "line")}</span>`,274)}</p>275`;276}277278function repoForm(c: Context, ctx: AdminContext, repo: AdminRepo, tab: Tab) {279 const synced =280 repo.last_sync_at === null ? "never synced" : `last sync ${formatDate(repo.last_sync_at)} UTC`;281 const link = (t: Tab) =>282 html`<a class="issues-tab${t === tab ? " active" : ""}" href="/admin/repos?repo=${repo.name}&tab=${t}"${283 t === tab ? html` aria-current="page"` : ""284 }>${t}</a>`;285 const content = {286 overview: () => overviewTab(ctx, repo),287 settings: () => settingsTab(c, ctx, repo),288 builds: () => buildsTab(c, ctx, repo),289 archives: () => archivesTab(c, repo),290 }[tab]();291 return html`<article class="issue-post" id="repo-editor">292<p class="issue-post-head mono">293<span class="issue-author">294${repo.public ? html`<a href="/${repo.name}">${repo.name}</a>` : repo.name}</span>295<span>${repo.public ? "public" : "private"}</span><span class="history-when">${synced}</span></p>296<nav class="issues-bar mono" aria-label="${repo.name} workspace">${TABS.map(link)}</nav>297${content}298</article>`;299}300301function overviewTab(ctx: AdminContext, repo: AdminRepo) {302 const quarantined = quarantinedPaths(openMirror(ctx.mirrorDir, repo.name));303 return html`${workspace(ctx, repo)}304${305 repo.last_sync_error && html`<p class="issues-error mono">sync error: ${repo.last_sync_error}</p>`306}307${308 quarantined.length > 0 &&309 html`<p class="issues-error mono">${plural(quarantined.length, "path")} quarantined: ${quarantined.join(", ")}</p>`310}`;311}312313function settingsTab(c: Context, ctx: AdminContext, repo: AdminRepo) {314 const own = repoText(ctx.kepr, repo.name);315 const input = (name: keyof RepoEdit, label: string) =>316 html`<label class="issues-label" for="${repo.name}-${name}">${label}</label>317<input class="issues-input" id="${repo.name}-${name}" name="${name}" maxlength="${MAX_FIELD}" value="${String(repo[name])}">`;318 return html`<form class="issues-form" method="post" action="/admin/repos/${repo.name}">319${formField(c)}320<label class="issues-label">321<input type="checkbox" name="public" value="1"${repo.public ? html` checked` : ""}> public</label>322<label class="issues-label">323<input type="checkbox" name="issues_paused" value="1"${repo.issues_paused ? html` checked` : ""}>324pause new issues</label>325${input("category", "category")}326${input("homepage", "homepage")}327${input("languages", "shown languages")}328<p class="issue-meta mono">Up to five, separated by commas. Leave blank to show the detected one.</p>329${textArea(repo.name, "description", "description", 3, own.description)}330${textArea(repo.name, "details", "details", 12, own.details)}331<p class="issue-meta mono">Markdown. Leave either blank to use the README's.</p>332<label class="issues-label" for="${repo.name}-hidden_paths">hidden files and folders</label>333<textarea class="issues-textarea mono" id="${repo.name}-hidden_paths" name="hidden_paths"334rows="4">${repo.hidden_paths}</textarea>335<p class="issue-meta mono">One path per line, such as notes.md or docs/private. Hidden from every page,336the stats and tarballs, and passed to Koh for .kohignore when there is a write key.</p>337<button class="issues-submit" type="submit">save ${repo.name}</button>338</form>339${renameForm(c, repo.name)}`;340}341342343function renameForm(c: Context, name: string) {344 const to = renames.get(name);345 if (to)346 return html`<p class="admin-intro">Renaming ${name} to ${to}. This page shows ${to} once it is done.</p>`;347 return html`${notice(renameErrors.get(name) ? `rename failed: ${renameErrors.get(name)}` : "")}348<form class="issues-form" method="post" action="/admin/repos/${name}/rename">349${formField(c)}350<label class="issues-label" for="${name}-rename">rename</label>351<input class="issues-input mono" id="${name}-rename" name="name" maxlength="100" required>352<p class="issue-meta mono">Moves its history to the new name in the bucket, with its settings, issues and353counts, and sends old links there. Your machines follow it on their next save or steal.</p>354<button class="issues-submit" type="submit">rename ${name}</button>355</form>`;356}357358function buildsTab(c: Context, ctx: AdminContext, repo: AdminRepo) {359 const releases = operatorReleases(ctx.kepr, openMirror(ctx.mirrorDir, repo.name), repo.name);360 return html`<section class="repo-section" id="builds">361${362 releases.length > 0363 ? releases.map((release) => releaseForm(c, repo.name, release))364 : html`<p class="muted mono save-empty">no builds yet</p>`365}</section>`;366}367368function archivesTab(c: Context, repo: AdminRepo) {369 return html`<section class="repo-section">370<form class="issues-form" method="post" action="/admin/repos/${repo.name}/tarballs/delete">371${formField(c)}372<p class="issue-meta mono">Tarballs are kept in the bucket once downloaded, and rebuilt on the next download.373Each one is listed under <a href="/admin/storage">storage</a>.</p>374<button class="issues-submit" type="submit">delete kept tarballs</button>375</form></section>`;376}377378function textArea(repo: string, name: RepoText, label: string, rows: number, value: string) {379 return html`<label class="issues-label" for="${repo}-${name}">${label}</label>380<textarea class="issues-textarea" id="${repo}-${name}" name="${name}" rows="${String(rows)}"381maxlength="${String(LIMITS[name])}">${value}</textarea>`;382}383384function releaseForm(c: Context, repo: string, release: OperatorRelease) {385 const total = release.downloads.reduce((sum, [, n]) => sum + n, 0);386 const id = `${repo}-${release.version}`;387 return html`<article class="issue-post" id="${id}">388<p class="issue-post-head mono">389${ ""}${html`<span class="issue-author">${release.version}</span>`}${html`<span>${release.hidden ? "hidden" : "shown"}</span>`}${html`<span>${plural(total, "download")}</span>`}${release.downloads.map(390 ([platform, n]) => html`<span class="muted">${platform} ${n}</span>`,391)}392</p>393<form class="issues-form" method="post" action="/admin/releases/${repo}/${release.version}">394${formField(c)}395<label class="issues-label" for="${id}-notes">notes396${release.notes !== release.recordNotes ? html` <span class="muted">(edited)</span>` : ""}</label>397<textarea class="issues-textarea" id="${id}-notes" name="notes" rows="3"398maxlength="${MAX_CHARS}">${release.notes}</textarea>399${400 401 402 ""403}<label class="issues-label">${html`<input type="checkbox"`}${html` name="hidden" value="1"`}${release.hidden ? html` checked` : ""}> hidden</label>404<button class="issues-submit" type="submit">save ${release.version}</button>405</form>406${407 release.downloads.length > 1 &&408 release.downloads.map(409 ([platform]) => html`<form class="issues-form" method="post"410action="/admin/releases/${repo}/${release.version}/${platform}/delete">411${formField(c)}412<label class="issues-label"><input type="checkbox" name="confirm" value="1" required>413delete the ${platform} file from the bucket</label>414<button class="issues-submit" type="submit">delete ${platform}</button>415</form>`,416 )417}418<form class="issues-form" method="post" action="/admin/releases/${repo}/${release.version}/delete">419${formField(c)}420<label class="issues-label"><input type="checkbox" name="confirm" value="1" required>421delete ${release.version} and its files from the bucket; this cannot be undone</label>422<button class="issues-submit" type="submit">delete ${release.version}</button>423</form>424</article>`;425}