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:
Marc-André Bombeck committed 2026-10-25 13:50:14 +01:00
1 parent 41c6eea2a1
commit a69666fa16
158 files changed
+3164 -461

No files matched your search

+2
View File
@@ -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);
+7 -1
View File
@@ -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" } });
+55 -22
View File
@@ -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");
+7 -1
View File
@@ -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