import { execFileSync } from "node:child_process"; import { randomUUID } from "node:crypto"; import { mkdtempSync, readdirSync, statSync } from "node:fs"; import { tmpdir } from "node:os"; import path from "node:path"; import pg from "pg"; import { afterAll, beforeAll, describe, expect, it, vi } from "vitest"; import { seedHousehold, seedIngredient } from "./fixture"; vi.mock("server-only", () => ({})); // Die Sicherung (lib/backup.ts) in einer eigenen, frisch migrierten Datenbank: // Wache „jede Tabelle im Abzug oder ausdrücklich nicht“ und die Rundreise // Abzug → leere Datenbank → zurückspielen → derselbe Inhalt. const url = process.env.TEST_DATABASE_URL; describe.skipIf(!url)("backup", () => { const name = `lunch_backup_${randomUUID().slice(0, 8)}`; const admin = new pg.Client({ connectionString: url }); const target = url ? url.replace(/\/[^/?]+(\?|$)/, `/${name}$1`) : ""; let client: pg.Client; let backup: typeof import("@/lib/backup"); let db: typeof import("@/lib/db"); const dir = mkdtempSync(path.join(tmpdir(), "lunch-backup-")); beforeAll(async () => { await admin.connect(); await admin.query(`create database ${name}`); execFileSync("node", ["scripts/migrate.mjs"], { env: { ...process.env, DATABASE_URL: target, MIGRATE_ATTEMPTS: "3" }, stdio: "ignore" }); process.env.DATABASE_URL = target; process.env.APP_DATA_DIR = dir; db = await import("@/lib/db"); backup = await import("@/lib/backup"); client = new pg.Client({ connectionString: target }); await client.connect(); const ingredient = await seedIngredient(client); await seedHousehold(client, randomUUID(), ingredient); await seedHousehold(client, randomUUID(), ingredient); await client.query("begin"); await client.query("select set_config('app.auth', 'on', true)"); await client.query("insert into instance (origin, rp_id) values ('https://lunch.example', 'lunch.example')"); await client.query("commit"); }); afterAll(async () => { await client?.end(); await db?.pool.end(); await admin.query(`drop database if exists ${name}`); await admin.end(); }); it("every table is in the backup or excluded with a reason", async () => { const { rows } = await client.query<{ tablename: string }>("select tablename from pg_tables where schemaname = 'public'"); const covered = new Set([...backup.TABLES, ...Object.keys(backup.EXCLUDED)]); expect(rows.map((r) => r.tablename).filter((t) => !covered.has(t)).sort()).toEqual([]); for (const t of backup.TABLES) expect(t in backup.EXCLUDED).toBe(false); }); it("writes a backup only when something changed, readable only by the app", async () => { const first = await backup.backupIfChanged(new Date("2026-11-06T10:00:00Z")); expect(first).toBe("lunch-20261106-100000.json"); expect(statSync(path.join(dir, "sicherungen", first!)).mode & 0o777).toBe(0o600); expect(await backup.backupIfChanged(new Date("2026-11-06T10:05:00Z"))).toBeNull(); // Nach sechs Stunden ohne Änderung trotzdem ein neuer Abzug. expect(await backup.backupIfChanged(new Date("2026-11-06T16:01:00Z"))).toBe("lunch-20261106-160100.json"); expect(readdirSync(path.join(dir, "sicherungen"))).toHaveLength(2); }); it("restores into an empty database with the same content", async () => { const before = await backup.createBackup(); expect(before.households).toHaveLength(2); expect((await backup.backupSummary())?.members).toBe(2); // Was eine Deinstallation tut: Die Datenbank ist leer, /app/data bleibt. await client.query("begin"); await client.query("select set_config('app.auth', 'on', true)"); for (const h of before.households) { await client.query("select set_config('app.household_id', $1, true)", [h.id]); await client.query("delete from households where id = $1", [h.id]); } await client.query("delete from instance"); await client.query("commit"); expect((await backup.createBackup()).households).toHaveLength(0); await backup.restoreBackup((await backup.latestBackup())!); const after = await backup.createBackup(); expect(after.hash).toBe(before.hash); await expect(backup.restoreBackup((await backup.latestBackup())!)).rejects.toThrow(/not empty/); }); });