app: backups of the database and the uploaded images (APP-1.0-PLAN §10)

As the Website's: a gzipped pg_dump into backend/backups every night (02:40,
after Accounts' and the Website's) and on Back up now, named as the
crosscode script names them (app-YYYYMMDD-HHMMSS.sql.gz); a failed dump
leaves no file; the newest kept (14 by default). After each, a snapshot of
backend/uploads, hard-linking what hasn't changed. Settings → Backups lists
both, backs up now, downloads (audited) and sets how many to keep and what's
nightly; Owner and Church admin only. The heartbeat reports the newest
backup.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
This commit is contained in:
2026-12-01 14:50:17 +02:00
co-authored by Claude Opus 5.5
parent c934f47b28
commit 62cfb18c0b
9 changed files with 603 additions and 3 deletions
+77
View File
@@ -0,0 +1,77 @@
/**
* Settings → Backups (APP-1.0-PLAN §10, as Accounts', Events' and the Website's): the database
* backups and the snapshots of the uploaded images, Back up now, how many are kept, nightly on or
* off, and a download. Owner and Church admin only: a backup holds every prayer request.
*/
import fs from 'node:fs';
import express, { type RequestHandler } from 'express';
import type { Ctx } from '../context.js';
import { backupPath, listBackups, retainCount, rotate, runBackup } from '../backups/backups.js';
import { listUploadsSnapshots, rotateUploads, runUploadsBackup } from '../backups/uploads.js';
import { ApiError, handle, sendError } from '../http.js';
import { audit, clientIp } from '../lib/audit.js';
export function backupsRouter(ctx: Ctx, full: RequestHandler) {
const r = express.Router();
const actor = (req: express.Request) => ({ actorId: req.signed!.member.id, actorRole: req.signed!.member.roles.join(','), ip: clientIp(req) });
r.get('/backups', full, 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'),
uploads: {
enabled: await ctx.settings.bool('backup_uploads', true),
lastError: await ctx.settings.get('backup_uploads_last_error'),
items: (await listUploadsSnapshots(ctx)).map((s) => ({ name: s.name, createdAt: s.createdAt, files: s.files, bytes: s.bytes, newFiles: s.newFiles, newBytes: s.newBytes })),
},
})));
r.post('/backups/run', full, 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}`);
}
let uploads: { name: string; newFiles: number } | null = null;
let uploadsError: string | null = null;
if (await ctx.settings.bool('backup_uploads', true)) {
try {
const s = await runUploadsBackup(ctx);
uploads = { name: s.name, newFiles: s.newFiles };
} catch (e) {
uploadsError = (e as Error).message;
}
}
await audit(ctx, { ...actor(req), action: 'backup_made', targetType: 'backup', targetId: b.filename, metadata: { uploads: uploads?.name ?? null } });
return { filename: b.filename, size: b.size, createdAt: b.createdAt, uploads, uploadsError };
}));
r.put('/backups/settings', full, 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;
const uploadsOn = req.body?.uploads !== false;
await ctx.settings.setMany({ backup_retain_count: String(retain), backup_nightly: nightly ? 'true' : 'false', backup_uploads: uploadsOn ? 'true' : 'false' });
const deleted = (await rotate(ctx)) + (await rotateUploads(ctx));
await audit(ctx, { ...actor(req), action: 'backup_settings_changed', targetType: 'setting', targetId: 'backup_retain_count', metadata: { retain, nightly, uploads: uploadsOn, deleted } });
return { retain, nightly, uploads: uploadsOn, deleted };
}));
// A download holds every prayer request and member: audited, never cached.
r.get('/backups/:file/download', full, 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.');
await audit(ctx, { ...actor(req), 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);
}
});
return r;
}
+4
View File
@@ -13,6 +13,7 @@
* GET /jobs, PUT /jobs/:name { enabled?, cron? }, POST /jobs/:name/run Background jobs
* GET /audit?before= the audit log; GET /access?before= the access log
* GET /share, POST /share the App's link (and the poster), and "shared" for the checklist
* GET /backups, POST /backups/run, PUT /backups/settings, GET /backups/:file/download Backups
* GET /media, POST /media?alt= (the image's bytes), DELETE /media/:id uploaded images (anyone who
* writes content: Content admin, Devotional writer, Prayer coordinator)
*/
@@ -33,6 +34,7 @@ import { wallDay } from '../prayer/service.js';
import { wallSettings } from '../prayer/wall.js';
import { accessLogList, auditLog } from './logs.js';
import { addMember, listMembers, setRoles } from './members.js';
import { backupsRouter } from './backups.js';
import { deleteMedia, listMedia, MAX_UPLOAD_BYTES, upload } from '../media/media.js';
const modulesBody = z.object(Object.fromEntries(APP_MODULES.map((m) => [m, z.boolean().optional()]))).strict();
@@ -159,6 +161,8 @@ export function adminRouter(ctx: Ctx) {
r.get('/audit', full, handle(async (req) => ({ entries: await auditLog(ctx, { before: before(req) }) })));
r.get('/access', full, handle(async (req) => ({ entries: await accessLogList(ctx, { before: before(req) }) })));
r.use(backupsRouter(ctx, full));
// ─── Uploaded images ───
const writers = requireRole(ctx, ['content_admin', 'devotional_writer', 'prayer_coordinator']);
r.get('/media', writers, handle(() => listMedia(ctx)));