import type { Endpoint, PayloadRequest } from 'payload' import type { StatsOptions, StatsPage, StatsVisit } from './collection.js' import { CONSENT_COOKIE, CONSENT_VERSION, parseConsent } from '../consent/storage.js' import { createDailyPurge } from '../shared/purge.js' import { clientIp, consumeRateLimit } from '../shared/rateLimit.js' import { STATS_SLUG } from './collection.js' import { dayOf, deviceFromUa, isBot, referrerHost, sanitizePath, VISITOR_ID_PATTERN } from './parse.js' import { visitKey } from './visitKey.js' const VISIT_GAP_MS = 30 * 60 * 1000 const MAX_PAGES = 200 const purge = createDailyPurge(STATS_SLUG) let policy: { at: number; version: number } | null = null /** Cookie Settings → Policy version, cached for a minute (read on every hit). */ async function policyVersion(req: PayloadRequest): Promise { if (policy && Date.now() - policy.at < 60_000) {return policy.version} let version = CONSENT_VERSION try { const g = (await req.payload.findGlobal({ slug: 'cookie-settings' as never, depth: 0 })) as { policyVersion?: unknown } if (typeof g.policyVersion === 'number' && g.policyVersion >= 1) {version = Math.trunc(g.policyVersion)} } catch { // global missing — the default version applies } policy = { at: Date.now(), version } return version } function readCookie(header: null | string, name: string): string | undefined { return header ?.split(/;\s*/) .find((c) => c.startsWith(`${name}=`)) ?.slice(name.length + 1) } /** * POST /api/ipal/hit — one page view, sent by . Body: * `{ p: path, r?: referrer, l?: locale, v?: visitor id }`. * * Always 204 (nothing for a script to learn). The visitor id is kept only when * the request's own consent cookie grants analytics under the current policy * version — the server checks, it doesn't take the browser's word for it. * Logged-in panel users, bots and prefetches aren't counted. */ export function buildStatsEndpoint({ retentionDays = 90, timeZone = 'Europe/Warsaw' }: StatsOptions = {}): Endpoint { return { handler: async (req: PayloadRequest) => { const done = new Response(null, { status: 204 }) const request = req as unknown as Request const headers = request.headers const ip = clientIp(request) const limit = await consumeRateLimit({ key: ip, max: 60, scope: 'stats' }) if (!limit.ok) {return done} const ua = headers.get('user-agent') ?? '' if (isBot(ua) || req.user) {return done} if (/prefetch|prerender/i.test(headers.get('sec-purpose') ?? headers.get('purpose') ?? '')) {return done} let body: { l?: unknown; p?: unknown; r?: unknown; v?: unknown } try { body = (await request.json()) as typeof body } catch { return done } const path = sanitizePath(body?.p) if (!path) {return done} const host = headers.get('host') ?? '' let visitorId: string | undefined if (typeof body.v === 'string' && VISITOR_ID_PATTERN.test(body.v)) { const consent = parseConsent(readCookie(headers.get('cookie'), CONSENT_COOKIE), await policyVersion(req)) if (consent?.analytics) {visitorId = body.v} } const now = new Date() const day = dayOf(now, timeZone) const key = visitKey(day, [ip, ua, host]) try { const { docs } = await req.payload.find({ collection: STATS_SLUG as never, depth: 0, limit: 1, overrideAccess: true, pagination: false, sort: '-lastAt', where: { and: [ { visitKey: { equals: key } }, { lastAt: { greater_than: new Date(now.getTime() - VISIT_GAP_MS).toISOString() } }, ], }, }) const visit = docs[0] as StatsVisit | undefined if (visit) { const pages: StatsPage[] = Array.isArray(visit.pages) ? visit.pages : [] const last = pages[pages.length - 1] // a reload within 10 s isn't a new page view const reload = last?.p === path && now.getTime() - Date.parse(last.t) < 10_000 if (!reload && pages.length < MAX_PAGES) {pages.push({ p: path, t: now.toISOString() })} await req.payload.update({ id: visit.id, collection: STATS_SLUG as never, data: { exit: path, lastAt: now.toISOString(), pageCount: pages.length, pages, ...(visitorId && !visit.visitorId ? { visitorId } : {}), } as never, depth: 0, overrideAccess: true, }) } else { const country = headers.get('cf-ipcountry') await req.payload.create({ collection: STATS_SLUG as never, data: { day, device: deviceFromUa(ua), entry: path, exit: path, lastAt: now.toISOString(), pageCount: 1, pages: [{ p: path, t: now.toISOString() }], referrer: referrerHost(body.r, host), startedAt: now.toISOString(), visitKey: key, ...(typeof body.l === 'string' && /^[a-z]{2}(?:-[A-Za-z]{2})?$/.test(body.l) ? { locale: body.l } : {}), ...(country && /^[A-Z]{2}$/.test(country) && country !== 'XX' ? { country } : {}), ...(visitorId ? { visitorId } : {}), } as never, depth: 0, overrideAccess: true, }) } purge(req.payload, { lastAt: { less_than: new Date(now.getTime() - retentionDays * 86_400_000).toISOString() } }) } catch (err) { req.payload.logger.error(`[ipal] stats hit failed: ${err instanceof Error ? err.message : String(err)}`) } return done }, method: 'post', path: '/ipal/hit', } }