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:
Radosław Smoliński
2026-10-28 22:17:46 +01:00
co-authored by Claude Opus 5.5
parent 0e7966dfbb
commit 86ff3f5ff7
25 changed files with 1186 additions and 114 deletions
+2
View File
@@ -10,6 +10,8 @@ export { TestEmailButton } from '../globals/SiteIntegrations/components/TestEmai
export { DocumentTitle } from '../modules/admin-i18n/DocumentTitle.js'
export { RowLabel } from '../modules/admin-ui/RowLabelComponent.js'
export { AdminIcon, AdminLogo, IntecionCredit } from '../modules/branding/index.js'
export { CookieApprovalForm } from '../modules/consent/scanner/CookieApprovalForm.js'
export { CookieApprovalView } from '../modules/consent/scanner/CookieApprovalView.js'
export { CookieScanButton } from '../modules/consent/scanner/CookieScanButton.js'
export { CookieCrawlAlert } from '../modules/consent/scanner/crawl/CookieCrawlAlert.js'
export { IntegrationAlerts } from '../modules/integrations/IntegrationAlerts.js'
+16
View File
@@ -63,12 +63,16 @@ export type { ConsentCategory, ConsentLogOptions, ConsentState, ConsentTexts, Co
export {
addToCookieList,
applyCookieFindings,
approveCookies,
bearerMatches,
buildCookieApprovalEndpoints,
buildCookieCrawlEndpoints,
buildCookieCrawlGlobal,
buildCookieReviewCollection,
buildCookieScanEndpoints,
collectCookieFindings,
COOKIE_APPROVAL_PATH,
COOKIE_APPROVAL_VIEW_PATH,
COOKIE_CRAWL_PATH,
COOKIE_CRAWL_RESULTS_PATH,
COOKIE_CRAWL_SLUG,
@@ -79,26 +83,38 @@ export {
COOKIE_SCAN_URL_ENV,
cookieNameMatches,
cookieScanContext,
countPendingCookies,
DEFAULT_COOKIE_INTEGRATIONS,
DEFAULT_DATABASE_CATEGORIES,
DEFAULT_TRACKER_HOSTS,
DEFAULT_UNKNOWN_CATEGORY,
findCrawlViolations,
finishCrawl,
flagGoneEntries,
GOOGLE_TAG_HOSTS,
indexCookieDatabase,
ingestCrawlResult,
loadCookieApproval,
loadCookieDatabase,
lookupCookie,
mergeCookieReview,
mergeCookieScanLabels,
nextChange,
parseCookieNames,
parseCrawlResult,
PENDING_WHERE,
resolveCrawlConfig,
runCookieScan,
sameCookie,
sendCrawlWarning,
suggestionFor,
} from './modules/consent/scanner/index.js'
export type {
CookieApprovalItem,
CookieApprovalList,
CookieApprovalOptions,
CookieApprovalResult,
CookieChange,
CookieCrawlOptions,
CookieDatabaseIndex,
CookieDeclaration,
@@ -0,0 +1,189 @@
'use client'
import { Button, toast, useConfig, useTranslation } from '@payloadcms/ui'
import { useRouter } from 'next/navigation.js'
import { useState } from 'react'
import type { ConsentCategory } from '../categories.js'
import type { CookieApprovalItem, CookieApprovalResult } from './approval.js'
import type { CookieScanLabels } from './labels.js'
import { COOKIE_SCAN_LABELS } from './labels.js'
const CATEGORY_ORDER: ConsentCategory[] = ['necessary', 'functional', 'analytics', 'marketing']
// COOKIE_REVIEW_SLUG — not imported: collection.ts is server config, this file ships to the browser.
const REVIEW_SLUG = 'cookie-review'
const hidden = { clip: 'rect(0 0 0 0)', height: 1, overflow: 'hidden', position: 'absolute', width: 1 } as const
const fill = (template: string, values: Record<string, number | string>) =>
template.replace(/\{(\w+)\}/g, (_, k: string) => String(values[k] ?? ''))
const CSS = `
.ipal-cookie-approval table { border-collapse: collapse; width: 100%; margin-bottom: 1.5rem; }
.ipal-cookie-approval th, .ipal-cookie-approval td { border-bottom: 1px solid var(--theme-elevation-150); padding: .5rem .5rem; text-align: left; vertical-align: top; }
.ipal-cookie-approval th { font-weight: 600; font-size: .85rem; color: var(--theme-elevation-600); }
.ipal-cookie-approval h2 { margin: 1.5rem 0 .5rem; font-size: 1.15rem; }
.ipal-cookie-approval .ipal-badge { display: inline-block; border-radius: 999px; padding: 0 .5rem; margin: 0 .25rem .25rem 0; font-size: .75rem; line-height: 1.5rem; white-space: nowrap; background: var(--theme-elevation-100); }
.ipal-cookie-approval .ipal-badge--new { background: var(--theme-success-100, #d9f2e3); color: var(--theme-success-800, #14532d); }
.ipal-cookie-approval .ipal-badge--changed { background: var(--theme-warning-100, #fff1c2); color: var(--theme-warning-800, #6b4e00); }
.ipal-cookie-approval .ipal-badge--unknown { background: var(--theme-error-100, #fde2e2); color: var(--theme-error-800, #7f1d1d); }
.ipal-cookie-approval .ipal-bar { position: sticky; bottom: 0; display: flex; flex-wrap: wrap; gap: 1rem; align-items: center; padding: 1rem 0; background: var(--theme-bg); border-top: 1px solid var(--theme-elevation-150); }
`
/**
* The approval list (client): one table per consent category, every cookie
* ticked, a marker for new / changed / not yet described, an Edit link to the
* review entry, and one "Approve and add" button for the ticked ones.
*/
export function CookieApprovalForm({
adminRoute = '/admin',
gone,
labels = COOKIE_SCAN_LABELS,
pending,
unknownCategory,
}: {
adminRoute?: string
gone: CookieApprovalItem[]
labels?: Record<string, CookieScanLabels>
pending: CookieApprovalItem[]
unknownCategory: ConsentCategory
}) {
const { i18n } = useTranslation()
const { config } = useConfig()
const router = useRouter()
const t = labels[i18n.language] ?? labels.en ?? COOKIE_SCAN_LABELS.en
const endpoint = `${config.serverURL ?? ''}${config.routes?.api ?? '/api'}/ipal/cookie-approval`
const admin = adminRoute.replace(/\/$/, '')
const [excluded, setExcluded] = useState<Set<number | string>>(() => new Set())
const [busy, setBusy] = useState(false)
const [done, setDone] = useState<CookieApprovalResult | null>(null)
const selected = pending.filter((p) => !excluded.has(p.id))
const toggle = (id: number | string) =>
setExcluded((prev) => {
const next = new Set(prev)
if (next.has(id)) {next.delete(id)}
else {next.add(id)}
return next
})
const approve = async () => {
setBusy(true)
try {
const res = await fetch(endpoint, {
body: JSON.stringify({ ids: selected.map((p) => p.id) }),
credentials: 'include',
headers: { 'Content-Type': 'application/json' },
method: 'POST',
})
const data = (await res.json()) as { ok?: boolean; result?: CookieApprovalResult }
if (!res.ok || !data.ok || !data.result) {throw new Error('approval failed')}
setDone(data.result)
toast.success(fill(t.approvalDone, { ...data.result }))
setExcluded(new Set())
router.refresh()
} catch {
toast.error(t.approvalError)
} finally {
setBusy(false)
}
}
const groups = [
...CATEGORY_ORDER.map((c) => ({ items: pending.filter((p) => p.category === c), key: c, note: null as null | string, title: t[c] })),
{
items: pending.filter((p) => !p.category),
key: 'none',
note: fill(t.uncategorizedNote, { category: t[unknownCategory].toLowerCase() }),
title: t.uncategorized,
},
].filter((g) => g.items.length)
const row = (p: CookieApprovalItem, withBox: boolean) => (
<tr key={p.id}>
{withBox ? (
<td style={{ width: '2rem' }}>
<input
aria-label={`${t.include}: ${p.name}`}
checked={!excluded.has(p.id)}
onChange={() => toggle(p.id)}
type="checkbox"
/>
</td>
) : null}
<td>
<code>{p.name}</code>
<div>
{p.change === 'new' ? <span className="ipal-badge ipal-badge--new">{t.markerNew}</span> : null}
{p.change === 'changed' ? <span className="ipal-badge ipal-badge--changed">{t.markerChanged}</span> : null}
{p.unknown ? <span className="ipal-badge ipal-badge--unknown">{t.markerUnknown}</span> : null}
</div>
</td>
<td>{p.vendor ?? ''}</td>
<td>{p.purpose ?? ''}</td>
<td>{p.retention ?? ''}</td>
<td>
<a href={`${admin}/collections/${REVIEW_SLUG}/${p.id}`}>{t.edit}</a>
</td>
</tr>
)
const head = (withBox: boolean) => (
<thead>
<tr>
{withBox ? <th scope="col"><span style={hidden}>{t.include}</span></th> : null}
<th scope="col">{t.name}</th>
<th scope="col">{t.vendor}</th>
<th scope="col">{t.purpose}</th>
<th scope="col">{t.retention}</th>
<th scope="col"><span style={hidden}>{t.edit}</span></th>
</tr>
</thead>
)
return (
<div className="ipal-cookie-approval">
<style>{CSS}</style>
{pending.length ? (
<>
<p>{t.approvalIntro}</p>
{groups.map((g) => (
<section data-ipal={`approval-${g.key}`} key={g.key}>
<h2>{g.title} ({g.items.length})</h2>
{g.note ? <p style={{ marginTop: 0 }}>{g.note}</p> : null}
<table>
{head(true)}
<tbody>{g.items.map((p) => row(p, true))}</tbody>
</table>
</section>
))}
<div className="ipal-bar">
<Button buttonStyle="primary" disabled={busy || !selected.length} margin={false} onClick={() => void approve()} size="large">
{busy ? t.approving : `${t.approvalButton} (${selected.length})`}
</Button>
<span>{fill(t.approvalSelected, { count: selected.length })} / {pending.length}</span>
</div>
</>
) : (
<p>{t.approvalEmpty}</p>
)}
{done ? (
<p role="status">
✓ {fill(t.approvalDone, { ...done })} <a href={`${admin}/globals/cookie-settings`}>{t.openCookieBanner}</a>
</p>
) : null}
{gone.length ? (
<section data-ipal="approval-gone">
<h2>{t.goneTitle} ({gone.length})</h2>
<p style={{ marginTop: 0 }}>{t.goneNote}</p>
<table>
{head(false)}
<tbody>{gone.map((p) => row(p, false))}</tbody>
</table>
</section>
) : null}
</div>
)
}
export default CookieApprovalForm
@@ -0,0 +1,77 @@
import type { AdminViewServerProps, PayloadRequest } from 'payload'
import { DefaultTemplate } from '@payloadcms/next/templates'
import { Gutter } from '@payloadcms/ui'
import type { ConsentCategory } from '../categories.js'
import type { CookieScanLabels } from './labels.js'
import { DocumentTitle } from '../../admin-i18n/DocumentTitle.js'
import { adminDocumentTitle } from '../../admin-i18n/t.js'
import { DEFAULT_UNKNOWN_CATEGORY, loadCookieApproval } from './approval.js'
import { COOKIE_REVIEW_SLUG } from './collection.js'
import { CookieApprovalForm } from './CookieApprovalForm.js'
import { COOKIE_SCAN_LABELS, labelFor } from './labels.js'
type Props = {
adminRoute?: string
labels?: Record<string, CookieScanLabels>
unknownCategory?: ConsentCategory
} & AdminViewServerProps
/** Whether the user may read the review list — its own `access.read` decides (collectionOverrides narrow it). */
async function canReview(req: PayloadRequest): Promise<boolean> {
const read = req.payload.collections[COOKIE_REVIEW_SLUG as never]?.config.access?.read
if (!read || !req.user) {return false}
try {
return Boolean(await read({ req } as never))
} catch {
return false
}
}
/**
* Admin view at /admin/cookie-approval (`cookieScanner.approval`, on by
* default): everything the latest scans found, grouped by consent category,
* with one "Approve and add" button. Texts in the content locale that matches
* the admin language, else the default locale.
*/
export async function CookieApprovalView(props: Props) {
const { adminRoute = '/admin', initPageResult, labels = COOKIE_SCAN_LABELS, searchParams, unknownCategory = DEFAULT_UNKNOWN_CATEGORY } = props
const { req, visibleEntities } = initPageResult
const lang = req.i18n.language
const t = (key: keyof CookieScanLabels) => labelFor(labels, lang, key)
const l = req.payload.config.localization
const locale = l ? (l.localeCodes.includes(lang) ? lang : l.defaultLocale) : 'en'
const allowed = await canReview(req)
const list = allowed ? await loadCookieApproval({ locale, payload: req.payload, req }) : null
return (
<DefaultTemplate
i18n={req.i18n}
locale={initPageResult.locale}
params={props.params}
payload={req.payload}
permissions={initPageResult.permissions}
req={req}
searchParams={searchParams}
user={req.user ?? undefined}
visibleEntities={visibleEntities}
>
<Gutter>
<div data-ipal="cookie-approval" style={{ paddingBottom: '3rem' }}>
<DocumentTitle title={adminDocumentTitle(t('approvalTitle'), req.payload.config.admin?.meta?.titleSuffix)} />
<h1>{t('approvalTitle')}</h1>
{list ? (
<CookieApprovalForm adminRoute={adminRoute} gone={list.gone} labels={labels} pending={list.pending} unknownCategory={unknownCategory} />
) : (
<p>{t('approvalNoAccess')}</p>
)}
</div>
</Gutter>
</DefaultTemplate>
)
}
export default CookieApprovalView
@@ -2,7 +2,7 @@
import { Button, useConfig, useTranslation } from '@payloadcms/ui'
import { useRouter } from 'next/navigation.js'
import { useEffect, useState } from 'react'
import { useCallback, useEffect, useState } from 'react'
import type { CookieScanLabels } from './labels.js'
import type { CookieScanSummary } from './types.js'
@@ -37,7 +37,16 @@ const fill = (template: string, values: Record<string, null | number | string>)
* while it runs. Labels in the admin language (`labels` from the collection
* config, English fallback).
*/
export function CookieScanButton({ crawl = false, labels = COOKIE_SCAN_LABELS }: { crawl?: boolean; labels?: Record<string, CookieScanLabels> }) {
export function CookieScanButton({
approval = false,
crawl = false,
labels = COOKIE_SCAN_LABELS,
}: {
/** Cookie approval is on: show how many cookies wait and link to the approval view. */
approval?: boolean
crawl?: boolean
labels?: Record<string, CookieScanLabels>
}) {
const { i18n } = useTranslation()
const { config } = useConfig()
const router = useRouter()
@@ -49,6 +58,17 @@ export function CookieScanButton({ crawl = false, labels = COOKIE_SCAN_LABELS }:
const [crawlState, setCrawlState] = useState<CrawlState | null>(null)
const [crawlStarting, setCrawlStarting] = useState(false)
const crawlEndpoint = endpoint.replace(/cookie-scan$/, 'cookie-crawl')
const approvalEndpoint = endpoint.replace(/cookie-scan$/, 'cookie-approval')
const approvalView = `${(config.routes?.admin ?? '/admin').replace(/\/$/, '')}/cookie-approval`
const [pending, setPending] = useState<null | number>(null)
const refreshPending = useCallback(() => {
if (!approval) {return}
fetch(approvalEndpoint, { credentials: 'include' })
.then((r) => (r.ok ? r.json() : null))
.then((data: { pending?: unknown[] } | null) => setPending(data?.pending?.length ?? null))
.catch(() => setPending(null))
}, [approval, approvalEndpoint])
useEffect(refreshPending, [refreshPending])
const when = (iso: null | string) => (iso ? formatDateTime(iso, i18n.language) : '')
useEffect(() => {
@@ -61,7 +81,10 @@ export function CookieScanButton({ crawl = false, labels = COOKIE_SCAN_LABELS }:
const data = res.ok ? ((await res.json()) as CrawlState) : null
if (stopped || !data) {return}
setCrawlState(data)
if (wasRunning && data.status !== 'running') {router.refresh()}
if (wasRunning && data.status !== 'running') {
router.refresh()
refreshPending()
}
wasRunning = data.status === 'running'
} catch {
// offline — try again on the next tick
@@ -73,7 +96,7 @@ export function CookieScanButton({ crawl = false, labels = COOKIE_SCAN_LABELS }:
stopped = true
clearInterval(timer)
}
}, [crawl, crawlEndpoint, router])
}, [crawl, crawlEndpoint, refreshPending, router])
const startCrawl = async () => {
setCrawlStarting(true)
@@ -106,6 +129,7 @@ export function CookieScanButton({ crawl = false, labels = COOKIE_SCAN_LABELS }:
if (!res.ok || !data.ok || !data.summary) {throw new Error('scan failed')}
setStatus({ kind: 'done', summary: data.summary })
router.refresh()
refreshPending()
} catch {
setStatus({ kind: 'error' })
}
@@ -138,6 +162,14 @@ export function CookieScanButton({ crawl = false, labels = COOKIE_SCAN_LABELS }:
{status.kind === 'scanning' ? t.scanning : t.scanButton}
</Button>
{status.kind === 'done' ? <span role="status">✓ {result(status.summary)}</span> : null}
{approval && pending ? (
<span data-ipal="cookie-approval-pending">
<strong>{fill(t.approvalPending, { count: pending })}</strong>{' '}
<Button buttonStyle="primary" el="anchor" margin={false} size="medium" url={approvalView}>
{t.approvalLink}
</Button>
</span>
) : null}
{status.kind === 'error' ? (
<span role="alert" style={{ color: 'var(--theme-error-500, crimson)' }}>✗ {t.scanError}</span>
) : null}
+191
View File
@@ -0,0 +1,191 @@
import type { BasePayload, Endpoint, PayloadRequest, Where } from 'payload'
import type { ConsentCategory } from '../categories.js'
import type { CookieReviewValues } from './merge.js'
import type { CookieChange } from './scan.js'
import type { CookieScannerOptions } from './types.js'
import { userMeetsRole } from '../../access/predicates.js'
import { CONSENT_CATEGORIES } from '../categories.js'
import { COOKIE_REVIEW_SLUG } from './collection.js'
import { textFor } from './merge.js'
import { addToCookieList } from './sync.js'
/**
* One approval for everything a scan or crawl found: the "Approve cookies" view
* lists what is waiting, grouped by consent category, and one button adds the
* ticked cookies to Cookie banner → Cookies — which feeds the cookie banner's
* detailed window and the cookie policy table. Nothing is added before that.
*/
export const COOKIE_APPROVAL_PATH = '/ipal/cookie-approval'
/** Admin view path (under the admin route). */
export const COOKIE_APPROVAL_VIEW_PATH = '/cookie-approval'
/** Category for cookies nothing knows, until an editor describes them. It needs consent. */
export const DEFAULT_UNKNOWN_CATEGORY: ConsentCategory = 'marketing'
export type CookieApprovalItem = {
category: ConsentCategory | null
change: CookieChange | null
id: number | string
name: string
purpose: null | string
retention: null | string
/** Nothing knew it: no category or no purpose yet. */
unknown: boolean
vendor: null | string
}
export type CookieApprovalList = {
/** Accepted cookies the latest scan or crawl no longer found — for review only. */
gone: CookieApprovalItem[]
/** Waiting for approval: drafts, and accepted cookies a scan changed. */
pending: CookieApprovalItem[]
}
export type CookieApprovalResult = { added: number; filled: number; needsDescription: number; skipped: number; unchanged: number }
type Doc = {
category?: ConsentCategory | null
change?: CookieChange | null
id: number | string
name: string
purpose?: null | Record<string, null | string> | string
retention?: null | Record<string, null | string> | string
source?: null | string
status?: 'accepted' | 'draft' | 'rejected' | null
vendor?: null | string
}
/** Pending = a draft, or an accepted cookie whose values a scan changed. */
export const PENDING_WHERE: Where = {
or: [{ status: { equals: 'draft' } }, { and: [{ status: { equals: 'accepted' } }, { change: { equals: 'changed' } }] }],
}
const asText = (v: Doc['purpose'], locale: string) =>
(typeof v === 'string' ? v : v ? (textFor(Object.fromEntries(Object.entries(v).filter(([, t]) => Boolean(t))) as Record<string, string>, locale) ?? null) : null) || null
function item(doc: Doc, locale: string): CookieApprovalItem {
const purpose = asText(doc.purpose, locale)
return {
id: doc.id,
name: doc.name,
category: doc.category && (CONSENT_CATEGORIES as readonly string[]).includes(doc.category) ? doc.category : null,
change: doc.change ?? null,
purpose,
retention: asText(doc.retention, locale),
unknown: !doc.category || !purpose || doc.source === 'unknown',
vendor: doc.vendor ?? null,
}
}
/** The approval list in one content locale (texts fall back to English, then any language). */
export async function loadCookieApproval({ locale, payload, req }: { locale: string; payload: BasePayload; req?: PayloadRequest }): Promise<CookieApprovalList> {
const common = { collection: COOKIE_REVIEW_SLUG as never, depth: 0, limit: 0, locale: 'all' as never, overrideAccess: true, pagination: false, req, sort: 'name' }
const [pending, gone] = await Promise.all([
payload.find({ ...common, where: PENDING_WHERE }),
payload.find({ ...common, where: { and: [{ status: { equals: 'accepted' } }, { change: { equals: 'gone' } }] } }),
])
return {
gone: (gone.docs as unknown as Doc[]).map((d) => item(d, locale)),
pending: (pending.docs as unknown as Doc[]).map((d) => item(d, locale)),
}
}
/** How many cookies wait for approval (dashboard, e-mail). Never throws. */
export async function countPendingCookies(payload: BasePayload): Promise<number> {
try {
return (await payload.count({ collection: COOKIE_REVIEW_SLUG as never, overrideAccess: true, where: PENDING_WHERE })).totalDocs
} catch {
return 0
}
}
/**
* Approves pending entries (all of them, or only `ids`): each becomes accepted
* and goes to Cookie banner → Cookies in every locale — a missing row is added,
* an existing one (same name or pattern) only gets its empty text filled, its
* category is kept. A cookie without a category gets `unknownCategory` (needs
* consent) and every cookie without a purpose is flagged "Needs description".
* Never deletes, never adds a second row for the same cookie.
*/
export async function approveCookies({
addToList = true,
ids,
payload,
req,
unknownCategory = DEFAULT_UNKNOWN_CATEGORY,
}: {
/** False (`syncAccepted: false`) = only mark the entries accepted. */
addToList?: boolean
ids?: (number | string)[]
payload: BasePayload
req?: PayloadRequest
unknownCategory?: ConsentCategory
}): Promise<CookieApprovalResult> {
const common = { collection: COOKIE_REVIEW_SLUG as never, context: { ipalCookieScan: true }, depth: 0, overrideAccess: true, req }
const where: Where = ids ? { and: [PENDING_WHERE, { id: { in: ids } }] } : PENDING_WHERE
const { docs } = await payload.find({ ...common, limit: 0, locale: 'all' as never, pagination: false, where })
const result: CookieApprovalResult = { added: 0, filled: 0, needsDescription: 0, skipped: (ids?.length ?? docs.length) - docs.length, unchanged: 0 }
const defaultLocale = payload.config.localization ? payload.config.localization.defaultLocale : 'en'
for (const doc of docs as unknown as ({ name: string } & CookieReviewValues & Doc)[]) {
const category = doc.category ?? unknownCategory
const needsDescription = !asText(doc.purpose, defaultLocale)
const outcome = addToList ? await addToCookieList({ entry: { ...doc, category } as never, payload, req }) : 'unchanged'
result[outcome]++
if (needsDescription) {result.needsDescription++}
await payload.update({
...common,
id: doc.id,
data: { category, change: null, listed: true, needsDescription, status: 'accepted' } as never,
})
}
return result
}
/**
* GET /api/ipal/cookie-approval?locale=pl → `CookieApprovalList`
* POST /api/ipal/cookie-approval, body `{ ids?: (string|number)[] }` → `{ ok, result }`
* Editors and up (`cookieScanner.access`).
*/
export function buildCookieApprovalEndpoints(options: CookieScannerOptions): Endpoint[] {
const approval = typeof options.approval === 'object' ? options.approval : {}
const allowed = async (req: PayloadRequest) =>
options.access ? Boolean(await options.access({ req })) : userMeetsRole(req, 'editor')
return [
{
handler: async (req) => {
if (!(await allowed(req))) {return Response.json({ ok: false }, { status: 403 })}
const l = req.payload.config.localization
const asked = typeof req.query?.locale === 'string' ? req.query.locale : undefined
const locale = l ? (asked && l.localeCodes.includes(asked) ? asked : l.defaultLocale) : 'en'
return Response.json({ ok: true, ...(await loadCookieApproval({ locale, payload: req.payload, req })) })
},
method: 'get',
path: COOKIE_APPROVAL_PATH,
},
{
handler: async (req) => {
if (!(await allowed(req))) {return Response.json({ ok: false }, { status: 403 })}
let body: { ids?: unknown } = {}
try {
body = ((await (req as unknown as Request).json()) ?? {}) as { ids?: unknown }
} catch {
// no body = approve everything pending
}
const ids = Array.isArray(body.ids)
? body.ids.filter((id): id is number | string => (typeof id === 'string' && id.length <= 64) || Number.isInteger(id)).slice(0, 1000)
: undefined
try {
const result = await approveCookies({ addToList: options.syncAccepted !== false, ids, payload: req.payload, req, unknownCategory: approval.unknownCategory })
return Response.json({ ok: true, result })
} catch (err) {
req.payload.logger.error(`[ipal] cookie approval failed: ${err instanceof Error ? err.message : String(err)}`)
return Response.json({ ok: false }, { status: 500 })
}
},
method: 'post',
path: COOKIE_APPROVAL_PATH,
},
]
}
+25 -2
View File
@@ -23,6 +23,10 @@ const setKey: CollectionBeforeChangeHook = ({ data, originalDoc }) => {
data.name = name
data.key = `${storage}:${name}`
}
// An editor who writes the purpose has described the cookie.
if (typeof data.purpose === 'string' && data.purpose.trim() && (data.needsDescription ?? originalDoc?.needsDescription)) {
data.needsDescription = false
}
return data
}
@@ -91,9 +95,9 @@ export function buildCookieReviewCollection(options: CookieScannerOptions = {}):
},
admin: {
components: {
beforeListTable: [{ clientProps: { crawl, labels }, path: '@intecion/ipal-kit/admin#CookieScanButton' }],
beforeListTable: [{ clientProps: { approval: options.approval !== false, crawl, labels }, path: '@intecion/ipal-kit/admin#CookieScanButton' }],
},
defaultColumns: ['name', 'vendor', 'category', 'status', 'source', 'listed', ...(crawl ? ['violation'] : [])],
defaultColumns: ['name', 'vendor', 'category', 'status', 'change', 'listed', ...(crawl ? ['violation'] : [])],
description: L('collectionDescription'),
group: { en: 'Privacy', pl: 'Prywatność' },
listSearchableFields: ['name', 'vendor'],
@@ -178,6 +182,25 @@ export function buildCookieReviewCollection(options: CookieScannerOptions = {}):
admin: { description: L('listedDescription'), position: 'sidebar', readOnly: true },
label: L('listed'),
},
{
name: 'change',
type: 'select',
admin: { description: L('changeDescription'), position: 'sidebar', readOnly: true },
index: true,
label: L('change'),
options: [
{ label: L('changeNew'), value: 'new' },
{ label: L('changeChanged'), value: 'changed' },
{ label: L('changeGone'), value: 'gone' },
],
},
{
name: 'needsDescription',
type: 'checkbox',
admin: { description: L('needsDescriptionDescription'), position: 'sidebar' },
defaultValue: false,
label: L('needsDescription'),
},
{ name: 'lastScannedAt', type: 'date', admin: { position: 'sidebar', readOnly: true }, label: L('lastScannedAt') },
...crawlFields,
// `storage:name`, one entry per cookie — what a rescan matches on.
@@ -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)
+16 -3
View File
@@ -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 })
}
}
+12 -5
View File
@@ -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)}`)
+15 -3
View File
@@ -1,4 +1,15 @@
// Cookie scanner — server-safe building blocks. The admin button is in /admin.
export {
approveCookies,
buildCookieApprovalEndpoints,
COOKIE_APPROVAL_PATH,
COOKIE_APPROVAL_VIEW_PATH,
countPendingCookies,
DEFAULT_UNKNOWN_CATEGORY,
loadCookieApproval,
PENDING_WHERE,
} from './approval.js'
export type { CookieApprovalItem, CookieApprovalList, CookieApprovalResult } from './approval.js'
export { buildCookieReviewCollection, COOKIE_REVIEW_SLUG } from './collection.js'
export { DEFAULT_DATABASE_CATEGORIES, indexCookieDatabase, loadCookieDatabase, lookupCookie } from './cookieDatabase.js'
export type { CookieDatabaseIndex } from './cookieDatabase.js'
@@ -26,10 +37,11 @@ export { COOKIE_SCAN_LABELS, mergeCookieScanLabels } from './labels.js'
export type { CookieScanLabels } from './labels.js'
export { mergeCookieReview, suggestionFor } from './merge.js'
export type { CookieReviewValues } from './merge.js'
export { applyCookieFindings, collectCookieFindings, cookieScanContext, parseCookieNames, runCookieScan } from './scan.js'
export type { CookieObservation, CookieReviewEntryRef } from './scan.js'
export { addToCookieList } from './sync.js'
export { applyCookieFindings, collectCookieFindings, cookieScanContext, flagGoneEntries, nextChange, parseCookieNames, runCookieScan } from './scan.js'
export type { CookieChange, CookieObservation, CookieReviewEntryRef } from './scan.js'
export { addToCookieList, sameCookie } from './sync.js'
export type {
CookieApprovalOptions,
CookieCrawlOptions,
CookieDeclaration,
CookieFinding,
+94 -4
View File
@@ -10,9 +10,25 @@ export type CookieScanLabels = {
alertLink: string
alertTitle: string
analytics: string
approvalButton: string
approvalDone: string
approvalEmpty: string
approvalError: string
approvalIntro: string
approvalLink: string
approvalNoAccess: string
approvalPending: string
approvalSelected: string
approvalTitle: string
approving: string
beforeConsentOn: string
category: string
categoryRequired: string
change: string
changeChanged: string
changeDescription: string
changeGone: string
changeNew: string
collectionDescription: string
cookie: string
crawlButton: string
@@ -38,10 +54,16 @@ export type CookieScanLabels = {
database: string
domain: string
draft: string
edit: string
emailIntro: string
emailPending: string
emailSubject: string
emailSubjectPending: string
finishedAt: string
functional: string
goneNote: string
goneTitle: string
include: string
integration: string
integrationsFound: string
integrationsNone: string
@@ -50,14 +72,20 @@ export type CookieScanLabels = {
listedDescription: string
localStorage: string
manual: string
markerChanged: string
markerNew: string
markerUnknown: string
marketing: string
name: string
namesHint: string
namesLabel: string
necessary: string
needsDescription: string
needsDescriptionDescription: string
notifyEmails: string
notifyEmailsDescription: string
notifyEmailsInvalid: string
openCookieBanner: string
plural: string
project: string
purpose: string
@@ -81,6 +109,8 @@ export type CookieScanLabels = {
status: string
statusDescription: string
storage: string
uncategorized: string
uncategorizedNote: string
unknown: string
vendor: string
violation: string
@@ -97,10 +127,26 @@ export const COOKIE_SCAN_LABELS: Record<'en' | 'pl', CookieScanLabels> = {
alertLink: 'Open cookie review',
alertTitle: 'Cookie check: violations: {violations}, new unknown cookies: {newUnknown}.',
analytics: 'Analytics',
approvalButton: 'Approve and add',
approvalDone: 'Added: {added}, completed: {filled}, need a description: {needsDescription}.',
approvalEmpty: 'Nothing is waiting for approval. Scan cookies to look for new ones.',
approvalError: 'Approval failed. Please try again.',
approvalIntro: 'Check the cookies found, untick any you do not want, then add them to the cookie banner and the cookie policy.',
approvalLink: 'Review and approve',
approvalNoAccess: 'You cannot approve cookies. Ask your administrator.',
approvalPending: 'Waiting for approval: {count}.',
approvalSelected: 'Selected: {count}',
approvalTitle: 'Approve cookies',
approving: 'Adding…',
beforeConsentOn: 'before consent on {pages}',
category: 'Category',
categoryRequired: 'Choose a category before accepting.',
collectionDescription: 'Accept a cookie to add it to the cookie list; a new scan never overwrites your edits.',
change: 'Latest scan',
changeChanged: 'Changed',
changeDescription: 'What the latest scan found; approving clears it.',
changeGone: 'No longer found',
changeNew: 'New',
collectionDescription: 'Cookies found by scans; approve them to add them to the cookie banner, your edits are kept.',
cookie: 'Cookie',
crawlButton: 'Check site',
crawlCreated: 'New drafts',
@@ -125,10 +171,16 @@ export const COOKIE_SCAN_LABELS: Record<'en' | 'pl', CookieScanLabels> = {
database: 'Open Cookie Database',
domain: 'Domain',
draft: 'Draft',
edit: 'Edit',
emailIntro: 'The latest cookie check of {site} found:',
emailPending: 'Cookies waiting for approval: {count}. Nothing is added to the cookie banner until you approve them.',
emailSubject: 'Cookie check of {site}: violations: {violations}, new unknown cookies: {newUnknown}',
emailSubjectPending: 'Cookie check of {site}: cookies waiting for approval: {count}',
finishedAt: 'Finished',
functional: 'Functional',
goneNote: 'They stay in the cookie banner; remove them there if the site no longer uses them.',
goneTitle: 'No longer found',
include: 'Include',
integration: 'Built-in integration',
integrationsFound: 'Integrations in use',
integrationsNone: 'No integration that uses cookies is on.',
@@ -137,13 +189,19 @@ export const COOKIE_SCAN_LABELS: Record<'en' | 'pl', CookieScanLabels> = {
listedDescription: 'Already in the cookie list of the cookie banner.',
localStorage: 'Local storage',
manual: 'Added by hand',
markerChanged: 'Changed',
markerNew: 'New',
markerUnknown: 'Needs description',
marketing: 'Marketing',
namesHint: 'Optional. Other cookie names, one per line. They are looked up in the Open Cookie Database.',
namesLabel: 'More cookie names',
necessary: 'Necessary',
needsDescription: 'Needs description',
needsDescriptionDescription: 'Write the purpose so visitors know what this cookie does.',
notifyEmails: 'Warning e-mails to',
notifyEmailsDescription: 'Comma-separated addresses that get a warning when a check finds problems; leave empty for none.',
notifyEmailsInvalid: 'Enter e-mail addresses separated by commas, e.g. [email protected], [email protected].',
openCookieBanner: 'Open cookie banner',
plural: 'Cookie review',
project: 'Site configuration',
purpose: 'Purpose',
@@ -151,7 +209,7 @@ export const COOKIE_SCAN_LABELS: Record<'en' | 'pl', CookieScanLabels> = {
retention: 'Duration',
scanButton: 'Scan cookies',
scanError: 'The scan failed. Please try again.',
scanIntro: 'Adds the cookies of the integrations in use as drafts to review.',
scanIntro: 'Finds the cookies of the integrations in use; nothing is added to the cookie banner until you approve.',
scanning: 'Scanning…',
scanResult: 'New: {created}, updated: {updated}, unchanged: {unchanged}, unknown: {unknown}.',
seenBeforeConsent: 'Seen before consent',
@@ -166,6 +224,8 @@ export const COOKIE_SCAN_LABELS: Record<'en' | 'pl', CookieScanLabels> = {
status: 'Status',
statusDescription: 'Accepted cookies are added to the cookie list; rejecting never removes them from it.',
storage: 'Stored in',
uncategorized: 'Not yet described',
uncategorizedNote: 'Nothing is known about these yet; they are added as {category} until you describe them.',
unknown: 'Unknown',
vendor: 'Provider',
violation: 'Violation',
@@ -180,10 +240,26 @@ export const COOKIE_SCAN_LABELS: Record<'en' | 'pl', CookieScanLabels> = {
alertLink: 'Otwórz przegląd cookies',
alertTitle: 'Kontrola cookies: naruszenia: {violations}, nowe nieznane cookies: {newUnknown}.',
analytics: 'Analityczne',
approvalButton: 'Zatwierdź i dodaj',
approvalDone: 'Dodano: {added}, uzupełniono: {filled}, wymaga opisu: {needsDescription}.',
approvalEmpty: 'Nic nie czeka na zatwierdzenie. Zeskanuj cookies, aby znaleźć nowe.',
approvalError: 'Zatwierdzenie się nie powiodło. Spróbuj ponownie.',
approvalIntro: 'Sprawdź znalezione cookies, odznacz niepotrzebne i dodaj je do banera cookies oraz polityki cookies.',
approvalLink: 'Przejrzyj i zatwierdź',
approvalNoAccess: 'Brak uprawnień do zatwierdzania cookies. Zapytaj administratora.',
approvalPending: 'Czeka na zatwierdzenie: {count}.',
approvalSelected: 'Zaznaczone: {count}',
approvalTitle: 'Zatwierdzanie cookies',
approving: 'Dodawanie…',
beforeConsentOn: 'przed zgodą na {pages}',
category: 'Kategoria',
categoryRequired: 'Wybierz kategorię przed akceptacją.',
collectionDescription: 'Zaakceptuj plik cookie, aby dodać go do listy cookies; kolejny skan nie nadpisze zmian.',
change: 'Ostatni skan',
changeChanged: 'Zmieniony',
changeDescription: 'Co wykrył ostatni skan; zatwierdzenie to czyści.',
changeGone: 'Już nie występuje',
changeNew: 'Nowy',
collectionDescription: 'Cookies znalezione przez skany; zatwierdź je, aby dodać do banera cookies, wprowadzone zmiany zostają.',
cookie: 'Cookie',
crawlButton: 'Sprawdź witrynę',
crawlCreated: 'Nowe szkice',
@@ -208,10 +284,16 @@ export const COOKIE_SCAN_LABELS: Record<'en' | 'pl', CookieScanLabels> = {
database: 'Open Cookie Database',
domain: 'Domena',
draft: 'Szkic',
edit: 'Edytuj',
emailIntro: 'Ostatnia kontrola cookies witryny {site} wykazała:',
emailPending: 'Cookies czekające na zatwierdzenie: {count}. Nic nie trafi do banera cookies bez zatwierdzenia.',
emailSubject: 'Kontrola cookies {site}: naruszenia: {violations}, nowe nieznane cookies: {newUnknown}',
emailSubjectPending: 'Skan cookies {site}: cookies czekające na zatwierdzenie: {count}',
finishedAt: 'Zakończono',
functional: 'Funkcjonalne',
goneNote: 'Zostają w banerze cookies; usuń je tam, jeśli witryna już ich nie używa.',
goneTitle: 'Już nie występują',
include: 'Uwzględnij',
integration: 'Wbudowana integracja',
integrationsFound: 'Używane integracje',
integrationsNone: 'Żadna integracja używająca cookies nie jest włączona.',
@@ -220,13 +302,19 @@ export const COOKIE_SCAN_LABELS: Record<'en' | 'pl', CookieScanLabels> = {
listedDescription: 'Już jest na liście cookies banera.',
localStorage: 'Local storage',
manual: 'Dodany ręcznie',
markerChanged: 'Zmieniony',
markerNew: 'Nowy',
markerUnknown: 'Wymaga opisu',
marketing: 'Marketingowe',
namesHint: 'Opcjonalnie. Inne nazwy cookies, po jednej w wierszu. Zostaną wyszukane w Open Cookie Database.',
namesLabel: 'Dodatkowe nazwy cookies',
necessary: 'Niezbędne',
needsDescription: 'Wymaga opisu',
needsDescriptionDescription: 'Wpisz cel, aby odwiedzający wiedzieli, do czego służy to cookie.',
notifyEmails: 'Ostrzeżenia e-mail do',
notifyEmailsDescription: 'Adresy po przecinku, na które trafi ostrzeżenie, gdy kontrola wykryje problemy; zostaw puste, aby nie wysyłać.',
notifyEmailsInvalid: 'Wpisz adresy e-mail oddzielone przecinkami, np. [email protected], [email protected].',
openCookieBanner: 'Otwórz baner cookies',
plural: 'Przegląd cookies',
project: 'Konfiguracja witryny',
purpose: 'Cel',
@@ -234,7 +322,7 @@ export const COOKIE_SCAN_LABELS: Record<'en' | 'pl', CookieScanLabels> = {
retention: 'Okres',
scanButton: 'Skanuj cookies',
scanError: 'Skanowanie nie powiodło się. Spróbuj ponownie.',
scanIntro: 'Dodaje cookies używanych integracji jako szkice do przejrzenia.',
scanIntro: 'Wyszukuje cookies używanych integracji; nic nie trafi do banera cookies bez zatwierdzenia.',
scanning: 'Skanowanie…',
scanResult: 'Nowe: {created}, zaktualizowane: {updated}, bez zmian: {unchanged}, nieznane: {unknown}.',
seenBeforeConsent: 'Widoczny przed zgodą',
@@ -249,6 +337,8 @@ export const COOKIE_SCAN_LABELS: Record<'en' | 'pl', CookieScanLabels> = {
status: 'Status',
statusDescription: 'Zaakceptowane cookies trafiają na listę cookies; odrzucenie nigdy ich z niej nie usuwa.',
storage: 'Miejsce zapisu',
uncategorized: 'Jeszcze bez opisu',
uncategorizedNote: 'Nic o nich jeszcze nie wiadomo; zostaną dodane jako {category} do czasu uzupełnienia opisu.',
unknown: 'Nieznane',
vendor: 'Dostawca',
violation: 'Naruszenie',
+77 -5
View File
@@ -1,4 +1,4 @@
import type { BasePayload, PayloadRequest } from 'payload'
import type { BasePayload, PayloadRequest, Where } from 'payload'
import type { CookieReviewValues } from './merge.js'
import type {
@@ -15,6 +15,7 @@ import { COOKIE_REVIEW_SLUG } from './collection.js'
import { loadCookieDatabase, lookupCookie } from './cookieDatabase.js'
import { cookieNameMatches, declarationsOf, DEFAULT_COOKIE_INTEGRATIONS, integrationLabel, PROJECT_SOURCE } from './integrations.js'
import { mergeCookieReview, suggestionFor } from './merge.js'
import { sameCookie } from './sync.js'
/** Most names one scan looks up — the panel field is for a handful, not a dump. */
export const MAX_SCAN_NAMES = 200
@@ -142,12 +143,30 @@ export async function collectCookieFindings({
/** A review entry a scan wrote: its id, category (after the merge) and whether it is new. */
export type CookieReviewEntryRef = { category: null | string; created: boolean; id: number | string }
/** What the latest scan or crawl noticed about an entry (shown on the approval page). */
export type CookieChange = 'changed' | 'gone' | 'new'
type ReviewDoc = {
change?: CookieChange | null
id: number | string
key?: string
listed?: boolean | null
status?: 'accepted' | 'draft' | 'rejected' | null
suggested?: CookieReviewValues | null
} & CookieReviewValues
/**
* The marker after a scan: new entries are `new`; a scan that changed an entry's
* suggested values marks it `changed` (a still-unapproved `new` stays `new`);
* finding a `gone` entry again clears it. Rejected entries are never flagged.
*/
export function nextChange(existing: Pick<ReviewDoc, 'change' | 'status'> | undefined, changed: boolean): CookieChange | null {
if (!existing) {return 'new'}
if (existing.status === 'rejected') {return existing.change === 'gone' ? null : (existing.change ?? null)}
if (changed) {return existing.change === 'new' ? 'new' : 'changed'}
return existing.change === 'gone' ? null : (existing.change ?? null)
}
function localesOf(payload: BasePayload): { defaultLocale?: string; locales: (string | undefined)[] } {
const l = payload.config.localization
if (!l) {return { locales: [undefined] }}
@@ -155,6 +174,12 @@ function localesOf(payload: BasePayload): { defaultLocale?: string; locales: (st
return { defaultLocale: l.defaultLocale, locales: [l.defaultLocale, ...codes.filter((c) => c !== l.defaultLocale)] }
}
/** Cookie names that already have a review entry. */
async function reviewedNames(payload: BasePayload, req?: PayloadRequest): Promise<Set<string>> {
const { docs } = await payload.find({ collection: COOKIE_REVIEW_SLUG as never, depth: 0, limit: 0, overrideAccess: true, pagination: false, req, select: { name: true } as never })
return new Set((docs as unknown as { name?: string }[]).map((d) => d.name ?? '').filter(Boolean))
}
/** Names already in Cookie Settings → Cookies. */
async function listedNames(payload: BasePayload, req?: PayloadRequest): Promise<Set<string>> {
try {
@@ -188,7 +213,7 @@ export async function applyCookieFindings({
const { locales } = localesOf(payload)
const codes = locales.filter((l): l is string => Boolean(l))
const listed = await listedNames(payload, req)
const summary: CookieScanSummary = { created: 0, newUnknown: 0, unchanged: 0, unknown: 0, updated: 0 }
const summary: CookieScanSummary = { created: 0, gone: 0, newUnknown: 0, unchanged: 0, unknown: 0, updated: 0 }
const now = new Date().toISOString()
const common = { collection: collection as never, context: { ipalCookieScan: true }, depth: 0, fallbackLocale: false as never, overrideAccess: true, req }
@@ -199,7 +224,7 @@ export async function applyCookieFindings({
const machine = {
key,
lastScannedAt: now,
listed: listed.has(finding.name),
listed: [...listed].some((n) => sameCookie(n, finding.name)),
source: finding.source,
sourceDetail: finding.sourceDetail ?? null,
suggested: next,
@@ -208,6 +233,7 @@ export async function applyCookieFindings({
const existing = found.docs[0] as ReviewDoc | undefined
const values = existing ? mergeCookieReview(existing, existing.suggested, next) : { changed: true, values: next }
const change = nextChange(existing, values.changed)
const { purpose, retention, ...scalars } = values.values
const textIn = (locale: string | undefined) => ({
...(purpose && locale ? { purpose: purpose[locale] ?? null } : {}),
@@ -219,7 +245,7 @@ export async function applyCookieFindings({
let id = existing?.id
for (const [i, locale] of locales.entries()) {
const data = i === 0
? { ...scalars, ...machine, ...textIn(locale), ...(existing ? {} : { name: finding.name, status: 'draft', storage: finding.storage }) }
? { ...scalars, ...machine, change, ...textIn(locale), ...(existing ? {} : { name: finding.name, status: 'draft', storage: finding.storage }) }
: textIn(locale)
if (i > 0 && (!values.changed || !Object.keys(data).length)) {continue}
if (id === undefined) {
@@ -239,6 +265,41 @@ export async function applyCookieFindings({
return summary
}
/**
* Marks entries that a scan or crawl no longer finds as `gone` — for review
* only: nothing is deleted, and the cookie list keeps its row. `where` picks
* the entries this kind of scan is responsible for; `keep` are the review keys
* it did find. Rejected entries are left alone. Returns how many were flagged.
*/
export async function flagGoneEntries({
collection = COOKIE_REVIEW_SLUG,
keep,
payload,
req,
where,
}: {
collection?: string
keep: Set<string>
payload: BasePayload
req?: PayloadRequest
where: Where
}): Promise<number> {
const common = { collection: collection as never, context: { ipalCookieScan: true }, depth: 0, overrideAccess: true, req }
const { docs } = await payload.find({
...common,
limit: 0,
pagination: false,
where: { and: [where, { status: { not_equals: 'rejected' } }, { change: { not_equals: 'gone' } }] },
})
let flagged = 0
for (const doc of docs as unknown as ReviewDoc[]) {
if (!doc.key || keep.has(doc.key)) {continue}
await payload.update({ ...common, id: doc.id, data: { change: 'gone' } as never })
flagged++
}
return flagged
}
/** Scan context from a running Payload: SiteIntegrations + the plugin's module switches. */
export async function cookieScanContext(
payload: BasePayload,
@@ -273,14 +334,25 @@ export async function runCookieScan({
}): Promise<{ enabled: CookieIntegration[]; summary: CookieScanSummary }> {
const ctx = await cookieScanContext(payload, plugin, req)
const integrations = options.integrations ? options.integrations(DEFAULT_COOKIE_INTEGRATIONS) : DEFAULT_COOKIE_INTEGRATIONS
// Rows typed into the cookie list by hand are looked up once, when they have no review entry yet;
// after that the entry is the editor's, and a scan must not re-find it as something else.
const reviewed = await reviewedNames(payload, req)
const listed = [...(await listedNames(payload, req))].filter((n) => !reviewed.has(n))
const { enabled, findings } = await collectCookieFindings({
ctx,
database: options.database !== false,
databaseCategories: options.databaseCategories,
declarations: options.declarations,
integrations,
names: [...new Set([...(await listedNames(payload, req)), ...names])],
names: [...new Set([...listed, ...names])],
})
const summary = await applyCookieFindings({ findings, payload, req })
// An integration switched off, a declaration removed: its cookies are flagged, never deleted.
summary.gone = await flagGoneEntries({
keep: new Set(findings.filter((f) => f.source === 'integration' || f.source === 'project').map((f) => reviewKey(f.storage, f.name))),
payload,
req,
where: { source: { in: ['integration', 'project'] } },
})
return { enabled, summary }
}
+9 -1
View File
@@ -2,6 +2,8 @@ import type { BasePayload, PayloadRequest } from 'payload'
import type { CookieReviewValues } from './merge.js'
import { cookieNameMatches } from './integrations.js'
type Row = {
category?: null | string
duration?: null | string
@@ -15,6 +17,12 @@ type Entry = { name: string } & CookieReviewValues
const empty = (v: unknown) => v === undefined || v === null || (typeof v === 'string' && !v.trim())
/**
* The same cookie in the list: equal names, or one is a pattern covering the
* other (`_ga_*` and `_ga_ABC123`) — so a scan never adds a second row for it.
*/
export const sameCookie = (a: string, b: string) => a === b || cookieNameMatches(a, b) || cookieNameMatches(b, a)
/**
* Adds an accepted review entry to Cookie Settings → Cookies, in every locale.
* A missing row is added; an existing row (same name) gets only its EMPTY
@@ -45,7 +53,7 @@ export async function addToCookieList({
for (const [i, locale] of locales.entries()) {
const g = (await payload.findGlobal({ ...common, locale: locale as never })) as { cookies?: Row[] }
const rows = [...(g.cookies ?? [])]
const row = rows.find((r) => r.name?.trim() === entry.name)
const row = rows.find((r) => Boolean(r.name?.trim()) && sameCookie(r.name!.trim(), entry.name))
let changed = false
if (!row) {
if (i > 0) {continue} // added in the default locale; Payload keeps the row in every locale
+16
View File
@@ -80,6 +80,8 @@ export type OpenCookieCategory = 'Analytics' | 'Functional' | 'Marketing' | 'Nec
/** Totals a scan reports back to the panel. */
export type CookieScanSummary = {
created: number
/** Entries this scan no longer found, flagged for review (never deleted). */
gone: number
/** Entries created by this scan that nothing knew. */
newUnknown: number
unchanged: number
@@ -95,6 +97,12 @@ export type CookieScanSummary = {
export type CookieScannerOptions = {
/** Who may run a scan (GET/POST /api/ipal/cookie-scan) and start a crawl. Default: `editor` and up. */
access?: (args: { req: PayloadRequest }) => boolean | Promise<boolean>
/**
* One approval for everything a scan or crawl found: the "Approve cookies"
* view (grouped by category, one "Approve and add" button) and a dashboard
* reminder while cookies wait. Default on; `false` = review entry by entry only.
*/
approval?: CookieApprovalOptions | false
/** Change the `cookie-review` collection (object merges, function takes over). */
collectionOverrides?: CollectionOverride
/**
@@ -156,3 +164,11 @@ export type CookieCrawlOptions = {
/** Hosts whose requests before consent are violations: `(defaults) => hosts`. */
trackerHosts?: (defaults: string[]) => string[]
}
/** `cookieScanner.approval` — every key optional. */
export type CookieApprovalOptions = {
/** Dashboard reminder while cookies wait for approval. Default true. */
dashboard?: boolean
/** Category for cookies nothing knows until an editor describes them; it should need consent. Default `'marketing'`. */
unknownCategory?: ConsentCategory
}
+42 -15
View File
@@ -11,6 +11,7 @@ import { buildSiteSettings } from './globals/SiteSettings/index.js'
import { adminOnly, adminOrSelf, injectRoles } from './modules/access/index.js'
import { applyAdminI18n } from './modules/admin-i18n/apply.js'
import { buildConsentLogCollection, buildConsentLogEndpoint } from './modules/consent/consentLog.js'
import { buildCookieApprovalEndpoints, COOKIE_APPROVAL_VIEW_PATH } from './modules/consent/scanner/approval.js'
import { buildCookieReviewCollection } from './modules/consent/scanner/collection.js'
import { buildCookieCrawlEndpoints } from './modules/consent/scanner/crawl/endpoints.js'
import { buildCookieCrawlGlobal } from './modules/consent/scanner/crawl/global.js'
@@ -351,13 +352,36 @@ export const ipalKit = (options: IpalOptions): Plugin => {
// --- cookie scanner: review list + "Scan cookies" (opt-in) ---
if (options.cookieScanner) {
const scannerOptions = options.cookieScanner === true ? {} : options.cookieScanner
const adminRoute = options.adminRoute ?? '/admin'
const labels = mergeCookieScanLabels(scannerOptions.labels)
config.collections = [...(config.collections ?? []), applyCollectionOverride(buildCookieReviewCollection(scannerOptions), scannerOptions.collectionOverrides)]
const scanPlugin = { localeCount: options.i18n.locales.length, stats: Boolean(options.stats) }
config.endpoints = [...(config.endpoints ?? []), ...buildCookieScanEndpoints(scannerOptions, scanPlugin)]
// Browser crawl through the scanner service (opt-in): latest-result global, endpoints, dashboard warning.
if (scannerOptions.crawl) {
const crawl = scannerOptions.crawl === true ? {} : scannerOptions.crawl
const labels = mergeCookieScanLabels(scannerOptions.labels)
// One approval for everything found (default on): the "Approve cookies" view and its endpoint.
const approval = scannerOptions.approval === false ? null : (scannerOptions.approval ?? {})
if (approval) {
config.endpoints = [...(config.endpoints ?? []), ...buildCookieApprovalEndpoints(scannerOptions)]
config.admin = {
...(config.admin ?? {}),
components: {
...(config.admin?.components ?? {}),
views: {
...(config.admin?.components?.views ?? {}),
ipalCookieApproval: {
Component: {
path: '@intecion/ipal-kit/admin#CookieApprovalView',
serverProps: { adminRoute, labels, ...(approval.unknownCategory ? { unknownCategory: approval.unknownCategory } : {}) },
},
meta: { title: 'Approve cookies' },
path: COOKIE_APPROVAL_VIEW_PATH,
},
},
},
}
}
// Browser crawl through the scanner service (opt-in): latest-result global, endpoints.
const crawl = scannerOptions.crawl ? (scannerOptions.crawl === true ? {} : scannerOptions.crawl) : null
if (crawl) {
const crawlGlobal = buildCookieCrawlGlobal(labels)
const override = crawl.globalOverride
config.globals = [
@@ -365,17 +389,20 @@ export const ipalKit = (options: IpalOptions): Plugin => {
override ? applyGlobalOverrides([crawlGlobal], { [crawlGlobal.slug]: override } as never)[0] : crawlGlobal,
]
config.endpoints = [...(config.endpoints ?? []), ...buildCookieCrawlEndpoints({ labels, options: scannerOptions, plugin: scanPlugin })]
if (crawl.dashboard !== false) {
config.admin = {
...(config.admin ?? {}),
components: {
...(config.admin?.components ?? {}),
beforeDashboard: [
...(config.admin?.components?.beforeDashboard ?? []),
{ path: '@intecion/ipal-kit/admin#CookieCrawlAlert', serverProps: { adminRoute: options.adminRoute ?? '/admin', labels } },
],
},
}
}
// Dashboard warning: cookies waiting for approval, crawl violations or a failed crawl.
const alertApproval = Boolean(approval && approval.dashboard !== false)
const alertCrawl = Boolean(crawl && crawl.dashboard !== false)
if (alertApproval || alertCrawl) {
config.admin = {
...(config.admin ?? {}),
components: {
...(config.admin?.components ?? {}),
beforeDashboard: [
...(config.admin?.components?.beforeDashboard ?? []),
{ path: '@intecion/ipal-kit/admin#CookieCrawlAlert', serverProps: { adminRoute, approval: alertApproval, crawl: alertCrawl, labels } },
],
},
}
}
}