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) => 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 labels: Record options: CookieScannerOptions payload: BasePayload plugin: CookieScanContext['plugin'] req?: PayloadRequest result: Extract }): Promise { 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() 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; 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(), 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 payload: BasePayload req?: PayloadRequest result: CrawlResult siteUrl?: null | string summary?: CrawlIngestSummary }): Promise { 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 }) } }