Files
HiveGrid-Wireframes/hivegrid-cloud/apps/web/app/routes/app.$tenant/settings/privacy.delete.confirm.$token.tsx
T

218 lines
8.3 KiB
TypeScript

/**
* 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 "@toolctrl/db/audit-events.server";
import { getDbClient } from "@toolctrl/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<LoaderData>();
const action = useActionData<ActionData>();
const { t } = useTranslation();
const formatters = useLocaleFormatters();
const reactivateHref = `/app/${encodeURIComponent("tenantSlug" in data ? data.tenantSlug : "")}/settings/privacy`;
if (action && "stage" in action && action.stage === "confirmed") {
const reactivate = `/app/${encodeURIComponent(action.tenantSlug)}/settings/privacy`;
return (
<div className="mx-auto max-w-xl space-y-4 p-8">
<h1 className="text-xl font-semibold">{t("settings.privacy.deleteConfirm.confirmed.title")}</h1>
<p className="text-sm text-gray-700">
{t("settings.privacy.deleteConfirm.confirmed.bodyPrefix")}{" "}
<strong>{formatters.date(action.scheduledDeletionAtIso, { dateStyle: "medium", timeStyle: "short" })}</strong>.
{" "}
{t("settings.privacy.deleteConfirm.confirmed.bodySuffix")}
</p>
<p className="text-sm">
<a className="text-blue-600 underline" href={reactivate}>
{t("settings.privacy.deleteConfirm.confirmed.reactivate")}
</a>
</p>
</div>
);
}
if (action && "stage" in action && action.stage === "mismatch") {
return (
<div className="mx-auto max-w-xl space-y-4 p-8">
<h1 className="text-xl font-semibold">{t("settings.privacy.deleteConfirm.mismatch.title")}</h1>
<p className="text-sm text-gray-700">
{t("settings.privacy.deleteConfirm.mismatch.description")}
</p>
</div>
);
}
if (data.stage === "expired" || (action && "stage" in action && action.stage === "expired")) {
return (
<div className="mx-auto max-w-xl space-y-4 p-8">
<h1 className="text-xl font-semibold">{t("settings.privacy.deleteConfirm.expired.title")}</h1>
<p className="text-sm text-gray-700">
{t("settings.privacy.deleteConfirm.expired.description")}
</p>
<p className="text-sm">
<a className="text-blue-600 underline" href={reactivateHref}>
{t("settings.privacy.deleteConfirm.expired.returnToPrivacy")}
</a>
</p>
</div>
);
}
return (
<div className="mx-auto max-w-xl space-y-4 p-8">
<h1 className="text-xl font-semibold">{t("settings.privacy.deleteConfirm.ready.title")}</h1>
<p className="text-sm text-gray-700">
{t("settings.privacy.deleteConfirm.ready.bodyPrefix")}{" "}
<strong>{data.userEmail}</strong>.
{" "}
{t(
"settings.privacy.deleteConfirm.ready.bodySuffix",
{ days: formatters.number(DSGVO_GRACE_PERIOD_DAYS) },
)}
</p>
<p className="text-xs text-gray-500">
{t("settings.privacy.deleteConfirm.ready.expiresAt", {
date: formatters.date(data.expiresAtIso, { dateStyle: "medium", timeStyle: "short" }),
})}
</p>
<Form method="post">
<button
type="submit"
className="rounded bg-red-600 px-4 py-2 text-sm font-medium text-white hover:bg-red-500"
>
{t("settings.privacy.deleteConfirm.ready.submit")}
</button>
</Form>
</div>
);
}