/** * Phase 10 Task #68 — DSGVO self-service privacy hub. * * Top-level settings page that lets a logged-in user manage their * Art. 15/17/20 rights: * * • POST { intent: "export" } — enqueues a personal-data export * (rate-limited to 1 per 7 days; the worker streams the bundle to * S3 and emails a signed download URL). * * • POST { intent: "delete" } — emails a short-lived confirmation * link. The confirmation route flips User.pendingDeletion + * scheduledDeletionAt so a hijacked session cannot schedule deletion * without inbox access. * * • POST { intent: "reactivate" } — cancels a pending deletion. * * Every action is audited with regulatoryScope=[gdpr], * dataSensitivity=pii, actorType=user, and a stable requestId so the * worker job can be correlated with the UI action. */ import { randomUUID } from "node:crypto"; import type { ActionFunctionArgs, LoaderFunctionArgs } from "react-router"; import { Form, redirect, 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 { createGdprExportJob } from "@hivegrid/db/privacy-gdpr.server"; import { getTranslations } from "~/locale/i18next.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 { DeletionTokenSecretMissingError, signDeletionToken } from "~/utils/dsgvo/deletionToken.server"; import { sendEmailMailjet } from "~/modules/emails/services/MailjetEmailService"; import { enqueueGdprExport } from "~/utils/privacy/gdprExportQueue.server"; const DSGVO_GRACE_PERIOD_DAYS = Number(process.env.DSGVO_GRACE_PERIOD_DAYS ?? "30") || 30; type LoaderData = { title: string; tenantSlug: string; graceDays: number; user: { id: string; email: string; pendingDeletion: boolean; scheduledDeletionAt: string | null; pseudonymized: boolean; }; }; type ActionData = | { intent: "export"; ok: true; message: string } | { intent: "delete"; ok: true; emailSent: true; message: string } | { intent: "reactivate"; ok: true } | { ok: false; error: string }; const DELETION_CONFIRM_TOKEN_TTL_HOURS = Number(process.env.DSGVO_CONFIRM_TOKEN_TTL_HOURS ?? "24") || 24; function buildConfirmationUrl(request: Request, tenantSlug: string, token: string): string { const origin = new URL(request.url).origin; // Encode tenantSlug for safety; token is base64url which is already URL-safe. return `${origin}/app/${encodeURIComponent(tenantSlug)}/settings/privacy/delete/confirm/${token}`; } function getDeletionMailAppName(t: (key: string) => string): string { return process.env.APP_NAME?.trim() || t("settings.privacy.mail.deleteConfirm.defaultAppName"); } export const loader = async ({ request, params }: LoaderFunctionArgs) => { await requireAuth({ request, params }); const userInfo = await getUserInfo(request); const { t } = await getTranslations(request); const db = getDbClient(); const user = await db.user.findUnique({ where: { id: userInfo.userId }, select: { id: true, email: true, pendingDeletion: true, scheduledDeletionAt: true, pseudonymized: true, }, }); if (!user) throw new Response(t("settings.privacy.errors.userNotFound"), { status: 404 }); const data: LoaderData = { title: `${t("settings.privacy.title")} | ${process.env.APP_NAME ?? t("app.navbar.settings")}`, tenantSlug: params.tenant ?? "", graceDays: DSGVO_GRACE_PERIOD_DAYS, user: { id: user.id, email: user.email, pendingDeletion: user.pendingDeletion, scheduledDeletionAt: user.scheduledDeletionAt ? user.scheduledDeletionAt.toISOString() : null, pseudonymized: user.pseudonymized, }, }; return Response.json(data); }; export const action = async ({ request, params }: ActionFunctionArgs) => { await requireAuth({ request, params }); await validateCSRFToken(request); const { t } = await getTranslations(request); const userInfo = await getUserInfo(request); const tenantId = await getTenantIdFromUrl(params); const form = await request.formData(); const intent = String(form.get("intent") ?? ""); const db = getDbClient(); const requestId = randomUUID(); if (intent === "export") { const exportJob = await createGdprExportJob({ tenantId, requestedByUserId: userInfo.userId, targetUserId: userInfo.userId, scope: "user_self", }); const enqueueResult = await enqueueGdprExport({ exportJobId: exportJob.id, tenantId, requestedByUserId: userInfo.userId, targetUserId: userInfo.userId, scope: "user_self", requestId, }); await createAuditEvent({ tenantId, actorId: userInfo.userId, actorType: "user", action: "REQUEST_PERSONAL_DATA_EXPORT", targetType: "User", targetId: userInfo.userId, regulatoryScope: ["gdpr"], dataSensitivity: "pii", outcome: "success", metadata: { requestId, intent: "export", source: "self-service", gdprExportJobId: exportJob.id, enqueueResult }, }); const data: ActionData = { intent: "export", ok: true, message: t("settings.privacy.messages.exportRequested"), }; return Response.json(data); } if (intent === "delete") { const confirmation = String(form.get("confirmation") ?? ""); if (confirmation !== "LÖSCHEN" && confirmation.toUpperCase() !== "DELETE") { const data: ActionData = { ok: false, error: t("settings.privacy.errors.confirmationMismatch"), }; return Response.json(data, { status: 400 }); } const user = await db.user.findUnique({ where: { id: userInfo.userId }, select: { email: true } }); if (!user) { const data: ActionData = { ok: false, error: t("settings.privacy.errors.userNotFound") }; return Response.json(data, { status: 404 }); } // Mint a short-lived signed token; do NOT mutate User.pendingDeletion yet. // The pendingDeletion flag is only flipped after the user clicks the // confirmation link emailed below — that protects against an attacker // who has hijacked a session but cannot read the user's inbox. let token: string; try { token = signDeletionToken({ userId: userInfo.userId, expiresInHours: DELETION_CONFIRM_TOKEN_TTL_HOURS }); } catch (err) { if (err instanceof DeletionTokenSecretMissingError) { const data: ActionData = { ok: false, error: t("settings.privacy.errors.deletionTokenSecretMissing"), }; return Response.json(data, { status: 500 }); } throw err; } const tenantSlug = params.tenant ?? ""; const confirmUrl = buildConfirmationUrl(request, tenantSlug, token); const ttlHours = Math.min(Math.max(Math.floor(DELETION_CONFIRM_TOKEN_TTL_HOURS), 1), 72); const appName = getDeletionMailAppName(t); const mailSubject = t("settings.privacy.mail.deleteConfirm.subject", { appName }); const mailBody = [ t("settings.privacy.mail.deleteConfirm.intro", { appName }), "", t("settings.privacy.mail.deleteConfirm.instructions", { hours: ttlHours }), "", confirmUrl, "", t("settings.privacy.mail.deleteConfirm.gracePeriod", { days: DSGVO_GRACE_PERIOD_DAYS }), "", t("settings.privacy.mail.deleteConfirm.ignore", { requestId, }), ].join("\n"); try { await sendEmailMailjet({ data: { to: user.email, subject: mailSubject, body: mailBody, tenantId: tenantId ?? undefined, alias: "dsgvo-deletion-confirm", data: { requestId, ttlHours }, priorityOverride: "high", }, }); } catch (err) { // Audit the failure so the operator sees the problem but do NOT leak // detail to the end-user; deletion can always be re-requested. await createAuditEvent({ tenantId, actorId: userInfo.userId, actorType: "user", action: "REQUEST_USER_DELETION", targetType: "User", targetId: userInfo.userId, regulatoryScope: ["gdpr"], dataSensitivity: "pii", outcome: "failure", metadata: { requestId, intent: "delete", source: "self-service", phase: "send-confirmation-email", error: String(err) }, }); const data: ActionData = { ok: false, error: t("settings.privacy.errors.confirmationEmailFailed"), }; return Response.json(data, { status: 502 }); } 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: "confirmation-email-sent" }, }); const successMessage = t( "settings.privacy.messages.deleteConfirmationSent", { email: user.email, hours: ttlHours, days: DSGVO_GRACE_PERIOD_DAYS } ); const ok: ActionData = { intent: "delete", ok: true, emailSent: true, message: successMessage, }; return Response.json(ok); } if (intent === "reactivate") { await db.user.update({ where: { id: userInfo.userId }, data: { pendingDeletion: false, deletionRequestedAt: null, scheduledDeletionAt: null, deletionRequestId: null, }, }); await createAuditEvent({ tenantId, actorId: userInfo.userId, actorType: "user", action: "CANCEL_USER_DELETION", targetType: "User", targetId: userInfo.userId, regulatoryScope: ["gdpr"], dataSensitivity: "pii", outcome: "success", metadata: { requestId, intent: "reactivate", source: "self-service" }, }); return redirect("./privacy"); } const data: ActionData = { ok: false, error: t("settings.privacy.errors.unknownIntent", { intent }) }; return Response.json(data, { status: 400 }); }; export default function PrivacySettingsRoute() { const data = useLoaderData(); const action = useActionData(); const { t } = useTranslation(); const formatters = useLocaleFormatters(); return (

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

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

{action && "ok" in action && action.ok && "intent" in action && action.intent === "export" ? (
{action.message}
) : null} {action && "ok" in action && action.ok && "intent" in action && action.intent === "delete" ? (
{action.message}
) : null} {action && "ok" in action && !action.ok ? (
{action.error}
) : null} {/* Export */}

{t("settings.privacy.export.title")}

{t("settings.privacy.export.description")}

{/* Delete or Reactivate */}

{t("settings.privacy.delete.title")}

{data.user.pendingDeletion ? (

{t("settings.privacy.delete.scheduledPrefix")}{" "} {data.user.scheduledDeletionAt ? formatters.date(data.user.scheduledDeletionAt, { dateStyle: "medium", timeStyle: "short" }) : t("settings.privacy.delete.unknownDate")} . {t("settings.privacy.delete.scheduledSuffix")}

) : (

{t( "settings.privacy.delete.description", { days: formatters.number(data.graceDays) } )}

)}

{t("settings.privacy.inventory.title")}

{t("settings.privacy.inventory.descriptionPrefix")}{" "} {t("settings.privacy.inventory.documentationLink")} {" "} {t("settings.privacy.inventory.descriptionSuffix")}

); }