Compare commits
| Author | SHA1 | Date | |
|---|---|---|---|
|
|
6998b44431 | ||
|
|
e1f42615f3 | ||
|
|
eab26c98ca | ||
|
|
cad299c132 | ||
|
|
49e27175ae | ||
|
|
b10c2dc0e3 | ||
|
|
a9e1adc03b | ||
|
|
44598bbef2 | ||
|
|
5f4f2a07ab | ||
|
|
9b9c5fc872 | ||
|
|
86ff3f5ff7 |
@@ -41,6 +41,9 @@ import { IntegrationAlerts as IntegrationAlerts_7568fe47d582ff15ce85d2e1873c2c23
|
||||
import { TotpRedirectProvider as TotpRedirectProvider_7568fe47d582ff15ce85d2e1873c2c23 } from '@intecion/ipal-kit/admin'
|
||||
import { TOTPSetup as TOTPSetup_3eb2cc20d1a2569c2ccbafcee15bd128 } from '@clocklimited/payload-2fa/rsc'
|
||||
import { TOTPVerify as TOTPVerify_3eb2cc20d1a2569c2ccbafcee15bd128 } from '@clocklimited/payload-2fa/rsc'
|
||||
import { CookieApprovalView as CookieApprovalView_7568fe47d582ff15ce85d2e1873c2c23 } from '@intecion/ipal-kit/admin'
|
||||
import { CookieReviewTab as CookieReviewTab_7568fe47d582ff15ce85d2e1873c2c23 } from '@intecion/ipal-kit/admin'
|
||||
import { CookieSiteCheckTab as CookieSiteCheckTab_7568fe47d582ff15ce85d2e1873c2c23 } from '@intecion/ipal-kit/admin'
|
||||
import { StatsView as StatsView_7568fe47d582ff15ce85d2e1873c2c23 } from '@intecion/ipal-kit/admin'
|
||||
import { CollectionCards as CollectionCards_f9c02e79a4aed9a3924487c0cd4cafb1 } from '@payloadcms/next/rsc'
|
||||
|
||||
@@ -89,6 +92,9 @@ export const importMap = {
|
||||
"@intecion/ipal-kit/admin#TotpRedirectProvider": TotpRedirectProvider_7568fe47d582ff15ce85d2e1873c2c23,
|
||||
"@clocklimited/payload-2fa/rsc#TOTPSetup": TOTPSetup_3eb2cc20d1a2569c2ccbafcee15bd128,
|
||||
"@clocklimited/payload-2fa/rsc#TOTPVerify": TOTPVerify_3eb2cc20d1a2569c2ccbafcee15bd128,
|
||||
"@intecion/ipal-kit/admin#CookieApprovalView": CookieApprovalView_7568fe47d582ff15ce85d2e1873c2c23,
|
||||
"@intecion/ipal-kit/admin#CookieReviewTab": CookieReviewTab_7568fe47d582ff15ce85d2e1873c2c23,
|
||||
"@intecion/ipal-kit/admin#CookieSiteCheckTab": CookieSiteCheckTab_7568fe47d582ff15ce85d2e1873c2c23,
|
||||
"@intecion/ipal-kit/admin#StatsView": StatsView_7568fe47d582ff15ce85d2e1873c2c23,
|
||||
"@payloadcms/next/rsc#CollectionCards": CollectionCards_f9c02e79a4aed9a3924487c0cd4cafb1
|
||||
}
|
||||
|
||||
@@ -8,6 +8,95 @@ versions at once, go through every "Requires project changes" section in order,
|
||||
version you have. A new release = a new section at the top; we remove the oldest ones only
|
||||
once there are more than 20.
|
||||
|
||||
## 1.14.4
|
||||
|
||||
Cookie texts in every language without retyping them, and one **Cookies** entry in the admin instead of three.
|
||||
Both are on by default and can be turned off; no schema change.
|
||||
|
||||
### New
|
||||
- **Empty languages are filled automatically** (`fillEmptyLocales`, default on): text written in one language goes
|
||||
to every language where the same field is still empty — the cookie list (Cookies → Cookie list: `purpose`,
|
||||
`duration`) and the cookie review (`purpose`, `retention`). A language that has its own text is never overwritten,
|
||||
so editors can still change each language on its own. `fillEmptyLocales: false` turns it off; an object sets the
|
||||
fields per slug (`{ 'cookie-settings': [...], 'cookie-review': [...] }`, `[]` = off for that slug). Building blocks:
|
||||
`fillEmptyLocales`, `withFillLocales`, `buildFillEmptyLocalesGlobalHook`, `buildFillEmptyLocalesCollectionHook`,
|
||||
type `FillEmptyLocalesTarget` (docs/hooks.md).
|
||||
- **One Cookies entry in the admin** (`cookieScanner.adminLayout`, default `'combined'`): with the cookie scanner,
|
||||
the Cookies global gets **Review and approve** and **Site check** tabs (`CookieReviewTab`, `CookieSiteCheckTab`,
|
||||
`/admin`; `addCookieScannerTabs`). The Cookie review collection and the Cookie check global leave the navigation;
|
||||
their data, API and `/admin/cookie-approval` stay. `adminLayout: 'separate'` keeps the separate entries.
|
||||
`collectionOverrides` and `crawl.globalOverride` still win (e.g. `admin.group` to show an entry again).
|
||||
|
||||
### Changed
|
||||
- The **Cookie banner** global is labelled **Cookies** (pl: Cookies) in every project; the slug `cookie-settings` and
|
||||
the data are unchanged. Docs and skills use the new name.
|
||||
|
||||
### Known issue
|
||||
- `pnpm audit --prod` still reports one **low** advisory: `deepmerge` 4.2.0–4.3.1 (GHSA-gcqx-w48m-w2h4), reached
|
||||
through `payload`. No patched version exists yet; nothing to do in projects.
|
||||
|
||||
### What projects must update
|
||||
1. `pnpm payload generate:importmap` — with `cookieScanner` it adds `@intecion/ipal-kit/admin#CookieReviewTab` and
|
||||
(with `crawl`) `@intecion/ipal-kit/admin#CookieSiteCheckTab`; commit `importMap.js`. No migration (no schema change).
|
||||
2. **Behaviour to know (both overridable):**
|
||||
- Empty languages of the cookie texts are now filled from the language an editor writes in. To keep empty
|
||||
languages empty: `ipalKit({ fillEmptyLocales: false })`.
|
||||
- With `cookieScanner`, the cookie screens are one **Cookies** entry with tabs; Cookie review and Cookie check
|
||||
are no longer in the navigation. To keep the old entries: `cookieScanner: { adminLayout: 'separate' }`.
|
||||
3. Tell editors: **Cookie banner** is now **Cookies**; the review list and the site check are its tabs. Update
|
||||
screenshots and instructions. **Check:** the admin navigation shows one **Cookies** entry; its **Review and
|
||||
approve** tab lists the review entries; type a cookie purpose in one language, save → the other languages show it.
|
||||
|
||||
## 1.14.3
|
||||
|
||||
One approval for everything the cookie scanner finds: editors tick the cookies and add them all to the cookie list
|
||||
at once, instead of opening every review entry. Only for projects with `cookieScanner`.
|
||||
|
||||
### New
|
||||
- **Approve cookies** page (`/admin/cookie-approval`, `CookieApprovalView`; linked from the scan box on Privacy →
|
||||
Cookie review and from the dashboard): the cookies a scan or crawl found,
|
||||
grouped by category, with one **Approve and add** button for every ticked cookie. They go into Cookie banner →
|
||||
Cookies in every locale. Nothing reaches the cookie list until an editor approves it. The approve and list endpoints
|
||||
are for editors and up by default (`cookieScanner.access`).
|
||||
- **Markers** on each review entry (new `change` and `needsDescription` fields): **New**, **Changed** (a scan changed
|
||||
its suggested values), **Needs description** (no purpose yet; cleared when an editor writes one) and **No longer
|
||||
found** (a scan or crawl no longer sees it). A cookie that is no longer found is flagged for review only; neither the
|
||||
review entry nor the list row is deleted.
|
||||
- **Never overwrites, never duplicates:** an existing list row (same name, or a pattern such as `_ga_*` that covers
|
||||
it) only gets its empty texts filled; editor text is kept, and no second row is added.
|
||||
- **Unknown cookies** that no integration or database knows go to `cookieScanner.approval.unknownCategory` (default
|
||||
`marketing`, so they need consent until an editor describes them).
|
||||
- **Reminders:** a dashboard notice while cookies wait (`CookieCrawlAlert`; `approval.dashboard: false` hides it), and
|
||||
the crawl e-mail says how many cookies wait, with a link to the approval page.
|
||||
- **`cookieScanner.approval: false`** keeps the old review, entry by entry.
|
||||
- New exports: `approveCookies`, `loadCookieApproval`, `countPendingCookies`, `flagGoneEntries`, `nextChange`,
|
||||
`sameCookie`, `buildCookieApprovalEndpoints`, `COOKIE_APPROVAL_PATH`, `COOKIE_APPROVAL_VIEW_PATH`,
|
||||
`DEFAULT_UNKNOWN_CATEGORY`, `PENDING_WHERE`; `CookieApprovalView`, `CookieApprovalForm` (`/admin`); types
|
||||
`CookieApprovalOptions`, `CookieApprovalItem`, `CookieApprovalList`, `CookieApprovalResult`, `CookieChange`.
|
||||
|
||||
### Changed
|
||||
- **Hand-typed cookie list rows:** a scan looks a row up (database, integrations) only while it has no review entry.
|
||||
Once it has one, the review entry and the approval page are the place to change it.
|
||||
|
||||
### Known issue
|
||||
- `pnpm audit --prod` still reports one **low** advisory: `deepmerge` 4.2.0–4.3.1 (GHSA-gcqx-w48m-w2h4), reached
|
||||
through `payload`. No patched version exists yet; nothing to do in projects.
|
||||
|
||||
### What projects must update
|
||||
- **Projects with `cookieScanner`:**
|
||||
1. `pnpm payload generate:importmap` — adds `@intecion/ipal-kit/admin#CookieApprovalView` and
|
||||
`@intecion/ipal-kit/admin#CookieCrawlAlert` (the dashboard reminder now uses it even without `crawl`); commit
|
||||
`importMap.js`.
|
||||
2. Postgres/SQLite: `pnpm payload migrate:create` → `migrate` — the `cookie-review` collection gets `change` (an
|
||||
enum column with an index) and `needs_description` (boolean). Only new columns; nothing is dropped or renamed.
|
||||
MongoDB: nothing.
|
||||
3. Tell editors: after a scan, open **Approve cookies** (from the scan box on Privacy → Cookie review, or the
|
||||
dashboard), tick and **Approve and add**. Fill in the cookies
|
||||
marked **Needs description**. **Check:** run a scan → the new cookies appear on `/admin/cookie-approval`; approve
|
||||
one → it is in Cookie banner → Cookies in every language.
|
||||
4. Keep the old review instead: `cookieScanner: { approval: false }`.
|
||||
- Projects without `cookieScanner`: nothing.
|
||||
|
||||
## 1.14.2
|
||||
|
||||
### Fixed
|
||||
|
||||
+5
-2
@@ -108,7 +108,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 (`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 banner → Settings window → Cookie list headings 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** → *Approve cookies* → **Approve and add**; or cookie-scan → import) — feeds `<CookieTable>` on the policy page **and** the lists in the `detailed` window; Cookies → Settings window → Cookie list headings in every language | consent.md, analytics.md | A, `ipal-consent-check` |
|
||||
| 13 | Security | `buildSecurityHeaders` in `next.config.ts`; `withPayload(withSecurityConfig(nextConfig))` (no `X-Powered-By`); CSP: `buildSecurityHeaders({ csp: { mode: 'report-only', reportUri: '/api/csp-report', … } })` + `buildAdminCspHeaders` on `/admin/:path*` + `src/app/api/csp-report/route.ts` (`createCspReportRoute`) → read the reports → `mode: 'enforce'`; `twoFactor: { issuer, plugin: payloadTotp }` + `generate:importmap` (`TotpRedirectProvider`; check: a new admin lands on `/admin/setup-totp?back=%2Fadmin` with the QR, no reloading); `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 |
|
||||
@@ -948,7 +948,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 |
|
||||
| Cookie list filled from the panel (scan, then one approval adds every cookie to the list, the policy table and the detailed window) | `ipalKit({ cookieScanner: true })` + `pnpm generate:importmap` + migration; the editor approves on `/admin/cookie-approval`; project cookies: `cookieScanner.declarations` / `integrations`; per-entry review: `approval: false` — do not type the list by hand or build your own scanner or approval page | cookie-scanner.md |
|
||||
| Pre-consent check in a browser (button in the panel, violations, dashboard + e-mail warning) | `cookieScanner: { crawl: true }` + env `IPAL_COOKIE_SCAN_URL` / `IPAL_COOKIE_SCAN_TOKEN` (`ipalEnvRules({ cookieCrawl: true })`) + the site's `host=token` in the shared service's `IPAL_CRAWLER_SITES`; never Playwright/Chromium in the site | cookie-scanner.md → Browser crawl |
|
||||
| GA4, GTM, Pixel, Clarity, LinkedIn, TikTok | IDs in the panel — `SiteProviders` loads `Analytics` (`analytics={{ defer: true }}`; `consentMode: 'basic'` = no Google request before consent) | analytics.md |
|
||||
| Mail | `email: mailAdapter()`, `sendEmail` | email.md |
|
||||
@@ -982,6 +982,9 @@ add missing hosts with flags / `extra`; (3) change `mode` to `'enforce'` in both
|
||||
| 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 check (`crawl`): start editor+ or the token, results token-only for the running job, latest result only, dashboard warning on, e-mail off until recipients are set | omit `crawl`; `crawl.dashboard: false` | `crawl.serviceUrl` / `token` / `siteUrl` / `maxPages` / `acceptSelector` / `consentMode` / `trackerHosts` / `globalOverride`; *Cookie check → Warning e-mails to*; building blocks `ingestCrawlResult`, `findCrawlViolations`, `parseCrawlResult` |
|
||||
| Cookie admin: one *Cookies* entry — review list and site check as tabs, their own entries out of the navigation (pages and API kept) | `cookieScanner.adminLayout: 'separate'` | `addCookieScannerTabs`, `CookieReviewTab`, `CookieSiteCheckTab`; `collectionOverrides` / `crawl.globalOverride` win |
|
||||
| Text written in one language fills the empty languages (cookie list, cookie review), never over a language's own text | `fillEmptyLocales: false` | `fillEmptyLocales: { 'cookie-settings': [...], 'cookie-review': [...] }`; `buildFillEmptyLocalesGlobalHook` / `…CollectionHook` for your own globals and collections |
|
||||
| Cookie approval: one summary + **Approve and add** (editor+), unknown cookies approved as `marketing` + "Needs description", dashboard reminder while cookies wait; nothing reaches the cookie banner before approval | `cookieScanner.approval: false` (per-entry review) | `approval.unknownCategory`, `approval.dashboard: false`; building blocks `approveCookies`, `loadCookieApproval`, `countPendingCookies`, `flagGoneEntries`, `sameCookie` |
|
||||
| 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 |
|
||||
|
||||
@@ -50,15 +50,22 @@ list in the panel and you check it:
|
||||
(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. *Privacy → Cookie review* → **Scan cookies**. "Integrations in use" must match the IDs in Site
|
||||
2. *Privacy → Cookies → Review and approve* → **Scan cookies** (with `adminLayout: 'separate'`: *Privacy → Cookie review*). "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 banner →
|
||||
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
|
||||
names**, scan again. Cookies marked **Needs description** need provider, category and
|
||||
purpose: ask the client, do not guess (Edit on the approval page opens the entry).
|
||||
4. **Approve** in the same tab (also at `/admin/cookie-approval`): the cookies are grouped by category, new /
|
||||
changed / needs-description marked. Untick anything that should not be listed, then **Approve
|
||||
and add** — every ticked cookie goes to Cookies → Cookie list in every language (and so
|
||||
to the cookie policy table and the banner's detailed window); existing text is never
|
||||
overwritten, no row is duplicated. Unknown cookies land in `marketing` (or
|
||||
`approval.unknownCategory`) flagged "Needs description" — describe them before handover.
|
||||
Open the banner's "Settings" and check each category lists its cookies. A project with
|
||||
`approval: false` accepts entry by entry (Status → Accepted, bulk edit works).
|
||||
5. *No longer found* on the approval page = a cookie a scan stopped seeing; it stays in the cookie
|
||||
list. Remove the row there only when the site really no longer sets it.
|
||||
6. 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.
|
||||
|
||||
@@ -76,9 +83,11 @@ When the project has `cookieScanner: { crawl: true }` (cookie-scanner.md → Bro
|
||||
3. Filter the list by **Violation**: every entry is a non-necessary cookie or key stored before
|
||||
consent — fix it as in the table above (or, if it really is necessary, set its category and accept
|
||||
it). *Cookie check → Violations* also lists tracker **requests** before consent.
|
||||
4. Classify the new drafts (*Found by* = "Unknown — fill in"), then crawl again: 0 violations is
|
||||
the goal before handover.
|
||||
5. Optional: recipients in *Cookie check → Warning e-mails to*, and a weekly Coolify scheduled task
|
||||
4. Describe the cookies marked **Needs description**, approve on *Approve cookies* (the dashboard
|
||||
links there while cookies wait), then crawl again: 0 violations and nothing waiting is the goal
|
||||
before handover. A crawl never adds anything to the cookie banner by itself.
|
||||
5. Optional: recipients in *Cookie check → Warning e-mails to* (the e-mail also says when cookies
|
||||
wait for approval and links to the approval page), and a weekly Coolify scheduled task
|
||||
`curl -X POST -H "Authorization: Bearer $IPAL_COOKIE_SCAN_TOKEN" $NEXT_PUBLIC_SERVER_URL/api/ipal/cookie-crawl`.
|
||||
Record both in `AGENTS.md` → "Project decisions".
|
||||
|
||||
@@ -96,7 +105,7 @@ unknown names to the panel scan above instead of step 2):
|
||||
**non-necessary cookie set before consent** — fix it as in the table above. `[WARNING] unknown` —
|
||||
find the provider and purpose, set `category` (`necessary|functional|analytics|marketing`) and `purpose`
|
||||
in `cookies.json`. Do not guess — ask if you do not know.
|
||||
2. Import into the panel (Cookie banner → Cookie list), each language separately (scan with `--lang en` for English):
|
||||
2. Import into the panel (Cookies → Cookie list), each language separately (scan with `--lang en` for English):
|
||||
```bash
|
||||
LOCALE=pl pnpm payload run .agents/skills/ipal-consent-check/scripts/import-cookies.ts cookie-scan/cookies.json
|
||||
```
|
||||
@@ -104,7 +113,7 @@ unknown names to the panel scan above instead of step 2):
|
||||
the scan did not see — the editor does that in the panel. The same list feeds the
|
||||
`<CookieBanner settings="detailed">` window (an expandable list under each category) — after the import open
|
||||
"Settings" in the banner and check that every category shows its cookies and that the labels
|
||||
(Cookie banner → Settings window → Cookie list headings) are in that language.
|
||||
(Cookies → Settings window → Cookie list headings) are in that language.
|
||||
3. The cookie policy page shows the table from the panel — **do not paste the list into the policy text**:
|
||||
```tsx
|
||||
import { getCookieTable } from '@intecion/ipal-kit'
|
||||
@@ -115,7 +124,7 @@ unknown names to the panel scan above instead of step 2):
|
||||
<CookieTable rows={rows} categories={consent.categories} labels={labels} />
|
||||
```
|
||||
`labels` = `{ name, category, provider, purpose, duration }` (all required). The plugin panel
|
||||
has only `provider` / `purpose` / `duration` (Cookie banner → Settings window → Cookie list headings = `consent.details`);
|
||||
has only `provider` / `purpose` / `duration` (Cookies → Settings window → Cookie list headings = `consent.details`);
|
||||
take the `name` and `category` headers from (localized) fields of the project block. The table is unstyled
|
||||
(`classNames`: `table`, `caption`, `tr`, `th`, `td`; optional `caption`). A project "Cookie
|
||||
table" block on the policy page is a good place — then the editor decides where it appears.
|
||||
|
||||
@@ -66,7 +66,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 banner → Cookie list), "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: *Privacy → Cookie review* → **Scan cookies** → drafts appear; set one to Accepted → it is in Cookie banner → Cookie list (cookie-scanner.md) |
|
||||
| `cookieScanner` | off | `cookie-review` collection, "Scan cookies" box above its list (`CookieScanButton`), `GET`/`POST /api/ipal/cookie-scan`, and (unless `approval: false`) the *Approve cookies* view `/admin/cookie-approval` (`CookieApprovalView`) + `GET`/`POST /api/ipal/cookie-approval` + the dashboard reminder; a scan lists the cookies of the integrations switched on + names looked up in the bundled Open Cookie Database; one **Approve and add** puts the ticked cookies into Cookies → Cookie list (so `<CookieTable>` and the detailed window); never deletes, never overwrites edited text, never duplicates, nothing reaches the banner before approval | `true` / object; after switching on: `pnpm generate:importmap` + `migrate:create`. Check: *Privacy → Cookie review* → **Scan cookies** → "Waiting for approval: N" → **Review and approve** → **Approve and add** → the cookies are in Cookies → Cookie list (cookie-scanner.md) |
|
||||
| `cookieScanner.adminLayout` | `'combined'` | one *Cookies* entry: *Review and approve* and (with `crawl`) *Site check* tabs on the `cookie-settings` global (`ui` fields, `CookieReviewTab` / `CookieSiteCheckTab`); `cookie-review` and `cookie-crawl` get `admin.group: false` (out of the nav, pages and API kept) | `'separate'`; no migration, `generate:importmap` |
|
||||
| `fillEmptyLocales` | on | afterChange hooks: text saved in one language fills the empty languages of `cookie-settings` `cookies.purpose` / `cookies.duration` and `cookie-review` `purpose` / `retention`; never overwrites a language's own text | `false`; `{ 'cookie-settings': [...], 'cookie-review': [...] }` (`[]` = off); check: add a cookie in Polish, switch the locale to English → same purpose |
|
||||
| `cookieScanner.approval` | on | `false` = per-entry review only (no view, endpoint or reminder); `{ unknownCategory, dashboard }` — category for cookies nothing knows (default `'marketing'`, must need consent), dashboard reminder | adds `change` + `needsDescription` to `cookie-review` → `migrate:create` when upgrading |
|
||||
| `cookieScanner.declarations` / `.integrations` | built-ins only | the project's own cookies (`CookieDeclaration[]`), or `(defaults) => CookieIntegration[]` to add / change / drop integrations (`key`, `label`, `declarations`, `isEnabled(ctx)`) | e.g. a chat widget on when `ctx.integrations.chatId` is filled |
|
||||
| `cookieScanner.access` / `.collectionOverrides` / `.labels` | editor+ / none / `en` + `pl` | who may scan; changes `cookie-review` like `consentLog.collectionOverrides`; admin labels per language (`CookieScanLabels`) | object or function |
|
||||
| `cookieScanner.crawl` | off | browser pre-consent check through the shared scanner service (`services/cookie-crawler`, Coolify): **Check site** in the review box, `cookie-crawl` global (latest result only), `GET`/`POST /api/ipal/cookie-crawl`, `POST /api/ipal/cookie-crawl/results` (token), `violation` / `violationDetail` / `seenBeforeConsent` on `cookie-review`, `CookieCrawlAlert` on the dashboard, e-mail to *Cookie check → Warning e-mails to* | `true` / `CookieCrawlOptions`; env `IPAL_COOKIE_SCAN_URL` + `IPAL_COOKIE_SCAN_TOKEN`; `generate:importmap` + `migrate:create`. Check: the review box's **Check site** is enabled → click → "Last crawl …" with counts; `curl -X POST -H "Authorization: Bearer $IPAL_COOKIE_SCAN_TOKEN" $U/api/ipal/cookie-crawl` → 202 |
|
||||
@@ -92,7 +95,8 @@ description: Complete map of everything @intecion/ipal-kit provides — every ip
|
||||
| `forms`, `form-submissions` | form-builder + ipal blocks `step`, `checkboxGroup`, `time` | `forms` | omit `forms` |
|
||||
| `consent-records` | proof of consent (id, choices, policy version; `consentLog.collectionOverrides`) | `consentLog` | off by default |
|
||||
| global `cookie-crawl` | latest browser crawl (status, counts, violations, third-party hosts) + e-mail recipients; read editor+, update admin | `cookieScanner.crawl` (`globalOverride`) | off by default |
|
||||
| `cookie-review` | cookie scanner drafts (`status` draft / accepted / rejected; create/read/update editor+, delete admin) | `cookieScanner` | off by default |
|
||||
| `cookie-review` | cookie scanner entries (`status` draft / accepted / rejected, `change` new / changed / gone, `needsDescription`; create/read/update editor+, delete admin) | `cookieScanner` | off by default |
|
||||
| view `/admin/cookie-approval` | *Approve cookies*: everything waiting, grouped by category, one **Approve and add** | `cookieScanner.approval` | `approval: false` |
|
||||
| `stats-visits` | visits without IP (admin reads/deletes; `stats.collectionOverrides`) | `stats` | off by default |
|
||||
| global `site-settings` | General, Theme, [System pages], [E-mails], [Maintenance], Search engines, [More]; 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, [More]; admin only | `integrationsFields` | always present; `globalOverrides` |
|
||||
@@ -103,6 +107,7 @@ description: Complete map of everything @intecion/ipal-kit provides — every ip
|
||||
| `POST /api/ipal/consent` | saves consent | `consentLog` | off by default |
|
||||
| `POST /api/ipal/hit` | page view for stats | `stats` | off by default |
|
||||
| `GET`/`POST /api/ipal/cookie-crawl`, `POST /api/ipal/cookie-crawl/results` | crawl status / start (editor+ or bearer token) / the scanner service's callback (token, running job only) | `cookieScanner.crawl` | off by default |
|
||||
| `GET`/`POST /api/ipal/cookie-approval` | the approval list (`?locale=`) / approve (`{ ids? }`), editor+ | `cookieScanner.approval` (`access`) | `approval: false` |
|
||||
| `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` | — |
|
||||
@@ -119,7 +124,9 @@ description: Complete map of everything @intecion/ipal-kit provides — every ip
|
||||
| `IntecionCredit` | `afterLogin`, `afterNavLinks` | `whiteLabel` and `credit !== false` |
|
||||
| `StatsNavLink`, `StatsView` (`views.ipalStats`, `/stats`), `StatsWidget` (`beforeDashboard`) | nav, view, dashboard | `stats` (`dashboard: false` without the widget) |
|
||||
| `CookieScanButton` | `beforeListTable` of `cookie-review` (with **Check site** when `crawl` is on) | `cookieScanner` |
|
||||
| `CookieCrawlAlert` | `beforeDashboard` | `cookieScanner.crawl` and `dashboard !== false` |
|
||||
| `CookieReviewTab`, `CookieSiteCheckTab` | `ui` fields in the `cookie-settings` tabs | `cookieScanner` with `adminLayout !== 'separate'` (Site check: `crawl`) |
|
||||
| `CookieApprovalView` (+ client `CookieApprovalForm`) | `views.ipalCookieApproval`, path `/cookie-approval` | `cookieScanner` and `approval !== false` |
|
||||
| `CookieCrawlAlert` | `beforeDashboard` | `cookieScanner` with `approval.dashboard !== false` ("Waiting for approval"), or `crawl` with `dashboard !== false` |
|
||||
| `IntegrationAlerts` | `beforeDashboard` | **currently always** (renders nothing when everything works) |
|
||||
| `IntegrationStatusBanner` | UI field in the Site integrations tabs | always (with the global) |
|
||||
| `MaskedField` | SMTP / Turnstile secrets | always |
|
||||
@@ -168,7 +175,7 @@ Mandatory set: AGENT.md §0b, skill **ipal-setup**; checks: **ipal-audit**, **ip
|
||||
| Turnstile | panel / env | `SiteProviders` wires `TurnstileProvider`; keys in Site integrations → Turnstile or env; server: `verifyTurnstile` (`/server`) | widget in the form; dashboard alert on a bad key | turnstile.md |
|
||||
| consent | layout + policy page | banner via `SiteProviders`; table `<CookieTable rows={…} labels={…} />` (`/rsc`) from `getCookieTable` | `ipal-consent-check`; delete the consent cookie → the banner comes back | consent.md |
|
||||
| cookie crawl | config + env + service | `cookieScanner: { crawl: true }`, `IPAL_COOKIE_SCAN_URL` / `IPAL_COOKIE_SCAN_TOKEN`, site in the service's `IPAL_CRAWLER_SITES`; optional Coolify scheduled task `curl -X POST -H "Authorization: Bearer $IPAL_COOKIE_SCAN_TOKEN" $U/api/ipal/cookie-crawl` | **Check site** → "Last crawl …: N pages, N violations"; *Privacy → Cookie check* | cookie-scanner.md → Browser crawl |
|
||||
| cookie list | config | `cookieScanner: true` (+ `declarations` for embeds/chat), `generate:importmap`, `migrate:create` | *Cookie review* → **Scan cookies** → accept → Cookie banner → Cookie list; `<CookieBanner settings="detailed">` lists it | cookie-scanner.md |
|
||||
| cookie list | config | `cookieScanner: true` (+ `declarations` for embeds/chat), `generate:importmap`, `migrate:create` | *Cookie review* → **Scan cookies** → **Review and approve** → **Approve and add** → Cookies → Cookie list; `<CookieBanner settings="detailed">` and `<CookieTable>` list 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 |
|
||||
|
||||
@@ -25,7 +25,11 @@ Admin panel components from `@intecion/ipal-kit/admin` — the project does NOT
|
||||
| `RowLabel` | `@intecion/ipal-kit/admin` | Array row title in the panel taken from the row content (e.g. "Fast delivery" instead of "Item 01"). Do not wire by hand — use `rowLabel()`; after adding, `pnpm generate:importmap`. |
|
||||
| `AdminLogo` | `@intecion/ipal-kit/admin` | Server Component: large panel logo (login screen) from SiteSettings `logo`, fallback `siteName`. Injected by the plugin with `whiteLabel`; after turning the option on, `pnpm generate:importmap`. |
|
||||
| `AdminIcon` | `@intecion/ipal-kit/admin` | Server Component: small panel nav icon from SiteSettings `favicon`, fallback initials. Injected by the plugin with `whiteLabel`; after turning the option on, `pnpm generate:importmap`. |
|
||||
| `CookieCrawlAlert` | `@intecion/ipal-kit/admin` | Server Component: dashboard warning after a cookie crawl with violations or new unknown cookies, or a failed crawl; renders nothing otherwise. Injected with `cookieScanner.crawl` (`dashboard: false` drops it); after turning it on, `pnpm generate:importmap`. |
|
||||
| `CookieReviewTab` | `@intecion/ipal-kit/admin` | Client: the *Review and approve* tab of *Cookies* — scan box + approval list inline (reloads after approving; waits while the form has unsaved changes) + link to the review entries. Injected by `addCookieScannerTabs` (combined layout); `pnpm generate:importmap`. |
|
||||
| `CookieSiteCheckTab` | `@intecion/ipal-kit/admin` | Client: the *Site check* tab — start a check, status, latest violations, link to the warning e-mails. Injected with `crawl` in the combined layout. |
|
||||
| `CookieApprovalView` | `@intecion/ipal-kit/admin` | Server Component: the *Approve cookies* view at `/admin/cookie-approval` — everything waiting, grouped by consent category, one **Approve and add**. Injected with `cookieScanner` (unless `approval: false`); after turning it on, `pnpm generate:importmap`. |
|
||||
| `CookieApprovalForm` | `@intecion/ipal-kit/admin` | Client part of the view: tick boxes, markers (New / Changed / Needs description), Edit links, the button. Props `pending`, `gone`, `unknownCategory`, `labels?`, `adminRoute?` — reuse it in your own view. |
|
||||
| `CookieCrawlAlert` | `@intecion/ipal-kit/admin` | Server Component: dashboard warning — "Waiting for approval: N" with a link to the approval view, and with the crawl violations or a failed crawl; renders nothing otherwise. Props `approval`, `crawl`. Injected with `cookieScanner` (`approval.dashboard: false` / `crawl.dashboard: false` drop its parts); after turning it on, `pnpm generate:importmap`. |
|
||||
| `CookieScanButton` | `@intecion/ipal-kit/admin` | "Scan cookies" box above the *Cookie review* list: integrations in use, optional extra names, runs `POST /api/ipal/cookie-scan`. Injected by the plugin with `cookieScanner`; after turning it on, `pnpm generate:importmap`. |
|
||||
| `TotpRedirectProvider` | `@intecion/ipal-kit/admin` | Client admin provider: sends a user without TOTP to `/admin/setup-totp?back=…` and a user whose session has not passed TOTP to `/admin/verify-totp?back=…` (path read in the browser; never redirects away from those screens or logout; renders nothing while redirecting). Injected by the plugin with `twoFactor` in place of the package's header-based provider; swap with `twoFactor.provider`. After upgrading, `pnpm generate:importmap`. Check: a new admin lands on `setup-totp?back=%2Fadmin` with the QR code. Props type `TotpRedirectProviderProps` (`forceSetup`) |
|
||||
| `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 }`. |
|
||||
@@ -113,14 +117,14 @@ Admin panel components from `@intecion/ipal-kit/admin` — the project does NOT
|
||||
| `useConsent(options?)` | `@intecion/ipal-kit/client` | Low-level consent state hook → `{ state, decided, consentId, acceptAll, rejectAll, savePreferences, reopen }`. Usually use `ConsentProvider` + `useConsentContext` (the provider calls it itself). |
|
||||
| `useConsentContext()` | `@intecion/ipal-kit/client` | Hook: the `useConsent` value + `texts` from `ConsentProvider` — for your own consent-dependent UI (e.g. `state.marketing`). Throws outside the provider. |
|
||||
| `getConsentTexts({ payload, config, locale?, privacyPolicy?, settingsSlug? })` | `@intecion/ipal-kit` | Server: banner texts from the CookieSettings global (EN fallback per field) + privacy policy link from the system pages → `Promise<ConsentTexts>`; pass to `ConsentProvider texts`. |
|
||||
| `getCookieTable({ payload, locale? })` | `@intecion/ipal-kit` | Server: Cookie banner → Cookie list rows in one language → `Promise<CookieTableRow[]>` (does not throw) — for `CookieTable`. |
|
||||
| `getCookieTable({ payload, locale? })` | `@intecion/ipal-kit` | Server: Cookies → Cookie list rows in one language → `Promise<CookieTableRow[]>` (does not throw) — for `CookieTable`. |
|
||||
| `setDefaultConsent(state)` | `@intecion/ipal-kit` | Google Consent Mode `consent default` (with `wait_for_update`). `Analytics` calls it itself before loading Google tags — do not call. |
|
||||
| `updateConsent(state)` | `@intecion/ipal-kit` | Google Consent Mode `consent update` after the decision. `useConsent` calls it itself — do not call. |
|
||||
| `parseConsent(raw, version?)` | `@intecion/ipal-kit` | Consent cookie value → `ConsentState \| null` (null: missing, error or a different policy version). For server-side gating. |
|
||||
| `readConsentRecord(raw, version?)` | `@intecion/ipal-kit` | Like `parseConsent`, but the full record `{ id, state, timestamp, version } \| null`. |
|
||||
| `serializeConsent(state, version?, id?)` | `@intecion/ipal-kit` | `ConsentState` → encoded cookie value (with timestamp and version). Usually the provider does this. |
|
||||
| `CONSENT_COOKIE` | `@intecion/ipal-kit` | Consent cookie name: `'cookie-consent'`. |
|
||||
| `CONSENT_VERSION` | `@intecion/ipal-kit` | Default policy version: `1` (overridden in the panel: Cookie banner → Policy version; changing it invalidates old consents). |
|
||||
| `CONSENT_VERSION` | `@intecion/ipal-kit` | Default policy version: `1` (overridden in the panel: Cookies → Policy version; changing it invalidates old consents). |
|
||||
| `CONSENT_MAX_AGE` | `@intecion/ipal-kit` | Consent cookie lifetime in seconds: 180 days. |
|
||||
| `CONSENT_CATEGORIES` | `@intecion/ipal-kit` | `['necessary', 'functional', 'analytics', 'marketing']`; `necessary` always on. |
|
||||
| `DEFAULT_CONSENT` | `@intecion/ipal-kit` | State before the decision: only `necessary: true`. |
|
||||
@@ -136,7 +140,24 @@ Admin panel components from `@intecion/ipal-kit/admin` — the project does NOT
|
||||
|
||||
## 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.
|
||||
Opt-in with `ipalKit({ cookieScanner: true })`; the plugin wires the collection, endpoints, admin box and approval view. The exports are building blocks for a CLI, a scheduled job or your own admin view.
|
||||
|
||||
**One approval** (`cookieScanner.approval`, on by default):
|
||||
|
||||
| Export | Import from | What it does / when |
|
||||
|---|---|---|
|
||||
| `loadCookieApproval({ payload, locale, req? })` | `@intecion/ipal-kit` | What waits (`pending`: drafts and accepted cookies marked changed) and what is no longer found (`gone`), texts in one content locale → `CookieApprovalList` of `CookieApprovalItem`s. |
|
||||
| `approveCookies({ payload, ids?, unknownCategory?, addToList?, req? })` | `@intecion/ipal-kit` | **Approve and add**: accepts the pending entries (all, or `ids`) and adds them to Cookies → Cookie list in every locale — no duplicates (`sameCookie`), editor text and categories kept, unknown ones get `unknownCategory` + "Needs description" → `CookieApprovalResult`. |
|
||||
| `countPendingCookies(payload)` / `PENDING_WHERE` | `@intecion/ipal-kit` | How many cookies wait (dashboard, e-mail) / the `Where` for them. |
|
||||
| `buildCookieApprovalEndpoints(options)` | `@intecion/ipal-kit` | `GET`/`POST /api/ipal/cookie-approval` — the plugin wires them; call only to wire by hand. |
|
||||
| `flagGoneEntries({ payload, keep, where, req? })` | `@intecion/ipal-kit` | Marks entries a scan no longer finds `change: 'gone'` (never deletes) → count. |
|
||||
| `nextChange(existing, changed)` | `@intecion/ipal-kit` | Pure marker rule → `CookieChange` (`'new' \| 'changed' \| 'gone'`) or null. |
|
||||
| `addCookieScannerTabs(global, { approval, crawl, labels, unknownCategory? })` | `@intecion/ipal-kit` | Adds the *Review and approve* / *Site check* tabs (`ui` fields) to a global's `tabs` field — the plugin does it for `cookie-settings` (`adminLayout: 'combined'`). |
|
||||
| `sameCookie(a, b)` | `@intecion/ipal-kit` | Same name, or one is a pattern covering the other (`_ga_*` / `_ga_XYZ`). |
|
||||
| `COOKIE_APPROVAL_PATH` / `COOKIE_APPROVAL_VIEW_PATH` / `DEFAULT_UNKNOWN_CATEGORY` | `@intecion/ipal-kit` | `'/ipal/cookie-approval'` / `'/cookie-approval'` (admin route) / `'marketing'`. |
|
||||
|
||||
**Types:** `CookieApprovalOptions` (`approval`), `CookieApprovalItem`, `CookieApprovalList`, `CookieApprovalResult`, `CookieChange`.
|
||||
|
||||
|
||||
| Export | Import from | What it does / when |
|
||||
|---|---|---|
|
||||
@@ -147,7 +168,7 @@ Opt-in with `ipalKit({ cookieScanner: true })`; the plugin wires the collection,
|
||||
| `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 banner → Cookie list or fills only its empty text, every locale → `'added' \| 'filled' \| 'unchanged'`. |
|
||||
| `addToCookieList({ payload, entry, req? })` | `@intecion/ipal-kit` | What accepting does: adds the row to Cookies → Cookie list 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. |
|
||||
@@ -259,6 +280,9 @@ Full option lists of `createContentHelpers` / `createPageRoute` / `SiteProviders
|
||||
|---|---|---|
|
||||
| `buildRevalidateHook({ revalidatePath, config, homeSlug? })` | `@intecion/ipal-kit` | → `{ afterChange, afterDelete }` that revalidate ISR for the document paths in all languages; the project injects `revalidatePath` from `next/cache` |
|
||||
| `buildGlobalRevalidateHook({ revalidatePath })` | `@intecion/ipal-kit` | Global `afterChange`: `revalidatePath('/', 'layout')` — the whole site picks up the change. The plugin adds it to its own globals when you pass `ipalKit({ revalidatePath })`; wire it yourself on your own globals (Header, Footer). Skip once: `context: { disableRevalidate: true }`. |
|
||||
| `buildFillEmptyLocalesGlobalHook({ global, fields })` / `buildFillEmptyLocalesCollectionHook({ collection, fields })` | `@intecion/ipal-kit` | `afterChange`: text saved in one language fills the same field in every language where it is empty; never overwrites a language's own text. Fields `'field'` or `'array.subField'` (rows matched by id). The plugin adds them to the cookie list and the cookie review (`fillEmptyLocales`). |
|
||||
| `fillEmptyLocales({ payload, target, source, sourceLocale, fields, req? })` | `@intecion/ipal-kit` | The core of those hooks (`FillEmptyLocalesTarget`: `{ global }` or `{ collection, id }`) → locales changed. |
|
||||
| `withFillLocales(kind, config, fields)` | `@intecion/ipal-kit` | Adds the right hook to a global (`'global'`) or collection (`'collection'`) config; no fields = unchanged. |
|
||||
| `setPublishedAtHook` | `@intecion/ipal-kit` | `beforeChange`: sets `publishedAt` on first publish (does not overwrite an existing date) |
|
||||
| `trackSlugHistoryHook` | `@intecion/ipal-kit` | `beforeChange`: appends the old slug to the `slugHistory` field (add the field yourself); `resolveRedirect` reads it |
|
||||
| `buildPreventDeleteSystemPage({ settingsSlug?, roleFields? })` | `@intecion/ipal-kit` | `beforeDelete`: blocks deleting a page assigned to a system role (homepage, policies) |
|
||||
|
||||
@@ -432,8 +432,8 @@ list is currently fixed; block Markdown: `markdown: { overrides }` in `createCon
|
||||
**Steps.** Skill **ipal-form**: a block with `<RenderForm>` (`/rsc`), `src/components/forms/formClasses.ts`, the action from stage 6
|
||||
(one per project), every form from a **seed** `scripts/seed-form-*.ts` (email to the company + confirmation to the customer,
|
||||
every language, consent checkbox). Cookies: skill **ipal-consent-check** — `cookie-scan.mjs` → `import-cookies.ts` into
|
||||
Cookie banner → Cookie list; on the cookie policy page a block with `<CookieTable>` (`/rsc`, data from `getCookieTable`);
|
||||
the same list appears in the `settings="detailed"` dialog (labels: Cookie banner → Settings window → Cookie list headings, every language).
|
||||
Cookies → Cookie list; on the cookie policy page a block with `<CookieTable>` (`/rsc`, data from `getCookieTable`);
|
||||
the same list appears in the `settings="detailed"` dialog (labels: Cookies → Settings window → Cookie list headings, every language).
|
||||
|
||||
**Check.** Panel → Forms: the seeded form; a submission on `/pl` → an entry in Form Submissions + 2 emails (SMTP:
|
||||
Site integrations → SMTP → Send test); with Turnstile test keys the widget is visible, without a token the submission is rejected;
|
||||
@@ -450,7 +450,7 @@ no request to `googletagmanager.com` before analytics or marketing consent (a cl
|
||||
Check in `basic`: DevTools → Network shows no `gtm.js` / `gtag/js` before consent. Analytics: empty IDs in the panel or
|
||||
`analytics={false}`. Forms: `createSubmitAction({ turnstileHostnames: ['client.pl'] })` rejects a token solved on
|
||||
another domain (leave it empty in dev — Cloudflare test keys report `example.com`). The locale cookie respects consent;
|
||||
after an editor bumps Cookie banner → Policy version nothing to change (`createProxy(config, { policyVersion })` pins one).
|
||||
after an editor bumps Cookies → Policy version nothing to change (`createProxy(config, { policyVersion })` pins one).
|
||||
|
||||
## 10. Navigation
|
||||
|
||||
@@ -496,7 +496,7 @@ scaling (5). `●` routes for pages need the database at build time (PROGRAMISTA
|
||||
3. **Pages**: home page (title and slug **in every language**, otherwise `/en` → 404), 404, privacy policy,
|
||||
cookie policy (with the `CookieTable` block), terms if needed; `noindex` on the policies; AI summary.
|
||||
4. **Site settings → System pages**: Homepage (without it `/pl` → 404), 404, policies; content collection archives.
|
||||
5. **Cookie banner**: banner texts, Privacy link label, Policy version, Cookies (import from the scan), Detail labels —
|
||||
5. **Cookies**: banner texts, Privacy link label, Policy version, Cookies (import from the scan), Detail labels —
|
||||
in every language.
|
||||
6. **Notifications**: form messages in every language.
|
||||
7. **Site integrations**: SMTP or Graph (From Name/Address; Send test), Turnstile (for testing site
|
||||
|
||||
@@ -52,7 +52,7 @@ a custom table of contents (→ `extractHeadings` + `TableOfContents` + `heading
|
||||
|
||||
**→ 1.12.3 (PROGRAMISTA §6, item 46):** Postgres/SQLite: `migrate:create` (new Cookie banner group →
|
||||
`detailLabels`, only new columns — no rename). A custom cookie settings window or a cookie list added to
|
||||
the banner → `<CookieBanner settings="detailed">` and remove the copy. With `detailed`: Cookie banner → Cookie list filled in
|
||||
the banner → `<CookieBanner settings="detailed">` and remove the copy. With `detailed`: Cookies → Cookie list filled in
|
||||
(scan, **ipal-consent-check**) and Detail labels in every language.
|
||||
|
||||
**→ 1.13.0 (PROGRAMISTA §6, item 47; CHANGELOG "What projects must update" — do all 7, in order):**
|
||||
@@ -108,7 +108,7 @@ the banner → `<CookieBanner settings="detailed">` and remove the copy. With `d
|
||||
client; English only → `i18n: { supportedLanguages: { en } }`. Own admin texts → `i18n.translations.<lang>.ipal`.
|
||||
7. **Frontend texts:** validator messages are full sentences and `pl` locales get Polish fallbacks — grep the
|
||||
project's tests and code for the old strings (`'required'`, `'invalid email'`) and update them.
|
||||
8. **Sidebar:** `roles` (users) and Cookie banner → Consent version moved to the sidebar — update editor instructions.
|
||||
8. **Sidebar:** `roles` (users) and Cookies → Consent version moved to the sidebar — update editor instructions.
|
||||
Nothing else to change: the statistics tab title, the cookie scanner's integration names and the maintenance
|
||||
notice's close button follow the language by themselves.
|
||||
|
||||
@@ -135,6 +135,30 @@ the banner → `<CookieBanner settings="detailed">` and remove the copy. With `d
|
||||
3. **Enforce later** — after a few days of clean `[csp]` lines in the Coolify logs: `mode: 'enforce'` in both places,
|
||||
redeploy, check the pages again. Record the date in `AGENTS.md` → "Project decisions".
|
||||
|
||||
**→ 1.14.3 (PROGRAMISTA §6, item 52; cookie approval; cookie-scanner.md) — only with `cookieScanner`:**
|
||||
1. `pnpm payload generate:importmap` — `@intecion/ipal-kit/admin#CookieApprovalView` and
|
||||
`@intecion/ipal-kit/admin#CookieCrawlAlert` (the dashboard reminder, also without `crawl`); commit `importMap.js`.
|
||||
2. Postgres/SQLite: `pnpm payload migrate:create` → `migrate` (`cookie_review.change` enum + index,
|
||||
`cookie_review.needs_description`); check the migration only adds columns. MongoDB: nothing.
|
||||
3. Tell the editors about **Approve cookies** (`/admin/cookie-approval`, linked from the scan box on Privacy →
|
||||
Cookie review and from the dashboard): tick, **Approve and add**, then
|
||||
describe the ones marked **Needs description**. The client wants the old entry-by-entry review →
|
||||
`cookieScanner: { approval: false }`; unknown cookies in another category → `approval: { unknownCategory }`.
|
||||
4. Behaviour: hand-typed Cookie list rows are looked up only while they have no review entry.
|
||||
**Check:** run a scan → the cookies appear on `/admin/cookie-approval`; approve one → it is in Cookies →
|
||||
Cookies in every language; the dashboard shows the reminder while cookies wait. Without `cookieScanner`: nothing.
|
||||
|
||||
**→ 1.14.4 (PROGRAMISTA §6, item 53; cookie languages and one Cookies entry; consent.md, cookie-scanner.md):**
|
||||
1. `pnpm payload generate:importmap` — with `cookieScanner`: `@intecion/ipal-kit/admin#CookieReviewTab` and (with
|
||||
`crawl`) `@intecion/ipal-kit/admin#CookieSiteCheckTab`; commit `importMap.js`. No migration.
|
||||
2. **Ask the client** about the two new defaults (both overridable): empty languages of the cookie texts fill
|
||||
themselves from the language an editor writes in (`ipalKit({ fillEmptyLocales: false })` to turn it off); with
|
||||
`cookieScanner` the cookie screens become one **Cookies** entry with **Review and approve** and **Site check** tabs
|
||||
(`cookieScanner: { adminLayout: 'separate' }` for the old entries).
|
||||
3. Editor instructions and screenshots: **Cookie banner** is now **Cookies**.
|
||||
**Check:** one **Cookies** entry in the admin navigation; its tabs list the review entries and the site check;
|
||||
type a cookie purpose in one language and save → the other languages show it, and a language with its own text keeps it.
|
||||
|
||||
## 2. Inventory (no code changes)
|
||||
For **every** item in the PROGRAMISTA §6 table show evidence (grep / file) of whether
|
||||
it applies to the project. Run the **ipal-audit** skill (`--quick`) and attach the result.
|
||||
|
||||
+39
-12
@@ -14,8 +14,10 @@ project.
|
||||
|
||||
## Config
|
||||
|
||||
The **CookieSettings** global (slug `cookie-settings`, group *Settings*) is always
|
||||
built. Public read (`read: () => true` — the banner reads it for anonymous
|
||||
The **CookieSettings** global — **Cookies** in the admin (slug `cookie-settings`, group *Privacy*) — is always
|
||||
built. Tabs: *Banner*, *Settings window*, *Categories*, *Cookie list*; with the cookie scanner also
|
||||
*Review and approve* and *Site check* (one entry for everything about cookies — see
|
||||
[cookie-scanner.md → Admin layout](./cookie-scanner.md#admin-layout)). Public read (`read: () => true` — the banner reads it for anonymous
|
||||
visitors); `update` is limited to the `admin` and `editor` roles (`adminOrEditor` —
|
||||
consent texts are legal copy, not for plain `user` accounts). To change it:
|
||||
`ipalKit({ globalOverrides: { 'cookie-settings': { access: { update } } } })`.
|
||||
@@ -29,7 +31,7 @@ from a separate field.
|
||||
| What | Where from |
|
||||
|---|---|
|
||||
| Where it leads | Site settings → System pages → Privacy Policy |
|
||||
| Link text | Cookie banner → `privacyLinkLabel` (per language) |
|
||||
| Link text | Cookies → `privacyLinkLabel` (per language) |
|
||||
| When the text is empty | title of the policy page in that language |
|
||||
|
||||
`privacyPolicy` options in `getConsentTexts`: omit (automatic), `false` (no
|
||||
@@ -65,7 +67,7 @@ export default async function Layout({ children, params }) {
|
||||
const payload = await getPayload({ config })
|
||||
|
||||
// texts from Cookie banner; the policy link is automatic:
|
||||
// target = System pages → Privacy Policy, text = Cookie banner → privacyLinkLabel
|
||||
// target = System pages → Privacy Policy, text = Cookies → privacyLinkLabel
|
||||
const texts = await getConsentTexts({ payload, config: i18nConfig, locale })
|
||||
|
||||
return (
|
||||
@@ -248,7 +250,7 @@ Three settings modes to pick in the project — one prop:
|
||||
<CookieBanner equalChoice controls="switch" settings="detailed" />
|
||||
```
|
||||
|
||||
The cookie list comes from **Cookie banner → Cookie list** (the same source as `<CookieTable>` on the policy
|
||||
The cookie list comes from **Cookies → Cookie list** (the same source as `<CookieTable>` on the policy
|
||||
page), filtered by category — a category without entries has no expandable list. List labels: **Cookie
|
||||
Settings → Detail labels** (`cookies` — e.g. "Cookies used", the counter is added automatically; `provider`,
|
||||
`purpose`, `duration`), per language; empty → English. `getConsentTexts` passes this in `texts.cookies` /
|
||||
@@ -257,7 +259,7 @@ 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 (`ipalKit({ cookieScanner: true })` → *Cookie review* → **Scan cookies**,
|
||||
provided the Cookies list is filled from a scan (`ipalKit({ cookieScanner: true })` → *Cookie review* → **Scan cookies** → *Approve cookies* → **Approve and add**,
|
||||
[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".
|
||||
@@ -266,7 +268,7 @@ Recommendation (AGENT.md §7): tokens and `classNames` first — then fixes from
|
||||
project. When you need a completely different layout, you can build your own window; the data is in the
|
||||
context: `useConsentContext()` → `texts.cookies`, `texts.details`, `state`, `savePreferences`.
|
||||
|
||||
Texts from the panel (**Cookie banner**, per language) — empty field = the element is not shown:
|
||||
Texts from the panel (**Cookies**, per language) — empty field = the element is not shown:
|
||||
|
||||
| Field | Where |
|
||||
|---|---|
|
||||
@@ -286,7 +288,7 @@ The elements also have stable `data-ipal` handles for CSS and e2e tests (used by
|
||||
`accept`, `back`, `save`; in modal mode also `consent-overlay`, `consent-dialog`, `close`; in detailed mode
|
||||
additionally `category-<category>` (card) and `cookies` (expandable list).
|
||||
|
||||
Accessibility: the banner dialog and `CookieButton` have an `aria-label` from **Cookie banner →
|
||||
Accessibility: the banner dialog and `CookieButton` have an `aria-label` from **Cookies →
|
||||
title** or **settingsTitle** (per language) — no hard-coded texts in the components. The modal has
|
||||
`aria-modal`, focus on ✕ after opening and closes on Escape; switches have `role="switch"` and `aria-checked`.
|
||||
|
||||
@@ -330,9 +332,32 @@ independent consent state).
|
||||
> The consent mechanism for the locale is also described from the i18n side:
|
||||
> [i18n.md](./i18n.md#locale-cookie-and-consent-gdpr).
|
||||
|
||||
## Every language filled (`fillEmptyLocales`)
|
||||
|
||||
The cookie list's **Purpose** and **Duration** are per language. Text an editor writes in one language
|
||||
is copied to every language where that field is still empty, when the document is saved — a cookie
|
||||
added in Polish is not blank on the English page. A language that already has its own text is never
|
||||
overwritten, so each language can still be changed on its own. The same applies to the cookie review
|
||||
entries (purpose, duration). Cookie scanner and approval writes do the same with their own texts:
|
||||
English and Polish where they exist, the default language's text for any other language.
|
||||
|
||||
Payload's `localization.fallback` covers only part of this: an empty language *reads* as the default
|
||||
language's text, but nothing is stored, the admin shows the field empty, and the text always comes
|
||||
from the default language, not from the one just edited.
|
||||
|
||||
| Option | Default | |
|
||||
|---|---|---|
|
||||
| `fillEmptyLocales` | `true` | `false` = off; `{ 'cookie-settings': ['cookies.purpose'], 'cookie-review': [] }` = choose the fields per slug (`[]` = off for that slug). Field paths: `'field'` or `'arrayField.subField'` |
|
||||
|
||||
Building blocks for your own globals and collections (`@intecion/ipal-kit`):
|
||||
`buildFillEmptyLocalesGlobalHook({ global, fields })`, `buildFillEmptyLocalesCollectionHook({ collection, fields })`
|
||||
(afterChange hooks), `fillEmptyLocales({ payload, target, source, sourceLocale, fields, req? })` (the
|
||||
core, `FillEmptyLocalesTarget` = `{ global }` or `{ collection, id }`), and `withFillLocales(kind, config, fields)`
|
||||
to add the hook to a config. Nothing to migrate.
|
||||
|
||||
## Policy version, withdrawing consent, consent log, cookie table (1.9.1)
|
||||
|
||||
- **New consent after a policy change:** Cookie banner → *Consent version* (sidebar). Raise it by 1
|
||||
- **New consent after a policy change:** Cookies → *Consent version* (sidebar). Raise it by 1
|
||||
after adding a tool or changing the policy — every visitor will see the banner again.
|
||||
`getConsentTexts` passes the version to `<ConsentProvider texts>` automatically.
|
||||
- **Withdrawing consent deletes the tools' cookies** (`_ga`, `_ga_*`, `_gid`, `_fbp`, `_gcl_*`, Clarity,
|
||||
@@ -348,8 +373,8 @@ 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 banner → *Cookie list* + `getCookieTable` + `<CookieTable>` from `/rsc`.
|
||||
Fill the list from the panel with the cookie scanner (`cookieScanner` option — drafts an editor accepts,
|
||||
- **Cookie table** for the policy page: Cookies → *Cookie list* + `getCookieTable` + `<CookieTable>` from `/rsc`.
|
||||
Fill the list from the panel with the cookie scanner (`cookieScanner` option — one approval adds every cookie found to the list, the table and the detailed window,
|
||||
[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
|
||||
@@ -396,7 +421,9 @@ 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 list from the panel:** `ipalKit({ cookieScanner: true })` — opt-in: scan, then one **Approve and add**
|
||||
on the *Approve cookies* page puts every cookie found into the cookie list (and so into `<CookieTable>` and the
|
||||
detailed window); `cookieScanner: { approval: false }` keeps per-entry review. See
|
||||
[cookie-scanner.md](./cookie-scanner.md) (off, overrides and building blocks there).
|
||||
- **Pre-consent check in a real browser:** `cookieScanner: { crawl: true }` + the shared scanner service
|
||||
— **Check site** in the panel, violations (non-necessary cookies or trackers before consent), dashboard
|
||||
|
||||
+102
-35
@@ -1,13 +1,15 @@
|
||||
# cookie scanner
|
||||
|
||||
Fills the cookie list (Cookie banner → Cookie list) 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)).
|
||||
Fills the cookie list (Cookies → Cookie list) from the admin panel. A scan lists the cookies of
|
||||
every integration the project switches on, plus any extra names, in a review list. The editor then
|
||||
sees **one summary** — *Approve cookies*, grouped by consent category, new / changed / unknown marked —
|
||||
and one button, **Approve and add**, puts every ticked cookie everywhere it is listed: the cookie list,
|
||||
which feeds the `<CookieBanner settings="detailed">` window and `<CookieTable>` on the policy page
|
||||
([consent.md](./consent.md)). Projects that prefer it keep per-entry review (`approval: false`).
|
||||
|
||||
What a scan never does: delete an entry, change text an editor edited, change an entry's status, or
|
||||
publish anything by itself.
|
||||
What a scan never does: delete an entry, change text an editor edited, change an entry's status,
|
||||
add a second row for a cookie that is already listed, or add anything to the cookie banner before
|
||||
the editor approves.
|
||||
|
||||
Opt-in (`cookieScanner`, default off). Nothing is fetched at runtime and no browser is needed.
|
||||
|
||||
@@ -28,28 +30,66 @@ ipalKit({
|
||||
|
||||
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`.
|
||||
1. **Import map** — the scan box, the *Review and approve* / *Site check* tabs and the approval view
|
||||
are admin components (`@intecion/ipal-kit/admin#CookieScanButton`, `#CookieReviewTab`,
|
||||
`#CookieSiteCheckTab`, `#CookieApprovalView`). Run `pnpm generate:importmap` (again after upgrading
|
||||
to the combined layout — the two tab components are new).
|
||||
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 *Privacy → 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.
|
||||
**Upgrading a project that already had `cookieScanner` (1.14.x or earlier):** the approval step adds two
|
||||
fields to `cookie-review` — `change` (select) and `needsDescription` (checkbox). Run
|
||||
`pnpm payload migrate:create cookie-approval` and commit it. Existing entries keep their status;
|
||||
accepted ones are not re-approved, drafts show up on the approval page without a marker.
|
||||
3. **Verify** — log in as an editor, open *Privacy → Cookies → Review and approve*. The box lists
|
||||
"Integrations in use" (e.g. Cookie banner, Admin panel login, Google Analytics 4). Click **Scan
|
||||
cookies**: the cookies found appear below, grouped by category. Click **Approve and add**; the page
|
||||
reloads — open the *Cookie list* tab: the cookies are there, with purpose and duration in every
|
||||
language.
|
||||
|
||||
## Admin layout
|
||||
|
||||
One **Cookies** entry in *Privacy* holds everything (`adminLayout: 'combined'`, the default):
|
||||
|
||||
| Tab | What it is |
|
||||
|---|---|
|
||||
| Banner, Settings window, Categories | the banner texts ([consent.md](./consent.md)) |
|
||||
| Cookie list | the cookies shown in the banner's detailed window and the cookie policy table |
|
||||
| Review and approve | the scan box and the approval list inline; **Edit cookies one by one** opens the review entries |
|
||||
| Site check | only with `crawl`: start a check, its status, the violations of the latest check, a link to the warning e-mail settings |
|
||||
|
||||
The review list (`cookie-review`) and the site check result (`cookie-crawl`) leave the navigation
|
||||
(`admin.group: false`) but keep their pages, data and API — links from the dashboard, the e-mail and
|
||||
**Edit** still open them, and `/admin/cookie-approval` still works. The two tabs are `ui` fields: no data,
|
||||
no schema change, **no migration** — only `pnpm generate:importmap`. Approving in the tab writes the
|
||||
cookie list of the same screen, so the page reloads afterwards; while the screen has unsaved changes the
|
||||
button waits ("Save your changes first.").
|
||||
|
||||
`adminLayout: 'separate'` keeps the older layout: *Cookie review* and *Cookie check* as their own
|
||||
navigation entries, no extra tabs. A project's `collectionOverrides` / `crawl.globalOverride` (e.g. its own
|
||||
`admin.group`) win in both layouts.
|
||||
|
||||
Every language is filled: text written in one language (in the cookie list or a review entry) goes to
|
||||
the languages where that field is still empty, never over a language's own text
|
||||
([consent.md → Every language filled](./consent.md#every-language-filled-fillemptylocales)).
|
||||
|
||||
## How editors use it
|
||||
|
||||
| Step | What happens |
|
||||
|---|---|
|
||||
| **Scan cookies** | One draft per cookie of the integrations in use. Cookies already in Cookie banner → Cookie list 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 banner → Cookie list 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 banner — delete it there. |
|
||||
| **Scan cookies** | Every cookie of the integrations in use goes into the review list, marked **New**. Rows typed into the cookie list by hand are looked up once (*In the cookie list* is ticked). Nothing is added to the cookie banner yet. |
|
||||
| **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 is marked **Needs description**. |
|
||||
| **Review and approve** | The *Review and approve* tab of *Cookies* (the same list is also at `/admin/cookie-approval`, linked from the dashboard and the e-mail): one table per consent category (Necessary, Functional, Analytics, Marketing, then *Not yet described*), each cookie with provider, purpose and duration in the content language that matches the admin language, markers **New**, **Changed**, **Needs description**, an **Edit** link and a tick box. |
|
||||
| Untick or edit | Untick a cookie to leave it waiting; **Edit** opens its review entry (provider, category, purpose, duration per language). A later scan keeps every value you changed and still updates values you left as suggested. |
|
||||
| **Approve and add** | Every ticked cookie becomes *Accepted* and is added to *Cookies → Cookie list* in every language, with the plugin's English and Polish texts (a language without its own text gets the default language's text). A row that already lists the cookie — the same name, or a pattern that covers it, e.g. `_ga_*` and `_ga_XYZ123` — is never duplicated: only its empty provider / purpose / duration are filled, its text and category stay. The cookie list feeds the cookie policy table and the banner's detailed window, so the cookie appears there too. |
|
||||
| Unknown cookies | Approved into a category that needs consent (`approval.unknownCategory`, default `marketing`) and flagged **Needs description** on the review entry; writing a purpose clears the flag. |
|
||||
| A scan finds a change | An accepted cookie whose suggested text changed is marked **Changed** and waits for approval again; approving it fills only empty text in the cookie list. |
|
||||
| A cookie disappears | An integration switched off, a declaration removed, or a cookie the site check no longer sees: the entry is marked **No longer found** and listed under that heading on the approval page. Nothing is deleted — the cookie list keeps its row until an editor removes it there. Found again → the mark goes away. |
|
||||
| Per-entry review | Still works: set *Status* to *Accepted* on one entry (or in bulk edit) to add just that cookie. *Rejected* entries stay out and later scans do not bring them back. Rejecting never removes a row from the cookie list. |
|
||||
|
||||
Status changes work in the list's bulk edit too. Deleting review entries is admin-only and never done
|
||||
by the plugin.
|
||||
Deleting review entries is admin-only and never done by the plugin. While cookies wait, the
|
||||
dashboard shows "Waiting for approval: N" with a link to the approval view (`approval.dashboard: false`
|
||||
turns it off).
|
||||
|
||||
Labels are in English and Polish and follow the editor's admin language; `cookieScanner.labels` adds
|
||||
languages or changes text. The built-in integrations without a product name (Cookie banner, Admin panel
|
||||
@@ -131,8 +171,12 @@ run the tests, commit.
|
||||
| `access` | editor and up | `({ req }) => boolean` — who may scan, start a crawl and read its status |
|
||||
| `collectionOverrides` | — | Change `cookie-review`: an object merges `access` / `admin` / `hooks` key by key (your keys win), a function takes over (keep the slug) |
|
||||
| `labels` | `en`, `pl` | `{ de: { scanButton: 'Cookies scannen', … } }` — merged over the plugin's labels (`CookieScanLabels`) |
|
||||
| `syncAccepted` | `true` | `false` = accepting only marks the entry; nothing is written to Cookie banner |
|
||||
| `syncAccepted` | `true` | `false` = accepting or approving only marks the entry; nothing is written to Cookie banner |
|
||||
| `approval` | on | one summary and one **Approve and add** for everything found — `false` = per-entry review only (no view, no endpoint, no dashboard reminder); `{ unknownCategory, dashboard }` — see below |
|
||||
| `approval.unknownCategory` | `'marketing'` | category given to cookies nothing knows when they are approved; pick one that needs consent (`functional`, `analytics`, `marketing`) |
|
||||
| `approval.dashboard` | `true` | `false` = no "Waiting for approval" reminder on the dashboard |
|
||||
| `crawl` | off | browser crawl through the scanner service — [Browser crawl](#browser-crawl) |
|
||||
| `adminLayout` | `'combined'` | one *Cookies* entry with *Review and approve* and *Site check* tabs; `'separate'` = own navigation entries — [Admin layout](#admin-layout) |
|
||||
|
||||
A project declaration:
|
||||
|
||||
@@ -175,16 +219,21 @@ ipalKit({ cookieScanner: { integrations: (defaults) => [...defaults, chat] } })
|
||||
| | |
|
||||
|---|---|
|
||||
| `GET /api/ipal/cookie-scan` | `{ ok, integrations: [{ key, label }] }` — what a scan covers; `label` in the admin language of the request |
|
||||
| `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 }` |
|
||||
| `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, newUnknown, gone }, integrations }` |
|
||||
| `GET /api/ipal/cookie-approval?locale=pl` | `{ ok, pending, gone }` — `CookieApprovalItem`s (`id`, `name`, `category`, `vendor`, `purpose`, `retention`, `change`, `unknown`) in that content locale (default locale otherwise) |
|
||||
| `POST /api/ipal/cookie-approval` | body `{ ids?: (string \| number)[] }` — approves those pending entries (all pending without `ids`) → `{ ok, result: { added, filled, unchanged, needsDescription, skipped } }` |
|
||||
| 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).
|
||||
Paths: `COOKIE_SCAN_PATH` (`/ipal/cookie-scan`), `COOKIE_APPROVAL_PATH` (`/ipal/cookie-approval`), under the
|
||||
API route; the admin view is at `COOKIE_APPROVAL_VIEW_PATH` (`/cookie-approval`) under the admin 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`
|
||||
`setBeforeConsent`, `status` (`draft` / `accepted` / `rejected`), `needsDescription` (set when an
|
||||
unknown cookie is approved without a purpose; cleared when a purpose is written), and read-only
|
||||
`change` (`new` / `changed` / `gone` — what the latest scan noticed; approving clears it), `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
|
||||
@@ -202,26 +251,38 @@ All from `@intecion/ipal-kit` (server-safe), for your own admin view, a CLI or a
|
||||
| `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'` |
|
||||
| `addToCookieList({ payload, entry, req? })` | what accepting does: add the row or fill its empty text → `'added' \| 'filled' \| 'unchanged'`; a row with the same name or a covering pattern counts as the same cookie (`sameCookie(a, b)`) |
|
||||
| `loadCookieApproval({ payload, locale, req? })` | the approval list → `CookieApprovalList` (`pending`, `gone`) |
|
||||
| `approveCookies({ payload, ids?, unknownCategory?, addToList?, req? })` | what **Approve and add** does → `CookieApprovalResult` |
|
||||
| `countPendingCookies(payload)`, `PENDING_WHERE` | how many wait / the query for them (drafts, and accepted cookies marked changed) |
|
||||
| `buildCookieApprovalEndpoints(options)` | the GET/POST approval endpoints, to wire by hand |
|
||||
| `flagGoneEntries({ payload, keep, where, req? })`, `nextChange(existing, changed)` | the "no longer found" flag and the marker rule (`CookieChange`) |
|
||||
| `DEFAULT_UNKNOWN_CATEGORY` | `'marketing'` |
|
||||
| `CookieApprovalView`, `CookieApprovalForm` (`/admin`) | the approval view (server) and its form (client), injected as `views.ipalCookieApproval` |
|
||||
| `loadCookieDatabase()`, `indexCookieDatabase(rows)`, `lookupCookie(index, name, categories?)` | the Open Cookie Database lookup |
|
||||
| `DEFAULT_COOKIE_INTEGRATIONS`, `DEFAULT_DATABASE_CATEGORIES`, `cookieNameMatches(pattern, name)` | declarations and matching |
|
||||
| `buildCookieReviewCollection(options)`, `buildCookieScanEndpoints(options, plugin)` | the collection and endpoints, to wire by hand |
|
||||
| `COOKIE_SCAN_LABELS`, `mergeCookieScanLabels(overrides)` | admin labels |
|
||||
| `CookieScanButton` (`/admin`) | the box above the list (with **Check site** when `crawl` is on) |
|
||||
| `CookieCrawlAlert` (`/admin`) | the dashboard warning (injected with `crawl`) |
|
||||
| `CookieReviewTab`, `CookieSiteCheckTab` (`/admin`) | the two tabs of the combined layout (client components; props `approval`, `labels`, `unknownCategory` / `labels`) |
|
||||
| `addCookieScannerTabs(global, { approval, crawl, labels, unknownCategory? })` | adds those tabs to a global with a `tabs` field — for a project that builds its own cookie global |
|
||||
| `CookieScanButton` props `scan` / `onChange` | hide the scan part (the Site check tab) / called after a scan or a finished check |
|
||||
| `CookieApprovalForm` props `onApproved` / `blockedReason` | after approving (the tab reloads the page) / why the button waits |
|
||||
| `CookieCrawlAlert` (`/admin`) | the dashboard warning: cookies waiting for approval, and with `crawl` violations or a failed check (props `approval`, `crawl`) |
|
||||
| `buildCookieCrawlGlobal(labels)`, `buildCookieCrawlEndpoints({ labels, options, plugin })` | the crawl's global and endpoints, to wire by hand |
|
||||
| `resolveCrawlConfig(crawlOptions, payload)` | options + env + `serverURL` → `ResolvedCrawlConfig` (what is missing) |
|
||||
| `parseCrawlResult(body)` | validates the service's JSON (`CrawlResult`, `CrawlObservation`, `CrawlRequest`) |
|
||||
| `ingestCrawlResult({ payload, result, options, config, labels, plugin })`, `finishCrawl(…)` | applies a result: drafts, flags (→ `CrawlIngestSummary`), then the global and the e-mail |
|
||||
| `findCrawlViolations({ observations, requests, categoryOf, consentMode?, trackerHosts? })` | the violation rule, pure (`CrawlViolation`) |
|
||||
| `DEFAULT_TRACKER_HOSTS`, `GOOGLE_TAG_HOSTS` | request hosts that count before consent |
|
||||
| `sendCrawlWarning({ payload, labels, siteUrl, summary, to })` | the e-mail, through `payload.sendEmail` |
|
||||
| `sendCrawlWarning({ payload, labels, siteUrl, summary, to, pending? })` | the e-mail, through `payload.sendEmail`; with `pending` it says approval is waiting and links to the approval view |
|
||||
| `bearerMatches(header, token)` | constant-time bearer check |
|
||||
|
||||
Types: `CookieDeclaration`, `CookieIntegration`, `CookieScanContext`, `CookieFinding`,
|
||||
`CookieFindingSource`, `CookieStorage`, `LocalizedText`, `CookieScannerOptions`, `CookieScanSummary`,
|
||||
`CookieReviewValues`, `CookieDatabaseIndex`, `CookieScanLabels`, `OpenCookieCategory`,
|
||||
`CookieObservation`, `CookieReviewEntryRef`; crawl: `CookieCrawlOptions`, `ResolvedCrawlConfig`,
|
||||
`CookieObservation`, `CookieReviewEntryRef`; approval: `CookieApprovalOptions`, `CookieApprovalItem`,
|
||||
`CookieApprovalList`, `CookieApprovalResult`, `CookieChange`; crawl: `CookieCrawlOptions`, `ResolvedCrawlConfig`,
|
||||
`CrawlResult`, `CrawlObservation`, `CrawlRequest`, `CrawlViolation`, `CrawlIngestSummary`.
|
||||
|
||||
## Browser crawl
|
||||
@@ -275,14 +336,15 @@ ipalKit({
|
||||
|---|---|
|
||||
| Pages | the site URL + up to `maxPages` (default 20, max 100) same-origin URLs from `/sitemap.xml` (one level of sitemap index) |
|
||||
| Recorded per run | cookies (name, domain), `localStorage` and `sessionStorage` keys, hosts of third-party requests, with the first pages they appeared on |
|
||||
| New findings | every cookie / key goes through the same lookup and merge rules as **Scan cookies** — new names become **drafts**, edited text is kept, status is never changed, nothing is deleted |
|
||||
| New findings | every cookie / key goes through the same lookup and merge rules as **Scan cookies** — new names wait on the approval page (marked **New**), edited text is kept, status is never changed, nothing is added to the cookie banner before approval |
|
||||
| Disappeared | an accepted cookie the crawl no longer sees (and nothing still declares) is marked **No longer found** — for review only, never deleted |
|
||||
| Violation (cookie or key) | seen **before consent** and its review entry's category is not `necessary` — an entry without a category counts too, until an editor classifies it |
|
||||
| Violation (request) | a request **before consent** to a tracker host (`DEFAULT_TRACKER_HOSTS`: Meta, LinkedIn, TikTok, Clarity, Bing, Hotjar, YouTube). Google's tag hosts (`GOOGLE_TAG_HOSTS`) count only with `consentMode: 'basic'` — in `advanced` (the plugin's default) the Google tag may load before consent with every signal denied |
|
||||
| Review entries | `seenBeforeConsent`, `violation` and `violationDetail` ("before consent on /, /about") — from the **latest crawl only**: every crawl clears the previous flags |
|
||||
| Cookie check global (`cookie-crawl`) | latest result only (no history): status, started / finished, by whom, pages, counts, violations, third-party hosts, error |
|
||||
| "Accept all" not found | the second run had no consent — the global's error says so (`crawl.acceptSelector` for a custom banner) |
|
||||
| Dashboard | a warning above the dashboard after a crawl with violations or new unknown cookies, or a failed crawl (`crawl.dashboard: false` turns it off) |
|
||||
| E-mail | opt-in per site: *Privacy → Cookie check → E-mail warnings to* (admin; comma-separated). Sent after a crawl with violations or new unknown cookies, through the project's Payload email adapter (`email: mailAdapter()`, email.md). Empty = no e-mail |
|
||||
| Dashboard | a warning above the dashboard after a crawl with violations or a failed crawl (`crawl.dashboard: false` turns it off), and "Waiting for approval: N" with **Review and approve** while cookies wait (`approval.dashboard`) |
|
||||
| E-mail | opt-in per site: *Privacy → Cookie check → E-mail warnings to* (admin; comma-separated). Sent after a crawl with violations, new unknown cookies, or new cookies waiting for approval — then it says "Cookies waiting for approval: N. Nothing is added to the cookie banner until you approve them." and links to the approval view. Through the project's Payload email adapter (`email: mailAdapter()`, email.md). Empty = no e-mail |
|
||||
|
||||
A crawl still "running" after 30 minutes counts as failed (the service never reported back), and a new
|
||||
one may start. One crawl per site at a time (`409` otherwise).
|
||||
@@ -296,8 +358,9 @@ no editor session needed:
|
||||
curl -fsS -X POST -H "Authorization: Bearer $IPAL_COOKIE_SCAN_TOKEN" "$NEXT_PUBLIC_SERVER_URL/api/ipal/cookie-crawl"
|
||||
```
|
||||
|
||||
Weekly is plenty (`0 6 * * 1`). New violations or unknown cookies then show on the dashboard and, when
|
||||
recipients are set, by e-mail.
|
||||
Weekly is plenty (`0 6 * * 1`). New violations, unknown cookies and cookies waiting for approval then
|
||||
show on the dashboard and, when recipients are set, by e-mail. Nothing a scheduled crawl finds is added
|
||||
to the cookie banner until an editor approves it.
|
||||
|
||||
### `crawl` options
|
||||
|
||||
@@ -390,13 +453,17 @@ as unknown into **More cookie names**.
|
||||
|
||||
## Turn off, override, extend
|
||||
|
||||
- **Separate screens:** `adminLayout: 'separate'`.
|
||||
- **Turn off one approval:** `approval: false` — per-entry review only (set *Accepted* on each entry), no
|
||||
approval view, endpoint or reminder.
|
||||
- **Turn off the crawl only:** omit `crawl` (default) — no `cookie-crawl` global, no crawl endpoints, no
|
||||
dashboard warning, no violation fields; `dashboard: false` keeps the crawl without the warning.
|
||||
- **Turn off:** omit `cookieScanner` (default). Turning it off later keeps no endpoint and no
|
||||
collection; Cookie banner → Cookie list keeps every row (it is still edited by hand or by the skill's
|
||||
collection; Cookies → Cookie list keeps every row (it is still edited by hand or by the skill's
|
||||
import script).
|
||||
- **Override:** `collectionOverrides` (access, admin, hooks), `access` (who scans), `labels`,
|
||||
`databaseCategories`, `integrations` (change or drop a built-in), `syncAccepted: false`; for the
|
||||
`databaseCategories`, `integrations` (change or drop a built-in), `syncAccepted: false`,
|
||||
`approval.unknownCategory`, `approval.dashboard`; for the
|
||||
crawl `serviceUrl`, `token`, `siteUrl`, `maxPages`, `acceptSelector`, `consentMode`, `trackerHosts`,
|
||||
`globalOverride`.
|
||||
- **Extend:** `declarations` and `integrations` for the project's own cookies; the building blocks
|
||||
|
||||
@@ -312,7 +312,7 @@ turn off every part: `banner={<CookieBanner classNames={…} />}` / `false`, `co
|
||||
|
||||
Pick the consent settings window with the banner's `settings` prop: `'inline'` (default — categories in the bar),
|
||||
`'modal'` (small window in the center) or `'detailed'` (large window: each category with a switch, a description and
|
||||
an expandable list of cookies from Cookie banner → Cookie list). Example:
|
||||
an expandable list of cookies from Cookies → Cookie list). Example:
|
||||
`banner={<CookieBanner equalChoice controls="switch" settings="detailed" />}` — description: consent.md, the
|
||||
`settings="detailed"` section.
|
||||
|
||||
@@ -433,7 +433,7 @@ pnpm dev
|
||||
3. **Pages** — the homepage with a title **in every language** (empty EN slug = 404 on `/en`).
|
||||
4. **Site settings → System pages** — Homepage (without it `/pl` → 404), 404,
|
||||
policies; archives of content collections.
|
||||
5. **Cookie banner** — banner texts per language; **Cookies** (list from the scan, `ipal-consent-check`) and **Detail
|
||||
5. **Cookies** — banner texts per language; **Cookies** (list from the scan, `ipal-consent-check`) and **Detail
|
||||
labels** (captions of the list in the `settings="detailed"` window) — also in every language.
|
||||
6. **Notifications** — form messages per language.
|
||||
7. **Site integrations** — SMTP/Graph (From Name, From Address), Turnstile, analytics/pixel
|
||||
@@ -613,7 +613,7 @@ Do one item at a time, build, check. Order by importance:
|
||||
| 15m | own plugin moving Notifications into a group; `formOverrides`/`formSubmissionOverrides` only for labels and the admin group | delete — the plugin itself puts Form messages → Settings, and forms → the "Forms" group with labels (`forms.adminGroup`) | forms.md |
|
||||
| 15n | mail errors visible only in logs | nothing in the project: `mailAdapter()` shows the send error on the dashboard and in Site integrations → SMTP; `generate:importmap`, Postgres: `migrate:create` | email.md |
|
||||
| 16 | Hard-coded 404 | 404 role in System pages + `getNotFoundPage` | pages.md |
|
||||
| 16a | `privacyPolicy: { label: 'Polityka prywatności', … }` in the layout | delete the whole parameter; enter the text in Cookie banner → Privacy link label | consent.md |
|
||||
| 16a | `privacyPolicy: { label: 'Polityka prywatności', … }` in the layout | delete the whole parameter; enter the text in Cookies → Privacy link label | consent.md |
|
||||
| 17 | **AI/GEO (mandatory since 1.9.0)** | llms.txt + llms-full.txt, the `/md/…` route, `markdownAlternate: true`, `prefersMarkdown` in the proxy, `/api/mcp`, `buildSummaryField`, AI bots allowed — AGENT.md §0b | content.md, seo.md, mcp.md |
|
||||
| 18 | **1.9.0** — `TurnstileProvider siteKey` from `getSiteIntegrations(…).turnstileSiteKey` | `getTurnstileConfig(payload).siteKey`. Note: with both keys set `submitForm` **requires** a token — a form without the widget will be rejected | turnstile.md |
|
||||
| 19 | **1.9.0** — `twoFactor: { issuer }` without `plugin` | add `plugin: payloadTotp` (the fallback with a dynamic import was removed — startup fails with an error) | security.md |
|
||||
@@ -622,7 +622,7 @@ Do one item at a time, build, check. Order by importance:
|
||||
| 22 | **1.9.1** — hand-written `actions.ts` / `md` route / no form seed | `createSubmitAction`, `createMarkdownRoute`, seed from `ipal-form` (mail to the company + to the visitor) | forms.md, content.md |
|
||||
| 23 | **1.9.1** — `createProxy` without `markdown: true` | add it — otherwise `/md/…` redirects to `/pl/md/…` | content.md |
|
||||
| 24 | **1.9.1** — page JSON-LD assembled by hand | `getPageJsonLd`, `buildNavigationJsonLd`, `sameAsUrls`, `formatOpeningHours` | seo.md |
|
||||
| 25 | **1.9.1** — consent: version, log, table | Cookie banner → Policy version; `consentLog: true` + `logEndpoint`; `<CookieBanner equalChoice>`; scan + `<CookieTable>`; Postgres: `migrate:create` | consent.md |
|
||||
| 25 | **1.9.1** — consent: version, log, table | Cookies → Policy version; `consentLog: true` + `logEndpoint`; `<CookieBanner equalChoice>`; scan + `<CookieTable>`; Postgres: `migrate:create` | consent.md |
|
||||
| 26 | **1.9.1** — media: `priority`, no placeholders, `images` in next.config | `<Media>` through `mediaImageProps`/`videoProps`, `buildMediaPlaceholderHook`, `buildImagesConfig`, `buildUploadSecurityHeaders` | media.md, storage.md |
|
||||
| 27 | **1.9.1** — staging indexed | `IPAL_NOINDEX=1` in the staging env | seo.md |
|
||||
| 28 | **1.9.2** — own `FormRenderer` (a copy of the engine on `useForm`) | **security:** it passed the whole form document, including the Emails tab, to the browser (company addresses in the HTML). Block → `<RenderForm form action locale texts classNames>`, styling into `formClasses.ts`, delete `FormRenderer.tsx`; unusual form → `useBuilderForm` | forms.md |
|
||||
@@ -643,12 +643,14 @@ Do one item at a time, build, check. Order by importance:
|
||||
| 43 | **1.11.1** — `<Media>` sets the background color only for JPEG | delete the condition — `mediaImageProps` does it itself (`placeholderColor`) | media.md |
|
||||
| 44 | **1.11.1** — `CmsLink['appearance']` replaced with an own type because the type depended on field order | types per shape: `CmsLink`, `CmsLinkPlain`, `CmsLinkNoLabel`; `pnpm generate:types` and fix the imports | links.md |
|
||||
| 45 | **1.11.1** — format description in a form field label / time as text | the **Placeholder** field in the admin panel, the **Time** type; Postgres: `migrate:create` | forms.md |
|
||||
| 46 | **1.12.3** — own cookie settings window / cookie list in the banner written in the project | `<CookieBanner settings="detailed">` (list from Cookie banner → Cookie list, captions: Detail labels); delete your own version; Postgres: `migrate:create` | consent.md |
|
||||
| 46 | **1.12.3** — own cookie settings window / cookie list in the banner written in the project | `<CookieBanner settings="detailed">` (list from Cookies → Cookie list, captions: Detail labels); delete your own version; Postgres: `migrate:create` | consent.md |
|
||||
| 47 | **1.13.0** — staff access, Search engines, seed scripts, workarounds around plugin globals | without `access`: every logged-in account gets the staff features → `access` or `globalOverrides` / `formOverrides` / `formSubmissionOverrides` / `collectionOverrides`; with `access`: staff need `editor`/`admin`; Postgres: `migrate:create`; check `settingsDepth`, `sitemap()` throwing, 2FA slug, client IP; own seed code → `@intecion/ipal-kit/seed`; global hooks/access plugins → `revalidatePath` / `globalOverrides` | CHANGELOG 1.13.0, AGENT.md §7.1, seo.md, seeding.md |
|
||||
| 48 | **1.14.0 — image lightbox** — own image modal (`useState(index)` + `div role="dialog"`), `glightbox` / other lightbox library, thumbnails linking to the raw file in a new tab | `ipalKit({ lightbox: true })` + Postgres `migrate:create`; `<SiteProviders lightbox>`; `<LightboxTrigger group image={lightboxImage(media, { size })}>` around the thumbnail; delete the old dialog and `pnpm remove glightbox`; old label fields → Form messages → Image viewer | lightbox.md → "Replacing a hand-made modal" |
|
||||
| 49 | **1.14.0** — import map, Node, Next, audit, cookie list, admin languages | `pnpm payload generate:importmap` (`FaviconCheck`, `RowLabel`); Node 20.9+; `next@^16.4.3` + `sharp@^0.35.5` (Next ≤16.4.0 has two RCEs); `pnpm audit --prod` + `dompurify` / `undici` overrides on payload 3.90.x; hand-kept cookie list → `cookieScanner` (+ `crawl`, `IPAL_COOKIE_SCAN_URL` / `IPAL_COOKIE_SCAN_TOKEN`) + `migrate:create`; English-only admin → `i18n.supportedLanguages`; tests on validator strings → full sentences | CHANGELOG 1.14.0, cookie-scanner.md, i18n.md, AGENT.md §4 items 11–12 |
|
||||
| 50 | **1.14.1** — `X-Powered-By: Next.js, Payload` in responses, no CSP or a hand-written one | `withPayload(withSecurityConfig(nextConfig))`; `buildSecurityHeaders({ csp: { mode: 'report-only', reportUri: '/api/csp-report', …flags } })` + `buildAdminCspHeaders` on `/admin/:path*` + `export const POST = createCspReportRoute()`; after clean reports `mode: 'enforce'`; nonces (`createProxy({ csp })` + `<SiteProviders nonce>`) only for dynamic sites | security.md, CHANGELOG 1.14.1 |
|
||||
| 51 | **1.14.2** — a new admin stuck on `/admin/setup-totp?back=null` (the page keeps redirecting to itself), or an own `x-pathname` rule on `/admin` added as a workaround | `pnpm payload generate:importmap` (`TotpRedirectProvider`), commit `importMap.js`, redeploy; delete the workaround; own redirect rules → `twoFactor.provider` | security.md → "The redirect to the 2FA screens", CHANGELOG |
|
||||
| 52 | **1.14.3** — editors open every Cookie review entry one by one to accept it | with `cookieScanner`: `pnpm payload generate:importmap` (`CookieApprovalView`, `CookieCrawlAlert`), Postgres/SQLite `migrate:create` (`change`, `needs_description`); editors use Approve cookies (`/admin/cookie-approval`, linked from Privacy → Cookie review); old flow: `cookieScanner: { approval: false }` | cookie-scanner.md, CHANGELOG 1.14.3 |
|
||||
| 53 | **1.14.4** — cookie texts retyped in every language; three cookie entries in the admin navigation | `pnpm payload generate:importmap` (`CookieReviewTab`, `CookieSiteCheckTab`); empty languages fill themselves (`fillEmptyLocales: false` to keep them empty); with `cookieScanner` one **Cookies** entry with tabs (`cookieScanner: { adminLayout: 'separate' }` for the old entries); Cookie banner is now called Cookies — update editor instructions; no migration | consent.md, cookie-scanner.md, hooks.md, CHANGELOG 1.14.4 |
|
||||
|
||||
After updating the package: `pnpm ipal:skills` (new skill versions), `pnpm payload generate:importmap`, `rm -rf .next`, restart dev, grep for the new symbol in
|
||||
`node_modules/@intecion/ipal-kit/dist`.
|
||||
|
||||
@@ -159,6 +159,11 @@ Rules:
|
||||
`Ustawienia`, `Prywatność`, `Statystyki`). Settings holds configuration only; logs and records
|
||||
(consent log, visits) go to their own group. A nav link or view the user cannot open is
|
||||
hidden, never shown with "You do not have access".
|
||||
- **One entry per feature.** Screens that serve one feature become tabs of one global, not
|
||||
separate navigation entries: *Cookies* holds the banner texts, the cookie list, *Review and
|
||||
approve* and *Site check*. Supporting collections and globals leave the navigation with
|
||||
`admin.group: false` (their pages and API stay, links still open them) and appear as `ui`-field
|
||||
tabs. Logs stay separate (*Consent log*).
|
||||
- A global or collection is named for what the editor finds in it ("Form messages"), not
|
||||
for the mechanism behind it ("Notifications"). Renaming the visible label never changes
|
||||
the slug.
|
||||
|
||||
@@ -232,6 +232,28 @@ A sync error is logged; the save does not fail.
|
||||
|
||||
---
|
||||
|
||||
## buildFillEmptyLocalesGlobalHook / buildFillEmptyLocalesCollectionHook — text into empty languages
|
||||
|
||||
The text counterpart of `buildCrossLocaleFieldSync`: text saved in one language goes to every
|
||||
language where that field is still empty; a language with its own text is never overwritten. The
|
||||
plugin adds it to the cookie list and the cookie review (`ipalKit({ fillEmptyLocales })`, consent.md).
|
||||
On your own global or collection:
|
||||
|
||||
```ts
|
||||
import { buildFillEmptyLocalesGlobalHook } from '@intecion/ipal-kit'
|
||||
|
||||
hooks: {
|
||||
afterChange: [buildFillEmptyLocalesGlobalHook({ global: 'footer', fields: ['tagline', 'links.label'] })],
|
||||
}
|
||||
```
|
||||
|
||||
Fields: `'field'` or `'arrayField.subField'` (rows matched by their id). The collection variant takes
|
||||
`{ collection, fields }`. It skips its own writes (`context.ipalFillLocales`) and the cookie scanner's,
|
||||
puts `req.locale` back afterwards, and logs instead of failing the save. Core function:
|
||||
`fillEmptyLocales`; `withFillLocales(kind, config, fields)` adds the hook to a config.
|
||||
|
||||
---
|
||||
|
||||
## buildNoindexField — checkbox → meta.noindex (a field, not a hook)
|
||||
|
||||
A sidebar `noindex` checkbox kept in sync with `meta.noindex` (which the sitemap and
|
||||
|
||||
+1
-1
@@ -125,7 +125,7 @@ changes when `day` changes in the `timeZone` zone.
|
||||
|
||||
## For the privacy policy and the cookie table
|
||||
|
||||
Add a row in **Cookie banner → Cookie list** (panel):
|
||||
Add a row in **Cookies → Cookie list** (panel):
|
||||
|
||||
| Name | Provider | Category | Purpose | Duration |
|
||||
|---|---|---|---|---|
|
||||
|
||||
+1
-1
@@ -1,6 +1,6 @@
|
||||
{
|
||||
"name": "@intecion/ipal-kit",
|
||||
"version": "1.14.2",
|
||||
"version": "1.14.4",
|
||||
"description": "Intecion Payload Advanced Library — a Payload CMS 3 plugin: i18n, SEO, forms, consent, analytics, blog/archives.",
|
||||
"license": "MIT",
|
||||
"repository": {
|
||||
|
||||
@@ -10,7 +10,11 @@ export { TestEmailButton } from '../globals/SiteIntegrations/components/TestEmai
|
||||
export { DocumentTitle } from '../modules/admin-i18n/DocumentTitle.js'
|
||||
export { RowLabel } from '../modules/admin-ui/RowLabelComponent.js'
|
||||
export { AdminIcon, AdminLogo, IntecionCredit } from '../modules/branding/index.js'
|
||||
export { CookieApprovalForm } from '../modules/consent/scanner/CookieApprovalForm.js'
|
||||
export { CookieApprovalView } from '../modules/consent/scanner/CookieApprovalView.js'
|
||||
export { CookieReviewTab } from '../modules/consent/scanner/CookieReviewTab.js'
|
||||
export { CookieScanButton } from '../modules/consent/scanner/CookieScanButton.js'
|
||||
export { CookieSiteCheckTab } from '../modules/consent/scanner/CookieSiteCheckTab.js'
|
||||
export { CookieCrawlAlert } from '../modules/consent/scanner/crawl/CookieCrawlAlert.js'
|
||||
export { IntegrationAlerts } from '../modules/integrations/IntegrationAlerts.js'
|
||||
export { IntegrationStatusBanner } from '../modules/integrations/IntegrationStatusBanner.js'
|
||||
|
||||
@@ -4,7 +4,8 @@ import { userMeetsRole } from '../../modules/access/index.js'
|
||||
import { cookieSettingsFields } from './fields.js'
|
||||
|
||||
/**
|
||||
* Builds the CookieSettings global — consent banner copy managed by editors.
|
||||
* Builds the CookieSettings global ("Cookies" in the admin) — consent banner copy and the
|
||||
* cookie list, managed by editors. With the cookie scanner it also carries its tabs.
|
||||
* Public read (the banner needs it on the frontend for anonymous visitors).
|
||||
*/
|
||||
export function buildCookieSettings(): GlobalConfig {
|
||||
@@ -18,6 +19,6 @@ export function buildCookieSettings(): GlobalConfig {
|
||||
group: { en: 'Privacy', pl: 'Prywatność' },
|
||||
},
|
||||
fields: cookieSettingsFields,
|
||||
label: { en: 'Cookie banner', pl: 'Baner cookies' },
|
||||
label: { en: 'Cookies', pl: 'Cookies' },
|
||||
}
|
||||
}
|
||||
|
||||
+31
-1
@@ -61,14 +61,19 @@ export {
|
||||
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 {
|
||||
addCookieScannerTabs,
|
||||
addToCookieList,
|
||||
applyCookieFindings,
|
||||
approveCookies,
|
||||
bearerMatches,
|
||||
buildCookieApprovalEndpoints,
|
||||
buildCookieCrawlEndpoints,
|
||||
buildCookieCrawlGlobal,
|
||||
buildCookieReviewCollection,
|
||||
buildCookieScanEndpoints,
|
||||
collectCookieFindings,
|
||||
COOKIE_APPROVAL_PATH,
|
||||
COOKIE_APPROVAL_VIEW_PATH,
|
||||
COOKIE_CRAWL_PATH,
|
||||
COOKIE_CRAWL_RESULTS_PATH,
|
||||
COOKIE_CRAWL_SLUG,
|
||||
@@ -79,26 +84,38 @@ export {
|
||||
COOKIE_SCAN_URL_ENV,
|
||||
cookieNameMatches,
|
||||
cookieScanContext,
|
||||
countPendingCookies,
|
||||
DEFAULT_COOKIE_INTEGRATIONS,
|
||||
DEFAULT_DATABASE_CATEGORIES,
|
||||
DEFAULT_TRACKER_HOSTS,
|
||||
DEFAULT_UNKNOWN_CATEGORY,
|
||||
findCrawlViolations,
|
||||
finishCrawl,
|
||||
flagGoneEntries,
|
||||
GOOGLE_TAG_HOSTS,
|
||||
indexCookieDatabase,
|
||||
ingestCrawlResult,
|
||||
loadCookieApproval,
|
||||
loadCookieDatabase,
|
||||
lookupCookie,
|
||||
mergeCookieReview,
|
||||
mergeCookieScanLabels,
|
||||
nextChange,
|
||||
parseCookieNames,
|
||||
parseCrawlResult,
|
||||
PENDING_WHERE,
|
||||
resolveCrawlConfig,
|
||||
runCookieScan,
|
||||
sameCookie,
|
||||
sendCrawlWarning,
|
||||
suggestionFor,
|
||||
} from './modules/consent/scanner/index.js'
|
||||
export type {
|
||||
CookieApprovalItem,
|
||||
CookieApprovalList,
|
||||
CookieApprovalOptions,
|
||||
CookieApprovalResult,
|
||||
CookieChange,
|
||||
CookieCrawlOptions,
|
||||
CookieDatabaseIndex,
|
||||
CookieDeclaration,
|
||||
@@ -198,7 +215,20 @@ export type { ContentHelpers, EntryJsonLdContext, PageJsonLdOptions, SiteShell }
|
||||
export { createContentHelpers } from './modules/frontend/index.js'
|
||||
// Healthcheck route (Coolify/Docker liveness with a real DB round-trip).
|
||||
export { createHealthRoute } from './modules/health/index.js'
|
||||
export { buildCrossLocaleFieldSync, buildGlobalRevalidateHook, buildPreventDeleteSystemPage, buildRevalidateHook, buildValidateUniqueRole, setPublishedAtHook, trackSlugHistoryHook } from './modules/hooks/index.js'
|
||||
export {
|
||||
buildCrossLocaleFieldSync,
|
||||
buildFillEmptyLocalesCollectionHook,
|
||||
buildFillEmptyLocalesGlobalHook,
|
||||
buildGlobalRevalidateHook,
|
||||
buildPreventDeleteSystemPage,
|
||||
buildRevalidateHook,
|
||||
buildValidateUniqueRole,
|
||||
fillEmptyLocales,
|
||||
setPublishedAtHook,
|
||||
trackSlugHistoryHook,
|
||||
withFillLocales,
|
||||
} from './modules/hooks/index.js'
|
||||
export type { FillEmptyLocalesTarget } from './modules/hooks/index.js'
|
||||
export { createProxy, DEFAULT_PROXY_MATCHER } from './modules/i18n/createProxy.js'
|
||||
export { getLocalizedSlugs } from './modules/i18n/getLocalizedSlugs.js'
|
||||
export { getDefaultLocale, getLocaleCodes, getLocaleDefinition, isValidLocale } from './modules/i18n/helpers.js'
|
||||
|
||||
@@ -0,0 +1,197 @@
|
||||
'use client'
|
||||
|
||||
import { Button, toast, useConfig, useTranslation } from '@payloadcms/ui'
|
||||
import { useRouter } from 'next/navigation.js'
|
||||
import { useState } from 'react'
|
||||
|
||||
import type { ConsentCategory } from '../categories.js'
|
||||
import type { CookieApprovalItem, CookieApprovalResult } from './approval.js'
|
||||
import type { CookieScanLabels } from './labels.js'
|
||||
|
||||
import { COOKIE_SCAN_LABELS } from './labels.js'
|
||||
|
||||
const CATEGORY_ORDER: ConsentCategory[] = ['necessary', 'functional', 'analytics', 'marketing']
|
||||
// COOKIE_REVIEW_SLUG — not imported: collection.ts is server config, this file ships to the browser.
|
||||
const REVIEW_SLUG = 'cookie-review'
|
||||
const hidden = { clip: 'rect(0 0 0 0)', height: 1, overflow: 'hidden', position: 'absolute', width: 1 } as const
|
||||
|
||||
const fill = (template: string, values: Record<string, number | string>) =>
|
||||
template.replace(/\{(\w+)\}/g, (_, k: string) => String(values[k] ?? ''))
|
||||
|
||||
const CSS = `
|
||||
.ipal-cookie-approval table { border-collapse: collapse; width: 100%; margin-bottom: 1.5rem; }
|
||||
.ipal-cookie-approval th, .ipal-cookie-approval td { border-bottom: 1px solid var(--theme-elevation-150); padding: .5rem .5rem; text-align: left; vertical-align: top; }
|
||||
.ipal-cookie-approval th { font-weight: 600; font-size: .85rem; color: var(--theme-elevation-600); }
|
||||
.ipal-cookie-approval h2 { margin: 1.5rem 0 .5rem; font-size: 1.15rem; }
|
||||
.ipal-cookie-approval .ipal-badge { display: inline-block; border-radius: 999px; padding: 0 .5rem; margin: 0 .25rem .25rem 0; font-size: .75rem; line-height: 1.5rem; white-space: nowrap; background: var(--theme-elevation-100); }
|
||||
.ipal-cookie-approval .ipal-badge--new { background: var(--theme-success-100, #d9f2e3); color: var(--theme-success-800, #14532d); }
|
||||
.ipal-cookie-approval .ipal-badge--changed { background: var(--theme-warning-100, #fff1c2); color: var(--theme-warning-800, #6b4e00); }
|
||||
.ipal-cookie-approval .ipal-badge--unknown { background: var(--theme-error-100, #fde2e2); color: var(--theme-error-800, #7f1d1d); }
|
||||
.ipal-cookie-approval .ipal-bar { position: sticky; bottom: 0; display: flex; flex-wrap: wrap; gap: 1rem; align-items: center; padding: 1rem 0; background: var(--theme-bg); border-top: 1px solid var(--theme-elevation-150); }
|
||||
`
|
||||
|
||||
/**
|
||||
* The approval list (client): one table per consent category, every cookie
|
||||
* ticked, a marker for new / changed / not yet described, an Edit link to the
|
||||
* review entry, and one "Approve and add" button for the ticked ones.
|
||||
*/
|
||||
export function CookieApprovalForm({
|
||||
adminRoute = '/admin',
|
||||
blockedReason,
|
||||
gone,
|
||||
labels = COOKIE_SCAN_LABELS,
|
||||
onApproved,
|
||||
pending,
|
||||
unknownCategory,
|
||||
}: {
|
||||
adminRoute?: string
|
||||
/** Why approving is not possible right now (shown next to the disabled button), e.g. unsaved changes. */
|
||||
blockedReason?: null | string
|
||||
gone: CookieApprovalItem[]
|
||||
labels?: Record<string, CookieScanLabels>
|
||||
/** After a successful approval. Default: reload the route's server data. */
|
||||
onApproved?: (result: CookieApprovalResult) => void
|
||||
pending: CookieApprovalItem[]
|
||||
unknownCategory: ConsentCategory
|
||||
}) {
|
||||
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-approval`
|
||||
const admin = adminRoute.replace(/\/$/, '')
|
||||
const [excluded, setExcluded] = useState<Set<number | string>>(() => new Set())
|
||||
const [busy, setBusy] = useState(false)
|
||||
const [done, setDone] = useState<CookieApprovalResult | null>(null)
|
||||
const selected = pending.filter((p) => !excluded.has(p.id))
|
||||
|
||||
const toggle = (id: number | string) =>
|
||||
setExcluded((prev) => {
|
||||
const next = new Set(prev)
|
||||
if (next.has(id)) {next.delete(id)}
|
||||
else {next.add(id)}
|
||||
return next
|
||||
})
|
||||
|
||||
const approve = async () => {
|
||||
setBusy(true)
|
||||
try {
|
||||
const res = await fetch(endpoint, {
|
||||
body: JSON.stringify({ ids: selected.map((p) => p.id) }),
|
||||
credentials: 'include',
|
||||
headers: { 'Content-Type': 'application/json' },
|
||||
method: 'POST',
|
||||
})
|
||||
const data = (await res.json()) as { ok?: boolean; result?: CookieApprovalResult }
|
||||
if (!res.ok || !data.ok || !data.result) {throw new Error('approval failed')}
|
||||
setDone(data.result)
|
||||
toast.success(fill(t.approvalDone, { ...data.result }))
|
||||
setExcluded(new Set())
|
||||
if (onApproved) {onApproved(data.result)}
|
||||
else {router.refresh()}
|
||||
} catch {
|
||||
toast.error(t.approvalError)
|
||||
} finally {
|
||||
setBusy(false)
|
||||
}
|
||||
}
|
||||
|
||||
const groups = [
|
||||
...CATEGORY_ORDER.map((c) => ({ items: pending.filter((p) => p.category === c), key: c, note: null as null | string, title: t[c] })),
|
||||
{
|
||||
items: pending.filter((p) => !p.category),
|
||||
key: 'none',
|
||||
note: fill(t.uncategorizedNote, { category: t[unknownCategory].toLowerCase() }),
|
||||
title: t.uncategorized,
|
||||
},
|
||||
].filter((g) => g.items.length)
|
||||
|
||||
const row = (p: CookieApprovalItem, withBox: boolean) => (
|
||||
<tr key={p.id}>
|
||||
{withBox ? (
|
||||
<td style={{ width: '2rem' }}>
|
||||
<input
|
||||
aria-label={`${t.include}: ${p.name}`}
|
||||
checked={!excluded.has(p.id)}
|
||||
onChange={() => toggle(p.id)}
|
||||
type="checkbox"
|
||||
/>
|
||||
</td>
|
||||
) : null}
|
||||
<td>
|
||||
<code>{p.name}</code>
|
||||
<div>
|
||||
{p.change === 'new' ? <span className="ipal-badge ipal-badge--new">{t.markerNew}</span> : null}
|
||||
{p.change === 'changed' ? <span className="ipal-badge ipal-badge--changed">{t.markerChanged}</span> : null}
|
||||
{p.unknown ? <span className="ipal-badge ipal-badge--unknown">{t.markerUnknown}</span> : null}
|
||||
</div>
|
||||
</td>
|
||||
<td>{p.vendor ?? ''}</td>
|
||||
<td>{p.purpose ?? ''}</td>
|
||||
<td>{p.retention ?? ''}</td>
|
||||
<td>
|
||||
<a href={`${admin}/collections/${REVIEW_SLUG}/${p.id}`}>{t.edit}</a>
|
||||
</td>
|
||||
</tr>
|
||||
)
|
||||
|
||||
const head = (withBox: boolean) => (
|
||||
<thead>
|
||||
<tr>
|
||||
{withBox ? <th scope="col"><span style={hidden}>{t.include}</span></th> : null}
|
||||
<th scope="col">{t.name}</th>
|
||||
<th scope="col">{t.vendor}</th>
|
||||
<th scope="col">{t.purpose}</th>
|
||||
<th scope="col">{t.retention}</th>
|
||||
<th scope="col"><span style={hidden}>{t.edit}</span></th>
|
||||
</tr>
|
||||
</thead>
|
||||
)
|
||||
|
||||
return (
|
||||
<div className="ipal-cookie-approval">
|
||||
<style>{CSS}</style>
|
||||
{pending.length ? (
|
||||
<>
|
||||
<p>{t.approvalIntro}</p>
|
||||
{groups.map((g) => (
|
||||
<section data-ipal={`approval-${g.key}`} key={g.key}>
|
||||
<h2>{g.title} ({g.items.length})</h2>
|
||||
{g.note ? <p style={{ marginTop: 0 }}>{g.note}</p> : null}
|
||||
<table>
|
||||
{head(true)}
|
||||
<tbody>{g.items.map((p) => row(p, true))}</tbody>
|
||||
</table>
|
||||
</section>
|
||||
))}
|
||||
<div className="ipal-bar">
|
||||
<Button buttonStyle="primary" disabled={busy || !selected.length || Boolean(blockedReason)} margin={false} onClick={() => void approve()} size="large">
|
||||
{busy ? t.approving : `${t.approvalButton} (${selected.length})`}
|
||||
</Button>
|
||||
<span>{fill(t.approvalSelected, { count: selected.length })} / {pending.length}</span>
|
||||
{blockedReason ? <span role="status">{blockedReason}</span> : null}
|
||||
</div>
|
||||
</>
|
||||
) : (
|
||||
<p>{t.approvalEmpty}</p>
|
||||
)}
|
||||
{done ? (
|
||||
<p role="status">
|
||||
✓ {fill(t.approvalDone, { ...done })} <a href={`${admin}/globals/cookie-settings`}>{t.openCookieBanner}</a>
|
||||
</p>
|
||||
) : null}
|
||||
{gone.length ? (
|
||||
<section data-ipal="approval-gone">
|
||||
<h2>{t.goneTitle} ({gone.length})</h2>
|
||||
<p style={{ marginTop: 0 }}>{t.goneNote}</p>
|
||||
<table>
|
||||
{head(false)}
|
||||
<tbody>{gone.map((p) => row(p, false))}</tbody>
|
||||
</table>
|
||||
</section>
|
||||
) : null}
|
||||
</div>
|
||||
)
|
||||
}
|
||||
|
||||
export default CookieApprovalForm
|
||||
@@ -0,0 +1,77 @@
|
||||
import type { AdminViewServerProps, PayloadRequest } from 'payload'
|
||||
|
||||
import { DefaultTemplate } from '@payloadcms/next/templates'
|
||||
import { Gutter } from '@payloadcms/ui'
|
||||
|
||||
import type { ConsentCategory } from '../categories.js'
|
||||
import type { CookieScanLabels } from './labels.js'
|
||||
|
||||
import { DocumentTitle } from '../../admin-i18n/DocumentTitle.js'
|
||||
import { adminDocumentTitle } from '../../admin-i18n/t.js'
|
||||
import { DEFAULT_UNKNOWN_CATEGORY, loadCookieApproval } from './approval.js'
|
||||
import { COOKIE_REVIEW_SLUG } from './collection.js'
|
||||
import { CookieApprovalForm } from './CookieApprovalForm.js'
|
||||
import { COOKIE_SCAN_LABELS, labelFor } from './labels.js'
|
||||
|
||||
type Props = {
|
||||
adminRoute?: string
|
||||
labels?: Record<string, CookieScanLabels>
|
||||
unknownCategory?: ConsentCategory
|
||||
} & AdminViewServerProps
|
||||
|
||||
/** Whether the user may read the review list — its own `access.read` decides (collectionOverrides narrow it). */
|
||||
async function canReview(req: PayloadRequest): Promise<boolean> {
|
||||
const read = req.payload.collections[COOKIE_REVIEW_SLUG as never]?.config.access?.read
|
||||
if (!read || !req.user) {return false}
|
||||
try {
|
||||
return Boolean(await read({ req } as never))
|
||||
} catch {
|
||||
return false
|
||||
}
|
||||
}
|
||||
|
||||
/**
|
||||
* Admin view at /admin/cookie-approval (`cookieScanner.approval`, on by
|
||||
* default): everything the latest scans found, grouped by consent category,
|
||||
* with one "Approve and add" button. Texts in the content locale that matches
|
||||
* the admin language, else the default locale.
|
||||
*/
|
||||
export async function CookieApprovalView(props: Props) {
|
||||
const { adminRoute = '/admin', initPageResult, labels = COOKIE_SCAN_LABELS, searchParams, unknownCategory = DEFAULT_UNKNOWN_CATEGORY } = props
|
||||
const { req, visibleEntities } = initPageResult
|
||||
const lang = req.i18n.language
|
||||
const t = (key: keyof CookieScanLabels) => labelFor(labels, lang, key)
|
||||
const l = req.payload.config.localization
|
||||
const locale = l ? (l.localeCodes.includes(lang) ? lang : l.defaultLocale) : 'en'
|
||||
|
||||
const allowed = await canReview(req)
|
||||
const list = allowed ? await loadCookieApproval({ locale, payload: req.payload, req }) : null
|
||||
|
||||
return (
|
||||
<DefaultTemplate
|
||||
i18n={req.i18n}
|
||||
locale={initPageResult.locale}
|
||||
params={props.params}
|
||||
payload={req.payload}
|
||||
permissions={initPageResult.permissions}
|
||||
req={req}
|
||||
searchParams={searchParams}
|
||||
user={req.user ?? undefined}
|
||||
visibleEntities={visibleEntities}
|
||||
>
|
||||
<Gutter>
|
||||
<div data-ipal="cookie-approval" style={{ paddingBottom: '3rem' }}>
|
||||
<DocumentTitle title={adminDocumentTitle(t('approvalTitle'), req.payload.config.admin?.meta?.titleSuffix)} />
|
||||
<h1>{t('approvalTitle')}</h1>
|
||||
{list ? (
|
||||
<CookieApprovalForm adminRoute={adminRoute} gone={list.gone} labels={labels} pending={list.pending} unknownCategory={unknownCategory} />
|
||||
) : (
|
||||
<p>{t('approvalNoAccess')}</p>
|
||||
)}
|
||||
</div>
|
||||
</Gutter>
|
||||
</DefaultTemplate>
|
||||
)
|
||||
}
|
||||
|
||||
export default CookieApprovalView
|
||||
@@ -0,0 +1,78 @@
|
||||
'use client'
|
||||
|
||||
import { useConfig, useFormModified, useLocale, useTranslation } from '@payloadcms/ui'
|
||||
import { useCallback, useEffect, useState } from 'react'
|
||||
|
||||
import type { ConsentCategory } from '../categories.js'
|
||||
import type { CookieApprovalList } from './approval.js'
|
||||
import type { CookieScanLabels } from './labels.js'
|
||||
|
||||
import { CookieApprovalForm } from './CookieApprovalForm.js'
|
||||
import { CookieScanButton } from './CookieScanButton.js'
|
||||
import { COOKIE_SCAN_LABELS } from './labels.js'
|
||||
|
||||
/**
|
||||
* "Review and approve" tab of the Cookies global (`ui` field, combined admin
|
||||
* layout): the scan box, the approval list inline, and a link to the review
|
||||
* entries one by one. Approving writes the cookie list on this same screen, so
|
||||
* the page reloads afterwards — and approving waits while the form has
|
||||
* unsaved changes, which a reload would lose.
|
||||
*/
|
||||
export function CookieReviewTab({
|
||||
approval = true,
|
||||
labels = COOKIE_SCAN_LABELS,
|
||||
unknownCategory = 'marketing',
|
||||
}: {
|
||||
approval?: boolean
|
||||
labels?: Record<string, CookieScanLabels>
|
||||
unknownCategory?: ConsentCategory
|
||||
}) {
|
||||
const { i18n } = useTranslation()
|
||||
const { config } = useConfig()
|
||||
const { code: locale } = useLocale()
|
||||
const modified = useFormModified()
|
||||
const t = labels[i18n.language] ?? labels.en ?? COOKIE_SCAN_LABELS.en
|
||||
const admin = (config.routes?.admin ?? '/admin').replace(/\/$/, '')
|
||||
const endpoint = `${config.serverURL ?? ''}${config.routes?.api ?? '/api'}/ipal/cookie-approval?locale=${encodeURIComponent(locale ?? '')}`
|
||||
const [list, setList] = useState<CookieApprovalList | null>(null)
|
||||
const [reloading, setReloading] = useState(false)
|
||||
|
||||
const load = useCallback(() => {
|
||||
if (!approval) {return}
|
||||
fetch(endpoint, { credentials: 'include' })
|
||||
.then((r) => (r.ok ? r.json() : null))
|
||||
.then((data: CookieApprovalList | null) => setList(data ? { gone: data.gone ?? [], pending: data.pending ?? [] } : { gone: [], pending: [] }))
|
||||
.catch(() => setList({ gone: [], pending: [] }))
|
||||
}, [approval, endpoint])
|
||||
useEffect(load, [load])
|
||||
|
||||
return (
|
||||
<div data-ipal="cookies-review-tab" style={{ marginTop: '1rem' }}>
|
||||
<CookieScanButton approval={false} labels={labels} onChange={load} />
|
||||
{approval ? (
|
||||
list ? (
|
||||
<CookieApprovalForm
|
||||
adminRoute={admin}
|
||||
blockedReason={reloading ? t.reloading : modified ? t.saveFirst : null}
|
||||
gone={list.gone}
|
||||
labels={labels}
|
||||
onApproved={() => {
|
||||
// The cookie list in this form is now out of date: load the saved one.
|
||||
setReloading(true)
|
||||
setTimeout(() => window.location.reload(), 1200)
|
||||
}}
|
||||
pending={list.pending}
|
||||
unknownCategory={unknownCategory}
|
||||
/>
|
||||
) : (
|
||||
<p>{t.loadingList}</p>
|
||||
)
|
||||
) : null}
|
||||
<p style={{ marginTop: '1.5rem' }}>
|
||||
<a href={`${admin}/collections/cookie-review`}>{t.openReviewList}</a>
|
||||
</p>
|
||||
</div>
|
||||
)
|
||||
}
|
||||
|
||||
export default CookieReviewTab
|
||||
@@ -2,7 +2,7 @@
|
||||
|
||||
import { Button, useConfig, useTranslation } from '@payloadcms/ui'
|
||||
import { useRouter } from 'next/navigation.js'
|
||||
import { useEffect, useState } from 'react'
|
||||
import { useCallback, useEffect, useState } from 'react'
|
||||
|
||||
import type { CookieScanLabels } from './labels.js'
|
||||
import type { CookieScanSummary } from './types.js'
|
||||
@@ -37,7 +37,22 @@ const fill = (template: string, values: Record<string, null | number | string>)
|
||||
* while it runs. Labels in the admin language (`labels` from the collection
|
||||
* config, English fallback).
|
||||
*/
|
||||
export function CookieScanButton({ crawl = false, labels = COOKIE_SCAN_LABELS }: { crawl?: boolean; labels?: Record<string, CookieScanLabels> }) {
|
||||
export function CookieScanButton({
|
||||
approval = false,
|
||||
crawl = false,
|
||||
labels = COOKIE_SCAN_LABELS,
|
||||
onChange,
|
||||
scan: showScan = true,
|
||||
}: {
|
||||
/** Cookie approval is on: show how many cookies wait and link to the approval view. */
|
||||
approval?: boolean
|
||||
crawl?: boolean
|
||||
labels?: Record<string, CookieScanLabels>
|
||||
/** Called after a scan or a finished site check (the Cookies tabs reload their lists). */
|
||||
onChange?: () => void
|
||||
/** Show the "Scan cookies" part. Default true; the Site check tab shows only the crawl. */
|
||||
scan?: boolean
|
||||
}) {
|
||||
const { i18n } = useTranslation()
|
||||
const { config } = useConfig()
|
||||
const router = useRouter()
|
||||
@@ -49,6 +64,17 @@ export function CookieScanButton({ crawl = false, labels = COOKIE_SCAN_LABELS }:
|
||||
const [crawlState, setCrawlState] = useState<CrawlState | null>(null)
|
||||
const [crawlStarting, setCrawlStarting] = useState(false)
|
||||
const crawlEndpoint = endpoint.replace(/cookie-scan$/, 'cookie-crawl')
|
||||
const approvalEndpoint = endpoint.replace(/cookie-scan$/, 'cookie-approval')
|
||||
const approvalView = `${(config.routes?.admin ?? '/admin').replace(/\/$/, '')}/cookie-approval`
|
||||
const [pending, setPending] = useState<null | number>(null)
|
||||
const refreshPending = useCallback(() => {
|
||||
if (!approval) {return}
|
||||
fetch(approvalEndpoint, { credentials: 'include' })
|
||||
.then((r) => (r.ok ? r.json() : null))
|
||||
.then((data: { pending?: unknown[] } | null) => setPending(data?.pending?.length ?? null))
|
||||
.catch(() => setPending(null))
|
||||
}, [approval, approvalEndpoint])
|
||||
useEffect(refreshPending, [refreshPending])
|
||||
const when = (iso: null | string) => (iso ? formatDateTime(iso, i18n.language) : '')
|
||||
|
||||
useEffect(() => {
|
||||
@@ -61,7 +87,11 @@ export function CookieScanButton({ crawl = false, labels = COOKIE_SCAN_LABELS }:
|
||||
const data = res.ok ? ((await res.json()) as CrawlState) : null
|
||||
if (stopped || !data) {return}
|
||||
setCrawlState(data)
|
||||
if (wasRunning && data.status !== 'running') {router.refresh()}
|
||||
if (wasRunning && data.status !== 'running') {
|
||||
router.refresh()
|
||||
refreshPending()
|
||||
onChange?.()
|
||||
}
|
||||
wasRunning = data.status === 'running'
|
||||
} catch {
|
||||
// offline — try again on the next tick
|
||||
@@ -73,7 +103,7 @@ export function CookieScanButton({ crawl = false, labels = COOKIE_SCAN_LABELS }:
|
||||
stopped = true
|
||||
clearInterval(timer)
|
||||
}
|
||||
}, [crawl, crawlEndpoint, router])
|
||||
}, [crawl, crawlEndpoint, onChange, refreshPending, router])
|
||||
|
||||
const startCrawl = async () => {
|
||||
setCrawlStarting(true)
|
||||
@@ -106,6 +136,8 @@ export function CookieScanButton({ crawl = false, labels = COOKIE_SCAN_LABELS }:
|
||||
if (!res.ok || !data.ok || !data.summary) {throw new Error('scan failed')}
|
||||
setStatus({ kind: 'done', summary: data.summary })
|
||||
router.refresh()
|
||||
refreshPending()
|
||||
onChange?.()
|
||||
} catch {
|
||||
setStatus({ kind: 'error' })
|
||||
}
|
||||
@@ -116,34 +148,46 @@ export function CookieScanButton({ crawl = false, labels = COOKIE_SCAN_LABELS }:
|
||||
|
||||
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>
|
||||
{showScan ? (
|
||||
<>
|
||||
<p style={{ marginTop: 0 }}>{t.scanIntro}</p>
|
||||
{integrations ? (
|
||||
<p style={{ fontSize: '.85rem', opacity: 0.8 }}>
|
||||
{integrations.length ? `${t.integrationsFound}: ${integrations.map((i) => i.label).join(', ')}` : t.integrationsNone}
|
||||
</p>
|
||||
) : null}
|
||||
<label className="field-label" htmlFor="ipal-cookie-scan-names">{t.namesLabel}</label>
|
||||
<p style={{ fontSize: '.85rem', marginTop: 0, opacity: 0.7 }}>{t.namesHint}</p>
|
||||
<textarea
|
||||
aria-label={t.namesLabel}
|
||||
id="ipal-cookie-scan-names"
|
||||
onChange={(e) => setNames(e.target.value)}
|
||||
placeholder={'_hjSessionUser_123\nintercom-id-abc'}
|
||||
rows={3}
|
||||
style={{ fontFamily: 'monospace', marginBottom: '.5rem', width: '100%' }}
|
||||
value={names}
|
||||
/>
|
||||
<div style={{ alignItems: 'center', display: 'flex', flexWrap: 'wrap', gap: '1rem' }}>
|
||||
<Button buttonStyle="primary" disabled={status.kind === 'scanning'} margin={false} onClick={() => void scan()} size="medium">
|
||||
{status.kind === 'scanning' ? t.scanning : t.scanButton}
|
||||
</Button>
|
||||
{status.kind === 'done' ? <span role="status">✓ {result(status.summary)}</span> : null}
|
||||
{approval && pending ? (
|
||||
<span data-ipal="cookie-approval-pending">
|
||||
<strong>{fill(t.approvalPending, { count: pending })}</strong>{' '}
|
||||
<Button buttonStyle="primary" el="anchor" margin={false} size="medium" url={approvalView}>
|
||||
{t.approvalLink}
|
||||
</Button>
|
||||
</span>
|
||||
) : null}
|
||||
{status.kind === 'error' ? (
|
||||
<span role="alert" style={{ color: 'var(--theme-error-500, crimson)' }}>✗ {t.scanError}</span>
|
||||
) : null}
|
||||
</div>
|
||||
</>
|
||||
) : null}
|
||||
<label className="field-label" htmlFor="ipal-cookie-scan-names">{t.namesLabel}</label>
|
||||
<p style={{ fontSize: '.85rem', marginTop: 0, opacity: 0.7 }}>{t.namesHint}</p>
|
||||
<textarea
|
||||
aria-label={t.namesLabel}
|
||||
id="ipal-cookie-scan-names"
|
||||
onChange={(e) => setNames(e.target.value)}
|
||||
placeholder={'_hjSessionUser_123\nintercom-id-abc'}
|
||||
rows={3}
|
||||
style={{ fontFamily: 'monospace', marginBottom: '.5rem', width: '100%' }}
|
||||
value={names}
|
||||
/>
|
||||
<div style={{ alignItems: 'center', display: 'flex', flexWrap: 'wrap', gap: '1rem' }}>
|
||||
<Button buttonStyle="primary" disabled={status.kind === 'scanning'} margin={false} onClick={() => void scan()} size="medium">
|
||||
{status.kind === 'scanning' ? t.scanning : t.scanButton}
|
||||
</Button>
|
||||
{status.kind === 'done' ? <span role="status">✓ {result(status.summary)}</span> : null}
|
||||
{status.kind === 'error' ? (
|
||||
<span role="alert" style={{ color: 'var(--theme-error-500, crimson)' }}>✗ {t.scanError}</span>
|
||||
) : null}
|
||||
</div>
|
||||
{crawl ? (
|
||||
<div data-ipal="cookie-crawl" style={{ borderTop: '1px solid var(--theme-elevation-150, #ddd)', marginTop: '1.25rem', paddingTop: '1rem' }}>
|
||||
<div data-ipal="cookie-crawl" style={showScan ? { borderTop: '1px solid var(--theme-elevation-150, #ddd)', marginTop: '1.25rem', paddingTop: '1rem' } : {}}>
|
||||
<p style={{ marginTop: 0 }}>{t.crawlIntro}</p>
|
||||
<div style={{ alignItems: 'center', display: 'flex', flexWrap: 'wrap', gap: '1rem' }}>
|
||||
<Button
|
||||
|
||||
@@ -0,0 +1,70 @@
|
||||
'use client'
|
||||
|
||||
import { useConfig, useTranslation } from '@payloadcms/ui'
|
||||
import { useCallback, useEffect, useState } from 'react'
|
||||
|
||||
import type { CrawlViolation } from './crawl/violations.js'
|
||||
import type { CookieScanLabels } from './labels.js'
|
||||
|
||||
import { CookieScanButton } from './CookieScanButton.js'
|
||||
import { COOKIE_SCAN_LABELS } from './labels.js'
|
||||
|
||||
/**
|
||||
* "Site check" tab of the Cookies global (`ui` field, combined admin layout,
|
||||
* only with `cookieScanner.crawl`): start a check, its status, the violations
|
||||
* of the latest check, and a link to the warning e-mail settings.
|
||||
*/
|
||||
export function CookieSiteCheckTab({ labels = COOKIE_SCAN_LABELS }: { labels?: Record<string, CookieScanLabels> }) {
|
||||
const { i18n } = useTranslation()
|
||||
const { config } = useConfig()
|
||||
const t = labels[i18n.language] ?? labels.en ?? COOKIE_SCAN_LABELS.en
|
||||
const admin = (config.routes?.admin ?? '/admin').replace(/\/$/, '')
|
||||
const endpoint = `${config.serverURL ?? ''}${config.routes?.api ?? '/api'}/globals/cookie-crawl?depth=0`
|
||||
const [violations, setViolations] = useState<CrawlViolation[] | null>(null)
|
||||
|
||||
const load = useCallback(() => {
|
||||
fetch(endpoint, { credentials: 'include' })
|
||||
.then((r) => (r.ok ? r.json() : null))
|
||||
.then((data: { violations?: CrawlViolation[] | null } | null) => setViolations(Array.isArray(data?.violations) ? data.violations : []))
|
||||
.catch(() => setViolations([]))
|
||||
}, [endpoint])
|
||||
useEffect(load, [load])
|
||||
|
||||
const kind = (v: CrawlViolation) => (v.kind === 'request' ? t.request : v.kind === 'cookie' ? t.cookie : v.kind === 'localStorage' ? t.localStorage : t.sessionStorage)
|
||||
|
||||
return (
|
||||
<div data-ipal="cookies-site-check-tab" style={{ marginTop: '1rem' }}>
|
||||
<CookieScanButton crawl labels={labels} onChange={load} scan={false} />
|
||||
<h3 style={{ marginTop: '1.5rem' }}>{t.violationsTitle}</h3>
|
||||
{violations === null ? <p>{t.loadingList}</p> : null}
|
||||
{violations?.length === 0 ? <p>{t.noViolations}</p> : null}
|
||||
{violations?.length ? (
|
||||
<table style={{ borderCollapse: 'collapse', width: '100%' }}>
|
||||
<thead>
|
||||
<tr>
|
||||
<th scope="col" style={{ textAlign: 'left' }}>{t.name}</th>
|
||||
<th scope="col" style={{ textAlign: 'left' }}>{t.kind}</th>
|
||||
<th scope="col" style={{ textAlign: 'left' }}>{t.category}</th>
|
||||
<th scope="col" style={{ textAlign: 'left' }}>{t.pages}</th>
|
||||
</tr>
|
||||
</thead>
|
||||
<tbody>
|
||||
{violations.map((v) => (
|
||||
<tr key={`${v.kind}:${v.name}`}>
|
||||
<td><code>{v.name}</code></td>
|
||||
<td>{kind(v)}</td>
|
||||
<td>{v.category && v.category in t ? t[v.category as keyof CookieScanLabels] : (v.category ?? '')}</td>
|
||||
<td>{v.pages.join(', ')}</td>
|
||||
</tr>
|
||||
))}
|
||||
</tbody>
|
||||
</table>
|
||||
) : null}
|
||||
<p style={{ marginTop: '1.5rem' }}>
|
||||
<a href={`${admin}/globals/cookie-crawl`}>{t.warningEmailsLink}</a>
|
||||
</p>
|
||||
</div>
|
||||
)
|
||||
}
|
||||
|
||||
export default CookieSiteCheckTab
|
||||
@@ -0,0 +1,63 @@
|
||||
import type { Field, GlobalConfig, Tab } from 'payload'
|
||||
|
||||
import type { ConsentCategory } from '../categories.js'
|
||||
import type { CookieScanLabels } from './labels.js'
|
||||
|
||||
import { labelRecord } from './labels.js'
|
||||
|
||||
/**
|
||||
* The combined admin layout (`cookieScanner.adminLayout: 'combined'`, the
|
||||
* default): the Cookies global gets a "Review and approve" tab and — with the
|
||||
* crawl — a "Site check" tab. They are `ui` fields (no data, no schema
|
||||
* change) that render the scanner's admin components; the review list and the
|
||||
* site-check global leave the navigation but keep their pages and API.
|
||||
*/
|
||||
export function addCookieScannerTabs(
|
||||
global: GlobalConfig,
|
||||
{
|
||||
approval,
|
||||
crawl,
|
||||
labels,
|
||||
unknownCategory,
|
||||
}: { approval: boolean; crawl: boolean; labels: Record<string, CookieScanLabels>; unknownCategory?: ConsentCategory },
|
||||
): GlobalConfig {
|
||||
const tabsField = global.fields.find((f): f is { tabs: Tab[] } & Field => f.type === 'tabs')
|
||||
if (!tabsField) {return global} // a project replaced the global's fields — nothing to attach to
|
||||
const tabs: Tab[] = [
|
||||
{
|
||||
fields: [
|
||||
{
|
||||
name: 'ipalCookieReview',
|
||||
type: 'ui',
|
||||
admin: {
|
||||
components: {
|
||||
Field: {
|
||||
clientProps: { approval, labels, ...(unknownCategory ? { unknownCategory } : {}) },
|
||||
path: '@intecion/ipal-kit/admin#CookieReviewTab',
|
||||
},
|
||||
},
|
||||
},
|
||||
},
|
||||
],
|
||||
label: labelRecord(labels, 'tabReview'),
|
||||
},
|
||||
...(crawl
|
||||
? [
|
||||
{
|
||||
fields: [
|
||||
{
|
||||
name: 'ipalCookieSiteCheck',
|
||||
type: 'ui' as const,
|
||||
admin: { components: { Field: { clientProps: { labels }, path: '@intecion/ipal-kit/admin#CookieSiteCheckTab' } } },
|
||||
},
|
||||
],
|
||||
label: labelRecord(labels, 'tabSiteCheck'),
|
||||
},
|
||||
]
|
||||
: []),
|
||||
]
|
||||
return {
|
||||
...global,
|
||||
fields: global.fields.map((f) => (f === tabsField ? { ...tabsField, tabs: [...tabsField.tabs, ...tabs] } : f)),
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,191 @@
|
||||
import type { BasePayload, Endpoint, PayloadRequest, Where } from 'payload'
|
||||
|
||||
import type { ConsentCategory } from '../categories.js'
|
||||
import type { CookieReviewValues } from './merge.js'
|
||||
import type { CookieChange } from './scan.js'
|
||||
import type { CookieScannerOptions } from './types.js'
|
||||
|
||||
import { userMeetsRole } from '../../access/predicates.js'
|
||||
import { CONSENT_CATEGORIES } from '../categories.js'
|
||||
import { COOKIE_REVIEW_SLUG } from './collection.js'
|
||||
import { textFor } from './merge.js'
|
||||
import { addToCookieList } from './sync.js'
|
||||
|
||||
/**
|
||||
* One approval for everything a scan or crawl found: the "Approve cookies" view
|
||||
* lists what is waiting, grouped by consent category, and one button adds the
|
||||
* ticked cookies to Cookies → Cookies — which feeds the cookie banner's
|
||||
* detailed window and the cookie policy table. Nothing is added before that.
|
||||
*/
|
||||
export const COOKIE_APPROVAL_PATH = '/ipal/cookie-approval'
|
||||
/** Admin view path (under the admin route). */
|
||||
export const COOKIE_APPROVAL_VIEW_PATH = '/cookie-approval'
|
||||
/** Category for cookies nothing knows, until an editor describes them. It needs consent. */
|
||||
export const DEFAULT_UNKNOWN_CATEGORY: ConsentCategory = 'marketing'
|
||||
|
||||
export type CookieApprovalItem = {
|
||||
category: ConsentCategory | null
|
||||
change: CookieChange | null
|
||||
id: number | string
|
||||
name: string
|
||||
purpose: null | string
|
||||
retention: null | string
|
||||
/** Nothing knew it: no category or no purpose yet. */
|
||||
unknown: boolean
|
||||
vendor: null | string
|
||||
}
|
||||
|
||||
export type CookieApprovalList = {
|
||||
/** Accepted cookies the latest scan or crawl no longer found — for review only. */
|
||||
gone: CookieApprovalItem[]
|
||||
/** Waiting for approval: drafts, and accepted cookies a scan changed. */
|
||||
pending: CookieApprovalItem[]
|
||||
}
|
||||
|
||||
export type CookieApprovalResult = { added: number; filled: number; needsDescription: number; skipped: number; unchanged: number }
|
||||
|
||||
type Doc = {
|
||||
category?: ConsentCategory | null
|
||||
change?: CookieChange | null
|
||||
id: number | string
|
||||
name: string
|
||||
purpose?: null | Record<string, null | string> | string
|
||||
retention?: null | Record<string, null | string> | string
|
||||
source?: null | string
|
||||
status?: 'accepted' | 'draft' | 'rejected' | null
|
||||
vendor?: null | string
|
||||
}
|
||||
|
||||
/** Pending = a draft, or an accepted cookie whose values a scan changed. */
|
||||
export const PENDING_WHERE: Where = {
|
||||
or: [{ status: { equals: 'draft' } }, { and: [{ status: { equals: 'accepted' } }, { change: { equals: 'changed' } }] }],
|
||||
}
|
||||
|
||||
const asText = (v: Doc['purpose'], locale: string) =>
|
||||
(typeof v === 'string' ? v : v ? (textFor(Object.fromEntries(Object.entries(v).filter(([, t]) => Boolean(t))) as Record<string, string>, locale) ?? null) : null) || null
|
||||
|
||||
function item(doc: Doc, locale: string): CookieApprovalItem {
|
||||
const purpose = asText(doc.purpose, locale)
|
||||
return {
|
||||
id: doc.id,
|
||||
name: doc.name,
|
||||
category: doc.category && (CONSENT_CATEGORIES as readonly string[]).includes(doc.category) ? doc.category : null,
|
||||
change: doc.change ?? null,
|
||||
purpose,
|
||||
retention: asText(doc.retention, locale),
|
||||
unknown: !doc.category || !purpose || doc.source === 'unknown',
|
||||
vendor: doc.vendor ?? null,
|
||||
}
|
||||
}
|
||||
|
||||
/** The approval list in one content locale (texts fall back to English, then any language). */
|
||||
export async function loadCookieApproval({ locale, payload, req }: { locale: string; payload: BasePayload; req?: PayloadRequest }): Promise<CookieApprovalList> {
|
||||
const common = { collection: COOKIE_REVIEW_SLUG as never, depth: 0, limit: 0, locale: 'all' as never, overrideAccess: true, pagination: false, req, sort: 'name' }
|
||||
const [pending, gone] = await Promise.all([
|
||||
payload.find({ ...common, where: PENDING_WHERE }),
|
||||
payload.find({ ...common, where: { and: [{ status: { equals: 'accepted' } }, { change: { equals: 'gone' } }] } }),
|
||||
])
|
||||
return {
|
||||
gone: (gone.docs as unknown as Doc[]).map((d) => item(d, locale)),
|
||||
pending: (pending.docs as unknown as Doc[]).map((d) => item(d, locale)),
|
||||
}
|
||||
}
|
||||
|
||||
/** How many cookies wait for approval (dashboard, e-mail). Never throws. */
|
||||
export async function countPendingCookies(payload: BasePayload): Promise<number> {
|
||||
try {
|
||||
return (await payload.count({ collection: COOKIE_REVIEW_SLUG as never, overrideAccess: true, where: PENDING_WHERE })).totalDocs
|
||||
} catch {
|
||||
return 0
|
||||
}
|
||||
}
|
||||
|
||||
/**
|
||||
* Approves pending entries (all of them, or only `ids`): each becomes accepted
|
||||
* and goes to Cookies → Cookies in every locale — a missing row is added,
|
||||
* an existing one (same name or pattern) only gets its empty text filled, its
|
||||
* category is kept. A cookie without a category gets `unknownCategory` (needs
|
||||
* consent) and every cookie without a purpose is flagged "Needs description".
|
||||
* Never deletes, never adds a second row for the same cookie.
|
||||
*/
|
||||
export async function approveCookies({
|
||||
addToList = true,
|
||||
ids,
|
||||
payload,
|
||||
req,
|
||||
unknownCategory = DEFAULT_UNKNOWN_CATEGORY,
|
||||
}: {
|
||||
/** False (`syncAccepted: false`) = only mark the entries accepted. */
|
||||
addToList?: boolean
|
||||
ids?: (number | string)[]
|
||||
payload: BasePayload
|
||||
req?: PayloadRequest
|
||||
unknownCategory?: ConsentCategory
|
||||
}): Promise<CookieApprovalResult> {
|
||||
const common = { collection: COOKIE_REVIEW_SLUG as never, context: { ipalCookieScan: true }, depth: 0, overrideAccess: true, req }
|
||||
const where: Where = ids ? { and: [PENDING_WHERE, { id: { in: ids } }] } : PENDING_WHERE
|
||||
const { docs } = await payload.find({ ...common, limit: 0, locale: 'all' as never, pagination: false, where })
|
||||
const result: CookieApprovalResult = { added: 0, filled: 0, needsDescription: 0, skipped: (ids?.length ?? docs.length) - docs.length, unchanged: 0 }
|
||||
const defaultLocale = payload.config.localization ? payload.config.localization.defaultLocale : 'en'
|
||||
|
||||
for (const doc of docs as unknown as ({ name: string } & CookieReviewValues & Doc)[]) {
|
||||
const category = doc.category ?? unknownCategory
|
||||
const needsDescription = !asText(doc.purpose, defaultLocale)
|
||||
const outcome = addToList ? await addToCookieList({ entry: { ...doc, category } as never, payload, req }) : 'unchanged'
|
||||
result[outcome]++
|
||||
if (needsDescription) {result.needsDescription++}
|
||||
await payload.update({
|
||||
...common,
|
||||
id: doc.id,
|
||||
data: { category, change: null, listed: true, needsDescription, status: 'accepted' } as never,
|
||||
})
|
||||
}
|
||||
return result
|
||||
}
|
||||
|
||||
/**
|
||||
* GET /api/ipal/cookie-approval?locale=pl → `CookieApprovalList`
|
||||
* POST /api/ipal/cookie-approval, body `{ ids?: (string|number)[] }` → `{ ok, result }`
|
||||
* Editors and up (`cookieScanner.access`).
|
||||
*/
|
||||
export function buildCookieApprovalEndpoints(options: CookieScannerOptions): Endpoint[] {
|
||||
const approval = typeof options.approval === 'object' ? options.approval : {}
|
||||
const allowed = async (req: PayloadRequest) =>
|
||||
options.access ? Boolean(await options.access({ req })) : userMeetsRole(req, 'editor')
|
||||
return [
|
||||
{
|
||||
handler: async (req) => {
|
||||
if (!(await allowed(req))) {return Response.json({ ok: false }, { status: 403 })}
|
||||
const l = req.payload.config.localization
|
||||
const asked = typeof req.query?.locale === 'string' ? req.query.locale : undefined
|
||||
const locale = l ? (asked && l.localeCodes.includes(asked) ? asked : l.defaultLocale) : 'en'
|
||||
return Response.json({ ok: true, ...(await loadCookieApproval({ locale, payload: req.payload, req })) })
|
||||
},
|
||||
method: 'get',
|
||||
path: COOKIE_APPROVAL_PATH,
|
||||
},
|
||||
{
|
||||
handler: async (req) => {
|
||||
if (!(await allowed(req))) {return Response.json({ ok: false }, { status: 403 })}
|
||||
let body: { ids?: unknown } = {}
|
||||
try {
|
||||
body = ((await (req as unknown as Request).json()) ?? {}) as { ids?: unknown }
|
||||
} catch {
|
||||
// no body = approve everything pending
|
||||
}
|
||||
const ids = Array.isArray(body.ids)
|
||||
? body.ids.filter((id): id is number | string => (typeof id === 'string' && id.length <= 64) || Number.isInteger(id)).slice(0, 1000)
|
||||
: undefined
|
||||
try {
|
||||
const result = await approveCookies({ addToList: options.syncAccepted !== false, ids, payload: req.payload, req, unknownCategory: approval.unknownCategory })
|
||||
return Response.json({ ok: true, result })
|
||||
} catch (err) {
|
||||
req.payload.logger.error(`[ipal] cookie approval failed: ${err instanceof Error ? err.message : String(err)}`)
|
||||
return Response.json({ ok: false }, { status: 500 })
|
||||
}
|
||||
},
|
||||
method: 'post',
|
||||
path: COOKIE_APPROVAL_PATH,
|
||||
},
|
||||
]
|
||||
}
|
||||
@@ -23,6 +23,10 @@ const setKey: CollectionBeforeChangeHook = ({ data, originalDoc }) => {
|
||||
data.name = name
|
||||
data.key = `${storage}:${name}`
|
||||
}
|
||||
// An editor who writes the purpose has described the cookie.
|
||||
if (typeof data.purpose === 'string' && data.purpose.trim() && (data.needsDescription ?? originalDoc?.needsDescription)) {
|
||||
data.needsDescription = false
|
||||
}
|
||||
return data
|
||||
}
|
||||
|
||||
@@ -91,9 +95,9 @@ export function buildCookieReviewCollection(options: CookieScannerOptions = {}):
|
||||
},
|
||||
admin: {
|
||||
components: {
|
||||
beforeListTable: [{ clientProps: { crawl, labels }, path: '@intecion/ipal-kit/admin#CookieScanButton' }],
|
||||
beforeListTable: [{ clientProps: { approval: options.approval !== false, crawl, labels }, path: '@intecion/ipal-kit/admin#CookieScanButton' }],
|
||||
},
|
||||
defaultColumns: ['name', 'vendor', 'category', 'status', 'source', 'listed', ...(crawl ? ['violation'] : [])],
|
||||
defaultColumns: ['name', 'vendor', 'category', 'status', 'change', 'listed', ...(crawl ? ['violation'] : [])],
|
||||
description: L('collectionDescription'),
|
||||
group: { en: 'Privacy', pl: 'Prywatność' },
|
||||
listSearchableFields: ['name', 'vendor'],
|
||||
@@ -178,6 +182,25 @@ export function buildCookieReviewCollection(options: CookieScannerOptions = {}):
|
||||
admin: { description: L('listedDescription'), position: 'sidebar', readOnly: true },
|
||||
label: L('listed'),
|
||||
},
|
||||
{
|
||||
name: 'change',
|
||||
type: 'select',
|
||||
admin: { description: L('changeDescription'), position: 'sidebar', readOnly: true },
|
||||
index: true,
|
||||
label: L('change'),
|
||||
options: [
|
||||
{ label: L('changeNew'), value: 'new' },
|
||||
{ label: L('changeChanged'), value: 'changed' },
|
||||
{ label: L('changeGone'), value: 'gone' },
|
||||
],
|
||||
},
|
||||
{
|
||||
name: 'needsDescription',
|
||||
type: 'checkbox',
|
||||
admin: { description: L('needsDescriptionDescription'), position: 'sidebar' },
|
||||
defaultValue: false,
|
||||
label: L('needsDescription'),
|
||||
},
|
||||
{ name: 'lastScannedAt', type: 'date', admin: { position: 'sidebar', readOnly: true }, label: L('lastScannedAt') },
|
||||
...crawlFields,
|
||||
// `storage:name`, one entry per cookie — what a rescan matches on.
|
||||
|
||||
@@ -2,41 +2,53 @@ import type { Payload } from 'payload'
|
||||
|
||||
import type { CookieScanLabels } from '../labels.js'
|
||||
|
||||
import { COOKIE_APPROVAL_VIEW_PATH, countPendingCookies } from '../approval.js'
|
||||
import { COOKIE_REVIEW_SLUG } from '../collection.js'
|
||||
import { COOKIE_SCAN_LABELS, labelFor } from '../labels.js'
|
||||
import { COOKIE_CRAWL_SLUG } from './config.js'
|
||||
|
||||
type Props = {
|
||||
adminRoute?: string
|
||||
/** Cookie approval is on: remind while cookies wait, link to the approval view. Default true. */
|
||||
approval?: boolean
|
||||
/** The browser crawl is on: report violations and failed crawls. Default true. */
|
||||
crawl?: boolean
|
||||
/** Injected by Payload into admin server components. */
|
||||
i18n?: { language?: string }
|
||||
labels?: Record<string, CookieScanLabels>
|
||||
payload?: Payload
|
||||
}
|
||||
|
||||
type CrawlDoc = { error?: null | string; status?: null | string; summary?: { newUnknown?: null | number; violations?: null | number } | null }
|
||||
|
||||
const fill = (template: string, values: Record<string, number | string>) =>
|
||||
template.replace(/\{(\w+)\}/g, (_, k: string) => String(values[k] ?? ''))
|
||||
|
||||
/**
|
||||
* Dashboard warning (beforeDashboard) after the latest cookie crawl found
|
||||
* violations or new unknown cookies, or failed. Renders nothing otherwise and
|
||||
* never throws.
|
||||
* Dashboard warning (beforeDashboard): cookies waiting for approval (with a
|
||||
* link to the approval view), and — with the crawl — violations or a failed
|
||||
* crawl. Renders nothing when nothing needs attention, and never throws.
|
||||
*/
|
||||
export async function CookieCrawlAlert({ adminRoute = '/admin', i18n, labels = COOKIE_SCAN_LABELS, payload }: Props) {
|
||||
export async function CookieCrawlAlert({ adminRoute = '/admin', approval = true, crawl = true, i18n, labels = COOKIE_SCAN_LABELS, payload }: Props) {
|
||||
if (!payload) {return null}
|
||||
let doc: { error?: null | string; status?: null | string; summary?: { newUnknown?: null | number; violations?: null | number } | null }
|
||||
try {
|
||||
doc = (await payload.findGlobal({ slug: COOKIE_CRAWL_SLUG as never, depth: 0 })) as typeof doc
|
||||
} catch {
|
||||
return null
|
||||
let doc: CrawlDoc = {}
|
||||
if (crawl) {
|
||||
try {
|
||||
doc = (await payload.findGlobal({ slug: COOKIE_CRAWL_SLUG as never, depth: 0 })) as CrawlDoc
|
||||
} catch {
|
||||
doc = {}
|
||||
}
|
||||
}
|
||||
const pending = approval ? await countPendingCookies(payload) : 0
|
||||
const t = (key: keyof CookieScanLabels) => labelFor(labels, i18n?.language, key)
|
||||
const violations = doc.summary?.violations ?? 0
|
||||
const newUnknown = doc.summary?.newUnknown ?? 0
|
||||
const failed = doc.status === 'failed'
|
||||
if (!failed && !(doc.status === 'done' && (violations || newUnknown))) {return null}
|
||||
const base = `${adminRoute.replace(/\/$/, '')}/collections/${COOKIE_REVIEW_SLUG}`
|
||||
const href = violations ? `${base}?where[violation][equals]=true` : base
|
||||
// Without approval, new unknown cookies are the reason to look; with it, the pending count says so.
|
||||
const findings = doc.status === 'done' && (violations > 0 || (!approval && newUnknown > 0))
|
||||
if (!failed && !findings && !pending) {return null}
|
||||
const admin = adminRoute.replace(/\/$/, '')
|
||||
const review = `${admin}/collections/${COOKIE_REVIEW_SLUG}`
|
||||
|
||||
return (
|
||||
<div
|
||||
@@ -50,17 +62,27 @@ export async function CookieCrawlAlert({ adminRoute = '/admin', i18n, labels = C
|
||||
padding: '1rem 1.25rem',
|
||||
}}
|
||||
>
|
||||
{failed ? (
|
||||
<strong>{fill(t('alertFailed'), { error: doc.error ?? '' })}</strong>
|
||||
) : (
|
||||
{failed ? <p style={{ margin: 0 }}><strong>{fill(t('alertFailed'), { error: doc.error ?? '' })}</strong></p> : null}
|
||||
{findings ? (
|
||||
<>
|
||||
<strong>{fill(t('alertTitle'), { newUnknown, violations })}</strong>
|
||||
<p style={{ margin: 0 }}><strong>{fill(t('alertTitle'), { newUnknown, violations })}</strong></p>
|
||||
<p style={{ margin: '0.5rem 0 0' }}>{t('alertBody')}</p>
|
||||
<a href={violations ? `${review}?where[violation][equals]=true` : review} style={{ display: 'block', marginTop: '0.5rem' }}>
|
||||
{t('alertLink')}
|
||||
</a>
|
||||
</>
|
||||
)}
|
||||
<a href={href} style={{ display: 'block', marginTop: '0.5rem' }}>
|
||||
{t('alertLink')}
|
||||
</a>
|
||||
) : null}
|
||||
{pending ? (
|
||||
<p style={{ margin: failed || findings ? '0.75rem 0 0' : 0 }}>
|
||||
<strong>{fill(t('approvalPending'), { count: pending })}</strong>{' '}
|
||||
<a href={`${admin}${COOKIE_APPROVAL_VIEW_PATH}`}>{t('approvalLink')}</a>
|
||||
</p>
|
||||
) : null}
|
||||
{failed && !findings && !pending ? (
|
||||
<a href={review} style={{ display: 'block', marginTop: '0.5rem' }}>
|
||||
{t('alertLink')}
|
||||
</a>
|
||||
) : null}
|
||||
</div>
|
||||
)
|
||||
}
|
||||
|
||||
@@ -150,7 +150,7 @@ export function buildCookieCrawlEndpoints({
|
||||
const summary = result.ok
|
||||
? await ingestCrawlResult({ config, labels, options, payload: req.payload, plugin, req, result })
|
||||
: undefined
|
||||
await finishCrawl({ labels, payload: req.payload, req, result, siteUrl: config.siteUrl, summary })
|
||||
await finishCrawl({ approval: options.approval !== false, labels, payload: req.payload, req, result, siteUrl: config.siteUrl, summary })
|
||||
return Response.json({ ok: true })
|
||||
} catch (err) {
|
||||
const message = err instanceof Error ? err.message : String(err)
|
||||
|
||||
@@ -7,10 +7,11 @@ import type { ResolvedCrawlConfig } from './config.js'
|
||||
import type { CrawlResult } from './result.js'
|
||||
import type { CrawlViolation } from './violations.js'
|
||||
|
||||
import { countPendingCookies } from '../approval.js'
|
||||
import { COOKIE_REVIEW_SLUG } from '../collection.js'
|
||||
import { DEFAULT_COOKIE_INTEGRATIONS } from '../integrations.js'
|
||||
import { labelFor } from '../labels.js'
|
||||
import { applyCookieFindings, collectCookieFindings, cookieScanContext } from '../scan.js'
|
||||
import { applyCookieFindings, collectCookieFindings, cookieScanContext, flagGoneEntries } from '../scan.js'
|
||||
import { COOKIE_CRAWL_SLUG } from './config.js'
|
||||
import { sendCrawlWarning } from './notify.js'
|
||||
import { findCrawlViolations } from './violations.js'
|
||||
@@ -71,6 +72,13 @@ export async function ingestCrawlResult({
|
||||
payload,
|
||||
req,
|
||||
})
|
||||
// Accepted cookies the browser no longer saw (and nothing still declares) are flagged for review, never deleted.
|
||||
summary.gone = await flagGoneEntries({
|
||||
keep: new Set([...(seenKeys as Set<string>), ...findings.filter((f) => f.source === 'integration' || f.source === 'project').map((f) => `${f.storage}:${f.name}`)]),
|
||||
payload,
|
||||
req,
|
||||
where: { status: { equals: 'accepted' } },
|
||||
})
|
||||
|
||||
const keyOf = (o: { name: string; storage: string }) => matches.get(`${o.storage}:${o.name}`)
|
||||
const violations = findCrawlViolations({
|
||||
@@ -108,6 +116,7 @@ export async function ingestCrawlResult({
|
||||
|
||||
/** Writes the finished crawl into the `cookie-crawl` global and sends the e-mail warning when asked for. */
|
||||
export async function finishCrawl({
|
||||
approval = true,
|
||||
labels,
|
||||
payload,
|
||||
req,
|
||||
@@ -115,6 +124,8 @@ export async function finishCrawl({
|
||||
siteUrl,
|
||||
summary,
|
||||
}: {
|
||||
/** Cookie approval is on: the e-mail says how many cookies wait and links to the approval view. */
|
||||
approval?: boolean
|
||||
labels: Record<string, CookieScanLabels>
|
||||
payload: BasePayload
|
||||
req?: PayloadRequest
|
||||
@@ -150,7 +161,9 @@ export async function finishCrawl({
|
||||
})) as { notifyEmails?: null | string }
|
||||
|
||||
const to = (doc.notifyEmails ?? '').split(',').map((v) => v.trim()).filter(Boolean)
|
||||
if (to.length && (summary.violations.length || summary.newUnknown)) {
|
||||
await sendCrawlWarning({ labels, payload, siteUrl: siteUrl ?? '', summary, to })
|
||||
// Something new waits for approval, or something breaks the rules: say so. Nothing is added by itself.
|
||||
const pending = approval ? await countPendingCookies(payload) : 0
|
||||
if (to.length && (summary.violations.length || summary.newUnknown || (approval && summary.created && pending))) {
|
||||
await sendCrawlWarning({ labels, payload, pending, siteUrl: siteUrl ?? '', summary, to })
|
||||
}
|
||||
}
|
||||
|
||||
@@ -3,6 +3,7 @@ import type { BasePayload } from 'payload'
|
||||
import type { CookieScanLabels } from '../labels.js'
|
||||
import type { CrawlIngestSummary } from './ingest.js'
|
||||
|
||||
import { COOKIE_APPROVAL_VIEW_PATH } from '../approval.js'
|
||||
import { COOKIE_REVIEW_SLUG } from '../collection.js'
|
||||
import { labelFor } from '../labels.js'
|
||||
|
||||
@@ -18,12 +19,15 @@ const fill = (template: string, values: Record<string, number | string>) =>
|
||||
export async function sendCrawlWarning({
|
||||
labels,
|
||||
payload,
|
||||
pending = 0,
|
||||
siteUrl,
|
||||
summary,
|
||||
to,
|
||||
}: {
|
||||
labels: Record<string, CookieScanLabels>
|
||||
payload: BasePayload
|
||||
/** Cookies waiting for approval — the e-mail says so and links to the approval view. */
|
||||
pending?: number
|
||||
siteUrl: string
|
||||
summary: CrawlIngestSummary
|
||||
to: string[]
|
||||
@@ -32,18 +36,21 @@ export async function sendCrawlWarning({
|
||||
const t = (key: keyof CookieScanLabels) => labelFor(labels, lang, key)
|
||||
const site = siteUrl.replace(/^https?:\/\//, '') || 'site'
|
||||
const values = { newUnknown: summary.newUnknown, site, violations: summary.violations.length }
|
||||
const adminUrl = `${siteUrl}${payload.config.routes?.admin ?? '/admin'}/collections/${COOKIE_REVIEW_SLUG}`
|
||||
const admin = `${siteUrl}${payload.config.routes?.admin ?? '/admin'}`
|
||||
const adminUrl = `${admin}/collections/${COOKIE_REVIEW_SLUG}`
|
||||
const items = summary.violations
|
||||
.slice(0, 30)
|
||||
.map((v) => `<li><code>${esc(v.name)}</code> (${esc(v.kind)}${v.category ? `, ${esc(v.category)}` : ''}) — ${esc(fill(t('beforeConsentOn'), { pages: v.pages.join(', ') }))}</li>`)
|
||||
.join('')
|
||||
const problems = summary.violations.length > 0 || summary.newUnknown > 0
|
||||
const html = `<p>${esc(fill(t('emailIntro'), values))}</p>
|
||||
<p><strong>${esc(fill(t('alertTitle'), values))}</strong></p>
|
||||
${problems ? `<p><strong>${esc(fill(t('alertTitle'), values))}</strong></p>` : ''}
|
||||
${items ? `<ul>${items}</ul>` : ''}
|
||||
<p>${esc(t('alertBody'))}</p>
|
||||
<p><a href="${esc(adminUrl)}">${esc(t('alertLink'))}</a></p>`
|
||||
${problems ? `<p>${esc(t('alertBody'))}</p>\n<p><a href="${esc(adminUrl)}">${esc(t('alertLink'))}</a></p>` : ''}
|
||||
${pending ? `<p><strong>${esc(fill(t('emailPending'), { count: pending }))}</strong></p>\n<p><a href="${esc(`${admin}${COOKIE_APPROVAL_VIEW_PATH}`)}">${esc(t('approvalLink'))}</a></p>` : ''}`
|
||||
try {
|
||||
await payload.sendEmail({ html, subject: fill(t('emailSubject'), values), to })
|
||||
const subject = problems || !pending ? fill(t('emailSubject'), values) : fill(t('emailSubjectPending'), { count: pending, site })
|
||||
await payload.sendEmail({ html, subject, to })
|
||||
return true
|
||||
} catch (err) {
|
||||
payload.logger.error(`[ipal] cookie crawl warning e-mail failed: ${err instanceof Error ? err.message : String(err)}`)
|
||||
|
||||
@@ -1,4 +1,16 @@
|
||||
// Cookie scanner — server-safe building blocks. The admin button is in /admin.
|
||||
export { addCookieScannerTabs } from './adminTabs.js'
|
||||
export {
|
||||
approveCookies,
|
||||
buildCookieApprovalEndpoints,
|
||||
COOKIE_APPROVAL_PATH,
|
||||
COOKIE_APPROVAL_VIEW_PATH,
|
||||
countPendingCookies,
|
||||
DEFAULT_UNKNOWN_CATEGORY,
|
||||
loadCookieApproval,
|
||||
PENDING_WHERE,
|
||||
} from './approval.js'
|
||||
export type { CookieApprovalItem, CookieApprovalList, CookieApprovalResult } from './approval.js'
|
||||
export { buildCookieReviewCollection, COOKIE_REVIEW_SLUG } from './collection.js'
|
||||
export { DEFAULT_DATABASE_CATEGORIES, indexCookieDatabase, loadCookieDatabase, lookupCookie } from './cookieDatabase.js'
|
||||
export type { CookieDatabaseIndex } from './cookieDatabase.js'
|
||||
@@ -26,10 +38,11 @@ export { COOKIE_SCAN_LABELS, mergeCookieScanLabels } from './labels.js'
|
||||
export type { CookieScanLabels } from './labels.js'
|
||||
export { mergeCookieReview, suggestionFor } from './merge.js'
|
||||
export type { CookieReviewValues } from './merge.js'
|
||||
export { applyCookieFindings, collectCookieFindings, cookieScanContext, parseCookieNames, runCookieScan } from './scan.js'
|
||||
export type { CookieObservation, CookieReviewEntryRef } from './scan.js'
|
||||
export { addToCookieList } from './sync.js'
|
||||
export { applyCookieFindings, collectCookieFindings, cookieScanContext, flagGoneEntries, nextChange, parseCookieNames, runCookieScan } from './scan.js'
|
||||
export type { CookieChange, CookieObservation, CookieReviewEntryRef } from './scan.js'
|
||||
export { addToCookieList, sameCookie } from './sync.js'
|
||||
export type {
|
||||
CookieApprovalOptions,
|
||||
CookieCrawlOptions,
|
||||
CookieDeclaration,
|
||||
CookieFinding,
|
||||
|
||||
@@ -10,9 +10,25 @@ export type CookieScanLabels = {
|
||||
alertLink: string
|
||||
alertTitle: string
|
||||
analytics: string
|
||||
approvalButton: string
|
||||
approvalDone: string
|
||||
approvalEmpty: string
|
||||
approvalError: string
|
||||
approvalIntro: string
|
||||
approvalLink: string
|
||||
approvalNoAccess: string
|
||||
approvalPending: string
|
||||
approvalSelected: string
|
||||
approvalTitle: string
|
||||
approving: string
|
||||
beforeConsentOn: string
|
||||
category: string
|
||||
categoryRequired: string
|
||||
change: string
|
||||
changeChanged: string
|
||||
changeDescription: string
|
||||
changeGone: string
|
||||
changeNew: string
|
||||
collectionDescription: string
|
||||
cookie: string
|
||||
crawlButton: string
|
||||
@@ -38,31 +54,51 @@ export type CookieScanLabels = {
|
||||
database: string
|
||||
domain: string
|
||||
draft: string
|
||||
edit: string
|
||||
emailIntro: string
|
||||
emailPending: string
|
||||
emailSubject: string
|
||||
emailSubjectPending: string
|
||||
finishedAt: string
|
||||
functional: string
|
||||
goneNote: string
|
||||
goneTitle: string
|
||||
include: string
|
||||
integration: string
|
||||
integrationsFound: string
|
||||
integrationsNone: string
|
||||
kind: string
|
||||
lastScannedAt: string
|
||||
listed: string
|
||||
listedDescription: string
|
||||
loadingList: string
|
||||
localStorage: string
|
||||
manual: string
|
||||
markerChanged: string
|
||||
markerNew: string
|
||||
markerUnknown: string
|
||||
marketing: string
|
||||
name: string
|
||||
namesHint: string
|
||||
namesLabel: string
|
||||
necessary: string
|
||||
needsDescription: string
|
||||
needsDescriptionDescription: string
|
||||
notifyEmails: string
|
||||
notifyEmailsDescription: string
|
||||
notifyEmailsInvalid: string
|
||||
noViolations: string
|
||||
openCookieBanner: string
|
||||
openReviewList: string
|
||||
pages: string
|
||||
plural: string
|
||||
project: string
|
||||
purpose: string
|
||||
rejected: string
|
||||
reloading: string
|
||||
request: string
|
||||
retention: string
|
||||
saveFirst: string
|
||||
scanButton: string
|
||||
scanError: string
|
||||
scanIntro: string
|
||||
@@ -81,11 +117,17 @@ export type CookieScanLabels = {
|
||||
status: string
|
||||
statusDescription: string
|
||||
storage: string
|
||||
tabReview: string
|
||||
tabSiteCheck: string
|
||||
uncategorized: string
|
||||
uncategorizedNote: string
|
||||
unknown: string
|
||||
vendor: string
|
||||
violation: string
|
||||
violationDescription: string
|
||||
violationDetail: string
|
||||
violationsTitle: string
|
||||
warningEmailsLink: string
|
||||
}
|
||||
|
||||
export const COOKIE_SCAN_LABELS: Record<'en' | 'pl', CookieScanLabels> = {
|
||||
@@ -97,10 +139,26 @@ export const COOKIE_SCAN_LABELS: Record<'en' | 'pl', CookieScanLabels> = {
|
||||
alertLink: 'Open cookie review',
|
||||
alertTitle: 'Cookie check: violations: {violations}, new unknown cookies: {newUnknown}.',
|
||||
analytics: 'Analytics',
|
||||
approvalButton: 'Approve and add',
|
||||
approvalDone: 'Added: {added}, completed: {filled}, need a description: {needsDescription}.',
|
||||
approvalEmpty: 'Nothing is waiting for approval. Scan cookies to look for new ones.',
|
||||
approvalError: 'Approval failed. Please try again.',
|
||||
approvalIntro: 'Check the cookies found, untick any you do not want, then add them to the cookie banner and the cookie policy.',
|
||||
approvalLink: 'Review and approve',
|
||||
approvalNoAccess: 'You cannot approve cookies. Ask your administrator.',
|
||||
approvalPending: 'Waiting for approval: {count}.',
|
||||
approvalSelected: 'Selected: {count}',
|
||||
approvalTitle: 'Approve cookies',
|
||||
approving: 'Adding…',
|
||||
beforeConsentOn: 'before consent on {pages}',
|
||||
category: 'Category',
|
||||
categoryRequired: 'Choose a category before accepting.',
|
||||
collectionDescription: 'Accept a cookie to add it to the cookie list; a new scan never overwrites your edits.',
|
||||
change: 'Latest scan',
|
||||
changeChanged: 'Changed',
|
||||
changeDescription: 'What the latest scan found; approving clears it.',
|
||||
changeGone: 'No longer found',
|
||||
changeNew: 'New',
|
||||
collectionDescription: 'Cookies found by scans; approve them to add them to the cookie banner, your edits are kept.',
|
||||
cookie: 'Cookie',
|
||||
crawlButton: 'Check site',
|
||||
crawlCreated: 'New drafts',
|
||||
@@ -125,33 +183,53 @@ export const COOKIE_SCAN_LABELS: Record<'en' | 'pl', CookieScanLabels> = {
|
||||
database: 'Open Cookie Database',
|
||||
domain: 'Domain',
|
||||
draft: 'Draft',
|
||||
edit: 'Edit',
|
||||
emailIntro: 'The latest cookie check of {site} found:',
|
||||
emailPending: 'Cookies waiting for approval: {count}. Nothing is added to the cookie banner until you approve them.',
|
||||
emailSubject: 'Cookie check of {site}: violations: {violations}, new unknown cookies: {newUnknown}',
|
||||
emailSubjectPending: 'Cookie check of {site}: cookies waiting for approval: {count}',
|
||||
finishedAt: 'Finished',
|
||||
functional: 'Functional',
|
||||
goneNote: 'They stay in the cookie banner; remove them there if the site no longer uses them.',
|
||||
goneTitle: 'No longer found',
|
||||
include: 'Include',
|
||||
integration: 'Built-in integration',
|
||||
integrationsFound: 'Integrations in use',
|
||||
integrationsNone: 'No integration that uses cookies is on.',
|
||||
kind: 'Type',
|
||||
lastScannedAt: 'Last found',
|
||||
listed: 'In cookie list',
|
||||
listedDescription: 'Already in the cookie list of the cookie banner.',
|
||||
loadingList: 'Loading…',
|
||||
localStorage: 'Local storage',
|
||||
manual: 'Added by hand',
|
||||
markerChanged: 'Changed',
|
||||
markerNew: 'New',
|
||||
markerUnknown: 'Needs description',
|
||||
marketing: 'Marketing',
|
||||
namesHint: 'Optional. Other cookie names, one per line. They are looked up in the Open Cookie Database.',
|
||||
namesLabel: 'More cookie names',
|
||||
necessary: 'Necessary',
|
||||
needsDescription: 'Needs description',
|
||||
needsDescriptionDescription: 'Write the purpose so visitors know what this cookie does.',
|
||||
notifyEmails: 'Warning e-mails to',
|
||||
notifyEmailsDescription: 'Comma-separated addresses that get a warning when a check finds problems; leave empty for none.',
|
||||
notifyEmailsInvalid: 'Enter e-mail addresses separated by commas, e.g. [email protected], [email protected].',
|
||||
noViolations: 'No violations in the latest check.',
|
||||
openCookieBanner: 'Open cookie banner',
|
||||
openReviewList: 'Edit cookies one by one',
|
||||
pages: 'Pages',
|
||||
plural: 'Cookie review',
|
||||
project: 'Site configuration',
|
||||
purpose: 'Purpose',
|
||||
rejected: 'Rejected',
|
||||
reloading: 'Added. Reloading the cookie list…',
|
||||
request: 'Request',
|
||||
retention: 'Duration',
|
||||
saveFirst: 'Save your changes first.',
|
||||
scanButton: 'Scan cookies',
|
||||
scanError: 'The scan failed. Please try again.',
|
||||
scanIntro: 'Adds the cookies of the integrations in use as drafts to review.',
|
||||
scanIntro: 'Finds the cookies of the integrations in use; nothing is added to the cookie banner until you approve.',
|
||||
scanning: 'Scanning…',
|
||||
scanResult: 'New: {created}, updated: {updated}, unchanged: {unchanged}, unknown: {unknown}.',
|
||||
seenBeforeConsent: 'Seen before consent',
|
||||
@@ -166,11 +244,17 @@ export const COOKIE_SCAN_LABELS: Record<'en' | 'pl', CookieScanLabels> = {
|
||||
status: 'Status',
|
||||
statusDescription: 'Accepted cookies are added to the cookie list; rejecting never removes them from it.',
|
||||
storage: 'Stored in',
|
||||
tabReview: 'Review and approve',
|
||||
tabSiteCheck: 'Site check',
|
||||
uncategorized: 'Not yet described',
|
||||
uncategorizedNote: 'Nothing is known about these yet; they are added as {category} until you describe them.',
|
||||
unknown: 'Unknown',
|
||||
vendor: 'Provider',
|
||||
violation: 'Violation',
|
||||
violationDescription: 'Not necessary, yet seen before consent in the latest site check.',
|
||||
violationDetail: 'Violation details',
|
||||
violationsTitle: 'Violations in the latest check',
|
||||
warningEmailsLink: 'Warning e-mails',
|
||||
},
|
||||
pl: {
|
||||
name: 'Nazwa',
|
||||
@@ -180,10 +264,26 @@ export const COOKIE_SCAN_LABELS: Record<'en' | 'pl', CookieScanLabels> = {
|
||||
alertLink: 'Otwórz przegląd cookies',
|
||||
alertTitle: 'Kontrola cookies: naruszenia: {violations}, nowe nieznane cookies: {newUnknown}.',
|
||||
analytics: 'Analityczne',
|
||||
approvalButton: 'Zatwierdź i dodaj',
|
||||
approvalDone: 'Dodano: {added}, uzupełniono: {filled}, wymaga opisu: {needsDescription}.',
|
||||
approvalEmpty: 'Nic nie czeka na zatwierdzenie. Zeskanuj cookies, aby znaleźć nowe.',
|
||||
approvalError: 'Zatwierdzenie się nie powiodło. Spróbuj ponownie.',
|
||||
approvalIntro: 'Sprawdź znalezione cookies, odznacz niepotrzebne i dodaj je do banera cookies oraz polityki cookies.',
|
||||
approvalLink: 'Przejrzyj i zatwierdź',
|
||||
approvalNoAccess: 'Brak uprawnień do zatwierdzania cookies. Zapytaj administratora.',
|
||||
approvalPending: 'Czeka na zatwierdzenie: {count}.',
|
||||
approvalSelected: 'Zaznaczone: {count}',
|
||||
approvalTitle: 'Zatwierdzanie cookies',
|
||||
approving: 'Dodawanie…',
|
||||
beforeConsentOn: 'przed zgodą na {pages}',
|
||||
category: 'Kategoria',
|
||||
categoryRequired: 'Wybierz kategorię przed akceptacją.',
|
||||
collectionDescription: 'Zaakceptuj plik cookie, aby dodać go do listy cookies; kolejny skan nie nadpisze zmian.',
|
||||
change: 'Ostatni skan',
|
||||
changeChanged: 'Zmieniony',
|
||||
changeDescription: 'Co wykrył ostatni skan; zatwierdzenie to czyści.',
|
||||
changeGone: 'Już nie występuje',
|
||||
changeNew: 'Nowy',
|
||||
collectionDescription: 'Cookies znalezione przez skany; zatwierdź je, aby dodać do banera cookies, wprowadzone zmiany zostają.',
|
||||
cookie: 'Cookie',
|
||||
crawlButton: 'Sprawdź witrynę',
|
||||
crawlCreated: 'Nowe szkice',
|
||||
@@ -208,33 +308,53 @@ export const COOKIE_SCAN_LABELS: Record<'en' | 'pl', CookieScanLabels> = {
|
||||
database: 'Open Cookie Database',
|
||||
domain: 'Domena',
|
||||
draft: 'Szkic',
|
||||
edit: 'Edytuj',
|
||||
emailIntro: 'Ostatnia kontrola cookies witryny {site} wykazała:',
|
||||
emailPending: 'Cookies czekające na zatwierdzenie: {count}. Nic nie trafi do banera cookies bez zatwierdzenia.',
|
||||
emailSubject: 'Kontrola cookies {site}: naruszenia: {violations}, nowe nieznane cookies: {newUnknown}',
|
||||
emailSubjectPending: 'Skan cookies {site}: cookies czekające na zatwierdzenie: {count}',
|
||||
finishedAt: 'Zakończono',
|
||||
functional: 'Funkcjonalne',
|
||||
goneNote: 'Zostają w banerze cookies; usuń je tam, jeśli witryna już ich nie używa.',
|
||||
goneTitle: 'Już nie występują',
|
||||
include: 'Uwzględnij',
|
||||
integration: 'Wbudowana integracja',
|
||||
integrationsFound: 'Używane integracje',
|
||||
integrationsNone: 'Żadna integracja używająca cookies nie jest włączona.',
|
||||
kind: 'Rodzaj',
|
||||
lastScannedAt: 'Ostatnio znaleziony',
|
||||
listed: 'Na liście cookies',
|
||||
listedDescription: 'Już jest na liście cookies banera.',
|
||||
loadingList: 'Wczytywanie…',
|
||||
localStorage: 'Local storage',
|
||||
manual: 'Dodany ręcznie',
|
||||
markerChanged: 'Zmieniony',
|
||||
markerNew: 'Nowy',
|
||||
markerUnknown: 'Wymaga opisu',
|
||||
marketing: 'Marketingowe',
|
||||
namesHint: 'Opcjonalnie. Inne nazwy cookies, po jednej w wierszu. Zostaną wyszukane w Open Cookie Database.',
|
||||
namesLabel: 'Dodatkowe nazwy cookies',
|
||||
necessary: 'Niezbędne',
|
||||
needsDescription: 'Wymaga opisu',
|
||||
needsDescriptionDescription: 'Wpisz cel, aby odwiedzający wiedzieli, do czego służy to cookie.',
|
||||
notifyEmails: 'Ostrzeżenia e-mail do',
|
||||
notifyEmailsDescription: 'Adresy po przecinku, na które trafi ostrzeżenie, gdy kontrola wykryje problemy; zostaw puste, aby nie wysyłać.',
|
||||
notifyEmailsInvalid: 'Wpisz adresy e-mail oddzielone przecinkami, np. [email protected], [email protected].',
|
||||
noViolations: 'Brak naruszeń w ostatniej kontroli.',
|
||||
openCookieBanner: 'Otwórz baner cookies',
|
||||
openReviewList: 'Edytuj cookies pojedynczo',
|
||||
pages: 'Strony',
|
||||
plural: 'Przegląd cookies',
|
||||
project: 'Konfiguracja witryny',
|
||||
purpose: 'Cel',
|
||||
rejected: 'Odrzucony',
|
||||
reloading: 'Dodano. Odświeżanie listy cookies…',
|
||||
request: 'Zapytanie',
|
||||
retention: 'Okres',
|
||||
saveFirst: 'Najpierw zapisz zmiany.',
|
||||
scanButton: 'Skanuj cookies',
|
||||
scanError: 'Skanowanie nie powiodło się. Spróbuj ponownie.',
|
||||
scanIntro: 'Dodaje cookies używanych integracji jako szkice do przejrzenia.',
|
||||
scanIntro: 'Wyszukuje cookies używanych integracji; nic nie trafi do banera cookies bez zatwierdzenia.',
|
||||
scanning: 'Skanowanie…',
|
||||
scanResult: 'Nowe: {created}, zaktualizowane: {updated}, bez zmian: {unchanged}, nieznane: {unknown}.',
|
||||
seenBeforeConsent: 'Widoczny przed zgodą',
|
||||
@@ -249,11 +369,17 @@ export const COOKIE_SCAN_LABELS: Record<'en' | 'pl', CookieScanLabels> = {
|
||||
status: 'Status',
|
||||
statusDescription: 'Zaakceptowane cookies trafiają na listę cookies; odrzucenie nigdy ich z niej nie usuwa.',
|
||||
storage: 'Miejsce zapisu',
|
||||
tabReview: 'Przegląd i zatwierdzanie',
|
||||
tabSiteCheck: 'Kontrola witryny',
|
||||
uncategorized: 'Jeszcze bez opisu',
|
||||
uncategorizedNote: 'Nic o nich jeszcze nie wiadomo; zostaną dodane jako {category} do czasu uzupełnienia opisu.',
|
||||
unknown: 'Nieznane',
|
||||
vendor: 'Dostawca',
|
||||
violation: 'Naruszenie',
|
||||
violationDescription: 'Nie jest niezbędny, a pojawił się przed zgodą w ostatniej kontroli witryny.',
|
||||
violationDetail: 'Szczegóły naruszenia',
|
||||
violationsTitle: 'Naruszenia w ostatniej kontroli',
|
||||
warningEmailsLink: 'Ostrzeżenia e-mail',
|
||||
},
|
||||
}
|
||||
|
||||
|
||||
@@ -21,11 +21,13 @@ export function textFor(text: LocalizedText | undefined, locale: string): string
|
||||
return text[locale] ?? text.en ?? Object.values(text)[0]
|
||||
}
|
||||
|
||||
/** What a scan suggests for an entry, resolved for the project's locales. */
|
||||
/** What a scan suggests for an entry, resolved for the project's locales (default locale first). */
|
||||
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]))
|
||||
// A locale without its own text gets the default locale's (locales[0]), then English, then any.
|
||||
const fallback = typeof text === 'string' ? text : (text[locales[0]] ?? undefined)
|
||||
return Object.fromEntries(locales.map((l) => [l, (typeof text === 'string' ? text : text[l]) ?? fallback ?? textFor(text, l) ?? null]))
|
||||
}
|
||||
const out: CookieReviewValues = {}
|
||||
if (finding.category) {out.category = finding.category}
|
||||
|
||||
@@ -1,4 +1,4 @@
|
||||
import type { BasePayload, PayloadRequest } from 'payload'
|
||||
import type { BasePayload, PayloadRequest, Where } from 'payload'
|
||||
|
||||
import type { CookieReviewValues } from './merge.js'
|
||||
import type {
|
||||
@@ -15,6 +15,7 @@ import { COOKIE_REVIEW_SLUG } from './collection.js'
|
||||
import { loadCookieDatabase, lookupCookie } from './cookieDatabase.js'
|
||||
import { cookieNameMatches, declarationsOf, DEFAULT_COOKIE_INTEGRATIONS, integrationLabel, PROJECT_SOURCE } from './integrations.js'
|
||||
import { mergeCookieReview, suggestionFor } from './merge.js'
|
||||
import { sameCookie } from './sync.js'
|
||||
|
||||
/** Most names one scan looks up — the panel field is for a handful, not a dump. */
|
||||
export const MAX_SCAN_NAMES = 200
|
||||
@@ -142,12 +143,30 @@ export async function collectCookieFindings({
|
||||
/** A review entry a scan wrote: its id, category (after the merge) and whether it is new. */
|
||||
export type CookieReviewEntryRef = { category: null | string; created: boolean; id: number | string }
|
||||
|
||||
/** What the latest scan or crawl noticed about an entry (shown on the approval page). */
|
||||
export type CookieChange = 'changed' | 'gone' | 'new'
|
||||
|
||||
type ReviewDoc = {
|
||||
change?: CookieChange | null
|
||||
id: number | string
|
||||
key?: string
|
||||
listed?: boolean | null
|
||||
status?: 'accepted' | 'draft' | 'rejected' | null
|
||||
suggested?: CookieReviewValues | null
|
||||
} & CookieReviewValues
|
||||
|
||||
/**
|
||||
* The marker after a scan: new entries are `new`; a scan that changed an entry's
|
||||
* suggested values marks it `changed` (a still-unapproved `new` stays `new`);
|
||||
* finding a `gone` entry again clears it. Rejected entries are never flagged.
|
||||
*/
|
||||
export function nextChange(existing: Pick<ReviewDoc, 'change' | 'status'> | undefined, changed: boolean): CookieChange | null {
|
||||
if (!existing) {return 'new'}
|
||||
if (existing.status === 'rejected') {return existing.change === 'gone' ? null : (existing.change ?? null)}
|
||||
if (changed) {return existing.change === 'new' ? 'new' : 'changed'}
|
||||
return existing.change === 'gone' ? null : (existing.change ?? null)
|
||||
}
|
||||
|
||||
function localesOf(payload: BasePayload): { defaultLocale?: string; locales: (string | undefined)[] } {
|
||||
const l = payload.config.localization
|
||||
if (!l) {return { locales: [undefined] }}
|
||||
@@ -155,6 +174,12 @@ function localesOf(payload: BasePayload): { defaultLocale?: string; locales: (st
|
||||
return { defaultLocale: l.defaultLocale, locales: [l.defaultLocale, ...codes.filter((c) => c !== l.defaultLocale)] }
|
||||
}
|
||||
|
||||
/** Cookie names that already have a review entry. */
|
||||
async function reviewedNames(payload: BasePayload, req?: PayloadRequest): Promise<Set<string>> {
|
||||
const { docs } = await payload.find({ collection: COOKIE_REVIEW_SLUG as never, depth: 0, limit: 0, overrideAccess: true, pagination: false, req, select: { name: true } as never })
|
||||
return new Set((docs as unknown as { name?: string }[]).map((d) => d.name ?? '').filter(Boolean))
|
||||
}
|
||||
|
||||
/** Names already in Cookie Settings → Cookies. */
|
||||
async function listedNames(payload: BasePayload, req?: PayloadRequest): Promise<Set<string>> {
|
||||
try {
|
||||
@@ -188,7 +213,7 @@ export async function applyCookieFindings({
|
||||
const { locales } = localesOf(payload)
|
||||
const codes = locales.filter((l): l is string => Boolean(l))
|
||||
const listed = await listedNames(payload, req)
|
||||
const summary: CookieScanSummary = { created: 0, newUnknown: 0, unchanged: 0, unknown: 0, updated: 0 }
|
||||
const summary: CookieScanSummary = { created: 0, gone: 0, newUnknown: 0, unchanged: 0, unknown: 0, updated: 0 }
|
||||
const now = new Date().toISOString()
|
||||
const common = { collection: collection as never, context: { ipalCookieScan: true }, depth: 0, fallbackLocale: false as never, overrideAccess: true, req }
|
||||
|
||||
@@ -199,7 +224,7 @@ export async function applyCookieFindings({
|
||||
const machine = {
|
||||
key,
|
||||
lastScannedAt: now,
|
||||
listed: listed.has(finding.name),
|
||||
listed: [...listed].some((n) => sameCookie(n, finding.name)),
|
||||
source: finding.source,
|
||||
sourceDetail: finding.sourceDetail ?? null,
|
||||
suggested: next,
|
||||
@@ -208,6 +233,7 @@ export async function applyCookieFindings({
|
||||
const existing = found.docs[0] as ReviewDoc | undefined
|
||||
|
||||
const values = existing ? mergeCookieReview(existing, existing.suggested, next) : { changed: true, values: next }
|
||||
const change = nextChange(existing, values.changed)
|
||||
const { purpose, retention, ...scalars } = values.values
|
||||
const textIn = (locale: string | undefined) => ({
|
||||
...(purpose && locale ? { purpose: purpose[locale] ?? null } : {}),
|
||||
@@ -219,7 +245,7 @@ export async function applyCookieFindings({
|
||||
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 }) }
|
||||
? { ...scalars, ...machine, change, ...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) {
|
||||
@@ -239,6 +265,41 @@ export async function applyCookieFindings({
|
||||
return summary
|
||||
}
|
||||
|
||||
/**
|
||||
* Marks entries that a scan or crawl no longer finds as `gone` — for review
|
||||
* only: nothing is deleted, and the cookie list keeps its row. `where` picks
|
||||
* the entries this kind of scan is responsible for; `keep` are the review keys
|
||||
* it did find. Rejected entries are left alone. Returns how many were flagged.
|
||||
*/
|
||||
export async function flagGoneEntries({
|
||||
collection = COOKIE_REVIEW_SLUG,
|
||||
keep,
|
||||
payload,
|
||||
req,
|
||||
where,
|
||||
}: {
|
||||
collection?: string
|
||||
keep: Set<string>
|
||||
payload: BasePayload
|
||||
req?: PayloadRequest
|
||||
where: Where
|
||||
}): Promise<number> {
|
||||
const common = { collection: collection as never, context: { ipalCookieScan: true }, depth: 0, overrideAccess: true, req }
|
||||
const { docs } = await payload.find({
|
||||
...common,
|
||||
limit: 0,
|
||||
pagination: false,
|
||||
where: { and: [where, { status: { not_equals: 'rejected' } }, { change: { not_equals: 'gone' } }] },
|
||||
})
|
||||
let flagged = 0
|
||||
for (const doc of docs as unknown as ReviewDoc[]) {
|
||||
if (!doc.key || keep.has(doc.key)) {continue}
|
||||
await payload.update({ ...common, id: doc.id, data: { change: 'gone' } as never })
|
||||
flagged++
|
||||
}
|
||||
return flagged
|
||||
}
|
||||
|
||||
/** Scan context from a running Payload: SiteIntegrations + the plugin's module switches. */
|
||||
export async function cookieScanContext(
|
||||
payload: BasePayload,
|
||||
@@ -273,14 +334,25 @@ export async function runCookieScan({
|
||||
}): Promise<{ enabled: CookieIntegration[]; summary: CookieScanSummary }> {
|
||||
const ctx = await cookieScanContext(payload, plugin, req)
|
||||
const integrations = options.integrations ? options.integrations(DEFAULT_COOKIE_INTEGRATIONS) : DEFAULT_COOKIE_INTEGRATIONS
|
||||
// Rows typed into the cookie list by hand are looked up once, when they have no review entry yet;
|
||||
// after that the entry is the editor's, and a scan must not re-find it as something else.
|
||||
const reviewed = await reviewedNames(payload, req)
|
||||
const listed = [...(await listedNames(payload, req))].filter((n) => !reviewed.has(n))
|
||||
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])],
|
||||
names: [...new Set([...listed, ...names])],
|
||||
})
|
||||
const summary = await applyCookieFindings({ findings, payload, req })
|
||||
// An integration switched off, a declaration removed: its cookies are flagged, never deleted.
|
||||
summary.gone = await flagGoneEntries({
|
||||
keep: new Set(findings.filter((f) => f.source === 'integration' || f.source === 'project').map((f) => reviewKey(f.storage, f.name))),
|
||||
payload,
|
||||
req,
|
||||
where: { source: { in: ['integration', 'project'] } },
|
||||
})
|
||||
return { enabled, summary }
|
||||
}
|
||||
|
||||
@@ -2,6 +2,8 @@ import type { BasePayload, PayloadRequest } from 'payload'
|
||||
|
||||
import type { CookieReviewValues } from './merge.js'
|
||||
|
||||
import { cookieNameMatches } from './integrations.js'
|
||||
|
||||
type Row = {
|
||||
category?: null | string
|
||||
duration?: null | string
|
||||
@@ -15,6 +17,12 @@ type Entry = { name: string } & CookieReviewValues
|
||||
|
||||
const empty = (v: unknown) => v === undefined || v === null || (typeof v === 'string' && !v.trim())
|
||||
|
||||
/**
|
||||
* The same cookie in the list: equal names, or one is a pattern covering the
|
||||
* other (`_ga_*` and `_ga_ABC123`) — so a scan never adds a second row for it.
|
||||
*/
|
||||
export const sameCookie = (a: string, b: string) => a === b || cookieNameMatches(a, b) || cookieNameMatches(b, a)
|
||||
|
||||
/**
|
||||
* 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
|
||||
@@ -35,8 +43,9 @@ export async function addToCookieList({
|
||||
const codes = l ? (l.localeCodes ?? []) : []
|
||||
const defaultLocale = l ? l.defaultLocale : undefined
|
||||
const locales = l ? [defaultLocale!, ...codes.filter((c) => c !== defaultLocale)] : [undefined]
|
||||
// A locale without its own text gets the default locale's text — never nothing.
|
||||
const text = (map: Record<string, null | string> | undefined, locale: string | undefined) =>
|
||||
(locale ? map?.[locale] : map && Object.values(map)[0]) ?? null
|
||||
(locale ? map?.[locale]?.trim() || (defaultLocale ? map?.[defaultLocale]?.trim() : '') : 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 }
|
||||
@@ -45,7 +54,7 @@ export async function addToCookieList({
|
||||
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)
|
||||
const row = rows.find((r) => Boolean(r.name?.trim()) && sameCookie(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
|
||||
|
||||
@@ -80,6 +80,8 @@ export type OpenCookieCategory = 'Analytics' | 'Functional' | 'Marketing' | 'Nec
|
||||
/** Totals a scan reports back to the panel. */
|
||||
export type CookieScanSummary = {
|
||||
created: number
|
||||
/** Entries this scan no longer found, flagged for review (never deleted). */
|
||||
gone: number
|
||||
/** Entries created by this scan that nothing knew. */
|
||||
newUnknown: number
|
||||
unchanged: number
|
||||
@@ -95,6 +97,19 @@ export type CookieScanSummary = {
|
||||
export type CookieScannerOptions = {
|
||||
/** Who may run a scan (GET/POST /api/ipal/cookie-scan) and start a crawl. Default: `editor` and up. */
|
||||
access?: (args: { req: PayloadRequest }) => boolean | Promise<boolean>
|
||||
/**
|
||||
* `'combined'` (default): one "Cookies" entry in the navigation — the review
|
||||
* list and the site check become tabs of the Cookies global ("Review and
|
||||
* approve", "Site check") and leave the navigation; their pages, data and API
|
||||
* stay. `'separate'`: each keeps its own navigation entry.
|
||||
*/
|
||||
adminLayout?: 'combined' | 'separate'
|
||||
/**
|
||||
* One approval for everything a scan or crawl found: the "Approve cookies"
|
||||
* view (grouped by category, one "Approve and add" button) and a dashboard
|
||||
* reminder while cookies wait. Default on; `false` = review entry by entry only.
|
||||
*/
|
||||
approval?: CookieApprovalOptions | false
|
||||
/** Change the `cookie-review` collection (object merges, function takes over). */
|
||||
collectionOverrides?: CollectionOverride
|
||||
/**
|
||||
@@ -156,3 +171,11 @@ export type CookieCrawlOptions = {
|
||||
/** Hosts whose requests before consent are violations: `(defaults) => hosts`. */
|
||||
trackerHosts?: (defaults: string[]) => string[]
|
||||
}
|
||||
|
||||
/** `cookieScanner.approval` — every key optional. */
|
||||
export type CookieApprovalOptions = {
|
||||
/** Dashboard reminder while cookies wait for approval. Default true. */
|
||||
dashboard?: boolean
|
||||
/** Category for cookies nothing knows until an editor describes them; it should need consent. Default `'marketing'`. */
|
||||
unknownCategory?: ConsentCategory
|
||||
}
|
||||
|
||||
@@ -0,0 +1,134 @@
|
||||
import type { BasePayload, CollectionAfterChangeHook, CollectionConfig, GlobalAfterChangeHook, GlobalConfig, PayloadRequest } from 'payload'
|
||||
|
||||
/**
|
||||
* Localized text the editor wrote in one language goes to every language that
|
||||
* is still empty — so a cookie added in Polish is not blank on the English page.
|
||||
* A language that already has its own text is never touched: the editor can
|
||||
* still change any language on its own.
|
||||
*
|
||||
* Fields: `'purpose'` (top-level) or `'cookies.purpose'` (a sub-field of the
|
||||
* rows of an array; rows are matched by their id, which Payload keeps the same
|
||||
* in every locale).
|
||||
*
|
||||
* Payload's own `localization.fallback` only covers part of this: an empty
|
||||
* locale *reads* as the default locale's text, but nothing is stored, the admin
|
||||
* shows the field empty, and the text always comes from the default locale,
|
||||
* not from the language that was just edited.
|
||||
*/
|
||||
export type FillEmptyLocalesTarget = { collection: string; id: number | string } | { global: string }
|
||||
|
||||
const empty = (v: unknown) => v === undefined || v === null || (typeof v === 'string' && !v.trim())
|
||||
|
||||
/** Writes `source`'s text (read in `sourceLocale`) into every other locale where that text is empty. Returns the locales changed. */
|
||||
export async function fillEmptyLocales({
|
||||
fields,
|
||||
payload,
|
||||
req,
|
||||
source,
|
||||
sourceLocale,
|
||||
target,
|
||||
}: {
|
||||
fields: string[]
|
||||
payload: BasePayload
|
||||
req?: PayloadRequest
|
||||
source: Record<string, unknown>
|
||||
sourceLocale: string
|
||||
target: FillEmptyLocalesTarget
|
||||
}): Promise<string[]> {
|
||||
const l = payload.config.localization
|
||||
if (!l) {return []}
|
||||
const others = l.localeCodes.filter((c) => c !== sourceLocale)
|
||||
const common = { context: { ipalFillLocales: true }, depth: 0, fallbackLocale: false as never, overrideAccess: true, req }
|
||||
const changedLocales: string[] = []
|
||||
|
||||
for (const locale of others) {
|
||||
const doc = (
|
||||
'global' in target
|
||||
? await payload.findGlobal({ ...common, slug: target.global as never, locale: locale as never })
|
||||
: await payload.findByID({ ...common, id: target.id as never, collection: target.collection as never, locale: locale as never })
|
||||
) as Record<string, unknown>
|
||||
const patch: Record<string, unknown> = {}
|
||||
|
||||
for (const field of fields) {
|
||||
const [head, sub] = field.split('.')
|
||||
if (!sub) {
|
||||
if (empty(doc[head]) && !empty(source[head])) {patch[head] = source[head]}
|
||||
continue
|
||||
}
|
||||
const sourceRows = Array.isArray(source[head]) ? (source[head] as Record<string, unknown>[]) : []
|
||||
const rows = (patch[head] as Record<string, unknown>[] | undefined) ?? (Array.isArray(doc[head]) ? (doc[head] as Record<string, unknown>[]).map((r) => ({ ...r })) : [])
|
||||
let changed = false
|
||||
for (const row of rows) {
|
||||
const from = sourceRows.find((s) => s.id != null && s.id === row.id)
|
||||
if (from && empty(row[sub]) && !empty(from[sub])) {
|
||||
row[sub] = from[sub]
|
||||
changed = true
|
||||
}
|
||||
}
|
||||
if (changed) {patch[head] = rows}
|
||||
}
|
||||
|
||||
if (!Object.keys(patch).length) {continue}
|
||||
if ('global' in target) {
|
||||
await payload.updateGlobal({ ...common, slug: target.global as never, data: patch as never, locale: locale as never })
|
||||
} else {
|
||||
await payload.update({ ...common, id: target.id as never, collection: target.collection as never, data: patch as never, locale: locale as never })
|
||||
}
|
||||
changedLocales.push(locale)
|
||||
}
|
||||
return changedLocales
|
||||
}
|
||||
|
||||
/** Runs `fn` with `req`, then puts back req.locale / req.fallbackLocale (Local API calls with `req` change them). */
|
||||
async function keepingLocale(req: PayloadRequest, fn: () => Promise<unknown>) {
|
||||
const { fallbackLocale, locale } = req
|
||||
try {
|
||||
await fn()
|
||||
} catch (err) {
|
||||
req.payload.logger.error(`[ipal] filling empty locales failed: ${err instanceof Error ? err.message : String(err)}`)
|
||||
} finally {
|
||||
req.locale = locale
|
||||
req.fallbackLocale = fallbackLocale
|
||||
}
|
||||
}
|
||||
|
||||
/** Skips its own writes and writes that fill every locale themselves (the cookie scanner). */
|
||||
const skip = (context: Record<string, unknown> | undefined, locale: unknown) =>
|
||||
Boolean(context?.ipalFillLocales || context?.ipalCookieScan) || typeof locale !== 'string' || locale === 'all' || locale === '*'
|
||||
|
||||
/**
|
||||
* afterChange hook for a global: text saved in one language fills that field in
|
||||
* every language where it is empty.
|
||||
*
|
||||
* hooks: { afterChange: [buildFillEmptyLocalesGlobalHook({ global: 'cookie-settings', fields: ['cookies.purpose'] })] }
|
||||
*/
|
||||
export function buildFillEmptyLocalesGlobalHook({ fields, global }: { fields: string[]; global: string }): GlobalAfterChangeHook {
|
||||
return async ({ context, doc, req }) => {
|
||||
if (skip(context, req.locale)) {return doc}
|
||||
await keepingLocale(req, () =>
|
||||
fillEmptyLocales({ fields, payload: req.payload, req, source: doc as Record<string, unknown>, sourceLocale: req.locale as string, target: { global } }),
|
||||
)
|
||||
return doc
|
||||
}
|
||||
}
|
||||
|
||||
/** The same for a collection: the saved document's text fills its empty languages. */
|
||||
export function buildFillEmptyLocalesCollectionHook({ collection, fields }: { collection: string; fields: string[] }): CollectionAfterChangeHook {
|
||||
return async ({ context, doc, req }) => {
|
||||
if (skip(context, req.locale) || doc?.id == null) {return doc}
|
||||
await keepingLocale(req, () =>
|
||||
fillEmptyLocales({ fields, payload: req.payload, req, source: doc as Record<string, unknown>, sourceLocale: req.locale as string, target: { id: doc.id, collection } }),
|
||||
)
|
||||
return doc
|
||||
}
|
||||
}
|
||||
|
||||
/** Adds the fill hook to a global or a collection config (no fields = unchanged). */
|
||||
export function withFillLocales<T extends CollectionConfig | GlobalConfig>(kind: 'collection' | 'global', entity: T, fields: string[] | undefined): T {
|
||||
if (!fields?.length) {return entity}
|
||||
const hook =
|
||||
kind === 'collection'
|
||||
? buildFillEmptyLocalesCollectionHook({ collection: entity.slug, fields })
|
||||
: buildFillEmptyLocalesGlobalHook({ fields, global: entity.slug })
|
||||
return { ...entity, hooks: { ...entity.hooks, afterChange: [...(entity.hooks?.afterChange ?? []), hook] } } as T
|
||||
}
|
||||
@@ -5,6 +5,8 @@ export { buildAutoFillMetaHook, validateFaviconField } from '../seo/index.js'
|
||||
export { buildCrossLocaleFieldSync } from './buildCrossLocaleFieldSync.js'
|
||||
export { buildGlobalRevalidateHook, buildRevalidateHook } from './buildRevalidateHook.js'
|
||||
export type { RevalidatePathFn } from './buildRevalidateHook.js'
|
||||
export { buildFillEmptyLocalesCollectionHook, buildFillEmptyLocalesGlobalHook, fillEmptyLocales, withFillLocales } from './fillEmptyLocales.js'
|
||||
export type { FillEmptyLocalesTarget } from './fillEmptyLocales.js'
|
||||
export { buildPreventDeleteSystemPage } from './preventDeleteSystemPage.js'
|
||||
export { setPublishedAtHook } from './setPublishedAt.js'
|
||||
|
||||
|
||||
+68
-18
@@ -11,6 +11,8 @@ import { buildSiteSettings } from './globals/SiteSettings/index.js'
|
||||
import { adminOnly, adminOrSelf, injectRoles } from './modules/access/index.js'
|
||||
import { applyAdminI18n } from './modules/admin-i18n/apply.js'
|
||||
import { buildConsentLogCollection, buildConsentLogEndpoint } from './modules/consent/consentLog.js'
|
||||
import { addCookieScannerTabs } from './modules/consent/scanner/adminTabs.js'
|
||||
import { buildCookieApprovalEndpoints, COOKIE_APPROVAL_VIEW_PATH } from './modules/consent/scanner/approval.js'
|
||||
import { buildCookieReviewCollection } from './modules/consent/scanner/collection.js'
|
||||
import { buildCookieCrawlEndpoints } from './modules/consent/scanner/crawl/endpoints.js'
|
||||
import { buildCookieCrawlGlobal } from './modules/consent/scanner/crawl/global.js'
|
||||
@@ -22,6 +24,7 @@ import { testEmailEndpoint } from './modules/email/test/testEmailEndpoint.js'
|
||||
import { emailSettingsFields } from './modules/forms/emailLayout.js'
|
||||
import { buildFormsPlugin } from './modules/forms/formsPluginConfig.js'
|
||||
import { buildGlobalRevalidateHook } from './modules/hooks/buildRevalidateHook.js'
|
||||
import { withFillLocales } from './modules/hooks/fillEmptyLocales.js'
|
||||
import { buildLocalizationConfig, validateI18nConfig } from './modules/i18n/index.js'
|
||||
import { buildSystemPagesFields } from './modules/pages/index.js'
|
||||
import { buildSeoPlugin, injectAutoFillMeta, injectSeoTabs } from './modules/seo/index.js'
|
||||
@@ -81,6 +84,13 @@ export const ipalKit = (options: IpalOptions): Plugin => {
|
||||
|
||||
let config = { ...incomingConfig }
|
||||
|
||||
// Text written in one language fills the empty languages of the same field (cookie list, cookie review).
|
||||
const fillDefaults = { 'cookie-review': ['purpose', 'retention'], 'cookie-settings': ['cookies.purpose', 'cookies.duration'] }
|
||||
const fillLocales: Record<keyof typeof fillDefaults, string[]> =
|
||||
options.fillEmptyLocales === false
|
||||
? { 'cookie-review': [], 'cookie-settings': [] }
|
||||
: { ...fillDefaults, ...(typeof options.fillEmptyLocales === 'object' ? options.fillEmptyLocales : {}) }
|
||||
|
||||
// --- auth collection: Payload adds its default `users` only AFTER plugins
|
||||
// run (config sanitize), so roles and 2FA would have nothing to attach to,
|
||||
// and a project without it crashes ("users is not a valid admin user
|
||||
@@ -328,7 +338,7 @@ export const ipalKit = (options: IpalOptions): Plugin => {
|
||||
systemPageFields,
|
||||
}),
|
||||
buildSiteIntegrations({ additionalFields: options.integrationsFields }),
|
||||
buildCookieSettings(),
|
||||
withFillLocales('global', buildCookieSettings(), fillLocales['cookie-settings']),
|
||||
buildNotifications({ lightbox: options.lightbox === true }),
|
||||
]
|
||||
// A global feeds every page's layout — revalidate the site on save.
|
||||
@@ -351,31 +361,71 @@ export const ipalKit = (options: IpalOptions): Plugin => {
|
||||
// --- cookie scanner: review list + "Scan cookies" (opt-in) ---
|
||||
if (options.cookieScanner) {
|
||||
const scannerOptions = options.cookieScanner === true ? {} : options.cookieScanner
|
||||
config.collections = [...(config.collections ?? []), applyCollectionOverride(buildCookieReviewCollection(scannerOptions), scannerOptions.collectionOverrides)]
|
||||
const adminRoute = options.adminRoute ?? '/admin'
|
||||
const labels = mergeCookieScanLabels(scannerOptions.labels)
|
||||
// One "Cookies" entry by default: the review list and the site check leave the navigation
|
||||
// (their pages and API stay) and appear as tabs of the Cookies global.
|
||||
const combined = scannerOptions.adminLayout !== 'separate'
|
||||
const hideFromNav = <T extends { admin?: object }>(entity: T): T => (combined ? { ...entity, admin: { ...entity.admin, group: false } } : entity)
|
||||
config.collections = [
|
||||
...(config.collections ?? []),
|
||||
applyCollectionOverride(hideFromNav(withFillLocales('collection', buildCookieReviewCollection(scannerOptions), fillLocales['cookie-review'])), scannerOptions.collectionOverrides),
|
||||
]
|
||||
const scanPlugin = { localeCount: options.i18n.locales.length, stats: Boolean(options.stats) }
|
||||
config.endpoints = [...(config.endpoints ?? []), ...buildCookieScanEndpoints(scannerOptions, scanPlugin)]
|
||||
// Browser crawl through the scanner service (opt-in): latest-result global, endpoints, dashboard warning.
|
||||
if (scannerOptions.crawl) {
|
||||
const crawl = scannerOptions.crawl === true ? {} : scannerOptions.crawl
|
||||
const labels = mergeCookieScanLabels(scannerOptions.labels)
|
||||
const crawlGlobal = buildCookieCrawlGlobal(labels)
|
||||
// One approval for everything found (default on): the "Approve cookies" view and its endpoint.
|
||||
const approval = scannerOptions.approval === false ? null : (scannerOptions.approval ?? {})
|
||||
if (approval) {
|
||||
config.endpoints = [...(config.endpoints ?? []), ...buildCookieApprovalEndpoints(scannerOptions)]
|
||||
config.admin = {
|
||||
...(config.admin ?? {}),
|
||||
components: {
|
||||
...(config.admin?.components ?? {}),
|
||||
views: {
|
||||
...(config.admin?.components?.views ?? {}),
|
||||
ipalCookieApproval: {
|
||||
Component: {
|
||||
path: '@intecion/ipal-kit/admin#CookieApprovalView',
|
||||
serverProps: { adminRoute, labels, ...(approval.unknownCategory ? { unknownCategory: approval.unknownCategory } : {}) },
|
||||
},
|
||||
meta: { title: 'Approve cookies' },
|
||||
path: COOKIE_APPROVAL_VIEW_PATH,
|
||||
},
|
||||
},
|
||||
},
|
||||
}
|
||||
}
|
||||
// Browser crawl through the scanner service (opt-in): latest-result global, endpoints.
|
||||
const crawl = scannerOptions.crawl ? (scannerOptions.crawl === true ? {} : scannerOptions.crawl) : null
|
||||
if (crawl) {
|
||||
const crawlGlobal = hideFromNav(buildCookieCrawlGlobal(labels))
|
||||
const override = crawl.globalOverride
|
||||
config.globals = [
|
||||
...(config.globals ?? []),
|
||||
override ? applyGlobalOverrides([crawlGlobal], { [crawlGlobal.slug]: override } as never)[0] : crawlGlobal,
|
||||
]
|
||||
config.endpoints = [...(config.endpoints ?? []), ...buildCookieCrawlEndpoints({ labels, options: scannerOptions, plugin: scanPlugin })]
|
||||
if (crawl.dashboard !== false) {
|
||||
config.admin = {
|
||||
...(config.admin ?? {}),
|
||||
components: {
|
||||
...(config.admin?.components ?? {}),
|
||||
beforeDashboard: [
|
||||
...(config.admin?.components?.beforeDashboard ?? []),
|
||||
{ path: '@intecion/ipal-kit/admin#CookieCrawlAlert', serverProps: { adminRoute: options.adminRoute ?? '/admin', labels } },
|
||||
],
|
||||
},
|
||||
}
|
||||
}
|
||||
if (combined) {
|
||||
config.globals = (config.globals ?? []).map((g) =>
|
||||
g.slug === 'cookie-settings'
|
||||
? addCookieScannerTabs(g, { approval: Boolean(approval), crawl: Boolean(crawl), labels, unknownCategory: approval?.unknownCategory })
|
||||
: g,
|
||||
)
|
||||
}
|
||||
// Dashboard warning: cookies waiting for approval, crawl violations or a failed crawl.
|
||||
const alertApproval = Boolean(approval && approval.dashboard !== false)
|
||||
const alertCrawl = Boolean(crawl && crawl.dashboard !== false)
|
||||
if (alertApproval || alertCrawl) {
|
||||
config.admin = {
|
||||
...(config.admin ?? {}),
|
||||
components: {
|
||||
...(config.admin?.components ?? {}),
|
||||
beforeDashboard: [
|
||||
...(config.admin?.components?.beforeDashboard ?? []),
|
||||
{ path: '@intecion/ipal-kit/admin#CookieCrawlAlert', serverProps: { adminRoute, approval: alertApproval, crawl: alertCrawl, labels } },
|
||||
],
|
||||
},
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
@@ -82,6 +82,16 @@ export type IpalOptions = {
|
||||
*/
|
||||
enabled?: boolean
|
||||
|
||||
/**
|
||||
* Text written in one language fills the same field in every language that is
|
||||
* still empty; a language with its own text is never overwritten. Default on
|
||||
* for the cookie list (`cookie-settings`: `cookies.purpose`, `cookies.duration`)
|
||||
* and the cookie review (`cookie-review`: `purpose`, `retention`). `false` turns
|
||||
* it off; an object sets the fields per slug (`[]` = off for that slug).
|
||||
* Building blocks: buildFillEmptyLocalesGlobalHook / …CollectionHook.
|
||||
*/
|
||||
fillEmptyLocales?: { 'cookie-review'?: string[]; 'cookie-settings'?: string[] } | boolean
|
||||
|
||||
/**
|
||||
* Forms — form-builder collections (forms, form-submissions) plus the
|
||||
* callable submitForm (Turnstile + persistence + SMTP-from-panel email).
|
||||
|
||||
@@ -0,0 +1,206 @@
|
||||
/**
|
||||
* One approval for everything a scan found, through a REAL Payload (SQLite,
|
||||
* pl + en): scan → approval list → "Approve and add" → Cookie banner → Cookies,
|
||||
* the cookie policy table and the banner's detailed window.
|
||||
*/
|
||||
import type { Config, Payload } from 'payload'
|
||||
|
||||
import { sqliteAdapter } from '@payloadcms/db-sqlite'
|
||||
import { lexicalEditor } from '@payloadcms/richtext-lexical'
|
||||
import os from 'os'
|
||||
import path from 'path'
|
||||
import { getPayload } from 'payload'
|
||||
import { afterAll, beforeAll, describe, expect, test, vi } from 'vitest'
|
||||
|
||||
import type { I18nConfig } from '../src/modules/i18n/types.js'
|
||||
|
||||
import { getConsentTexts, getCookieTable } from '../src/modules/consent/getConsentTexts.js'
|
||||
import { approveCookies, buildCookieApprovalEndpoints, loadCookieApproval } from '../src/modules/consent/scanner/approval.js'
|
||||
import { nextChange, runCookieScan } from '../src/modules/consent/scanner/scan.js'
|
||||
import { sameCookie } from '../src/modules/consent/scanner/sync.js'
|
||||
import { ipalKit } from '../src/plugin.js'
|
||||
import { buildTestConfig } from './helpers.js'
|
||||
|
||||
vi.mock('server-only', () => ({}))
|
||||
|
||||
const SLUG = 'cookie-review' as never
|
||||
const plugin = { localeCount: 2, stats: true }
|
||||
const i18n: I18nConfig = { defaultLocale: 'pl', locales: [{ code: 'pl', label: 'Polski' }, { code: 'en', label: 'English' }] }
|
||||
const youtube = (purpose = { en: 'YouTube embed', pl: 'Film YouTube' }) => ({
|
||||
name: 'yt-*',
|
||||
category: 'marketing' as const,
|
||||
purpose,
|
||||
retention: { en: '6 months', pl: '6 mies.' },
|
||||
setBeforeConsent: false,
|
||||
vendor: 'Google',
|
||||
})
|
||||
|
||||
type Row = { category: string; duration?: null | string; name: string; provider?: null | string; purpose?: null | string }
|
||||
type Entry = { category?: null | string; change?: null | string; id: number; name: string; needsDescription?: boolean; status: string }
|
||||
|
||||
let payload: Payload
|
||||
const list = async (locale: string) =>
|
||||
((await payload.findGlobal({ slug: 'cookie-settings' as never, fallbackLocale: false as never, locale: locale as never })) as { cookies?: Row[] }).cookies ?? []
|
||||
const entry = async (name: string) =>
|
||||
(await payload.find({ collection: SLUG, depth: 0, where: { name: { equals: name } } })).docs[0] as unknown as Entry
|
||||
|
||||
beforeAll(async () => {
|
||||
payload = await getPayload({
|
||||
config: buildTestConfig({
|
||||
collections: [
|
||||
{ slug: 'users', auth: true, fields: [] },
|
||||
{ slug: 'media', fields: [], upload: { staticDir: path.join(os.tmpdir(), 'ipal-test-media') } },
|
||||
],
|
||||
db: sqliteAdapter({ client: { url: 'file::memory:' }, push: true }),
|
||||
editor: lexicalEditor(),
|
||||
plugins: [ipalKit({ access: { authCollection: 'users' }, cookieScanner: true, i18n, stats: true, twoFactor: false })],
|
||||
secret: 'cookie-approval-test-secret',
|
||||
telemetry: false,
|
||||
}),
|
||||
})
|
||||
await payload.updateGlobal({ slug: 'site-integrations' as never, data: { ga4MeasurementId: 'G-ABC123DEF4' } as never })
|
||||
// A row an editor wrote by hand, before any scan: a concrete name the scan knows as `_ga_*`.
|
||||
await payload.updateGlobal({
|
||||
slug: 'cookie-settings' as never,
|
||||
data: { cookies: [{ name: '_ga_XYZ123', category: 'analytics', provider: 'Google', purpose: 'Tekst redaktora' }] } as never,
|
||||
locale: 'pl' as never,
|
||||
})
|
||||
}, 60_000)
|
||||
|
||||
afterAll(async () => {
|
||||
await payload?.destroy()
|
||||
})
|
||||
|
||||
describe('cookie approval — pure rules', () => {
|
||||
test('markers: new, changed, found again, rejected left alone', () => {
|
||||
expect(nextChange(undefined, true)).toBe('new')
|
||||
expect(nextChange({ change: null, status: 'accepted' }, true)).toBe('changed')
|
||||
expect(nextChange({ change: 'new', status: 'draft' }, true)).toBe('new')
|
||||
expect(nextChange({ change: 'gone', status: 'accepted' }, false)).toBeNull()
|
||||
expect(nextChange({ change: null, status: 'accepted' }, false)).toBeNull()
|
||||
expect(nextChange({ change: null, status: 'rejected' }, true)).toBeNull()
|
||||
})
|
||||
|
||||
test('the same cookie: equal names or a pattern covering the other', () => {
|
||||
expect(sameCookie('_ga_*', '_ga_XYZ123')).toBe(true)
|
||||
expect(sameCookie('_ga_XYZ123', '_ga_*')).toBe(true)
|
||||
expect(sameCookie('_ga', '_ga_XYZ123')).toBe(false)
|
||||
})
|
||||
})
|
||||
|
||||
describe('cookie approval against a real Payload', () => {
|
||||
test('a scan adds nothing to the cookie banner; the approval list groups what it found', async () => {
|
||||
await runCookieScan({ names: ['mystery_cookie'], options: { declarations: [youtube()] }, payload, plugin })
|
||||
expect((await list('pl')).map((r) => r.name)).toEqual(['_ga_XYZ123']) // nothing added before approval
|
||||
|
||||
const { gone, pending } = await loadCookieApproval({ locale: 'en', payload })
|
||||
expect(gone).toEqual([])
|
||||
const names = pending.map((p) => p.name)
|
||||
for (const n of ['_ga', '_ga_*', 'cookie-consent', 'ipal_vid', 'NEXT_LOCALE', 'yt-*', 'mystery_cookie']) {expect(names).toContain(n)}
|
||||
expect(pending.find((p) => p.name === 'ipal_vid')).toMatchObject({ category: 'analytics', change: 'new', purpose: expect.stringContaining('Built-in statistics'), unknown: false })
|
||||
expect(pending.find((p) => p.name === 'mystery_cookie')).toMatchObject({ category: null, unknown: true })
|
||||
// In Polish when the admin reads Polish.
|
||||
const pl = await loadCookieApproval({ locale: 'pl', payload })
|
||||
expect(pl.pending.find((p) => p.name === 'ipal_vid')?.purpose).toContain('Wbudowane statystyki')
|
||||
})
|
||||
|
||||
test('approving adds the ticked cookies everywhere they are listed — once, without touching editor text', async () => {
|
||||
const yt = await entry('yt-*')
|
||||
const ids = (await loadCookieApproval({ locale: 'pl', payload })).pending.filter((p) => p.id !== yt.id).map((p) => p.id)
|
||||
const result = await approveCookies({ ids, payload })
|
||||
expect(result).toMatchObject({ filled: 1, needsDescription: 1 })
|
||||
|
||||
const pl = await list('pl')
|
||||
const en = await list('en')
|
||||
// Cookie banner → Cookies, in every locale, with the plugin's texts.
|
||||
expect(pl.find((r) => r.name === 'ipal_vid')).toMatchObject({ category: 'analytics', duration: '6 mies.', purpose: expect.stringContaining('Wbudowane') })
|
||||
expect(en.find((r) => r.name === 'ipal_vid')?.purpose).toContain('Built-in statistics')
|
||||
// `_ga_*` is the editor's `_ga_XYZ123`: no second row, their text and category kept, only empty text filled.
|
||||
expect(pl.filter((r) => sameCookie(r.name, '_ga_*'))).toHaveLength(1)
|
||||
expect(pl.find((r) => r.name === '_ga_XYZ123')).toMatchObject({ category: 'analytics', duration: '2 lata', purpose: 'Tekst redaktora' })
|
||||
// Unknown: a category that needs consent, flagged "needs description".
|
||||
expect(pl.find((r) => r.name === 'mystery_cookie')?.category).toBe('marketing')
|
||||
expect(await entry('mystery_cookie')).toMatchObject({ category: 'marketing', change: null, needsDescription: true, status: 'accepted' })
|
||||
// Unticked: still waiting, not in the list.
|
||||
expect(await entry('yt-*')).toMatchObject({ status: 'draft' })
|
||||
expect(pl.some((r) => r.name === 'yt-*')).toBe(false)
|
||||
|
||||
// The cookie policy table and the banner's detailed window read the same list.
|
||||
expect((await getCookieTable({ locale: 'en', payload })).map((r) => r.name)).toContain('ipal_vid')
|
||||
const texts = await getConsentTexts({ config: i18n, locale: 'pl', payload, privacyPolicy: false })
|
||||
expect(texts.cookies?.map((r) => r.name)).toContain('ipal_vid')
|
||||
})
|
||||
|
||||
test('writing a purpose clears "needs description"', async () => {
|
||||
const mystery = await entry('mystery_cookie')
|
||||
await payload.update({ id: mystery.id, collection: SLUG, data: { purpose: 'Czat na stronie' } as never, locale: 'pl' as never })
|
||||
expect((await entry('mystery_cookie')).needsDescription).toBe(false)
|
||||
})
|
||||
|
||||
test('a changed suggestion asks again; approving never overwrites the cookie banner text', async () => {
|
||||
await approveCookies({ payload }) // yt-* too
|
||||
const before = (await list('pl')).find((r) => r.name === 'yt-*')!
|
||||
await runCookieScan({ options: { declarations: [youtube({ en: 'YouTube player', pl: 'Odtwarzacz YouTube' })] }, payload, plugin })
|
||||
const { pending } = await loadCookieApproval({ locale: 'pl', payload })
|
||||
expect(pending.map((p) => [p.name, p.change])).toEqual([['yt-*', 'changed']])
|
||||
await approveCookies({ payload })
|
||||
expect((await list('pl')).find((r) => r.name === 'yt-*')?.purpose).toBe(before.purpose)
|
||||
expect((await loadCookieApproval({ locale: 'pl', payload })).pending).toEqual([])
|
||||
})
|
||||
|
||||
test('a cookie no longer found is only flagged: nothing is deleted', async () => {
|
||||
const rows = (await list('pl')).length
|
||||
const entries = (await payload.count({ collection: SLUG })).totalDocs
|
||||
const { summary } = await runCookieScan({ options: { declarations: [] }, payload, plugin })
|
||||
expect(summary.gone).toBe(1)
|
||||
const { gone, pending } = await loadCookieApproval({ locale: 'pl', payload })
|
||||
expect(gone.map((g) => g.name)).toEqual(['yt-*'])
|
||||
expect(pending).toEqual([])
|
||||
expect((await list('pl')).length).toBe(rows)
|
||||
expect((await payload.count({ collection: SLUG })).totalDocs).toBe(entries)
|
||||
// Found again → the flag goes away.
|
||||
await runCookieScan({ options: { declarations: [youtube({ en: 'YouTube player', pl: 'Odtwarzacz YouTube' })] }, payload, plugin })
|
||||
expect((await entry('yt-*')).change).toBeNull()
|
||||
})
|
||||
|
||||
test('the endpoint: editors only; approves what it is given', async () => {
|
||||
const [get, post] = buildCookieApprovalEndpoints({})
|
||||
const call = (e: typeof get, user: unknown, body: unknown = {}) =>
|
||||
e.handler({ json: async () => body, payload, query: { locale: 'en' }, user } as never) as Promise<Response>
|
||||
expect((await call(get, null)).status).toBe(403)
|
||||
expect((await call(post, { collection: 'users', roles: ['user'] })).status).toBe(403)
|
||||
await runCookieScan({ names: ['late_cookie'], payload, plugin })
|
||||
const editor = { collection: 'users', roles: ['editor'] }
|
||||
const listed = (await (await call(get, editor)).json()) as { pending: { id: number; name: string }[] }
|
||||
expect(listed.pending.map((p) => p.name)).toEqual(['late_cookie'])
|
||||
const res = (await (await call(post, editor, { ids: [listed.pending[0].id] })).json()) as { result: { added: number } }
|
||||
expect(res.result.added).toBe(1)
|
||||
})
|
||||
})
|
||||
|
||||
describe('cookie approval — optional', () => {
|
||||
const config = (cookieScanner: unknown) =>
|
||||
ipalKit({ cookieScanner: cookieScanner as never, i18n, twoFactor: false })({ collections: [{ slug: 'users', auth: true, fields: [] }] } as unknown as Config)
|
||||
|
||||
test('on by default: the view, its endpoint and the dashboard reminder', async () => {
|
||||
const c = await config(true)
|
||||
expect(c.admin?.components?.views?.ipalCookieApproval).toMatchObject({ path: '/cookie-approval' })
|
||||
expect(c.endpoints?.some((e) => e.path === '/ipal/cookie-approval')).toBe(true)
|
||||
expect(c.admin?.components?.beforeDashboard).toEqual(
|
||||
expect.arrayContaining([expect.objectContaining({ path: '@intecion/ipal-kit/admin#CookieCrawlAlert' })]),
|
||||
)
|
||||
})
|
||||
|
||||
test('approval: false keeps per-entry review only', async () => {
|
||||
const c = await config({ approval: false })
|
||||
expect(c.admin?.components?.views?.ipalCookieApproval).toBeUndefined()
|
||||
expect(c.endpoints?.some((e) => e.path === '/ipal/cookie-approval')).toBe(false)
|
||||
expect((c.admin?.components?.beforeDashboard ?? []).some((x) => JSON.stringify(x).includes('CookieCrawlAlert'))).toBe(false)
|
||||
})
|
||||
|
||||
test('own category for unknown cookies; no dashboard reminder', async () => {
|
||||
const c = await config({ approval: { dashboard: false, unknownCategory: 'analytics' } })
|
||||
expect(JSON.stringify(c.admin?.components?.views?.ipalCookieApproval)).toContain('"unknownCategory":"analytics"')
|
||||
expect((c.admin?.components?.beforeDashboard ?? []).some((x) => JSON.stringify(x).includes('CookieCrawlAlert'))).toBe(false)
|
||||
})
|
||||
})
|
||||
@@ -157,7 +157,9 @@ describe('cookie crawl — panel button → service → results', () => {
|
||||
expect((await payload.count({ collection: 'cookie-review' as never })).totalDocs).toBe(before)
|
||||
const crawl = (await payload.findGlobal({ slug: 'cookie-crawl' as never })) as unknown as CrawlDoc
|
||||
expect(crawl.summary.violations).toBe(0)
|
||||
expect(await CookieCrawlAlert({ payload })).toBeNull()
|
||||
// No crawl problem left; only the approval reminder remains (drafts from the first crawl wait).
|
||||
expect(await CookieCrawlAlert({ approval: false, payload })).toBeNull()
|
||||
expect(await CookieCrawlAlert({ crawl: false, payload })).not.toBeNull()
|
||||
})
|
||||
|
||||
test('a failed crawl is reported and the next one may start', async () => {
|
||||
|
||||
@@ -206,7 +206,8 @@ describe('cookie scanner — labels and config', () => {
|
||||
expect(review?.admin?.components?.beforeListTable).toEqual([
|
||||
expect.objectContaining({ path: '@intecion/ipal-kit/admin#CookieScanButton' }),
|
||||
])
|
||||
expect(review?.hooks?.afterChange).toEqual([])
|
||||
// No accept → cookie list hook; only the hook that fills empty locales (fillEmptyLocales).
|
||||
expect(review?.hooks?.afterChange).toHaveLength(1)
|
||||
expect(config.endpoints?.filter((e) => e.path === '/ipal/cookie-scan').map((e) => e.method).sort()).toEqual(['get', 'post'])
|
||||
})
|
||||
})
|
||||
|
||||
@@ -132,7 +132,8 @@ describe('cookie scanner against a real Payload', () => {
|
||||
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')
|
||||
// The editor wrote Polish only; saving filled the empty English text from it (fillEmptyLocales) — the scan keeps it.
|
||||
expect((await cookieList('en')).find((c) => c.name === '_ga')?.purpose).toBe('Tekst redaktora')
|
||||
})
|
||||
|
||||
test('an entry without a category cannot be accepted', async () => {
|
||||
|
||||
@@ -0,0 +1,142 @@
|
||||
/**
|
||||
* Text written in one language fills the empty languages (cookie list, cookie
|
||||
* review), never one that has its own text — through a REAL Payload (SQLite,
|
||||
* pl + en + de). Plus the combined "Cookies" admin layout (config only).
|
||||
*/
|
||||
import type { Config, Field, GlobalConfig, Payload, Tab } from 'payload'
|
||||
|
||||
import { sqliteAdapter } from '@payloadcms/db-sqlite'
|
||||
import { lexicalEditor } from '@payloadcms/richtext-lexical'
|
||||
import os from 'os'
|
||||
import path from 'path'
|
||||
import { getPayload } from 'payload'
|
||||
import { afterAll, beforeAll, describe, expect, test, vi } from 'vitest'
|
||||
|
||||
import type { I18nConfig } from '../src/modules/i18n/types.js'
|
||||
|
||||
import { suggestionFor } from '../src/modules/consent/scanner/merge.js'
|
||||
import { addToCookieList } from '../src/modules/consent/scanner/sync.js'
|
||||
import { ipalKit } from '../src/plugin.js'
|
||||
import { buildTestConfig } from './helpers.js'
|
||||
|
||||
vi.mock('server-only', () => ({}))
|
||||
|
||||
const i18n: I18nConfig = {
|
||||
defaultLocale: 'pl',
|
||||
locales: [
|
||||
{ code: 'pl', label: 'Polski' },
|
||||
{ code: 'en', label: 'English' },
|
||||
{ code: 'de', label: 'Deutsch' },
|
||||
],
|
||||
}
|
||||
|
||||
type Row = { category?: string; duration?: null | string; id?: string; name: string; purpose?: null | string }
|
||||
|
||||
let payload: Payload
|
||||
const list = async (locale: string) =>
|
||||
((await payload.findGlobal({ slug: 'cookie-settings' as never, fallbackLocale: false as never, locale: locale as never })) as { cookies?: Row[] }).cookies ?? []
|
||||
const row = async (locale: string, name: string) => (await list(locale)).find((r) => r.name === name)
|
||||
const save = async (locale: string, rows: Row[]) =>
|
||||
payload.updateGlobal({ slug: 'cookie-settings' as never, data: { cookies: rows } as never, locale: locale as never })
|
||||
|
||||
beforeAll(async () => {
|
||||
payload = await getPayload({
|
||||
config: buildTestConfig({
|
||||
collections: [
|
||||
{ slug: 'users', auth: true, fields: [] },
|
||||
{ slug: 'media', fields: [], upload: { staticDir: path.join(os.tmpdir(), 'ipal-test-media') } },
|
||||
],
|
||||
db: sqliteAdapter({ client: { url: 'file::memory:' }, push: true }),
|
||||
editor: lexicalEditor(),
|
||||
plugins: [ipalKit({ access: { authCollection: 'users' }, cookieScanner: true, i18n, twoFactor: false })],
|
||||
secret: 'fill-locales-test-secret',
|
||||
telemetry: false,
|
||||
}),
|
||||
})
|
||||
}, 60_000)
|
||||
|
||||
afterAll(async () => {
|
||||
await payload?.destroy()
|
||||
})
|
||||
|
||||
describe('fill empty locales — cookie list', () => {
|
||||
test('a row added in Polish gets the same text in English and German', async () => {
|
||||
await save('pl', [{ name: 'chat_id', category: 'functional', duration: '1 rok', purpose: 'Okno czatu' }])
|
||||
expect(await row('en', 'chat_id')).toMatchObject({ duration: '1 rok', purpose: 'Okno czatu' })
|
||||
expect(await row('de', 'chat_id')).toMatchObject({ duration: '1 rok', purpose: 'Okno czatu' })
|
||||
})
|
||||
|
||||
test('a language with its own text is never overwritten; each can still be changed alone', async () => {
|
||||
const en = await list('en')
|
||||
await save('en', en.map((r) => (r.name === 'chat_id' ? { ...r, duration: '1 year', purpose: 'Chat window' } : r)))
|
||||
expect(await row('en', 'chat_id')).toMatchObject({ duration: '1 year', purpose: 'Chat window' })
|
||||
expect(await row('pl', 'chat_id')).toMatchObject({ duration: '1 rok', purpose: 'Okno czatu' })
|
||||
expect(await row('de', 'chat_id')).toMatchObject({ purpose: 'Okno czatu' }) // already had text: kept
|
||||
})
|
||||
|
||||
test('the source is the language just edited, not the default one', async () => {
|
||||
const en = await list('en')
|
||||
await save('en', [...en, { name: 'map_id', category: 'marketing', purpose: 'Embedded map' }])
|
||||
expect((await row('pl', 'map_id'))?.purpose).toBe('Embedded map')
|
||||
expect((await row('de', 'map_id'))?.purpose).toBe('Embedded map')
|
||||
})
|
||||
|
||||
test('scanner writes: a language without its own text gets the default language’s text', async () => {
|
||||
const s = suggestionFor({ name: 'x', purpose: { en: 'EN', pl: 'PL' }, retention: '1 day', source: 'project', storage: 'cookie' }, ['pl', 'en', 'de'])
|
||||
expect(s.purpose).toEqual({ de: 'PL', en: 'EN', pl: 'PL' })
|
||||
expect(s.retention).toEqual({ de: '1 day', en: '1 day', pl: '1 day' })
|
||||
await addToCookieList({ entry: { name: 'only_pl', category: 'analytics', purpose: { pl: 'Tylko po polsku' } }, payload })
|
||||
expect((await row('en', 'only_pl'))?.purpose).toBe('Tylko po polsku')
|
||||
expect((await row('de', 'only_pl'))?.purpose).toBe('Tylko po polsku')
|
||||
})
|
||||
})
|
||||
|
||||
describe('fill empty locales — cookie review', () => {
|
||||
test('an entry described in English gets the text in the empty languages', async () => {
|
||||
const created = (await payload.create({ collection: 'cookie-review' as never, data: { name: 'widget', storage: 'cookie' } as never, locale: 'pl' as never })) as { id: number }
|
||||
await payload.update({ id: created.id, collection: 'cookie-review' as never, data: { purpose: 'Support widget', retention: '30 days' } as never, locale: 'en' as never })
|
||||
const pl = (await payload.findByID({ id: created.id, collection: 'cookie-review' as never, fallbackLocale: false as never, locale: 'pl' as never })) as { purpose?: string; retention?: string }
|
||||
expect(pl).toMatchObject({ purpose: 'Support widget', retention: '30 days' })
|
||||
})
|
||||
})
|
||||
|
||||
describe('options', () => {
|
||||
const build = (extra: Record<string, unknown>) =>
|
||||
ipalKit({ i18n, twoFactor: false, ...extra } as never)({ collections: [{ slug: 'users', auth: true, fields: [] }] } as unknown as Config)
|
||||
const global = (c: Config, slug: string) => c.globals!.find((g) => g.slug === slug)!
|
||||
const tabs = (g: GlobalConfig) => (g.fields.find((f) => f.type === 'tabs') as { tabs: Tab[] } & Field).tabs
|
||||
|
||||
test('fillEmptyLocales: false removes the hook; an object picks the fields', async () => {
|
||||
expect(global(await build({}), 'cookie-settings').hooks?.afterChange).toHaveLength(1)
|
||||
expect(global(await build({ fillEmptyLocales: false }), 'cookie-settings').hooks?.afterChange ?? []).toHaveLength(0)
|
||||
expect(global(await build({ fillEmptyLocales: { 'cookie-settings': [] } }), 'cookie-settings').hooks?.afterChange ?? []).toHaveLength(0)
|
||||
})
|
||||
|
||||
test('combined layout (default): one Cookies entry with Review and approve + Site check tabs', async () => {
|
||||
const c = await build({ cookieScanner: { crawl: true } })
|
||||
const cookies = global(c, 'cookie-settings')
|
||||
expect(cookies.label).toEqual({ en: 'Cookies', pl: 'Cookies' })
|
||||
const labels = tabs(cookies).map((t) => (t.label as Record<string, string>).en)
|
||||
expect(labels.slice(-2)).toEqual(['Review and approve', 'Site check'])
|
||||
expect(c.collections!.find((x) => x.slug === 'cookie-review')!.admin?.group).toBe(false)
|
||||
expect(global(c, 'cookie-crawl').admin?.group).toBe(false)
|
||||
// Pages and API stay: the approval view and the endpoints are still there.
|
||||
expect(c.admin?.components?.views?.ipalCookieApproval).toBeTruthy()
|
||||
expect(c.endpoints?.some((e) => e.path === '/ipal/cookie-crawl')).toBe(true)
|
||||
})
|
||||
|
||||
test('no crawl → no Site check tab; approval: false → the tab shows the scan and the list link only', async () => {
|
||||
const c = await build({ cookieScanner: { approval: false } })
|
||||
const review = tabs(global(c, 'cookie-settings')).at(-1)!
|
||||
expect((review.label as Record<string, string>).en).toBe('Review and approve')
|
||||
expect(JSON.stringify(review.fields)).toContain('"approval":false')
|
||||
})
|
||||
|
||||
test("'separate' keeps every entry in the navigation and no extra tabs; the project's group wins", async () => {
|
||||
const c = await build({ cookieScanner: { adminLayout: 'separate', crawl: true } })
|
||||
expect(tabs(global(c, 'cookie-settings')).map((t) => (t.label as Record<string, string>).en)).not.toContain('Review and approve')
|
||||
expect(c.collections!.find((x) => x.slug === 'cookie-review')!.admin?.group).toEqual({ en: 'Privacy', pl: 'Prywatność' })
|
||||
const own = await build({ cookieScanner: { collectionOverrides: { admin: { group: 'Legal' } } } })
|
||||
expect(own.collections!.find((x) => x.slug === 'cookie-review')!.admin?.group).toBe('Legal')
|
||||
})
|
||||
})
|
||||
Reference in New Issue
Block a user