Cookie scanner, phase 2: browser crawl through a shared scanner service

cookieScanner.crawl (opt-in) adds "Crawl site" to the Cookie review box. The
site asks the shared scanner service (services/cookie-crawler: Node +
Playwright, Dockerfile, deployed once on Coolify) to crawl its sitemap pages
twice, with no consent and after "Accept all". The service posts cookies,
storage keys and third-party hosts back to POST /api/ipal/cookie-crawl/results
(bearer token, running job only). No browser in the site.

Findings land as drafts through the same merge rules. Anything stored before
consent that is not necessary, and tracker requests before consent, are
violations, flagged on the review entries from the latest crawl only. The
cookie-crawl global keeps the latest result (no history). A dashboard warning
(CookieCrawlAlert) and an opt-in e-mail through the project's mail adapter
follow a crawl with violations or new unknown cookies. Scheduled crawls: a
Coolify scheduled task with the token. ipalEnvRules({ cookieCrawl: true }).

Also: the six older real-Payload tests no longer leave an orphaned
payload generate:types process (typescript.autoGenerate: false).

Co-Authored-By: Claude Opus 5.5 <[email protected]>
This commit is contained in:
Radosław Smoliński
2026-10-27 15:14:01 +01:00
co-authored by Claude Opus 5.5
parent 4f69f6ed20
commit 4bb9c663fd
44 changed files with 2165 additions and 36 deletions
+191 -13
View File
@@ -11,6 +11,11 @@ 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 — **Crawl site** (`cookieScanner.crawl`, see [Browser crawl](#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
```ts
@@ -118,10 +123,11 @@ run the tests, commit.
| `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 |
| `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 Settings |
| `crawl` | off | browser crawl through the scanner service — [Browser crawl](#browser-crawl) |
A project declaration:
@@ -186,8 +192,8 @@ All from `@intecion/ipal-kit` (server-safe), for your own admin view, a CLI or a
| 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` |
| `collectCookieFindings({ ctx, integrations?, declarations?, names?, database?, databaseCategories? })` | findings without writing anything; `names` are strings or `CookieObservation`s (`{ 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 `CookieReviewEntryRef`s |
| `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 |
@@ -196,26 +202,198 @@ All from `@intecion/ipal-kit` (server-safe), for your own admin view, a CLI or a
| `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 |
| `CookieScanButton` (`/admin`) | the box above the list (with **Crawl 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`.
`CookieReviewValues`, `CookieDatabaseIndex`, `CookieScanLabels`, `OpenCookieCategory`,
`CookieObservation`, `CookieReviewEntryRef`; crawl: `CookieCrawlOptions`, `ResolvedCrawlConfig`,
`CrawlResult`, `CrawlObservation`, `CrawlRequest`, `CrawlViolation`, `CrawlIngestSummary`.
## The browser scan in the skill
## Browser crawl
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.
What a page really sets — a GTM tag, an iframe, a script pasted into a block — shows only in a
browser. `cookieScanner.crawl` adds **Crawl 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 ── Crawl 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 crawl global, dashboard warning, e-mail
```
### Turn it on in a site
```ts
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 "Crawl 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. *Settings → Cookie crawl* 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 crawl global | 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: *Settings → Cookie crawl → 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:
```bash
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 **Crawl 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 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`.
`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.
above for your own UI, CLI or scheduled scan; the crawl's wire format (`CrawlResult`) to feed results
from another crawler.