Cookie scanner: one approval for everything a scan finds
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]>
This commit is contained in:
co-authored by
Claude Opus 5.5
parent
0e7966dfbb
commit
86ff3f5ff7
@@ -2,41 +2,53 @@ import type { Payload } from 'payload'
|
||||
|
||||
import type { CookieScanLabels } from '../labels.js'
|
||||
|
||||
import { COOKIE_APPROVAL_VIEW_PATH, countPendingCookies } from '../approval.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
|
||||
/** Cookie approval is on: remind while cookies wait, link to the approval view. Default true. */
|
||||
approval?: boolean
|
||||
/** The browser crawl is on: report violations and failed crawls. Default true. */
|
||||
crawl?: boolean
|
||||
/** Injected by Payload into admin server components. */
|
||||
i18n?: { language?: string }
|
||||
labels?: Record<string, CookieScanLabels>
|
||||
payload?: Payload
|
||||
}
|
||||
|
||||
type CrawlDoc = { error?: null | string; status?: null | string; summary?: { newUnknown?: null | number; violations?: null | number } | null }
|
||||
|
||||
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.
|
||||
* Dashboard warning (beforeDashboard): cookies waiting for approval (with a
|
||||
* link to the approval view), and — with the crawl — violations or a failed
|
||||
* crawl. Renders nothing when nothing needs attention, and never throws.
|
||||
*/
|
||||
export async function CookieCrawlAlert({ adminRoute = '/admin', i18n, labels = COOKIE_SCAN_LABELS, payload }: Props) {
|
||||
export async function CookieCrawlAlert({ adminRoute = '/admin', approval = true, crawl = true, 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
|
||||
let doc: CrawlDoc = {}
|
||||
if (crawl) {
|
||||
try {
|
||||
doc = (await payload.findGlobal({ slug: COOKIE_CRAWL_SLUG as never, depth: 0 })) as CrawlDoc
|
||||
} catch {
|
||||
doc = {}
|
||||
}
|
||||
}
|
||||
const pending = approval ? await countPendingCookies(payload) : 0
|
||||
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
|
||||
// Without approval, new unknown cookies are the reason to look; with it, the pending count says so.
|
||||
const findings = doc.status === 'done' && (violations > 0 || (!approval && newUnknown > 0))
|
||||
if (!failed && !findings && !pending) {return null}
|
||||
const admin = adminRoute.replace(/\/$/, '')
|
||||
const review = `${admin}/collections/${COOKIE_REVIEW_SLUG}`
|
||||
|
||||
return (
|
||||
<div
|
||||
@@ -50,17 +62,27 @@ export async function CookieCrawlAlert({ adminRoute = '/admin', i18n, labels = C
|
||||
padding: '1rem 1.25rem',
|
||||
}}
|
||||
>
|
||||
{failed ? (
|
||||
<strong>{fill(t('alertFailed'), { error: doc.error ?? '' })}</strong>
|
||||
) : (
|
||||
{failed ? <p style={{ margin: 0 }}><strong>{fill(t('alertFailed'), { error: doc.error ?? '' })}</strong></p> : null}
|
||||
{findings ? (
|
||||
<>
|
||||
<strong>{fill(t('alertTitle'), { newUnknown, violations })}</strong>
|
||||
<p style={{ margin: 0 }}><strong>{fill(t('alertTitle'), { newUnknown, violations })}</strong></p>
|
||||
<p style={{ margin: '0.5rem 0 0' }}>{t('alertBody')}</p>
|
||||
<a href={violations ? `${review}?where[violation][equals]=true` : review} style={{ display: 'block', marginTop: '0.5rem' }}>
|
||||
{t('alertLink')}
|
||||
</a>
|
||||
</>
|
||||
)}
|
||||
<a href={href} style={{ display: 'block', marginTop: '0.5rem' }}>
|
||||
{t('alertLink')}
|
||||
</a>
|
||||
) : null}
|
||||
{pending ? (
|
||||
<p style={{ margin: failed || findings ? '0.75rem 0 0' : 0 }}>
|
||||
<strong>{fill(t('approvalPending'), { count: pending })}</strong>{' '}
|
||||
<a href={`${admin}${COOKIE_APPROVAL_VIEW_PATH}`}>{t('approvalLink')}</a>
|
||||
</p>
|
||||
) : null}
|
||||
{failed && !findings && !pending ? (
|
||||
<a href={review} style={{ display: 'block', marginTop: '0.5rem' }}>
|
||||
{t('alertLink')}
|
||||
</a>
|
||||
) : null}
|
||||
</div>
|
||||
)
|
||||
}
|
||||
|
||||
@@ -150,7 +150,7 @@ export function buildCookieCrawlEndpoints({
|
||||
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 })
|
||||
await finishCrawl({ approval: options.approval !== false, 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)
|
||||
|
||||
@@ -7,10 +7,11 @@ 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 } from '../scan.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'
|
||||
@@ -71,6 +72,13 @@ export async function ingestCrawlResult({
|
||||
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({
|
||||
@@ -108,6 +116,7 @@ export async function ingestCrawlResult({
|
||||
|
||||
/** 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,
|
||||
@@ -115,6 +124,8 @@ export async function finishCrawl({
|
||||
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
|
||||
@@ -150,7 +161,9 @@ export async function finishCrawl({
|
||||
})) 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 })
|
||||
// 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 })
|
||||
}
|
||||
}
|
||||
|
||||
@@ -3,6 +3,7 @@ import type { BasePayload } from 'payload'
|
||||
import type { CookieScanLabels } from '../labels.js'
|
||||
import type { CrawlIngestSummary } from './ingest.js'
|
||||
|
||||
import { COOKIE_APPROVAL_VIEW_PATH } from '../approval.js'
|
||||
import { COOKIE_REVIEW_SLUG } from '../collection.js'
|
||||
import { labelFor } from '../labels.js'
|
||||
|
||||
@@ -18,12 +19,15 @@ const fill = (template: string, values: Record<string, number | string>) =>
|
||||
export async function sendCrawlWarning({
|
||||
labels,
|
||||
payload,
|
||||
pending = 0,
|
||||
siteUrl,
|
||||
summary,
|
||||
to,
|
||||
}: {
|
||||
labels: Record<string, CookieScanLabels>
|
||||
payload: BasePayload
|
||||
/** Cookies waiting for approval — the e-mail says so and links to the approval view. */
|
||||
pending?: number
|
||||
siteUrl: string
|
||||
summary: CrawlIngestSummary
|
||||
to: string[]
|
||||
@@ -32,18 +36,21 @@ export async function sendCrawlWarning({
|
||||
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 admin = `${siteUrl}${payload.config.routes?.admin ?? '/admin'}`
|
||||
const adminUrl = `${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 problems = summary.violations.length > 0 || summary.newUnknown > 0
|
||||
const html = `<p>${esc(fill(t('emailIntro'), values))}</p>
|
||||
<p><strong>${esc(fill(t('alertTitle'), values))}</strong></p>
|
||||
${problems ? `<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>`
|
||||
${problems ? `<p>${esc(t('alertBody'))}</p>\n<p><a href="${esc(adminUrl)}">${esc(t('alertLink'))}</a></p>` : ''}
|
||||
${pending ? `<p><strong>${esc(fill(t('emailPending'), { count: pending }))}</strong></p>\n<p><a href="${esc(`${admin}${COOKIE_APPROVAL_VIEW_PATH}`)}">${esc(t('approvalLink'))}</a></p>` : ''}`
|
||||
try {
|
||||
await payload.sendEmail({ html, subject: fill(t('emailSubject'), values), to })
|
||||
const subject = problems || !pending ? fill(t('emailSubject'), values) : fill(t('emailSubjectPending'), { count: pending, site })
|
||||
await payload.sendEmail({ html, subject, to })
|
||||
return true
|
||||
} catch (err) {
|
||||
payload.logger.error(`[ipal] cookie crawl warning e-mail failed: ${err instanceof Error ? err.message : String(err)}`)
|
||||
|
||||
Reference in New Issue
Block a user