mirror of
https://github.com/MBombeck/HealthLog.git
synced 2026-11-15 23:12:04 +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
@@ -46,6 +46,7 @@
|
||||
* can be walked.
|
||||
*/
|
||||
import { NextRequest } from "next/server";
|
||||
import { ACTIVE_ACCOUNT } from "@/lib/account-deletion/active-account";
|
||||
|
||||
import {
|
||||
apiHandler,
|
||||
@@ -100,7 +101,9 @@ export const GET = apiHandler(async () => {
|
||||
),
|
||||
listPage(MAX_GRANTS_PER_DIRECTION, (take) =>
|
||||
prisma.accountGrant.findMany({
|
||||
where: { granteeId: user.id },
|
||||
// A record pending deletion is locked for everyone who could
|
||||
// reach it, so it leaves the list of records shared with them.
|
||||
where: { granteeId: user.id, grantor: ACTIVE_ACCOUNT },
|
||||
orderBy: [{ createdAt: "desc" }, { id: "desc" }],
|
||||
take,
|
||||
include: { grantor: { select: GRANT_PARTY_SELECT } },
|
||||
|
||||
@@ -36,6 +36,8 @@ import {
|
||||
probeOffhostLifecycle,
|
||||
} from "@/lib/jobs/offhost-backup";
|
||||
import { OFFHOST_BACKUP_QUEUE } from "@/lib/jobs/offhost-backup-queue";
|
||||
import { offhostPurgeDue } from "@/lib/jobs/offhost-purge-queue";
|
||||
import { ACTIVE_ACCOUNT } from "@/lib/account-deletion/active-account";
|
||||
import {
|
||||
classifyOffhostBackup,
|
||||
OFFHOST_BACKUP_PERIOD_HOURS,
|
||||
@@ -106,7 +108,10 @@ export const GET = apiHandler(async () => {
|
||||
// listing call from a page render would put the operator's credentials on
|
||||
// the request path of every page view.
|
||||
const now = new Date();
|
||||
// An account pending deletion is skipped by the nightly upload on purpose;
|
||||
// its copy ageing is not a backup failure, so it is not listed.
|
||||
const offhostAccounts = await prisma.user.findMany({
|
||||
where: ACTIVE_ACCOUNT,
|
||||
select: {
|
||||
id: true,
|
||||
username: true,
|
||||
@@ -175,12 +180,16 @@ export const GET = apiHandler(async () => {
|
||||
// A wipe whose copies are already gone waits for the next nightly run
|
||||
// before its request is removed (see `offhost-purge.ts`); nothing of it is
|
||||
// left in the bucket, so it is not counted as a pending deletion.
|
||||
//
|
||||
// A wipe's request held back to the end of its grace window is not a
|
||||
// pending deletion either: those copies are kept on purpose until then.
|
||||
const stillInBucket = {
|
||||
NOT: {
|
||||
reason: "data_wiped",
|
||||
lastFailure: null,
|
||||
lastAttemptAt: { not: null },
|
||||
},
|
||||
...offhostPurgeDue(new Date()),
|
||||
};
|
||||
const [weeklyRunningSince, offhostRunningSince] = await Promise.all([
|
||||
readQueueRunningSince(DATA_BACKUP_QUEUE),
|
||||
|
||||
@@ -0,0 +1,53 @@
|
||||
/**
|
||||
* POST /api/admin/users/[id]/undo-deletion — give back an account pending
|
||||
* deletion.
|
||||
*
|
||||
* Account deletion, and a Guardian's deletion of a managed profile, lock the
|
||||
* account for a grace window before the purge job erases it
|
||||
* (`ACCOUNT_DELETION_GRACE_DAYS`). Until then the record, its stored copies
|
||||
* and its off-host objects are untouched, so undoing it clears the pending
|
||||
* stamp and nothing else: everything the account held is there as it was.
|
||||
* Every credential stays revoked; the person signs in again (a managed
|
||||
* profile is reached through its Guardians, as before).
|
||||
*
|
||||
* Cookie-only (`requireAdmin`), audit-logged for the admin and on the account
|
||||
* itself. Serialised with the purge job on the account row, so an undo either
|
||||
* lands before the erasure or answers 404 after it.
|
||||
*/
|
||||
import { NextRequest } from "next/server";
|
||||
import { apiHandler, requireAdmin } from "@/lib/api-handler";
|
||||
import { apiError, apiSuccess, getClientIp } from "@/lib/api-response";
|
||||
import { annotate } from "@/lib/logging/context";
|
||||
import { cancelAccountDeletion } from "@/lib/account-deletion/lifecycle";
|
||||
|
||||
export const dynamic = "force-dynamic";
|
||||
|
||||
export const POST = apiHandler(
|
||||
async (
|
||||
request: NextRequest,
|
||||
{ params }: { params: Promise<{ id: string }> },
|
||||
) => {
|
||||
const { user: admin } = await requireAdmin();
|
||||
const { id } = await params;
|
||||
annotate({
|
||||
action: {
|
||||
name: "admin.users.undo-deletion",
|
||||
entity_type: "user",
|
||||
entity_id: id,
|
||||
},
|
||||
});
|
||||
|
||||
const outcome = await cancelAccountDeletion({
|
||||
userId: id,
|
||||
adminId: admin.id,
|
||||
ipAddress: getClientIp(request),
|
||||
});
|
||||
if (outcome === "not_found") return apiError("User not found", 404);
|
||||
if (outcome === "not_pending") {
|
||||
return apiError("This account is not pending deletion", 409, {
|
||||
errorCode: "account.deletion.not_pending",
|
||||
});
|
||||
}
|
||||
return apiSuccess({ restored: true });
|
||||
},
|
||||
);
|
||||
@@ -100,6 +100,8 @@ describe("GET /api/admin/users", () => {
|
||||
// BigInt in Prisma, plain number on the wire.
|
||||
documentQuotaBytes: 2_147_483_648,
|
||||
passkeyCount: 2,
|
||||
// Not pending deletion.
|
||||
deletion: null,
|
||||
});
|
||||
expect(body.data[1].passkeyCount).toBe(0);
|
||||
expect(body.data[1].email).toBeNull();
|
||||
@@ -123,6 +125,9 @@ describe("GET /api/admin/users", () => {
|
||||
createdAt: true,
|
||||
mfaEnforced: true,
|
||||
documentQuotaBytes: true,
|
||||
deletionRequestedAt: true,
|
||||
deletionPurgeAt: true,
|
||||
deletionRequestedById: true,
|
||||
_count: { select: { passkeys: true } },
|
||||
});
|
||||
expect(args.select).not.toHaveProperty("passwordHash");
|
||||
|
||||
@@ -18,6 +18,9 @@ export const GET = apiHandler(async () => {
|
||||
createdAt: true,
|
||||
mfaEnforced: true,
|
||||
documentQuotaBytes: true,
|
||||
deletionRequestedAt: true,
|
||||
deletionPurgeAt: true,
|
||||
deletionRequestedById: true,
|
||||
_count: { select: { passkeys: true } },
|
||||
},
|
||||
orderBy: { createdAt: "asc" },
|
||||
@@ -39,6 +42,20 @@ export const GET = apiHandler(async () => {
|
||||
documentQuotaBytes:
|
||||
u.documentQuotaBytes === null ? null : Number(u.documentQuotaBytes),
|
||||
passkeyCount: u._count.passkeys,
|
||||
// An account pending deletion: when it was asked for, when the
|
||||
// purge job erases it, and whether the account asked itself or a
|
||||
// Guardian deleted the managed profile. Null on every other account.
|
||||
// The list offers "Undo deletion" on these rows until `purgeAt`.
|
||||
deletion: u.deletionRequestedAt
|
||||
? {
|
||||
requestedAt: u.deletionRequestedAt,
|
||||
purgeAt: u.deletionPurgeAt,
|
||||
requestedBy:
|
||||
u.deletionRequestedById === u.id
|
||||
? ("self" as const)
|
||||
: ("guardian" as const),
|
||||
}
|
||||
: null,
|
||||
})),
|
||||
);
|
||||
});
|
||||
@@ -112,6 +112,8 @@ export const POST = apiHandler(async (request: NextRequest) => {
|
||||
username: true,
|
||||
email: true,
|
||||
onboardingCompletedAt: true,
|
||||
deletionRequestedAt: true,
|
||||
deletionPurgeAt: true,
|
||||
totpConfirmedAt: true,
|
||||
totpSecretEncrypted: true,
|
||||
totpLastStep: true,
|
||||
|
||||
@@ -102,7 +102,13 @@ export const POST = apiHandler(async (request: NextRequest) => {
|
||||
|
||||
const user = await prisma.user.findUnique({
|
||||
where: { id: challenge.userId },
|
||||
select: { id: true, username: true, onboardingCompletedAt: true },
|
||||
select: {
|
||||
id: true,
|
||||
username: true,
|
||||
onboardingCompletedAt: true,
|
||||
deletionRequestedAt: true,
|
||||
deletionPurgeAt: true,
|
||||
},
|
||||
});
|
||||
if (!user) {
|
||||
await recordChallengeFailure(challenge.id);
|
||||
|
||||
@@ -114,7 +114,13 @@ export const POST = apiHandler(async (request: NextRequest) => {
|
||||
// (5) Load the user (may have been deleted mid-flight).
|
||||
const user = await prisma.user.findUnique({
|
||||
where: { id: result.userId },
|
||||
select: { id: true, username: true, onboardingCompletedAt: true },
|
||||
select: {
|
||||
id: true,
|
||||
username: true,
|
||||
onboardingCompletedAt: true,
|
||||
deletionRequestedAt: true,
|
||||
deletionPurgeAt: true,
|
||||
},
|
||||
});
|
||||
if (!user) {
|
||||
annotate({ action: { name: "auth.native.token.user_missing" } });
|
||||
|
||||
@@ -47,6 +47,7 @@ import {
|
||||
completeSsoClaim,
|
||||
SSO_CLAIM_LANDING,
|
||||
} from "@/lib/managed-profiles/claim-sso";
|
||||
import { pendingDeletionOf } from "@/lib/account-deletion/pending";
|
||||
import { isHandoverUsable } from "@/lib/managed-profiles/handover";
|
||||
|
||||
const LOGIN_ERROR_URL = "/auth/login";
|
||||
@@ -59,6 +60,51 @@ function errorRedirect(reason: string): NextResponse {
|
||||
return response;
|
||||
}
|
||||
|
||||
/**
|
||||
* The web sign-in page, with the single-use second-factor ticket parked in a
|
||||
* short-lived cookie its script reads (`OIDC_MFA_COOKIE`).
|
||||
*/
|
||||
function secondFactorRedirect(
|
||||
next: string,
|
||||
secondFactor: { ticket: string; methods: readonly string[] },
|
||||
): NextResponse {
|
||||
const loginUrl = oidcAppUrl(LOGIN_ERROR_URL);
|
||||
if (next !== "/") {
|
||||
loginUrl.searchParams.set("next", next);
|
||||
}
|
||||
const response = NextResponse.redirect(loginUrl);
|
||||
deleteStateCookie(response);
|
||||
response.cookies.set(
|
||||
OIDC_MFA_COOKIE,
|
||||
JSON.stringify({
|
||||
ticket: secondFactor.ticket,
|
||||
methods: secondFactor.methods,
|
||||
}),
|
||||
{
|
||||
// Not httpOnly by design — see the constant's doc comment.
|
||||
httpOnly: false,
|
||||
secure: shouldEmitSecureCookie(),
|
||||
sameSite: "lax",
|
||||
maxAge: Math.floor(OIDC_MFA_TTL_MS / 1000),
|
||||
path: OIDC_MFA_COOKIE_PATH,
|
||||
},
|
||||
);
|
||||
return response;
|
||||
}
|
||||
|
||||
/**
|
||||
* The web sign-in page for an account pending deletion, with the date it is
|
||||
* erased, so the page can say until when an admin can undo it.
|
||||
*/
|
||||
function deletionPendingRedirect(purgeAt: Date | null): NextResponse {
|
||||
const url = oidcAppUrl(LOGIN_ERROR_URL);
|
||||
url.searchParams.set("error", "account_deletion_pending");
|
||||
if (purgeAt) url.searchParams.set("purgeAt", purgeAt.toISOString());
|
||||
const response = NextResponse.redirect(url);
|
||||
deleteStateCookie(response);
|
||||
return response;
|
||||
}
|
||||
|
||||
/**
|
||||
* The state cookie is set with `path: "/api/auth/oidc"`; the delete must
|
||||
* repeat that path (RFC 6265 keys cookies by name+domain+path — a bare
|
||||
@@ -305,6 +351,14 @@ export const GET = apiHandler(async (req: NextRequest) => {
|
||||
}
|
||||
const user = account.user;
|
||||
|
||||
// An account pending deletion is locked. The identity provider proved
|
||||
// the caller is this account, so the sign-in page may name the date.
|
||||
const pendingDeletion = await pendingDeletionOf(user.id);
|
||||
if (pendingDeletion) {
|
||||
if (isNative || isClaim) return failRedirect("account_deletion_pending");
|
||||
return deletionPendingRedirect(pendingDeletion.purgeAt);
|
||||
}
|
||||
|
||||
const secondFactor = await startOidcSecondFactor(user, ip, isNative);
|
||||
if (secondFactor) {
|
||||
// Native: hand the app the SAME single-use ticket via the custom scheme.
|
||||
@@ -325,28 +379,7 @@ export const GET = apiHandler(async (req: NextRequest) => {
|
||||
return response;
|
||||
}
|
||||
|
||||
const loginUrl = oidcAppUrl(LOGIN_ERROR_URL);
|
||||
if (stored.next !== "/") {
|
||||
loginUrl.searchParams.set("next", stored.next);
|
||||
}
|
||||
const response = NextResponse.redirect(loginUrl);
|
||||
deleteStateCookie(response);
|
||||
response.cookies.set(
|
||||
OIDC_MFA_COOKIE,
|
||||
JSON.stringify({
|
||||
ticket: secondFactor.ticket,
|
||||
methods: secondFactor.methods,
|
||||
}),
|
||||
{
|
||||
// Not httpOnly by design — see the constant's doc comment.
|
||||
httpOnly: false,
|
||||
secure: shouldEmitSecureCookie(),
|
||||
sameSite: "lax",
|
||||
maxAge: Math.floor(OIDC_MFA_TTL_MS / 1000),
|
||||
path: OIDC_MFA_COOKIE_PATH,
|
||||
},
|
||||
);
|
||||
return response;
|
||||
return secondFactorRedirect(stored.next, secondFactor);
|
||||
}
|
||||
|
||||
const ua = req.headers.get("user-agent");
|
||||
|
||||
@@ -122,7 +122,13 @@ export const POST = apiHandler(async (request: NextRequest) => {
|
||||
// (9) Load the user (may have been deleted mid-flight).
|
||||
const user = await prisma.user.findUnique({
|
||||
where: { id: result.userId },
|
||||
select: { id: true, username: true, onboardingCompletedAt: true },
|
||||
select: {
|
||||
id: true,
|
||||
username: true,
|
||||
onboardingCompletedAt: true,
|
||||
deletionRequestedAt: true,
|
||||
deletionPurgeAt: true,
|
||||
},
|
||||
});
|
||||
if (!user) {
|
||||
annotate({ action: { name: "auth.oidc.native.token.user_missing" } });
|
||||
|
||||
@@ -14,6 +14,7 @@ import { checkAuthSurfaceRateLimit } from "@/lib/rate-limit";
|
||||
import { NextRequest } from "next/server";
|
||||
import { apiHandler } from "@/lib/api-handler";
|
||||
import { annotate } from "@/lib/logging/context";
|
||||
import { refuseIfPendingDeletion } from "@/lib/account-deletion/pending";
|
||||
import { issueApiToken, isNativeClientRequest } from "@/lib/auth/issue-token";
|
||||
import {
|
||||
resolveTokenPolicy,
|
||||
@@ -139,6 +140,10 @@ export const POST = apiHandler(async (request: NextRequest) => {
|
||||
return apiError("User not found", 404);
|
||||
}
|
||||
|
||||
// An account pending deletion is locked; the passkey proved the caller
|
||||
// could sign in, so the refusal may say why and until when.
|
||||
refuseIfPendingDeletion(user);
|
||||
|
||||
// v1.4.22 — `createSession` anchors the
|
||||
// `hl_onboarding` cookie itself; pass the user's onboarding state
|
||||
// through so the proxy short-circuits the redirect before
|
||||
|
||||
@@ -162,8 +162,12 @@ export const DELETE = apiHandler(
|
||||
const { user } = await requireFreshMfa(MFA_STEP_UP_MAX_AGE_SECONDS);
|
||||
const { id } = await params;
|
||||
|
||||
let scheduledPurgeAt: Date | null;
|
||||
try {
|
||||
await deleteManagedProfile({ profileId: id, guardianId: user.id });
|
||||
({ scheduledPurgeAt } = await deleteManagedProfile({
|
||||
profileId: id,
|
||||
guardianId: user.id,
|
||||
}));
|
||||
} catch (error) {
|
||||
if (error instanceof ManagedProfileLifecycleError) return notFound();
|
||||
throw error;
|
||||
@@ -171,8 +175,13 @@ export const DELETE = apiHandler(
|
||||
|
||||
annotate({
|
||||
action: { name: "managed_profile.delete" },
|
||||
meta: { profile_id: id },
|
||||
meta: { profile_id: id, deletion_scheduled: scheduledPurgeAt !== null },
|
||||
});
|
||||
// When the profile is erased; null when it already was. Until then it is
|
||||
// locked and an admin can undo the deletion.
|
||||
return apiSuccess({
|
||||
deleted: true,
|
||||
scheduledPurgeAt: scheduledPurgeAt?.toISOString() ?? null,
|
||||
});
|
||||
return apiSuccess({ deleted: true });
|
||||
},
|
||||
);
|
||||
@@ -100,12 +100,14 @@ export const POST = apiHandler(
|
||||
|
||||
const user = await prisma.user.findUnique({
|
||||
where: { id: verdict.userId },
|
||||
select: { id: true, timezone: true },
|
||||
select: { id: true, timezone: true, deletionRequestedAt: true },
|
||||
});
|
||||
if (!user) {
|
||||
// An account pending deletion is locked: a quick answer from a
|
||||
// notification sent before the deletion records nothing.
|
||||
if (!user || user.deletionRequestedAt != null) {
|
||||
annotate({
|
||||
action: { name: "notification.action.refused" },
|
||||
meta: { reason: "unknown_user" },
|
||||
meta: { reason: user ? "account_deletion_pending" : "unknown_user" },
|
||||
});
|
||||
return apiError("Invalid action", 401, {
|
||||
errorCode: "notification.action.invalid",
|
||||
|
||||
@@ -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(),
|
||||
};
|
||||
}
|
||||
|
||||
|
||||
@@ -166,7 +166,7 @@ describe("POST /api/whoop/webhook/[token]", () => {
|
||||
expect(res.status).toBe(200);
|
||||
expect(prisma.whoopConnection.findUnique).toHaveBeenCalledWith({
|
||||
where: { whoopUserId: "42" },
|
||||
select: { userId: true },
|
||||
select: { userId: true, user: { select: { deletionRequestedAt: true } } },
|
||||
});
|
||||
// v1.16.16 (iOS #17) — the resource id rides through so the worker can do
|
||||
// a targeted fetch-by-id refresh instead of re-walking the collection.
|
||||
|
||||
@@ -109,7 +109,9 @@ describe("POST /api/withings/webhook/[token] (path-segment secret)", () => {
|
||||
expect(body.status).toBe("ok");
|
||||
|
||||
expect(prisma.withingsConnection.findMany).toHaveBeenCalledWith(
|
||||
expect.objectContaining({ where: { withingsUserId: "wu-1" } }),
|
||||
expect.objectContaining({
|
||||
where: { withingsUserId: "wu-1", user: { deletionRequestedAt: null } },
|
||||
}),
|
||||
);
|
||||
expect(syncUserMeasurements).toHaveBeenCalledTimes(1);
|
||||
expect(syncUserMeasurements).toHaveBeenCalledWith("user-42");
|
||||
|
||||
@@ -164,7 +164,9 @@ describe("POST /api/withings/webhook", () => {
|
||||
expect(body.status).toBe("ok");
|
||||
|
||||
expect(prisma.withingsConnection.findMany).toHaveBeenCalledWith(
|
||||
expect.objectContaining({ where: { withingsUserId: "wu-1" } }),
|
||||
expect.objectContaining({
|
||||
where: { withingsUserId: "wu-1", user: { deletionRequestedAt: null } },
|
||||
}),
|
||||
);
|
||||
expect(syncUserMeasurements).toHaveBeenCalledTimes(1);
|
||||
expect(syncUserMeasurements).toHaveBeenCalledWith("user-42");
|
||||
|
||||
Reference in new issue
Block a user