/** * Phase 10 Task #68 — DSGVO deletion-confirmation route. * * Handles the link emailed by the self-service privacy page after a user * requests account deletion. The HMAC-signed token in the URL identifies * the user and bounds the validity window (default 24h). Only when the * user opens this link AND submits the confirmation button (POST) does * the system actually flip `User.pendingDeletion=true` and schedule the * 30-day grace-period deletion. * * GET /app/:tenant/settings/privacy/delete/confirm/:token * → verify token; show "Confirm Deletion" button or expired-page. * * POST same path * → re-verify (defense-in-depth), flip User.pendingDeletion + * scheduledDeletionAt = now + GRACE_DAYS, audit, show the * reactivate-link page. * * The audit row uses regulatoryScope=[gdpr], dataSensitivity=pii, * actorType=user (the user themself triggered) and metadata.requestId * for cross-correlation with the earlier email-send audit. */ import { randomUUID } from "node:crypto"; import type { ActionFunctionArgs, LoaderFunctionArgs } from "react-router"; import { Form, useActionData, useLoaderData } from "react-router"; import { useTranslation } from "react-i18next"; import { createAuditEvent } from "@hivegrid/db/audit-events.server"; import { getDbClient } from "@hivegrid/db/client.server"; import { useLocaleFormatters } from "~/locale/format"; import { getUserInfo, validateCSRFToken } from "~/utils/session.server"; import { getTenantIdFromUrl } from "~/utils/services/.server/urlService"; import { requireAuth } from "~/utils/loaders.middleware"; import { verifyDeletionToken } from "~/utils/dsgvo/deletionToken.server"; const DSGVO_GRACE_PERIOD_DAYS = Number(process.env.DSGVO_GRACE_PERIOD_DAYS ?? "30") || 30; type LoaderData = | { stage: "ready"; tenantSlug: string; userEmail: string; expiresAtIso: string } | { stage: "expired"; tenantSlug: string }; type ActionData = | { stage: "confirmed"; scheduledDeletionAtIso: string; tenantSlug: string } | { stage: "expired"; tenantSlug: string } | { stage: "mismatch"; tenantSlug: string } | { ok: false; error: string }; export const loader = async ({ request, params }: LoaderFunctionArgs) => { // The user MUST be authenticated as the deletion target before we even // show the confirm button — owning the email link alone is not enough, // they must also have an active session for that same user id. await requireAuth({ request, params }); const userInfo = await getUserInfo(request); const tenantSlug = params.tenant ?? ""; const token = params.token ?? ""; const payload = verifyDeletionToken(token); if (!payload) { const data: LoaderData = { stage: "expired", tenantSlug }; return Response.json(data); } if (payload.userId !== userInfo.userId) { // Same as expired from the end-user perspective — never disclose // that the token is valid for a different user. const data: LoaderData = { stage: "expired", tenantSlug }; return Response.json(data); } const db = getDbClient(); const user = await db.user.findUnique({ where: { id: userInfo.userId }, select: { email: true } }); if (!user) { const data: LoaderData = { stage: "expired", tenantSlug }; return Response.json(data); } const data: LoaderData = { stage: "ready", tenantSlug, userEmail: user.email, expiresAtIso: new Date(payload.exp * 1000).toISOString(), }; return Response.json(data); }; export const action = async ({ request, params }: ActionFunctionArgs) => { await requireAuth({ request, params }); await validateCSRFToken(request); const userInfo = await getUserInfo(request); const tenantId = await getTenantIdFromUrl(params); const tenantSlug = params.tenant ?? ""; const token = params.token ?? ""; const payload = verifyDeletionToken(token); if (!payload) { const data: ActionData = { stage: "expired", tenantSlug }; return Response.json(data, { status: 410 }); } if (payload.userId !== userInfo.userId) { const data: ActionData = { stage: "mismatch", tenantSlug }; return Response.json(data, { status: 403 }); } const db = getDbClient(); const requestId = randomUUID(); const now = new Date(); const scheduledDeletionAt = new Date(now.getTime() + DSGVO_GRACE_PERIOD_DAYS * 24 * 60 * 60 * 1000); await db.user.update({ where: { id: userInfo.userId }, data: { pendingDeletion: true, deletionRequestedAt: now, scheduledDeletionAt, deletionRequestId: requestId, }, }); await createAuditEvent({ tenantId, actorId: userInfo.userId, actorType: "user", action: "REQUEST_USER_DELETION", targetType: "User", targetId: userInfo.userId, regulatoryScope: ["gdpr"], dataSensitivity: "pii", outcome: "success", metadata: { requestId, intent: "delete", source: "self-service", phase: "confirmed-via-email-link", scheduledDeletionAt: scheduledDeletionAt.toISOString(), tokenRequestedAt: payload.requestedAt, }, }); const data: ActionData = { stage: "confirmed", scheduledDeletionAtIso: scheduledDeletionAt.toISOString(), tenantSlug }; return Response.json(data); }; export default function PrivacyDeleteConfirmRoute() { const data = useLoaderData(); const action = useActionData(); const { t } = useTranslation(); const formatters = useLocaleFormatters(); const reactivateHref = `/app/${encodeURIComponent("tenantSlug" in data ? data.tenantSlug : "")}/settings/profile/data`; if (action && "stage" in action && action.stage === "confirmed") { const reactivate = `/app/${encodeURIComponent(action.tenantSlug)}/settings/profile/data`; return (

{t("settings.privacy.deleteConfirm.confirmed.title")}

{t("settings.privacy.deleteConfirm.confirmed.bodyPrefix")}{" "} {formatters.date(action.scheduledDeletionAtIso, { dateStyle: "medium", timeStyle: "short" })}. {" "} {t("settings.privacy.deleteConfirm.confirmed.bodySuffix")}

{t("settings.privacy.deleteConfirm.confirmed.reactivate")}

); } if (action && "stage" in action && action.stage === "mismatch") { return (

{t("settings.privacy.deleteConfirm.mismatch.title")}

{t("settings.privacy.deleteConfirm.mismatch.description")}

); } if (data.stage === "expired" || (action && "stage" in action && action.stage === "expired")) { return (

{t("settings.privacy.deleteConfirm.expired.title")}

{t("settings.privacy.deleteConfirm.expired.description")}

{t("settings.privacy.deleteConfirm.expired.returnToPrivacy")}

); } return (

{t("settings.privacy.deleteConfirm.ready.title")}

{t("settings.privacy.deleteConfirm.ready.bodyPrefix")}{" "} {data.userEmail}. {" "} {t( "settings.privacy.deleteConfirm.ready.bodySuffix", { days: formatters.number(DSGVO_GRACE_PERIOD_DAYS) }, )}

{t("settings.privacy.deleteConfirm.ready.expiresAt", { date: formatters.date(data.expiresAtIso, { dateStyle: "medium", timeStyle: "short" }), })}

); }