1import type { Context, Hono } from "hono";2import { checkFormat, listRepos } from "../bucket/repo.ts";3import type { SyncTarget } from "../bucket/sync.ts";4import { operatorIssues } from "../issues/store.ts";5import { type Html, html } from "../pages/html.ts";6import { type PageContext, page, plural, relativeTime } from "../pages/layout.ts";7import { backups, newestBackupTarball } from "../server/backup.ts";8import type { Config } from "../server/config.ts";9import { connectKeys, MACHINES_LISTED } from "../server/connect.ts";10import { setting } from "../server/db.ts";11import { formToken } from "../server/login.ts";12import { allRepos } from "./store.ts";1314export type AdminContext = PageContext & {15 sync: SyncTarget;16 dataDir: string;17 config: Config;18 configPath: string;19};2021const SECTIONS = [22 ["/admin", "overview"],23 ["/admin/repos", "repos"],24 ["/admin/issues", "issues"],25 ["/admin/releases", "releases"],26 ["/admin/notifications", "notifications"],27 ["/admin/bucket", "bucket"],28 ["/admin?section=backups", "backups"],29 ["/admin/site?section=profile", "profile"],30 ["/admin/site", "site"],31] as const;323334export function formField(c: Context): Html {35 return html`<input type="hidden" name="form" value="${formToken(c)}">`;36}373839export async function textFields(c: Context): Promise<Record<string, string>> {40 const fields: Record<string, string> = {};41 for (const [name, value] of Object.entries(await c.req.parseBody())) {42 if (typeof value === "string") fields[name] = value;43 }44 return fields;45}4647export function notice(error: string): Html | "" {48 return error && html`<p class="issues-error mono" role="alert">${error}</p>`;49}505152export function adminPage(c: Context, ctx: AdminContext, title: string, body: Html): string {53 const tab = ([href, name]: (typeof SECTIONS)[number]) =>54 html`<a href="${href}"${55 (56 c.req.path === "/admin"57 ? (c.req.query("section") === "backups" ? "backups" : "overview") === name58 : c.req.path === "/admin/site"59 ? (c.req.query("section") === "profile" ? "profile" : "site") === name60 : c.req.path === href || (href !== "/admin" && c.req.path.startsWith(`${href}/`))61 )62 ? html` aria-current="page"`63 : ""64 }>${name}${65 name === "notifications" && unread > 066 ? html` <span class="admin-unread">${String(unread)}</span>`67 : ""68 }</a>`;69 const unread =70 ctx.kepr71 .query<{ n: number }, []>("SELECT COUNT(*) AS n FROM notifications WHERE read = 0")72 .get()?.n ?? 0;73 const handle = setting(ctx.kepr, "handle");74 return page(ctx, {75 title: `${title} · admin`,76 description: "",77 path: c.req.path,78 body: html`<div class="admin-layout">79<aside class="admin-sidebar mono">80<span class="section-label">workspace</span>81<nav aria-label="operator workspace">${SECTIONS.map(tab)}</nav>82<div class="admin-sidebar-foot">83${handle && html`<a href="/@${handle}">view profile ↗</a>`}84<a href="/">view site ↗</a>85<form class="nav-logout" method="post" action="/admin/sign-out">86${formField(c)}<button type="submit">log out</button>87</form></div></aside>88<section class="admin-content">89<header class="admin-heading"><span class="section-label mono">operator</span>90<h1>${title}</h1></header>91${c.req.query("saved") === "1" && html`<p class="admin-notice" role="status">Changes saved.</p>`}92${body}</section></div>`,93 });94}959697let runningLines: number | null = null;98async function sourceLines(): Promise<number> {99 if (runningLines !== null) return runningLines;100 let total = 0;101 const root = `${import.meta.dir}/../..`;102 for await (const path of new Bun.Glob("{src,scripts}/**/*.ts").scan(root)) {103 if (path.endsWith(".test.ts")) continue;104 const text = await Bun.file(`${root}/${path}`).text();105 total += text.split("\n").length - (text.endsWith("\n") ? 1 : 0);106 }107 runningLines = total;108 return total;109}110111112function connectedMachines(ctx: AdminContext): Html | "" {113 const rows = ctx.kepr114 .query<{ machine: string; used_at: number }, [number]>(115 `SELECT machine, used_at FROM connect_codes116 WHERE used_at IS NOT NULL117 ORDER BY used_at DESC, rowid DESC118 LIMIT ?`,119 )120 .all(MACHINES_LISTED);121 if (rows.length === 0) return "";122 const led = rows.map((row) => {123 const at = new Date(row.used_at * 1000).toISOString();124 return html`<li>${row.machine} <span class="muted">${at}</span></li>`;125 });126 return html`<h2>Machines connected</h2>127<ul>${led}</ul>128<p class="muted">To revoke access, rotate the write key in Scaleway and update it under <a href="/admin/bucket">bucket</a>.</p>`;129}130131132export function registerStatus(app: Hono, ctx: AdminContext): void {133 app.get("/admin", async (c) => {134 if (c.req.query("section") === "backups") {135 const newest = backups(ctx.dataDir).at(-1);136 const backup = newest137 ? html`<p>Last backup: ${newest.replace(138 /^(\d{4})(\d\d)(\d\d)T(\d\d)(\d\d)(\d\d)Z$/,139 "$1-$2-$3 $4:$5:$6 UTC",140 )}. <a href="/admin/backup">download backup</a></p>`141 : html`<p>No backup yet.</p>`;142 return c.html(143 adminPage(144 c,145 ctx,146 "backups",147 html`${backup}148<p>Kepr keeps the last 14 daily backups of its database and assets.</p>149<p class="muted">Backups stay on this server. Keep a copy elsewhere, along with kepr.toml.</p>150<p class="muted">Sessions and bucket credentials are not included.</p>`,151 ),152 );153 }154 let bucket: Html;155 try {156 const repos = await listRepos(ctx.sync.bucket);157 const formats = await Promise.all(158 repos.map(async (repo) => {159 try {160 await checkFormat(ctx.sync.bucket, repo);161 return html`<li><span class="mono">${repo}</span> <span class="muted">format ok</span></li>`;162 } catch (error) {163 return html`<li><span class="mono">${repo}</span>164<span class="issues-error">${String(error)}</span></li>`;165 }166 }),167 );168 bucket = html`<p>Bucket reachable: ${plural(repos.length, "repo")}.</p><ul>${formats}</ul>`;169 } catch (error) {170 bucket = html`<p class="issues-error" role="alert">Bucket unreachable: ${String(error)}</p>`;171 }172 const { version } = (await Bun.file(`${import.meta.dir}/../../package.json`).json()) as {173 version: string;174 };175 const lines = (await sourceLines()).toLocaleString("en-US");176 const newest = backups(ctx.dataDir).at(-1);177 const repos = allRepos(ctx.kepr);178 const open = operatorIssues(ctx.kepr, "open").length;179 const attention = repos.filter((repo) => repo.last_sync_error || repo.last_sync_at === null);180 const vital = (label: string, value: number, href: string) =>181 html`<a href="${href}"><strong>${value}</strong><span class="mono">${label}</span></a>`;182 const overview = html`<div class="admin-vitals">183${vital("repositories", repos.length, "/admin/repos")}184${vital("public", repos.filter((repo) => repo.public).length, "/browse")}185${vital("open issues", open, "/admin/issues")}186</div>187<section class="repo-section"><h2 class="section-label mono">needs attention</h2>188${attention.map(189 (repo) => html`<a class="issue-row" href="/admin/repos?repo=${repo.name}">190<span>${repo.name}</span><span class="issues-error">${repo.last_sync_error ?? "Not synced yet"}</span></a>`,191)}192${!newest && html`<p class="issues-error">No backup yet. Check the server log for backup errors.</p>`}193${!setting(ctx.kepr, "handle") && html`<p><a href="/admin/site?section=profile">Set your handle to publish your profile →</a></p>`}194${attention.length === 0 && newest && html`<p class="muted">All repositories are synced. A local backup is available.</p>`}195</section>196<section class="repo-section"><h2 class="section-label mono">repositories</h2>197${repos198 .slice()199 .sort((a, b) => (b.last_sync_at ?? 0) - (a.last_sync_at ?? 0))200 .slice(0, 8)201 .map(202 (repo) => html`203<a class="issue-row" href="/admin/repos?repo=${repo.name}"><span>${repo.name}</span>204<span class="issue-meta mono">${repo.public ? "public" : "private"} · ${repo.last_sync_at === null ? "never synced" : `synced ${relativeTime(repo.last_sync_at)}`}</span></a>`,205 )}206${repos.length === 0 && html`<p class="muted">No repositories yet. Offer one with Koh, then sync it here.</p>`}207</section>`;208 return c.html(209 adminPage(210 c,211 ctx,212 "overview",213 html`${overview}<section class="repo-section markdown">214<p><a href="/admin?section=backups">manage backups →</a></p>215<details><summary class="mono">bucket and runtime</summary>${bucket}216${connectKeys(ctx.config) ? connectedMachines(ctx) : ""}217<p>Running kepr ${version}: ${lines} lines of TypeScript.</p></details></section>`,218 ),219 );220 });221222 app.get("/admin/backup", (c) => {223 const backup = newestBackupTarball(ctx.dataDir);224 if (!backup) return c.notFound();225 return c.body(backup.bytes, 200, {226 "Content-Type": "application/gzip",227 "Content-Disposition": `attachment; filename="kepr-backup-${backup.name}.tar.gz"`,228 });229 });230}