Skip to content
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
89 changes: 89 additions & 0 deletions app/api/tracker/v1/bot-hits/route.ts
Original file line number Diff line number Diff line change
@@ -0,0 +1,89 @@
// /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 }] }
//
// 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 { ANON_MAX_TOTAL, parseBotHits, resolveTrackedSite } from "@/lib/tracker/botHits";

export const runtime = "nodejs";
export const dynamic = "force-dynamic";

export async function POST(req: NextRequest) {
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();
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<string, number>();
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) });
}
76 changes: 76 additions & 0 deletions lib/tracker/botHits.ts
Original file line number Diff line number Diff line change
@@ -0,0 +1,76 @@
// 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;
/** 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 };

/** 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<string, BotHit>();
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()] };
}

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<string | null> {
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;
}
49 changes: 49 additions & 0 deletions tests/tracker-bot-hits.test.ts
Original file line number Diff line number Diff line change
@@ -0,0 +1,49 @@
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 }]);
});
});

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);
});
});