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

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

Overlap with claude/test-no-typegen, resolved here: one test-config fix.
- the six real-Payload tests keep buildTestConfig and drop the branch's
  duplicate typescript: { autoGenerate: false } lines;
- cookieScannerIntegration and cookieCrawlIntegration use buildTestConfig
  instead of buildConfig + their own flag (testConfig.test.ts guard passes).
This commit is contained in:
Radosław Smoliński
2026-10-27 15:26:44 +01:00
54 changed files with 6925 additions and 7 deletions
+4
View File
@@ -27,10 +27,12 @@ import { StrikethroughFeatureClient as StrikethroughFeatureClient_e70f5e05f09f93
import { UnderlineFeatureClient as UnderlineFeatureClient_e70f5e05f09f93e00b997edb1ef0c864 } from '@payloadcms/richtext-lexical/client'
import { BoldFeatureClient as BoldFeatureClient_e70f5e05f09f93e00b997edb1ef0c864 } from '@payloadcms/richtext-lexical/client'
import { ItalicFeatureClient as ItalicFeatureClient_e70f5e05f09f93e00b997edb1ef0c864 } from '@payloadcms/richtext-lexical/client'
import { CookieScanButton as CookieScanButton_7568fe47d582ff15ce85d2e1873c2c23 } from '@intecion/ipal-kit/admin'
import { IntegrationStatusBanner as IntegrationStatusBanner_7568fe47d582ff15ce85d2e1873c2c23 } from '@intecion/ipal-kit/admin'
import { MaskedField as MaskedField_7568fe47d582ff15ce85d2e1873c2c23 } from '@intecion/ipal-kit/admin'
import { TestEmailButton as TestEmailButton_7568fe47d582ff15ce85d2e1873c2c23 } from '@intecion/ipal-kit/admin'
import { StatsNavLink as StatsNavLink_7568fe47d582ff15ce85d2e1873c2c23 } from '@intecion/ipal-kit/admin'
import { CookieCrawlAlert as CookieCrawlAlert_7568fe47d582ff15ce85d2e1873c2c23 } from '@intecion/ipal-kit/admin'
import { StatsWidget as StatsWidget_7568fe47d582ff15ce85d2e1873c2c23 } from '@intecion/ipal-kit/admin'
import { IntegrationAlerts as IntegrationAlerts_7568fe47d582ff15ce85d2e1873c2c23 } from '@intecion/ipal-kit/admin'
import { StatsView as StatsView_7568fe47d582ff15ce85d2e1873c2c23 } from '@intecion/ipal-kit/admin'
@@ -67,10 +69,12 @@ export const importMap = {
"@payloadcms/richtext-lexical/client#UnderlineFeatureClient": UnderlineFeatureClient_e70f5e05f09f93e00b997edb1ef0c864,
"@payloadcms/richtext-lexical/client#BoldFeatureClient": BoldFeatureClient_e70f5e05f09f93e00b997edb1ef0c864,
"@payloadcms/richtext-lexical/client#ItalicFeatureClient": ItalicFeatureClient_e70f5e05f09f93e00b997edb1ef0c864,
"@intecion/ipal-kit/admin#CookieScanButton": CookieScanButton_7568fe47d582ff15ce85d2e1873c2c23,
"@intecion/ipal-kit/admin#IntegrationStatusBanner": IntegrationStatusBanner_7568fe47d582ff15ce85d2e1873c2c23,
"@intecion/ipal-kit/admin#MaskedField": MaskedField_7568fe47d582ff15ce85d2e1873c2c23,
"@intecion/ipal-kit/admin#TestEmailButton": TestEmailButton_7568fe47d582ff15ce85d2e1873c2c23,
"@intecion/ipal-kit/admin#StatsNavLink": StatsNavLink_7568fe47d582ff15ce85d2e1873c2c23,
"@intecion/ipal-kit/admin#CookieCrawlAlert": CookieCrawlAlert_7568fe47d582ff15ce85d2e1873c2c23,
"@intecion/ipal-kit/admin#StatsWidget": StatsWidget_7568fe47d582ff15ce85d2e1873c2c23,
"@intecion/ipal-kit/admin#IntegrationAlerts": IntegrationAlerts_7568fe47d582ff15ce85d2e1873c2c23,
"@intecion/ipal-kit/admin#StatsView": StatsView_7568fe47d582ff15ce85d2e1873c2c23,
+2
View File
@@ -67,6 +67,8 @@ export default buildConfig({
access: { authCollection: 'users' },
i18n: i18nConfig,
consentLog: true,
// Cookie review + "Crawl site" (needs IPAL_COOKIE_SCAN_URL / IPAL_COOKIE_SCAN_TOKEN and a running services/cookie-crawler).
cookieScanner: { crawl: true },
forms: {},
seo: { collections: ['posts', 'pages'] },
stats: true,
+1
View File
@@ -24,6 +24,7 @@ API details — one file per module:
| GA4, GTM, Meta Pixel, Clarity, LinkedIn, TikTok, `defer` | [analytics.md](./analytics.md) |
| Blocks, RenderBlocks, enhanceProps | [blocks.md](./blocks.md) |
| Cookie consent, banner, settings window (in the bar / modal / large with cookie details) | [consent.md](./consent.md) |
| Cookie scanner: review list of drafts, "Scan cookies", Open Cookie Database lookup (optional) | [cookie-scanner.md](./cookie-scanner.md) |
| Under construction — locks subpages behind a popup (developer tool) | [construction.md](./construction.md) |
| Routing, archives, redirects, Markdown, search | [content.md](./content.md) |
| Site frontend: `createContentHelpers` (`@/lib/content`), `createPageRoute`, `SiteProviders` | [frontend.md](./frontend.md) |
+6 -1
View File
@@ -107,7 +107,7 @@ site), **P** = a test in the panel. Full code: PROGRAMISTA.md §2.
| 9 | **Media / R2 / speed** | `Media` with `focalPoint`, `normalizeFilenameHook`, `buildOptimizeUploadHook`, `buildMediaPlaceholderHook` + field; **always** `buildR2Storage(['media'], { s3Storage })` + `@payloadcms/storage-s3`; `R2_*` in `.env.example`; `<MediaPreconnect/>`; `images: buildImagesConfig()` and `buildUploadSecurityHeaders()` in `next.config.ts`; the project's `<Media>` via `mediaImageProps`/`videoProps` (§6.11b) | `buildR2Storage`, `mediaImageProps`, `videoProps`, `buildImagesConfig` | A, S |
| 10 | **Forms** | every form from a **seed** (`scripts/seed-form-*.ts`: fields, confirmation, mail to the company **and** confirmation to the customer, every language); a block with `<RenderForm>` + `formClasses.ts` (look, once); `actions.ts` = `createSubmitAction({ getCachedPayload, headers })`; `forms: {…}` in `ipalKit`; `email: mailAdapter()` | `RenderForm` (`/rsc`), `createSubmitAction`, `mailAdapter` | A, P |
| 11 | **Turnstile** | `<SiteProviders>` in `[locale]/layout.tsx` (wires `TurnstileProvider` with the key from the panel); `RenderForm` renders the widget; keys in Site Integrations | `SiteProviders`, `getTurnstileConfig`, `TurnstileProvider` | A, P |
| 12 | Consent + analytics | Consent Mode: `'advanced'` (default — the Google tag loads at once with every signal `denied`) or `'basic'` (`<SiteProviders analytics={{ consentMode: 'basic' }}>` — no request to Google before consent; a client who wants zero requests), the choice goes to "Project decisions"; `ipalKit({ consentLog: true })` (without it the `/api/ipal/consent` endpoint does not exist) + `<SiteProviders logEndpoint="/api/ipal/consent" banner={<CookieBanner equalChoice settings="detailed" />}>` (ConsentProvider, banner, CookieButton, Analytics in the right order); settings window mode (`settings`: `inline` / `modal` / `detailed`) per the design, brief is silent → `detailed`, the decision goes to "Project decisions"; tool IDs in the panel; the cookie list from a scan (cookie-scan → import) — feeds `<CookieTable>` on the policy page **and** the lists in the `detailed` window; Cookie Settings → Detail labels in every language | consent.md, analytics.md | A, `ipal-consent-check` |
| 12 | Consent + analytics | Consent Mode: `'advanced'` (default — the Google tag loads at once with every signal `denied`) or `'basic'` (`<SiteProviders analytics={{ consentMode: 'basic' }}>` — no request to Google before consent; a client who wants zero requests), the choice goes to "Project decisions"; `ipalKit({ consentLog: true })` (without it the `/api/ipal/consent` endpoint does not exist) + `<SiteProviders logEndpoint="/api/ipal/consent" banner={<CookieBanner equalChoice settings="detailed" />}>` (ConsentProvider, banner, CookieButton, Analytics in the right order); settings window mode (`settings`: `inline` / `modal` / `detailed`) per the design, brief is silent → `detailed`, the decision goes to "Project decisions"; tool IDs in the panel; the cookie list from a scan (`cookieScanner: true` → *Cookie review* → **Scan cookies** → the editor accepts; or cookie-scan → import) — feeds `<CookieTable>` on the policy page **and** the lists in the `detailed` window; Cookie Settings → Detail labels in every language | consent.md, analytics.md | A, `ipal-consent-check` |
| 13 | Security | `buildSecurityHeaders` in `next.config.ts`; `twoFactor: { issuer, plugin: payloadTotp }`; CSP `report-only` → `enforce`; `IPAL_IP_HEADER` in production | security.md, forms.md | A |
| 14 | Operations | `src/app/api/health/route.ts` (`healthRoute`); `src/instrumentation.ts` with `assertEnv(ipalEnvRules({ storage: true, ipHeader: true }))`; staging with `IPAL_NOINDEX=1`; smoke tests (§8a) | `healthRoute`, `assertEnv`, `ipalEnvRules` | A |
| 15 | System pages | Site Settings → System Pages: homepage, 404, privacy policy, cookies; legal links in the footer by role (`getSystemLinks(locale)`) | `getSystemLinks`, `getSystemPagePath`, `getNotFoundPage` | P |
@@ -910,6 +910,8 @@ project → **plugin gap**, not a copy.
| Settings window: in the bar / small / large with cookie details | `<CookieBanner settings="inline" \| "modal" \| "detailed">` — do not build your own window or cookie list | consent.md → "Large window with details" |
| 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 |
@@ -933,6 +935,8 @@ 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 |
| First registered account = admin | `access.firstUserAdmin: false` | `buildRolesField(defaultRole, { firstUserAdmin })` |
@@ -1109,6 +1113,7 @@ Anything that needs a developer → move it to the panel.
| GA4, GTM, Meta Pixel, Clarity, LinkedIn, TikTok | [analytics.md](../analytics.md) |
| Blocks, RenderBlocks, enhanceProps | [blocks.md](../blocks.md) |
| Cookie consent, banner | [consent.md](../consent.md) |
| Cookie scanner (review list, Open Cookie Database) | [cookie-scanner.md](../cookie-scanner.md) |
| Routing, archives, redirects, Markdown, search | [content.md](../content.md) |
| Email SMTP / Graph | [email.md](../email.md) |
| Env validation | [env.md](../env.md) |
+44 -1
View File
@@ -41,9 +41,52 @@ before analytics or marketing consent — check the project's choice in "Project
The script needs buttons with `data-ipal="accept"` / `"reject"` — the plugin's
`CookieBanner` has them in every `settings` mode (`inline`, `modal`, `detailed`). A custom banner in the project violates AGENT.md §7.
## Cookie list from the panel (`cookieScanner`)
When the project has `ipalKit({ cookieScanner: true })` (cookie-scanner.md), the editor fills the
list in the panel and you check it:
1. Not on yet → turn it on, `pnpm generate:importmap`, `pnpm payload migrate:create cookie-scanner`
(Postgres), commit the migration. Embeds and widgets the plugin does not inject (YouTube, maps,
chat): add them as `cookieScanner.declarations` (or an `integrations` entry with `isEnabled`) —
never a hand-typed list in code.
2. *Settings → Cookie review* → **Scan cookies**. "Integrations in use" must match the IDs in Site
Integrations; a filled ID that is missing → **ipal-debug**.
3. Run the browser scan below and paste every cookie it reports as unknown into **More cookie
names**, scan again. Entries with *Found by* = "Unknown — fill in" need provider, category and
purpose: ask the client, do not guess.
4. The editor accepts or rejects every draft (bulk edit works). Accepted → Cookie Settings →
Cookies, every language; existing text there is never overwritten. Open the banner's
"Settings" and check each category lists its cookies.
5. Database lookups come with category `functional` when the Open Cookie Database says
"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:
After every change of tools (new pixel, chat, map, video) and before handing the site over
(with `cookieScanner` on, use step 1 below to find what really appears in the browser, then feed the
unknown names to the panel scan above instead of step 2):
1. Scan the running site (without consent and after "Accept all", homepage + up to 10 pages from the sitemap):
```bash
+16
View File
@@ -64,6 +64,13 @@ description: Complete map of everything @intecion/ipal-kit provides — every ip
| `forms.consentFieldName` | `'consent'` | name of the GDPR consent field `submitForm` requires (read from `config.custom.ipal`) | `createSubmitAction({ consentFieldName })` / `submitForm` argument wins |
| `consentLog` | off | `consent-records` collection + `POST /api/ipal/consent` (rate limit 20/min) | `true` / `{ retentionDays }` (default 1095) |
| `consentLog.collectionOverrides` | none | changes `consent-records`: an object merges `access` / `admin` / `hooks` key by key (your keys win), a function `(collection) => collection` takes over (keep the slug) | e.g. `{ access: { read: ({ req }) => req.user?.email === '[email protected]' } }` — narrows who reads records in a project without roles |
| `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 |
| `stats.retentionDays` / `timeZone` / `dashboard` | 90 / `'Europe/Warsaw'` / `true` | retention, day boundary, `StatsWidget` | `dashboard: false` hides the chart |
@@ -82,6 +89,8 @@ 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` |
| global `site-integrations` | Analytics, Turnstile, SMTP, IndexNow, [Custom]; admin only | `integrationsFields` | always present; `globalOverrides` |
@@ -91,6 +100,8 @@ 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` | — |
| `beforeChange` meta auto-fill hook | in `seo.collections` | `seo.autoFill` | `autoFill: false` |
@@ -105,6 +116,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` (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 |
@@ -151,6 +164,8 @@ 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 |
| analytics | layout | `SiteProviders` wires `Analytics` (ID from Site Integrations → Analytics); Consent Mode: `analytics={{ consentMode: 'basic' }}` = no request to Google before consent, default `'advanced'` = the Google tag loads at once with every signal `denied` | Meta/other pixels only after consent; in `basic` no `gtm.js` / `gtag/js` in Network before consent | analytics.md, gtm-meta-pixel.md |
@@ -200,6 +215,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 |
@@ -12,7 +12,7 @@ project wires: `../SKILL.md`. Module details: `node_modules/@intecion/ipal-kit/d
|---|---|---|
| `ipalKit(options)` | `@intecion/ipal-kit` | Payload 3 plugin (`plugins: [ipalKit({...})]`) — the only wiring point: adds globals (SiteSettings, SiteIntegrations, CookieSettings, Notifications), roles, enforced 2FA, SEO, forms, i18n (localization), white-label, stats, consent log, `/api/ipal/*` endpoints; no auth collection → injects a simple `users`. Validates `i18n` right away (fail fast). `enabled: false` = schema stays, behaviour off. |
**Types:** `IpalOptions` — `ipalKit()` options: `i18n`, `access`, `twoFactor` (`{ issuer, plugin: payloadTotp }` or `false`), `whiteLabel`, `adminRoute`, `consentLog`, `content`, `forms`, `pages`, `seo`, `searchSettings`, `stats`, `indexNow`, `siteSettingsFields`, `integrationsFields`, `globalOverrides`, `revalidatePath`, `enabled`. `GlobalOverride`, `GlobalOverrides`, `IpalGlobalSlug` — see Payload globals below.
**Types:** `IpalOptions` — `ipalKit()` options: `i18n`, `access`, `twoFactor` (`{ issuer, plugin: payloadTotp }` or `false`), `whiteLabel`, `adminRoute`, `consentLog`, `content`, `cookieScanner`, `forms`, `pages`, `seo`, `searchSettings`, `stats`, `indexNow`, `siteSettingsFields`, `integrationsFields`, `globalOverrides`, `revalidatePath`, `enabled`. `GlobalOverride`, `GlobalOverrides`, `IpalGlobalSlug` — see Payload globals below.
## Admin (import map) (`admin`, `branding`, `admin-ui`, `globals/SiteIntegrations`) — details: `node_modules/@intecion/ipal-kit/docs/white-label.md`, `…/docs/integrations.md`, `…/docs/email.md`, `…/docs/links.md`
@@ -25,6 +25,8 @@ 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 }`. |
## Readable array rows in the panel (`admin-ui`) — details: `node_modules/@intecion/ipal-kit/docs/links.md`
@@ -128,6 +130,46 @@ Admin panel components from `@intecion/ipal-kit/admin` — the project does NOT
**Types:** `ConsentCategory`, `ConsentState`, `ConsentTexts`, `CookieTableRow`, `ConsentLogOptions` (root) — categories, consent state, banner texts, cookie table row, log options; `CookieBannerAction`, `CookieSettingsAction`, `CookieBannerClassNames` (`/client`) — `CookieBanner` buttons and classes; `CookieTableLabels` (`/rsc`) — `CookieTable` column headers.
## Cookie scanner (`consent/scanner`) — details: `node_modules/@intecion/ipal-kit/docs/cookie-scanner.md`
Opt-in with `ipalKit({ cookieScanner: true })`; the plugin wires the collection, endpoints and admin box. The exports are building blocks for a CLI, a scheduled job or your own admin view.
| Export | Import from | What it does / when |
|---|---|---|
| `runCookieScan({ payload, plugin, options?, names?, req? })` | `@intecion/ipal-kit` | The whole scan as `POST /api/ipal/cookie-scan` runs it → `{ enabled, summary }` (`plugin` = `{ localeCount, stats }`). |
| `collectCookieFindings({ ctx, integrations?, declarations?, names?, database?, databaseCategories? })` | `@intecion/ipal-kit` | Findings for the project without writing: enabled integrations' cookies, project declarations, extra names looked up (declarations → built-ins → Open Cookie Database → `unknown`). |
| `applyCookieFindings({ payload, findings, req?, collection? })` | `@intecion/ipal-kit` | Writes findings to `cookie-review` as drafts: new names created, existing ones updated only where the editor did not change the value; status untouched, nothing deleted → `CookieScanSummary`. |
| `cookieScanContext(payload, plugin, req?)` | `@intecion/ipal-kit` | Builds the `CookieScanContext` (Site Integrations + module switches). |
| `parseCookieNames(input)` | `@intecion/ipal-kit` | Text box / array → clean, unique names (max 200; no spaces, `;`, `,`, `=`). |
| `mergeCookieReview(current, previous, next)` | `@intecion/ipal-kit` | Pure "never overwrite an edit" rule, per field and per locale. |
| `suggestionFor(finding, locales)` | `@intecion/ipal-kit` | A finding's values resolved per locale (own language → English → first). |
| `addToCookieList({ payload, entry, req? })` | `@intecion/ipal-kit` | What accepting does: adds the row to Cookie Settings → Cookies or fills only its empty text, every locale → `'added' \| 'filled' \| 'unchanged'`. |
| `loadCookieDatabase()` / `indexCookieDatabase(rows)` / `lookupCookie(index, name, categories?)` | `@intecion/ipal-kit` | Bundled Open Cookie Database (Apache-2.0, loaded on first use): exact name, then the longest wildcard prefix → `CookieFinding \| null`. |
| `DEFAULT_DATABASE_CATEGORIES` | `@intecion/ipal-kit` | Database → consent category map (Functional → `functional` on purpose; override with `cookieScanner.databaseCategories`). |
| `DEFAULT_COOKIE_INTEGRATIONS` | `@intecion/ipal-kit` | Built-in declarations: consent cookie, admin login, `NEXT_LOCALE`, `ipal_vid`, GA4, GTM, Meta Pixel, Clarity, LinkedIn, TikTok, Turnstile — each with its `isEnabled` check. |
| `cookieNameMatches(pattern, name)` | `@intecion/ipal-kit` | `*` at the end = prefix, else exact. |
| `buildCookieReviewCollection(options)` / `buildCookieScanEndpoints(options, plugin)` | `@intecion/ipal-kit` | The collection and the GET/POST endpoints — the plugin wires them with `cookieScanner`; call only to wire by hand. |
| `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. |
**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`
| Export | Import from | What it does / when |
+10 -3
View File
@@ -252,7 +252,8 @@ window width `max-w-4xl` — change it with `classNames.dialog`.
Which mode to choose: the project design decides. If the brief is silent → `'detailed'` (at the moment of
consent the user sees which cookies are set and by whom — full information where the decision is made),
provided the Cookies list is filled from a scan (`ipal-consent-check` → cookie-scan); an empty list = a
provided the Cookies list is filled from a scan (`ipalKit({ cookieScanner: true })` → *Cookie review* → **Scan cookies**,
[cookie-scanner.md](./cookie-scanner.md), or `ipal-consent-check` → cookie-scan); an empty list = a
window without expandable lists, then `'modal'` is enough. Record the decision in `AGENTS.md` →
"Project decisions".
@@ -342,8 +343,9 @@ independent consent state).
choices, the policy version and the time — **no IP and no user agent**. *Consent records* collection
(admin only), automatic cleanup after `retentionDays` (default 1095). Details below. Postgres:
`migrate:create`.
- **Cookie table** for the policy page: Cookie Settings → *Cookies* (filled by a scan,
skill `ipal-consent-check` → cookie-scan) + `getCookieTable` + `<CookieTable>` from `/rsc`.
- **Cookie table** for the policy page: Cookie Settings → *Cookies* + `getCookieTable` + `<CookieTable>` from `/rsc`.
Fill the list from the panel with the cookie scanner (`cookieScanner` option — drafts an editor accepts,
[cookie-scanner.md](./cookie-scanner.md)) and check the real site with `ipal-consent-check` → cookie-scan.
- Consent cookie: `cookie-consent` (`CONSENT_COOKIE`), JSON `{ id, state, timestamp, version }`,
`max-age` 180 days (`CONSENT_MAX_AGE`), `samesite=lax`, `Secure` on HTTPS. Consent with another
policy version is treated as no decision.
@@ -389,6 +391,11 @@ ipalKit({
global (write access is `admin` + `editor` by default, hooks, admin options):
`ipalKit({ globalOverrides: { 'cookie-settings': { access: { update } } } })` — your access rules win,
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`,
+399
View File
@@ -0,0 +1,399 @@
# cookie scanner
Fills the cookie list (Cookie Settings → Cookies) from the admin panel. A scan lists the cookies of
every integration the project switches on, plus any extra names, as **drafts** in a review list. An
editor accepts, edits or rejects each one; accepting adds it to the cookie list, which feeds the
`<CookieBanner settings="detailed">` window and `<CookieTable>` on the policy page
([consent.md](./consent.md)).
What a scan never does: delete an entry, change text an editor edited, change an entry's status, or
publish anything by itself.
Opt-in (`cookieScanner`, default off). Nothing is fetched at runtime and no browser is needed.
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
// payload.config.ts
ipalKit({
// …
cookieScanner: true,
})
```
Then, in the project:
1. **Import map** — the "Scan cookies" box above the list is an admin component
(`@intecion/ipal-kit/admin#CookieScanButton`). Run `pnpm generate:importmap`.
2. **Postgres / SQLite migration** — the option adds the `cookie-review` collection (with localized
`purpose` and `retention`). Run `pnpm payload migrate:create cookie-scanner`, commit the migration;
Coolify runs `payload migrate` on deploy (deployment.md). MongoDB: nothing to do.
3. **Verify** — log in as an editor, open *Settings → Cookie review*. The box lists "Integrations in
use" (e.g. Cookie banner, Admin panel login, Google Analytics 4). Click **Scan cookies**: drafts
appear, each with *Found by* = Plugin integration. Set one to *Accepted*, save, open *Cookie
Settings → Cookies*: the cookie is there, with purpose and retention in every language.
## How editors use it
| Step | What happens |
|---|---|
| **Scan cookies** | One draft per cookie of the integrations in use. Cookies already in Cookie Settings → Cookies are looked up too (*In the cookie list* is ticked). |
| **More cookie names** (optional text box) | Names seen in the browser (DevTools → Application → Cookies), one per line. Each is looked up in the project's declarations, every built-in integration, then the Open Cookie Database. A name nothing knows becomes an entry with *Found by* = "Unknown — fill in" and no category. |
| Edit a draft | Change provider, category, purpose, retention. A later scan keeps every value you changed (per language) and still updates values you left as suggested. |
| **Accepted** | The cookie is added to Cookie Settings → Cookies in every language. When a row with that name already exists, only its empty provider / purpose / retention are filled — text written there stays, its category is not changed. An entry without a category cannot be accepted. |
| **Rejected** | Stays in the list as rejected; later scans do not bring it back to draft. Rejecting never removes a row from Cookie Settings — delete it there. |
Status changes work in the list's bulk edit too. Deleting review entries is admin-only and never done
by the plugin.
Labels are in English and Polish and follow the editor's admin language; `cookieScanner.labels` adds
languages or changes text.
## What the plugin declares
Each integration the plugin injects declares its cookies in one place
(`DEFAULT_COOKIE_INTEGRATIONS`): name or pattern (`*` at the end = prefix), provider, category,
purpose and retention (English and Polish), and whether it may be set before consent. Only the
integrations switched on in this project are part of a scan:
| Integration | On when | Cookies |
|---|---|---|
| Cookie banner | always | `cookie-consent` (necessary, 6 months) |
| Admin panel login | always | `payload-token` (`<cookiePrefix>-token`, necessary, editors only) |
| Language choice | more than one locale in `i18n` | `NEXT_LOCALE` (functional, session) |
| Built-in statistics | `stats` option | `ipal_vid` (analytics, 6 months) |
| Google Analytics 4 | GA4 ID in Site Integrations | `_ga`, `_ga_*` (analytics, 2 years) |
| Google Tag Manager | GTM ID in Site Integrations | `_gcl_*` (marketing — the Conversion Linker; other tags in the container: add their names or declare them) |
| Meta Pixel | Pixel ID | `_fbp`, `_fbc` (marketing, 3 months) |
| Microsoft Clarity | Clarity ID | `_clck`, `_clsk`, `CLID`, `MUID` |
| LinkedIn Insight Tag | partner ID | `li_fat_id`, `bcookie`, `lidc`, `UserMatchHistory` |
| TikTok Pixel | Pixel ID | `_ttp`, `_tt_enable_cookie` |
| Cloudflare Turnstile | both Turnstile keys set | `cf_clearance` (necessary; only when pre-clearance is on in Cloudflare) |
An ID that fails its format check counts as off. The theme switcher (`ipal-theme` in localStorage)
and the accessibility widget (`a11y-prefs`) have no plugin option, so they are not declared: add
them with `declarations` when the site uses them.
## Open Cookie Database
Unknown names are looked up in a bundled copy of the
[Open Cookie Database](https://github.com/jkwakman/Open-Cookie-Database) (about 2,300 entries,
Apache License 2.0). The package ships the license text in
[licenses/open-cookie-database-LICENSE.txt](./licenses/open-cookie-database-LICENSE.txt); the
data module names the upstream commit and the changes made (converted from CSV, two columns left
out). The table is loaded only when a scan runs.
Category mapping (`DEFAULT_DATABASE_CATEGORIES`):
| Database | Consent category |
|---|---|
| Analytics | analytics |
| Marketing | marketing |
| Necessary, Security | necessary |
| Functional, Personalization | functional |
"Functional" is **not** mapped to necessary on purpose: the database files some trackers there
(Hotjar's user id), and a lookup nobody checked yet must not skip consent. The editor lowers the
category when a cookie really is necessary, or the project changes the map:
`cookieScanner: { databaseCategories: { Functional: 'necessary' } }`.
Refresh the copy (maintainers of ipal-kit, not projects):
```bash
pnpm cookie-db:refresh
```
`scripts/refresh-cookie-database.mjs` downloads the CSV and the license at the latest commit (or
`--ref <sha>`), refuses to write if the license is no longer Apache-2.0, and rewrites
`src/modules/consent/scanner/data/openCookieDatabase.ts` and the license file. Review the diff,
run the tests, commit.
## Options
`cookieScanner: true` or an object (`CookieScannerOptions`, every key optional):
| Key | Default | What it does |
|---|---|---|
| `declarations` | `[]` | The project's own cookies (custom embeds, chat, YouTube): `CookieDeclaration[]`, always part of a scan |
| `integrations` | built-ins | `(defaults) => integrations` — filter, change or add `CookieIntegration`s (each: `key`, `label`, `declarations`, `isEnabled(ctx)`) |
| `database` | `true` | `false` = no Open Cookie Database lookup |
| `databaseCategories` | table above | Partial map from database category to consent category |
| `access` | editor and up | `({ req }) => boolean` — who may 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:
```ts
import type { CookieDeclaration } from '@intecion/ipal-kit'
const youtube: CookieDeclaration = {
name: 'VISITOR_INFO1_LIVE',
vendor: 'Google (YouTube)',
category: 'marketing',
domain: 'youtube.com',
purpose: { en: 'YouTube: player preferences and bandwidth estimate.', pl: 'YouTube: preferencje odtwarzacza.' },
retention: { en: '6 months', pl: '6 mies.' },
setBeforeConsent: false,
}
ipalKit({ cookieScanner: { declarations: [youtube] } })
```
A project integration that is on only when a field is filled:
```ts
import type { CookieIntegration } from '@intecion/ipal-kit'
const chat: CookieIntegration = {
key: 'chat',
label: 'Live chat',
isEnabled: (ctx) => Boolean(ctx.integrations.chatWidgetId),
declarations: [/* CookieDeclaration … */],
}
ipalKit({ cookieScanner: { integrations: (defaults) => [...defaults, chat] } })
```
`ctx` (`CookieScanContext`) has `payload`, `integrations` (the Site Integrations global, depth 0) and
`plugin` (`{ localeCount, stats }`).
## Endpoint
| | |
|---|---|
| `GET /api/ipal/cookie-scan` | `{ ok, integrations: [{ key, label }] }` — what a scan covers |
| `POST /api/ipal/cookie-scan` | body `{ names?: string[] \| string }` (newline or comma separated, up to 200, names with spaces, `;`, `,` or `=` dropped) → `{ ok, summary: { created, updated, unchanged, unknown }, integrations }` |
| Access | editor and up (`userMeetsRole`; without `access` every logged-in account), or `cookieScanner.access`; otherwise `403` |
The path is `COOKIE_SCAN_PATH` (`/ipal/cookie-scan`, under the API route).
## Collection `cookie-review`
`COOKIE_REVIEW_SLUG`, group *Settings*. Fields: `name`, `storage` (`cookie` / `localStorage` /
`sessionStorage`), `category`, `vendor`, `domain`, `purpose` (localized), `retention` (localized),
`setBeforeConsent`, `status` (`draft` / `accepted` / `rejected`), and read-only `source`
(`integration` / `project` / `database` / `unknown` / `manual`), `sourceDetail`, `listed`,
`lastScannedAt`; hidden `key` (`storage:name`, unique — what a rescan matches) and `suggested` (the
last scan's values — a value still equal to it was not edited). Access: create / read / update
editor and up, delete admin.
## Building blocks
All from `@intecion/ipal-kit` (server-safe), for your own admin view, a CLI or a scheduled job:
| Export | What it does |
|---|---|
| `runCookieScan({ payload, plugin, options?, names?, req? })` | the whole scan as the endpoint runs it → `{ enabled, summary }` |
| `collectCookieFindings({ ctx, integrations?, declarations?, names?, database?, databaseCategories? })` | findings without writing anything; `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 |
| `addToCookieList({ payload, entry, req? })` | what accepting does: add the row or fill its empty text → `'added' \| 'filled' \| 'unchanged'` |
| `loadCookieDatabase()`, `indexCookieDatabase(rows)`, `lookupCookie(index, name, categories?)` | the Open Cookie Database lookup |
| `DEFAULT_COOKIE_INTEGRATIONS`, `DEFAULT_DATABASE_CATEGORIES`, `cookieNameMatches(pattern, name)` | declarations and matching |
| `buildCookieReviewCollection(options)`, `buildCookieScanEndpoints(options, plugin)` | the collection and endpoints, to wire by hand |
| `COOKIE_SCAN_LABELS`, `mergeCookieScanLabels(overrides)` | admin labels |
| `CookieScanButton` (`/admin`) | the box above the list (with **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`,
`CookieObservation`, `CookieReviewEntryRef`; crawl: `CookieCrawlOptions`, `ResolvedCrawlConfig`,
`CrawlResult`, `CrawlObservation`, `CrawlRequest`, `CrawlViolation`, `CrawlIngestSummary`.
## Browser crawl
What a page really sets — a GTM tag, an iframe, a script pasted into a block — shows only in a
browser. `cookieScanner.crawl` adds **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`; for the
crawl `serviceUrl`, `token`, `siteUrl`, `maxPages`, `acceptSelector`, `consentMode`, `trackerHosts`,
`globalOverride`.
- **Extend:** `declarations` and `integrations` for the project's own cookies; the building blocks
above for your own UI, CLI or scheduled scan; the crawl's wire format (`CrawlResult`) to feed results
from another crawler.
+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'
@@ -0,0 +1,201 @@
Apache License
Version 2.0, January 2004
http://www.apache.org/licenses/
TERMS AND CONDITIONS FOR USE, REPRODUCTION, AND DISTRIBUTION
1. Definitions.
"License" shall mean the terms and conditions for use, reproduction,
and distribution as defined by Sections 1 through 9 of this document.
"Licensor" shall mean the copyright owner or entity authorized by
the copyright owner that is granting the License.
"Legal Entity" shall mean the union of the acting entity and all
other entities that control, are controlled by, or are under common
control with that entity. For the purposes of this definition,
"control" means (i) the power, direct or indirect, to cause the
direction or management of such entity, whether by contract or
otherwise, or (ii) ownership of fifty percent (50%) or more of the
outstanding shares, or (iii) beneficial ownership of such entity.
"You" (or "Your") shall mean an individual or Legal Entity
exercising permissions granted by this License.
"Source" form shall mean the preferred form for making modifications,
including but not limited to software source code, documentation
source, and configuration files.
"Object" form shall mean any form resulting from mechanical
transformation or translation of a Source form, including but
not limited to compiled object code, generated documentation,
and conversions to other media types.
"Work" shall mean the work of authorship, whether in Source or
Object form, made available under the License, as indicated by a
copyright notice that is included in or attached to the work
(an example is provided in the Appendix below).
"Derivative Works" shall mean any work, whether in Source or Object
form, that is based on (or derived from) the Work and for which the
editorial revisions, annotations, elaborations, or other modifications
represent, as a whole, an original work of authorship. For the purposes
of this License, Derivative Works shall not include works that remain
separable from, or merely link (or bind by name) to the interfaces of,
the Work and Derivative Works thereof.
"Contribution" shall mean any work of authorship, including
the original version of the Work and any modifications or additions
to that Work or Derivative Works thereof, that is intentionally
submitted to Licensor for inclusion in the Work by the copyright owner
or by an individual or Legal Entity authorized to submit on behalf of
the copyright owner. For the purposes of this definition, "submitted"
means any form of electronic, verbal, or written communication sent
to the Licensor or its representatives, including but not limited to
communication on electronic mailing lists, source code control systems,
and issue tracking systems that are managed by, or on behalf of, the
Licensor for the purpose of discussing and improving the Work, but
excluding communication that is conspicuously marked or otherwise
designated in writing by the copyright owner as "Not a Contribution."
"Contributor" shall mean Licensor and any individual or Legal Entity
on behalf of whom a Contribution has been received by Licensor and
subsequently incorporated within the Work.
2. Grant of Copyright License. Subject to the terms and conditions of
this License, each Contributor hereby grants to You a perpetual,
worldwide, non-exclusive, no-charge, royalty-free, irrevocable
copyright license to reproduce, prepare Derivative Works of,
publicly display, publicly perform, sublicense, and distribute the
Work and such Derivative Works in Source or Object form.
3. Grant of Patent License. Subject to the terms and conditions of
this License, each Contributor hereby grants to You a perpetual,
worldwide, non-exclusive, no-charge, royalty-free, irrevocable
(except as stated in this section) patent license to make, have made,
use, offer to sell, sell, import, and otherwise transfer the Work,
where such license applies only to those patent claims licensable
by such Contributor that are necessarily infringed by their
Contribution(s) alone or by combination of their Contribution(s)
with the Work to which such Contribution(s) was submitted. If You
institute patent litigation against any entity (including a
cross-claim or counterclaim in a lawsuit) alleging that the Work
or a Contribution incorporated within the Work constitutes direct
or contributory patent infringement, then any patent licenses
granted to You under this License for that Work shall terminate
as of the date such litigation is filed.
4. Redistribution. You may reproduce and distribute copies of the
Work or Derivative Works thereof in any medium, with or without
modifications, and in Source or Object form, provided that You
meet the following conditions:
(a) You must give any other recipients of the Work or
Derivative Works a copy of this License; and
(b) You must cause any modified files to carry prominent notices
stating that You changed the files; and
(c) You must retain, in the Source form of any Derivative Works
that You distribute, all copyright, patent, trademark, and
attribution notices from the Source form of the Work,
excluding those notices that do not pertain to any part of
the Derivative Works; and
(d) If the Work includes a "NOTICE" text file as part of its
distribution, then any Derivative Works that You distribute must
include a readable copy of the attribution notices contained
within such NOTICE file, excluding those notices that do not
pertain to any part of the Derivative Works, in at least one
of the following places: within a NOTICE text file distributed
as part of the Derivative Works; within the Source form or
documentation, if provided along with the Derivative Works; or,
within a display generated by the Derivative Works, if and
wherever such third-party notices normally appear. The contents
of the NOTICE file are for informational purposes only and
do not modify the License. You may add Your own attribution
notices within Derivative Works that You distribute, alongside
or as an addendum to the NOTICE text from the Work, provided
that such additional attribution notices cannot be construed
as modifying the License.
You may add Your own copyright statement to Your modifications and
may provide additional or different license terms and conditions
for use, reproduction, or distribution of Your modifications, or
for any such Derivative Works as a whole, provided Your use,
reproduction, and distribution of the Work otherwise complies with
the conditions stated in this License.
5. Submission of Contributions. Unless You explicitly state otherwise,
any Contribution intentionally submitted for inclusion in the Work
by You to the Licensor shall be under the terms and conditions of
this License, without any additional terms or conditions.
Notwithstanding the above, nothing herein shall supersede or modify
the terms of any separate license agreement you may have executed
with Licensor regarding such Contributions.
6. Trademarks. This License does not grant permission to use the trade
names, trademarks, service marks, or product names of the Licensor,
except as required for reasonable and customary use in describing the
origin of the Work and reproducing the content of the NOTICE file.
7. Disclaimer of Warranty. Unless required by applicable law or
agreed to in writing, Licensor provides the Work (and each
Contributor provides its Contributions) on an "AS IS" BASIS,
WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or
implied, including, without limitation, any warranties or conditions
of TITLE, NON-INFRINGEMENT, MERCHANTABILITY, or FITNESS FOR A
PARTICULAR PURPOSE. You are solely responsible for determining the
appropriateness of using or redistributing the Work and assume any
risks associated with Your exercise of permissions under this License.
8. Limitation of Liability. In no event and under no legal theory,
whether in tort (including negligence), contract, or otherwise,
unless required by applicable law (such as deliberate and grossly
negligent acts) or agreed to in writing, shall any Contributor be
liable to You for damages, including any direct, indirect, special,
incidental, or consequential damages of any character arising as a
result of this License or out of the use or inability to use the
Work (including but not limited to damages for loss of goodwill,
work stoppage, computer failure or malfunction, or any and all
other commercial damages or losses), even if such Contributor
has been advised of the possibility of such damages.
9. Accepting Warranty or Additional Liability. While redistributing
the Work or Derivative Works thereof, You may choose to offer,
and charge a fee for, acceptance of support, warranty, indemnity,
or other liability obligations and/or rights consistent with this
License. However, in accepting such obligations, You may act only
on Your own behalf and on Your sole responsibility, not on behalf
of any other Contributor, and only if You agree to indemnify,
defend, and hold each Contributor harmless for any liability
incurred by, or claims asserted against, such Contributor by reason
of your accepting any such warranty or additional liability.
END OF TERMS AND CONDITIONS
APPENDIX: How to apply the Apache License to your work.
To apply the Apache License to your work, attach the following
boilerplate notice, with the fields enclosed by brackets "[]"
replaced with your own identifying information. (Don't include
the brackets!) The text should be enclosed in the appropriate
comment syntax for the file format. We also recommend that a
file or class name and description of purpose be included on the
same "printed page" as the copyright notice for easier
identification within third-party archives.
Copyright [yyyy] [name of copyright owner]
Licensed under the Apache License, Version 2.0 (the "License");
you may not use this file except in compliance with the License.
You may obtain a copy of the License at
http://www.apache.org/licenses/LICENSE-2.0
Unless required by applicable law or agreed to in writing, software
distributed under the License is distributed on an "AS IS" BASIS,
WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
See the License for the specific language governing permissions and
limitations under the License.
+1
View File
@@ -70,6 +70,7 @@
"build:swc": "swc ./src -d ./dist --config-file .swcrc --strip-leading-paths",
"build:types": "tsc --outDir dist --rootDir ./src",
"clean": "rimraf {dist,*.tsbuildinfo}",
"cookie-db:refresh": "node scripts/refresh-cookie-database.mjs",
"copyfiles": "copyfiles -u 1 \"src/**/*.{html,css,scss,ttf,woff,woff2,eot,svg,jpg,png,json}\" dist/",
"dev": "next dev dev --turbo",
"dev:generate-importmap": "pnpm dev:payload generate:importmap",
+125
View File
@@ -0,0 +1,125 @@
#!/usr/bin/env node
// Refreshes the bundled copy of the Open Cookie Database (Apache-2.0,
// https://github.com/jkwakman/Open-Cookie-Database) that the cookie scanner
// looks unknown cookie names up in. Nothing is fetched at runtime — run this,
// review the diff, commit.
//
// pnpm cookie-db:refresh # latest commit on master
// pnpm cookie-db:refresh --ref <sha>
//
// Writes:
// src/modules/consent/scanner/data/openCookieDatabase.ts (rows, source commit, date)
// docs/licenses/open-cookie-database-LICENSE.txt (the upstream license, verbatim)
import { mkdirSync, writeFileSync } from 'node:fs'
import path from 'node:path'
import { fileURLToPath } from 'node:url'
const REPO = 'jkwakman/Open-Cookie-Database'
const root = path.resolve(path.dirname(fileURLToPath(import.meta.url)), '..')
const args = process.argv.slice(2)
const refArg = args.indexOf('--ref') >= 0 ? args[args.indexOf('--ref') + 1] : undefined
async function get(url) {
const res = await fetch(url, { headers: { 'User-Agent': 'ipal-kit cookie-db refresh' } })
if (!res.ok) {throw new Error(`${url}: HTTP ${res.status}`)}
return res
}
const ref = refArg ?? (await (await get(`https://api.github.com/repos/${REPO}/commits/master`)).json()).sha
const raw = (file) => `https://raw.githubusercontent.com/${REPO}/${ref}/${file}`
const csv = await (await get(raw('open-cookie-database.csv'))).text()
const license = await (await get(raw('LICENSE'))).text()
if (!/Apache License\s+Version 2\.0/.test(license)) {
console.error('The upstream license is no longer Apache-2.0 — check it before bundling. Nothing written.')
process.exit(1)
}
/** RFC 4180 CSV: quoted fields, "" escapes, newlines inside quotes. */
function parseCsv(text) {
const rows = []
let row = []
let field = ''
let quoted = false
for (let i = 0; i < text.length; i++) {
const ch = text[i]
if (quoted) {
if (ch === '"' && text[i + 1] === '"') {field += '"'; i++}
else if (ch === '"') {quoted = false}
else {field += ch}
} else if (ch === '"') {quoted = true}
else if (ch === ',') {row.push(field); field = ''}
else if (ch === '\n' || ch === '\r') {
if (ch === '\r' && text[i + 1] === '\n') {i++}
row.push(field); field = ''
if (row.some((f) => f !== '')) {rows.push(row)}
row = []
} else {field += ch}
}
if (field || row.length) {row.push(field); rows.push(row)}
return rows
}
const [header, ...body] = parseCsv(csv)
const col = (name) => {
const i = header.findIndex((h) => h.trim().toLowerCase() === name.toLowerCase())
if (i < 0) {throw new Error(`Column "${name}" missing — the upstream CSV changed, update this script.`)}
return i
}
const C = {
category: col('Category'),
controller: col('Data Controller'),
description: col('Description'),
domain: col('Domain'),
name: col('Cookie / Data Key name'),
platform: col('Platform'),
retention: col('Retention period'),
wildcard: col('Wildcard match'),
}
const clean = (s) => (s ?? '').replace(/\s+/g, ' ').trim()
const rows = body
.map((r) => [
clean(r[C.name]),
clean(r[C.platform]),
clean(r[C.category]),
clean(r[C.domain]),
clean(r[C.description]),
clean(r[C.retention]),
clean(r[C.controller]),
clean(r[C.wildcard]) === '1' ? 1 : 0,
])
.filter((r) => r[0])
const today = new Date().toISOString().slice(0, 10)
const out = `/* eslint-disable */
// GENERATED by scripts/refresh-cookie-database.mjs — do not edit by hand.
//
// Open Cookie Database, https://github.com/${REPO}
// Commit ${ref}, fetched ${today}.
// Licensed under the Apache License, Version 2.0 — full text in
// docs/licenses/open-cookie-database-LICENSE.txt (shipped with the package).
//
// Changes made by ipal-kit: converted from open-cookie-database.csv to this
// module; the columns "ID" and "User Privacy & GDPR Rights Portals" were left
// out and whitespace was collapsed. The data is otherwise unchanged.
/** [name, platform, category, domain, description, retention, data controller, wildcard (1 = name is a prefix)] */
export type OpenCookieRow = readonly [string, string, string, string, string, string, string, 0 | 1]
export const OPEN_COOKIE_DATABASE_SOURCE = {
commit: '${ref}',
fetchedAt: '${today}',
license: 'Apache-2.0',
url: 'https://github.com/${REPO}',
} as const
export const OPEN_COOKIE_DATABASE: readonly OpenCookieRow[] = [
${rows.map((r) => ` ${JSON.stringify(r)},`).join('\n')}
]
`
const dataFile = path.join(root, 'src/modules/consent/scanner/data/openCookieDatabase.ts')
mkdirSync(path.dirname(dataFile), { recursive: true })
writeFileSync(dataFile, out)
const licenseFile = path.join(root, 'docs/licenses/open-cookie-database-LICENSE.txt')
mkdirSync(path.dirname(licenseFile), { recursive: true })
writeFileSync(licenseFile, license)
console.log(`Open Cookie Database @ ${ref.slice(0, 7)}: ${rows.length} rows → ${path.relative(root, dataFile)}`)
+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)
}
+2
View File
@@ -9,6 +9,8 @@ export { MaskedField } from '../globals/SiteIntegrations/components/MaskedField.
export { TestEmailButton } from '../globals/SiteIntegrations/components/TestEmailButton.js'
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'
+1 -1
View File
@@ -136,7 +136,7 @@ export const cookieSettingsFields: Field[] = [
type: 'array',
admin: {
description:
'Cookies the site uses — shown on the cookie policy page (<CookieTable>) and per category in the detailed settings window. Fill it from a scan: ipal-consent-check → cookie-scan.',
'Cookies the site uses — shown on the cookie policy page (<CookieTable>) and per category in the detailed settings window. Fill it from a scan: Cookie review → Scan cookies (cookieScanner option), or ipal-consent-check → cookie-scan.',
initCollapsed: true,
},
fields: [
+63
View File
@@ -51,6 +51,69 @@ export {
updateConsent,
} from './modules/consent/index.js'
export type { ConsentCategory, ConsentLogOptions, ConsentState, ConsentTexts, CookieTableRow } from './modules/consent/index.js'
// Cookie scanner — review list, scan, declarations, Open Cookie Database lookup (docs/cookie-scanner.md).
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'
export { CONSTRUCTION_NOTICE_PARAM } from './modules/construction/types.js'
@@ -0,0 +1,175 @@
'use client'
import { Button, useConfig, useTranslation } from '@payloadcms/ui'
import { useRouter } from 'next/navigation.js'
import { useEffect, useState } from 'react'
import type { CookieScanLabels } from './labels.js'
import type { CookieScanSummary } from './types.js'
import { COOKIE_SCAN_LABELS } from './labels.js'
type CrawlState = {
configured: boolean
error: null | string
finishedAt: null | string
missing: string[]
startedAt: null | string
status: 'done' | 'failed' | 'idle' | 'running'
summary: { newUnknown?: null | number; pages?: null | number; violations?: null | number } | null
}
type Status =
| { kind: 'done'; summary: CookieScanSummary }
| { kind: 'error' }
| { kind: 'idle' }
| { kind: 'scanning' }
const fill = (template: string, values: Record<string, null | number | string>) =>
template.replace(/\{(\w+)\}/g, (_, k: string) => String(values[k] ?? ''))
/**
* Admin UI above the Cookie review list (beforeListTable): shows which
* integrations a scan covers, takes optional extra cookie names, runs
* POST /api/ipal/cookie-scan and reloads the list. With `crawl`, also "Crawl
* site" (POST /api/ipal/cookie-crawl) and the latest crawl's status, polled
* while it runs. Labels in the admin language (`labels` from the collection
* config, English fallback).
*/
export function CookieScanButton({ crawl = false, labels = COOKIE_SCAN_LABELS }: { crawl?: boolean; labels?: Record<string, CookieScanLabels> }) {
const { i18n } = useTranslation()
const { config } = useConfig()
const router = useRouter()
const t = labels[i18n.language] ?? labels.en ?? COOKIE_SCAN_LABELS.en
const endpoint = `${config.serverURL ?? ''}${config.routes?.api ?? '/api'}/ipal/cookie-scan`
const [names, setNames] = useState('')
const [integrations, setIntegrations] = useState<{ key: string; label: string }[] | null>(null)
const [status, setStatus] = useState<Status>({ kind: 'idle' })
const [crawlState, setCrawlState] = useState<CrawlState | null>(null)
const [crawlStarting, setCrawlStarting] = useState(false)
const crawlEndpoint = endpoint.replace(/cookie-scan$/, 'cookie-crawl')
const when = (iso: null | string) => (iso ? new Date(iso).toLocaleString(i18n.language) : '')
useEffect(() => {
if (!crawl) {return}
let stopped = false
let wasRunning = false
const poll = async () => {
try {
const res = await fetch(crawlEndpoint, { credentials: 'include' })
const data = res.ok ? ((await res.json()) as CrawlState) : null
if (stopped || !data) {return}
setCrawlState(data)
if (wasRunning && data.status !== 'running') {router.refresh()}
wasRunning = data.status === 'running'
} catch {
// offline — try again on the next tick
}
}
void poll()
const timer = setInterval(() => void poll(), 3000)
return () => {
stopped = true
clearInterval(timer)
}
}, [crawl, crawlEndpoint, router])
const startCrawl = async () => {
setCrawlStarting(true)
try {
await fetch(crawlEndpoint, { credentials: 'include', method: 'POST' })
const res = await fetch(crawlEndpoint, { credentials: 'include' })
if (res.ok) {setCrawlState((await res.json()) as CrawlState)}
} finally {
setCrawlStarting(false)
}
}
useEffect(() => {
fetch(endpoint, { credentials: 'include' })
.then((r) => (r.ok ? r.json() : null))
.then((data: { integrations?: { key: string; label: string }[] } | null) => setIntegrations(data?.integrations ?? []))
.catch(() => setIntegrations([]))
}, [endpoint])
const scan = async () => {
setStatus({ kind: 'scanning' })
try {
const res = await fetch(endpoint, {
body: JSON.stringify({ names: names.split('\n') }),
credentials: 'include',
headers: { 'Content-Type': 'application/json' },
method: 'POST',
})
const data = (await res.json()) as { ok?: boolean; summary?: CookieScanSummary }
if (!res.ok || !data.ok || !data.summary) {throw new Error('scan failed')}
setStatus({ kind: 'done', summary: data.summary })
router.refresh()
} catch {
setStatus({ kind: 'error' })
}
}
const result = (s: CookieScanSummary) =>
t.scanResult.replace(/\{(\w+)\}/g, (_, k: string) => String(s[k as keyof CookieScanSummary] ?? ''))
return (
<div className="ipal-cookie-scan" data-ipal="cookie-scan" style={{ marginBottom: '1.5rem' }}>
<p style={{ marginTop: 0 }}>{t.scanIntro}</p>
{integrations ? (
<p style={{ fontSize: '.85rem', opacity: 0.8 }}>
{integrations.length ? `${t.integrationsFound}: ${integrations.map((i) => i.label).join(', ')}` : t.integrationsNone}
</p>
) : null}
<label className="field-label" htmlFor="ipal-cookie-scan-names">{t.namesLabel}</label>
<p style={{ fontSize: '.85rem', marginTop: 0, opacity: 0.7 }}>{t.namesHint}</p>
<textarea
aria-label={t.namesLabel}
id="ipal-cookie-scan-names"
onChange={(e) => setNames(e.target.value)}
placeholder={'_hjSessionUser_123\nintercom-id-abc'}
rows={3}
style={{ fontFamily: 'monospace', marginBottom: '.5rem', width: '100%' }}
value={names}
/>
<div style={{ alignItems: 'center', display: 'flex', flexWrap: 'wrap', gap: '1rem' }}>
<Button buttonStyle="primary" disabled={status.kind === 'scanning'} margin={false} onClick={() => void scan()} size="medium">
{status.kind === 'scanning' ? t.scanning : t.scanButton}
</Button>
{status.kind === 'done' ? <span role="status">✓ {result(status.summary)}</span> : null}
{status.kind === 'error' ? (
<span role="alert" style={{ color: 'var(--theme-error-500, crimson)' }}>✗ {t.scanError}</span>
) : null}
</div>
{crawl ? (
<div data-ipal="cookie-crawl" style={{ borderTop: '1px solid var(--theme-elevation-150, #ddd)', marginTop: '1.25rem', paddingTop: '1rem' }}>
<p style={{ marginTop: 0 }}>{t.crawlIntro}</p>
<div style={{ alignItems: 'center', display: 'flex', flexWrap: 'wrap', gap: '1rem' }}>
<Button
buttonStyle="secondary"
disabled={!crawlState?.configured || crawlState.status === 'running' || crawlStarting}
margin={false}
onClick={() => void startCrawl()}
size="medium"
>
{t.crawlButton}
</Button>
<span role="status">
{crawlState && !crawlState.configured ? `${t.crawlNotConfigured} (${crawlState.missing.join(', ')})` : null}
{crawlState?.configured && crawlState.status === 'running' ? fill(t.crawlRunning, { startedAt: when(crawlState.startedAt) }) : null}
{crawlState?.configured && crawlState.status === 'done'
? fill(t.crawlDone, { finishedAt: when(crawlState.finishedAt), newUnknown: crawlState.summary?.newUnknown ?? 0, pages: crawlState.summary?.pages ?? 0, violations: crawlState.summary?.violations ?? 0 })
: null}
{/* a finished crawl can still carry a note, e.g. "Accept all" not found */}
{crawlState?.configured && crawlState.status === 'done' && crawlState.error ? ` ⚠ ${crawlState.error}` : null}
{crawlState?.configured && crawlState.status === 'idle' ? t.crawlIdle : null}
{crawlState?.configured && crawlState.status === 'failed' ? fill(t.crawlFailed, { error: crawlState.error ?? '' }) : null}
</span>
</div>
</div>
) : null}
</div>
)
}
export default CookieScanButton
+195
View File
@@ -0,0 +1,195 @@
import type { CollectionAfterChangeHook, CollectionBeforeChangeHook, CollectionConfig, Field } from 'payload'
import type { CookieReviewValues } from './merge.js'
import type { CookieScannerOptions } from './types.js'
import { userMeetsRole } from '../../access/predicates.js'
import { CONSENT_CATEGORIES } from '../categories.js'
import { type CookieScanLabels, labelFor, labelRecord, mergeCookieScanLabels } from './labels.js'
import { addToCookieList } from './sync.js'
/**
* Cookie review list — drafts from "Scan cookies" that an editor accepts,
* edits or rejects. Accepting adds the cookie to Cookie Settings → Cookies
* (the banner's detailed window and <CookieTable>). Opt-in:
* `ipalKit({ cookieScanner: true })`.
*/
export const COOKIE_REVIEW_SLUG = 'cookie-review'
const setKey: CollectionBeforeChangeHook = ({ data, originalDoc }) => {
const name = (data.name ?? originalDoc?.name)?.trim()
const storage = data.storage ?? originalDoc?.storage ?? 'cookie'
if (name) {
data.name = name
data.key = `${storage}:${name}`
}
return data
}
function buildSyncHook(): CollectionAfterChangeHook {
return async ({ context, doc, previousDoc, req }) => {
if (context?.ipalCookieScan || doc.status !== 'accepted' || previousDoc?.status === 'accepted') {return doc}
// Local API calls with `req` rewrite req.locale / req.fallbackLocale; the editor's own
// save is still being read after this hook, so put them back.
const { fallbackLocale, locale } = req
try {
const full = (await req.payload.findByID({
id: doc.id,
collection: COOKIE_REVIEW_SLUG as never,
depth: 0,
locale: (req.payload.config.localization ? 'all' : undefined) as never,
overrideAccess: true,
req,
})) as unknown as { name: string } & CookieReviewValues
const result = await addToCookieList({ entry: full, payload: req.payload, req })
req.payload.logger.info(`[ipal] cookie review: "${full.name}" accepted → Cookie Settings (${result})`)
if (!doc.listed) {
await req.payload.update({
id: doc.id,
collection: COOKIE_REVIEW_SLUG as never,
context: { ipalCookieScan: true },
data: { listed: true } as never,
overrideAccess: true,
req,
})
}
} finally {
req.locale = locale
req.fallbackLocale = fallbackLocale
}
return { ...doc, listed: true }
}
}
export function buildCookieReviewCollection(options: CookieScannerOptions = {}): CollectionConfig {
const labels = mergeCookieScanLabels(options.labels)
const L = (key: keyof CookieScanLabels) => labelRecord(labels, key)
const crawl = Boolean(options.crawl)
// Only with `crawl`: what the latest browser crawl saw before consent (reset on every crawl).
const crawlFields: Field[] = crawl
? [
{
name: 'violation',
type: 'checkbox',
admin: { description: L('violationDescription'), position: 'sidebar', readOnly: true },
defaultValue: false,
index: true,
label: L('violation'),
},
{ name: 'violationDetail', type: 'text', admin: { position: 'sidebar', readOnly: true }, label: L('violationDetail') },
{ name: 'seenBeforeConsent', type: 'checkbox', admin: { position: 'sidebar', readOnly: true }, defaultValue: false, index: true, label: L('seenBeforeConsent') },
]
: []
return {
slug: COOKIE_REVIEW_SLUG,
access: {
// Written by editors (review) and by the scan (Local API); deleting is admin-only and never automatic.
create: ({ req }) => userMeetsRole(req, 'editor'),
delete: ({ req }) => userMeetsRole(req, 'admin'),
read: ({ req }) => userMeetsRole(req, 'editor'),
update: ({ req }) => userMeetsRole(req, 'editor'),
},
admin: {
components: {
beforeListTable: [{ clientProps: { crawl, labels }, path: '@intecion/ipal-kit/admin#CookieScanButton' }],
},
defaultColumns: ['name', 'vendor', 'category', 'status', 'source', 'listed', ...(crawl ? ['violation'] : [])],
description: L('collectionDescription'),
group: 'Settings',
listSearchableFields: ['name', 'vendor'],
useAsTitle: 'name',
},
fields: [
{
type: 'row',
fields: [
{ name: 'name', type: 'text', admin: { width: '50%' }, label: L('name'), required: true },
{
name: 'storage',
type: 'select',
admin: { width: '25%' },
defaultValue: 'cookie',
label: L('storage'),
options: [
{ label: L('cookie'), value: 'cookie' },
{ label: L('localStorage'), value: 'localStorage' },
{ label: L('sessionStorage'), value: 'sessionStorage' },
],
required: true,
},
{
name: 'category',
type: 'select',
admin: { width: '25%' },
label: L('category'),
options: CONSENT_CATEGORIES.map((c) => ({ label: L(c), value: c })),
validate: (value: unknown, { req, siblingData }: { req: { i18n?: { language?: string } }; siblingData: { status?: string } }) =>
siblingData?.status === 'accepted' && !value ? labelFor(labels, req.i18n?.language, 'categoryRequired') : true,
},
],
},
{
type: 'row',
fields: [
{ name: 'vendor', type: 'text', admin: { width: '50%' }, label: L('vendor') },
{ name: 'domain', type: 'text', admin: { width: '50%' }, label: L('domain') },
],
},
{ name: 'purpose', type: 'textarea', label: L('purpose'), localized: true },
{ name: 'retention', type: 'text', label: L('retention'), localized: true },
{
name: 'setBeforeConsent',
type: 'checkbox',
admin: { description: L('setBeforeConsentDescription') },
label: L('setBeforeConsent'),
},
{
name: 'status',
type: 'select',
admin: { description: L('statusDescription'), position: 'sidebar' },
defaultValue: 'draft',
index: true,
label: L('status'),
options: [
{ label: L('draft'), value: 'draft' },
{ label: L('accepted'), value: 'accepted' },
{ label: L('rejected'), value: 'rejected' },
],
required: true,
},
{
name: 'source',
type: 'select',
admin: { position: 'sidebar', readOnly: true },
defaultValue: 'manual',
label: L('source'),
options: [
{ label: L('integration'), value: 'integration' },
{ label: L('project'), value: 'project' },
{ label: L('database'), value: 'database' },
{ label: L('unknown'), value: 'unknown' },
{ label: L('manual'), value: 'manual' },
],
},
{ name: 'sourceDetail', type: 'text', admin: { position: 'sidebar', readOnly: true }, label: L('sourceDetail') },
{
name: 'listed',
type: 'checkbox',
admin: { description: L('listedDescription'), position: 'sidebar', readOnly: true },
label: L('listed'),
},
{ name: 'lastScannedAt', type: 'date', admin: { position: 'sidebar', readOnly: true }, label: L('lastScannedAt') },
...crawlFields,
// `storage:name`, one entry per cookie — what a rescan matches on.
{ name: 'key', type: 'text', admin: { hidden: true }, index: true, unique: true },
// The last scan's suggestion: a value still equal to it was not edited and may follow the next scan.
{ name: 'suggested', type: 'json', admin: { hidden: true } },
],
hooks: {
afterChange: options.syncAccepted === false ? [] : [buildSyncHook()],
beforeChange: [setKey],
},
labels: { plural: L('plural'), singular: L('singular') },
timestamps: true,
}
}
@@ -0,0 +1,78 @@
import type { ConsentCategory } from '../categories.js'
import type { OpenCookieRow } from './data/openCookieDatabase.js'
import type { CookieFinding, OpenCookieCategory } from './types.js'
/**
* Lookup in the bundled Open Cookie Database (Apache-2.0,
* github.com/jkwakman/Open-Cookie-Database; license in
* docs/licenses/open-cookie-database-LICENSE.txt). Refreshed by
* `scripts/refresh-cookie-database.mjs` — nothing is fetched at runtime. The
* ~430 KB table is imported only when a scan needs it.
*/
export const DEFAULT_DATABASE_CATEGORIES: Record<OpenCookieCategory, ConsentCategory> = {
Analytics: 'analytics',
// The database defines Functional as "technical, essential or strictly necessary", but
// contributors file trackers there too (Hotjar's user id). An unchecked lookup must not
// land as "no consent needed": it asks for consent until an editor says otherwise.
Functional: 'functional',
Marketing: 'marketing',
Necessary: 'necessary',
Personalization: 'functional',
Security: 'necessary',
}
/** An index over database rows: exact names, then prefixes (longest first). */
export type CookieDatabaseIndex = {
exact: Map<string, OpenCookieRow>
prefixes: OpenCookieRow[]
}
export function indexCookieDatabase(rows: readonly OpenCookieRow[]): CookieDatabaseIndex {
const exact = new Map<string, OpenCookieRow>()
const prefixes: OpenCookieRow[] = []
for (const row of rows) {
if (row[7] === 1) {prefixes.push(row)}
else if (!exact.has(row[0])) {exact.set(row[0], row)}
}
prefixes.sort((a, b) => b[0].length - a[0].length)
return { exact, prefixes }
}
let bundled: CookieDatabaseIndex | null = null
/** The bundled database, indexed once per process. */
export async function loadCookieDatabase(): Promise<CookieDatabaseIndex> {
if (!bundled) {
const { OPEN_COOKIE_DATABASE } = await import('./data/openCookieDatabase.js')
bundled = indexCookieDatabase(OPEN_COOKIE_DATABASE)
}
return bundled
}
/**
* A cookie name looked up in the database: exact name first, then the longest
* matching wildcard prefix (`_gac_` matches `_gac_UA-1`). Null when unknown.
*/
export function lookupCookie(
index: CookieDatabaseIndex,
name: string,
categories: Partial<Record<OpenCookieCategory, ConsentCategory>> = {},
): CookieFinding | null {
const row = index.exact.get(name) ?? index.prefixes.find((r) => r[0] && name.startsWith(r[0]))
if (!row) {return null}
const [pattern, platform, category, domain, description, retention, controller, wildcard] = row
const map = { ...DEFAULT_DATABASE_CATEGORIES, ...categories }
const thirdParty = /\(3rd party\)/i.test(domain) ? domain.replace(/\s*\(3rd party\)/i, '').trim() : ''
return {
category: map[category as OpenCookieCategory],
...(thirdParty ? { domain: thirdParty } : {}),
name: wildcard === 1 && pattern !== name ? `${pattern}*` : name,
...(description ? { purpose: description } : {}),
...(retention ? { retention } : {}),
source: 'database',
sourceDetail: `Open Cookie Database: ${platform}${category ? ` (${category})` : ''}`,
storage: 'cookie',
vendor: controller || platform,
}
}
@@ -0,0 +1,68 @@
import type { Payload } from 'payload'
import type { CookieScanLabels } from '../labels.js'
import { COOKIE_REVIEW_SLUG } from '../collection.js'
import { COOKIE_SCAN_LABELS, labelFor } from '../labels.js'
import { COOKIE_CRAWL_SLUG } from './config.js'
type Props = {
adminRoute?: string
/** Injected by Payload into admin server components. */
i18n?: { language?: string }
labels?: Record<string, CookieScanLabels>
payload?: Payload
}
const fill = (template: string, values: Record<string, number | string>) =>
template.replace(/\{(\w+)\}/g, (_, k: string) => String(values[k] ?? ''))
/**
* Dashboard warning (beforeDashboard) after the latest cookie crawl found
* violations or new unknown cookies, or failed. Renders nothing otherwise and
* never throws.
*/
export async function CookieCrawlAlert({ adminRoute = '/admin', i18n, labels = COOKIE_SCAN_LABELS, payload }: Props) {
if (!payload) {return null}
let doc: { error?: null | string; status?: null | string; summary?: { newUnknown?: null | number; violations?: null | number } | null }
try {
doc = (await payload.findGlobal({ slug: COOKIE_CRAWL_SLUG as never, depth: 0 })) as typeof doc
} catch {
return null
}
const t = (key: keyof CookieScanLabels) => labelFor(labels, i18n?.language, key)
const violations = doc.summary?.violations ?? 0
const newUnknown = doc.summary?.newUnknown ?? 0
const failed = doc.status === 'failed'
if (!failed && !(doc.status === 'done' && (violations || newUnknown))) {return null}
const base = `${adminRoute.replace(/\/$/, '')}/collections/${COOKIE_REVIEW_SLUG}`
const href = violations ? `${base}?where[violation][equals]=true` : base
return (
<div
data-ipal="cookie-crawl-alert"
role="alert"
style={{
background: 'var(--theme-warning-50, rgba(255, 178, 36, 0.1))',
border: '1px solid var(--theme-warning-400, #ffb224)',
borderRadius: 4,
marginBottom: '1.5rem',
padding: '1rem 1.25rem',
}}
>
{failed ? (
<strong>{fill(t('alertFailed'), { error: doc.error ?? '' })}</strong>
) : (
<>
<strong>{fill(t('alertTitle'), { newUnknown, violations })}</strong>
<p style={{ margin: '0.5rem 0 0' }}>{t('alertBody')}</p>
</>
)}
<a href={href} style={{ display: 'block', marginTop: '0.5rem' }}>
{t('alertLink')}
</a>
</div>
)
}
export default CookieCrawlAlert
@@ -0,0 +1,42 @@
import type { BasePayload } from 'payload'
import type { CookieCrawlOptions } from '../types.js'
import { DEFAULT_TRACKER_HOSTS } from './violations.js'
export const COOKIE_CRAWL_SLUG = 'cookie-crawl'
export const COOKIE_CRAWL_PATH = '/ipal/cookie-crawl'
export const COOKIE_CRAWL_RESULTS_PATH = '/ipal/cookie-crawl/results'
export const COOKIE_SCAN_URL_ENV = 'IPAL_COOKIE_SCAN_URL'
export const COOKIE_SCAN_TOKEN_ENV = 'IPAL_COOKIE_SCAN_TOKEN'
/** A crawl still "running" after this long is treated as lost (the service never called back). */
export const CRAWL_TIMEOUT_MS = 30 * 60_000
export type ResolvedCrawlConfig = {
acceptSelector: string
consentMode: 'advanced' | 'basic'
maxPages: number
/** Null when not configured — the panel says what is missing. */
serviceUrl: null | string
siteUrl: null | string
token: null | string
trackerHosts: string[]
}
const trimSlash = (v: string) => v.replace(/\/+$/, '')
/** Options + env + Payload config, read at call time (env can change between deploys, not between requests). */
export function resolveCrawlConfig(options: CookieCrawlOptions, payload: BasePayload): ResolvedCrawlConfig {
const serviceUrl = options.serviceUrl ?? process.env[COOKIE_SCAN_URL_ENV]?.trim()
const token = options.token ?? process.env[COOKIE_SCAN_TOKEN_ENV]?.trim()
const siteUrl = options.siteUrl ?? (payload.config.serverURL || process.env.NEXT_PUBLIC_SERVER_URL?.trim())
return {
acceptSelector: options.acceptSelector ?? '[data-ipal="accept"]',
consentMode: options.consentMode ?? 'advanced',
maxPages: Math.min(100, Math.max(0, Math.trunc(options.maxPages ?? 20))),
serviceUrl: serviceUrl && /^https?:\/\//.test(serviceUrl) ? trimSlash(serviceUrl) : null,
siteUrl: siteUrl && /^https?:\/\//.test(siteUrl) ? trimSlash(siteUrl) : null,
token: token && token.length >= 16 ? token : null,
trackerHosts: options.trackerHosts ? options.trackerHosts(DEFAULT_TRACKER_HOSTS) : DEFAULT_TRACKER_HOSTS,
}
}
@@ -0,0 +1,166 @@
import type { Endpoint, PayloadRequest } from 'payload'
import { createHash, randomBytes, timingSafeEqual } from 'node:crypto'
import type { CookieScanLabels } from '../labels.js'
import type { CookieCrawlOptions, CookieScanContext, CookieScannerOptions } from '../types.js'
import { userMeetsRole } from '../../../access/predicates.js'
import {
COOKIE_CRAWL_PATH,
COOKIE_CRAWL_RESULTS_PATH,
COOKIE_CRAWL_SLUG,
COOKIE_SCAN_TOKEN_ENV,
COOKIE_SCAN_URL_ENV,
CRAWL_TIMEOUT_MS,
resolveCrawlConfig,
} from './config.js'
import { finishCrawl, ingestCrawlResult } from './ingest.js'
import { parseCrawlResult } from './result.js'
type CrawlDoc = {
error?: null | string
finishedAt?: null | string
jobId?: null | string
startedAt?: null | string
startedBy?: null | string
status?: 'done' | 'failed' | 'idle' | 'running' | null
summary?: null | Record<string, null | number>
}
/** Constant-time comparison of a bearer token with the configured one. */
export function bearerMatches(header: null | string | undefined, token: null | string): boolean {
if (!token || !header?.startsWith('Bearer ')) {return false}
const a = createHash('sha256').update(header.slice(7).trim()).digest()
const b = createHash('sha256').update(token).digest()
return timingSafeEqual(a, b)
}
const isStale = (doc: CrawlDoc, now = Date.now()) =>
doc.status === 'running' && (!doc.startedAt || now - new Date(doc.startedAt).getTime() > CRAWL_TIMEOUT_MS)
/**
* GET /api/ipal/cookie-crawl → `{ configured, missing, status, startedAt, finishedAt, summary, error }`
* POST /api/ipal/cookie-crawl → asks the scanner service to crawl this site (editor, or the bearer token
* — for a Coolify scheduled task); `202`, `409` while one runs, `503` when not configured
* POST /api/ipal/cookie-crawl/results → the service's callback, bearer token only; refuses any job but the running one
*/
export function buildCookieCrawlEndpoints({
fetchImpl = fetch,
labels,
options,
plugin,
}: {
/** For tests. */
fetchImpl?: typeof fetch
labels: Record<string, CookieScanLabels>
options: CookieScannerOptions
plugin: CookieScanContext['plugin']
}): Endpoint[] {
const crawl: CookieCrawlOptions = typeof options.crawl === 'object' ? options.crawl : {}
const isStaff = async (req: PayloadRequest) =>
options.access ? Boolean(await options.access({ req })) : userMeetsRole(req, 'editor')
const read = async (req: PayloadRequest) =>
(await req.payload.findGlobal({ slug: COOKIE_CRAWL_SLUG as never, depth: 0, overrideAccess: true, req })) as CrawlDoc
const write = (req: PayloadRequest, data: Partial<CrawlDoc>) =>
req.payload.updateGlobal({ slug: COOKIE_CRAWL_SLUG as never, context: { ipalCookieScan: true }, data: data as never, depth: 0, overrideAccess: true, req })
return [
{
handler: async (req) => {
if (!(await isStaff(req))) {return Response.json({ ok: false }, { status: 403 })}
const config = resolveCrawlConfig(crawl, req.payload)
const doc = await read(req)
const stale = isStale(doc)
return Response.json({
configured: Boolean(config.serviceUrl && config.token && config.siteUrl),
error: stale ? 'Timed out — the scanner service never reported back.' : (doc.error ?? null),
finishedAt: doc.finishedAt ?? null,
missing: [
...(config.serviceUrl ? [] : [COOKIE_SCAN_URL_ENV]),
...(config.token ? [] : [COOKIE_SCAN_TOKEN_ENV]),
...(config.siteUrl ? [] : ['serverURL / NEXT_PUBLIC_SERVER_URL']),
],
ok: true,
startedAt: doc.startedAt ?? null,
status: stale ? 'failed' : (doc.status ?? 'idle'),
summary: doc.summary ?? null,
})
},
method: 'get',
path: COOKIE_CRAWL_PATH,
},
{
handler: async (req) => {
const config = resolveCrawlConfig(crawl, req.payload)
const byToken = bearerMatches(req.headers.get('authorization'), config.token)
if (!byToken && !(await isStaff(req))) {return Response.json({ ok: false }, { status: 403 })}
if (!config.serviceUrl || !config.token || !config.siteUrl) {
return Response.json({ error: 'not_configured', ok: false }, { status: 503 })
}
const doc = await read(req)
if (doc.status === 'running' && !isStale(doc)) {return Response.json({ error: 'running', ok: false }, { status: 409 })}
const jobId = randomBytes(16).toString('hex')
const user = req.user as { email?: string } | null | undefined
await write(req, { error: null, finishedAt: null, jobId, startedAt: new Date().toISOString(), startedBy: byToken ? 'schedule' : (user?.email ?? 'editor'), status: 'running' })
const api = req.payload.config.routes?.api ?? '/api'
try {
const res = await fetchImpl(`${config.serviceUrl}/crawl`, {
body: JSON.stringify({
acceptSelector: config.acceptSelector,
callbackUrl: `${config.siteUrl}${api}${COOKIE_CRAWL_RESULTS_PATH}`,
jobId,
maxPages: config.maxPages,
siteUrl: config.siteUrl,
}),
headers: { Authorization: `Bearer ${config.token}`, 'Content-Type': 'application/json' },
method: 'POST',
signal: AbortSignal.timeout(15_000),
})
if (!res.ok) {throw new Error(`scanner service answered HTTP ${res.status}`)}
} catch (err) {
const message = err instanceof Error ? err.message : String(err)
req.payload.logger.error(`[ipal] cookie crawl: could not start — ${message}`)
await write(req, { error: `Could not reach the scanner service: ${message}`, finishedAt: new Date().toISOString(), jobId: null, status: 'failed' })
return Response.json({ error: 'service_unreachable', ok: false }, { status: 502 })
}
return Response.json({ ok: true, status: 'running' }, { status: 202 })
},
method: 'post',
path: COOKIE_CRAWL_PATH,
},
{
handler: async (req) => {
const config = resolveCrawlConfig(crawl, req.payload)
if (!bearerMatches(req.headers.get('authorization'), config.token)) {return Response.json({ ok: false }, { status: 401 })}
let body: unknown
try {
body = await (req as unknown as Request).json()
} catch {
return Response.json({ ok: false }, { status: 400 })
}
const result = parseCrawlResult(body)
if (!result) {return Response.json({ ok: false }, { status: 400 })}
const doc = await read(req)
if (doc.status !== 'running' || !doc.jobId || doc.jobId !== result.jobId) {
return Response.json({ error: 'unknown_job', ok: false }, { status: 409 })
}
try {
const summary = result.ok
? await ingestCrawlResult({ config, labels, options, payload: req.payload, plugin, req, result })
: undefined
await finishCrawl({ labels, payload: req.payload, req, result, siteUrl: config.siteUrl, summary })
return Response.json({ ok: true })
} catch (err) {
const message = err instanceof Error ? err.message : String(err)
req.payload.logger.error(`[ipal] cookie crawl: saving the result failed — ${message}`)
await write(req, { error: `Saving the result failed: ${message}`, finishedAt: new Date().toISOString(), jobId: null, status: 'failed' })
return Response.json({ ok: false }, { status: 500 })
}
},
method: 'post',
path: COOKIE_CRAWL_RESULTS_PATH,
},
]
}
@@ -0,0 +1,73 @@
import type { GlobalConfig } from 'payload'
import type { CookieScanLabels } from '../labels.js'
import { userMeetsRole } from '../../../access/predicates.js'
import { labelRecord } from '../labels.js'
import { COOKIE_CRAWL_SLUG } from './config.js'
/**
* The latest crawl only (no history): status, counts, violations, third-party
* hosts, and the e-mail recipients for warnings (the only editable field —
* opt-in per site). Written by the crawl endpoints through the Local API.
*/
export function buildCookieCrawlGlobal(labels: Record<string, CookieScanLabels>): GlobalConfig {
const L = (key: keyof CookieScanLabels) => labelRecord(labels, key)
const ro = { readOnly: true }
return {
slug: COOKIE_CRAWL_SLUG,
access: {
read: ({ req }) => userMeetsRole(req, 'editor'),
update: ({ req }) => userMeetsRole(req, 'admin'),
},
admin: { description: L('crawlGlobalDescription'), group: 'Settings' },
fields: [
{
name: 'notifyEmails',
type: 'text',
admin: { description: L('notifyEmailsDescription') },
label: L('notifyEmails'),
validate: (value: null | string | undefined) => {
const list = (value ?? '').split(',').map((v) => v.trim()).filter(Boolean)
return list.every((v) => /^[^\s@]+@[^\s@][^\s.@]*\.[^\s@]+$/.test(v)) || 'Comma-separated e-mail addresses.'
},
},
{
name: 'status',
type: 'select',
admin: { ...ro, position: 'sidebar' },
defaultValue: 'idle',
label: L('crawlStatus'),
options: [
{ label: L('crawlIdle'), value: 'idle' },
{ label: L('crawlStateRunning'), value: 'running' },
{ label: L('crawlStateDone'), value: 'done' },
{ label: L('crawlStateFailed'), value: 'failed' },
],
},
{ name: 'startedAt', type: 'date', admin: { ...ro, date: { pickerAppearance: 'dayAndTime' }, position: 'sidebar' }, label: L('startedAt') },
{ name: 'finishedAt', type: 'date', admin: { ...ro, date: { pickerAppearance: 'dayAndTime' }, position: 'sidebar' }, label: L('finishedAt') },
{ name: 'startedBy', type: 'text', admin: { ...ro, position: 'sidebar' }, label: L('startedBy') },
{ name: 'error', type: 'textarea', admin: ro, label: L('crawlError') },
{
name: 'summary',
type: 'group',
admin: ro,
fields: [
{ name: 'pages', type: 'number', admin: ro, label: L('crawlPages') },
{ name: 'violations', type: 'number', admin: ro, label: L('crawlViolations') },
{ name: 'newUnknown', type: 'number', admin: ro, label: L('unknown') },
{ name: 'created', type: 'number', admin: ro },
{ name: 'updated', type: 'number', admin: ro },
],
label: false,
},
{ name: 'violations', type: 'json', admin: ro, label: L('crawlViolations') },
{ name: 'requests', type: 'json', admin: ro, label: L('crawlRequests') },
{ name: 'pages', type: 'json', admin: ro, label: L('crawlPages') },
// One-time id of the running crawl; a result with another id is refused.
{ name: 'jobId', type: 'text', admin: { hidden: true } },
],
label: L('crawlGlobal'),
}
}
+156
View File
@@ -0,0 +1,156 @@
import type { BasePayload, PayloadRequest } from 'payload'
import type { CookieScanLabels } from '../labels.js'
import type { CookieReviewEntryRef } from '../scan.js'
import type { CookieScanContext, CookieScannerOptions, CookieScanSummary } from '../types.js'
import type { ResolvedCrawlConfig } from './config.js'
import type { CrawlResult } from './result.js'
import type { CrawlViolation } from './violations.js'
import { COOKIE_REVIEW_SLUG } from '../collection.js'
import { DEFAULT_COOKIE_INTEGRATIONS } from '../integrations.js'
import { labelFor } from '../labels.js'
import { applyCookieFindings, collectCookieFindings, cookieScanContext } from '../scan.js'
import { COOKIE_CRAWL_SLUG } from './config.js'
import { sendCrawlWarning } from './notify.js'
import { findCrawlViolations } from './violations.js'
export type CrawlIngestSummary = { pages: number; violations: CrawlViolation[] } & CookieScanSummary
const fill = (template: string, values: Record<string, number | string>) =>
template.replace(/\{(\w+)\}/g, (_, k: string) => String(values[k] ?? ''))
/**
* Applies a crawl result: every cookie and storage key seen becomes (or
* updates) a draft through the same rules as "Scan cookies"; entries seen
* before consent get `seenBeforeConsent`, and those not `necessary` get
* `violation`. Flags from the previous crawl are cleared first — only the
* latest crawl counts. Status is never changed and nothing is deleted.
*/
export async function ingestCrawlResult({
config,
labels,
options,
payload,
plugin,
req,
result,
}: {
config: Pick<ResolvedCrawlConfig, 'consentMode' | 'trackerHosts'>
labels: Record<string, CookieScanLabels>
options: CookieScannerOptions
payload: BasePayload
plugin: CookieScanContext['plugin']
req?: PayloadRequest
result: Extract<CrawlResult, { ok: true }>
}): Promise<CrawlIngestSummary> {
const lang = payload.config.i18n?.fallbackLanguage
const common = { collection: COOKIE_REVIEW_SLUG as never, context: { ipalCookieScan: true }, depth: 0, overrideAccess: true, req }
await payload.update({
...common,
data: { seenBeforeConsent: false, violation: false, violationDetail: null } as never,
where: { or: [{ violation: { equals: true } }, { seenBeforeConsent: { equals: true } }] },
})
const ctx = await cookieScanContext(payload, plugin, req)
const { findings, matches } = await collectCookieFindings({
ctx,
database: options.database !== false,
databaseCategories: options.databaseCategories,
declarations: options.declarations,
integrations: options.integrations ? options.integrations(DEFAULT_COOKIE_INTEGRATIONS) : DEFAULT_COOKIE_INTEGRATIONS,
names: result.observations.map((o) => ({ name: o.name, domain: o.domain, storage: o.storage })),
})
// Only what the browser saw — declarations of integrations it did not see are not part of a crawl.
const seenKeys = new Set(result.observations.map((o) => matches.get(`${o.storage}:${o.name}`)).filter(Boolean))
const entries = new Map<string, CookieReviewEntryRef>()
const summary = await applyCookieFindings({
entries,
findings: findings.filter((f) => seenKeys.has(`${f.storage}:${f.name}`)),
payload,
req,
})
const keyOf = (o: { name: string; storage: string }) => matches.get(`${o.storage}:${o.name}`)
const violations = findCrawlViolations({
categoryOf: (o) => entries.get(keyOf(o) ?? '')?.category,
consentMode: config.consentMode,
observations: result.observations,
requests: result.requests,
trackerHosts: config.trackerHosts,
})
// Flag the review entries (one update per entry, pages merged).
const flagged = new Map<string, { pages: Set<string>; violation: boolean }>()
for (const o of result.observations.filter((x) => x.before)) {
const key = keyOf(o)
if (!key || !entries.has(key)) {continue}
const f = flagged.get(key) ?? { pages: new Set<string>(), violation: false }
o.pages.forEach((p) => f.pages.add(p))
if (violations.some((v) => v.kind === o.storage && v.name === o.name)) {f.violation = true}
flagged.set(key, f)
}
for (const [key, f] of flagged) {
const pages = [...f.pages].slice(0, 5).join(', ')
await payload.update({
...common,
id: entries.get(key)!.id,
data: {
seenBeforeConsent: true,
violation: f.violation,
violationDetail: f.violation ? fill(labelFor(labels, lang, 'beforeConsentOn'), { pages }) : null,
} as never,
})
}
return { ...summary, pages: result.pages.length, violations }
}
/** Writes the finished crawl into the `cookie-crawl` global and sends the e-mail warning when asked for. */
export async function finishCrawl({
labels,
payload,
req,
result,
siteUrl,
summary,
}: {
labels: Record<string, CookieScanLabels>
payload: BasePayload
req?: PayloadRequest
result: CrawlResult
siteUrl?: null | string
summary?: CrawlIngestSummary
}): Promise<void> {
const now = new Date().toISOString()
const common = { slug: COOKIE_CRAWL_SLUG as never, context: { ipalCookieScan: true }, depth: 0, overrideAccess: true, req }
if (!result.ok || !summary) {
await payload.updateGlobal({ ...common, data: { error: result.ok ? 'No result' : result.error, finishedAt: now, jobId: null, status: 'failed' } as never })
return
}
const doc = (await payload.updateGlobal({
...common,
data: {
// Not a failure, but the "after accept" half saw no consent — say so where the editor looks.
error: result.accepted ? null : 'The "Accept all" button was not found (acceptSelector), so the second run had no consent.',
finishedAt: now,
jobId: null,
pages: result.pages,
requests: result.requests.filter((r) => r.before || r.after).map(({ after, before, host }) => ({ after, before, host })),
status: 'done',
summary: {
created: summary.created,
newUnknown: summary.newUnknown,
pages: summary.pages,
updated: summary.updated,
violations: summary.violations.length,
},
violations: summary.violations,
} as never,
})) as { notifyEmails?: null | string }
const to = (doc.notifyEmails ?? '').split(',').map((v) => v.trim()).filter(Boolean)
if (to.length && (summary.violations.length || summary.newUnknown)) {
await sendCrawlWarning({ labels, payload, siteUrl: siteUrl ?? '', summary, to })
}
}
@@ -0,0 +1,52 @@
import type { BasePayload } from 'payload'
import type { CookieScanLabels } from '../labels.js'
import type { CrawlIngestSummary } from './ingest.js'
import { COOKIE_REVIEW_SLUG } from '../collection.js'
import { labelFor } from '../labels.js'
const esc = (v: string) => v.replace(/[&<>"']/g, (c) => `&#${c.charCodeAt(0)};`)
const fill = (template: string, values: Record<string, number | string>) =>
template.replace(/\{(\w+)\}/g, (_, k: string) => String(values[k] ?? ''))
/**
* E-mail warning after a crawl, through the project's Payload email adapter
* (`email: mailAdapter()` — the plugin's mail setup). Never throws: a failed
* send is logged and the crawl result stays saved.
*/
export async function sendCrawlWarning({
labels,
payload,
siteUrl,
summary,
to,
}: {
labels: Record<string, CookieScanLabels>
payload: BasePayload
siteUrl: string
summary: CrawlIngestSummary
to: string[]
}): Promise<boolean> {
const lang = payload.config.i18n?.fallbackLanguage
const t = (key: keyof CookieScanLabels) => labelFor(labels, lang, key)
const site = siteUrl.replace(/^https?:\/\//, '') || 'site'
const values = { newUnknown: summary.newUnknown, site, violations: summary.violations.length }
const adminUrl = `${siteUrl}${payload.config.routes?.admin ?? '/admin'}/collections/${COOKIE_REVIEW_SLUG}`
const items = summary.violations
.slice(0, 30)
.map((v) => `<li><code>${esc(v.name)}</code> (${esc(v.kind)}${v.category ? `, ${esc(v.category)}` : ''}) — ${esc(fill(t('beforeConsentOn'), { pages: v.pages.join(', ') }))}</li>`)
.join('')
const html = `<p>${esc(fill(t('emailIntro'), values))}</p>
<p><strong>${esc(fill(t('alertTitle'), values))}</strong></p>
${items ? `<ul>${items}</ul>` : ''}
<p>${esc(t('alertBody'))}</p>
<p><a href="${esc(adminUrl)}">${esc(t('alertLink'))}</a></p>`
try {
await payload.sendEmail({ html, subject: fill(t('emailSubject'), values), to })
return true
} catch (err) {
payload.logger.error(`[ipal] cookie crawl warning e-mail failed: ${err instanceof Error ? err.message : String(err)}`)
return false
}
}
@@ -0,0 +1,77 @@
import type { CookieStorage } from '../types.js'
/**
* What the scanner service sends back to the site (POST
* /api/ipal/cookie-crawl/results). The service lives in
* services/cookie-crawler; keep both sides in step.
*/
export type CrawlObservation = {
/** Set on the "after accept all" run. */
after: boolean
/** Set on the run with no consent. */
before: boolean
/** Cookie domain without the leading dot; omitted for storage keys. */
domain?: string
name: string
/** Paths where it was first seen (max 5). */
pages: string[]
storage: CookieStorage
}
export type CrawlRequest = { after: boolean; before: boolean; host: string; pages: string[] }
export type CrawlResult =
| {
/** False when the "Accept all" button was not found — the second run had no consent. */
accepted: boolean
jobId: string
observations: CrawlObservation[]
ok: true
pages: string[]
requests: CrawlRequest[]
}
| { error: string; jobId: string; ok: false }
const STORAGES = new Set<CookieStorage>(['cookie', 'localStorage', 'sessionStorage'])
const NAME = /^[^\s;,=]{1,200}$/
const HOST = /^(?=.{1,253}$)[a-z0-9-]+(?:\.[a-z0-9-]+)*$/i
const MAX_ITEMS = 2000
const MAX_PAGES = 200
const pathList = (v: unknown, max: number) =>
(Array.isArray(v) ? v : []).filter((p): p is string => typeof p === 'string' && p.length <= 2000).slice(0, max)
/** Validates the service's JSON. Anything malformed is dropped, not trusted; null = unusable. */
export function parseCrawlResult(body: unknown): CrawlResult | null {
if (!body || typeof body !== 'object') {return null}
const b = body as Record<string, unknown>
if (typeof b.jobId !== 'string' || !/^[0-9a-f]{16,64}$/.test(b.jobId)) {return null}
if (b.ok === false) {
return { error: typeof b.error === 'string' ? b.error.slice(0, 500) : 'Crawl failed', jobId: b.jobId, ok: false }
}
if (b.ok !== true) {return null}
const observations: CrawlObservation[] = []
for (const o of (Array.isArray(b.observations) ? b.observations : []).slice(0, MAX_ITEMS)) {
if (!o || typeof o !== 'object') {continue}
const x = o as Record<string, unknown>
const storage = x.storage as CookieStorage
if (typeof x.name !== 'string' || !NAME.test(x.name) || !STORAGES.has(storage)) {continue}
const domain = typeof x.domain === 'string' ? x.domain.replace(/^\./, '').toLowerCase() : ''
observations.push({
after: x.after === true,
before: x.before === true,
...(domain && HOST.test(domain) ? { domain } : {}),
name: x.name,
pages: pathList(x.pages, 5),
storage,
})
}
const requests: CrawlRequest[] = []
for (const r of (Array.isArray(b.requests) ? b.requests : []).slice(0, MAX_ITEMS)) {
if (!r || typeof r !== 'object') {continue}
const x = r as Record<string, unknown>
if (typeof x.host !== 'string' || !HOST.test(x.host)) {continue}
requests.push({ after: x.after === true, before: x.before === true, host: x.host.toLowerCase(), pages: pathList(x.pages, 5) })
}
return { accepted: b.accepted !== false, jobId: b.jobId, observations, ok: true, pages: pathList(b.pages, MAX_PAGES), requests }
}
@@ -0,0 +1,71 @@
import type { CookieStorage } from '../types.js'
import type { CrawlObservation, CrawlRequest } from './result.js'
/**
* Hosts whose requests before consent are a violation. Google's tag hosts are
* separate: with Consent Mode `advanced` (the plugin's default) the Google tag
* loads before consent with every signal denied, which is allowed; with
* `basic` nothing may reach Google before consent.
*/
export const DEFAULT_TRACKER_HOSTS = [
'analytics.tiktok.com',
'bat.bing.com',
'clarity.ms',
'connect.facebook.net',
'facebook.com',
'hotjar.com',
'licdn.com',
'linkedin.com',
'youtube.com',
]
export const GOOGLE_TAG_HOSTS = [
'doubleclick.net',
'google-analytics.com',
'googleadservices.com',
'googlesyndication.com',
'googletagmanager.com',
]
export type CrawlViolation = {
/** Consent category of the cookie or key (null = not classified yet). */
category?: null | string
kind: 'request' | CookieStorage
/** Cookie / key name, or the host for a request. */
name: string
pages: string[]
}
const hostMatches = (host: string, list: string[]) => list.some((h) => host === h || host.endsWith(`.${h}`))
/**
* Violations of one crawl: anything stored before consent whose category is not
* `necessary` (unclassified counts — the editor decides), and requests before
* consent to tracker hosts. `categoryOf` gives the review entry's category after
* the scan merged it (an editor's category wins).
*/
export function findCrawlViolations({
categoryOf,
consentMode = 'advanced',
observations,
requests,
trackerHosts = DEFAULT_TRACKER_HOSTS,
}: {
categoryOf: (o: CrawlObservation) => null | string | undefined
consentMode?: 'advanced' | 'basic'
observations: CrawlObservation[]
requests: CrawlRequest[]
trackerHosts?: string[]
}): CrawlViolation[] {
const out: CrawlViolation[] = []
for (const o of observations) {
if (!o.before) {continue}
const category = categoryOf(o) ?? null
if (category !== 'necessary') {out.push({ name: o.name, category, kind: o.storage, pages: o.pages })}
}
const hosts = consentMode === 'basic' ? [...trackerHosts, ...GOOGLE_TAG_HOSTS] : trackerHosts
for (const r of requests) {
if (r.before && hostMatches(r.host, hosts)) {out.push({ name: r.host, kind: 'request', pages: r.pages })}
}
return out
}
File diff suppressed because it is too large Load Diff
+54
View File
@@ -0,0 +1,54 @@
import type { Endpoint, PayloadRequest } from 'payload'
import type { CookieScanContext, CookieScannerOptions } from './types.js'
import { userMeetsRole } from '../../access/predicates.js'
import { DEFAULT_COOKIE_INTEGRATIONS } from './integrations.js'
import { cookieScanContext, enabledCookieIntegrations, parseCookieNames, runCookieScan } from './scan.js'
export const COOKIE_SCAN_PATH = '/ipal/cookie-scan'
/**
* GET /api/ipal/cookie-scan → `{ integrations: [{ key, label }] }` — what a scan would cover.
* POST /api/ipal/cookie-scan, body `{ names?: string[] | string }` → runs a scan,
* `{ ok, summary: { created, updated, unchanged, unknown }, integrations }`.
* Editors and up by default (`cookieScanner.access`).
*/
export function buildCookieScanEndpoints(options: CookieScannerOptions, plugin: CookieScanContext['plugin']): Endpoint[] {
const allowed = async (req: PayloadRequest) =>
options.access ? Boolean(await options.access({ req })) : userMeetsRole(req, 'editor')
const integrations = options.integrations ? options.integrations(DEFAULT_COOKIE_INTEGRATIONS) : DEFAULT_COOKIE_INTEGRATIONS
const list = (items: { key: string; label: string }[]) => items.map(({ key, label }) => ({ key, label }))
return [
{
handler: async (req) => {
if (!(await allowed(req))) {return Response.json({ ok: false }, { status: 403 })}
const enabled = await enabledCookieIntegrations(integrations, await cookieScanContext(req.payload, plugin, req))
return Response.json({ integrations: list(enabled), ok: true })
},
method: 'get',
path: COOKIE_SCAN_PATH,
},
{
handler: async (req) => {
if (!(await allowed(req))) {return Response.json({ ok: false }, { status: 403 })}
let body: { names?: unknown } = {}
try {
body = ((await (req as unknown as Request).json()) ?? {}) as { names?: unknown }
} catch {
// empty body = scan without extra names
}
try {
const { enabled, summary } = await runCookieScan({ names: parseCookieNames(body.names), options, payload: req.payload, plugin, req })
return Response.json({ integrations: list(enabled), ok: true, summary })
} catch (err) {
req.payload.logger.error(`[ipal] cookie scan failed: ${err instanceof Error ? err.message : String(err)}`)
return Response.json({ ok: false }, { status: 500 })
}
},
method: 'post',
path: COOKIE_SCAN_PATH,
},
]
}
+44
View File
@@ -0,0 +1,44 @@
// Cookie scanner — server-safe building blocks. The admin button is in /admin.
export { buildCookieReviewCollection, COOKIE_REVIEW_SLUG } from './collection.js'
export { DEFAULT_DATABASE_CATEGORIES, indexCookieDatabase, loadCookieDatabase, lookupCookie } from './cookieDatabase.js'
export type { CookieDatabaseIndex } from './cookieDatabase.js'
export {
COOKIE_CRAWL_PATH,
COOKIE_CRAWL_RESULTS_PATH,
COOKIE_CRAWL_SLUG,
COOKIE_SCAN_TOKEN_ENV,
COOKIE_SCAN_URL_ENV,
resolveCrawlConfig,
} from './crawl/config.js'
export type { ResolvedCrawlConfig } from './crawl/config.js'
export { bearerMatches, buildCookieCrawlEndpoints } from './crawl/endpoints.js'
export { buildCookieCrawlGlobal } from './crawl/global.js'
export { finishCrawl, ingestCrawlResult } from './crawl/ingest.js'
export type { CrawlIngestSummary } from './crawl/ingest.js'
export { sendCrawlWarning } from './crawl/notify.js'
export { parseCrawlResult } from './crawl/result.js'
export type { CrawlObservation, CrawlRequest, CrawlResult } from './crawl/result.js'
export { DEFAULT_TRACKER_HOSTS, findCrawlViolations, GOOGLE_TAG_HOSTS } from './crawl/violations.js'
export type { CrawlViolation } from './crawl/violations.js'
export { buildCookieScanEndpoints, COOKIE_SCAN_PATH } from './endpoint.js'
export { cookieNameMatches, DEFAULT_COOKIE_INTEGRATIONS } from './integrations.js'
export { COOKIE_SCAN_LABELS, mergeCookieScanLabels } from './labels.js'
export type { CookieScanLabels } from './labels.js'
export { mergeCookieReview, suggestionFor } from './merge.js'
export type { CookieReviewValues } from './merge.js'
export { applyCookieFindings, collectCookieFindings, cookieScanContext, parseCookieNames, runCookieScan } from './scan.js'
export type { CookieObservation, CookieReviewEntryRef } from './scan.js'
export { addToCookieList } from './sync.js'
export type {
CookieCrawlOptions,
CookieDeclaration,
CookieFinding,
CookieFindingSource,
CookieIntegration,
CookieScanContext,
CookieScannerOptions,
CookieScanSummary,
CookieStorage,
LocalizedText,
OpenCookieCategory,
} from './types.js'
+292
View File
@@ -0,0 +1,292 @@
import type { CookieDeclaration, CookieIntegration, CookieScanContext } from './types.js'
import { validAnalyticsId } from '../../analytics/idFormats.js'
import { LOCALE_COOKIE_NAME } from '../../i18n/negotiateLocale.js'
import { getTurnstileConfig } from '../../turnstile/config.js'
import { CONSENT_COOKIE } from '../storage.js'
/** A tag ID from Site Integrations is filled in and valid. */
const hasId = (field: string) => (ctx: CookieScanContext) =>
Boolean(validAnalyticsId(field as never, ctx.integrations[field]))
const T = (en: string, pl: string) => ({ en, pl })
const SESSION = T('Session', 'Sesja')
const days = (n: number) => T(`${n} days`, `${n} dni`)
const months = (n: number) => T(`${n} months`, `${n} mies.`)
const YEAR = T('1 year', '1 rok')
const TWO_YEARS = T('2 years', '2 lata')
const SITE = 'This site'
/**
* Cookies of everything the plugin itself injects — one place per integration.
* Each one is part of a scan only when this project switches it on (an ID in
* Site Integrations, a plugin option). Change the list with
* `cookieScanner.integrations: (defaults) => …`.
*/
export const DEFAULT_COOKIE_INTEGRATIONS: CookieIntegration[] = [
{
declarations: [
{
name: CONSENT_COOKIE,
category: 'necessary',
purpose: T('Stores your cookie consent decision.', 'Zapamiętuje Twoją decyzję w sprawie plików cookie.'),
retention: months(6),
setBeforeConsent: false,
vendor: SITE,
},
],
isEnabled: () => true,
key: 'consent',
label: 'Cookie banner',
},
{
declarations: (ctx) => [
{
name: `${ctx.payload.config.cookiePrefix ?? 'payload'}-token`,
category: 'necessary',
purpose: T('Session of a logged-in editor (admin panel only).', 'Sesja zalogowanego redaktora (tylko panel administracyjny).'),
retention: T('Until logout (2 hours by default)', 'Do wylogowania (domyślnie 2 godziny)'),
setBeforeConsent: true,
vendor: SITE,
},
],
isEnabled: () => true,
key: 'admin',
label: 'Admin panel login',
},
{
declarations: [
{
name: LOCALE_COOKIE_NAME,
category: 'functional',
purpose: T('Remembers the selected site language.', 'Zapamiętuje wybrany język strony.'),
retention: SESSION,
setBeforeConsent: false,
vendor: SITE,
},
],
isEnabled: (ctx) => ctx.plugin.localeCount > 1,
key: 'locale',
label: 'Language choice',
},
{
declarations: [
{
name: 'ipal_vid', // VISITOR_COOKIE — that file is a client component
category: 'analytics',
purpose: T(
'Built-in statistics: random visitor id that joins your visits across days. Set only with analytics consent.',
'Wbudowane statystyki: losowy identyfikator łączący Twoje wizyty z różnych dni. Tylko po zgodzie na analitykę.',
),
retention: months(6),
setBeforeConsent: false,
vendor: SITE,
},
],
isEnabled: (ctx) => ctx.plugin.stats,
key: 'stats',
label: 'Built-in statistics',
},
{
declarations: [
{
name: '_ga',
category: 'analytics',
purpose: T('Google Analytics: distinguishes users in statistics.', 'Google Analytics: rozróżnia użytkowników w statystykach.'),
retention: TWO_YEARS,
setBeforeConsent: false,
vendor: 'Google',
},
{
name: '_ga_*',
category: 'analytics',
purpose: T('Google Analytics: keeps the session state.', 'Google Analytics: przechowuje stan sesji.'),
retention: TWO_YEARS,
setBeforeConsent: false,
vendor: 'Google',
},
],
isEnabled: hasId('ga4MeasurementId'),
key: 'ga4',
label: 'Google Analytics 4',
},
{
// GTM itself sets no cookie; its tags do. The Conversion Linker (Google Ads)
// is the usual one — anything else the container fires shows up in a crawl.
declarations: [
{
name: '_gcl_*',
category: 'marketing',
purpose: T(
'Google Ads (via Google Tag Manager): attributes conversions to ad clicks.',
'Google Ads (przez Google Tag Manager): przypisuje konwersje do kliknięć reklam.',
),
retention: months(3),
setBeforeConsent: false,
vendor: 'Google',
},
],
isEnabled: hasId('gtmContainerId'),
key: 'gtm',
label: 'Google Tag Manager',
},
{
declarations: [
{
name: '_fbp',
category: 'marketing',
purpose: T('Meta Pixel: ad measurement and targeting.', 'Meta Pixel: pomiar i dopasowanie reklam.'),
retention: months(3),
setBeforeConsent: false,
vendor: 'Meta',
},
{
name: '_fbc',
category: 'marketing',
purpose: T('Meta Pixel: stores the last ad click.', 'Meta Pixel: zapamiętuje ostatnie kliknięcie reklamy.'),
retention: months(3),
setBeforeConsent: false,
vendor: 'Meta',
},
],
isEnabled: hasId('metaPixelId'),
key: 'metaPixel',
label: 'Meta Pixel',
},
{
declarations: [
{
name: '_clck',
category: 'analytics',
purpose: T('Clarity: user id for behaviour analytics.', 'Clarity: identyfikator użytkownika w analizie zachowań.'),
retention: YEAR,
setBeforeConsent: false,
vendor: 'Microsoft Clarity',
},
{
name: '_clsk',
category: 'analytics',
purpose: T('Clarity: joins page views into one session.', 'Clarity: łączy odsłony w jedną sesję.'),
retention: T('1 day', '1 dzień'),
setBeforeConsent: false,
vendor: 'Microsoft Clarity',
},
{
name: 'CLID',
category: 'analytics',
domain: 'clarity.ms',
purpose: T('Clarity: user id across sites using Clarity.', 'Clarity: identyfikator użytkownika między stronami z Clarity.'),
retention: YEAR,
setBeforeConsent: false,
vendor: 'Microsoft Clarity',
},
{
name: 'MUID',
category: 'marketing',
domain: 'clarity.ms',
purpose: T('Microsoft: browser id used across Microsoft services and ads.', 'Microsoft: identyfikator przeglądarki w usługach i reklamach Microsoft.'),
retention: YEAR,
setBeforeConsent: false,
vendor: 'Microsoft',
},
],
isEnabled: hasId('clarityProjectId'),
key: 'clarity',
label: 'Microsoft Clarity',
},
{
declarations: [
{
name: 'li_fat_id',
category: 'marketing',
purpose: T('LinkedIn Insight Tag: conversion attribution.', 'LinkedIn Insight Tag: przypisanie konwersji.'),
retention: days(30),
setBeforeConsent: false,
vendor: 'LinkedIn',
},
{
name: 'bcookie',
category: 'marketing',
domain: 'linkedin.com',
purpose: T('LinkedIn: browser id.', 'LinkedIn: identyfikator przeglądarki.'),
retention: YEAR,
setBeforeConsent: false,
vendor: 'LinkedIn',
},
{
name: 'lidc',
category: 'marketing',
domain: 'linkedin.com',
purpose: T('LinkedIn: data-centre routing.', 'LinkedIn: wybór centrum danych.'),
retention: T('1 day', '1 dzień'),
setBeforeConsent: false,
vendor: 'LinkedIn',
},
{
name: 'UserMatchHistory',
category: 'marketing',
domain: 'linkedin.com',
purpose: T('LinkedIn Ads: id sync with ad partners.', 'LinkedIn Ads: synchronizacja identyfikatorów z partnerami reklamowymi.'),
retention: days(30),
setBeforeConsent: false,
vendor: 'LinkedIn',
},
],
isEnabled: hasId('linkedInPartnerId'),
key: 'linkedIn',
label: 'LinkedIn Insight Tag',
},
{
declarations: [
{
name: '_ttp',
category: 'marketing',
purpose: T('TikTok Pixel: ad measurement.', 'TikTok Pixel: pomiar reklam.'),
retention: months(13),
setBeforeConsent: false,
vendor: 'TikTok',
},
{
name: '_tt_enable_cookie',
category: 'marketing',
purpose: T('TikTok Pixel: checks that cookies work.', 'TikTok Pixel: sprawdza, czy cookies działają.'),
retention: months(13),
setBeforeConsent: false,
vendor: 'TikTok',
},
],
isEnabled: hasId('tiktokPixelId'),
key: 'tiktok',
label: 'TikTok Pixel',
},
{
// Turnstile hands back a one-time token; cf_clearance appears only when the
// widget has pre-clearance switched on in the Cloudflare dashboard.
declarations: [
{
name: 'cf_clearance',
category: 'necessary',
purpose: T(
'Cloudflare Turnstile: proves the anti-spam check was passed (only with pre-clearance on).',
'Cloudflare Turnstile: potwierdza przejście zabezpieczenia antyspamowego (tylko z włączonym pre-clearance).',
),
retention: T('30 minutes (set in Cloudflare)', '30 minut (ustawiane w Cloudflare)'),
setBeforeConsent: true,
vendor: 'Cloudflare',
},
],
isEnabled: async (ctx) => (await getTurnstileConfig(ctx.payload)).enabled,
key: 'turnstile',
label: 'Cloudflare Turnstile',
},
]
/** An integration's declarations for this project. */
export function declarationsOf(integration: CookieIntegration, ctx: CookieScanContext): CookieDeclaration[] {
return typeof integration.declarations === 'function' ? integration.declarations(ctx) : integration.declarations
}
/** True when `name` matches `pattern` (a trailing `*` = prefix). */
export function cookieNameMatches(pattern: string, name: string): boolean {
return pattern.endsWith('*') ? name.startsWith(pattern.slice(0, -1)) : name === pattern
}
+267
View File
@@ -0,0 +1,267 @@
/**
* Admin labels of the cookie scanner, per admin language. Payload picks the
* user's admin language from a `{ en, pl }` record; a language missing here falls
* back to English. Projects add or change languages with `cookieScanner.labels`.
*/
export type CookieScanLabels = {
accepted: string
alertBody: string
alertFailed: string
alertLink: string
alertTitle: string
analytics: string
beforeConsentOn: string
category: string
categoryRequired: string
collectionDescription: string
cookie: string
crawlButton: string
crawlDone: string
crawlError: string
crawlFailed: string
crawlGlobal: string
crawlGlobalDescription: string
crawlIdle: string
crawlIntro: string
crawlNotConfigured: string
crawlPages: string
crawlRequests: string
crawlRunning: string
crawlStateDone: string
crawlStateFailed: string
crawlStateRunning: string
crawlStatus: string
crawlViolations: string
database: string
domain: string
draft: string
emailIntro: string
emailSubject: string
finishedAt: string
functional: string
integration: string
integrationsFound: string
integrationsNone: string
lastScannedAt: string
listed: string
listedDescription: string
localStorage: string
manual: string
marketing: string
name: string
namesHint: string
namesLabel: string
necessary: string
notifyEmails: string
notifyEmailsDescription: string
plural: string
project: string
purpose: string
rejected: string
retention: string
scanButton: string
scanError: string
scanIntro: string
scanning: string
/** `{created}`, `{updated}`, `{unchanged}`, `{unknown}` are filled in. */
scanResult: string
seenBeforeConsent: string
sessionStorage: string
setBeforeConsent: string
setBeforeConsentDescription: string
singular: string
source: string
sourceDetail: string
startedAt: string
startedBy: string
status: string
statusDescription: string
storage: string
unknown: string
vendor: string
violation: string
violationDescription: string
violationDetail: string
}
export const COOKIE_SCAN_LABELS: Record<'en' | 'pl', CookieScanLabels> = {
en: {
name: 'Name',
accepted: 'Accepted',
alertBody: 'Non-necessary cookies or trackers load before consent, or the site sets cookies nobody has described yet. Check the review list.',
alertFailed: 'Cookie crawl failed: {error}',
alertLink: 'Open Cookie review →',
alertTitle: 'Cookie crawl: {violations} violations, {newUnknown} new unknown cookies.',
analytics: 'Analytics',
beforeConsentOn: 'before consent on {pages}',
category: 'Category',
categoryRequired: 'Pick a category before accepting.',
collectionDescription:
'Cookies found by "Scan cookies". Check each draft, then set it to Accepted (it is added to Cookie Settings → Cookies) or Rejected. A scan never deletes entries and never changes text you edited.',
cookie: 'Cookie',
crawlButton: 'Crawl site',
crawlDone: 'Last crawl {finishedAt}: {pages} pages, {violations} violations, {newUnknown} new unknown.',
crawlError: 'Error',
crawlFailed: 'The last crawl failed: {error}',
crawlGlobal: 'Cookie crawl',
crawlGlobalDescription: 'The latest browser crawl only. Start one from Cookie review → Crawl site.',
crawlIdle: 'Never run',
crawlIntro: 'Opens the site in a browser twice — without consent and after "Accept all" — and records cookies, storage and third-party requests. New findings become drafts.',
crawlNotConfigured: 'The crawl needs IPAL_COOKIE_SCAN_URL and IPAL_COOKIE_SCAN_TOKEN on the server.',
crawlPages: 'Pages crawled',
crawlRequests: 'Third-party requests',
crawlRunning: 'Crawling… started {startedAt}.',
crawlStateDone: 'Done',
crawlStateFailed: 'Failed',
crawlStateRunning: 'Running',
crawlStatus: 'Status',
crawlViolations: 'Violations',
database: 'Open Cookie Database',
domain: 'Domain',
draft: 'Draft',
emailIntro: 'The latest cookie crawl of {site} found:',
emailSubject: 'Cookie crawl of {site}: {violations} violations, {newUnknown} new unknown',
finishedAt: 'Finished',
functional: 'Functional',
integration: 'Plugin integration',
integrationsFound: 'Integrations in use',
integrationsNone: 'No integration with cookies is switched on.',
lastScannedAt: 'Last seen by a scan',
listed: 'In the cookie list',
listedDescription: 'Already in Cookie Settings → Cookies.',
localStorage: 'Local storage',
manual: 'Added by hand',
marketing: 'Marketing',
namesHint: 'Optional: cookie names seen in the browser (DevTools → Application → Cookies), one per line. They are looked up in the plugin and the Open Cookie Database.',
namesLabel: 'More cookie names',
necessary: 'Necessary',
notifyEmails: 'E-mail warnings to',
notifyEmailsDescription: 'Comma-separated addresses. After a crawl with violations or new unknown cookies, a warning is sent through the site\'s mail setup. Empty = no e-mail.',
plural: 'Cookie review',
project: 'Project declaration',
purpose: 'Purpose',
rejected: 'Rejected',
retention: 'Retention',
scanButton: 'Scan cookies',
scanError: 'The scan failed.',
scanIntro: 'Lists the cookies of the integrations switched on in this project as drafts to review.',
scanning: 'Scanning…',
scanResult: '{created} new, {updated} updated, {unchanged} unchanged, {unknown} unknown.',
seenBeforeConsent: 'Seen before consent',
sessionStorage: 'Session storage',
setBeforeConsent: 'Set before consent',
setBeforeConsentDescription: 'May be set before the visitor decides. Only necessary cookies should be.',
singular: 'Cookie review entry',
source: 'Found by',
sourceDetail: 'Source',
startedAt: 'Started',
startedBy: 'Started by',
status: 'Status',
statusDescription: 'Accepted → added to Cookie Settings → Cookies. Rejecting never removes a row from that list.',
storage: 'Stored in',
unknown: 'Unknown — fill in',
vendor: 'Provider',
violation: 'Violation',
violationDescription: 'Seen before consent in the latest crawl and not necessary.',
violationDetail: 'Violation details',
},
pl: {
name: 'Nazwa',
accepted: 'Zaakceptowany',
alertBody: 'Cookies lub skrypty śledzące, które nie są niezbędne, ładują się przed zgodą — albo strona ustawia cookies, których nikt jeszcze nie opisał. Sprawdź listę przeglądu.',
alertFailed: 'Skan cookies się nie powiódł: {error}',
alertLink: 'Otwórz Przegląd cookies →',
alertTitle: 'Skan cookies: naruszeń {violations}, nowych nieznanych cookies {newUnknown}.',
analytics: 'Analityczne',
beforeConsentOn: 'przed zgodą na {pages}',
category: 'Kategoria',
categoryRequired: 'Wybierz kategorię przed akceptacją.',
collectionDescription:
'Pliki cookie znalezione przez „Skanuj cookies”. Sprawdź każdy szkic i ustaw Zaakceptowany (trafi do Ustawień cookies → Cookies) albo Odrzucony. Skan nigdy nie usuwa wpisów ani nie zmienia poprawionych przez Ciebie tekstów.',
cookie: 'Cookie',
crawlButton: 'Przeskanuj stronę',
crawlDone: 'Ostatni skan {finishedAt}: stron {pages}, naruszeń {violations}, nowych nieznanych {newUnknown}.',
crawlError: 'Błąd',
crawlFailed: 'Ostatni skan się nie powiódł: {error}',
crawlGlobal: 'Skan cookies przeglądarką',
crawlGlobalDescription: 'Tylko ostatni skan przeglądarką. Uruchom go w Przeglądzie cookies → Przeskanuj stronę.',
crawlIdle: 'Nie uruchamiano',
crawlIntro: 'Otwiera stronę w przeglądarce dwa razy — bez zgody i po „Akceptuj wszystkie” — i zapisuje cookies, pamięć przeglądarki i zapytania do zewnętrznych serwisów. Nowe znaleziska trafiają jako szkice.',
crawlNotConfigured: 'Skan przeglądarką wymaga IPAL_COOKIE_SCAN_URL i IPAL_COOKIE_SCAN_TOKEN na serwerze.',
crawlPages: 'Przeskanowane strony',
crawlRequests: 'Zapytania do zewnętrznych serwisów',
crawlRunning: 'Skanowanie… rozpoczęte {startedAt}.',
crawlStateDone: 'Gotowe',
crawlStateFailed: 'Błąd',
crawlStateRunning: 'W toku',
crawlStatus: 'Status',
crawlViolations: 'Naruszenia',
database: 'Open Cookie Database',
domain: 'Domena',
draft: 'Szkic',
emailIntro: 'Ostatni skan cookies strony {site} znalazł:',
emailSubject: 'Skan cookies {site}: naruszeń {violations}, nowych nieznanych {newUnknown}',
finishedAt: 'Zakończony',
functional: 'Funkcjonalne',
integration: 'Integracja wtyczki',
integrationsFound: 'Używane integracje',
integrationsNone: 'Żadna integracja z plikami cookie nie jest włączona.',
lastScannedAt: 'Ostatnio widziany w skanie',
listed: 'Na liście cookies',
listedDescription: 'Już jest w Ustawieniach cookies → Cookies.',
localStorage: 'Local storage',
manual: 'Dodany ręcznie',
marketing: 'Marketingowe',
namesHint: 'Opcjonalnie: nazwy cookies widoczne w przeglądarce (DevTools → Application → Cookies), po jednej w wierszu. Zostaną wyszukane we wtyczce i w Open Cookie Database.',
namesLabel: 'Dodatkowe nazwy cookies',
necessary: 'Niezbędne',
notifyEmails: 'Ostrzeżenia e-mail do',
notifyEmailsDescription: 'Adresy po przecinku. Po skanie z naruszeniami lub nowymi nieznanymi cookies wysyłane jest ostrzeżenie przez konfigurację poczty strony. Puste = bez e-maili.',
plural: 'Przegląd cookies',
project: 'Deklaracja projektu',
purpose: 'Cel',
rejected: 'Odrzucony',
retention: 'Czas przechowywania',
scanButton: 'Skanuj cookies',
scanError: 'Skan się nie powiódł.',
scanIntro: 'Dodaje cookies integracji włączonych w tym projekcie jako szkice do przejrzenia.',
scanning: 'Skanowanie…',
scanResult: 'Nowe: {created}, zaktualizowane: {updated}, bez zmian: {unchanged}, nieznane: {unknown}.',
seenBeforeConsent: 'Widoczny przed zgodą',
sessionStorage: 'Session storage',
setBeforeConsent: 'Ustawiany przed zgodą',
setBeforeConsentDescription: 'Może powstać, zanim odwiedzający zdecyduje. Tylko niezbędne cookies powinny.',
singular: 'Wpis przeglądu cookies',
source: 'Źródło',
sourceDetail: 'Skąd',
startedAt: 'Rozpoczęty',
startedBy: 'Uruchomił',
status: 'Status',
statusDescription: 'Zaakceptowany → trafia do Ustawień cookies → Cookies. Odrzucenie nigdy nie usuwa wiersza z tej listy.',
storage: 'Przechowywany w',
unknown: 'Nieznany — uzupełnij',
vendor: 'Dostawca',
violation: 'Naruszenie',
violationDescription: 'Widoczny przed zgodą w ostatnim skanie i nie jest niezbędny.',
violationDetail: 'Szczegóły naruszenia',
},
}
/** Plugin labels with the project's languages and changes merged over them. */
export function mergeCookieScanLabels(overrides: Record<string, Partial<CookieScanLabels>> = {}): Record<string, CookieScanLabels> {
const out: Record<string, CookieScanLabels> = { ...COOKIE_SCAN_LABELS }
for (const [lang, labels] of Object.entries(overrides)) {
out[lang] = { ...(out[lang] ?? COOKIE_SCAN_LABELS.en), ...labels }
}
return out
}
/** One label as a Payload `{ en, pl, … }` record. */
export function labelRecord(labels: Record<string, CookieScanLabels>, key: keyof CookieScanLabels): Record<string, string> {
return Object.fromEntries(Object.entries(labels).map(([lang, l]) => [lang, l[key]]))
}
/** One label in one language (English when the language is missing). */
export function labelFor(labels: Record<string, CookieScanLabels>, lang: string | undefined, key: keyof CookieScanLabels): string {
return (lang && labels[lang]?.[key]) || labels.en?.[key] || COOKIE_SCAN_LABELS.en[key]
}
+82
View File
@@ -0,0 +1,82 @@
import type { ConsentCategory } from '../categories.js'
import type { CookieFinding, LocalizedText } from './types.js'
/** The editable values of a review entry; `purpose` / `retention` per locale. */
export type CookieReviewValues = {
category?: ConsentCategory | null
domain?: null | string
purpose?: Record<string, null | string>
retention?: Record<string, null | string>
setBeforeConsent?: boolean | null
vendor?: null | string
}
const SCALARS = ['category', 'domain', 'setBeforeConsent', 'vendor'] as const
const TEXTS = ['purpose', 'retention'] as const
/** Text for one locale: that language, else English, else the first one given. */
export function textFor(text: LocalizedText | undefined, locale: string): string | undefined {
if (text === undefined) {return undefined}
if (typeof text === 'string') {return text}
return text[locale] ?? text.en ?? Object.values(text)[0]
}
/** What a scan suggests for an entry, resolved for the project's locales. */
export function suggestionFor(finding: CookieFinding, locales: string[]): CookieReviewValues {
const perLocale = (text: LocalizedText | undefined) => {
if (text === undefined) {return undefined}
return Object.fromEntries(locales.map((l) => [l, textFor(text, l) ?? null]))
}
const out: CookieReviewValues = {}
if (finding.category) {out.category = finding.category}
if (finding.domain) {out.domain = finding.domain}
if (finding.vendor) {out.vendor = finding.vendor}
if (typeof finding.setBeforeConsent === 'boolean') {out.setBeforeConsent = finding.setBeforeConsent}
const purpose = perLocale(finding.purpose)
const retention = perLocale(finding.retention)
if (purpose) {out.purpose = purpose}
if (retention) {out.retention = retention}
return out
}
const isEmpty = (v: unknown) => v === undefined || v === null || v === ''
/**
* New values for an entry after a scan. A value takes the new suggestion only
* while it is empty or still equal to what the previous scan suggested — once an
* editor changed it, it is theirs and stays. Text is compared per locale.
*/
export function mergeCookieReview(
current: CookieReviewValues,
previous: CookieReviewValues | null | undefined,
next: CookieReviewValues,
): { changed: boolean; values: CookieReviewValues } {
const prev = previous ?? {}
const values: CookieReviewValues = { ...current }
let changed = false
const pick = <V>(cur: V, before: undefined | V, suggested: undefined | V): V => {
if (suggested === undefined || isEmpty(suggested)) {return cur}
if (isEmpty(cur) || cur === before) {return suggested}
return cur
}
for (const key of SCALARS) {
const v = pick(current[key], prev[key], next[key])
if (v !== current[key]) {
;(values as Record<string, unknown>)[key] = v
changed = true
}
}
for (const key of TEXTS) {
const cur = current[key] ?? {}
const merged = { ...cur }
for (const [locale, suggested] of Object.entries(next[key] ?? {})) {
const v = pick(cur[locale], prev[key]?.[locale], suggested)
if (v !== cur[locale]) {
merged[locale] = v ?? null
changed = true
}
}
if (Object.keys(merged).length) {values[key] = merged}
}
return { changed, values }
}
+282
View File
@@ -0,0 +1,282 @@
import type { BasePayload, PayloadRequest } from 'payload'
import type { CookieReviewValues } from './merge.js'
import type {
CookieDeclaration,
CookieFinding,
CookieIntegration,
CookieScanContext,
CookieScannerOptions,
CookieScanSummary,
CookieStorage,
} from './types.js'
import { COOKIE_REVIEW_SLUG } from './collection.js'
import { loadCookieDatabase, lookupCookie } from './cookieDatabase.js'
import { cookieNameMatches, declarationsOf, DEFAULT_COOKIE_INTEGRATIONS } from './integrations.js'
import { mergeCookieReview, suggestionFor } from './merge.js'
/** Most names one scan looks up — the panel field is for a handful, not a dump. */
export const MAX_SCAN_NAMES = 200
/** Cookie / storage key names as browsers allow them: no spaces, `;`, `,` or `=`. */
const NAME = /^[^\s;,=]{1,200}$/
/** Names from the panel's text box: trimmed, de-duplicated, invalid ones dropped. */
export function parseCookieNames(input: unknown): string[] {
const list = Array.isArray(input) ? input : typeof input === 'string' ? input.split(/[\n,]/) : []
const out = new Set<string>()
for (const raw of list) {
if (typeof raw !== 'string') {continue}
const name = raw.trim()
if (NAME.test(name)) {out.add(name)}
if (out.size >= MAX_SCAN_NAMES) {break}
}
return [...out]
}
const reviewKey = (storage: CookieStorage, name: string) => `${storage}:${name}`
function fromDeclaration(d: CookieDeclaration, source: 'integration' | 'project', sourceDetail: string): CookieFinding {
return {
category: d.category,
...(d.domain ? { domain: d.domain } : {}),
name: d.name,
purpose: d.purpose,
retention: d.retention,
setBeforeConsent: d.setBeforeConsent,
source,
sourceDetail,
storage: d.storage ?? 'cookie',
vendor: d.vendor,
}
}
/** The integrations this project uses (a failing check counts as off and is logged). */
export async function enabledCookieIntegrations(
integrations: CookieIntegration[],
ctx: CookieScanContext,
): Promise<CookieIntegration[]> {
const on: CookieIntegration[] = []
for (const integration of integrations) {
try {
if (await integration.isEnabled(ctx)) {on.push(integration)}
} catch (err) {
ctx.payload.logger.warn(`[ipal] cookie scan: could not check "${integration.key}": ${err instanceof Error ? err.message : String(err)}`)
}
}
return on
}
/** A name seen somewhere: in the panel's text box (a string) or by a crawl (with storage and domain). */
export type CookieObservation = { domain?: string; name: string; storage?: CookieStorage } | string
/**
* Everything a scan reports, before anything is written: the cookies of the
* enabled integrations, the project's declarations, and each extra name looked
* up in the project's declarations, every built-in integration, then the Open
* Cookie Database. A name nothing knows comes back with `source: 'unknown'`.
* `matches` maps each extra name (`storage:name`) to the review key that covers
* it — `_ga_ABC` → `cookie:_ga_*`.
*/
export async function collectCookieFindings({
ctx,
database = true,
databaseCategories,
declarations = [],
integrations = DEFAULT_COOKIE_INTEGRATIONS,
names = [],
}: {
ctx: CookieScanContext
database?: boolean
databaseCategories?: CookieScannerOptions['databaseCategories']
declarations?: CookieDeclaration[]
integrations?: CookieIntegration[]
names?: CookieObservation[]
}): Promise<{ enabled: CookieIntegration[]; findings: CookieFinding[]; matches: Map<string, string> }> {
const enabled = await enabledCookieIntegrations(integrations, ctx)
const found = new Map<string, CookieFinding>()
const matches = new Map<string, string>()
const add = (f: CookieFinding) => {
const key = reviewKey(f.storage, f.name)
if (!found.has(key)) {found.set(key, f)}
return key
}
for (const d of declarations) {add(fromDeclaration(d, 'project', 'Project'))}
for (const integration of enabled) {
for (const d of declarationsOf(integration, ctx)) {add(fromDeclaration(d, 'integration', integration.label))}
}
const known = [
...declarations.map((d) => ({ d, detail: 'Project', source: 'project' as const })),
...integrations.flatMap((i) => declarationsOf(i, ctx).map((d) => ({ d, detail: i.label, source: 'integration' as const }))),
]
const index = database ? await loadCookieDatabase() : null
for (const raw of names) {
const { name, domain, storage = 'cookie' } = typeof raw === 'string' ? { name: raw } : raw
const seenKey = reviewKey(storage, name)
if (matches.has(seenKey)) {continue}
const covering = [...found.values()].find((f) => f.storage === storage && cookieNameMatches(f.name, name))
if (covering) {
matches.set(seenKey, reviewKey(storage, covering.name))
continue
}
const declared = known.find((k) => (k.d.storage ?? 'cookie') === storage && cookieNameMatches(k.d.name, name))
if (declared) {
matches.set(seenKey, add(fromDeclaration(declared.d, declared.source, declared.detail)))
continue
}
const fromDb = index ? lookupCookie(index, name, databaseCategories) : null
const finding: CookieFinding = fromDb
? { ...fromDb, storage, ...(domain && !fromDb.domain ? { domain } : {}) }
: { ...(domain ? { domain } : {}), name, source: 'unknown', storage }
matches.set(seenKey, add(finding))
}
return { enabled, findings: [...found.values()], matches }
}
/** A review entry a scan wrote: its id, category (after the merge) and whether it is new. */
export type CookieReviewEntryRef = { category: null | string; created: boolean; id: number | string }
type ReviewDoc = {
id: number | string
listed?: boolean | null
suggested?: CookieReviewValues | null
} & CookieReviewValues
function localesOf(payload: BasePayload): { defaultLocale?: string; locales: (string | undefined)[] } {
const l = payload.config.localization
if (!l) {return { locales: [undefined] }}
const codes = l.localeCodes ?? l.locales.map((x) => (typeof x === 'string' ? x : x.code))
return { defaultLocale: l.defaultLocale, locales: [l.defaultLocale, ...codes.filter((c) => c !== l.defaultLocale)] }
}
/** Names already in Cookie Settings → Cookies. */
async function listedNames(payload: BasePayload, req?: PayloadRequest): Promise<Set<string>> {
try {
const g = (await payload.findGlobal({ slug: 'cookie-settings' as never, depth: 0, req })) as { cookies?: { name?: null | string }[] }
return new Set((g.cookies ?? []).map((c) => c.name?.trim() ?? '').filter(Boolean))
} catch {
return new Set()
}
}
/**
* Writes findings to the review list as drafts. New names become drafts; an
* existing entry gets the new suggestion only where an editor has not changed
* the value (see mergeCookieReview). Status is never changed, nothing is
* deleted and nothing is published — accepting stays the editor's step.
*/
export async function applyCookieFindings({
collection = COOKIE_REVIEW_SLUG,
entries,
findings,
payload,
req,
}: {
collection?: string
/** Filled with every written entry by review key — id and its category after the merge. */
entries?: Map<string, CookieReviewEntryRef>
findings: CookieFinding[]
payload: BasePayload
req?: PayloadRequest
}): Promise<CookieScanSummary> {
const { locales } = localesOf(payload)
const codes = locales.filter((l): l is string => Boolean(l))
const listed = await listedNames(payload, req)
const summary: CookieScanSummary = { created: 0, newUnknown: 0, unchanged: 0, unknown: 0, updated: 0 }
const now = new Date().toISOString()
const common = { collection: collection as never, context: { ipalCookieScan: true }, depth: 0, fallbackLocale: false as never, overrideAccess: true, req }
for (const finding of findings) {
if (finding.source === 'unknown') {summary.unknown++}
const key = reviewKey(finding.storage, finding.name)
const next = suggestionFor(finding, codes.length ? codes : ['en'])
const machine = {
key,
lastScannedAt: now,
listed: listed.has(finding.name),
source: finding.source,
sourceDetail: finding.sourceDetail ?? null,
suggested: next,
}
const found = await payload.find({ ...common, limit: 1, locale: (codes.length ? 'all' : undefined) as never, where: { key: { equals: key } } })
const existing = found.docs[0] as ReviewDoc | undefined
const values = existing ? mergeCookieReview(existing, existing.suggested, next) : { changed: true, values: next }
const { purpose, retention, ...scalars } = values.values
const textIn = (locale: string | undefined) => ({
...(purpose && locale ? { purpose: purpose[locale] ?? null } : {}),
...(retention && locale ? { retention: retention[locale] ?? null } : {}),
...(!locale && purpose ? { purpose: Object.values(purpose)[0] ?? null } : {}),
...(!locale && retention ? { retention: Object.values(retention)[0] ?? null } : {}),
})
let id = existing?.id
for (const [i, locale] of locales.entries()) {
const data = i === 0
? { ...scalars, ...machine, ...textIn(locale), ...(existing ? {} : { name: finding.name, status: 'draft', storage: finding.storage }) }
: textIn(locale)
if (i > 0 && (!values.changed || !Object.keys(data).length)) {continue}
if (id === undefined) {
id = ((await payload.create({ ...common, data: data as never, locale: locale as never })) as { id: number | string }).id
} else {
await payload.update({ ...common, id, data: data as never, locale: locale as never })
}
}
entries?.set(key, { id: id!, category: scalars.category ?? null, created: !existing })
if (!existing) {
summary.created++
if (finding.source === 'unknown') {summary.newUnknown++}
}
else if (values.changed) {summary.updated++}
else {summary.unchanged++}
}
return summary
}
/** Scan context from a running Payload: SiteIntegrations + the plugin's module switches. */
export async function cookieScanContext(
payload: BasePayload,
plugin: CookieScanContext['plugin'],
req?: PayloadRequest,
): Promise<CookieScanContext> {
let integrations: Record<string, unknown> = {}
try {
integrations = (await payload.findGlobal({ slug: 'site-integrations' as never, depth: 0, req })) as Record<string, unknown>
} catch {
// No such global (project replaced it) — integrations keyed on its IDs count as off.
}
return { integrations, payload, plugin }
}
/**
* One full scan: findings for this project, plus the names already in Cookie
* Settings and the extra `names`, written to the review list.
*/
export async function runCookieScan({
names = [],
options = {},
payload,
plugin,
req,
}: {
names?: string[]
options?: CookieScannerOptions
payload: BasePayload
plugin: CookieScanContext['plugin']
req?: PayloadRequest
}): Promise<{ enabled: CookieIntegration[]; summary: CookieScanSummary }> {
const ctx = await cookieScanContext(payload, plugin, req)
const integrations = options.integrations ? options.integrations(DEFAULT_COOKIE_INTEGRATIONS) : DEFAULT_COOKIE_INTEGRATIONS
const { enabled, findings } = await collectCookieFindings({
ctx,
database: options.database !== false,
databaseCategories: options.databaseCategories,
declarations: options.declarations,
integrations,
names: [...new Set([...(await listedNames(payload, req)), ...names])],
})
const summary = await applyCookieFindings({ findings, payload, req })
return { enabled, summary }
}
+76
View File
@@ -0,0 +1,76 @@
import type { BasePayload, PayloadRequest } from 'payload'
import type { CookieReviewValues } from './merge.js'
type Row = {
category?: null | string
duration?: null | string
id?: string
name?: null | string
provider?: null | string
purpose?: null | string
}
type Entry = { name: string } & CookieReviewValues
const empty = (v: unknown) => v === undefined || v === null || (typeof v === 'string' && !v.trim())
/**
* Adds an accepted review entry to Cookie Settings → Cookies, in every locale.
* A missing row is added; an existing row (same name) gets only its EMPTY
* provider, purpose and retention filled — text an editor wrote there stays,
* and its category is never changed. Never removes a row.
* Returns what happened, for the log.
*/
export async function addToCookieList({
entry,
payload,
req,
}: {
entry: Entry
payload: BasePayload
req?: PayloadRequest
}): Promise<'added' | 'filled' | 'unchanged'> {
const l = payload.config.localization
const codes = l ? (l.localeCodes ?? []) : []
const defaultLocale = l ? l.defaultLocale : undefined
const locales = l ? [defaultLocale!, ...codes.filter((c) => c !== defaultLocale)] : [undefined]
const text = (map: Record<string, null | string> | undefined, locale: string | undefined) =>
(locale ? map?.[locale] : map && Object.values(map)[0]) ?? null
// fallbackLocale off for reads AND writes: an update in one locale otherwise reads the
// stored rows with the default locale's text filled in and saves that text into it.
const common = { slug: 'cookie-settings' as never, context: { ipalCookieScan: true }, depth: 0, fallbackLocale: false as never, overrideAccess: true, req }
let result: 'added' | 'filled' | 'unchanged' = 'unchanged'
for (const [i, locale] of locales.entries()) {
const g = (await payload.findGlobal({ ...common, locale: locale as never })) as { cookies?: Row[] }
const rows = [...(g.cookies ?? [])]
const row = rows.find((r) => r.name?.trim() === entry.name)
let changed = false
if (!row) {
if (i > 0) {continue} // added in the default locale; Payload keeps the row in every locale
rows.push({
name: entry.name,
category: entry.category ?? 'necessary',
duration: text(entry.retention, locale),
provider: entry.vendor ?? null,
purpose: text(entry.purpose, locale),
})
changed = true
result = 'added'
} else {
const fill = (key: 'duration' | 'provider' | 'purpose', value: null | string | undefined) => {
if (empty(row[key]) && !empty(value)) {
row[key] = value
changed = true
}
}
if (i === 0) {fill('provider', entry.vendor)}
fill('purpose', text(entry.purpose, locale))
fill('duration', text(entry.retention, locale))
if (changed && result === 'unchanged') {result = 'filled'}
}
if (changed) {await payload.updateGlobal({ ...common, data: { cookies: rows } as never, locale: locale as never })}
}
return result
}
+156
View File
@@ -0,0 +1,156 @@
import type { BasePayload, PayloadRequest } from 'payload'
import type { GlobalOverride } from '../../../globals/overrides.js'
import type { CollectionOverride } from '../../shared/collectionOverride.js'
import type { ConsentCategory } from '../categories.js'
import type { CookieScanLabels } from './labels.js'
/** Text per admin/content language (`{ en, pl }`), or one string for every language. */
export type LocalizedText = Record<string, string> | string
/** Where a key is kept in the browser. */
export type CookieStorage = 'cookie' | 'localStorage' | 'sessionStorage'
/**
* One cookie (or storage key) an integration sets — the single place its cookie
* policy text lives. A trailing `*` in `name` matches every name with that prefix
* (`_ga_*` → `_ga_ABC123`).
*/
export type CookieDeclaration = {
category: ConsentCategory
/** Third-party domain that sets it, e.g. `clarity.ms`. Omit for the site's own cookies. */
domain?: string
name: string
purpose: LocalizedText
retention: LocalizedText
/** True when it may be set before the visitor decides (only `necessary` cookies should be). */
setBeforeConsent: boolean
/** Default `'cookie'`. */
storage?: CookieStorage
vendor: string
}
/** What a scan knows about the project when it decides which integrations are on. */
export type CookieScanContext = {
/** SiteIntegrations (depth 0); `{}` when it can't be read. */
integrations: Record<string, unknown>
payload: BasePayload
/** Plugin options that switch modules on. */
plugin: { localeCount: number; stats: boolean }
}
/**
* A feature that sets cookies, with the check whether this project uses it.
* Built-ins: DEFAULT_COOKIE_INTEGRATIONS. Projects add their own (custom embeds,
* chat widgets) through `cookieScanner.integrations` or `cookieScanner.declarations`.
*/
export type CookieIntegration = {
declarations: ((ctx: CookieScanContext) => CookieDeclaration[]) | CookieDeclaration[]
/** Whether the project uses it — e.g. an ID is filled in Site Integrations. */
isEnabled: (ctx: CookieScanContext) => boolean | Promise<boolean>
/** Stable id, e.g. `ga4`. */
key: string
/** Shown in the panel, e.g. `Google Analytics 4`. */
label: string
}
/** Where a review entry's suggestion came from. `manual` = added by hand in the panel. */
export type CookieFindingSource = 'database' | 'integration' | 'manual' | 'project' | 'unknown'
/** One cookie a scan found, before it is written to the review list. */
export type CookieFinding = {
category?: ConsentCategory
domain?: string
name: string
purpose?: LocalizedText
retention?: LocalizedText
setBeforeConsent?: boolean
source: CookieFindingSource
/** e.g. `Google Analytics 4`, `Open Cookie Database: Hotjar`. */
sourceDetail?: string
storage: CookieStorage
vendor?: string
}
/** Open Cookie Database category names. */
export type OpenCookieCategory = 'Analytics' | 'Functional' | 'Marketing' | 'Necessary' | 'Personalization' | 'Security'
/** Totals a scan reports back to the panel. */
export type CookieScanSummary = {
created: number
/** Entries created by this scan that nothing knew. */
newUnknown: number
unchanged: number
/** Names nothing knew — the editor fills provider, purpose and category. */
unknown: number
updated: number
}
/**
* `ipalKit({ cookieScanner })` — the Cookie review list and the "Scan cookies"
* action. Every key is optional.
*/
export type CookieScannerOptions = {
/** Who may run a scan (GET/POST /api/ipal/cookie-scan) and start a crawl. Default: `editor` and up. */
access?: (args: { req: PayloadRequest }) => boolean | Promise<boolean>
/** Change the `cookie-review` collection (object merges, function takes over). */
collectionOverrides?: CollectionOverride
/**
* Browser crawl through the scanner service (services/cookie-crawler):
* "Crawl site" in the panel, the `cookie-crawl` global (latest result only),
* violations, a dashboard warning and an optional e-mail. Default off.
*/
crawl?: boolean | CookieCrawlOptions
/** Look unknown names up in the bundled Open Cookie Database. Default true. */
database?: boolean
/**
* How Open Cookie Database categories map to consent categories. Default:
* Functional / Personalization → functional, Security / Necessary → necessary,
* Analytics → analytics, Marketing → marketing. Functional is not mapped to
* necessary on purpose: the database files some trackers there, and a lookup
* nobody checked yet must not skip consent. `{ Functional: 'necessary' }` to change it.
*/
databaseCategories?: Partial<Record<OpenCookieCategory, ConsentCategory>>
/** The project's own cookies (custom embeds, chat): always part of a scan. */
declarations?: CookieDeclaration[]
/**
* Built-in integrations → the ones to use: filter, change or add.
* `(defaults) => [...defaults, myChatWidget]`.
*/
integrations?: (defaults: CookieIntegration[]) => CookieIntegration[]
/** Admin labels per language, merged over the plugin's `en` / `pl` (add `de: {…}`). */
labels?: Record<string, Partial<CookieScanLabels>>
/**
* Accepting an entry adds it to Cookie Settings → Cookies (fills only empty
* text of an existing row). Default true; `false` = the list is only a review aid.
*/
syncAccepted?: boolean
}
/**
* `cookieScanner.crawl` — the site side of the browser crawl. The browser runs
* in the scanner service, never in the site. Every key is optional.
*/
export type CookieCrawlOptions = {
/** CSS selector of the banner's "Accept all" button. Default `[data-ipal="accept"]`. */
acceptSelector?: string
/**
* The site's Consent Mode: `'advanced'` (default) lets Google tag requests
* through before consent (signals denied, no cookies); `'basic'` reports them.
*/
consentMode?: 'advanced' | 'basic'
/** Warning on the dashboard after a crawl with violations or new unknown cookies. Default true. */
dashboard?: boolean
/** Change the `cookie-crawl` global (object merges, function takes over). */
globalOverride?: GlobalOverride
/** Sitemap pages crawled besides the home page. Default 20, at most 100. */
maxPages?: number
/** Scanner service base URL. Default env `IPAL_COOKIE_SCAN_URL`. */
serviceUrl?: string
/** Public origin of this site the service crawls and calls back. Default `serverURL`, else `NEXT_PUBLIC_SERVER_URL`. */
siteUrl?: string
/** Shared secret with the service. Default env `IPAL_COOKIE_SCAN_TOKEN`. */
token?: string
/** Hosts whose requests before consent are violations: `(defaults) => hosts`. */
trackerHosts?: (defaults: string[]) => string[]
}
+19
View File
@@ -3,6 +3,11 @@ import type { EnvRule } from './assertEnv.js'
type TurnstileNames = { secretVar?: string; siteKeyVar?: string }
export type IpalEnvFeatures = {
/**
* Cookie crawl (cookieScanner.crawl): the scanner service URL and the shared
* token (at least 16 characters). Required in production only.
*/
cookieCrawl?: boolean
/** Override the database var. Default 'DATABASE_URI'. */
databaseVar?: string
/** Microsoft Graph e-mail (graphAdapter). Adds the GRAPH_* vars. */
@@ -56,6 +61,7 @@ export type IpalEnvFeatures = {
*/
export function ipalEnvRules(features: IpalEnvFeatures = {}): EnvRule[] {
const {
cookieCrawl = false,
databaseVar = 'DATABASE_URI',
emailGraph = false,
ipHeader = false,
@@ -125,6 +131,19 @@ export function ipalEnvRules(features: IpalEnvFeatures = {}): EnvRule[] {
})
}
if (cookieCrawl) {
const required = process.env.NODE_ENV === 'production'
rules.push(
{ name: 'IPAL_COOKIE_SCAN_URL', description: 'Cookie crawler service base URL, e.g. https://cookie-crawler.example.com', kind: 'url', required },
{
name: 'IPAL_COOKIE_SCAN_TOKEN',
description: 'Token shared with the cookie crawler (this site\'s entry in IPAL_CRAWLER_SITES)',
required,
validate: (v) => (v.length >= 16 ? true : 'IPAL_COOKIE_SCAN_TOKEN must be at least 16 characters'),
},
)
}
if (turnstile) {
const names = typeof turnstile === 'object' ? turnstile : {}
rules.push(
+37
View File
@@ -10,6 +10,11 @@ import { buildSiteIntegrations } from './globals/SiteIntegrations/index.js'
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'
@@ -311,6 +316,38 @@ export const ipalKit = (options: IpalOptions): Plugin => {
config.endpoints = [...(config.endpoints ?? []), buildConsentLogEndpoint(logOptions)]
}
// --- cookie scanner: review list + "Scan cookies" (opt-in) ---
if (options.cookieScanner) {
const scannerOptions = options.cookieScanner === true ? {} : options.cookieScanner
config.collections = [...(config.collections ?? []), applyCollectionOverride(buildCookieReviewCollection(scannerOptions), scannerOptions.collectionOverrides)]
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) ---
if (options.stats) {
const statsOptions = options.stats === true ? {} : options.stats
+12
View File
@@ -15,6 +15,7 @@ export type TotpPluginFactory = (options: {
import type { GlobalOverrides } from './globals/overrides.js'
import type { AccessOption } from './modules/access/types.js'
import type { ConsentLogOptions } from './modules/consent/consentLog.js'
import type { CookieScannerOptions } from './modules/consent/scanner/types.js'
import type { ContentOption } from './modules/content/types.js'
import type { FormsOption } from './modules/forms/types.js'
import type { RevalidatePathFn } from './modules/hooks/buildRevalidateHook.js'
@@ -63,6 +64,17 @@ export type IpalOptions = {
*/
content?: ContentOption
/**
* Cookie scanner (docs/cookie-scanner.md): the `cookie-review` collection, a
* "Scan cookies" action above its list and GET/POST /api/ipal/cookie-scan. A
* scan lists the cookies of the integrations this project switches on, plus
* names looked up in the bundled Open Cookie Database, as drafts an editor
* accepts (→ Cookie Settings → Cookies), edits or rejects. Never deletes,
* never overwrites edited text, never publishes by itself.
* `true` or CookieScannerOptions. Default off.
*/
cookieScanner?: boolean | CookieScannerOptions
/**
* `false` = plugin off without uninstalling: its collections, globals and
* fields stay (DB schema and migrations unchanged), but it adds no endpoints,
+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 { 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'
import { buildTestConfig } from './helpers.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: buildTestConfig({
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,
}),
})
}, 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()
})
})
+212
View File
@@ -0,0 +1,212 @@
import type { BasePayload, Config } from 'payload'
import { describe, expect, test, vi } from 'vitest'
import type { CookieScanContext } from '../src/modules/consent/scanner/types.js'
import { indexCookieDatabase, loadCookieDatabase, lookupCookie } from '../src/modules/consent/scanner/cookieDatabase.js'
import { OPEN_COOKIE_DATABASE_SOURCE } from '../src/modules/consent/scanner/data/openCookieDatabase.js'
import { cookieNameMatches, DEFAULT_COOKIE_INTEGRATIONS } from '../src/modules/consent/scanner/integrations.js'
import { COOKIE_SCAN_LABELS, labelFor, labelRecord, mergeCookieScanLabels } from '../src/modules/consent/scanner/labels.js'
import { mergeCookieReview, suggestionFor, textFor } from '../src/modules/consent/scanner/merge.js'
import { collectCookieFindings, parseCookieNames } from '../src/modules/consent/scanner/scan.js'
import { ipalKit } from '../src/plugin.js'
vi.mock('server-only', () => ({}))
const ctx = (integrations: Record<string, unknown> = {}, plugin: Partial<CookieScanContext['plugin']> = {}): CookieScanContext => ({
integrations,
payload: {
config: { cookiePrefix: 'payload' },
findGlobal: vi.fn(async () => integrations),
logger: { error: vi.fn(), info: vi.fn(), warn: vi.fn() },
} as unknown as BasePayload,
plugin: { localeCount: 1, stats: false, ...plugin },
})
describe('cookie scanner — names', () => {
test('a trailing * is a prefix, anything else exact', () => {
expect(cookieNameMatches('_ga_*', '_ga_ABC123')).toBe(true)
expect(cookieNameMatches('_ga_*', '_ga')).toBe(false)
expect(cookieNameMatches('_ga', '_ga')).toBe(true)
expect(cookieNameMatches('_ga', '_gat')).toBe(false)
})
test('names from the panel: trimmed, unique, invalid dropped, capped', () => {
expect(parseCookieNames(' _ga \n\n_fbp\n_ga\nbad name\na;b\nx=y')).toEqual(['_ga', '_fbp'])
expect(parseCookieNames(['a', 1, null, 'b'])).toEqual(['a', 'b'])
expect(parseCookieNames(undefined)).toEqual([])
expect(parseCookieNames(Array.from({ length: 500 }, (_, i) => `c${i}`))).toHaveLength(200)
})
})
describe('cookie scanner — Open Cookie Database', () => {
test('the bundled copy names its source, license and commit', () => {
expect(OPEN_COOKIE_DATABASE_SOURCE.license).toBe('Apache-2.0')
expect(OPEN_COOKIE_DATABASE_SOURCE.commit).toMatch(/^[0-9a-f]{40}$/)
})
test('exact names, wildcard prefixes, third-party domains', async () => {
const db = await loadCookieDatabase()
expect(lookupCookie(db, '_ga')).toMatchObject({ name: '_ga', category: 'analytics', source: 'database', vendor: 'Google' })
const gac = lookupCookie(db, '_gac_UA-123')
expect(gac?.name).toBe('_gac_*') // one entry per pattern, not per site-specific suffix
expect(lookupCookie(db, '_fbp')).toMatchObject({ category: 'marketing', domain: 'facebook.com' })
expect(lookupCookie(db, 'no-such-cookie-xyz')).toBeNull()
})
test('categories map to consent categories, and the map is overridable', () => {
const db = indexCookieDatabase([
['sess', 'App', 'Functional', '', 'Session', 'session', 'Acme', 0],
['pref', 'App', 'Personalization', '', 'Prefs', '1 year', 'Acme', 0],
['pre_', 'App', 'Security', '', 'Guard', '1 day', 'Acme', 1],
['pre_long_', 'App', 'Marketing', '', 'Ads', '1 day', 'Acme', 1],
])
// Functional is never mapped to necessary by default — an unchecked lookup must not skip consent
expect(lookupCookie(db, 'sess')?.category).toBe('functional')
expect(lookupCookie(db, 'pref')?.category).toBe('functional')
expect(lookupCookie(db, 'sess', { Functional: 'necessary' })?.category).toBe('necessary')
// the longest prefix wins
expect(lookupCookie(db, 'pre_long_1')?.category).toBe('marketing')
expect(lookupCookie(db, 'pre_1')?.category).toBe('necessary')
})
})
describe('cookie scanner — findings', () => {
test('only integrations the project switches on', async () => {
const { enabled, findings } = await collectCookieFindings({ ctx: ctx({ ga4MeasurementId: 'G-ABC123DEF4' }), database: false })
expect(enabled.map((i) => i.key)).toEqual(['consent', 'admin', 'ga4'])
expect(findings.map((f) => f.name)).toEqual(['cookie-consent', 'payload-token', '_ga', '_ga_*'])
expect(findings.every((f) => f.source === 'integration')).toBe(true)
})
test('stats, languages, pixels and Turnstile follow the project config', async () => {
const on = await collectCookieFindings({
ctx: ctx(
{ clarityProjectId: 'abcdefghij', metaPixelId: '1234567890123456', turnstileSecretKey: 's', turnstileSiteKey: 'k' },
{ localeCount: 2, stats: true },
),
database: false,
})
const names = on.findings.map((f) => f.name)
for (const n of ['ipal_vid', 'NEXT_LOCALE', '_fbp', '_fbc', '_clck', 'cf_clearance']) {expect(names).toContain(n)}
expect(names).not.toContain('_ttp')
// an invalid ID counts as off
const bad = await collectCookieFindings({ ctx: ctx({ metaPixelId: 'nope' }), database: false })
expect(bad.findings.map((f) => f.name)).not.toContain('_fbp')
})
test('every built-in declaration has text in English and Polish and a sane category', () => {
for (const integration of DEFAULT_COOKIE_INTEGRATIONS) {
const list = typeof integration.declarations === 'function' ? integration.declarations(ctx()) : integration.declarations
for (const d of list) {
expect(typeof d.purpose === 'object' && d.purpose.en && d.purpose.pl, `${d.name} purpose`).toBeTruthy()
expect(typeof d.retention === 'object' && d.retention.en && d.retention.pl, `${d.name} retention`).toBeTruthy()
// only necessary cookies may be set before consent
if (d.setBeforeConsent) {expect(d.category, d.name).toBe('necessary')}
}
}
})
test('project declarations, then built-ins, then the database, then unknown', async () => {
const { findings } = await collectCookieFindings({
ctx: ctx(),
declarations: [{ name: 'yt-*', category: 'marketing', purpose: 'YouTube embed', retention: '6 months', setBeforeConsent: false, vendor: 'Google' }],
names: ['yt-player', '_fbp', '_hjSessionUser_123', 'totally_unknown', 'cookie-consent'],
})
const by = Object.fromEntries(findings.map((f) => [f.name, f]))
expect(by['yt-*'].source).toBe('project')
expect(by['yt-player']).toBeUndefined() // covered by the project's pattern
expect(by._fbp).toMatchObject({ source: 'integration', sourceDetail: 'Meta Pixel' }) // built-in text even with the pixel off
expect(by['_hjSessionUser_*']).toMatchObject({ category: 'functional', source: 'database' }) // filed as Functional upstream — asks for consent
expect(by.totally_unknown).toEqual({ name: 'totally_unknown', source: 'unknown', storage: 'cookie' })
expect(findings.filter((f) => f.name === 'cookie-consent')).toHaveLength(1)
})
test('a failing isEnabled counts as off and is logged', async () => {
const c = ctx()
const { enabled } = await collectCookieFindings({
ctx: c,
database: false,
integrations: [{ declarations: [], isEnabled: () => { throw new Error('boom') }, key: 'x', label: 'X' }],
})
expect(enabled).toEqual([])
expect(c.payload.logger.warn).toHaveBeenCalled()
})
})
describe('cookie scanner — merging a rescan', () => {
const next = suggestionFor(
{ name: '_ga', category: 'analytics', purpose: { en: 'New EN', pl: 'Nowy PL' }, retention: '2 years', source: 'integration', storage: 'cookie', vendor: 'Google' },
['pl', 'en'],
)
test('text per locale: own language, English, first', () => {
expect(textFor({ en: 'E', pl: 'P' }, 'pl')).toBe('P')
expect(textFor({ en: 'E', pl: 'P' }, 'de')).toBe('E')
expect(textFor({ fr: 'F' }, 'de')).toBe('F')
expect(textFor('same', 'pl')).toBe('same')
expect(next.retention).toEqual({ en: '2 years', pl: '2 years' })
})
test('empty and untouched values follow the scan', () => {
const previous = { category: 'analytics' as const, purpose: { en: 'Old EN', pl: 'Stary PL' }, vendor: 'Google' }
const { changed, values } = mergeCookieReview({ ...previous, retention: {} }, previous, next)
expect(changed).toBe(true)
expect(values.purpose).toEqual({ en: 'New EN', pl: 'Nowy PL' })
expect(values.retention).toEqual({ en: '2 years', pl: '2 years' })
})
test('text an editor changed is never overwritten — per locale and per field', () => {
const previous = { category: 'analytics' as const, purpose: { en: 'Old EN', pl: 'Stary PL' }, vendor: 'Google' }
const current = { category: 'marketing' as const, purpose: { en: 'Old EN', pl: 'Mój tekst' }, vendor: 'Google LLC' }
const { values } = mergeCookieReview(current, previous, next)
expect(values.purpose).toEqual({ en: 'New EN', pl: 'Mój tekst' })
expect(values.vendor).toBe('Google LLC')
expect(values.category).toBe('marketing')
})
test('same suggestion again → nothing changes', () => {
expect(mergeCookieReview(next, next, next).changed).toBe(false)
})
test('a missing suggestion never clears a value', () => {
const { changed, values } = mergeCookieReview({ vendor: 'Mine' }, undefined, {})
expect(changed).toBe(false)
expect(values.vendor).toBe('Mine')
})
})
describe('cookie scanner — labels and config', () => {
test('English and Polish for every label; projects add languages and change text', () => {
expect(Object.keys(COOKIE_SCAN_LABELS.pl).sort()).toEqual(Object.keys(COOKIE_SCAN_LABELS.en).sort())
const labels = mergeCookieScanLabels({ de: { scanButton: 'Cookies scannen' }, pl: { scanButton: 'Skanuj' } })
expect(labelRecord(labels, 'scanButton')).toEqual({ de: 'Cookies scannen', en: 'Scan cookies', pl: 'Skanuj' })
expect(labels.de.status).toBe('Status') // missing keys fall back to English
expect(labelFor(labels, 'fr', 'scanButton')).toBe('Scan cookies')
})
const run = async (cookieScanner?: unknown) =>
ipalKit({
cookieScanner: cookieScanner as never,
i18n: { defaultLocale: 'pl', locales: [{ code: 'pl', label: 'Polski' }] },
twoFactor: false,
})({ collections: [{ slug: 'users', auth: true, fields: [] }] } as unknown as Config)
test('off by default: no collection, no endpoint', async () => {
const config = await run()
expect(config.collections?.some((c) => c.slug === 'cookie-review')).toBe(false)
expect(config.endpoints?.some((e) => e.path === '/ipal/cookie-scan')).toBe(false)
})
test('on: collection with the scan button, GET + POST endpoint; overrides win', async () => {
const config = await run({ collectionOverrides: { admin: { group: 'Privacy' } }, syncAccepted: false })
const review = config.collections?.find((c) => c.slug === 'cookie-review')
expect(review?.admin?.group).toBe('Privacy')
expect(review?.admin?.components?.beforeListTable).toEqual([
expect.objectContaining({ path: '@intecion/ipal-kit/admin#CookieScanButton' }),
])
expect(review?.hooks?.afterChange).toEqual([])
expect(config.endpoints?.filter((e) => e.path === '/ipal/cookie-scan').map((e) => e.method).sort()).toEqual(['get', 'post'])
})
})
+175
View File
@@ -0,0 +1,175 @@
/**
* Cookie scanner through a REAL Payload (SQLite in memory, two locales): scan →
* drafts → editor edits → rescan keeps the edits → accept → Cookie Settings.
*/
import type { Payload } from 'payload'
import { sqliteAdapter } from '@payloadcms/db-sqlite'
import { lexicalEditor } from '@payloadcms/richtext-lexical'
import os from 'os'
import path from 'path'
import { getPayload } from 'payload'
import { afterAll, beforeAll, describe, expect, test, vi } from 'vitest'
import { buildCookieScanEndpoints } from '../src/modules/consent/scanner/endpoint.js'
import { runCookieScan } from '../src/modules/consent/scanner/scan.js'
import { ipalKit } from '../src/plugin.js'
import { buildTestConfig } from './helpers.js'
vi.mock('server-only', () => ({}))
const SLUG = 'cookie-review' as never
const plugin = { localeCount: 2, stats: true }
const declarations = [
{ name: 'yt-*', category: 'marketing' as const, purpose: { en: 'YouTube embed', pl: 'Film YouTube' }, retention: '6 months', setBeforeConsent: false, vendor: 'Google' },
]
type Entry = {
category?: string
id: number
key: string
listed?: boolean
name: string
purpose?: Record<string, string> | string
source: string
status: string
vendor?: string
}
let payload: Payload
const all = async () => (await payload.find({ collection: SLUG, depth: 0, limit: 100, locale: 'all' as never })).docs as unknown as Entry[]
const byName = async (name: string) => (await all()).find((e) => e.name === name)!
const cookieList = async (locale: string) =>
((await payload.findGlobal({ slug: 'cookie-settings' as never, fallbackLocale: false as never, locale: locale as never })) as {
cookies?: { category: string; duration?: null | string; name: string; provider?: null | string; purpose?: null | string }[]
}).cookies ?? []
beforeAll(async () => {
const config = buildTestConfig({
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: { declarations },
i18n: {
defaultLocale: 'pl',
locales: [
{ code: 'pl', label: 'Polski' },
{ code: 'en', label: 'English' },
],
},
stats: true,
twoFactor: false,
}),
],
secret: 'cookie-scanner-test-secret',
telemetry: false,
})
payload = await getPayload({ config })
await payload.updateGlobal({ slug: 'site-integrations' as never, data: { ga4MeasurementId: 'G-ABC123DEF4' } as never })
// An editor's own row, already published before the first scan.
await payload.updateGlobal({
slug: 'cookie-settings' as never,
data: { cookies: [{ name: '_ga', category: 'analytics', provider: 'Google', purpose: 'Tekst redaktora' }] } as never,
locale: 'pl' as never,
})
}, 60_000)
afterAll(async () => {
await payload?.destroy()
})
describe('cookie scanner against a real Payload', () => {
test('a scan writes drafts in every locale and publishes nothing', async () => {
const { enabled, summary } = await runCookieScan({ names: ['_hjSessionUser_42', 'mystery'], options: { declarations }, payload, plugin })
expect(enabled.map((i) => i.key)).toEqual(['consent', 'admin', 'locale', 'stats', 'ga4'])
expect(summary).toMatchObject({ unknown: 1, updated: 0 })
const entries = await all()
expect(entries.every((e) => e.status === 'draft')).toBe(true)
expect(entries.map((e) => e.name).sort()).toEqual(
['NEXT_LOCALE', '_ga', '_ga_*', '_hjSessionUser_*', 'cookie-consent', 'ipal_vid', 'mystery', 'payload-token', 'yt-*'].sort(),
)
expect((await byName('ipal_vid')).purpose).toMatchObject({ en: expect.stringContaining('Built-in statistics'), pl: expect.stringContaining('Wbudowane') })
expect(await byName('_ga')).toMatchObject({ listed: true, source: 'integration' })
expect(await byName('mystery')).toMatchObject({ source: 'unknown' })
expect((await cookieList('pl')).map((c) => c.name)).toEqual(['_ga']) // nothing published
})
test('a rescan keeps what an editor changed, adds nothing twice, deletes nothing', async () => {
const vid = await byName('ipal_vid')
await payload.update({ id: vid.id, collection: SLUG, data: { purpose: 'Mój opis', vendor: 'Nasza strona' } as never, locale: 'pl' as never })
const before = (await all()).length
const { summary } = await runCookieScan({ options: { declarations }, payload, plugin })
expect(summary.created).toBe(0)
const after = await byName('ipal_vid')
expect(after.purpose).toMatchObject({ en: expect.stringContaining('Built-in statistics'), pl: 'Mój opis' })
expect(after.vendor).toBe('Nasza strona')
expect((await all()).length).toBe(before) // names not passed again are kept
})
test('accepting adds the cookie to Cookie Settings in every locale', async () => {
const vid = await byName('ipal_vid')
const saved = (await payload.update({ id: vid.id, collection: SLUG, data: { status: 'accepted' } as never, locale: 'pl' as never })) as unknown as Entry
expect(saved.purpose).toBe('Mój opis') // the editor's save still answers in their locale
const pl = (await cookieList('pl')).find((c) => c.name === 'ipal_vid')
const en = (await cookieList('en')).find((c) => c.name === 'ipal_vid')
expect(pl).toMatchObject({ category: 'analytics', duration: '6 mies.', provider: 'Nasza strona', purpose: 'Mój opis' })
expect(en?.purpose).toContain('Built-in statistics')
expect((await byName('ipal_vid')).listed).toBe(true)
})
test('accepting an existing row fills only empty text, never the editor’s', async () => {
const ga = await byName('_ga')
await payload.update({ id: ga.id, collection: SLUG, data: { status: 'accepted' } as never, locale: 'pl' as never })
const pl = (await cookieList('pl')).filter((c) => c.name === '_ga')
expect(pl).toHaveLength(1)
expect(pl[0]).toMatchObject({ duration: '2 lata', provider: 'Google', purpose: 'Tekst redaktora' })
expect((await cookieList('en')).find((c) => c.name === '_ga')?.purpose).toContain('Google Analytics')
})
test('an entry without a category cannot be accepted', async () => {
const mystery = await byName('mystery')
await expect(
payload.update({ id: mystery.id, collection: SLUG, data: { status: 'accepted' } as never, locale: 'pl' as never }),
).rejects.toThrow()
})
test('rejecting keeps the entry; a rescan never changes its status', async () => {
const yt = await byName('yt-*')
await payload.update({ id: yt.id, collection: SLUG, data: { status: 'rejected' } as never, locale: 'pl' as never })
await runCookieScan({ options: { declarations }, payload, plugin })
expect((await byName('yt-*')).status).toBe('rejected')
expect((await byName('ipal_vid')).status).toBe('accepted')
expect((await cookieList('pl')).some((c) => c.name === 'yt-*')).toBe(false)
})
test('the endpoint: editors scan, visitors and plain users get 403', async () => {
const [get, post] = buildCookieScanEndpoints({ declarations }, plugin)
const call = (endpoint: typeof get, user: unknown, body: unknown = {}) =>
endpoint.handler({ json: async () => body, payload, user } as never) as Promise<Response>
expect((await call(post, null)).status).toBe(403)
expect((await call(post, { collection: 'users', roles: ['user'] })).status).toBe(403)
const editor = { collection: 'users', roles: ['editor'] }
const listed = (await (await call(get, editor)).json()) as { integrations: { key: string }[] }
expect(listed.integrations.map((i) => i.key)).toContain('ga4')
const res = await call(post, editor, { names: ['_fbp'] })
expect(res.status).toBe(200)
expect(((await res.json()) as { summary: { created: number } }).summary.created).toBe(1)
expect(await byName('_fbp')).toMatchObject({ source: 'integration', status: 'draft' })
})
test('custom access option replaces the editor check', async () => {
const [, post] = buildCookieScanEndpoints({ access: () => false }, plugin)
const res = (await post.handler({ json: async () => ({}), payload, user: { collection: 'users', roles: ['admin'] } } as never))
expect(res.status).toBe(403)
})
})
+3
View File
@@ -236,6 +236,9 @@ describe('agent guide covers the whole plugin', () => {
...typeKeys('src/modules/access/types.ts', 'AccessOption'),
...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'),