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
+44
View File
@@ -7,10 +7,12 @@ import { markdownHref, prefersMarkdown } from '../src/modules/content/markdownNe
import { lexicalToMarkdown } from '../src/modules/richtext/lexicalToMarkdown.js'
import { buildCsp } from '../src/modules/security/buildCsp.js'
import { buildSecurityHeaders } from '../src/modules/security/buildSecurityHeaders.js'
import { buildAutoFillMetaHook } from '../src/modules/seo/autoFillMeta.js'
import { AI_TRAINING_BOTS, buildRobots } from '../src/modules/seo/buildRobots.js'
import { buildSitemapXml } from '../src/modules/seo/buildSitemapXml.js'
import { createPageMetadata } from '../src/modules/seo/createPageMetadata.js'
import { buildHreflangAlternates } from '../src/modules/seo/hreflang.js'
import { describeFromMarkdown } from '../src/modules/seo/plainText.js'
const config: I18nConfig = {
defaultLocale: 'pl',
@@ -301,3 +303,45 @@ describe('buildProductJsonLd', () => {
})
})
})
describe('meta description auto-fill', () => {
const layout = [
{ blockType: 'hero', heading: 'Car detailing in Opole', subheading: 'For drivers who expect more' },
{ blockType: 'content', body: 'We apply Gtechniq ceramic coatings and correct paint. Every car gets a written report.' },
{ blockType: 'content', body: 'Book a free consultation — we will advise on the scope. Opening hours are listed on the contact page.' },
]
// the hook ignores everything but data and originalDoc
const run = (data: Record<string, unknown>, originalDoc?: Record<string, unknown>, mapping = {}) =>
buildAutoFillMetaHook(mapping)({ data, operation: originalDoc ? 'update' : 'create', originalDoc } as never) as Record<string, unknown>
test('describeFromMarkdown skips headings and keeps whole sentences', () => {
const md = '## Title\n\nFirst sentence here. Second one.\n\n### Sub\n\nThird part without a stop'
expect(describeFromMarkdown(md)).toBe('First sentence here. Second one. Third part without a stop.')
const long = describeFromMarkdown('One short sentence. ' + 'word '.repeat(60), 155)
expect(long).toBe('One short sentence.')
expect(describeFromMarkdown('## Only a heading')).toBe('Only a heading.')
expect(describeFromMarkdown('')).toBe('')
})
test('fills an empty description from the page blocks', () => {
const out = run({ layout, title: 'Detailing' })
const meta = out.meta as Record<string, string>
expect(meta.title).toBe('Detailing')
expect(meta.description).toBe(
'We apply Gtechniq ceramic coatings and correct paint. Every car gets a written report. Book a free consultation — we will advise on the scope.',
)
expect(meta.description.length).toBeLessThanOrEqual(155)
})
test('never replaces a description — typed now or already stored', () => {
expect((run({ layout, meta: { description: 'Mine' } }).meta as Record<string, string>).description).toBe('Mine')
// partial update: data carries only the layout, the stored doc has a description
const out = run({ layout }, { meta: { description: 'Stored', title: 'T' } })
expect(out.meta).toBeUndefined()
})
test('mapped description field wins; content: false turns the fallback off', () => {
expect((run({ excerpt: 'Excerpt text', layout }, undefined, { description: 'excerpt' }).meta as Record<string, string>).description).toBe('Excerpt text')
expect((run({ layout, title: 'T' }, undefined, { content: false }).meta as Record<string, string>).description).toBeUndefined()
})
})
+200
View File
@@ -0,0 +1,200 @@
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')
})
})