feat(account): show the deletion grace window and its undo

The deletion dialogs, the managed-profile delete dialog and the Data &
Privacy page read the window from the privacy summary and say what
happens: the account is locked at once, erased after the stated number
of days, and an admin of the server can undo it until then; a wipe keeps
a copy an admin can restore for the same time. Copies in the server's
backups age out after their retention period, and the text says that
too. With the window set to 0 they keep the immediate wording.

The sign-in page names the erasure date when a sign-in, a passkey or the
single sign-on callback is refused for an account pending deletion. The
admin users list shows a pending account with its date and an "Undo
deletion" action, and the backups list labels the copy taken before a
wipe. Every new string is translated in all nine languages.
This commit is contained in:
Marc-André Bombeck committed 2026-10-25 13:51:01 +01:00
1 parent a69666fa16
commit 63574b98a6
21 files changed
+573 -141

No files matched your search

+10
View File
@@ -34,6 +34,16 @@ export interface AdminUser {
// the instance-wide default applies.
documentQuotaBytes: number | null;
passkeyCount: number;
/**
* Set while the account is pending deletion: when the purge job
* erases it, and whether the account asked itself or a Guardian deleted
* the managed profile. The row offers "Undo deletion" until then.
*/
deletion: {
requestedAt: string;
purgeAt: string | null;
requestedBy: "self" | "guardian";
} | null;
}
export interface WorkerStatus {
@@ -8,6 +8,7 @@ import { useFormatters, useTranslations } from "@/lib/i18n/context";
import type { BackupRow } from "@/types/backups";
import { RestoreRowDialog } from "./restore-dialog";
import { isPreWipeBackupType } from "@/lib/account-deletion/pre-wipe-type";
/** What a row's Download and Restore controls act through. */
export type BackupRowActionProps = {
@@ -31,6 +32,9 @@ function formatBackupType(
) {
if (type === "WEEKLY_AUTO") return t("admin.section.backups.typeWeeklyAuto");
if (type === "MANUAL") return t("admin.section.backups.typeManual");
// The copy "Delete all entries" takes first; restorable until the deletion
// grace window ends, when the purge job deletes it.
if (isPreWipeBackupType(type)) return t("admin.section.backups.typePreWipe");
return type;
}
@@ -0,0 +1,79 @@
"use client";
import { useMutation, useQueryClient } from "@tanstack/react-query";
import { Undo2 } from "lucide-react";
import { toast } from "sonner";
import { Badge } from "@/components/ui/badge";
import { ConfirmButton } from "@/components/ui/confirm-button";
import { showErrorToast } from "@/lib/errors/error-toast";
import { apiPost } from "@/lib/api/api-fetch";
import { formatDate } from "@/lib/format";
import { useTranslations } from "@/lib/i18n/context";
import { queryKeys } from "@/lib/query-keys";
import type { AdminUser } from "./_shared";
/**
* An account pending deletion, in the admin users list: the date the purge
* job erases it, and the one action that stops it.
*
* The account, its stored copies and its off-host objects are untouched
* until that date, so "Undo deletion" (`POST /api/admin/users/{id}/undo-deletion`)
* gives it back exactly as it was. Renders nothing for any other account.
*/
export function PendingDeletionControls({ user }: { user: AdminUser }) {
const { t } = useTranslations();
const queryClient = useQueryClient();
const undo = useMutation({
mutationFn: () => apiPost(`/api/admin/users/${user.id}/undo-deletion`),
onSuccess: () => {
void queryClient.invalidateQueries({ queryKey: queryKeys.adminUsers() });
toast.success(
t("admin.section.users.undoDeletionDone", { name: user.username }),
);
},
onError: (err) => {
showErrorToast(
err instanceof Error && err.message
? err.message
: t("admin.section.users.undoDeletionFailed"),
{ cause: err },
);
},
});
if (!user.deletion) return null;
return (
<span
className="flex flex-wrap items-center gap-1"
data-slot="admin-user-deletion-pending"
>
<Badge variant="destructive" className="text-xs">
{user.deletion.purgeAt
? t("admin.section.users.deletionPending", {
date: formatDate(user.deletion.purgeAt),
})
: t("admin.section.users.deletionPendingNoDate")}
</Badge>
<ConfirmButton
slot="admin-user-undo-deletion"
size="sm"
className="min-h-11 text-xs"
icon={<Undo2 className="h-3 w-3" aria-hidden="true" />}
label={t("admin.section.users.undoDeletion")}
title={t("admin.section.users.undoDeletionTitle", {
name: user.username,
})}
body={t(
user.deletion.requestedBy === "guardian"
? "admin.section.users.undoDeletionBodyGuardian"
: "admin.section.users.undoDeletionBody",
{ name: user.username },
)}
confirmLabel={t("admin.section.users.undoDeletion")}
pending={undo.isPending}
onConfirm={() => undo.mutate()}
/>
</span>
);
}
@@ -39,6 +39,7 @@ import { ListRow } from "@/components/ui/list-row";
import { useTranslations } from "@/lib/i18n/context";
import { queryKeys } from "@/lib/query-keys";
import { type AdminUser, PasswordInput } from "./_shared";
import { PendingDeletionControls } from "./pending-deletion-controls";
import { apiGet, apiPost, apiPut } from "@/lib/api/api-fetch";
import {
recentProofErrorMessage,
@@ -56,8 +57,7 @@ type UserFilter = "all" | "admin" | "user";
export function UserManagementSection() {
const { t } = useTranslations();
const { user } = useAuth();
const currentUserId = user?.id ?? "";
const currentUserId = useAuth().user?.id ?? "";
const queryClient = useQueryClient();
const [editingUser, setEditingUser] = useState<AdminUser | null>(null);
const [editUsername, setEditUsername] = useState("");
@@ -182,6 +182,7 @@ export function UserManagementSection() {
*/
const renderUserActions = (u: AdminUser) => (
<>
<PendingDeletionControls user={u} />
<Button
variant="ghost"
size="sm"
@@ -153,6 +153,13 @@ vi.mock("@/hooks/use-account-switch", () => ({
useAccountSwitch: () => ({ mutate: vi.fn(), isPending: false }),
}));
// The deletion grace window the delete dialog states. 0 here, the immediate
// erasure these tests were written against; the grace wording is pinned on
// `deleteProfileBody` below.
vi.mock("@/lib/queries/use-privacy-summary", () => ({
useAccountDeletionGrace: () => ({ days: 0, pending: false }),
}));
interface FakeMutation {
mutate: ReturnType<typeof vi.fn>;
isPending: boolean;
@@ -662,6 +669,20 @@ describe("what the confirmation says before it deletes", () => {
expect(body).toContain("recordSharing.managed.deleteFloorNote");
});
it("says the profile is locked, erased after the window, and undoable", () => {
const body = deleteProfileBody({
t,
tCount,
name: "Managed record",
activeGuardians: 1,
graceDays: 14,
});
expect(body).toContain(
'recordSharing.managed.deleteBodyGrace({"name":"Managed record","days":14})',
);
expect(body).not.toContain("recordSharing.managed.deleteBody(");
});
it("counts the guardians who actually hold the record", () => {
// A pending invitation confers nothing, and the server counts the same
// way. Counting it would tell somebody two people lose the record when
@@ -31,6 +31,7 @@ import {
accountLabel,
type AccountAccessEntry,
} from "@/lib/sharing/account-access-view";
import { useAccountDeletionGrace } from "@/lib/queries/use-privacy-summary";
/**
* v1.37.0 — the records this account looks after.
@@ -140,6 +141,7 @@ function ManagedProfileRow({
}) {
const { t, tCount } = useTranslations();
const guardians = useManagedProfileGuardians(profile.accountId);
const grace = useAccountDeletionGrace();
const name = accountLabel(profile);
const failed =
remove.isError &&
@@ -185,7 +187,7 @@ function ManagedProfileRow({
>
{t("recordSharing.managed.edit")}
</Button>
{guardians.data && (
{guardians.data && !grace.pending && (
<ConfirmButton
slot="managed-profile-delete"
destructive
@@ -198,6 +200,7 @@ function ManagedProfileRow({
tCount,
name,
activeGuardians: activeGuardianCount(guardians.data),
graceDays: grace.days ?? 0,
})}
confirmLabel={t("recordSharing.managed.deleteConfirm")}
pending={remove.isPending}
@@ -335,6 +338,7 @@ export function deleteProfileBody({
tCount,
name,
activeGuardians,
graceDays = 0,
}: {
t: (key: string, params?: Record<string, string | number>) => string;
tCount: (
@@ -345,9 +349,17 @@ export function deleteProfileBody({
name: string;
/** Taken from the roster read, never from a local counter. */
activeGuardians: number;
/**
* The deletion grace window (`GET /api/settings/privacy-summary`). Above 0
* the profile is locked and erased when it ends, and an admin can undo it
* until then; 0 erases it at once.
*/
graceDays?: number;
}): string {
return [
t("recordSharing.managed.deleteBody", { name }),
graceDays > 0
? t("recordSharing.managed.deleteBodyGrace", { name, days: graceDays })
: t("recordSharing.managed.deleteBody", { name }),
tCount("recordSharing.managed.deleteGuardians", activeGuardians, {
count: activeGuardians,
}),
+60 -14
View File
@@ -17,15 +17,18 @@ import {
useRecentProof,
} from "@/components/settings/security-section/use-recent-proof";
import { loadDocument } from "@/lib/navigation/load-document";
import { useAccountDeletionGrace } from "@/lib/queries/use-privacy-summary";
import { formatDate } from "@/lib/format";
/**
* Settings → Advanced.
*
* v1.4.16: every export path (CSV, JSON, doctor-report PDF)
* moved out into the dedicated `<ExportSection>` under `/settings/export`.
* What stays here is the irreversible danger-zone — the "wipe all my
* data" surface that should never live next to a single-click export
* button.
* What stays here is the danger-zone — the "wipe all my data" and
* "delete my account" surfaces that should never live next to a
* single-click export button. Both complete after the deletion grace
* window (`ACCOUNT_DELETION_GRACE_DAYS`), which the dialogs state.
*
* v1.4.25 added a Research Mode opt-in here, gating the estimated GLP-1
* drug-level curve behind an acknowledged disclaimer version. The chart
@@ -52,6 +55,10 @@ export function AdvancedSection() {
function DataResetCard() {
const { t } = useTranslations();
const queryClient = useQueryClient();
// With a grace window the wipe keeps a copy an admin can restore until the
// window ends; the dialog says so only once it knows the number.
const grace = useAccountDeletionGrace();
const graceDays = grace.days ?? 0;
const recentProof = useRecentProof({
description: t("settings.reproof.descriptionChange"),
});
@@ -86,7 +93,14 @@ function DataResetCard() {
}
await queryClient.invalidateQueries();
setMsg(t("settings.dangerZoneSuccess"));
const restorableUntil: unknown = json?.data?.restorableUntil;
setMsg(
typeof restorableUntil === "string"
? t("settings.dangerZoneSuccessGrace", {
date: formatDate(restorableUntil),
})
: t("settings.dangerZoneSuccess"),
);
setMsgType("success");
setConfirmOpen(false);
} catch (err) {
@@ -132,7 +146,7 @@ function DataResetCard() {
onClick={() => setConfirmOpen(true)}
variant="destructive"
size="sm"
disabled={deleting}
disabled={deleting || grace.pending}
className="min-h-11 w-full shrink-0 sm:min-h-9 sm:w-auto"
>
{deleting ? (
@@ -151,7 +165,13 @@ function DataResetCard() {
setConfirmOpen(open);
}}
title={t("settings.dangerZoneConfirm")}
body={t("settings.dangerZoneConfirmDescription")}
body={
graceDays > 0
? t("settings.dangerZoneConfirmDescriptionGrace", {
days: graceDays,
})
: t("settings.dangerZoneConfirmDescription")
}
confirmLabel={t("settings.finalDelete")}
onConfirm={() => void handleDeleteAllData()}
pending={deleting}
@@ -180,6 +200,10 @@ function DataResetCard() {
*/
function AccountDeleteCard() {
const { t } = useTranslations();
// With a grace window the account is locked at once and erased when the
// window ends; until then an admin can undo it. Stated only once known.
const grace = useAccountDeletionGrace();
const graceDays = grace.days ?? 0;
const recentProof = useRecentProof({
description: t("settings.reproof.descriptionChange"),
});
@@ -216,12 +240,24 @@ function AccountDeleteCard() {
setDeleting(false);
return;
}
setMsg(t("settings.deleteAccountSuccess"));
let scheduledPurgeAt: unknown = null;
try {
scheduledPurgeAt = (await res.json())?.data?.scheduledPurgeAt;
} catch {
scheduledPurgeAt = null;
}
setMsg(
typeof scheduledPurgeAt === "string"
? t("settings.deleteAccountScheduled", {
date: formatDate(scheduledPurgeAt),
})
: t("settings.deleteAccountSuccess"),
);
setMsgType("success");
// The route destroyed every session before deleting the row;
// give the toast a beat to paint, then bounce to the login page.
// Leave `deleting` set so the confirm button keeps its pending
// state through the redirect — the row is gone, nothing to undo.
// The route revoked every session (and, without a grace window,
// deleted the row); give the toast a beat to paint, then bounce to the
// login page. Leave `deleting` set so the confirm button keeps its
// pending state through the redirect: only an admin can undo it now.
setTimeout(() => {
loadDocument("/auth/login");
}, 1_500);
@@ -246,7 +282,11 @@ function AccountDeleteCard() {
title={t("settings.deleteAccountCardTitle")}
description={t("settings.deleteAccountCardDescription")}
/>
<p className="text-sm">{t("settings.deleteAccountCardDetail")}</p>
<p className="text-sm">
{graceDays > 0
? t("settings.deleteAccountCardDetailGrace", { days: graceDays })
: t("settings.deleteAccountCardDetail")}
</p>
{msg && (
<p
@@ -262,7 +302,7 @@ function AccountDeleteCard() {
onClick={() => setConfirmOpen(true)}
variant="destructive"
size="sm"
disabled={deleting}
disabled={deleting || grace.pending}
className="min-h-11 w-full shrink-0 sm:min-h-9 sm:w-auto"
data-slot="settings-account-delete-trigger"
>
@@ -282,7 +322,13 @@ function AccountDeleteCard() {
setConfirmOpen(open);
}}
title={t("settings.deleteAccountConfirmTitle")}
body={t("settings.deleteAccountConfirmDescription")}
body={
graceDays > 0
? t("settings.deleteAccountConfirmDescriptionGrace", {
days: graceDays,
})
: t("settings.deleteAccountConfirmDescription")
}
confirmLabel={t("settings.deleteAccountFinal")}
onConfirm={() => void handleDeleteAccount()}
pending={deleting}
+18 -26
View File
@@ -14,7 +14,6 @@
* left: Export & import and the Health record sit next to this page in the
* Data group. The old anchors forward (`settings-anchor-forward.tsx`).
*/
import { useQuery } from "@tanstack/react-query";
import Link from "next/link";
import {
Database,
@@ -33,26 +32,11 @@ import { SettingsCard } from "@/components/settings/settings-card";
import { SettingsCardHeader } from "@/components/settings/_card-header";
import { SettingsInfoTile } from "@/components/settings/_info-tile";
import { WorkoutRoutesCard } from "@/components/settings/workout-routes-card";
import { useAuth } from "@/hooks/use-auth";
import { useTranslations } from "@/lib/i18n/context";
import { MODULE_KEYS, MODULE_REGISTRY } from "@/lib/modules/registry";
import { queryKeys } from "@/lib/query-keys";
import { apiGet } from "@/lib/api/api-fetch";
import { usePrivacySummary } from "@/lib/queries/use-privacy-summary";
import { QueryErrorRow } from "@/components/ui/query-error-row";
interface PrivacySummary {
retention: {
coachMessagesDays: number;
auditLogDays: number;
deliveryLogDays: number;
};
encryption: {
algorithm: string;
columnCount: number;
modelCount: number;
};
}
/**
* The modules that keep records of their own, read off the module registry
* so a new module joins the "What's stored" list without anyone editing it.
@@ -69,7 +53,6 @@ export function storedModuleLabelKeys(): string[] {
export function PrivacySection() {
const { t, locale } = useTranslations();
const { isAuthenticated } = useAuth();
const {
data: summary,
@@ -77,11 +60,7 @@ export function PrivacySection() {
isError: summaryError,
error: summaryFailure,
refetch: refetchSummary,
} = useQuery({
queryKey: queryKeys.privacySummary(),
queryFn: () => apiGet<PrivacySummary>("/api/settings/privacy-summary"),
enabled: isAuthenticated,
});
} = usePrivacySummary();
return (
<div className="space-y-6">
@@ -177,6 +156,13 @@ export function PrivacySection() {
days: summary.retention.deliveryLogDays,
})}
</li>
<li>
{summary.retention.accountDeletionGraceDays > 0
? t("settings.privacy.retention.accountDeletion", {
days: summary.retention.accountDeletionGraceDays,
})
: t("settings.privacy.retention.accountDeletionImmediate")}
</li>
</ul>
)}
</SettingsCard>
@@ -208,9 +194,15 @@ export function PrivacySection() {
title={t("settings.privacy.delete.title")}
description={t("settings.privacy.delete.description")}
/>
<SettingsInfoTile icon={Info} tone="warning">
{t("settings.privacy.delete.backupLag")}
</SettingsInfoTile>
{summary && (
<SettingsInfoTile icon={Info} tone="warning">
{summary.retention.accountDeletionGraceDays > 0
? t("settings.privacy.delete.graceNotice", {
days: summary.retention.accountDeletionGraceDays,
})
: t("settings.privacy.delete.immediateNotice")}
</SettingsInfoTile>
)}
<SettingsCardActions align="start">
<Button asChild variant="outline" size="sm">
<Link href="/settings/advanced">