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