From da54f700717c6e2da02301b4c899379e0799f333 Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?Kai=20B=C3=B6hm?= Date: Fri, 6 Nov 2026 20:05:14 +0000 Subject: [PATCH] Data model, two-household test, backup to /app/data (26.11.3) Migration 0003 adds the concept's tables: dishes with ingredients, steps and translations, stores and aisles, rounds, wishes, slots, shopping items, pantry staples, receipts and lines, ingredient aliases, price points, ratings, kudos, helper points, achievements, plus global canonical ingredients (readable by all, writable only in migrations). Every household table carries household_id with FORCE RLS, and references inside a household are paired foreign keys so a row can never point at another household's data (E-0007). Roles follow the concept: admin, member, child, guest; households.created_by marks who set up (E-0008). The two-household test seeds every table for two households and reads each one against the other. lib/backup.ts writes a backup to /app/data/sicherungen after changes (checked every five minutes, at least every six hours, last 14 kept); an empty database offers it on /einrichten for restore with the setup code. Co-Authored-By: Claude Opus 5.5 Claude-Session: https://claude.ai/code/session_01HUc2nv7rJVU2gp3Bgtha3q --- .github/workflows/ci.yml | 3 +- CLAUDE.md | 26 +- OlaresManifest.yaml | 4 +- app/(app)/mehr/page.tsx | 15 +- app/api/auth/invite/options/route.ts | 9 +- app/api/auth/invite/verify/route.ts | 12 +- app/api/auth/recovery/options/route.ts | 9 +- app/api/auth/setup/restore/route.ts | 38 +++ app/api/auth/setup/verify/route.ts | 3 +- app/api/household/invitations/route.ts | 13 +- app/api/household/members/remove/route.ts | 13 +- app/einrichten/page.tsx | 18 +- components/auth/restore-form.tsx | 54 ++++ components/more/invite-panel.tsx | 16 +- db/migrations/0003_data_model.sql | 377 ++++++++++++++++++++++ docs/PROJEKTSTART.md | 1 + docs/entscheidungen.md | 37 +++ instrumentation.ts | 7 + lib/auth/invitations.ts | 4 +- lib/auth/schemas.ts | 2 +- lib/auth/session.ts | 2 +- lib/backup-schedule.ts | 23 ++ lib/backup.ts | 202 ++++++++++++ messages/de.json | 27 +- messages/en.json | 27 +- messages/es.json | 27 +- messages/fr.json | 27 +- olares/Chart.yaml | 4 +- olares/OlaresManifest.yaml | 4 +- olares/markt/26.11.3.md | 5 + tests/backup.test.ts | 90 ++++++ tests/fixture.ts | 89 +++++ tests/rls.test.ts | 134 ++++++-- 33 files changed, 1226 insertions(+), 96 deletions(-) create mode 100644 app/api/auth/setup/restore/route.ts create mode 100644 components/auth/restore-form.tsx create mode 100644 db/migrations/0003_data_model.sql create mode 100644 instrumentation.ts create mode 100644 lib/backup-schedule.ts create mode 100644 lib/backup.ts create mode 100644 olares/markt/26.11.3.md create mode 100644 tests/backup.test.ts create mode 100644 tests/fixture.ts diff --git a/.github/workflows/ci.yml b/.github/workflows/ci.yml index 6381a3f..a8ba919 100644 --- a/.github/workflows/ci.yml +++ b/.github/workflows/ci.yml @@ -88,11 +88,12 @@ jobs: run: npm run type-check # Wie auf der Box: Die Migrationen laufen mit der Rolle der App, die + # (createdb nur für die eigene Datenbank von tests/backup.test.ts) # dadurch Eigentümerin der Tabellen wird — kein Superuser. Nur so prüft # der Test mit zwei Haushalten, dass FORCE ROW LEVEL SECURITY greift. - name: database and migrations run: | - PGPASSWORD=postgres psql -U postgres -c "create role lunch login password 'lunch_dev_only';" + PGPASSWORD=postgres psql -U postgres -c "create role lunch login password 'lunch_dev_only' createdb;" PGPASSWORD=postgres psql -U postgres -c "create database lunch owner lunch;" DATABASE_URL="$TEST_DATABASE_URL" MIGRATE_ATTEMPTS=3 npm run migrate # Ein zweiter Lauf darf nichts tun. diff --git a/CLAUDE.md b/CLAUDE.md index 9d1c60f..2a8351d 100644 --- a/CLAUDE.md +++ b/CLAUDE.md @@ -7,9 +7,9 @@ > **Plattform:** Olares One (Kubernetes), Repo und CI auf Gitea — kein Supabase, > kein Vercel (E-0001). Eigene Gestaltung, nicht AImighty (E-0002). > Verteilung über den Markt, Repo öffentlich (E-0005). -> **Status:** 26.11.2 — Arbeitspaket 1 fertig: Gerüst, Chart, CI, Release, Markt, -> eigene Anmeldung mit Passkeys (E-0006), Entrance `public`. Als Nächstes -> Arbeitspaket 2 (`docs/PROJEKTSTART.md`). +> **Status:** 26.11.3 — Arbeitspakete 1 und 2 fertig: Anmeldung mit Passkeys, +> Datenmodell (24 Tabellen, E-0007/E-0008), Test mit zwei Haushalten, Sicherung nach +> `/app/data`. Als Nächstes Arbeitspaket 3, Seed (`docs/PROJEKTSTART.md`). > **Letzte Aktualisierung:** 6. November 2026 Diese Datei ist das Gedächtnis jeder Sitzung. Entscheidungen stehen in @@ -55,10 +55,15 @@ Datenmodells (`households`, `dishes`, `rounds`, `slots`, …). 2. **Mengen** immer in Basiseinheiten speichern (g, ml, Stück), pro Portion; Umrechnung nur in `lib/units.ts`, Hochrechnen und Zusammenfassen in `lib/aggregate.ts`. -3. **Jede neue Tabelle bekommt RLS vor dem ersten Insert** — mit - `FORCE ROW LEVEL SECURITY` und der Policy „Mitglied des Haushalts“ über - `current_setting('app.household_id')`. Der Test mit zwei Haushalten liest - jede Tabelle gegen (E-0001). +3. **Jede neue Tabelle** (E-0007): `household_id`, Verweise als paarweise + Fremdschlüssel `(x_id, household_id)`, RLS mit **FORCE** und der Policy + „Mitglied des Haushalts“ (`household_id = app_household_id()`) — in derselben + Migration, vor dem ersten Insert. Dazu eine Zeile in `tests/fixture.ts` und ein + Eintrag in `lib/backup.ts` (`TABLES`, oder mit Grund in `EXCLUDED`); der Test mit + zwei Haushalten und die Wache der Sicherung brechen sonst. Migrationen laufen + ebenfalls unter FORCE: Bestandsdaten nur mit gesetztem Haushalt ändern. + Seed-Daten in globalen Tabellen (`ingredients`) mit **festen Kennungen** und + `set_config('app.maintenance', 'on', true)` — die Sicherung verweist auf sie. 4. **KI:** Ausgaben nur über ein Zod-Schema; was nicht validiert, verwerfen und einmal wiederholen. Kein Modellaufruf aus dem Browser. Prompts versioniert unter `prompts/` mit Testbons und Testrezepten. Die KI schlägt vor, ein Mensch @@ -123,8 +128,11 @@ gelernt: 6. **Ein Upgrade friert `values.yaml` ein.** Image-Tag aus `.Chart.AppVersion`, `values.yaml` mit `tag: ""`; neue Schlüssel über `(default (dict) .Values.x).y`. 7. **Eine Deinstallation löscht die Datenbank**, `/app/data` überlebt. Fotos - dort, dazu eine Sicherung der Datenbank nach `/app/data` (Muster Rocket - `app/sicherung.py`); jede neue Tabelle muss in die Sicherung. + dort; die Sicherung (`lib/backup.ts`, Takt in `instrumentation.ts`) legt nach + jeder Änderung (Prüfung alle 5 Minuten), spätestens alle 6 Stunden, einen Abzug + nach `/app/data/sicherungen/` (0600, die letzten 14). Eine leere Datenbank bietet + ihn auf `/einrichten` zum Zurückspielen an, mit dem Einrichtungscode, unter der + alten Adresse. 8. **Keine Helm-Hooks, kein `.Files.Get`.** Migrationen als eingebettete ConfigMap plus Vorlauf-Container mit Wiederholschleife (Muster Rocket `scripts/regen-migrations.py`, `olares/templates/configmap-migrations.yaml`). diff --git a/OlaresManifest.yaml b/OlaresManifest.yaml index 5d3716d..2a8ccee 100644 --- a/OlaresManifest.yaml +++ b/OlaresManifest.yaml @@ -21,7 +21,7 @@ metadata: title: What's cooking? description: The family decides together what's for dinner — and the shopping list writes itself. Runs entirely on your own box. icon: https://git.aimighty.olares.de/aimighty/bilder/raw/branch/main/lunch/icon.png - version: 26.11.2 + version: 26.11.3 categories: - Applications @@ -61,7 +61,7 @@ permission: appData: true spec: - versionName: '26.11.2' + versionName: '26.11.3' featuredImage: https://git.aimighty.olares.de/aimighty/bilder/raw/branch/main/lunch/icon.png promoteImage: diff --git a/app/(app)/mehr/page.tsx b/app/(app)/mehr/page.tsx index 2c6dd6a..9ef3575 100644 --- a/app/(app)/mehr/page.tsx +++ b/app/(app)/mehr/page.tsx @@ -19,14 +19,15 @@ export default async function MorePage() { const session = await requireSession(); const t = await getTranslations("more"); const locale = await getLocale(); - const { members, passkeys } = await withHousehold(session.householdId, async (client) => { + const { members, passkeys, founder } = await withHousehold(session.householdId, async (client) => { const members = (await client.query("select id, display_name, role from members order by created_at")).rows; + const founder = (await client.query("select created_by from households")).rows[0]?.created_by as string | null; const passkeys = ( await client.query("select id, label, created_at, last_used_at from passkeys where member_id = $1 order by created_at", [ session.memberId, ]) ).rows; - return { members, passkeys }; + return { members, passkeys, founder }; }); const date = new Intl.DateTimeFormat(locale, { dateStyle: "medium" }); @@ -44,15 +45,19 @@ export default async function MorePage() { {m.id === session.memberId ? ({t("you")}) : null} - {t(`roles.${m.role}`)} - {session.role === "owner" && m.role !== "owner" ? : null} + + {m.id === founder ? t("founder") : t(`roles.${m.role}`)} + + {session.role === "admin" && m.id !== founder && m.id !== session.memberId ? ( + + ) : null} ))} - {session.role === "owner" ? ( + {session.role === "admin" ? (
diff --git a/app/api/auth/invite/options/route.ts b/app/api/auth/invite/options/route.ts index 0835cf4..a382e6b 100644 --- a/app/api/auth/invite/options/route.ts +++ b/app/api/auth/invite/options/route.ts @@ -40,7 +40,14 @@ export async function POST(request: Request) { name = body.data.name ?? invitation.displayName ?? ""; } if (!name) return fail("invalid", 400); - const context = { invitationId: invitation.id, memberId, isNew: !invitation.memberId, name, householdId: invitation.householdId }; + const context = { + invitationId: invitation.id, + memberId, + isNew: !invitation.memberId, + name, + householdId: invitation.householdId, + role: invitation.role, + }; return json(await registrationOptions(client, instance, { id: memberId, name }, "invite", context, exclude)); }); } diff --git a/app/api/auth/invite/verify/route.ts b/app/api/auth/invite/verify/route.ts index cc119ae..f99bb26 100644 --- a/app/api/auth/invite/verify/route.ts +++ b/app/api/auth/invite/verify/route.ts @@ -9,7 +9,14 @@ import { LOCALE_COOKIE, resolveLocale } from "@/lib/locale"; export const dynamic = "force-dynamic"; -type InviteContext = { invitationId: string; memberId: string; isNew: boolean; name: string; householdId: string }; +type InviteContext = { + invitationId: string; + memberId: string; + isNew: boolean; + name: string; + householdId: string; + role: "admin" | "member"; +}; // Einladung annehmen, Schritt 2: Passkey prüfen, die Einladung verbrauchen // (genau einmal), Person anlegen, falls neu, Sitzung beginnen. @@ -36,10 +43,11 @@ export async function POST(request: Request) { if (used.rowCount !== 1) return fail("invitation", 410); if (ctx.isNew) { - await client.query("insert into members (id, household_id, display_name, role, locale) values ($1, $2, $3, 'adult', $4)", [ + await client.query("insert into members (id, household_id, display_name, role, locale) values ($1, $2, $3, $4, $5)", [ ctx.memberId, ctx.householdId, ctx.name, + ctx.role === "admin" ? "admin" : "member", resolveLocale((await cookies()).get(LOCALE_COOKIE)?.value, request.headers.get("accept-language")), ]); } diff --git a/app/api/auth/recovery/options/route.ts b/app/api/auth/recovery/options/route.ts index 528ac82..c6837d9 100644 --- a/app/api/auth/recovery/options/route.ts +++ b/app/api/auth/recovery/options/route.ts @@ -26,7 +26,14 @@ export async function POST(request: Request) { if (!body.success) return fail("invalid", 400); if (!(await recoveryCodeMatches(body.data.code))) return fail("code", 401); - const { rows } = await client.query("select id, household_id, display_name from members where role = 'owner' order by created_at limit 1"); + // Wer eingerichtet hat (households.created_by); fehlt die Person, der älteste Admin. + const { rows } = await client.query( + `select m.id, m.household_id, m.display_name + from households h + join members m on m.household_id = h.id and m.role = 'admin' + order by (m.id = h.created_by) desc, m.created_at + limit 1`, + ); const owner = rows[0]; if (!owner) return fail("unknown", 500); const existing = await client.query("select id, transports from passkeys where member_id = $1", [owner.id]); diff --git a/app/api/auth/setup/restore/route.ts b/app/api/auth/setup/restore/route.ts new file mode 100644 index 0000000..a0a0d97 --- /dev/null +++ b/app/api/auth/setup/restore/route.ts @@ -0,0 +1,38 @@ +import { z } from "zod"; +import { latestBackup, restoreBackup } from "@/lib/backup"; +import { removeSetupCode, setupCodeMatches } from "@/lib/auth/codes"; +import { withAuth } from "@/lib/db"; +import { fail, json, readJson } from "@/lib/auth/http"; +import { browserOrigin, clientIp } from "@/lib/auth/request"; +import { tooManyAttempts } from "@/lib/auth/throttle"; +import { loadInstance } from "@/lib/auth/webauthn"; + +export const dynamic = "force-dynamic"; + +// Einrichtung aus der Sicherung: Nur in eine leere Datenbank, nur mit dem +// Einrichtungscode — dieselbe Wand wie bei der Neueinrichtung. Danach melden +// sich alle mit ihren vorhandenen Passkeys an, unter der alten Adresse. +export async function POST(request: Request) { + const body = z.object({ code: z.string().min(1).max(64) }).safeParse(await readJson(request)); + const gate = await withAuth(async (client) => { + if (await loadInstance(client)) return fail("alreadySetUp", 409); + if ( + (await tooManyAttempts(client, `setup:${clientIp(request)}`, 10, 15)) || + (await tooManyAttempts(client, "setup:*", 100, 60)) + ) { + return fail("tooMany", 429); + } + if (!body.success) return fail("invalid", 400); + if (!(await setupCodeMatches(body.data.code))) return fail("code", 401); + return null; + }); + if (gate) return gate; + + const backup = await latestBackup(); + if (!backup?.instance) return fail("noBackup", 404); + // Passkeys hängen an der Adresse der Sicherung; unter einer anderen ginge danach niemand hinein. + if (browserOrigin(request)?.origin !== backup.instance.origin) return json({ error: "otherOrigin", origin: backup.instance.origin }, 409); + await restoreBackup(backup); + await removeSetupCode(); + return json({ ok: true }); +} diff --git a/app/api/auth/setup/verify/route.ts b/app/api/auth/setup/verify/route.ts index 2fc3d14..af7a3d0 100644 --- a/app/api/auth/setup/verify/route.ts +++ b/app/api/auth/setup/verify/route.ts @@ -32,12 +32,13 @@ export async function POST(request: Request) { await client.query("select set_config('app.household_id', $1, true)", [ctx.householdId]); await client.query("insert into instance (origin, rp_id) values ($1, $2)", [instance.origin, instance.rpId]); await client.query("insert into households (id, name) values ($1, $2)", [ctx.householdId, ctx.household]); - await client.query("insert into members (id, household_id, display_name, role, locale) values ($1, $2, $3, 'owner', $4)", [ + await client.query("insert into members (id, household_id, display_name, role, locale) values ($1, $2, $3, 'admin', $4)", [ ctx.memberId, ctx.householdId, ctx.name, locale, ]); + await client.query("update households set created_by = $1 where id = $2", [ctx.memberId, ctx.householdId]); await client.query( `insert into passkeys (id, member_id, household_id, public_key, counter, transports, device_type, backed_up, label) values ($1, $2, $3, $4, $5, $6, $7, $8, $9)`, diff --git a/app/api/household/invitations/route.ts b/app/api/household/invitations/route.ts index 092b3b5..37b0fb2 100644 --- a/app/api/household/invitations/route.ts +++ b/app/api/household/invitations/route.ts @@ -7,8 +7,8 @@ import { loadInstance } from "@/lib/auth/webauthn"; export const dynamic = "force-dynamic"; -// Einladungslink: eine neue Person (nur wer eingerichtet hat) oder ein -// weiteres eigenes Gerät (jede erwachsene Person). Der Link wird einmal +// Einladungslink: eine neue Person als Mitglied oder Admin (nur Admins) oder +// ein weiteres eigenes Gerät (jede erwachsene Person). Der Link wird einmal // gezeigt; gespeichert ist nur sein Hash. const DAYS = { person: 7, device: 1 } as const; @@ -19,20 +19,21 @@ export async function POST(request: Request) { if (!instance || !sameOrigin(request, instance.origin)) return fail("origin", 403); const body = createInvitationBody.safeParse(await readJson(request)); if (!body.success) return fail("invalid", 400); - if (body.data.kind === "person" && session.role !== "owner") return fail("forbidden", 403); - if (session.role === "child") return fail("forbidden", 403); + if (body.data.kind === "person" && session.role !== "admin") return fail("forbidden", 403); + if (session.role === "child" || session.role === "guest") return fail("forbidden", 403); const token = randomToken(); const data = body.data; await withHousehold(session.householdId, (client) => client.query( - `insert into invitations (household_id, token_hash, member_id, display_name, created_by, expires_at) - values ($1, $2, $3, $4, $5, now() + make_interval(days => $6))`, + `insert into invitations (household_id, token_hash, member_id, display_name, role, created_by, expires_at) + values ($1, $2, $3, $4, $5, $6, now() + make_interval(days => $7))`, [ session.householdId, hashToken(token), data.kind === "device" ? session.memberId : null, data.kind === "person" ? data.name : null, + data.kind === "person" ? data.role : "member", session.memberId, DAYS[data.kind], ], diff --git a/app/api/household/members/remove/route.ts b/app/api/household/members/remove/route.ts index 702f5d4..63a9fda 100644 --- a/app/api/household/members/remove/route.ts +++ b/app/api/household/members/remove/route.ts @@ -6,18 +6,23 @@ import { loadInstance } from "@/lib/auth/webauthn"; export const dynamic = "force-dynamic"; -// Eine Person aus dem Haushalt nehmen — nur wer eingerichtet hat, nie sich -// selbst. Passkeys, Sitzungen und offene Einladungen gehen mit (on delete cascade). +// Eine Person aus dem Haushalt nehmen — nur Admins, nie sich selbst und nie +// die Person, die eingerichtet hat. Passkeys, Sitzungen und offene Einladungen gehen mit (on delete cascade). export async function POST(request: Request) { const session = await getSession(); if (!session) return fail("signedOut", 401); const instance = await withAuth(loadInstance); if (!instance || !sameOrigin(request, instance.origin)) return fail("origin", 403); - if (session.role !== "owner") return fail("forbidden", 403); + if (session.role !== "admin") return fail("forbidden", 403); const body = z.object({ id: z.string().uuid() }).safeParse(await readJson(request)); if (!body.success || body.data.id === session.memberId) return fail("invalid", 400); return withHousehold(session.householdId, async (client) => { - const removed = await client.query("delete from members where id = $1 and role <> 'owner'", [body.data.id]); + // Wer eingerichtet hat, bleibt (Ziel des Rückwegs); jede andere Person, + // auch ein weiterer Admin, kann gehen. + const removed = await client.query( + "delete from members where id = $1 and id is distinct from (select created_by from households where id = $2)", + [body.data.id, session.householdId], + ); return removed.rowCount === 1 ? new Response(null, { status: 204 }) : fail("invalid", 404); }); } diff --git a/app/einrichten/page.tsx b/app/einrichten/page.tsx index 124a1ab..a2f3d4d 100644 --- a/app/einrichten/page.tsx +++ b/app/einrichten/page.tsx @@ -1,7 +1,9 @@ import { redirect } from "next/navigation"; -import { getTranslations } from "next-intl/server"; +import { getLocale, getTranslations } from "next-intl/server"; import { AuthShell } from "@/components/auth/auth-shell"; +import { RestoreForm } from "@/components/auth/restore-form"; import { SetupForm } from "@/components/auth/setup-form"; +import { backupSummary } from "@/lib/backup"; import { isSetUp } from "@/lib/auth/session"; import { ensureSetupCode } from "@/lib/auth/codes"; @@ -10,9 +12,19 @@ export const dynamic = "force-dynamic"; export default async function SetupPage() { if (await isSetUp()) redirect("/anmelden"); await ensureSetupCode(); - const t = await getTranslations("auth.setup"); + const t = await getTranslations("auth"); + const summary = await backupSummary(); + const date = summary + ? new Intl.DateTimeFormat(await getLocale(), { dateStyle: "long", timeStyle: "short" }).format(new Date(summary.createdAt)) + : ""; return ( - + + {summary ? ( + <> + +

{t("restore.or")}

+ + ) : null}
); diff --git a/components/auth/restore-form.tsx b/components/auth/restore-form.tsx new file mode 100644 index 0000000..4af97c0 --- /dev/null +++ b/components/auth/restore-form.tsx @@ -0,0 +1,54 @@ +"use client"; + +import { useRouter } from "next/navigation"; +import { useTranslations } from "next-intl"; +import { useState } from "react"; +import { Button } from "@/components/ui/button"; +import { Input } from "@/components/ui/input"; +import { Label } from "@/components/ui/label"; +import { ErrorNotice } from "@/components/ui/notice"; + +type Summary = { createdAt: string; households: string[]; members: number; origin: string }; + +// Auf /einrichten, wenn die Datenbank leer ist, aber eine Sicherung in /app/data liegt. +export function RestoreForm({ summary, date }: { summary: Summary; date: string }) { + const t = useTranslations("auth"); + const router = useRouter(); + const [error, setError] = useState(null); + const [busy, setBusy] = useState(false); + + async function onSubmit(event: React.FormEvent) { + event.preventDefault(); + setBusy(true); + setError(null); + const res = await fetch("/api/auth/setup/restore", { + method: "POST", + headers: { "content-type": "application/json" }, + body: JSON.stringify({ code: new FormData(event.currentTarget).get("restore-code") }), + }); + const data = await res.json().catch(() => ({})); + setBusy(false); + if (res.ok) return router.replace("/anmelden"); + if (data.error === "otherOrigin") setError(t("restore.otherOrigin", { origin: data.origin })); + else setError(t.has(`errors.${data.error}`) ? t(`errors.${data.error}`) : t("errors.unknown")); + } + + return ( +
+

{t("restore.title")}

+

+ {t("restore.summary", { date, households: summary.households.join(", "), members: summary.members })} +

+
+
+ + +
+ {error ? {error} : null} + +
+
+ ); +} diff --git a/components/more/invite-panel.tsx b/components/more/invite-panel.tsx index 90d02ed..1a43bf0 100644 --- a/components/more/invite-panel.tsx +++ b/components/more/invite-panel.tsx @@ -61,8 +61,8 @@ export function InvitePerson() { className="flex flex-col gap-3" onSubmit={async (event) => { event.preventDefault(); - const name = new FormData(event.currentTarget).get("name"); - const result = await create({ kind: "person", name }); + const form = new FormData(event.currentTarget); + const result = await create({ kind: "person", name: form.get("name"), role: form.get("role") }); if (typeof result === "string") setError(result); else { setError(null); @@ -74,6 +74,18 @@ export function InvitePerson() { +
+ {t("inviteRole")} + {(["member", "admin"] as const).map((role) => ( + + ))} +
{error ? {te.has(error) ? te(error) : te("unknown")} : null} {created ? : null} diff --git a/db/migrations/0003_data_model.sql b/db/migrations/0003_data_model.sql new file mode 100644 index 0000000..16c9a46 --- /dev/null +++ b/db/migrations/0003_data_model.sql @@ -0,0 +1,377 @@ +-- 0003_data_model.sql — das Datenmodell aus docs/konzept.md („Datenmodell“). +-- +-- Jede Haushaltstabelle trägt household_id selbst (E-0007) und hat dieselbe +-- Policy „Mitglied des Haushalts“ mit FORCE. Verweise innerhalb des Haushalts +-- laufen über zusammengesetzte Fremdschlüssel (x_id, household_id) — eine +-- Zeile kann so nie auf das Gericht, die Runde oder das Mitglied eines anderen +-- Haushalts zeigen, auch nicht durch einen Fehler im Code. +-- +-- Mengen immer in Basiseinheiten (g, ml, piece), pro Portion. Statuswerte als +-- text mit check statt Enum (E-0008). + +-- Die Migration läuft als Eigentümerin der Tabellen, und FORCE gilt auch für +-- sie: Ohne Haushalt sähe ein UPDATE keine Zeile. Für die Bestandsdaten unten +-- gilt deshalb die Sicht der Anmeldung (app.auth, nur in dieser Transaktion); +-- members, households und invitations lassen sie zu (Migration 0002). +select set_config('app.auth', 'on', true); + +-- ── Rollen wie im Konzept (E-0008) ────────────────────────────────────────── +alter table members drop constraint members_role_check; +update members set role = 'admin' where role = 'owner'; +update members set role = 'member' where role = 'adult'; +alter table members add constraint members_role_check check (role in ('admin', 'member', 'child', 'guest')); +alter table members + add column avatar text, + add column pin_hash text, -- Kinder, Arbeitspaket 5 + add column expires_at timestamptz, -- Gäste: bis wann + add constraint members_id_household_key unique (id, household_id); + +alter table invitations drop constraint invitations_role_check; +update invitations set role = 'member' where role = 'adult'; +alter table invitations alter column role set default 'member'; +alter table invitations add constraint invitations_role_check check (role in ('admin', 'member')); + +-- ── Haushalt: Einstellungen ───────────────────────────────────────────────── +alter table households + add column currency text not null default 'EUR' check (currency ~ '^[A-Z]{3}$'), + add column budget_per_round numeric(10, 2) check (budget_per_round > 0), + add column expensive_per_slots integer not null default 4 check (expensive_per_slots between 1 and 14), + add column tokens_per_round integer not null default 2 check (tokens_per_round between 0 and 10), + add column vetos_per_round integer not null default 1 check (vetos_per_round between 0 and 5), + -- Wer eingerichtet hat: Ziel des Rückwegs (lib/auth, /wiederherstellen). + add column created_by uuid references members (id) on delete set null; + +-- Schreiben in households verlangt den eigenen Haushalt (with check), also je +-- Haushalt einzeln. +do $$ +declare h uuid; +begin + for h in select id from households loop + perform set_config('app.household_id', h::text, true); + update households set created_by = ( + select m.id from members m where m.household_id = h and m.role = 'admin' order by m.created_at limit 1 + ) where id = h; + end loop; + perform set_config('app.household_id', '', true); +end $$; + +-- Darf in Migrationen globale Tabellen schreiben (Seeds, Arbeitspaket 3). +create function app_maintenance() returns boolean + language sql stable + as $$ select coalesce(current_setting('app.maintenance', true), '') = 'on' $$; + +-- ── Kanonische Zutaten (global, nicht je Haushalt) ────────────────────────── +create table ingredients ( + id uuid primary key default gen_random_uuid(), + key text not null unique check (key ~ '^[a-z0-9_]+$'), + category text not null, + default_unit text not null check (default_unit in ('g', 'ml', 'piece')), + names jsonb not null default '{}'::jsonb, -- {"de": "Hackfleisch", "en": …} + synonyms text[] not null default '{}', + -- Für den Vorschlag „Frisches zuerst“: 1 frisch (Fisch, Hack), 2 einige Tage, 3 haltbar. + freshness smallint not null default 3 check (freshness between 1 and 3) +); + +-- ── Gerichte ──────────────────────────────────────────────────────────────── +create table dishes ( + id uuid primary key default gen_random_uuid(), + household_id uuid not null references households (id) on delete cascade, + title text not null check (length(trim(title)) between 1 and 120), + source_locale text not null default 'de' check (source_locale in ('de', 'en', 'fr', 'es')), + source_url text, + photo_path text, + base text check (base in ('pasta', 'rice', 'potato', 'bread', 'grain', 'none')), + tags text[] not null default '{}', + effort_minutes integer check (effort_minutes between 1 and 1440), + is_trial boolean not null default false, -- „Ausprobieren“ statt Pool + created_by uuid, + created_at timestamptz not null default now(), + updated_at timestamptz not null default now(), + archived_at timestamptz, + unique (id, household_id), + foreign key (created_by, household_id) references members (id, household_id) on delete set null (created_by) +); + +create table dish_ingredients ( + id uuid primary key default gen_random_uuid(), + household_id uuid not null references households (id) on delete cascade, + dish_id uuid not null, + ingredient_id uuid not null references ingredients (id), + qty_per_portion numeric(12, 3) not null check (qty_per_portion >= 0), + unit text not null check (unit in ('g', 'ml', 'piece')), + note text, + is_staple boolean not null default false, -- Grundvorrat: nicht einzeln einkaufen + position integer not null default 0, + foreign key (dish_id, household_id) references dishes (id, household_id) on delete cascade +); +create index dish_ingredients_dish_idx on dish_ingredients (dish_id); + +create table dish_steps ( + id uuid primary key default gen_random_uuid(), + household_id uuid not null references households (id) on delete cascade, + dish_id uuid not null, + position integer not null, + text text not null, + timer_seconds integer check (timer_seconds > 0), + ingredient_ids uuid[] not null default '{}', + unique (dish_id, position) deferrable initially deferred, + foreign key (dish_id, household_id) references dishes (id, household_id) on delete cascade +); + +create table dish_translations ( + household_id uuid not null references households (id) on delete cascade, + dish_id uuid not null, + locale text not null check (locale in ('de', 'en', 'fr', 'es')), + title text not null, + steps jsonb not null default '[]'::jsonb, + translated_at timestamptz not null default now(), + primary key (dish_id, locale), + foreign key (dish_id, household_id) references dishes (id, household_id) on delete cascade +); + +-- ── Läden ─────────────────────────────────────────────────────────────────── +create table stores ( + id uuid primary key default gen_random_uuid(), + household_id uuid not null references households (id) on delete cascade, + name text not null check (length(trim(name)) between 1 and 80), + chain text, + is_default boolean not null default false, + created_at timestamptz not null default now(), + unique (id, household_id) +); +create unique index stores_one_default_idx on stores (household_id) where is_default; + +create table store_aisles ( + id uuid primary key default gen_random_uuid(), + household_id uuid not null references households (id) on delete cascade, + store_id uuid not null, + position integer not null, + name text not null, + ingredient_categories text[] not null default '{}', + unique (store_id, position) deferrable initially deferred, + foreign key (store_id, household_id) references stores (id, household_id) on delete cascade +); + +-- ── Planungsrunden ────────────────────────────────────────────────────────── +create table rounds ( + id uuid primary key default gen_random_uuid(), + household_id uuid not null references households (id) on delete cascade, + shopping_date date, + slots_count integer not null check (slots_count between 1 and 14), + default_portions integer not null check (default_portions between 1 and 30), + status text not null default 'open' check (status in ('open', 'planned', 'shopping', 'done')), + wish_deadline timestamptz, + store_id uuid, + created_by uuid, + approved_by uuid, + approved_at timestamptz, + created_at timestamptz not null default now(), + unique (id, household_id), + foreign key (store_id, household_id) references stores (id, household_id) on delete set null (store_id), + foreign key (created_by, household_id) references members (id, household_id) on delete set null (created_by), + foreign key (approved_by, household_id) references members (id, household_id) on delete set null (approved_by) +); +create index rounds_household_idx on rounds (household_id, created_at desc); + +create table wishes ( + id uuid primary key default gen_random_uuid(), + household_id uuid not null references households (id) on delete cascade, + round_id uuid not null, + member_id uuid not null, + dish_id uuid not null, + note text, + is_veto boolean not null default false, + wants_to_cook boolean not null default false, + created_at timestamptz not null default now(), + unique (round_id, member_id, dish_id), + foreign key (round_id, household_id) references rounds (id, household_id) on delete cascade, + foreign key (member_id, household_id) references members (id, household_id) on delete cascade, + foreign key (dish_id, household_id) references dishes (id, household_id) on delete cascade +); + +create table slots ( + id uuid primary key default gen_random_uuid(), + household_id uuid not null references households (id) on delete cascade, + round_id uuid not null, + position integer not null, + dish_id uuid, + portions integer not null check (portions between 1 and 30), + cook_member_id uuid, + planned_day date, + cooked_at timestamptz, + locked boolean not null default false, + reason text, -- warum hier: „Wunsch von Maike“, „lange nicht gehabt“ + unique (id, household_id), + unique (round_id, position) deferrable initially deferred, + foreign key (round_id, household_id) references rounds (id, household_id) on delete cascade, + foreign key (dish_id, household_id) references dishes (id, household_id) on delete set null (dish_id), + foreign key (cook_member_id, household_id) references members (id, household_id) on delete set null (cook_member_id) +); +create index slots_dish_idx on slots (dish_id, cooked_at desc); + +create table shopping_items ( + id uuid primary key default gen_random_uuid(), + household_id uuid not null references households (id) on delete cascade, + round_id uuid not null, + ingredient_id uuid references ingredients (id), -- leer bei Freitext („Klopapier“) + label text not null, + qty numeric(12, 3), + unit text check (unit in ('g', 'ml', 'piece')), + aisle_position integer, + added_manually boolean not null default false, + checked_by uuid, + checked_at timestamptz, + created_at timestamptz not null default now(), + foreign key (round_id, household_id) references rounds (id, household_id) on delete cascade, + foreign key (checked_by, household_id) references members (id, household_id) on delete set null (checked_by) +); +create index shopping_items_round_idx on shopping_items (round_id); + +create table pantry_staples ( + household_id uuid not null references households (id) on delete cascade, + ingredient_id uuid not null references ingredients (id), + last_confirmed_at timestamptz, + primary key (household_id, ingredient_id) +); + +-- ── Bons und Preisgedächtnis (V2) ─────────────────────────────────────────── +create table receipts ( + id uuid primary key default gen_random_uuid(), + household_id uuid not null references households (id) on delete cascade, + store_id uuid, + purchased_at timestamptz, + total numeric(10, 2), + photo_path text, -- gelöscht nach der Bestätigung + status text not null default 'queued' check (status in ('queued', 'processing', 'review', 'done', 'failed')), + created_by uuid, + created_at timestamptz not null default now(), + unique (id, household_id), + foreign key (store_id, household_id) references stores (id, household_id) on delete set null (store_id), + foreign key (created_by, household_id) references members (id, household_id) on delete set null (created_by) +); + +create table receipt_lines ( + id uuid primary key default gen_random_uuid(), + household_id uuid not null references households (id) on delete cascade, + receipt_id uuid not null, + position integer not null, + raw_text text not null, + qty numeric(12, 3), + unit_price numeric(10, 2), + total_price numeric(10, 2), + ingredient_id uuid references ingredients (id), + pack_qty numeric(12, 3), + pack_unit text check (pack_unit in ('g', 'ml', 'piece')), + confirmed boolean not null default false, + foreign key (receipt_id, household_id) references receipts (id, household_id) on delete cascade +); + +create table ingredient_aliases ( + household_id uuid not null references households (id) on delete cascade, + raw_text_normalized text not null, + ingredient_id uuid not null references ingredients (id), + pack_qty numeric(12, 3), + pack_unit text check (pack_unit in ('g', 'ml', 'piece')), + primary key (household_id, raw_text_normalized) +); + +create table price_points ( + id uuid primary key default gen_random_uuid(), + household_id uuid not null references households (id) on delete cascade, + ingredient_id uuid not null references ingredients (id), + store_id uuid, + price_per_unit numeric(12, 6) not null check (price_per_unit >= 0), -- je g, ml oder Stück + unit text not null check (unit in ('g', 'ml', 'piece')), + observed_at timestamptz not null default now(), + source text not null check (source in ('receipt', 'manual', 'default')), + receipt_id uuid, + foreign key (store_id, household_id) references stores (id, household_id) on delete cascade, + foreign key (receipt_id, household_id) references receipts (id, household_id) on delete set null (receipt_id) +); +create index price_points_lookup_idx on price_points (household_id, ingredient_id, store_id, observed_at desc); + +-- ── Bewerten und Anerkennung ──────────────────────────────────────────────── +create table ratings ( + id uuid primary key default gen_random_uuid(), + household_id uuid not null references households (id) on delete cascade, + slot_id uuid not null, + member_id uuid not null, + thumbs_up boolean not null, + comment text check (length(comment) <= 280), + created_at timestamptz not null default now(), + unique (slot_id, member_id), + foreign key (slot_id, household_id) references slots (id, household_id) on delete cascade, + foreign key (member_id, household_id) references members (id, household_id) on delete cascade +); + +create table kudos ( + household_id uuid not null references households (id) on delete cascade, + slot_id uuid not null, + from_member_id uuid not null, + created_at timestamptz not null default now(), + primary key (slot_id, from_member_id), + foreign key (slot_id, household_id) references slots (id, household_id) on delete cascade, + foreign key (from_member_id, household_id) references members (id, household_id) on delete cascade +); + +create table helper_points ( + id uuid primary key default gen_random_uuid(), + household_id uuid not null references households (id) on delete cascade, + member_id uuid not null, + points integer not null check (points between 1 and 10), + reason text, + granted_by uuid, + created_at timestamptz not null default now(), + foreign key (member_id, household_id) references members (id, household_id) on delete cascade, + foreign key (granted_by, household_id) references members (id, household_id) on delete set null (granted_by) +); + +create table achievements ( + id uuid primary key default gen_random_uuid(), + household_id uuid not null references households (id) on delete cascade, + member_id uuid, -- leer: Meilenstein des ganzen Haushalts + key text not null, + achieved_at timestamptz not null default now(), + unique nulls not distinct (household_id, member_id, key), + foreign key (member_id, household_id) references members (id, household_id) on delete cascade +); + +-- ── Zeilensicherheit ──────────────────────────────────────────────────────── +alter table ingredients enable row level security; +alter table ingredients force row level security; +create policy ingredients_read on ingredients for select using (true); +create policy ingredients_maintain on ingredients using (app_maintenance()) with check (app_maintenance()); + +do $$ +declare t text; +begin + foreach t in array array[ + 'dishes', 'dish_ingredients', 'dish_steps', 'dish_translations', 'stores', 'store_aisles', + 'rounds', 'wishes', 'slots', 'shopping_items', 'pantry_staples', 'receipts', 'receipt_lines', + 'ingredient_aliases', 'price_points', 'ratings', 'kudos', 'helper_points', 'achievements' + ] loop + execute format('alter table %I enable row level security', t); + execute format('alter table %I force row level security', t); + execute format( + 'create policy %I on %I using (household_id = app_household_id()) with check (household_id = app_household_id())', + t || '_household', t); + end loop; +end $$; + +-- ── Sichten ───────────────────────────────────────────────────────────────── +-- Beliebtheit: Anteil Daumen hoch über die letzten fünf Male, die das Gericht +-- gekocht wurde. security_invoker: Die Zeilensicherheit gilt für die Abfragende. +create view dish_popularity with (security_invoker = true) as +select d.id as dish_id, + d.household_id, + count(r.id)::int as ratings, + avg(case when r.thumbs_up then 1.0 else 0.0 end) as share_up + from dishes d + left join lateral ( + select s.id from slots s + where s.dish_id = d.id and s.cooked_at is not null + order by s.cooked_at desc + limit 5 + ) last5 on true + left join ratings r on r.slot_id = last5.id + group by d.id, d.household_id; diff --git a/docs/PROJEKTSTART.md b/docs/PROJEKTSTART.md index a698dde..3d5b13c 100644 --- a/docs/PROJEKTSTART.md +++ b/docs/PROJEKTSTART.md @@ -47,6 +47,7 @@ Das Repo erbt sie, weil es in der Organisation liegt. der Mailweg feststeht. `olares-cli chart lint` läuft nicht in der CI (der Runner hat das Werkzeug nicht); der Markt-Beweis mit wrangler schon. 2. **Datenmodell** als Migrationen (22 Tabellen, RLS mit FORCE), Test mit zwei Haushalten; Sicherung nach `/app/data`. + **Erledigt** in 26.11.3 (E-0007, E-0008); `dish_costs` folgt mit V2. 3. **Seed:** etwa 300 kanonische Zutaten in vier Sprachen, Starter-Pool DE und EN, Gangfolgen REWE, Edeka, Lidl, Aldi. 4. **Gerichte:** von Hand, Import per JSON-LD, Foto-Import über LiteLLM. 5. **Wünschen:** Jetons, Kacheln, Kinder-Login mit Haushaltscode und PIN. diff --git a/docs/entscheidungen.md b/docs/entscheidungen.md index 0f93b36..feb622c 100644 --- a/docs/entscheidungen.md +++ b/docs/entscheidungen.md @@ -122,3 +122,40 @@ der Person am Gerät. Sicherheitscheck: `docs/sicherheit/login-2026-11-06.md`. **Folgen:** Kommt der Magic Link, wird er ein Weg zum Anmelden, nicht zur Wiederherstellung — sonst wäre die Sicherheit jedes Kontos die des Postfachs. Kinder (Haushaltscode und PIN) folgen mit Arbeitspaket 5. + +--- + +## E-0007 · `household_id` an jeder Haushaltstabelle, Fremdschlüssel paarweise + +**Stand:** entschieden, Claude im Auftrag von Kai („mach mit Arbeitspaket 2 weiter“), 6.11.2026 + +**Konzept sagte:** Jede Tabelle trägt `household_id` „direkt oder über einen Join“. + +**Entschieden:** direkt, an jeder Haushaltstabelle. Eine Policy-Form für alle +(`household_id = app_household_id()`, mit FORCE), keine Joins in Policies. Verweise +innerhalb des Haushalts laufen über zusammengesetzte Fremdschlüssel +(`(dish_id, household_id) → dishes (id, household_id)`): Eine Zeile kann nie auf Gericht, +Runde oder Mitglied eines anderen Haushalts zeigen, auch nicht durch einen Fehler im Code. +Fällt ein Verweis weg, setzt `on delete set null (spalte)` nur diese Spalte zurück. + +**Folgen:** Jede neue Tabelle bekommt `household_id`, paarweise Fremdschlüssel, RLS mit +FORCE und eine Zeile in `tests/fixture.ts`; `tests/rls.test.ts` liest jede Tabelle mit zwei +Haushalten gegen und bricht, wenn eine fehlt. Global sind nur `ingredients` (lesbar für +alle, schreibbar nur in Migrationen über `app.maintenance`) und die Tabellen der Anmeldung. + +--- + +## E-0008 · Rollen wie im Konzept, Statuswerte als Text + +**Stand:** entschieden, Claude im Auftrag von Kai, 6.11.2026 + +Rollen `admin`, `member`, `child`, `guest` wie im Konzept (bis 26.11.2 hießen sie `owner` +und `adult`). Mehrere Admins sind möglich; wer eingerichtet hat, steht in +`households.created_by`, kann nicht entfernt werden und ist das Ziel des Rückwegs. Admins +laden als Mitglied oder Admin ein. Gäste bekommen später ein Ablaufdatum (`expires_at`). + +Statuswerte (`rounds.status`, `price_points.source`, `receipts.status`) stehen als `text` +mit `check` statt als Postgres-Enum: Ein neuer Wert ist dann eine Zeile in einer Migration, +kein `alter type` mit seinen Einschränkungen. + +**Offen:** `dish_costs` (Kosten pro Portion und Konfidenz) kommt mit den Preisen in V2. diff --git a/instrumentation.ts b/instrumentation.ts new file mode 100644 index 0000000..08a05c2 --- /dev/null +++ b/instrumentation.ts @@ -0,0 +1,7 @@ +// Läuft einmal beim Start des Servers (Next.js). Startet den Takt der +// Sicherung — nur in Node, nicht beim Bauen und nicht im Edge-Laufzeitteil. +export async function register() { + if (process.env.NEXT_RUNTIME !== "nodejs" || process.env.BACKUP_DISABLED === "1") return; + const { startBackupSchedule } = await import("./lib/backup-schedule"); + startBackupSchedule(); +} diff --git a/lib/auth/invitations.ts b/lib/auth/invitations.ts index 703d608..a2eb03f 100644 --- a/lib/auth/invitations.ts +++ b/lib/auth/invitations.ts @@ -9,12 +9,13 @@ export type OpenInvitation = { memberId: string | null; displayName: string | null; memberName: string | null; + role: "admin" | "member"; }; /** Die gültige, unbenutzte Einladung zum Link — oder null. In withAuth. */ export async function findInvitation(client: PoolClient, token: string): Promise { const { rows } = await client.query( - `select i.id, i.household_id, h.name as household_name, i.member_id, i.display_name, m.display_name as member_name + `select i.id, i.household_id, h.name as household_name, i.member_id, i.display_name, i.role, m.display_name as member_name from invitations i join households h on h.id = i.household_id left join members m on m.id = i.member_id @@ -30,6 +31,7 @@ export async function findInvitation(client: PoolClient, token: string): Promise memberId: r.member_id, displayName: r.display_name, memberName: r.member_name, + role: r.role, } : null; } diff --git a/lib/auth/schemas.ts b/lib/auth/schemas.ts index 07b97d3..787e9d7 100644 --- a/lib/auth/schemas.ts +++ b/lib/auth/schemas.ts @@ -19,6 +19,6 @@ export const inviteOptionsBody = z.object({ }); export const createInvitationBody = z.discriminatedUnion("kind", [ - z.object({ kind: z.literal("person"), name }), + z.object({ kind: z.literal("person"), name, role: z.enum(["member", "admin"]).default("member") }), z.object({ kind: z.literal("device") }), ]); diff --git a/lib/auth/session.ts b/lib/auth/session.ts index be6e3a4..e07b996 100644 --- a/lib/auth/session.ts +++ b/lib/auth/session.ts @@ -18,7 +18,7 @@ export type Session = { memberId: string; householdId: string; displayName: string; - role: "owner" | "adult" | "child"; + role: "admin" | "member" | "child" | "guest"; householdName: string; }; diff --git a/lib/backup-schedule.ts b/lib/backup-schedule.ts new file mode 100644 index 0000000..a57ffa4 --- /dev/null +++ b/lib/backup-schedule.ts @@ -0,0 +1,23 @@ +import { backupIfChanged } from "./backup"; + +// Alle fünf Minuten prüfen, ob sich etwas geändert hat; der erste Lauf eine +// Minute nach dem Start, damit die Migrationen und der Server zur Ruhe kommen. +const EVERY_MS = 5 * 60 * 1000; +let started = false; + +export function startBackupSchedule(): void { + if (started) return; + started = true; + const run = async () => { + try { + const name = await backupIfChanged(); + if (name) console.log(`backup written: ${name}`); + } catch (error) { + // Eine fehlgeschlagene Sicherung darf die App nicht anhalten; sie meldet + // sich im Log und versucht es beim nächsten Takt wieder. + console.error("backup failed:", error instanceof Error ? error.message : error); + } + }; + setTimeout(run, 60 * 1000).unref(); + setInterval(run, EVERY_MS).unref(); +} diff --git a/lib/backup.ts b/lib/backup.ts new file mode 100644 index 0000000..5f03694 --- /dev/null +++ b/lib/backup.ts @@ -0,0 +1,202 @@ +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", + "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", +] as const; + +/** 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", + ingredients: "kommt aus den Seed-Migrationen mit festen Kennungen, nicht aus dem Haushalt", + schema_migrations: "gehört zur Datenbank, nicht zu den Daten", +}; + +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`); + 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 })); + } + 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(); + } +} diff --git a/messages/de.json b/messages/de.json index 1f3d432..4c1cf0e 100644 --- a/messages/de.json +++ b/messages/de.json @@ -46,9 +46,10 @@ "invitation": "Dieser Link gilt nicht mehr.", "alreadySetUp": "Der Haushalt ist schon eingerichtet.", "origin": "Die Anfrage kam nicht von dieser App.", - "forbidden": "Das darf nur, wer den Haushalt eingerichtet hat.", + "forbidden": "Das dürfen nur Admins.", "unknown": "Das hat nicht geklappt. Bitte versuch es noch einmal.", - "lastPasskey": "Das ist dein letzter Passkey. Füge erst ein anderes Gerät hinzu." + "lastPasskey": "Das ist dein letzter Passkey. Füge erst ein anderes Gerät hinzu.", + "noBackup": "Es liegt keine Sicherung vor." }, "recovery": { "title": "Zugang wiederherstellen", @@ -58,6 +59,13 @@ "code": "Wiederherstellungscode", "submit": "Neuen Passkey anlegen", "others": "Alle anderen bekommen einen neuen Link von der Person, die eingerichtet hat." + }, + "restore": { + "title": "Sicherung zurückspielen", + "summary": "Auf der Box liegt eine Sicherung vom {date}: {households}, {members, plural, one {eine Person} other {# Personen}}. Danach meldet sich jede Person mit ihrem bisherigen Passkey an.", + "submit": "Sicherung zurückspielen", + "otherOrigin": "Die Sicherung gehört zur Adresse {origin}. Öffne die App dort, sonst passen die Passkeys nicht.", + "or": "Oder neu beginnen" } }, "more": { @@ -66,9 +74,10 @@ "members": "Mitglieder", "you": "du", "roles": { - "owner": "hat eingerichtet", - "adult": "erwachsen", - "child": "Kind" + "admin": "Admin", + "member": "Mitglied", + "child": "Kind", + "guest": "Gast" }, "invitePerson": "Person einladen", "inviteName": "Name", @@ -84,7 +93,13 @@ "signOut": "Abmelden", "remove": "Entfernen", "confirmRemove": "Wirklich entfernen", - "removeHint": "Ein entferntes Gerät ist sofort abgemeldet." + "removeHint": "Ein entferntes Gerät ist sofort abgemeldet.", + "founder": "hat eingerichtet", + "inviteRole": "Rolle", + "roleHints": { + "member": "wünschen, kochen, einkaufen, bewerten", + "admin": "dazu Runden planen und freigeben, Gerichte und Läden pflegen, einladen" + } }, "nav": { "today": "Heute", diff --git a/messages/en.json b/messages/en.json index 8d983d4..1c92ac4 100644 --- a/messages/en.json +++ b/messages/en.json @@ -46,9 +46,10 @@ "invitation": "This link is no longer valid.", "alreadySetUp": "The household is already set up.", "origin": "The request didn't come from this app.", - "forbidden": "Only the person who set up the household can do this.", + "forbidden": "Only admins can do this.", "unknown": "That didn't work. Please try again.", - "lastPasskey": "This is your last passkey. Add another device first." + "lastPasskey": "This is your last passkey. Add another device first.", + "noBackup": "There is no backup." }, "recovery": { "title": "Restore access", @@ -58,6 +59,13 @@ "code": "Recovery code", "submit": "Create new passkey", "others": "Everyone else gets a new link from the person who set up the household." + }, + "restore": { + "title": "Restore backup", + "summary": "There is a backup on the box from {date}: {households}, {members, plural, one {one person} other {# people}}. Afterwards everyone signs in with their existing passkey.", + "submit": "Restore backup", + "otherOrigin": "The backup belongs to the address {origin}. Open the app there, otherwise the passkeys won't match.", + "or": "Or start fresh" } }, "more": { @@ -66,9 +74,10 @@ "members": "Members", "you": "you", "roles": { - "owner": "set it up", - "adult": "adult", - "child": "child" + "admin": "Admin", + "member": "Member", + "child": "Child", + "guest": "Guest" }, "invitePerson": "Invite someone", "inviteName": "Name", @@ -84,7 +93,13 @@ "signOut": "Sign out", "remove": "Remove", "confirmRemove": "Really remove", - "removeHint": "A removed device is signed out immediately." + "removeHint": "A removed device is signed out immediately.", + "founder": "set it up", + "inviteRole": "Role", + "roleHints": { + "member": "wish, cook, shop, rate", + "admin": "also plan and approve rounds, manage dishes and stores, invite" + } }, "nav": { "today": "Today", diff --git a/messages/es.json b/messages/es.json index 215ac64..8e0f41e 100644 --- a/messages/es.json +++ b/messages/es.json @@ -46,9 +46,10 @@ "invitation": "This link is no longer valid.", "alreadySetUp": "The household is already set up.", "origin": "The request didn't come from this app.", - "forbidden": "Only the person who set up the household can do this.", + "forbidden": "Only admins can do this.", "unknown": "That didn't work. Please try again.", - "lastPasskey": "This is your last passkey. Add another device first." + "lastPasskey": "This is your last passkey. Add another device first.", + "noBackup": "There is no backup." }, "recovery": { "title": "Restore access", @@ -58,6 +59,13 @@ "code": "Recovery code", "submit": "Create new passkey", "others": "Everyone else gets a new link from the person who set up the household." + }, + "restore": { + "title": "Restore backup", + "summary": "There is a backup on the box from {date}: {households}, {members, plural, one {one person} other {# people}}. Afterwards everyone signs in with their existing passkey.", + "submit": "Restore backup", + "otherOrigin": "The backup belongs to the address {origin}. Open the app there, otherwise the passkeys won't match.", + "or": "Or start fresh" } }, "more": { @@ -66,9 +74,10 @@ "members": "Members", "you": "you", "roles": { - "owner": "set it up", - "adult": "adult", - "child": "child" + "admin": "Admin", + "member": "Member", + "child": "Child", + "guest": "Guest" }, "invitePerson": "Invite someone", "inviteName": "Name", @@ -84,7 +93,13 @@ "signOut": "Sign out", "remove": "Remove", "confirmRemove": "Really remove", - "removeHint": "A removed device is signed out immediately." + "removeHint": "A removed device is signed out immediately.", + "founder": "set it up", + "inviteRole": "Role", + "roleHints": { + "member": "wish, cook, shop, rate", + "admin": "also plan and approve rounds, manage dishes and stores, invite" + } }, "nav": { "today": "Today", diff --git a/messages/fr.json b/messages/fr.json index f85056c..ba653ba 100644 --- a/messages/fr.json +++ b/messages/fr.json @@ -46,9 +46,10 @@ "invitation": "This link is no longer valid.", "alreadySetUp": "The household is already set up.", "origin": "The request didn't come from this app.", - "forbidden": "Only the person who set up the household can do this.", + "forbidden": "Only admins can do this.", "unknown": "That didn't work. Please try again.", - "lastPasskey": "This is your last passkey. Add another device first." + "lastPasskey": "This is your last passkey. Add another device first.", + "noBackup": "There is no backup." }, "recovery": { "title": "Restore access", @@ -58,6 +59,13 @@ "code": "Recovery code", "submit": "Create new passkey", "others": "Everyone else gets a new link from the person who set up the household." + }, + "restore": { + "title": "Restore backup", + "summary": "There is a backup on the box from {date}: {households}, {members, plural, one {one person} other {# people}}. Afterwards everyone signs in with their existing passkey.", + "submit": "Restore backup", + "otherOrigin": "The backup belongs to the address {origin}. Open the app there, otherwise the passkeys won't match.", + "or": "Or start fresh" } }, "more": { @@ -66,9 +74,10 @@ "members": "Members", "you": "you", "roles": { - "owner": "set it up", - "adult": "adult", - "child": "child" + "admin": "Admin", + "member": "Member", + "child": "Child", + "guest": "Guest" }, "invitePerson": "Invite someone", "inviteName": "Name", @@ -84,7 +93,13 @@ "signOut": "Sign out", "remove": "Remove", "confirmRemove": "Really remove", - "removeHint": "A removed device is signed out immediately." + "removeHint": "A removed device is signed out immediately.", + "founder": "set it up", + "inviteRole": "Role", + "roleHints": { + "member": "wish, cook, shop, rate", + "admin": "also plan and approve rounds, manage dishes and stores, invite" + } }, "nav": { "today": "Today", diff --git a/olares/Chart.yaml b/olares/Chart.yaml index da73ea2..a0291fd 100644 --- a/olares/Chart.yaml +++ b/olares/Chart.yaml @@ -2,5 +2,5 @@ apiVersion: v2 name: lunch description: Was gibt's? — die Familie entscheidet gemeinsam, was es gibt; aus dem Plan entsteht die Einkaufsliste type: application -version: 26.11.2 # YY.M. wie im AImighty-Markt — bei jeder Chart-Änderung erhöhen -appVersion: "26.11.2" # MUSS gleich version sein: der Linter prüft es, und der Image-Tag hängt daran +version: 26.11.3 # YY.M. wie im AImighty-Markt — bei jeder Chart-Änderung erhöhen +appVersion: "26.11.3" # MUSS gleich version sein: der Linter prüft es, und der Image-Tag hängt daran diff --git a/olares/OlaresManifest.yaml b/olares/OlaresManifest.yaml index 5d3716d..2a8ccee 100644 --- a/olares/OlaresManifest.yaml +++ b/olares/OlaresManifest.yaml @@ -21,7 +21,7 @@ metadata: title: What's cooking? description: The family decides together what's for dinner — and the shopping list writes itself. Runs entirely on your own box. icon: https://git.aimighty.olares.de/aimighty/bilder/raw/branch/main/lunch/icon.png - version: 26.11.2 + version: 26.11.3 categories: - Applications @@ -61,7 +61,7 @@ permission: appData: true spec: - versionName: '26.11.2' + versionName: '26.11.3' featuredImage: https://git.aimighty.olares.de/aimighty/bilder/raw/branch/main/lunch/icon.png promoteImage: diff --git a/olares/markt/26.11.3.md b/olares/markt/26.11.3.md new file mode 100644 index 0000000..37f20a0 --- /dev/null +++ b/olares/markt/26.11.3.md @@ -0,0 +1,5 @@ +# Household data model and automatic backup +v26.11.3: The groundwork for dishes, planning rounds, wishes, shopping lists, ratings and receipts, each kept strictly within its household; a test reads every table with two households against each other. Roles now follow the concept: admins, members, children and guests, and admins can invite further admins. After every change the app writes a backup to the box's files, which survive an uninstall; a fresh install offers to restore it with the setup code, and everyone signs in again with their existing passkey. + +## Deutsch +v26.11.3: Das Fundament für Gerichte, Planungsrunden, Wünsche, Einkaufslisten, Bewertungen und Kassenbons, jedes streng im eigenen Haushalt; ein Test liest jede Tabelle mit zwei Haushalten gegeneinander. Die Rollen folgen jetzt dem Konzept: Admins, Mitglieder, Kinder und Gäste, und Admins können weitere Admins einladen. Nach jeder Änderung legt die App eine Sicherung in die Dateien der Box, die eine Deinstallation überleben; eine neue Installation bietet an, sie mit dem Einrichtungscode zurückzuspielen, und alle melden sich mit ihrem bisherigen Passkey wieder an. diff --git a/tests/backup.test.ts b/tests/backup.test.ts new file mode 100644 index 0000000..104a05f --- /dev/null +++ b/tests/backup.test.ts @@ -0,0 +1,90 @@ +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/); + }); +}); diff --git a/tests/fixture.ts b/tests/fixture.ts new file mode 100644 index 0000000..019ac15 --- /dev/null +++ b/tests/fixture.ts @@ -0,0 +1,89 @@ +import { randomUUID } from "node:crypto"; +import type pg from "pg"; + +// Ein Haushalt mit je mindestens einer Zeile in **jeder** Haushaltstabelle. +// Kommt eine Tabelle dazu, gehört sie hierher — tests/rls.test.ts bricht sonst. +export const SEEDED_TABLES = [ + "households", "members", "passkeys", "sessions", "invitations", "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", +]; + +/** Eine globale Zutat, wie sie eine Seed-Migration anlegt. */ +export async function seedIngredient(client: pg.Client | pg.PoolClient): Promise { + const id = randomUUID(); + await client.query("begin"); + await client.query("select set_config('app.maintenance', 'on', true)"); + await client.query( + "insert into ingredients (id, key, category, default_unit, names) values ($1, $2, 'meat', 'g', $3)", + [id, `test_${id.replace(/-/g, "")}`, JSON.stringify({ de: "Hackfleisch", en: "Ground beef" })], + ); + await client.query("commit"); + return id; +} + +/** Legt den Haushalt `h` mit allem an; läuft in einer eigenen Transaktion als dieser Haushalt. */ +export async function seedHousehold(client: pg.Client | pg.PoolClient, h: string, ingredient: string): Promise<{ dish: string; member: string }> { + const q = (sql: string, params: unknown[] = []) => client.query(sql, params); + const member = randomUUID(); + const dish = randomUUID(); + const store = randomUUID(); + const round = randomUUID(); + const slot = randomUUID(); + const receipt = randomUUID(); + const passkey = `pk-${h}`; + await q("begin"); + await q("select set_config('app.household_id', $1, true)", [h]); + await q("insert into households (id, name) values ($1, $2)", [h, `Haushalt ${h.slice(0, 4)}`]); + await q("insert into members (id, household_id, display_name, role) values ($1, $2, 'Kai', 'admin')", [member, h]); + await q("update households set created_by = $1 where id = $2", [member, h]); + await q("insert into passkeys (id, member_id, household_id, public_key) values ($1, $2, $3, '\\x0102')", [passkey, member, h]); + await q( + "insert into sessions (token_hash, member_id, household_id, passkey_id, expires_at) values (sha256(convert_to($1, 'utf8')), $2, $3, $4, now() + interval '1 day')", + [randomUUID(), member, h, passkey], + ); + await q( + "insert into invitations (household_id, token_hash, display_name, created_by, expires_at) values ($1, sha256(convert_to($2, 'utf8')), 'Maike', $3, now() + interval '1 day')", + [h, randomUUID(), member], + ); + await q("insert into stores (id, household_id, name, chain, is_default) values ($1, $2, 'REWE', 'rewe', true)", [store, h]); + await q("insert into store_aisles (household_id, store_id, position, name) values ($1, $2, 1, 'Obst')", [h, store]); + await q("insert into dishes (id, household_id, title, base, created_by) values ($1, $2, 'Bolognese', 'pasta', $3)", [dish, h, member]); + await q( + "insert into dish_ingredients (household_id, dish_id, ingredient_id, qty_per_portion, unit) values ($1, $2, $3, 125, 'g')", + [h, dish, ingredient], + ); + await q("insert into dish_steps (household_id, dish_id, position, text) values ($1, $2, 1, 'Anbraten')", [h, dish]); + await q("insert into dish_translations (household_id, dish_id, locale, title) values ($1, $2, 'en', 'Bolognese')", [h, dish]); + await q( + "insert into rounds (id, household_id, slots_count, default_portions, store_id, created_by) values ($1, $2, 4, 4, $3, $4)", + [round, h, store, member], + ); + await q("insert into wishes (household_id, round_id, member_id, dish_id) values ($1, $2, $3, $4)", [h, round, member, dish]); + await q( + "insert into slots (id, household_id, round_id, position, dish_id, portions, cook_member_id, cooked_at) values ($1, $2, $3, 1, $4, 4, $5, now())", + [slot, h, round, dish, member], + ); + await q( + "insert into shopping_items (household_id, round_id, ingredient_id, label, qty, unit) values ($1, $2, $3, 'Hackfleisch', 500, 'g')", + [h, round, ingredient], + ); + await q("insert into pantry_staples (household_id, ingredient_id) values ($1, $2)", [h, ingredient]); + await q("insert into receipts (id, household_id, store_id, total, created_by) values ($1, $2, $3, 12.5, $4)", [receipt, h, store, member]); + await q( + "insert into receipt_lines (household_id, receipt_id, position, raw_text, ingredient_id) values ($1, $2, 1, 'RINDERHACK 500G', $3)", + [h, receipt, ingredient], + ); + await q("insert into ingredient_aliases (household_id, raw_text_normalized, ingredient_id) values ($1, 'rinderhack 500g', $2)", [h, ingredient]); + await q( + "insert into price_points (household_id, ingredient_id, store_id, price_per_unit, unit, source, receipt_id) values ($1, $2, $3, 0.0099, 'g', 'receipt', $4)", + [h, ingredient, store, receipt], + ); + await q("insert into ratings (household_id, slot_id, member_id, thumbs_up) values ($1, $2, $3, true)", [h, slot, member]); + await q("insert into kudos (household_id, slot_id, from_member_id) values ($1, $2, $3)", [h, slot, member]); + await q("insert into helper_points (household_id, member_id, points, granted_by) values ($1, $2, 1, $2)", [h, member]); + await q("insert into achievements (household_id, key) values ($1, 'first_round')", [h]); + await q("commit"); + return { dish, member }; +} diff --git a/tests/rls.test.ts b/tests/rls.test.ts index ed1ac3e..4962375 100644 --- a/tests/rls.test.ts +++ b/tests/rls.test.ts @@ -1,46 +1,143 @@ import { randomUUID } from "node:crypto"; import pg from "pg"; import { afterAll, beforeAll, describe, expect, it } from "vitest"; +import { SEEDED_TABLES, seedHousehold, seedIngredient } from "./fixture"; -// Der Test mit zwei Haushalten (CLAUDE.md, Regel 3). Läuft gegen eine -// migrierte Datenbank als Eigentümerin der Tabellen — genau wie die App auf +// Der Test mit zwei Haushalten (CLAUDE.md, Regel 3; Konzept „Datenschutz“): +// Er legt zwei Haushalte mit Zeilen in **jeder** Tabelle an und liest jede +// Tabelle gegen. Läuft als Eigentümerin der Tabellen — genau wie die App auf // der Box. Ohne FORCE sähe diese Rolle alles, und der Test bräche. const url = process.env.TEST_DATABASE_URL; +// Tabellen ohne household_id, je mit Grund. +const GLOBAL = { + households: "ist selbst der Haushalt (id)", + instance: "die Box, eine Zeile", + ingredients: "kanonische Zutaten für alle, schreibbar nur in Migrationen", + auth_challenges: "vor der Anmeldung", + auth_attempts: "vor der Anmeldung", + schema_migrations: "gehört zur Datenbank", +}; + describe.skipIf(!url)("row level security", () => { const client = new pg.Client({ connectionString: url }); const a = randomUUID(); const b = randomUUID(); + let dishOfA = ""; + let tables: string[] = []; - async function asHousehold(id: string | null, fn: () => Promise): Promise { + async function as(household: string | null, fn: () => Promise): Promise { await client.query("begin"); try { - if (id) await client.query("select set_config('app.household_id', $1, true)", [id]); + if (household) await client.query("select set_config('app.household_id', $1, true)", [household]); return await fn(); } finally { - await client.query("commit"); + await client.query("rollback"); } } beforeAll(async () => { await client.connect(); - await asHousehold(a, () => client.query("insert into households (id, name) values ($1, 'A')", [a])); - await asHousehold(b, () => client.query("insert into households (id, name) values ($1, 'B')", [b])); + const ingredient = await seedIngredient(client); + dishOfA = (await seedHousehold(client, a, ingredient)).dish; + await seedHousehold(client, b, ingredient); + tables = ( + await client.query<{ table_name: string }>( + `select table_name from information_schema.columns + where table_schema = 'public' and column_name = 'household_id' + and table_name in (select tablename from pg_tables where schemaname = 'public') + order by 1`, + ) + ).rows.map((r) => r.table_name); }); afterAll(async () => { await client.end(); }); - it("every table with household data forces RLS", async () => { + it("every table forces RLS", async () => { const { rows } = await client.query(` select c.relname, c.relrowsecurity, c.relforcerowsecurity from pg_class c join pg_namespace n on n.oid = c.relnamespace where n.nspname = 'public' and c.relkind = 'r' and c.relname <> 'schema_migrations'`); - expect(rows.length).toBeGreaterThan(0); + expect(rows.length).toBeGreaterThan(20); for (const r of rows) expect([r.relname, r.relrowsecurity, r.relforcerowsecurity]).toEqual([r.relname, true, true]); }); + it("every table except the global ones carries household_id", async () => { + const all = (await client.query<{ tablename: string }>("select tablename from pg_tables where schemaname = 'public'")).rows.map( + (r) => r.tablename, + ); + expect(all.filter((t) => !tables.includes(t) && !(t in GLOBAL)).sort()).toEqual([]); + }); + + it("the fixture fills every household table", () => { + expect([...tables].sort()).toEqual(SEEDED_TABLES.filter((t) => t !== "households").sort()); + }); + + it("each household sees only its own rows, in every table", async () => { + for (const own of [a, b]) { + for (const table of tables) { + const { rows } = await as(own, () => + client.query( + `select count(*) filter (where household_id = $1)::int as own, count(*) filter (where household_id <> $1)::int as other from ${table}`, + [own], + ), + ); + expect([table, rows[0].other]).toEqual([table, 0]); + expect([table, rows[0].own > 0]).toEqual([table, true]); + } + const h = await as(own, () => client.query("select id from households")); + expect(h.rows.map((r) => r.id)).toEqual([own]); + } + }); + + it("without a household nothing is visible", async () => { + for (const table of [...tables, "households"]) { + const { rows } = await as(null, () => client.query(`select count(*)::int as n from ${table}`)); + expect([table, rows[0].n]).toEqual([table, 0]); + } + }); + + it("a household cannot change or delete another's rows", async () => { + for (const table of tables) { + const removed = await as(a, () => client.query(`delete from ${table} where household_id = $1`, [b])); + expect([table, removed.rowCount]).toEqual([table, 0]); + } + await expect(as(a, () => client.query("insert into dishes (household_id, title) values ($1, 'X')", [b]))).rejects.toThrow( + /row-level security/, + ); + await expect(as(a, () => client.query("insert into households (id, name) values ($1, 'C')", [randomUUID()]))).rejects.toThrow( + /row-level security/, + ); + }); + + it("a row cannot point at another household's dish (paired foreign key)", async () => { + const { rows } = await as(b, () => client.query("select id from ingredients limit 1")); + await expect( + as(b, () => + client.query( + "insert into dish_ingredients (household_id, dish_id, ingredient_id, qty_per_portion, unit) values ($1, $2, $3, 1, 'g')", + [b, dishOfA, rows[0].id], + ), + ), + ).rejects.toThrow(/foreign key/); + }); + + it("global ingredients are readable, but writable only in migrations", async () => { + const { rows } = await as(a, () => client.query("select count(*)::int as n from ingredients")); + expect(rows[0].n).toBeGreaterThan(0); + await expect( + as(a, () => client.query(`insert into ingredients (key, category, default_unit) values ('x_${Date.now()}', 'x', 'g')`)), + ).rejects.toThrow(/row-level security/); + }); + + it("popularity view respects the household", async () => { + const { rows } = await as(a, () => client.query("select household_id, share_up from dish_popularity")); + expect(rows.every((r) => r.household_id === a)).toBe(true); + expect(rows.find((r) => Number(r.share_up) === 1)).toBeTruthy(); + }); + it("the sign-in bypass (app.auth) is limited to the sign-in tables", async () => { // Nur diese Tabellen darf withAuth() über Haushalte hinweg lesen. Eine // neue Fachtabelle mit app_auth() in der Policy wäre ein Leck. @@ -51,23 +148,4 @@ describe.skipIf(!url)("row level security", () => { "auth_attempts", "auth_challenges", "households", "instance", "invitations", "members", "passkeys", "sessions", ]); }); - - it("a household sees only itself", async () => { - const seen = await asHousehold(a, () => client.query("select id from households")); - expect(seen.rows.map((r) => r.id)).toEqual([a]); - }); - - it("without a household nothing is visible", async () => { - const seen = await asHousehold(null, () => client.query("select count(*)::int as n from households")); - expect(seen.rows[0].n).toBe(0); - }); - - it("a household cannot write into another", async () => { - await expect( - asHousehold(a, () => client.query("update households set name = 'X' where id = $1 returning id", [b])), - ).resolves.toMatchObject({ rowCount: 0 }); - await expect( - asHousehold(a, () => client.query("insert into households (id, name) values ($1, 'C')", [randomUUID()])), - ).rejects.toThrow(/row-level security/); - }); }); -- 2.54.0