console.ts

8.2 KB · raw

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 } 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 { backupsPage } from "./backups.ts";13import { allRepos } from "./store.ts";1415export type AdminContext = PageContext & {16	sync: SyncTarget;17	dataDir: string;18	config: Config;19	configPath: string;20};2122const SECTIONS = [23	["/admin", "overview"],24	["/admin/repos", "repos"],25	["/admin/issues", "issues"],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;3334/** The hidden same-site token (§25) that every admin form posts back. */35export function formField(c: Context): Html {36	return html`<input type="hidden" name="form" value="${formToken(c)}">`;37}3839/** A posted form's text fields; the guard has already parsed and checked the body. */40export 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}5152/** An admin page: the site's own look, with the console's sections and sign-out on top. */53export 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}9697// ponytail: counted once per process by walking the source, since there is no build step.98let 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}111112/** The last machines that redeemed a code, and how to take their access away again. */113function 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}131132/** §24's Status section at `/admin`: the bucket, each repo's format, backups, the running version. */133export function registerStatus(app: Hono, ctx: AdminContext): void {134	app.get("/admin", async (c) => {135		if (c.req.query("section") === "backups") return c.html(backupsPage(c, ctx));136		let bucket: Html;137		try {138			const repos = await listRepos(ctx.sync.bucket);139			const formats = await Promise.all(140				repos.map(async (repo) => {141					try {142						await checkFormat(ctx.sync.bucket, repo);143						return html`<li><span class="mono">${repo}</span> <span class="muted">format ok</span></li>`;144					} catch (error) {145						return html`<li><span class="mono">${repo}</span>146<span class="issues-error">${String(error)}</span></li>`;147					}148				}),149			);150			bucket = html`<p>Bucket reachable: ${plural(repos.length, "repo")}.</p><ul>${formats}</ul>`;151		} catch (error) {152			bucket = html`<p class="issues-error" role="alert">Bucket unreachable: ${String(error)}</p>`;153		}154		const { version } = (await Bun.file(`${import.meta.dir}/../../package.json`).json()) as {155			version: string;156		};157		const lines = (await sourceLines()).toLocaleString("en-US");158		const newest = backups(ctx.dataDir).at(-1);159		const repos = allRepos(ctx.kepr);160		const open = operatorIssues(ctx.kepr, "open").length;161		const attention = repos.filter((repo) => repo.last_sync_error || repo.last_sync_at === null);162		const vital = (label: string, value: number, href: string) =>163			html`<a href="${href}"><strong>${value}</strong><span class="mono">${label}</span></a>`;164		const overview = html`<div class="admin-vitals">165${vital("repositories", repos.length, "/admin/repos")}166${vital("public", repos.filter((repo) => repo.public).length, "/browse")}167${vital("open issues", open, "/admin/issues")}168</div>169<section class="repo-section"><h2 class="section-label mono">needs attention</h2>170${attention.map(171	(repo) => html`<a class="issue-row" href="/admin/repos?repo=${repo.name}">172<span>${repo.name}</span><span class="issues-error">${repo.last_sync_error ?? "Not synced yet"}</span></a>`,173)}174${!newest && html`<p class="issues-error">No backup yet. Check the server log for backup errors.</p>`}175${!setting(ctx.kepr, "handle") && html`<p><a href="/admin/site?section=profile">Set your handle to publish your profile →</a></p>`}176${attention.length === 0 && newest && html`<p class="muted">All repositories are synced. A local backup is available.</p>`}177</section>178<section class="repo-section"><h2 class="section-label mono">repositories</h2>179${repos180	.slice()181	.sort((a, b) => (b.last_sync_at ?? 0) - (a.last_sync_at ?? 0))182	.slice(0, 8)183	.map(184		(repo) => html`185<a class="issue-row" href="/admin/repos?repo=${repo.name}"><span>${repo.name}</span>186<span class="issue-meta mono">${repo.public ? "public" : "private"} · ${repo.last_sync_at === null ? "never synced" : `synced ${relativeTime(repo.last_sync_at)}`}</span></a>`,187	)}188${repos.length === 0 && html`<p class="muted">No repositories yet. Offer one with Koh, then sync it here.</p>`}189</section>`;190		return c.html(191			adminPage(192				c,193				ctx,194				"overview",195				html`${overview}<section class="repo-section markdown">196<p><a href="/admin?section=backups">manage backups →</a></p>197<details><summary class="mono">bucket and runtime</summary>${bucket}198${connectKeys(ctx.config) ? connectedMachines(ctx) : ""}199<p>Running kepr ${version}: ${lines} lines of TypeScript.</p></details></section>`,200			),201		);202	});203}