Phase 1 of replacing Microsoft Clarity with first-party usage analytics: - Plain Postgres tables via shared DDL module (src/lib/analytics/schema.ts) executed by both the add_analytics_tables migration and the test bootstrap; test-db.ts drops them around drizzle push (composite-PK introspector bug) - /api/collect beacon collector with IP/UA enrichment, retroactive login attribution, bot blocklist, per-IP rate limiting, strict validation - Client SDK (src/lib/client-analytics): SPA pageviews, clicks, scroll depth, focus, data-track visibility, heartbeats; NEXT_PUBLIC_ANALYTICS_DEV=1 dev gate with console mirror; mounted beside Clarity in the two frontend layouts - Hourly rollup + daily retention bins (payload analytics-rollup/-purge) - Chronicle read progress/completion, wiki new-clicked/created, minigame route mapping custom events - admin:analytics:manage permission (+ roles enum migration) and the /admin/analytics Payload view with six recharts-backed report panels
177 lines
5.7 KiB
TypeScript
177 lines
5.7 KiB
TypeScript
/**
|
|
* Shared analytics event taxonomy and envelope validation (Phase 1).
|
|
*
|
|
* Pure module: no Payload, no DOM. Imported by the client SDK
|
|
* (`src/lib/client-analytics/`), the collector route, the ingest service and
|
|
* the rollup bins, so the event vocabulary has exactly one source of truth.
|
|
* The Postgres `analytics_events.type` column mirrors this union; adding a
|
|
* type here is a taxonomy change that belongs in the SDK README.
|
|
*/
|
|
|
|
export const ANALYTICS_EVENT_TYPES = [
|
|
"pageview",
|
|
"click",
|
|
"scroll",
|
|
"focus",
|
|
"visible",
|
|
"custom",
|
|
"heartbeat",
|
|
] as const;
|
|
|
|
export type AnalyticsEventType = (typeof ANALYTICS_EVENT_TYPES)[number];
|
|
|
|
export function isAnalyticsEventType(value: unknown): value is AnalyticsEventType {
|
|
return typeof value === "string" && (ANALYTICS_EVENT_TYPES as readonly string[]).includes(value);
|
|
}
|
|
|
|
/** Environment tag carried on every row ("dev" vs "production"). */
|
|
export const ANALYTICS_ENVS = ["dev", "production"] as const;
|
|
export type AnalyticsEnv = (typeof ANALYTICS_ENVS)[number];
|
|
|
|
/** Resolve the env tag from the server process (clients never set it). */
|
|
export function resolveAnalyticsEnv(nodeEnv: string | undefined): AnalyticsEnv {
|
|
return nodeEnv === "production" ? "production" : "dev";
|
|
}
|
|
|
|
// ---------------------------------------------------------------------------
|
|
// Ingest limits (strict validation at the collector boundary)
|
|
// ---------------------------------------------------------------------------
|
|
|
|
/** Maximum events accepted per batched envelope. */
|
|
export const MAX_EVENTS_PER_BATCH = 50;
|
|
/** Maximum characters kept for a path. */
|
|
export const MAX_PATH_LENGTH = 2048;
|
|
/** Maximum serialized JSON size for one `element` or `data` payload. */
|
|
export const MAX_JSON_BYTES = 4_096;
|
|
/** Maximum characters for the session / anonymous identifiers. */
|
|
export const MAX_ID_LENGTH = 64;
|
|
/** A batch may not carry timestamps further ahead than this. */
|
|
export const MAX_FUTURE_SKEW_MS = 5 * 60 * 1000;
|
|
/** A batch may not carry timestamps older than this (stale beacon replays). */
|
|
export const MAX_PAST_AGE_MS = 24 * 60 * 60 * 1000;
|
|
|
|
// ---------------------------------------------------------------------------
|
|
// Envelope shape
|
|
// ---------------------------------------------------------------------------
|
|
|
|
/** One client event before validation. The SDK sends epoch-ms `ts`. */
|
|
export interface RawClientEvent {
|
|
ts?: number;
|
|
type: string;
|
|
path?: string;
|
|
element?: unknown;
|
|
data?: unknown;
|
|
}
|
|
|
|
/** POST body of `/api/collect`: `{ sid, aid, events }`. */
|
|
export interface CollectEnvelope {
|
|
sid: string | null;
|
|
aid: string | null;
|
|
events: RawClientEvent[];
|
|
}
|
|
|
|
/** A validated event ready for insertion. */
|
|
export interface ValidatedEvent {
|
|
ts: Date;
|
|
type: AnalyticsEventType;
|
|
path: string | null;
|
|
element: Record<string, unknown> | null;
|
|
data: Record<string, unknown> | null;
|
|
}
|
|
|
|
export interface ParsedEnvelope {
|
|
sid: string | null;
|
|
aid: string | null;
|
|
events: ValidatedEvent[];
|
|
/** Events dropped by per-event validation (bad type, oversized json, ...). */
|
|
dropped: number;
|
|
}
|
|
|
|
function clampId(value: unknown): string | null {
|
|
if (typeof value !== "string") return null;
|
|
const trimmed = value.trim();
|
|
if (!trimmed) return null;
|
|
return trimmed.slice(0, MAX_ID_LENGTH);
|
|
}
|
|
|
|
function clampPath(value: unknown): string | null {
|
|
if (typeof value !== "string") return null;
|
|
const trimmed = value.trim();
|
|
if (!trimmed || !trimmed.startsWith("/")) return null;
|
|
return trimmed.slice(0, MAX_PATH_LENGTH);
|
|
}
|
|
|
|
function clampJsonObject(value: unknown): Record<string, unknown> | null {
|
|
if (value === null || value === undefined) return null;
|
|
if (typeof value !== "object" || Array.isArray(value)) return null;
|
|
let serialized: string;
|
|
try {
|
|
serialized = JSON.stringify(value);
|
|
} catch {
|
|
return null;
|
|
}
|
|
if (serialized.length > MAX_JSON_BYTES) return null;
|
|
return value as Record<string, unknown>;
|
|
}
|
|
|
|
/**
|
|
* Validate a parsed JSON body into a `ParsedEnvelope`. Structural problems
|
|
* (non-object body, missing/empty events array, oversized batch) reject the
|
|
* whole request; individual bad events are dropped and counted so one broken
|
|
* event never costs the rest of the batch.
|
|
*/
|
|
export function parseCollectEnvelope(body: unknown):
|
|
| { ok: true; envelope: ParsedEnvelope }
|
|
| { ok: false; error: string } {
|
|
if (body === null || typeof body !== "object" || Array.isArray(body)) {
|
|
return { ok: false, error: "Body must be a JSON object" };
|
|
}
|
|
const raw = body as Record<string, unknown>;
|
|
if (!Array.isArray(raw.events) || raw.events.length === 0) {
|
|
return { ok: false, error: "events must be a non-empty array" };
|
|
}
|
|
if (raw.events.length > MAX_EVENTS_PER_BATCH) {
|
|
return { ok: false, error: `events exceeds ${MAX_EVENTS_PER_BATCH}` };
|
|
}
|
|
|
|
const now = Date.now();
|
|
const events: ValidatedEvent[] = [];
|
|
let dropped = 0;
|
|
|
|
for (const candidate of raw.events as unknown[]) {
|
|
if (candidate === null || typeof candidate !== "object" || Array.isArray(candidate)) {
|
|
dropped += 1;
|
|
continue;
|
|
}
|
|
const event = candidate as Record<string, unknown>;
|
|
if (!isAnalyticsEventType(event.type)) {
|
|
dropped += 1;
|
|
continue;
|
|
}
|
|
let tsMs = now;
|
|
if (typeof event.ts === "number" && Number.isFinite(event.ts)) {
|
|
if (event.ts > now + MAX_FUTURE_SKEW_MS || event.ts < now - MAX_PAST_AGE_MS) {
|
|
dropped += 1;
|
|
continue;
|
|
}
|
|
tsMs = event.ts;
|
|
}
|
|
events.push({
|
|
ts: new Date(tsMs),
|
|
type: event.type,
|
|
path: clampPath(event.path),
|
|
element: clampJsonObject(event.element),
|
|
data: clampJsonObject(event.data),
|
|
});
|
|
}
|
|
|
|
return {
|
|
ok: true,
|
|
envelope: {
|
|
sid: clampId(raw.sid),
|
|
aid: clampId(raw.aid),
|
|
events,
|
|
dropped,
|
|
},
|
|
};
|
|
}
|