Files
HiveGrid-Wireframes/03 Quellen und Referenzen/hivegrid-cloud/apps/web/app/routes/e.c.$outboundEmailId.tsx
T

71 lines
2.7 KiB
TypeScript

/**
* AK-P14a · P14 Email — click-tracking redirect.
*
* GET /e/c/:outboundEmailId?u=<absolute-http(s)-url>&s=<signature>
*
* Records an OutboundEmailClick (IP stored only as a truncated sha256 hash) and
* 302-redirects to the target. The target and outbound-email id are bound by
* an HMAC so this unauthenticated endpoint cannot be repurposed as an open
* redirect. A missing/invalid signature or target returns 400; an unknown
* email id still redirects (tracking is best-effort) when the signature is
* valid.
*
* The marketing send path (AK-P14b) rewrites campaign links through this route;
* this is the tracking sink only.
*/
import type { LoaderFunctionArgs } from "react-router";
import { anonymizeTrackingIp, recordEmailClick, safeRedirectTarget } from "@hivegrid/db/email-tracking.server";
import { resolveOutboundEmailClickRlsIdentity } from "@hivegrid/db/rls-resolvers.server";
import { runWithRlsContext } from "@hivegrid/db/rls-context.server";
import { verifyClickTargetSignature } from "@hivegrid/email-sequences/click-tracking-token";
import { db } from "~/utils/db.server";
import { getTrustedClientIpOrNull } from "~/utils/server/IpUtils";
import { createScopedLogger } from "~/utils/logger.server";
import { getTranslations } from "~/locale/i18next.server";
const log = createScopedLogger("email.tracking.click");
export async function loader({ params, request }: LoaderFunctionArgs) {
const url = new URL(request.url);
const outboundEmailId = params.outboundEmailId ?? "";
const rawTarget = url.searchParams.get("u") ?? "";
const target = safeRedirectTarget(rawTarget);
if (
!target ||
!verifyClickTargetSignature({
deliveryId: outboundEmailId,
targetUrl: rawTarget,
signature: url.searchParams.get("s"),
})
) {
const { t } = await getTranslations(request);
return new Response(t("mail:tracking.invalidOrExpiredLink"), { status: 400 });
}
if (outboundEmailId) {
try {
const identity = await resolveOutboundEmailClickRlsIdentity(outboundEmailId);
if (identity) {
const ipHash = anonymizeTrackingIp(getTrustedClientIpOrNull(request));
await runWithRlsContext({ tenantId: identity.tenantId }, () =>
recordEmailClick({ tenantId: identity.tenantId, outboundEmailId: identity.resourceId, link: target, ipHash }, db as never)
);
}
} catch (error) {
// Tracking must never block the redirect.
log.error({ outboundEmailId, err: error instanceof Error ? error.message : String(error) }, "email click tracking failed");
}
}
return new Response(null, {
status: 302,
headers: {
Location: target,
"Cache-Control": "no-store",
"Referrer-Policy": "no-referrer",
},
});
}