After "Scan cookies" or a site check, the new Approve cookies view (/admin/cookie-approval) lists what waits, grouped by consent category, with provider, purpose and duration and New / Changed / Needs description markers. One "Approve and add" puts every ticked cookie into Cookie banner -> Cookie list in every locale. That list feeds the cookie policy table and the detailed settings window. - Never overwrites editor text or categories, never adds a second row (a pattern and a concrete name are the same cookie), never deletes. - Unknown cookies are approved into a category that needs consent (approval.unknownCategory, default marketing) and flagged Needs description; writing a purpose clears the flag. - Cookies a scan or crawl no longer finds are flagged No longer found, for review only. - The dashboard and the crawl e-mail say how many cookies wait and link to the view; nothing is added without approval. - Optional: cookieScanner.approval false keeps per-entry review. - Migration: cookie-review gains change and needsDescription. Co-Authored-By: Claude Opus 5.5 <[email protected]>
170 lines
7.1 KiB
TypeScript
170 lines
7.1 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 { countPendingCookies } from '../approval.js'
|
|
import { COOKIE_REVIEW_SLUG } from '../collection.js'
|
|
import { DEFAULT_COOKIE_INTEGRATIONS } from '../integrations.js'
|
|
import { labelFor } from '../labels.js'
|
|
import { applyCookieFindings, collectCookieFindings, cookieScanContext, flagGoneEntries } 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,
|
|
})
|
|
// Accepted cookies the browser no longer saw (and nothing still declares) are flagged for review, never deleted.
|
|
summary.gone = await flagGoneEntries({
|
|
keep: new Set([...(seenKeys as Set<string>), ...findings.filter((f) => f.source === 'integration' || f.source === 'project').map((f) => `${f.storage}:${f.name}`)]),
|
|
payload,
|
|
req,
|
|
where: { status: { equals: 'accepted' } },
|
|
})
|
|
|
|
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({
|
|
approval = true,
|
|
labels,
|
|
payload,
|
|
req,
|
|
result,
|
|
siteUrl,
|
|
summary,
|
|
}: {
|
|
/** Cookie approval is on: the e-mail says how many cookies wait and links to the approval view. */
|
|
approval?: boolean
|
|
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, so the site could not be checked after 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)
|
|
// Something new waits for approval, or something breaks the rules: say so. Nothing is added by itself.
|
|
const pending = approval ? await countPendingCookies(payload) : 0
|
|
if (to.length && (summary.violations.length || summary.newUnknown || (approval && summary.created && pending))) {
|
|
await sendCrawlWarning({ labels, payload, pending, siteUrl: siteUrl ?? '', summary, to })
|
|
}
|
|
}
|