commit
aaa
diff --git a/.dev.vars.example b/.dev.vars.example
index 56075ea..9e24fa3 100644
--- a/.dev.vars.example
+++ b/.dev.vars.example
@@ -21,7 +21,7 @@ DISCORD_USER_TOKEN2=
DISCORD_USER_TOKEN3=
# =====================================================================
-# Doughmination system API (/v2/plural, /v2/battery, /v2/system-data)
+# Doughmination system API (/v2/plural, /v2/battery, /v2/counter)
# =====================================================================
# PluralKit system token (Authorization header for api.pluralkit.me).
diff --git a/README.md b/README.md
index 05fd763..56be269 100644
--- a/README.md
+++ b/README.md
@@ -15,7 +15,7 @@ This code wasn't just me. It took a good chunk of my own brain plus a lot of hel
Two Durable Objects behind the Worker router (`src/index.ts`):
- **GATEWAY** (`GatewayManager`) — holds the single Discord gateway socket, ingests presences from `READY` / `GUILD_CREATE` / `PRESENCE_UPDATE`, and keeps an in-memory `userId → presence` map. It doesn't serve browser sockets; it relays each live presence change to the SYSTEM DO for fan-out.
-- **SYSTEM** (`SystemState`) — all persistent state (users, tags, statuses, mental state, devices) in DO storage, the visitor-log SQLite table, and the single realtime WebSocket hub.
+- **SYSTEM** (`SystemState`) — all persistent state (users, tags, statuses, mental state, devices) in DO storage, the visit-counter SQLite tables, and the single realtime WebSocket hub.
A cron trigger (`*/2 * * * *`) keeps the gateway DO connected. Static assets under `assets/` are served at the site root (`/icon.png`, `/capes/*`, …).
@@ -31,7 +31,7 @@ Full, filterable reference at [`/docs`](https://doughmination.uk/docs). The map:
| `/v2/discord/guilds/:invite`, `/v2/discord/girls/:idType/:id` | Guild info from an invite; role/member lookups |
| `/v2/minecraft/general/:uuid`, `/v2/minecraft/hypixel/:uuid`, `/v2/minecraft/capes` | Mojang identity + skins/capes, Hypixel stats, vanilla cape catalogue |
| `/v2/contribapi` | Merged git contribution heatmaps (GitHub + Codeberg) |
-| `/v2/plural/*`, `/v2/devices/*`, `/v2/guestbook/*`, `/v2/system-data/*` | The plural-system API: fronting, members, mental state, devices/battery, guestbook, visitor logs |
+| `/v2/plural/*`, `/v2/devices/*`, `/v2/guestbook/*`, `/v2/counter/*` | The plural-system API: fronting, members, mental state, devices/battery, guestbook, site visit counters |
| `/v2/health` | Liveness: gateway connection + DO reachability (200 ok / 503 degraded) — point uptime monitors here |
| `/docs`, `/openapi.json` | Full HTML API reference + machine-readable OpenAPI 3.1 spec (both generated from `src/apidata.ts`) |
| `/abuse`, `/terms`, `/privacy`, `/.well-known/security.txt` | Abuse reports, terms of service, privacy, vulnerability disclosure |
@@ -136,7 +136,7 @@ bun decode "X-Super-Properties: [BASE64 HERE]"
## Abuse, privacy & security
- **Terms:** [`/terms`](https://doughmination.uk/terms) — the short version: be reasonable with request volume or your IP gets blocked.
-- **Privacy:** [`/privacy`](https://doughmination.uk/privacy) — what's logged (visitor IPs, guestbook entries, brief Discord/Minecraft caches) and how to get it removed.
+- **Privacy:** [`/privacy`](https://doughmination.uk/privacy) — what's stored (guestbook entries, anonymous visit counts, brief Discord/Minecraft caches) and how to get it removed.
- **Report abuse / request data removal:** [`/abuse`](https://doughmination.uk/abuse) or email **[email protected]**.
- **Opt out of presence tracking:** leave the Discord server(s) the bot is in, or email with your Discord user ID to be blocked from lookups.
- **Vulnerability disclosure:** email the address above; machine-readable contact at [`/.well-known/security.txt`](https://doughmination.uk/.well-known/security.txt). Responsible disclosure appreciated.
diff --git a/src/apidata.ts b/src/apidata.ts
index 42c7056..990c735 100644
--- a/src/apidata.ts
+++ b/src/apidata.ts
@@ -247,18 +247,26 @@ export const GROUPS: GroupDef[] = [
],
},
{
- id: "system-data", name: "System-data — visitor logs", blurb: "Visit logging plus an admin-only log viewer.",
+ id: "counter", name: "Counter — site visit counters", blurb: "A hit counter per site id. Stores no IPs, no headers, no cookies — just a salted, non-reversible visitor hash.",
endpoints: [
- { m: "POST", path: "/system-data/helper", auth: "public",
- desc: "Log a page visit (the frontend pings this on navigation). Body { path? }." },
- { m: "GET", path: "/system-data/helper?path=", auth: "public", desc: "Log a page visit via a plain GET, for cases where a POST isn't convenient." },
- { m: "GET", path: "/system-data", auth: "admin", desc: "HTML log viewer (single page)." },
- { m: "GET", path: "/system-data/api/stats", auth: "admin", desc: "Totals, unique IPs, last-24h, top paths." },
- { m: "GET", path: "/system-data/api/recent?limit=100", auth: "admin", desc: "Recent visits." },
- { m: "GET", path: "/system-data/api/by-ip/:ip", auth: "admin", desc: "Visits from an IP." },
- { m: "GET", path: "/system-data/api/by-path?q=", auth: "admin", desc: "Visits matching a path substring." },
- { m: "GET", path: "/system-data/api/suspicious", auth: "admin", desc: ">20 hits/hour from one IP." },
- { m: "GET", path: "/system-data/api/entry/:id", auth: "admin", desc: "One full log row." },
+ { m: "GET", path: "/counter", auth: "public",
+ desc: "Every site with a counter, busiest first \u2192 { sites: [{ site_id, total, unique, today, created_at, updated_at }] }." },
+ { m: "GET", path: "/counter/:siteId", auth: "public",
+ desc: "Read a site's counts without recording a visit \u2192 { site_id, total, unique, today, created_at, updated_at }. 404 if the site has never been hit.",
+ params: [["siteId", "1\u201364 chars: lowercase letters, digits, dot, dash, underscore."]] },
+ { m: "POST", path: "/counter/:siteId", auth: "public",
+ desc: "Record a visit and get the updated counts back, plus 'counted' (false when the 30-minute per-visitor cooldown swallowed it) and 'first_visit'. The site registers itself on its first hit. No request body.",
+ params: [["siteId", "1\u201364 chars: lowercase letters, digits, dot, dash, underscore."]],
+ example: 'POST /counter/is.doughmination.gay \u2192 { "site_id": "is.doughmination.gay", "total": 1337, "unique": 402, "today": 12, "counted": true, "first_visit": false }' },
+ { m: "GET", path: "/counter/:siteId/hit", auth: "public",
+ desc: "The same thing over a plain GET, for callers that can't POST (a no-JS beacon, a hand-typed URL). Reading /counter/:siteId itself never records anything." },
+ { m: "GET", path: "/counter/:siteId/history?days=30", auth: "public",
+ desc: "Daily visit histogram, oldest first \u2192 { site_id, days, history: [{ day, hits }] }. Days are UTC and kept for 400 days.",
+ params: [["?days", "Optional. 1\u2013400, default 30."]] },
+ { m: "POST", path: "/counter/:siteId/reset", auth: "key",
+ desc: "Zero a site's counters, keeping the site registered. Send the X-Battery-Key header." },
+ { m: "DELETE", path: "/counter/:siteId", auth: "key",
+ desc: "Delete a site and everything recorded for it. Returns 404 if not found. Send the X-Battery-Key header." },
],
},
{
@@ -287,7 +295,7 @@ export const GROUPS: GroupDef[] = [
{ m: "GET", path: "/openapi.json", auth: "public", desc: "Machine-readable OpenAPI 3.1 spec generated from the same catalogue that renders this page.", root: true },
{ m: "GET", path: "/abuse", auth: "public", desc: "Abuse & contact page: how to report abuse, request data removal / opt-out, or disclose a vulnerability.", root: true },
{ m: "GET", path: "/terms", auth: "public", desc: "Terms of service — the short version: be reasonable with request volume or your IP gets blocked.", root: true },
- { m: "GET", path: "/privacy", auth: "public", desc: "Privacy page: what's logged (visitor IPs, guestbook entries, cached Discord data), why, and how to get it removed.", root: true },
+ { m: "GET", path: "/privacy", auth: "public", desc: "Privacy page: what's stored (guestbook entries, anonymous visit counts, cached Discord data), why, and how to get it removed.", root: true },
{ m: "GET", path: "/.well-known/security.txt", auth: "public", desc: "RFC 9116 security contact file. Also available at /security.txt.", root: true },
],
},
diff --git a/src/index.ts b/src/index.ts
index 5584158..f80f142 100644
--- a/src/index.ts
+++ b/src/index.ts
@@ -10,7 +10,7 @@
* /v2/plural/* — Doughmination system API (SystemState DO)
* /v2/devices/* — device state (battery, etc.) (SystemState DO)
* /v2/guestbook/* — public guestbook (SystemState DO)
- * /v2/system-data/* — visitor logs + viewer (SystemState DO)
+ * /v2/counter/* — per-site visit counters (SystemState DO)
* /abuse, /terms, /privacy, /.well-known/security.txt — contact & legal pages
* /docs, /openapi.json — API reference (HTML + OpenAPI 3.1)
* /v2/health — liveness for uptime monitors
@@ -149,8 +149,8 @@ function isSystemPath(path: string): boolean {
path.startsWith("/v2/devices/") ||
path === "/v2/guestbook" ||
path.startsWith("/v2/guestbook/") ||
- path === "/v2/system-data" ||
- path.startsWith("/v2/system-data/")
+ path === "/v2/counter" ||
+ path.startsWith("/v2/counter/")
);
}
@@ -187,7 +187,7 @@ export default {
const path = url.pathname.replace(/\/+$/, "") || "/";
- // ---- SystemState DO (plural / devices / system-data / realtime) ------
+ // ---- SystemState DO (plural / devices / counter / realtime) ----------
// Forwarded first, and untouched, so its Hono CORS + the single realtime
// WebSocket upgrade (/v2/ws) work end-to-end.
if (isSystemPath(path)) {
diff --git a/src/pages.ts b/src/pages.ts
index 1921a84..a0da8a0 100644
--- a/src/pages.ts
+++ b/src/pages.ts
@@ -156,12 +156,12 @@ export const PRIVACY_HTML = pageShell(
`What this service stores, why, and how to get it removed. <a href="/docs">← API reference</a>`,
`
<div class="card">
- <strong>tl;dr:</strong> no ads, no analytics, no selling anything. Visit logs (IP + path) are kept for abuse monitoring, guestbook posts are public, and Discord/Minecraft data is cached briefly. Email <a href="mailto:${ABUSE_CONTACT}">${ABUSE_CONTACT}</a> to have anything about you removed.
+ <strong>tl;dr:</strong> no ads, no analytics, no selling anything. Visit counters are anonymous totals only, guestbook posts are public, and Discord/Minecraft data is cached briefly. Email <a href="mailto:${ABUSE_CONTACT}">${ABUSE_CONTACT}</a> to have anything about you removed.
</div>
<h2>What's collected</h2>
<ul>
- <li><strong>Visit logs.</strong> Requests logged via the site frontend record IP address, request path, user agent, and timestamp. They exist purely for security and abuse monitoring (spotting floods and probes) and are visible only to the admin. They are not shared with anyone and are cleared periodically.</li>
+ <li><strong>Visit counters.</strong> Pages that show a visitor count call <code>/v2/counter/<site></code>. Nothing identifying is stored: your IP and user agent are hashed together with a per-site secret salt into an opaque value that can't be reversed or matched across sites, and only that hash, a running total and a per-day tally are kept. No IP addresses, headers, cookies or request paths are written down.</li>
<li><strong>Guestbook entries.</strong> Name, message, and optional website are public by design. The submitting IP is used transiently for rate limiting (one post per 60 seconds) and spam protection (Cloudflare Turnstile).</li>
<li><strong>Discord presence & profiles.</strong> The API tracks live presence only for users who share a Discord server with its bot. Presence is held in memory only and never written to storage. Profile data (avatar, badges, connections) is fetched live from Discord on each request and not stored.</li>
<li><strong>Minecraft & Hypixel data.</strong> Public data fetched from Mojang/Hypixel on request, cached for about 5 minutes. The vanilla-cape catalogue keeps cape textures (not player identities) permanently.</li>
diff --git a/src/system/app.ts b/src/system/app.ts
index 1ae4c56..5bbda79 100644
--- a/src/system/app.ts
+++ b/src/system/app.ts
@@ -12,7 +12,7 @@
* admin, member status, bot, SEO (robots/sitemap)
* /v2/devices/* — device state (battery, etc.) (misc)
* /v2/guestbook/* — public guestbook (post/list/delete) (misc)
- * /v2/system-data/* — visitor logging + log viewer (misc)
+ * /v2/counter/* — per-site visit counters (misc)
*
* The single realtime socket /v2/ws is handled by the DO before the request
* ever reaches this app (see do.ts).
@@ -39,7 +39,7 @@ import { botRoutes } from "./routes/bot";
import { staticRoutes } from "./routes/static";
import { deviceRoutes } from "./routes/devices";
import { guestbookRoutes } from "./routes/guestbook";
-import { systemDataRoutes } from "./routes/system_data";
+import { counterRoutes } from "./routes/counter";
// One-time owner seed per DO lifetime (there is no startup phase on a Worker).
let seeded = false;
@@ -76,8 +76,14 @@ export const systemApp = new Hono<Env>();
systemApp.use(
"*",
cors({
- origin: (origin) =>
- isLocalhostOrigin(origin) || corsOrigins().includes(origin) ? origin : "",
+ // /v2/counter is meant to be called from whatever site owns the :siteId,
+ // so it echoes any origin. Everything else stays on the allow-list.
+ origin: (origin, c) =>
+ c.req.path.startsWith("/v2/counter") ||
+ isLocalhostOrigin(origin) ||
+ corsOrigins().includes(origin)
+ ? origin
+ : "",
credentials: true,
allowMethods: ["GET", "POST", "PUT", "PATCH", "DELETE", "OPTIONS"],
}),
@@ -102,6 +108,6 @@ systemApp.onError((err, c) => {
systemApp.route("/v2/plural", pluralApp);
systemApp.route("/v2/devices", deviceRoutes);
systemApp.route("/v2/guestbook", guestbookRoutes);
-systemApp.route("/v2/system-data", systemDataRoutes);
+systemApp.route("/v2/counter", counterRoutes);
systemApp.notFound((c) => c.json({ detail: "Unknown route." }, 404));
diff --git a/src/system/config.ts b/src/system/config.ts
index 3d88bf7..50a1bbe 100644
--- a/src/system/config.ts
+++ b/src/system/config.ts
@@ -131,6 +131,15 @@ export function isLocalhostOrigin(origin: string): boolean {
return /^https?:\/\/(localhost|127\.0\.0\.1|\[::1\])(:\d+)?$/.test(origin);
}
+/** Site ids the visit counter (/v2/counter) will accept. Empty means open:
+ * any well-formed id auto-registers on its first hit, up to MAX_SITES. */
+export function counterSiteIds(): string[] {
+ return (rt().env.COUNTER_SITE_IDS ?? "")
+ .split(",")
+ .map((s) => s.trim().toLowerCase())
+ .filter(Boolean);
+}
+
/** CORS allow-list: built-in defaults plus anything in CORS_ORIGINS.
* Localhost origins are additionally allowed via isLocalhostOrigin(). */
export function corsOrigins(): string[] {
@@ -145,6 +154,8 @@ export function corsOrigins(): string[] {
"https://vibecoded.doughmination.gay",
"http://www.doughmination.gay",
"https://www.doughmination.gay",
+ "http://is.doughmination.gay",
+ "https://is.doughmination.gay",
"https://c.stupid.cat",
"http://c.stupid.cat"
];
diff --git a/src/system/do.ts b/src/system/do.ts
index ed69ffe..2fdc1ae 100644
--- a/src/system/do.ts
+++ b/src/system/do.ts
@@ -9,7 +9,7 @@
*
* - Holds all persistent state (users, tags, statuses, battery, mental
* state) in DO key-value storage via a small Store adapter.
- * - Owns the visitor-log SQLite table (DO embedded SQLite).
+ * - Owns the visit-counter SQLite tables (DO embedded SQLite).
* - Is the SINGLE realtime WebSocket hub for the whole API, at /v2/ws,
* using the hibernatable WebSocket API so idle sockets don't keep the DO
* billed/awake. Every live update — presence, fronting, mental state,
diff --git a/src/system/routes/counter.ts b/src/system/routes/counter.ts
new file mode 100644
index 0000000..1e55689
--- /dev/null
+++ b/src/system/routes/counter.ts
@@ -0,0 +1,119 @@
+/**
+ * Copyright (c) 2026 Clove Twilight
+ * Licensed under the ESAL-2.0 Licence.
+ * See LICENCE.md in the project root for full licence information.
+ */
+
+/**
+ * Site visit counters. Mounted at /v2/counter. Replaces /v2/system-data.
+ *
+ * GET /v2/counter list every site's counts
+ * GET /v2/counter/:siteId read counts (records nothing)
+ * POST /v2/counter/:siteId record a visit → updated counts
+ * GET /v2/counter/:siteId/hit record a visit via a plain GET
+ * GET /v2/counter/:siteId/history?days=30 daily histogram
+ * DELETE /v2/counter/:siteId delete the site (X-Battery-Key)
+ * POST /v2/counter/:siteId/reset zero the counters (X-Battery-Key)
+ *
+ * A repeat visit from the same person inside VISIT_COOLDOWN_MS is answered
+ * with the current counts and `counted: false`, so refreshing doesn't inflate
+ * the number. Nothing identifying is stored — see services/counter.ts.
+ */
+
+import { Hono } from "hono";
+import type { Context } from "hono";
+
+import type { Env } from "../hono";
+import { verifyBatteryAccess } from "../middleware/auth";
+import { counterSiteIds } from "../config";
+import { HttpError } from "../errors";
+import {
+ SITE_ID_RE,
+ SiteRejected,
+ deleteSite,
+ getHistory,
+ getStats,
+ listSites,
+ recordHit,
+ resetSite,
+} from "../services/counter";
+
+export const counterRoutes = new Hono<Env>();
+
+/** Validate a :siteId path param, 422 if malformed. */
+function siteIdOf(raw: string | undefined): string {
+ const siteId = (raw ?? "").toLowerCase();
+ if (!SITE_ID_RE.test(siteId)) {
+ throw new HttpError(
+ 422,
+ "Site id must be 1–64 chars of lowercase letters, digits, dot, dash or underscore, starting with a letter or digit.",
+ );
+ }
+ return siteId;
+}
+
+/** SiteRejected carries the reason a site couldn't be created; map it onto a
+ * status the caller can act on (bad id vs. closed counter). */
+function rejectionStatus(code: SiteRejected["code"]): number {
+ return code === "invalid_site_id" ? 422 : 403;
+}
+
+async function hit(c: Context<Env>) {
+ const siteId = siteIdOf(c.req.param("siteId"));
+ try {
+ const result = await recordHit(siteId, c.req.raw, counterSiteIds());
+ // Never cached: the whole point is that the next reader sees this visit.
+ c.header("Cache-Control", "no-store");
+ return c.json(result);
+ } catch (err) {
+ if (err instanceof SiteRejected) {
+ throw new HttpError(rejectionStatus(err.code), err.message);
+ }
+ throw err;
+ }
+}
+
+// ---- Public read -----------------------------------------------------------
+
+counterRoutes.get("/", (c) => c.json({ sites: listSites() }));
+
+counterRoutes.get("/:siteId", (c) => {
+ const siteId = siteIdOf(c.req.param("siteId"));
+ const stats = getStats(siteId);
+ if (!stats) throw new HttpError(404, `No counter for site '${siteId}'.`);
+ c.header("Cache-Control", "no-store");
+ return c.json(stats);
+});
+
+counterRoutes.get("/:siteId/history", (c) => {
+ const siteId = siteIdOf(c.req.param("siteId"));
+ if (!getStats(siteId)) throw new HttpError(404, `No counter for site '${siteId}'.`);
+ let days = Number(c.req.query("days") ?? 30);
+ if (Number.isNaN(days)) days = 30;
+ days = Math.min(400, Math.max(1, Math.trunc(days)));
+ return c.json({ site_id: siteId, days, history: getHistory(siteId, days) });
+});
+
+// ---- Public write (record a visit) -----------------------------------------
+
+counterRoutes.post("/:siteId", hit);
+
+// The GET twin exists for callers that can't send a POST — a no-JS <img>/beacon
+// or a hand-typed URL. Same effect, so it's deliberately not a bare GET on the
+// site path (which must stay side-effect free for the read above).
+counterRoutes.get("/:siteId/hit", hit);
+
+// ---- Protected admin (X-Battery-Key) ---------------------------------------
+
+counterRoutes.post("/:siteId/reset", verifyBatteryAccess, (c) => {
+ const siteId = siteIdOf(c.req.param("siteId"));
+ const stats = resetSite(siteId);
+ if (!stats) throw new HttpError(404, `No counter for site '${siteId}'.`);
+ return c.json({ ok: true, reset: true, ...stats });
+});
+
+counterRoutes.delete("/:siteId", verifyBatteryAccess, (c) => {
+ const siteId = siteIdOf(c.req.param("siteId"));
+ if (!deleteSite(siteId)) throw new HttpError(404, `No counter for site '${siteId}'.`);
+ return c.json({ ok: true, site_id: siteId, deleted: true });
+});
diff --git a/src/system/routes/system_data.ts b/src/system/routes/system_data.ts
deleted file mode 100644
index bcce66c..0000000
--- a/src/system/routes/system_data.ts
+++ /dev/null
@@ -1,276 +0,0 @@
-/**
- * Copyright (c) 2026 Clove Twilight
- * Licensed under the ESAL-2.0 Licence.
- * See LICENCE.md in the project root for full licence information.
- */
-
-/**
- * Visitor logging + log viewer. Mounted at /v2/system-data.
- * POST/GET /v2/system-data/helper public ingest (frontend pings on nav)
- * GET /v2/system-data/ admin HTML viewer
- * GET /v2/system-data/api/* admin JSON API
- */
-
-import { Hono } from "hono";
-
-import type { Env } from "../hono";
-import { logVisitor, LogQuery } from "../services/visitors";
-import { requireAuth, requireAdmin } from "../middleware/auth";
-import { HttpError } from "../errors";
-
-export const systemDataRoutes = new Hono<Env>();
-
-// ---- Public ingest (must be registered before the admin guard) ------------
-
-systemDataRoutes.post("/helper", async (c) => {
- const body = (await c.req.json().catch(() => ({}))) as { path?: unknown };
- const path = typeof body.path === "string" ? body.path : undefined;
- await logVisitor(c.req.raw, { path });
- return c.json({ ok: true });
-});
-
-systemDataRoutes.get("/helper", async (c) => {
- const path = c.req.query("path");
- await logVisitor(c.req.raw, { path });
- return c.json({ ok: true });
-});
-
-// ---- Everything below requires an authenticated admin ---------------------
-
-systemDataRoutes.use("*", requireAuth, requireAdmin);
-
-systemDataRoutes.get("/api/stats", (c) => {
- try {
- return c.json(LogQuery.stats());
- } catch (err) {
- throw new HttpError(500, `DB error: ${String(err)}`);
- }
-});
-
-systemDataRoutes.get("/api/recent", (c) => {
- let limit = Number(c.req.query("limit") ?? 100);
- if (Number.isNaN(limit)) limit = 100;
- limit = Math.min(1000, Math.max(1, limit));
- return c.json(LogQuery.recent(limit));
-});
-
-systemDataRoutes.get("/api/by-ip/:ip", (c) => c.json(LogQuery.findByIp(c.req.param("ip"))));
-
-systemDataRoutes.get("/api/by-path", (c) => {
- const q = c.req.query("q") ?? "";
- if (!q) throw new HttpError(422, "Query param 'q' is required");
- return c.json(LogQuery.findByPath(q));
-});
-
-systemDataRoutes.get("/api/suspicious", (c) => c.json(LogQuery.findSuspiciousPatterns()));
-
-systemDataRoutes.get("/api/entry/:entry_id", (c) => {
- const entryId = Number(c.req.param("entry_id"));
- if (Number.isNaN(entryId)) throw new HttpError(422, "'entry_id' must be an integer");
- const row = LogQuery.entry(entryId);
- if (!row) throw new HttpError(404, "Entry not found");
- return c.json(row);
-});
-
-systemDataRoutes.get("/healthz", (c) => c.json({ ok: true, db: "durable-object-sqlite" }));
-
-systemDataRoutes.get("/", (c) => c.html(INDEX_HTML));
-
-// ---------------------------------------------------------------------------
-// HTML UI (single page, vanilla JS, no build step). Ported from the old
-// relay page; every fetch() is prefixed with the new mount point.
-// ---------------------------------------------------------------------------
-
-const INDEX_HTML = `<!doctype html>
-<html lang="en">
-<head>
-<meta charset="utf-8" />
-<title>Visitor Log Relay</title>
-<style>
- /* Comic Code + info dark palette, matching every other app. */
- @font-face { font-family: "Comic Code";
- src: url("https://fonts.doughmination.co.uk/ComicCode-Regular_2022-05-24-151938_hsmz.woff2") format("woff2");
- font-weight: 400; font-style: normal; font-display: swap; }
- @font-face { font-family: "Comic Code";
- src: url("https://fonts.doughmination.co.uk/ComicCode-Bold_2022-05-24-152309_zqkm.woff2") format("woff2");
- font-weight: 700; font-style: normal; font-display: swap; }
- :root { color-scheme: dark; }
- body { font: 14px/1.4 "Comic Code", ui-monospace, monospace; margin: 0; padding: 16px;
- background: #0a0b10; color: #f4f6fb; }
- h1 { margin: 0 0 8px; font-size: 18px; }
- .stats { display: flex; gap: 12px; flex-wrap: wrap; margin-bottom: 12px; }
- .stat { background: #12141c; border: 1px solid #232838; border-radius: 8px;
- padding: 8px 12px; min-width: 120px; }
- .stat .n { font-size: 22px; font-weight: 600; }
- .stat .l { font-size: 11px; opacity: 0.7; text-transform: uppercase; letter-spacing: 0.05em; }
- .controls { display: flex; gap: 8px; flex-wrap: wrap; margin-bottom: 12px; align-items: center; }
- input, select, button { font: inherit; padding: 6px 10px; border-radius: 6px;
- border: 1px solid #232838; background: #12141c;
- color: inherit; }
- button { cursor: pointer; }
- button.primary { background: #f5a9b8; border-color: #f5a9b8; color: #0a0b10; }
- table { width: 100%; border-collapse: collapse; background: #0e1017;
- border: 1px solid #232838; border-radius: 8px; overflow: hidden; }
- th, td { padding: 6px 10px; text-align: left; border-bottom: 1px solid #1b1e2a;
- font-size: 13px; vertical-align: top; }
- th { background: #12141c; font-weight: 600; }
- tr:hover { background: #1b1e2a; cursor: pointer; }
- td.ip { font-family: "Comic Code", ui-monospace, monospace; }
- td.path { font-family: "Comic Code", ui-monospace, monospace; max-width: 320px;
- overflow: hidden; text-overflow: ellipsis; white-space: nowrap; }
- .code-2xx { color: #6ee787; }
- .code-3xx { color: #f0c674; }
- .code-4xx, .code-5xx { color: #ff6b6b; }
- .top-paths { display: flex; flex-wrap: wrap; gap: 4px; margin-top: 6px; }
- .top-paths span { background: #12141c; border: 1px solid #232838;
- border-radius: 4px; padding: 2px 6px; font-size: 12px;
- font-family: "Comic Code", ui-monospace, monospace; }
- details { margin-top: 12px; }
- pre { background: #12141c; border: 1px solid #232838; padding: 8px;
- border-radius: 6px; overflow: auto; max-height: 60vh; font-size: 12px; }
- .hint { opacity: 0.6; font-size: 12px; margin-left: auto; }
- .empty { opacity: 0.6; text-align: center; padding: 32px; }
-</style>
-</head>
-<body>
- <h1>Visitor Log Relay</h1>
-
- <div class="stats" id="stats"></div>
-
- <div class="controls">
- <select id="mode">
- <option value="recent">Recent</option>
- <option value="ip">By IP</option>
- <option value="path">By path</option>
- <option value="suspicious">Suspicious patterns</option>
- </select>
- <input id="filter" placeholder="filter value" style="min-width: 220px;" />
- <input id="limit" type="number" value="100" min="1" max="1000" style="width: 80px;" />
- <button class="primary" id="go">Load</button>
- <span class="hint">click any row for full details</span>
- </div>
-
- <div id="results"></div>
-
- <details>
- <summary>Selected entry</summary>
- <pre id="detail">(click a row)</pre>
- </details>
-
-<script>
-const BASE = '/v2/system-data';
-const $ = (id) => document.getElementById(id);
-
-async function loadStats() {
- try {
- const s = await fetch(BASE + '/api/stats').then(r => r.json());
- const top = (s.top_paths || []).map(p =>
- \`<span title="\${p.count} visits">\${escapeHtml(p.path || '(none)')} · \${p.count}</span>\`
- ).join('');
- $('stats').innerHTML = \`
- <div class="stat"><div class="n">\${s.total_visits}</div><div class="l">total</div></div>
- <div class="stat"><div class="n">\${s.unique_ips}</div><div class="l">unique IPs</div></div>
- <div class="stat"><div class="n">\${s.last_24h}</div><div class="l">last 24h</div></div>
- <div class="stat" style="flex:1; min-width: 280px;">
- <div class="l">top paths</div>
- <div class="top-paths">\${top || '<span>(none)</span>'}</div>
- </div>\`;
- } catch (e) {
- $('stats').innerHTML = \`<div class="stat"><div class="l">stats unavailable</div></div>\`;
- }
-}
-
-function escapeHtml(s) {
- return String(s ?? '').replace(/[&<>"']/g, c =>
- ({'&':'&','<':'<','>':'>','"':'"',"'":'''}[c]));
-}
-
-function codeClass(code) {
- if (!code) return '';
- if (code < 300) return 'code-2xx';
- if (code < 400) return 'code-3xx';
- if (code < 500) return 'code-4xx';
- return 'code-5xx';
-}
-
-function renderRows(rows) {
- if (!rows || !rows.length) {
- $('results').innerHTML = '<div class="empty">no results</div>';
- return;
- }
- const head = \`<tr>
- <th>id</th><th>time</th><th>ip</th><th>method</th>
- <th>path</th><th>code</th><th>user agent</th></tr>\`;
- const body = rows.map(r => \`
- <tr data-id="\${r.id}">
- <td>\${r.id}</td>
- <td>\${escapeHtml(r.timestamp || '')}</td>
- <td class="ip">\${escapeHtml(r.ip_address || '')}</td>
- <td>\${escapeHtml(r.method || '')}</td>
- <td class="path" title="\${escapeHtml(r.path || '')}">\${escapeHtml(r.path || '')}</td>
- <td class="\${codeClass(r.response_code)}">\${escapeHtml(r.response_code ?? '')}</td>
- <td class="path" title="\${escapeHtml(r.user_agent || '')}">\${escapeHtml(r.user_agent || '')}</td>
- </tr>\`).join('');
- $('results').innerHTML = \`<table><thead>\${head}</thead><tbody>\${body}</tbody></table>\`;
- $('results').querySelectorAll('tr[data-id]').forEach(tr => {
- tr.addEventListener('click', () => loadDetail(tr.dataset.id));
- });
-}
-
-function renderSuspicious(rows) {
- if (!rows || !rows.length) {
- $('results').innerHTML = '<div class="empty">no suspicious activity in the last hour</div>';
- return;
- }
- const head = \`<tr><th>ip</th><th>visits</th><th>first</th><th>last</th></tr>\`;
- const body = rows.map(r => \`
- <tr><td class="ip">\${escapeHtml(r.ip_address)}</td>
- <td>\${r.visit_count}</td>
- <td>\${escapeHtml(r.first_visit)}</td>
- <td>\${escapeHtml(r.last_visit)}</td></tr>\`).join('');
- $('results').innerHTML = \`<table><thead>\${head}</thead><tbody>\${body}</tbody></table>\`;
-}
-
-async function loadDetail(id) {
- try {
- const e = await fetch(\`\${BASE}/api/entry/\${id}\`).then(r => r.json());
- $('detail').textContent = JSON.stringify(e, null, 2);
- } catch (err) {
- $('detail').textContent = String(err);
- }
-}
-
-async function go() {
- const mode = $('mode').value;
- const filter = $('filter').value.trim();
- const limit = parseInt($('limit').value || '100', 10);
- let url;
- if (mode === 'recent') url = \`\${BASE}/api/recent?limit=\${limit}\`;
- else if (mode === 'ip') url = \`\${BASE}/api/by-ip/\${encodeURIComponent(filter)}\`;
- else if (mode === 'path') url = \`\${BASE}/api/by-path?q=\${encodeURIComponent(filter)}\`;
- else if (mode === 'suspicious') url = \`\${BASE}/api/suspicious\`;
-
- $('results').innerHTML = '<div class="empty">loading...</div>';
- try {
- const rows = await fetch(url).then(r => r.json());
- if (mode === 'suspicious') renderSuspicious(rows);
- else renderRows(rows);
- } catch (e) {
- $('results').innerHTML = \`<div class="empty">error: \${escapeHtml(e.message)}</div>\`;
- }
-}
-
-$('go').addEventListener('click', go);
-$('filter').addEventListener('keydown', e => { if (e.key === 'Enter') go(); });
-$('mode').addEventListener('change', () => {
- const needsFilter = ['ip', 'path'].includes($('mode').value);
- $('filter').style.display = needsFilter ? '' : 'none';
-});
-$('mode').dispatchEvent(new Event('change'));
-
-loadStats();
-go();
-</script>
-</body>
-</html>
-`;
diff --git a/src/system/runtime.ts b/src/system/runtime.ts
index b8f3bee..cdb4e82 100644
--- a/src/system/runtime.ts
+++ b/src/system/runtime.ts
@@ -28,7 +28,7 @@ export interface Store {
export interface SysRuntime {
env: SystemEnv;
store: Store;
- /** DO SQLite handle, used by the visitor logger. */
+ /** DO SQLite handle, used by the site visit counters. */
sql: SqlStorage;
/** Broadcast a JSON-serialisable payload to every connected /ws client. */
broadcast(data: unknown): void;
diff --git a/src/system/services/counter.ts b/src/system/services/counter.ts
new file mode 100644
index 0000000..3ce198d
--- /dev/null
+++ b/src/system/services/counter.ts
@@ -0,0 +1,352 @@
+/**
+ * Copyright (c) 2026 Clove Twilight
+ * Licensed under the ESAL-2.0 Licence.
+ * See LICENCE.md in the project root for full licence information.
+ */
+
+/**
+ * Per-site visit counters, backed by the SystemState DO's embedded SQLite
+ * (`rt().sql`). Replaces the old visitor-log system, which stored full
+ * request headers, cookies and raw IPs for every hit.
+ *
+ * The counter deliberately stores NO personal data. A visitor is identified
+ * only by a SHA-256 of `siteId | per-site random salt | ip | user-agent`.
+ * The salt is generated when the site row is created and never leaves the
+ * DO, so the hashes can't be reversed into IPs or correlated across sites.
+ *
+ * Three tables:
+ * counter_sites one row per site: running total + its salt
+ * counter_visitors one row per (site, visitor hash): all-time unique set
+ * counter_days one row per (site, UTC day): the daily histogram
+ */
+
+import { rt } from "../runtime";
+
+function db(): SqlStorage {
+ return rt().sql;
+}
+
+/** A site id is a short, lowercase, DNS-ish slug — e.g. "is.doughmination.gay". */
+export const SITE_ID_RE = /^[a-z0-9][a-z0-9._-]{0,63}$/;
+
+/**
+ * A repeat hit from the same visitor within this window does not move the
+ * total. Without it a held-down F5 inflates the count without limit; with it
+ * the number means "visits" rather than "page loads".
+ */
+export const VISIT_COOLDOWN_MS = 30 * 60 * 1000; // 30 minutes
+
+/** Safety valve on auto-created sites, so an open endpoint can't be used to
+ * fill the DO with junk site rows. Ignored when COUNTER_SITE_IDS is set. */
+export const MAX_SITES = 100;
+
+/** Daily rows older than this are pruned when a new day is first recorded. */
+const DAY_RETENTION = 400;
+
+export interface CounterStats {
+ site_id: string;
+ /** Visits, all time (repeat hits inside the cooldown don't count). */
+ total: number;
+ /** Distinct visitors, all time. */
+ unique: number;
+ /** Visits so far during the current UTC day. */
+ today: number;
+ /** Epoch ms the site row was created. */
+ created_at: number;
+ /** Epoch ms of the most recent counted visit. */
+ updated_at: number;
+}
+
+export interface HitResult extends CounterStats {
+ /** False when the cooldown swallowed this hit, so the caller can tell the
+ * difference between "you were counted" and "you already were". */
+ counted: boolean;
+ /** True when this visitor had never been seen on this site before. */
+ first_visit: boolean;
+}
+
+let initialised = false;
+
+export function initCounterSchema(): void {
+ if (initialised) return;
+ const sql = db();
+
+ // The visitor-log table this system replaces. Dropped on first touch so the
+ // old per-request header/cookie/IP rows don't linger in DO storage.
+ sql.exec("DROP TABLE IF EXISTS visitor_logs");
+
+ sql.exec(`
+ CREATE TABLE IF NOT EXISTS counter_sites (
+ site_id TEXT PRIMARY KEY,
+ salt TEXT NOT NULL,
+ total INTEGER NOT NULL DEFAULT 0,
+ created_at INTEGER NOT NULL,
+ updated_at INTEGER NOT NULL
+ )
+ `);
+ sql.exec(`
+ CREATE TABLE IF NOT EXISTS counter_visitors (
+ site_id TEXT NOT NULL,
+ visitor_hash TEXT NOT NULL,
+ first_seen INTEGER NOT NULL,
+ last_seen INTEGER NOT NULL,
+ hits INTEGER NOT NULL DEFAULT 0,
+ PRIMARY KEY (site_id, visitor_hash)
+ )
+ `);
+ sql.exec(`
+ CREATE TABLE IF NOT EXISTS counter_days (
+ site_id TEXT NOT NULL,
+ day TEXT NOT NULL,
+ hits INTEGER NOT NULL DEFAULT 0,
+ PRIMARY KEY (site_id, day)
+ )
+ `);
+
+ initialised = true;
+}
+
+// ---- helpers ---------------------------------------------------------------
+
+/** Current UTC day as YYYY-MM-DD. Days are UTC so the histogram doesn't shift
+ * with the caller's timezone. */
+function utcDay(at: number): string {
+ return new Date(at).toISOString().slice(0, 10);
+}
+
+function clientIp(req: Request): string {
+ for (const header of ["cf-connecting-ip", "true-client-ip", "x-real-ip"]) {
+ const v = req.headers.get(header);
+ if (v) return v;
+ }
+ return req.headers.get("x-forwarded-for")?.split(",")[0].trim() ?? "";
+}
+
+/** Opaque, non-reversible visitor id. See the file header for why. */
+async function visitorHash(siteId: string, salt: string, req: Request): Promise<string> {
+ const material = `${siteId}|${salt}|${clientIp(req)}|${req.headers.get("user-agent") ?? ""}`;
+ const digest = await crypto.subtle.digest("SHA-256", new TextEncoder().encode(material));
+ return [...new Uint8Array(digest)].map((b) => b.toString(16).padStart(2, "0")).join("");
+}
+
+interface SiteRow {
+ site_id: string;
+ salt: string;
+ total: number;
+ created_at: number;
+ updated_at: number;
+}
+
+function readSite(siteId: string): SiteRow | null {
+ const rows = db()
+ .exec("SELECT site_id, salt, total, created_at, updated_at FROM counter_sites WHERE site_id = ?", siteId)
+ .toArray() as unknown as SiteRow[];
+ return rows[0] ?? null;
+}
+
+function countSites(): number {
+ return (db().exec("SELECT COUNT(*) AS n FROM counter_sites").one() as { n: number }).n;
+}
+
+function uniqueVisitors(siteId: string): number {
+ return (
+ db().exec("SELECT COUNT(*) AS n FROM counter_visitors WHERE site_id = ?", siteId).one() as {
+ n: number;
+ }
+ ).n;
+}
+
+function dayHits(siteId: string, day: string): number {
+ const rows = db()
+ .exec("SELECT hits FROM counter_days WHERE site_id = ? AND day = ?", siteId, day)
+ .toArray() as unknown as { hits: number }[];
+ return rows[0]?.hits ?? 0;
+}
+
+function toStats(site: SiteRow, at: number): CounterStats {
+ return {
+ site_id: site.site_id,
+ total: site.total,
+ unique: uniqueVisitors(site.site_id),
+ today: dayHits(site.site_id, utcDay(at)),
+ created_at: site.created_at,
+ updated_at: site.updated_at,
+ };
+}
+
+// ---- public API ------------------------------------------------------------
+
+/** Read a site's counts without recording anything. Null if it doesn't exist. */
+export function getStats(siteId: string): CounterStats | null {
+ initCounterSchema();
+ const site = readSite(siteId);
+ return site ? toStats(site, Date.now()) : null;
+}
+
+/** Every site with a counter, busiest first. */
+export function listSites(): CounterStats[] {
+ initCounterSchema();
+ const now = Date.now();
+ const sites = db()
+ .exec(
+ "SELECT site_id, salt, total, created_at, updated_at FROM counter_sites ORDER BY total DESC, site_id ASC",
+ )
+ .toArray() as unknown as SiteRow[];
+ return sites.map((s) => toStats(s, now));
+}
+
+/** Thrown when a site can't be created — bad id, not on the allow-list, or the
+ * auto-create cap is already reached. */
+export class SiteRejected extends Error {
+ constructor(
+ public readonly code: "invalid_site_id" | "not_allowed" | "too_many_sites",
+ message: string,
+ ) {
+ super(message);
+ this.name = "SiteRejected";
+ }
+}
+
+/**
+ * Record a visit and return the updated counts.
+ *
+ * `allowList` is the configured COUNTER_SITE_IDS; when it's empty any
+ * well-formed id auto-creates a site (up to MAX_SITES), and when it's set
+ * only those ids are accepted.
+ */
+export async function recordHit(
+ siteId: string,
+ req: Request,
+ allowList: string[],
+): Promise<HitResult> {
+ initCounterSchema();
+
+ if (!SITE_ID_RE.test(siteId)) {
+ throw new SiteRejected(
+ "invalid_site_id",
+ "Site id must be 1–64 chars of lowercase letters, digits, dot, dash or underscore, starting with a letter or digit.",
+ );
+ }
+
+ const sql = db();
+ const now = Date.now();
+ const day = utcDay(now);
+ let site = readSite(siteId);
+
+ if (!site) {
+ if (allowList.length && !allowList.includes(siteId)) {
+ throw new SiteRejected("not_allowed", `Site '${siteId}' is not registered on this counter.`);
+ }
+ if (!allowList.length && countSites() >= MAX_SITES) {
+ throw new SiteRejected("too_many_sites", "This counter is not accepting new sites.");
+ }
+ sql.exec(
+ "INSERT INTO counter_sites (site_id, salt, total, created_at, updated_at) VALUES (?,?,0,?,?)",
+ siteId,
+ crypto.randomUUID(),
+ now,
+ now,
+ );
+ site = readSite(siteId)!;
+ }
+
+ const hash = await visitorHash(siteId, site.salt, req);
+ const seen = sql
+ .exec(
+ "SELECT first_seen, last_seen, hits FROM counter_visitors WHERE site_id = ? AND visitor_hash = ?",
+ siteId,
+ hash,
+ )
+ .toArray() as unknown as { first_seen: number; last_seen: number; hits: number }[];
+ const previous = seen[0] ?? null;
+
+ const firstVisit = previous === null;
+ const counted = firstVisit || now - previous.last_seen >= VISIT_COOLDOWN_MS;
+
+ if (!counted) {
+ // Still refresh last_seen so a continuous session keeps extending the
+ // cooldown rather than tipping over mid-browse.
+ sql.exec(
+ "UPDATE counter_visitors SET last_seen = ? WHERE site_id = ? AND visitor_hash = ?",
+ now,
+ siteId,
+ hash,
+ );
+ return { ...toStats(site, now), counted: false, first_visit: false };
+ }
+
+ if (firstVisit) {
+ sql.exec(
+ "INSERT INTO counter_visitors (site_id, visitor_hash, first_seen, last_seen, hits) VALUES (?,?,?,?,1)",
+ siteId,
+ hash,
+ now,
+ now,
+ );
+ } else {
+ sql.exec(
+ "UPDATE counter_visitors SET last_seen = ?, hits = hits + 1 WHERE site_id = ? AND visitor_hash = ?",
+ now,
+ siteId,
+ hash,
+ );
+ }
+
+ sql.exec(
+ "UPDATE counter_sites SET total = total + 1, updated_at = ? WHERE site_id = ?",
+ now,
+ siteId,
+ );
+
+ const dayExisted = dayHits(siteId, day) > 0;
+ sql.exec(
+ `INSERT INTO counter_days (site_id, day, hits) VALUES (?,?,1)
+ ON CONFLICT (site_id, day) DO UPDATE SET hits = hits + 1`,
+ siteId,
+ day,
+ );
+ if (!dayExisted) pruneDays(siteId, now);
+
+ return { ...toStats(readSite(siteId)!, now), counted: true, first_visit: firstVisit };
+}
+
+/** Drop daily rows past the retention window. Called once per new day, so the
+ * histogram stays bounded without doing work on every hit. */
+function pruneDays(siteId: string, at: number): void {
+ const cutoff = utcDay(at - DAY_RETENTION * 86_400_000);
+ db().exec("DELETE FROM counter_days WHERE site_id = ? AND day < ?", siteId, cutoff);
+}
+
+/** The daily histogram, oldest first — `days` back from today (UTC). */
+export function getHistory(siteId: string, days: number): { day: string; hits: number }[] {
+ initCounterSchema();
+ const from = utcDay(Date.now() - (days - 1) * 86_400_000);
+ return db()
+ .exec(
+ "SELECT day, hits FROM counter_days WHERE site_id = ? AND day >= ? ORDER BY day ASC",
+ siteId,
+ from,
+ )
+ .toArray() as unknown as { day: string; hits: number }[];
+}
+
+/** Delete a site and everything recorded for it. True if it existed. */
+export function deleteSite(siteId: string): boolean {
+ initCounterSchema();
+ if (!readSite(siteId)) return false;
+ db().exec("DELETE FROM counter_visitors WHERE site_id = ?", siteId);
+ db().exec("DELETE FROM counter_days WHERE site_id = ?", siteId);
+ db().exec("DELETE FROM counter_sites WHERE site_id = ?", siteId);
+ return true;
+}
+
+/** Zero a site's counters, keeping the row (and its salt) in place. */
+export function resetSite(siteId: string): CounterStats | null {
+ initCounterSchema();
+ if (!readSite(siteId)) return null;
+ const now = Date.now();
+ db().exec("DELETE FROM counter_visitors WHERE site_id = ?", siteId);
+ db().exec("DELETE FROM counter_days WHERE site_id = ?", siteId);
+ db().exec("UPDATE counter_sites SET total = 0, updated_at = ? WHERE site_id = ?", now, siteId);
+ return toStats(readSite(siteId)!, now);
+}
diff --git a/src/system/services/visitors.ts b/src/system/services/visitors.ts
deleted file mode 100644
index 7340fd1..0000000
--- a/src/system/services/visitors.ts
+++ /dev/null
@@ -1,219 +0,0 @@
-/**
- * Copyright (c) 2026 Clove Twilight
- * Licensed under the ESAL-2.0 Licence.
- * See LICENCE.md in the project root for full licence information.
- */
-
-/**
- * Visitor logging, backed by the SystemState DO's embedded SQLite
- * (`rt().sql`) instead of bun:sqlite + a JSONL file. Same schema and the
- * same query helpers the /v2/system-data viewer relies on.
- */
-
-import { rt } from "../runtime";
-import type { PKObject } from "../types";
-
-let initialised = false;
-
-function db(): SqlStorage {
- return rt().sql;
-}
-
-export function initVisitorSchema(): void {
- if (initialised) return;
- const sql = db();
- sql.exec(`
- CREATE TABLE IF NOT EXISTS visitor_logs (
- id INTEGER PRIMARY KEY AUTOINCREMENT,
- timestamp TEXT NOT NULL,
- unix_timestamp REAL NOT NULL,
- ip_address TEXT NOT NULL,
- user_agent TEXT,
- referer TEXT,
- method TEXT,
- path TEXT,
- query_string TEXT,
- remote_addr TEXT,
- x_forwarded_for TEXT,
- x_real_ip TEXT,
- accept_language TEXT,
- accept_encoding TEXT,
- host TEXT,
- all_headers TEXT,
- cookies TEXT,
- body_size INTEGER,
- response_code INTEGER,
- request_time_ms REAL,
- browser_fingerprint TEXT,
- country TEXT,
- asn TEXT
- )
- `);
- sql.exec("CREATE INDEX IF NOT EXISTS idx_timestamp ON visitor_logs(timestamp)");
- sql.exec("CREATE INDEX IF NOT EXISTS idx_ip ON visitor_logs(ip_address)");
- sql.exec("CREATE INDEX IF NOT EXISTS idx_path ON visitor_logs(path)");
- initialised = true;
-}
-
-function headerObject(req: Request): Record<string, string> {
- const out: Record<string, string> = {};
- req.headers.forEach((v, k) => {
- out[k] = v;
- });
- return out;
-}
-
-function getClientIp(req: Request): string {
- const xff = req.headers.get("x-forwarded-for");
- if (xff) return xff.split(",")[0].trim();
- for (const header of ["cf-connecting-ip", "x-real-ip", "true-client-ip"]) {
- const v = req.headers.get(header);
- if (v) return v;
- }
- return "";
-}
-
-async function browserFingerprint(req: Request): Promise<string> {
- const ua = req.headers.get("user-agent") ?? "";
- const lang = req.headers.get("accept-language") ?? "";
- const encoding = req.headers.get("accept-encoding") ?? "";
- const data = new TextEncoder().encode(`${ua}|${lang}|${encoding}`);
- const digest = await crypto.subtle.digest("SHA-256", data);
- return [...new Uint8Array(digest)].map((b) => b.toString(16).padStart(2, "0")).join("");
-}
-
-function parseCookies(header: string | null): Record<string, string> {
- const out: Record<string, string> = {};
- if (!header) return out;
- for (const part of header.split(";")) {
- const idx = part.indexOf("=");
- if (idx === -1) continue;
- out[part.slice(0, idx).trim()] = decodeURIComponent(part.slice(idx + 1).trim());
- }
- return out;
-}
-
-/** Record a page visit. `path` overrides the request path (frontend supplies it). */
-export async function logVisitor(
- req: Request,
- options: { path?: string; bodySize?: number; responseCode?: number; requestTimeMs?: number } = {},
-): Promise<void> {
- initVisitorSchema();
-
- const url = new URL(req.url);
- const now = new Date();
- const headers = headerObject(req);
-
- db().exec(
- `INSERT INTO visitor_logs (
- timestamp, unix_timestamp, ip_address, user_agent, referer,
- method, path, query_string, remote_addr, x_forwarded_for,
- x_real_ip, accept_language, accept_encoding, host,
- all_headers, cookies, body_size, response_code,
- request_time_ms, browser_fingerprint, country, asn
- ) VALUES (?,?,?,?,?,?,?,?,?,?,?,?,?,?,?,?,?,?,?,?,?,?)`,
- now.toISOString(),
- now.getTime() / 1000,
- getClientIp(req),
- headers["user-agent"] ?? "",
- headers["referer"] ?? "",
- req.method,
- options.path || url.pathname,
- url.search ? url.search.slice(1) : "",
- "",
- headers["x-forwarded-for"] ?? "",
- headers["x-real-ip"] ?? "",
- headers["accept-language"] ?? "",
- headers["accept-encoding"] ?? "",
- headers["host"] ?? "",
- JSON.stringify(headers),
- JSON.stringify(parseCookies(req.headers.get("cookie"))),
- options.bodySize ?? 0,
- options.responseCode ?? 200,
- options.requestTimeMs ?? 0,
- await browserFingerprint(req),
- headers["cf-ipcountry"] ?? "Unknown",
- "Unknown",
- );
-}
-
-// ---- Query helpers (used by the /v2/system-data viewer) -------------------
-
-function rows(cursor: SqlStorageCursor<Record<string, SqlStorageValue>>): PKObject[] {
- return cursor.toArray() as PKObject[];
-}
-
-export const LogQuery = {
- stats(): PKObject {
- const sql = db();
- const total = (sql.exec("SELECT COUNT(*) AS n FROM visitor_logs").one() as { n: number }).n;
- const uniqueIps = (
- sql.exec("SELECT COUNT(DISTINCT ip_address) AS n FROM visitor_logs").one() as { n: number }
- ).n;
- const last24h = (
- sql
- .exec(
- "SELECT COUNT(*) AS n FROM visitor_logs WHERE unix_timestamp > strftime('%s','now') - 86400",
- )
- .one() as { n: number }
- ).n;
- const topPaths = rows(
- sql.exec(
- "SELECT path, COUNT(*) c FROM visitor_logs GROUP BY path ORDER BY c DESC LIMIT 10",
- ),
- );
- return {
- total_visits: total,
- unique_ips: uniqueIps,
- last_24h: last24h,
- top_paths: topPaths.map((r) => ({ path: r.path, count: r.c })),
- };
- },
-
- recent(limit: number): PKObject[] {
- return rows(
- db().exec(
- `SELECT id, timestamp, ip_address, method, path, response_code, user_agent, referer
- FROM visitor_logs ORDER BY unix_timestamp DESC LIMIT ?`,
- limit,
- ),
- );
- },
-
- findByIp(ipAddress: string): PKObject[] {
- return rows(
- db().exec(
- "SELECT * FROM visitor_logs WHERE ip_address = ? ORDER BY timestamp DESC",
- ipAddress,
- ),
- );
- },
-
- findByPath(path: string): PKObject[] {
- return rows(
- db().exec(
- "SELECT * FROM visitor_logs WHERE path LIKE ? ORDER BY timestamp DESC",
- `%${path}%`,
- ),
- );
- },
-
- findSuspiciousPatterns(): PKObject[] {
- return rows(
- db().exec(`
- SELECT ip_address, COUNT(*) as visit_count,
- MIN(timestamp) as first_visit, MAX(timestamp) as last_visit
- FROM visitor_logs
- WHERE unix_timestamp > (unixepoch('now') - 3600)
- GROUP BY ip_address
- HAVING COUNT(*) > 20
- ORDER BY visit_count DESC
- `),
- );
- },
-
- entry(entryId: number): PKObject | null {
- const result = rows(db().exec("SELECT * FROM visitor_logs WHERE id = ?", entryId));
- return result[0] ?? null;
- },
-};
diff --git a/src/system/types.ts b/src/system/types.ts
index 31d7066..9703278 100644
--- a/src/system/types.ts
+++ b/src/system/types.ts
@@ -72,6 +72,9 @@ export interface SystemEnv {
FRONTEND_URL?: string;
/** Comma-separated extra CORS origins (added to the built-in defaults). */
CORS_ORIGINS?: string;
+ /** Comma-separated site ids the /v2/counter endpoints will accept. Empty
+ * leaves the counter open, so any well-formed id registers on first hit. */
+ COUNTER_SITE_IDS?: string;
}
/** A member object from PluralKit is large and loosely typed upstream. */
diff --git a/wrangler.jsonc b/wrangler.jsonc
index 37a1bf7..72978d4 100644
--- a/wrangler.jsonc
+++ b/wrangler.jsonc
@@ -83,6 +83,11 @@
"BASE_URL": "https://doughmination.uk",
"CORS_ORIGINS": "",
+ // Site ids /v2/counter will accept. Empty leaves the counter open, so
+ // any well-formed id registers itself on its first hit (capped at
+ // MAX_SITES). Set it to lock the counter to a known list of sites.
+ "COUNTER_SITE_IDS": "is.doughmination.gay",
+
// The frontend lives on doughmination.co.uk; this API is
// doughmination.uk — so this must NOT inherit BASE_URL.
"FRONTEND_URL": "https://doughmination.co.uk",