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)));
+136
View File
@@ -0,0 +1,136 @@
/**
* Database backups (APP-1.0-PLAN §10, as Accounts', Cross Events' and the Website's Settings → Backups): a gzipped
* `pg_dump` into backend/backups/ every night (02:40, after Accounts' at 02:00 and the Website's at 02:20) and whenever an
* admin asks, kept on this server only. The `crosscode` script makes the same files before every
* deploy and uninstall (scripts/products/app.sh), so the admin's list shows both, newest first.
* The database only: the uploaded images (backend/uploads) are snapshotted next to it (uploads.ts).
*
* Settings: `backup_nightly` (default on), `backup_retain_count` (default 14), and what the last
* run did (`backup_last_error`). Needs the `pg_dump` program on the server (Postgres client).
*/
import { spawn } from 'node:child_process';
import fs from 'node:fs';
import path from 'node:path';
import type { Readable } from 'node:stream';
import { pipeline } from 'node:stream/promises';
import { fileURLToPath } from 'node:url';
import zlib from 'node:zlib';
import type { Ctx } from '../context.js';
/** backend/backups, from src/ and dist/ alike (never relative to where the process started). */
export const DEFAULT_BACKUP_DIR = path.join(path.dirname(fileURLToPath(import.meta.url)), '..', '..', 'backups');
/** The names this module and the crosscode script give a backup: app-YYYYMMDD-HHMMSS.sql.gz. */
export const BACKUP_FILE = /^app-\d{8}-\d{6}\.sql\.gz$/;
export const DEFAULT_RETAIN = 14;
const MAX_RETAIN = 365;
export type Backup = { filename: string; size: number; createdAt: Date };
/** Something that writes a plain-SQL dump of the database to a stream (tests pass their own). */
export type Dumper = (databaseUrl: string) => { stdout: Readable; done: Promise<void> };
const dir = (ctx: Ctx) => ctx.config.backupDir ?? DEFAULT_BACKUP_DIR;
/** `pg_dump`, plain SQL, without owners or privileges (restores into any database user). */
export const pgDump: Dumper = (databaseUrl) => {
const child = spawn('pg_dump', ['--no-owner', '--no-privileges', databaseUrl], { stdio: ['ignore', 'pipe', 'pipe'] });
let stderr = '';
child.stderr.on('data', (d) => { stderr += String(d); });
const done = new Promise<void>((resolve, reject) => {
child.on('error', (e) => reject(new Error(`pg_dump couldn't start (${e.message}). Install the PostgreSQL client on this server.`)));
child.on('close', (code) => (code === 0 ? resolve() : reject(new Error(`pg_dump stopped (exit ${code}): ${stderr.trim().slice(0, 400)}`))));
});
return { stdout: child.stdout, done };
};
const pad = (n: number) => String(n).padStart(2, '0');
/** app-20261201-020000.sql.gz in the server's local time, as the crosscode script names them. */
export function backupName(at: Date): string {
return `app-${at.getFullYear()}${pad(at.getMonth() + 1)}${pad(at.getDate())}-${pad(at.getHours())}${pad(at.getMinutes())}${pad(at.getSeconds())}.sql.gz`;
}
export async function retainCount(ctx: Ctx): Promise<number> {
const n = Number(await ctx.settings.get('backup_retain_count'));
return Number.isInteger(n) && n >= 1 ? Math.min(n, MAX_RETAIN) : DEFAULT_RETAIN;
}
/** Every backup in the folder, newest first. */
export async function listBackups(ctx: Ctx): Promise<Backup[]> {
let names: string[];
try {
names = await fs.promises.readdir(dir(ctx));
} catch {
return [];
}
const items = await Promise.all(names.filter((n) => BACKUP_FILE.test(n)).map(async (filename) => {
const st = await fs.promises.stat(path.join(dir(ctx), filename));
return { filename, size: st.size, createdAt: st.mtime };
}));
return items.sort((a, b) => b.createdAt.getTime() - a.createdAt.getTime() || b.filename.localeCompare(a.filename));
}
/** The newest backup's time, for the Hub heartbeat. */
export async function lastBackupAt(ctx: Ctx): Promise<Date | null> {
return (await listBackups(ctx))[0]?.createdAt ?? null;
}
/** The full path of a backup to download, or null if there's no such backup (or a bad name). */
export function backupPath(ctx: Ctx, filename: string): string | null {
if (!BACKUP_FILE.test(filename)) return null;
const p = path.join(dir(ctx), filename);
return fs.existsSync(p) ? p : null;
}
/** Deletes the oldest backups beyond the number kept. */
export async function rotate(ctx: Ctx): Promise<number> {
const old = (await listBackups(ctx)).slice(await retainCount(ctx));
await Promise.all(old.map((b) => fs.promises.unlink(path.join(dir(ctx), b.filename)).catch(() => {})));
return old.length;
}
/**
* Makes a backup now. A dump that fails part-way leaves no file behind (a truncated one would
* look like a real backup). Records the outcome for the admin page.
*/
let defaultDumper: Dumper = pgDump;
/** Tests: the dump the job and the admin's button use, instead of pg_dump. */
export function useDumperForTest(d: Dumper | null): void {
defaultDumper = d ?? pgDump;
}
export async function runBackup(ctx: Ctx, dumper: Dumper = defaultDumper): Promise<Backup> {
const url = ctx.config.databaseUrl;
try {
if (!url) throw new Error('DATABASE_URL isn\'t set, so there\'s no database to back up.');
await fs.promises.mkdir(dir(ctx), { recursive: true, mode: 0o700 });
// Two in the same second (the button pressed twice): the next free second's name.
const at = ctx.now().getTime();
let filename = backupName(new Date(at));
for (let s = 1; fs.existsSync(path.join(dir(ctx), filename)); s++) filename = backupName(new Date(at + s * 1000));
const file = path.join(dir(ctx), filename);
const { stdout, done } = dumper(url);
// Both must finish: pg_dump exiting cleanly, and the file written. Wait for both either way,
// so a failed one's file is deleted after the last write, not before it.
const [dumped, written] = await Promise.allSettled([done, pipeline(stdout, zlib.createGzip(), fs.createWriteStream(file, { mode: 0o600 }))]);
const failed = [dumped, written].find((r): r is PromiseRejectedResult => r.status === 'rejected');
if (failed) {
await fs.promises.unlink(file).catch(() => {});
throw failed.reason;
}
await rotate(ctx);
await ctx.settings.set('backup_last_error', null);
const st = await fs.promises.stat(file);
return { filename, size: st.size, createdAt: st.mtime };
} catch (e) {
await ctx.settings.set('backup_last_error', `${ctx.now().toISOString()} ${(e as Error).message}`.slice(0, 600));
throw e;
}
}
/** The nightly `backup` job: skipped when an admin has turned nightly backups off. */
export async function runBackupJob(ctx: Ctx) {
if (!(await ctx.settings.bool('backup_nightly', true))) return { skipped: true };
const b = await runBackup(ctx);
return { filename: b.filename, size: b.size };
}
+171
View File
@@ -0,0 +1,171 @@
/**
* Backups of the uploads (APP-1.0-PLAN §10, as the Website's): the images uploaded in the admin, which the database
* backups (backups.ts) don't hold. Each is a folder `backups/uploads-YYYYMMDD-HHMMSS/` with the
* uploads as they were, made right after the nightly database backup (and with "Back up now").
*
* Snapshots, not archives: a file that's the same as in the last snapshot (same size and time) is
* a hard link to it, so after the first full copy a night costs only the files added since. An
* uploaded file never changes (a new upload is a new file), so this is cheap and still a real
* copy: deleting or damaging a file in uploads/ doesn't touch the snapshots. Deleting an old
* snapshot frees only what no newer one shares.
*
* A snapshot is built in a `.uploads-…-partial` folder and renamed when complete, so a failed one
* never looks like a backup. Dot entries are left
* out. Kept: the same number as the database backups (`backup_retain_count`). Off with
* `backup_uploads` = false. To restore: copy a snapshot's contents back into backend/uploads as
* the site's user (`cp -a backups/uploads-…/. uploads/`).
*/
import fs from 'node:fs';
import path from 'node:path';
import type { Ctx } from '../context.js';
import { uploadDir } from '../media/media.js';
import { DEFAULT_BACKUP_DIR, retainCount, runBackupJob } from './backups.js';
export const UPLOADS_SNAPSHOT = /^uploads-\d{8}-\d{6}$/;
const MANIFEST = '.snapshot.json';
export type UploadsSnapshot = { name: string; createdAt: Date; files: number; bytes: number; newFiles: number; newBytes: number };
const dir = (ctx: Ctx) => ctx.config.backupDir ?? DEFAULT_BACKUP_DIR;
const pad = (n: number) => String(n).padStart(2, '0');
/** uploads-20261127-022000, in the server's local time, as the database backups are named. */
export function snapshotName(at: Date): string {
return `uploads-${at.getFullYear()}${pad(at.getMonth() + 1)}${pad(at.getDate())}-${pad(at.getHours())}${pad(at.getMinutes())}${pad(at.getSeconds())}`;
}
/** Every complete snapshot, newest first, with what its manifest says. */
export async function listUploadsSnapshots(ctx: Ctx): Promise<UploadsSnapshot[]> {
let names: string[];
try {
names = await fs.promises.readdir(dir(ctx));
} catch {
return [];
}
const out: UploadsSnapshot[] = [];
for (const name of names.filter((n) => UPLOADS_SNAPSHOT.test(n))) {
const p = path.join(dir(ctx), name);
const st = await fs.promises.stat(p).catch(() => null);
if (!st?.isDirectory()) continue;
const m = await fs.promises.readFile(path.join(p, MANIFEST), 'utf8').then((t) => JSON.parse(t) as Partial<UploadsSnapshot>).catch(() => ({} as Partial<UploadsSnapshot>));
out.push({ name, createdAt: m.createdAt ? new Date(m.createdAt) : st.mtime, files: m.files ?? 0, bytes: m.bytes ?? 0, newFiles: m.newFiles ?? 0, newBytes: m.newBytes ?? 0 });
}
return out.sort((a, b) => b.createdAt.getTime() - a.createdAt.getTime() || b.name.localeCompare(a.name));
}
/** The uploads' files, relative to the folder: no dot entries, no links. */
async function filesIn(root: string, rel = ''): Promise<{ rel: string; size: number; mtimeMs: number }[]> {
let entries: fs.Dirent[];
try {
entries = await fs.promises.readdir(path.join(root, rel), { withFileTypes: true });
} catch (e) {
if ((e as NodeJS.ErrnoException).code === 'ENOENT' && !rel) return [];
throw e;
}
const out: { rel: string; size: number; mtimeMs: number }[] = [];
for (const e of entries) {
if (e.name.startsWith('.')) continue;
const r = path.join(rel, e.name);
if (e.isDirectory()) out.push(...(await filesIn(root, r)));
else if (e.isFile()) {
const st = await fs.promises.stat(path.join(root, r));
out.push({ rel: r, size: st.size, mtimeMs: st.mtimeMs });
}
}
return out;
}
/** Deletes the oldest snapshots beyond the number kept, and any partial one left by a crash. */
export async function rotateUploads(ctx: Ctx): Promise<number> {
const old = (await listUploadsSnapshots(ctx)).slice(await retainCount(ctx));
for (const s of old) await fs.promises.rm(path.join(dir(ctx), s.name), { recursive: true, force: true });
const names = await fs.promises.readdir(dir(ctx)).catch(() => [] as string[]);
for (const n of names.filter((x) => /^\.uploads-\d{8}-\d{6}-partial$/.test(x))) await fs.promises.rm(path.join(dir(ctx), n), { recursive: true, force: true });
return old.length;
}
/** Free bytes on the backups' disk, or null where the system can't say. */
async function freeBytes(p: string): Promise<number | null> {
try {
const s = await fs.promises.statfs(p);
return Number(s.bavail) * Number(s.bsize);
} catch {
return null;
}
}
/** Makes a snapshot of the uploads now. Records the outcome for the admin page. */
export async function runUploadsBackup(ctx: Ctx): Promise<UploadsSnapshot> {
try {
const source = uploadDir(ctx);
await fs.promises.mkdir(dir(ctx), { recursive: true, mode: 0o700 });
const at = ctx.now().getTime();
let name = snapshotName(new Date(at));
for (let s = 1; fs.existsSync(path.join(dir(ctx), name)); s++) name = snapshotName(new Date(at + s * 1000));
const partial = path.join(dir(ctx), `.${name}-partial`);
const previous = (await listUploadsSnapshots(ctx))[0];
const prevDir = previous ? path.join(dir(ctx), previous.name) : null;
const files = await filesIn(source);
// What's the same as last time is linked; the rest is copied. Check there's room for that first.
const same = async (f: { rel: string; size: number; mtimeMs: number }) => {
if (!prevDir) return false;
const st = await fs.promises.stat(path.join(prevDir, f.rel)).catch(() => null);
return !!st && st.isFile() && st.size === f.size && Math.abs(st.mtimeMs - f.mtimeMs) < 1;
};
const plan = await Promise.all(files.map(async (f) => ({ ...f, link: await same(f) })));
const needed = plan.filter((f) => !f.link).reduce((n, f) => n + f.size, 0);
const free = await freeBytes(dir(ctx));
if (free !== null && needed > free * 0.9) {
throw new Error(`Not enough disk space for the uploaded images: ${Math.ceil(needed / 1e6)} MB to copy, ${Math.floor(free / 1e6)} MB free.`);
}
await fs.promises.rm(partial, { recursive: true, force: true });
await fs.promises.mkdir(partial, { recursive: true, mode: 0o700 });
let newFiles = 0;
let newBytes = 0;
try {
for (const f of plan) {
const dest = path.join(partial, f.rel);
await fs.promises.mkdir(path.dirname(dest), { recursive: true });
let linked = false;
if (f.link) {
linked = await fs.promises.link(path.join(prevDir!, f.rel), dest).then(() => true, () => false);
}
if (!linked) {
await fs.promises.copyFile(path.join(source, f.rel), dest);
// The source's time, so tomorrow's run sees it as the same file.
const t = new Date(f.mtimeMs);
await fs.promises.utimes(dest, t, t);
newFiles++;
newBytes += f.size;
}
}
const snapshot: UploadsSnapshot = { name, createdAt: new Date(at), files: plan.length, bytes: plan.reduce((n, f) => n + f.size, 0), newFiles, newBytes };
await fs.promises.writeFile(path.join(partial, MANIFEST), JSON.stringify(snapshot), { mode: 0o600 });
await fs.promises.rename(partial, path.join(dir(ctx), name));
await rotateUploads(ctx);
await ctx.settings.set('backup_uploads_last_error', null);
return snapshot;
} catch (e) {
await fs.promises.rm(partial, { recursive: true, force: true }).catch(() => {});
throw e;
}
} catch (e) {
await ctx.settings.set('backup_uploads_last_error', `${ctx.now().toISOString()} ${(e as Error).message}`.slice(0, 600));
throw e;
}
}
/**
* The nightly `backup` job: the database (skipped when nightly backups are off), then the
* uploads (unless `backup_uploads` is off). The database backup is made even when the uploads'
* fails; the job then fails too, so the run shows it (and the Hub's "jobs failing").
*/
export async function runNightlyBackups(ctx: Ctx) {
const database = await runBackupJob(ctx);
if ('skipped' in database) return { database };
if (!(await ctx.settings.bool('backup_uploads', true))) return { database, uploads: { skipped: true } };
const s = await runUploadsBackup(ctx);
return { database, uploads: { name: s.name, files: s.files, newFiles: s.newFiles, newBytes: s.newBytes } };
}
+3 -2
View File
@@ -22,6 +22,7 @@ import { hubPublicKey, verifyToken } from './licence.js';
import { prayerStats } from '../prayer/service.js';
import { announcementsLast30d } from '../content/announcements.js';
import { messagesLast30d } from '../messaging/send.js';
import { lastBackupAt } from '../backups/backups.js';
import { jobsHealth } from '../jobs.js';
export const PROTOCOL_VERSION = 2;
@@ -68,8 +69,8 @@ export async function health(ctx: Ctx) {
uptimeSeconds: Math.round((Date.now() - STARTED_AT) / 1000),
db: await dbUp(ctx),
jobs: await jobsHealth(ctx),
// The nightly backup comes with the App's backups (as the Website's, before 1.0.0).
lastBackupAt: null,
// The newest backup, the nightly one or one the crosscode script made (backups/backups.ts).
lastBackupAt: (await lastBackupAt(ctx).catch(() => null))?.toISOString() ?? null,
disk: null,
errorsLast24h: null,
pendingMigrations: 0,
+5 -1
View File
@@ -6,7 +6,8 @@
* The Hub heartbeat, the event feed, Cross Code's devotionals (the next 2 weeks, today included, once
* a night, §6), the House of Prayer's reminders and renewal notices (prayer/jobs.ts), tidying prayer
* requests, and email and WhatsApp (§8, messaging/send.ts): sending what's queued, and queuing
* announcements and the day's devotional. The nightly backup comes with the admin (§10).
* announcements and the day's devotional; and the nightly backup of the database and the uploaded
* images (§10, backups/).
*
* Settings → Background jobs (§10) shows each job's schedule and last runs, runs one now, and
* switches one on or off or changes its schedule. That choice is kept in the database
@@ -23,6 +24,7 @@ import { nightlySync } from './content/devotionals.js';
import { syncAll } from './events/feed.js';
import { DELETE_AFTER_CLOSED_DAYS } from './requests/settings.js';
import { queueAnnouncements, queueDevotionals, sendOutbox } from './messaging/send.js';
import { runNightlyBackups } from './backups/uploads.js';
export type Job = { name: string; label: string; cron: string; env: string | null; run: (ctx: Ctx) => Promise<unknown> };
@@ -35,6 +37,8 @@ export const JOBS: Job[] = [
{ name: 'messages-send', label: 'Email and WhatsApp: send what\'s queued (reminders, notices, announcements, devotionals)', cron: '* * * * *', env: 'MESSAGES_ENABLED', run: (ctx) => sendOutbox(ctx) },
{ name: 'announcement-sends', label: 'Announcements: queue "Also send it" at the publish time', cron: '* * * * *', env: null, run: (ctx) => queueAnnouncements(ctx) },
{ name: 'devotional-sends', label: 'Today\'s devotional: queue it at each member\'s time', cron: '*/5 * * * *', env: null, run: (ctx) => queueDevotionals(ctx) },
// After Accounts' (02:00) and the Website's (02:20) on the same server.
{ name: 'backup', label: 'Backup: the database, and the uploaded images', cron: '40 2 * * *', env: 'BACKUP_ENABLED', run: (ctx) => runNightlyBackups(ctx) },
{ name: 'prayer-renewals', label: 'House of Prayer: renewal notices (14 and 3 days before the end)', cron: '0 9 * * *', env: 'PRAYER_RENEWALS_ENABLED', run: (ctx) => sendRenewalNotices(ctx) },
];
+93
View File
@@ -0,0 +1,93 @@
import { after, describe, it } from 'node:test';
import assert from 'node:assert/strict';
import fs from 'node:fs';
import os from 'node:os';
import path from 'node:path';
import { Readable } from 'node:stream';
import zlib from 'node:zlib';
import request from 'supertest';
import { BACKUP_FILE, backupName, backupPath, listBackups, runBackup, runBackupJob, useDumperForTest, type Dumper } from '../src/backups/backups.js';
import { listUploadsSnapshots, runNightlyBackups, UPLOADS_SNAPSHOT } from '../src/backups/uploads.js';
import { health } from '../src/hub/client.js';
import { cookieHeader, harness, PASTOR, signInAs, type Harness } from './support/harness.js';
const COORD = '55555555-5555-4555-8555-555555555555';
const ORIGIN = 'https://app.hope.test';
const dumpOf = (sql: string): Dumper => () => ({ stdout: Readable.from([sql]), done: Promise.resolve() });
const failing: Dumper = () => ({ stdout: Readable.from(['-- half a dump']), done: Promise.reject(new Error('pg_dump stopped (exit 1): connection refused')) });
after(() => useDumperForTest(null));
async function setup() {
const uploads = fs.mkdtempSync(path.join(os.tmpdir(), 'cca-uploads-'));
const h = await harness({ env: { UPLOAD_DIR: uploads } }) as Harness;
const dir = fs.mkdtempSync(path.join(os.tmpdir(), 'cca-backups-'));
h.ctx.config.backupDir = dir;
h.ctx.config.databaseUrl = 'postgresql://test@127.0.0.1/app_test';
return { h, dir, uploads };
}
describe('backups (§10)', () => {
it('is the gzipped dump, named as the crosscode script names them', async () => {
const { h, dir } = await setup();
const b = await runBackup(h.ctx, dumpOf('CREATE TABLE "Member" ();\n'));
assert.match(b.filename, BACKUP_FILE);
assert.equal(zlib.gunzipSync(fs.readFileSync(path.join(dir, b.filename))).toString(), 'CREATE TABLE "Member" ();\n');
assert.equal(backupName(new Date(2026, 11, 1, 2, 40, 5)), 'app-20261201-024005.sql.gz');
assert.ok((await health(h.ctx)).lastBackupAt);
});
it('leaves no file when the dump fails part-way, says why, and keeps only the newest', async () => {
const { h } = await setup();
await assert.rejects(runBackup(h.ctx, failing), /connection refused/);
assert.equal((await listBackups(h.ctx)).length, 0);
assert.match(String(await h.ctx.settings.get('backup_last_error')), /connection refused/);
await h.ctx.settings.set('backup_retain_count', '2');
for (const n of [1, 2, 3]) await runBackup(h.ctx, dumpOf(`-- ${n}\n`));
assert.equal((await listBackups(h.ctx)).length, 2);
assert.equal(await h.ctx.settings.get('backup_last_error'), null);
assert.equal(backupPath(h.ctx, '../.env'), null);
assert.equal(backupPath(h.ctx, 'website-20200101-000000.sql.gz'), null);
});
it('snapshots the uploaded images each night, linking what hasn\'t changed', async () => {
const { h, uploads } = await setup();
useDumperForTest(dumpOf('-- nightly\n'));
fs.mkdirSync(path.join(uploads, '2026', '12'), { recursive: true });
fs.writeFileSync(path.join(uploads, '2026', '12', 'a.jpg'), 'photo a');
const first = await runNightlyBackups(h.ctx) as { uploads: { newFiles: number } };
assert.equal(first.uploads.newFiles, 1);
h.clock.add(1000);
fs.writeFileSync(path.join(uploads, '2026', '12', 'b.jpg'), 'photo b');
const second = await runNightlyBackups(h.ctx) as { uploads: { newFiles: number } };
assert.equal(second.uploads.newFiles, 1, 'only the new photo is copied');
const snaps = await listUploadsSnapshots(h.ctx);
assert.equal(snaps.length, 2);
assert.match(snaps[0]!.name, UPLOADS_SNAPSHOT);
assert.equal(snaps[0]!.files, 2);
await h.ctx.settings.set('backup_nightly', 'false');
assert.deepEqual(await runBackupJob(h.ctx), { skipped: true });
});
it('in the admin: Back up now and a download, audited, for an Owner or Church admin only', async () => {
const { h } = await setup();
useDumperForTest(dumpOf('-- from the admin\n'));
const owner = await signInAs(h, { sub: PASTOR, name: 'Pastor Sam', roles: ['owner'] }, true);
const coord = await signInAs(h, { sub: COORD, name: 'Lerato', roles: ['prayer_coordinator'] }, true);
assert.equal((await request(h.app).get('/api/v1/admin/backups').set('Cookie', cookieHeader(coord))).status, 403);
const made = await request(h.app).post('/api/v1/admin/backups/run').set('Cookie', cookieHeader(owner)).set('Origin', ORIGIN).send({});
assert.equal(made.status, 200);
const list = await request(h.app).get('/api/v1/admin/backups').set('Cookie', cookieHeader(owner));
assert.equal(list.body.items[0].filename, made.body.filename);
const file = await request(h.app).get(`/api/v1/admin/backups/${made.body.filename}/download`).set('Cookie', cookieHeader(owner)).buffer(true).parse((res, cb) => {
const chunks: Buffer[] = [];
res.on('data', (c: Buffer) => chunks.push(c));
res.on('end', () => cb(null, Buffer.concat(chunks)));
});
assert.equal(file.status, 200);
assert.equal(zlib.gunzipSync(file.body as Buffer).toString(), '-- from the admin\n');
const actions = [...h.db.tables.get('auditLog')!.values()].map((r) => r.action);
assert.ok(actions.includes('backup_made') && actions.includes('backup_downloaded'));
assert.equal((await request(h.app).put('/api/v1/admin/backups/settings').set('Cookie', cookieHeader(owner)).set('Origin', ORIGIN).send({ retain: 0 })).status, 400);
});
});
@@ -0,0 +1,16 @@
import type { Metadata } from "next";
import { AdminBackups } from "@/components/admin/AdminBackups";
import { requireAdmin } from "@/lib/admin";
export const metadata: Metadata = { title: "Backups · Admin", robots: { index: false, follow: false } };
/** Settings → Backups (APP-1.0-PLAN §10): Owner and Church admin. */
export default async function BackupsPage() {
const { app } = await requireAdmin([]);
return (
<div className="space-y-6">
<h1 className="text-2xl font-semibold">Backups</h1>
<AdminBackups timezone={app.timezone} />
</div>
);
}
@@ -0,0 +1,98 @@
"use client";
import { useCallback, useEffect, useState } from "react";
import { Download } from "lucide-react";
import { adminCall, Field, input, Notice, Panel, type Msg } from "./kit";
type Snapshot = { name: string; createdAt: string; files: number; bytes: number; newFiles: number; newBytes: number };
type BackupList = {
items: { filename: string; size: number; createdAt: string }[]; nightly: boolean; retain: number; lastError: string | null;
uploads: { enabled: boolean; lastError: string | null; items: Snapshot[] };
};
const size = (n: number) => (n < 1024 ? `${n} B` : n < 1024 * 1024 ? `${(n / 1024).toFixed(1)} KB` : `${(n / (1024 * 1024)).toFixed(1)} MB`);
/**
* Settings → Backups (APP-1.0-PLAN §10, as Accounts', Events' and the Website's): the database
* backups on this server, every night and before every update, and snapshots of the uploaded
* images. Back up now, download one, how many to keep. A backup holds every prayer request: keep
* a download somewhere safe, and delete it when you're done.
*/
export function AdminBackups({ timezone }: { timezone: string }) {
const [d, setD] = useState<BackupList | null>(null);
const [msg, setMsg] = useState<Msg>(null);
const [busy, setBusy] = useState(false);
const [form, setForm] = useState<{ nightly: boolean; retain: string; uploads: boolean } | null>(null);
const load = useCallback(() => {
adminCall<BackupList>("GET", "/backups").then((r) => {
if (!r.ok) return setMsg({ kind: "error", text: r.error });
setD(r.data);
setForm({ nightly: r.data.nightly, retain: String(r.data.retain), uploads: r.data.uploads.enabled });
});
}, []);
useEffect(load, [load]);
const when = (iso: string) => new Intl.DateTimeFormat("en-ZA", { timeZone: timezone, dateStyle: "medium", timeStyle: "short" }).format(new Date(iso));
async function backUpNow() {
setBusy(true);
setMsg(null);
const r = await adminCall<{ filename: string; uploadsError: string | null }>("POST", "/backups/run", {});
setBusy(false);
if (!r.ok) return setMsg({ kind: "error", text: r.error });
setMsg(r.data.uploadsError ? { kind: "error", text: `The database was backed up, but the images weren't: ${r.data.uploadsError}` } : { kind: "ok", text: `Backed up: ${r.data.filename}.` });
load();
}
async function save(e: React.FormEvent) {
e.preventDefault();
if (!form) return;
setBusy(true);
const r = await adminCall<{ deleted: number }>("PUT", "/backups/settings", { nightly: form.nightly, retain: Number(form.retain), uploads: form.uploads });
setBusy(false);
if (!r.ok) return setMsg({ kind: "error", text: r.error });
setMsg({ kind: "ok", text: `Saved.${r.data.deleted ? ` ${r.data.deleted} older backups deleted.` : ""}` });
load();
}
if (!d || !form) return <Notice msg={msg} />;
return (
<div className="space-y-6">
<Notice msg={msg} />
<Panel title="The database" aside={<button type="button" className="cca-btn" disabled={busy} onClick={backUpNow}>{busy ? "Backing up…" : "Back up now"}</button>}>
<p className="mb-3 text-sm text-gray-600">Made every night and before every update, and kept on this server. A backup holds everything in the App, prayer requests included: keep a download somewhere safe, and delete it when you&apos;re done with it.</p>
{d.lastError && <p className="mb-3 rounded-md bg-red-50 p-3 text-sm text-red-800">The last backup failed: {d.lastError}</p>}
{d.items.length === 0 ? <p className="text-sm text-gray-600">No backups yet.</p> : (
<ul className="divide-y divide-gray-100 text-sm">
{d.items.map((b) => (
<li key={b.filename} className="flex flex-wrap items-center justify-between gap-2 py-2">
<span><span className="font-mono">{b.filename}</span> <span className="text-gray-500">· {when(b.createdAt)} · {size(b.size)}</span></span>
<a href={`/api/v1/admin/backups/${encodeURIComponent(b.filename)}/download`} className="inline-flex items-center gap-1 font-semibold underline-offset-4 hover:underline"><Download className="h-4 w-4" aria-hidden />Download</a>
</li>
))}
</ul>
)}
</Panel>
<Panel title="Uploaded images">
<p className="mb-3 text-sm text-gray-600">A snapshot after each database backup. Only new images take space: the rest are shared with the snapshot before.</p>
{d.uploads.lastError && <p className="mb-3 rounded-md bg-red-50 p-3 text-sm text-red-800">The last snapshot failed: {d.uploads.lastError}</p>}
{d.uploads.items.length === 0 ? <p className="text-sm text-gray-600">No snapshots yet.</p> : (
<ul className="divide-y divide-gray-100 text-sm">
{d.uploads.items.map((s) => <li key={s.name} className="py-2"><span className="font-mono">{s.name}</span> <span className="text-gray-500">· {when(s.createdAt)} · {s.files} images, {size(s.bytes)} ({s.newFiles} new)</span></li>)}
</ul>
)}
</Panel>
<Panel title="Settings">
<form onSubmit={save} className="space-y-3">
<label className="flex items-center gap-2 text-sm"><input type="checkbox" checked={form.nightly} onChange={(e) => setForm({ ...form, nightly: e.target.checked })} />Back up every night (02:40)</label>
<label className="flex items-center gap-2 text-sm"><input type="checkbox" checked={form.uploads} onChange={(e) => setForm({ ...form, uploads: e.target.checked })} />Snapshot the uploaded images too</label>
<Field label="How many to keep" hint="The oldest are deleted beyond this (1 to 365)." className="max-w-xs"><input type="number" min={1} max={365} className={input} value={form.retain} onChange={(e) => setForm({ ...form, retain: e.target.value })} /></Field>
<button type="submit" className="cca-btn" disabled={busy}>Save</button>
</form>
</Panel>
</div>
);
}