diff --git a/dev/app/(payload)/admin/importMap.js b/dev/app/(payload)/admin/importMap.js index f49cc3f..8bc0e21 100644 --- a/dev/app/(payload)/admin/importMap.js +++ b/dev/app/(payload)/admin/importMap.js @@ -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, diff --git a/dev/payload.config.ts b/dev/payload.config.ts index bb9f6c7..a33bb53 100644 --- a/dev/payload.config.ts +++ b/dev/payload.config.ts @@ -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, diff --git a/docs/README.md b/docs/README.md index ea1cb7a..bf4a847 100644 --- a/docs/README.md +++ b/docs/README.md @@ -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) | diff --git a/docs/agent/AGENT.md b/docs/agent/AGENT.md index c18f6e4..400c50f 100644 --- a/docs/agent/AGENT.md +++ b/docs/agent/AGENT.md @@ -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`; ``; `images: buildImagesConfig()` and `buildUploadSecurityHeaders()` in `next.config.ts`; the project's `` 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 `` + `formClasses.ts` (look, once); `actions.ts` = `createSubmitAction({ getCachedPayload, headers })`; `forms: {…}` in `ipalKit`; `email: mailAdapter()` | `RenderForm` (`/rsc`), `createSubmitAction`, `mailAdapter` | A, P | | 11 | **Turnstile** | `` 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'` (`` — 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) + `}>` (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 `` 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'` (`` — 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) + `}>` (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 `` 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 | `` — 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 | `` (`/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: { : { 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) | diff --git a/docs/agent/skills/ipal-consent-check/SKILL.md b/docs/agent/skills/ipal-consent-check/SKILL.md index 0b77a71..48e973e 100644 --- a/docs/agent/skills/ipal-consent-check/SKILL.md +++ b/docs/agent/skills/ipal-consent-check/SKILL.md @@ -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 + `=` 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 diff --git a/docs/agent/skills/ipal-reference/SKILL.md b/docs/agent/skills/ipal-reference/SKILL.md index eb52b9f..0cff2a8 100644 --- a/docs/agent/skills/ipal-reference/SKILL.md +++ b/docs/agent/skills/ipal-reference/SKILL.md @@ -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 === 'dpo@acme.pl' } }` — 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`, `//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 | `` (`/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 `` (`/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; `` 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` + `` (or `` inside `ConsentProvider`) | `//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 | diff --git a/docs/agent/skills/ipal-reference/resources/api.md b/docs/agent/skills/ipal-reference/resources/api.md index d0b0054..719e1b7 100644 --- a/docs/agent/skills/ipal-reference/resources/api.md +++ b/docs/agent/skills/ipal-reference/resources/api.md @@ -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 | diff --git a/docs/consent.md b/docs/consent.md index 1c05653..13e8dd5 100644 --- a/docs/consent.md +++ b/docs/consent.md @@ -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` + `` from `/rsc`. +- **Cookie table** for the policy page: Cookie Settings → *Cookies* + `getCookieTable` + `` 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`, diff --git a/docs/cookie-scanner.md b/docs/cookie-scanner.md new file mode 100644 index 0000000..ae4bcde --- /dev/null +++ b/docs/cookie-scanner.md @@ -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 +`` window and `` 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` (`-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 `), 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 `` 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 `/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 `, 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.` → `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. diff --git a/docs/deployment.md b/docs/deployment.md index 5ffcf96..4bdbeb2 100644 --- a/docs/deployment.md +++ b/docs/deployment.md @@ -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.` → `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. diff --git a/docs/env.md b/docs/env.md index e6cebc0..3fccaa3 100644 --- a/docs/env.md +++ b/docs/env.md @@ -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' diff --git a/docs/licenses/open-cookie-database-LICENSE.txt b/docs/licenses/open-cookie-database-LICENSE.txt new file mode 100644 index 0000000..261eeb9 --- /dev/null +++ b/docs/licenses/open-cookie-database-LICENSE.txt @@ -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. diff --git a/package.json b/package.json index 83b661f..a2a3b3a 100644 --- a/package.json +++ b/package.json @@ -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", diff --git a/scripts/refresh-cookie-database.mjs b/scripts/refresh-cookie-database.mjs new file mode 100644 index 0000000..1522416 --- /dev/null +++ b/scripts/refresh-cookie-database.mjs @@ -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 +// +// 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)}`) diff --git a/services/cookie-crawler/.dockerignore b/services/cookie-crawler/.dockerignore new file mode 100644 index 0000000..5038a10 --- /dev/null +++ b/services/cookie-crawler/.dockerignore @@ -0,0 +1,3 @@ +node_modules +npm-debug.log +*.md diff --git a/services/cookie-crawler/Dockerfile b/services/cookie-crawler/Dockerfile new file mode 100644 index 0000000..8cf7f7a --- /dev/null +++ b/services/cookie-crawler/Dockerfile @@ -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"] diff --git a/services/cookie-crawler/README.md b/services/cookie-crawler/README.md new file mode 100644 index 0000000..d18da5d --- /dev/null +++ b/services/cookie-crawler/README.md @@ -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. diff --git a/services/cookie-crawler/cli.mjs b/services/cookie-crawler/cli.mjs new file mode 100644 index 0000000..921f6d0 --- /dev/null +++ b/services/cookie-crawler/cli.mjs @@ -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 [--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 [--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) diff --git a/services/cookie-crawler/crawl.mjs b/services/cookie-crawler/crawl.mjs new file mode 100644 index 0000000..483f531 --- /dev/null +++ b/services/cookie-crawler/crawl.mjs @@ -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() + } +} diff --git a/services/cookie-crawler/lib.mjs b/services/cookie-crawler/lib.mjs new file mode 100644 index 0000000..74d1fc0 --- /dev/null +++ b/services/cookie-crawler/lib.mjs @@ -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(/\s*([^<\s]+)\s*<\/loc>/g)].map((m) => m[1].replace(/&/g, '&')) + let xml = await text(`${origin}/sitemap.xml`) + if (/ 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()] } +} diff --git a/services/cookie-crawler/package-lock.json b/services/cookie-crawler/package-lock.json new file mode 100644 index 0000000..7ce23e5 --- /dev/null +++ b/services/cookie-crawler/package-lock.json @@ -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" + } + } + } +} diff --git a/services/cookie-crawler/package.json b/services/cookie-crawler/package.json new file mode 100644 index 0000000..48ccafe --- /dev/null +++ b/services/cookie-crawler/package.json @@ -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" + } +} diff --git a/services/cookie-crawler/server.mjs b/services/cookie-crawler/server.mjs new file mode 100644 index 0000000..d1d8834 --- /dev/null +++ b/services/cookie-crawler/server.mjs @@ -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 +// { 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) +} diff --git a/src/exports/admin.ts b/src/exports/admin.ts index 6bb56cc..4f45171 100644 --- a/src/exports/admin.ts +++ b/src/exports/admin.ts @@ -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' diff --git a/src/globals/CookieSettings/fields.ts b/src/globals/CookieSettings/fields.ts index 0263222..c53b265 100644 --- a/src/globals/CookieSettings/fields.ts +++ b/src/globals/CookieSettings/fields.ts @@ -136,7 +136,7 @@ export const cookieSettingsFields: Field[] = [ type: 'array', admin: { description: - 'Cookies the site uses — shown on the cookie policy page () 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 () 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: [ diff --git a/src/index.ts b/src/index.ts index 0481865..4d8590d 100644 --- a/src/index.ts +++ b/src/index.ts @@ -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' diff --git a/src/modules/consent/scanner/CookieScanButton.tsx b/src/modules/consent/scanner/CookieScanButton.tsx new file mode 100644 index 0000000..c81e49b --- /dev/null +++ b/src/modules/consent/scanner/CookieScanButton.tsx @@ -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) => + 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 }) { + 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({ kind: 'idle' }) + const [crawlState, setCrawlState] = useState(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 ( +
+

{t.scanIntro}

+ {integrations ? ( +

+ {integrations.length ? `${t.integrationsFound}: ${integrations.map((i) => i.label).join(', ')}` : t.integrationsNone} +

+ ) : null} + +

{t.namesHint}

+