export const trackingDisabled = (request) => /dm-tracking=off/.test(request.headers.get("cookie") || "") || request.headers.get("sec-gpc") === "1" || request.headers.get("dnt") === "1"; export function safePath(value) { try { return new URL(value, "https://local.invalid").pathname.split("/").map((s) => s.length > 32 || /@|%40/.test(s) ? ":private" : s).join("/").slice(0, 300); } catch { return "/"; } } export async function trackingRoute(request, env, ctx, project, ssoUser) { if (request.method !== "POST") return new Response(null, { status: 405 }); if (request.headers.get("origin") !== new URL(request.url).origin) return new Response(null, { status: 403 }); if (!env.TRACKING || trackingDisabled(request) || project.name === "account") return new Response(null, { status: 204 }); if (Number(request.headers.get("content-length") || 0) > 16e3) return new Response(null, { status: 413 }); const text = await request.text(); if (text.length > 16e3) return new Response(null, { status: 413 }); let body; try { body = JSON.parse(text); } catch { return new Response(null, { status: 400 }); } if (!Array.isArray(body.events) || body.events.length > 40) return new Response(null, { status: 400 }); const user = await ssoUser(request, env); const events = body.events.filter((e) => ["view", "click", "action", "cursor"].includes(e.kind)).map((e) => ({ kind: e.kind, path: safePath(e.path), target: /^[a-z0-9_-]{1,64}$/i.test(e.target || "") ? e.target : null, x: Math.max(0, Math.min(1, Number(e.x) || 0)), y: Math.max(0, Math.min(1, Number(e.y) || 0)), width: Math.min(1e4, Number(e.width) || 0), height: Math.min(1e4, Number(e.height) || 0) })); ctx.waitUntil(env.TRACKING.ingest({ app: project.name, events, account: user ? { id: user.id, email: user.email } : null, ip: request.headers.get("cf-connecting-ip"), ua: request.headers.get("user-agent"), country: request.cf?.country }).catch(() => console.error(JSON.stringify({ event: "tracking_delivery_failed", app: project.name })))); return new Response(null, { status: 204, headers: { "Cache-Control": "no-store" } }); }