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
+2
View File
@@ -905,6 +905,7 @@ project → **plugin gap**, not a copy.
| A consent-dependent script | `ConsentScript` | consent.md |
| Cookie table on the policy page | `<CookieTable>` (`/rsc`), `getCookieTable` | consent.md |
| Cookie list filled from the panel (drafts the editor accepts) | `ipalKit({ cookieScanner: true })` + `pnpm generate:importmap` + migration; project cookies: `cookieScanner.declarations` / `integrations` — do not type the list by hand or build your own scanner | cookie-scanner.md |
| Pre-consent check in a browser (button in the panel, violations, dashboard + e-mail warning) | `cookieScanner: { crawl: true }` + env `IPAL_COOKIE_SCAN_URL` / `IPAL_COOKIE_SCAN_TOKEN` (`ipalEnvRules({ cookieCrawl: true })`) + the site's `host=token` in the shared service's `IPAL_CRAWLER_SITES`; never Playwright/Chromium in the site | cookie-scanner.md → Browser crawl |
| GA4, GTM, Pixel, Clarity, LinkedIn, TikTok | IDs in the panel — `SiteProviders` loads `Analytics` (`analytics={{ defer: true }}`; `consentMode: 'basic'` = no Google request before consent) | analytics.md |
| Mail | `email: mailAdapter()`, `sendEmail` | email.md |
| Env validation, health | `assertEnv(ipalEnvRules({…}))` (`/env`), `healthRoute` | env.md |
@@ -928,6 +929,7 @@ payloadTotp } })`, never `twoFactor: false` without a client decision). CSP: fir
| Plugin globals: write editor+ (Site Integrations: admin) | — | `ipalKit({ globalOverrides: { <slug>: { access, admin, hooks } } })`; a function `(global) => global` takes over (`applyGlobalOverrides`) |
| Global saves revalidate the layout (with `ipalKit({ revalidatePath })`) | omit `revalidatePath`; once: `context: { disableRevalidate: true }` | `buildGlobalRevalidateHook` on your own globals |
| Staff features without `access` (no roles field): every logged-in account passes (`userMeetsRole`) | add `access` (roles decide) | `globalOverrides`, `forms.formSubmissionOverrides`, `consentLog.collectionOverrides`, `stats.collectionOverrides` |
| Cookie crawl (`crawl`): start editor+ or the token, results token-only for the running job, latest result only, dashboard warning on, e-mail off until recipients are set | omit `crawl`; `crawl.dashboard: false` | `crawl.serviceUrl` / `token` / `siteUrl` / `maxPages` / `acceptSelector` / `consentMode` / `trackerHosts` / `globalOverride`; *Cookie crawl → E-mail warnings to*; building blocks `ingestCrawlResult`, `findCrawlViolations`, `parseCrawlResult` |
| Cookie review: scan + review editor+, delete admin; Open Cookie Database "Functional" → `functional` | omit `cookieScanner` | `cookieScanner.access`, `collectionOverrides`, `databaseCategories`, `integrations`, `declarations`, `labels`, `syncAccepted: false`; building blocks `runCookieScan`, `collectCookieFindings`, `applyCookieFindings` |
| Consent records / stats visits: read and delete admin (stats view and chart follow `stats-visits` read access) | omit `consentLog` / `stats` | `consentLog.collectionOverrides`, `stats.collectionOverrides` (object merges `access`/`admin`/`hooks`, function takes over; `applyCollectionOverride`) |
| Injected `users`: admin manages everyone, others only themselves | — | `access.authAccess` (your keys win); your own `users` collection wins whole |
@@ -62,6 +62,26 @@ list in the panel and you check it:
"Functional" (it files some trackers there) — lower to `necessary` only when the cookie really
is needed for the site to work.
## Pre-consent check from the panel (`cookieScanner.crawl`)
When the project has `cookieScanner: { crawl: true }` (cookie-scanner.md → Browser crawl):
1. Not on yet and the client wants it → turn it on; env `IPAL_COOKIE_SCAN_URL` +
`IPAL_COOKIE_SCAN_TOKEN` (`openssl rand -hex 32`) in Coolify; ask the team to add
`<host>=<token>` to the scanner service's `IPAL_CRAWLER_SITES`; `generate:importmap`,
`migrate:create cookie-crawl`. Never add Playwright or Chromium to the site.
2. *Cookie review* → **Crawl site**. "Crawl site" disabled → the box names the missing variable.
Failed → *Settings → Cookie crawl → Error* ("Could not reach the scanner service" = URL / DNS /
firewall; a Cloudflare challenge page = allow the Coolify server's IP).
3. Filter the list by **Violation**: every entry is a non-necessary cookie or key stored before
consent — fix it as in the table above (or, if it really is necessary, set its category and accept
it). *Cookie crawl → Violations* also lists tracker **requests** before consent.
4. Classify the new drafts (*Found by* = "Unknown — fill in"), then crawl again: 0 violations is
the goal before handover.
5. Optional: recipients in *Cookie crawl → E-mail warnings to*, and a weekly Coolify scheduled task
`curl -X POST -H "Authorization: Bearer $IPAL_COOKIE_SCAN_TOKEN" $NEXT_PUBLIC_SERVER_URL/api/ipal/cookie-crawl`.
Record both in `AGENTS.md` → "Project decisions".
## Cookie list for the cookie policy (cookie-scan)
After every change of tools (new pixel, chat, map, video) and before handing the site over
+9 -1
View File
@@ -67,6 +67,9 @@ description: Complete map of everything @intecion/ipal-kit provides — every ip
| `cookieScanner` | off | `cookie-review` collection (drafts an editor accepts → Cookie Settings → Cookies), "Scan cookies" box above its list (`CookieScanButton`), `GET`/`POST /api/ipal/cookie-scan`; a scan lists the cookies of the integrations switched on + names looked up in the bundled Open Cookie Database; never deletes, never overwrites edited text, never publishes by itself | `true` / object; after switching on: `pnpm generate:importmap` + `migrate:create`. Check: *Settings → Cookie review* → **Scan cookies** → drafts appear; set one to Accepted → it is in Cookie Settings → Cookies (cookie-scanner.md) |
| `cookieScanner.declarations` / `.integrations` | built-ins only | the project's own cookies (`CookieDeclaration[]`), or `(defaults) => CookieIntegration[]` to add / change / drop integrations (`key`, `label`, `declarations`, `isEnabled(ctx)`) | e.g. a chat widget on when `ctx.integrations.chatId` is filled |
| `cookieScanner.access` / `.collectionOverrides` / `.labels` | editor+ / none / `en` + `pl` | who may scan; changes `cookie-review` like `consentLog.collectionOverrides`; admin labels per language (`CookieScanLabels`) | object or function |
| `cookieScanner.crawl` | off | browser pre-consent check through the shared scanner service (`services/cookie-crawler`, Coolify): **Crawl site** in the review box, `cookie-crawl` global (latest result only), `GET`/`POST /api/ipal/cookie-crawl`, `POST /api/ipal/cookie-crawl/results` (token), `violation` / `violationDetail` / `seenBeforeConsent` on `cookie-review`, `CookieCrawlAlert` on the dashboard, e-mail to *Cookie crawl → E-mail warnings to* | `true` / `CookieCrawlOptions`; env `IPAL_COOKIE_SCAN_URL` + `IPAL_COOKIE_SCAN_TOKEN`; `generate:importmap` + `migrate:create`. Check: the review box's **Crawl site** is enabled → click → "Last crawl …" with counts; `curl -X POST -H "Authorization: Bearer $IPAL_COOKIE_SCAN_TOKEN" $U/api/ipal/cookie-crawl` → 202 |
| `cookieScanner.crawl.serviceUrl` / `.token` / `.siteUrl` / `.maxPages` / `.acceptSelector` | env URL / env token / `serverURL` → `NEXT_PUBLIC_SERVER_URL` / `20` / `[data-ipal="accept"]` | where the service is, the shared secret, the public origin crawled and called back, pages from the sitemap (max 100), the banner's accept button | options win over env |
| `cookieScanner.crawl.consentMode` / `.trackerHosts` / `.dashboard` / `.globalOverride` | `'advanced'` / `DEFAULT_TRACKER_HOSTS` / `true` / none | `'basic'` also flags Google tag requests before consent; hosts counted as trackers; dashboard warning; changes the `cookie-crawl` global like `globalOverrides` | `(defaults) => [...defaults, 'chat.example']`; `dashboard: false` |
| `cookieScanner.database` / `.databaseCategories` / `.syncAccepted` | `true` / Functional+Personalization → functional, Security+Necessary → necessary / `true` | Open Cookie Database lookup on or off; category map; accepting writes to Cookie Settings | `database: false`; `{ Functional: 'necessary' }`; `syncAccepted: false` |
| `stats` | off | `stats-visits` collection, `POST /api/ipal/hit`, `/<admin>/stats` view, nav link, dashboard chart | `true` / object |
| `stats.collectionOverrides` | none | changes `stats-visits` like `consentLog.collectionOverrides`; its `access.read` also decides who sees the stats view and dashboard chart | object or function |
@@ -85,6 +88,7 @@ description: Complete map of everything @intecion/ipal-kit provides — every ip
| auth collection (`users`) | `{ slug, auth: true, useAsTitle: 'email' }`, when the project has none (slug: `access.authCollection` → `twoFactor.collectionSlug` → `admin.user` → `'users'`); with `access`: create/delete/unlock admin only, read/update admin or self | `access.authAccess`; your own collection with that slug | yours wins |
| `forms`, `form-submissions` | form-builder + ipal blocks `step`, `checkboxGroup`, `time` | `forms` | omit `forms` |
| `consent-records` | proof of consent (id, choices, policy version; `consentLog.collectionOverrides`) | `consentLog` | off by default |
| global `cookie-crawl` | latest browser crawl (status, counts, violations, third-party hosts) + e-mail recipients; read editor+, update admin | `cookieScanner.crawl` (`globalOverride`) | off by default |
| `cookie-review` | cookie scanner drafts (`status` draft / accepted / rejected; create/read/update editor+, delete admin) | `cookieScanner` | off by default |
| `stats-visits` | visits without IP (admin reads/deletes; `stats.collectionOverrides`) | `stats` | off by default |
| global `site-settings` | General, Theme, [System Pages], [Emails], [Under construction], Search & AI, [Custom]; public read, write editor+ | `pages`, `content`, `forms.emailLayout`, `searchSettings` / `seo.searchSettings`, `siteSettingsFields` | always present; access/hooks/fields: `globalOverrides` |
@@ -95,6 +99,7 @@ description: Complete map of everything @intecion/ipal-kit provides — every ip
| `POST /api/ipal/test-email` | SMTP/Graph test (admin only) | — | **currently always** |
| `POST /api/ipal/consent` | saves consent | `consentLog` | off by default |
| `POST /api/ipal/hit` | page view for stats | `stats` | off by default |
| `GET`/`POST /api/ipal/cookie-crawl`, `POST /api/ipal/cookie-crawl/results` | crawl status / start (editor+ or bearer token) / the scanner service's callback (token, running job only) | `cookieScanner.crawl` | off by default |
| `GET`/`POST /api/ipal/cookie-scan` | integrations a scan covers / run a scan (`{ names? }`), editor+ | `cookieScanner` (`access`) | off by default |
| `localization` | from `i18n` | `i18n` | **currently always** |
| `routes.admin` | from `adminRoute` | `adminRoute` | — |
@@ -110,7 +115,8 @@ description: Complete map of everything @intecion/ipal-kit provides — every ip
| `AdminLogo`, `AdminIcon` | `graphics.Logo/Icon` | `whiteLabel` |
| `IntecionCredit` | `afterLogin`, `afterNavLinks` | `whiteLabel` and `credit !== false` |
| `StatsNavLink`, `StatsView` (`views.ipalStats`, `/stats`), `StatsWidget` (`beforeDashboard`) | nav, view, dashboard | `stats` (`dashboard: false` without the widget) |
| `CookieScanButton` | `beforeListTable` of `cookie-review` | `cookieScanner` |
| `CookieScanButton` | `beforeListTable` of `cookie-review` (with **Crawl site** when `crawl` is on) | `cookieScanner` |
| `CookieCrawlAlert` | `beforeDashboard` | `cookieScanner.crawl` and `dashboard !== false` |
| `IntegrationAlerts` | `beforeDashboard` | **currently always** (renders nothing when everything works) |
| `IntegrationStatusBanner` | UI field in the Site Integrations tabs | always (with the global) |
| `MaskedField` | SMTP / Turnstile secrets | always |
@@ -156,6 +162,7 @@ Mandatory set: AGENT.md §0b, skill **ipal-setup**; checks: **ipal-audit**, **ip
| forms — render | form block | `<RenderForm form={form} action={sendForm} locale={locale} texts={formTexts} classNames={formClasses} />` (`/rsc`) | form from the panel, Turnstile, message from Notifications | forms.md |
| Turnstile | panel / env | `SiteProviders` wires `TurnstileProvider`; keys in Site Integrations → Turnstile or env; server: `verifyTurnstile` (`/server`) | widget in the form; dashboard alert on a bad key | turnstile.md |
| consent | layout + policy page | banner via `SiteProviders`; table `<CookieTable rows={…} labels={…} />` (`/rsc`) from `getCookieTable` | `ipal-consent-check`; delete the consent cookie → the banner comes back | consent.md |
| cookie crawl | config + env + service | `cookieScanner: { crawl: true }`, `IPAL_COOKIE_SCAN_URL` / `IPAL_COOKIE_SCAN_TOKEN`, site in the service's `IPAL_CRAWLER_SITES`; optional Coolify scheduled task `curl -X POST -H "Authorization: Bearer $IPAL_COOKIE_SCAN_TOKEN" $U/api/ipal/cookie-crawl` | **Crawl site** → "Last crawl …: N pages, N violations"; *Settings → Cookie crawl* | cookie-scanner.md → Browser crawl |
| cookie list | config | `cookieScanner: true` (+ `declarations` for embeds/chat), `generate:importmap`, `migrate:create` | *Cookie review* → **Scan cookies** → accept → Cookie Settings → Cookies; `<CookieBanner settings="detailed">` lists it | cookie-scanner.md |
| proof of consent | config + layout | `consentLog: true` + `logEndpoint="/api/ipal/consent"` | after a click, a document in Consent Records | consent.md |
| stats | config + layout | `stats: true` + `<SiteProviders stats={{ locale }}>` (or `<PageStats locale />` inside `ConsentProvider`) | `/<admin>/stats`; `POST /api/ipal/hit` request in Network | stats.md |
@@ -206,6 +213,7 @@ and what throws without `i18n`: frontend.md. `SiteProviders` props: `shell`, `ba
| `NEXT_PUBLIC_TURNSTILE_SITE_KEY`, `TURNSTILE_SECRET_KEY` | `turnstile: true` (names: `siteKeyVar`/`secretVar`) | fallback for keys from Site Integrations → Turnstile; neither set → Turnstile off | panel (takes precedence) or env |
| `INDEXNOW_KEY` | no | key from Site Integrations → IndexNow (generated) | env or panel |
| `IPAL_IP_HEADER` | `ipHeader: true` + production | rate limit trusts any IP header (spoofing) + warning in prod | env: `cf-connecting-ip` (Cloudflare) / `x-forwarded-for` (Traefik/nginx) |
| `IPAL_COOKIE_SCAN_URL`, `IPAL_COOKIE_SCAN_TOKEN` | `cookieScanner.crawl` (`ipalEnvRules({ cookieCrawl: true })` requires both in production; token ≥ 16 chars) | **Crawl site** disabled, the box names the missing variable | env; the token also goes into the scanner service's `IPAL_CRAWLER_SITES` as `host=token` |
| `IPAL_NOINDEX` | no; `1`/`true`/`yes` **staging/preview only** | — (when set: robots Disallow, meta noindex, `X-Robots-Tag`, IndexNow sends nothing) | staging env |
| `NEXT_PHASE` | set by Next | only tells `next build` from runtime: during the build an unreachable database gives an empty sitemap; at runtime the sitemap throws (route → 503) | do not set by hand |
| `NEXT_RUNTIME` | set by Next | `instrumentation.ts` checks for `nodejs`; missing (scripts, seed) → `buildRevalidateHook` does not revalidate | do not set by hand |
@@ -25,6 +25,7 @@ Admin panel components from `@intecion/ipal-kit/admin` — the project does NOT
| `RowLabel` | `@intecion/ipal-kit/admin` | Array row title in the panel taken from the row content (e.g. "Fast delivery" instead of "Item 01"). Do not wire by hand — use `rowLabel()`; after adding, `pnpm generate:importmap`. |
| `AdminLogo` | `@intecion/ipal-kit/admin` | Server Component: large panel logo (login screen) from SiteSettings `logo`, fallback `siteName`. Injected by the plugin with `whiteLabel`; after turning the option on, `pnpm generate:importmap`. |
| `AdminIcon` | `@intecion/ipal-kit/admin` | Server Component: small panel nav icon from SiteSettings `favicon`, fallback initials. Injected by the plugin with `whiteLabel`; after turning the option on, `pnpm generate:importmap`. |
| `CookieCrawlAlert` | `@intecion/ipal-kit/admin` | Server Component: dashboard warning after a cookie crawl with violations or new unknown cookies, or a failed crawl; renders nothing otherwise. Injected with `cookieScanner.crawl` (`dashboard: false` drops it); after turning it on, `pnpm generate:importmap`. |
| `CookieScanButton` | `@intecion/ipal-kit/admin` | "Scan cookies" box above the *Cookie review* list: integrations in use, optional extra names, runs `POST /api/ipal/cookie-scan`. Injected by the plugin with `cookieScanner`; after turning it on, `pnpm generate:importmap`. |
| `IntecionCredit` | `@intecion/ipal-kit/admin` | The line "Technology supported by Intecion.com" below the nav and below the login form (`variant: 'nav' \| 'login'`). Injected by the plugin with `whiteLabel`; turn off: `whiteLabel: { credit: false }`. |
@@ -151,7 +152,23 @@ Opt-in with `ipalKit({ cookieScanner: true })`; the plugin wires the collection,
| `COOKIE_REVIEW_SLUG` / `COOKIE_SCAN_PATH` | `@intecion/ipal-kit` | `'cookie-review'` / `'/ipal/cookie-scan'`. |
| `COOKIE_SCAN_LABELS` / `mergeCookieScanLabels(overrides)` | `@intecion/ipal-kit` | Admin labels (`en`, `pl`) and the merge `cookieScanner.labels` uses. |
**Types:** `CookieScannerOptions` (the option), `CookieDeclaration`, `CookieIntegration`, `CookieScanContext`, `CookieFinding`, `CookieFindingSource`, `CookieStorage`, `LocalizedText`, `CookieScanSummary`, `CookieReviewValues`, `CookieDatabaseIndex`, `CookieScanLabels`, `OpenCookieCategory`.
**Browser crawl** (`cookieScanner.crawl`; the browser runs in the shared service `services/cookie-crawler`, never in the site):
| Export | Import from | What it does / when |
|---|---|---|
| `buildCookieCrawlGlobal(labels)` / `buildCookieCrawlEndpoints({ labels, options, plugin })` | `@intecion/ipal-kit` | The `cookie-crawl` global (latest result only) and the three crawl endpoints — the plugin wires them with `crawl`; call only to wire by hand. |
| `resolveCrawlConfig(crawlOptions, payload)` | `@intecion/ipal-kit` | Options → env (`IPAL_COOKIE_SCAN_URL`, `IPAL_COOKIE_SCAN_TOKEN`) → `serverURL` / `NEXT_PUBLIC_SERVER_URL` → `ResolvedCrawlConfig` (null = missing). |
| `parseCrawlResult(body)` | `@intecion/ipal-kit` | Validates the service's JSON → `CrawlResult` (`CrawlObservation`, `CrawlRequest`) or null; junk dropped. |
| `ingestCrawlResult({ payload, result, options, config, labels, plugin, req? })` | `@intecion/ipal-kit` | Applies a result: clears the previous flags, drafts for new names (same merge rules), `seenBeforeConsent` / `violation` / `violationDetail` → `CrawlIngestSummary`. |
| `finishCrawl({ payload, labels, result, summary?, siteUrl?, req? })` | `@intecion/ipal-kit` | Writes the `cookie-crawl` global (done / failed) and sends the e-mail warning when recipients are set. |
| `findCrawlViolations({ observations, requests, categoryOf, consentMode?, trackerHosts? })` | `@intecion/ipal-kit` | Pure rule: stored before consent and not `necessary` (unclassified counts), tracker requests before consent → `CrawlViolation[]`. |
| `DEFAULT_TRACKER_HOSTS` / `GOOGLE_TAG_HOSTS` | `@intecion/ipal-kit` | Request hosts that are violations before consent; Google's only with `consentMode: 'basic'`. |
| `sendCrawlWarning({ payload, labels, siteUrl, summary, to })` | `@intecion/ipal-kit` | The warning e-mail through `payload.sendEmail` (the project's mail adapter); never throws. |
| `bearerMatches(header, token)` | `@intecion/ipal-kit` | Constant-time `Authorization: Bearer` check. |
| `COOKIE_CRAWL_SLUG` / `COOKIE_CRAWL_PATH` / `COOKIE_CRAWL_RESULTS_PATH` | `@intecion/ipal-kit` | `'cookie-crawl'` / `'/ipal/cookie-crawl'` / `'/ipal/cookie-crawl/results'`. |
| `COOKIE_SCAN_URL_ENV` / `COOKIE_SCAN_TOKEN_ENV` | `@intecion/ipal-kit` | `'IPAL_COOKIE_SCAN_URL'` / `'IPAL_COOKIE_SCAN_TOKEN'`. |
**Types:** `CookieScannerOptions` (the option), `CookieDeclaration`, `CookieIntegration`, `CookieScanContext`, `CookieFinding`, `CookieFindingSource`, `CookieStorage`, `LocalizedText`, `CookieScanSummary`, `CookieReviewValues`, `CookieDatabaseIndex`, `CookieScanLabels`, `OpenCookieCategory`, `CookieObservation` (a name with `storage` / `domain` for `collectCookieFindings`), `CookieReviewEntryRef` (`applyCookieFindings` `entries`); crawl: `CookieCrawlOptions`, `ResolvedCrawlConfig`, `CrawlResult`, `CrawlObservation`, `CrawlRequest`, `CrawlViolation`, `CrawlIngestSummary`.
## Under construction (`construction`) — details: `node_modules/@intecion/ipal-kit/docs/construction.md`
+3
View File
@@ -393,6 +393,9 @@ ipalKit({
your hooks run after the plugin's; a function gets the plugin's global and returns the one to use.
- **Cookie list from the panel:** `ipalKit({ cookieScanner: true })` — opt-in, see
[cookie-scanner.md](./cookie-scanner.md) (off, overrides and building blocks there).
- **Pre-consent check in a real browser:** `cookieScanner: { crawl: true }` + the shared scanner service
— **Crawl site** in the panel, violations (non-necessary cookies or trackers before consent), dashboard
warning, optional e-mail ([cookie-scanner.md → Browser crawl](./cookie-scanner.md#browser-crawl)).
- **Extend:** `cookieMap` (your own cookies to delete), `ConsentScript` (scripts without Consent
Mode), `useConsentContext()` (your own UI: `state`, `acceptAll`, `rejectAll`, `savePreferences`,
`reopen`, `texts`), server-safe helpers (`parseConsent`, `readConsentRecord`, `CONSENT_COOKIE`,
+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.
+3
View File
@@ -74,6 +74,7 @@ URLs point at that domain. Outside production, `R2_PUBLIC_URL` alone → read-on
| `IPAL_IP_HEADER` | ⬜ (✅ prod) | forms | header with the real IP for the rate limit (`cf-connecting-ip`, `x-forwarded-for`); without it, a warning in the log |
| `NEXT_PUBLIC_TURNSTILE_SITE_KEY`, `TURNSTILE_SECRET_KEY` | ⬜ | forms | fallback when the Turnstile keys are not in Site Integrations |
| `INDEXNOW_KEY` | ⬜ | SEO | IndexNow key (takes precedence over the key from the panel) |
| `IPAL_COOKIE_SCAN_URL`, `IPAL_COOKIE_SCAN_TOKEN` | ⬜ (✅ prod with `ipalEnvRules({ cookieCrawl: true })`) | consent | cookie crawl (`cookieScanner.crawl`): the shared scanner service's URL and this site's token ([cookie-scanner.md](./cookie-scanner.md#browser-crawl)) |
| `IPAL_NOINDEX` | ⬜ | SEO | `1`/`true`/`yes` **on staging only** — the whole site is noindex (robots, meta, `X-Robots-Tag`) |
"✅ prod" = required by `ipalEnvRules({ storage: true })` / `({ ipHeader: true })` with
@@ -446,6 +447,8 @@ be attached. Options, in order of preference:
3. A reverse proxy/cache on the Coolify server (`media.klient.pl` → the bucket) — possible, more moving parts.
4. `*.r2.dev` — rate-limited, **dev/testing only**, never production.
**Cookie crawler (once per team, not per site):** `cookie-crawler.<team domain>` → `A`/`AAAA` to the Coolify server running the scanner service ([cookie-scanner.md](./cookie-scanner.md#scanner-service-on-coolify)). A site using `cookieScanner.crawl` needs no record of its own.
**No DNS records needed:** Turnstile (hostname list set in the Cloudflare panel on the widget, not in
DNS), IndexNow (key file served by the app), llms.txt, MCP, Markdown, sitemap.
+1
View File
@@ -61,6 +61,7 @@ use).
ipalEnvRules({
storage?: boolean | { requirePublicUrl?: boolean }, // R2_* (R2_BUCKET, R2_ACCESS_KEY_ID, R2_SECRET_ACCESS_KEY, R2_ENDPOINT; R2_PUBLIC_URL optional)
emailGraph?: boolean, // GRAPH_* (GRAPH_TENANT_ID, GRAPH_CLIENT_ID, GRAPH_CLIENT_SECRET, GRAPH_SENDER — e-mail)
cookieCrawl?: boolean, // IPAL_COOKIE_SCAN_URL (url), IPAL_COOKIE_SCAN_TOKEN (≥ 16 chars) — required in production; cookieScanner.crawl (cookie-scanner.md)
ipHeader?: boolean, // IPAL_IP_HEADER — required in production, optional outside it (header name [a-z0-9-])
turnstile?: boolean | { siteKeyVar?: string; secretVar?: string }, // NEXT_PUBLIC_TURNSTILE_SITE_KEY, TURNSTILE_SECRET_KEY
serverUrlVar?: string, // default 'NEXT_PUBLIC_SERVER_URL'
+3
View File
@@ -0,0 +1,3 @@
node_modules
npm-debug.log
*.md
+17
View File
@@ -0,0 +1,17 @@
# ipal cookie crawler — one shared service for all sites (docs/cookie-scanner.md → Coolify).
# The Playwright image ships Chromium and its system libraries; the npm package
# version must match the image tag.
FROM mcr.microsoft.com/playwright:v1.64.0-noble
WORKDIR /app
ENV NODE_ENV=production
COPY package.json package-lock.json ./
RUN npm ci --omit=dev --no-audit --no-fund
COPY lib.mjs crawl.mjs server.mjs cli.mjs ./
# The image's non-root user; Chromium runs sandboxed as this user.
USER pwuser
EXPOSE 3000
HEALTHCHECK --interval=30s --timeout=5s --start-period=10s \
CMD node -e "fetch('http://127.0.0.1:'+(process.env.PORT||3000)+'/health').then(r=>process.exit(r.ok?0:1)).catch(()=>process.exit(1))"
CMD ["node", "server.mjs"]
+11
View File
@@ -0,0 +1,11 @@
# ipal cookie crawler
The browser half of ipal-kit's cookie scanner: one shared service that crawls a site twice (no
consent / after "Accept all") and posts cookies, storage keys and third-party hosts back to the
site. Sites never run a browser.
Setup, Coolify deploy, env and network notes: `docs/cookie-scanner.md` → "Browser crawl" in the
ipal-kit repository (also shipped in `node_modules/@intecion/ipal-kit/docs/`).
- `node server.mjs` — the service (`IPAL_CRAWLER_SITES="acme.pl=TOKEN"`).
- `node cli.mjs https://acme.pl --pages 10` — the same crawl from a laptop or CI, JSON on stdout.
+31
View File
@@ -0,0 +1,31 @@
#!/usr/bin/env node
// Same crawl as the service, from a laptop or CI — prints the result as JSON.
// node cli.mjs <siteUrl> [--pages 20] [--accept '[data-ipal="accept"]'] [--wait 3000]
// Exit code: 0 = nothing stored before consent but the consent cookie, 1 = something else was, 2 = setup problem.
// The verdict per cookie needs the site's categories: the panel's "Crawl site" does that.
import { crawlSite } from './crawl.mjs'
const args = process.argv.slice(2)
const opt = (name, def) => (args.includes(`--${name}`) ? args[args.indexOf(`--${name}`) + 1] : def)
if (!args[0] || args[0].startsWith('--')) {
console.error('Usage: node cli.mjs <siteUrl> [--pages N] [--accept selector] [--wait ms]')
process.exit(2)
}
let chromium
try {
;({ chromium } = await import('playwright'))
} catch {
console.error('Playwright not found: npm install (in services/cookie-crawler) && npx playwright install chromium')
process.exit(2)
}
const result = await crawlSite({
acceptSelector: opt('accept', '[data-ipal="accept"]'),
chromium,
maxPages: Number(opt('pages', 20)),
siteUrl: args[0],
waitMs: Number(opt('wait', 3000)),
})
console.log(JSON.stringify(result, null, 2))
const early = result.observations.filter((o) => o.before && o.name !== 'cookie-consent')
if (early.length) {console.error(`Stored before consent: ${early.map((o) => o.name).join(', ')} — classify them in the panel.`)}
process.exit(early.length ? 1 : 0)
+76
View File
@@ -0,0 +1,76 @@
// The crawl itself: two fresh browser profiles over the same pages — one with
// no consent decision, one after clicking "Accept all". Records cookies,
// localStorage / sessionStorage keys and third-party request hosts per page.
import { bareHost, discoverPages, isFirstParty, mergeRuns } from './lib.mjs'
async function run(browser, pages, { accept, acceptSelector, pageTimeoutMs, siteHost, waitMs }) {
const context = await browser.newContext()
const result = { accepted: false, cookies: [], requests: [], storage: [] }
let current = '/'
const seen = new Set()
const once = (key) => (seen.has(key) ? false : (seen.add(key), true))
context.on('request', (request) => {
let host
try {
host = new URL(request.url()).hostname.toLowerCase()
} catch {
return
}
if (!host || isFirstParty(host, siteHost) || !once(`r:${host}:${current}`)) {return}
result.requests.push({ host, page: current })
})
try {
const page = await context.newPage()
await page.setExtraHTTPHeaders({ 'X-Ipal-Cookie-Crawler': '1' })
for (const [i, url] of pages.entries()) {
current = new URL(url).pathname
await page.goto(url, { timeout: pageTimeoutMs, waitUntil: 'load' }).catch(() => {})
if (accept && i === 0) {
const button = page.locator(acceptSelector).first()
if (await button.count().catch(() => 0)) {
await button.click({ timeout: 5_000 }).then(() => (result.accepted = true)).catch(() => {})
}
}
await page.waitForTimeout(waitMs)
const keys = await page
.evaluate(() => ({ localStorage: Object.keys(localStorage), sessionStorage: Object.keys(sessionStorage) }))
.catch(() => ({ localStorage: [], sessionStorage: [] }))
for (const [storage, names] of Object.entries(keys)) {
for (const name of names) {if (once(`s:${storage}:${name}:${current}`)) {result.storage.push({ name, page: current, storage })}}
}
for (const c of await context.cookies()) {
if (once(`c:${c.name}:${current}`)) {result.cookies.push({ domain: c.domain, name: c.name, page: current })}
}
}
} finally {
await context.close()
}
return result
}
/**
* Crawls a site and returns the wire format (without jobId):
* `{ ok: true, pages, observations, requests, accepted }`. `chromium` is
* Playwright's (injected — the caller decides how it is installed).
*/
export async function crawlSite({
acceptSelector = '[data-ipal="accept"]',
chromium,
fetchImpl = fetch,
maxPages = 20,
pageTimeoutMs = 30_000,
siteUrl,
waitMs = 3_000,
}) {
const pages = await discoverPages(siteUrl, Math.min(100, Math.max(0, maxPages)), fetchImpl)
const siteHost = bareHost(siteUrl)
const browser = await chromium.launch()
try {
const options = { acceptSelector, pageTimeoutMs, siteHost, waitMs }
const before = await run(browser, pages, { ...options, accept: false })
const after = await run(browser, pages, { ...options, accept: true })
return { accepted: after.accepted, ok: true, pages: pages.map((p) => new URL(p).pathname), ...mergeRuns(before, after) }
} finally {
await browser.close()
}
}
+107
View File
@@ -0,0 +1,107 @@
// Pure helpers of the ipal cookie crawler (no browser, no network) — tested in
// test/cookieCrawler.test.ts. Wire format: src/modules/consent/scanner/crawl/result.ts.
import { createHash, timingSafeEqual } from 'node:crypto'
/** `acme.pl=TOKEN,shop.example.com=TOKEN2` → [{ host, token }]. Tokens shorter than 16 chars are refused. */
export function parseSites(value = '') {
const sites = []
for (const pair of value.split(/[,\n]/)) {
const i = pair.indexOf('=')
if (i < 1) {continue}
const host = pair.slice(0, i).trim().toLowerCase().replace(/^www\./, '')
const token = pair.slice(i + 1).trim()
if (host && token.length >= 16) {sites.push({ host, token })}
}
return sites
}
/** Host without `www.`, lower case. */
export const bareHost = (url) => new URL(url).hostname.toLowerCase().replace(/^www\./, '')
function sameToken(a, b) {
const x = createHash('sha256').update(String(a)).digest()
const y = createHash('sha256').update(String(b)).digest()
return timingSafeEqual(x, y)
}
/**
* Checks a crawl request: the site must be listed, the bearer token must be that
* site's token, the callback must be on the same origin as the site, and only
* https (http only when allowHttp — local tests). Returns an error string or null.
*/
export function checkCrawlRequest({ allowHttp = false, authorization, body, sites }) {
if (!body || typeof body !== 'object') {return 'bad_request'}
const { callbackUrl, jobId, siteUrl } = body
if (typeof jobId !== 'string' || !/^[0-9a-f]{16,64}$/.test(jobId)) {return 'bad_job_id'}
let site, callback
try {
site = new URL(siteUrl)
callback = new URL(callbackUrl)
} catch {
return 'bad_url'
}
const protocols = allowHttp ? ['https:', 'http:'] : ['https:']
if (!protocols.includes(site.protocol)) {return 'https_only'}
if (callback.origin !== site.origin) {return 'callback_not_on_site'}
const entry = sites.find((s) => s.host === bareHost(site.href))
if (!entry) {return 'site_not_allowed'}
const token = typeof authorization === 'string' && authorization.startsWith('Bearer ') ? authorization.slice(7).trim() : ''
if (!token || !sameToken(token, entry.token)) {return 'unauthorized'}
return null
}
/**
* Pages to visit: the site URL, then up to `max` same-origin URLs from
* /sitemap.xml (one level of sitemap index followed). Never throws.
*/
export async function discoverPages(siteUrl, max, fetchImpl = fetch) {
const origin = new URL(siteUrl).origin
const pages = [new URL(siteUrl).href]
const text = async (url) => {
try {
const res = await fetchImpl(url, { signal: AbortSignal.timeout(15_000) })
return res.ok ? await res.text() : ''
} catch {
return ''
}
}
const locs = (xml) => [...xml.matchAll(/<loc>\s*([^<\s]+)\s*<\/loc>/g)].map((m) => m[1].replace(/&amp;/g, '&'))
let xml = await text(`${origin}/sitemap.xml`)
if (/<sitemapindex/i.test(xml)) {
const children = locs(xml).filter((u) => u.startsWith(origin)).slice(0, 5)
xml = (await Promise.all(children.map(text))).join('\n')
}
for (const url of locs(xml)) {
if (pages.length > max) {break}
if (url.startsWith(`${origin}/`) && !pages.includes(url)) {pages.push(url)}
}
return pages
}
/** True for the site's own host and its subdomains. */
export function isFirstParty(host, siteHost) {
const h = host.toLowerCase().replace(/^www\./, '')
return h === siteHost || h.endsWith(`.${siteHost}`)
}
/**
* Two runs (no consent / accept all) → the wire format's observations and
* requests. A run: { cookies: [{ name, domain, page }], storage: [{ name, storage, page }],
* requests: [{ host, page }] } — first sighting per page.
*/
export function mergeRuns(before, after) {
const obs = new Map()
const reqs = new Map()
const add = (map, key, base, flag, page) => {
const entry = map.get(key) ?? { ...base, after: false, before: false, pages: [] }
entry[flag] = true
if (page && entry.pages.length < 5 && !entry.pages.includes(page)) {entry.pages.push(page)}
map.set(key, entry)
}
for (const [run, flag] of [[before, 'before'], [after, 'after']]) {
for (const c of run.cookies) {add(obs, `cookie:${c.name}`, { domain: c.domain.replace(/^\./, ''), name: c.name, storage: 'cookie' }, flag, c.page)}
for (const s of run.storage) {add(obs, `${s.storage}:${s.name}`, { name: s.name, storage: s.storage }, flag, s.page)}
for (const r of run.requests) {add(reqs, r.host, { host: r.host }, flag, r.page)}
}
return { observations: [...obs.values()], requests: [...reqs.values()] }
}
+46
View File
@@ -0,0 +1,46 @@
{
"name": "@intecion/ipal-cookie-crawler",
"version": "1.0.0",
"lockfileVersion": 3,
"requires": true,
"packages": {
"": {
"name": "@intecion/ipal-cookie-crawler",
"version": "1.0.0",
"license": "MIT",
"dependencies": {
"playwright": "1.64.0"
},
"engines": {
"node": ">=20"
}
},
"node_modules/playwright": {
"version": "1.64.0",
"resolved": "https://registry.npmjs.org/playwright/-/playwright-1.64.0.tgz",
"integrity": "sha512-kVzTnYFYEyQ9RGzBjNCd2+yEqWmVbxl3AHPynv3qQ6JTjv4a+kwRcnqQwIpuP3NnrnIrE/Q6wWAIAvMfIE2/Yg==",
"license": "Apache-2.0",
"dependencies": {
"playwright-core": "1.64.0"
},
"bin": {
"playwright": "cli.js"
},
"engines": {
"node": ">=20"
}
},
"node_modules/playwright-core": {
"version": "1.64.0",
"resolved": "https://registry.npmjs.org/playwright-core/-/playwright-core-1.64.0.tgz",
"integrity": "sha512-T9r+MZkTECl2+oUcZ26YgZzTrYidTsIhYYkJix+6iDOymOb1FB2RLLSOxRGnZGv5DStt+aduIVbt+E8WygXYpg==",
"license": "Apache-2.0",
"bin": {
"playwright-core": "cli.js"
},
"engines": {
"node": ">=20"
}
}
}
}
+18
View File
@@ -0,0 +1,18 @@
{
"name": "@intecion/ipal-cookie-crawler",
"version": "1.0.0",
"private": true,
"description": "Headless-browser cookie crawler for ipal-kit sites (Cookie review → Crawl site). Runs as one shared service, never inside a site.",
"license": "MIT",
"type": "module",
"scripts": {
"crawl": "node cli.mjs",
"start": "node server.mjs"
},
"dependencies": {
"playwright": "1.64.0"
},
"engines": {
"node": ">=20"
}
}
+163
View File
@@ -0,0 +1,163 @@
// ipal cookie crawler — HTTP service (deploy: docs/cookie-scanner.md → "Scanner service on Coolify").
//
// GET /health → { ok, running, queued }
// POST /crawl → Authorization: Bearer <the site's token>
// { jobId, siteUrl, callbackUrl, maxPages?, acceptSelector? } → 202 { ok, queued }
// The crawl runs in the background; the result is POSTed to callbackUrl with the
// same bearer token.
//
// Env: IPAL_CRAWLER_SITES="acme.pl=TOKEN,shop.example.com=TOKEN2" (required), PORT (3000),
// CRAWLER_CONCURRENCY (1), CRAWLER_QUEUE_MAX (20), CRAWLER_JOB_TIMEOUT_MS (600000),
// CRAWLER_WAIT_MS (3000), CRAWLER_ALLOW_HTTP (unset; "1" only for local tests).
import { createServer } from 'node:http'
import { pathToFileURL } from 'node:url'
import { checkCrawlRequest, parseSites } from './lib.mjs'
const MAX_BODY = 64 * 1024
function readJson(req) {
return new Promise((resolve) => {
let size = 0
const chunks = []
req.on('data', (c) => {
size += c.length
if (size > MAX_BODY) {req.destroy()}
else {chunks.push(c)}
})
req.on('end', () => {
try {
resolve(JSON.parse(Buffer.concat(chunks).toString('utf8')))
} catch {
resolve(null)
}
})
req.on('error', () => resolve(null))
})
}
const send = (res, status, body) => {
res.writeHead(status, { 'Content-Type': 'application/json' })
res.end(JSON.stringify(body))
}
/** POST the result to the site; 3 tries (0 s, 5 s, 30 s). */
async function deliver({ callbackUrl, fetchImpl, log, result, token }, delays = [0, 5_000, 30_000]) {
for (const delay of delays) {
if (delay) {await new Promise((r) => setTimeout(r, delay))}
try {
const res = await fetchImpl(callbackUrl, {
body: JSON.stringify(result),
headers: { Authorization: `Bearer ${token}`, 'Content-Type': 'application/json' },
method: 'POST',
signal: AbortSignal.timeout(60_000),
})
if (res.ok || (res.status >= 400 && res.status < 500)) {
log(`result for ${result.jobId} → ${callbackUrl}: HTTP ${res.status}`)
return res.status
}
} catch (err) {
log(`result for ${result.jobId} → ${callbackUrl} failed: ${err?.message ?? err}`)
}
}
return 0
}
/**
* The service as a function of its parts, so tests can inject `crawl` and
* `fetchImpl`. `crawl(job) → wire result without jobId`.
*/
export function createCrawlerServer({
allowHttp = false,
concurrency = 1,
crawl,
deliveryDelays,
fetchImpl = fetch,
jobTimeoutMs = 600_000,
log = (m) => console.log(`[crawler] ${m}`),
queueMax = 20,
sites,
}) {
const queue = []
let running = 0
const idle = []
const pump = () => {
while (running < concurrency && queue.length) {
const job = queue.shift()
running++
void (async () => {
let result
let timer
try {
result = await Promise.race([
crawl(job),
new Promise((_, reject) => {
timer = setTimeout(() => reject(new Error(`crawl took longer than ${jobTimeoutMs} ms`)), jobTimeoutMs)
}),
])
result = { ...result, jobId: job.jobId }
} catch (err) {
result = { error: String(err?.message ?? err).slice(0, 300), jobId: job.jobId, ok: false }
} finally {
clearTimeout(timer)
}
log(`crawled ${job.siteUrl} (${job.jobId}): ${result.ok ? `${result.pages.length} pages` : result.error}`)
await deliver({ callbackUrl: job.callbackUrl, fetchImpl, log, result, token: job.token }, deliveryDelays)
running--
if (!running && !queue.length) {idle.splice(0).forEach((r) => r())}
pump()
})()
}
}
const server = createServer(async (req, res) => {
const url = new URL(req.url ?? '/', 'http://x')
if (req.method === 'GET' && url.pathname === '/health') {return send(res, 200, { ok: true, queued: queue.length, running })}
if (req.method !== 'POST' || url.pathname !== '/crawl') {return send(res, 404, { ok: false })}
const body = await readJson(req)
const error = checkCrawlRequest({ allowHttp, authorization: req.headers.authorization, body, sites })
if (error) {return send(res, error === 'unauthorized' || error === 'site_not_allowed' ? 401 : 400, { error, ok: false })}
if (queue.length >= queueMax) {return send(res, 429, { error: 'queue_full', ok: false })}
const token = req.headers.authorization.slice(7).trim()
queue.push({
acceptSelector: typeof body.acceptSelector === 'string' ? body.acceptSelector.slice(0, 200) : undefined,
callbackUrl: body.callbackUrl,
jobId: body.jobId,
maxPages: Number.isFinite(body.maxPages) ? body.maxPages : 20,
siteUrl: body.siteUrl,
token,
})
send(res, 202, { ok: true, queued: queue.length + running })
pump()
})
/** Resolves when nothing is queued or running (tests). */
server.whenIdle = () => (running || queue.length ? new Promise((r) => idle.push(r)) : Promise.resolve())
return server
}
// Run directly: `node server.mjs`
if (import.meta.url === pathToFileURL(process.argv[1] ?? '').href) {
const sites = parseSites(process.env.IPAL_CRAWLER_SITES)
if (!sites.length) {
console.error('[crawler] IPAL_CRAWLER_SITES is empty — set "host=token" pairs (token ≥ 16 chars).')
process.exit(1)
}
const { chromium } = await import('playwright')
const { crawlSite } = await import('./crawl.mjs')
const waitMs = Number(process.env.CRAWLER_WAIT_MS) || 3_000
const server = createCrawlerServer({
allowHttp: process.env.CRAWLER_ALLOW_HTTP === '1',
concurrency: Number(process.env.CRAWLER_CONCURRENCY) || 1,
crawl: (job) => crawlSite({ acceptSelector: job.acceptSelector, chromium, maxPages: job.maxPages, siteUrl: job.siteUrl, waitMs }),
jobTimeoutMs: Number(process.env.CRAWLER_JOB_TIMEOUT_MS) || 600_000,
queueMax: Number(process.env.CRAWLER_QUEUE_MAX) || 20,
sites,
})
const port = Number(process.env.PORT) || 3000
server.listen(port, () => console.log(`[crawler] listening on :${port} for ${sites.map((s) => s.host).join(', ')}`))
const stop = () => server.close(() => process.exit(0))
process.on('SIGTERM', stop)
process.on('SIGINT', stop)
}
+1
View File
@@ -10,6 +10,7 @@ export { TestEmailButton } from '../globals/SiteIntegrations/components/TestEmai
export { RowLabel } from '../modules/admin-ui/RowLabelComponent.js'
export { AdminIcon, AdminLogo, IntecionCredit } from '../modules/branding/index.js'
export { CookieScanButton } from '../modules/consent/scanner/CookieScanButton.js'
export { CookieCrawlAlert } from '../modules/consent/scanner/crawl/CookieCrawlAlert.js'
export { IntegrationAlerts } from '../modules/integrations/IntegrationAlerts.js'
export { IntegrationStatusBanner } from '../modules/integrations/IntegrationStatusBanner.js'
export { MetaDescriptionCheck } from '../modules/seo/MetaDescriptionCheck.js'
+25
View File
@@ -54,39 +54,64 @@ export type { ConsentCategory, ConsentLogOptions, ConsentState, ConsentTexts, Co
export {
addToCookieList,
applyCookieFindings,
bearerMatches,
buildCookieCrawlEndpoints,
buildCookieCrawlGlobal,
buildCookieReviewCollection,
buildCookieScanEndpoints,
collectCookieFindings,
COOKIE_CRAWL_PATH,
COOKIE_CRAWL_RESULTS_PATH,
COOKIE_CRAWL_SLUG,
COOKIE_REVIEW_SLUG,
COOKIE_SCAN_LABELS,
COOKIE_SCAN_PATH,
COOKIE_SCAN_TOKEN_ENV,
COOKIE_SCAN_URL_ENV,
cookieNameMatches,
cookieScanContext,
DEFAULT_COOKIE_INTEGRATIONS,
DEFAULT_DATABASE_CATEGORIES,
DEFAULT_TRACKER_HOSTS,
findCrawlViolations,
finishCrawl,
GOOGLE_TAG_HOSTS,
indexCookieDatabase,
ingestCrawlResult,
loadCookieDatabase,
lookupCookie,
mergeCookieReview,
mergeCookieScanLabels,
parseCookieNames,
parseCrawlResult,
resolveCrawlConfig,
runCookieScan,
sendCrawlWarning,
suggestionFor,
} from './modules/consent/scanner/index.js'
export type {
CookieCrawlOptions,
CookieDatabaseIndex,
CookieDeclaration,
CookieFinding,
CookieFindingSource,
CookieIntegration,
CookieObservation,
CookieReviewEntryRef,
CookieReviewValues,
CookieScanContext,
CookieScanLabels,
CookieScannerOptions,
CookieScanSummary,
CookieStorage,
CrawlIngestSummary,
CrawlObservation,
CrawlRequest,
CrawlResult,
CrawlViolation,
LocalizedText,
OpenCookieCategory,
ResolvedCrawlConfig,
} from './modules/consent/scanner/index.js'
export { constructionNoticeHref, isPathAllowed, isPathVisibleIn } from './modules/construction/logic.js'
export type { ConstructionMode } from './modules/construction/types.js'
@@ -9,19 +9,34 @@ 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. Labels in the admin language
* (`labels` from the collection config, English fallback).
* 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({ labels = COOKIE_SCAN_LABELS }: { labels?: Record<string, CookieScanLabels> }) {
export function CookieScanButton({ crawl = false, labels = COOKIE_SCAN_LABELS }: { crawl?: boolean; labels?: Record<string, CookieScanLabels> }) {
const { i18n } = useTranslation()
const { config } = useConfig()
const router = useRouter()
@@ -30,6 +45,45 @@ export function CookieScanButton({ labels = COOKIE_SCAN_LABELS }: { labels?: Rec
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' })
@@ -93,6 +147,30 @@ export function CookieScanButton({ labels = COOKIE_SCAN_LABELS }: { labels?: Rec
<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
className="btn btn--style-secondary"
disabled={!crawlState?.configured || crawlState.status === 'running' || crawlStarting}
onClick={startCrawl}
style={{ margin: 0 }}
type="button"
>
{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}
{crawlState?.configured && crawlState.status === 'failed' ? fill(t.crawlFailed, { error: crawlState.error ?? '' }) : null}
</span>
</div>
</div>
) : null}
</div>
)
}
+20 -3
View File
@@ -1,4 +1,4 @@
import type { CollectionAfterChangeHook, CollectionBeforeChangeHook, CollectionConfig } from 'payload'
import type { CollectionAfterChangeHook, CollectionBeforeChangeHook, CollectionConfig, Field } from 'payload'
import type { CookieReviewValues } from './merge.js'
import type { CookieScannerOptions } from './types.js'
@@ -64,6 +64,22 @@ function buildSyncHook(): CollectionAfterChangeHook {
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: {
@@ -75,9 +91,9 @@ export function buildCookieReviewCollection(options: CookieScannerOptions = {}):
},
admin: {
components: {
beforeListTable: [{ clientProps: { labels }, path: '@intecion/ipal-kit/admin#CookieScanButton' }],
beforeListTable: [{ clientProps: { crawl, labels }, path: '@intecion/ipal-kit/admin#CookieScanButton' }],
},
defaultColumns: ['name', 'vendor', 'category', 'status', 'source', 'listed'],
defaultColumns: ['name', 'vendor', 'category', 'status', 'source', 'listed', ...(crawl ? ['violation'] : [])],
description: L('collectionDescription'),
group: 'Settings',
listSearchableFields: ['name', 'vendor'],
@@ -163,6 +179,7 @@ export function buildCookieReviewCollection(options: CookieScannerOptions = {}):
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.
@@ -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: 'inline-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
}
+20
View File
@@ -2,6 +2,24 @@
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'
@@ -9,8 +27,10 @@ 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,
+99
View File
@@ -5,14 +5,39 @@
*/
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
@@ -27,6 +52,8 @@ export type CookieScanLabels = {
namesHint: string
namesLabel: string
necessary: string
notifyEmails: string
notifyEmailsDescription: string
plural: string
project: string
purpose: string
@@ -38,32 +65,63 @@ export type CookieScanLabels = {
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',
@@ -77,6 +135,8 @@ export const COOKIE_SCAN_LABELS: Record<'en' | 'pl', CookieScanLabels> = {
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',
@@ -87,30 +147,61 @@ export const COOKIE_SCAN_LABELS: Record<'en' | 'pl', CookieScanLabels> = {
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',
@@ -124,6 +215,8 @@ export const COOKIE_SCAN_LABELS: Record<'en' | 'pl', CookieScanLabels> = {
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',
@@ -134,17 +227,23 @@ export const COOKIE_SCAN_LABELS: Record<'en' | 'pl', CookieScanLabels> = {
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',
},
}
+37 -10
View File
@@ -68,11 +68,16 @@ export async function enabledCookieIntegrations(
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,
@@ -87,13 +92,15 @@ export async function collectCookieFindings({
databaseCategories?: CookieScannerOptions['databaseCategories']
declarations?: CookieDeclaration[]
integrations?: CookieIntegration[]
names?: string[]
}): Promise<{ enabled: CookieIntegration[]; findings: CookieFinding[] }> {
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) {
@@ -105,19 +112,32 @@ export async function collectCookieFindings({
...integrations.flatMap((i) => declarationsOf(i, ctx).map((d) => ({ d, detail: i.label, source: 'integration' as const }))),
]
const index = database ? await loadCookieDatabase() : null
for (const name of names) {
if ([...found.values()].some((f) => f.storage === 'cookie' && cookieNameMatches(f.name, name))) {continue}
const declared = known.find((k) => (k.d.storage ?? 'cookie') === 'cookie' && cookieNameMatches(k.d.name, name))
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) {
add(fromDeclaration(declared.d, declared.source, declared.detail))
matches.set(seenKey, add(fromDeclaration(declared.d, declared.source, declared.detail)))
continue
}
const fromDb = index ? lookupCookie(index, name, databaseCategories) : null
add(fromDb ?? { name, source: 'unknown', storage: 'cookie' })
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()] }
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
@@ -149,11 +169,14 @@ async function listedNames(payload: BasePayload, req?: PayloadRequest): Promise<
*/
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
@@ -161,7 +184,7 @@ export async function applyCookieFindings({
const { locales } = localesOf(payload)
const codes = locales.filter((l): l is string => Boolean(l))
const listed = await listedNames(payload, req)
const summary: CookieScanSummary = { created: 0, unchanged: 0, unknown: 0, updated: 0 }
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 }
@@ -201,7 +224,11 @@ export async function applyCookieFindings({
await payload.update({ ...common, id, data: data as never, locale: locale as never })
}
}
if (!existing) {summary.created++}
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++}
}
+38 -1
View File
@@ -1,5 +1,6 @@
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'
@@ -77,6 +78,8 @@ export type OpenCookieCategory = 'Analytics' | 'Functional' | 'Marketing' | 'Nec
/** 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
@@ -88,10 +91,16 @@ export type CookieScanSummary = {
* action. Every key is optional.
*/
export type CookieScannerOptions = {
/** Who may run a scan (GET/POST /api/ipal/cookie-scan). Default: `editor` and up. */
/** 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
/**
@@ -117,3 +126,31 @@ export type CookieScannerOptions = {
*/
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(
+29 -4
View File
@@ -11,7 +11,10 @@ import { buildSiteSettings } from './globals/SiteSettings/index.js'
import { adminOnly, adminOrSelf, injectRoles } from './modules/access/index.js'
import { buildConsentLogCollection, buildConsentLogEndpoint } from './modules/consent/consentLog.js'
import { buildCookieReviewCollection } from './modules/consent/scanner/collection.js'
import { buildCookieCrawlEndpoints } from './modules/consent/scanner/crawl/endpoints.js'
import { buildCookieCrawlGlobal } from './modules/consent/scanner/crawl/global.js'
import { buildCookieScanEndpoints } from './modules/consent/scanner/endpoint.js'
import { mergeCookieScanLabels } from './modules/consent/scanner/labels.js'
import { buildConstructionFields } from './modules/construction/fields.js'
import { buildArchiveFields } from './modules/content/index.js'
import { testEmailEndpoint } from './modules/email/test/testEmailEndpoint.js'
@@ -317,10 +320,32 @@ export const ipalKit = (options: IpalOptions): Plugin => {
if (options.cookieScanner) {
const scannerOptions = options.cookieScanner === true ? {} : options.cookieScanner
config.collections = [...(config.collections ?? []), applyCollectionOverride(buildCookieReviewCollection(scannerOptions), scannerOptions.collectionOverrides)]
config.endpoints = [
...(config.endpoints ?? []),
...buildCookieScanEndpoints(scannerOptions, { localeCount: options.i18n.locales.length, stats: Boolean(options.stats) }),
]
const scanPlugin = { localeCount: options.i18n.locales.length, stats: Boolean(options.stats) }
config.endpoints = [...(config.endpoints ?? []), ...buildCookieScanEndpoints(scannerOptions, scanPlugin)]
// Browser crawl through the scanner service (opt-in): latest-result global, endpoints, dashboard warning.
if (scannerOptions.crawl) {
const crawl = scannerOptions.crawl === true ? {} : scannerOptions.crawl
const labels = mergeCookieScanLabels(scannerOptions.labels)
const crawlGlobal = buildCookieCrawlGlobal(labels)
const override = crawl.globalOverride
config.globals = [
...(config.globals ?? []),
override ? applyGlobalOverrides([crawlGlobal], { [crawlGlobal.slug]: override } as never)[0] : crawlGlobal,
]
config.endpoints = [...(config.endpoints ?? []), ...buildCookieCrawlEndpoints({ labels, options: scannerOptions, plugin: scanPlugin })]
if (crawl.dashboard !== false) {
config.admin = {
...(config.admin ?? {}),
components: {
...(config.admin?.components ?? {}),
beforeDashboard: [
...(config.admin?.components?.beforeDashboard ?? []),
{ path: '@intecion/ipal-kit/admin#CookieCrawlAlert', serverProps: { adminRoute: options.adminRoute ?? '/admin', labels } },
],
},
}
}
}
}
// --- built-in statistics: cookieless visits + consented history (opt-in) ---
+1
View File
@@ -47,6 +47,7 @@ describe('under construction — Site Settings → createPageRoute', () => {
plugins: [ipalKit({ access: { authCollection: 'users' }, i18n, pages: { slug: 'pages' }, twoFactor: false })],
secret: 'construction-test-secret',
telemetry: false,
typescript: { autoGenerate: false }, // no orphaned `payload generate:types` child
})
payload = await getPayload({ config: configPromise })
}, 60_000)
+171
View File
@@ -0,0 +1,171 @@
/**
* Phase 2 end to end: a REAL Payload (SQLite, pl + en) and a REAL Chromium crawl
* (services/cookie-crawler) of a small local test site. Only the HTTP hop
* between site and service is short-circuited (that hop: cookieCrawler.test.ts).
*/
import type { Server } from 'node:http'
import type { AddressInfo } from 'node:net'
import type { Payload } from 'payload'
import { sqliteAdapter } from '@payloadcms/db-sqlite'
import { lexicalEditor } from '@payloadcms/richtext-lexical'
import { chromium } from '@playwright/test'
import { createServer } from 'node:http'
import os from 'os'
import path from 'path'
import { buildConfig, getPayload } from 'payload'
import { afterAll, beforeAll, describe, expect, test, vi } from 'vitest'
import { crawlSite } from '../services/cookie-crawler/crawl.mjs'
import { CookieCrawlAlert } from '../src/modules/consent/scanner/crawl/CookieCrawlAlert.js'
import { buildCookieCrawlEndpoints } from '../src/modules/consent/scanner/crawl/endpoints.js'
import { COOKIE_SCAN_LABELS } from '../src/modules/consent/scanner/labels.js'
import { ipalKit } from '../src/plugin.js'
vi.mock('server-only', () => ({}))
type CrawlDoc = { status: string; summary: { pages: number; violations: number }; violations: { name: string }[] }
const TOKEN = 't'.repeat(32)
const editor = { collection: 'users', email: '[email protected]', roles: ['editor'] }
// The test site: `sid` (declared necessary) and `_fbp` + a tracker request before consent;
// `_ga` and a localStorage key only after "Accept all".
const PAGE = (body: string) => `<!doctype html><html><body>${body}</body></html>`
const site: Server = createServer((req, res) => {
if (req.url === '/sitemap.xml') {
res.writeHead(200, { 'Content-Type': 'application/xml' })
res.end(`<urlset><url><loc>${siteUrl}/about</loc></url></urlset>`)
return
}
res.writeHead(200, { 'Content-Type': 'text/html', 'Set-Cookie': 'sid=1; Path=/' })
res.end(
req.url === '/about'
? PAGE('<p>About</p>')
: PAGE(`<script>document.cookie='_fbp=fb.1; path=/'</script>
<img src="http://tracker.invalid/p.gif" alt="">
<button data-ipal="accept" onclick="document.cookie='_ga=GA1; path=/';localStorage.setItem('ipal-theme','dark')">Accept all</button>`),
)
})
let siteUrl = ''
let payload: Payload
const crawlOptions = () => ({ serviceUrl: 'http://crawler.test', siteUrl, token: TOKEN, trackerHosts: (d: string[]) => [...d, 'tracker.invalid'] })
const declarations = [{ name: 'sid', category: 'necessary' as const, purpose: 'Session', retention: 'Session', setBeforeConsent: true, vendor: 'This site' }]
beforeAll(async () => {
await new Promise<void>((r) => site.listen(0, '127.0.0.1', r))
siteUrl = `http://127.0.0.1:${(site.address() as AddressInfo).port}`
payload = await getPayload({
config: buildConfig({
collections: [
{ slug: 'users', auth: true, fields: [] },
{ slug: 'media', fields: [], upload: { staticDir: path.join(os.tmpdir(), 'ipal-test-media') } },
],
db: sqliteAdapter({ client: { url: 'file::memory:' }, push: true }),
editor: lexicalEditor(),
plugins: [
ipalKit({
access: { authCollection: 'users' },
cookieScanner: { crawl: crawlOptions(), declarations },
i18n: { defaultLocale: 'pl', locales: [{ code: 'pl', label: 'Polski' }, { code: 'en', label: 'English' }] },
twoFactor: false,
}),
],
secret: 'cookie-crawl-test-secret',
telemetry: false,
typescript: { autoGenerate: false },
}),
})
}, 60_000)
afterAll(async () => {
await payload?.destroy()
await new Promise<void>((r) => site.close(() => r()))
})
describe('cookie crawl — panel button → service → results', () => {
const started: Record<string, unknown>[] = []
const fetchImpl = vi.fn(async (_url: Request | string | URL, init?: RequestInit) => {
started.push(JSON.parse(init?.body as string))
return new Response('{}', { status: 202 })
}) as unknown as typeof fetch
const endpoints = () =>
buildCookieCrawlEndpoints({ fetchImpl, labels: COOKIE_SCAN_LABELS, options: { crawl: crawlOptions(), declarations }, plugin: { localeCount: 2, stats: false } })
const call = (i: number, { body = {}, token, user = null }: { body?: unknown; token?: string; user?: unknown } = {}) =>
endpoints()[i].handler({
headers: new Headers(token ? { authorization: `Bearer ${token}` } : {}),
json: async () => body,
payload,
user,
} as never) as Promise<Response>
const review = async (name: string, storage = 'cookie') =>
(await payload.find({ collection: 'cookie-review' as never, depth: 0, where: { key: { equals: `${storage}:${name}` } } })).docs[0] as unknown as Record<string, unknown>
test('visitors cannot start a crawl; an editor can; a second start while running is refused', async () => {
expect((await call(1)).status).toBe(403)
expect((await call(1, { user: { ...editor, roles: ['user'] } })).status).toBe(403)
expect((await call(1, { user: editor })).status).toBe(202)
expect(started[0]).toMatchObject({ callbackUrl: `${siteUrl}/api/ipal/cookie-crawl/results`, maxPages: 20, siteUrl })
expect((await call(1, { user: editor })).status).toBe(409)
const status = (await (await call(0, { user: editor })).json()) as Record<string, unknown>
expect(status).toMatchObject({ configured: true, status: 'running' })
})
test('results need the token and the running job id', async () => {
const jobId = started[0].jobId as string
expect((await call(2, { body: { jobId, observations: [], ok: true, pages: [], requests: [] } })).status).toBe(401)
expect((await call(2, { body: { jobId: 'a'.repeat(32), observations: [], ok: true, pages: [], requests: [] }, token: TOKEN })).status).toBe(409)
})
test('a real browser crawl lands as drafts with violations, a dashboard warning and an e-mail', async () => {
await payload.updateGlobal({ slug: 'cookie-crawl' as never, data: { notifyEmails: '[email protected]' } as never })
const sendEmail = vi.spyOn(payload, 'sendEmail').mockResolvedValue(undefined as never)
const result = await crawlSite({ chromium, maxPages: 5, siteUrl, waitMs: 300 })
expect(result.accepted).toBe(true)
expect(result.pages).toEqual(['/', '/about'])
const res = await call(2, { body: { ...result, jobId: started[0].jobId }, token: TOKEN })
expect(res.status).toBe(200)
expect(await review('sid')).toMatchObject({ seenBeforeConsent: true, status: 'draft', violation: false })
expect(await review('_fbp')).toMatchObject({ category: 'marketing', seenBeforeConsent: true, violation: true })
expect(await review('_ga')).toMatchObject({ seenBeforeConsent: false, status: 'draft', violation: false })
expect(await review('ipal-theme', 'localStorage')).toMatchObject({ source: 'unknown', status: 'draft' })
const crawl = (await payload.findGlobal({ slug: 'cookie-crawl' as never })) as unknown as CrawlDoc
expect(crawl.status).toBe('done')
expect(crawl.summary).toMatchObject({ pages: 2, violations: 2 })
expect(crawl.violations.map((v: { name: string }) => v.name).sort()).toEqual(['_fbp', 'tracker.invalid'])
expect(sendEmail).toHaveBeenCalledWith(expect.objectContaining({ subject: expect.stringContaining('2'), to: ['[email protected]'] }))
expect(await CookieCrawlAlert({ payload })).not.toBeNull()
sendEmail.mockRestore()
}, 60_000)
test('only the latest crawl counts: a clean crawl clears the flags; status and entries stay', async () => {
const fbp = await review('_fbp')
await payload.update({ id: fbp.id as number, collection: 'cookie-review' as never, data: { status: 'rejected' } as never })
const before = (await payload.count({ collection: 'cookie-review' as never })).totalDocs
expect((await call(1, { token: TOKEN })).status).toBe(202) // a scheduled task authenticates with the token
const jobId = started.at(-1)!.jobId
const clean = { accepted: true, jobId, observations: [{ name: 'sid', after: true, before: true, pages: ['/'], storage: 'cookie' }], ok: true, pages: ['/'], requests: [] }
expect((await call(2, { body: clean, token: TOKEN })).status).toBe(200)
expect(await review('_fbp')).toMatchObject({ seenBeforeConsent: false, status: 'rejected', violation: false })
expect((await payload.count({ collection: 'cookie-review' as never })).totalDocs).toBe(before)
const crawl = (await payload.findGlobal({ slug: 'cookie-crawl' as never })) as unknown as CrawlDoc
expect(crawl.summary.violations).toBe(0)
expect(await CookieCrawlAlert({ payload })).toBeNull()
})
test('a failed crawl is reported and the next one may start', async () => {
expect((await call(1, { user: editor })).status).toBe(202)
const jobId = started.at(-1)!.jobId
expect((await call(2, { body: { error: 'site down', jobId, ok: false }, token: TOKEN })).status).toBe(200)
const status = (await (await call(0, { user: editor })).json()) as Record<string, unknown>
expect(status).toMatchObject({ error: 'site down', status: 'failed' })
expect(await CookieCrawlAlert({ payload })).not.toBeNull()
})
})
+193
View File
@@ -0,0 +1,193 @@
import type { AddressInfo } from 'node:net'
/**
* The scanner service (services/cookie-crawler) without a browser, and the
* site side's pure pieces: wire format, violations, token check, config.
*/
import type { BasePayload } from 'payload'
import { afterEach, describe, expect, test, vi } from 'vitest'
import { checkCrawlRequest, discoverPages, isFirstParty, mergeRuns, parseSites } from '../services/cookie-crawler/lib.mjs'
import { createCrawlerServer } from '../services/cookie-crawler/server.mjs'
import { resolveCrawlConfig } from '../src/modules/consent/scanner/crawl/config.js'
import { bearerMatches } from '../src/modules/consent/scanner/crawl/endpoints.js'
import { parseCrawlResult } from '../src/modules/consent/scanner/crawl/result.js'
import { findCrawlViolations } from '../src/modules/consent/scanner/crawl/violations.js'
const TOKEN = 'a'.repeat(32)
const JOB = 'f'.repeat(32)
const sites = parseSites(`acme.pl=${TOKEN}, shop.example.com=${'b'.repeat(32)},short.pl=123`)
describe('crawler service — request checks', () => {
test('sites: host=token pairs, www dropped, short tokens refused', () => {
expect(sites).toEqual([
{ host: 'acme.pl', token: TOKEN },
{ host: 'shop.example.com', token: 'b'.repeat(32) },
])
})
const body = { callbackUrl: 'https://www.acme.pl/api/ipal/cookie-crawl/results', jobId: JOB, siteUrl: 'https://www.acme.pl' }
const check = (b: object, authorization = `Bearer ${TOKEN}`, allowHttp = false) => checkCrawlRequest({ allowHttp, authorization, body: b, sites })
test('a listed site with its own token passes', () => {
expect(check(body)).toBeNull()
})
test('refuses other sites, other tokens, foreign callbacks, http, bad job ids', () => {
expect(check({ ...body, callbackUrl: 'https://evil.com/x', siteUrl: 'https://evil.com' })).toBe('site_not_allowed')
expect(check(body, `Bearer ${'b'.repeat(32)}`)).toBe('unauthorized') // shop's token cannot crawl acme
expect(check(body, '')).toBe('unauthorized')
expect(check({ ...body, callbackUrl: 'https://evil.com/collect' })).toBe('callback_not_on_site')
expect(check({ ...body, callbackUrl: 'http://acme.pl/x', siteUrl: 'http://acme.pl' })).toBe('https_only')
expect(check({ ...body, callbackUrl: 'http://acme.pl/x', siteUrl: 'http://acme.pl' }, `Bearer ${TOKEN}`, true)).toBeNull()
expect(check({ ...body, jobId: '../etc' })).toBe('bad_job_id')
expect(check(null as never)).toBe('bad_request')
})
})
describe('crawler service — pages and runs', () => {
test('pages from the sitemap index: same origin only, capped', async () => {
const files: Record<string, string> = {
'https://acme.pl/sitemap.xml': '<sitemapindex><sitemap><loc>https://acme.pl/sitemap-pages.xml</loc></sitemap></sitemapindex>',
'https://acme.pl/sitemap-pages.xml': '<urlset><url><loc>https://acme.pl/pl</loc></url><url><loc>https://evil.com/x</loc></url><url><loc>https://acme.pl/en</loc></url><url><loc>https://acme.pl/de</loc></url></urlset>',
}
const fakeFetch = vi.fn(async (url: string) => new Response(files[url] ?? '', { status: files[url] ? 200 : 404 }))
expect(await discoverPages('https://acme.pl/', 2, fakeFetch as unknown as typeof fetch)).toEqual(['https://acme.pl/', 'https://acme.pl/pl', 'https://acme.pl/en'])
const offline = vi.fn(async () => { throw new Error('down') })
expect(await discoverPages('https://acme.pl/', 5, offline as unknown as typeof fetch)).toEqual(['https://acme.pl/'])
})
test('first party includes subdomains', () => {
expect(isFirstParty('www.acme.pl', 'acme.pl')).toBe(true)
expect(isFirstParty('cdn.acme.pl', 'acme.pl')).toBe(true)
expect(isFirstParty('notacme.pl', 'acme.pl')).toBe(false)
})
test('two runs merge into before/after flags with the first pages', () => {
const { observations, requests } = mergeRuns(
{ cookies: [{ name: 'sid', domain: '.acme.pl', page: '/' }], requests: [{ host: 'connect.facebook.net', page: '/' }], storage: [] },
{
cookies: [{ name: 'sid', domain: 'acme.pl', page: '/' }, { name: '_ga', domain: '.acme.pl', page: '/' }, { name: '_ga', domain: '.acme.pl', page: '/en' }],
requests: [],
storage: [{ name: 'ipal-theme', page: '/', storage: 'localStorage' }],
},
)
expect(observations).toEqual([
{ name: 'sid', after: true, before: true, domain: 'acme.pl', pages: ['/'], storage: 'cookie' },
{ name: '_ga', after: true, before: false, domain: 'acme.pl', pages: ['/', '/en'], storage: 'cookie' },
{ name: 'ipal-theme', after: true, before: false, pages: ['/'], storage: 'localStorage' },
])
expect(requests).toEqual([{ after: false, before: true, host: 'connect.facebook.net', pages: ['/'] }])
})
})
describe('crawler service — HTTP', () => {
let close: (() => Promise<void>) | undefined
afterEach(async () => {
await close?.()
close = undefined
})
async function start(crawl: (job: unknown) => Promise<unknown>, extra: Record<string, unknown> = {}) {
const delivered: { auth: null | string; body: Record<string, unknown>; url: string }[] = []
const fetchImpl = vi.fn(async (url: string, init: RequestInit) => {
delivered.push({ auth: new Headers(init.headers).get('authorization'), body: JSON.parse(init.body as string), url })
return new Response('{}', { status: 200 })
})
const server = createCrawlerServer({ allowHttp: true, crawl, deliveryDelays: [0], fetchImpl: fetchImpl as unknown as typeof fetch, log: () => {}, sites, ...extra }) as { whenIdle: () => Promise<void> } & ReturnType<typeof createCrawlerServer>
await new Promise<void>((r) => server.listen(0, '127.0.0.1', r))
close = () => new Promise<void>((r) => server.close(() => r()))
const base = `http://127.0.0.1:${(server.address() as AddressInfo).port}`
const post = (body: unknown, token = TOKEN) =>
fetch(`${base}/crawl`, { body: JSON.stringify(body), headers: { Authorization: `Bearer ${token}` }, method: 'POST' })
return { base, delivered, post, server }
}
const job = { callbackUrl: 'https://acme.pl/api/ipal/cookie-crawl/results', jobId: JOB, siteUrl: 'https://acme.pl' }
test('202, crawl in the background, result posted back with the site token', async () => {
const crawl = vi.fn(async () => ({ accepted: true, observations: [], ok: true, pages: ['/'], requests: [] }))
const { base, delivered, post, server } = await start(crawl)
expect((await fetch(`${base}/health`)).status).toBe(200)
const res = await post(job)
expect(res.status).toBe(202)
await server.whenIdle()
expect(crawl).toHaveBeenCalledWith(expect.objectContaining({ maxPages: 20, siteUrl: 'https://acme.pl' }))
expect(delivered).toEqual([{ auth: `Bearer ${TOKEN}`, body: expect.objectContaining({ jobId: JOB, ok: true }), url: job.callbackUrl }])
})
test('401 for a wrong token, 404 elsewhere, a crash or timeout is reported as ok:false', async () => {
const { base, delivered, post, server } = await start(() => new Promise(() => {}), { jobTimeoutMs: 50 })
expect((await post(job, 'x'.repeat(32))).status).toBe(401)
expect((await fetch(`${base}/nope`)).status).toBe(404)
expect((await post(job)).status).toBe(202)
await server.whenIdle()
expect(delivered[0].body).toMatchObject({ error: expect.stringContaining('longer than 50 ms'), jobId: JOB, ok: false })
})
test('a full queue answers 429', async () => {
const { post } = await start(() => new Promise(() => {}), { jobTimeoutMs: 60_000, queueMax: 1 })
expect((await post(job)).status).toBe(202) // running
expect((await post(job)).status).toBe(202) // queued
expect((await post(job)).status).toBe(429)
})
})
describe('crawl — site side', () => {
test('the wire format is validated, junk dropped', () => {
expect(parseCrawlResult({ jobId: 'nope', ok: true })).toBeNull()
expect(parseCrawlResult({ error: 'boom', jobId: JOB, ok: false })).toEqual({ error: 'boom', jobId: JOB, ok: false })
const r = parseCrawlResult({
jobId: JOB,
observations: [
{ name: '_ga', after: true, before: true, domain: '.Acme.pl', pages: ['/'], storage: 'cookie' },
{ name: 'bad name', storage: 'cookie' },
{ name: 'x', storage: 'indexedDB' },
],
ok: true,
pages: ['/', 3],
requests: [{ before: true, host: 'connect.facebook.net' }, { host: 'not a host' }],
})
expect(r).toEqual({
accepted: true,
jobId: JOB,
observations: [{ name: '_ga', after: true, before: true, domain: 'acme.pl', pages: ['/'], storage: 'cookie' }],
ok: true,
pages: ['/'],
requests: [{ after: false, before: true, host: 'connect.facebook.net', pages: [] }],
})
})
test('violations: stored before consent and not necessary; tracker hosts; Google only in basic mode', () => {
const o = (name: string, before: boolean) => ({ name, after: true, before, pages: ['/'], storage: 'cookie' as const })
const categories: Record<string, null | string> = { _fbp: 'marketing', 'cookie-consent': 'necessary', mystery: null }
const args = {
categoryOf: (x: { name: string }) => categories[x.name],
observations: [o('cookie-consent', true), o('_fbp', true), o('mystery', true), o('_ga', false)],
requests: [
{ after: true, before: true, host: 'connect.facebook.net', pages: ['/'] },
{ after: true, before: true, host: 'www.googletagmanager.com', pages: ['/'] },
{ after: true, before: false, host: 'px.ads.linkedin.com', pages: ['/'] },
],
}
expect(findCrawlViolations(args).map((v) => v.name)).toEqual(['_fbp', 'mystery', 'connect.facebook.net'])
expect(findCrawlViolations({ ...args, consentMode: 'basic' }).map((v) => v.name)).toContain('www.googletagmanager.com')
expect(findCrawlViolations({ ...args, trackerHosts: [] }).map((v) => v.kind)).toEqual(['cookie', 'cookie'])
})
test('bearer token: constant-time match, nothing without a token', () => {
expect(bearerMatches(`Bearer ${TOKEN}`, TOKEN)).toBe(true)
expect(bearerMatches(`Bearer ${TOKEN}x`, TOKEN)).toBe(false)
expect(bearerMatches(TOKEN, TOKEN)).toBe(false)
expect(bearerMatches(`Bearer ${TOKEN}`, null)).toBe(false)
})
test('config: options, then env, then Payload serverURL; short tokens are not a token', () => {
const payload = { config: { serverURL: 'https://acme.pl/' } } as unknown as BasePayload
vi.stubEnv('IPAL_COOKIE_SCAN_URL', 'https://crawler.intecion.net/')
vi.stubEnv('IPAL_COOKIE_SCAN_TOKEN', 'short')
const c = resolveCrawlConfig({ maxPages: 500 }, payload)
expect(c).toMatchObject({ maxPages: 100, serviceUrl: 'https://crawler.intecion.net', siteUrl: 'https://acme.pl', token: null })
expect(resolveCrawlConfig({ token: TOKEN, trackerHosts: (d) => [...d, 'chat.example'] }, payload).trackerHosts).toContain('chat.example')
vi.unstubAllEnvs()
})
})
+2
View File
@@ -237,6 +237,8 @@ describe('agent guide covers the whole plugin', () => {
...typeKeys('src/modules/content/types.ts', 'ContentCollectionOption'),
...typeKeys('src/modules/content/types.ts', 'ContentOption'),
...typeKeys('src/modules/consent/scanner/types.ts', 'CookieScannerOptions'),
...typeKeys('src/modules/consent/scanner/types.ts', 'CookieCrawlOptions'),
...typeKeys('src/modules/env/ipalEnvRules.ts', 'IpalEnvFeatures'),
...typeKeys('src/modules/forms/types.ts', 'FormsOption'),
...typeKeys('src/modules/i18n/types.ts', 'I18nConfig'),
...typeKeys('src/modules/i18n/types.ts', 'LocaleDefinition'),
+1
View File
@@ -42,6 +42,7 @@ beforeAll(async () => {
],
secret: 'drafts-test',
telemetry: false,
typescript: { autoGenerate: false }, // no orphaned `payload generate:types` child
})
payload = await getPayload({ config })
}, 60_000)
+1
View File
@@ -53,6 +53,7 @@ beforeAll(async () => {
],
secret: 'integration-test-secret',
telemetry: false,
typescript: { autoGenerate: false }, // no orphaned `payload generate:types` child
})
configPromise = config
payload = await getPayload({ config })
+1
View File
@@ -120,6 +120,7 @@ describe('createSeeder', () => {
plugins: [ipalKit({ i18n: { defaultLocale: 'pl', locales: [{ code: 'pl', label: 'PL' }, { code: 'en', label: 'EN' }] }, indexNow: true, pages: { slug: 'pages' }, twoFactor: false })],
secret: 'seed-test-secret',
telemetry: false,
typescript: { autoGenerate: false }, // no orphaned `payload generate:types` child
})
payload = await getPayload({ config })
}, 60_000)
+1
View File
@@ -44,6 +44,7 @@ describe('SEO outputs against a real database', () => {
plugins: [ipalKit({ access: { authCollection: 'users' }, i18n, pages: { slug: 'pages' }, twoFactor: false })],
secret: 'seo-integration-test-secret',
telemetry: false,
typescript: { autoGenerate: false }, // no orphaned `payload generate:types` child
})
payload = await getPayload({ config: configPromise })
+1
View File
@@ -45,6 +45,7 @@ beforeAll(async () => {
],
secret: 'depth-test',
telemetry: false,
typescript: { autoGenerate: false }, // no orphaned `payload generate:types` child
})
payload = await getPayload({ config: configPromise })
const png = Buffer.from('iVBORw0KGgoAAAANSUhEUgAAAAEAAAABCAYAAAAfFcSJAAAADUlEQVR42mNk+M9QDwADhgGAWjR9awAAAABJRU5ErkJggg==', 'base64')