diff --git a/docs/README.md b/docs/README.md index f14bf05..7f564a1 100644 --- a/docs/README.md +++ b/docs/README.md @@ -24,6 +24,7 @@ API details — one file per module: | GA4, GTM, Meta Pixel, Clarity, LinkedIn, TikTok, `defer` | [analytics.md](./analytics.md) | | Blocks, RenderBlocks, enhanceProps | [blocks.md](./blocks.md) | | Cookie consent, banner, settings window (in the bar / modal / large with cookie details) | [consent.md](./consent.md) | +| Cookie scanner: review list of drafts, "Scan cookies", Open Cookie Database lookup (optional) | [cookie-scanner.md](./cookie-scanner.md) | | Under construction — locks subpages behind a popup (developer tool) | [construction.md](./construction.md) | | Routing, archives, redirects, Markdown, search | [content.md](./content.md) | | Site frontend: `createContentHelpers` (`@/lib/content`), `createPageRoute`, `SiteProviders` | [frontend.md](./frontend.md) | diff --git a/docs/agent/AGENT.md b/docs/agent/AGENT.md index a487039..1f5036a 100644 --- a/docs/agent/AGENT.md +++ b/docs/agent/AGENT.md @@ -107,7 +107,7 @@ site), **P** = a test in the panel. Full code: PROGRAMISTA.md §2. | 9 | **Media / R2 / speed** | `Media` with `focalPoint`, `normalizeFilenameHook`, `buildOptimizeUploadHook`, `buildMediaPlaceholderHook` + field; **always** `buildR2Storage(['media'], { s3Storage })` + `@payloadcms/storage-s3`; `R2_*` in `.env.example`; ``; `images: buildImagesConfig()` and `buildUploadSecurityHeaders()` in `next.config.ts`; the project's `` via `mediaImageProps`/`videoProps` (§6.11b) | `buildR2Storage`, `mediaImageProps`, `videoProps`, `buildImagesConfig` | A, S | | 10 | **Forms** | every form from a **seed** (`scripts/seed-form-*.ts`: fields, confirmation, mail to the company **and** confirmation to the customer, every language); a block with `` + `formClasses.ts` (look, once); `actions.ts` = `createSubmitAction({ getCachedPayload, headers })`; `forms: {…}` in `ipalKit`; `email: mailAdapter()` | `RenderForm` (`/rsc`), `createSubmitAction`, `mailAdapter` | A, P | | 11 | **Turnstile** | `` in `[locale]/layout.tsx` (wires `TurnstileProvider` with the key from the panel); `RenderForm` renders the widget; keys in Site Integrations | `SiteProviders`, `getTurnstileConfig`, `TurnstileProvider` | A, P | -| 12 | Consent + analytics | Consent Mode: `'advanced'` (default — the Google tag loads at once with every signal `denied`) or `'basic'` (`` — no request to Google before consent; a client who wants zero requests), the choice goes to "Project decisions"; `ipalKit({ consentLog: true })` (without it the `/api/ipal/consent` endpoint does not exist) + `}>` (ConsentProvider, banner, CookieButton, Analytics in the right order); settings window mode (`settings`: `inline` / `modal` / `detailed`) per the design, brief is silent → `detailed`, the decision goes to "Project decisions"; tool IDs in the panel; the cookie list from a scan (cookie-scan → import) — feeds `` on the policy page **and** the lists in the `detailed` window; Cookie Settings → Detail labels in every language | consent.md, analytics.md | A, `ipal-consent-check` | +| 12 | Consent + analytics | Consent Mode: `'advanced'` (default — the Google tag loads at once with every signal `denied`) or `'basic'` (`` — no request to Google before consent; a client who wants zero requests), the choice goes to "Project decisions"; `ipalKit({ consentLog: true })` (without it the `/api/ipal/consent` endpoint does not exist) + `}>` (ConsentProvider, banner, CookieButton, Analytics in the right order); settings window mode (`settings`: `inline` / `modal` / `detailed`) per the design, brief is silent → `detailed`, the decision goes to "Project decisions"; tool IDs in the panel; the cookie list from a scan (`cookieScanner: true` → *Cookie review* → **Scan cookies** → the editor accepts; or cookie-scan → import) — feeds `` on the policy page **and** the lists in the `detailed` window; Cookie Settings → Detail labels in every language | consent.md, analytics.md | A, `ipal-consent-check` | | 13 | Security | `buildSecurityHeaders` in `next.config.ts`; `twoFactor: { issuer, plugin: payloadTotp }`; CSP `report-only` → `enforce`; `IPAL_IP_HEADER` in production | security.md, forms.md | A | | 14 | Operations | `src/app/api/health/route.ts` (`healthRoute`); `src/instrumentation.ts` with `assertEnv(ipalEnvRules({ storage: true, ipHeader: true }))`; staging with `IPAL_NOINDEX=1`; smoke tests (§8a) | `healthRoute`, `assertEnv`, `ipalEnvRules` | A | | 15 | System pages | Site Settings → System Pages: homepage, 404, privacy policy, cookies; legal links in the footer by role (`getSystemLinks(locale)`) | `getSystemLinks`, `getSystemPagePath`, `getNotFoundPage` | P | @@ -904,6 +904,7 @@ project → **plugin gap**, not a copy. | Settings window: in the bar / small / large with cookie details | `` — do not build your own window or cookie list | consent.md → "Large window with details" | | A consent-dependent script | `ConsentScript` | consent.md | | Cookie table on the policy page | `` (`/rsc`), `getCookieTable` | consent.md | +| Cookie list filled from the panel (drafts the editor accepts) | `ipalKit({ cookieScanner: true })` + `pnpm generate:importmap` + migration; project cookies: `cookieScanner.declarations` / `integrations` — do not type the list by hand or build your own scanner | cookie-scanner.md | | 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: { : { 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) | diff --git a/docs/agent/skills/ipal-consent-check/SKILL.md b/docs/agent/skills/ipal-consent-check/SKILL.md index 0b77a71..44c23ac 100644 --- a/docs/agent/skills/ipal-consent-check/SKILL.md +++ b/docs/agent/skills/ipal-consent-check/SKILL.md @@ -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 diff --git a/docs/agent/skills/ipal-reference/SKILL.md b/docs/agent/skills/ipal-reference/SKILL.md index 54483a7..c401611 100644 --- a/docs/agent/skills/ipal-reference/SKILL.md +++ b/docs/agent/skills/ipal-reference/SKILL.md @@ -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 === 'dpo@acme.pl' } }` — narrows who reads records in a project without roles | +| `cookieScanner` | off | `cookie-review` collection (drafts an editor accepts → Cookie Settings → Cookies), "Scan cookies" box above its list (`CookieScanButton`), `GET`/`POST /api/ipal/cookie-scan`; a scan lists the cookies of the integrations switched on + names looked up in the bundled Open Cookie Database; never deletes, never overwrites edited text, never publishes by itself | `true` / object; after switching on: `pnpm generate:importmap` + `migrate:create`. Check: *Settings → Cookie review* → **Scan cookies** → drafts appear; set one to Accepted → it is in Cookie Settings → Cookies (cookie-scanner.md) | +| `cookieScanner.declarations` / `.integrations` | built-ins only | the project's own cookies (`CookieDeclaration[]`), or `(defaults) => CookieIntegration[]` to add / change / drop integrations (`key`, `label`, `declarations`, `isEnabled(ctx)`) | e.g. a chat widget on when `ctx.integrations.chatId` is filled | +| `cookieScanner.access` / `.collectionOverrides` / `.labels` | editor+ / none / `en` + `pl` | who may scan; changes `cookie-review` like `consentLog.collectionOverrides`; admin labels per language (`CookieScanLabels`) | object or function | +| `cookieScanner.database` / `.databaseCategories` / `.syncAccepted` | `true` / Functional+Personalization → functional, Security+Necessary → necessary / `true` | Open Cookie Database lookup on or off; category map; accepting writes to Cookie Settings | `database: false`; `{ Functional: 'necessary' }`; `syncAccepted: false` | | `stats` | off | `stats-visits` collection, `POST /api/ipal/hit`, `//stats` view, nav link, dashboard chart | `true` / object | | `stats.collectionOverrides` | none | changes `stats-visits` like `consentLog.collectionOverrides`; its `access.read` also decides who sees the stats view and dashboard chart | object or function | | `stats.retentionDays` / `timeZone` / `dashboard` | 90 / `'Europe/Warsaw'` / `true` | retention, day boundary, `StatsWidget` | `dashboard: false` hides the chart | @@ -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 | `` (`/rsc`) | form from the panel, Turnstile, message from Notifications | forms.md | | Turnstile | panel / env | `SiteProviders` wires `TurnstileProvider`; keys in Site Integrations → Turnstile or env; server: `verifyTurnstile` (`/server`) | widget in the form; dashboard alert on a bad key | turnstile.md | | consent | layout + policy page | banner via `SiteProviders`; table `` (`/rsc`) from `getCookieTable` | `ipal-consent-check`; delete the consent cookie → the banner comes back | consent.md | +| cookie list | config | `cookieScanner: true` (+ `declarations` for embeds/chat), `generate:importmap`, `migrate:create` | *Cookie review* → **Scan cookies** → accept → Cookie Settings → Cookies; `` lists it | cookie-scanner.md | | proof of consent | config + layout | `consentLog: true` + `logEndpoint="/api/ipal/consent"` | after a click, a document in Consent Records | consent.md | | stats | config + layout | `stats: true` + `` (or `` inside `ConsentProvider`) | `//stats`; `POST /api/ipal/hit` request in Network | stats.md | | analytics | layout | `SiteProviders` wires `Analytics` (ID from Site Integrations → Analytics); Consent Mode: `analytics={{ consentMode: 'basic' }}` = no request to Google before consent, default `'advanced'` = the Google tag loads at once with every signal `denied` | Meta/other pixels only after consent; in `basic` no `gtm.js` / `gtag/js` in Network before consent | analytics.md, gtm-meta-pixel.md | diff --git a/docs/agent/skills/ipal-reference/resources/api.md b/docs/agent/skills/ipal-reference/resources/api.md index 10b545d..369cb7a 100644 --- a/docs/agent/skills/ipal-reference/resources/api.md +++ b/docs/agent/skills/ipal-reference/resources/api.md @@ -12,7 +12,7 @@ project wires: `../SKILL.md`. Module details: `node_modules/@intecion/ipal-kit/d |---|---|---| | `ipalKit(options)` | `@intecion/ipal-kit` | Payload 3 plugin (`plugins: [ipalKit({...})]`) — the only wiring point: adds globals (SiteSettings, SiteIntegrations, CookieSettings, Notifications), roles, enforced 2FA, SEO, forms, i18n (localization), white-label, stats, consent log, `/api/ipal/*` endpoints; no auth collection → injects a simple `users`. Validates `i18n` right away (fail fast). `enabled: false` = schema stays, behaviour off. | -**Types:** `IpalOptions` — `ipalKit()` options: `i18n`, `access`, `twoFactor` (`{ issuer, plugin: payloadTotp }` or `false`), `whiteLabel`, `adminRoute`, `consentLog`, `content`, `forms`, `pages`, `seo`, `searchSettings`, `stats`, `indexNow`, `siteSettingsFields`, `integrationsFields`, `globalOverrides`, `revalidatePath`, `enabled`. `GlobalOverride`, `GlobalOverrides`, `IpalGlobalSlug` — see Payload globals below. +**Types:** `IpalOptions` — `ipalKit()` options: `i18n`, `access`, `twoFactor` (`{ issuer, plugin: payloadTotp }` or `false`), `whiteLabel`, `adminRoute`, `consentLog`, `content`, `cookieScanner`, `forms`, `pages`, `seo`, `searchSettings`, `stats`, `indexNow`, `siteSettingsFields`, `integrationsFields`, `globalOverrides`, `revalidatePath`, `enabled`. `GlobalOverride`, `GlobalOverrides`, `IpalGlobalSlug` — see Payload globals below. ## Admin (import map) (`admin`, `branding`, `admin-ui`, `globals/SiteIntegrations`) — details: `node_modules/@intecion/ipal-kit/docs/white-label.md`, `…/docs/integrations.md`, `…/docs/email.md`, `…/docs/links.md` @@ -25,6 +25,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 | diff --git a/docs/consent.md b/docs/consent.md index 1c05653..e4f401d 100644 --- a/docs/consent.md +++ b/docs/consent.md @@ -252,7 +252,8 @@ window width `max-w-4xl` — change it with `classNames.dialog`. Which mode to choose: the project design decides. If the brief is silent → `'detailed'` (at the moment of consent the user sees which cookies are set and by whom — full information where the decision is made), -provided the Cookies list is filled from a scan (`ipal-consent-check` → cookie-scan); an empty list = a +provided the Cookies list is filled from a scan (`ipalKit({ cookieScanner: true })` → *Cookie review* → **Scan cookies**, +[cookie-scanner.md](./cookie-scanner.md), or `ipal-consent-check` → cookie-scan); an empty list = a window without expandable lists, then `'modal'` is enough. Record the decision in `AGENTS.md` → "Project decisions". @@ -342,8 +343,9 @@ independent consent state). choices, the policy version and the time — **no IP and no user agent**. *Consent records* collection (admin only), automatic cleanup after `retentionDays` (default 1095). Details below. Postgres: `migrate:create`. -- **Cookie table** for the policy page: Cookie Settings → *Cookies* (filled by a scan, - skill `ipal-consent-check` → cookie-scan) + `getCookieTable` + `` from `/rsc`. +- **Cookie table** for the policy page: Cookie Settings → *Cookies* + `getCookieTable` + `` from `/rsc`. + Fill the list from the panel with the cookie scanner (`cookieScanner` option — drafts an editor accepts, + [cookie-scanner.md](./cookie-scanner.md)) and check the real site with `ipal-consent-check` → cookie-scan. - Consent cookie: `cookie-consent` (`CONSENT_COOKIE`), JSON `{ id, state, timestamp, version }`, `max-age` 180 days (`CONSENT_MAX_AGE`), `samesite=lax`, `Secure` on HTTPS. Consent with another policy version is treated as no decision. @@ -389,6 +391,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`, diff --git a/docs/cookie-scanner.md b/docs/cookie-scanner.md new file mode 100644 index 0000000..e837cf9 --- /dev/null +++ b/docs/cookie-scanner.md @@ -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 +`` window and `` on the policy page +([consent.md](./consent.md)). + +What a scan never does: delete an entry, change text an editor edited, change an entry's status, or +publish anything by itself. + +Opt-in (`cookieScanner`, default off). Nothing is fetched at runtime and no browser is needed. + +## Turn it on + +```ts +// payload.config.ts +ipalKit({ + // … + cookieScanner: true, +}) +``` + +Then, in the project: + +1. **Import map** — the "Scan cookies" box above the list is an admin component + (`@intecion/ipal-kit/admin#CookieScanButton`). Run `pnpm generate:importmap`. +2. **Postgres / SQLite migration** — the option adds the `cookie-review` collection (with localized + `purpose` and `retention`). Run `pnpm payload migrate:create cookie-scanner`, commit the migration; + Coolify runs `payload migrate` on deploy (deployment.md). MongoDB: nothing to do. +3. **Verify** — log in as an editor, open *Settings → Cookie review*. The box lists "Integrations in + use" (e.g. Cookie banner, Admin panel login, Google Analytics 4). Click **Scan cookies**: drafts + appear, each with *Found by* = Plugin integration. Set one to *Accepted*, save, open *Cookie + Settings → Cookies*: the cookie is there, with purpose and retention in every language. + +## How editors use it + +| Step | What happens | +|---|---| +| **Scan cookies** | One draft per cookie of the integrations in use. Cookies already in Cookie Settings → Cookies are looked up too (*In the cookie list* is ticked). | +| **More cookie names** (optional text box) | Names seen in the browser (DevTools → Application → Cookies), one per line. Each is looked up in the project's declarations, every built-in integration, then the Open Cookie Database. A name nothing knows becomes an entry with *Found by* = "Unknown — fill in" and no category. | +| Edit a draft | Change provider, category, purpose, retention. A later scan keeps every value you changed (per language) and still updates values you left as suggested. | +| **Accepted** | The cookie is added to Cookie Settings → Cookies in every language. When a row with that name already exists, only its empty provider / purpose / retention are filled — text written there stays, its category is not changed. An entry without a category cannot be accepted. | +| **Rejected** | Stays in the list as rejected; later scans do not bring it back to draft. Rejecting never removes a row from Cookie Settings — delete it there. | + +Status changes work in the list's bulk edit too. Deleting review entries is admin-only and never done +by the plugin. + +Labels are in English and Polish and follow the editor's admin language; `cookieScanner.labels` adds +languages or changes text. + +## What the plugin declares + +Each integration the plugin injects declares its cookies in one place +(`DEFAULT_COOKIE_INTEGRATIONS`): name or pattern (`*` at the end = prefix), provider, category, +purpose and retention (English and Polish), and whether it may be set before consent. Only the +integrations switched on in this project are part of a scan: + +| Integration | On when | Cookies | +|---|---|---| +| Cookie banner | always | `cookie-consent` (necessary, 6 months) | +| Admin panel login | always | `payload-token` (`-token`, necessary, editors only) | +| Language choice | more than one locale in `i18n` | `NEXT_LOCALE` (functional, session) | +| Built-in statistics | `stats` option | `ipal_vid` (analytics, 6 months) | +| Google Analytics 4 | GA4 ID in Site Integrations | `_ga`, `_ga_*` (analytics, 2 years) | +| Google Tag Manager | GTM ID in Site Integrations | `_gcl_*` (marketing — the Conversion Linker; other tags in the container: add their names or declare them) | +| Meta Pixel | Pixel ID | `_fbp`, `_fbc` (marketing, 3 months) | +| Microsoft Clarity | Clarity ID | `_clck`, `_clsk`, `CLID`, `MUID` | +| LinkedIn Insight Tag | partner ID | `li_fat_id`, `bcookie`, `lidc`, `UserMatchHistory` | +| TikTok Pixel | Pixel ID | `_ttp`, `_tt_enable_cookie` | +| Cloudflare Turnstile | both Turnstile keys set | `cf_clearance` (necessary; only when pre-clearance is on in Cloudflare) | + +An ID that fails its format check counts as off. The theme switcher (`ipal-theme` in localStorage) +and the accessibility widget (`a11y-prefs`) have no plugin option, so they are not declared: add +them with `declarations` when the site uses them. + +## Open Cookie Database + +Unknown names are looked up in a bundled copy of the +[Open Cookie Database](https://github.com/jkwakman/Open-Cookie-Database) (about 2,300 entries, +Apache License 2.0). The package ships the license text in +[licenses/open-cookie-database-LICENSE.txt](./licenses/open-cookie-database-LICENSE.txt); the +data module names the upstream commit and the changes made (converted from CSV, two columns left +out). The table is loaded only when a scan runs. + +Category mapping (`DEFAULT_DATABASE_CATEGORIES`): + +| Database | Consent category | +|---|---| +| Analytics | analytics | +| Marketing | marketing | +| Necessary, Security | necessary | +| Functional, Personalization | functional | + +"Functional" is **not** mapped to necessary on purpose: the database files some trackers there +(Hotjar's user id), and a lookup nobody checked yet must not skip consent. The editor lowers the +category when a cookie really is necessary, or the project changes the map: +`cookieScanner: { databaseCategories: { Functional: 'necessary' } }`. + +Refresh the copy (maintainers of ipal-kit, not projects): + +```bash +pnpm cookie-db:refresh +``` + +`scripts/refresh-cookie-database.mjs` downloads the CSV and the license at the latest commit (or +`--ref `), refuses to write if the license is no longer Apache-2.0, and rewrites +`src/modules/consent/scanner/data/openCookieDatabase.ts` and the license file. Review the diff, +run the tests, commit. + +## Options + +`cookieScanner: true` or an object (`CookieScannerOptions`, every key optional): + +| Key | Default | What it does | +|---|---|---| +| `declarations` | `[]` | The project's own cookies (custom embeds, chat, YouTube): `CookieDeclaration[]`, always part of a scan | +| `integrations` | built-ins | `(defaults) => integrations` — filter, change or add `CookieIntegration`s (each: `key`, `label`, `declarations`, `isEnabled(ctx)`) | +| `database` | `true` | `false` = no Open Cookie Database lookup | +| `databaseCategories` | table above | Partial map from database category to consent category | +| `access` | editor and up | `({ req }) => boolean` — who may 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. diff --git a/src/exports/admin.ts b/src/exports/admin.ts index 6bb56cc..e7f2faa 100644 --- a/src/exports/admin.ts +++ b/src/exports/admin.ts @@ -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' diff --git a/src/globals/CookieSettings/fields.ts b/src/globals/CookieSettings/fields.ts index 0263222..c53b265 100644 --- a/src/globals/CookieSettings/fields.ts +++ b/src/globals/CookieSettings/fields.ts @@ -136,7 +136,7 @@ export const cookieSettingsFields: Field[] = [ type: 'array', admin: { description: - 'Cookies the site uses — shown on the cookie policy page () and per category in the detailed settings window. Fill it from a scan: ipal-consent-check → cookie-scan.', + 'Cookies the site uses — shown on the cookie policy page () and per category in the detailed settings window. Fill it from a scan: Cookie review → Scan cookies (cookieScanner option), or ipal-consent-check → cookie-scan.', initCollapsed: true, }, fields: [ diff --git a/src/index.ts b/src/index.ts index 504d047..7a6be46 100644 --- a/src/index.ts +++ b/src/index.ts @@ -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' diff --git a/src/modules/consent/scanner/CookieScanButton.tsx b/src/modules/consent/scanner/CookieScanButton.tsx new file mode 100644 index 0000000..52f7a25 --- /dev/null +++ b/src/modules/consent/scanner/CookieScanButton.tsx @@ -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 }) { + const { i18n } = useTranslation() + const { config } = useConfig() + const router = useRouter() + const t = labels[i18n.language] ?? labels.en ?? COOKIE_SCAN_LABELS.en + const endpoint = `${config.serverURL ?? ''}${config.routes?.api ?? '/api'}/ipal/cookie-scan` + const [names, setNames] = useState('') + const [integrations, setIntegrations] = useState<{ key: string; label: string }[] | null>(null) + const [status, setStatus] = useState({ kind: 'idle' }) + + useEffect(() => { + fetch(endpoint, { credentials: 'include' }) + .then((r) => (r.ok ? r.json() : null)) + .then((data: { integrations?: { key: string; label: string }[] } | null) => setIntegrations(data?.integrations ?? [])) + .catch(() => setIntegrations([])) + }, [endpoint]) + + const scan = async () => { + setStatus({ kind: 'scanning' }) + try { + const res = await fetch(endpoint, { + body: JSON.stringify({ names: names.split('\n') }), + credentials: 'include', + headers: { 'Content-Type': 'application/json' }, + method: 'POST', + }) + const data = (await res.json()) as { ok?: boolean; summary?: CookieScanSummary } + if (!res.ok || !data.ok || !data.summary) {throw new Error('scan failed')} + setStatus({ kind: 'done', summary: data.summary }) + router.refresh() + } catch { + setStatus({ kind: 'error' }) + } + } + + const result = (s: CookieScanSummary) => + t.scanResult.replace(/\{(\w+)\}/g, (_, k: string) => String(s[k as keyof CookieScanSummary] ?? '')) + + return ( +
+

{t.scanIntro}

+ {integrations ? ( +

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

+ ) : null} + +

{t.namesHint}

+