Cookie scanner, phase 1: declarations, database lookup, review list

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

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

Co-Authored-By: Claude Opus 5.5 <[email protected]>
This commit is contained in:
Radosław Smoliński
2026-10-27 14:55:20 +01:00
co-authored by Claude Opus 5.5
parent ab45cf48be
commit a0545b6716
26 changed files with 2168 additions and 7 deletions
+1
View File
@@ -24,6 +24,7 @@ API details — one file per module:
| GA4, GTM, Meta Pixel, Clarity, LinkedIn, TikTok, `defer` | [analytics.md](./analytics.md) |
| Blocks, RenderBlocks, enhanceProps | [blocks.md](./blocks.md) |
| Cookie consent, banner, settings window (in the bar / modal / large with cookie details) | [consent.md](./consent.md) |
| Cookie scanner: review list of drafts, "Scan cookies", Open Cookie Database lookup (optional) | [cookie-scanner.md](./cookie-scanner.md) |
| Under construction — locks subpages behind a popup (developer tool) | [construction.md](./construction.md) |
| Routing, archives, redirects, Markdown, search | [content.md](./content.md) |
| Site frontend: `createContentHelpers` (`@/lib/content`), `createPageRoute`, `SiteProviders` | [frontend.md](./frontend.md) |
+4 -1
View File
@@ -107,7 +107,7 @@ site), **P** = a test in the panel. Full code: PROGRAMISTA.md §2.
| 9 | **Media / R2 / speed** | `Media` with `focalPoint`, `normalizeFilenameHook`, `buildOptimizeUploadHook`, `buildMediaPlaceholderHook` + field; **always** `buildR2Storage(['media'], { s3Storage })` + `@payloadcms/storage-s3`; `R2_*` in `.env.example`; `<MediaPreconnect/>`; `images: buildImagesConfig()` and `buildUploadSecurityHeaders()` in `next.config.ts`; the project's `<Media>` via `mediaImageProps`/`videoProps` (§6.11b) | `buildR2Storage`, `mediaImageProps`, `videoProps`, `buildImagesConfig` | A, S |
| 10 | **Forms** | every form from a **seed** (`scripts/seed-form-*.ts`: fields, confirmation, mail to the company **and** confirmation to the customer, every language); a block with `<RenderForm>` + `formClasses.ts` (look, once); `actions.ts` = `createSubmitAction({ getCachedPayload, headers })`; `forms: {…}` in `ipalKit`; `email: mailAdapter()` | `RenderForm` (`/rsc`), `createSubmitAction`, `mailAdapter` | A, P |
| 11 | **Turnstile** | `<SiteProviders>` in `[locale]/layout.tsx` (wires `TurnstileProvider` with the key from the panel); `RenderForm` renders the widget; keys in Site Integrations | `SiteProviders`, `getTurnstileConfig`, `TurnstileProvider` | A, P |
| 12 | Consent + analytics | Consent Mode: `'advanced'` (default — the Google tag loads at once with every signal `denied`) or `'basic'` (`<SiteProviders analytics={{ consentMode: 'basic' }}>` — no request to Google before consent; a client who wants zero requests), the choice goes to "Project decisions"; `ipalKit({ consentLog: true })` (without it the `/api/ipal/consent` endpoint does not exist) + `<SiteProviders logEndpoint="/api/ipal/consent" banner={<CookieBanner equalChoice settings="detailed" />}>` (ConsentProvider, banner, CookieButton, Analytics in the right order); settings window mode (`settings`: `inline` / `modal` / `detailed`) per the design, brief is silent → `detailed`, the decision goes to "Project decisions"; tool IDs in the panel; the cookie list from a scan (cookie-scan → import) — feeds `<CookieTable>` on the policy page **and** the lists in the `detailed` window; Cookie Settings → Detail labels in every language | consent.md, analytics.md | A, `ipal-consent-check` |
| 12 | Consent + analytics | Consent Mode: `'advanced'` (default — the Google tag loads at once with every signal `denied`) or `'basic'` (`<SiteProviders analytics={{ consentMode: 'basic' }}>` — no request to Google before consent; a client who wants zero requests), the choice goes to "Project decisions"; `ipalKit({ consentLog: true })` (without it the `/api/ipal/consent` endpoint does not exist) + `<SiteProviders logEndpoint="/api/ipal/consent" banner={<CookieBanner equalChoice settings="detailed" />}>` (ConsentProvider, banner, CookieButton, Analytics in the right order); settings window mode (`settings`: `inline` / `modal` / `detailed`) per the design, brief is silent → `detailed`, the decision goes to "Project decisions"; tool IDs in the panel; the cookie list from a scan (`cookieScanner: true` → *Cookie review* → **Scan cookies** → the editor accepts; or cookie-scan → import) — feeds `<CookieTable>` on the policy page **and** the lists in the `detailed` window; Cookie Settings → Detail labels in every language | consent.md, analytics.md | A, `ipal-consent-check` |
| 13 | Security | `buildSecurityHeaders` in `next.config.ts`; `twoFactor: { issuer, plugin: payloadTotp }`; CSP `report-only` → `enforce`; `IPAL_IP_HEADER` in production | security.md, forms.md | A |
| 14 | Operations | `src/app/api/health/route.ts` (`healthRoute`); `src/instrumentation.ts` with `assertEnv(ipalEnvRules({ storage: true, ipHeader: true }))`; staging with `IPAL_NOINDEX=1`; smoke tests (§8a) | `healthRoute`, `assertEnv`, `ipalEnvRules` | A |
| 15 | System pages | Site Settings → System Pages: homepage, 404, privacy policy, cookies; legal links in the footer by role (`getSystemLinks(locale)`) | `getSystemLinks`, `getSystemPagePath`, `getNotFoundPage` | P |
@@ -904,6 +904,7 @@ project → **plugin gap**, not a copy.
| Settings window: in the bar / small / large with cookie details | `<CookieBanner settings="inline" \| "modal" \| "detailed">` — do not build your own window or cookie list | consent.md → "Large window with details" |
| A consent-dependent script | `ConsentScript` | consent.md |
| Cookie table on the policy page | `<CookieTable>` (`/rsc`), `getCookieTable` | consent.md |
| Cookie list filled from the panel (drafts the editor accepts) | `ipalKit({ cookieScanner: true })` + `pnpm generate:importmap` + migration; project cookies: `cookieScanner.declarations` / `integrations` — do not type the list by hand or build your own scanner | cookie-scanner.md |
| 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 |
@@ -927,6 +928,7 @@ payloadTotp } })`, never `twoFactor: false` without a client decision). CSP: fir
| Plugin globals: write editor+ (Site Integrations: admin) | — | `ipalKit({ globalOverrides: { <slug>: { access, admin, hooks } } })`; a function `(global) => global` takes over (`applyGlobalOverrides`) |
| Global saves revalidate the layout (with `ipalKit({ revalidatePath })`) | omit `revalidatePath`; once: `context: { disableRevalidate: true }` | `buildGlobalRevalidateHook` on your own globals |
| Staff features without `access` (no roles field): every logged-in account passes (`userMeetsRole`) | add `access` (roles decide) | `globalOverrides`, `forms.formSubmissionOverrides`, `consentLog.collectionOverrides`, `stats.collectionOverrides` |
| Cookie 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 })` |
@@ -1102,6 +1104,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) |
+24 -1
View File
@@ -41,9 +41,32 @@ 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.
## 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
@@ -64,6 +64,10 @@ description: Complete map of everything @intecion/ipal-kit provides — every ip
| `forms.consentFieldName` | `'consent'` | name of the GDPR consent field `submitForm` requires (read from `config.custom.ipal`) | `createSubmitAction({ consentFieldName })` / `submitForm` argument wins |
| `consentLog` | off | `consent-records` collection + `POST /api/ipal/consent` (rate limit 20/min) | `true` / `{ retentionDays }` (default 1095) |
| `consentLog.collectionOverrides` | none | changes `consent-records`: an object merges `access` / `admin` / `hooks` key by key (your keys win), a function `(collection) => collection` takes over (keep the slug) | e.g. `{ access: { read: ({ req }) => req.user?.email === '[email protected]' } }` — narrows who reads records in a project without roles |
| `cookieScanner` | off | `cookie-review` collection (drafts an editor accepts → Cookie Settings → Cookies), "Scan cookies" box above its list (`CookieScanButton`), `GET`/`POST /api/ipal/cookie-scan`; a scan lists the cookies of the integrations switched on + names looked up in the bundled Open Cookie Database; never deletes, never overwrites edited text, never publishes by itself | `true` / object; after switching on: `pnpm generate:importmap` + `migrate:create`. Check: *Settings → Cookie review* → **Scan cookies** → drafts appear; set one to Accepted → it is in Cookie Settings → Cookies (cookie-scanner.md) |
| `cookieScanner.declarations` / `.integrations` | built-ins only | the project's own cookies (`CookieDeclaration[]`), or `(defaults) => CookieIntegration[]` to add / change / drop integrations (`key`, `label`, `declarations`, `isEnabled(ctx)`) | e.g. a chat widget on when `ctx.integrations.chatId` is filled |
| `cookieScanner.access` / `.collectionOverrides` / `.labels` | editor+ / none / `en` + `pl` | who may scan; changes `cookie-review` like `consentLog.collectionOverrides`; admin labels per language (`CookieScanLabels`) | object or function |
| `cookieScanner.database` / `.databaseCategories` / `.syncAccepted` | `true` / Functional+Personalization → functional, Security+Necessary → necessary / `true` | Open Cookie Database lookup on or off; category map; accepting writes to Cookie Settings | `database: false`; `{ Functional: 'necessary' }`; `syncAccepted: false` |
| `stats` | off | `stats-visits` collection, `POST /api/ipal/hit`, `/<admin>/stats` view, nav link, dashboard chart | `true` / object |
| `stats.collectionOverrides` | none | changes `stats-visits` like `consentLog.collectionOverrides`; its `access.read` also decides who sees the stats view and dashboard chart | object or function |
| `stats.retentionDays` / `timeZone` / `dashboard` | 90 / `'Europe/Warsaw'` / `true` | retention, day boundary, `StatsWidget` | `dashboard: false` hides the chart |
@@ -81,6 +85,7 @@ description: Complete map of everything @intecion/ipal-kit provides — every ip
| auth collection (`users`) | `{ slug, auth: true, useAsTitle: 'email' }`, when the project has none (slug: `access.authCollection` → `twoFactor.collectionSlug` → `admin.user` → `'users'`); with `access`: create/delete/unlock admin only, read/update admin or self | `access.authAccess`; your own collection with that slug | yours wins |
| `forms`, `form-submissions` | form-builder + ipal blocks `step`, `checkboxGroup`, `time` | `forms` | omit `forms` |
| `consent-records` | proof of consent (id, choices, policy version; `consentLog.collectionOverrides`) | `consentLog` | off by default |
| `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` |
@@ -90,6 +95,7 @@ description: Complete map of everything @intecion/ipal-kit provides — every ip
| `POST /api/ipal/test-email` | SMTP/Graph test (admin only) | — | **currently always** |
| `POST /api/ipal/consent` | saves consent | `consentLog` | off by default |
| `POST /api/ipal/hit` | page view for stats | `stats` | off by default |
| `GET`/`POST /api/ipal/cookie-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` |
@@ -104,6 +110,7 @@ description: Complete map of everything @intecion/ipal-kit provides — every ip
| `AdminLogo`, `AdminIcon` | `graphics.Logo/Icon` | `whiteLabel` |
| `IntecionCredit` | `afterLogin`, `afterNavLinks` | `whiteLabel` and `credit !== false` |
| `StatsNavLink`, `StatsView` (`views.ipalStats`, `/stats`), `StatsWidget` (`beforeDashboard`) | nav, view, dashboard | `stats` (`dashboard: false` without the widget) |
| `CookieScanButton` | `beforeListTable` of `cookie-review` | `cookieScanner` |
| `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 |
@@ -149,6 +156,7 @@ Mandatory set: AGENT.md §0b, skill **ipal-setup**; checks: **ipal-audit**, **ip
| forms — render | form block | `<RenderForm form={form} action={sendForm} locale={locale} texts={formTexts} classNames={formClasses} />` (`/rsc`) | form from the panel, Turnstile, message from Notifications | forms.md |
| Turnstile | panel / env | `SiteProviders` wires `TurnstileProvider`; keys in Site Integrations → Turnstile or env; server: `verifyTurnstile` (`/server`) | widget in the form; dashboard alert on a bad key | turnstile.md |
| consent | layout + policy page | banner via `SiteProviders`; table `<CookieTable rows={…} labels={…} />` (`/rsc`) from `getCookieTable` | `ipal-consent-check`; delete the consent cookie → the banner comes back | consent.md |
| cookie list | config | `cookieScanner: true` (+ `declarations` for embeds/chat), `generate:importmap`, `migrate:create` | *Cookie review* → **Scan cookies** → accept → Cookie Settings → Cookies; `<CookieBanner settings="detailed">` lists it | cookie-scanner.md |
| proof of consent | config + layout | `consentLog: true` + `logEndpoint="/api/ipal/consent"` | after a click, a document in Consent Records | consent.md |
| stats | config + layout | `stats: true` + `<SiteProviders stats={{ locale }}>` (or `<PageStats locale />` inside `ConsentProvider`) | `/<admin>/stats`; `POST /api/ipal/hit` request in Network | stats.md |
| analytics | layout | `SiteProviders` wires `Analytics` (ID from Site Integrations → Analytics); Consent Mode: `analytics={{ consentMode: 'basic' }}` = no request to Google before consent, default `'advanced'` = the Google tag loads at once with every signal `denied` | Meta/other pixels only after consent; in `basic` no `gtm.js` / `gtag/js` in Network before consent | analytics.md, gtm-meta-pixel.md |
@@ -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,7 @@ Admin panel components from `@intecion/ipal-kit/admin` — the project does NOT
| `RowLabel` | `@intecion/ipal-kit/admin` | Array row title in the panel taken from the row content (e.g. "Fast delivery" instead of "Item 01"). Do not wire by hand — use `rowLabel()`; after adding, `pnpm generate:importmap`. |
| `AdminLogo` | `@intecion/ipal-kit/admin` | Server Component: large panel logo (login screen) from SiteSettings `logo`, fallback `siteName`. Injected by the plugin with `whiteLabel`; after turning the option on, `pnpm generate:importmap`. |
| `AdminIcon` | `@intecion/ipal-kit/admin` | Server Component: small panel nav icon from SiteSettings `favicon`, fallback initials. Injected by the plugin with `whiteLabel`; after turning the option on, `pnpm generate:importmap`. |
| `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 +129,30 @@ 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. |
**Types:** `CookieScannerOptions` (the option), `CookieDeclaration`, `CookieIntegration`, `CookieScanContext`, `CookieFinding`, `CookieFindingSource`, `CookieStorage`, `LocalizedText`, `CookieScanSummary`, `CookieReviewValues`, `CookieDatabaseIndex`, `CookieScanLabels`, `OpenCookieCategory`.
## Under construction (`construction`) — details: `node_modules/@intecion/ipal-kit/docs/construction.md`
| Export | Import from | What it does / when |
+7 -3
View File
@@ -252,7 +252,8 @@ window width `max-w-4xl` — change it with `classNames.dialog`.
Which mode to choose: the project design decides. If the brief is silent → `'detailed'` (at the moment of
consent the user sees which cookies are set and by whom — full information where the decision is made),
provided the Cookies list is filled from a scan (`ipal-consent-check` → cookie-scan); an empty list = a
provided the Cookies list is filled from a scan (`ipalKit({ cookieScanner: true })` → *Cookie review* → **Scan cookies**,
[cookie-scanner.md](./cookie-scanner.md), or `ipal-consent-check` → cookie-scan); an empty list = a
window without expandable lists, then `'modal'` is enough. Record the decision in `AGENTS.md` →
"Project decisions".
@@ -342,8 +343,9 @@ independent consent state).
choices, the policy version and the time — **no IP and no user agent**. *Consent records* collection
(admin only), automatic cleanup after `retentionDays` (default 1095). Details below. Postgres:
`migrate:create`.
- **Cookie table** for the policy page: Cookie Settings → *Cookies* (filled by a scan,
skill `ipal-consent-check` → cookie-scan) + `getCookieTable` + `<CookieTable>` from `/rsc`.
- **Cookie table** for the policy page: Cookie Settings → *Cookies* + `getCookieTable` + `<CookieTable>` from `/rsc`.
Fill the list from the panel with the cookie scanner (`cookieScanner` option — drafts an editor accepts,
[cookie-scanner.md](./cookie-scanner.md)) and check the real site with `ipal-consent-check` → cookie-scan.
- Consent cookie: `cookie-consent` (`CONSENT_COOKIE`), JSON `{ id, state, timestamp, version }`,
`max-age` 180 days (`CONSENT_MAX_AGE`), `samesite=lax`, `Secure` on HTTPS. Consent with another
policy version is treated as no decision.
@@ -389,6 +391,8 @@ 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).
- **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`,
+221
View File
@@ -0,0 +1,221 @@
# cookie scanner
Fills the cookie list (Cookie Settings → Cookies) from the admin panel. A scan lists the cookies of
every integration the project switches on, plus any extra names, as **drafts** in a review list. An
editor accepts, edits or rejects each one; accepting adds it to the cookie list, which feeds the
`<CookieBanner settings="detailed">` window and `<CookieTable>` on the policy page
([consent.md](./consent.md)).
What a scan never does: delete an entry, change text an editor edited, change an entry's status, or
publish anything by itself.
Opt-in (`cookieScanner`, default off). Nothing is fetched at runtime and no browser is needed.
## Turn it on
```ts
// payload.config.ts
ipalKit({
// …
cookieScanner: true,
})
```
Then, in the project:
1. **Import map** — the "Scan cookies" box above the list is an admin component
(`@intecion/ipal-kit/admin#CookieScanButton`). Run `pnpm generate:importmap`.
2. **Postgres / SQLite migration** — the option adds the `cookie-review` collection (with localized
`purpose` and `retention`). Run `pnpm payload migrate:create cookie-scanner`, commit the migration;
Coolify runs `payload migrate` on deploy (deployment.md). MongoDB: nothing to do.
3. **Verify** — log in as an editor, open *Settings → Cookie review*. The box lists "Integrations in
use" (e.g. Cookie banner, Admin panel login, Google Analytics 4). Click **Scan cookies**: drafts
appear, each with *Found by* = Plugin integration. Set one to *Accepted*, save, open *Cookie
Settings → Cookies*: the cookie is there, with purpose and retention in every language.
## How editors use it
| Step | What happens |
|---|---|
| **Scan cookies** | One draft per cookie of the integrations in use. Cookies already in Cookie Settings → Cookies are looked up too (*In the cookie list* is ticked). |
| **More cookie names** (optional text box) | Names seen in the browser (DevTools → Application → Cookies), one per line. Each is looked up in the project's declarations, every built-in integration, then the Open Cookie Database. A name nothing knows becomes an entry with *Found by* = "Unknown — fill in" and no category. |
| Edit a draft | Change provider, category, purpose, retention. A later scan keeps every value you changed (per language) and still updates values you left as suggested. |
| **Accepted** | The cookie is added to Cookie Settings → Cookies in every language. When a row with that name already exists, only its empty provider / purpose / retention are filled — text written there stays, its category is not changed. An entry without a category cannot be accepted. |
| **Rejected** | Stays in the list as rejected; later scans do not bring it back to draft. Rejecting never removes a row from Cookie Settings — delete it there. |
Status changes work in the list's bulk edit too. Deleting review entries is admin-only and never done
by the plugin.
Labels are in English and Polish and follow the editor's admin language; `cookieScanner.labels` adds
languages or changes text.
## What the plugin declares
Each integration the plugin injects declares its cookies in one place
(`DEFAULT_COOKIE_INTEGRATIONS`): name or pattern (`*` at the end = prefix), provider, category,
purpose and retention (English and Polish), and whether it may be set before consent. Only the
integrations switched on in this project are part of a scan:
| Integration | On when | Cookies |
|---|---|---|
| Cookie banner | always | `cookie-consent` (necessary, 6 months) |
| Admin panel login | always | `payload-token` (`<cookiePrefix>-token`, necessary, editors only) |
| Language choice | more than one locale in `i18n` | `NEXT_LOCALE` (functional, session) |
| Built-in statistics | `stats` option | `ipal_vid` (analytics, 6 months) |
| Google Analytics 4 | GA4 ID in Site Integrations | `_ga`, `_ga_*` (analytics, 2 years) |
| Google Tag Manager | GTM ID in Site Integrations | `_gcl_*` (marketing — the Conversion Linker; other tags in the container: add their names or declare them) |
| Meta Pixel | Pixel ID | `_fbp`, `_fbc` (marketing, 3 months) |
| Microsoft Clarity | Clarity ID | `_clck`, `_clsk`, `CLID`, `MUID` |
| LinkedIn Insight Tag | partner ID | `li_fat_id`, `bcookie`, `lidc`, `UserMatchHistory` |
| TikTok Pixel | Pixel ID | `_ttp`, `_tt_enable_cookie` |
| Cloudflare Turnstile | both Turnstile keys set | `cf_clearance` (necessary; only when pre-clearance is on in Cloudflare) |
An ID that fails its format check counts as off. The theme switcher (`ipal-theme` in localStorage)
and the accessibility widget (`a11y-prefs`) have no plugin option, so they are not declared: add
them with `declarations` when the site uses them.
## Open Cookie Database
Unknown names are looked up in a bundled copy of the
[Open Cookie Database](https://github.com/jkwakman/Open-Cookie-Database) (about 2,300 entries,
Apache License 2.0). The package ships the license text in
[licenses/open-cookie-database-LICENSE.txt](./licenses/open-cookie-database-LICENSE.txt); the
data module names the upstream commit and the changes made (converted from CSV, two columns left
out). The table is loaded only when a scan runs.
Category mapping (`DEFAULT_DATABASE_CATEGORIES`):
| Database | Consent category |
|---|---|
| Analytics | analytics |
| Marketing | marketing |
| Necessary, Security | necessary |
| Functional, Personalization | functional |
"Functional" is **not** mapped to necessary on purpose: the database files some trackers there
(Hotjar's user id), and a lookup nobody checked yet must not skip consent. The editor lowers the
category when a cookie really is necessary, or the project changes the map:
`cookieScanner: { databaseCategories: { Functional: 'necessary' } }`.
Refresh the copy (maintainers of ipal-kit, not projects):
```bash
pnpm cookie-db:refresh
```
`scripts/refresh-cookie-database.mjs` downloads the CSV and the license at the latest commit (or
`--ref <sha>`), refuses to write if the license is no longer Apache-2.0, and rewrites
`src/modules/consent/scanner/data/openCookieDatabase.ts` and the license file. Review the diff,
run the tests, commit.
## Options
`cookieScanner: true` or an object (`CookieScannerOptions`, every key optional):
| Key | Default | What it does |
|---|---|---|
| `declarations` | `[]` | The project's own cookies (custom embeds, chat, YouTube): `CookieDeclaration[]`, always part of a scan |
| `integrations` | built-ins | `(defaults) => integrations` — filter, change or add `CookieIntegration`s (each: `key`, `label`, `declarations`, `isEnabled(ctx)`) |
| `database` | `true` | `false` = no Open Cookie Database lookup |
| `databaseCategories` | table above | Partial map from database category to consent category |
| `access` | editor and up | `({ req }) => boolean` — who may call the scan endpoint |
| `collectionOverrides` | — | Change `cookie-review`: an object merges `access` / `admin` / `hooks` key by key (your keys win), a function takes over (keep the slug) |
| `labels` | `en`, `pl` | `{ de: { scanButton: 'Cookies scannen', … } }` — merged over the plugin's labels (`CookieScanLabels`) |
| `syncAccepted` | `true` | `false` = accepting only marks the entry; nothing is written to Cookie Settings |
A project declaration:
```ts
import type { CookieDeclaration } from '@intecion/ipal-kit'
const youtube: CookieDeclaration = {
name: 'VISITOR_INFO1_LIVE',
vendor: 'Google (YouTube)',
category: 'marketing',
domain: 'youtube.com',
purpose: { en: 'YouTube: player preferences and bandwidth estimate.', pl: 'YouTube: preferencje odtwarzacza.' },
retention: { en: '6 months', pl: '6 mies.' },
setBeforeConsent: false,
}
ipalKit({ cookieScanner: { declarations: [youtube] } })
```
A project integration that is on only when a field is filled:
```ts
import type { CookieIntegration } from '@intecion/ipal-kit'
const chat: CookieIntegration = {
key: 'chat',
label: 'Live chat',
isEnabled: (ctx) => Boolean(ctx.integrations.chatWidgetId),
declarations: [/* CookieDeclaration … */],
}
ipalKit({ cookieScanner: { integrations: (defaults) => [...defaults, chat] } })
```
`ctx` (`CookieScanContext`) has `payload`, `integrations` (the Site Integrations global, depth 0) and
`plugin` (`{ localeCount, stats }`).
## Endpoint
| | |
|---|---|
| `GET /api/ipal/cookie-scan` | `{ ok, integrations: [{ key, label }] }` — what a scan covers |
| `POST /api/ipal/cookie-scan` | body `{ names?: string[] \| string }` (newline or comma separated, up to 200, names with spaces, `;`, `,` or `=` dropped) → `{ ok, summary: { created, updated, unchanged, unknown }, integrations }` |
| Access | editor and up (`userMeetsRole`; without `access` every logged-in account), or `cookieScanner.access`; otherwise `403` |
The path is `COOKIE_SCAN_PATH` (`/ipal/cookie-scan`, under the API route).
## Collection `cookie-review`
`COOKIE_REVIEW_SLUG`, group *Settings*. Fields: `name`, `storage` (`cookie` / `localStorage` /
`sessionStorage`), `category`, `vendor`, `domain`, `purpose` (localized), `retention` (localized),
`setBeforeConsent`, `status` (`draft` / `accepted` / `rejected`), and read-only `source`
(`integration` / `project` / `database` / `unknown` / `manual`), `sourceDetail`, `listed`,
`lastScannedAt`; hidden `key` (`storage:name`, unique — what a rescan matches) and `suggested` (the
last scan's values — a value still equal to it was not edited). Access: create / read / update
editor and up, delete admin.
## Building blocks
All from `@intecion/ipal-kit` (server-safe), for your own admin view, a CLI or a scheduled job:
| Export | What it does |
|---|---|
| `runCookieScan({ payload, plugin, options?, names?, req? })` | the whole scan as the endpoint runs it → `{ enabled, summary }` |
| `collectCookieFindings({ ctx, integrations?, declarations?, names?, database?, databaseCategories? })` | findings without writing anything |
| `applyCookieFindings({ payload, findings, req?, collection? })` | writes findings as drafts with the merge rules above → `CookieScanSummary` |
| `cookieScanContext(payload, plugin, req?)` | the `CookieScanContext` a scan uses |
| `parseCookieNames(input)` | the panel's text box → clean names |
| `mergeCookieReview(current, previous, next)`, `suggestionFor(finding, locales)` | the "never overwrite an edit" rule, pure |
| `addToCookieList({ payload, entry, req? })` | what accepting does: add the row or fill its empty text → `'added' \| 'filled' \| 'unchanged'` |
| `loadCookieDatabase()`, `indexCookieDatabase(rows)`, `lookupCookie(index, name, categories?)` | the Open Cookie Database lookup |
| `DEFAULT_COOKIE_INTEGRATIONS`, `DEFAULT_DATABASE_CATEGORIES`, `cookieNameMatches(pattern, name)` | declarations and matching |
| `buildCookieReviewCollection(options)`, `buildCookieScanEndpoints(options, plugin)` | the collection and endpoints, to wire by hand |
| `COOKIE_SCAN_LABELS`, `mergeCookieScanLabels(overrides)` | admin labels |
| `CookieScanButton` (`/admin`) | the box above the list |
Types: `CookieDeclaration`, `CookieIntegration`, `CookieScanContext`, `CookieFinding`,
`CookieFindingSource`, `CookieStorage`, `LocalizedText`, `CookieScannerOptions`, `CookieScanSummary`,
`CookieReviewValues`, `CookieDatabaseIndex`, `CookieScanLabels`, `OpenCookieCategory`.
## The browser scan in the skill
The panel scan knows what the plugin and the project declare. What a page really sets (a GTM tag, an
iframe, a script pasted into a block) shows only in a browser: `ipal-consent-check` → cookie-scan
(`cookie-scan.mjs`, Playwright on the developer's machine) lists every cookie before and after
consent and fails on a non-necessary cookie set before consent. Paste the names it reports as
unknown into **More cookie names** to get them into the review list.
## Turn off, override, extend
- **Turn off:** omit `cookieScanner` (default). Turning it off later keeps no endpoint and no
collection; Cookie Settings → Cookies keeps every row (it is still edited by hand or by the skill's
import script).
- **Override:** `collectionOverrides` (access, admin, hooks), `access` (who scans), `labels`,
`databaseCategories`, `integrations` (change or drop a built-in), `syncAccepted: false`.
- **Extend:** `declarations` and `integrations` for the project's own cookies; the building blocks
above for your own UI, CLI or scheduled scan.
+1
View File
@@ -9,6 +9,7 @@ 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 { IntegrationAlerts } from '../modules/integrations/IntegrationAlerts.js'
export { IntegrationStatusBanner } from '../modules/integrations/IntegrationStatusBanner.js'
export { MetaDescriptionCheck } from '../modules/seo/MetaDescriptionCheck.js'
+1 -1
View File
@@ -136,7 +136,7 @@ export const cookieSettingsFields: Field[] = [
type: 'array',
admin: {
description:
'Cookies the site uses — shown on the cookie policy page (<CookieTable>) and per category in the detailed settings window. Fill it from a scan: ipal-consent-check → cookie-scan.',
'Cookies the site uses — shown on the cookie policy page (<CookieTable>) and per category in the detailed settings window. Fill it from a scan: Cookie review → Scan cookies (cookieScanner option), or ipal-consent-check → cookie-scan.',
initCollapsed: true,
},
fields: [
+38
View File
@@ -50,6 +50,44 @@ 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,
buildCookieReviewCollection,
buildCookieScanEndpoints,
collectCookieFindings,
COOKIE_REVIEW_SLUG,
COOKIE_SCAN_LABELS,
COOKIE_SCAN_PATH,
cookieNameMatches,
cookieScanContext,
DEFAULT_COOKIE_INTEGRATIONS,
DEFAULT_DATABASE_CATEGORIES,
indexCookieDatabase,
loadCookieDatabase,
lookupCookie,
mergeCookieReview,
mergeCookieScanLabels,
parseCookieNames,
runCookieScan,
suggestionFor,
} from './modules/consent/scanner/index.js'
export type {
CookieDatabaseIndex,
CookieDeclaration,
CookieFinding,
CookieFindingSource,
CookieIntegration,
CookieReviewValues,
CookieScanContext,
CookieScanLabels,
CookieScannerOptions,
CookieScanSummary,
CookieStorage,
LocalizedText,
OpenCookieCategory,
} from './modules/consent/scanner/index.js'
export { constructionNoticeHref, isPathAllowed, isPathVisibleIn } from './modules/construction/logic.js'
export type { ConstructionMode } from './modules/construction/types.js'
export { CONSTRUCTION_NOTICE_PARAM } from './modules/construction/types.js'
@@ -0,0 +1,100 @@
'use client'
import { 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 Status =
| { kind: 'done'; summary: CookieScanSummary }
| { kind: 'error' }
| { kind: 'idle' }
| { kind: 'scanning' }
/**
* Admin UI above the Cookie review list (beforeListTable): shows which
* integrations a scan covers, takes optional extra cookie names, runs
* POST /api/ipal/cookie-scan and reloads the list. Labels in the admin language
* (`labels` from the collection config, English fallback).
*/
export function CookieScanButton({ labels = COOKIE_SCAN_LABELS }: { labels?: Record<string, CookieScanLabels> }) {
const { i18n } = useTranslation()
const { config } = useConfig()
const router = useRouter()
const t = labels[i18n.language] ?? labels.en ?? COOKIE_SCAN_LABELS.en
const endpoint = `${config.serverURL ?? ''}${config.routes?.api ?? '/api'}/ipal/cookie-scan`
const [names, setNames] = useState('')
const [integrations, setIntegrations] = useState<{ key: string; label: string }[] | null>(null)
const [status, setStatus] = useState<Status>({ kind: 'idle' })
useEffect(() => {
fetch(endpoint, { credentials: 'include' })
.then((r) => (r.ok ? r.json() : null))
.then((data: { integrations?: { key: string; label: string }[] } | null) => setIntegrations(data?.integrations ?? []))
.catch(() => setIntegrations([]))
}, [endpoint])
const scan = async () => {
setStatus({ kind: 'scanning' })
try {
const res = await fetch(endpoint, {
body: JSON.stringify({ names: names.split('\n') }),
credentials: 'include',
headers: { 'Content-Type': 'application/json' },
method: 'POST',
})
const data = (await res.json()) as { ok?: boolean; summary?: CookieScanSummary }
if (!res.ok || !data.ok || !data.summary) {throw new Error('scan failed')}
setStatus({ kind: 'done', summary: data.summary })
router.refresh()
} catch {
setStatus({ kind: 'error' })
}
}
const result = (s: CookieScanSummary) =>
t.scanResult.replace(/\{(\w+)\}/g, (_, k: string) => String(s[k as keyof CookieScanSummary] ?? ''))
return (
<div className="ipal-cookie-scan" data-ipal="cookie-scan" style={{ marginBottom: '1.5rem' }}>
<p style={{ marginTop: 0 }}>{t.scanIntro}</p>
{integrations ? (
<p style={{ fontSize: '.85rem', opacity: 0.8 }}>
{integrations.length ? `${t.integrationsFound}: ${integrations.map((i) => i.label).join(', ')}` : t.integrationsNone}
</p>
) : null}
<label className="field-label" htmlFor="ipal-cookie-scan-names">{t.namesLabel}</label>
<p style={{ fontSize: '.85rem', marginTop: 0, opacity: 0.7 }}>{t.namesHint}</p>
<textarea
aria-label={t.namesLabel}
id="ipal-cookie-scan-names"
onChange={(e) => setNames(e.target.value)}
placeholder={'_hjSessionUser_123\nintercom-id-abc'}
rows={3}
style={{ fontFamily: 'monospace', marginBottom: '.5rem', width: '100%' }}
value={names}
/>
<div style={{ alignItems: 'center', display: 'flex', flexWrap: 'wrap', gap: '1rem' }}>
<button
className="btn btn--style-primary"
disabled={status.kind === 'scanning'}
onClick={scan}
style={{ margin: 0 }}
type="button"
>
{status.kind === 'scanning' ? t.scanning : t.scanButton}
</button>
{status.kind === 'done' ? <span role="status">✓ {result(status.summary)}</span> : null}
{status.kind === 'error' ? (
<span role="alert" style={{ color: 'var(--theme-error-500, crimson)' }}>✗ {t.scanError}</span>
) : null}
</div>
</div>
)
}
export default CookieScanButton
+178
View File
@@ -0,0 +1,178 @@
import type { CollectionAfterChangeHook, CollectionBeforeChangeHook, CollectionConfig } from 'payload'
import type { CookieReviewValues } from './merge.js'
import type { CookieScannerOptions } from './types.js'
import { userMeetsRole } from '../../access/predicates.js'
import { CONSENT_CATEGORIES } from '../categories.js'
import { type CookieScanLabels, labelFor, labelRecord, mergeCookieScanLabels } from './labels.js'
import { addToCookieList } from './sync.js'
/**
* Cookie review list — drafts from "Scan cookies" that an editor accepts,
* edits or rejects. Accepting adds the cookie to Cookie Settings → Cookies
* (the banner's detailed window and <CookieTable>). Opt-in:
* `ipalKit({ cookieScanner: true })`.
*/
export const COOKIE_REVIEW_SLUG = 'cookie-review'
const setKey: CollectionBeforeChangeHook = ({ data, originalDoc }) => {
const name = (data.name ?? originalDoc?.name)?.trim()
const storage = data.storage ?? originalDoc?.storage ?? 'cookie'
if (name) {
data.name = name
data.key = `${storage}:${name}`
}
return data
}
function buildSyncHook(): CollectionAfterChangeHook {
return async ({ context, doc, previousDoc, req }) => {
if (context?.ipalCookieScan || doc.status !== 'accepted' || previousDoc?.status === 'accepted') {return doc}
// Local API calls with `req` rewrite req.locale / req.fallbackLocale; the editor's own
// save is still being read after this hook, so put them back.
const { fallbackLocale, locale } = req
try {
const full = (await req.payload.findByID({
id: doc.id,
collection: COOKIE_REVIEW_SLUG as never,
depth: 0,
locale: (req.payload.config.localization ? 'all' : undefined) as never,
overrideAccess: true,
req,
})) as unknown as { name: string } & CookieReviewValues
const result = await addToCookieList({ entry: full, payload: req.payload, req })
req.payload.logger.info(`[ipal] cookie review: "${full.name}" accepted → Cookie Settings (${result})`)
if (!doc.listed) {
await req.payload.update({
id: doc.id,
collection: COOKIE_REVIEW_SLUG as never,
context: { ipalCookieScan: true },
data: { listed: true } as never,
overrideAccess: true,
req,
})
}
} finally {
req.locale = locale
req.fallbackLocale = fallbackLocale
}
return { ...doc, listed: true }
}
}
export function buildCookieReviewCollection(options: CookieScannerOptions = {}): CollectionConfig {
const labels = mergeCookieScanLabels(options.labels)
const L = (key: keyof CookieScanLabels) => labelRecord(labels, key)
return {
slug: COOKIE_REVIEW_SLUG,
access: {
// Written by editors (review) and by the scan (Local API); deleting is admin-only and never automatic.
create: ({ req }) => userMeetsRole(req, 'editor'),
delete: ({ req }) => userMeetsRole(req, 'admin'),
read: ({ req }) => userMeetsRole(req, 'editor'),
update: ({ req }) => userMeetsRole(req, 'editor'),
},
admin: {
components: {
beforeListTable: [{ clientProps: { labels }, path: '@intecion/ipal-kit/admin#CookieScanButton' }],
},
defaultColumns: ['name', 'vendor', 'category', 'status', 'source', 'listed'],
description: L('collectionDescription'),
group: 'Settings',
listSearchableFields: ['name', 'vendor'],
useAsTitle: 'name',
},
fields: [
{
type: 'row',
fields: [
{ name: 'name', type: 'text', admin: { width: '50%' }, label: L('name'), required: true },
{
name: 'storage',
type: 'select',
admin: { width: '25%' },
defaultValue: 'cookie',
label: L('storage'),
options: [
{ label: L('cookie'), value: 'cookie' },
{ label: L('localStorage'), value: 'localStorage' },
{ label: L('sessionStorage'), value: 'sessionStorage' },
],
required: true,
},
{
name: 'category',
type: 'select',
admin: { width: '25%' },
label: L('category'),
options: CONSENT_CATEGORIES.map((c) => ({ label: L(c), value: c })),
validate: (value: unknown, { req, siblingData }: { req: { i18n?: { language?: string } }; siblingData: { status?: string } }) =>
siblingData?.status === 'accepted' && !value ? labelFor(labels, req.i18n?.language, 'categoryRequired') : true,
},
],
},
{
type: 'row',
fields: [
{ name: 'vendor', type: 'text', admin: { width: '50%' }, label: L('vendor') },
{ name: 'domain', type: 'text', admin: { width: '50%' }, label: L('domain') },
],
},
{ name: 'purpose', type: 'textarea', label: L('purpose'), localized: true },
{ name: 'retention', type: 'text', label: L('retention'), localized: true },
{
name: 'setBeforeConsent',
type: 'checkbox',
admin: { description: L('setBeforeConsentDescription') },
label: L('setBeforeConsent'),
},
{
name: 'status',
type: 'select',
admin: { description: L('statusDescription'), position: 'sidebar' },
defaultValue: 'draft',
index: true,
label: L('status'),
options: [
{ label: L('draft'), value: 'draft' },
{ label: L('accepted'), value: 'accepted' },
{ label: L('rejected'), value: 'rejected' },
],
required: true,
},
{
name: 'source',
type: 'select',
admin: { position: 'sidebar', readOnly: true },
defaultValue: 'manual',
label: L('source'),
options: [
{ label: L('integration'), value: 'integration' },
{ label: L('project'), value: 'project' },
{ label: L('database'), value: 'database' },
{ label: L('unknown'), value: 'unknown' },
{ label: L('manual'), value: 'manual' },
],
},
{ name: 'sourceDetail', type: 'text', admin: { position: 'sidebar', readOnly: true }, label: L('sourceDetail') },
{
name: 'listed',
type: 'checkbox',
admin: { description: L('listedDescription'), position: 'sidebar', readOnly: true },
label: L('listed'),
},
{ name: 'lastScannedAt', type: 'date', admin: { position: 'sidebar', readOnly: true }, label: L('lastScannedAt') },
// `storage:name`, one entry per cookie — what a rescan matches on.
{ name: 'key', type: 'text', admin: { hidden: true }, index: true, unique: true },
// The last scan's suggestion: a value still equal to it was not edited and may follow the next scan.
{ name: 'suggested', type: 'json', admin: { hidden: true } },
],
hooks: {
afterChange: options.syncAccepted === false ? [] : [buildSyncHook()],
beforeChange: [setKey],
},
labels: { plural: L('plural'), singular: L('singular') },
timestamps: true,
}
}
@@ -0,0 +1,78 @@
import type { ConsentCategory } from '../categories.js'
import type { OpenCookieRow } from './data/openCookieDatabase.js'
import type { CookieFinding, OpenCookieCategory } from './types.js'
/**
* Lookup in the bundled Open Cookie Database (Apache-2.0,
* github.com/jkwakman/Open-Cookie-Database; license in
* docs/licenses/open-cookie-database-LICENSE.txt). Refreshed by
* `scripts/refresh-cookie-database.mjs` — nothing is fetched at runtime. The
* ~430 KB table is imported only when a scan needs it.
*/
export const DEFAULT_DATABASE_CATEGORIES: Record<OpenCookieCategory, ConsentCategory> = {
Analytics: 'analytics',
// The database defines Functional as "technical, essential or strictly necessary", but
// contributors file trackers there too (Hotjar's user id). An unchecked lookup must not
// land as "no consent needed": it asks for consent until an editor says otherwise.
Functional: 'functional',
Marketing: 'marketing',
Necessary: 'necessary',
Personalization: 'functional',
Security: 'necessary',
}
/** An index over database rows: exact names, then prefixes (longest first). */
export type CookieDatabaseIndex = {
exact: Map<string, OpenCookieRow>
prefixes: OpenCookieRow[]
}
export function indexCookieDatabase(rows: readonly OpenCookieRow[]): CookieDatabaseIndex {
const exact = new Map<string, OpenCookieRow>()
const prefixes: OpenCookieRow[] = []
for (const row of rows) {
if (row[7] === 1) {prefixes.push(row)}
else if (!exact.has(row[0])) {exact.set(row[0], row)}
}
prefixes.sort((a, b) => b[0].length - a[0].length)
return { exact, prefixes }
}
let bundled: CookieDatabaseIndex | null = null
/** The bundled database, indexed once per process. */
export async function loadCookieDatabase(): Promise<CookieDatabaseIndex> {
if (!bundled) {
const { OPEN_COOKIE_DATABASE } = await import('./data/openCookieDatabase.js')
bundled = indexCookieDatabase(OPEN_COOKIE_DATABASE)
}
return bundled
}
/**
* A cookie name looked up in the database: exact name first, then the longest
* matching wildcard prefix (`_gac_` matches `_gac_UA-1`). Null when unknown.
*/
export function lookupCookie(
index: CookieDatabaseIndex,
name: string,
categories: Partial<Record<OpenCookieCategory, ConsentCategory>> = {},
): CookieFinding | null {
const row = index.exact.get(name) ?? index.prefixes.find((r) => r[0] && name.startsWith(r[0]))
if (!row) {return null}
const [pattern, platform, category, domain, description, retention, controller, wildcard] = row
const map = { ...DEFAULT_DATABASE_CATEGORIES, ...categories }
const thirdParty = /\(3rd party\)/i.test(domain) ? domain.replace(/\s*\(3rd party\)/i, '').trim() : ''
return {
category: map[category as OpenCookieCategory],
...(thirdParty ? { domain: thirdParty } : {}),
name: wildcard === 1 && pattern !== name ? `${pattern}*` : name,
...(description ? { purpose: description } : {}),
...(retention ? { retention } : {}),
source: 'database',
sourceDetail: `Open Cookie Database: ${platform}${category ? ` (${category})` : ''}`,
storage: 'cookie',
vendor: controller || platform,
}
}
+54
View File
@@ -0,0 +1,54 @@
import type { Endpoint, PayloadRequest } from 'payload'
import type { CookieScanContext, CookieScannerOptions } from './types.js'
import { userMeetsRole } from '../../access/predicates.js'
import { DEFAULT_COOKIE_INTEGRATIONS } from './integrations.js'
import { cookieScanContext, enabledCookieIntegrations, parseCookieNames, runCookieScan } from './scan.js'
export const COOKIE_SCAN_PATH = '/ipal/cookie-scan'
/**
* GET /api/ipal/cookie-scan → `{ integrations: [{ key, label }] }` — what a scan would cover.
* POST /api/ipal/cookie-scan, body `{ names?: string[] | string }` → runs a scan,
* `{ ok, summary: { created, updated, unchanged, unknown }, integrations }`.
* Editors and up by default (`cookieScanner.access`).
*/
export function buildCookieScanEndpoints(options: CookieScannerOptions, plugin: CookieScanContext['plugin']): Endpoint[] {
const allowed = async (req: PayloadRequest) =>
options.access ? Boolean(await options.access({ req })) : userMeetsRole(req, 'editor')
const integrations = options.integrations ? options.integrations(DEFAULT_COOKIE_INTEGRATIONS) : DEFAULT_COOKIE_INTEGRATIONS
const list = (items: { key: string; label: string }[]) => items.map(({ key, label }) => ({ key, label }))
return [
{
handler: async (req) => {
if (!(await allowed(req))) {return Response.json({ ok: false }, { status: 403 })}
const enabled = await enabledCookieIntegrations(integrations, await cookieScanContext(req.payload, plugin, req))
return Response.json({ integrations: list(enabled), ok: true })
},
method: 'get',
path: COOKIE_SCAN_PATH,
},
{
handler: async (req) => {
if (!(await allowed(req))) {return Response.json({ ok: false }, { status: 403 })}
let body: { names?: unknown } = {}
try {
body = ((await (req as unknown as Request).json()) ?? {}) as { names?: unknown }
} catch {
// empty body = scan without extra names
}
try {
const { enabled, summary } = await runCookieScan({ names: parseCookieNames(body.names), options, payload: req.payload, plugin, req })
return Response.json({ integrations: list(enabled), ok: true, summary })
} catch (err) {
req.payload.logger.error(`[ipal] cookie scan failed: ${err instanceof Error ? err.message : String(err)}`)
return Response.json({ ok: false }, { status: 500 })
}
},
method: 'post',
path: COOKIE_SCAN_PATH,
},
]
}
+24
View File
@@ -0,0 +1,24 @@
// Cookie scanner — server-safe building blocks. The admin button is in /admin.
export { buildCookieReviewCollection, COOKIE_REVIEW_SLUG } from './collection.js'
export { DEFAULT_DATABASE_CATEGORIES, indexCookieDatabase, loadCookieDatabase, lookupCookie } from './cookieDatabase.js'
export type { CookieDatabaseIndex } from './cookieDatabase.js'
export { buildCookieScanEndpoints, COOKIE_SCAN_PATH } from './endpoint.js'
export { cookieNameMatches, DEFAULT_COOKIE_INTEGRATIONS } from './integrations.js'
export { COOKIE_SCAN_LABELS, mergeCookieScanLabels } from './labels.js'
export type { CookieScanLabels } from './labels.js'
export { mergeCookieReview, suggestionFor } from './merge.js'
export type { CookieReviewValues } from './merge.js'
export { applyCookieFindings, collectCookieFindings, cookieScanContext, parseCookieNames, runCookieScan } from './scan.js'
export { addToCookieList } from './sync.js'
export type {
CookieDeclaration,
CookieFinding,
CookieFindingSource,
CookieIntegration,
CookieScanContext,
CookieScannerOptions,
CookieScanSummary,
CookieStorage,
LocalizedText,
OpenCookieCategory,
} from './types.js'
+292
View File
@@ -0,0 +1,292 @@
import type { CookieDeclaration, CookieIntegration, CookieScanContext } from './types.js'
import { validAnalyticsId } from '../../analytics/idFormats.js'
import { LOCALE_COOKIE_NAME } from '../../i18n/negotiateLocale.js'
import { getTurnstileConfig } from '../../turnstile/config.js'
import { CONSENT_COOKIE } from '../storage.js'
/** A tag ID from Site Integrations is filled in and valid. */
const hasId = (field: string) => (ctx: CookieScanContext) =>
Boolean(validAnalyticsId(field as never, ctx.integrations[field]))
const T = (en: string, pl: string) => ({ en, pl })
const SESSION = T('Session', 'Sesja')
const days = (n: number) => T(`${n} days`, `${n} dni`)
const months = (n: number) => T(`${n} months`, `${n} mies.`)
const YEAR = T('1 year', '1 rok')
const TWO_YEARS = T('2 years', '2 lata')
const SITE = 'This site'
/**
* Cookies of everything the plugin itself injects — one place per integration.
* Each one is part of a scan only when this project switches it on (an ID in
* Site Integrations, a plugin option). Change the list with
* `cookieScanner.integrations: (defaults) => …`.
*/
export const DEFAULT_COOKIE_INTEGRATIONS: CookieIntegration[] = [
{
declarations: [
{
name: CONSENT_COOKIE,
category: 'necessary',
purpose: T('Stores your cookie consent decision.', 'Zapamiętuje Twoją decyzję w sprawie plików cookie.'),
retention: months(6),
setBeforeConsent: false,
vendor: SITE,
},
],
isEnabled: () => true,
key: 'consent',
label: 'Cookie banner',
},
{
declarations: (ctx) => [
{
name: `${ctx.payload.config.cookiePrefix ?? 'payload'}-token`,
category: 'necessary',
purpose: T('Session of a logged-in editor (admin panel only).', 'Sesja zalogowanego redaktora (tylko panel administracyjny).'),
retention: T('Until logout (2 hours by default)', 'Do wylogowania (domyślnie 2 godziny)'),
setBeforeConsent: true,
vendor: SITE,
},
],
isEnabled: () => true,
key: 'admin',
label: 'Admin panel login',
},
{
declarations: [
{
name: LOCALE_COOKIE_NAME,
category: 'functional',
purpose: T('Remembers the selected site language.', 'Zapamiętuje wybrany język strony.'),
retention: SESSION,
setBeforeConsent: false,
vendor: SITE,
},
],
isEnabled: (ctx) => ctx.plugin.localeCount > 1,
key: 'locale',
label: 'Language choice',
},
{
declarations: [
{
name: 'ipal_vid', // VISITOR_COOKIE — that file is a client component
category: 'analytics',
purpose: T(
'Built-in statistics: random visitor id that joins your visits across days. Set only with analytics consent.',
'Wbudowane statystyki: losowy identyfikator łączący Twoje wizyty z różnych dni. Tylko po zgodzie na analitykę.',
),
retention: months(6),
setBeforeConsent: false,
vendor: SITE,
},
],
isEnabled: (ctx) => ctx.plugin.stats,
key: 'stats',
label: 'Built-in statistics',
},
{
declarations: [
{
name: '_ga',
category: 'analytics',
purpose: T('Google Analytics: distinguishes users in statistics.', 'Google Analytics: rozróżnia użytkowników w statystykach.'),
retention: TWO_YEARS,
setBeforeConsent: false,
vendor: 'Google',
},
{
name: '_ga_*',
category: 'analytics',
purpose: T('Google Analytics: keeps the session state.', 'Google Analytics: przechowuje stan sesji.'),
retention: TWO_YEARS,
setBeforeConsent: false,
vendor: 'Google',
},
],
isEnabled: hasId('ga4MeasurementId'),
key: 'ga4',
label: 'Google Analytics 4',
},
{
// GTM itself sets no cookie; its tags do. The Conversion Linker (Google Ads)
// is the usual one — anything else the container fires shows up in a crawl.
declarations: [
{
name: '_gcl_*',
category: 'marketing',
purpose: T(
'Google Ads (via Google Tag Manager): attributes conversions to ad clicks.',
'Google Ads (przez Google Tag Manager): przypisuje konwersje do kliknięć reklam.',
),
retention: months(3),
setBeforeConsent: false,
vendor: 'Google',
},
],
isEnabled: hasId('gtmContainerId'),
key: 'gtm',
label: 'Google Tag Manager',
},
{
declarations: [
{
name: '_fbp',
category: 'marketing',
purpose: T('Meta Pixel: ad measurement and targeting.', 'Meta Pixel: pomiar i dopasowanie reklam.'),
retention: months(3),
setBeforeConsent: false,
vendor: 'Meta',
},
{
name: '_fbc',
category: 'marketing',
purpose: T('Meta Pixel: stores the last ad click.', 'Meta Pixel: zapamiętuje ostatnie kliknięcie reklamy.'),
retention: months(3),
setBeforeConsent: false,
vendor: 'Meta',
},
],
isEnabled: hasId('metaPixelId'),
key: 'metaPixel',
label: 'Meta Pixel',
},
{
declarations: [
{
name: '_clck',
category: 'analytics',
purpose: T('Clarity: user id for behaviour analytics.', 'Clarity: identyfikator użytkownika w analizie zachowań.'),
retention: YEAR,
setBeforeConsent: false,
vendor: 'Microsoft Clarity',
},
{
name: '_clsk',
category: 'analytics',
purpose: T('Clarity: joins page views into one session.', 'Clarity: łączy odsłony w jedną sesję.'),
retention: T('1 day', '1 dzień'),
setBeforeConsent: false,
vendor: 'Microsoft Clarity',
},
{
name: 'CLID',
category: 'analytics',
domain: 'clarity.ms',
purpose: T('Clarity: user id across sites using Clarity.', 'Clarity: identyfikator użytkownika między stronami z Clarity.'),
retention: YEAR,
setBeforeConsent: false,
vendor: 'Microsoft Clarity',
},
{
name: 'MUID',
category: 'marketing',
domain: 'clarity.ms',
purpose: T('Microsoft: browser id used across Microsoft services and ads.', 'Microsoft: identyfikator przeglądarki w usługach i reklamach Microsoft.'),
retention: YEAR,
setBeforeConsent: false,
vendor: 'Microsoft',
},
],
isEnabled: hasId('clarityProjectId'),
key: 'clarity',
label: 'Microsoft Clarity',
},
{
declarations: [
{
name: 'li_fat_id',
category: 'marketing',
purpose: T('LinkedIn Insight Tag: conversion attribution.', 'LinkedIn Insight Tag: przypisanie konwersji.'),
retention: days(30),
setBeforeConsent: false,
vendor: 'LinkedIn',
},
{
name: 'bcookie',
category: 'marketing',
domain: 'linkedin.com',
purpose: T('LinkedIn: browser id.', 'LinkedIn: identyfikator przeglądarki.'),
retention: YEAR,
setBeforeConsent: false,
vendor: 'LinkedIn',
},
{
name: 'lidc',
category: 'marketing',
domain: 'linkedin.com',
purpose: T('LinkedIn: data-centre routing.', 'LinkedIn: wybór centrum danych.'),
retention: T('1 day', '1 dzień'),
setBeforeConsent: false,
vendor: 'LinkedIn',
},
{
name: 'UserMatchHistory',
category: 'marketing',
domain: 'linkedin.com',
purpose: T('LinkedIn Ads: id sync with ad partners.', 'LinkedIn Ads: synchronizacja identyfikatorów z partnerami reklamowymi.'),
retention: days(30),
setBeforeConsent: false,
vendor: 'LinkedIn',
},
],
isEnabled: hasId('linkedInPartnerId'),
key: 'linkedIn',
label: 'LinkedIn Insight Tag',
},
{
declarations: [
{
name: '_ttp',
category: 'marketing',
purpose: T('TikTok Pixel: ad measurement.', 'TikTok Pixel: pomiar reklam.'),
retention: months(13),
setBeforeConsent: false,
vendor: 'TikTok',
},
{
name: '_tt_enable_cookie',
category: 'marketing',
purpose: T('TikTok Pixel: checks that cookies work.', 'TikTok Pixel: sprawdza, czy cookies działają.'),
retention: months(13),
setBeforeConsent: false,
vendor: 'TikTok',
},
],
isEnabled: hasId('tiktokPixelId'),
key: 'tiktok',
label: 'TikTok Pixel',
},
{
// Turnstile hands back a one-time token; cf_clearance appears only when the
// widget has pre-clearance switched on in the Cloudflare dashboard.
declarations: [
{
name: 'cf_clearance',
category: 'necessary',
purpose: T(
'Cloudflare Turnstile: proves the anti-spam check was passed (only with pre-clearance on).',
'Cloudflare Turnstile: potwierdza przejście zabezpieczenia antyspamowego (tylko z włączonym pre-clearance).',
),
retention: T('30 minutes (set in Cloudflare)', '30 minut (ustawiane w Cloudflare)'),
setBeforeConsent: true,
vendor: 'Cloudflare',
},
],
isEnabled: async (ctx) => (await getTurnstileConfig(ctx.payload)).enabled,
key: 'turnstile',
label: 'Cloudflare Turnstile',
},
]
/** An integration's declarations for this project. */
export function declarationsOf(integration: CookieIntegration, ctx: CookieScanContext): CookieDeclaration[] {
return typeof integration.declarations === 'function' ? integration.declarations(ctx) : integration.declarations
}
/** True when `name` matches `pattern` (a trailing `*` = prefix). */
export function cookieNameMatches(pattern: string, name: string): boolean {
return pattern.endsWith('*') ? name.startsWith(pattern.slice(0, -1)) : name === pattern
}
+168
View File
@@ -0,0 +1,168 @@
/**
* Admin labels of the cookie scanner, per admin language. Payload picks the
* user's admin language from a `{ en, pl }` record; a language missing here falls
* back to English. Projects add or change languages with `cookieScanner.labels`.
*/
export type CookieScanLabels = {
accepted: string
analytics: string
category: string
categoryRequired: string
collectionDescription: string
cookie: string
database: string
domain: string
draft: string
functional: string
integration: string
integrationsFound: string
integrationsNone: string
lastScannedAt: string
listed: string
listedDescription: string
localStorage: string
manual: string
marketing: string
name: string
namesHint: string
namesLabel: string
necessary: string
plural: string
project: string
purpose: string
rejected: string
retention: string
scanButton: string
scanError: string
scanIntro: string
scanning: string
/** `{created}`, `{updated}`, `{unchanged}`, `{unknown}` are filled in. */
scanResult: string
sessionStorage: string
setBeforeConsent: string
setBeforeConsentDescription: string
singular: string
source: string
sourceDetail: string
status: string
statusDescription: string
storage: string
unknown: string
vendor: string
}
export const COOKIE_SCAN_LABELS: Record<'en' | 'pl', CookieScanLabels> = {
en: {
name: 'Name',
accepted: 'Accepted',
analytics: 'Analytics',
category: 'Category',
categoryRequired: 'Pick a category before accepting.',
collectionDescription:
'Cookies found by "Scan cookies". Check each draft, then set it to Accepted (it is added to Cookie Settings → Cookies) or Rejected. A scan never deletes entries and never changes text you edited.',
cookie: 'Cookie',
database: 'Open Cookie Database',
domain: 'Domain',
draft: 'Draft',
functional: 'Functional',
integration: 'Plugin integration',
integrationsFound: 'Integrations in use',
integrationsNone: 'No integration with cookies is switched on.',
lastScannedAt: 'Last seen by a scan',
listed: 'In the cookie list',
listedDescription: 'Already in Cookie Settings → Cookies.',
localStorage: 'Local storage',
manual: 'Added by hand',
marketing: 'Marketing',
namesHint: 'Optional: cookie names seen in the browser (DevTools → Application → Cookies), one per line. They are looked up in the plugin and the Open Cookie Database.',
namesLabel: 'More cookie names',
necessary: 'Necessary',
plural: 'Cookie review',
project: 'Project declaration',
purpose: 'Purpose',
rejected: 'Rejected',
retention: 'Retention',
scanButton: 'Scan cookies',
scanError: 'The scan failed.',
scanIntro: 'Lists the cookies of the integrations switched on in this project as drafts to review.',
scanning: 'Scanning…',
scanResult: '{created} new, {updated} updated, {unchanged} unchanged, {unknown} unknown.',
sessionStorage: 'Session storage',
setBeforeConsent: 'Set before consent',
setBeforeConsentDescription: 'May be set before the visitor decides. Only necessary cookies should be.',
singular: 'Cookie review entry',
source: 'Found by',
sourceDetail: 'Source',
status: 'Status',
statusDescription: 'Accepted → added to Cookie Settings → Cookies. Rejecting never removes a row from that list.',
storage: 'Stored in',
unknown: 'Unknown — fill in',
vendor: 'Provider',
},
pl: {
name: 'Nazwa',
accepted: 'Zaakceptowany',
analytics: 'Analityczne',
category: 'Kategoria',
categoryRequired: 'Wybierz kategorię przed akceptacją.',
collectionDescription:
'Pliki cookie znalezione przez „Skanuj cookies”. Sprawdź każdy szkic i ustaw Zaakceptowany (trafi do Ustawień cookies → Cookies) albo Odrzucony. Skan nigdy nie usuwa wpisów ani nie zmienia poprawionych przez Ciebie tekstów.',
cookie: 'Cookie',
database: 'Open Cookie Database',
domain: 'Domena',
draft: 'Szkic',
functional: 'Funkcjonalne',
integration: 'Integracja wtyczki',
integrationsFound: 'Używane integracje',
integrationsNone: 'Żadna integracja z plikami cookie nie jest włączona.',
lastScannedAt: 'Ostatnio widziany w skanie',
listed: 'Na liście cookies',
listedDescription: 'Już jest w Ustawieniach cookies → Cookies.',
localStorage: 'Local storage',
manual: 'Dodany ręcznie',
marketing: 'Marketingowe',
namesHint: 'Opcjonalnie: nazwy cookies widoczne w przeglądarce (DevTools → Application → Cookies), po jednej w wierszu. Zostaną wyszukane we wtyczce i w Open Cookie Database.',
namesLabel: 'Dodatkowe nazwy cookies',
necessary: 'Niezbędne',
plural: 'Przegląd cookies',
project: 'Deklaracja projektu',
purpose: 'Cel',
rejected: 'Odrzucony',
retention: 'Czas przechowywania',
scanButton: 'Skanuj cookies',
scanError: 'Skan się nie powiódł.',
scanIntro: 'Dodaje cookies integracji włączonych w tym projekcie jako szkice do przejrzenia.',
scanning: 'Skanowanie…',
scanResult: 'Nowe: {created}, zaktualizowane: {updated}, bez zmian: {unchanged}, nieznane: {unknown}.',
sessionStorage: 'Session storage',
setBeforeConsent: 'Ustawiany przed zgodą',
setBeforeConsentDescription: 'Może powstać, zanim odwiedzający zdecyduje. Tylko niezbędne cookies powinny.',
singular: 'Wpis przeglądu cookies',
source: 'Źródło',
sourceDetail: 'Skąd',
status: 'Status',
statusDescription: 'Zaakceptowany → trafia do Ustawień cookies → Cookies. Odrzucenie nigdy nie usuwa wiersza z tej listy.',
storage: 'Przechowywany w',
unknown: 'Nieznany — uzupełnij',
vendor: 'Dostawca',
},
}
/** Plugin labels with the project's languages and changes merged over them. */
export function mergeCookieScanLabels(overrides: Record<string, Partial<CookieScanLabels>> = {}): Record<string, CookieScanLabels> {
const out: Record<string, CookieScanLabels> = { ...COOKIE_SCAN_LABELS }
for (const [lang, labels] of Object.entries(overrides)) {
out[lang] = { ...(out[lang] ?? COOKIE_SCAN_LABELS.en), ...labels }
}
return out
}
/** One label as a Payload `{ en, pl, … }` record. */
export function labelRecord(labels: Record<string, CookieScanLabels>, key: keyof CookieScanLabels): Record<string, string> {
return Object.fromEntries(Object.entries(labels).map(([lang, l]) => [lang, l[key]]))
}
/** One label in one language (English when the language is missing). */
export function labelFor(labels: Record<string, CookieScanLabels>, lang: string | undefined, key: keyof CookieScanLabels): string {
return (lang && labels[lang]?.[key]) || labels.en?.[key] || COOKIE_SCAN_LABELS.en[key]
}
+82
View File
@@ -0,0 +1,82 @@
import type { ConsentCategory } from '../categories.js'
import type { CookieFinding, LocalizedText } from './types.js'
/** The editable values of a review entry; `purpose` / `retention` per locale. */
export type CookieReviewValues = {
category?: ConsentCategory | null
domain?: null | string
purpose?: Record<string, null | string>
retention?: Record<string, null | string>
setBeforeConsent?: boolean | null
vendor?: null | string
}
const SCALARS = ['category', 'domain', 'setBeforeConsent', 'vendor'] as const
const TEXTS = ['purpose', 'retention'] as const
/** Text for one locale: that language, else English, else the first one given. */
export function textFor(text: LocalizedText | undefined, locale: string): string | undefined {
if (text === undefined) {return undefined}
if (typeof text === 'string') {return text}
return text[locale] ?? text.en ?? Object.values(text)[0]
}
/** What a scan suggests for an entry, resolved for the project's locales. */
export function suggestionFor(finding: CookieFinding, locales: string[]): CookieReviewValues {
const perLocale = (text: LocalizedText | undefined) => {
if (text === undefined) {return undefined}
return Object.fromEntries(locales.map((l) => [l, textFor(text, l) ?? null]))
}
const out: CookieReviewValues = {}
if (finding.category) {out.category = finding.category}
if (finding.domain) {out.domain = finding.domain}
if (finding.vendor) {out.vendor = finding.vendor}
if (typeof finding.setBeforeConsent === 'boolean') {out.setBeforeConsent = finding.setBeforeConsent}
const purpose = perLocale(finding.purpose)
const retention = perLocale(finding.retention)
if (purpose) {out.purpose = purpose}
if (retention) {out.retention = retention}
return out
}
const isEmpty = (v: unknown) => v === undefined || v === null || v === ''
/**
* New values for an entry after a scan. A value takes the new suggestion only
* while it is empty or still equal to what the previous scan suggested — once an
* editor changed it, it is theirs and stays. Text is compared per locale.
*/
export function mergeCookieReview(
current: CookieReviewValues,
previous: CookieReviewValues | null | undefined,
next: CookieReviewValues,
): { changed: boolean; values: CookieReviewValues } {
const prev = previous ?? {}
const values: CookieReviewValues = { ...current }
let changed = false
const pick = <V>(cur: V, before: undefined | V, suggested: undefined | V): V => {
if (suggested === undefined || isEmpty(suggested)) {return cur}
if (isEmpty(cur) || cur === before) {return suggested}
return cur
}
for (const key of SCALARS) {
const v = pick(current[key], prev[key], next[key])
if (v !== current[key]) {
;(values as Record<string, unknown>)[key] = v
changed = true
}
}
for (const key of TEXTS) {
const cur = current[key] ?? {}
const merged = { ...cur }
for (const [locale, suggested] of Object.entries(next[key] ?? {})) {
const v = pick(cur[locale], prev[key]?.[locale], suggested)
if (v !== cur[locale]) {
merged[locale] = v ?? null
changed = true
}
}
if (Object.keys(merged).length) {values[key] = merged}
}
return { changed, values }
}
+255
View File
@@ -0,0 +1,255 @@
import type { BasePayload, PayloadRequest } from 'payload'
import type { CookieReviewValues } from './merge.js'
import type {
CookieDeclaration,
CookieFinding,
CookieIntegration,
CookieScanContext,
CookieScannerOptions,
CookieScanSummary,
CookieStorage,
} from './types.js'
import { COOKIE_REVIEW_SLUG } from './collection.js'
import { loadCookieDatabase, lookupCookie } from './cookieDatabase.js'
import { cookieNameMatches, declarationsOf, DEFAULT_COOKIE_INTEGRATIONS } from './integrations.js'
import { mergeCookieReview, suggestionFor } from './merge.js'
/** Most names one scan looks up — the panel field is for a handful, not a dump. */
export const MAX_SCAN_NAMES = 200
/** Cookie / storage key names as browsers allow them: no spaces, `;`, `,` or `=`. */
const NAME = /^[^\s;,=]{1,200}$/
/** Names from the panel's text box: trimmed, de-duplicated, invalid ones dropped. */
export function parseCookieNames(input: unknown): string[] {
const list = Array.isArray(input) ? input : typeof input === 'string' ? input.split(/[\n,]/) : []
const out = new Set<string>()
for (const raw of list) {
if (typeof raw !== 'string') {continue}
const name = raw.trim()
if (NAME.test(name)) {out.add(name)}
if (out.size >= MAX_SCAN_NAMES) {break}
}
return [...out]
}
const reviewKey = (storage: CookieStorage, name: string) => `${storage}:${name}`
function fromDeclaration(d: CookieDeclaration, source: 'integration' | 'project', sourceDetail: string): CookieFinding {
return {
category: d.category,
...(d.domain ? { domain: d.domain } : {}),
name: d.name,
purpose: d.purpose,
retention: d.retention,
setBeforeConsent: d.setBeforeConsent,
source,
sourceDetail,
storage: d.storage ?? 'cookie',
vendor: d.vendor,
}
}
/** The integrations this project uses (a failing check counts as off and is logged). */
export async function enabledCookieIntegrations(
integrations: CookieIntegration[],
ctx: CookieScanContext,
): Promise<CookieIntegration[]> {
const on: CookieIntegration[] = []
for (const integration of integrations) {
try {
if (await integration.isEnabled(ctx)) {on.push(integration)}
} catch (err) {
ctx.payload.logger.warn(`[ipal] cookie scan: could not check "${integration.key}": ${err instanceof Error ? err.message : String(err)}`)
}
}
return on
}
/**
* Everything a scan reports, before anything is written: the cookies of the
* enabled integrations, the project's declarations, and each extra name looked
* up in the project's declarations, every built-in integration, then the Open
* Cookie Database. A name nothing knows comes back with `source: 'unknown'`.
*/
export async function collectCookieFindings({
ctx,
database = true,
databaseCategories,
declarations = [],
integrations = DEFAULT_COOKIE_INTEGRATIONS,
names = [],
}: {
ctx: CookieScanContext
database?: boolean
databaseCategories?: CookieScannerOptions['databaseCategories']
declarations?: CookieDeclaration[]
integrations?: CookieIntegration[]
names?: string[]
}): Promise<{ enabled: CookieIntegration[]; findings: CookieFinding[] }> {
const enabled = await enabledCookieIntegrations(integrations, ctx)
const found = new Map<string, CookieFinding>()
const add = (f: CookieFinding) => {
const key = reviewKey(f.storage, f.name)
if (!found.has(key)) {found.set(key, f)}
}
for (const d of declarations) {add(fromDeclaration(d, 'project', 'Project'))}
for (const integration of enabled) {
for (const d of declarationsOf(integration, ctx)) {add(fromDeclaration(d, 'integration', integration.label))}
}
const known = [
...declarations.map((d) => ({ d, detail: 'Project', source: 'project' as const })),
...integrations.flatMap((i) => declarationsOf(i, ctx).map((d) => ({ d, detail: i.label, source: 'integration' as const }))),
]
const index = database ? await loadCookieDatabase() : null
for (const name of names) {
if ([...found.values()].some((f) => f.storage === 'cookie' && cookieNameMatches(f.name, name))) {continue}
const declared = known.find((k) => (k.d.storage ?? 'cookie') === 'cookie' && cookieNameMatches(k.d.name, name))
if (declared) {
add(fromDeclaration(declared.d, declared.source, declared.detail))
continue
}
const fromDb = index ? lookupCookie(index, name, databaseCategories) : null
add(fromDb ?? { name, source: 'unknown', storage: 'cookie' })
}
return { enabled, findings: [...found.values()] }
}
type ReviewDoc = {
id: number | string
listed?: boolean | null
suggested?: CookieReviewValues | null
} & CookieReviewValues
function localesOf(payload: BasePayload): { defaultLocale?: string; locales: (string | undefined)[] } {
const l = payload.config.localization
if (!l) {return { locales: [undefined] }}
const codes = l.localeCodes ?? l.locales.map((x) => (typeof x === 'string' ? x : x.code))
return { defaultLocale: l.defaultLocale, locales: [l.defaultLocale, ...codes.filter((c) => c !== l.defaultLocale)] }
}
/** Names already in Cookie Settings → Cookies. */
async function listedNames(payload: BasePayload, req?: PayloadRequest): Promise<Set<string>> {
try {
const g = (await payload.findGlobal({ slug: 'cookie-settings' as never, depth: 0, req })) as { cookies?: { name?: null | string }[] }
return new Set((g.cookies ?? []).map((c) => c.name?.trim() ?? '').filter(Boolean))
} catch {
return new Set()
}
}
/**
* Writes findings to the review list as drafts. New names become drafts; an
* existing entry gets the new suggestion only where an editor has not changed
* the value (see mergeCookieReview). Status is never changed, nothing is
* deleted and nothing is published — accepting stays the editor's step.
*/
export async function applyCookieFindings({
collection = COOKIE_REVIEW_SLUG,
findings,
payload,
req,
}: {
collection?: string
findings: CookieFinding[]
payload: BasePayload
req?: PayloadRequest
}): Promise<CookieScanSummary> {
const { locales } = localesOf(payload)
const codes = locales.filter((l): l is string => Boolean(l))
const listed = await listedNames(payload, req)
const summary: CookieScanSummary = { created: 0, unchanged: 0, unknown: 0, updated: 0 }
const now = new Date().toISOString()
const common = { collection: collection as never, context: { ipalCookieScan: true }, depth: 0, fallbackLocale: false as never, overrideAccess: true, req }
for (const finding of findings) {
if (finding.source === 'unknown') {summary.unknown++}
const key = reviewKey(finding.storage, finding.name)
const next = suggestionFor(finding, codes.length ? codes : ['en'])
const machine = {
key,
lastScannedAt: now,
listed: listed.has(finding.name),
source: finding.source,
sourceDetail: finding.sourceDetail ?? null,
suggested: next,
}
const found = await payload.find({ ...common, limit: 1, locale: (codes.length ? 'all' : undefined) as never, where: { key: { equals: key } } })
const existing = found.docs[0] as ReviewDoc | undefined
const values = existing ? mergeCookieReview(existing, existing.suggested, next) : { changed: true, values: next }
const { purpose, retention, ...scalars } = values.values
const textIn = (locale: string | undefined) => ({
...(purpose && locale ? { purpose: purpose[locale] ?? null } : {}),
...(retention && locale ? { retention: retention[locale] ?? null } : {}),
...(!locale && purpose ? { purpose: Object.values(purpose)[0] ?? null } : {}),
...(!locale && retention ? { retention: Object.values(retention)[0] ?? null } : {}),
})
let id = existing?.id
for (const [i, locale] of locales.entries()) {
const data = i === 0
? { ...scalars, ...machine, ...textIn(locale), ...(existing ? {} : { name: finding.name, status: 'draft', storage: finding.storage }) }
: textIn(locale)
if (i > 0 && (!values.changed || !Object.keys(data).length)) {continue}
if (id === undefined) {
id = ((await payload.create({ ...common, data: data as never, locale: locale as never })) as { id: number | string }).id
} else {
await payload.update({ ...common, id, data: data as never, locale: locale as never })
}
}
if (!existing) {summary.created++}
else if (values.changed) {summary.updated++}
else {summary.unchanged++}
}
return summary
}
/** Scan context from a running Payload: SiteIntegrations + the plugin's module switches. */
export async function cookieScanContext(
payload: BasePayload,
plugin: CookieScanContext['plugin'],
req?: PayloadRequest,
): Promise<CookieScanContext> {
let integrations: Record<string, unknown> = {}
try {
integrations = (await payload.findGlobal({ slug: 'site-integrations' as never, depth: 0, req })) as Record<string, unknown>
} catch {
// No such global (project replaced it) — integrations keyed on its IDs count as off.
}
return { integrations, payload, plugin }
}
/**
* One full scan: findings for this project, plus the names already in Cookie
* Settings and the extra `names`, written to the review list.
*/
export async function runCookieScan({
names = [],
options = {},
payload,
plugin,
req,
}: {
names?: string[]
options?: CookieScannerOptions
payload: BasePayload
plugin: CookieScanContext['plugin']
req?: PayloadRequest
}): Promise<{ enabled: CookieIntegration[]; summary: CookieScanSummary }> {
const ctx = await cookieScanContext(payload, plugin, req)
const integrations = options.integrations ? options.integrations(DEFAULT_COOKIE_INTEGRATIONS) : DEFAULT_COOKIE_INTEGRATIONS
const { enabled, findings } = await collectCookieFindings({
ctx,
database: options.database !== false,
databaseCategories: options.databaseCategories,
declarations: options.declarations,
integrations,
names: [...new Set([...(await listedNames(payload, req)), ...names])],
})
const summary = await applyCookieFindings({ findings, payload, req })
return { enabled, summary }
}
+76
View File
@@ -0,0 +1,76 @@
import type { BasePayload, PayloadRequest } from 'payload'
import type { CookieReviewValues } from './merge.js'
type Row = {
category?: null | string
duration?: null | string
id?: string
name?: null | string
provider?: null | string
purpose?: null | string
}
type Entry = { name: string } & CookieReviewValues
const empty = (v: unknown) => v === undefined || v === null || (typeof v === 'string' && !v.trim())
/**
* Adds an accepted review entry to Cookie Settings → Cookies, in every locale.
* A missing row is added; an existing row (same name) gets only its EMPTY
* provider, purpose and retention filled — text an editor wrote there stays,
* and its category is never changed. Never removes a row.
* Returns what happened, for the log.
*/
export async function addToCookieList({
entry,
payload,
req,
}: {
entry: Entry
payload: BasePayload
req?: PayloadRequest
}): Promise<'added' | 'filled' | 'unchanged'> {
const l = payload.config.localization
const codes = l ? (l.localeCodes ?? []) : []
const defaultLocale = l ? l.defaultLocale : undefined
const locales = l ? [defaultLocale!, ...codes.filter((c) => c !== defaultLocale)] : [undefined]
const text = (map: Record<string, null | string> | undefined, locale: string | undefined) =>
(locale ? map?.[locale] : map && Object.values(map)[0]) ?? null
// fallbackLocale off for reads AND writes: an update in one locale otherwise reads the
// stored rows with the default locale's text filled in and saves that text into it.
const common = { slug: 'cookie-settings' as never, context: { ipalCookieScan: true }, depth: 0, fallbackLocale: false as never, overrideAccess: true, req }
let result: 'added' | 'filled' | 'unchanged' = 'unchanged'
for (const [i, locale] of locales.entries()) {
const g = (await payload.findGlobal({ ...common, locale: locale as never })) as { cookies?: Row[] }
const rows = [...(g.cookies ?? [])]
const row = rows.find((r) => r.name?.trim() === entry.name)
let changed = false
if (!row) {
if (i > 0) {continue} // added in the default locale; Payload keeps the row in every locale
rows.push({
name: entry.name,
category: entry.category ?? 'necessary',
duration: text(entry.retention, locale),
provider: entry.vendor ?? null,
purpose: text(entry.purpose, locale),
})
changed = true
result = 'added'
} else {
const fill = (key: 'duration' | 'provider' | 'purpose', value: null | string | undefined) => {
if (empty(row[key]) && !empty(value)) {
row[key] = value
changed = true
}
}
if (i === 0) {fill('provider', entry.vendor)}
fill('purpose', text(entry.purpose, locale))
fill('duration', text(entry.retention, locale))
if (changed && result === 'unchanged') {result = 'filled'}
}
if (changed) {await payload.updateGlobal({ ...common, data: { cookies: rows } as never, locale: locale as never })}
}
return result
}
+119
View File
@@ -0,0 +1,119 @@
import type { BasePayload, PayloadRequest } from 'payload'
import type { CollectionOverride } from '../../shared/collectionOverride.js'
import type { ConsentCategory } from '../categories.js'
import type { CookieScanLabels } from './labels.js'
/** Text per admin/content language (`{ en, pl }`), or one string for every language. */
export type LocalizedText = Record<string, string> | string
/** Where a key is kept in the browser. */
export type CookieStorage = 'cookie' | 'localStorage' | 'sessionStorage'
/**
* One cookie (or storage key) an integration sets — the single place its cookie
* policy text lives. A trailing `*` in `name` matches every name with that prefix
* (`_ga_*` → `_ga_ABC123`).
*/
export type CookieDeclaration = {
category: ConsentCategory
/** Third-party domain that sets it, e.g. `clarity.ms`. Omit for the site's own cookies. */
domain?: string
name: string
purpose: LocalizedText
retention: LocalizedText
/** True when it may be set before the visitor decides (only `necessary` cookies should be). */
setBeforeConsent: boolean
/** Default `'cookie'`. */
storage?: CookieStorage
vendor: string
}
/** What a scan knows about the project when it decides which integrations are on. */
export type CookieScanContext = {
/** SiteIntegrations (depth 0); `{}` when it can't be read. */
integrations: Record<string, unknown>
payload: BasePayload
/** Plugin options that switch modules on. */
plugin: { localeCount: number; stats: boolean }
}
/**
* A feature that sets cookies, with the check whether this project uses it.
* Built-ins: DEFAULT_COOKIE_INTEGRATIONS. Projects add their own (custom embeds,
* chat widgets) through `cookieScanner.integrations` or `cookieScanner.declarations`.
*/
export type CookieIntegration = {
declarations: ((ctx: CookieScanContext) => CookieDeclaration[]) | CookieDeclaration[]
/** Whether the project uses it — e.g. an ID is filled in Site Integrations. */
isEnabled: (ctx: CookieScanContext) => boolean | Promise<boolean>
/** Stable id, e.g. `ga4`. */
key: string
/** Shown in the panel, e.g. `Google Analytics 4`. */
label: string
}
/** Where a review entry's suggestion came from. `manual` = added by hand in the panel. */
export type CookieFindingSource = 'database' | 'integration' | 'manual' | 'project' | 'unknown'
/** One cookie a scan found, before it is written to the review list. */
export type CookieFinding = {
category?: ConsentCategory
domain?: string
name: string
purpose?: LocalizedText
retention?: LocalizedText
setBeforeConsent?: boolean
source: CookieFindingSource
/** e.g. `Google Analytics 4`, `Open Cookie Database: Hotjar`. */
sourceDetail?: string
storage: CookieStorage
vendor?: string
}
/** Open Cookie Database category names. */
export type OpenCookieCategory = 'Analytics' | 'Functional' | 'Marketing' | 'Necessary' | 'Personalization' | 'Security'
/** Totals a scan reports back to the panel. */
export type CookieScanSummary = {
created: number
unchanged: number
/** Names nothing knew — the editor fills provider, purpose and category. */
unknown: number
updated: number
}
/**
* `ipalKit({ cookieScanner })` — the Cookie review list and the "Scan cookies"
* action. Every key is optional.
*/
export type CookieScannerOptions = {
/** Who may run a scan (GET/POST /api/ipal/cookie-scan). Default: `editor` and up. */
access?: (args: { req: PayloadRequest }) => boolean | Promise<boolean>
/** Change the `cookie-review` collection (object merges, function takes over). */
collectionOverrides?: CollectionOverride
/** Look unknown names up in the bundled Open Cookie Database. Default true. */
database?: boolean
/**
* How Open Cookie Database categories map to consent categories. Default:
* Functional / Personalization → functional, Security / Necessary → necessary,
* Analytics → analytics, Marketing → marketing. Functional is not mapped to
* necessary on purpose: the database files some trackers there, and a lookup
* nobody checked yet must not skip consent. `{ Functional: 'necessary' }` to change it.
*/
databaseCategories?: Partial<Record<OpenCookieCategory, ConsentCategory>>
/** The project's own cookies (custom embeds, chat): always part of a scan. */
declarations?: CookieDeclaration[]
/**
* Built-in integrations → the ones to use: filter, change or add.
* `(defaults) => [...defaults, myChatWidget]`.
*/
integrations?: (defaults: CookieIntegration[]) => CookieIntegration[]
/** Admin labels per language, merged over the plugin's `en` / `pl` (add `de: {…}`). */
labels?: Record<string, Partial<CookieScanLabels>>
/**
* Accepting an entry adds it to Cookie Settings → Cookies (fills only empty
* text of an existing row). Default true; `false` = the list is only a review aid.
*/
syncAccepted?: boolean
}
+12
View File
@@ -10,6 +10,8 @@ import { buildSiteIntegrations } from './globals/SiteIntegrations/index.js'
import { buildSiteSettings } from './globals/SiteSettings/index.js'
import { adminOnly, adminOrSelf, injectRoles } from './modules/access/index.js'
import { buildConsentLogCollection, buildConsentLogEndpoint } from './modules/consent/consentLog.js'
import { buildCookieReviewCollection } from './modules/consent/scanner/collection.js'
import { buildCookieScanEndpoints } from './modules/consent/scanner/endpoint.js'
import { buildConstructionFields } from './modules/construction/fields.js'
import { buildArchiveFields } from './modules/content/index.js'
import { testEmailEndpoint } from './modules/email/test/testEmailEndpoint.js'
@@ -311,6 +313,16 @@ export const ipalKit = (options: IpalOptions): Plugin => {
config.endpoints = [...(config.endpoints ?? []), buildConsentLogEndpoint(logOptions)]
}
// --- cookie scanner: review list + "Scan cookies" (opt-in) ---
if (options.cookieScanner) {
const scannerOptions = options.cookieScanner === true ? {} : options.cookieScanner
config.collections = [...(config.collections ?? []), applyCollectionOverride(buildCookieReviewCollection(scannerOptions), scannerOptions.collectionOverrides)]
config.endpoints = [
...(config.endpoints ?? []),
...buildCookieScanEndpoints(scannerOptions, { localeCount: options.i18n.locales.length, stats: Boolean(options.stats) }),
]
}
// --- built-in statistics: cookieless visits + consented history (opt-in) ---
if (options.stats) {
const statsOptions = options.stats === true ? {} : options.stats
+12
View File
@@ -15,6 +15,7 @@ export type TotpPluginFactory = (options: {
import type { GlobalOverrides } from './globals/overrides.js'
import type { AccessOption } from './modules/access/types.js'
import type { ConsentLogOptions } from './modules/consent/consentLog.js'
import type { CookieScannerOptions } from './modules/consent/scanner/types.js'
import type { ContentOption } from './modules/content/types.js'
import type { FormsOption } from './modules/forms/types.js'
import type { RevalidatePathFn } from './modules/hooks/buildRevalidateHook.js'
@@ -63,6 +64,17 @@ export type IpalOptions = {
*/
content?: ContentOption
/**
* Cookie scanner (docs/cookie-scanner.md): the `cookie-review` collection, a
* "Scan cookies" action above its list and GET/POST /api/ipal/cookie-scan. A
* scan lists the cookies of the integrations this project switches on, plus
* names looked up in the bundled Open Cookie Database, as drafts an editor
* accepts (→ Cookie Settings → Cookies), edits or rejects. Never deletes,
* never overwrites edited text, never publishes by itself.
* `true` or CookieScannerOptions. Default off.
*/
cookieScanner?: boolean | CookieScannerOptions
/**
* `false` = plugin off without uninstalling: its collections, globals and
* fields stay (DB schema and migrations unchanged), but it adds no endpoints,
+212
View File
@@ -0,0 +1,212 @@
import type { BasePayload, Config } from 'payload'
import { describe, expect, test, vi } from 'vitest'
import type { CookieScanContext } from '../src/modules/consent/scanner/types.js'
import { indexCookieDatabase, loadCookieDatabase, lookupCookie } from '../src/modules/consent/scanner/cookieDatabase.js'
import { OPEN_COOKIE_DATABASE_SOURCE } from '../src/modules/consent/scanner/data/openCookieDatabase.js'
import { cookieNameMatches, DEFAULT_COOKIE_INTEGRATIONS } from '../src/modules/consent/scanner/integrations.js'
import { COOKIE_SCAN_LABELS, labelFor, labelRecord, mergeCookieScanLabels } from '../src/modules/consent/scanner/labels.js'
import { mergeCookieReview, suggestionFor, textFor } from '../src/modules/consent/scanner/merge.js'
import { collectCookieFindings, parseCookieNames } from '../src/modules/consent/scanner/scan.js'
import { ipalKit } from '../src/plugin.js'
vi.mock('server-only', () => ({}))
const ctx = (integrations: Record<string, unknown> = {}, plugin: Partial<CookieScanContext['plugin']> = {}): CookieScanContext => ({
integrations,
payload: {
config: { cookiePrefix: 'payload' },
findGlobal: vi.fn(async () => integrations),
logger: { error: vi.fn(), info: vi.fn(), warn: vi.fn() },
} as unknown as BasePayload,
plugin: { localeCount: 1, stats: false, ...plugin },
})
describe('cookie scanner — names', () => {
test('a trailing * is a prefix, anything else exact', () => {
expect(cookieNameMatches('_ga_*', '_ga_ABC123')).toBe(true)
expect(cookieNameMatches('_ga_*', '_ga')).toBe(false)
expect(cookieNameMatches('_ga', '_ga')).toBe(true)
expect(cookieNameMatches('_ga', '_gat')).toBe(false)
})
test('names from the panel: trimmed, unique, invalid dropped, capped', () => {
expect(parseCookieNames(' _ga \n\n_fbp\n_ga\nbad name\na;b\nx=y')).toEqual(['_ga', '_fbp'])
expect(parseCookieNames(['a', 1, null, 'b'])).toEqual(['a', 'b'])
expect(parseCookieNames(undefined)).toEqual([])
expect(parseCookieNames(Array.from({ length: 500 }, (_, i) => `c${i}`))).toHaveLength(200)
})
})
describe('cookie scanner — Open Cookie Database', () => {
test('the bundled copy names its source, license and commit', () => {
expect(OPEN_COOKIE_DATABASE_SOURCE.license).toBe('Apache-2.0')
expect(OPEN_COOKIE_DATABASE_SOURCE.commit).toMatch(/^[0-9a-f]{40}$/)
})
test('exact names, wildcard prefixes, third-party domains', async () => {
const db = await loadCookieDatabase()
expect(lookupCookie(db, '_ga')).toMatchObject({ name: '_ga', category: 'analytics', source: 'database', vendor: 'Google' })
const gac = lookupCookie(db, '_gac_UA-123')
expect(gac?.name).toBe('_gac_*') // one entry per pattern, not per site-specific suffix
expect(lookupCookie(db, '_fbp')).toMatchObject({ category: 'marketing', domain: 'facebook.com' })
expect(lookupCookie(db, 'no-such-cookie-xyz')).toBeNull()
})
test('categories map to consent categories, and the map is overridable', () => {
const db = indexCookieDatabase([
['sess', 'App', 'Functional', '', 'Session', 'session', 'Acme', 0],
['pref', 'App', 'Personalization', '', 'Prefs', '1 year', 'Acme', 0],
['pre_', 'App', 'Security', '', 'Guard', '1 day', 'Acme', 1],
['pre_long_', 'App', 'Marketing', '', 'Ads', '1 day', 'Acme', 1],
])
// Functional is never mapped to necessary by default — an unchecked lookup must not skip consent
expect(lookupCookie(db, 'sess')?.category).toBe('functional')
expect(lookupCookie(db, 'pref')?.category).toBe('functional')
expect(lookupCookie(db, 'sess', { Functional: 'necessary' })?.category).toBe('necessary')
// the longest prefix wins
expect(lookupCookie(db, 'pre_long_1')?.category).toBe('marketing')
expect(lookupCookie(db, 'pre_1')?.category).toBe('necessary')
})
})
describe('cookie scanner — findings', () => {
test('only integrations the project switches on', async () => {
const { enabled, findings } = await collectCookieFindings({ ctx: ctx({ ga4MeasurementId: 'G-ABC123DEF4' }), database: false })
expect(enabled.map((i) => i.key)).toEqual(['consent', 'admin', 'ga4'])
expect(findings.map((f) => f.name)).toEqual(['cookie-consent', 'payload-token', '_ga', '_ga_*'])
expect(findings.every((f) => f.source === 'integration')).toBe(true)
})
test('stats, languages, pixels and Turnstile follow the project config', async () => {
const on = await collectCookieFindings({
ctx: ctx(
{ clarityProjectId: 'abcdefghij', metaPixelId: '1234567890123456', turnstileSecretKey: 's', turnstileSiteKey: 'k' },
{ localeCount: 2, stats: true },
),
database: false,
})
const names = on.findings.map((f) => f.name)
for (const n of ['ipal_vid', 'NEXT_LOCALE', '_fbp', '_fbc', '_clck', 'cf_clearance']) {expect(names).toContain(n)}
expect(names).not.toContain('_ttp')
// an invalid ID counts as off
const bad = await collectCookieFindings({ ctx: ctx({ metaPixelId: 'nope' }), database: false })
expect(bad.findings.map((f) => f.name)).not.toContain('_fbp')
})
test('every built-in declaration has text in English and Polish and a sane category', () => {
for (const integration of DEFAULT_COOKIE_INTEGRATIONS) {
const list = typeof integration.declarations === 'function' ? integration.declarations(ctx()) : integration.declarations
for (const d of list) {
expect(typeof d.purpose === 'object' && d.purpose.en && d.purpose.pl, `${d.name} purpose`).toBeTruthy()
expect(typeof d.retention === 'object' && d.retention.en && d.retention.pl, `${d.name} retention`).toBeTruthy()
// only necessary cookies may be set before consent
if (d.setBeforeConsent) {expect(d.category, d.name).toBe('necessary')}
}
}
})
test('project declarations, then built-ins, then the database, then unknown', async () => {
const { findings } = await collectCookieFindings({
ctx: ctx(),
declarations: [{ name: 'yt-*', category: 'marketing', purpose: 'YouTube embed', retention: '6 months', setBeforeConsent: false, vendor: 'Google' }],
names: ['yt-player', '_fbp', '_hjSessionUser_123', 'totally_unknown', 'cookie-consent'],
})
const by = Object.fromEntries(findings.map((f) => [f.name, f]))
expect(by['yt-*'].source).toBe('project')
expect(by['yt-player']).toBeUndefined() // covered by the project's pattern
expect(by._fbp).toMatchObject({ source: 'integration', sourceDetail: 'Meta Pixel' }) // built-in text even with the pixel off
expect(by['_hjSessionUser_*']).toMatchObject({ category: 'functional', source: 'database' }) // filed as Functional upstream — asks for consent
expect(by.totally_unknown).toEqual({ name: 'totally_unknown', source: 'unknown', storage: 'cookie' })
expect(findings.filter((f) => f.name === 'cookie-consent')).toHaveLength(1)
})
test('a failing isEnabled counts as off and is logged', async () => {
const c = ctx()
const { enabled } = await collectCookieFindings({
ctx: c,
database: false,
integrations: [{ declarations: [], isEnabled: () => { throw new Error('boom') }, key: 'x', label: 'X' }],
})
expect(enabled).toEqual([])
expect(c.payload.logger.warn).toHaveBeenCalled()
})
})
describe('cookie scanner — merging a rescan', () => {
const next = suggestionFor(
{ name: '_ga', category: 'analytics', purpose: { en: 'New EN', pl: 'Nowy PL' }, retention: '2 years', source: 'integration', storage: 'cookie', vendor: 'Google' },
['pl', 'en'],
)
test('text per locale: own language, English, first', () => {
expect(textFor({ en: 'E', pl: 'P' }, 'pl')).toBe('P')
expect(textFor({ en: 'E', pl: 'P' }, 'de')).toBe('E')
expect(textFor({ fr: 'F' }, 'de')).toBe('F')
expect(textFor('same', 'pl')).toBe('same')
expect(next.retention).toEqual({ en: '2 years', pl: '2 years' })
})
test('empty and untouched values follow the scan', () => {
const previous = { category: 'analytics' as const, purpose: { en: 'Old EN', pl: 'Stary PL' }, vendor: 'Google' }
const { changed, values } = mergeCookieReview({ ...previous, retention: {} }, previous, next)
expect(changed).toBe(true)
expect(values.purpose).toEqual({ en: 'New EN', pl: 'Nowy PL' })
expect(values.retention).toEqual({ en: '2 years', pl: '2 years' })
})
test('text an editor changed is never overwritten — per locale and per field', () => {
const previous = { category: 'analytics' as const, purpose: { en: 'Old EN', pl: 'Stary PL' }, vendor: 'Google' }
const current = { category: 'marketing' as const, purpose: { en: 'Old EN', pl: 'Mój tekst' }, vendor: 'Google LLC' }
const { values } = mergeCookieReview(current, previous, next)
expect(values.purpose).toEqual({ en: 'New EN', pl: 'Mój tekst' })
expect(values.vendor).toBe('Google LLC')
expect(values.category).toBe('marketing')
})
test('same suggestion again → nothing changes', () => {
expect(mergeCookieReview(next, next, next).changed).toBe(false)
})
test('a missing suggestion never clears a value', () => {
const { changed, values } = mergeCookieReview({ vendor: 'Mine' }, undefined, {})
expect(changed).toBe(false)
expect(values.vendor).toBe('Mine')
})
})
describe('cookie scanner — labels and config', () => {
test('English and Polish for every label; projects add languages and change text', () => {
expect(Object.keys(COOKIE_SCAN_LABELS.pl).sort()).toEqual(Object.keys(COOKIE_SCAN_LABELS.en).sort())
const labels = mergeCookieScanLabels({ de: { scanButton: 'Cookies scannen' }, pl: { scanButton: 'Skanuj' } })
expect(labelRecord(labels, 'scanButton')).toEqual({ de: 'Cookies scannen', en: 'Scan cookies', pl: 'Skanuj' })
expect(labels.de.status).toBe('Status') // missing keys fall back to English
expect(labelFor(labels, 'fr', 'scanButton')).toBe('Scan cookies')
})
const run = async (cookieScanner?: unknown) =>
ipalKit({
cookieScanner: cookieScanner as never,
i18n: { defaultLocale: 'pl', locales: [{ code: 'pl', label: 'Polski' }] },
twoFactor: false,
})({ collections: [{ slug: 'users', auth: true, fields: [] }] } as unknown as Config)
test('off by default: no collection, no endpoint', async () => {
const config = await run()
expect(config.collections?.some((c) => c.slug === 'cookie-review')).toBe(false)
expect(config.endpoints?.some((e) => e.path === '/ipal/cookie-scan')).toBe(false)
})
test('on: collection with the scan button, GET + POST endpoint; overrides win', async () => {
const config = await run({ collectionOverrides: { admin: { group: 'Privacy' } }, syncAccepted: false })
const review = config.collections?.find((c) => c.slug === 'cookie-review')
expect(review?.admin?.group).toBe('Privacy')
expect(review?.admin?.components?.beforeListTable).toEqual([
expect.objectContaining({ path: '@intecion/ipal-kit/admin#CookieScanButton' }),
])
expect(review?.hooks?.afterChange).toEqual([])
expect(config.endpoints?.filter((e) => e.path === '/ipal/cookie-scan').map((e) => e.method).sort()).toEqual(['get', 'post'])
})
})
+174
View File
@@ -0,0 +1,174 @@
/**
* Cookie scanner through a REAL Payload (SQLite in memory, two locales): scan →
* drafts → editor edits → rescan keeps the edits → accept → Cookie Settings.
*/
import type { Payload } from 'payload'
import { sqliteAdapter } from '@payloadcms/db-sqlite'
import { lexicalEditor } from '@payloadcms/richtext-lexical'
import os from 'os'
import path from 'path'
import { buildConfig, getPayload } from 'payload'
import { afterAll, beforeAll, describe, expect, test, vi } from 'vitest'
import { buildCookieScanEndpoints } from '../src/modules/consent/scanner/endpoint.js'
import { runCookieScan } from '../src/modules/consent/scanner/scan.js'
import { ipalKit } from '../src/plugin.js'
vi.mock('server-only', () => ({}))
const SLUG = 'cookie-review' as never
const plugin = { localeCount: 2, stats: true }
const declarations = [
{ name: 'yt-*', category: 'marketing' as const, purpose: { en: 'YouTube embed', pl: 'Film YouTube' }, retention: '6 months', setBeforeConsent: false, vendor: 'Google' },
]
type Entry = {
category?: string
id: number
key: string
listed?: boolean
name: string
purpose?: Record<string, string> | string
source: string
status: string
vendor?: string
}
let payload: Payload
const all = async () => (await payload.find({ collection: SLUG, depth: 0, limit: 100, locale: 'all' as never })).docs as unknown as Entry[]
const byName = async (name: string) => (await all()).find((e) => e.name === name)!
const cookieList = async (locale: string) =>
((await payload.findGlobal({ slug: 'cookie-settings' as never, fallbackLocale: false as never, locale: locale as never })) as {
cookies?: { category: string; duration?: null | string; name: string; provider?: null | string; purpose?: null | string }[]
}).cookies ?? []
beforeAll(async () => {
const config = buildConfig({
collections: [
{ slug: 'users', auth: true, fields: [] },
{ slug: 'media', fields: [], upload: { staticDir: path.join(os.tmpdir(), 'ipal-test-media') } },
],
db: sqliteAdapter({ client: { url: 'file::memory:' }, push: true }),
editor: lexicalEditor(),
plugins: [
ipalKit({
access: { authCollection: 'users' },
cookieScanner: { declarations },
i18n: {
defaultLocale: 'pl',
locales: [
{ code: 'pl', label: 'Polski' },
{ code: 'en', label: 'English' },
],
},
stats: true,
twoFactor: false,
}),
],
secret: 'cookie-scanner-test-secret',
telemetry: false,
})
payload = await getPayload({ config })
await payload.updateGlobal({ slug: 'site-integrations' as never, data: { ga4MeasurementId: 'G-ABC123DEF4' } as never })
// An editor's own row, already published before the first scan.
await payload.updateGlobal({
slug: 'cookie-settings' as never,
data: { cookies: [{ name: '_ga', category: 'analytics', provider: 'Google', purpose: 'Tekst redaktora' }] } as never,
locale: 'pl' as never,
})
}, 60_000)
afterAll(async () => {
await payload?.destroy()
})
describe('cookie scanner against a real Payload', () => {
test('a scan writes drafts in every locale and publishes nothing', async () => {
const { enabled, summary } = await runCookieScan({ names: ['_hjSessionUser_42', 'mystery'], options: { declarations }, payload, plugin })
expect(enabled.map((i) => i.key)).toEqual(['consent', 'admin', 'locale', 'stats', 'ga4'])
expect(summary).toMatchObject({ unknown: 1, updated: 0 })
const entries = await all()
expect(entries.every((e) => e.status === 'draft')).toBe(true)
expect(entries.map((e) => e.name).sort()).toEqual(
['NEXT_LOCALE', '_ga', '_ga_*', '_hjSessionUser_*', 'cookie-consent', 'ipal_vid', 'mystery', 'payload-token', 'yt-*'].sort(),
)
expect((await byName('ipal_vid')).purpose).toMatchObject({ en: expect.stringContaining('Built-in statistics'), pl: expect.stringContaining('Wbudowane') })
expect(await byName('_ga')).toMatchObject({ listed: true, source: 'integration' })
expect(await byName('mystery')).toMatchObject({ source: 'unknown' })
expect((await cookieList('pl')).map((c) => c.name)).toEqual(['_ga']) // nothing published
})
test('a rescan keeps what an editor changed, adds nothing twice, deletes nothing', async () => {
const vid = await byName('ipal_vid')
await payload.update({ id: vid.id, collection: SLUG, data: { purpose: 'Mój opis', vendor: 'Nasza strona' } as never, locale: 'pl' as never })
const before = (await all()).length
const { summary } = await runCookieScan({ options: { declarations }, payload, plugin })
expect(summary.created).toBe(0)
const after = await byName('ipal_vid')
expect(after.purpose).toMatchObject({ en: expect.stringContaining('Built-in statistics'), pl: 'Mój opis' })
expect(after.vendor).toBe('Nasza strona')
expect((await all()).length).toBe(before) // names not passed again are kept
})
test('accepting adds the cookie to Cookie Settings in every locale', async () => {
const vid = await byName('ipal_vid')
const saved = (await payload.update({ id: vid.id, collection: SLUG, data: { status: 'accepted' } as never, locale: 'pl' as never })) as unknown as Entry
expect(saved.purpose).toBe('Mój opis') // the editor's save still answers in their locale
const pl = (await cookieList('pl')).find((c) => c.name === 'ipal_vid')
const en = (await cookieList('en')).find((c) => c.name === 'ipal_vid')
expect(pl).toMatchObject({ category: 'analytics', duration: '6 mies.', provider: 'Nasza strona', purpose: 'Mój opis' })
expect(en?.purpose).toContain('Built-in statistics')
expect((await byName('ipal_vid')).listed).toBe(true)
})
test('accepting an existing row fills only empty text, never the editor’s', async () => {
const ga = await byName('_ga')
await payload.update({ id: ga.id, collection: SLUG, data: { status: 'accepted' } as never, locale: 'pl' as never })
const pl = (await cookieList('pl')).filter((c) => c.name === '_ga')
expect(pl).toHaveLength(1)
expect(pl[0]).toMatchObject({ duration: '2 lata', provider: 'Google', purpose: 'Tekst redaktora' })
expect((await cookieList('en')).find((c) => c.name === '_ga')?.purpose).toContain('Google Analytics')
})
test('an entry without a category cannot be accepted', async () => {
const mystery = await byName('mystery')
await expect(
payload.update({ id: mystery.id, collection: SLUG, data: { status: 'accepted' } as never, locale: 'pl' as never }),
).rejects.toThrow()
})
test('rejecting keeps the entry; a rescan never changes its status', async () => {
const yt = await byName('yt-*')
await payload.update({ id: yt.id, collection: SLUG, data: { status: 'rejected' } as never, locale: 'pl' as never })
await runCookieScan({ options: { declarations }, payload, plugin })
expect((await byName('yt-*')).status).toBe('rejected')
expect((await byName('ipal_vid')).status).toBe('accepted')
expect((await cookieList('pl')).some((c) => c.name === 'yt-*')).toBe(false)
})
test('the endpoint: editors scan, visitors and plain users get 403', async () => {
const [get, post] = buildCookieScanEndpoints({ declarations }, plugin)
const call = (endpoint: typeof get, user: unknown, body: unknown = {}) =>
endpoint.handler({ json: async () => body, payload, user } as never) as Promise<Response>
expect((await call(post, null)).status).toBe(403)
expect((await call(post, { collection: 'users', roles: ['user'] })).status).toBe(403)
const editor = { collection: 'users', roles: ['editor'] }
const listed = (await (await call(get, editor)).json()) as { integrations: { key: string }[] }
expect(listed.integrations.map((i) => i.key)).toContain('ga4')
const res = await call(post, editor, { names: ['_fbp'] })
expect(res.status).toBe(200)
expect(((await res.json()) as { summary: { created: number } }).summary.created).toBe(1)
expect(await byName('_fbp')).toMatchObject({ source: 'integration', status: 'draft' })
})
test('custom access option replaces the editor check', async () => {
const [, post] = buildCookieScanEndpoints({ access: () => false }, plugin)
const res = (await post.handler({ json: async () => ({}), payload, user: { collection: 'users', roles: ['admin'] } } as never))
expect(res.status).toBe(403)
})
})
+1
View File
@@ -236,6 +236,7 @@ describe('agent guide covers the whole plugin', () => {
...typeKeys('src/modules/access/types.ts', 'AccessOption'),
...typeKeys('src/modules/content/types.ts', 'ContentCollectionOption'),
...typeKeys('src/modules/content/types.ts', 'ContentOption'),
...typeKeys('src/modules/consent/scanner/types.ts', 'CookieScannerOptions'),
...typeKeys('src/modules/forms/types.ts', 'FormsOption'),
...typeKeys('src/modules/i18n/types.ts', 'I18nConfig'),
...typeKeys('src/modules/i18n/types.ts', 'LocaleDefinition'),