Files
ipal-kit/src/modules/consent/scanner/crawl/ingest.ts
T
Radosław SmolińskiandClaude Opus 5.5 4bb9c663fd 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]>
2026-10-27 15:14:01 +01:00

157 lines
6.3 KiB
TypeScript

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 })
}
}