Files
ipal-kit/docs/cookie-scanner.md
T
Radosław SmolińskiandClaude Opus 5.5 546806fe39 Admin follow-ups: localised stats tab title, scanner names, close label, favicon hint
- Statistics view: the browser-tab title follows the admin language.
  Payload's custom-view meta.title is one plain string and its custom-view
  metadata ignores i18n, so the view renders <DocumentTitle> (/admin) with the
  translated title; it re-applies the title while the view is open because
  Next streams the English metadata in after hydration. adminDocumentTitle()
  adds admin.meta.titleSuffix the way Payload does.
- Cookie scanner: CookieIntegration.label may be { en, pl, ... }. The built-in
  names without a product name come from the shared admin texts
  (cookieIntegration*, cookieSourceProject); the scan endpoint answers in the
  request's admin language and stored source names use the scanning editor's.
- Maintenance notice: getConstructionMode(locale) returns `locale`; the "x"
  close button gets a screen-reader name "Close" / "Zamknij" (locale and
  closeLabel props; constructionCloseLabel exported).
- Favicon: FaviconCheck (/admin, afterInput on Site settings -> Site icon)
  warns in the admin language when the image is under 48x48 or not square,
  without blocking the save; validateFaviconField shares faviconProblems().
- Docs, AGENT.md and skills: the above, plus Next.js 16.4.1 or later as the
  minimum safe version (AGENT.md 4.11, ipal-setup, ipal-upgrade).

Co-Authored-By: Claude Opus 5.5 <[email protected]>
2026-10-27 16:31:46 +01:00

26 KiB
Raw Permalink Blame History

cookie scanner

Fills the cookie list (Cookie banner → Cookie list) from the admin panel. A scan lists the cookies of every integration the project switches on, plus any extra names, as drafts in a review list. An editor accepts, edits or rejects each one; accepting adds it to the cookie list, which feeds the <CookieBanner settings="detailed"> window and <CookieTable> on the policy page (consent.md).

What a scan never does: delete an entry, change text an editor edited, change an entry's status, or publish anything by itself.

Opt-in (cookieScanner, default off). Nothing is fetched at runtime and no browser is needed.

A second, also opt-in step — Check site (cookieScanner.crawl, see Browser crawl) — opens the site in a real browser twice (no consent / after "Accept all") through a shared scanner service, reports every non-necessary cookie or tracker present before consent as a violation, and adds what it finds to the same review list. The browser runs in the service, never in the site.

Turn it on

// payload.config.ts
ipalKit({
  // …
  cookieScanner: true,
})

Then, in the project:

  1. Import map — the "Scan cookies" box above the list is an admin component (@intecion/ipal-kit/admin#CookieScanButton). Run pnpm generate:importmap.
  2. Postgres / SQLite migration — the option adds the cookie-review collection (with localized purpose and retention). Run pnpm payload migrate:create cookie-scanner, commit the migration; Coolify runs payload migrate on deploy (deployment.md). MongoDB: nothing to do.
  3. Verify — log in as an editor, open Privacy → Cookie review. The box lists "Integrations in use" (e.g. Cookie banner, Admin panel login, Google Analytics 4). Click Scan cookies: drafts appear, each with Found by = Plugin integration. Set one to Accepted, save, open Cookie Settings → Cookies: the cookie is there, with purpose and retention in every language.

How editors use it

Step What happens
Scan cookies One draft per cookie of the integrations in use. Cookies already in Cookie banner → Cookie list are looked up too (In the cookie list is ticked).
More cookie names (optional text box) Names seen in the browser (DevTools → Application → Cookies), one per line. Each is looked up in the project's declarations, every built-in integration, then the Open Cookie Database. A name nothing knows becomes an entry with Found by = "Unknown — fill in" and no category.
Edit a draft Change provider, category, purpose, retention. A later scan keeps every value you changed (per language) and still updates values you left as suggested.
Accepted The cookie is added to Cookie banner → Cookie list in every language. When a row with that name already exists, only its empty provider / purpose / retention are filled — text written there stays, its category is not changed. An entry without a category cannot be accepted.
Rejected Stays in the list as rejected; later scans do not bring it back to draft. Rejecting never removes a row from Cookie banner — delete it there.

Status changes work in the list's bulk edit too. Deleting review entries is admin-only and never done by the plugin.

Labels are in English and Polish and follow the editor's admin language; cookieScanner.labels adds languages or changes text. The built-in integrations without a product name (Cookie banner, Admin panel login, Language choice, Built-in statistics) take their names from the shared admin texts (adminTexts, keys cookieIntegration*, and cookieSourceProject for your own declarations), so the scan box lists them in the editor's language; the Source stored on a review entry is in the language of whoever ran the scan (English for a site check). Rename one through cookieScanner.integrations (label: { en: '…', pl: '…' }).

What the plugin declares

Each integration the plugin injects declares its cookies in one place (DEFAULT_COOKIE_INTEGRATIONS): name or pattern (* at the end = prefix), provider, category, purpose and retention (English and Polish), and whether it may be set before consent. Only the integrations switched on in this project are part of a scan:

Integration On when Cookies
Cookie banner always cookie-consent (necessary, 6 months)
Admin panel login always payload-token (<cookiePrefix>-token, necessary, editors only)
Language choice more than one locale in i18n NEXT_LOCALE (functional, session)
Built-in statistics stats option ipal_vid (analytics, 6 months)
Google Analytics 4 GA4 ID in Site integrations _ga, _ga_* (analytics, 2 years)
Google Tag Manager GTM ID in Site integrations _gcl_* (marketing — the Conversion Linker; other tags in the container: add their names or declare them)
Meta Pixel Pixel ID _fbp, _fbc (marketing, 3 months)
Microsoft Clarity Clarity ID _clck, _clsk, CLID, MUID
LinkedIn Insight Tag partner ID li_fat_id, bcookie, lidc, UserMatchHistory
TikTok Pixel Pixel ID _ttp, _tt_enable_cookie
Cloudflare Turnstile both Turnstile keys set cf_clearance (necessary; only when pre-clearance is on in Cloudflare)

An ID that fails its format check counts as off. The theme switcher (ipal-theme in localStorage) and the accessibility widget (a11y-prefs) have no plugin option, so they are not declared: add them with declarations when the site uses them.

Unknown names are looked up in a bundled copy of the Open Cookie Database (about 2,300 entries, Apache License 2.0). The package ships the license text in licenses/open-cookie-database-LICENSE.txt; the data module names the upstream commit and the changes made (converted from CSV, two columns left out). The table is loaded only when a scan runs.

Category mapping (DEFAULT_DATABASE_CATEGORIES):

Database Consent category
Analytics analytics
Marketing marketing
Necessary, Security necessary
Functional, Personalization functional

"Functional" is not mapped to necessary on purpose: the database files some trackers there (Hotjar's user id), and a lookup nobody checked yet must not skip consent. The editor lowers the category when a cookie really is necessary, or the project changes the map: cookieScanner: { databaseCategories: { Functional: 'necessary' } }.

Refresh the copy (maintainers of ipal-kit, not projects):

pnpm cookie-db:refresh

scripts/refresh-cookie-database.mjs downloads the CSV and the license at the latest commit (or --ref <sha>), refuses to write if the license is no longer Apache-2.0, and rewrites src/modules/consent/scanner/data/openCookieDatabase.ts and the license file. Review the diff, run the tests, commit.

Options

cookieScanner: true or an object (CookieScannerOptions, every key optional):

Key Default What it does
declarations [] The project's own cookies (custom embeds, chat, YouTube): CookieDeclaration[], always part of a scan
integrations built-ins (defaults) => integrations — filter, change or add CookieIntegrations (each: key, label — one string or { en, pl, … } per admin language, declarations, isEnabled(ctx))
database true false = no Open Cookie Database lookup
databaseCategories table above Partial map from database category to consent category
access editor and up ({ req }) => boolean — who may scan, start a crawl and read its status
collectionOverrides — Change cookie-review: an object merges access / admin / hooks key by key (your keys win), a function takes over (keep the slug)
labels en, pl { de: { scanButton: 'Cookies scannen', … } } — merged over the plugin's labels (CookieScanLabels)
syncAccepted true false = accepting only marks the entry; nothing is written to Cookie banner
crawl off browser crawl through the scanner service — Browser crawl

A project declaration:

import type { CookieDeclaration } from '@intecion/ipal-kit'

const youtube: CookieDeclaration = {
  name: 'VISITOR_INFO1_LIVE',
  vendor: 'Google (YouTube)',
  category: 'marketing',
  domain: 'youtube.com',
  purpose: { en: 'YouTube: player preferences and bandwidth estimate.', pl: 'YouTube: preferencje odtwarzacza.' },
  retention: { en: '6 months', pl: '6 mies.' },
  setBeforeConsent: false,
}

ipalKit({ cookieScanner: { declarations: [youtube] } })

A project integration that is on only when a field is filled:

import type { CookieIntegration } from '@intecion/ipal-kit'

const chat: CookieIntegration = {
  key: 'chat',
  label: 'Live chat',
  isEnabled: (ctx) => Boolean(ctx.integrations.chatWidgetId),
  declarations: [/* CookieDeclaration … */],
}

ipalKit({ cookieScanner: { integrations: (defaults) => [...defaults, chat] } })

ctx (CookieScanContext) has payload, integrations (the Site integrations global, depth 0) and plugin ({ localeCount, stats }).

Endpoint

GET /api/ipal/cookie-scan { ok, integrations: [{ key, label }] } — what a scan covers; label in the admin language of the request
POST /api/ipal/cookie-scan body { names?: string[] | string } (newline or comma separated, up to 200, names with spaces, ;, , or = dropped) → { ok, summary: { created, updated, unchanged, unknown }, integrations }
Access editor and up (userMeetsRole; without access every logged-in account), or cookieScanner.access; otherwise 403

The path is COOKIE_SCAN_PATH (/ipal/cookie-scan, under the API route).

COOKIE_REVIEW_SLUG, group Settings. Fields: name, storage (cookie / localStorage / sessionStorage), category, vendor, domain, purpose (localized), retention (localized), setBeforeConsent, status (draft / accepted / rejected), and read-only source (integration / project / database / unknown / manual), sourceDetail, listed, lastScannedAt; hidden key (storage:name, unique — what a rescan matches) and suggested (the last scan's values — a value still equal to it was not edited). Access: create / read / update editor and up, delete admin.

Building blocks

All from @intecion/ipal-kit (server-safe), for your own admin view, a CLI or a scheduled job:

Export What it does
runCookieScan({ payload, plugin, options?, names?, req? }) the whole scan as the endpoint runs it → { enabled, summary }
collectCookieFindings({ ctx, integrations?, declarations?, names?, database?, databaseCategories? }) findings without writing anything; names are strings or CookieObservations ({ name, storage?, domain? }); matches maps each to its review key
applyCookieFindings({ payload, findings, entries?, req?, collection? }) writes findings as drafts with the merge rules above → CookieScanSummary (created, updated, unchanged, unknown, newUnknown); entries collects CookieReviewEntryRefs
cookieScanContext(payload, plugin, req?) the CookieScanContext a scan uses
parseCookieNames(input) the panel's text box → clean names
mergeCookieReview(current, previous, next), suggestionFor(finding, locales) the "never overwrite an edit" rule, pure
addToCookieList({ payload, entry, req? }) what accepting does: add the row or fill its empty text → 'added' | 'filled' | 'unchanged'
loadCookieDatabase(), indexCookieDatabase(rows), lookupCookie(index, name, categories?) the Open Cookie Database lookup
DEFAULT_COOKIE_INTEGRATIONS, DEFAULT_DATABASE_CATEGORIES, cookieNameMatches(pattern, name) declarations and matching
buildCookieReviewCollection(options), buildCookieScanEndpoints(options, plugin) the collection and endpoints, to wire by hand
COOKIE_SCAN_LABELS, mergeCookieScanLabels(overrides) admin labels
CookieScanButton (/admin) the box above the list (with Check site when crawl is on)
CookieCrawlAlert (/admin) the dashboard warning (injected with crawl)
buildCookieCrawlGlobal(labels), buildCookieCrawlEndpoints({ labels, options, plugin }) the crawl's global and endpoints, to wire by hand
resolveCrawlConfig(crawlOptions, payload) options + env + serverURL → ResolvedCrawlConfig (what is missing)
parseCrawlResult(body) validates the service's JSON (CrawlResult, CrawlObservation, CrawlRequest)
ingestCrawlResult({ payload, result, options, config, labels, plugin }), finishCrawl(…) applies a result: drafts, flags (→ CrawlIngestSummary), then the global and the e-mail
findCrawlViolations({ observations, requests, categoryOf, consentMode?, trackerHosts? }) the violation rule, pure (CrawlViolation)
DEFAULT_TRACKER_HOSTS, GOOGLE_TAG_HOSTS request hosts that count before consent
sendCrawlWarning({ payload, labels, siteUrl, summary, to }) the e-mail, through payload.sendEmail
bearerMatches(header, token) constant-time bearer check

Types: CookieDeclaration, CookieIntegration, CookieScanContext, CookieFinding, CookieFindingSource, CookieStorage, LocalizedText, CookieScannerOptions, CookieScanSummary, CookieReviewValues, CookieDatabaseIndex, CookieScanLabels, OpenCookieCategory, CookieObservation, CookieReviewEntryRef; crawl: CookieCrawlOptions, ResolvedCrawlConfig, CrawlResult, CrawlObservation, CrawlRequest, CrawlViolation, CrawlIngestSummary.

Browser crawl

What a page really sets — a GTM tag, an iframe, a script pasted into a block — shows only in a browser. cookieScanner.crawl adds Check site to the Cookie review box. One shared scanner service (services/cookie-crawler in the ipal-kit repository, run by the team on Coolify) does the browsing for every site:

editor ── Check site ──▶ site  POST /api/ipal/cookie-crawl
                         site ── POST {IPAL_COOKIE_SCAN_URL}/crawl (Bearer token) ──▶ scanner service
                                                              crawls the sitemap pages twice:
                                                              1. fresh profile, no decision
                                                              2. fresh profile, clicks "Accept all"
site  POST /api/ipal/cookie-crawl/results (Bearer token) ◀── cookies, storage keys, third-party hosts
      → drafts in Cookie review, violations, Cookie check global (`cookie-crawl`), dashboard warning, e-mail

Turn it on in a site

ipalKit({
  cookieScanner: { crawl: true },
})
  1. Env (Coolify → the site → Environment Variables):

    Variable Value
    IPAL_COOKIE_SCAN_URL the service's URL, e.g. https://cookie-crawler.intecion.net
    IPAL_COOKIE_SCAN_TOKEN a random token of at least 16 characters (openssl rand -hex 32), the same one as in the service's IPAL_CRAWLER_SITES entry for this site
    NEXT_PUBLIC_SERVER_URL already set — the public origin the service crawls and calls back (or Payload serverURL, or crawl.siteUrl)

    Validate them at startup: assertEnv(ipalEnvRules({ cookieCrawl: true })) (required in production).

  2. Import map: pnpm generate:importmap (the dashboard warning CookieCrawlAlert).

  3. Migration (Postgres / SQLite): crawl adds the cookie-crawl global and three fields to cookie-review (violation, violationDetail, seenBeforeConsent): pnpm payload migrate:create cookie-crawl, commit; Coolify runs payload migrate on deploy.

  4. Service: add the site to the service's IPAL_CRAWLER_SITES (below) and redeploy the service.

  5. Verify: Cookie review shows "Check site" enabled (when disabled, the box names the missing env var). Click it: the status says "Crawling…", then after one to a few minutes "Last crawl …: N pages, N violations, N new unknown" and the list reloads. Privacy → Cookie check shows the latest result. A test: put a <script>document.cookie='_fbp=x'</script> in a block on a staging page → the next crawl reports _fbp as a violation and the dashboard shows the warning.

What a crawl records and reports

Pages the site URL + up to maxPages (default 20, max 100) same-origin URLs from /sitemap.xml (one level of sitemap index)
Recorded per run cookies (name, domain), localStorage and sessionStorage keys, hosts of third-party requests, with the first pages they appeared on
New findings every cookie / key goes through the same lookup and merge rules as Scan cookies — new names become drafts, edited text is kept, status is never changed, nothing is deleted
Violation (cookie or key) seen before consent and its review entry's category is not necessary — an entry without a category counts too, until an editor classifies it
Violation (request) a request before consent to a tracker host (DEFAULT_TRACKER_HOSTS: Meta, LinkedIn, TikTok, Clarity, Bing, Hotjar, YouTube). Google's tag hosts (GOOGLE_TAG_HOSTS) count only with consentMode: 'basic' — in advanced (the plugin's default) the Google tag may load before consent with every signal denied
Review entries seenBeforeConsent, violation and violationDetail ("before consent on /, /about") — from the latest crawl only: every crawl clears the previous flags
Cookie check global (cookie-crawl) latest result only (no history): status, started / finished, by whom, pages, counts, violations, third-party hosts, error
"Accept all" not found the second run had no consent — the global's error says so (crawl.acceptSelector for a custom banner)
Dashboard a warning above the dashboard after a crawl with violations or new unknown cookies, or a failed crawl (crawl.dashboard: false turns it off)
E-mail opt-in per site: Privacy → Cookie check → E-mail warnings to (admin; comma-separated). Sent after a crawl with violations or new unknown cookies, through the project's Payload email adapter (email: mailAdapter(), email.md). Empty = no e-mail

A crawl still "running" after 30 minutes counts as failed (the service never reported back), and a new one may start. One crawl per site at a time (409 otherwise).

Scheduled crawls

A Coolify Scheduled Task on the site's application (or any cron) starts a crawl with the token — no editor session needed:

curl -fsS -X POST -H "Authorization: Bearer $IPAL_COOKIE_SCAN_TOKEN" "$NEXT_PUBLIC_SERVER_URL/api/ipal/cookie-crawl"

Weekly is plenty (0 6 * * 1). New violations or unknown cookies then show on the dashboard and, when recipients are set, by e-mail.

crawl options

crawl: true or CookieCrawlOptions:

Key Default What it does
serviceUrl env IPAL_COOKIE_SCAN_URL scanner service base URL
token env IPAL_COOKIE_SCAN_TOKEN shared secret (≥ 16 characters); shorter = not configured
siteUrl Payload serverURL, else NEXT_PUBLIC_SERVER_URL public origin to crawl; the callback goes to <siteUrl>/api/ipal/cookie-crawl/results
maxPages 20 (max 100) sitemap pages besides the site URL
acceptSelector [data-ipal="accept"] the banner's "Accept all" button (the plugin's CookieBanner has it in every mode)
consentMode 'advanced' 'basic' = Google tag requests before consent are violations too — match the project's SiteProviders analytics={{ consentMode }}
trackerHosts DEFAULT_TRACKER_HOSTS (defaults) => [...defaults, 'widget.chat.example']
dashboard true false = no dashboard warning
globalOverride — change the cookie-crawl global like globalOverrides (object merges access / admin / hooks, a function takes over)

Access: start a crawl and read its status — editor and up (cookieScanner.access), or the bearer token; the results endpoint — the bearer token only, and only for the running job id; the cookie-crawl global — read editor and up, update (the e-mail field) admin.

Endpoints

GET /api/ipal/cookie-crawl { configured, missing, status, startedAt, finishedAt, summary, error }
POST /api/ipal/cookie-crawl starts a crawl → 202; 403, 409 (one is running), 503 (not configured), 502 (service unreachable — the global says why)
POST /api/ipal/cookie-crawl/results the service's callback: Authorization: Bearer <token>, body = the wire format (CrawlResult) → 200; 401, 400, 409 (not the running job)

Paths: COOKIE_CRAWL_PATH, COOKIE_CRAWL_RESULTS_PATH; env names: COOKIE_SCAN_URL_ENV, COOKIE_SCAN_TOKEN_ENV; global slug COOKIE_CRAWL_SLUG.

Scanner service on Coolify

One service for every site the team runs. Code: services/cookie-crawler/ in the ipal-kit repository (Node + Playwright, no other dependency; not part of the npm package).

  1. Coolify → Project → New Resource → Application from the ipal-kit Git repository.

    • Build pack: Dockerfile; base directory services/cookie-crawler; Dockerfile Dockerfile.
    • Port: 3000. Health check path: /health (the image also has a Docker HEALTHCHECK).
    • Domain: e.g. https://cookie-crawler.intecion.net (Coolify issues the certificate).
    • Resources: 1–2 GB RAM, 1 CPU per concurrent crawl (Chromium). Keep CRAWLER_CONCURRENCY=1 unless the server has room.
  2. Environment variables:

    Variable Default
    IPAL_CRAWLER_SITES — (required) acme.pl=TOKEN1,shop.example.com=TOKEN2 — the sites it may crawl, each with its own token (≥ 16 characters; www. is ignored). A token only opens its own site
    PORT 3000
    CRAWLER_CONCURRENCY 1 crawls at the same time
    CRAWLER_QUEUE_MAX 20 waiting crawls; more → 429
    CRAWLER_JOB_TIMEOUT_MS 600000 a longer crawl is reported as failed
    CRAWLER_WAIT_MS 3000 wait on every page for late tags (defer analytics)
    CRAWLER_ALLOW_HTTP unset 1 only for local tests; sites must be https
  3. Deploy, then check: curl https://cookie-crawler.intecion.net/health → {"ok":true,…}.

  4. Adding a site: generate a token, add host=token to IPAL_CRAWLER_SITES, redeploy the service; set the same token as the site's IPAL_COOKIE_SCAN_TOKEN.

  5. Updating Playwright: the npm version in services/cookie-crawler/package.json and the image tag in its Dockerfile (mcr.microsoft.com/playwright:v1.64.0-noble) must match; change both, redeploy.

What the service refuses: a site not in IPAL_CRAWLER_SITES, a token that is not that site's, a callback URL on another origin than the site, plain http. It crawls only the listed origins (no open proxy), runs Chromium as the image's non-root user, and keeps nothing after a crawl.

DNS and network:

  • One DNS record for the service: cookie-crawler.<team domain> → A/AAAA to the Coolify server (the team runs the zone; add it with the other records, deployment.md §6). No record is needed per site.
  • The site must reach the service URL (outbound HTTPS from the site container), and the service must reach each site's public URL (outbound HTTPS) — the crawl must go through the public domain, CDN and proxy, as a visitor's browser does. On the same Coolify server both go out and back through the public domain; do not point siteUrl at an internal container name (cookies are set for the public domain).
  • Sites behind Cloudflare (WAF, Bot Fight Mode, "Under Attack"): allow the Coolify server's IP, or the crawl sees a challenge page instead of the site. Every crawler request carries the header X-Ipal-Cookie-Crawler: 1 for a WAF rule.
  • The crawler's page views land in the site's stats and analytics like any visitor without consent (cookieless) and with consent on the second run. Filter the Coolify server's IP in GA4 if it matters.

From a laptop or CI

The same crawl, without the service: cd services/cookie-crawler && npm install && npx playwright install chromium, then node cli.mjs https://acme.pl --pages 10 prints the result as JSON (exit code 1 when anything but the consent cookie is stored before consent). It does not know the site's categories — the panel's Check site gives the verdict. ipal-consent-check → cookie-scan (cookie-scan.mjs) stays the quick check for projects without the service; paste the names it reports as unknown into More cookie names.

Turn off, override, extend

  • Turn off the crawl only: omit crawl (default) — no cookie-crawl global, no crawl endpoints, no dashboard warning, no violation fields; dashboard: false keeps the crawl without the warning.
  • Turn off: omit cookieScanner (default). Turning it off later keeps no endpoint and no collection; Cookie banner → Cookie list keeps every row (it is still edited by hand or by the skill's import script).
  • Override: collectionOverrides (access, admin, hooks), access (who scans), labels, databaseCategories, integrations (change or drop a built-in), syncAccepted: false; for the crawl serviceUrl, token, siteUrl, maxPages, acceptSelector, consentMode, trackerHosts, globalOverride.
  • Extend: declarations and integrations for the project's own cookies; the building blocks above for your own UI, CLI or scheduled scan; the crawl's wire format (CrawlResult) to feed results from another crawler.