Refresh HiveGrid Cloud reference snapshot

This commit is contained in:
david committed 2026-08-03 15:31:14 +02:00
1 parent 5e99e14772
commit 7f88026f79
5955 files changed
+1177325 -188362

No files matched your search

@@ -1,31 +1,52 @@
/**
* Marketing-Funnel Phase 3 unsubscribe route (Phase 05 #80).
*
* Accepts both GET (one-click via List-Unsubscribe header per RFC-8058)
* and POST. Verifies the HMAC token and flips the EmailSequenceRun
* status to `unsubscribed`. Idempotent: clicking the link twice is a
* no-op on the second hit.
* GET verifies the HMAC token and displays a confirmation without writing.
* Only POST flips the EmailSequenceRun status to `unsubscribed`; repeats are
* idempotent.
*
* Intentionally minimal — no session, no CSRF (token IS the auth).
* Mail-clients (Gmail, Outlook) POST to this URL automatically when
* the user hits the inbox "Unsubscribe" button.
* Browser POSTs require CSRF. RFC-8058 clients may instead send the exact
* `List-Unsubscribe=One-Click` form body; the signed path token is the scoped
* capability in that protocol flow.
*/
import type { ActionFunctionArgs, LoaderFunctionArgs } from "react-router";
import { useLoaderData } from "react-router";
import { Form, useActionData, useLoaderData } from "react-router";
import { useTranslation } from "react-i18next";
import { runWithRlsContext } from "@hivegrid/db/rls-context.server";
import { db } from "~/utils/db.server";
import { verifyUnsubscribeToken } from "~/utils/email/unsubscribeToken.server";
import { verifyMarketingToken } from "~/utils/email/marketingToken.server";
import { unsubscribeKontakt } from "~/modules/emailMarketing/services/ConsentService.server";
import { getMarketingUnsubscribeConfirmationStatus, unsubscribeKontakt } from "~/modules/emailMarketing/services/ConsentService.server";
import { createScopedLogger } from "~/utils/logger.server";
import { MarketingResultPage } from "~/components/screens/email-marketing/EmailMarketingInterimScreens";
import { validateCSRFToken } from "~/utils/session.server";
import { useRootData } from "~/utils/data/useRootData";
import { Button } from "~/ui/components/Button";
const logger = createScopedLogger("marketing.unsubscribe");
type LoaderData = {
status: "ok" | "invalid" | "already_unsubscribed" | "run_not_found";
status: "confirm" | "ok" | "invalid" | "already_unsubscribed" | "run_not_found";
};
async function getUnsubscribeConfirmationStatus(token: string): Promise<LoaderData> {
const marketingStatus = await getMarketingUnsubscribeConfirmationStatus(token);
if (marketingStatus !== "invalid") return { status: marketingStatus };
const payload = verifyUnsubscribeToken(token);
if (!payload) return { status: "invalid" };
if (!payload.tenantId) return { status: "run_not_found" };
const run = await runWithRlsContext({ tenantId: payload.tenantId }, () =>
db.emailSequenceRun.findUnique({
where: { id: payload.runId },
select: { status: true },
})
);
if (!run) return { status: "run_not_found" };
return { status: run.status === "unsubscribed" ? "already_unsubscribed" : "confirm" };
}
/** Marketing campaign unsubscribe (AK-P14b token, version m1). Tries this first;
* falls through to the email-sequence path when the token isn't a marketing one. */
async function processMarketingUnsubscribe(token: string): Promise<LoaderData | null> {
@@ -48,7 +69,11 @@ async function processUnsubscribe(token: string): Promise<LoaderData> {
logger.warn({ op: "unsubscribe.invalid_token" }, "invalid unsubscribe token");
return { status: "invalid" };
}
const run = await db.emailSequenceRun.findUnique({ where: { id: payload.runId } });
if (!payload.tenantId) {
logger.warn({ op: "unsubscribe.missing_tenant", runId: payload.runId }, "unsubscribe token has no tenant scope");
return { status: "run_not_found" };
}
const run = await runWithRlsContext({ tenantId: payload.tenantId }, () => db.emailSequenceRun.findUnique({ where: { id: payload.runId } }));
if (!run) {
logger.warn({ op: "unsubscribe.run_missing", runId: payload.runId }, "unsubscribe run not found");
return { status: "run_not_found" };
@@ -56,28 +81,42 @@ async function processUnsubscribe(token: string): Promise<LoaderData> {
if (run.status === "unsubscribed") {
return { status: "already_unsubscribed" };
}
await db.emailSequenceRun.update({
where: { id: payload.runId },
data: { status: "unsubscribed", completedAt: new Date() },
});
logger.info(
{ op: "unsubscribe.applied", runId: payload.runId, leadId: payload.leadId, tenantId: payload.tenantId },
"sequence unsubscribed"
await runWithRlsContext({ tenantId: payload.tenantId }, () =>
db.emailSequenceRun.update({
where: { id: payload.runId },
data: { status: "unsubscribed", completedAt: new Date() },
})
);
logger.info({ op: "unsubscribe.applied", runId: payload.runId, leadId: payload.leadId, tenantId: payload.tenantId }, "sequence unsubscribed");
return { status: "ok" };
}
export async function loader({ params }: LoaderFunctionArgs): Promise<LoaderData> {
const token = params.token ?? "";
return processUnsubscribe(token);
return getUnsubscribeConfirmationStatus(token);
}
export async function action({ params }: ActionFunctionArgs): Promise<LoaderData> {
export async function action({ request, params }: ActionFunctionArgs): Promise<LoaderData> {
const formData = await request.formData();
const contentType = request.headers.get("content-type")?.toLowerCase() ?? "";
const entries = [...formData.entries()];
const isRfc8058OneClick =
contentType.startsWith("application/x-www-form-urlencoded") &&
entries.length === 1 &&
entries[0]?.[0] === "List-Unsubscribe" &&
entries[0]?.[1] === "One-Click";
if (!isRfc8058OneClick) {
await validateCSRFToken(request, { formData });
}
const token = params.token ?? "";
return processUnsubscribe(token);
}
const MESSAGES: Record<LoaderData["status"], { title: string; description: string }> = {
confirm: {
title: "marketing.unsubscribe.confirm.title",
description: "marketing.unsubscribe.confirm.description",
},
ok: {
title: "marketing.unsubscribe.ok.title",
description: "marketing.unsubscribe.ok.description",
@@ -97,13 +136,25 @@ const MESSAGES: Record<LoaderData["status"], { title: string; description: strin
};
export default function UnsubscribeRoute() {
const data = useLoaderData<LoaderData>();
const loaderData = useLoaderData<LoaderData>();
const actionData = useActionData<LoaderData>();
const data = actionData ?? loaderData;
const { t } = useTranslation();
const { csrf } = useRootData();
const msg = MESSAGES[data.status];
return (
<main style={{ maxWidth: "600px", margin: "60px auto", padding: "0 20px", fontFamily: "system-ui, sans-serif" }}>
<h1 style={{ fontSize: "24px" }}>{t(msg.title)}</h1>
<p style={{ fontSize: "16px", lineHeight: "1.5", color: "#475569" }}>{t(msg.description)}</p>
</main>
);
const action =
data.status === "confirm" ? (
<Form method="post">
<input type="hidden" name="csrf" value={csrf} readOnly />
<Button type="submit">{t("marketing.unsubscribe.confirm.action")}</Button>
</Form>
) : undefined;
return <MarketingResultPage title={t(msg.title)} description={t(msg.description)} action={action} />;
}
export function headers() {
return {
"Cache-Control": "no-store",
"Referrer-Policy": "no-referrer",
};
}