161 lines
6.6 KiB
TypeScript
161 lines
6.6 KiB
TypeScript
/**
|
|
* Marketing-Funnel Phase 3 unsubscribe route (Phase 05 #80).
|
|
*
|
|
* GET verifies the HMAC token and displays a confirmation without writing.
|
|
* Only POST flips the EmailSequenceRun status to `unsubscribed`; repeats are
|
|
* idempotent.
|
|
*
|
|
* 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 { 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 { 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: "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> {
|
|
const payload = verifyMarketingToken(token, { expectedPurpose: "unsub" });
|
|
if (!payload) return null;
|
|
const result = await unsubscribeKontakt({ tenantId: payload.tenantId, kontaktId: payload.kontaktId, campaignId: payload.campaignId, reason: "one_click" });
|
|
logger.info(
|
|
{ op: "unsubscribe.marketing", kontaktId: payload.kontaktId, tenantId: payload.tenantId, campaignId: payload.campaignId, result },
|
|
"marketing unsubscribe processed"
|
|
);
|
|
return { status: result === "already_unsubscribed" ? "already_unsubscribed" : "ok" };
|
|
}
|
|
|
|
async function processUnsubscribe(token: string): Promise<LoaderData> {
|
|
const marketing = await processMarketingUnsubscribe(token);
|
|
if (marketing) return marketing;
|
|
|
|
const payload = verifyUnsubscribeToken(token);
|
|
if (!payload) {
|
|
logger.warn({ op: "unsubscribe.invalid_token" }, "invalid unsubscribe token");
|
|
return { status: "invalid" };
|
|
}
|
|
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" };
|
|
}
|
|
if (run.status === "unsubscribed") {
|
|
return { status: "already_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 getUnsubscribeConfirmationStatus(token);
|
|
}
|
|
|
|
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",
|
|
},
|
|
already_unsubscribed: {
|
|
title: "marketing.unsubscribe.alreadyUnsubscribed.title",
|
|
description: "marketing.unsubscribe.alreadyUnsubscribed.description",
|
|
},
|
|
invalid: {
|
|
title: "marketing.unsubscribe.invalid.title",
|
|
description: "marketing.unsubscribe.invalid.description",
|
|
},
|
|
run_not_found: {
|
|
title: "marketing.unsubscribe.runNotFound.title",
|
|
description: "marketing.unsubscribe.runNotFound.description",
|
|
},
|
|
};
|
|
|
|
export default function UnsubscribeRoute() {
|
|
const loaderData = useLoaderData<LoaderData>();
|
|
const actionData = useActionData<LoaderData>();
|
|
const data = actionData ?? loaderData;
|
|
const { t } = useTranslation();
|
|
const { csrf } = useRootData();
|
|
const msg = MESSAGES[data.status];
|
|
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",
|
|
};
|
|
}
|