210 lines
8.4 KiB
TypeScript
210 lines
8.4 KiB
TypeScript
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
|
|
"stores",
|
|
"store_aisles",
|
|
"dishes",
|
|
"dish_ingredients",
|
|
"dish_steps",
|
|
"dish_translations",
|
|
"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
|
|
] as const;
|
|
|
|
/** Bewusst nicht im Abzug, je mit Grund. */
|
|
export const EXCLUDED: Record<string, string> = {
|
|
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",
|
|
ingredients: "kommt aus db/seed mit festen Kennungen (scripts/seed.mjs), nicht aus dem Haushalt",
|
|
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",
|
|
};
|
|
|
|
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<string, Record<string, unknown>[]> }[];
|
|
};
|
|
|
|
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<Backup> {
|
|
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<string, Record<string, unknown>[]> = {};
|
|
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`);
|
|
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<string[]> {
|
|
try {
|
|
return (await readdir(backupDir())).filter((f) => /^lunch-\d{8}-\d{6}\.json$/.test(f)).sort();
|
|
} catch {
|
|
return [];
|
|
}
|
|
}
|
|
|
|
export async function latestBackup(): Promise<Backup | null> {
|
|
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<string | null> {
|
|
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<void> {
|
|
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 }));
|
|
}
|
|
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();
|
|
}
|
|
}
|