mirror of
https://github.com/MBombeck/HealthLog.git
synced 2026-11-19 00:12:18 +00:00
feat(account): hold account deletion and data wipe for a grace window
Deleting an account, a guardian deleting a managed profile, and "Delete
all data" were final the moment they were confirmed: the account row
cascaded into every table and every stored copy, and the off-host objects
were purged in the same breath. Nothing short of rolling the whole
instance back could return one account.
ACCOUNT_DELETION_GRACE_DAYS (14 by default, at most 30, 0 erases at once
as before) now sets a window:
- Account and managed-profile deletion lock the account (migration 0488:
deletion_requested_at, deletion_purge_at, deletion_requested_by_id).
Every session, refresh token, API token, connector, share link and
step-up elevation is revoked in the same transaction, and the record,
its stored copies and its off-host objects are left as they are.
- Sign-in is refused with 403 auth.account.deletion_pending and the
erasure date, after the credential was proved and before a second
factor is asked for. The session and Bearer resolvers and the acting-
account resolver refuse a pending account too, so a credential minted
in the moment before the lock is useless.
- POST /api/admin/users/{id}/undo-deletion (cookie-only, audit-logged)
clears the lock. The admin users list reports the pending state.
- The hourly account-deletion-purge job erases accounts whose window has
ended, exactly as the immediate deletion did, with the off-host purge
request committed alongside. The Guardian invariant is decided again;
a refused erasure stays pending and is reported.
- A wipe first stores the whole record as a PRE_WIPE_<ms> copy through
the writer the weekly copy uses, keeps it out of the wipe, and holds
its off-host purge back with a new not_before on the request. The
ordinary restore brings the record back; restoring that copy withdraws
the held purge. The purge job deletes the copy when its window ends.
Background work skips accounts pending deletion through one shared
predicate (src/lib/account-deletion/active-account.ts): every reminder,
digest, Coach, sync, backfill, rollup, score and backup enumeration
filters with it, and account-deletion-enumeration-guard.test.ts fails on
a query in background work that neither filters nor says why it need
not. Notification delivery and the AI capability loader refuse a pending
account as chokepoints behind it, and the Withings, WHOOP and Telegram
webhooks and the notification quick actions ignore one.
The privacy summary publishes the window. Two pieces of the reminder tick
and the off-host pass moved into modules of their own to keep the files
inside their size ratchet.
This commit is contained in:
1 parent
41c6eea2a1
commit
a69666fa16
158 files changed
+3164
-461
No files matched your search
@@ -8,20 +8,33 @@ import {
|
||||
MFA_STEP_UP_MAX_AGE_SECONDS,
|
||||
} from "@/lib/api-handler";
|
||||
import { annotate } from "@/lib/logging/context";
|
||||
import {
|
||||
kickOffhostPurge,
|
||||
requestOffhostPurge,
|
||||
} from "@/lib/jobs/offhost-purge";
|
||||
import { kickOffhostPurge } from "@/lib/jobs/offhost-purge";
|
||||
import {
|
||||
deleteGuardianAccountWithLifecycle,
|
||||
LastManagedGuardianError,
|
||||
} from "@/lib/managed-profiles/lifecycle";
|
||||
import {
|
||||
accountDeletionGraceDays,
|
||||
accountDeletionPurgeAt,
|
||||
} from "@/lib/account-deletion/grace";
|
||||
import {
|
||||
eraseAccount,
|
||||
lockAccountForDeletion,
|
||||
} from "@/lib/account-deletion/lifecycle";
|
||||
import { ACTIVE_ACCOUNT } from "@/lib/account-deletion/active-account";
|
||||
|
||||
export const dynamic = "force-dynamic";
|
||||
|
||||
/**
|
||||
* Permanently delete the user account and ALL associated data.
|
||||
* Cascading deletes in the schema handle all related records.
|
||||
* Delete the user account and ALL associated data.
|
||||
*
|
||||
* With a grace window (`ACCOUNT_DELETION_GRACE_DAYS`, 14 by default)
|
||||
* the account is locked rather than erased: every credential is revoked and
|
||||
* sign-in is refused at once, nothing acts for the account any more, and the
|
||||
* purge job erases it when the window ends. Until then an admin can undo it,
|
||||
* and the record, its stored copies and its off-host objects are exactly as
|
||||
* they were. With the window set to 0 the account is erased here, as before:
|
||||
* cascading deletes in the schema handle all related records.
|
||||
*
|
||||
* v1.23 — for an account with a second factor active this requires a fresh
|
||||
* step-up (within MFA_STEP_UP_MAX_AGE_SECONDS) in addition to the typed
|
||||
@@ -63,7 +76,11 @@ export const DELETE = apiHandler(async (request: NextRequest) => {
|
||||
|
||||
// Prevent last admin from deleting themselves
|
||||
if (user.role === "ADMIN") {
|
||||
const adminCount = await prisma.user.count({ where: { role: "ADMIN" } });
|
||||
// An admin already pending deletion is on their way out and cannot sign
|
||||
// in: they do not count as the one who stays.
|
||||
const adminCount = await prisma.user.count({
|
||||
where: { role: "ADMIN", ...ACTIVE_ACCOUNT },
|
||||
});
|
||||
if (adminCount <= 1) {
|
||||
return apiError("The last admin account cannot be deleted", 400);
|
||||
}
|
||||
@@ -83,35 +100,50 @@ export const DELETE = apiHandler(async (request: NextRequest) => {
|
||||
// the elevation would stay redeemable while the erasure was already running.
|
||||
await auth.commitElevation();
|
||||
|
||||
const requestedAt = new Date();
|
||||
const purgeAt = accountDeletionPurgeAt(
|
||||
requestedAt,
|
||||
accountDeletionGraceDays(),
|
||||
);
|
||||
|
||||
try {
|
||||
await deleteGuardianAccountWithLifecycle(userId, async (tx) => {
|
||||
// The invariant has now passed, so this success event cannot survive a
|
||||
// refusal. It is purged with the rest of the account's audit history.
|
||||
await auditLog("user.account.delete", {
|
||||
userId,
|
||||
ipAddress: getClientIp(request),
|
||||
details: { username },
|
||||
client: tx,
|
||||
});
|
||||
await deleteGuardianAccountWithLifecycle(
|
||||
userId,
|
||||
async (tx) => {
|
||||
// The invariant has now passed, so this success event cannot survive
|
||||
// a refusal. On an immediate erasure it is purged with the rest of the
|
||||
// account's audit history; during a grace window it is the account's
|
||||
// own record of the request.
|
||||
await auditLog("user.account.delete", {
|
||||
userId,
|
||||
ipAddress: getClientIp(request),
|
||||
details: {
|
||||
username,
|
||||
scheduledPurgeAt: purgeAt?.toISOString() ?? null,
|
||||
},
|
||||
client: tx,
|
||||
});
|
||||
|
||||
// Destroy all sessions before the user row goes, inside the same record
|
||||
// lifecycle transaction so a refusal leaves every account state intact.
|
||||
await tx.session.deleteMany({ where: { userId } });
|
||||
if (purgeAt) {
|
||||
// Locked, not erased: credentials revoked in this transaction,
|
||||
// the record untouched until the purge job reaches `purgeAt`.
|
||||
await lockAccountForDeletion(tx, {
|
||||
userId,
|
||||
requestedById: userId,
|
||||
requestedAt,
|
||||
purgeAt,
|
||||
});
|
||||
return;
|
||||
}
|
||||
|
||||
// Audit V3 NEW-V3-2 / GDPR Art. 17 fix: AuditLog rows have
|
||||
// `onDelete: SetNull` in the schema, which keeps PII (IP addresses, login
|
||||
// city geo) attached to the record after the user is deleted. We explicitly
|
||||
// purge them inside the same logical operation so account deletion is
|
||||
// genuinely complete erasure.
|
||||
await tx.auditLog.deleteMany({ where: { userId } });
|
||||
|
||||
// The nightly off-host copies go with the account. The request commits
|
||||
// with the deletion; the purge job deletes the objects.
|
||||
await requestOffhostPurge(tx, userId, "account_deleted");
|
||||
|
||||
// Delete user — all other related data is removed via onDelete: Cascade.
|
||||
await tx.user.delete({ where: { id: userId } });
|
||||
});
|
||||
// No window: erase now, inside the same record lifecycle transaction
|
||||
// so a refusal leaves every account state intact (sessions, the
|
||||
// account's audit history — GDPR Art. 17 — the off-host purge
|
||||
// request, then the row with everything cascading from it).
|
||||
await eraseAccount(tx, userId, "account_deleted");
|
||||
},
|
||||
{ erasing: purgeAt === null },
|
||||
);
|
||||
} catch (error) {
|
||||
if (error instanceof LastManagedGuardianError) {
|
||||
return apiError(
|
||||
@@ -123,12 +155,18 @@ export const DELETE = apiHandler(async (request: NextRequest) => {
|
||||
throw error;
|
||||
}
|
||||
|
||||
await kickOffhostPurge();
|
||||
if (!purgeAt) await kickOffhostPurge();
|
||||
|
||||
annotate({
|
||||
action: { name: "settings.account.delete" },
|
||||
meta: { username },
|
||||
meta: { username, deletion_scheduled: purgeAt !== null },
|
||||
});
|
||||
|
||||
return apiSuccess({ deleted: true });
|
||||
// `deleted` stays true either way: from the person's side the account is
|
||||
// gone now. `scheduledPurgeAt` says when it is erased, null when it already
|
||||
// was.
|
||||
return apiSuccess({
|
||||
deleted: true,
|
||||
scheduledPurgeAt: purgeAt?.toISOString() ?? null,
|
||||
});
|
||||
});
|
||||
@@ -25,6 +25,12 @@ import {
|
||||
WIPE_MODELS,
|
||||
} from "@/lib/data-wipe/wipe-plan";
|
||||
import { stampSyncReset } from "@/lib/sync/reset";
|
||||
import {
|
||||
accountDeletionGraceDays,
|
||||
accountDeletionPurgeAt,
|
||||
} from "@/lib/account-deletion/grace";
|
||||
import { takePreWipeCopy } from "@/lib/account-deletion/pre-wipe-copy";
|
||||
import { logCaught } from "@/lib/logging/signal";
|
||||
|
||||
export const dynamic = "force-dynamic";
|
||||
|
||||
@@ -85,6 +91,29 @@ export const DELETE = apiHandler(async (request: NextRequest) => {
|
||||
// (a no-op on the cookie path).
|
||||
await auth.commitElevation();
|
||||
|
||||
// With a deletion grace window, the whole record is stored first,
|
||||
// through the writer the weekly copy uses, as a copy of its own
|
||||
// (`PRE_WIPE_<ms>`). The wipe below leaves it in place, an admin can
|
||||
// restore it until the window ends, and the off-host copies from before
|
||||
// the wipe wait for the same date. A copy that cannot be written stops the
|
||||
// wipe before anything is deleted: an undoable wipe the person was told
|
||||
// about must not quietly become a final one.
|
||||
const wipedAt = new Date();
|
||||
const purgeAt = accountDeletionPurgeAt(wipedAt, accountDeletionGraceDays());
|
||||
let preWipeCopy: { id: string; type: string } | null = null;
|
||||
if (purgeAt) {
|
||||
try {
|
||||
preWipeCopy = await takePreWipeCopy(prisma, userId, wipedAt);
|
||||
} catch (error) {
|
||||
logCaught("settings.data.clear.pre_wipe_copy_failed", error);
|
||||
return apiError(
|
||||
"The copy kept before deleting could not be written, so nothing was deleted. Try again later or ask your admin.",
|
||||
503,
|
||||
{ errorCode: "data_wipe.copy_failed" },
|
||||
);
|
||||
}
|
||||
}
|
||||
|
||||
let counts: Record<string, number>;
|
||||
try {
|
||||
counts = await prisma.$transaction(
|
||||
@@ -116,7 +145,11 @@ export const DELETE = apiHandler(async (request: NextRequest) => {
|
||||
// The nightly off-host copies of the record are part of "all your
|
||||
// data". The request commits with the wipe; the purge job deletes
|
||||
// the objects and removes it.
|
||||
await requestOffhostPurge(tx, userId, "data_wiped");
|
||||
// Held back to the end of the grace window when there is one, so the
|
||||
// off-host copies from before the wipe stay as long as the copy above.
|
||||
await requestOffhostPurge(tx, userId, "data_wiped", {
|
||||
notBefore: purgeAt,
|
||||
});
|
||||
|
||||
// A guardian's wipe ends their grants; a provider app a profile
|
||||
// borrowed from them goes with those grants.
|
||||
@@ -133,6 +166,12 @@ export const DELETE = apiHandler(async (request: NextRequest) => {
|
||||
},
|
||||
);
|
||||
} catch (error) {
|
||||
// Nothing was wiped, so the copy taken for undoing it has no purpose.
|
||||
if (preWipeCopy) {
|
||||
await prisma.dataBackup
|
||||
.delete({ where: { id: preWipeCopy.id } })
|
||||
.catch((err) => logCaught("settings.data.clear.copy_cleanup", err));
|
||||
}
|
||||
if (error instanceof LastManagedGuardianError) {
|
||||
return apiError(
|
||||
"Add another Guardian or delete the managed profile first",
|
||||
@@ -153,7 +192,12 @@ export const DELETE = apiHandler(async (request: NextRequest) => {
|
||||
await auditLog("user.data.clear", {
|
||||
userId,
|
||||
ipAddress: getClientIp(request),
|
||||
details: { deletedRows, models: counts },
|
||||
details: {
|
||||
deletedRows,
|
||||
models: counts,
|
||||
preWipeCopyId: preWipeCopy?.id ?? null,
|
||||
restorableUntil: purgeAt?.toISOString() ?? null,
|
||||
},
|
||||
});
|
||||
|
||||
annotate({
|
||||
@@ -170,5 +214,12 @@ export const DELETE = apiHandler(async (request: NextRequest) => {
|
||||
invalidateUserData(userId);
|
||||
await kickOffhostPurge();
|
||||
|
||||
return apiSuccess({ cleared: true, deletedRows, models: counts });
|
||||
// `restorableUntil`: until when an admin can bring the record back from
|
||||
// the copy taken first; null when there is no grace window.
|
||||
return apiSuccess({
|
||||
cleared: true,
|
||||
deletedRows,
|
||||
models: counts,
|
||||
restorableUntil: purgeAt?.toISOString() ?? null,
|
||||
});
|
||||
});
|
||||
@@ -11,6 +11,7 @@ import { apiSuccess } from "@/lib/api-response";
|
||||
import { getAuditLogRetentionDays } from "@/lib/jobs/audit-log-cleanup";
|
||||
import { annotate } from "@/lib/logging/context";
|
||||
import { ENCRYPTED_COLUMNS } from "@/lib/crypto/encrypted-columns";
|
||||
import { accountDeletionGraceDays } from "@/lib/account-deletion/grace";
|
||||
|
||||
export const dynamic = "force-dynamic";
|
||||
|
||||
@@ -39,6 +40,11 @@ function resolveRetention() {
|
||||
auditLogDays: getAuditLogRetentionDays(),
|
||||
// The push-attempt + mood-dispatch ledgers are a fixed 90-day window.
|
||||
deliveryLogDays: 90,
|
||||
// Account deletion, a data wipe and a managed-profile deletion complete
|
||||
// after this many days (0: at once). The same resolver the purge job and
|
||||
// the deletion routes read, so the dialogs and this page state the
|
||||
// window that is enforced.
|
||||
accountDeletionGraceDays: accountDeletionGraceDays(),
|
||||
};
|
||||
}
|
||||
|
||||
|
||||
Reference in new issue
Block a user