Merge claude/cookie-scanner-eef8a8: cookie scanner phases 1 and 2

cookieScanner option: cookie-review collection, Scan cookies (declarations +
bundled Open Cookie Database), opt-in browser crawl through
services/cookie-crawler with the cookie-crawl global and dashboard alert.

Overlap with claude/test-no-typegen, resolved here: one test-config fix.
- the six real-Payload tests keep buildTestConfig and drop the branch's
  duplicate typescript: { autoGenerate: false } lines;
- cookieScannerIntegration and cookieCrawlIntegration use buildTestConfig
  instead of buildConfig + their own flag (testConfig.test.ts guard passes).
This commit is contained in:
Radosław Smoliński
2026-10-27 15:26:44 +01:00
54 changed files with 6925 additions and 7 deletions
@@ -0,0 +1,175 @@
'use client'
import { Button, useConfig, useTranslation } from '@payloadcms/ui'
import { useRouter } from 'next/navigation.js'
import { useEffect, useState } from 'react'
import type { CookieScanLabels } from './labels.js'
import type { CookieScanSummary } from './types.js'
import { COOKIE_SCAN_LABELS } from './labels.js'
type CrawlState = {
configured: boolean
error: null | string
finishedAt: null | string
missing: string[]
startedAt: null | string
status: 'done' | 'failed' | 'idle' | 'running'
summary: { newUnknown?: null | number; pages?: null | number; violations?: null | number } | null
}
type Status =
| { kind: 'done'; summary: CookieScanSummary }
| { kind: 'error' }
| { kind: 'idle' }
| { kind: 'scanning' }
const fill = (template: string, values: Record<string, null | number | string>) =>
template.replace(/\{(\w+)\}/g, (_, k: string) => String(values[k] ?? ''))
/**
* Admin UI above the Cookie review list (beforeListTable): shows which
* integrations a scan covers, takes optional extra cookie names, runs
* POST /api/ipal/cookie-scan and reloads the list. With `crawl`, also "Crawl
* site" (POST /api/ipal/cookie-crawl) and the latest crawl's status, polled
* 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> }) {
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-scan`
const [names, setNames] = useState('')
const [integrations, setIntegrations] = useState<{ key: string; label: string }[] | null>(null)
const [status, setStatus] = useState<Status>({ kind: 'idle' })
const [crawlState, setCrawlState] = useState<CrawlState | null>(null)
const [crawlStarting, setCrawlStarting] = useState(false)
const crawlEndpoint = endpoint.replace(/cookie-scan$/, 'cookie-crawl')
const when = (iso: null | string) => (iso ? new Date(iso).toLocaleString(i18n.language) : '')
useEffect(() => {
if (!crawl) {return}
let stopped = false
let wasRunning = false
const poll = async () => {
try {
const res = await fetch(crawlEndpoint, { credentials: 'include' })
const data = res.ok ? ((await res.json()) as CrawlState) : null
if (stopped || !data) {return}
setCrawlState(data)
if (wasRunning && data.status !== 'running') {router.refresh()}
wasRunning = data.status === 'running'
} catch {
// offline — try again on the next tick
}
}
void poll()
const timer = setInterval(() => void poll(), 3000)
return () => {
stopped = true
clearInterval(timer)
}
}, [crawl, crawlEndpoint, router])
const startCrawl = async () => {
setCrawlStarting(true)
try {
await fetch(crawlEndpoint, { credentials: 'include', method: 'POST' })
const res = await fetch(crawlEndpoint, { credentials: 'include' })
if (res.ok) {setCrawlState((await res.json()) as CrawlState)}
} finally {
setCrawlStarting(false)
}
}
useEffect(() => {
fetch(endpoint, { credentials: 'include' })
.then((r) => (r.ok ? r.json() : null))
.then((data: { integrations?: { key: string; label: string }[] } | null) => setIntegrations(data?.integrations ?? []))
.catch(() => setIntegrations([]))
}, [endpoint])
const scan = async () => {
setStatus({ kind: 'scanning' })
try {
const res = await fetch(endpoint, {
body: JSON.stringify({ names: names.split('\n') }),
credentials: 'include',
headers: { 'Content-Type': 'application/json' },
method: 'POST',
})
const data = (await res.json()) as { ok?: boolean; summary?: CookieScanSummary }
if (!res.ok || !data.ok || !data.summary) {throw new Error('scan failed')}
setStatus({ kind: 'done', summary: data.summary })
router.refresh()
} catch {
setStatus({ kind: 'error' })
}
}
const result = (s: CookieScanSummary) =>
t.scanResult.replace(/\{(\w+)\}/g, (_, k: string) => String(s[k as keyof CookieScanSummary] ?? ''))
return (
<div className="ipal-cookie-scan" data-ipal="cookie-scan" style={{ marginBottom: '1.5rem' }}>
<p style={{ marginTop: 0 }}>{t.scanIntro}</p>
{integrations ? (
<p style={{ fontSize: '.85rem', opacity: 0.8 }}>
{integrations.length ? `${t.integrationsFound}: ${integrations.map((i) => i.label).join(', ')}` : t.integrationsNone}
</p>
) : null}
<label className="field-label" htmlFor="ipal-cookie-scan-names">{t.namesLabel}</label>
<p style={{ fontSize: '.85rem', marginTop: 0, opacity: 0.7 }}>{t.namesHint}</p>
<textarea
aria-label={t.namesLabel}
id="ipal-cookie-scan-names"
onChange={(e) => setNames(e.target.value)}
placeholder={'_hjSessionUser_123\nintercom-id-abc'}
rows={3}
style={{ fontFamily: 'monospace', marginBottom: '.5rem', width: '100%' }}
value={names}
/>
<div style={{ alignItems: 'center', display: 'flex', flexWrap: 'wrap', gap: '1rem' }}>
<Button buttonStyle="primary" disabled={status.kind === 'scanning'} margin={false} onClick={() => void scan()} size="medium">
{status.kind === 'scanning' ? t.scanning : t.scanButton}
</Button>
{status.kind === 'done' ? <span role="status">✓ {result(status.summary)}</span> : null}
{status.kind === 'error' ? (
<span role="alert" style={{ color: 'var(--theme-error-500, crimson)' }}>✗ {t.scanError}</span>
) : null}
</div>
{crawl ? (
<div data-ipal="cookie-crawl" style={{ borderTop: '1px solid var(--theme-elevation-150, #ddd)', marginTop: '1.25rem', paddingTop: '1rem' }}>
<p style={{ marginTop: 0 }}>{t.crawlIntro}</p>
<div style={{ alignItems: 'center', display: 'flex', flexWrap: 'wrap', gap: '1rem' }}>
<Button
buttonStyle="secondary"
disabled={!crawlState?.configured || crawlState.status === 'running' || crawlStarting}
margin={false}
onClick={() => void startCrawl()}
size="medium"
>
{t.crawlButton}
</Button>
<span role="status">
{crawlState && !crawlState.configured ? `${t.crawlNotConfigured} (${crawlState.missing.join(', ')})` : null}
{crawlState?.configured && crawlState.status === 'running' ? fill(t.crawlRunning, { startedAt: when(crawlState.startedAt) }) : null}
{crawlState?.configured && crawlState.status === 'done'
? fill(t.crawlDone, { finishedAt: when(crawlState.finishedAt), newUnknown: crawlState.summary?.newUnknown ?? 0, pages: crawlState.summary?.pages ?? 0, violations: crawlState.summary?.violations ?? 0 })
: null}
{/* a finished crawl can still carry a note, e.g. "Accept all" not found */}
{crawlState?.configured && crawlState.status === 'done' && crawlState.error ? ` ⚠ ${crawlState.error}` : null}
{crawlState?.configured && crawlState.status === 'idle' ? t.crawlIdle : null}
{crawlState?.configured && crawlState.status === 'failed' ? fill(t.crawlFailed, { error: crawlState.error ?? '' }) : null}
</span>
</div>
</div>
) : null}
</div>
)
}
export default CookieScanButton
+195
View File
@@ -0,0 +1,195 @@
import type { CollectionAfterChangeHook, CollectionBeforeChangeHook, CollectionConfig, Field } from 'payload'
import type { CookieReviewValues } from './merge.js'
import type { CookieScannerOptions } from './types.js'
import { userMeetsRole } from '../../access/predicates.js'
import { CONSENT_CATEGORIES } from '../categories.js'
import { type CookieScanLabels, labelFor, labelRecord, mergeCookieScanLabels } from './labels.js'
import { addToCookieList } from './sync.js'
/**
* Cookie review list — drafts from "Scan cookies" that an editor accepts,
* edits or rejects. Accepting adds the cookie to Cookie Settings → Cookies
* (the banner's detailed window and <CookieTable>). Opt-in:
* `ipalKit({ cookieScanner: true })`.
*/
export const COOKIE_REVIEW_SLUG = 'cookie-review'
const setKey: CollectionBeforeChangeHook = ({ data, originalDoc }) => {
const name = (data.name ?? originalDoc?.name)?.trim()
const storage = data.storage ?? originalDoc?.storage ?? 'cookie'
if (name) {
data.name = name
data.key = `${storage}:${name}`
}
return data
}
function buildSyncHook(): CollectionAfterChangeHook {
return async ({ context, doc, previousDoc, req }) => {
if (context?.ipalCookieScan || doc.status !== 'accepted' || previousDoc?.status === 'accepted') {return doc}
// Local API calls with `req` rewrite req.locale / req.fallbackLocale; the editor's own
// save is still being read after this hook, so put them back.
const { fallbackLocale, locale } = req
try {
const full = (await req.payload.findByID({
id: doc.id,
collection: COOKIE_REVIEW_SLUG as never,
depth: 0,
locale: (req.payload.config.localization ? 'all' : undefined) as never,
overrideAccess: true,
req,
})) as unknown as { name: string } & CookieReviewValues
const result = await addToCookieList({ entry: full, payload: req.payload, req })
req.payload.logger.info(`[ipal] cookie review: "${full.name}" accepted → Cookie Settings (${result})`)
if (!doc.listed) {
await req.payload.update({
id: doc.id,
collection: COOKIE_REVIEW_SLUG as never,
context: { ipalCookieScan: true },
data: { listed: true } as never,
overrideAccess: true,
req,
})
}
} finally {
req.locale = locale
req.fallbackLocale = fallbackLocale
}
return { ...doc, listed: true }
}
}
export function buildCookieReviewCollection(options: CookieScannerOptions = {}): CollectionConfig {
const labels = mergeCookieScanLabels(options.labels)
const L = (key: keyof CookieScanLabels) => labelRecord(labels, key)
const crawl = Boolean(options.crawl)
// Only with `crawl`: what the latest browser crawl saw before consent (reset on every crawl).
const crawlFields: Field[] = crawl
? [
{
name: 'violation',
type: 'checkbox',
admin: { description: L('violationDescription'), position: 'sidebar', readOnly: true },
defaultValue: false,
index: true,
label: L('violation'),
},
{ name: 'violationDetail', type: 'text', admin: { position: 'sidebar', readOnly: true }, label: L('violationDetail') },
{ name: 'seenBeforeConsent', type: 'checkbox', admin: { position: 'sidebar', readOnly: true }, defaultValue: false, index: true, label: L('seenBeforeConsent') },
]
: []
return {
slug: COOKIE_REVIEW_SLUG,
access: {
// Written by editors (review) and by the scan (Local API); deleting is admin-only and never automatic.
create: ({ req }) => userMeetsRole(req, 'editor'),
delete: ({ req }) => userMeetsRole(req, 'admin'),
read: ({ req }) => userMeetsRole(req, 'editor'),
update: ({ req }) => userMeetsRole(req, 'editor'),
},
admin: {
components: {
beforeListTable: [{ clientProps: { crawl, labels }, path: '@intecion/ipal-kit/admin#CookieScanButton' }],
},
defaultColumns: ['name', 'vendor', 'category', 'status', 'source', 'listed', ...(crawl ? ['violation'] : [])],
description: L('collectionDescription'),
group: 'Settings',
listSearchableFields: ['name', 'vendor'],
useAsTitle: 'name',
},
fields: [
{
type: 'row',
fields: [
{ name: 'name', type: 'text', admin: { width: '50%' }, label: L('name'), required: true },
{
name: 'storage',
type: 'select',
admin: { width: '25%' },
defaultValue: 'cookie',
label: L('storage'),
options: [
{ label: L('cookie'), value: 'cookie' },
{ label: L('localStorage'), value: 'localStorage' },
{ label: L('sessionStorage'), value: 'sessionStorage' },
],
required: true,
},
{
name: 'category',
type: 'select',
admin: { width: '25%' },
label: L('category'),
options: CONSENT_CATEGORIES.map((c) => ({ label: L(c), value: c })),
validate: (value: unknown, { req, siblingData }: { req: { i18n?: { language?: string } }; siblingData: { status?: string } }) =>
siblingData?.status === 'accepted' && !value ? labelFor(labels, req.i18n?.language, 'categoryRequired') : true,
},
],
},
{
type: 'row',
fields: [
{ name: 'vendor', type: 'text', admin: { width: '50%' }, label: L('vendor') },
{ name: 'domain', type: 'text', admin: { width: '50%' }, label: L('domain') },
],
},
{ name: 'purpose', type: 'textarea', label: L('purpose'), localized: true },
{ name: 'retention', type: 'text', label: L('retention'), localized: true },
{
name: 'setBeforeConsent',
type: 'checkbox',
admin: { description: L('setBeforeConsentDescription') },
label: L('setBeforeConsent'),
},
{
name: 'status',
type: 'select',
admin: { description: L('statusDescription'), position: 'sidebar' },
defaultValue: 'draft',
index: true,
label: L('status'),
options: [
{ label: L('draft'), value: 'draft' },
{ label: L('accepted'), value: 'accepted' },
{ label: L('rejected'), value: 'rejected' },
],
required: true,
},
{
name: 'source',
type: 'select',
admin: { position: 'sidebar', readOnly: true },
defaultValue: 'manual',
label: L('source'),
options: [
{ label: L('integration'), value: 'integration' },
{ label: L('project'), value: 'project' },
{ label: L('database'), value: 'database' },
{ label: L('unknown'), value: 'unknown' },
{ label: L('manual'), value: 'manual' },
],
},
{ name: 'sourceDetail', type: 'text', admin: { position: 'sidebar', readOnly: true }, label: L('sourceDetail') },
{
name: 'listed',
type: 'checkbox',
admin: { description: L('listedDescription'), position: 'sidebar', readOnly: true },
label: L('listed'),
},
{ name: 'lastScannedAt', type: 'date', admin: { position: 'sidebar', readOnly: true }, label: L('lastScannedAt') },
...crawlFields,
// `storage:name`, one entry per cookie — what a rescan matches on.
{ name: 'key', type: 'text', admin: { hidden: true }, index: true, unique: true },
// The last scan's suggestion: a value still equal to it was not edited and may follow the next scan.
{ name: 'suggested', type: 'json', admin: { hidden: true } },
],
hooks: {
afterChange: options.syncAccepted === false ? [] : [buildSyncHook()],
beforeChange: [setKey],
},
labels: { plural: L('plural'), singular: L('singular') },
timestamps: true,
}
}
@@ -0,0 +1,78 @@
import type { ConsentCategory } from '../categories.js'
import type { OpenCookieRow } from './data/openCookieDatabase.js'
import type { CookieFinding, OpenCookieCategory } from './types.js'
/**
* Lookup in the bundled Open Cookie Database (Apache-2.0,
* github.com/jkwakman/Open-Cookie-Database; license in
* docs/licenses/open-cookie-database-LICENSE.txt). Refreshed by
* `scripts/refresh-cookie-database.mjs` — nothing is fetched at runtime. The
* ~430 KB table is imported only when a scan needs it.
*/
export const DEFAULT_DATABASE_CATEGORIES: Record<OpenCookieCategory, ConsentCategory> = {
Analytics: 'analytics',
// The database defines Functional as "technical, essential or strictly necessary", but
// contributors file trackers there too (Hotjar's user id). An unchecked lookup must not
// land as "no consent needed": it asks for consent until an editor says otherwise.
Functional: 'functional',
Marketing: 'marketing',
Necessary: 'necessary',
Personalization: 'functional',
Security: 'necessary',
}
/** An index over database rows: exact names, then prefixes (longest first). */
export type CookieDatabaseIndex = {
exact: Map<string, OpenCookieRow>
prefixes: OpenCookieRow[]
}
export function indexCookieDatabase(rows: readonly OpenCookieRow[]): CookieDatabaseIndex {
const exact = new Map<string, OpenCookieRow>()
const prefixes: OpenCookieRow[] = []
for (const row of rows) {
if (row[7] === 1) {prefixes.push(row)}
else if (!exact.has(row[0])) {exact.set(row[0], row)}
}
prefixes.sort((a, b) => b[0].length - a[0].length)
return { exact, prefixes }
}
let bundled: CookieDatabaseIndex | null = null
/** The bundled database, indexed once per process. */
export async function loadCookieDatabase(): Promise<CookieDatabaseIndex> {
if (!bundled) {
const { OPEN_COOKIE_DATABASE } = await import('./data/openCookieDatabase.js')
bundled = indexCookieDatabase(OPEN_COOKIE_DATABASE)
}
return bundled
}
/**
* A cookie name looked up in the database: exact name first, then the longest
* matching wildcard prefix (`_gac_` matches `_gac_UA-1`). Null when unknown.
*/
export function lookupCookie(
index: CookieDatabaseIndex,
name: string,
categories: Partial<Record<OpenCookieCategory, ConsentCategory>> = {},
): CookieFinding | null {
const row = index.exact.get(name) ?? index.prefixes.find((r) => r[0] && name.startsWith(r[0]))
if (!row) {return null}
const [pattern, platform, category, domain, description, retention, controller, wildcard] = row
const map = { ...DEFAULT_DATABASE_CATEGORIES, ...categories }
const thirdParty = /\(3rd party\)/i.test(domain) ? domain.replace(/\s*\(3rd party\)/i, '').trim() : ''
return {
category: map[category as OpenCookieCategory],
...(thirdParty ? { domain: thirdParty } : {}),
name: wildcard === 1 && pattern !== name ? `${pattern}*` : name,
...(description ? { purpose: description } : {}),
...(retention ? { retention } : {}),
source: 'database',
sourceDetail: `Open Cookie Database: ${platform}${category ? ` (${category})` : ''}`,
storage: 'cookie',
vendor: controller || platform,
}
}
@@ -0,0 +1,68 @@
import type { Payload } from 'payload'
import type { CookieScanLabels } from '../labels.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
/** Injected by Payload into admin server components. */
i18n?: { language?: string }
labels?: Record<string, CookieScanLabels>
payload?: Payload
}
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.
*/
export async function CookieCrawlAlert({ adminRoute = '/admin', 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
}
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
return (
<div
data-ipal="cookie-crawl-alert"
role="alert"
style={{
background: 'var(--theme-warning-50, rgba(255, 178, 36, 0.1))',
border: '1px solid var(--theme-warning-400, #ffb224)',
borderRadius: 4,
marginBottom: '1.5rem',
padding: '1rem 1.25rem',
}}
>
{failed ? (
<strong>{fill(t('alertFailed'), { error: doc.error ?? '' })}</strong>
) : (
<>
<strong>{fill(t('alertTitle'), { newUnknown, violations })}</strong>
<p style={{ margin: '0.5rem 0 0' }}>{t('alertBody')}</p>
</>
)}
<a href={href} style={{ display: 'block', marginTop: '0.5rem' }}>
{t('alertLink')}
</a>
</div>
)
}
export default CookieCrawlAlert
@@ -0,0 +1,42 @@
import type { BasePayload } from 'payload'
import type { CookieCrawlOptions } from '../types.js'
import { DEFAULT_TRACKER_HOSTS } from './violations.js'
export const COOKIE_CRAWL_SLUG = 'cookie-crawl'
export const COOKIE_CRAWL_PATH = '/ipal/cookie-crawl'
export const COOKIE_CRAWL_RESULTS_PATH = '/ipal/cookie-crawl/results'
export const COOKIE_SCAN_URL_ENV = 'IPAL_COOKIE_SCAN_URL'
export const COOKIE_SCAN_TOKEN_ENV = 'IPAL_COOKIE_SCAN_TOKEN'
/** A crawl still "running" after this long is treated as lost (the service never called back). */
export const CRAWL_TIMEOUT_MS = 30 * 60_000
export type ResolvedCrawlConfig = {
acceptSelector: string
consentMode: 'advanced' | 'basic'
maxPages: number
/** Null when not configured — the panel says what is missing. */
serviceUrl: null | string
siteUrl: null | string
token: null | string
trackerHosts: string[]
}
const trimSlash = (v: string) => v.replace(/\/+$/, '')
/** Options + env + Payload config, read at call time (env can change between deploys, not between requests). */
export function resolveCrawlConfig(options: CookieCrawlOptions, payload: BasePayload): ResolvedCrawlConfig {
const serviceUrl = options.serviceUrl ?? process.env[COOKIE_SCAN_URL_ENV]?.trim()
const token = options.token ?? process.env[COOKIE_SCAN_TOKEN_ENV]?.trim()
const siteUrl = options.siteUrl ?? (payload.config.serverURL || process.env.NEXT_PUBLIC_SERVER_URL?.trim())
return {
acceptSelector: options.acceptSelector ?? '[data-ipal="accept"]',
consentMode: options.consentMode ?? 'advanced',
maxPages: Math.min(100, Math.max(0, Math.trunc(options.maxPages ?? 20))),
serviceUrl: serviceUrl && /^https?:\/\//.test(serviceUrl) ? trimSlash(serviceUrl) : null,
siteUrl: siteUrl && /^https?:\/\//.test(siteUrl) ? trimSlash(siteUrl) : null,
token: token && token.length >= 16 ? token : null,
trackerHosts: options.trackerHosts ? options.trackerHosts(DEFAULT_TRACKER_HOSTS) : DEFAULT_TRACKER_HOSTS,
}
}
@@ -0,0 +1,166 @@
import type { Endpoint, PayloadRequest } from 'payload'
import { createHash, randomBytes, timingSafeEqual } from 'node:crypto'
import type { CookieScanLabels } from '../labels.js'
import type { CookieCrawlOptions, CookieScanContext, CookieScannerOptions } from '../types.js'
import { userMeetsRole } from '../../../access/predicates.js'
import {
COOKIE_CRAWL_PATH,
COOKIE_CRAWL_RESULTS_PATH,
COOKIE_CRAWL_SLUG,
COOKIE_SCAN_TOKEN_ENV,
COOKIE_SCAN_URL_ENV,
CRAWL_TIMEOUT_MS,
resolveCrawlConfig,
} from './config.js'
import { finishCrawl, ingestCrawlResult } from './ingest.js'
import { parseCrawlResult } from './result.js'
type CrawlDoc = {
error?: null | string
finishedAt?: null | string
jobId?: null | string
startedAt?: null | string
startedBy?: null | string
status?: 'done' | 'failed' | 'idle' | 'running' | null
summary?: null | Record<string, null | number>
}
/** Constant-time comparison of a bearer token with the configured one. */
export function bearerMatches(header: null | string | undefined, token: null | string): boolean {
if (!token || !header?.startsWith('Bearer ')) {return false}
const a = createHash('sha256').update(header.slice(7).trim()).digest()
const b = createHash('sha256').update(token).digest()
return timingSafeEqual(a, b)
}
const isStale = (doc: CrawlDoc, now = Date.now()) =>
doc.status === 'running' && (!doc.startedAt || now - new Date(doc.startedAt).getTime() > CRAWL_TIMEOUT_MS)
/**
* GET /api/ipal/cookie-crawl → `{ configured, missing, status, startedAt, finishedAt, summary, error }`
* POST /api/ipal/cookie-crawl → asks the scanner service to crawl this site (editor, or the bearer token
* — for a Coolify scheduled task); `202`, `409` while one runs, `503` when not configured
* POST /api/ipal/cookie-crawl/results → the service's callback, bearer token only; refuses any job but the running one
*/
export function buildCookieCrawlEndpoints({
fetchImpl = fetch,
labels,
options,
plugin,
}: {
/** For tests. */
fetchImpl?: typeof fetch
labels: Record<string, CookieScanLabels>
options: CookieScannerOptions
plugin: CookieScanContext['plugin']
}): Endpoint[] {
const crawl: CookieCrawlOptions = typeof options.crawl === 'object' ? options.crawl : {}
const isStaff = async (req: PayloadRequest) =>
options.access ? Boolean(await options.access({ req })) : userMeetsRole(req, 'editor')
const read = async (req: PayloadRequest) =>
(await req.payload.findGlobal({ slug: COOKIE_CRAWL_SLUG as never, depth: 0, overrideAccess: true, req })) as CrawlDoc
const write = (req: PayloadRequest, data: Partial<CrawlDoc>) =>
req.payload.updateGlobal({ slug: COOKIE_CRAWL_SLUG as never, context: { ipalCookieScan: true }, data: data as never, depth: 0, overrideAccess: true, req })
return [
{
handler: async (req) => {
if (!(await isStaff(req))) {return Response.json({ ok: false }, { status: 403 })}
const config = resolveCrawlConfig(crawl, req.payload)
const doc = await read(req)
const stale = isStale(doc)
return Response.json({
configured: Boolean(config.serviceUrl && config.token && config.siteUrl),
error: stale ? 'Timed out — the scanner service never reported back.' : (doc.error ?? null),
finishedAt: doc.finishedAt ?? null,
missing: [
...(config.serviceUrl ? [] : [COOKIE_SCAN_URL_ENV]),
...(config.token ? [] : [COOKIE_SCAN_TOKEN_ENV]),
...(config.siteUrl ? [] : ['serverURL / NEXT_PUBLIC_SERVER_URL']),
],
ok: true,
startedAt: doc.startedAt ?? null,
status: stale ? 'failed' : (doc.status ?? 'idle'),
summary: doc.summary ?? null,
})
},
method: 'get',
path: COOKIE_CRAWL_PATH,
},
{
handler: async (req) => {
const config = resolveCrawlConfig(crawl, req.payload)
const byToken = bearerMatches(req.headers.get('authorization'), config.token)
if (!byToken && !(await isStaff(req))) {return Response.json({ ok: false }, { status: 403 })}
if (!config.serviceUrl || !config.token || !config.siteUrl) {
return Response.json({ error: 'not_configured', ok: false }, { status: 503 })
}
const doc = await read(req)
if (doc.status === 'running' && !isStale(doc)) {return Response.json({ error: 'running', ok: false }, { status: 409 })}
const jobId = randomBytes(16).toString('hex')
const user = req.user as { email?: string } | null | undefined
await write(req, { error: null, finishedAt: null, jobId, startedAt: new Date().toISOString(), startedBy: byToken ? 'schedule' : (user?.email ?? 'editor'), status: 'running' })
const api = req.payload.config.routes?.api ?? '/api'
try {
const res = await fetchImpl(`${config.serviceUrl}/crawl`, {
body: JSON.stringify({
acceptSelector: config.acceptSelector,
callbackUrl: `${config.siteUrl}${api}${COOKIE_CRAWL_RESULTS_PATH}`,
jobId,
maxPages: config.maxPages,
siteUrl: config.siteUrl,
}),
headers: { Authorization: `Bearer ${config.token}`, 'Content-Type': 'application/json' },
method: 'POST',
signal: AbortSignal.timeout(15_000),
})
if (!res.ok) {throw new Error(`scanner service answered HTTP ${res.status}`)}
} catch (err) {
const message = err instanceof Error ? err.message : String(err)
req.payload.logger.error(`[ipal] cookie crawl: could not start — ${message}`)
await write(req, { error: `Could not reach the scanner service: ${message}`, finishedAt: new Date().toISOString(), jobId: null, status: 'failed' })
return Response.json({ error: 'service_unreachable', ok: false }, { status: 502 })
}
return Response.json({ ok: true, status: 'running' }, { status: 202 })
},
method: 'post',
path: COOKIE_CRAWL_PATH,
},
{
handler: async (req) => {
const config = resolveCrawlConfig(crawl, req.payload)
if (!bearerMatches(req.headers.get('authorization'), config.token)) {return Response.json({ ok: false }, { status: 401 })}
let body: unknown
try {
body = await (req as unknown as Request).json()
} catch {
return Response.json({ ok: false }, { status: 400 })
}
const result = parseCrawlResult(body)
if (!result) {return Response.json({ ok: false }, { status: 400 })}
const doc = await read(req)
if (doc.status !== 'running' || !doc.jobId || doc.jobId !== result.jobId) {
return Response.json({ error: 'unknown_job', ok: false }, { status: 409 })
}
try {
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 })
return Response.json({ ok: true })
} catch (err) {
const message = err instanceof Error ? err.message : String(err)
req.payload.logger.error(`[ipal] cookie crawl: saving the result failed — ${message}`)
await write(req, { error: `Saving the result failed: ${message}`, finishedAt: new Date().toISOString(), jobId: null, status: 'failed' })
return Response.json({ ok: false }, { status: 500 })
}
},
method: 'post',
path: COOKIE_CRAWL_RESULTS_PATH,
},
]
}
@@ -0,0 +1,73 @@
import type { GlobalConfig } from 'payload'
import type { CookieScanLabels } from '../labels.js'
import { userMeetsRole } from '../../../access/predicates.js'
import { labelRecord } from '../labels.js'
import { COOKIE_CRAWL_SLUG } from './config.js'
/**
* The latest crawl only (no history): status, counts, violations, third-party
* hosts, and the e-mail recipients for warnings (the only editable field —
* opt-in per site). Written by the crawl endpoints through the Local API.
*/
export function buildCookieCrawlGlobal(labels: Record<string, CookieScanLabels>): GlobalConfig {
const L = (key: keyof CookieScanLabels) => labelRecord(labels, key)
const ro = { readOnly: true }
return {
slug: COOKIE_CRAWL_SLUG,
access: {
read: ({ req }) => userMeetsRole(req, 'editor'),
update: ({ req }) => userMeetsRole(req, 'admin'),
},
admin: { description: L('crawlGlobalDescription'), group: 'Settings' },
fields: [
{
name: 'notifyEmails',
type: 'text',
admin: { description: L('notifyEmailsDescription') },
label: L('notifyEmails'),
validate: (value: null | string | undefined) => {
const list = (value ?? '').split(',').map((v) => v.trim()).filter(Boolean)
return list.every((v) => /^[^\s@]+@[^\s@][^\s.@]*\.[^\s@]+$/.test(v)) || 'Comma-separated e-mail addresses.'
},
},
{
name: 'status',
type: 'select',
admin: { ...ro, position: 'sidebar' },
defaultValue: 'idle',
label: L('crawlStatus'),
options: [
{ label: L('crawlIdle'), value: 'idle' },
{ label: L('crawlStateRunning'), value: 'running' },
{ label: L('crawlStateDone'), value: 'done' },
{ label: L('crawlStateFailed'), value: 'failed' },
],
},
{ name: 'startedAt', type: 'date', admin: { ...ro, date: { pickerAppearance: 'dayAndTime' }, position: 'sidebar' }, label: L('startedAt') },
{ name: 'finishedAt', type: 'date', admin: { ...ro, date: { pickerAppearance: 'dayAndTime' }, position: 'sidebar' }, label: L('finishedAt') },
{ name: 'startedBy', type: 'text', admin: { ...ro, position: 'sidebar' }, label: L('startedBy') },
{ name: 'error', type: 'textarea', admin: ro, label: L('crawlError') },
{
name: 'summary',
type: 'group',
admin: ro,
fields: [
{ name: 'pages', type: 'number', admin: ro, label: L('crawlPages') },
{ name: 'violations', type: 'number', admin: ro, label: L('crawlViolations') },
{ name: 'newUnknown', type: 'number', admin: ro, label: L('unknown') },
{ name: 'created', type: 'number', admin: ro },
{ name: 'updated', type: 'number', admin: ro },
],
label: false,
},
{ name: 'violations', type: 'json', admin: ro, label: L('crawlViolations') },
{ name: 'requests', type: 'json', admin: ro, label: L('crawlRequests') },
{ name: 'pages', type: 'json', admin: ro, label: L('crawlPages') },
// One-time id of the running crawl; a result with another id is refused.
{ name: 'jobId', type: 'text', admin: { hidden: true } },
],
label: L('crawlGlobal'),
}
}
+156
View File
@@ -0,0 +1,156 @@
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 })
}
}
@@ -0,0 +1,52 @@
import type { BasePayload } from 'payload'
import type { CookieScanLabels } from '../labels.js'
import type { CrawlIngestSummary } from './ingest.js'
import { COOKIE_REVIEW_SLUG } from '../collection.js'
import { labelFor } from '../labels.js'
const esc = (v: string) => v.replace(/[&<>"']/g, (c) => `&#${c.charCodeAt(0)};`)
const fill = (template: string, values: Record<string, number | string>) =>
template.replace(/\{(\w+)\}/g, (_, k: string) => String(values[k] ?? ''))
/**
* E-mail warning after a crawl, through the project's Payload email adapter
* (`email: mailAdapter()` — the plugin's mail setup). Never throws: a failed
* send is logged and the crawl result stays saved.
*/
export async function sendCrawlWarning({
labels,
payload,
siteUrl,
summary,
to,
}: {
labels: Record<string, CookieScanLabels>
payload: BasePayload
siteUrl: string
summary: CrawlIngestSummary
to: string[]
}): Promise<boolean> {
const lang = payload.config.i18n?.fallbackLanguage
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 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 html = `<p>${esc(fill(t('emailIntro'), values))}</p>
<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>`
try {
await payload.sendEmail({ html, subject: fill(t('emailSubject'), values), to })
return true
} catch (err) {
payload.logger.error(`[ipal] cookie crawl warning e-mail failed: ${err instanceof Error ? err.message : String(err)}`)
return false
}
}
@@ -0,0 +1,77 @@
import type { CookieStorage } from '../types.js'
/**
* What the scanner service sends back to the site (POST
* /api/ipal/cookie-crawl/results). The service lives in
* services/cookie-crawler; keep both sides in step.
*/
export type CrawlObservation = {
/** Set on the "after accept all" run. */
after: boolean
/** Set on the run with no consent. */
before: boolean
/** Cookie domain without the leading dot; omitted for storage keys. */
domain?: string
name: string
/** Paths where it was first seen (max 5). */
pages: string[]
storage: CookieStorage
}
export type CrawlRequest = { after: boolean; before: boolean; host: string; pages: string[] }
export type CrawlResult =
| {
/** False when the "Accept all" button was not found — the second run had no consent. */
accepted: boolean
jobId: string
observations: CrawlObservation[]
ok: true
pages: string[]
requests: CrawlRequest[]
}
| { error: string; jobId: string; ok: false }
const STORAGES = new Set<CookieStorage>(['cookie', 'localStorage', 'sessionStorage'])
const NAME = /^[^\s;,=]{1,200}$/
const HOST = /^(?=.{1,253}$)[a-z0-9-]+(?:\.[a-z0-9-]+)*$/i
const MAX_ITEMS = 2000
const MAX_PAGES = 200
const pathList = (v: unknown, max: number) =>
(Array.isArray(v) ? v : []).filter((p): p is string => typeof p === 'string' && p.length <= 2000).slice(0, max)
/** Validates the service's JSON. Anything malformed is dropped, not trusted; null = unusable. */
export function parseCrawlResult(body: unknown): CrawlResult | null {
if (!body || typeof body !== 'object') {return null}
const b = body as Record<string, unknown>
if (typeof b.jobId !== 'string' || !/^[0-9a-f]{16,64}$/.test(b.jobId)) {return null}
if (b.ok === false) {
return { error: typeof b.error === 'string' ? b.error.slice(0, 500) : 'Crawl failed', jobId: b.jobId, ok: false }
}
if (b.ok !== true) {return null}
const observations: CrawlObservation[] = []
for (const o of (Array.isArray(b.observations) ? b.observations : []).slice(0, MAX_ITEMS)) {
if (!o || typeof o !== 'object') {continue}
const x = o as Record<string, unknown>
const storage = x.storage as CookieStorage
if (typeof x.name !== 'string' || !NAME.test(x.name) || !STORAGES.has(storage)) {continue}
const domain = typeof x.domain === 'string' ? x.domain.replace(/^\./, '').toLowerCase() : ''
observations.push({
after: x.after === true,
before: x.before === true,
...(domain && HOST.test(domain) ? { domain } : {}),
name: x.name,
pages: pathList(x.pages, 5),
storage,
})
}
const requests: CrawlRequest[] = []
for (const r of (Array.isArray(b.requests) ? b.requests : []).slice(0, MAX_ITEMS)) {
if (!r || typeof r !== 'object') {continue}
const x = r as Record<string, unknown>
if (typeof x.host !== 'string' || !HOST.test(x.host)) {continue}
requests.push({ after: x.after === true, before: x.before === true, host: x.host.toLowerCase(), pages: pathList(x.pages, 5) })
}
return { accepted: b.accepted !== false, jobId: b.jobId, observations, ok: true, pages: pathList(b.pages, MAX_PAGES), requests }
}
@@ -0,0 +1,71 @@
import type { CookieStorage } from '../types.js'
import type { CrawlObservation, CrawlRequest } from './result.js'
/**
* Hosts whose requests before consent are a violation. Google's tag hosts are
* separate: with Consent Mode `advanced` (the plugin's default) the Google tag
* loads before consent with every signal denied, which is allowed; with
* `basic` nothing may reach Google before consent.
*/
export const DEFAULT_TRACKER_HOSTS = [
'analytics.tiktok.com',
'bat.bing.com',
'clarity.ms',
'connect.facebook.net',
'facebook.com',
'hotjar.com',
'licdn.com',
'linkedin.com',
'youtube.com',
]
export const GOOGLE_TAG_HOSTS = [
'doubleclick.net',
'google-analytics.com',
'googleadservices.com',
'googlesyndication.com',
'googletagmanager.com',
]
export type CrawlViolation = {
/** Consent category of the cookie or key (null = not classified yet). */
category?: null | string
kind: 'request' | CookieStorage
/** Cookie / key name, or the host for a request. */
name: string
pages: string[]
}
const hostMatches = (host: string, list: string[]) => list.some((h) => host === h || host.endsWith(`.${h}`))
/**
* Violations of one crawl: anything stored before consent whose category is not
* `necessary` (unclassified counts — the editor decides), and requests before
* consent to tracker hosts. `categoryOf` gives the review entry's category after
* the scan merged it (an editor's category wins).
*/
export function findCrawlViolations({
categoryOf,
consentMode = 'advanced',
observations,
requests,
trackerHosts = DEFAULT_TRACKER_HOSTS,
}: {
categoryOf: (o: CrawlObservation) => null | string | undefined
consentMode?: 'advanced' | 'basic'
observations: CrawlObservation[]
requests: CrawlRequest[]
trackerHosts?: string[]
}): CrawlViolation[] {
const out: CrawlViolation[] = []
for (const o of observations) {
if (!o.before) {continue}
const category = categoryOf(o) ?? null
if (category !== 'necessary') {out.push({ name: o.name, category, kind: o.storage, pages: o.pages })}
}
const hosts = consentMode === 'basic' ? [...trackerHosts, ...GOOGLE_TAG_HOSTS] : trackerHosts
for (const r of requests) {
if (r.before && hostMatches(r.host, hosts)) {out.push({ name: r.host, kind: 'request', pages: r.pages })}
}
return out
}
File diff suppressed because it is too large Load Diff
+54
View File
@@ -0,0 +1,54 @@
import type { Endpoint, PayloadRequest } from 'payload'
import type { CookieScanContext, CookieScannerOptions } from './types.js'
import { userMeetsRole } from '../../access/predicates.js'
import { DEFAULT_COOKIE_INTEGRATIONS } from './integrations.js'
import { cookieScanContext, enabledCookieIntegrations, parseCookieNames, runCookieScan } from './scan.js'
export const COOKIE_SCAN_PATH = '/ipal/cookie-scan'
/**
* GET /api/ipal/cookie-scan → `{ integrations: [{ key, label }] }` — what a scan would cover.
* POST /api/ipal/cookie-scan, body `{ names?: string[] | string }` → runs a scan,
* `{ ok, summary: { created, updated, unchanged, unknown }, integrations }`.
* Editors and up by default (`cookieScanner.access`).
*/
export function buildCookieScanEndpoints(options: CookieScannerOptions, plugin: CookieScanContext['plugin']): Endpoint[] {
const allowed = async (req: PayloadRequest) =>
options.access ? Boolean(await options.access({ req })) : userMeetsRole(req, 'editor')
const integrations = options.integrations ? options.integrations(DEFAULT_COOKIE_INTEGRATIONS) : DEFAULT_COOKIE_INTEGRATIONS
const list = (items: { key: string; label: string }[]) => items.map(({ key, label }) => ({ key, label }))
return [
{
handler: async (req) => {
if (!(await allowed(req))) {return Response.json({ ok: false }, { status: 403 })}
const enabled = await enabledCookieIntegrations(integrations, await cookieScanContext(req.payload, plugin, req))
return Response.json({ integrations: list(enabled), ok: true })
},
method: 'get',
path: COOKIE_SCAN_PATH,
},
{
handler: async (req) => {
if (!(await allowed(req))) {return Response.json({ ok: false }, { status: 403 })}
let body: { names?: unknown } = {}
try {
body = ((await (req as unknown as Request).json()) ?? {}) as { names?: unknown }
} catch {
// empty body = scan without extra names
}
try {
const { enabled, summary } = await runCookieScan({ names: parseCookieNames(body.names), options, payload: req.payload, plugin, req })
return Response.json({ integrations: list(enabled), ok: true, summary })
} catch (err) {
req.payload.logger.error(`[ipal] cookie scan failed: ${err instanceof Error ? err.message : String(err)}`)
return Response.json({ ok: false }, { status: 500 })
}
},
method: 'post',
path: COOKIE_SCAN_PATH,
},
]
}
+44
View File
@@ -0,0 +1,44 @@
// Cookie scanner — server-safe building blocks. The admin button is in /admin.
export { buildCookieReviewCollection, COOKIE_REVIEW_SLUG } from './collection.js'
export { DEFAULT_DATABASE_CATEGORIES, indexCookieDatabase, loadCookieDatabase, lookupCookie } from './cookieDatabase.js'
export type { CookieDatabaseIndex } from './cookieDatabase.js'
export {
COOKIE_CRAWL_PATH,
COOKIE_CRAWL_RESULTS_PATH,
COOKIE_CRAWL_SLUG,
COOKIE_SCAN_TOKEN_ENV,
COOKIE_SCAN_URL_ENV,
resolveCrawlConfig,
} from './crawl/config.js'
export type { ResolvedCrawlConfig } from './crawl/config.js'
export { bearerMatches, buildCookieCrawlEndpoints } from './crawl/endpoints.js'
export { buildCookieCrawlGlobal } from './crawl/global.js'
export { finishCrawl, ingestCrawlResult } from './crawl/ingest.js'
export type { CrawlIngestSummary } from './crawl/ingest.js'
export { sendCrawlWarning } from './crawl/notify.js'
export { parseCrawlResult } from './crawl/result.js'
export type { CrawlObservation, CrawlRequest, CrawlResult } from './crawl/result.js'
export { DEFAULT_TRACKER_HOSTS, findCrawlViolations, GOOGLE_TAG_HOSTS } from './crawl/violations.js'
export type { CrawlViolation } from './crawl/violations.js'
export { buildCookieScanEndpoints, COOKIE_SCAN_PATH } from './endpoint.js'
export { cookieNameMatches, DEFAULT_COOKIE_INTEGRATIONS } from './integrations.js'
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 type {
CookieCrawlOptions,
CookieDeclaration,
CookieFinding,
CookieFindingSource,
CookieIntegration,
CookieScanContext,
CookieScannerOptions,
CookieScanSummary,
CookieStorage,
LocalizedText,
OpenCookieCategory,
} from './types.js'
+292
View File
@@ -0,0 +1,292 @@
import type { CookieDeclaration, CookieIntegration, CookieScanContext } from './types.js'
import { validAnalyticsId } from '../../analytics/idFormats.js'
import { LOCALE_COOKIE_NAME } from '../../i18n/negotiateLocale.js'
import { getTurnstileConfig } from '../../turnstile/config.js'
import { CONSENT_COOKIE } from '../storage.js'
/** A tag ID from Site Integrations is filled in and valid. */
const hasId = (field: string) => (ctx: CookieScanContext) =>
Boolean(validAnalyticsId(field as never, ctx.integrations[field]))
const T = (en: string, pl: string) => ({ en, pl })
const SESSION = T('Session', 'Sesja')
const days = (n: number) => T(`${n} days`, `${n} dni`)
const months = (n: number) => T(`${n} months`, `${n} mies.`)
const YEAR = T('1 year', '1 rok')
const TWO_YEARS = T('2 years', '2 lata')
const SITE = 'This site'
/**
* Cookies of everything the plugin itself injects — one place per integration.
* Each one is part of a scan only when this project switches it on (an ID in
* Site Integrations, a plugin option). Change the list with
* `cookieScanner.integrations: (defaults) => …`.
*/
export const DEFAULT_COOKIE_INTEGRATIONS: CookieIntegration[] = [
{
declarations: [
{
name: CONSENT_COOKIE,
category: 'necessary',
purpose: T('Stores your cookie consent decision.', 'Zapamiętuje Twoją decyzję w sprawie plików cookie.'),
retention: months(6),
setBeforeConsent: false,
vendor: SITE,
},
],
isEnabled: () => true,
key: 'consent',
label: 'Cookie banner',
},
{
declarations: (ctx) => [
{
name: `${ctx.payload.config.cookiePrefix ?? 'payload'}-token`,
category: 'necessary',
purpose: T('Session of a logged-in editor (admin panel only).', 'Sesja zalogowanego redaktora (tylko panel administracyjny).'),
retention: T('Until logout (2 hours by default)', 'Do wylogowania (domyślnie 2 godziny)'),
setBeforeConsent: true,
vendor: SITE,
},
],
isEnabled: () => true,
key: 'admin',
label: 'Admin panel login',
},
{
declarations: [
{
name: LOCALE_COOKIE_NAME,
category: 'functional',
purpose: T('Remembers the selected site language.', 'Zapamiętuje wybrany język strony.'),
retention: SESSION,
setBeforeConsent: false,
vendor: SITE,
},
],
isEnabled: (ctx) => ctx.plugin.localeCount > 1,
key: 'locale',
label: 'Language choice',
},
{
declarations: [
{
name: 'ipal_vid', // VISITOR_COOKIE — that file is a client component
category: 'analytics',
purpose: T(
'Built-in statistics: random visitor id that joins your visits across days. Set only with analytics consent.',
'Wbudowane statystyki: losowy identyfikator łączący Twoje wizyty z różnych dni. Tylko po zgodzie na analitykę.',
),
retention: months(6),
setBeforeConsent: false,
vendor: SITE,
},
],
isEnabled: (ctx) => ctx.plugin.stats,
key: 'stats',
label: 'Built-in statistics',
},
{
declarations: [
{
name: '_ga',
category: 'analytics',
purpose: T('Google Analytics: distinguishes users in statistics.', 'Google Analytics: rozróżnia użytkowników w statystykach.'),
retention: TWO_YEARS,
setBeforeConsent: false,
vendor: 'Google',
},
{
name: '_ga_*',
category: 'analytics',
purpose: T('Google Analytics: keeps the session state.', 'Google Analytics: przechowuje stan sesji.'),
retention: TWO_YEARS,
setBeforeConsent: false,
vendor: 'Google',
},
],
isEnabled: hasId('ga4MeasurementId'),
key: 'ga4',
label: 'Google Analytics 4',
},
{
// GTM itself sets no cookie; its tags do. The Conversion Linker (Google Ads)
// is the usual one — anything else the container fires shows up in a crawl.
declarations: [
{
name: '_gcl_*',
category: 'marketing',
purpose: T(
'Google Ads (via Google Tag Manager): attributes conversions to ad clicks.',
'Google Ads (przez Google Tag Manager): przypisuje konwersje do kliknięć reklam.',
),
retention: months(3),
setBeforeConsent: false,
vendor: 'Google',
},
],
isEnabled: hasId('gtmContainerId'),
key: 'gtm',
label: 'Google Tag Manager',
},
{
declarations: [
{
name: '_fbp',
category: 'marketing',
purpose: T('Meta Pixel: ad measurement and targeting.', 'Meta Pixel: pomiar i dopasowanie reklam.'),
retention: months(3),
setBeforeConsent: false,
vendor: 'Meta',
},
{
name: '_fbc',
category: 'marketing',
purpose: T('Meta Pixel: stores the last ad click.', 'Meta Pixel: zapamiętuje ostatnie kliknięcie reklamy.'),
retention: months(3),
setBeforeConsent: false,
vendor: 'Meta',
},
],
isEnabled: hasId('metaPixelId'),
key: 'metaPixel',
label: 'Meta Pixel',
},
{
declarations: [
{
name: '_clck',
category: 'analytics',
purpose: T('Clarity: user id for behaviour analytics.', 'Clarity: identyfikator użytkownika w analizie zachowań.'),
retention: YEAR,
setBeforeConsent: false,
vendor: 'Microsoft Clarity',
},
{
name: '_clsk',
category: 'analytics',
purpose: T('Clarity: joins page views into one session.', 'Clarity: łączy odsłony w jedną sesję.'),
retention: T('1 day', '1 dzień'),
setBeforeConsent: false,
vendor: 'Microsoft Clarity',
},
{
name: 'CLID',
category: 'analytics',
domain: 'clarity.ms',
purpose: T('Clarity: user id across sites using Clarity.', 'Clarity: identyfikator użytkownika między stronami z Clarity.'),
retention: YEAR,
setBeforeConsent: false,
vendor: 'Microsoft Clarity',
},
{
name: 'MUID',
category: 'marketing',
domain: 'clarity.ms',
purpose: T('Microsoft: browser id used across Microsoft services and ads.', 'Microsoft: identyfikator przeglądarki w usługach i reklamach Microsoft.'),
retention: YEAR,
setBeforeConsent: false,
vendor: 'Microsoft',
},
],
isEnabled: hasId('clarityProjectId'),
key: 'clarity',
label: 'Microsoft Clarity',
},
{
declarations: [
{
name: 'li_fat_id',
category: 'marketing',
purpose: T('LinkedIn Insight Tag: conversion attribution.', 'LinkedIn Insight Tag: przypisanie konwersji.'),
retention: days(30),
setBeforeConsent: false,
vendor: 'LinkedIn',
},
{
name: 'bcookie',
category: 'marketing',
domain: 'linkedin.com',
purpose: T('LinkedIn: browser id.', 'LinkedIn: identyfikator przeglądarki.'),
retention: YEAR,
setBeforeConsent: false,
vendor: 'LinkedIn',
},
{
name: 'lidc',
category: 'marketing',
domain: 'linkedin.com',
purpose: T('LinkedIn: data-centre routing.', 'LinkedIn: wybór centrum danych.'),
retention: T('1 day', '1 dzień'),
setBeforeConsent: false,
vendor: 'LinkedIn',
},
{
name: 'UserMatchHistory',
category: 'marketing',
domain: 'linkedin.com',
purpose: T('LinkedIn Ads: id sync with ad partners.', 'LinkedIn Ads: synchronizacja identyfikatorów z partnerami reklamowymi.'),
retention: days(30),
setBeforeConsent: false,
vendor: 'LinkedIn',
},
],
isEnabled: hasId('linkedInPartnerId'),
key: 'linkedIn',
label: 'LinkedIn Insight Tag',
},
{
declarations: [
{
name: '_ttp',
category: 'marketing',
purpose: T('TikTok Pixel: ad measurement.', 'TikTok Pixel: pomiar reklam.'),
retention: months(13),
setBeforeConsent: false,
vendor: 'TikTok',
},
{
name: '_tt_enable_cookie',
category: 'marketing',
purpose: T('TikTok Pixel: checks that cookies work.', 'TikTok Pixel: sprawdza, czy cookies działają.'),
retention: months(13),
setBeforeConsent: false,
vendor: 'TikTok',
},
],
isEnabled: hasId('tiktokPixelId'),
key: 'tiktok',
label: 'TikTok Pixel',
},
{
// Turnstile hands back a one-time token; cf_clearance appears only when the
// widget has pre-clearance switched on in the Cloudflare dashboard.
declarations: [
{
name: 'cf_clearance',
category: 'necessary',
purpose: T(
'Cloudflare Turnstile: proves the anti-spam check was passed (only with pre-clearance on).',
'Cloudflare Turnstile: potwierdza przejście zabezpieczenia antyspamowego (tylko z włączonym pre-clearance).',
),
retention: T('30 minutes (set in Cloudflare)', '30 minut (ustawiane w Cloudflare)'),
setBeforeConsent: true,
vendor: 'Cloudflare',
},
],
isEnabled: async (ctx) => (await getTurnstileConfig(ctx.payload)).enabled,
key: 'turnstile',
label: 'Cloudflare Turnstile',
},
]
/** An integration's declarations for this project. */
export function declarationsOf(integration: CookieIntegration, ctx: CookieScanContext): CookieDeclaration[] {
return typeof integration.declarations === 'function' ? integration.declarations(ctx) : integration.declarations
}
/** True when `name` matches `pattern` (a trailing `*` = prefix). */
export function cookieNameMatches(pattern: string, name: string): boolean {
return pattern.endsWith('*') ? name.startsWith(pattern.slice(0, -1)) : name === pattern
}
+267
View File
@@ -0,0 +1,267 @@
/**
* Admin labels of the cookie scanner, per admin language. Payload picks the
* user's admin language from a `{ en, pl }` record; a language missing here falls
* back to English. Projects add or change languages with `cookieScanner.labels`.
*/
export type CookieScanLabels = {
accepted: string
alertBody: string
alertFailed: string
alertLink: string
alertTitle: string
analytics: string
beforeConsentOn: string
category: string
categoryRequired: string
collectionDescription: string
cookie: string
crawlButton: string
crawlDone: string
crawlError: string
crawlFailed: string
crawlGlobal: string
crawlGlobalDescription: string
crawlIdle: string
crawlIntro: string
crawlNotConfigured: string
crawlPages: string
crawlRequests: string
crawlRunning: string
crawlStateDone: string
crawlStateFailed: string
crawlStateRunning: string
crawlStatus: string
crawlViolations: string
database: string
domain: string
draft: string
emailIntro: string
emailSubject: string
finishedAt: string
functional: string
integration: string
integrationsFound: string
integrationsNone: string
lastScannedAt: string
listed: string
listedDescription: string
localStorage: string
manual: string
marketing: string
name: string
namesHint: string
namesLabel: string
necessary: string
notifyEmails: string
notifyEmailsDescription: string
plural: string
project: string
purpose: string
rejected: string
retention: string
scanButton: string
scanError: string
scanIntro: string
scanning: string
/** `{created}`, `{updated}`, `{unchanged}`, `{unknown}` are filled in. */
scanResult: string
seenBeforeConsent: string
sessionStorage: string
setBeforeConsent: string
setBeforeConsentDescription: string
singular: string
source: string
sourceDetail: string
startedAt: string
startedBy: string
status: string
statusDescription: string
storage: string
unknown: string
vendor: string
violation: string
violationDescription: string
violationDetail: string
}
export const COOKIE_SCAN_LABELS: Record<'en' | 'pl', CookieScanLabels> = {
en: {
name: 'Name',
accepted: 'Accepted',
alertBody: 'Non-necessary cookies or trackers load before consent, or the site sets cookies nobody has described yet. Check the review list.',
alertFailed: 'Cookie crawl failed: {error}',
alertLink: 'Open Cookie review →',
alertTitle: 'Cookie crawl: {violations} violations, {newUnknown} new unknown cookies.',
analytics: 'Analytics',
beforeConsentOn: 'before consent on {pages}',
category: 'Category',
categoryRequired: 'Pick a category before accepting.',
collectionDescription:
'Cookies found by "Scan cookies". Check each draft, then set it to Accepted (it is added to Cookie Settings → Cookies) or Rejected. A scan never deletes entries and never changes text you edited.',
cookie: 'Cookie',
crawlButton: 'Crawl site',
crawlDone: 'Last crawl {finishedAt}: {pages} pages, {violations} violations, {newUnknown} new unknown.',
crawlError: 'Error',
crawlFailed: 'The last crawl failed: {error}',
crawlGlobal: 'Cookie crawl',
crawlGlobalDescription: 'The latest browser crawl only. Start one from Cookie review → Crawl site.',
crawlIdle: 'Never run',
crawlIntro: 'Opens the site in a browser twice — without consent and after "Accept all" — and records cookies, storage and third-party requests. New findings become drafts.',
crawlNotConfigured: 'The crawl needs IPAL_COOKIE_SCAN_URL and IPAL_COOKIE_SCAN_TOKEN on the server.',
crawlPages: 'Pages crawled',
crawlRequests: 'Third-party requests',
crawlRunning: 'Crawling… started {startedAt}.',
crawlStateDone: 'Done',
crawlStateFailed: 'Failed',
crawlStateRunning: 'Running',
crawlStatus: 'Status',
crawlViolations: 'Violations',
database: 'Open Cookie Database',
domain: 'Domain',
draft: 'Draft',
emailIntro: 'The latest cookie crawl of {site} found:',
emailSubject: 'Cookie crawl of {site}: {violations} violations, {newUnknown} new unknown',
finishedAt: 'Finished',
functional: 'Functional',
integration: 'Plugin integration',
integrationsFound: 'Integrations in use',
integrationsNone: 'No integration with cookies is switched on.',
lastScannedAt: 'Last seen by a scan',
listed: 'In the cookie list',
listedDescription: 'Already in Cookie Settings → Cookies.',
localStorage: 'Local storage',
manual: 'Added by hand',
marketing: 'Marketing',
namesHint: 'Optional: cookie names seen in the browser (DevTools → Application → Cookies), one per line. They are looked up in the plugin and the Open Cookie Database.',
namesLabel: 'More cookie names',
necessary: 'Necessary',
notifyEmails: 'E-mail warnings to',
notifyEmailsDescription: 'Comma-separated addresses. After a crawl with violations or new unknown cookies, a warning is sent through the site\'s mail setup. Empty = no e-mail.',
plural: 'Cookie review',
project: 'Project declaration',
purpose: 'Purpose',
rejected: 'Rejected',
retention: 'Retention',
scanButton: 'Scan cookies',
scanError: 'The scan failed.',
scanIntro: 'Lists the cookies of the integrations switched on in this project as drafts to review.',
scanning: 'Scanning…',
scanResult: '{created} new, {updated} updated, {unchanged} unchanged, {unknown} unknown.',
seenBeforeConsent: 'Seen before consent',
sessionStorage: 'Session storage',
setBeforeConsent: 'Set before consent',
setBeforeConsentDescription: 'May be set before the visitor decides. Only necessary cookies should be.',
singular: 'Cookie review entry',
source: 'Found by',
sourceDetail: 'Source',
startedAt: 'Started',
startedBy: 'Started by',
status: 'Status',
statusDescription: 'Accepted → added to Cookie Settings → Cookies. Rejecting never removes a row from that list.',
storage: 'Stored in',
unknown: 'Unknown — fill in',
vendor: 'Provider',
violation: 'Violation',
violationDescription: 'Seen before consent in the latest crawl and not necessary.',
violationDetail: 'Violation details',
},
pl: {
name: 'Nazwa',
accepted: 'Zaakceptowany',
alertBody: 'Cookies lub skrypty śledzące, które nie są niezbędne, ładują się przed zgodą — albo strona ustawia cookies, których nikt jeszcze nie opisał. Sprawdź listę przeglądu.',
alertFailed: 'Skan cookies się nie powiódł: {error}',
alertLink: 'Otwórz Przegląd cookies →',
alertTitle: 'Skan cookies: naruszeń {violations}, nowych nieznanych cookies {newUnknown}.',
analytics: 'Analityczne',
beforeConsentOn: 'przed zgodą na {pages}',
category: 'Kategoria',
categoryRequired: 'Wybierz kategorię przed akceptacją.',
collectionDescription:
'Pliki cookie znalezione przez „Skanuj cookies”. Sprawdź każdy szkic i ustaw Zaakceptowany (trafi do Ustawień cookies → Cookies) albo Odrzucony. Skan nigdy nie usuwa wpisów ani nie zmienia poprawionych przez Ciebie tekstów.',
cookie: 'Cookie',
crawlButton: 'Przeskanuj stronę',
crawlDone: 'Ostatni skan {finishedAt}: stron {pages}, naruszeń {violations}, nowych nieznanych {newUnknown}.',
crawlError: 'Błąd',
crawlFailed: 'Ostatni skan się nie powiódł: {error}',
crawlGlobal: 'Skan cookies przeglądarką',
crawlGlobalDescription: 'Tylko ostatni skan przeglądarką. Uruchom go w Przeglądzie cookies → Przeskanuj stronę.',
crawlIdle: 'Nie uruchamiano',
crawlIntro: 'Otwiera stronę w przeglądarce dwa razy — bez zgody i po „Akceptuj wszystkie” — i zapisuje cookies, pamięć przeglądarki i zapytania do zewnętrznych serwisów. Nowe znaleziska trafiają jako szkice.',
crawlNotConfigured: 'Skan przeglądarką wymaga IPAL_COOKIE_SCAN_URL i IPAL_COOKIE_SCAN_TOKEN na serwerze.',
crawlPages: 'Przeskanowane strony',
crawlRequests: 'Zapytania do zewnętrznych serwisów',
crawlRunning: 'Skanowanie… rozpoczęte {startedAt}.',
crawlStateDone: 'Gotowe',
crawlStateFailed: 'Błąd',
crawlStateRunning: 'W toku',
crawlStatus: 'Status',
crawlViolations: 'Naruszenia',
database: 'Open Cookie Database',
domain: 'Domena',
draft: 'Szkic',
emailIntro: 'Ostatni skan cookies strony {site} znalazł:',
emailSubject: 'Skan cookies {site}: naruszeń {violations}, nowych nieznanych {newUnknown}',
finishedAt: 'Zakończony',
functional: 'Funkcjonalne',
integration: 'Integracja wtyczki',
integrationsFound: 'Używane integracje',
integrationsNone: 'Żadna integracja z plikami cookie nie jest włączona.',
lastScannedAt: 'Ostatnio widziany w skanie',
listed: 'Na liście cookies',
listedDescription: 'Już jest w Ustawieniach cookies → Cookies.',
localStorage: 'Local storage',
manual: 'Dodany ręcznie',
marketing: 'Marketingowe',
namesHint: 'Opcjonalnie: nazwy cookies widoczne w przeglądarce (DevTools → Application → Cookies), po jednej w wierszu. Zostaną wyszukane we wtyczce i w Open Cookie Database.',
namesLabel: 'Dodatkowe nazwy cookies',
necessary: 'Niezbędne',
notifyEmails: 'Ostrzeżenia e-mail do',
notifyEmailsDescription: 'Adresy po przecinku. Po skanie z naruszeniami lub nowymi nieznanymi cookies wysyłane jest ostrzeżenie przez konfigurację poczty strony. Puste = bez e-maili.',
plural: 'Przegląd cookies',
project: 'Deklaracja projektu',
purpose: 'Cel',
rejected: 'Odrzucony',
retention: 'Czas przechowywania',
scanButton: 'Skanuj cookies',
scanError: 'Skan się nie powiódł.',
scanIntro: 'Dodaje cookies integracji włączonych w tym projekcie jako szkice do przejrzenia.',
scanning: 'Skanowanie…',
scanResult: 'Nowe: {created}, zaktualizowane: {updated}, bez zmian: {unchanged}, nieznane: {unknown}.',
seenBeforeConsent: 'Widoczny przed zgodą',
sessionStorage: 'Session storage',
setBeforeConsent: 'Ustawiany przed zgodą',
setBeforeConsentDescription: 'Może powstać, zanim odwiedzający zdecyduje. Tylko niezbędne cookies powinny.',
singular: 'Wpis przeglądu cookies',
source: 'Źródło',
sourceDetail: 'Skąd',
startedAt: 'Rozpoczęty',
startedBy: 'Uruchomił',
status: 'Status',
statusDescription: 'Zaakceptowany → trafia do Ustawień cookies → Cookies. Odrzucenie nigdy nie usuwa wiersza z tej listy.',
storage: 'Przechowywany w',
unknown: 'Nieznany — uzupełnij',
vendor: 'Dostawca',
violation: 'Naruszenie',
violationDescription: 'Widoczny przed zgodą w ostatnim skanie i nie jest niezbędny.',
violationDetail: 'Szczegóły naruszenia',
},
}
/** Plugin labels with the project's languages and changes merged over them. */
export function mergeCookieScanLabels(overrides: Record<string, Partial<CookieScanLabels>> = {}): Record<string, CookieScanLabels> {
const out: Record<string, CookieScanLabels> = { ...COOKIE_SCAN_LABELS }
for (const [lang, labels] of Object.entries(overrides)) {
out[lang] = { ...(out[lang] ?? COOKIE_SCAN_LABELS.en), ...labels }
}
return out
}
/** One label as a Payload `{ en, pl, … }` record. */
export function labelRecord(labels: Record<string, CookieScanLabels>, key: keyof CookieScanLabels): Record<string, string> {
return Object.fromEntries(Object.entries(labels).map(([lang, l]) => [lang, l[key]]))
}
/** One label in one language (English when the language is missing). */
export function labelFor(labels: Record<string, CookieScanLabels>, lang: string | undefined, key: keyof CookieScanLabels): string {
return (lang && labels[lang]?.[key]) || labels.en?.[key] || COOKIE_SCAN_LABELS.en[key]
}
+82
View File
@@ -0,0 +1,82 @@
import type { ConsentCategory } from '../categories.js'
import type { CookieFinding, LocalizedText } from './types.js'
/** The editable values of a review entry; `purpose` / `retention` per locale. */
export type CookieReviewValues = {
category?: ConsentCategory | null
domain?: null | string
purpose?: Record<string, null | string>
retention?: Record<string, null | string>
setBeforeConsent?: boolean | null
vendor?: null | string
}
const SCALARS = ['category', 'domain', 'setBeforeConsent', 'vendor'] as const
const TEXTS = ['purpose', 'retention'] as const
/** Text for one locale: that language, else English, else the first one given. */
export function textFor(text: LocalizedText | undefined, locale: string): string | undefined {
if (text === undefined) {return undefined}
if (typeof text === 'string') {return text}
return text[locale] ?? text.en ?? Object.values(text)[0]
}
/** What a scan suggests for an entry, resolved for the project's locales. */
export function suggestionFor(finding: CookieFinding, locales: string[]): CookieReviewValues {
const perLocale = (text: LocalizedText | undefined) => {
if (text === undefined) {return undefined}
return Object.fromEntries(locales.map((l) => [l, textFor(text, l) ?? null]))
}
const out: CookieReviewValues = {}
if (finding.category) {out.category = finding.category}
if (finding.domain) {out.domain = finding.domain}
if (finding.vendor) {out.vendor = finding.vendor}
if (typeof finding.setBeforeConsent === 'boolean') {out.setBeforeConsent = finding.setBeforeConsent}
const purpose = perLocale(finding.purpose)
const retention = perLocale(finding.retention)
if (purpose) {out.purpose = purpose}
if (retention) {out.retention = retention}
return out
}
const isEmpty = (v: unknown) => v === undefined || v === null || v === ''
/**
* New values for an entry after a scan. A value takes the new suggestion only
* while it is empty or still equal to what the previous scan suggested — once an
* editor changed it, it is theirs and stays. Text is compared per locale.
*/
export function mergeCookieReview(
current: CookieReviewValues,
previous: CookieReviewValues | null | undefined,
next: CookieReviewValues,
): { changed: boolean; values: CookieReviewValues } {
const prev = previous ?? {}
const values: CookieReviewValues = { ...current }
let changed = false
const pick = <V>(cur: V, before: undefined | V, suggested: undefined | V): V => {
if (suggested === undefined || isEmpty(suggested)) {return cur}
if (isEmpty(cur) || cur === before) {return suggested}
return cur
}
for (const key of SCALARS) {
const v = pick(current[key], prev[key], next[key])
if (v !== current[key]) {
;(values as Record<string, unknown>)[key] = v
changed = true
}
}
for (const key of TEXTS) {
const cur = current[key] ?? {}
const merged = { ...cur }
for (const [locale, suggested] of Object.entries(next[key] ?? {})) {
const v = pick(cur[locale], prev[key]?.[locale], suggested)
if (v !== cur[locale]) {
merged[locale] = v ?? null
changed = true
}
}
if (Object.keys(merged).length) {values[key] = merged}
}
return { changed, values }
}
+282
View File
@@ -0,0 +1,282 @@
import type { BasePayload, PayloadRequest } from 'payload'
import type { CookieReviewValues } from './merge.js'
import type {
CookieDeclaration,
CookieFinding,
CookieIntegration,
CookieScanContext,
CookieScannerOptions,
CookieScanSummary,
CookieStorage,
} from './types.js'
import { COOKIE_REVIEW_SLUG } from './collection.js'
import { loadCookieDatabase, lookupCookie } from './cookieDatabase.js'
import { cookieNameMatches, declarationsOf, DEFAULT_COOKIE_INTEGRATIONS } from './integrations.js'
import { mergeCookieReview, suggestionFor } from './merge.js'
/** Most names one scan looks up — the panel field is for a handful, not a dump. */
export const MAX_SCAN_NAMES = 200
/** Cookie / storage key names as browsers allow them: no spaces, `;`, `,` or `=`. */
const NAME = /^[^\s;,=]{1,200}$/
/** Names from the panel's text box: trimmed, de-duplicated, invalid ones dropped. */
export function parseCookieNames(input: unknown): string[] {
const list = Array.isArray(input) ? input : typeof input === 'string' ? input.split(/[\n,]/) : []
const out = new Set<string>()
for (const raw of list) {
if (typeof raw !== 'string') {continue}
const name = raw.trim()
if (NAME.test(name)) {out.add(name)}
if (out.size >= MAX_SCAN_NAMES) {break}
}
return [...out]
}
const reviewKey = (storage: CookieStorage, name: string) => `${storage}:${name}`
function fromDeclaration(d: CookieDeclaration, source: 'integration' | 'project', sourceDetail: string): CookieFinding {
return {
category: d.category,
...(d.domain ? { domain: d.domain } : {}),
name: d.name,
purpose: d.purpose,
retention: d.retention,
setBeforeConsent: d.setBeforeConsent,
source,
sourceDetail,
storage: d.storage ?? 'cookie',
vendor: d.vendor,
}
}
/** The integrations this project uses (a failing check counts as off and is logged). */
export async function enabledCookieIntegrations(
integrations: CookieIntegration[],
ctx: CookieScanContext,
): Promise<CookieIntegration[]> {
const on: CookieIntegration[] = []
for (const integration of integrations) {
try {
if (await integration.isEnabled(ctx)) {on.push(integration)}
} catch (err) {
ctx.payload.logger.warn(`[ipal] cookie scan: could not check "${integration.key}": ${err instanceof Error ? err.message : String(err)}`)
}
}
return on
}
/** A name seen somewhere: in the panel's text box (a string) or by a crawl (with storage and domain). */
export type CookieObservation = { domain?: string; name: string; storage?: CookieStorage } | string
/**
* Everything a scan reports, before anything is written: the cookies of the
* enabled integrations, the project's declarations, and each extra name looked
* up in the project's declarations, every built-in integration, then the Open
* Cookie Database. A name nothing knows comes back with `source: 'unknown'`.
* `matches` maps each extra name (`storage:name`) to the review key that covers
* it — `_ga_ABC` → `cookie:_ga_*`.
*/
export async function collectCookieFindings({
ctx,
database = true,
databaseCategories,
declarations = [],
integrations = DEFAULT_COOKIE_INTEGRATIONS,
names = [],
}: {
ctx: CookieScanContext
database?: boolean
databaseCategories?: CookieScannerOptions['databaseCategories']
declarations?: CookieDeclaration[]
integrations?: CookieIntegration[]
names?: CookieObservation[]
}): Promise<{ enabled: CookieIntegration[]; findings: CookieFinding[]; matches: Map<string, string> }> {
const enabled = await enabledCookieIntegrations(integrations, ctx)
const found = new Map<string, CookieFinding>()
const matches = new Map<string, string>()
const add = (f: CookieFinding) => {
const key = reviewKey(f.storage, f.name)
if (!found.has(key)) {found.set(key, f)}
return key
}
for (const d of declarations) {add(fromDeclaration(d, 'project', 'Project'))}
for (const integration of enabled) {
for (const d of declarationsOf(integration, ctx)) {add(fromDeclaration(d, 'integration', integration.label))}
}
const known = [
...declarations.map((d) => ({ d, detail: 'Project', source: 'project' as const })),
...integrations.flatMap((i) => declarationsOf(i, ctx).map((d) => ({ d, detail: i.label, source: 'integration' as const }))),
]
const index = database ? await loadCookieDatabase() : null
for (const raw of names) {
const { name, domain, storage = 'cookie' } = typeof raw === 'string' ? { name: raw } : raw
const seenKey = reviewKey(storage, name)
if (matches.has(seenKey)) {continue}
const covering = [...found.values()].find((f) => f.storage === storage && cookieNameMatches(f.name, name))
if (covering) {
matches.set(seenKey, reviewKey(storage, covering.name))
continue
}
const declared = known.find((k) => (k.d.storage ?? 'cookie') === storage && cookieNameMatches(k.d.name, name))
if (declared) {
matches.set(seenKey, add(fromDeclaration(declared.d, declared.source, declared.detail)))
continue
}
const fromDb = index ? lookupCookie(index, name, databaseCategories) : null
const finding: CookieFinding = fromDb
? { ...fromDb, storage, ...(domain && !fromDb.domain ? { domain } : {}) }
: { ...(domain ? { domain } : {}), name, source: 'unknown', storage }
matches.set(seenKey, add(finding))
}
return { enabled, findings: [...found.values()], matches }
}
/** 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 }
type ReviewDoc = {
id: number | string
listed?: boolean | null
suggested?: CookieReviewValues | null
} & CookieReviewValues
function localesOf(payload: BasePayload): { defaultLocale?: string; locales: (string | undefined)[] } {
const l = payload.config.localization
if (!l) {return { locales: [undefined] }}
const codes = l.localeCodes ?? l.locales.map((x) => (typeof x === 'string' ? x : x.code))
return { defaultLocale: l.defaultLocale, locales: [l.defaultLocale, ...codes.filter((c) => c !== l.defaultLocale)] }
}
/** Names already in Cookie Settings → Cookies. */
async function listedNames(payload: BasePayload, req?: PayloadRequest): Promise<Set<string>> {
try {
const g = (await payload.findGlobal({ slug: 'cookie-settings' as never, depth: 0, req })) as { cookies?: { name?: null | string }[] }
return new Set((g.cookies ?? []).map((c) => c.name?.trim() ?? '').filter(Boolean))
} catch {
return new Set()
}
}
/**
* Writes findings to the review list as drafts. New names become drafts; an
* existing entry gets the new suggestion only where an editor has not changed
* the value (see mergeCookieReview). Status is never changed, nothing is
* deleted and nothing is published — accepting stays the editor's step.
*/
export async function applyCookieFindings({
collection = COOKIE_REVIEW_SLUG,
entries,
findings,
payload,
req,
}: {
collection?: string
/** Filled with every written entry by review key — id and its category after the merge. */
entries?: Map<string, CookieReviewEntryRef>
findings: CookieFinding[]
payload: BasePayload
req?: PayloadRequest
}): Promise<CookieScanSummary> {
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 now = new Date().toISOString()
const common = { collection: collection as never, context: { ipalCookieScan: true }, depth: 0, fallbackLocale: false as never, overrideAccess: true, req }
for (const finding of findings) {
if (finding.source === 'unknown') {summary.unknown++}
const key = reviewKey(finding.storage, finding.name)
const next = suggestionFor(finding, codes.length ? codes : ['en'])
const machine = {
key,
lastScannedAt: now,
listed: listed.has(finding.name),
source: finding.source,
sourceDetail: finding.sourceDetail ?? null,
suggested: next,
}
const found = await payload.find({ ...common, limit: 1, locale: (codes.length ? 'all' : undefined) as never, where: { key: { equals: key } } })
const existing = found.docs[0] as ReviewDoc | undefined
const values = existing ? mergeCookieReview(existing, existing.suggested, next) : { changed: true, values: next }
const { purpose, retention, ...scalars } = values.values
const textIn = (locale: string | undefined) => ({
...(purpose && locale ? { purpose: purpose[locale] ?? null } : {}),
...(retention && locale ? { retention: retention[locale] ?? null } : {}),
...(!locale && purpose ? { purpose: Object.values(purpose)[0] ?? null } : {}),
...(!locale && retention ? { retention: Object.values(retention)[0] ?? null } : {}),
})
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 }) }
: textIn(locale)
if (i > 0 && (!values.changed || !Object.keys(data).length)) {continue}
if (id === undefined) {
id = ((await payload.create({ ...common, data: data as never, locale: locale as never })) as { id: number | string }).id
} else {
await payload.update({ ...common, id, data: data as never, locale: locale as never })
}
}
entries?.set(key, { id: id!, category: scalars.category ?? null, created: !existing })
if (!existing) {
summary.created++
if (finding.source === 'unknown') {summary.newUnknown++}
}
else if (values.changed) {summary.updated++}
else {summary.unchanged++}
}
return summary
}
/** Scan context from a running Payload: SiteIntegrations + the plugin's module switches. */
export async function cookieScanContext(
payload: BasePayload,
plugin: CookieScanContext['plugin'],
req?: PayloadRequest,
): Promise<CookieScanContext> {
let integrations: Record<string, unknown> = {}
try {
integrations = (await payload.findGlobal({ slug: 'site-integrations' as never, depth: 0, req })) as Record<string, unknown>
} catch {
// No such global (project replaced it) — integrations keyed on its IDs count as off.
}
return { integrations, payload, plugin }
}
/**
* One full scan: findings for this project, plus the names already in Cookie
* Settings and the extra `names`, written to the review list.
*/
export async function runCookieScan({
names = [],
options = {},
payload,
plugin,
req,
}: {
names?: string[]
options?: CookieScannerOptions
payload: BasePayload
plugin: CookieScanContext['plugin']
req?: PayloadRequest
}): Promise<{ enabled: CookieIntegration[]; summary: CookieScanSummary }> {
const ctx = await cookieScanContext(payload, plugin, req)
const integrations = options.integrations ? options.integrations(DEFAULT_COOKIE_INTEGRATIONS) : DEFAULT_COOKIE_INTEGRATIONS
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])],
})
const summary = await applyCookieFindings({ findings, payload, req })
return { enabled, summary }
}
+76
View File
@@ -0,0 +1,76 @@
import type { BasePayload, PayloadRequest } from 'payload'
import type { CookieReviewValues } from './merge.js'
type Row = {
category?: null | string
duration?: null | string
id?: string
name?: null | string
provider?: null | string
purpose?: null | string
}
type Entry = { name: string } & CookieReviewValues
const empty = (v: unknown) => v === undefined || v === null || (typeof v === 'string' && !v.trim())
/**
* 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
* provider, purpose and retention filled — text an editor wrote there stays,
* and its category is never changed. Never removes a row.
* Returns what happened, for the log.
*/
export async function addToCookieList({
entry,
payload,
req,
}: {
entry: Entry
payload: BasePayload
req?: PayloadRequest
}): Promise<'added' | 'filled' | 'unchanged'> {
const l = payload.config.localization
const codes = l ? (l.localeCodes ?? []) : []
const defaultLocale = l ? l.defaultLocale : undefined
const locales = l ? [defaultLocale!, ...codes.filter((c) => c !== defaultLocale)] : [undefined]
const text = (map: Record<string, null | string> | undefined, locale: string | undefined) =>
(locale ? map?.[locale] : map && Object.values(map)[0]) ?? null
// fallbackLocale off for reads AND writes: an update in one locale otherwise reads the
// stored rows with the default locale's text filled in and saves that text into it.
const common = { slug: 'cookie-settings' as never, context: { ipalCookieScan: true }, depth: 0, fallbackLocale: false as never, overrideAccess: true, req }
let result: 'added' | 'filled' | 'unchanged' = 'unchanged'
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)
let changed = false
if (!row) {
if (i > 0) {continue} // added in the default locale; Payload keeps the row in every locale
rows.push({
name: entry.name,
category: entry.category ?? 'necessary',
duration: text(entry.retention, locale),
provider: entry.vendor ?? null,
purpose: text(entry.purpose, locale),
})
changed = true
result = 'added'
} else {
const fill = (key: 'duration' | 'provider' | 'purpose', value: null | string | undefined) => {
if (empty(row[key]) && !empty(value)) {
row[key] = value
changed = true
}
}
if (i === 0) {fill('provider', entry.vendor)}
fill('purpose', text(entry.purpose, locale))
fill('duration', text(entry.retention, locale))
if (changed && result === 'unchanged') {result = 'filled'}
}
if (changed) {await payload.updateGlobal({ ...common, data: { cookies: rows } as never, locale: locale as never })}
}
return result
}
+156
View File
@@ -0,0 +1,156 @@
import type { BasePayload, PayloadRequest } from 'payload'
import type { GlobalOverride } from '../../../globals/overrides.js'
import type { CollectionOverride } from '../../shared/collectionOverride.js'
import type { ConsentCategory } from '../categories.js'
import type { CookieScanLabels } from './labels.js'
/** Text per admin/content language (`{ en, pl }`), or one string for every language. */
export type LocalizedText = Record<string, string> | string
/** Where a key is kept in the browser. */
export type CookieStorage = 'cookie' | 'localStorage' | 'sessionStorage'
/**
* One cookie (or storage key) an integration sets — the single place its cookie
* policy text lives. A trailing `*` in `name` matches every name with that prefix
* (`_ga_*` → `_ga_ABC123`).
*/
export type CookieDeclaration = {
category: ConsentCategory
/** Third-party domain that sets it, e.g. `clarity.ms`. Omit for the site's own cookies. */
domain?: string
name: string
purpose: LocalizedText
retention: LocalizedText
/** True when it may be set before the visitor decides (only `necessary` cookies should be). */
setBeforeConsent: boolean
/** Default `'cookie'`. */
storage?: CookieStorage
vendor: string
}
/** What a scan knows about the project when it decides which integrations are on. */
export type CookieScanContext = {
/** SiteIntegrations (depth 0); `{}` when it can't be read. */
integrations: Record<string, unknown>
payload: BasePayload
/** Plugin options that switch modules on. */
plugin: { localeCount: number; stats: boolean }
}
/**
* A feature that sets cookies, with the check whether this project uses it.
* Built-ins: DEFAULT_COOKIE_INTEGRATIONS. Projects add their own (custom embeds,
* chat widgets) through `cookieScanner.integrations` or `cookieScanner.declarations`.
*/
export type CookieIntegration = {
declarations: ((ctx: CookieScanContext) => CookieDeclaration[]) | CookieDeclaration[]
/** Whether the project uses it — e.g. an ID is filled in Site Integrations. */
isEnabled: (ctx: CookieScanContext) => boolean | Promise<boolean>
/** Stable id, e.g. `ga4`. */
key: string
/** Shown in the panel, e.g. `Google Analytics 4`. */
label: string
}
/** Where a review entry's suggestion came from. `manual` = added by hand in the panel. */
export type CookieFindingSource = 'database' | 'integration' | 'manual' | 'project' | 'unknown'
/** One cookie a scan found, before it is written to the review list. */
export type CookieFinding = {
category?: ConsentCategory
domain?: string
name: string
purpose?: LocalizedText
retention?: LocalizedText
setBeforeConsent?: boolean
source: CookieFindingSource
/** e.g. `Google Analytics 4`, `Open Cookie Database: Hotjar`. */
sourceDetail?: string
storage: CookieStorage
vendor?: string
}
/** Open Cookie Database category names. */
export type OpenCookieCategory = 'Analytics' | 'Functional' | 'Marketing' | 'Necessary' | 'Personalization' | 'Security'
/** Totals a scan reports back to the panel. */
export type CookieScanSummary = {
created: number
/** Entries created by this scan that nothing knew. */
newUnknown: number
unchanged: number
/** Names nothing knew — the editor fills provider, purpose and category. */
unknown: number
updated: number
}
/**
* `ipalKit({ cookieScanner })` — the Cookie review list and the "Scan cookies"
* action. Every key is optional.
*/
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>
/** Change the `cookie-review` collection (object merges, function takes over). */
collectionOverrides?: CollectionOverride
/**
* Browser crawl through the scanner service (services/cookie-crawler):
* "Crawl site" in the panel, the `cookie-crawl` global (latest result only),
* violations, a dashboard warning and an optional e-mail. Default off.
*/
crawl?: boolean | CookieCrawlOptions
/** Look unknown names up in the bundled Open Cookie Database. Default true. */
database?: boolean
/**
* How Open Cookie Database categories map to consent categories. Default:
* Functional / Personalization → functional, Security / Necessary → necessary,
* Analytics → analytics, Marketing → marketing. Functional is not mapped to
* necessary on purpose: the database files some trackers there, and a lookup
* nobody checked yet must not skip consent. `{ Functional: 'necessary' }` to change it.
*/
databaseCategories?: Partial<Record<OpenCookieCategory, ConsentCategory>>
/** The project's own cookies (custom embeds, chat): always part of a scan. */
declarations?: CookieDeclaration[]
/**
* Built-in integrations → the ones to use: filter, change or add.
* `(defaults) => [...defaults, myChatWidget]`.
*/
integrations?: (defaults: CookieIntegration[]) => CookieIntegration[]
/** Admin labels per language, merged over the plugin's `en` / `pl` (add `de: {…}`). */
labels?: Record<string, Partial<CookieScanLabels>>
/**
* Accepting an entry adds it to Cookie Settings → Cookies (fills only empty
* text of an existing row). Default true; `false` = the list is only a review aid.
*/
syncAccepted?: boolean
}
/**
* `cookieScanner.crawl` — the site side of the browser crawl. The browser runs
* in the scanner service, never in the site. Every key is optional.
*/
export type CookieCrawlOptions = {
/** CSS selector of the banner's "Accept all" button. Default `[data-ipal="accept"]`. */
acceptSelector?: string
/**
* The site's Consent Mode: `'advanced'` (default) lets Google tag requests
* through before consent (signals denied, no cookies); `'basic'` reports them.
*/
consentMode?: 'advanced' | 'basic'
/** Warning on the dashboard after a crawl with violations or new unknown cookies. Default true. */
dashboard?: boolean
/** Change the `cookie-crawl` global (object merges, function takes over). */
globalOverride?: GlobalOverride
/** Sitemap pages crawled besides the home page. Default 20, at most 100. */
maxPages?: number
/** Scanner service base URL. Default env `IPAL_COOKIE_SCAN_URL`. */
serviceUrl?: string
/** Public origin of this site the service crawls and calls back. Default `serverURL`, else `NEXT_PUBLIC_SERVER_URL`. */
siteUrl?: string
/** Shared secret with the service. Default env `IPAL_COOKIE_SCAN_TOKEN`. */
token?: string
/** Hosts whose requests before consent are violations: `(defaults) => hosts`. */
trackerHosts?: (defaults: string[]) => string[]
}
+19
View File
@@ -3,6 +3,11 @@ import type { EnvRule } from './assertEnv.js'
type TurnstileNames = { secretVar?: string; siteKeyVar?: string }
export type IpalEnvFeatures = {
/**
* Cookie crawl (cookieScanner.crawl): the scanner service URL and the shared
* token (at least 16 characters). Required in production only.
*/
cookieCrawl?: boolean
/** Override the database var. Default 'DATABASE_URI'. */
databaseVar?: string
/** Microsoft Graph e-mail (graphAdapter). Adds the GRAPH_* vars. */
@@ -56,6 +61,7 @@ export type IpalEnvFeatures = {
*/
export function ipalEnvRules(features: IpalEnvFeatures = {}): EnvRule[] {
const {
cookieCrawl = false,
databaseVar = 'DATABASE_URI',
emailGraph = false,
ipHeader = false,
@@ -125,6 +131,19 @@ export function ipalEnvRules(features: IpalEnvFeatures = {}): EnvRule[] {
})
}
if (cookieCrawl) {
const required = process.env.NODE_ENV === 'production'
rules.push(
{ name: 'IPAL_COOKIE_SCAN_URL', description: 'Cookie crawler service base URL, e.g. https://cookie-crawler.example.com', kind: 'url', required },
{
name: 'IPAL_COOKIE_SCAN_TOKEN',
description: 'Token shared with the cookie crawler (this site\'s entry in IPAL_CRAWLER_SITES)',
required,
validate: (v) => (v.length >= 16 ? true : 'IPAL_COOKIE_SCAN_TOKEN must be at least 16 characters'),
},
)
}
if (turnstile) {
const names = typeof turnstile === 'object' ? turnstile : {}
rules.push(