Files
ipal-kit/docs/cookie-scanner.md
T
Radosław SmolińskiandClaude Opus 5.5 a0545b6716 Cookie scanner, phase 1: declarations, database lookup, review list
ipalKit({ cookieScanner }) (opt-in) adds the cookie-review collection, a
"Scan cookies" box above its list and GET/POST /api/ipal/cookie-scan. A scan
lists the cookies of every integration the project switches on (consent,
admin login, locale, stats, GA4, GTM, Meta Pixel, Clarity, LinkedIn, TikTok,
Turnstile), the project's own declarations, and extra names looked up in the
bundled Open Cookie Database, as drafts. Editors accept (→ Cookie Settings →
Cookies, every locale, only empty text filled), edit or reject. A rescan never
deletes, never changes status and never overwrites edited text.

Everything is overridable (access, collectionOverrides, integrations,
declarations, databaseCategories, labels, syncAccepted) and the building
blocks are exported. Admin labels in en + pl. Docs: cookie-scanner.md,
consent.md, AGENT.md, ipal-reference, ipal-consent-check.

Co-Authored-By: Claude Opus 5.5 <[email protected]>
2026-10-27 14:55:20 +01:00

222 lines
12 KiB
Markdown

# cookie scanner
Fills the cookie list (Cookie Settings → Cookies) 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](./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.
## Turn it on
```ts
// 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 *Settings → 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 Settings → Cookies 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 Settings → Cookies 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 Settings — 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.
## 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.
## Open Cookie Database
Unknown names are looked up in a bundled copy of the
[Open Cookie Database](https://github.com/jkwakman/Open-Cookie-Database) (about 2,300 entries,
Apache License 2.0). The package ships the license text in
[licenses/open-cookie-database-LICENSE.txt](./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):
```bash
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 `CookieIntegration`s (each: `key`, `label`, `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 call the scan endpoint |
| `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 Settings |
A project declaration:
```ts
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:
```ts
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 |
| `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).
## Collection `cookie-review`
`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 |
| `applyCookieFindings({ payload, findings, req?, collection? })` | writes findings as drafts with the merge rules above → `CookieScanSummary` |
| `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 |
Types: `CookieDeclaration`, `CookieIntegration`, `CookieScanContext`, `CookieFinding`,
`CookieFindingSource`, `CookieStorage`, `LocalizedText`, `CookieScannerOptions`, `CookieScanSummary`,
`CookieReviewValues`, `CookieDatabaseIndex`, `CookieScanLabels`, `OpenCookieCategory`.
## The browser scan in the skill
The panel scan knows what the plugin and the project declare. What a page really sets (a GTM tag, an
iframe, a script pasted into a block) shows only in a browser: `ipal-consent-check` → cookie-scan
(`cookie-scan.mjs`, Playwright on the developer's machine) lists every cookie before and after
consent and fails on a non-necessary cookie set before consent. Paste the names it reports as
unknown into **More cookie names** to get them into the review list.
## Turn off, override, extend
- **Turn off:** omit `cookieScanner` (default). Turning it off later keeps no endpoint and no
collection; Cookie Settings → Cookies 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`.
- **Extend:** `declarations` and `integrations` for the project's own cookies; the building blocks
above for your own UI, CLI or scheduled scan.