/** * Settings → Backups and Settings → Background jobs (1.4.0, as Accounts and Cross Events). Admins * only: a backup holds the whole site, and a job switched off stops the heartbeat or the backups. */ import fs from 'node:fs'; import express from 'express'; import type { Ctx } from '../context.js'; import { requireRole } from '../auth/sessions.js'; import { backupPath, listBackups, retainCount, rotate, runBackup } from '../backups/backups.js'; import { ApiError, handle, sendError } from '../http.js'; import { audit } from '../lib/audit.js'; import { JobError, jobStatus, runNow, setOverride } from '../jobs.js'; type Who = { id: string; role: string }; export function maintenanceRouter(ctx: Ctx, who: (req: express.Request) => Who) { const r = express.Router(); const json = express.json({ limit: '16kb' }); // On each route, not r.use: this router is mounted on the admin API's root. const admin = requireRole(ctx, 'admin'); const jobError = (e: unknown) => { if (e instanceof JobError) throw new ApiError(e.status, e.status === 404 ? 'NOT_FOUND' : e.status === 400 ? 'VALIDATION' : 'JOB_FAILED', e.message); throw e; }; // ─── Backups ─── r.get('/backups', admin, handle(async () => ({ items: (await listBackups(ctx)).map((b) => ({ filename: b.filename, size: b.size, createdAt: b.createdAt })), nightly: await ctx.settings.bool('backup_nightly', true), retain: await retainCount(ctx), lastError: await ctx.settings.get('backup_last_error'), }))); r.post('/backups/run', admin, handle(async (req) => { let b; try { b = await runBackup(ctx); } catch (e) { throw new ApiError(502, 'BACKUP_FAILED', `The backup didn't work: ${(e as Error).message}`); } const me = who(req); await audit(ctx, { actorId: me.id, actorRole: me.role, action: 'backup_made', targetType: 'backup', targetId: b.filename }); return { filename: b.filename, size: b.size, createdAt: b.createdAt }; })); r.put('/backups/settings', admin, json, handle(async (req) => { const retain = Number(req.body?.retain); if (!Number.isInteger(retain) || retain < 1 || retain > 365) throw new ApiError(400, 'VALIDATION', 'Keep between 1 and 365 backups.', { retain: 'Between 1 and 365' }); const nightly = req.body?.nightly !== false; await ctx.settings.setMany({ backup_retain_count: String(retain), backup_nightly: nightly ? 'true' : 'false' }); const deleted = await rotate(ctx); const me = who(req); await audit(ctx, { actorId: me.id, actorRole: me.role, action: 'backup_settings_changed', targetType: 'setting', targetId: 'backup_retain_count', metadata: { retain, nightly, deleted } }); return { retain, nightly, deleted }; })); // A download holds the whole site's content and its editors: audited, never cached. r.get('/backups/:file/download', admin, async (req, res) => { try { const file = backupPath(ctx, String(req.params.file)); if (!file) throw new ApiError(404, 'NOT_FOUND', 'That backup isn\'t there any more.'); const me = who(req); await audit(ctx, { actorId: me.id, actorRole: me.role, action: 'backup_downloaded', targetType: 'backup', targetId: String(req.params.file) }); res.setHeader('Content-Type', 'application/gzip'); res.setHeader('Cache-Control', 'no-store'); res.setHeader('Content-Disposition', `attachment; filename="${String(req.params.file)}"`); fs.createReadStream(file).pipe(res); } catch (e) { sendError(res, e); } }); // ─── Background jobs ─── r.get('/jobs', admin, handle(() => jobStatus(ctx))); r.put('/jobs/:name', admin, json, handle(async (req) => { const name = String(req.params.name); const out = await setOverride(ctx, name, { enabled: req.body?.enabled, cron: req.body?.cron }).catch(jobError); const me = who(req); await audit(ctx, { actorId: me.id, actorRole: me.role, action: 'job_settings_changed', targetType: 'job', targetId: name, metadata: out }); return { name, override: out }; })); r.post('/jobs/:name/run', admin, handle(async (req) => { const name = String(req.params.name); const out = await runNow(ctx, name).catch(jobError); const me = who(req); await audit(ctx, { actorId: me.id, actorRole: me.role, action: 'job_run', targetType: 'job', targetId: name, metadata: { queued: out.queued } }); return out; })); return r; }