import "server-only"; import { createHash } from "node:crypto"; import { chmod, mkdir, readdir, readFile, rm, writeFile } from "node:fs/promises"; import path from "node:path"; import { pool, withAuth, withHousehold } from "@/lib/db"; // Sicherung nach /app/data (Muster Rocket backend/app/sicherung.py). // // Eine Deinstallation löscht auf Olares die Datenbank, /app/data überlebt. // Deshalb liegt hier nach jeder Änderung (Prüfung alle fünf Minuten), // spätestens alle sechs Stunden, ein vollständiger Abzug; die letzten 14 // bleiben. Eine leere Datenbank bietet ihn bei der Einrichtung zum // Zurückspielen an (app/api/auth/setup/restore). // // **Jede neue Tabelle gehört in TABLES oder mit Grund in EXCLUDED** — // tests/backup.test.ts bricht sonst. /** Haushaltstabellen in der Reihenfolge ihrer Fremdschlüssel. */ export const TABLES = [ "households", "members", "passkeys", "invitations", "kid_devices", // nur Hashes; nach dem Zurückspielen gilt das Tablet weiter "ingredients", // nur die eigenen des Haushalts (WHERE unten); die globalen kommen aus db/seed "household_products", "household_pack_sizes", "stores", "store_aisles", "dishes", "dish_ingredients", "dish_steps", "dish_translations", "dish_photos", // Pfade; die Dateien liegen ohnehin unter /app/data/fotos "rounds", "wishes", "slots", "shopping_items", "pantry_staples", "receipts", "receipt_lines", "ingredient_aliases", "price_points", "ratings", "kudos", "helper_points", "achievements", "household_ai", // Schlüssel verschlüsselt: gehört mit tresor.key zusammen "household_mail", // ebenso: Resend-Schlüssel verschlüsselt (26.11.40) ] as const; /** Tabellen, die globale und eigene Zeilen mischen: nur die eigenen in den Abzug. */ const ONLY_OWN: Record = { ingredients: "where t.household_id is not null" }; /** Bewusst nicht im Abzug, je mit Grund. */ export const EXCLUDED: Record = { instance: "eigene Zeile im Abzug (box-weit, nicht je Haushalt)", sessions: "kurzlebig; nach dem Zurückspielen meldet sich jede Person mit ihrem Passkey neu an", auth_challenges: "lebt fünf Minuten", auth_attempts: "Bremse, lebt einen Tag", mail_tokens: "Einmal-Links aus der Mail, gelten höchstens einen Tag", schema_migrations: "gehört zur Datenbank, nicht zu den Daten", starter_dishes: "Vorlage aus db/seed, wird bei jedem Start eingespielt", starter_dish_ingredients: "Vorlage aus db/seed", starter_dish_steps: "Vorlage aus db/seed", store_chains: "Vorlage aus db/seed", chain_aisles: "Vorlage aus db/seed", default_prices: "Richtpreise aus db/seed/prices.de.json", }; const FORMAT = 1; const KEEP = 14; const MAX_AGE_MS = 6 * 60 * 60 * 1000; export type Backup = { format: number; createdAt: string; schema: string; hash: string; instance: { origin: string; rp_id: string; created_at: string } | null; households: { id: string; tables: Record[]> }[]; }; function backupDir(): string { return path.join(process.env.APP_DATA_DIR ?? path.join(process.cwd(), ".data"), "sicherungen"); } /** Liest alles: Haushalte über die Anmeldesicht, je Haushalt mit seiner eigenen Sicht. */ export async function createBackup(): Promise { const { instance, householdIds, schema } = await withAuth(async (client) => { const instance = (await client.query("select origin, rp_id, created_at from instance")).rows[0] ?? null; const householdIds = (await client.query<{ id: string }>("select id from households order by created_at, id")).rows.map((r) => r.id); const schema = (await client.query("select max(name) as name from schema_migrations")).rows[0]?.name ?? ""; return { instance, householdIds, schema }; }); const households = []; for (const id of householdIds) { const tables = await withHousehold(id, async (client) => { const out: Record[]> = {}; for (const table of TABLES) { // to_jsonb hält bytea als \x…-Text; jsonb_populate_recordset wandelt beim Zurückspielen zurück. const { rows } = await client.query( `select coalesce(jsonb_agg(to_jsonb(t) order by to_jsonb(t)::text), '[]'::jsonb) as rows from ${table} t ${ONLY_OWN[table] ?? ""}`, ); out[table] = rows[0].rows; } return out; }); households.push({ id, tables }); } const body = { format: FORMAT, schema, instance, households }; const hash = createHash("sha256").update(JSON.stringify(body)).digest("hex"); return { ...body, createdAt: new Date().toISOString(), hash }; } async function backupFiles(): Promise { try { return (await readdir(backupDir())).filter((f) => /^lunch-\d{8}-\d{6}\.json$/.test(f)).sort(); } catch { return []; } } export async function latestBackup(): Promise { const files = await backupFiles(); const last = files.at(-1); if (!last) return null; try { return JSON.parse(await readFile(path.join(backupDir(), last), "utf8")) as Backup; } catch { return null; } } function stamp(date: Date): string { const p = (n: number) => String(n).padStart(2, "0"); return `${date.getUTCFullYear()}${p(date.getUTCMonth() + 1)}${p(date.getUTCDate())}-${p(date.getUTCHours())}${p(date.getUTCMinutes())}${p(date.getUTCSeconds())}`; } /** * Schreibt einen Abzug, wenn sich etwas geändert hat oder der letzte älter als * sechs Stunden ist. Gibt den Dateinamen zurück oder null, wenn nichts zu tun war. */ export async function backupIfChanged(now = new Date()): Promise { const backup = await createBackup(); if (!backup.instance) return null; // noch nicht eingerichtet: nichts zu sichern const last = await latestBackup(); if (last && last.hash === backup.hash && now.getTime() - Date.parse(last.createdAt) < MAX_AGE_MS) return null; const dir = backupDir(); await mkdir(dir, { recursive: true, mode: 0o700 }); const name = `lunch-${stamp(now)}.json`; await writeFile(path.join(dir, name), JSON.stringify({ ...backup, createdAt: now.toISOString() }), { mode: 0o600 }); await chmod(path.join(dir, name), 0o600); const files = await backupFiles(); for (const old of files.slice(0, Math.max(0, files.length - KEEP))) await rm(path.join(dir, old), { force: true }); return name; } /** Was im neuesten Abzug steht — für die Einrichtungsseite. */ export async function backupSummary(): Promise<{ createdAt: string; households: string[]; members: number; origin: string } | null> { const backup = await latestBackup(); if (!backup?.instance) return null; return { createdAt: backup.createdAt, households: backup.households.map((h) => String(h.tables.households?.[0]?.name ?? "")), members: backup.households.reduce((n, h) => n + (h.tables.members?.length ?? 0), 0), origin: backup.instance.origin, }; } /** * Spielt einen Abzug in eine leere Datenbank zurück — alles in einer * Transaktion, ganz oder gar nicht. Spalten, die der Abzug nicht kennt * (älteres Schema), bekommen ihren Vorgabewert. */ export async function restoreBackup(backup: Backup): Promise { if (backup.format !== FORMAT || !backup.instance) throw new Error("unsupported backup"); const client = await pool.connect(); try { await client.query("begin"); await client.query("select set_config('app.auth', 'on', true)"); if ((await client.query("select 1 from instance")).rowCount) throw new Error("database is not empty"); await client.query("insert into instance (origin, rp_id, created_at) values ($1, $2, $3)", [ backup.instance.origin, backup.instance.rp_id, backup.instance.created_at, ]); for (const household of backup.households) { await client.query("select set_config('app.household_id', $1, true)", [household.id]); let createdBy: unknown = null; for (const table of TABLES) { let rows = household.tables[table] ?? []; if (!rows.length) continue; if (table === "households") { // created_by zeigt auf members, die erst danach kommen. createdBy = rows[0]?.created_by ?? null; rows = rows.map((r) => ({ ...r, created_by: null })); } if (table === "household_pack_sizes" && rows.some((r) => !r.unit)) { // Abzüge vor 26.11.49 kennen nur das Gebinde der Zutat — dessen Maß nachtragen. const kinds = new Map( (await client.query("select id, pack_kind from ingredients where pack_kind is not null")).rows.map((r) => [r.id as string, r.pack_kind as string]), ); rows = rows.map((r) => (r.unit ? r : { ...r, unit: kinds.get(r.ingredient_id as string) ?? null })).filter((r) => r.unit); if (!rows.length) continue; } const existing = ( await client.query<{ column_name: string }>( "select column_name from information_schema.columns where table_schema = 'public' and table_name = $1", [table], ) ).rows.map((r) => r.column_name); const columns = existing.filter((c) => c in rows[0]!).map((c) => `"${c}"`).join(", "); await client.query(`insert into ${table} (${columns}) select ${columns} from jsonb_populate_recordset(null::${table}, $1)`, [ JSON.stringify(rows), ]); } if (createdBy) await client.query("update households set created_by = $1 where id = $2", [createdBy, household.id]); } await client.query("commit"); } catch (error) { await client.query("rollback").catch(() => undefined); throw error; } finally { client.release(); } }