console.ts

8.3 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/downloads", "downloads"],27	["/admin/storage", "storage"],28	["/admin/notifications", "notifications"],29	["/admin/email", "email"],30	["/admin/bucket", "bucket"],31	["/admin?section=backups", "backups"],32	["/admin/site?section=profile", "profile"],33	["/admin/site", "site"],34	["/admin/account", "account"],35] as const;3637/** The hidden same-site token (§25) that every admin form posts back. */38export function formField(c: Context): Html {39	return html`<input type="hidden" name="form" value="${formToken(c)}">`;40}4142/** A posted form's text fields; the guard has already parsed and checked the body. */43export async function textFields(c: Context): Promise<Record<string, string>> {44	const fields: Record<string, string> = {};45	for (const [name, value] of Object.entries(await c.req.parseBody())) {46		if (typeof value === "string") fields[name] = value;47	}48	return fields;49}5051export function notice(error: string): Html | "" {52	return error && html`<p class="issues-error mono" role="alert">${error}</p>`;53}5455/** An admin page: the site's own look, with the console's sections and sign-out on top. */56export function adminPage(c: Context, ctx: AdminContext, title: string, body: Html): string {57	const tab = ([href, name]: (typeof SECTIONS)[number]) =>58		html`<a href="${href}"${59			(60				c.req.path === "/admin"61					? (c.req.query("section") === "backups" ? "backups" : "overview") === name62					: c.req.path === "/admin/site"63						? (c.req.query("section") === "profile" ? "profile" : "site") === name64						: c.req.path === href || (href !== "/admin" && c.req.path.startsWith(`${href}/`))65			)66				? html` aria-current="page"`67				: ""68		}>${name}${69			name === "notifications" && unread > 070				? html` <span class="admin-unread">${String(unread)}</span>`71				: ""72		}</a>`;73	const unread =74		ctx.kepr75			.query<{ n: number }, []>("SELECT COUNT(*) AS n FROM notifications WHERE read = 0")76			.get()?.n ?? 0;77	const handle = setting(ctx.kepr, "handle");78	return page(ctx, {79		title: `${title} · admin`,80		description: "",81		path: c.req.path,82		body: html`<div class="admin-layout">83<aside class="admin-sidebar mono">84<span class="section-label">workspace</span>85<nav aria-label="operator workspace">${SECTIONS.map(tab)}</nav>86<div class="admin-sidebar-foot">87${handle && html`<a href="/@${handle}">view profile ↗</a>`}88<a href="/">view site ↗</a>89<form class="nav-logout" method="post" action="/admin/sign-out">90${formField(c)}<button type="submit">log out</button>91</form></div></aside>92<section class="admin-content">93<header class="admin-heading"><span class="section-label mono">operator</span>94<h1>${title}</h1></header>95${c.req.query("saved") === "1" && html`<p class="admin-notice" role="status">Changes saved.</p>`}96${body}</section></div>`,97	});98}99100// ponytail: counted once per process by walking the source, since there is no build step.101let runningLines: number | null = null;102async function sourceLines(): Promise<number> {103	if (runningLines !== null) return runningLines;104	let total = 0;105	const root = `${import.meta.dir}/../..`;106	for await (const path of new Bun.Glob("{src,scripts}/**/*.ts").scan(root)) {107		if (path.endsWith(".test.ts")) continue;108		const text = await Bun.file(`${root}/${path}`).text();109		total += text.split("\n").length - (text.endsWith("\n") ? 1 : 0);110	}111	runningLines = total;112	return total;113}114115/** The last machines that redeemed a code, and how to take their access away again. */116function connectedMachines(ctx: AdminContext): Html | "" {117	const rows = ctx.kepr118		.query<{ machine: string; used_at: number }, [number]>(119			`SELECT machine, used_at FROM connect_codes120			 WHERE used_at IS NOT NULL121			 ORDER BY used_at DESC, rowid DESC122			 LIMIT ?`,123		)124		.all(MACHINES_LISTED);125	if (rows.length === 0) return "";126	const led = rows.map((row) => {127		const at = new Date(row.used_at * 1000).toISOString();128		return html`<li>${row.machine} <span class="muted">${at}</span></li>`;129	});130	return html`<h2>Machines connected</h2>131<ul>${led}</ul>132<p class="muted">To revoke access, rotate the write key in Scaleway and update it under <a href="/admin/bucket">bucket</a>.</p>`;133}134135/** §24's Status section at `/admin`: the bucket, each repo's format, backups, the running version. */136export function registerStatus(app: Hono, ctx: AdminContext): void {137	app.get("/admin", async (c) => {138		if (c.req.query("section") === "backups") return c.html(await backupsPage(c, ctx));139		let bucket: Html;140		try {141			const repos = await listRepos(ctx.sync.bucket);142			const formats = await Promise.all(143				repos.map(async (repo) => {144					try {145						await checkFormat(ctx.sync.bucket, repo);146						return html`<li><span class="mono">${repo}</span> <span class="muted">format ok</span></li>`;147					} catch (error) {148						return html`<li><span class="mono">${repo}</span>149<span class="issues-error">${String(error)}</span></li>`;150					}151				}),152			);153			bucket = html`<p>Bucket reachable: ${plural(repos.length, "repo")}.</p><ul>${formats}</ul>`;154		} catch (error) {155			bucket = html`<p class="issues-error" role="alert">Bucket unreachable: ${String(error)}</p>`;156		}157		const { version } = (await Bun.file(`${import.meta.dir}/../../package.json`).json()) as {158			version: string;159		};160		const lines = (await sourceLines()).toLocaleString("en-US");161		const newest = backups(ctx.dataDir).at(-1);162		const repos = allRepos(ctx.kepr);163		const open = operatorIssues(ctx.kepr, "open").length;164		const attention = repos.filter((repo) => repo.last_sync_error || repo.last_sync_at === null);165		const vital = (label: string, value: number, href: string) =>166			html`<a href="${href}"><strong>${value}</strong><span class="mono">${label}</span></a>`;167		const overview = html`<div class="admin-vitals">168${vital("repositories", repos.length, "/admin/repos")}169${vital("public", repos.filter((repo) => repo.public).length, "/browse")}170${vital("open issues", open, "/admin/issues")}171</div>172<section class="repo-section"><h2 class="section-label mono">needs attention</h2>173${attention.map(174	(repo) => html`<a class="issue-row" href="/admin/repos?repo=${repo.name}">175<span>${repo.name}</span><span class="issues-error">${repo.last_sync_error ?? "Not synced yet"}</span></a>`,176)}177${!newest && html`<p class="issues-error">No backup yet. Check the server log for backup errors.</p>`}178${!setting(ctx.kepr, "handle") && html`<p><a href="/admin/site?section=profile">Set your handle to publish your profile →</a></p>`}179${attention.length === 0 && newest && html`<p class="muted">All repositories are synced. A local backup is available.</p>`}180</section>181<section class="repo-section"><h2 class="section-label mono">repositories</h2>182${repos183	.slice()184	.sort((a, b) => (b.last_sync_at ?? 0) - (a.last_sync_at ?? 0))185	.slice(0, 8)186	.map(187		(repo) => html`188<a class="issue-row" href="/admin/repos?repo=${repo.name}"><span>${repo.name}</span>189<span class="issue-meta mono">${repo.public ? "public" : "private"} · ${repo.last_sync_at === null ? "never synced" : `synced ${relativeTime(repo.last_sync_at)}`}</span></a>`,190	)}191${repos.length === 0 && html`<p class="muted">No repositories yet. Offer one with Koh, then sync it here.</p>`}192</section>`;193		return c.html(194			adminPage(195				c,196				ctx,197				"overview",198				html`${overview}<section class="repo-section markdown">199<p><a href="/admin?section=backups">manage backups →</a></p>200<details><summary class="mono">bucket and runtime</summary>${bucket}201${connectKeys(ctx.config) ? connectedMachines(ctx) : ""}202<p>Running kepr ${version}: ${lines} lines of TypeScript.</p></details></section>`,203			),204		);205	});206}