51 lines
2.2 KiB
TypeScript
51 lines
2.2 KiB
TypeScript
/**
|
|
* Marketing-Funnel Phase 3 — click-through tracking + redirect (Phase 05 #80).
|
|
*
|
|
* GET /email/track-click/:deliveryId?u=<encoded-target-url>&s=<signature>
|
|
*
|
|
* Records the first clickedAt for the delivery row and 302-redirects
|
|
* the browser to the original href. The target and delivery id are bound by
|
|
* an HMAC so the public endpoint cannot be repurposed as an open redirect.
|
|
*
|
|
* Idempotent: subsequent clicks never overwrite the first-touch
|
|
* timestamp. Stats jobs aggregate raw counts per delivery.
|
|
*/
|
|
|
|
import type { LoaderFunctionArgs } from "react-router";
|
|
import { redirect } from "react-router";
|
|
import { runWithRlsContext } from "@hivegrid/db/rls-context.server";
|
|
import { resolveEmailSequenceDeliveryRlsIdentity } from "@hivegrid/db/rls-resolvers.server";
|
|
import { verifyClickTargetSignature } from "@hivegrid/email-sequences/click-tracking-token";
|
|
import { db } from "~/utils/db.server";
|
|
import { createScopedLogger } from "~/utils/logger.server";
|
|
import { getTranslations } from "~/locale/i18next.server";
|
|
|
|
const logger = createScopedLogger("marketing.tracking.click");
|
|
|
|
export async function loader({ params, request }: LoaderFunctionArgs): Promise<Response> {
|
|
const deliveryId = params.deliveryId ?? "";
|
|
const url = new URL(request.url);
|
|
const target = url.searchParams.get("u") ?? "";
|
|
const signature = url.searchParams.get("s");
|
|
if (!verifyClickTargetSignature({ deliveryId, targetUrl: target, signature })) {
|
|
const { t } = await getTranslations(request);
|
|
return new Response(t("mail:tracking.invalidOrExpiredLink"), { status: 400 });
|
|
}
|
|
if (deliveryId.length > 0) {
|
|
try {
|
|
const identity = await resolveEmailSequenceDeliveryRlsIdentity(deliveryId);
|
|
if (identity) {
|
|
await runWithRlsContext({ tenantId: identity.tenantId }, () =>
|
|
db.emailSequenceStepDelivery.updateMany({
|
|
where: { id: identity.resourceId, clickedAt: null },
|
|
data: { clickedAt: new Date() },
|
|
})
|
|
);
|
|
}
|
|
} catch (err) {
|
|
logger.warn({ op: "marketing.tracking.click.error", deliveryId, errorName: (err as Error)?.name }, "click tracker update failed");
|
|
}
|
|
}
|
|
return redirect(target, { headers: { "Referrer-Policy": "no-referrer", "Cache-Control": "no-store" } });
|
|
}
|