console.ts

9.1 KB · raw

1import type { Context, Hono } from "hono";2import type { Syncer, SyncTarget } from "../bucket/sync.ts";3import { operatorIssues } from "../issues/store.ts";4import { type Html, html } from "../pages/html.ts";5import { type PageContext, page, plural, relativeTime } from "../pages/layout.ts";6import { backups } from "../server/backup.ts";7import type { Config } from "../server/config.ts";8import { connectKeys, MACHINES_LISTED } from "../server/connect.ts";9import { setting } from "../server/db.ts";10import { formToken } from "../server/login.ts";11import { backupsPage } from "./backups.ts";12import { allRepos } from "./store.ts";1314export type AdminContext = PageContext & {15	/** The bucket, kepr.db and mirrors the console reads and writes itself. */16	sync: SyncTarget;17	/** The sync, which may run on its own thread. */18	syncer: Syncer;19	dataDir: string;20	config: Config;21	configPath: string;22};2324const SECTIONS = [25	["/admin", "overview"],26	["/admin/repos", "repos"],27	["/admin/issues", "issues"],28	["/admin/downloads", "downloads"],29	["/admin/storage", "storage"],30	["/admin/notifications", "notifications"],31	["/admin/email", "email"],32	["/admin/bucket", "bucket"],33	["/admin?section=backups", "backups"],34	["/admin/site?section=profile", "profile"],35	["/admin/site", "site"],36	["/admin/account", "account"],37] as const;3839/** The hidden same-site token (§25) that every admin form posts back. */40export function formField(c: Context): Html {41	return html`<input type="hidden" name="form" value="${formToken(c)}">`;42}4344/** A posted form's text fields; the guard has already parsed and checked the body. */45export async function textFields(c: Context): Promise<Record<string, string>> {46	const fields: Record<string, string> = {};47	for (const [name, value] of Object.entries(await c.req.parseBody())) {48		if (typeof value === "string") fields[name] = value;49	}50	return fields;51}5253export function notice(error: string): Html | "" {54	return error && html`<p class="issues-error mono" role="alert">${error}</p>`;55}5657/** An admin page: the site's own look, with the console's sections and sign-out on top. */58export function adminPage(c: Context, ctx: AdminContext, title: string, body: Html): string {59	const tab = ([href, name]: (typeof SECTIONS)[number]) =>60		html`<a href="${href}"${61			(62				c.req.path === "/admin"63					? (c.req.query("section") === "backups" ? "backups" : "overview") === name64					: c.req.path === "/admin/site"65						? (c.req.query("section") === "profile" ? "profile" : "site") === name66						: c.req.path === href || (href !== "/admin" && c.req.path.startsWith(`${href}/`))67			)68				? html` aria-current="page"`69				: ""70		}>${name}${71			name === "notifications" && unread > 072				? html` <span class="admin-unread">${String(unread)}</span>`73				: ""74		}</a>`;75	const unread =76		ctx.kepr77			.query<{ n: number }, []>("SELECT COUNT(*) AS n FROM notifications WHERE read = 0")78			.get()?.n ?? 0;79	const handle = setting(ctx.kepr, "handle");80	return page(ctx, {81		title: `${title} · admin`,82		description: "",83		path: c.req.path,84		body: html`<div class="admin-layout">85<aside class="admin-sidebar mono">86<span class="section-label">workspace</span>87<nav aria-label="operator workspace">${SECTIONS.map(tab)}</nav>88<div class="admin-sidebar-foot">89${handle && html`<a href="/@${handle}">view profile ↗</a>`}90<a href="/">view site ↗</a>91<form class="nav-logout" method="post" action="/admin/sign-out">92${formField(c)}<button type="submit">log out</button>93</form></div></aside>94<section class="admin-content">95<header class="admin-heading"><span class="section-label mono">operator</span>96<h1>${title}</h1></header>97${c.req.query("saved") === "1" && html`<p class="admin-notice" role="status">Changes saved.</p>`}98${body}</section></div>`,99	});100}101102// ponytail: counted once per process by walking the source, since there is no build step.103let runningLines: Promise<number> | null = null;104function sourceLines(): Promise<number> {105	// Cache the promise, not the value: concurrent first requests share one walk.106	runningLines ??= countLines().catch((error) => {107		runningLines = null;108		throw error;109	});110	return runningLines;111}112async function countLines(): Promise<number> {113	let total = 0;114	const root = `${import.meta.dir}/../..`;115	for await (const path of new Bun.Glob("{src,scripts}/**/*.ts").scan(root)) {116		if (path.endsWith(".test.ts")) continue;117		const text = await Bun.file(`${root}/${path}`).text();118		total += text.split("\n").length - (text.endsWith("\n") ? 1 : 0);119	}120	return total;121}122123/** The last machines that redeemed a code, and how to take their access away again. */124function connectedMachines(ctx: AdminContext): Html | "" {125	const rows = ctx.kepr126		.query<{ machine: string; used_at: number }, [number]>(127			`SELECT machine, used_at FROM connect_codes128			 WHERE used_at IS NOT NULL129			 ORDER BY used_at DESC, rowid DESC130			 LIMIT ?`,131		)132		.all(MACHINES_LISTED);133	if (rows.length === 0) return "";134	const led = rows.map((row) => {135		const at = new Date(row.used_at * 1000).toISOString();136		return html`<li>${row.machine} <span class="muted">${at}</span></li>`;137	});138	return html`<h2>Machines connected</h2>139<ul>${led}</ul>140<p class="muted">To revoke access, rotate the bucket key in Scaleway and update it under <a href="/admin/bucket">bucket</a>.</p>`;141}142143/**144 * The bucket as the sync last read it, and each repo's format and sync result: the sync checks the145 * format of every repo on every pass, so the console never waits on the bucket itself.146 */147function bucketStatus(ctx: AdminContext): Html {148	const error = setting(ctx.kepr, "bucket_error");149	if (error) {150		return html`<p class="issues-error" role="alert">Bucket unreachable at the last sync: ${error}</p>`;151	}152	const readAt = Number(setting(ctx.kepr, "bucket_read_at") ?? 0);153	if (readAt === 0) return html`<p class="muted">The sync has not read the bucket yet.</p>`;154	// The repos that listing found; Kepr keeps the rows of repos gone from the bucket.155	const seen = JSON.parse(setting(ctx.kepr, "bucket_repos") ?? "[]") as string[];156	const errors = new Map(allRepos(ctx.kepr).map((repo) => [repo.name, repo.last_sync_error]));157	return html`<p>Bucket read by the sync ${relativeTime(readAt)}: ${plural(seen.length, "repo")}.</p>158<ul>${seen.map((name) => {159		const failure = errors.get(name);160		return html`<li><span class="mono">${name}</span> ${161			failure162				? html`<span class="issues-error">${failure}</span>`163				: html`<span class="muted">format ok</span>`164		}</li>`;165	})}</ul>`;166}167168/** §24's Status section at `/admin`: the bucket, each repo's format, backups, the running version. */169export function registerStatus(app: Hono, ctx: AdminContext): void {170	app.get("/admin", async (c) => {171		if (c.req.query("section") === "backups") return c.html(await backupsPage(c, ctx));172		const bucket = bucketStatus(ctx);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	});222}