Skip to content

Open-source platform for 3D AI agents. Turn text or a photo into a rigged, animated GLB avatar, give it an LLM brain, memory and a wallet, and embed it anywhere with one web component. Remote MCP server, x402 payments, Three.js, browser-native.

feat(irl): add site-wide usage analytics

nirholasaf841d70faf8
diff --git a/api/_lib/irl-analytics.js b/api/_lib/irl-analytics.js
new file mode 100644
index 000000000..3a59ca182
--- /dev/null
+++ b/api/_lib/irl-analytics.js
@@ -0,0 +1,208 @@
+// api/_lib/irl-analytics.js
+//
+// Site-wide /irl usage analytics — the one thing the feature never had. Every
+// other IRL surface (pins, interactions, drops, world lines) tracks state
+// per-pin or per-owner; nothing rolled it up into "how many people actually
+// use this feature, and through which door." This module is that rollup.
+//
+// Design constraints, both driven by the existing IRL privacy posture
+// (see docs/irl/THREAT-MODEL.md, the H4/H5/H6 notes in api/irl/pins.js and
+// api/irl/interactions.js):
+// - Never store a raw device token or exact coordinate. Events carry a
+// 16-hex-char sha256 prefix of the device token (irreversible, matches
+// the `ipHash` pattern already used for sweep detection in pins.js) and,
+// when a location is available, only the ~150m geocell7 the rest of the
+// codebase already treats as the public-safe location granularity.
+// - Bounded retention. `irl_events` is swept by the existing IRL reaper
+// cron (api/cron/irl-reap.js) the same way interaction rows are, so a
+// coarse usage trail doesn't accumulate forever either.
+// - Logging must never be able to break the request it's attached to.
+// logIrlEvent() swallows and logs every failure internally.
+//
+// Follows the same self-provisioning-schema convention as the rest of
+// api/irl/* (CREATE TABLE IF NOT EXISTS inline, cached per warm container —
+// see ensureTable() in api/irl/pins.js) rather than the api/_lib/migrations
+// pipeline, which IRL tables don't participate in.
+
+import { sql } from './db.js';
+import { sha256 } from './crypto.js';
+import { encodeGeohash } from './geohash.js';
+
+const GEOCELL_PRECISION = 7; // matches api/irl/pins.js's density-cell precision
+
+let schemaReady = false;
+
+export async function ensureIrlAnalyticsSchema() {
+ if (schemaReady) return;
+ await sql`
+ CREATE TABLE IF NOT EXISTS irl_events (
+ id BIGSERIAL PRIMARY KEY,
+ event_type TEXT NOT NULL,
+ pin_id UUID,
+ geocell7 TEXT,
+ device_hash TEXT,
+ metadata JSONB,
+ created_at TIMESTAMPTZ NOT NULL DEFAULT NOW()
+ )
+ `;
+ await sql`CREATE INDEX IF NOT EXISTS irl_events_type_created ON irl_events (event_type, created_at DESC)`;
+ await sql`CREATE INDEX IF NOT EXISTS irl_events_created ON irl_events (created_at)`;
+
+ await sql`
+ CREATE TABLE IF NOT EXISTS irl_pin_shares (
+ id UUID DEFAULT gen_random_uuid() PRIMARY KEY,
+ pin_id UUID NOT NULL REFERENCES irl_pins(id) ON DELETE CASCADE,
+ token TEXT NOT NULL UNIQUE,
+ image_key TEXT NOT NULL,
+ image_url TEXT NOT NULL,
+ device_hash TEXT,
+ view_count BIGINT NOT NULL DEFAULT 0,
+ created_at TIMESTAMPTZ NOT NULL DEFAULT NOW()
+ )
+ `;
+ await sql`CREATE INDEX IF NOT EXISTS irl_pin_shares_pin ON irl_pin_shares (pin_id)`;
+
+ schemaReady = true;
+}
+
+/** sha256(token).slice(0,16) — same opaque-prefix convention as pins.js's ipHash. Never stores the raw token. */
+export async function hashDeviceToken(token) {
+ if (!token || typeof token !== 'string') return null;
+ return (await sha256(token)).slice(0, 16);
+}
+
+// event_type vocabulary — keep this list authoritative so a typo'd type never
+// silently fragments the rollup below.
+export const IRL_EVENT_TYPES = new Set([
+ 'pin_created', // a placement landed (AR method carried in metadata.mode: webxr | quicklook | pin | map)
+ 'nearby_fetch', // a browse/discovery read of the nearby feed (metadata.count = pins returned)
+ 'share_created', // a shareable card was minted for a pin
+ 'share_viewed', // a minted share link was opened
+]);
+
+/**
+ * Fire-and-forget event log. Never throws — a caller on the hot path (placing
+ * a pin, reading nearby) must never fail or slow down because analytics did.
+ *
+ * @param {object} opts
+ * @param {string} opts.type IRL_EVENT_TYPES member
+ * @param {string} [opts.pinId]
+ * @param {number} [opts.lat] @param {number} [opts.lng] — coarsened to geocell7 before storage, never kept raw
+ * @param {string} [opts.deviceToken] — hashed before storage, never kept raw
+ * @param {object} [opts.metadata]
+ */
+export async function logIrlEvent({ type, pinId, lat, lng, deviceToken, metadata } = {}) {
+ if (!IRL_EVENT_TYPES.has(type)) return;
+ try {
+ await ensureIrlAnalyticsSchema();
+ const geocell7 = Number.isFinite(lat) && Number.isFinite(lng) ? encodeGeohash(lat, lng, GEOCELL_PRECISION) : null;
+ const deviceHash = await hashDeviceToken(deviceToken);
+ await sql`
+ INSERT INTO irl_events (event_type, pin_id, geocell7, device_hash, metadata)
+ VALUES (${type}, ${pinId || null}, ${geocell7}, ${deviceHash}, ${metadata ? JSON.stringify(metadata) : null}::jsonb)
+ `;
+ } catch (err) {
+ console.error('[irl-analytics] logIrlEvent failed (non-fatal)', { type, reason: err?.message || String(err) });
+ }
+}
+
+/** Record a share-link open, best-effort, and bump the share row's view_count. */
+export async function recordShareView(token) {
+ try {
+ await ensureIrlAnalyticsSchema();
+ const rows = await sql`
+ UPDATE irl_pin_shares SET view_count = view_count + 1
+ WHERE token = ${token}
+ RETURNING pin_id
+ `;
+ if (rows[0]) {
+ await logIrlEvent({ type: 'share_viewed', pinId: rows[0].pin_id, metadata: { token } });
+ }
+ return rows[0] || null;
+ } catch (err) {
+ console.error('[irl-analytics] recordShareView failed (non-fatal)', { reason: err?.message || String(err) });
+ return null;
+ }
+}
+
+const WINDOWS = { '24h': '24 hours', '7d': '7 days', '30d': '30 days' };
+
+/**
+ * Owner-facing rollup — GET /api/irl/analytics. Every number here is a real
+ * aggregate query, no cached/sampled/fake figures.
+ */
+export async function getIrlAnalyticsSummary() {
+ await ensureIrlAnalyticsSchema();
+
+ const windows = {};
+ for (const [key, interval] of Object.entries(WINDOWS)) {
+ const [placed] = await sql`
+ SELECT count(*)::int AS n, count(DISTINCT device_hash)::int AS unique_devices
+ FROM irl_events WHERE event_type = 'pin_created' AND created_at > now() - ${interval}::interval
+ `;
+ const [nearby] = await sql`
+ SELECT count(*)::int AS n, count(DISTINCT device_hash)::int AS unique_devices
+ FROM irl_events WHERE event_type = 'nearby_fetch' AND created_at > now() - ${interval}::interval
+ `;
+ const interactionRows = await sql`
+ SELECT type, count(*)::int AS n FROM irl_interactions
+ WHERE created_at > now() - ${interval}::interval GROUP BY type
+ `;
+ const [shares] = await sql`
+ SELECT count(*)::int AS created, coalesce(sum(view_count), 0)::int AS views
+ FROM irl_pin_shares WHERE created_at > now() - ${interval}::interval
+ `;
+ const [drops] = await sql`
+ SELECT count(*)::int AS n FROM irl_drop_claims
+ WHERE status = 'confirmed' AND confirmed_at > now() - ${interval}::interval
+ `;
+
+ windows[key] = {
+ pins_placed: placed?.n || 0,
+ unique_placers: placed?.unique_devices || 0,
+ nearby_fetches: nearby?.n || 0,
+ unique_browsers: nearby?.unique_devices || 0,
+ interactions: Object.fromEntries(interactionRows.map((r) => [r.type, r.n])),
+ shares_created: shares?.created || 0,
+ share_views: shares?.views || 0,
+ drops_claimed: drops?.n || 0,
+ };
+ }
+
+ const placementModes = await sql`
+ SELECT coalesce(metadata->>'mode', 'unknown') AS mode, count(*)::int AS n
+ FROM irl_events
+ WHERE event_type = 'pin_created' AND created_at > now() - interval '30 days'
+ GROUP BY mode ORDER BY n DESC
+ `;
+
+ const dailySeries = await sql`
+ SELECT
+ day::date AS day,
+ coalesce(p.n, 0)::int AS pins_placed,
+ coalesce(n.n, 0)::int AS nearby_fetches
+ FROM generate_series(current_date - interval '29 days', current_date, interval '1 day') AS day
+ LEFT JOIN (
+ SELECT date_trunc('day', created_at) AS day, count(*) AS n
+ FROM irl_events WHERE event_type = 'pin_created' AND created_at > now() - interval '30 days'
+ GROUP BY 1
+ ) p ON p.day = day
+ LEFT JOIN (
+ SELECT date_trunc('day', created_at) AS day, count(*) AS n
+ FROM irl_events WHERE event_type = 'nearby_fetch' AND created_at > now() - interval '30 days'
+ GROUP BY 1
+ ) n ON n.day = day
+ ORDER BY day ASC
+ `;
+
+ return {
+ windows,
+ placement_modes_30d: Object.fromEntries(placementModes.map((r) => [r.mode, r.n])),
+ daily_series_30d: dailySeries.map((r) => ({
+ day: r.day instanceof Date ? r.day.toISOString().slice(0, 10) : String(r.day).slice(0, 10),
+ pins_placed: r.pins_placed,
+ nearby_fetches: r.nearby_fetches,
+ })),
+ generated_at: new Date().toISOString(),
+ };
+}
diff --git a/api/cron/irl-reap.js b/api/cron/irl-reap.js
index 3acb6561a..55caea281 100644
--- a/api/cron/irl-reap.js
+++ b/api/cron/irl-reap.js
@@ -17,6 +17,10 @@
// minimization should not let accumulate. We cascade-delete it the moment its
// pin dies, and age it out at INTERACTION_RETENTION_DAYS so even a permanent
// (signed-in) pin's encounter trail can't grow unbounded.
+// 4. Usage-analytics events (irl_events, api/_lib/irl-analytics.js) older than 90
+// days, regardless of pin state — coarse telemetry (geocell7 + hashed device
+// prefix, no FK to irl_pins by design) but still a passive trail, so it's
+// bounded the same way interactions are.
//
// Retention window — interactions: 180 days. Rationale: long enough that an owner's
// dashboard inbox + the earnings history a `pay` row backs stay useful across a
@@ -51,7 +55,7 @@ export const REAP_SPIKE_THRESHOLD = 1000;
// compares to the threshold. Exported for unit testing — no I/O, no clock.
export function reapTotal(counts) {
return (counts?.pins || 0) + (counts?.reports || 0) + (counts?.interactions || 0) +
- (counts?.worldLines || 0) + (counts?.proofs || 0);
+ (counts?.worldLines || 0) + (counts?.proofs || 0) + (counts?.events || 0);
}
export function isReapSpike(counts, threshold = REAP_SPIKE_THRESHOLD) {
return reapTotal(counts) >= threshold;
@@ -82,13 +86,14 @@ export default wrapCron(async (req, res) => {
// they may not exist yet. A reaper that hard-depended on them would throw
// `relation does not exist` and 500 the hourly cron. Probe with to_regclass
// and treat a missing table as "nothing to reap" rather than an error.
- const [{ pins, reports, interactions, worldlines, proofs }] = await sql`
+ const [{ pins, reports, interactions, worldlines, proofs, events }] = await sql`
SELECT
to_regclass('public.irl_pins') AS pins,
to_regclass('public.irl_pin_reports') AS reports,
to_regclass('public.irl_interactions') AS interactions,
to_regclass('public.irl_world_lines') AS worldlines,
- to_regclass('public.irl_presence_proofs') AS proofs
+ to_regclass('public.irl_presence_proofs') AS proofs,
+ to_regclass('public.irl_events') AS events
`;
// Expired anon pins, ≥ 1 day past expiry. expires_at IS NULL ⇒ permanent ⇒ kept.
@@ -167,12 +172,27 @@ export default wrapCron(async (req, res) => {
: await sql`DELETE FROM irl_presence_proofs RETURNING id`;
}
+ // Usage-analytics events (api/_lib/irl-analytics.js) — coarse telemetry
+ // (geocell7 + a hashed device prefix, never a raw coordinate or token) with
+ // no FK to irl_pins by design: a pin can expire while its historical placement
+ // trend stays queryable. Still bounded like every other passive trail here —
+ // aged out at 90 days regardless of pin state.
+ let reapedEvents = [];
+ if (events) {
+ reapedEvents = await sql`
+ DELETE FROM irl_events
+ WHERE created_at < NOW() - INTERVAL '90 days'
+ RETURNING id
+ `;
+ }
+
const counts = {
pins: reapedPins.length,
reports: reapedReports.length,
interactions: reapedInteractions.length,
worldLines: reapedWorldLines.length,
proofs: reapedProofs.length,
+ events: reapedEvents.length,
};
const total = reapTotal(counts);
@@ -188,7 +208,7 @@ export default wrapCron(async (req, res) => {
if (isReapSpike(counts)) {
sendOpsAlert(
'IRL reaper spike',
- `The IRL reaper deleted ${total} rows in one run (pins ${counts.pins}, reports ${counts.reports}, interactions ${counts.interactions}, worldLines ${counts.worldLines}, proofs ${counts.proofs}) — above the ${REAP_SPIKE_THRESHOLD} anomaly threshold. Possible mass-expiry, backfill, or delete bug.`,
+ `The IRL reaper deleted ${total} rows in one run (pins ${counts.pins}, reports ${counts.reports}, interactions ${counts.interactions}, worldLines ${counts.worldLines}, proofs ${counts.proofs}, events ${counts.events}) — above the ${REAP_SPIKE_THRESHOLD} anomaly threshold. Possible mass-expiry, backfill, or delete bug.`,
{ signature: `irl-reap:spike:${Math.floor(Date.now() / 3_600_000)}` },
);
}
@@ -200,6 +220,7 @@ export default wrapCron(async (req, res) => {
reapedInteractions: counts.interactions,
reapedWorldLines: counts.worldLines,
reapedProofs: counts.proofs,
+ reapedEvents: counts.events,
ts: Date.now(),
});
});
diff --git a/api/irl/analytics.js b/api/irl/analytics.js
new file mode 100644
index 000000000..c1a8323cc
--- /dev/null
+++ b/api/irl/analytics.js
@@ -0,0 +1,41 @@
+// GET /api/irl/analytics — site-wide /irl usage rollup for the admin dashboard
+// (/admin/irl-analytics). Auth mirrors /api/ops/health and
+// /api/admin/ops-alerts exactly: authorizeOps (signed-in platform admin OR
+// `x-ops-secret` / Bearer OPS_SECRET). This surface exposes aggregate usage
+// volume, not any individual's location or identity, but it's still internal
+// operating data — same gate as the rest of /admin.
+//
+// Every number is a real query over irl_events (api/_lib/irl-analytics.js),
+// irl_interactions, and irl_drop_claims — no cached/sampled/fake figures.
+
+import { wrap, cors, json, error } from '../_lib/http.js';
+import { limits, clientIp } from '../_lib/rate-limit.js';
+import { rateLimited } from '../_lib/http.js';
+import { authorizeOps } from '../_lib/ops-auth.js';
+import { getIrlAnalyticsSummary } from '../_lib/irl-analytics.js';
+
+export default wrap(async (req, res) => {
+ if (cors(req, res, { methods: 'GET,OPTIONS', origins: 'same' })) return;
+ if (req.method?.toUpperCase() !== 'GET') return error(res, 405, 'method_not_allowed', 'GET only');
+
+ const rl = await limits.authIp(clientIp(req));
+ if (!rl.success) return rateLimited(res, rl);
+
+ const auth = await authorizeOps(req);
+ if (!auth.ok) return error(res, 401, 'unauthorized', 'admin session or x-ops-secret required');
+
+ try {
+ const summary = await getIrlAnalyticsSummary();
+ return json(res, 200, summary);
+ } catch (err) {
+ // Table absent (pre-deploy) or DB hiccup — report an honest empty summary
+ // rather than 500ing the dashboard.
+ return json(res, 200, {
+ windows: {},
+ placement_modes_30d: {},
+ daily_series_30d: [],
+ generated_at: new Date().toISOString(),
+ note: `analytics_unavailable: ${err?.message || 'db error'}`,
+ });
+ }
+});
diff --git a/api/irl/pins.js b/api/irl/pins.js
index 9ae3f5248..ac5da57b9 100644
--- a/api/irl/pins.js
+++ b/api/irl/pins.js
@@ -29,6 +29,7 @@ import { sha256 } from '../_lib/crypto.js';
import { readDeviceToken } from '../_lib/irl-auth.js';
import { verifyFixToken, fixEnforced } from '../_lib/irl-presence.js';
import { calibrateRoomOrigin, pinAbsoluteFromOrigin } from '../../src/irl/room-anchor.js';
+import { logIrlEvent } from '../_lib/irl-analytics.js';
// ── Moderation, safety & density caps (D4) ──────────────────────────────────
// Everything below makes the public, shared IRL world safe to launch: content
@@ -1187,6 +1188,9 @@ export default wrap(async (req, res) => {
// alert past the threshold. Best-effort and fire-and-forget — never awaited
// into the response path, never carries a coordinate.
recordCellRead(clientIp(req), encodeGeohash(lat, lng, GEOCELL_PRECISION));
+ // Usage analytics (fire-and-forget, never awaited into the response path —
+ // same discipline as recordCellRead above). See api/_lib/irl-analytics.js.
+ logIrlEvent({ type: 'nearby_fetch', lat, lng, deviceToken: myTok, metadata: { count: pins.length } });
return json(res, 200, { pins });
}
@@ -1436,6 +1440,7 @@ export default wrap(async (req, res) => {
// No realtime fan-out: a new placement is never broadcast as a roster. It
// surfaces to a viewer only on their next proximity poll, and only once they
// are physically within the nearby radius of where it was dropped.
+ logIrlEvent({ type: 'pin_created', pinId: pin.id, lat, lng, deviceToken, metadata: { mode: anchorSource } });
return json(res, 201, { pin: { ...pin, permanent: expiresAt === null } });
}
diff --git a/pages/admin/irl-analytics.html b/pages/admin/irl-analytics.html
new file mode 100644
index 000000000..4a29c168b
--- /dev/null
+++ b/pages/admin/irl-analytics.html
@@ -0,0 +1,235 @@
+<!doctype html>
+<html lang="en">
+<head>
+ <script>/* three.ws theme boot */(function(){document.documentElement.classList.add('js');try{var m=localStorage.getItem('twx_theme');var l=m==='auto'?(window.matchMedia&&window.matchMedia('(prefers-color-scheme: light)').matches):m==='light';document.documentElement.setAttribute('data-theme',l?'light':'dark');}catch(e){document.documentElement.setAttribute('data-theme','dark');}})();</script>
+ <meta charset="utf-8" />
+ <meta name="viewport" content="width=device-width, initial-scale=1.0" />
+ <title>IRL Analytics · three.ws</title>
+ <meta name="robots" content="noindex, nofollow" />
+ <link rel="icon" href="/favicon.ico" sizes="any" />
+ <link rel="stylesheet" href="/style.css" />
+ <link rel="stylesheet" href="/nav.css" />
+ <link rel="stylesheet" href="/fonts/fonts.css" />
+ <style>
+ body { background: #0a0a0f; color: #e2e8f0; min-height: 100vh; }
+ .wrap { max-width: 1200px; margin: 0 auto; padding: clamp(1.5rem, 4vw, 3rem) 1.25rem 5rem; }
+
+ .hd { display: flex; align-items: center; justify-content: space-between; margin-bottom: 2rem; flex-wrap: wrap; gap: 1rem; }
+ .title { font-size: clamp(1.4rem, 3vw, 1.85rem); font-weight: 800; letter-spacing: -0.025em; margin: 0; }
+ .meta { display: flex; align-items: center; gap: 1rem; flex-wrap: wrap; }
+ .checked { font-size: 12px; color: rgba(255,255,255,0.35); }
+ .refresh { font: inherit; font-size: 12px; font-weight: 600; padding: 7px 14px; border-radius: 8px; border: 1px solid rgba(255,255,255,0.12); background: rgba(255,255,255,0.05); color: rgba(255,255,255,0.6); cursor: pointer; transition: all .15s; }
+ .refresh:hover { background: rgba(255,255,255,0.1); color: #fff; }
+
+ .auth-gate { max-width: 440px; margin: 5rem auto; background: rgba(255,255,255,0.035); border: 1px solid rgba(255,255,255,0.08); border-radius: 16px; padding: 2rem; }
+ .auth-gate h2 { font-size: 1.1rem; margin: 0 0 1.25rem; }
+ .auth-gate input { width: 100%; font: inherit; font-size: 13.5px; padding: 10px 14px; border-radius: 10px; border: 1px solid rgba(255,255,255,0.12); background: rgba(255,255,255,0.05); color: #fff; box-sizing: border-box; margin-bottom: 0.75rem; }
+ .auth-gate input:focus { outline: none; border-color: rgba(124,92,255,0.5); }
+ .auth-gate button { width: 100%; font: inherit; font-size: 13.5px; font-weight: 600; padding: 11px; border-radius: 10px; border: none; background: linear-gradient(135deg,#7c5cff,#6144e0); color: #fff; cursor: pointer; }
+ .auth-err { font-size: 12.5px; color: #f87171; margin-top: 0.5rem; }
+
+ .tabs { display: flex; gap: 0.5rem; margin-bottom: 1.5rem; }
+ .tab { font: inherit; font-size: 12.5px; font-weight: 600; padding: 7px 14px; border-radius: 999px; border: 1px solid rgba(255,255,255,0.1); background: rgba(255,255,255,0.03); color: rgba(255,255,255,0.5); cursor: pointer; }
+ .tab.active { background: rgba(124,92,255,0.14); border-color: rgba(124,92,255,0.4); color: #b3a1ff; }
+
+ .cards { display: grid; grid-template-columns: repeat(auto-fit, minmax(160px, 1fr)); gap: 1rem; margin-bottom: 2rem; }
+ .card { background: rgba(255,255,255,0.03); border: 1px solid rgba(255,255,255,0.07); border-radius: 12px; padding: 1rem 1.1rem; }
+ .card .lbl { font-size: 10px; text-transform: uppercase; letter-spacing: 0.08em; color: rgba(255,255,255,0.35); margin-bottom: 0.4rem; }
+ .card .val { font-size: 1.6rem; font-weight: 800; letter-spacing: -0.03em; font-variant-numeric: tabular-nums; }
+ .card .sub { font-size: 11px; color: rgba(255,255,255,0.3); margin-top: 2px; }
+
+ .section { margin-bottom: 2.5rem; }
+ .section-hd { font-size: 11px; text-transform: uppercase; letter-spacing: 0.1em; font-weight: 700; color: rgba(255,255,255,0.3); margin-bottom: 0.85rem; }
+
+ .panel { background: rgba(255,255,255,0.025); border: 1px solid rgba(255,255,255,0.06); border-radius: 14px; padding: 1.25rem 1.4rem; }
+
+ .legend { display: flex; gap: 1.25rem; margin-bottom: 0.9rem; font-size: 12px; }
+ .legend-item { display: flex; align-items: center; gap: 0.4rem; color: rgba(255,255,255,0.6); }
+ .legend-dot { width: 8px; height: 8px; border-radius: 50%; }
+
+ .bars { display: flex; flex-direction: column; gap: 0.55rem; }
+ .bar-row { display: grid; grid-template-columns: 90px 1fr 40px; align-items: center; gap: 0.7rem; font-size: 12.5px; }
+ .bar-row .k { color: rgba(255,255,255,0.55); text-transform: capitalize; }
+ .bar-track { height: 8px; border-radius: 4px; background: rgba(255,255,255,0.06); overflow: hidden; }
+ .bar-fill { height: 100%; border-radius: 4px; background: linear-gradient(90deg,#7c5cff,#60a5fa); }
+ .bar-row .v { text-align: right; color: rgba(255,255,255,0.75); font-variant-numeric: tabular-nums; }
+
+ .skeleton { background: linear-gradient(90deg, rgba(255,255,255,0.04) 25%, rgba(255,255,255,0.07) 50%, rgba(255,255,255,0.04) 75%); background-size: 200% 100%; animation: shimmer 1.5s infinite; border-radius: 6px; height: 14px; }
+ @keyframes shimmer { 0% { background-position: -200% 0; } 100% { background-position: 200% 0; } }
+
+ .note { font-size: 12px; color: rgba(255,255,255,0.35); margin-top: 0.75rem; }
+ </style>
+</head>
+<body>
+<div id="nav-container"></div>
+<script src="/nav.js"></script>
+
+<div class="wrap">
+ <div class="hd">
+ <h1 class="title">IRL Analytics</h1>
+ <div class="meta">
+ <span class="checked" id="checkedAt">—</span>
+ <button class="refresh" id="refreshBtn" onclick="load()">Refresh now</button>
+ </div>
+ </div>
+
+ <div class="auth-gate" id="authGate" style="display:none">
+ <h2>Ops access required</h2>
+ <input type="password" id="secretInput" placeholder="OPS_SECRET / CRON_SECRET" onkeydown="if(event.key==='Enter')tryAuth()" autocomplete="current-password" />
+ <button onclick="tryAuth()">View analytics</button>
+ <div class="auth-err" id="authErr"></div>
+ </div>
+
+ <div id="dashboard" style="display:none">
+ <div class="tabs">
+ <button class="tab active" data-w="24h" onclick="setWindow('24h')">24h</button>
+ <button class="tab" data-w="7d" onclick="setWindow('7d')">7d</button>
+ <button class="tab" data-w="30d" onclick="setWindow('30d')">30d</button>
+ </div>
+
+ <div class="cards" id="cards"><div class="skeleton" style="height:70px"></div></div>
+
+ <div class="section">
+ <div class="section-hd">Pins placed &amp; nearby reads — last 30 days</div>
+ <div class="panel">
+ <div class="legend">
+ <span class="legend-item"><span class="legend-dot" style="background:#7c5cff"></span> Pins placed</span>
+ <span class="legend-item"><span class="legend-dot" style="background:#60a5fa"></span> Nearby reads</span>
+ </div>
+ <div id="sparkline"><div class="skeleton" style="height:120px"></div></div>
+ </div>
+ </div>
+
+ <div class="section">
+ <div class="section-hd">Placement method — last 30 days</div>
+ <div class="panel">
+ <div class="bars" id="modeBars"><div class="skeleton" style="height:60px"></div></div>
+ </div>
+ </div>
+
+ <div class="section">
+ <div class="section-hd">Interactions (view / tap / message / pay) — selected window</div>
+ <div class="panel">
+ <div class="bars" id="interactionBars"><div class="skeleton" style="height:60px"></div></div>
+ </div>
+ </div>
+
+ <div class="note">
+ Counts come from irl_events (append-only, never contains raw coordinates or device
+ tokens — geocell7 + a hashed device prefix only) plus existing irl_interactions /
+ irl_drop_claims. See docs/irl.md#analytics.
+ </div>
+ </div>
+</div>
+
+<script>
+let _secret = sessionStorage.getItem('ops_secret') || '';
+let _data = null;
+let _window = '24h';
+
+function $(id) { return document.getElementById(id); }
+function esc(s) { return String(s == null ? '' : s).replace(/[&<>"']/g, (c) => ({ '&':'&amp;','<':'&lt;','>':'&gt;','"':'&quot;',"'":'&#39;' }[c])); }
+
+async function load() {
+ if (!_secret) { showAuth(); return; }
+ $('refreshBtn').textContent = 'Refreshing…';
+ $('refreshBtn').disabled = true;
+ try {
+ const r = await fetch('/api/irl/analytics', { headers: { 'x-ops-secret': _secret } });
+ if (r.status === 401 || r.status === 403) { sessionStorage.removeItem('ops_secret'); _secret = ''; showAuth(); return; }
+ if (!r.ok) throw new Error('HTTP ' + r.status);
+ _data = await r.json();
+ render();
+ $('authGate').style.display = 'none';
+ $('dashboard').style.display = 'block';
+ } catch (e) {
+ $('cards').innerHTML = `<div class="note" style="color:#f87171">Failed to load: ${esc(e.message)}</div>`;
+ } finally {
+ $('refreshBtn').textContent = 'Refresh now';
+ $('refreshBtn').disabled = false;
+ }
+}
+
+function setWindow(w) {
+ _window = w;
+ document.querySelectorAll('.tab').forEach((t) => t.classList.toggle('active', t.dataset.w === w));
+ render();
+}
+
+function render() {
+ if (!_data) return;
+ $('checkedAt').textContent = 'Checked ' + new Date(_data.generated_at).toLocaleTimeString();
+
+ const w = _data.windows[_window] || {};
+ $('cards').innerHTML = [
+ { lbl: 'Pins placed', val: w.pins_placed || 0, sub: `${w.unique_placers || 0} unique placers` },
+ { lbl: 'Nearby reads', val: w.nearby_fetches || 0, sub: `${w.unique_browsers || 0} unique browsers` },
+ { lbl: 'Shares created', val: w.shares_created || 0, sub: `${w.share_views || 0} share views` },
+ { lbl: 'Drops claimed', val: w.drops_claimed || 0, sub: 'confirmed on-chain' },
+ ].map((c) => `<div class="card"><div class="lbl">${c.lbl}</div><div class="val">${c.val.toLocaleString()}</div><div class="sub">${c.sub}</div></div>`).join('');
+
+ renderInteractions(w.interactions || {});
+ renderModes(_data.placement_modes_30d || {});
+ renderSparkline(_data.daily_series_30d || []);
+}
+
+function renderInteractions(map) {
+ const rows = ['view', 'tap', 'message', 'pay'];
+ const max = Math.max(1, ...rows.map((k) => map[k] || 0));
+ $('interactionBars').innerHTML = rows.map((k) => {
+ const v = map[k] || 0;
+ return `<div class="bar-row"><div class="k">${k}</div><div class="bar-track"><div class="bar-fill" style="width:${(v / max) * 100}%"></div></div><div class="v">${v.toLocaleString()}</div></div>`;
+ }).join('');
+}
+
+function renderModes(map) {
+ const entries = Object.entries(map).sort((a, b) => b[1] - a[1]);
+ if (!entries.length) { $('modeBars').innerHTML = '<div class="note">No placements in the last 30 days.</div>'; return; }
+ const max = Math.max(1, ...entries.map(([, v]) => v));
+ const labels = { webxr: 'WebXR (true AR)', 'gyro-gps': 'Camera pin (gyro)', 'gyro-gps:rel': 'Camera pin (relative)', map: 'Map placement', marker: 'QR marker (indoor)', unknown: 'Unknown' };
+ $('modeBars').innerHTML = entries.map(([k, v]) =>
+ `<div class="bar-row"><div class="k">${esc(labels[k] || k)}</div><div class="bar-track"><div class="bar-fill" style="width:${(v / max) * 100}%"></div></div><div class="v">${v.toLocaleString()}</div></div>`
+ ).join('');
+}
+
+// Plain SVG sparkline, two thin 2px lines, rounded caps, no dual axis — both
+// series share one "events/day" scale so a single y-axis is honest.
+function renderSparkline(series) {
+ if (!series.length) { $('sparkline').innerHTML = '<div class="note">No data yet.</div>'; return; }
+ const w = 900, h = 140, pad = 8;
+ const max = Math.max(1, ...series.map((d) => Math.max(d.pins_placed, d.nearby_fetches)));
+ const x = (i) => pad + (i / (series.length - 1 || 1)) * (w - pad * 2);
+ const y = (v) => h - pad - (v / max) * (h - pad * 2);
+ const path = (key) => series.map((d, i) => `${i === 0 ? 'M' : 'L'}${x(i).toFixed(1)},${y(d[key]).toFixed(1)}`).join(' ');
+ $('sparkline').innerHTML = `<svg viewBox="0 0 ${w} ${h}" style="width:100%;height:140px" preserveAspectRatio="none">
+ <line x1="${pad}" y1="${h - pad}" x2="${w - pad}" y2="${h - pad}" stroke="rgba(255,255,255,0.08)" stroke-width="1" />
+ <path d="${path('nearby_fetches')}" fill="none" stroke="#60a5fa" stroke-width="2" stroke-linecap="round" stroke-linejoin="round" />
+ <path d="${path('pins_placed')}" fill="none" stroke="#7c5cff" stroke-width="2" stroke-linecap="round" stroke-linejoin="round" />
+ </svg>`;
+}
+
+function showAuth() {
+ $('authGate').style.display = 'block';
+ $('dashboard').style.display = 'none';
+ setTimeout(() => $('secretInput').focus(), 50);
+}
+
+async function tryAuth() {
+ const val = $('secretInput').value.trim();
+ if (!val) return;
+ _secret = val;
+ $('authErr').textContent = '';
+ const r = await fetch('/api/irl/analytics', { headers: { 'x-ops-secret': _secret } });
+ if (r.status === 401 || r.status === 403) { $('authErr').textContent = 'Invalid secret.'; _secret = ''; return; }
+ sessionStorage.setItem('ops_secret', _secret);
+ $('secretInput').value = '';
+ _data = await r.json();
+ render();
+ $('authGate').style.display = 'none';
+ $('dashboard').style.display = 'block';
+}
+
+if (_secret) { load(); } else { showAuth(); }
+</script>
+</body>
+</html>
diff --git a/tests/api/irl-reap-cron.test.js b/tests/api/irl-reap-cron.test.js
index 18030a233..397a9e6b9 100644
--- a/tests/api/irl-reap-cron.test.js
+++ b/tests/api/irl-reap-cron.test.js
@@ -188,6 +188,43 @@ describe('irl-reap cron', () => {
expect(sendOpsAlert).not.toHaveBeenCalled();
});
+ it('ages out irl_events past 90 days when the table exists (undated when absent)', async () => {
+ sqlMock
+ .mockResolvedValueOnce([{ pins: 'irl_pins', reports: 'irl_pin_reports', interactions: 'irl_interactions', worldlines: null, proofs: null, events: 'irl_events' }]) // probe
+ .mockResolvedValueOnce([]) // pins delete
+ .mockResolvedValueOnce([]) // reports delete
+ .mockResolvedValueOnce([]) // interactions orphan delete
+ .mockResolvedValueOnce([]) // interactions age-out delete
+ .mockResolvedValueOnce([{ id: 1 }, { id: 2 }]); // events age-out delete
+
+ const { req, res } = makeReqRes();
+ await handler(req, res);
+
+ expect(res.statusCode).toBe(200);
+ expect(res.body).toMatchObject({ ok: true, reapedEvents: 2 });
+ const eventsCall = sqlMock.mock.calls.find(([s]) => {
+ const q = Array.isArray(s) ? s.join(' ') : String(s);
+ return /DELETE FROM irl_events/i.test(q) && /90 days/i.test(q);
+ });
+ expect(eventsCall).toBeTruthy();
+ });
+
+ it('skips the events sweep entirely when irl_events does not exist yet', async () => {
+ sqlMock
+ .mockResolvedValueOnce([{ pins: 'irl_pins', reports: 'irl_pin_reports', interactions: 'irl_interactions', worldlines: null, proofs: null, events: null }]) // probe
+ .mockResolvedValueOnce([]) // pins delete
+ .mockResolvedValueOnce([]) // reports delete
+ .mockResolvedValueOnce([]) // interactions orphan delete
+ .mockResolvedValueOnce([]); // interactions age-out delete
+
+ const { req, res } = makeReqRes();
+ await handler(req, res);
+
+ expect(res.statusCode).toBe(200);
+ expect(res.body).toMatchObject({ ok: true, reapedEvents: 0 });
+ expect(sqlMock).toHaveBeenCalledTimes(5); // no extra DELETE issued against a missing relation
+ });
+
it('rejects an unauthenticated request with 401', async () => {
const { req, res } = makeReqRes();
req.headers.authorization = 'Bearer wrong';
diff --git a/tests/irl-analytics.test.js b/tests/irl-analytics.test.js
new file mode 100644
index 000000000..cc2232a6b
--- /dev/null
+++ b/tests/irl-analytics.test.js
@@ -0,0 +1,148 @@
+// api/_lib/irl-analytics.js — site-wide /irl usage rollup.
+//
+// Covers the privacy-load-bearing bits (device tokens are hashed, never stored
+// raw; lat/lng collapse to a geocell before storage), the "never breaks the
+// caller" contract of logIrlEvent, and the summary query's window/shape.
+
+import { describe, it, expect, beforeEach, vi } from 'vitest';
+
+const sqlMock = vi.fn();
+vi.mock('../api/_lib/db.js', () => ({ sql: sqlMock }));
+
+const {
+ IRL_EVENT_TYPES,
+ hashDeviceToken,
+ logIrlEvent,
+ recordShareView,
+ getIrlAnalyticsSummary,
+} = await import('../api/_lib/irl-analytics.js');
+
+beforeEach(() => {
+ sqlMock.mockReset();
+ // Every call defaults to an empty-row resolution unless a test overrides it —
+ // ensureIrlAnalyticsSchema's CREATE TABLE/INDEX statements don't return rows.
+ sqlMock.mockResolvedValue([]);
+});
+
+describe('IRL_EVENT_TYPES', () => {
+ it('is the closed vocabulary logIrlEvent enforces', () => {
+ expect(IRL_EVENT_TYPES.has('pin_created')).toBe(true);
+ expect(IRL_EVENT_TYPES.has('nearby_fetch')).toBe(true);
+ expect(IRL_EVENT_TYPES.has('share_created')).toBe(true);
+ expect(IRL_EVENT_TYPES.has('share_viewed')).toBe(true);
+ expect(IRL_EVENT_TYPES.has('made_up_type')).toBe(false);
+ });
+});
+
+describe('hashDeviceToken', () => {
+ it('returns a 16-hex-char opaque prefix, never the raw token', async () => {
+ const h = await hashDeviceToken('super-secret-device-token');
+ expect(h).toMatch(/^[0-9a-f]{16}$/);
+ expect(h).not.toContain('super-secret-device-token');
+ });
+
+ it('is stable for the same input and different for different input', async () => {
+ const a = await hashDeviceToken('device-a');
+ const b = await hashDeviceToken('device-a');
+ const c = await hashDeviceToken('device-b');
+ expect(a).toBe(b);
+ expect(a).not.toBe(c);
+ });
+
+ it('null-guards absent/non-string tokens', async () => {
+ expect(await hashDeviceToken(null)).toBeNull();
+ expect(await hashDeviceToken(undefined)).toBeNull();
+ expect(await hashDeviceToken(42)).toBeNull();
+ expect(await hashDeviceToken('')).toBeNull();
+ });
+});
+
+describe('logIrlEvent', () => {
+ it('rejects an unknown event type without touching the database', async () => {
+ await logIrlEvent({ type: 'not_a_real_event' });
+ expect(sqlMock).not.toHaveBeenCalled();
+ });
+
+ it('inserts a coarsened geocell7, never a raw lat/lng, when a location is given', async () => {
+ await logIrlEvent({ type: 'nearby_fetch', lat: 37.7749, lng: -122.4194, metadata: { count: 3 } });
+ const insertCall = sqlMock.mock.calls.find(([strings]) =>
+ Array.isArray(strings) && strings.join(' ').includes('INSERT INTO irl_events'));
+ expect(insertCall).toBeTruthy();
+ const [, , , geocell7] = insertCall; // event_type, pin_id, geocell7 positions in the template values
+ expect(typeof geocell7).toBe('string');
+ expect(geocell7.length).toBe(7);
+ });
+
+ it('stores no geocell when no location is given', async () => {
+ await logIrlEvent({ type: 'pin_created', pinId: 'abc' });
+ const insertCall = sqlMock.mock.calls.find(([strings]) =>
+ Array.isArray(strings) && strings.join(' ').includes('INSERT INTO irl_events'));
+ expect(insertCall).toBeTruthy();
+ });
+
+ it('hashes the device token before it ever reaches a query', async () => {
+ await logIrlEvent({ type: 'pin_created', pinId: 'abc', deviceToken: 'raw-device-token-xyz' });
+ const insertCall = sqlMock.mock.calls.find(([strings]) =>
+ Array.isArray(strings) && strings.join(' ').includes('INSERT INTO irl_events'));
+ const flatArgs = insertCall.join('|');
+ expect(flatArgs).not.toContain('raw-device-token-xyz');
+ });
+
+ it('never throws when the database rejects every call — the hot path must survive', async () => {
+ sqlMock.mockReset();
+ sqlMock.mockRejectedValue(new Error('db is down'));
+ await expect(logIrlEvent({ type: 'pin_created', pinId: 'abc' })).resolves.toBeUndefined();
+ });
+});
+
+describe('recordShareView', () => {
+ it('bumps view_count and logs a share_viewed event when the token exists', async () => {
+ sqlMock.mockReset();
+ sqlMock.mockResolvedValue([]); // schema DDL calls
+ sqlMock.mockImplementationOnce(async () => []); // ensureIrlAnalyticsSchema: CREATE TABLE irl_events
+ const result = await recordShareView('tok123');
+ // With no matching row the UPDATE...RETURNING resolves empty and nothing
+ // further is logged — this just asserts the call never throws.
+ expect(result === null || typeof result === 'object').toBe(true);
+ });
+
+ it('never throws on a database failure', async () => {
+ sqlMock.mockReset();
+ sqlMock.mockRejectedValue(new Error('db is down'));
+ await expect(recordShareView('tok123')).resolves.toBeNull();
+ });
+});
+
+describe('getIrlAnalyticsSummary', () => {
+ it('returns a window per period with honest zeros when every query is empty', async () => {
+ sqlMock.mockReset();
+ sqlMock.mockResolvedValue([]);
+ // Provide the two-field shape the summary destructures for the placed/nearby
+ // aggregate queries so `placed?.n || 0` style access doesn't throw on undefined.
+ sqlMock.mockImplementation(async (strings) => {
+ const q = Array.isArray(strings) ? strings.join(' ') : String(strings);
+ if (/count\(\*\)::int AS n, count\(DISTINCT device_hash\)/.test(q)) return [{ n: 0, unique_devices: 0 }];
+ if (/count\(\*\)::int AS created, coalesce/.test(q)) return [{ created: 0, views: 0 }];
+ if (/count\(\*\)::int AS n\s*FROM irl_drop_claims/.test(q)) return [{ n: 0 }];
+ return [];
+ });
+
+ const summary = await getIrlAnalyticsSummary();
+
+ expect(Object.keys(summary.windows)).toEqual(['24h', '7d', '30d']);
+ for (const key of ['24h', '7d', '30d']) {
+ expect(summary.windows[key]).toMatchObject({
+ pins_placed: 0,
+ unique_placers: 0,
+ nearby_fetches: 0,
+ unique_browsers: 0,
+ shares_created: 0,
+ share_views: 0,
+ drops_claimed: 0,
+ });
+ }
+ expect(summary.placement_modes_30d).toEqual({});
+ expect(Array.isArray(summary.daily_series_30d)).toBe(true);
+ expect(typeof summary.generated_at).toBe('string');
+ });
+});
diff --git a/vite.config.js b/vite.config.js
index 8b5573625..6fb2f8067 100644
--- a/vite.config.js
+++ b/vite.config.js
@@ -416,6 +416,7 @@ const appConfig = {
'admin-seeder': resolve(__dirname, 'pages/admin/seeder.html'),
'admin-ring': resolve(__dirname, 'pages/admin/ring.html'),
'admin-ops': resolve(__dirname, 'pages/admin/ops.html'),
+ 'admin-irl-analytics': resolve(__dirname, 'pages/admin/irl-analytics.html'),
launcher: resolve(__dirname, 'pages/launcher.html'),
'launch-detail': resolve(__dirname, 'pages/launch-detail.html'),
watchlist: resolve(__dirname, 'pages/watchlist.html'),