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:
co-authored by
Claude Opus 5.5
parent
4f69f6ed20
commit
4bb9c663fd
@@ -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'),
|
||||
}
|
||||
}
|
||||
@@ -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
|
||||
}
|
||||
Reference in New Issue
Block a user