From 0919d8b962717b52bcdd80d91714a0f639a446a6 Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?Marc-Andr=C3=A9=20Bombeck?= Date: Sun, 26 Jul 2026 01:44:41 +0200 Subject: [PATCH] fix(settings): make Delete All Data delete what it says MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit The wipe deleted thirteen tables against a schema that carries more than eighty user-scoped ones. Mental-health assessments, lab results, the menstrual record, allergies, family history, the document vault, every AI conversation and live clinician share links all survived a confirmation that promised to permanently delete all health data. So did MeasurementRollup, the per-day reconstruction of the measurements the same transaction had just removed. The list now lives in src/lib/data-wipe/wipe-plan.ts next to its own exemption list, and a structural guard enumerates schema.prisma and fails when a model belongs to neither. Adding a model can no longer widen the set of things that survive a wipe by default. The same guard covers the User row's own columns, which had drifted the same way. The boundary is explicit: everything the account owns goes, except what is needed to sign in again. The confirmation and the toast say so before the person types the confirmation rather than after. Checkup reminders and allergies promised permanence over a soft delete with no restore path; both now hard-delete, so the dialog is true. The lab biomarker dialog was checked and is already accurate — it maps to the hard-deleting /api/biomarkers/[id] route, not to the soft-deleting lab result route. --- messages/de.json | 6 +- messages/en.json | 6 +- messages/es.json | 6 +- messages/fr.json | 6 +- messages/it.json | 6 +- messages/pl.json | 6 +- .../copy-matches-behaviour-guard.test.ts | 9 +- src/__tests__/data-wipe-completeness.test.ts | 286 +++++++++++++ src/app/api/allergies/[id]/route.ts | 26 +- .../api/measurement-reminders/[id]/route.ts | 13 +- src/app/api/settings/data/route.ts | 136 +++--- src/lib/data-wipe/wipe-plan.ts | 403 ++++++++++++++++++ 12 files changed, 796 insertions(+), 113 deletions(-) create mode 100644 src/__tests__/data-wipe-completeness.test.ts create mode 100644 src/lib/data-wipe/wipe-plan.ts diff --git a/messages/de.json b/messages/de.json index 4728f85d6..ee218f830 100644 --- a/messages/de.json +++ b/messages/de.json @@ -5217,10 +5217,10 @@ "apiEndpointAuth": "Authentifizierung", "apiEndpointExample": "Body-Beispiel", "dangerZone": "Alle Daten löschen", - "dangerZoneDescription": "Löscht alle deine Gesundheitsdaten und Integrationen. Dein Nutzerkonto bleibt erhalten.", + "dangerZoneDescription": "Löscht deine gesamte Gesundheitsakte und jede Integrationsverbindung. Dein Konto und deine Anmeldedaten bleiben erhalten.", "dangerZoneConfirm": "Alle Daten löschen?", - "dangerZoneConfirmDescription": "Dieser Vorgang löscht alle deine Gesundheitsdaten und Integrationen unwiderruflich. Dein Nutzerkonto bleibt erhalten.", - "dangerZoneSuccess": "Alle persönlichen Daten wurden gelöscht", + "dangerZoneConfirmDescription": "Dieser Vorgang löscht unwiderruflich alles in deiner Akte: Messwerte, Medikamente, Stimmungseinträge, Laborwerte, Zykluseinträge, Dokumente, KI-Gespräche und jede Integrationsverbindung, dazu alles daraus Abgeleitete und alles, was du früher gelöscht hast. Freigabe-Links, die du an eine Praxis gegeben hast, funktionieren sofort nicht mehr. Dein Konto bleibt bestehen, ebenso deine Anmeldedaten und Anzeigeeinstellungen wie Sprache, Zeitzone und Einheiten. Das lässt sich nicht rückgängig machen.", + "dangerZoneSuccess": "Deine Gesundheitsakte wurde gelöscht. Dein Konto und deine Anmeldung bleiben unverändert.", "dangerZoneDeleteFailed": "Löschen fehlgeschlagen", "finalDelete": "Endgültig löschen", "deleteAccountCardTitle": "Konto vollständig löschen", diff --git a/messages/en.json b/messages/en.json index 4191253be..4c498d987 100644 --- a/messages/en.json +++ b/messages/en.json @@ -5217,10 +5217,10 @@ "apiEndpointAuth": "Authentication", "apiEndpointExample": "Body example", "dangerZone": "Delete All Data", - "dangerZoneDescription": "Deletes all your health data and integrations. Your user account will be preserved.", + "dangerZoneDescription": "Erases your whole health record and every integration connection. Your account and the credentials you sign in with are kept.", "dangerZoneConfirm": "Delete all data?", - "dangerZoneConfirmDescription": "This will permanently delete all your health data and integrations. Your user account will be preserved.", - "dangerZoneSuccess": "All personal data has been deleted", + "dangerZoneConfirmDescription": "This permanently deletes everything in your record: measurements, medications, mood entries, lab results, cycle entries, documents, AI conversations and every integration connection, together with everything derived from them and anything you deleted earlier. Share links you gave to a doctor stop working immediately. Your account stays, along with the credentials you sign in with and display settings such as language, timezone and units. This cannot be undone.", + "dangerZoneSuccess": "Your health record has been deleted. Your account and sign-in are unchanged.", "dangerZoneDeleteFailed": "Deletion failed", "finalDelete": "Delete permanently", "deleteAccountCardTitle": "Delete account entirely", diff --git a/messages/es.json b/messages/es.json index d046fbd97..8c609dfcd 100644 --- a/messages/es.json +++ b/messages/es.json @@ -5217,10 +5217,10 @@ "apiEndpointAuth": "Autenticación", "apiEndpointExample": "Ejemplo de cuerpo", "dangerZone": "Eliminar todos los datos", - "dangerZoneDescription": "Elimina todos tus datos de salud e integraciones. Tu cuenta de usuario se conservará.", + "dangerZoneDescription": "Borra todo tu historial de salud y todas las conexiones de integración. Tu cuenta y las credenciales con las que inicias sesión se conservan.", "dangerZoneConfirm": "¿Eliminar todos los datos?", - "dangerZoneConfirmDescription": "Esto eliminará de forma permanente todos tus datos de salud e integraciones. Tu cuenta de usuario se conservará.", - "dangerZoneSuccess": "Se han eliminado todos los datos personales", + "dangerZoneConfirmDescription": "Esto elimina de forma permanente todo lo que hay en tu historial: mediciones, medicamentos, entradas de ánimo, resultados de laboratorio, entradas de ciclo, documentos, conversaciones con la IA y todas las conexiones de integración, junto con todo lo derivado de ello y todo lo que eliminaste antes. Los enlaces compartidos que diste a una consulta dejan de funcionar de inmediato. Tu cuenta se mantiene, junto con las credenciales con las que inicias sesión y los ajustes de presentación como el idioma, la zona horaria y las unidades. Esto no se puede deshacer.", + "dangerZoneSuccess": "Se ha eliminado tu historial de salud. Tu cuenta y tu inicio de sesión no han cambiado.", "dangerZoneDeleteFailed": "Falló la eliminación", "finalDelete": "Eliminar permanentemente", "deleteAccountCardTitle": "Eliminar la cuenta por completo", diff --git a/messages/fr.json b/messages/fr.json index 2eda57ea9..678b46765 100644 --- a/messages/fr.json +++ b/messages/fr.json @@ -5217,10 +5217,10 @@ "apiEndpointAuth": "Authentification", "apiEndpointExample": "Exemple de corps", "dangerZone": "Supprimer toutes les données", - "dangerZoneDescription": "Supprime toutes vos données de santé et intégrations. Votre compte utilisateur sera conservé.", + "dangerZoneDescription": "Efface l’intégralité de votre dossier de santé et toutes les connexions d’intégration. Votre compte et vos identifiants de connexion sont conservés.", "dangerZoneConfirm": "Supprimer toutes les données ?", - "dangerZoneConfirmDescription": "Cette action supprimera définitivement toutes vos données de santé et intégrations. Votre compte utilisateur sera conservé.", - "dangerZoneSuccess": "Toutes les données personnelles ont été supprimées", + "dangerZoneConfirmDescription": "Cette action supprime définitivement tout ce que contient votre dossier : mesures, médicaments, entrées d’humeur, résultats de laboratoire, entrées de cycle, documents, conversations avec l’IA et toutes les connexions d’intégration, ainsi que tout ce qui en découle et tout ce que vous aviez supprimé auparavant. Les liens de partage remis à un cabinet cessent aussitôt de fonctionner. Votre compte reste en place, de même que vos identifiants de connexion et vos réglages d’affichage comme la langue, le fuseau horaire et les unités. Cette action est irréversible.", + "dangerZoneSuccess": "Votre dossier de santé a été supprimé. Votre compte et votre connexion sont inchangés.", "dangerZoneDeleteFailed": "Échec de la suppression", "finalDelete": "Supprimer définitivement", "deleteAccountCardTitle": "Supprimer entièrement le compte", diff --git a/messages/it.json b/messages/it.json index f772e54ed..5a791cdc9 100644 --- a/messages/it.json +++ b/messages/it.json @@ -5217,10 +5217,10 @@ "apiEndpointAuth": "Autenticazione", "apiEndpointExample": "Esempio di body", "dangerZone": "Elimina tutti i dati", - "dangerZoneDescription": "Elimina tutti i tuoi dati sanitari e le integrazioni. Il tuo account utente verrà conservato.", + "dangerZoneDescription": "Cancella l’intera cartella sanitaria e ogni connessione di integrazione. Il tuo account e le credenziali con cui accedi restano.", "dangerZoneConfirm": "Eliminare tutti i dati?", - "dangerZoneConfirmDescription": "Questa azione eliminerà definitivamente tutti i tuoi dati sanitari e le integrazioni. Il tuo account utente verrà conservato.", - "dangerZoneSuccess": "Tutti i dati personali sono stati eliminati", + "dangerZoneConfirmDescription": "Questa azione elimina definitivamente tutto ciò che contiene la tua cartella: misurazioni, farmaci, voci dell’umore, risultati di laboratorio, voci del ciclo, documenti, conversazioni con l’IA e ogni connessione di integrazione, insieme a tutto ciò che ne deriva e a tutto quello che avevi eliminato prima. I link di condivisione consegnati a uno studio medico smettono subito di funzionare. Il tuo account resta, insieme alle credenziali con cui accedi e alle impostazioni di visualizzazione come lingua, fuso orario e unità. Non può essere annullato.", + "dangerZoneSuccess": "La tua cartella sanitaria è stata eliminata. Account e accesso restano invariati.", "dangerZoneDeleteFailed": "Eliminazione non riuscita", "finalDelete": "Elimina definitivamente", "deleteAccountCardTitle": "Elimina completamente l’account", diff --git a/messages/pl.json b/messages/pl.json index 45354f0dc..92b747092 100644 --- a/messages/pl.json +++ b/messages/pl.json @@ -5217,10 +5217,10 @@ "apiEndpointAuth": "Uwierzytelnianie", "apiEndpointExample": "Przykład treści", "dangerZone": "Usuń wszystkie dane", - "dangerZoneDescription": "Usuwa wszystkie Twoje dane zdrowotne i integracje. Twoje konto użytkownika zostanie zachowane.", + "dangerZoneDescription": "Kasuje całą Twoją dokumentację zdrowotną i wszystkie połączenia integracji. Konto i dane logowania zostają zachowane.", "dangerZoneConfirm": "Usunąć wszystkie dane?", - "dangerZoneConfirmDescription": "Spowoduje to trwałe usunięcie wszystkich Twoich danych zdrowotnych i integracji. Twoje konto użytkownika zostanie zachowane.", - "dangerZoneSuccess": "Wszystkie dane osobowe zostały usunięte", + "dangerZoneConfirmDescription": "Ta czynność trwale usuwa wszystko z Twojej dokumentacji: pomiary, leki, wpisy nastroju, wyniki badań, wpisy cyklu, dokumenty, rozmowy z SI oraz wszystkie połączenia integracji, a wraz z nimi wszystko, co z nich wyliczono, i wszystko, co usunięto wcześniej. Linki udostępnione poradni natychmiast przestają działać. Konto zostaje, razem z danymi logowania i ustawieniami wyświetlania, takimi jak język, strefa czasowa i jednostki. Nie można tego cofnąć.", + "dangerZoneSuccess": "Twoja dokumentacja zdrowotna została usunięta. Konto i logowanie pozostają bez zmian.", "dangerZoneDeleteFailed": "Usuwanie nie powiodło się", "finalDelete": "Usuń trwale", "deleteAccountCardTitle": "Usuń całe konto", diff --git a/src/__tests__/copy-matches-behaviour-guard.test.ts b/src/__tests__/copy-matches-behaviour-guard.test.ts index 5b26a9c1c..345f18467 100644 --- a/src/__tests__/copy-matches-behaviour-guard.test.ts +++ b/src/__tests__/copy-matches-behaviour-guard.test.ts @@ -69,11 +69,12 @@ const FINALITY_PHRASES: Record = { ], it: [ "non può essere annullata", + "non può essere annullato", "definitivamente", "definitiva", "permanente", ], - pl: ["nie można cofnąć", "trwale", "nieodwracaln"], + pl: ["nie można cofnąć", "nie można tego cofnąć", "trwale", "nieodwracaln"], }; /** Per-locale phrase that promises the short undo window. */ @@ -108,6 +109,12 @@ const PERMANENT_CONFIRM_KEYS = [ "mood.manage.purgeBody", // GDPR Art. 17 account purge "settings.deleteAccountConfirmDescription", + // hard delete of every user-scoped row except the sign-in credentials + "settings.dangerZoneConfirmDescription", + // hard delete since v1.32.40 — the tombstone served nothing and the + // dialog already promised permanence + "measurementReminders.deleteConfirmDescription", + "records.allergies.deleteConfirmDescription", ] as const; describe("delete confirmations describe what the surface actually does", () => { diff --git a/src/__tests__/data-wipe-completeness.test.ts b/src/__tests__/data-wipe-completeness.test.ts new file mode 100644 index 000000000..98315046d --- /dev/null +++ b/src/__tests__/data-wipe-completeness.test.ts @@ -0,0 +1,286 @@ +/** + * Structural guard binding `prisma/schema.prisma` to the "Delete All Data" + * wipe plan. + * + * The failure it exists to catch: a model is added to the schema, it is + * user-scoped from birth, and the wipe list is "the follow-up". Nothing fails + * — the route keeps deleting what it always deleted, the toast keeps saying + * "all personal data has been deleted", and the new table quietly joins the + * set of things that survive a confirmation the person typed by hand. That is + * how a 13-table wipe ended up facing an 80-table schema. + * + * Both ends are literals — Prisma model blocks on one side, exported arrays + * and objects on the other — so the matcher is exact. Nothing here greps for + * intent. + * + * What it proves: + * 1. every model carrying a `userId` column is either wiped or exempt with a + * reason; + * 2. every model without one either reaches a wiped model through a chain of + * required `onDelete: Cascade` relations (so the database removes it) or + * is declared instance-scoped; + * 3. every `User` column is either reset or kept with a reason; + * 4. the delete order lists children before parents, so the per-model counts + * in the audit row are truthful; + * 5. no exemption has gone stale. + * + * Its honest limit: it proves classification, not judgement. It cannot tell + * that a model was put on the exempt list for a bad reason — only that + * somebody had to write a reason down. And it reads relations, so a table + * linked to an account by a bare `userId` string with no foreign key (there + * are two: `TelegramScheduledDeletion`, `TelegramPromptContext`) is caught by + * rule 1 only because the column name matches the convention. + * + * Mutation check: remove any entry from `WIPE_MODELS` and this goes red naming + * that model; add a column to `model User` without classifying it and it goes + * red naming the column. + */ +import { readFileSync } from "node:fs"; +import { join } from "node:path"; + +import { describe, it, expect } from "vitest"; + +import { + INSTANCE_SCOPED, + USER_KEPT_FIELDS, + USER_RESET, + WIPE_EXEMPT, + WIPE_MODELS, + wipeDelegateKey, +} from "@/lib/data-wipe/wipe-plan"; + +const SCHEMA = join(process.cwd(), "prisma", "schema.prisma"); + +interface Relation { + /** Target model name. */ + target: string; + cascade: boolean; + /** `true` when the relation field is optional (`Model?`). */ + optional: boolean; +} + +interface ModelShape { + scalars: string[]; + relations: Relation[]; +} + +function parseSchema(schema: string): Map { + const blocks = [...schema.matchAll(/^model\s+(\w+)\s*\{([\s\S]*?)^\}/gm)].map( + (m) => ({ name: m[1], body: m[2] }), + ); + const modelNames = new Set(blocks.map((b) => b.name)); + + const out = new Map(); + for (const block of blocks) { + const scalars: string[] = []; + const relations: Relation[] = []; + for (const rawLine of block.body.split("\n")) { + const line = rawLine.trim(); + if (!line || line.startsWith("//") || line.startsWith("@@")) continue; + const match = /^(\w+)\s+(\w+)(\[\])?(\?)?/.exec(line); + if (!match) continue; + const [, field, type, isList, isOptional] = match; + if (modelNames.has(type)) { + // A list side of a relation carries no column and cannot cascade. + if (isList) continue; + relations.push({ + target: type, + cascade: line.includes("onDelete: Cascade"), + optional: Boolean(isOptional), + }); + continue; + } + if (isList && type === type.toUpperCase()) { + // Scalar / enum list column — still a column. + scalars.push(field); + continue; + } + scalars.push(field); + } + out.set(block.name, { scalars, relations }); + } + return out; +} + +const schemaText = readFileSync(SCHEMA, "utf8"); +const models = parseSchema(schemaText); +const wipeSet = new Set(WIPE_MODELS); + +describe("data-wipe completeness", () => { + it("parses the schema into a plausible shape", () => { + expect(models.size).toBeGreaterThan(100); + expect(models.get("Measurement")?.scalars).toContain("userId"); + expect(models.get("Measurement")?.scalars).not.toContain("user"); + expect(models.get("User")?.scalars).toContain("heightCm"); + expect(models.get("User")?.scalars).not.toContain("measurements"); + expect( + models.get("CoachMessage")?.relations.map((r) => r.target), + ).toContain("CoachConversation"); + }); + + it("every model with a userId column is wiped or exempt with a reason", () => { + const userScoped = [...models] + .filter(([, shape]) => shape.scalars.includes("userId")) + .map(([name]) => name); + + expect(userScoped.length).toBeGreaterThan(80); + + const unclassified = userScoped.filter( + (name) => + !wipeSet.has(name) && + !(name in WIPE_EXEMPT) && + !(name in INSTANCE_SCOPED), + ); + + if (unclassified.length > 0) { + throw new Error( + `${unclassified.length} user-scoped model(s) are in neither the wipe list nor the exemption list:\n` + + unclassified.map((n) => ` ❌ ${n}`).join("\n") + + "\n\nA person who types the confirmation on Settings → Delete All Data " + + "expects these rows gone. Add each to WIPE_MODELS, or to WIPE_EXEMPT " + + "with the reason keeping it is not account deletion — and say so in " + + "the confirmation copy.", + ); + } + + const bothWays = userScoped.filter( + (name) => wipeSet.has(name) && name in WIPE_EXEMPT, + ); + expect(bothWays, "a model cannot be both wiped and exempt").toEqual([]); + }); + + it("every model without a userId column is reached by cascade or declared instance-scoped", () => { + // Fixpoint over required cascade relations: a model is covered when the + // database removes it as a consequence of a row the wipe deletes. + const covered = new Set(wipeSet); + for (;;) { + let grew = false; + for (const [name, shape] of models) { + if (covered.has(name)) continue; + const reached = shape.relations.some( + (r) => r.cascade && !r.optional && covered.has(r.target), + ); + if (reached) { + covered.add(name); + grew = true; + } + } + if (!grew) break; + } + + const orphans = [...models] + .filter(([name, shape]) => !shape.scalars.includes("userId")) + .map(([name]) => name) + .filter( + (name) => + !covered.has(name) && + !(name in INSTANCE_SCOPED) && + !(name in WIPE_EXEMPT), + ); + + if (orphans.length > 0) { + throw new Error( + `${orphans.length} model(s) carry no userId, are not removed by any cascade from a wiped row, and are not declared instance-scoped:\n` + + orphans.map((n) => ` ❌ ${n}`).join("\n") + + "\n\nEither give the parent relation onDelete: Cascade, add the model " + + "to WIPE_MODELS, or add it to INSTANCE_SCOPED with the reason it " + + "belongs to the instance rather than to an account.", + ); + } + }); + + it("every User column is either reset or kept with a reason", () => { + const columns = models.get("User")?.scalars ?? []; + expect(columns.length).toBeGreaterThan(80); + + const reset = new Set(Object.keys(USER_RESET)); + const kept = new Set(Object.keys(USER_KEPT_FIELDS)); + + const unclassified = columns.filter((c) => !reset.has(c) && !kept.has(c)); + if (unclassified.length > 0) { + throw new Error( + `${unclassified.length} User column(s) are in neither USER_RESET nor USER_KEPT_FIELDS:\n` + + unclassified.map((c) => ` ❌ ${c}`).join("\n") + + "\n\nA column on the account row survives the wipe by default. Reset " + + "it, or record why keeping it is not keeping the person's record.", + ); + } + + const bothWays = columns.filter((c) => reset.has(c) && kept.has(c)); + expect(bothWays, "a column cannot be both reset and kept").toEqual([]); + }); + + it("carries no stale classification", () => { + for (const name of WIPE_MODELS) { + expect( + models.has(name), + `WIPE_MODELS names "${name}", which is not a model`, + ).toBe(true); + } + for (const [name, reason] of Object.entries(WIPE_EXEMPT)) { + expect( + models.has(name), + `WIPE_EXEMPT names "${name}", which is not a model`, + ).toBe(true); + expect( + reason.length, + `WIPE_EXEMPT.${name} needs a real reason`, + ).toBeGreaterThan(30); + } + for (const [name, reason] of Object.entries(INSTANCE_SCOPED)) { + expect( + models.has(name), + `INSTANCE_SCOPED names "${name}", which is not a model`, + ).toBe(true); + expect( + reason.length, + `INSTANCE_SCOPED.${name} needs a real reason`, + ).toBeGreaterThan(20); + } + const columns = new Set(models.get("User")?.scalars ?? []); + for (const [column, reason] of Object.entries(USER_KEPT_FIELDS)) { + expect( + columns.has(column), + `USER_KEPT_FIELDS names "${column}", which is no longer a User column`, + ).toBe(true); + expect( + reason.length, + `USER_KEPT_FIELDS.${column} needs a real reason`, + ).toBeGreaterThan(20); + } + expect(new Set(WIPE_MODELS).size, "WIPE_MODELS repeats a model").toBe( + WIPE_MODELS.length, + ); + }); + + it("deletes children before their parents so the counts are truthful", () => { + const position = new Map(WIPE_MODELS.map((m, i) => [m as string, i])); + const violations: string[] = []; + for (const child of WIPE_MODELS) { + const shape = models.get(child); + if (!shape) continue; + for (const relation of shape.relations) { + if (!relation.cascade) continue; + if (relation.target === child) continue; + if (!position.has(relation.target)) continue; + if (position.get(child)! > position.get(relation.target)!) { + violations.push( + `${child} (#${position.get(child)}) cascades from ${relation.target} (#${position.get(relation.target)})`, + ); + } + } + } + expect( + violations, + `WIPE_MODELS deletes a parent before its child, so the child's count reports 0 for rows that existed:\n${violations.join("\n")}`, + ).toEqual([]); + }); + + it("maps every wiped model to a plausible delegate key", () => { + for (const model of WIPE_MODELS) { + const key = wipeDelegateKey(model); + expect(key[0]).toBe(model[0].toLowerCase()); + expect(key.slice(1)).toBe(model.slice(1)); + } + }); +}); diff --git a/src/app/api/allergies/[id]/route.ts b/src/app/api/allergies/[id]/route.ts index af618247e..10ee3ccb2 100644 --- a/src/app/api/allergies/[id]/route.ts +++ b/src/app/api/allergies/[id]/route.ts @@ -117,23 +117,25 @@ export const DELETE = apiHandler( const { id } = await params; const existing = await prisma.allergy.findUnique({ where: { id }, - select: { id: true, userId: true, deletedAt: true }, + select: { id: true, userId: true }, }); if (!existing || existing.userId !== user.id) { return apiError("Allergy not found", 404); } - if (existing.deletedAt === null) { - await prisma.allergy.update({ - where: { id }, - data: { deletedAt: new Date() }, - }); - await auditLog("allergy.delete", { - userId: user.id, - ipAddress: getClientIp(request), - details: { allergyId: id }, - }); - } + // Hard delete. The confirmation says it can't be undone, and nothing here + // needs a tombstone: no restore route reaches an allergy, no other table + // references one, it is absent from the `/api/sync/changes` delta feed, + // and every read already filters `deletedAt: null`. A row already carrying + // a tombstone from before this changed is removed too, so the record + // converges on what the dialog promised. + await prisma.allergy.delete({ where: { id } }); + + await auditLog("allergy.delete", { + userId: user.id, + ipAddress: getClientIp(request), + details: { allergyId: id }, + }); annotate({ action: { name: "allergy.delete", entity_type: "allergy", entity_id: id }, diff --git a/src/app/api/measurement-reminders/[id]/route.ts b/src/app/api/measurement-reminders/[id]/route.ts index aad5e46e0..6f37d2fd6 100644 --- a/src/app/api/measurement-reminders/[id]/route.ts +++ b/src/app/api/measurement-reminders/[id]/route.ts @@ -206,12 +206,13 @@ export const DELETE = apiHandler( return apiError("Measurement reminder not found", 404); } - // Soft-delete (tombstone) parity with the rest of the tree. A - // re-delete of an already-tombstoned row is idempotent. - await prisma.measurementReminder.update({ - where: { id }, - data: { deletedAt: new Date() }, - }); + // Hard delete. The confirmation says "permanently deleted", and this row + // has nothing that a tombstone would serve: it is not in the + // `/api/sync/changes` delta feed, no restore route reaches it, no other + // table references it, and every read already filters `deletedAt: null`. + // The tombstone bought parity with tables that need one and cost the + // dialog its accuracy, so the row goes. + await prisma.measurementReminder.delete({ where: { id } }); await auditLog("measurementReminder.delete", { userId: user.id, diff --git a/src/app/api/settings/data/route.ts b/src/app/api/settings/data/route.ts index beb67d1fc..38a744be4 100644 --- a/src/app/api/settings/data/route.ts +++ b/src/app/api/settings/data/route.ts @@ -9,11 +9,37 @@ import { } from "@/lib/api-handler"; import { annotate } from "@/lib/logging/context"; import { invalidateUserData } from "@/lib/cache/invalidate"; +import { + resolveWipeDelegate, + USER_RESET, + wipeDelegateKey, + WIPE_MODELS, +} from "@/lib/data-wipe/wipe-plan"; export const dynamic = "force-dynamic"; /** - * Delete all user-owned health/integration data while keeping the account. + * Budget for the wipe transaction. + * + * Prisma's default interactive-transaction timeout is 5 s, which was already + * optimistic for thirteen `deleteMany` statements and is not survivable for + * the full user-scoped set on an account with a large import behind it. The + * whole action is one transaction on purpose — a half-applied wipe is worse + * than none, because the person is told it succeeded either way. + */ +const WIPE_TRANSACTION_TIMEOUT_MS = 120_000; +const WIPE_TRANSACTION_MAX_WAIT_MS = 15_000; + +/** + * Delete every row this account owns, keeping the account and the credentials + * that sign into it. + * + * The set of tables is not written here. It is declared once in + * `@/lib/data-wipe/wipe-plan` and held against `prisma/schema.prisma` by + * `src/__tests__/data-wipe-completeness.test.ts`, so a model added to the + * schema cannot quietly land outside the wipe — which is exactly how this + * route came to delete thirteen tables out of eighty-odd while telling people + * it had deleted all of them. * * v1.23 — gated by a fresh step-up for MFA-enrolled accounts (see the account * deletion route); single-factor accounts keep the typed-confirmation-only @@ -40,92 +66,50 @@ export const DELETE = apiHandler(async (request: NextRequest) => { const userId = user.id; - const result = await prisma.$transaction(async (tx) => { - const measurements = await tx.measurement.deleteMany({ - where: { userId }, - }); - const intakeEvents = await tx.medicationIntakeEvent.deleteMany({ - where: { userId }, - }); - const medications = await tx.medication.deleteMany({ - where: { userId }, - }); - const moodEntries = await tx.moodEntry.deleteMany({ - where: { userId }, - }); - // v1.4.39 W-MOOD — wipe the persisted rollup partition for this - // user so the next analytics read returns an empty envelope. - await tx.moodEntryRollup.deleteMany({ where: { userId } }); - const apiTokens = await tx.apiToken.deleteMany({ - where: { userId }, - }); - const withingsConnections = await tx.withingsConnection.deleteMany({ - where: { userId }, - }); - const notificationChannels = await tx.notificationChannel.deleteMany({ - where: { userId }, - }); - const pushSubscriptions = await tx.pushSubscription.deleteMany({ - where: { userId }, - }); - const dataBackups = await tx.dataBackup.deleteMany({ - where: { userId }, - }); - const achievements = await tx.userAchievement.deleteMany({ - where: { userId }, - }); - const telegramDeletions = await tx.telegramScheduledDeletion.deleteMany({ - where: { userId }, - }); - const auditLogs = await tx.auditLog.deleteMany({ - where: { userId }, - }); + const counts = await prisma.$transaction( + async (tx) => { + const perModel: Record = {}; + for (const model of WIPE_MODELS) { + const { count } = await resolveWipeDelegate(tx, model).deleteMany({ + where: { userId }, + }); + if (count > 0) perModel[wipeDelegateKey(model)] = count; + } - await tx.user.update({ - where: { id: userId }, - data: { - heightCm: null, - dateOfBirth: null, - gender: null, - insightsPrivacyMode: "aggregated", - insightsCachedAt: null, - insightsCachedText: null, - telegramBotToken: null, - telegramChatId: null, - telegramEnabled: false, - withingsClientIdEncrypted: null, - withingsClientSecretEncrypted: null, - onboardingCompletedAt: null, - }, - }); + // The account row survives; the personal data carried on its own columns + // does not. Same classification contract as the model list. + await tx.user.update({ where: { id: userId }, data: USER_RESET }); - return { - measurements: measurements.count, - intakeEvents: intakeEvents.count, - medications: medications.count, - moodEntries: moodEntries.count, - apiTokens: apiTokens.count, - withingsConnections: withingsConnections.count, - notificationChannels: notificationChannels.count, - pushSubscriptions: pushSubscriptions.count, - dataBackups: dataBackups.count, - achievements: achievements.count, - telegramDeletions: telegramDeletions.count, - auditLogs: auditLogs.count, - }; - }); + return perModel; + }, + { + timeout: WIPE_TRANSACTION_TIMEOUT_MS, + maxWait: WIPE_TRANSACTION_MAX_WAIT_MS, + }, + ); + const deletedRows = Object.values(counts).reduce((sum, n) => sum + n, 0); + + // Written after the transaction commits, so the row cannot be removed by the + // AuditLog delete inside it. await auditLog("user.data.clear", { userId, ipAddress: getClientIp(request), - details: result, + details: { deletedRows, models: counts }, }); - annotate({ action: { name: "settings.data.clear" }, meta: result }); + annotate({ + action: { name: "settings.data.clear" }, + meta: { + deleted_rows: deletedRows, + models_wiped: WIPE_MODELS.length, + models_with_rows: Object.keys(counts).length, + }, + }); // v1.16.9 — every cached payload was built on the rows just deleted; // hard-evict the user's buckets so no surface serves pre-wipe data. invalidateUserData(userId); - return apiSuccess({ cleared: true, ...result }); + return apiSuccess({ cleared: true, deletedRows, models: counts }); }); diff --git a/src/lib/data-wipe/wipe-plan.ts b/src/lib/data-wipe/wipe-plan.ts new file mode 100644 index 000000000..f14986763 --- /dev/null +++ b/src/lib/data-wipe/wipe-plan.ts @@ -0,0 +1,403 @@ +/** + * The one declaration of what "Delete All Data" means. + * + * The route this feeds used to carry its delete calls inline. That list was + * correct on the day it was written and then stopped being correct, silently, + * every time a model was added to `prisma/schema.prisma` — a new table is + * user-scoped from birth and outside the wipe by default, and nothing anywhere + * noticed. Sixty-odd tables accumulated on the wrong side of a confirmation + * dialog that says "permanently delete all your health data". + * + * So the list lives here, next to its own exemption list, and + * `src/__tests__/data-wipe-completeness.test.ts` enumerates the schema and + * fails when a model belongs to neither. Adding a model to the schema now + * forces a decision instead of granting a default. + * + * ── The boundary ─────────────────────────────────────────────────────────── + * + * This action erases everything the account owns EXCEPT what is needed to sign + * in again. Removing the sign-in credentials too would not be data deletion, + * it would be account deletion — and that has its own route + * (`src/app/api/settings/account/route.ts`, which deletes the `User` row and + * lets the schema's `onDelete: Cascade` do the rest). + * + * Everything in {@link WIPE_MODELS} is hard-deleted, including rows that were + * only soft-deleted before: `deleteMany({ where: { userId } })` carries no + * `deletedAt` filter, so a tombstone goes with the record. + * + * ── Why the list is ordered ──────────────────────────────────────────────── + * + * Correctness does not depend on the order — every child of a wiped model + * cascades at the database level. The order exists so the per-model counts in + * the audit row are truthful: delete a parent first and its children are gone + * before their own `deleteMany` runs, which would report 0 for rows that did + * exist. Children therefore come before their parents, and the completeness + * test asserts that property rather than trusting the author. + */ +import { Prisma } from "@/generated/prisma/client"; + +/** + * Every user-scoped model this action deletes, children before parents. + * + * Names are Prisma model names; {@link wipeDelegateKey} maps each to its + * client delegate. Keeping model names (not delegate keys) is what lets the + * completeness test compare this list against `schema.prisma` literally. + */ +export const WIPE_MODELS = [ + // ── Measurements and their derived tiers ──────────────────────────────── + "Measurement", + // The rollup tier is a per-day, per-metric reconstruction of the same + // history. A wipe that leaves it behind is not a wipe. + "MeasurementRollup", + "MeasurementReminder", + + // ── Medication ────────────────────────────────────────────────────────── + "MedicationIntakeEvent", + "MedicationPauseEra", + "MedicationSideEffect", + "MedicationInventoryItem", + "MedicationIntakeImportJob", + "MedicationComplianceRollup", + + // ── Mood ──────────────────────────────────────────────────────────────── + "MoodEntry", + "MoodEntryRollup", + "MoodReminderDispatch", + "MoodTagHidden", + + // ── Clinical record ───────────────────────────────────────────────────── + "MentalHealthAssessment", + "LabResult", + "Biomarker", + "CustomMetricEntry", + "MenstrualCycle", + "CycleDayLog", + "CycleSymptom", + "CycleProfile", + "CyclePrediction", + "Allergy", + "FamilyHistoryEntry", + "IllnessDayLog", + "EcgRecording", + "NutrientIntakeDay", + + // ── Activity ──────────────────────────────────────────────────────────── + "WorkoutInsight", + "WorkoutInsightGenerationClaim", + "PersonalRecord", + "StrainTrimpCache", + + // ── Context and engagement ────────────────────────────────────────────── + "EnvironmentContext", + "EnvironmentTravelLocation", + "UserHealthProfile", + "UserAchievement", + "ArrivalReaction", + "DismissedPriorityItem", + "RecommendationFeedback", + + // ── Documents ─────────────────────────────────────────────────────────── + "DocumentContentIndex", + "DocumentThumbnail", + "DocumentConditionLink", + "ExtractedFact", + "ImportJob", + + // ── AI ────────────────────────────────────────────────────────────────── + "CoachConversation", + "CoachFact", + "CoachPlan", + "CoachReminder", + "CoachUsage", + "InsightNarrative", + "ProviderHealth", + + // ── Sharing ───────────────────────────────────────────────────────────── + // Deleting the row is the revocation: `resolveShareToken` / + // `resolveShareGateState` both resolve an unknown `tokenHash` to `null`, and + // null is the same blunt 404 a revoked link gets. + "ClinicianShareLink", + + // ── Integrations ──────────────────────────────────────────────────────── + "WithingsConnection", + "WithingsOAuthState", + "WhoopConnection", + "WhoopOAuthState", + "WhoopConnectTicket", + "FitbitConnection", + "FitbitOAuthState", + "GoogleHealthConnection", + "GoogleHealthOAuthState", + "McpOAuthConnection", + "IntegrationStatus", + + // ── Notification transports ───────────────────────────────────────────── + "NotificationChannel", + "PushSubscription", + "PushAttempt", + "Device", + "TelegramScheduledDeletion", + "TelegramPromptContext", + + // ── API surface and operational trails ────────────────────────────────── + "StepUpElevation", + // Cached response envelopes — the bodies are the health payloads the API + // just returned. + "IdempotencyKey", + "DataBackup", + "AuditLog", + "ConsentReceipt", + "UserKnownDevice", + + // ── Parents, last ─────────────────────────────────────────────────────── + "Medication", + "MoodTag", + "MoodTagCategory", + "CustomMetric", + "IllnessEpisode", + "Workout", + "InboundDocument", + "ApiToken", +] as const; + +export type WipeModel = (typeof WIPE_MODELS)[number]; + +/** + * User-scoped models this action deliberately keeps, each with the reason. + * + * The rule is narrow and stated in the confirmation copy: what the account + * needs to sign in again survives. Anything added here that is not a sign-in + * credential needs a reason that survives being read aloud to the person who + * typed the confirmation. + */ +export const WIPE_EXEMPT: Readonly> = { + Session: + "the signed-in session performing the wipe; deleting it signs the person out mid-action and the account is preserved", + RefreshToken: + "per-device sign-in continuity; deleting it signs every paired device out and is account deletion by another name", + Passkey: "a sign-in credential — without it the account may be unreachable", + WebauthnMfaCredential: + "a second-factor credential; removing it weakens the account rather than clearing data", + MfaRecoveryCode: + "the second-factor recovery path; removing it can lock the account out permanently", + MfaChallenge: + "an in-flight authentication challenge, seconds-lived and swept by its own expiry", + AuthChallenge: + "an in-flight WebAuthn challenge, seconds-lived and swept by its own expiry", + TrustedDevice: + "the remember-this-device grant that suppresses a second-factor prompt; a sign-in credential", + OidcNativeHandoff: + "an in-flight one-time sign-in code, minutes-lived and swept by its own expiry", + InviteRedemption: + "the instance's registration ledger, not the person's record; even account deletion only detaches it (onDelete: SetNull) rather than removing it", +}; + +/** + * Models that carry no `userId` and belong to the instance rather than to any + * account, so no wipe of a single account may touch them. + * + * Everything else without a `userId` reaches a wiped or exempt model through a + * chain of `onDelete: Cascade` relations and needs no entry here; the + * completeness test proves that reachability rather than assuming it. + */ +export const INSTANCE_SCOPED: Readonly> = { + AppSettings: "instance-wide configuration singleton", + RateLimit: "instance-wide rate-limit buckets, keyed by string, self-expiring", + HostMetric: "instance-wide host telemetry, not attributable to an account", + CycleSymptomCategory: + "seeded catalogue shared by every account; a user's custom symptoms live on CycleSymptom", + IllnessSymptom: "seeded symptom catalogue shared by every account", + InviteToken: + "the instance's invite ledger; the creator relation cascades on account deletion, and a data wipe keeps the account", + User: "the account itself — preserved by definition; its columns are handled by USER_RESET / USER_KEPT_FIELDS", +}; + +/** + * The `User` columns this action clears, and the value each is reset to. + * + * The same rot applies here: a column added to `User` is personal data from + * birth and outside the reset by default. The completeness test compares these + * keys against the model's scalar columns, so a new column has to be + * classified. + * + * `Prisma.DbNull` rather than `null` for the JSON columns — on a nullable JSON + * field `null` is the JSON value `null`, not SQL NULL. + */ +export const USER_RESET = { + // Body and identity-of-the-record + heightCm: null, + dateOfBirth: null, + gender: null, + hasDiabetes: false, + fullName: null, + displayName: null, + insurerName: null, + insuranceNumberEncrypted: null, + insurerIkNumber: null, + lastReportPracticeName: null, + avatarBytes: null, + avatarContentType: null, + avatarUpdatedAt: null, + + // Where the person lives — an environment-context input, and a location + homeLat: null, + homeLon: null, + homeLabel: null, + homeTimezone: null, + homeSince: null, + + // Derived AI output cached on the row + insightsPrivacyMode: "aggregated", + insightsCachedAt: null, + insightsCachedText: null, + insightsSnapshotHash: null, + insightsWarmFailedAt: null, + insightsBriefingRerollDate: null, + morningDigestRefreshedOn: null, + insightsExcludeMetrics: [], + insightsLayoutJson: Prisma.DbNull, + + // AI provider configuration and keys + aiProvider: null, + aiModel: null, + aiBaseUrl: null, + aiAnthropicKeyEncrypted: null, + aiLocalKeyEncrypted: null, + aiOpenaiKeyEncrypted: null, + aiProviderChain: Prisma.DbNull, + aiResponseTimeoutSeconds: null, + disableCoach: false, + coachPrefsJson: Prisma.DbNull, + coachLastSeenAt: null, + documentsAutoAiRead: false, + labsLocalOcrEnabled: false, + codexAccessTokenEncrypted: null, + codexRefreshTokenEncrypted: null, + codexTokenExpiresAt: null, + codexConnectedAt: null, + codexConnectionStatus: "disconnected", + useCentralCodex: false, + + // Integration credentials and per-integration state + telegramBotToken: null, + telegramChatId: null, + telegramEnabled: false, + withingsClientIdEncrypted: null, + withingsClientSecretEncrypted: null, + whoopClientIdEncrypted: null, + whoopClientSecretEncrypted: null, + fitbitClientIdEncrypted: null, + fitbitClientSecretEncrypted: null, + googleHealthClientIdEncrypted: null, + googleHealthClientSecretEncrypted: null, + nightscoutUrlEncrypted: null, + nightscoutTokenEncrypted: null, + nightscoutAllowPrivateHost: false, + polarAccessTokenEncrypted: null, + polarUserIdEncrypted: null, + polarClientIdEncrypted: null, + polarClientSecretEncrypted: null, + ouraAccessTokenEncrypted: null, + ouraRefreshTokenEncrypted: null, + ouraClientIdEncrypted: null, + ouraClientSecretEncrypted: null, + stravaClientIdEncrypted: null, + stravaClientSecretEncrypted: null, + stravaAccessTokenEncrypted: null, + stravaRefreshTokenEncrypted: null, + stravaAthleteId: null, + stravaLastActivityAt: null, + stravaBackfillCompletedAt: null, + healthKitConfigJson: Prisma.DbNull, + healthKitLastSyncedAt: null, + lastSyncedAt: null, + sourcePriorityJson: Prisma.DbNull, + + // Choices that describe the record rather than the interface + thresholdsJson: Prisma.DbNull, + dashboardWidgetsJson: Prisma.DbNull, + medicationListLayoutJson: Prisma.DbNull, + moodTagLayoutJson: Prisma.DbNull, + reportSelectionJson: Prisma.DbNull, + modulePreferencesJson: Prisma.DbNull, + globalExcludedInjectionSites: [], + moodReminderEnabled: false, + notificationPrefs: Prisma.DbNull, + researchModeEnabled: false, + researchModeAcknowledgedAt: null, + researchModeAcknowledgedVersion: null, + + // Back to the start of the tour — the record it was built around is gone + onboardingCompletedAt: null, + onboardingStep: 0, + onboardingGoals: [], + onboardingTourCompleted: false, + onboardingTourProgressJson: Prisma.DbNull, +} satisfies Prisma.UserUpdateInput; + +/** + * `User` columns the wipe leaves alone, each with the reason. Same contract as + * {@link WIPE_EXEMPT}: sign-in, identity, and how the interface is rendered. + */ +export const USER_KEPT_FIELDS: Readonly> = { + id: "the account's primary key", + username: "the account's sign-in identity", + email: "the account's sign-in identity and recovery address", + passwordHash: "a sign-in credential — the account password", + role: "the account's authorisation level, set by the operator", + oidcIssuer: "a sign-in credential — the external identity binding", + oidcSub: "a sign-in credential — the external identity binding", + createdAt: "when the account was created; the account is preserved", + updatedAt: "row bookkeeping maintained by Prisma", + totpSecretEncrypted: "a second-factor credential", + totpConfirmedAt: "second-factor enrolment state", + totpLastStep: + "second-factor replay guard; clearing it re-opens a replay window", + mfaEnforced: "the operator's per-account second-factor policy", + passkeyUpgradeNudgeDismissed: + "an interface nudge the person already dismissed", + timezone: "an interface preference — how dates and times are rendered", + locale: "an interface preference — which language the interface speaks", + unitPreference: "an interface preference — metric or imperial rendering", + timeFormat: "an interface preference — 12- or 24-hour rendering", + dateFormat: "an interface preference — date-order rendering", + glucoseUnit: "an interface preference — mg/dL or mmol/L rendering", + disclaimerAcknowledgedAt: + "the account's acknowledgement of the medical disclaimer, which is about the app and not about the record", + disclaimerAcknowledgedVersion: + "the version of the medical disclaimer the account acknowledged", + documentQuotaBytes: + "a per-account storage quota set by the operator, not by the person", +}; + +/** Prisma client delegate key for a model name (`MoodEntry` → `moodEntry`). */ +export function wipeDelegateKey(model: string): string { + return model.charAt(0).toLowerCase() + model.slice(1); +} + +/** The narrow slice of a Prisma delegate the wipe loop uses. */ +export interface UserScopedDeleteDelegate { + deleteMany(args: { where: { userId: string } }): Promise<{ count: number }>; +} + +/** + * Resolve a model name to its delegate on a client or transaction handle. + * + * One documented cast: `WIPE_MODELS` is a literal list of model names checked + * against `schema.prisma` by the completeness test, and every entry indexes a + * delegate that exposes `deleteMany` over a `userId`. The test also asserts + * every entry resolves, so an unresolvable name fails the build rather than + * the request. + */ +export function resolveWipeDelegate( + client: object, + model: string, +): UserScopedDeleteDelegate { + const delegate = (client as Record)[ + wipeDelegateKey(model) + ]; + if (!delegate || typeof delegate.deleteMany !== "function") { + throw new Error(`No Prisma delegate for wipe model "${model}"`); + } + return delegate; +}