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

378 lines
14 KiB
TypeScript

/**
* 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 "@toolctrl/db/audit-events.server";
import { getDbClient } from "@toolctrl/db/client.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";
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") {
// Record the request as an AuditEvent — the worker job picks it up
// out-of-band (queue glue lives in apps/worker/src/index.ts).
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" },
});
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<LoaderData>();
const action = useActionData<ActionData>();
const { t } = useTranslation();
const formatters = useLocaleFormatters();
return (
<div className="space-y-8 p-6" data-ui-id="ui.settings.privacy.page">
<header>
<h1 className="text-xl font-semibold">{t("settings.privacy.title")}</h1>
<p className="text-sm text-gray-500">
{t("settings.privacy.description")}
</p>
</header>
{action && "ok" in action && action.ok && "intent" in action && action.intent === "export" ? (
<div role="status" aria-live="polite" data-ui-id="ui.settings.privacy.status.export" className="rounded border border-green-300 bg-green-50 p-3 text-sm">
{action.message}
</div>
) : null}
{action && "ok" in action && action.ok && "intent" in action && action.intent === "delete" ? (
<div role="status" aria-live="polite" data-ui-id="ui.settings.privacy.status.delete" className="rounded border border-blue-300 bg-blue-50 p-3 text-sm">
{action.message}
</div>
) : null}
{action && "ok" in action && !action.ok ? (
<div role="alert" data-ui-id="ui.settings.privacy.alert" className="rounded border border-red-300 bg-red-50 p-3 text-sm">
{action.error}
</div>
) : null}
{/* Export */}
<section className="rounded border p-4">
<h2 className="text-lg font-medium">{t("settings.privacy.export.title")}</h2>
<p className="mt-1 text-sm text-gray-600">
{t("settings.privacy.export.description")}
</p>
<Form method="post" className="mt-3" data-ui-id="ui.settings.privacy.export.form">
<input type="hidden" name="intent" value="export" />
<button type="submit" className="rounded bg-blue-600 px-4 py-2 text-sm font-medium text-white hover:bg-blue-500">
{t("settings.privacy.export.submit")}
</button>
</Form>
</section>
{/* Delete or Reactivate */}
<section className="rounded border p-4">
<h2 className="text-lg font-medium">{t("settings.privacy.delete.title")}</h2>
{data.user.pendingDeletion ? (
<div className="mt-2 space-y-3">
<p className="text-sm">
{t("settings.privacy.delete.scheduledPrefix")}{" "}
<strong>
{data.user.scheduledDeletionAt
? formatters.date(data.user.scheduledDeletionAt, { dateStyle: "medium", timeStyle: "short" })
: t("settings.privacy.delete.unknownDate")}
</strong>
. {t("settings.privacy.delete.scheduledSuffix")}
</p>
<Form method="post" data-ui-id="ui.settings.privacy.reactivate.form">
<input type="hidden" name="intent" value="reactivate" />
<button type="submit" className="rounded bg-green-600 px-4 py-2 text-sm font-medium text-white hover:bg-green-500">
{t("settings.privacy.delete.reactivate")}
</button>
</Form>
</div>
) : (
<div className="mt-2 space-y-3">
<p className="text-sm text-gray-600">
{t(
"settings.privacy.delete.description",
{ days: formatters.number(data.graceDays) }
)}
</p>
<Form method="post" className="space-y-3" data-ui-id="ui.settings.privacy.delete.form">
<input type="hidden" name="intent" value="delete" />
<label className="block text-sm">
<span>{t("settings.privacy.delete.confirmationLabel")}</span>
<input name="confirmation" type="text" className="mt-1 w-full rounded border px-2 py-1" autoComplete="off" />
</label>
<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.delete.submit")}
</button>
</Form>
</div>
)}
</section>
<section className="rounded border p-4 text-sm">
<h2 className="text-lg font-medium">{t("settings.privacy.inventory.title")}</h2>
<p className="mt-1 text-gray-600">
{t("settings.privacy.inventory.descriptionPrefix")}{" "}
<a className="underline" href="/docs/features/dsgvo-bulk-ops">
{t("settings.privacy.inventory.documentationLink")}
</a>{" "}
{t("settings.privacy.inventory.descriptionSuffix")}
</p>
</section>
</div>
);
}