Built-in statistics (cookieless, consent-gated visitor history); per-page meta descriptions, NoSnippet

Stats: ipalKit({ stats: true }) adds the stats-visits collection, POST /api/ipal/hit, the
/admin/stats view (30-day visits chart, top/entry pages, referrers, devices), a dashboard card
and a nav link. <PageStats> (or <SiteProviders stats>) sends one beacon per page view. Without
consent nothing is stored on the device and no IP is kept: page views are joined by a hash with
an in-memory salt replaced daily. With analytics consent an ipal_vid cookie links visits across
days (server re-checks the consent cookie and policy version; withdrawal deletes the cookie).
Bots, logged-in panel users and prefetches aren't counted. Retention 90 days.
@payloadcms/next added to peerDependencies (DefaultTemplate). Docs: stats.md with privacy text.

Also in this release: meta.description auto-filled from page blocks, <NoSnippet>,
MetaDescriptionCheck in the SEO tab, data-nosnippet on banner/language switcher, GA4 CSP
wildcards, consent version passed to Analytics' default consent.

Co-Authored-By: Claude Opus 5.5 <[email protected]>
This commit is contained in:
Radosław Smoliński
2026-10-21 15:10:55 +02:00
co-authored by Claude Opus 5.5
parent 305c564d13
commit 4ec27d9ef0
47 changed files with 1799 additions and 57 deletions
+158
View File
@@ -0,0 +1,158 @@
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 { 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
let lastPurge = 0
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<number> {
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 <PageStats>. 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,
})
}
if (now.getTime() - lastPurge > 24 * 60 * 60 * 1000) {
lastPurge = now.getTime()
await req.payload.delete({
collection: STATS_SLUG as never,
overrideAccess: true,
where: { 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',
}
}