backups.ts

7.9 KB · raw

1import type { Context, Hono } from "hono";2import { html } from "../pages/html.ts";3import { formatSize } from "../pages/layout.ts";4import {5	attemptBackup,6	attemptUpload,7	backupBytes,8	backups,9	backupTarball,10	checkBackupBucket,11	offsiteBackups,12} from "../server/backup.ts";13import { type BackupBucket, saveConfig } from "../server/config.ts";14import { setting } from "../server/db.ts";15import { s3FieldsProblem } from "./bucket.ts";16import { type AdminContext, adminPage, formField, notice, textFields } from "./console.ts";1718// The backup bucket's fields shown back to the operator; its secret is never among them.19const SHOWN: [key: string, label: string][] = [20	["endpoint", "endpoint"],21	["name", "bucket name"],22	["region", "region"],23	["access_key_id", "access key ID"],24];25const REQUIRED = new Set(SHOWN.map(([key]) => key));2627/** `20260926T031500Z` as `2026-09-26 03:15:00 UTC`. */28function backupTime(name: string): string {29	return name.replace(/^(\d{4})(\d\d)(\d\d)T(\d\d)(\d\d)(\d\d)Z$/, "$1-$2-$3 $4:$5:$6 UTC");30}3132type Shown = { error?: string; status?: string; fields?: Record<string, string> };3334/**35 * §24's Backups section: every kept backup, back up now, the last failure, how to restore, and the36 * optional backup bucket (June, 2026-09-30) with what it holds.37 */38export async function backupsPage(c: Context, ctx: AdminContext, shown: Shown = {}) {39	const kept = backups(ctx.dataDir).reverse();40	const newest = kept[0];41	const failure = setting(ctx.kepr, "backup_error");42	const body = html`${notice(shown.error ?? "")}43${shown.status && html`<p class="admin-notice" role="status">${shown.status}</p>`}44${failure && !shown.error && html`<p class="issues-error mono" role="alert">The last backup failed: ${failure}</p>`}45${46	newest47		? html`<p>Last backup: ${backupTime(newest)}. <a href="/admin/backup">download backup</a></p>`48		: html`<p>No backup yet.</p>`49}50<form method="post" action="/admin/backup">${formField(c)}51<button class="issues-submit" type="submit">back up now</button></form>52<p>Kepr keeps the last 14 daily backups of its database and assets.</p>53<ul class="admin-releases mono">${kept.map(54		(name) => html`<li><a href="/admin/backup?name=${name}">${backupTime(name)}</a>55<span class="muted">${formatSize(backupBytes(ctx.dataDir, name))}</span></li>`,56	)}</ul>57${await bucketSection(c, ctx, shown.fields)}58<section class="repo-section"><h2 class="section-label mono">restoring one</h2>59<div class="markdown"><ol>60<li>Stop Kepr.</li>61<li>Unpack the download: it holds a folder with kepr.db and assets/.</li>62<li>Put kepr.db and assets/ in Kepr's data directory, over the old ones.</li>63<li>Start Kepr. Its first sync rebuilds the mirrors, and everyone signs in again.</li>64</ol>65<p class="muted">Sessions and bucket credentials are not included: after restoring onto a new66server, enter the bucket settings again here.</p></div></section>`;67	return adminPage(c, ctx, "backups", body);68}6970/** The backup bucket's form, its last upload and what it holds. */71async function bucketSection(c: Context, ctx: AdminContext, fields?: Record<string, string>) {72	const current = ctx.config.backup;73	const stored: Record<string, string> = {74		endpoint: current?.endpoint ?? "",75		name: current?.name ?? "",76		region: current?.region ?? "",77		access_key_id: current?.accessKeyId ?? "",78	};79	const value = (key: string) => fields?.[key] ?? stored[key] ?? "";80	const uploadError = setting(ctx.kepr, "backup_upload_error");81	let held: Awaited<ReturnType<typeof offsiteBackups>> | string = [];82	if (current) {83		try {84			held = (await offsiteBackups(current)).reverse();85		} catch (error) {86			held = `Could not list the backup bucket: ${String(error)}`;87		}88	}89	return html`<section class="repo-section"><h2 class="section-label mono">backup bucket</h2>90<p class="admin-intro">An optional second S3 bucket, apart from the one Koh offers to. Each backup is91copied there too, and the newest 14 kept. Its key needs to read, write and delete.</p>92${uploadError && html`<p class="issues-error mono" role="alert">The last upload to the backup bucket failed: ${uploadError}</p>`}93${typeof held === "string" && html`<p class="issues-error mono">${held}</p>`}94${95	Array.isArray(held) &&96	held.length > 0 &&97	html`<p class="muted">${String(held.length)} in the backup bucket:</p>98<ul class="admin-releases mono">${held.map(99		(backup) =>100			html`<li>${backupTime(backup.name)} <span class="muted">${formatSize(backup.size)}</span></li>`,101	)}</ul>`102}103<form class="issues-form" method="post" action="/admin/backup-bucket">104${formField(c)}105${SHOWN.map(106	([key, label]) => html`<label class="issues-label" for="backup-${key}">${label}</label>107<input class="issues-input mono" id="backup-${key}" name="${key}" value="${value(key)}"108autocomplete="off" spellcheck="false">`,109)}110<label class="issues-label" for="backup-secret_access_key">secret key</label>111<input class="issues-input mono" id="backup-secret_access_key" name="secret_access_key"112type="password" autocomplete="new-password" placeholder="${current ? "unchanged" : ""}">113<div class="issues-actions">114<button class="issues-submit" type="submit" name="action" value="test">test connection</button>115<button class="issues-submit" type="submit" name="action" value="save">save</button>116${current && html`<button class="issues-submit" type="submit" name="action" value="remove">remove</button>`}117</div>118</form></section>`;119}120121/** The backup bucket a form describes, a blank secret keeping the stored one; or what is wrong. */122function candidate(fields: Record<string, string>, current?: BackupBucket): BackupBucket | string {123	const problem = s3FieldsProblem(fields, SHOWN, REQUIRED);124	if (problem) return problem;125	const value = (key: string) => (fields[key] ?? "").trim();126	const secretAccessKey = value("secret_access_key") || current?.secretAccessKey;127	if (!secretAccessKey) return "The secret key is required.";128	return {129		endpoint: value("endpoint"),130		name: value("name"),131		region: value("region"),132		accessKeyId: value("access_key_id"),133		secretAccessKey,134	};135}136137export function registerBackups(app: Hono, ctx: AdminContext): void {138	app.get("/admin/backup", (c) => {139		const backup = backupTarball(ctx.dataDir, c.req.query("name"));140		if (!backup) return c.notFound();141		return c.body(backup.stream, 200, {142			"Content-Type": "application/gzip",143			"Content-Disposition": `attachment; filename="kepr-backup-${backup.name}.tar.gz"`,144		});145	});146147	app.post("/admin/backup", async (c) => {148		const failure = await attemptBackup(ctx.kepr, () => ctx.syncer.backup(ctx.dataDir, "now"));149		if (failure)150			return c.html(await backupsPage(c, ctx, { error: `The backup failed: ${failure}` }), 500);151		const upload = await attemptUpload(ctx.kepr, ctx.dataDir, ctx.config.backup);152		if (upload) {153			const error = `The backup was made here, but not copied to the backup bucket: ${upload}`;154			return c.html(await backupsPage(c, ctx, { error }), 502);155		}156		return c.redirect("/admin?section=backups&saved=1", 303);157	});158159	app.post("/admin/backup-bucket", async (c) => {160		const fields = await textFields(c);161		const refuse = async (error: string, status: 400 | 500) =>162			c.html(await backupsPage(c, ctx, { error, fields }), status);163		let backup: BackupBucket | undefined;164		if (fields.action !== "remove") {165			const next = candidate(fields, ctx.config.backup);166			if (typeof next === "string") return refuse(next, 400);167			const failure = await checkBackupBucket(next);168			if (failure) return refuse(failure, 400);169			if (fields.action !== "save") {170				const status = "The backup bucket works. Nothing was saved.";171				return c.html(await backupsPage(c, ctx, { status, fields }));172			}173			backup = next;174		}175		const { backup: _, ...rest } = ctx.config;176		try {177			await saveConfig(ctx.configPath, backup ? { ...rest, backup } : rest);178		} catch (error) {179			return refuse(`The settings could not be saved: ${String(error)}`, 500);180		}181		// In place, so the backup loop sees it at its next check.182		if (backup) ctx.config.backup = backup;183		else delete ctx.config.backup;184		return c.redirect("/admin?section=backups&saved=1", 303);185	});186}