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