Cookie scanner, phase 2: browser crawl through a shared scanner service

cookieScanner.crawl (opt-in) adds "Crawl site" to the Cookie review box. The
site asks the shared scanner service (services/cookie-crawler: Node +
Playwright, Dockerfile, deployed once on Coolify) to crawl its sitemap pages
twice, with no consent and after "Accept all". The service posts cookies,
storage keys and third-party hosts back to POST /api/ipal/cookie-crawl/results
(bearer token, running job only). No browser in the site.

Findings land as drafts through the same merge rules. Anything stored before
consent that is not necessary, and tracker requests before consent, are
violations, flagged on the review entries from the latest crawl only. The
cookie-crawl global keeps the latest result (no history). A dashboard warning
(CookieCrawlAlert) and an opt-in e-mail through the project's mail adapter
follow a crawl with violations or new unknown cookies. Scheduled crawls: a
Coolify scheduled task with the token. ipalEnvRules({ cookieCrawl: true }).

Also: the six older real-Payload tests no longer leave an orphaned
payload generate:types process (typescript.autoGenerate: false).

Co-Authored-By: Claude Opus 5.5 <[email protected]>
This commit is contained in:
Radosław Smoliński
2026-10-27 15:14:01 +01:00
co-authored by Claude Opus 5.5
parent 4f69f6ed20
commit 4bb9c663fd
44 changed files with 2165 additions and 36 deletions
+1
View File
@@ -10,6 +10,7 @@ export { TestEmailButton } from '../globals/SiteIntegrations/components/TestEmai
export { RowLabel } from '../modules/admin-ui/RowLabelComponent.js'
export { AdminIcon, AdminLogo, IntecionCredit } from '../modules/branding/index.js'
export { CookieScanButton } from '../modules/consent/scanner/CookieScanButton.js'
export { CookieCrawlAlert } from '../modules/consent/scanner/crawl/CookieCrawlAlert.js'
export { IntegrationAlerts } from '../modules/integrations/IntegrationAlerts.js'
export { IntegrationStatusBanner } from '../modules/integrations/IntegrationStatusBanner.js'
export { MetaDescriptionCheck } from '../modules/seo/MetaDescriptionCheck.js'
+25
View File
@@ -54,39 +54,64 @@ export type { ConsentCategory, ConsentLogOptions, ConsentState, ConsentTexts, Co
export {
addToCookieList,
applyCookieFindings,
bearerMatches,
buildCookieCrawlEndpoints,
buildCookieCrawlGlobal,
buildCookieReviewCollection,
buildCookieScanEndpoints,
collectCookieFindings,
COOKIE_CRAWL_PATH,
COOKIE_CRAWL_RESULTS_PATH,
COOKIE_CRAWL_SLUG,
COOKIE_REVIEW_SLUG,
COOKIE_SCAN_LABELS,
COOKIE_SCAN_PATH,
COOKIE_SCAN_TOKEN_ENV,
COOKIE_SCAN_URL_ENV,
cookieNameMatches,
cookieScanContext,
DEFAULT_COOKIE_INTEGRATIONS,
DEFAULT_DATABASE_CATEGORIES,
DEFAULT_TRACKER_HOSTS,
findCrawlViolations,
finishCrawl,
GOOGLE_TAG_HOSTS,
indexCookieDatabase,
ingestCrawlResult,
loadCookieDatabase,
lookupCookie,
mergeCookieReview,
mergeCookieScanLabels,
parseCookieNames,
parseCrawlResult,
resolveCrawlConfig,
runCookieScan,
sendCrawlWarning,
suggestionFor,
} from './modules/consent/scanner/index.js'
export type {
CookieCrawlOptions,
CookieDatabaseIndex,
CookieDeclaration,
CookieFinding,
CookieFindingSource,
CookieIntegration,
CookieObservation,
CookieReviewEntryRef,
CookieReviewValues,
CookieScanContext,
CookieScanLabels,
CookieScannerOptions,
CookieScanSummary,
CookieStorage,
CrawlIngestSummary,
CrawlObservation,
CrawlRequest,
CrawlResult,
CrawlViolation,
LocalizedText,
OpenCookieCategory,
ResolvedCrawlConfig,
} from './modules/consent/scanner/index.js'
export { constructionNoticeHref, isPathAllowed, isPathVisibleIn } from './modules/construction/logic.js'
export type { ConstructionMode } from './modules/construction/types.js'
@@ -9,19 +9,34 @@ import type { CookieScanSummary } from './types.js'
import { COOKIE_SCAN_LABELS } from './labels.js'
type CrawlState = {
configured: boolean
error: null | string
finishedAt: null | string
missing: string[]
startedAt: null | string
status: 'done' | 'failed' | 'idle' | 'running'
summary: { newUnknown?: null | number; pages?: null | number; violations?: null | number } | null
}
type Status =
| { kind: 'done'; summary: CookieScanSummary }
| { kind: 'error' }
| { kind: 'idle' }
| { kind: 'scanning' }
const fill = (template: string, values: Record<string, null | number | string>) =>
template.replace(/\{(\w+)\}/g, (_, k: string) => String(values[k] ?? ''))
/**
* Admin UI above the Cookie review list (beforeListTable): shows which
* integrations a scan covers, takes optional extra cookie names, runs
* POST /api/ipal/cookie-scan and reloads the list. Labels in the admin language
* (`labels` from the collection config, English fallback).
* POST /api/ipal/cookie-scan and reloads the list. With `crawl`, also "Crawl
* site" (POST /api/ipal/cookie-crawl) and the latest crawl's status, polled
* while it runs. Labels in the admin language (`labels` from the collection
* config, English fallback).
*/
export function CookieScanButton({ labels = COOKIE_SCAN_LABELS }: { labels?: Record<string, CookieScanLabels> }) {
export function CookieScanButton({ crawl = false, labels = COOKIE_SCAN_LABELS }: { crawl?: boolean; labels?: Record<string, CookieScanLabels> }) {
const { i18n } = useTranslation()
const { config } = useConfig()
const router = useRouter()
@@ -30,6 +45,45 @@ export function CookieScanButton({ labels = COOKIE_SCAN_LABELS }: { labels?: Rec
const [names, setNames] = useState('')
const [integrations, setIntegrations] = useState<{ key: string; label: string }[] | null>(null)
const [status, setStatus] = useState<Status>({ kind: 'idle' })
const [crawlState, setCrawlState] = useState<CrawlState | null>(null)
const [crawlStarting, setCrawlStarting] = useState(false)
const crawlEndpoint = endpoint.replace(/cookie-scan$/, 'cookie-crawl')
const when = (iso: null | string) => (iso ? new Date(iso).toLocaleString(i18n.language) : '')
useEffect(() => {
if (!crawl) {return}
let stopped = false
let wasRunning = false
const poll = async () => {
try {
const res = await fetch(crawlEndpoint, { credentials: 'include' })
const data = res.ok ? ((await res.json()) as CrawlState) : null
if (stopped || !data) {return}
setCrawlState(data)
if (wasRunning && data.status !== 'running') {router.refresh()}
wasRunning = data.status === 'running'
} catch {
// offline — try again on the next tick
}
}
void poll()
const timer = setInterval(() => void poll(), 3000)
return () => {
stopped = true
clearInterval(timer)
}
}, [crawl, crawlEndpoint, router])
const startCrawl = async () => {
setCrawlStarting(true)
try {
await fetch(crawlEndpoint, { credentials: 'include', method: 'POST' })
const res = await fetch(crawlEndpoint, { credentials: 'include' })
if (res.ok) {setCrawlState((await res.json()) as CrawlState)}
} finally {
setCrawlStarting(false)
}
}
useEffect(() => {
fetch(endpoint, { credentials: 'include' })
@@ -93,6 +147,30 @@ export function CookieScanButton({ labels = COOKIE_SCAN_LABELS }: { labels?: Rec
<span role="alert" style={{ color: 'var(--theme-error-500, crimson)' }}>✗ {t.scanError}</span>
) : null}
</div>
{crawl ? (
<div data-ipal="cookie-crawl" style={{ borderTop: '1px solid var(--theme-elevation-150, #ddd)', marginTop: '1.25rem', paddingTop: '1rem' }}>
<p style={{ marginTop: 0 }}>{t.crawlIntro}</p>
<div style={{ alignItems: 'center', display: 'flex', flexWrap: 'wrap', gap: '1rem' }}>
<button
className="btn btn--style-secondary"
disabled={!crawlState?.configured || crawlState.status === 'running' || crawlStarting}
onClick={startCrawl}
style={{ margin: 0 }}
type="button"
>
{t.crawlButton}
</button>
<span role="status">
{crawlState && !crawlState.configured ? `${t.crawlNotConfigured} (${crawlState.missing.join(', ')})` : null}
{crawlState?.configured && crawlState.status === 'running' ? fill(t.crawlRunning, { startedAt: when(crawlState.startedAt) }) : null}
{crawlState?.configured && crawlState.status === 'done'
? fill(t.crawlDone, { finishedAt: when(crawlState.finishedAt), newUnknown: crawlState.summary?.newUnknown ?? 0, pages: crawlState.summary?.pages ?? 0, violations: crawlState.summary?.violations ?? 0 })
: null}
{crawlState?.configured && crawlState.status === 'failed' ? fill(t.crawlFailed, { error: crawlState.error ?? '' }) : null}
</span>
</div>
</div>
) : null}
</div>
)
}
+20 -3
View File
@@ -1,4 +1,4 @@
import type { CollectionAfterChangeHook, CollectionBeforeChangeHook, CollectionConfig } from 'payload'
import type { CollectionAfterChangeHook, CollectionBeforeChangeHook, CollectionConfig, Field } from 'payload'
import type { CookieReviewValues } from './merge.js'
import type { CookieScannerOptions } from './types.js'
@@ -64,6 +64,22 @@ function buildSyncHook(): CollectionAfterChangeHook {
export function buildCookieReviewCollection(options: CookieScannerOptions = {}): CollectionConfig {
const labels = mergeCookieScanLabels(options.labels)
const L = (key: keyof CookieScanLabels) => labelRecord(labels, key)
const crawl = Boolean(options.crawl)
// Only with `crawl`: what the latest browser crawl saw before consent (reset on every crawl).
const crawlFields: Field[] = crawl
? [
{
name: 'violation',
type: 'checkbox',
admin: { description: L('violationDescription'), position: 'sidebar', readOnly: true },
defaultValue: false,
index: true,
label: L('violation'),
},
{ name: 'violationDetail', type: 'text', admin: { position: 'sidebar', readOnly: true }, label: L('violationDetail') },
{ name: 'seenBeforeConsent', type: 'checkbox', admin: { position: 'sidebar', readOnly: true }, defaultValue: false, index: true, label: L('seenBeforeConsent') },
]
: []
return {
slug: COOKIE_REVIEW_SLUG,
access: {
@@ -75,9 +91,9 @@ export function buildCookieReviewCollection(options: CookieScannerOptions = {}):
},
admin: {
components: {
beforeListTable: [{ clientProps: { labels }, path: '@intecion/ipal-kit/admin#CookieScanButton' }],
beforeListTable: [{ clientProps: { crawl, labels }, path: '@intecion/ipal-kit/admin#CookieScanButton' }],
},
defaultColumns: ['name', 'vendor', 'category', 'status', 'source', 'listed'],
defaultColumns: ['name', 'vendor', 'category', 'status', 'source', 'listed', ...(crawl ? ['violation'] : [])],
description: L('collectionDescription'),
group: 'Settings',
listSearchableFields: ['name', 'vendor'],
@@ -163,6 +179,7 @@ export function buildCookieReviewCollection(options: CookieScannerOptions = {}):
label: L('listed'),
},
{ name: 'lastScannedAt', type: 'date', admin: { position: 'sidebar', readOnly: true }, label: L('lastScannedAt') },
...crawlFields,
// `storage:name`, one entry per cookie — what a rescan matches on.
{ name: 'key', type: 'text', admin: { hidden: true }, index: true, unique: true },
// The last scan's suggestion: a value still equal to it was not edited and may follow the next scan.
@@ -0,0 +1,68 @@
import type { Payload } from 'payload'
import type { CookieScanLabels } from '../labels.js'
import { COOKIE_REVIEW_SLUG } from '../collection.js'
import { COOKIE_SCAN_LABELS, labelFor } from '../labels.js'
import { COOKIE_CRAWL_SLUG } from './config.js'
type Props = {
adminRoute?: string
/** Injected by Payload into admin server components. */
i18n?: { language?: string }
labels?: Record<string, CookieScanLabels>
payload?: Payload
}
const fill = (template: string, values: Record<string, number | string>) =>
template.replace(/\{(\w+)\}/g, (_, k: string) => String(values[k] ?? ''))
/**
* Dashboard warning (beforeDashboard) after the latest cookie crawl found
* violations or new unknown cookies, or failed. Renders nothing otherwise and
* never throws.
*/
export async function CookieCrawlAlert({ adminRoute = '/admin', i18n, labels = COOKIE_SCAN_LABELS, payload }: Props) {
if (!payload) {return null}
let doc: { error?: null | string; status?: null | string; summary?: { newUnknown?: null | number; violations?: null | number } | null }
try {
doc = (await payload.findGlobal({ slug: COOKIE_CRAWL_SLUG as never, depth: 0 })) as typeof doc
} catch {
return null
}
const t = (key: keyof CookieScanLabels) => labelFor(labels, i18n?.language, key)
const violations = doc.summary?.violations ?? 0
const newUnknown = doc.summary?.newUnknown ?? 0
const failed = doc.status === 'failed'
if (!failed && !(doc.status === 'done' && (violations || newUnknown))) {return null}
const base = `${adminRoute.replace(/\/$/, '')}/collections/${COOKIE_REVIEW_SLUG}`
const href = violations ? `${base}?where[violation][equals]=true` : base
return (
<div
data-ipal="cookie-crawl-alert"
role="alert"
style={{
background: 'var(--theme-warning-50, rgba(255, 178, 36, 0.1))',
border: '1px solid var(--theme-warning-400, #ffb224)',
borderRadius: 4,
marginBottom: '1.5rem',
padding: '1rem 1.25rem',
}}
>
{failed ? (
<strong>{fill(t('alertFailed'), { error: doc.error ?? '' })}</strong>
) : (
<>
<strong>{fill(t('alertTitle'), { newUnknown, violations })}</strong>
<p style={{ margin: '0.5rem 0 0' }}>{t('alertBody')}</p>
</>
)}
<a href={href} style={{ display: 'inline-block', marginTop: '0.5rem' }}>
{t('alertLink')}
</a>
</div>
)
}
export default CookieCrawlAlert
@@ -0,0 +1,42 @@
import type { BasePayload } from 'payload'
import type { CookieCrawlOptions } from '../types.js'
import { DEFAULT_TRACKER_HOSTS } from './violations.js'
export const COOKIE_CRAWL_SLUG = 'cookie-crawl'
export const COOKIE_CRAWL_PATH = '/ipal/cookie-crawl'
export const COOKIE_CRAWL_RESULTS_PATH = '/ipal/cookie-crawl/results'
export const COOKIE_SCAN_URL_ENV = 'IPAL_COOKIE_SCAN_URL'
export const COOKIE_SCAN_TOKEN_ENV = 'IPAL_COOKIE_SCAN_TOKEN'
/** A crawl still "running" after this long is treated as lost (the service never called back). */
export const CRAWL_TIMEOUT_MS = 30 * 60_000
export type ResolvedCrawlConfig = {
acceptSelector: string
consentMode: 'advanced' | 'basic'
maxPages: number
/** Null when not configured — the panel says what is missing. */
serviceUrl: null | string
siteUrl: null | string
token: null | string
trackerHosts: string[]
}
const trimSlash = (v: string) => v.replace(/\/+$/, '')
/** Options + env + Payload config, read at call time (env can change between deploys, not between requests). */
export function resolveCrawlConfig(options: CookieCrawlOptions, payload: BasePayload): ResolvedCrawlConfig {
const serviceUrl = options.serviceUrl ?? process.env[COOKIE_SCAN_URL_ENV]?.trim()
const token = options.token ?? process.env[COOKIE_SCAN_TOKEN_ENV]?.trim()
const siteUrl = options.siteUrl ?? (payload.config.serverURL || process.env.NEXT_PUBLIC_SERVER_URL?.trim())
return {
acceptSelector: options.acceptSelector ?? '[data-ipal="accept"]',
consentMode: options.consentMode ?? 'advanced',
maxPages: Math.min(100, Math.max(0, Math.trunc(options.maxPages ?? 20))),
serviceUrl: serviceUrl && /^https?:\/\//.test(serviceUrl) ? trimSlash(serviceUrl) : null,
siteUrl: siteUrl && /^https?:\/\//.test(siteUrl) ? trimSlash(siteUrl) : null,
token: token && token.length >= 16 ? token : null,
trackerHosts: options.trackerHosts ? options.trackerHosts(DEFAULT_TRACKER_HOSTS) : DEFAULT_TRACKER_HOSTS,
}
}
@@ -0,0 +1,166 @@
import type { Endpoint, PayloadRequest } from 'payload'
import { createHash, randomBytes, timingSafeEqual } from 'node:crypto'
import type { CookieScanLabels } from '../labels.js'
import type { CookieCrawlOptions, CookieScanContext, CookieScannerOptions } from '../types.js'
import { userMeetsRole } from '../../../access/predicates.js'
import {
COOKIE_CRAWL_PATH,
COOKIE_CRAWL_RESULTS_PATH,
COOKIE_CRAWL_SLUG,
COOKIE_SCAN_TOKEN_ENV,
COOKIE_SCAN_URL_ENV,
CRAWL_TIMEOUT_MS,
resolveCrawlConfig,
} from './config.js'
import { finishCrawl, ingestCrawlResult } from './ingest.js'
import { parseCrawlResult } from './result.js'
type CrawlDoc = {
error?: null | string
finishedAt?: null | string
jobId?: null | string
startedAt?: null | string
startedBy?: null | string
status?: 'done' | 'failed' | 'idle' | 'running' | null
summary?: null | Record<string, null | number>
}
/** Constant-time comparison of a bearer token with the configured one. */
export function bearerMatches(header: null | string | undefined, token: null | string): boolean {
if (!token || !header?.startsWith('Bearer ')) {return false}
const a = createHash('sha256').update(header.slice(7).trim()).digest()
const b = createHash('sha256').update(token).digest()
return timingSafeEqual(a, b)
}
const isStale = (doc: CrawlDoc, now = Date.now()) =>
doc.status === 'running' && (!doc.startedAt || now - new Date(doc.startedAt).getTime() > CRAWL_TIMEOUT_MS)
/**
* GET /api/ipal/cookie-crawl → `{ configured, missing, status, startedAt, finishedAt, summary, error }`
* POST /api/ipal/cookie-crawl → asks the scanner service to crawl this site (editor, or the bearer token
* — for a Coolify scheduled task); `202`, `409` while one runs, `503` when not configured
* POST /api/ipal/cookie-crawl/results → the service's callback, bearer token only; refuses any job but the running one
*/
export function buildCookieCrawlEndpoints({
fetchImpl = fetch,
labels,
options,
plugin,
}: {
/** For tests. */
fetchImpl?: typeof fetch
labels: Record<string, CookieScanLabels>
options: CookieScannerOptions
plugin: CookieScanContext['plugin']
}): Endpoint[] {
const crawl: CookieCrawlOptions = typeof options.crawl === 'object' ? options.crawl : {}
const isStaff = async (req: PayloadRequest) =>
options.access ? Boolean(await options.access({ req })) : userMeetsRole(req, 'editor')
const read = async (req: PayloadRequest) =>
(await req.payload.findGlobal({ slug: COOKIE_CRAWL_SLUG as never, depth: 0, overrideAccess: true, req })) as CrawlDoc
const write = (req: PayloadRequest, data: Partial<CrawlDoc>) =>
req.payload.updateGlobal({ slug: COOKIE_CRAWL_SLUG as never, context: { ipalCookieScan: true }, data: data as never, depth: 0, overrideAccess: true, req })
return [
{
handler: async (req) => {
if (!(await isStaff(req))) {return Response.json({ ok: false }, { status: 403 })}
const config = resolveCrawlConfig(crawl, req.payload)
const doc = await read(req)
const stale = isStale(doc)
return Response.json({
configured: Boolean(config.serviceUrl && config.token && config.siteUrl),
error: stale ? 'Timed out — the scanner service never reported back.' : (doc.error ?? null),
finishedAt: doc.finishedAt ?? null,
missing: [
...(config.serviceUrl ? [] : [COOKIE_SCAN_URL_ENV]),
...(config.token ? [] : [COOKIE_SCAN_TOKEN_ENV]),
...(config.siteUrl ? [] : ['serverURL / NEXT_PUBLIC_SERVER_URL']),
],
ok: true,
startedAt: doc.startedAt ?? null,
status: stale ? 'failed' : (doc.status ?? 'idle'),
summary: doc.summary ?? null,
})
},
method: 'get',
path: COOKIE_CRAWL_PATH,
},
{
handler: async (req) => {
const config = resolveCrawlConfig(crawl, req.payload)
const byToken = bearerMatches(req.headers.get('authorization'), config.token)
if (!byToken && !(await isStaff(req))) {return Response.json({ ok: false }, { status: 403 })}
if (!config.serviceUrl || !config.token || !config.siteUrl) {
return Response.json({ error: 'not_configured', ok: false }, { status: 503 })
}
const doc = await read(req)
if (doc.status === 'running' && !isStale(doc)) {return Response.json({ error: 'running', ok: false }, { status: 409 })}
const jobId = randomBytes(16).toString('hex')
const user = req.user as { email?: string } | null | undefined
await write(req, { error: null, finishedAt: null, jobId, startedAt: new Date().toISOString(), startedBy: byToken ? 'schedule' : (user?.email ?? 'editor'), status: 'running' })
const api = req.payload.config.routes?.api ?? '/api'
try {
const res = await fetchImpl(`${config.serviceUrl}/crawl`, {
body: JSON.stringify({
acceptSelector: config.acceptSelector,
callbackUrl: `${config.siteUrl}${api}${COOKIE_CRAWL_RESULTS_PATH}`,
jobId,
maxPages: config.maxPages,
siteUrl: config.siteUrl,
}),
headers: { Authorization: `Bearer ${config.token}`, 'Content-Type': 'application/json' },
method: 'POST',
signal: AbortSignal.timeout(15_000),
})
if (!res.ok) {throw new Error(`scanner service answered HTTP ${res.status}`)}
} catch (err) {
const message = err instanceof Error ? err.message : String(err)
req.payload.logger.error(`[ipal] cookie crawl: could not start — ${message}`)
await write(req, { error: `Could not reach the scanner service: ${message}`, finishedAt: new Date().toISOString(), jobId: null, status: 'failed' })
return Response.json({ error: 'service_unreachable', ok: false }, { status: 502 })
}
return Response.json({ ok: true, status: 'running' }, { status: 202 })
},
method: 'post',
path: COOKIE_CRAWL_PATH,
},
{
handler: async (req) => {
const config = resolveCrawlConfig(crawl, req.payload)
if (!bearerMatches(req.headers.get('authorization'), config.token)) {return Response.json({ ok: false }, { status: 401 })}
let body: unknown
try {
body = await (req as unknown as Request).json()
} catch {
return Response.json({ ok: false }, { status: 400 })
}
const result = parseCrawlResult(body)
if (!result) {return Response.json({ ok: false }, { status: 400 })}
const doc = await read(req)
if (doc.status !== 'running' || !doc.jobId || doc.jobId !== result.jobId) {
return Response.json({ error: 'unknown_job', ok: false }, { status: 409 })
}
try {
const summary = result.ok
? await ingestCrawlResult({ config, labels, options, payload: req.payload, plugin, req, result })
: undefined
await finishCrawl({ labels, payload: req.payload, req, result, siteUrl: config.siteUrl, summary })
return Response.json({ ok: true })
} catch (err) {
const message = err instanceof Error ? err.message : String(err)
req.payload.logger.error(`[ipal] cookie crawl: saving the result failed — ${message}`)
await write(req, { error: `Saving the result failed: ${message}`, finishedAt: new Date().toISOString(), jobId: null, status: 'failed' })
return Response.json({ ok: false }, { status: 500 })
}
},
method: 'post',
path: COOKIE_CRAWL_RESULTS_PATH,
},
]
}
@@ -0,0 +1,73 @@
import type { GlobalConfig } from 'payload'
import type { CookieScanLabels } from '../labels.js'
import { userMeetsRole } from '../../../access/predicates.js'
import { labelRecord } from '../labels.js'
import { COOKIE_CRAWL_SLUG } from './config.js'
/**
* The latest crawl only (no history): status, counts, violations, third-party
* hosts, and the e-mail recipients for warnings (the only editable field —
* opt-in per site). Written by the crawl endpoints through the Local API.
*/
export function buildCookieCrawlGlobal(labels: Record<string, CookieScanLabels>): GlobalConfig {
const L = (key: keyof CookieScanLabels) => labelRecord(labels, key)
const ro = { readOnly: true }
return {
slug: COOKIE_CRAWL_SLUG,
access: {
read: ({ req }) => userMeetsRole(req, 'editor'),
update: ({ req }) => userMeetsRole(req, 'admin'),
},
admin: { description: L('crawlGlobalDescription'), group: 'Settings' },
fields: [
{
name: 'notifyEmails',
type: 'text',
admin: { description: L('notifyEmailsDescription') },
label: L('notifyEmails'),
validate: (value: null | string | undefined) => {
const list = (value ?? '').split(',').map((v) => v.trim()).filter(Boolean)
return list.every((v) => /^[^\s@]+@[^\s@][^\s.@]*\.[^\s@]+$/.test(v)) || 'Comma-separated e-mail addresses.'
},
},
{
name: 'status',
type: 'select',
admin: { ...ro, position: 'sidebar' },
defaultValue: 'idle',
label: L('crawlStatus'),
options: [
{ label: L('crawlIdle'), value: 'idle' },
{ label: L('crawlStateRunning'), value: 'running' },
{ label: L('crawlStateDone'), value: 'done' },
{ label: L('crawlStateFailed'), value: 'failed' },
],
},
{ name: 'startedAt', type: 'date', admin: { ...ro, date: { pickerAppearance: 'dayAndTime' }, position: 'sidebar' }, label: L('startedAt') },
{ name: 'finishedAt', type: 'date', admin: { ...ro, date: { pickerAppearance: 'dayAndTime' }, position: 'sidebar' }, label: L('finishedAt') },
{ name: 'startedBy', type: 'text', admin: { ...ro, position: 'sidebar' }, label: L('startedBy') },
{ name: 'error', type: 'textarea', admin: ro, label: L('crawlError') },
{
name: 'summary',
type: 'group',
admin: ro,
fields: [
{ name: 'pages', type: 'number', admin: ro, label: L('crawlPages') },
{ name: 'violations', type: 'number', admin: ro, label: L('crawlViolations') },
{ name: 'newUnknown', type: 'number', admin: ro, label: L('unknown') },
{ name: 'created', type: 'number', admin: ro },
{ name: 'updated', type: 'number', admin: ro },
],
label: false,
},
{ name: 'violations', type: 'json', admin: ro, label: L('crawlViolations') },
{ name: 'requests', type: 'json', admin: ro, label: L('crawlRequests') },
{ name: 'pages', type: 'json', admin: ro, label: L('crawlPages') },
// One-time id of the running crawl; a result with another id is refused.
{ name: 'jobId', type: 'text', admin: { hidden: true } },
],
label: L('crawlGlobal'),
}
}
+156
View File
@@ -0,0 +1,156 @@
import type { BasePayload, PayloadRequest } from 'payload'
import type { CookieScanLabels } from '../labels.js'
import type { CookieReviewEntryRef } from '../scan.js'
import type { CookieScanContext, CookieScannerOptions, CookieScanSummary } from '../types.js'
import type { ResolvedCrawlConfig } from './config.js'
import type { CrawlResult } from './result.js'
import type { CrawlViolation } from './violations.js'
import { COOKIE_REVIEW_SLUG } from '../collection.js'
import { DEFAULT_COOKIE_INTEGRATIONS } from '../integrations.js'
import { labelFor } from '../labels.js'
import { applyCookieFindings, collectCookieFindings, cookieScanContext } from '../scan.js'
import { COOKIE_CRAWL_SLUG } from './config.js'
import { sendCrawlWarning } from './notify.js'
import { findCrawlViolations } from './violations.js'
export type CrawlIngestSummary = { pages: number; violations: CrawlViolation[] } & CookieScanSummary
const fill = (template: string, values: Record<string, number | string>) =>
template.replace(/\{(\w+)\}/g, (_, k: string) => String(values[k] ?? ''))
/**
* Applies a crawl result: every cookie and storage key seen becomes (or
* updates) a draft through the same rules as "Scan cookies"; entries seen
* before consent get `seenBeforeConsent`, and those not `necessary` get
* `violation`. Flags from the previous crawl are cleared first — only the
* latest crawl counts. Status is never changed and nothing is deleted.
*/
export async function ingestCrawlResult({
config,
labels,
options,
payload,
plugin,
req,
result,
}: {
config: Pick<ResolvedCrawlConfig, 'consentMode' | 'trackerHosts'>
labels: Record<string, CookieScanLabels>
options: CookieScannerOptions
payload: BasePayload
plugin: CookieScanContext['plugin']
req?: PayloadRequest
result: Extract<CrawlResult, { ok: true }>
}): Promise<CrawlIngestSummary> {
const lang = payload.config.i18n?.fallbackLanguage
const common = { collection: COOKIE_REVIEW_SLUG as never, context: { ipalCookieScan: true }, depth: 0, overrideAccess: true, req }
await payload.update({
...common,
data: { seenBeforeConsent: false, violation: false, violationDetail: null } as never,
where: { or: [{ violation: { equals: true } }, { seenBeforeConsent: { equals: true } }] },
})
const ctx = await cookieScanContext(payload, plugin, req)
const { findings, matches } = await collectCookieFindings({
ctx,
database: options.database !== false,
databaseCategories: options.databaseCategories,
declarations: options.declarations,
integrations: options.integrations ? options.integrations(DEFAULT_COOKIE_INTEGRATIONS) : DEFAULT_COOKIE_INTEGRATIONS,
names: result.observations.map((o) => ({ name: o.name, domain: o.domain, storage: o.storage })),
})
// Only what the browser saw — declarations of integrations it did not see are not part of a crawl.
const seenKeys = new Set(result.observations.map((o) => matches.get(`${o.storage}:${o.name}`)).filter(Boolean))
const entries = new Map<string, CookieReviewEntryRef>()
const summary = await applyCookieFindings({
entries,
findings: findings.filter((f) => seenKeys.has(`${f.storage}:${f.name}`)),
payload,
req,
})
const keyOf = (o: { name: string; storage: string }) => matches.get(`${o.storage}:${o.name}`)
const violations = findCrawlViolations({
categoryOf: (o) => entries.get(keyOf(o) ?? '')?.category,
consentMode: config.consentMode,
observations: result.observations,
requests: result.requests,
trackerHosts: config.trackerHosts,
})
// Flag the review entries (one update per entry, pages merged).
const flagged = new Map<string, { pages: Set<string>; violation: boolean }>()
for (const o of result.observations.filter((x) => x.before)) {
const key = keyOf(o)
if (!key || !entries.has(key)) {continue}
const f = flagged.get(key) ?? { pages: new Set<string>(), violation: false }
o.pages.forEach((p) => f.pages.add(p))
if (violations.some((v) => v.kind === o.storage && v.name === o.name)) {f.violation = true}
flagged.set(key, f)
}
for (const [key, f] of flagged) {
const pages = [...f.pages].slice(0, 5).join(', ')
await payload.update({
...common,
id: entries.get(key)!.id,
data: {
seenBeforeConsent: true,
violation: f.violation,
violationDetail: f.violation ? fill(labelFor(labels, lang, 'beforeConsentOn'), { pages }) : null,
} as never,
})
}
return { ...summary, pages: result.pages.length, violations }
}
/** Writes the finished crawl into the `cookie-crawl` global and sends the e-mail warning when asked for. */
export async function finishCrawl({
labels,
payload,
req,
result,
siteUrl,
summary,
}: {
labels: Record<string, CookieScanLabels>
payload: BasePayload
req?: PayloadRequest
result: CrawlResult
siteUrl?: null | string
summary?: CrawlIngestSummary
}): Promise<void> {
const now = new Date().toISOString()
const common = { slug: COOKIE_CRAWL_SLUG as never, context: { ipalCookieScan: true }, depth: 0, overrideAccess: true, req }
if (!result.ok || !summary) {
await payload.updateGlobal({ ...common, data: { error: result.ok ? 'No result' : result.error, finishedAt: now, jobId: null, status: 'failed' } as never })
return
}
const doc = (await payload.updateGlobal({
...common,
data: {
// Not a failure, but the "after accept" half saw no consent — say so where the editor looks.
error: result.accepted ? null : 'The "Accept all" button was not found (acceptSelector), so the second run had no consent.',
finishedAt: now,
jobId: null,
pages: result.pages,
requests: result.requests.filter((r) => r.before || r.after).map(({ after, before, host }) => ({ after, before, host })),
status: 'done',
summary: {
created: summary.created,
newUnknown: summary.newUnknown,
pages: summary.pages,
updated: summary.updated,
violations: summary.violations.length,
},
violations: summary.violations,
} as never,
})) as { notifyEmails?: null | string }
const to = (doc.notifyEmails ?? '').split(',').map((v) => v.trim()).filter(Boolean)
if (to.length && (summary.violations.length || summary.newUnknown)) {
await sendCrawlWarning({ labels, payload, siteUrl: siteUrl ?? '', summary, to })
}
}
@@ -0,0 +1,52 @@
import type { BasePayload } from 'payload'
import type { CookieScanLabels } from '../labels.js'
import type { CrawlIngestSummary } from './ingest.js'
import { COOKIE_REVIEW_SLUG } from '../collection.js'
import { labelFor } from '../labels.js'
const esc = (v: string) => v.replace(/[&<>"']/g, (c) => `&#${c.charCodeAt(0)};`)
const fill = (template: string, values: Record<string, number | string>) =>
template.replace(/\{(\w+)\}/g, (_, k: string) => String(values[k] ?? ''))
/**
* E-mail warning after a crawl, through the project's Payload email adapter
* (`email: mailAdapter()` — the plugin's mail setup). Never throws: a failed
* send is logged and the crawl result stays saved.
*/
export async function sendCrawlWarning({
labels,
payload,
siteUrl,
summary,
to,
}: {
labels: Record<string, CookieScanLabels>
payload: BasePayload
siteUrl: string
summary: CrawlIngestSummary
to: string[]
}): Promise<boolean> {
const lang = payload.config.i18n?.fallbackLanguage
const t = (key: keyof CookieScanLabels) => labelFor(labels, lang, key)
const site = siteUrl.replace(/^https?:\/\//, '') || 'site'
const values = { newUnknown: summary.newUnknown, site, violations: summary.violations.length }
const adminUrl = `${siteUrl}${payload.config.routes?.admin ?? '/admin'}/collections/${COOKIE_REVIEW_SLUG}`
const items = summary.violations
.slice(0, 30)
.map((v) => `<li><code>${esc(v.name)}</code> (${esc(v.kind)}${v.category ? `, ${esc(v.category)}` : ''}) — ${esc(fill(t('beforeConsentOn'), { pages: v.pages.join(', ') }))}</li>`)
.join('')
const html = `<p>${esc(fill(t('emailIntro'), values))}</p>
<p><strong>${esc(fill(t('alertTitle'), values))}</strong></p>
${items ? `<ul>${items}</ul>` : ''}
<p>${esc(t('alertBody'))}</p>
<p><a href="${esc(adminUrl)}">${esc(t('alertLink'))}</a></p>`
try {
await payload.sendEmail({ html, subject: fill(t('emailSubject'), values), to })
return true
} catch (err) {
payload.logger.error(`[ipal] cookie crawl warning e-mail failed: ${err instanceof Error ? err.message : String(err)}`)
return false
}
}
@@ -0,0 +1,77 @@
import type { CookieStorage } from '../types.js'
/**
* What the scanner service sends back to the site (POST
* /api/ipal/cookie-crawl/results). The service lives in
* services/cookie-crawler; keep both sides in step.
*/
export type CrawlObservation = {
/** Set on the "after accept all" run. */
after: boolean
/** Set on the run with no consent. */
before: boolean
/** Cookie domain without the leading dot; omitted for storage keys. */
domain?: string
name: string
/** Paths where it was first seen (max 5). */
pages: string[]
storage: CookieStorage
}
export type CrawlRequest = { after: boolean; before: boolean; host: string; pages: string[] }
export type CrawlResult =
| {
/** False when the "Accept all" button was not found — the second run had no consent. */
accepted: boolean
jobId: string
observations: CrawlObservation[]
ok: true
pages: string[]
requests: CrawlRequest[]
}
| { error: string; jobId: string; ok: false }
const STORAGES = new Set<CookieStorage>(['cookie', 'localStorage', 'sessionStorage'])
const NAME = /^[^\s;,=]{1,200}$/
const HOST = /^(?=.{1,253}$)[a-z0-9-]+(?:\.[a-z0-9-]+)*$/i
const MAX_ITEMS = 2000
const MAX_PAGES = 200
const pathList = (v: unknown, max: number) =>
(Array.isArray(v) ? v : []).filter((p): p is string => typeof p === 'string' && p.length <= 2000).slice(0, max)
/** Validates the service's JSON. Anything malformed is dropped, not trusted; null = unusable. */
export function parseCrawlResult(body: unknown): CrawlResult | null {
if (!body || typeof body !== 'object') {return null}
const b = body as Record<string, unknown>
if (typeof b.jobId !== 'string' || !/^[0-9a-f]{16,64}$/.test(b.jobId)) {return null}
if (b.ok === false) {
return { error: typeof b.error === 'string' ? b.error.slice(0, 500) : 'Crawl failed', jobId: b.jobId, ok: false }
}
if (b.ok !== true) {return null}
const observations: CrawlObservation[] = []
for (const o of (Array.isArray(b.observations) ? b.observations : []).slice(0, MAX_ITEMS)) {
if (!o || typeof o !== 'object') {continue}
const x = o as Record<string, unknown>
const storage = x.storage as CookieStorage
if (typeof x.name !== 'string' || !NAME.test(x.name) || !STORAGES.has(storage)) {continue}
const domain = typeof x.domain === 'string' ? x.domain.replace(/^\./, '').toLowerCase() : ''
observations.push({
after: x.after === true,
before: x.before === true,
...(domain && HOST.test(domain) ? { domain } : {}),
name: x.name,
pages: pathList(x.pages, 5),
storage,
})
}
const requests: CrawlRequest[] = []
for (const r of (Array.isArray(b.requests) ? b.requests : []).slice(0, MAX_ITEMS)) {
if (!r || typeof r !== 'object') {continue}
const x = r as Record<string, unknown>
if (typeof x.host !== 'string' || !HOST.test(x.host)) {continue}
requests.push({ after: x.after === true, before: x.before === true, host: x.host.toLowerCase(), pages: pathList(x.pages, 5) })
}
return { accepted: b.accepted !== false, jobId: b.jobId, observations, ok: true, pages: pathList(b.pages, MAX_PAGES), requests }
}
@@ -0,0 +1,71 @@
import type { CookieStorage } from '../types.js'
import type { CrawlObservation, CrawlRequest } from './result.js'
/**
* Hosts whose requests before consent are a violation. Google's tag hosts are
* separate: with Consent Mode `advanced` (the plugin's default) the Google tag
* loads before consent with every signal denied, which is allowed; with
* `basic` nothing may reach Google before consent.
*/
export const DEFAULT_TRACKER_HOSTS = [
'analytics.tiktok.com',
'bat.bing.com',
'clarity.ms',
'connect.facebook.net',
'facebook.com',
'hotjar.com',
'licdn.com',
'linkedin.com',
'youtube.com',
]
export const GOOGLE_TAG_HOSTS = [
'doubleclick.net',
'google-analytics.com',
'googleadservices.com',
'googlesyndication.com',
'googletagmanager.com',
]
export type CrawlViolation = {
/** Consent category of the cookie or key (null = not classified yet). */
category?: null | string
kind: 'request' | CookieStorage
/** Cookie / key name, or the host for a request. */
name: string
pages: string[]
}
const hostMatches = (host: string, list: string[]) => list.some((h) => host === h || host.endsWith(`.${h}`))
/**
* Violations of one crawl: anything stored before consent whose category is not
* `necessary` (unclassified counts — the editor decides), and requests before
* consent to tracker hosts. `categoryOf` gives the review entry's category after
* the scan merged it (an editor's category wins).
*/
export function findCrawlViolations({
categoryOf,
consentMode = 'advanced',
observations,
requests,
trackerHosts = DEFAULT_TRACKER_HOSTS,
}: {
categoryOf: (o: CrawlObservation) => null | string | undefined
consentMode?: 'advanced' | 'basic'
observations: CrawlObservation[]
requests: CrawlRequest[]
trackerHosts?: string[]
}): CrawlViolation[] {
const out: CrawlViolation[] = []
for (const o of observations) {
if (!o.before) {continue}
const category = categoryOf(o) ?? null
if (category !== 'necessary') {out.push({ name: o.name, category, kind: o.storage, pages: o.pages })}
}
const hosts = consentMode === 'basic' ? [...trackerHosts, ...GOOGLE_TAG_HOSTS] : trackerHosts
for (const r of requests) {
if (r.before && hostMatches(r.host, hosts)) {out.push({ name: r.host, kind: 'request', pages: r.pages })}
}
return out
}
+20
View File
@@ -2,6 +2,24 @@
export { buildCookieReviewCollection, COOKIE_REVIEW_SLUG } from './collection.js'
export { DEFAULT_DATABASE_CATEGORIES, indexCookieDatabase, loadCookieDatabase, lookupCookie } from './cookieDatabase.js'
export type { CookieDatabaseIndex } from './cookieDatabase.js'
export {
COOKIE_CRAWL_PATH,
COOKIE_CRAWL_RESULTS_PATH,
COOKIE_CRAWL_SLUG,
COOKIE_SCAN_TOKEN_ENV,
COOKIE_SCAN_URL_ENV,
resolveCrawlConfig,
} from './crawl/config.js'
export type { ResolvedCrawlConfig } from './crawl/config.js'
export { bearerMatches, buildCookieCrawlEndpoints } from './crawl/endpoints.js'
export { buildCookieCrawlGlobal } from './crawl/global.js'
export { finishCrawl, ingestCrawlResult } from './crawl/ingest.js'
export type { CrawlIngestSummary } from './crawl/ingest.js'
export { sendCrawlWarning } from './crawl/notify.js'
export { parseCrawlResult } from './crawl/result.js'
export type { CrawlObservation, CrawlRequest, CrawlResult } from './crawl/result.js'
export { DEFAULT_TRACKER_HOSTS, findCrawlViolations, GOOGLE_TAG_HOSTS } from './crawl/violations.js'
export type { CrawlViolation } from './crawl/violations.js'
export { buildCookieScanEndpoints, COOKIE_SCAN_PATH } from './endpoint.js'
export { cookieNameMatches, DEFAULT_COOKIE_INTEGRATIONS } from './integrations.js'
export { COOKIE_SCAN_LABELS, mergeCookieScanLabels } from './labels.js'
@@ -9,8 +27,10 @@ export type { CookieScanLabels } from './labels.js'
export { mergeCookieReview, suggestionFor } from './merge.js'
export type { CookieReviewValues } from './merge.js'
export { applyCookieFindings, collectCookieFindings, cookieScanContext, parseCookieNames, runCookieScan } from './scan.js'
export type { CookieObservation, CookieReviewEntryRef } from './scan.js'
export { addToCookieList } from './sync.js'
export type {
CookieCrawlOptions,
CookieDeclaration,
CookieFinding,
CookieFindingSource,
+99
View File
@@ -5,14 +5,39 @@
*/
export type CookieScanLabels = {
accepted: string
alertBody: string
alertFailed: string
alertLink: string
alertTitle: string
analytics: string
beforeConsentOn: string
category: string
categoryRequired: string
collectionDescription: string
cookie: string
crawlButton: string
crawlDone: string
crawlError: string
crawlFailed: string
crawlGlobal: string
crawlGlobalDescription: string
crawlIdle: string
crawlIntro: string
crawlNotConfigured: string
crawlPages: string
crawlRequests: string
crawlRunning: string
crawlStateDone: string
crawlStateFailed: string
crawlStateRunning: string
crawlStatus: string
crawlViolations: string
database: string
domain: string
draft: string
emailIntro: string
emailSubject: string
finishedAt: string
functional: string
integration: string
integrationsFound: string
@@ -27,6 +52,8 @@ export type CookieScanLabels = {
namesHint: string
namesLabel: string
necessary: string
notifyEmails: string
notifyEmailsDescription: string
plural: string
project: string
purpose: string
@@ -38,32 +65,63 @@ export type CookieScanLabels = {
scanning: string
/** `{created}`, `{updated}`, `{unchanged}`, `{unknown}` are filled in. */
scanResult: string
seenBeforeConsent: string
sessionStorage: string
setBeforeConsent: string
setBeforeConsentDescription: string
singular: string
source: string
sourceDetail: string
startedAt: string
startedBy: string
status: string
statusDescription: string
storage: string
unknown: string
vendor: string
violation: string
violationDescription: string
violationDetail: string
}
export const COOKIE_SCAN_LABELS: Record<'en' | 'pl', CookieScanLabels> = {
en: {
name: 'Name',
accepted: 'Accepted',
alertBody: 'Non-necessary cookies or trackers load before consent, or the site sets cookies nobody has described yet. Check the review list.',
alertFailed: 'Cookie crawl failed: {error}',
alertLink: 'Open Cookie review →',
alertTitle: 'Cookie crawl: {violations} violations, {newUnknown} new unknown cookies.',
analytics: 'Analytics',
beforeConsentOn: 'before consent on {pages}',
category: 'Category',
categoryRequired: 'Pick a category before accepting.',
collectionDescription:
'Cookies found by "Scan cookies". Check each draft, then set it to Accepted (it is added to Cookie Settings → Cookies) or Rejected. A scan never deletes entries and never changes text you edited.',
cookie: 'Cookie',
crawlButton: 'Crawl site',
crawlDone: 'Last crawl {finishedAt}: {pages} pages, {violations} violations, {newUnknown} new unknown.',
crawlError: 'Error',
crawlFailed: 'The last crawl failed: {error}',
crawlGlobal: 'Cookie crawl',
crawlGlobalDescription: 'The latest browser crawl only. Start one from Cookie review → Crawl site.',
crawlIdle: 'Never run',
crawlIntro: 'Opens the site in a browser twice — without consent and after "Accept all" — and records cookies, storage and third-party requests. New findings become drafts.',
crawlNotConfigured: 'The crawl needs IPAL_COOKIE_SCAN_URL and IPAL_COOKIE_SCAN_TOKEN on the server.',
crawlPages: 'Pages crawled',
crawlRequests: 'Third-party requests',
crawlRunning: 'Crawling… started {startedAt}.',
crawlStateDone: 'Done',
crawlStateFailed: 'Failed',
crawlStateRunning: 'Running',
crawlStatus: 'Status',
crawlViolations: 'Violations',
database: 'Open Cookie Database',
domain: 'Domain',
draft: 'Draft',
emailIntro: 'The latest cookie crawl of {site} found:',
emailSubject: 'Cookie crawl of {site}: {violations} violations, {newUnknown} new unknown',
finishedAt: 'Finished',
functional: 'Functional',
integration: 'Plugin integration',
integrationsFound: 'Integrations in use',
@@ -77,6 +135,8 @@ export const COOKIE_SCAN_LABELS: Record<'en' | 'pl', CookieScanLabels> = {
namesHint: 'Optional: cookie names seen in the browser (DevTools → Application → Cookies), one per line. They are looked up in the plugin and the Open Cookie Database.',
namesLabel: 'More cookie names',
necessary: 'Necessary',
notifyEmails: 'E-mail warnings to',
notifyEmailsDescription: 'Comma-separated addresses. After a crawl with violations or new unknown cookies, a warning is sent through the site\'s mail setup. Empty = no e-mail.',
plural: 'Cookie review',
project: 'Project declaration',
purpose: 'Purpose',
@@ -87,30 +147,61 @@ export const COOKIE_SCAN_LABELS: Record<'en' | 'pl', CookieScanLabels> = {
scanIntro: 'Lists the cookies of the integrations switched on in this project as drafts to review.',
scanning: 'Scanning…',
scanResult: '{created} new, {updated} updated, {unchanged} unchanged, {unknown} unknown.',
seenBeforeConsent: 'Seen before consent',
sessionStorage: 'Session storage',
setBeforeConsent: 'Set before consent',
setBeforeConsentDescription: 'May be set before the visitor decides. Only necessary cookies should be.',
singular: 'Cookie review entry',
source: 'Found by',
sourceDetail: 'Source',
startedAt: 'Started',
startedBy: 'Started by',
status: 'Status',
statusDescription: 'Accepted → added to Cookie Settings → Cookies. Rejecting never removes a row from that list.',
storage: 'Stored in',
unknown: 'Unknown — fill in',
vendor: 'Provider',
violation: 'Violation',
violationDescription: 'Seen before consent in the latest crawl and not necessary.',
violationDetail: 'Violation details',
},
pl: {
name: 'Nazwa',
accepted: 'Zaakceptowany',
alertBody: 'Cookies lub skrypty śledzące, które nie są niezbędne, ładują się przed zgodą — albo strona ustawia cookies, których nikt jeszcze nie opisał. Sprawdź listę przeglądu.',
alertFailed: 'Skan cookies się nie powiódł: {error}',
alertLink: 'Otwórz Przegląd cookies →',
alertTitle: 'Skan cookies: naruszeń {violations}, nowych nieznanych cookies {newUnknown}.',
analytics: 'Analityczne',
beforeConsentOn: 'przed zgodą na {pages}',
category: 'Kategoria',
categoryRequired: 'Wybierz kategorię przed akceptacją.',
collectionDescription:
'Pliki cookie znalezione przez „Skanuj cookies”. Sprawdź każdy szkic i ustaw Zaakceptowany (trafi do Ustawień cookies → Cookies) albo Odrzucony. Skan nigdy nie usuwa wpisów ani nie zmienia poprawionych przez Ciebie tekstów.',
cookie: 'Cookie',
crawlButton: 'Przeskanuj stronę',
crawlDone: 'Ostatni skan {finishedAt}: stron {pages}, naruszeń {violations}, nowych nieznanych {newUnknown}.',
crawlError: 'Błąd',
crawlFailed: 'Ostatni skan się nie powiódł: {error}',
crawlGlobal: 'Skan cookies przeglądarką',
crawlGlobalDescription: 'Tylko ostatni skan przeglądarką. Uruchom go w Przeglądzie cookies → Przeskanuj stronę.',
crawlIdle: 'Nie uruchamiano',
crawlIntro: 'Otwiera stronę w przeglądarce dwa razy — bez zgody i po „Akceptuj wszystkie” — i zapisuje cookies, pamięć przeglądarki i zapytania do zewnętrznych serwisów. Nowe znaleziska trafiają jako szkice.',
crawlNotConfigured: 'Skan przeglądarką wymaga IPAL_COOKIE_SCAN_URL i IPAL_COOKIE_SCAN_TOKEN na serwerze.',
crawlPages: 'Przeskanowane strony',
crawlRequests: 'Zapytania do zewnętrznych serwisów',
crawlRunning: 'Skanowanie… rozpoczęte {startedAt}.',
crawlStateDone: 'Gotowe',
crawlStateFailed: 'Błąd',
crawlStateRunning: 'W toku',
crawlStatus: 'Status',
crawlViolations: 'Naruszenia',
database: 'Open Cookie Database',
domain: 'Domena',
draft: 'Szkic',
emailIntro: 'Ostatni skan cookies strony {site} znalazł:',
emailSubject: 'Skan cookies {site}: naruszeń {violations}, nowych nieznanych {newUnknown}',
finishedAt: 'Zakończony',
functional: 'Funkcjonalne',
integration: 'Integracja wtyczki',
integrationsFound: 'Używane integracje',
@@ -124,6 +215,8 @@ export const COOKIE_SCAN_LABELS: Record<'en' | 'pl', CookieScanLabels> = {
namesHint: 'Opcjonalnie: nazwy cookies widoczne w przeglądarce (DevTools → Application → Cookies), po jednej w wierszu. Zostaną wyszukane we wtyczce i w Open Cookie Database.',
namesLabel: 'Dodatkowe nazwy cookies',
necessary: 'Niezbędne',
notifyEmails: 'Ostrzeżenia e-mail do',
notifyEmailsDescription: 'Adresy po przecinku. Po skanie z naruszeniami lub nowymi nieznanymi cookies wysyłane jest ostrzeżenie przez konfigurację poczty strony. Puste = bez e-maili.',
plural: 'Przegląd cookies',
project: 'Deklaracja projektu',
purpose: 'Cel',
@@ -134,17 +227,23 @@ export const COOKIE_SCAN_LABELS: Record<'en' | 'pl', CookieScanLabels> = {
scanIntro: 'Dodaje cookies integracji włączonych w tym projekcie jako szkice do przejrzenia.',
scanning: 'Skanowanie…',
scanResult: 'Nowe: {created}, zaktualizowane: {updated}, bez zmian: {unchanged}, nieznane: {unknown}.',
seenBeforeConsent: 'Widoczny przed zgodą',
sessionStorage: 'Session storage',
setBeforeConsent: 'Ustawiany przed zgodą',
setBeforeConsentDescription: 'Może powstać, zanim odwiedzający zdecyduje. Tylko niezbędne cookies powinny.',
singular: 'Wpis przeglądu cookies',
source: 'Źródło',
sourceDetail: 'Skąd',
startedAt: 'Rozpoczęty',
startedBy: 'Uruchomił',
status: 'Status',
statusDescription: 'Zaakceptowany → trafia do Ustawień cookies → Cookies. Odrzucenie nigdy nie usuwa wiersza z tej listy.',
storage: 'Przechowywany w',
unknown: 'Nieznany — uzupełnij',
vendor: 'Dostawca',
violation: 'Naruszenie',
violationDescription: 'Widoczny przed zgodą w ostatnim skanie i nie jest niezbędny.',
violationDetail: 'Szczegóły naruszenia',
},
}
+37 -10
View File
@@ -68,11 +68,16 @@ export async function enabledCookieIntegrations(
return on
}
/** A name seen somewhere: in the panel's text box (a string) or by a crawl (with storage and domain). */
export type CookieObservation = { domain?: string; name: string; storage?: CookieStorage } | string
/**
* Everything a scan reports, before anything is written: the cookies of the
* enabled integrations, the project's declarations, and each extra name looked
* up in the project's declarations, every built-in integration, then the Open
* Cookie Database. A name nothing knows comes back with `source: 'unknown'`.
* `matches` maps each extra name (`storage:name`) to the review key that covers
* it — `_ga_ABC` → `cookie:_ga_*`.
*/
export async function collectCookieFindings({
ctx,
@@ -87,13 +92,15 @@ export async function collectCookieFindings({
databaseCategories?: CookieScannerOptions['databaseCategories']
declarations?: CookieDeclaration[]
integrations?: CookieIntegration[]
names?: string[]
}): Promise<{ enabled: CookieIntegration[]; findings: CookieFinding[] }> {
names?: CookieObservation[]
}): Promise<{ enabled: CookieIntegration[]; findings: CookieFinding[]; matches: Map<string, string> }> {
const enabled = await enabledCookieIntegrations(integrations, ctx)
const found = new Map<string, CookieFinding>()
const matches = new Map<string, string>()
const add = (f: CookieFinding) => {
const key = reviewKey(f.storage, f.name)
if (!found.has(key)) {found.set(key, f)}
return key
}
for (const d of declarations) {add(fromDeclaration(d, 'project', 'Project'))}
for (const integration of enabled) {
@@ -105,19 +112,32 @@ export async function collectCookieFindings({
...integrations.flatMap((i) => declarationsOf(i, ctx).map((d) => ({ d, detail: i.label, source: 'integration' as const }))),
]
const index = database ? await loadCookieDatabase() : null
for (const name of names) {
if ([...found.values()].some((f) => f.storage === 'cookie' && cookieNameMatches(f.name, name))) {continue}
const declared = known.find((k) => (k.d.storage ?? 'cookie') === 'cookie' && cookieNameMatches(k.d.name, name))
for (const raw of names) {
const { name, domain, storage = 'cookie' } = typeof raw === 'string' ? { name: raw } : raw
const seenKey = reviewKey(storage, name)
if (matches.has(seenKey)) {continue}
const covering = [...found.values()].find((f) => f.storage === storage && cookieNameMatches(f.name, name))
if (covering) {
matches.set(seenKey, reviewKey(storage, covering.name))
continue
}
const declared = known.find((k) => (k.d.storage ?? 'cookie') === storage && cookieNameMatches(k.d.name, name))
if (declared) {
add(fromDeclaration(declared.d, declared.source, declared.detail))
matches.set(seenKey, add(fromDeclaration(declared.d, declared.source, declared.detail)))
continue
}
const fromDb = index ? lookupCookie(index, name, databaseCategories) : null
add(fromDb ?? { name, source: 'unknown', storage: 'cookie' })
const finding: CookieFinding = fromDb
? { ...fromDb, storage, ...(domain && !fromDb.domain ? { domain } : {}) }
: { ...(domain ? { domain } : {}), name, source: 'unknown', storage }
matches.set(seenKey, add(finding))
}
return { enabled, findings: [...found.values()] }
return { enabled, findings: [...found.values()], matches }
}
/** A review entry a scan wrote: its id, category (after the merge) and whether it is new. */
export type CookieReviewEntryRef = { category: null | string; created: boolean; id: number | string }
type ReviewDoc = {
id: number | string
listed?: boolean | null
@@ -149,11 +169,14 @@ async function listedNames(payload: BasePayload, req?: PayloadRequest): Promise<
*/
export async function applyCookieFindings({
collection = COOKIE_REVIEW_SLUG,
entries,
findings,
payload,
req,
}: {
collection?: string
/** Filled with every written entry by review key — id and its category after the merge. */
entries?: Map<string, CookieReviewEntryRef>
findings: CookieFinding[]
payload: BasePayload
req?: PayloadRequest
@@ -161,7 +184,7 @@ export async function applyCookieFindings({
const { locales } = localesOf(payload)
const codes = locales.filter((l): l is string => Boolean(l))
const listed = await listedNames(payload, req)
const summary: CookieScanSummary = { created: 0, unchanged: 0, unknown: 0, updated: 0 }
const summary: CookieScanSummary = { created: 0, newUnknown: 0, unchanged: 0, unknown: 0, updated: 0 }
const now = new Date().toISOString()
const common = { collection: collection as never, context: { ipalCookieScan: true }, depth: 0, fallbackLocale: false as never, overrideAccess: true, req }
@@ -201,7 +224,11 @@ export async function applyCookieFindings({
await payload.update({ ...common, id, data: data as never, locale: locale as never })
}
}
if (!existing) {summary.created++}
entries?.set(key, { id: id!, category: scalars.category ?? null, created: !existing })
if (!existing) {
summary.created++
if (finding.source === 'unknown') {summary.newUnknown++}
}
else if (values.changed) {summary.updated++}
else {summary.unchanged++}
}
+38 -1
View File
@@ -1,5 +1,6 @@
import type { BasePayload, PayloadRequest } from 'payload'
import type { GlobalOverride } from '../../../globals/overrides.js'
import type { CollectionOverride } from '../../shared/collectionOverride.js'
import type { ConsentCategory } from '../categories.js'
import type { CookieScanLabels } from './labels.js'
@@ -77,6 +78,8 @@ export type OpenCookieCategory = 'Analytics' | 'Functional' | 'Marketing' | 'Nec
/** Totals a scan reports back to the panel. */
export type CookieScanSummary = {
created: number
/** Entries created by this scan that nothing knew. */
newUnknown: number
unchanged: number
/** Names nothing knew — the editor fills provider, purpose and category. */
unknown: number
@@ -88,10 +91,16 @@ export type CookieScanSummary = {
* action. Every key is optional.
*/
export type CookieScannerOptions = {
/** Who may run a scan (GET/POST /api/ipal/cookie-scan). Default: `editor` and up. */
/** Who may run a scan (GET/POST /api/ipal/cookie-scan) and start a crawl. Default: `editor` and up. */
access?: (args: { req: PayloadRequest }) => boolean | Promise<boolean>
/** Change the `cookie-review` collection (object merges, function takes over). */
collectionOverrides?: CollectionOverride
/**
* Browser crawl through the scanner service (services/cookie-crawler):
* "Crawl site" in the panel, the `cookie-crawl` global (latest result only),
* violations, a dashboard warning and an optional e-mail. Default off.
*/
crawl?: boolean | CookieCrawlOptions
/** Look unknown names up in the bundled Open Cookie Database. Default true. */
database?: boolean
/**
@@ -117,3 +126,31 @@ export type CookieScannerOptions = {
*/
syncAccepted?: boolean
}
/**
* `cookieScanner.crawl` — the site side of the browser crawl. The browser runs
* in the scanner service, never in the site. Every key is optional.
*/
export type CookieCrawlOptions = {
/** CSS selector of the banner's "Accept all" button. Default `[data-ipal="accept"]`. */
acceptSelector?: string
/**
* The site's Consent Mode: `'advanced'` (default) lets Google tag requests
* through before consent (signals denied, no cookies); `'basic'` reports them.
*/
consentMode?: 'advanced' | 'basic'
/** Warning on the dashboard after a crawl with violations or new unknown cookies. Default true. */
dashboard?: boolean
/** Change the `cookie-crawl` global (object merges, function takes over). */
globalOverride?: GlobalOverride
/** Sitemap pages crawled besides the home page. Default 20, at most 100. */
maxPages?: number
/** Scanner service base URL. Default env `IPAL_COOKIE_SCAN_URL`. */
serviceUrl?: string
/** Public origin of this site the service crawls and calls back. Default `serverURL`, else `NEXT_PUBLIC_SERVER_URL`. */
siteUrl?: string
/** Shared secret with the service. Default env `IPAL_COOKIE_SCAN_TOKEN`. */
token?: string
/** Hosts whose requests before consent are violations: `(defaults) => hosts`. */
trackerHosts?: (defaults: string[]) => string[]
}
+19
View File
@@ -3,6 +3,11 @@ import type { EnvRule } from './assertEnv.js'
type TurnstileNames = { secretVar?: string; siteKeyVar?: string }
export type IpalEnvFeatures = {
/**
* Cookie crawl (cookieScanner.crawl): the scanner service URL and the shared
* token (at least 16 characters). Required in production only.
*/
cookieCrawl?: boolean
/** Override the database var. Default 'DATABASE_URI'. */
databaseVar?: string
/** Microsoft Graph e-mail (graphAdapter). Adds the GRAPH_* vars. */
@@ -56,6 +61,7 @@ export type IpalEnvFeatures = {
*/
export function ipalEnvRules(features: IpalEnvFeatures = {}): EnvRule[] {
const {
cookieCrawl = false,
databaseVar = 'DATABASE_URI',
emailGraph = false,
ipHeader = false,
@@ -125,6 +131,19 @@ export function ipalEnvRules(features: IpalEnvFeatures = {}): EnvRule[] {
})
}
if (cookieCrawl) {
const required = process.env.NODE_ENV === 'production'
rules.push(
{ name: 'IPAL_COOKIE_SCAN_URL', description: 'Cookie crawler service base URL, e.g. https://cookie-crawler.example.com', kind: 'url', required },
{
name: 'IPAL_COOKIE_SCAN_TOKEN',
description: 'Token shared with the cookie crawler (this site\'s entry in IPAL_CRAWLER_SITES)',
required,
validate: (v) => (v.length >= 16 ? true : 'IPAL_COOKIE_SCAN_TOKEN must be at least 16 characters'),
},
)
}
if (turnstile) {
const names = typeof turnstile === 'object' ? turnstile : {}
rules.push(
+29 -4
View File
@@ -11,7 +11,10 @@ import { buildSiteSettings } from './globals/SiteSettings/index.js'
import { adminOnly, adminOrSelf, injectRoles } from './modules/access/index.js'
import { buildConsentLogCollection, buildConsentLogEndpoint } from './modules/consent/consentLog.js'
import { buildCookieReviewCollection } from './modules/consent/scanner/collection.js'
import { buildCookieCrawlEndpoints } from './modules/consent/scanner/crawl/endpoints.js'
import { buildCookieCrawlGlobal } from './modules/consent/scanner/crawl/global.js'
import { buildCookieScanEndpoints } from './modules/consent/scanner/endpoint.js'
import { mergeCookieScanLabels } from './modules/consent/scanner/labels.js'
import { buildConstructionFields } from './modules/construction/fields.js'
import { buildArchiveFields } from './modules/content/index.js'
import { testEmailEndpoint } from './modules/email/test/testEmailEndpoint.js'
@@ -317,10 +320,32 @@ export const ipalKit = (options: IpalOptions): Plugin => {
if (options.cookieScanner) {
const scannerOptions = options.cookieScanner === true ? {} : options.cookieScanner
config.collections = [...(config.collections ?? []), applyCollectionOverride(buildCookieReviewCollection(scannerOptions), scannerOptions.collectionOverrides)]
config.endpoints = [
...(config.endpoints ?? []),
...buildCookieScanEndpoints(scannerOptions, { localeCount: options.i18n.locales.length, stats: Boolean(options.stats) }),
]
const scanPlugin = { localeCount: options.i18n.locales.length, stats: Boolean(options.stats) }
config.endpoints = [...(config.endpoints ?? []), ...buildCookieScanEndpoints(scannerOptions, scanPlugin)]
// Browser crawl through the scanner service (opt-in): latest-result global, endpoints, dashboard warning.
if (scannerOptions.crawl) {
const crawl = scannerOptions.crawl === true ? {} : scannerOptions.crawl
const labels = mergeCookieScanLabels(scannerOptions.labels)
const crawlGlobal = buildCookieCrawlGlobal(labels)
const override = crawl.globalOverride
config.globals = [
...(config.globals ?? []),
override ? applyGlobalOverrides([crawlGlobal], { [crawlGlobal.slug]: override } as never)[0] : crawlGlobal,
]
config.endpoints = [...(config.endpoints ?? []), ...buildCookieCrawlEndpoints({ labels, options: scannerOptions, plugin: scanPlugin })]
if (crawl.dashboard !== false) {
config.admin = {
...(config.admin ?? {}),
components: {
...(config.admin?.components ?? {}),
beforeDashboard: [
...(config.admin?.components?.beforeDashboard ?? []),
{ path: '@intecion/ipal-kit/admin#CookieCrawlAlert', serverProps: { adminRoute: options.adminRoute ?? '/admin', labels } },
],
},
}
}
}
}
// --- built-in statistics: cookieless visits + consented history (opt-in) ---