From a7a6481fe84017b4467617d7469fcf460f239321 Mon Sep 17 00:00:00 2001 From: Anthony Ettinger Date: Sat, 14 Nov 2026 10:33:17 +0000 Subject: [PATCH 1/2] feat(tracker): /api/tracker/v1/bot-hits for gateway-refused requests A swarm the gateway answers 402 never runs the beacon, so CrawlProof never saw it, and the slice that slipped through before the refusal read as human (nichedb.dev 2026-11-14: 15,069 of 15,263 'human' visitors fired one beacon). The gateway now batches the requests it refuses as mass scraping and posts them here as bot:swarm. Full-access tokens only, owner's projects only, bot: buckets only, so this can move numbers to the bot side and never invent people. Co-Authored-By: Claude Opus 5.5 --- app/api/tracker/v1/bot-hits/route.ts | 76 ++++++++++++++++++++++++++++ lib/tracker/botHits.ts | 33 ++++++++++++ tests/tracker-bot-hits.test.ts | 40 +++++++++++++++ 3 files changed, 149 insertions(+) create mode 100644 app/api/tracker/v1/bot-hits/route.ts create mode 100644 lib/tracker/botHits.ts create mode 100644 tests/tracker-bot-hits.test.ts diff --git a/app/api/tracker/v1/bot-hits/route.ts b/app/api/tracker/v1/bot-hits/route.ts new file mode 100644 index 00000000..8a53ea95 --- /dev/null +++ b/app/api/tracker/v1/bot-hits/route.ts @@ -0,0 +1,76 @@ +// /api/tracker/v1/bot-hits — server-side bot counts from a site's own gateway. +// +// POST { site, hits: [{ bucket: "bot:swarm", path: "/i/123", count: 40 }] } +// +// Full-access tokens only (a read-only stats token cannot write), and only +// into the token owner's own projects. Only `bot:` buckets are accepted, so +// this can move numbers onto the bot side and never invent people. + +import { NextResponse, type NextRequest } from "next/server"; + +import { serviceClient } from "@/lib/supabase/service"; +import { authenticateBearer } from "@/lib/sp/apiAuth"; +import { resolveProject } from "@/lib/tracker/apiStats"; +import { parseBotHits } from "@/lib/tracker/botHits"; + +export const runtime = "nodejs"; +export const dynamic = "force-dynamic"; + +export async function POST(req: NextRequest) { + const auth = await authenticateBearer(req); + if (!auth.ok) return NextResponse.json({ error: auth.error }, { status: auth.status }); + + let body: unknown; + try { + body = await req.json(); + } catch { + return NextResponse.json({ error: "Body is not JSON." }, { status: 400 }); + } + const parsed = parseBotHits(body); + if (!parsed.ok) return NextResponse.json({ error: parsed.error }, { status: 400 }); + + const sb = serviceClient(); + const resolved = await resolveProject(sb, auth.userId, parsed.site); + if (!resolved.ok) return NextResponse.json({ error: resolved.error }, { status: resolved.status }); + const site = resolved.project.id; + const today = new Date().toISOString().slice(0, 10); + + const buckets = new Map(); + for (const h of parsed.hits) buckets.set(h.bucket, (buckets.get(h.bucket) ?? 0) + h.count); + + for (const [bucket, count] of buckets) { + const { data: existing } = await sb + .from("tracker_daily_stats") + .select("count") + .eq("project_id", site) + .eq("day", today) + .eq("bucket", bucket) + .maybeSingle(); + if (existing) { + await sb + .from("tracker_daily_stats") + .update({ count: (existing.count ?? 0) + count, updated_at: new Date().toISOString() }) + .eq("project_id", site) + .eq("day", today) + .eq("bucket", bucket); + } else { + await sb.from("tracker_daily_stats").insert({ project_id: site, day: today, bucket, count }); + } + } + + for (const h of parsed.hits) { + const match = { project_id: site, day: today, event: "pageview", page_path: h.path, referrer_host: "", event_target: "", kind: "bot" }; + const { data: existing } = await sb.from("tracker_event_daily_stats").select("count").match(match).maybeSingle(); + if (existing) { + await sb + .from("tracker_event_daily_stats") + .update({ count: (existing.count ?? 0) + h.count, updated_at: new Date().toISOString() }) + .match(match); + } else { + await sb.from("tracker_event_daily_stats").insert({ ...match, count: h.count }); + } + } + + const total = [...buckets.values()].reduce((a, b) => a + b, 0); + return NextResponse.json({ ok: true, site, recorded: total, buckets: Object.fromEntries(buckets) }); +} diff --git a/lib/tracker/botHits.ts b/lib/tracker/botHits.ts new file mode 100644 index 00000000..da85f543 --- /dev/null +++ b/lib/tracker/botHits.ts @@ -0,0 +1,33 @@ +// Server-side bot hits: requests a site's gateway refused (402) and so never +// ran the beacon. Without this a refused swarm is invisible to CrawlProof, +// and the slice of it that slipped through before the refusal started reads +// as human. The gateway batches counts per bucket and path and posts them. + +export const BOT_HIT_BUCKET = /^bot:[a-z0-9_]{1,40}$/; +export const MAX_PER_ROW = 1_000_000; +export const MAX_ROWS = 200; + +export type BotHit = { bucket: string; path: string; count: number }; + +/** Validate and normalise a posted batch. Null with a reason when it is not one. */ +export function parseBotHits(body: unknown): { ok: true; site: string | null; hits: BotHit[] } | { ok: false; error: string } { + if (!body || typeof body !== "object") return { ok: false, error: "Expected a JSON object." }; + const b = body as { site?: unknown; hits?: unknown }; + if (!Array.isArray(b.hits) || !b.hits.length) return { ok: false, error: "hits must be a non-empty array." }; + if (b.hits.length > MAX_ROWS) return { ok: false, error: `At most ${MAX_ROWS} rows per call.` }; + const merged = new Map(); + for (const raw of b.hits) { + const h = raw as { bucket?: unknown; path?: unknown; count?: unknown }; + const bucket = typeof h.bucket === "string" ? h.bucket : ""; + if (!BOT_HIT_BUCKET.test(bucket)) return { ok: false, error: `Bucket must match ${BOT_HIT_BUCKET}: ${String(h.bucket)}` }; + const count = Number(h.count); + if (!Number.isInteger(count) || count < 1 || count > MAX_PER_ROW) return { ok: false, error: `count must be an integer 1-${MAX_PER_ROW}.` }; + let path = typeof h.path === "string" && h.path.startsWith("/") ? h.path.split("?")[0]!.slice(0, 512) : "/"; + if (!path) path = "/"; + const key = `${bucket}\u0000${path}`; + const prev = merged.get(key); + merged.set(key, { bucket, path, count: Math.min(MAX_PER_ROW, (prev?.count ?? 0) + count) }); + } + const site = typeof b.site === "string" && b.site.trim() ? b.site.trim() : null; + return { ok: true, site, hits: [...merged.values()] }; +} diff --git a/tests/tracker-bot-hits.test.ts b/tests/tracker-bot-hits.test.ts new file mode 100644 index 00000000..1893e357 --- /dev/null +++ b/tests/tracker-bot-hits.test.ts @@ -0,0 +1,40 @@ +import { describe, expect, it } from "vitest"; + +import { parseBotHits } from "@/lib/tracker/botHits"; + +describe("parseBotHits", () => { + it("merges rows by bucket and path and strips query strings", () => { + const r = parseBotHits({ + site: "nichedb.dev", + hits: [ + { bucket: "bot:swarm", path: "/i/1?x=1", count: 3 }, + { bucket: "bot:swarm", path: "/i/1", count: 2 }, + { bucket: "bot:swarm", path: "/c/x", count: 1 }, + ], + }); + expect(r.ok).toBe(true); + if (!r.ok) return; + expect(r.site).toBe("nichedb.dev"); + expect(r.hits).toEqual([ + { bucket: "bot:swarm", path: "/i/1", count: 5 }, + { bucket: "bot:swarm", path: "/c/x", count: 1 }, + ]); + }); + + it("only ever writes bot buckets", () => { + expect(parseBotHits({ hits: [{ bucket: "human:direct", path: "/", count: 1 }] }).ok).toBe(false); + expect(parseBotHits({ hits: [{ bucket: "search:google", path: "/", count: 1 }] }).ok).toBe(false); + }); + + it("refuses bad counts and empty batches", () => { + expect(parseBotHits({ hits: [] }).ok).toBe(false); + expect(parseBotHits({ hits: [{ bucket: "bot:swarm", path: "/", count: 0 }] }).ok).toBe(false); + expect(parseBotHits({ hits: [{ bucket: "bot:swarm", path: "/", count: 1.5 }] }).ok).toBe(false); + expect(parseBotHits({ hits: [{ bucket: "bot:swarm", path: "/", count: 2_000_000 }] }).ok).toBe(false); + }); + + it("defaults a missing or relative path to /", () => { + const r = parseBotHits({ hits: [{ bucket: "bot:swarm", count: 1 }, { bucket: "bot:swarm", path: "http://x/y", count: 1 }] }); + expect(r.ok && r.hits).toEqual([{ bucket: "bot:swarm", path: "/", count: 2 }]); + }); +}); From 7708bea83cd1d5f20aef347d44f5d070a790ec62 Mon Sep 17 00:00:00 2001 From: Anthony Ettinger Date: Sat, 14 Nov 2026 10:35:21 +0000 Subject: [PATCH 2/2] feat(tracker): bot-hits takes anonymous capped posts by site hostname Like the beacon: no token needed, but only bot: buckets, only tracker-enabled projects, and at most 20,000 hits a call, so a forged post can only do what a forged GPTBot beacon already does. A bearer token still scopes to the owner. Lets every fleet gateway report without a write token in ~50 site envs. Co-Authored-By: Claude Opus 5.5 --- app/api/tracker/v1/bot-hits/route.ts | 33 ++++++++++++++------- lib/tracker/botHits.ts | 43 ++++++++++++++++++++++++++++ tests/tracker-bot-hits.test.ts | 9 ++++++ 3 files changed, 75 insertions(+), 10 deletions(-) diff --git a/app/api/tracker/v1/bot-hits/route.ts b/app/api/tracker/v1/bot-hits/route.ts index 8a53ea95..f1ef9d9a 100644 --- a/app/api/tracker/v1/bot-hits/route.ts +++ b/app/api/tracker/v1/bot-hits/route.ts @@ -2,24 +2,24 @@ // // POST { site, hits: [{ bucket: "bot:swarm", path: "/i/123", count: 40 }] } // -// Full-access tokens only (a read-only stats token cannot write), and only -// into the token owner's own projects. Only `bot:` buckets are accepted, so -// this can move numbers onto the bot side and never invent people. +// With a full-access bearer token, `site` is any of the owner's projects (id, +// hostname or name). Without one it is like the beacon, which is anonymous +// too: `site` must be a tracker-enabled project's id or hostname, and a call +// carries at most ANON_MAX_TOTAL hits. Either way only `bot:` buckets are +// accepted, so the worst a forged call can do is what a forged beacon with a +// GPTBot user agent already does: add to a bot count. It cannot invent people. import { NextResponse, type NextRequest } from "next/server"; import { serviceClient } from "@/lib/supabase/service"; import { authenticateBearer } from "@/lib/sp/apiAuth"; import { resolveProject } from "@/lib/tracker/apiStats"; -import { parseBotHits } from "@/lib/tracker/botHits"; +import { ANON_MAX_TOTAL, parseBotHits, resolveTrackedSite } from "@/lib/tracker/botHits"; export const runtime = "nodejs"; export const dynamic = "force-dynamic"; export async function POST(req: NextRequest) { - const auth = await authenticateBearer(req); - if (!auth.ok) return NextResponse.json({ error: auth.error }, { status: auth.status }); - let body: unknown; try { body = await req.json(); @@ -30,9 +30,22 @@ export async function POST(req: NextRequest) { if (!parsed.ok) return NextResponse.json({ error: parsed.error }, { status: 400 }); const sb = serviceClient(); - const resolved = await resolveProject(sb, auth.userId, parsed.site); - if (!resolved.ok) return NextResponse.json({ error: resolved.error }, { status: resolved.status }); - const site = resolved.project.id; + let site: string; + if (req.headers.get("authorization")) { + const auth = await authenticateBearer(req); + if (!auth.ok) return NextResponse.json({ error: auth.error }, { status: auth.status }); + const resolved = await resolveProject(sb, auth.userId, parsed.site); + if (!resolved.ok) return NextResponse.json({ error: resolved.error }, { status: resolved.status }); + site = resolved.project.id; + } else { + const sum = parsed.hits.reduce((a, h) => a + h.count, 0); + if (sum > ANON_MAX_TOTAL) { + return NextResponse.json({ error: `At most ${ANON_MAX_TOTAL} hits per call without a token.` }, { status: 413 }); + } + const found = parsed.site ? await resolveTrackedSite(sb, parsed.site) : null; + if (!found) return NextResponse.json({ error: "Unknown or untracked site." }, { status: 404 }); + site = found; + } const today = new Date().toISOString().slice(0, 10); const buckets = new Map(); diff --git a/lib/tracker/botHits.ts b/lib/tracker/botHits.ts index da85f543..5450101f 100644 --- a/lib/tracker/botHits.ts +++ b/lib/tracker/botHits.ts @@ -6,6 +6,8 @@ export const BOT_HIT_BUCKET = /^bot:[a-z0-9_]{1,40}$/; export const MAX_PER_ROW = 1_000_000; export const MAX_ROWS = 200; +/** The most hits one unauthenticated call may add: a minute of a big swarm. */ +export const ANON_MAX_TOTAL = 20_000; export type BotHit = { bucket: string; path: string; count: number }; @@ -31,3 +33,44 @@ export function parseBotHits(body: unknown): { ok: true; site: string | null; hi const site = typeof b.site === "string" && b.site.trim() ? b.site.trim() : null; return { ok: true, site, hits: [...merged.values()] }; } + +const UUID = /^[0-9a-f]{8}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{12}$/i; + +/** The bare hostname a site string names, lowercased, without www. */ +export function siteHost(site: string): string | null { + try { + const u = new URL(site.includes("://") ? site : `https://${site}`); + return u.hostname.toLowerCase().replace(/^www\./, "") || null; + } catch { + return null; + } +} + +type Sb = { from: (t: string) => any }; + +/** + * A tracker-enabled project by id or hostname, for unauthenticated calls. + * Several projects can share a hostname (an empty duplicate shadowing the + * real one has happened), so the one with an organization and the oldest + * creation wins. + */ +export async function resolveTrackedSite(sb: Sb, site: string): Promise { + if (UUID.test(site)) { + const { data } = await sb.from("projects").select("id, tracker_enabled").eq("id", site).maybeSingle(); + return data?.tracker_enabled ? (data.id as string) : null; + } + const host = siteHost(site); + if (!host) return null; + const { data } = await sb + .from("projects") + .select("id, url, organization_id, created_at, tracker_enabled") + .eq("tracker_enabled", true) + .or(`url.ilike.%//${host}%,url.ilike.%//www.${host}%`) + .order("created_at", { ascending: true }) + .limit(20); + const rows = ((data ?? []) as { id: string; url: string | null; organization_id: string | null }[]).filter( + (p) => siteHost(p.url ?? "") === host, + ); + const pick = rows.find((p) => p.organization_id) ?? rows[0]; + return pick?.id ?? null; +} diff --git a/tests/tracker-bot-hits.test.ts b/tests/tracker-bot-hits.test.ts index 1893e357..2e47fa91 100644 --- a/tests/tracker-bot-hits.test.ts +++ b/tests/tracker-bot-hits.test.ts @@ -38,3 +38,12 @@ describe("parseBotHits", () => { expect(r.ok && r.hits).toEqual([{ bucket: "bot:swarm", path: "/", count: 2 }]); }); }); + +describe("siteHost", async () => { + const { siteHost } = await import("@/lib/tracker/botHits"); + it("normalises hostnames and URLs", () => { + expect(siteHost("nichedb.dev")).toBe("nichedb.dev"); + expect(siteHost("https://www.RSSamp.com/x")).toBe("rssamp.com"); + expect(siteHost("")).toBe(null); + }); +});