61 lines
2.4 KiB
TypeScript
61 lines
2.4 KiB
TypeScript
/**
|
|
* AK-P14a · P14 Email — open-tracking pixel.
|
|
*
|
|
* GET /e/o/:outboundEmailId?t=<stored-tracking-token>
|
|
*
|
|
* Returns a 1x1 transparent GIF and records an OutboundEmailOpen (the first open
|
|
* of an email is flagged). Unauthenticated — it is fetched by the recipient's
|
|
* mail client. The client IP is stored ONLY as a truncated sha256 hash. An
|
|
* unknown / malformed id still returns the pixel (mail clients must not see an
|
|
* error), the open is simply not recorded.
|
|
*
|
|
* The marketing send path (AK-P14b) embeds this URL; this route is the tracking
|
|
* sink only.
|
|
*/
|
|
|
|
import type { LoaderFunctionArgs } from "react-router";
|
|
|
|
import { anonymizeTrackingIp, recordEmailOpen } from "@hivegrid/db/email-tracking.server";
|
|
import { resolveOutboundEmailOpenRlsIdentity } from "@hivegrid/db/rls-resolvers.server";
|
|
import { runWithRlsContext } from "@hivegrid/db/rls-context.server";
|
|
import { db } from "~/utils/db.server";
|
|
import { getTrustedClientIpOrNull } from "~/utils/server/IpUtils";
|
|
import { createScopedLogger } from "~/utils/logger.server";
|
|
|
|
const log = createScopedLogger("email.tracking.open");
|
|
|
|
// 1x1 transparent GIF.
|
|
const TRACKING_PIXEL = Buffer.from("R0lGODlhAQABAIAAAAAAAP///yH5BAEAAAAALAAAAAABAAEAAAIBRAA7", "base64");
|
|
|
|
function pixelResponse(): Response {
|
|
return new Response(TRACKING_PIXEL, {
|
|
status: 200,
|
|
headers: {
|
|
"Content-Type": "image/gif",
|
|
"Content-Length": String(TRACKING_PIXEL.byteLength),
|
|
"Cache-Control": "no-store, no-cache, must-revalidate, private",
|
|
Pragma: "no-cache",
|
|
},
|
|
});
|
|
}
|
|
|
|
export async function loader({ params, request }: LoaderFunctionArgs) {
|
|
const outboundEmailId = params.outboundEmailId;
|
|
const trackingToken = new URL(request.url).searchParams.get("t");
|
|
if (outboundEmailId && trackingToken) {
|
|
try {
|
|
const identity = await resolveOutboundEmailOpenRlsIdentity(outboundEmailId, trackingToken);
|
|
if (identity) {
|
|
const ipHash = anonymizeTrackingIp(getTrustedClientIpOrNull(request));
|
|
await runWithRlsContext({ tenantId: identity.tenantId }, () =>
|
|
recordEmailOpen({ tenantId: identity.tenantId, outboundEmailId: identity.resourceId, ipHash }, db as never)
|
|
);
|
|
}
|
|
} catch (error) {
|
|
// Tracking must never break pixel delivery.
|
|
log.error({ outboundEmailId, err: error instanceof Error ? error.message : String(error) }, "email open tracking failed");
|
|
}
|
|
}
|
|
return pixelResponse();
|
|
}
|