Files
ipal-kit/test/stats.test.ts
T
Radosław SmolińskiandClaude Opus 5.5 4ec27d9ef0 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]>
2026-10-21 15:10:55 +02:00

201 lines
8.8 KiB
TypeScript

import type { Config, PayloadRequest } from 'payload'
import { describe, expect, test, vi } from 'vitest'
import type { I18nConfig } from '../src/modules/i18n/types.js'
import type { StatsVisit } from '../src/modules/stats/collection.js'
import { serializeConsent } from '../src/modules/consent/storage.js'
import { buildStatsEndpoint } from '../src/modules/stats/endpoint.js'
import { dayOf, deviceFromUa, isBot, referrerHost, sanitizePath } from '../src/modules/stats/parse.js'
import { lastDays, summarize } from '../src/modules/stats/summarize.js'
import { ipalKit } from '../src/plugin.js'
const CHROME = 'Mozilla/5.0 (Macintosh; Intel Mac OS X 10_15_7) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/130.0 Safari/537.36'
const VID = 'a'.repeat(32)
describe('stats — request parsing', () => {
test('drops query strings and hashes, rejects non-paths', () => {
expect(sanitizePath('/pl/[email protected]#form')).toBe('/pl/kontakt')
expect(sanitizePath('https://evil.com/')).toBeNull()
expect(sanitizePath('//evil.com')).toBeNull()
expect(sanitizePath('/<script>')).toBeNull()
expect(sanitizePath(42)).toBeNull()
})
test('referrer is reduced to an external hostname', () => {
expect(referrerHost('https://www.google.com/search?q=secret', 'acme.pl')).toBe('google.com')
expect(referrerHost('https://acme.pl/pl/oferta', 'www.acme.pl')).toBe('')
expect(referrerHost('not a url', 'acme.pl')).toBe('')
})
test('bots and devices', () => {
expect(isBot('Googlebot/2.1')).toBe(true)
expect(isBot('')).toBe(true)
expect(isBot(CHROME)).toBe(false)
expect(deviceFromUa('Mozilla/5.0 (iPhone; CPU iPhone OS 17_0) Mobile/15E148')).toBe('mobile')
expect(deviceFromUa('Mozilla/5.0 (iPad; CPU OS 17_0)')).toBe('tablet')
expect(deviceFromUa(CHROME)).toBe('desktop')
})
test('day follows the site time zone, not UTC', () => {
const lateEvening = new Date('2026-10-20T22:30:00Z') // 00:30 on the 21st in Warsaw (CEST)
expect(dayOf(lateEvening, 'UTC')).toBe('2026-10-20')
expect(dayOf(lateEvening, 'Europe/Warsaw')).toBe('2026-10-21')
})
})
describe('stats — summary', () => {
test('lastDays is contiguous across a DST change', () => {
const days = lastDays(30, 'Europe/Warsaw', new Date('2026-11-05T12:00:00Z'))
expect(days).toHaveLength(30)
expect(days[0]).toBe('2026-10-07')
expect(days.at(-1)).toBe('2026-11-05')
expect(new Set(days).size).toBe(30)
})
test('daily series, totals and top lists', () => {
const visit = (day: string, pages: string[], extra: Partial<StatsVisit> = {}): StatsVisit => ({
id: Math.random(),
day,
entry: pages[0],
exit: pages.at(-1)!,
lastAt: `${day}T10:00:00Z`,
pageCount: pages.length,
pages: pages.map((p) => ({ p, t: `${day}T10:00:00Z` })),
startedAt: `${day}T10:00:00Z`,
...extra,
})
const s = summarize(
[
visit('2026-10-20', ['/pl', '/pl/oferta'], { referrer: 'google.com', visitorId: VID }),
visit('2026-10-21', ['/pl']),
visit('2026-10-21', ['/pl/oferta', '/pl/kontakt', '/pl']),
visit('2026-09-01', ['/old']), // outside the range — ignored
],
['2026-10-20', '2026-10-21'],
)
expect(s.days).toEqual([
{ day: '2026-10-20', views: 2, visits: 1 },
{ day: '2026-10-21', views: 4, visits: 2 },
])
expect(s.totals).toEqual({ bounceRate: 1 / 3, consented: 1, views: 6, visits: 3 })
expect(s.topPages[0]).toEqual(['/pl', 3])
expect(s.referrers).toEqual([['(direct)', 2], ['google.com', 1]])
})
})
/** Endpoint against an in-memory stats-visits collection. */
function harness(policyVersion = 1) {
const docs: Record<string, unknown>[] = []
const payload = {
create: vi.fn(async ({ data }: { data: Record<string, unknown> }) => {
const doc = { id: docs.length + 1, ...data }
docs.push(doc)
return doc
}),
delete: vi.fn(async () => ({ docs: [] })),
find: vi.fn(async ({ where }: { where: { and: [{ visitKey: { equals: string } }, { lastAt: { greater_than: string } }] } }) => {
const [key, since] = [where.and[0].visitKey.equals, where.and[1].lastAt.greater_than]
return { docs: docs.filter((d) => d.visitKey === key && (d.lastAt as string) > since).reverse() }
}),
findGlobal: vi.fn(async () => ({ policyVersion })),
logger: { error: vi.fn() },
update: vi.fn(async ({ id, data }: { data: Record<string, unknown>; id: number }) => Object.assign(docs.find((d) => d.id === id)!, data)),
}
const endpoint = buildStatsEndpoint({ timeZone: 'UTC' })
const hit = (body: Record<string, unknown>, headers: Record<string, string> = {}, user: unknown = null) => {
const request = new Request('http://acme.pl/api/ipal/hit', {
body: JSON.stringify(body),
headers: { 'content-type': 'application/json', host: 'acme.pl', 'user-agent': CHROME, 'x-real-ip': '203.0.113.7', ...headers },
method: 'POST',
})
return endpoint.handler(Object.assign(request, { payload, user }) as unknown as PayloadRequest)
}
return { docs, hit }
}
describe('stats — hit endpoint', () => {
test('joins page views into one visit and stores no IP or user agent', async () => {
const { docs, hit } = harness()
expect((await hit({ l: 'pl', p: '/pl', r: 'https://www.google.com/' })).status).toBe(204)
await hit({ p: '/pl/oferta?utm_source=x' })
expect(docs).toHaveLength(1)
expect(docs[0]).toMatchObject({ entry: '/pl', exit: '/pl/oferta', locale: 'pl', pageCount: 2, referrer: 'google.com' })
const stored = JSON.stringify(docs[0])
expect(stored).not.toContain('203.0.113.7')
expect(stored).not.toContain('Chrome')
expect(docs[0].visitorId).toBeUndefined()
})
test('a different IP is a different visit', async () => {
const { docs, hit } = harness()
await hit({ p: '/pl' })
await hit({ p: '/pl' }, { 'x-real-ip': '198.51.100.1' })
expect(docs).toHaveLength(2)
})
test('visitor id is kept only when the consent cookie grants analytics', async () => {
const granted = serializeConsent({ analytics: true, functional: false, marketing: false, necessary: true }, 1)
const denied = serializeConsent({ analytics: false, functional: false, marketing: false, necessary: true }, 1)
const a = harness()
await a.hit({ p: '/pl', v: VID })
expect(a.docs[0].visitorId).toBeUndefined() // no cookie at all
const b = harness()
await b.hit({ p: '/pl', v: VID }, { cookie: `cookie-consent=${denied}` })
expect(b.docs[0].visitorId).toBeUndefined()
const d = harness()
await d.hit({ p: '/pl', v: VID }, { cookie: `other=1; cookie-consent=${granted}` })
expect(d.docs[0].visitorId).toBe(VID)
// consent given under policy v1, panel now at v2 → no longer valid (once the
// endpoint's one-minute policy cache has expired)
vi.useFakeTimers({ now: Date.now() + 61_000, toFake: ['Date'] })
try {
const c = harness(2)
await c.hit({ p: '/pl', v: VID }, { cookie: `cookie-consent=${granted}` })
expect(c.docs[0].visitorId).toBeUndefined()
} finally {
vi.useRealTimers()
}
})
test('bots, logged-in panel users and prefetches are not counted', async () => {
const { docs, hit } = harness()
await hit({ p: '/pl' }, { 'user-agent': 'Googlebot/2.1' })
await hit({ p: '/pl' }, {}, { id: 1 })
await hit({ p: '/pl' }, { 'sec-purpose': 'prefetch' })
await hit({ p: 'https://evil.com' })
expect(docs).toHaveLength(0)
})
})
describe('stats — plugin wiring', () => {
const base = () => ({ collections: [{ slug: 'users', auth: true, fields: [] }], secret: 'test' }) as unknown as Config
const i18n: I18nConfig = { defaultLocale: 'pl', locales: [{ code: 'pl', label: 'Polski' }] }
test('off by default', async () => {
const config = await ipalKit({ i18n, twoFactor: false })(base())
expect(config.collections?.some((c) => c.slug === 'stats-visits')).toBe(false)
expect(config.endpoints?.some((e) => e.path === '/ipal/hit')).toBe(false)
})
test('stats: true adds the collection, endpoint, view, nav link and dashboard card', async () => {
const config = await ipalKit({ adminRoute: '/its', i18n, stats: true, twoFactor: false })(base())
expect(config.collections?.some((c) => c.slug === 'stats-visits')).toBe(true)
expect(config.endpoints?.some((e) => e.path === '/ipal/hit' && e.method === 'post')).toBe(true)
const components = config.admin?.components
expect(components?.views?.ipalStats).toMatchObject({ path: '/stats' })
expect(JSON.stringify(components?.afterNavLinks)).toContain('StatsNavLink')
expect(JSON.stringify(components?.beforeDashboard)).toContain('"adminRoute":"/its"')
})
test('dashboard: false leaves the dashboard alone', async () => {
const config = await ipalKit({ i18n, stats: { dashboard: false }, twoFactor: false })(base())
expect(JSON.stringify(config.admin?.components?.beforeDashboard)).not.toContain('StatsWidget')
})
})