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
+75
View File
@@ -0,0 +1,75 @@
'use client'
import { useEffect, useRef } from 'react'
// .js extension: Node's ESM resolution (this plugin's tsconfig) can't find
// 'next/navigation' without it.
import { usePathname } from 'next/navigation.js'
import { useConsentContext } from '../consent/ConsentContext.js'
import { CONSENT_COOKIE, CONSENT_MAX_AGE, parseConsent } from '../consent/storage.js'
/** Visitor id cookie — set ONLY with analytics consent, deleted on withdrawal (DEFAULT_COOKIE_MAP). */
export const VISITOR_COOKIE = 'ipal_vid'
function readCookie(name: string): string | undefined {
return document.cookie
.split('; ')
.find((c) => c.startsWith(`${name}=`))
?.split('=')[1]
}
function ensureVisitorId(): string {
const existing = readCookie(VISITOR_COOKIE)
if (existing && /^[0-9a-f]{32}$/.test(existing)) {return existing}
const bytes = new Uint8Array(16)
globalThis.crypto.getRandomValues(bytes)
const id = Array.from(bytes, (b) => b.toString(16).padStart(2, '0')).join('')
const secure = location.protocol === 'https:' ? ';secure' : ''
document.cookie = `${VISITOR_COOKIE}=${id};path=/;max-age=${CONSENT_MAX_AGE};samesite=lax${secure}`
return id
}
export type PageStatsProps = {
/** The hit endpoint. Default '/api/ipal/hit' (ipalKit({ stats: true })). */
endpoint?: string
/** Current locale code, stored with the visit. */
locale?: string
}
/**
* Built-in statistics: sends one beacon per page view to the hit endpoint.
*
* - **Everyone, no consent needed** — nothing is stored in the browser; the
* server joins page views into a visit with a daily-salted hash it can't
* reverse, and keeps no IP.
* - **With analytics consent** (the same category that turns on GA4) — sets the
* `ipal_vid` cookie with a random id, so the panel can show that visitor's
* history across days. Withdrawing consent deletes the cookie.
*
* Renders nothing. Mount once in the locale layout, INSIDE <ConsentProvider>.
*/
export function PageStats({ endpoint = '/api/ipal/hit', locale }: PageStatsProps) {
const pathname = usePathname()
const { texts } = useConsentContext()
const firstHit = useRef(true)
useEffect(() => {
if (!pathname) {return}
const body: Record<string, string> = { p: pathname }
// the external referrer belongs to the landing page only
if (firstHit.current && document.referrer) {body.r = document.referrer}
firstHit.current = false
if (locale) {body.l = locale}
// The cookie, not context state: on a full page load this effect runs before
// useConsent has read the cookie, so state would still say "no consent".
if (parseConsent(readCookie(CONSENT_COOKIE), texts.version)?.analytics) {body.v = ensureVisitorId()}
const json = JSON.stringify(body)
if (!navigator.sendBeacon?.(endpoint, new Blob([json], { type: 'application/json' }))) {
void fetch(endpoint, { body: json, headers: { 'content-type': 'application/json' }, keepalive: true, method: 'POST' }).catch(() => {})
}
// texts.version is read, not a trigger: a policy change isn't a page view
// eslint-disable-next-line react-hooks/exhaustive-deps
}, [pathname, endpoint, locale])
return null
}
+10
View File
@@ -0,0 +1,10 @@
/** Nav link to /admin/stats (admin.components.afterNavLinks). */
export function StatsNavLink({ adminRoute = '/admin' }: { adminRoute?: string }) {
return (
<a className="nav__link" href={`${adminRoute.replace(/\/$/, '')}/stats`} id="nav-ipal-stats">
<span className="nav__link-label">Statistics</span>
</a>
)
}
export default StatsNavLink
+172
View File
@@ -0,0 +1,172 @@
import type { AdminViewServerProps } from 'payload'
import { DefaultTemplate } from '@payloadcms/next/templates'
import { Gutter } from '@payloadcms/ui'
import type { StatsVisit } from '../collection.js'
import { isAdmin } from '../../access/predicates.js'
import { VISITOR_ID_PATTERN } from '../parse.js'
import { loadRecentVisitors, loadStats, loadVisitor } from './loadStats.js'
import { STATS_CSS, VisitsChart } from './VisitsChart.js'
type Props = { adminRoute?: string; timeZone?: string } & AdminViewServerProps
const fmt = (n: number) => n.toLocaleString('en-US')
const when = (iso: string, timeZone: string) =>
new Intl.DateTimeFormat('en-GB', { dateStyle: 'medium', timeStyle: 'short', timeZone }).format(new Date(iso))
function TopList({ rows, title, unit }: { rows: [string, number][]; title: string; unit: string }) {
return (
<section>
<h3>{title}</h3>
{rows.length ? (
<table className="ipal-stats-table">
<thead>
<tr>
<th scope="col">{title}</th>
<th scope="col">{unit}</th>
</tr>
</thead>
<tbody>
{rows.map(([key, count]) => (
<tr key={key}>
<td><code>{key}</code></td>
<td>{fmt(count)}</td>
</tr>
))}
</tbody>
</table>
) : (
<p>No data yet.</p>
)}
</section>
)
}
function VisitorHistory({ base, timeZone, visitorId, visits }: { base: string; timeZone: string; visitorId: string; visits: StatsVisit[] }) {
return (
<>
<p><a href={base}>← All statistics</a></p>
<h1>Visitor <code>{visitorId}</code></h1>
<p>
{visits.length} visit{visits.length === 1 ? '' : 's'} recorded with analytics consent. To erase this
visitor’s data, filter <em>Statistics → Visits</em> by this visitor id and delete the results.
</p>
{visits.map((v) => (
<section className="ipal-stats-tile" key={v.id} style={{ marginBottom: '1rem' }}>
<strong>{when(v.startedAt, timeZone)}</strong>
<span>
{' '}· {v.pageCount} page{v.pageCount === 1 ? '' : 's'} · {v.device ?? 'unknown device'}
{v.referrer ? ` · from ${v.referrer}` : ''}
</span>
<ol style={{ margin: '0.5rem 0 0', paddingLeft: '1.25rem' }}>
{(v.pages ?? []).map((p, i) => (
<li key={`${p.t}-${i}`}>
<code>{p.p}</code> <span>{when(p.t, timeZone).split(', ').pop()}</span>
</li>
))}
</ol>
</section>
))}
</>
)
}
/**
* Admin view at /admin/stats (ipalKit({ stats: true })): visits per day for the
* last 30 days, top pages, entry pages, referrers, devices, and — for visitors
* who accepted analytics cookies — a per-visitor history (?visitor=<id>).
* Admins only.
*/
export async function StatsView(props: Props) {
const { adminRoute = '/admin', initPageResult, searchParams, timeZone = 'Europe/Warsaw' } = props
const { req, visibleEntities } = initPageResult
const base = `${adminRoute.replace(/\/$/, '')}/stats`
const visitorParam = typeof searchParams?.visitor === 'string' ? searchParams.visitor : undefined
const visitorId = visitorParam && VISITOR_ID_PATTERN.test(visitorParam) ? visitorParam : undefined
let content: React.ReactNode
if (!isAdmin(req.user)) {
content = <p>Statistics are available to administrators only.</p>
} else if (visitorId) {
content = <VisitorHistory base={base} timeZone={timeZone} visitorId={visitorId} visits={await loadVisitor(req.payload, visitorId)} />
} else {
const [stats, recent] = await Promise.all([loadStats(req.payload, { timeZone }), loadRecentVisitors(req.payload, 50)])
const { totals } = stats
const visitors = [...new Map(recent.map((v) => [v.visitorId!, v])).values()].slice(0, 15)
content = (
<>
<h1>Statistics</h1>
<p>
Last 30 days. Counted without cookies, so no consent is needed; no IP addresses are stored. Visitors who accept
analytics cookies also get a history across days.
</p>
<div className="ipal-stats-tiles">
<div className="ipal-stats-tile"><b>{fmt(totals.visits)}</b><span>Visits</span></div>
<div className="ipal-stats-tile"><b>{fmt(totals.views)}</b><span>Page views</span></div>
<div className="ipal-stats-tile">
<b>{totals.visits ? (totals.views / totals.visits).toFixed(1) : '0'}</b><span>Pages per visit</span>
</div>
<div className="ipal-stats-tile"><b>{Math.round(totals.bounceRate * 100)}%</b><span>Single-page visits</span></div>
<div className="ipal-stats-tile"><b>{fmt(totals.consented)}</b><span>Visits with analytics consent</span></div>
</div>
<h2>Visits per day</h2>
<VisitsChart days={stats.days} />
<div className="ipal-stats-lists">
<TopList rows={stats.topPages} title="Page" unit="Views" />
<TopList rows={stats.entries} title="Entry page" unit="Visits" />
<TopList rows={stats.referrers} title="Referrer" unit="Visits" />
<TopList rows={stats.devices} title="Device" unit="Visits" />
</div>
<section style={{ marginTop: '2rem' }}>
<h3>Visitor history (analytics consent only)</h3>
{visitors.length ? (
<table className="ipal-stats-table">
<thead>
<tr>
<th scope="col">Visitor</th>
<th scope="col">Last seen</th>
</tr>
</thead>
<tbody>
{visitors.map((v) => (
<tr key={v.visitorId}>
<td><a aria-label={`Visitor ${v.visitorId}`} href={`${base}?visitor=${v.visitorId}`}><code>{v.visitorId}</code></a></td>
<td>{when(v.lastAt, timeZone)}</td>
</tr>
))}
</tbody>
</table>
) : (
<p>No visitor has accepted analytics cookies yet.</p>
)}
</section>
</>
)
}
return (
<DefaultTemplate
i18n={req.i18n}
locale={initPageResult.locale}
params={props.params}
payload={req.payload}
permissions={initPageResult.permissions}
req={req}
searchParams={searchParams}
user={req.user ?? undefined}
visibleEntities={visibleEntities}
>
<Gutter>
<div className="ipal-stats" style={{ paddingBottom: '3rem' }}>
<style>{STATS_CSS}</style>
{content}
</div>
</Gutter>
</DefaultTemplate>
)
}
export default StatsView
+42
View File
@@ -0,0 +1,42 @@
import type { Payload, PayloadRequest } from 'payload'
import { isAdmin } from '../../access/predicates.js'
import { loadStats } from './loadStats.js'
import { STATS_CSS, VisitsChart } from './VisitsChart.js'
type Props = {
adminRoute?: string
/** Injected by Payload into admin server components. */
payload?: Payload
req?: PayloadRequest
timeZone?: string
user?: unknown
}
/**
* Dashboard card (admin.components.beforeDashboard): visits per day for the
* last 30 days with a link to the full view. Admins only; renders nothing on
* any error (DB not ready, collection missing).
*/
export async function StatsWidget({ adminRoute = '/admin', payload, req, timeZone = 'Europe/Warsaw', user }: Props) {
if (!payload || !isAdmin((req?.user ?? user) as never)) {return null}
let stats
try {
stats = await loadStats(payload, { timeZone })
} catch {
return null
}
return (
<section className="ipal-stats" style={{ marginBottom: '2rem' }}>
<style>{STATS_CSS}</style>
<h2 style={{ marginBottom: '0.25rem' }}>Visits per day</h2>
<p style={{ color: 'var(--theme-elevation-500)', margin: '0 0 0.75rem' }}>
Last 30 days: {stats.totals.visits.toLocaleString('en-US')} visits, {stats.totals.views.toLocaleString('en-US')} page views ·{' '}
<a href={`${adminRoute.replace(/\/$/, '')}/stats`}>All statistics →</a>
</p>
<VisitsChart days={stats.days} />
</section>
)
}
export default StatsWidget
+108
View File
@@ -0,0 +1,108 @@
import type { StatsDay } from '../summarize.js'
const W = 1000
const H = 220
const PAD = { bottom: 24, left: 36, right: 8, top: 12 }
const RADIUS = 4
/** Round up to 1 / 2 / 5 × 10^k, so the gridlines land on readable numbers. */
function niceMax(value: number): number {
if (value <= 4) {return 4}
const pow = 10 ** Math.floor(Math.log10(value))
return ([1, 2, 5, 10].map((s) => s * pow).find((s) => s >= value) ?? 10 * pow)
}
/** Column with a 4px rounded top and a square base on the baseline. */
function column(x: number, y: number, w: number, h: number): string {
const r = Math.min(RADIUS, w / 2, h)
return `M${x},${y + h}V${y + r}Q${x},${y} ${x + r},${y}H${x + w - r}Q${x + w},${y} ${x + w},${y + r}V${y + h}Z`
}
const shortDate = (day: string) => `${day.slice(8, 10)}.${day.slice(5, 7)}`
/**
* Visits per day — server-rendered SVG, no client JS. One series, so no
* legend: the heading names it. Each day has a full-height hover target with
* a native tooltip, and the numbers are in a table below for screen readers.
*/
export function VisitsChart({ days }: { days: StatsDay[] }) {
const max = niceMax(Math.max(0, ...days.map((d) => d.visits)))
const plotW = W - PAD.left - PAD.right
const plotH = H - PAD.top - PAD.bottom
const band = plotW / Math.max(1, days.length)
const barW = Math.min(24, band - 2)
const y = (v: number) => PAD.top + plotH - (v / max) * plotH
const ticks = [0, max / 2, max]
return (
<figure className="ipal-stats-chart" style={{ margin: 0 }}>
<svg aria-hidden="true" style={{ display: 'block', height: 'auto', width: '100%' }} viewBox={`0 0 ${W} ${H}`}>
{ticks.map((t) => (
<g key={t}>
<line className="ipal-stats-grid" x1={PAD.left} x2={W - PAD.right} y1={y(t)} y2={y(t)} />
<text className="ipal-stats-axis" dominantBaseline="middle" textAnchor="end" x={PAD.left - 6} y={y(t)}>
{Number.isInteger(t) ? t : t.toFixed(1)}
</text>
</g>
))}
{days.map((d, i) => {
const x = PAD.left + i * band
const h = (d.visits / max) * plotH
const label = i % 7 === (days.length - 1) % 7
return (
<g className="ipal-stats-day" key={d.day}>
<title>{`${d.day}: ${d.visits} visits, ${d.views} page views`}</title>
<rect fill="transparent" height={plotH} width={band} x={x} y={PAD.top} />
{h > 0 ? <path className="ipal-stats-bar" d={column(x + (band - barW) / 2, y(d.visits), barW, h)} /> : null}
{label ? (
<text className="ipal-stats-axis" textAnchor="middle" x={x + band / 2} y={H - 6}>
{shortDate(d.day)}
</text>
) : null}
</g>
)
})}
</svg>
<details style={{ marginTop: '0.5rem' }}>
<summary>Table</summary>
<table className="ipal-stats-table">
<thead>
<tr>
<th scope="col">Day</th>
<th scope="col">Visits</th>
<th scope="col">Page views</th>
</tr>
</thead>
<tbody>
{[...days].reverse().map((d) => (
<tr key={d.day}>
<td>{d.day}</td>
<td>{d.visits}</td>
<td>{d.views}</td>
</tr>
))}
</tbody>
</table>
</details>
</figure>
)
}
/** Colors from the reference palette (series 1, light/dark) + Payload's theme tokens for ink. */
export const STATS_CSS = `
.ipal-stats { --ipal-series-1: #2a78d6; }
html[data-theme='dark'] .ipal-stats { --ipal-series-1: #3987e5; }
.ipal-stats-bar { fill: var(--ipal-series-1); }
.ipal-stats-day:hover .ipal-stats-bar { opacity: 0.8; }
.ipal-stats-grid { stroke: var(--theme-elevation-100); stroke-width: 1; }
.ipal-stats-axis { fill: var(--theme-elevation-500); font-size: 11px; }
.ipal-stats-tiles { display: grid; gap: 1rem; grid-template-columns: repeat(auto-fit, minmax(150px, 1fr)); margin: 1rem 0 1.5rem; }
.ipal-stats-tile { border: 1px solid var(--theme-elevation-150); border-radius: 4px; padding: 0.75rem 1rem; }
.ipal-stats-tile b { display: block; font-size: 1.75rem; line-height: 1.2; }
.ipal-stats-tile span { color: var(--theme-elevation-500); font-size: 0.85rem; }
.ipal-stats-lists { display: grid; gap: 1.5rem; grid-template-columns: repeat(auto-fit, minmax(280px, 1fr)); margin-top: 2rem; }
.ipal-stats-table { border-collapse: collapse; width: 100%; }
.ipal-stats-table th, .ipal-stats-table td { border-bottom: 1px solid var(--theme-elevation-100); padding: 0.35rem 0.5rem; text-align: left; }
.ipal-stats-table td:not(:first-child), .ipal-stats-table th:not(:first-child) { font-variant-numeric: tabular-nums; text-align: right; }
.ipal-stats-table code { word-break: break-all; }
`
+63
View File
@@ -0,0 +1,63 @@
import type { Payload } from 'payload'
import type { StatsVisit } from '../collection.js'
import type { StatsSummary } from '../summarize.js'
import { STATS_SLUG } from '../collection.js'
import { lastDays, summarize } from '../summarize.js'
const VISIT_FIELDS = {
day: true,
device: true,
entry: true,
exit: true,
lastAt: true,
pageCount: true,
pages: true,
referrer: true,
startedAt: true,
visitorId: true,
} as const
/** Summary of the last `days` days. Callers check the user is an admin first. */
export async function loadStats(payload: Payload, { days = 30, timeZone = 'Europe/Warsaw' } = {}): Promise<StatsSummary> {
const range = lastDays(days, timeZone)
const { docs } = await payload.find({
collection: STATS_SLUG as never,
depth: 0,
overrideAccess: true,
pagination: false,
select: VISIT_FIELDS as never,
where: { day: { greater_than_equal: range[0] } },
})
return summarize(docs as unknown as StatsVisit[], range)
}
/** Every stored visit of one consenting visitor, newest first. */
export async function loadVisitor(payload: Payload, visitorId: string): Promise<StatsVisit[]> {
const { docs } = await payload.find({
collection: STATS_SLUG as never,
depth: 0,
limit: 500,
overrideAccess: true,
pagination: false,
select: VISIT_FIELDS as never,
sort: '-startedAt',
where: { visitorId: { equals: visitorId } },
})
return docs as unknown as StatsVisit[]
}
/** Latest visits that carry a visitor id — the entry points into visitor history. */
export async function loadRecentVisitors(payload: Payload, limit = 20): Promise<StatsVisit[]> {
const { docs } = await payload.find({
collection: STATS_SLUG as never,
depth: 0,
limit,
overrideAccess: true,
select: VISIT_FIELDS as never,
sort: '-lastAt',
where: { visitorId: { exists: true } },
})
return docs as unknown as StatsVisit[]
}
+3
View File
@@ -0,0 +1,3 @@
'use client'
export { PageStats, VISITOR_COOKIE } from './PageStats.js'
export type { PageStatsProps } from './PageStats.js'
+90
View File
@@ -0,0 +1,90 @@
import type { CollectionConfig } from 'payload'
import { isAdmin } from '../access/predicates.js'
/**
* One document per visit (a run of page views with gaps under 30 minutes).
*
* Without consent a visit is anonymous: `visitKey` is a daily-salted hash
* (visitKey.ts) that can't be traced back to an IP or linked across days.
* With analytics consent the visit also carries `visitorId` — the random id
* from the visitor's `ipal_vid` cookie — and the panel can show that visitor's
* history across days. No IP, no user agent, no query strings are stored.
*/
export const STATS_SLUG = 'stats-visits'
export type StatsOptions = {
/** Show the 30-day chart on the admin dashboard. Default true. */
dashboard?: boolean
/** Days a visit is kept. Default 90 (the dashboard shows 30). */
retentionDays?: number
/** Time zone that decides where a day starts. Default 'Europe/Warsaw'. */
timeZone?: string
}
export type StatsPage = { p: string; t: string }
export type StatsVisit = {
country?: null | string
day: string
device?: 'desktop' | 'mobile' | 'tablet' | null
entry: string
exit: string
id: number | string
lastAt: string
locale?: null | string
pageCount: number
pages?: null | StatsPage[]
referrer?: null | string
startedAt: string
visitorId?: null | string
}
export function buildStatsCollection(): CollectionConfig {
return {
slug: STATS_SLUG,
access: {
// Written only by the hit endpoint (Local API); read and deleted by admins
// (deleting is how a visitor's erasure request is handled).
create: () => false,
delete: ({ req: { user } }) => isAdmin(user),
read: ({ req: { user } }) => isAdmin(user),
update: () => false,
},
admin: {
defaultColumns: ['day', 'entry', 'pageCount', 'referrer', 'device', 'visitorId'],
description:
'Visits from the built-in statistics. Anonymous by default; a visitor id appears only for visitors who accepted analytics cookies. No IP addresses are stored.',
group: 'Statistics',
useAsTitle: 'entry',
},
fields: [
{ name: 'day', type: 'text', index: true, required: true },
{ name: 'startedAt', type: 'date', admin: { date: { pickerAppearance: 'dayAndTime' } }, required: true },
{ name: 'lastAt', type: 'date', admin: { date: { pickerAppearance: 'dayAndTime' } }, index: true, required: true },
{ name: 'entry', type: 'text', required: true },
{ name: 'exit', type: 'text', required: true },
{ name: 'pageCount', type: 'number', required: true },
{ name: 'pages', type: 'json' },
{ name: 'referrer', type: 'text' },
{
name: 'device',
type: 'select',
options: ['desktop', 'mobile', 'tablet'],
},
{ name: 'locale', type: 'text' },
{ name: 'country', type: 'text' },
{
name: 'visitorId',
type: 'text',
admin: { description: 'Only with analytics consent — the id from the visitor’s ipal_vid cookie.' },
index: true,
},
// Daily-salted, unlinkable after midnight; only used to join hits into a visit.
{ name: 'visitKey', type: 'text', admin: { hidden: true }, index: true },
],
labels: { plural: 'Visits', singular: 'Visit' },
timestamps: false,
}
}
+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',
}
}
+5
View File
@@ -0,0 +1,5 @@
// Server-safe: collection + hit endpoint (wired by ipalKit({ stats })). <PageStats>
// is client-side (./client); the admin view and dashboard card are in /admin.
export { buildStatsCollection, STATS_SLUG } from './collection.js'
export type { StatsOptions, StatsPage, StatsVisit } from './collection.js'
export { buildStatsEndpoint } from './endpoint.js'
+50
View File
@@ -0,0 +1,50 @@
/**
* Request → clean, non-identifying fields for a stats hit. Pure functions, so
* they're testable and run the same on every runtime.
*/
export type Device = 'desktop' | 'mobile' | 'tablet'
/** Crawlers, link previews, headless browsers, uptime checks — not visitors. */
const BOT_UA =
/bot|crawl|spider|slurp|facebookexternalhit|embedly|preview|headless|lighthouse|pagespeed|pingdom|uptime|monitor|curl|wget|python|axios|node-fetch|go-http|java\//i
export function isBot(userAgent: string): boolean {
return !userAgent || BOT_UA.test(userAgent)
}
/** Coarse device class — never the model, OS version or browser build. */
export function deviceFromUa(userAgent: string): Device {
if (/ipad|tablet|android(?!.*mobile)/i.test(userAgent)) {return 'tablet'}
if (/mobi|iphone|ipod|android/i.test(userAgent)) {return 'mobile'}
return 'desktop'
}
/**
* Path only: query and hash dropped — they can carry e-mails, tokens, search
* terms. Null for anything that isn't a same-site path.
*/
export function sanitizePath(value: unknown): null | string {
if (typeof value !== 'string' || !value.startsWith('/') || value.startsWith('//')) {return null}
const path = value.split(/[?#]/)[0].slice(0, 300)
return /^[^\s<>"]*$/.test(path) ? path : null
}
/** Referrer reduced to its hostname; empty for internal navigation or garbage. */
export function referrerHost(value: unknown, ownHost: string): string {
if (typeof value !== 'string' || !value) {return ''}
try {
const host = new URL(value).hostname.replace(/^www\./, '')
return host && host !== ownHost.replace(/^www\./, '').split(':')[0] ? host.slice(0, 100) : ''
} catch {
return ''
}
}
/** Visitor id stored in the `ipal_vid` cookie — only ever set after analytics consent. */
export const VISITOR_ID_PATTERN = /^[0-9a-f]{32}$/
/** Calendar day in `timeZone`, 'YYYY-MM-DD' — the site's day, not the server's. */
export function dayOf(date: Date, timeZone = 'UTC'): string {
return new Intl.DateTimeFormat('en-CA', { day: '2-digit', month: '2-digit', timeZone, year: 'numeric' }).format(date)
}
+75
View File
@@ -0,0 +1,75 @@
import type { StatsVisit } from './collection.js'
import { dayOf } from './parse.js'
export type StatsDay = { day: string; views: number; visits: number }
export type StatsSummary = {
/** Oldest first, one entry per day — days without visits are zeros. */
days: StatsDay[]
devices: [string, number][]
entries: [string, number][]
referrers: [string, number][]
topPages: [string, number][]
totals: {
/** Share of visits with a single page view, 0–1. */
bounceRate: number
/** Visits that carry a visitor id (analytics consent given). */
consented: number
views: number
visits: number
}
}
/** The last `count` calendar days in `timeZone`, oldest first. */
export function lastDays(count: number, timeZone: string, now = new Date()): string[] {
// today in the site's zone, then plain calendar arithmetic — DST can't skip or repeat a day
const [y, m, d] = dayOf(now, timeZone).split('-').map(Number)
const today = Date.UTC(y, m - 1, d)
return Array.from({ length: count }, (_, i) => new Date(today - (count - 1 - i) * 86_400_000).toISOString().slice(0, 10))
}
function top(counts: Map<string, number>, limit: number): [string, number][] {
return [...counts].sort((a, b) => b[1] - a[1] || a[0].localeCompare(b[0])).slice(0, limit)
}
function bump(map: Map<string, number>, key: string, by = 1) {
map.set(key, (map.get(key) ?? 0) + by)
}
/** Daily series and top lists from raw visits. */
export function summarize(visits: StatsVisit[], days: string[], limit = 10): StatsSummary {
const byDay = new Map(days.map((d) => [d, { day: d, views: 0, visits: 0 }]))
const pages = new Map<string, number>()
const entries = new Map<string, number>()
const referrers = new Map<string, number>()
const devices = new Map<string, number>()
let views = 0
let bounces = 0
let consented = 0
let counted = 0
for (const visit of visits) {
const bucket = byDay.get(visit.day)
if (!bucket) {continue}
counted++
bucket.visits++
bucket.views += visit.pageCount
views += visit.pageCount
if (visit.pageCount <= 1) {bounces++}
if (visit.visitorId) {consented++}
for (const page of visit.pages ?? []) {bump(pages, page.p)}
bump(entries, visit.entry)
bump(referrers, visit.referrer || '(direct)')
if (visit.device) {bump(devices, visit.device)}
}
return {
days: [...byDay.values()],
devices: top(devices, limit),
entries: top(entries, limit),
referrers: top(referrers, limit),
topPages: top(pages, limit),
totals: { bounceRate: counted ? bounces / counted : 0, consented, views, visits: counted },
}
}
+19
View File
@@ -0,0 +1,19 @@
import { createHash, randomBytes } from 'node:crypto'
/**
* Cookieless visit key: SHA-256 of a random salt + IP + user agent + host. The
* salt lives only in this process's memory and is replaced when the day
* changes — the old one is gone, so nobody (us included) can link a stored key
* back to an IP or to the same visitor on another day. Nothing is stored on
* the visitor's device, which is why this needs no consent.
*
* Trade-off: a restart or a second instance starts its own salt, so a visit in
* progress can split in two. Fine for statistics; never fixed by persisting the
* salt — that would make yesterday's keys reversible.
*/
let current: { day: string; salt: Buffer } | null = null
export function visitKey(day: string, parts: string[]): string {
if (!current || current.day !== day) {current = { day, salt: randomBytes(32) }}
return createHash('sha256').update(current.salt).update(parts.join('\n')).digest('hex').slice(0, 32)
}