Compare commits

...
13 Commits
Author SHA1 Message Date
Radosław SmolińskiandClaude Opus 5.5 a9e1adc03b 1.14.3 upgrade notes
CI / check (push) Canceled after 0s
ipal-upgrade: "→ 1.14.3" section for the cookie approval flow. PROGRAMISTA §6:
item 52.

Co-Authored-By: Claude Opus 5.5 <[email protected]>
2026-10-28 22:26:53 +01:00
Radosław SmolińskiandClaude Opus 5.5 44598bbef2 1.14.3
Version bump and CHANGELOG entry: Approve cookies page with one Approve and add,
New/Changed/Needs description/No longer found markers, unknownCategory,
dashboard and e-mail reminders, approval: false, new exports, the lookup change
for hand-typed rows, and what projects with cookieScanner update.

Co-Authored-By: Claude Opus 5.5 <[email protected]>
2026-10-28 22:26:53 +01:00
Radosław Smoliński 5f4f2a07ab Merge claude/cookie-approve: one approval for everything a cookie scan finds
/admin/cookie-approval (Approve cookies): one "Approve and add" for the ticked
cookies into Cookie banner -> Cookies in every locale; statuses New, Changed,
Needs description, No longer found; never overwrites editor text, never
duplicates or deletes. Unknown cookies -> approval.unknownCategory (default
marketing). Dashboard and e-mail reminders. cookieScanner.approval: false keeps
the per-entry review. New cookie-review fields change and needsDescription
(Postgres: one enum column + index, one boolean).
2026-10-28 22:23:24 +01:00
Radosław SmolińskiandClaude Opus 5.5 9b9c5fc872 Dev app: import map entry for the cookie approval view
Co-Authored-By: Claude Opus 5.5 <[email protected]>
2026-10-28 22:20:51 +01:00
Radosław SmolińskiandClaude Opus 5.5 86ff3f5ff7 Cookie scanner: one approval for everything a scan finds
After "Scan cookies" or a site check, the new Approve cookies view
(/admin/cookie-approval) lists what waits, grouped by consent category, with
provider, purpose and duration and New / Changed / Needs description markers.
One "Approve and add" puts every ticked cookie into Cookie banner -> Cookie
list in every locale. That list feeds the cookie policy table and the
detailed settings window.

- Never overwrites editor text or categories, never adds a second row (a
  pattern and a concrete name are the same cookie), never deletes.
- Unknown cookies are approved into a category that needs consent
  (approval.unknownCategory, default marketing) and flagged Needs
  description; writing a purpose clears the flag.
- Cookies a scan or crawl no longer finds are flagged No longer found, for
  review only.
- The dashboard and the crawl e-mail say how many cookies wait and link to
  the view; nothing is added without approval.
- Optional: cookieScanner.approval false keeps per-entry review.
- Migration: cookie-review gains change and needsDescription.

Co-Authored-By: Claude Opus 5.5 <[email protected]>
2026-10-28 22:17:46 +01:00
Radosław SmolińskiandClaude Opus 5.5 0e7966dfbb 1.14.2 upgrade notes
CI / check (push) Canceled after 0s
ipal-upgrade, PROGRAMISTA §6 item 51 and security.md point at 1.14.2 instead of
"after 1.14.1".

Co-Authored-By: Claude Opus 5.5 <[email protected]>
2026-10-28 21:34:09 +01:00
Radosław SmolińskiandClaude Opus 5.5 2cadb425d6 1.14.2
Version bump; the Unreleased section becomes 1.14.2: 2FA setup-loop fix
(TotpRedirectProvider), twoFactor.provider, totpRedirectTarget/totpAdminPath,
known issue (low deepmerge advisory via payload), what projects with 2FA update.

Co-Authored-By: Claude Opus 5.5 <[email protected]>
2026-10-28 21:34:09 +01:00
Radosław Smoliński 41065940e8 Merge claude/recursing-wright-be31dd: fix the 2FA setup loop
ipal-kit swaps @clocklimited/payload-2fa's TOTPProvider (it read the path from an
x-pathname header nothing sets on /admin, so setup-totp?back=null redirected to
itself) for TotpRedirectProvider (/admin), which reads the path in the browser.
twoFactor.provider: own component, or false to keep the package's. Pure rules:
totpRedirectTarget, totpAdminPath. Server-side TOTP enforcement (the package's
access wrapper) is unchanged. Dev app: IPAL_DEV_2FA=1 turns 2FA on.
2026-10-28 21:30:03 +01:00
Radosław SmolińskiandClaude Opus 5.5 60f744e3ad Fix the 2FA setup loop: setup-totp?back=null redirected to itself
@clocklimited/payload-2fa's admin provider reads the current path from an
x-pathname request header. Nothing sets it on /admin (the createProxy matcher
skips /admin), so the path was null: every admin page, the setup screen too,
redirected to /admin/setup-totp?back=null, forever. Every new admin on a site
with 2FA got stuck.

ipalKit now swaps that provider for its own TotpRedirectProvider
(@intecion/ipal-kit/admin, client-side): it reads the path in the browser,
never redirects away from the setup/verify screens or logout, and renders
nothing while redirecting. twoFactor.provider takes a project component, or
false to keep the package's. totpRedirectTarget / totpAdminPath export the
rules. Projects run generate:importmap.

Test: test/totpRedirect.test.ts (redirect walk, provider swap). Dev app:
IPAL_DEV_2FA=1 turns 2FA on. Docs: security.md, CHANGELOG (Unreleased),
AGENT.md, ipal-setup/-upgrade/-debug/-reference, PROGRAMISTA item 51.

Co-Authored-By: Claude Opus 5.5 <[email protected]>
2026-10-28 21:27:19 +01:00
Radosław SmolińskiandClaude Opus 5.5 4e254057f9 1.14.1 upgrade notes
CI / check (push) Canceled after 0s
ipal-upgrade: the X-Powered-By/CSP section is now "→ 1.14.1". PROGRAMISTA §6:
item 50 for 1.14.1.

Co-Authored-By: Claude Opus 5.5 <[email protected]>
2026-10-27 21:53:22 +01:00
Radosław SmolińskiandClaude Opus 5.5 cdf80744ea 1.14.1
Version bump and CHANGELOG entry: withSecurityConfig (hide X-Powered-By),
opt-in CSP through buildSecurityHeaders({ csp }) with report-only/enforce and
reports, createCspReportRoute, buildAdminCspHeaders, opt-in nonces, new buildCsp
flags with extra/override, ipal-audit header check; nothing required on upgrade.

Co-Authored-By: Claude Opus 5.5 <[email protected]>
2026-10-27 21:53:22 +01:00
Radosław Smoliński 86ff9e3df0 Merge claude/csp-powered-by-ee307c: hide X-Powered-By, opt-in CSP with reports, admin policy, nonces
withSecurityConfig hides X-Powered-By (hidePoweredBy: false to keep it).
buildSecurityHeaders({ csp }) is off unless passed; report-only first, then
enforce, with reportUri / Reporting-Endpoints. buildCsp flags with extra and
override, buildAdminCsp(Headers), createCspReportRoute. Nonces only with
createProxy({ csp }) + SiteProviders nonce, so static and ISR pages stay static.
2026-10-27 21:37:39 +01:00
Radosław SmolińskiandClaude Opus 5.5 ff4c595b91 Security: hide X-Powered-By, CSP report-only with reports, admin policy and nonces
- withSecurityConfig: poweredByHeader false + strips X-Powered-By from headers()
  (Next's and withPayload's), works on either side of withPayload
- buildSecurityHeaders({ csp }): CSP + Reporting-Endpoints; mode switches
  report-only → enforce
- buildCsp: reportUri/reportGroup, nonce + strict-dynamic, dev unsafe-eval,
  metaPixel/linkedIn/tiktok/clarity flags, media-src for R2, override
- buildAdminCsp(Headers): looser policy for Payload admin (Monaco CDN, blob workers)
- createCspReportRoute + parseCspReports: report collector for both formats
- createProxy({ csp }) + createCspNonce: per-request nonce, x-nonce header;
  SiteProviders/ThemeScript/Analytics/ConsentScript accept nonce
- docs: security.md, AGENT.md, ipal-setup/reference/upgrade; ipal-audit checks

Co-Authored-By: Claude Opus 5.5 <[email protected]>
2026-10-27 21:28:11 +01:00
53 changed files with 2694 additions and 309 deletions
+10
View File
@@ -1,3 +1,4 @@
import { TOTPField as TOTPField_3eb2cc20d1a2569c2ccbafcee15bd128 } from '@clocklimited/payload-2fa/rsc'
import { OverviewComponent as OverviewComponent_a8a977ebc872c5d5ea7ee689724c0860 } from '@payloadcms/plugin-seo/client'
import { MetaTitleComponent as MetaTitleComponent_a8a977ebc872c5d5ea7ee689724c0860 } from '@payloadcms/plugin-seo/client'
import { MetaDescriptionComponent as MetaDescriptionComponent_a8a977ebc872c5d5ea7ee689724c0860 } from '@payloadcms/plugin-seo/client'
@@ -37,11 +38,16 @@ import { StatsNavLink as StatsNavLink_7568fe47d582ff15ce85d2e1873c2c23 } from '@
import { CookieCrawlAlert as CookieCrawlAlert_7568fe47d582ff15ce85d2e1873c2c23 } from '@intecion/ipal-kit/admin'
import { StatsWidget as StatsWidget_7568fe47d582ff15ce85d2e1873c2c23 } from '@intecion/ipal-kit/admin'
import { IntegrationAlerts as IntegrationAlerts_7568fe47d582ff15ce85d2e1873c2c23 } from '@intecion/ipal-kit/admin'
import { 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 { StatsView as StatsView_7568fe47d582ff15ce85d2e1873c2c23 } from '@intecion/ipal-kit/admin'
import { CollectionCards as CollectionCards_f9c02e79a4aed9a3924487c0cd4cafb1 } from '@payloadcms/next/rsc'
/** @type import('payload').ImportMap */
export const importMap = {
"@clocklimited/payload-2fa/rsc#TOTPField": TOTPField_3eb2cc20d1a2569c2ccbafcee15bd128,
"@payloadcms/plugin-seo/client#OverviewComponent": OverviewComponent_a8a977ebc872c5d5ea7ee689724c0860,
"@payloadcms/plugin-seo/client#MetaTitleComponent": MetaTitleComponent_a8a977ebc872c5d5ea7ee689724c0860,
"@payloadcms/plugin-seo/client#MetaDescriptionComponent": MetaDescriptionComponent_a8a977ebc872c5d5ea7ee689724c0860,
@@ -81,6 +87,10 @@ export const importMap = {
"@intecion/ipal-kit/admin#CookieCrawlAlert": CookieCrawlAlert_7568fe47d582ff15ce85d2e1873c2c23,
"@intecion/ipal-kit/admin#StatsWidget": StatsWidget_7568fe47d582ff15ce85d2e1873c2c23,
"@intecion/ipal-kit/admin#IntegrationAlerts": IntegrationAlerts_7568fe47d582ff15ce85d2e1873c2c23,
"@intecion/ipal-kit/admin#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#StatsView": StatsView_7568fe47d582ff15ce85d2e1873c2c23,
"@payloadcms/next/rsc#CollectionCards": CollectionCards_f9c02e79a4aed9a3924487c0cd4cafb1
}
+3 -1
View File
@@ -1,3 +1,4 @@
import { payloadTotp } from '@clocklimited/payload-2fa'
import { sqliteAdapter } from '@payloadcms/db-sqlite'
import { lexicalEditor } from '@payloadcms/richtext-lexical'
import { ipalKit } from '../src/index.js'
@@ -73,7 +74,8 @@ export default buildConfig({
seo: { collections: ['posts', 'pages'] },
stats: true,
// 2FA is enforced by default; the dev sandbox opts out so it boots without an authenticator.
twoFactor: false,
// IPAL_DEV_2FA=1 turns it on (first-login setup and verify screens).
twoFactor: process.env.IPAL_DEV_2FA ? { issuer: 'ipal-kit dev', plugin: payloadTotp } : false,
}),
],
secret: process.env.PAYLOAD_SECRET || 'test-secret_key',
+130
View File
@@ -8,6 +8,136 @@ 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.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
- **2FA setup loop.** A user without TOTP (every new admin) was sent to `/admin/setup-totp?back=null`, and that page
redirected to itself forever. `@clocklimited/payload-2fa`'s admin provider reads the path from an `x-pathname`
request header, which nothing sets on `/admin` (the `createProxy` matcher skips it). ipal-kit now swaps in its own
provider, `TotpRedirectProvider` (`@intecion/ipal-kit/admin`): it reads the path in the browser, never redirects
away from the setup or verify screen or from logout, and renders nothing while a redirect is pending.
### New
- **`twoFactor.provider`** — your own redirect component (path or `{ path, clientProps, serverProps }`), or `false`
to keep the package's (then set `x-pathname` on `/admin` yourself). **`totpRedirectTarget` / `totpAdminPath`** —
the redirect rules as a pure function, for your own provider.
### Known issue
- `pnpm audit --prod` reports one **low** advisory: `deepmerge` 4.2.0–4.3.1, prototype poisoning in `mergeObject()`
(GHSA-gcqx-w48m-w2h4), reached through `payload` (`@clocklimited/payload-2fa` → `payload` → `deepmerge`). No patched
version exists yet; nothing to do in projects until Payload or `deepmerge` ships a fix.
### What projects must update
- **Projects with 2FA on:** `pnpm payload generate:importmap` (adds `@intecion/ipal-kit/admin#TotpRedirectProvider`),
commit `importMap.js`, `rm -rf .next`, redeploy on Coolify. **Check:** a new admin lands on
`/admin/setup-totp?back=%2Fadmin` and sees the QR code. Remove an own `x-pathname` rule on `/admin` if one was added
as a workaround.
- Projects without 2FA (`twoFactor: false`): nothing.
## 1.14.1
Response-header hardening from the intecion.com audit: hide `X-Powered-By`, and a Content-Security-Policy the project
can roll out safely (report-only first, with reports). Everything is opt-in; nothing changes until the project uses it.
### New
- **`withSecurityConfig(nextConfig, { hidePoweredBy })`** — hides `X-Powered-By` (Next's `Next.js` and the
`Next.js, Payload` that `withPayload` adds) by setting `poweredByHeader: false` and dropping the header from
`headers()` rules. Works on either side of `withPayload`. Opt out: `hidePoweredBy: false`.
- **`buildSecurityHeaders({ csp })`** — off by default (`csp: false`). Pass `buildCsp` args to add the policy:
`mode: 'report-only'` (`Content-Security-Policy-Report-Only`) or `'enforce'`; with `reportUri` the policy gets
`report-uri` / `report-to` and the `Reporting-Endpoints` header is added (`reportGroup`, default
`csp-endpoint`). A hand-written policy in `additional` still wins.
- **`createCspReportRoute()`** — a POST route for violation reports (both the legacy `application/csp-report` and the
Reporting API format), logged as one `[csp]` line each (`onReport` to send them elsewhere, `maxBytes`); `parseCspReports` for your own handler.
- **`buildAdminCspHeaders` / `buildAdminCsp`** — a policy for `/admin/:path*` that fits Payload's admin, with the same
`mode` / `reportUri` / `extra` / `override`.
- **Nonces (opt-in)** — `createProxy(config, { csp })` creates a per-request nonce, puts the policy on the request (Next
adds the nonce to its own scripts) and the response, and exposes it as the `x-nonce` request header;
`<SiteProviders nonce>` passes it to the theme script and the analytics tags (`ThemeScript`, `Analytics`,
`ConsentScript` take `nonce`). `strictDynamic` (default on with a nonce). Nonces need dynamic rendering, so they are
only for sites that render per request; static and ISR sites keep the header-only CSP. `createCspNonce`,
`CSP_NONCE_HEADER`.
- **`buildCsp` flags** — `metaPixel`, `linkedIn`, `tiktok`, `clarity` next to `analytics`, `turnstile`, `youtube`,
`googleMaps`, `r2Url`; `dev` (adds `'unsafe-eval'`, default `NODE_ENV === 'development'`); `extra` adds sources
to any directive; `override` replaces a directive (`null` drops it). `buildCspHeaders`, `buildReportingEndpoints`,
`cspHeaderKey`, types `CspDirective`, `CspSources`, `CspViolation`.
- **ipal-audit** — checks the response headers: `X-Powered-By` anywhere → ERROR; no CSP on the site or `/admin` →
WARNING; report-only for weeks with clean reports → WARNING (switch to enforce).
### Changed
- `buildCsp` allowlists are slightly wider (nothing that was allowed is now blocked): `analytics` also allows the
Google Signals hosts (`https://*.g.doubleclick.net`, `https://www.google.com`) in `connect-src` and `img-src`;
`r2Url` is also added to `media-src`; in development `'unsafe-eval'` is added (`dev: false` to turn it off).
The order of the directives in the header changed (cosmetic).
- `buildSecurityHeaders({})` output is unchanged.
### Documentation
- security.md rewritten: X-Powered-By, CSP roll-out (report-only → enforce), report route, admin policy, nonces vs
static pages. AGENT.md, ipal-setup, ipal-reference, ipal-audit, ipal-upgrade.
### What projects must update
Nothing is required. Recommended, in this order (ipal-upgrade → 1.14.1, security.md):
1. **Hide `X-Powered-By`:** `export default withPayload(withSecurityConfig(nextConfig))`; remove a hand-written
`poweredByHeader: false`. **Check:** `curl -sI <site>/pl | grep -i x-powered-by` → nothing (also `/admin`).
2. **CSP report-only:** `buildSecurityHeaders({ csp: { mode: 'report-only', reportUri: '/api/csp-report', r2Url:
process.env.R2_PUBLIC_URL, …flags for what the site loads } })`, the admin rule
`{ source: '/admin/:path*', headers: buildAdminCspHeaders({ mode: 'report-only', reportUri: '/api/csp-report' }) }`
and `src/app/api/csp-report/route.ts` → `export const POST = createCspReportRoute()`. Deploy and read the `[csp]`
lines in the Coolify logs.
3. **Enforce:** after a few days of clean reports, `mode: 'enforce'` in both places; redeploy and check the pages.
4. Projects that already call `buildCsp({ analytics })` or pass `r2Url`: the policy gets the wider allowlists above
after upgrading — review them if the policy is audited line by line.
## 1.14.0
An image lightbox, a cookie scanner with a browser pre-consent check, an admin panel in English and Polish, and
+20 -8
View File
@@ -108,8 +108,8 @@ 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` |
| 13 | Security | `buildSecurityHeaders` in `next.config.ts`; `twoFactor: { issuer, plugin: payloadTotp }`; CSP `report-only` → `enforce`; `IPAL_IP_HEADER` in production | security.md, forms.md | A |
| 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; Cookie banner → 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 |
| 16 | **Nothing hardcoded** | every text, link, image, file, company data from the panel; domains and keys from `.env` (§2) | — | A, P |
@@ -146,7 +146,7 @@ In the project's `AGENTS.md`, under "Project decisions", one line with the item
ipal-audit-skip: mcp, llms-full — the client does not want to share content with AI agents (email 2026-03-02)
```
Keys: `llms`, `llms-full`, `markdown`, `mcp`, `jsonld`, `r2`, `turnstile`,
`analytics`, `twofactor`, `aibots`, `forms-seed` (`audit.sh` understands only these). Without this line a missing item is an error.
`analytics`, `twofactor`, `aibots`, `forms-seed`, `csp` (`audit.sh` understands only these). Without this line a missing item is an error.
---
@@ -937,7 +937,8 @@ project → **plugin gap**, not a copy.
| Image / video in `<Media>` | `mediaImageProps`, `videoProps`, `MEDIA_SIZES` | storage.md |
| Enlarge an image (card, gallery, product, rich text) | `<SiteProviders lightbox>` + `<LightboxTrigger group image={lightboxImage(media, { size })}>` (`/client`), `RenderRichText lightbox`, `useLightbox`; labels: `ipalKit({ lightbox: true })` → Form messages → Image viewer | lightbox.md |
| YouTube without cookies before a click | `<YouTubeEmbed>` (`/client`) | storage.md |
| `next.config` | `buildImagesConfig`, `buildSecurityHeaders`, `buildCsp`, `buildUploadSecurityHeaders` | storage.md, security.md |
| `next.config` | `buildImagesConfig`, `buildSecurityHeaders` (`csp`), `buildCsp`, `buildCspHeaders`, `buildAdminCsp` / `buildAdminCspHeaders`, `buildUploadSecurityHeaders`, `withSecurityConfig` (hides `X-Powered-By`) | storage.md, security.md |
| CSP reports, nonces | `createCspReportRoute` (`parseCspReports`, type `CspViolation`), `createProxy({ csp })` + `<SiteProviders nonce>` (dynamic pages only), `createCspNonce`, `CSP_NONCE_HEADER`, `buildReportingEndpoints`, `cspHeaderKey`, `DEFAULT_CSP_REPORT_GROUP`; types `BuildAdminCspArgs`, `CspDirective`, `CspSources`, `CreateCspReportRouteArgs`, `WithSecurityConfigOptions` | security.md |
| Fluid typography and spacing | `fluid.css` / `fluid-wide.css` (`--ipal-*` variables) | PROGRAMISTA §2.5 |
**Consent, analytics, operations**
@@ -947,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 |
@@ -962,8 +963,16 @@ table from the panel (`<CookieTable>` and the `settings="detailed"` window, scan
requires it (accessibility.md).
**Security:** 2FA enforced (`ipalKit({ twoFactor: { issuer, plugin:
payloadTotp } })`, never `twoFactor: false` without a client decision). CSP: first
`report-only`, then `enforce`; no Trusted Types (they break Turnstile/GA).
payloadTotp } })`, never `twoFactor: false` without a client decision). No `X-Powered-By`:
`withPayload(withSecurityConfig(nextConfig))`. CSP in three steps (security.md → "ROLL OUT CSP"):
(1) `buildSecurityHeaders({ csp: { mode: 'report-only', reportUri: '/api/csp-report', <flags for what the
site loads> } })`, the admin rule `{ source: '/admin/:path*', headers: buildAdminCspHeaders({ mode:
'report-only', reportUri }) }` AFTER the site-wide one, and `export const POST = createCspReportRoute()` in
`src/app/api/csp-report/route.ts`; (2) deploy, read the console and the `[csp]` lines in the Coolify logs,
add missing hosts with flags / `extra`; (3) change `mode` to `'enforce'` in both places. Check:
`curl -sI $U/pl | grep -iE 'content-security|x-powered-by'`. ISR/SSG sites keep the header policy (with
`'unsafe-inline'` — Next's inline RSC scripts cannot be hashed); nonces (`createProxy({ csp })` +
`<SiteProviders nonce>`) only on sites whose pages already render per request. No Trusted Types (they break Turnstile/GA).
### 7.1 Newer defaults — turn off / override (the plugin helps, never limits)
@@ -973,16 +982,19 @@ payloadTotp } })`, never `twoFactor: false` without a client decision). CSP: fir
| 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 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 |
| First registered account = admin | `access.firstUserAdmin: false` | `buildRolesField(defaultRole, { firstUserAdmin })` |
| 2FA on the panel's login collection, mismatch = startup error | `twoFactor: false` (discouraged) | `twoFactor.collectionSlug`, `allowCollectionMismatch: true` |
| 2FA on the panel's login collection, mismatch = startup error; redirect to the 2FA screens by `TotpRedirectProvider` | `twoFactor: false` (discouraged) | `twoFactor.collectionSlug`, `allowCollectionMismatch: true`, `twoFactor.provider` (own component, or `false` for the package's) |
| `enabled: false` keeps the schema | — | — (no endpoints, `onInit` or admin components; no DROP TABLE in `migrate:create`) |
| No client IP = one shared `unknown-ip` bucket at 20× the limit | `setUnknownIpFactor(0)` (only with a limiter in front) | `setUnknownIpFactor(n)`; `UNKNOWN_IP_FACTOR` |
| Turnstile token domain not checked | (default) | `createSubmitAction({ turnstileHostnames })`, `verifyTurnstile({ hostnames })` — leave empty in dev |
| Consent Mode `advanced` | `consentMode: 'basic'` | your own `<Analytics>` props (`SiteProviders analytics={false}`) |
| Locale cookie: consent read under its own stored version | — | `createProxy(config, { policyVersion })` / `createLocaleMiddleware({ policyVersion })` |
| No `X-Powered-By` (with `withSecurityConfig`) | `withSecurityConfig(config, { hidePoweredBy: false })` | — |
| CSP off until `buildSecurityHeaders({ csp })`; then hard rules, `'unsafe-eval'` only in dev | leave out `csp` | `buildCsp({ extra, override, strictDynamic, dev })`, `buildAdminCsp({ extra, override })`, `createCspReportRoute({ onReport, maxBytes })`, your own string via `additional` |
| Construction mode hides pages in Markdown, MCP | `markdown: { isPathVisible: () => true }`, `mcp: { isPathVisible: () => true }` | `isPathVisible`, `isPathVisibleIn(mode, path)`, `pathOf(url)`, type `PathVisibility` |
| Construction mode filters the sitemap and llms.txt | `underConstructionSeo: false` | `include` / `getIncludedPaths` in the low-level builders |
| `getSettings` at `depth: 1` | — | `createContentHelpers({ settingsDepth: 2 })` (every request pays) |
+10 -1
View File
@@ -1,6 +1,6 @@
---
name: ipal-audit
description: Audits an ipal-kit (Payload 3 + Next 16) project against AGENT.md rules with a deterministic script — the mandatory feature set (SEO, JSON-LD, llms.txt, Markdown, MCP, R2, Turnstile, panel forms, consent, 2FA, health, env), forbidden replacements (own forms, nodemailer, reCAPTCHA, hand-written JSON-LD), hardcoded texts/links, forbidden field names, monolithic sections, middleware.ts, missing ISR/generateStaticParams, hex colors, server imports in client components, extra collections, then tsc and build. Use before saying a task is done, after any block/collection/layout change, after an Impeccable pass, and when asked to review or audit the project.
description: Audits an ipal-kit (Payload 3 + Next 16) project against AGENT.md rules with a deterministic script — the mandatory feature set (SEO, JSON-LD, llms.txt, Markdown, MCP, R2, Turnstile, panel forms, consent, 2FA, health, env, security headers, X-Powered-By, CSP), forbidden replacements (own forms, nodemailer, reCAPTCHA, hand-written JSON-LD), hardcoded texts/links, forbidden field names, monolithic sections, middleware.ts, missing ISR/generateStaticParams, hex colors, server imports in client components, extra collections, then tsc and build. Use before saying a task is done, after any block/collection/layout change, after an Impeccable pass, and when asked to review or audit the project.
---
# ipal-audit
@@ -38,5 +38,14 @@ in AGENT.md §0b). Never add that line yourself just to make the audit pass.
google-analytics / googletagmanager (except Consent Mode), facebook.net,
clarity.ms, licdn, tiktok.
- **Content**: fallbacks contain no client data (`|| 'Firma X'`).
- **Response headers** (on a running build — `pnpm build && pnpm start`, or the deployed domain):
```bash
U=http://localhost:3000
for p in /pl /admin /api/health; do echo "== $p"; curl -sI "$U$p" | grep -iE 'x-powered-by|content-security-policy'; done
```
`x-powered-by` anywhere → ERROR (`withSecurityConfig`, security.md → "X-Powered-By"). No
`content-security-policy` / `content-security-policy-report-only` on `/pl` and `/admin` → WARNING (CSP not
rolled out). Report-only for more than a few weeks with clean reports → WARNING (switch to `mode: 'enforce'`).
Then open `/pl` and `/admin` in the browser: CSP lines in the console = missing sources (flags / `extra`).
Do not say "done" until the full audit (without `--quick`) has no errors.
@@ -261,6 +261,8 @@ if [ -n "$APP" ]; then
need ERROR '' "health route" "src/app/api/health/route.ts → export { healthRoute as GET } from '@/lib/content'" 'healthRoute|createHealthRoute' src/app
need ERROR '' "env validation" "src/instrumentation.ts → assertEnv(ipalEnvRules({...})) from @intecion/ipal-kit/env" 'assertEnv' src/instrumentation.ts instrumentation.ts
need ERROR '' "security headers" "next.config.ts → buildSecurityHeaders" 'buildSecurityHeaders' next.config.ts next.config.mjs next.config.js
need WARNING '' "X-Powered-By hidden" "next.config.ts → export default withPayload(withSecurityConfig(nextConfig)) — Next and withPayload send X-Powered-By: Next.js, Payload (security.md)" 'withSecurityConfig|poweredByHeader: *false' next.config.ts next.config.mjs next.config.js
need WARNING csp "Content-Security-Policy" "next.config.ts → buildSecurityHeaders({ csp: { mode: 'report-only', reportUri: '/api/csp-report', … } }) + buildAdminCspHeaders on /admin/:path*, then 'enforce' (security.md → ROLL OUT CSP)" "csp: *\\{|csp,|buildCsp|Content-Security-Policy" next.config.ts next.config.mjs next.config.js src/proxy.ts proxy.ts
# Consent, analytics, Turnstile (layout)
need ERROR '' "cookie consent" "<SiteProviders> (or ConsentProvider + CookieBanner + CookieButton) in [locale]/layout.tsx" 'SiteProviders|CookieBanner' src/app
need ERROR analytics "analytics" "<SiteProviders> (loads Analytics) or <Analytics> inside ConsentProvider" 'SiteProviders|<Analytics' src/app
+18 -9
View File
@@ -53,12 +53,19 @@ list in the panel and you check it:
2. *Privacy → Cookie review* → **Scan cookies**. "Integrations in use" must match the IDs in Site
Integrations; a filled ID that is missing → **ipal-debug**.
3. Run the browser scan below and paste every cookie it reports as unknown into **More cookie
names**, scan again. Entries with *Found by* = "Unknown — fill in" need provider, category and
purpose: ask the client, do not guess.
4. The editor accepts or rejects every draft (bulk edit works). Accepted → Cookie 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. **Review and approve** (`/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 Cookie banner → 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".
+1
View File
@@ -52,6 +52,7 @@ through this procedure. Ask only when you are missing something you cannot get y
| Symptom | Cause | Fix |
|---|---|---|
| `PayloadComponent not found in importMap` (e.g. `@intecion/ipal-kit/admin#RowLabel`) | importMap out of date after a plugin update / adding `rowLabel` | `pnpm payload generate:importmap`, restart |
| new admin stuck on `/admin/setup-totp?back=null` (the page keeps redirecting to itself) | ipal-kit ≤ 1.14.1: the 2FA package's provider needs an `x-pathname` header nothing sets on `/admin`; or `twoFactor.provider: false` without that header | update ipal-kit, `pnpm payload generate:importmap` (`TotpRedirectProvider`), restart; check: `/admin/setup-totp?back=%2Fadmin` shows the QR (security.md) |
| `Cannot destructure property 'config'` / UI hooks without context | two copies of `@payloadcms/ui` | `pnpm why @payloadcms/ui`; one version + `pnpm.overrides`; `ls node_modules/@intecion/ipal-kit/node_modules/@payloadcms` = empty |
| empty SEO tab, no Forms | mismatched `@payloadcms/*` versions | all `@payloadcms/*` = the `payload` version |
| upload rejected "Image is … Tick Optimize" | `buildOptimizeUploadHook` (intended) | tick the checkbox or prepare the file; limit in the hook options |
+11 -6
View File
@@ -33,6 +33,7 @@ description: Complete map of everything @intecion/ipal-kit provides — every ip
| `twoFactor.issuer` | — (required) | name in the authenticator app | — |
| `twoFactor.plugin` | — (required) | injected `payloadTotp` (the plugin does not import the peer) | missing function → throws |
| `twoFactor.collectionSlug` | the panel's login collection (`admin.user`, else the first auth collection) | collection with 2FA; startup fails with `[ipal] twoFactor…` when it is not an auth collection or differs from `admin.user` | point it at the login collection |
| `twoFactor.provider` | `'@intecion/ipal-kit/admin#TotpRedirectProvider'` | admin provider that sends users to `setup-totp` / `verify-totp` (path read in the browser); replaces the package's header-based one | own component path / `{ path, clientProps, serverProps }` (gets clientProps `forceSetup`); `false` keeps the package's (needs `x-pathname` on `/admin`, else `setup-totp?back=null` loops) |
| `twoFactor.allowCollectionMismatch` | `false` | allows `collectionSlug` ≠ `admin.user` (panel users of the other collection then skip 2FA) | `true` only when you protect a second auth collection on purpose |
| `whiteLabel` | none | `admin.components.graphics.Logo/Icon` (`AdminLogo`/`AdminIcon`) from Site settings + vendor credit | omit / `false`; `true` = defaults |
| `whiteLabel.settingsSlug` | `'site-settings'` | global it reads the logo/name from | — |
@@ -65,7 +66,8 @@ 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 Cookie banner → 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 Cookie banner → Cookie list (cookie-scanner.md) |
| `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 |
@@ -91,7 +93,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` |
@@ -102,6 +105,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` | — |
@@ -118,7 +122,8 @@ 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` |
| `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 |
@@ -139,8 +144,8 @@ Mandatory set: AGENT.md §0b, skill **ipal-setup**; checks: **ipal-audit**, **ip
| proxy | `src/proxy.ts` | `export const proxy = createProxy(i18nConfig, { NextResponse, markdown: true })` + `export const config = { matcher: ['/((?!api\|admin\|_next\|.*\\..*).*)'] }` (a literal!) | `curl -sI $U/` → `/pl`; `curl -s -H 'Accept: text/markdown' $U/pl` → Markdown | i18n.md, PROGRAMISTA §2.6 |
| proxy (Next 15 / custom) | `middleware`/`proxy.ts` | `createLocaleMiddleware({ config, … })` (`/next/middleware` or the main entry) | as above | i18n.md |
| env validation | `src/instrumentation.ts` | `if (process.env.NEXT_RUNTIME === 'nodejs') assertEnv(ipalEnvRules({ storage: true, ipHeader: true }))` from `@intecion/ipal-kit/env` | remove a variable → startup fails with the list of missing ones | env.md |
| Next config | `next.config.ts` | `withPayload({ images: buildImagesConfig(), htmlLimitedBots: /Googlebot\|Bingbot…/i, headers: async () => [{ source: '/:path*', headers: buildSecurityHeaders({ hsts }) }, ...buildUploadSecurityHeaders()] })` | `curl -sI $U/pl \| grep -i 'x-content-type\|strict-transport'` | security.md, storage.md, PROGRAMISTA §2.9 |
| CSP | `next.config.ts` | `buildCsp({ mode: 'report-only', … })` → later `enforce` | browser console without violations | security.md |
| Next config | `next.config.ts` | `withPayload(withSecurityConfig({ images: buildImagesConfig(), htmlLimitedBots: /Googlebot\|Bingbot…/i, headers: async () => [{ source: '/:path*', headers: buildSecurityHeaders({ hsts, csp }) }, { source: '/admin/:path*', headers: buildAdminCspHeaders(csp) }, ...buildUploadSecurityHeaders()] }))` | `curl -sI $U/pl \| grep -iE 'x-content-type\|strict-transport\|x-powered-by'` (no `x-powered-by`) | security.md, storage.md, PROGRAMISTA §2.9 |
| CSP | `next.config.ts`, `src/app/api/csp-report/route.ts` | `csp = { mode: 'report-only', reportUri: '/api/csp-report', r2Url, <flags> }` in `buildSecurityHeaders` + `buildAdminCspHeaders`; route `export const POST = createCspReportRoute()`; after clean reports `mode: 'enforce'` | `curl -sI $U/pl \| grep -i content-security-policy-report-only`; browser console and `[csp]` log lines without violations | security.md |
| data / routes | `src/lib/content.ts` | `export const { … } = createContentHelpers({ config, content, i18n: i18nConfig, baseUrl, markdownAlternate: true, summaryField: 'aiSummary', mcp: { serverName } })` | `pnpm tsc --noEmit` | frontend.md, PROGRAMISTA §2.7 |
| layout | `app/(frontend)/[locale]/layout.tsx` | `const shell = await getSiteShell(locale)`; `<SiteProviders shell={shell} logEndpoint="/api/ipal/consent" banner={<CookieBanner equalChoice settings="detailed" />} theme stats>` | HTML: `<script type="application/ld+json">` (WebSite+Organization), cookie banner | frontend.md, consent.md |
| theme | layout | `<SiteProviders theme>` (or `<ThemeScript {...shell.theme} />` from `/rsc`), `<html suppressHydrationWarning>`; switcher `<ThemeSwitcher>` (`/client`) | `data-theme` on `<html>` before hydration | theme.md |
@@ -167,7 +172,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** → Cookie banner → 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,8 +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`. |
| `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 }`. |
## Readable array rows in the panel (`admin-ui`) — details: `node_modules/@intecion/ipal-kit/docs/links.md`
@@ -135,7 +138,23 @@ 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 Cookie banner → 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. |
| `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 |
|---|---|---|
@@ -240,7 +259,7 @@ Opt-in with `ipalKit({ cookieScanner: true })`; the plugin wires the collection,
| `createPageRoute(content, { blocks, notFound, permanentRedirect, redirect?, … })` | `@intecion/ipal-kit/rsc` | ready `[[...slug]]` catch-all page → `{ Page, generateMetadata, generateStaticParams }` (blocks, slug history redirects, JSON-LD, under-construction mode); does not paginate `?page=` |
| `createNotFoundPage(content, { load } \| { blocks, fallback?, … })` | `@intecion/ipal-kit/rsc` | default export of `not-found.tsx` — the 404 page chosen in the panel or a fallback (the lazy `load` variant is recommended) |
| `renderNotFoundView(content, { blocks, fallback?, blockProps?, layoutField? }, locale)` | `@intecion/ipal-kit/rsc` | 404 content in one language — called from a server action for the lazy `createNotFoundPage({ load })` (pages.md) |
| `SiteProviders` | `@intecion/ipal-kit/rsc` | layout component: `shell={await getSiteShell(locale)}` mounts consent, cookie banner, analytics, Turnstile, site JSON-LD, theme script (and `lightbox` → `LightboxProvider`); does not mount `AlternateLinksProvider` |
| `SiteProviders` | `@intecion/ipal-kit/rsc` | layout component: `shell={await getSiteShell(locale)}` mounts consent, cookie banner, analytics, Turnstile, site JSON-LD, theme script (and `lightbox` → `LightboxProvider`); `nonce` (from `x-nonce`) goes on the theme script and the GA4/GTM tag; does not mount `AlternateLinksProvider` |
Full option lists of `createContentHelpers` / `createPageRoute` / `SiteProviders` and the returned `@/lib/content` keys: `node_modules/@intecion/ipal-kit/docs/frontend.md`.
@@ -279,7 +298,7 @@ Full option lists of `createContentHelpers` / `createPageRoute` / `SiteProviders
| `negotiateLocale({ config, cookieLocale, acceptLanguage })` | `@intecion/ipal-kit` | language choice: cookie → Accept-Language → default |
| `matchAcceptLanguage(header, config)` | `@intecion/ipal-kit` | matches the `Accept-Language` header to the configured languages |
| `LOCALE_COOKIE_NAME` | `@intecion/ipal-kit` | constant `'NEXT_LOCALE'` — cookie with the chosen language (functional, saved only with consent) |
| `createProxy(i18nConfig, { NextResponse, markdown?, exposeHeaders?, consentCategory?, cookieName?, policyVersion? })` | `@intecion/ipal-kit/next/middleware`, `@intecion/ipal-kit` | recommended `proxy.ts`: language negotiation, redirect `/` → `/{locale}`, cookie with consent, `x-locale`/`x-pathname` headers, optional Markdown routes |
| `createProxy(i18nConfig, { NextResponse, markdown?, exposeHeaders?, consentCategory?, cookieName?, policyVersion?, csp? })` | `@intecion/ipal-kit/next/middleware`, `@intecion/ipal-kit` | recommended `proxy.ts`: language negotiation, redirect `/` → `/{locale}`, cookie with consent, `x-locale`/`x-pathname` headers, optional Markdown routes; `csp` (buildCsp args) = a nonce CSP per request + `x-nonce` for `<SiteProviders nonce>` (dynamic pages only, security.md) |
| `createLocaleMiddleware({ config, cookieName?, policyVersion? })` | `@intecion/ipal-kit/next/middleware`, `@intecion/ipal-kit` | lower level: a `req → LocaleMiddlewareResult` function for your own proxy. The locale cookie is saved only with `functional` consent (`consentCategory: 'necessary'` = always), read under the version the consent was stored with; `policyVersion` pins one version |
| `DEFAULT_PROXY_MATCHER` | `@intecion/ipal-kit/next/middleware`, `@intecion/ipal-kit` | alias of `DEFAULT_MIDDLEWARE_MATCHER` for `createProxy`; paste the value into `config.matcher` as a literal |
| `DEFAULT_MIDDLEWARE_MATCHER` | `@intecion/ipal-kit/next/middleware`, `@intecion/ipal-kit` | array `['/((?!api\|admin\|_next\|.*\\..*).*)']` (excludes `api`, `admin`, `_next`, files); paste into `config.matcher` as a literal — Next reads the matcher statically |
@@ -508,11 +527,19 @@ Server only (`pnpm payload run`); never import it from client code, the Payload
| Export | Import from | What it does / when |
|---|---|---|
| `buildSecurityHeaders({ hsts?, additional?, coop?, frameOptions?, permissionsPolicy?, referrerPolicy?, … })` | `@intecion/ipal-kit` | Returns `SecurityHeader[]` (HSTS, X-Frame-Options, nosniff, Referrer-Policy, Permissions-Policy, COOP; with `IPAL_NOINDEX` also `X-Robots-Tag`) for `headers()` in `next.config.ts`. Add CSP via `additional`. |
| `buildCsp({ mode?, r2Url?, turnstile?, analytics?, googleMaps?, youtube?, extra? })` | `@intecion/ipal-kit` | Returns `{ key, value }` with a hardened CSP (`base-uri`, `object-src` etc.) + sources for the enabled integrations; put it into `additional`. Start with `mode: 'report-only'`. |
| `buildSecurityHeaders({ hsts?, csp?, additional?, coop?, frameOptions?, permissionsPolicy?, referrerPolicy?, … })` | `@intecion/ipal-kit` | Returns `SecurityHeader[]` (HSTS, X-Frame-Options, nosniff, Referrer-Policy, Permissions-Policy, COOP; with `IPAL_NOINDEX` also `X-Robots-Tag`) for `headers()` in `next.config.ts`. `csp` = `buildCsp` args → the CSP header (+ `Reporting-Endpoints` with `reportUri`); off by default. `additional` overrides by key. |
| `withSecurityConfig(nextConfig, { hidePoweredBy? })` | `@intecion/ipal-kit` | Next config wrapper: `poweredByHeader: false` + drops `X-Powered-By` from `headers()` (Next's "Next.js" and withPayload's "Next.js, Payload"). `withPayload(withSecurityConfig(nextConfig))`; `hidePoweredBy: false` = no change. |
| `totpRedirectTarget({ adminRoute, forceSetup?, pathname, user, excludePaths? })`, `totpAdminPath(adminRoute, path)` | `@intecion/ipal-kit` | The 2FA redirect rules as pure functions: the setup / verify URL (with `back`) to send this user to, or `null` (no path, api key, already on a TOTP screen or logout). For an own `twoFactor.provider`. Types `TotpRedirectArgs`, `TotpUser` |
| `buildCsp({ mode?, reportUri?, reportGroup?, r2Url?, analytics?, metaPixel?, linkedIn?, tiktok?, clarity?, turnstile?, youtube?, googleMaps?, nonce?, strictDynamic?, dev?, extra?, override? })` | `@intecion/ipal-kit` | Returns `{ key, value }` with a hardened CSP (`base-uri`, `object-src`, `frame-ancestors`, `form-action`) + sources for the enabled integrations. `mode: 'report-only'` → `…-Report-Only` (start here), `'enforce'` later. `extra` adds to any directive, `override` replaces / drops one (`null`). `dev` (default `NODE_ENV === 'development'`) adds `'unsafe-eval'`. `nonce` → `'nonce-…' 'strict-dynamic'`. |
| `buildCspHeaders(args)` | `@intecion/ipal-kit` | `[csp, Reporting-Endpoints]` (the second only with `reportUri`). |
| `buildAdminCsp(args)` / `buildAdminCspHeaders(args)` | `@intecion/ipal-kit` | Looser policy for Payload's admin: Monaco from `cdn.jsdelivr.net`, `blob:` workers, `https:` images, Live Preview `frame-src 'self'`, `frame-ancestors 'self'`. Rule `{ source: '/admin/:path*', headers: buildAdminCspHeaders({ mode, reportUri }) }` AFTER the site-wide rule. |
| `createCspReportRoute({ onReport?, maxBytes? })` | `@intecion/ipal-kit` | `POST` handler for `reportUri` (`src/app/api/csp-report/route.ts`): both report formats, body cap 16 KB, always `204`; default sink = one `[csp] …` `console.warn` line per violation (Coolify logs). |
| `parseCspReports(body)` | `@intecion/ipal-kit` | Normalises a report body (`csp-report` object or Reporting API array) to `CspViolation[]` — for your own collector. |
| `buildReportingEndpoints(url, group?)`, `cspHeaderKey(mode?)`, `DEFAULT_CSP_REPORT_GROUP` | `@intecion/ipal-kit` | Building blocks: the `Reporting-Endpoints` header, the header name for a mode, the default `report-to` group (`'csp-endpoint'`). |
| `createCspNonce()`, `CSP_NONCE_HEADER` | `@intecion/ipal-kit/next/middleware`, `@intecion/ipal-kit` | A per-request nonce and the request header (`x-nonce`) `createProxy({ csp })` passes it in — for your own proxy. Nonces make pages dynamic (no ISR). |
| `buildUploadSecurityHeaders({ collections? })` | `@intecion/ipal-kit` | `headers()` entries for `/api/<upload>/file/*` (`media` by default): files from disk are displayed, never executed (sandbox). Needed for media without R2. |
**Types:** `BuildCspArgs`, `BuildSecurityHeadersArgs` — builder options; `SecurityHeader` — `{ key, value }` in the Next.js shape.
**Types:** `BuildCspArgs`, `BuildAdminCspArgs`, `BuildSecurityHeadersArgs`, `WithSecurityConfigOptions`, `CreateCspReportRouteArgs` — builder options; `CspDirective`, `CspSources` — directive names / sources per directive; `CspViolation` — one normalised report; `SecurityHeader` — `{ key, value }` in the Next.js shape.
## SEO (`seo`) — details: `node_modules/@intecion/ipal-kit/docs/seo.md`
+26 -9
View File
@@ -137,7 +137,7 @@ behind Cloudflare, `x-forwarded-for` behind a plain proxy), `IPAL_NOINDEX` (empt
One language: one entry in `locales`, no `[locale]` folder (i18n.md).
**Check.** `pnpm payload generate:importmap` (whiteLabel adds admin components) and `pnpm generate:types` without
errors; `pnpm dev`, `/admin`: first-user screen → after saving, TOTP setup is enforced (QR);
errors (the import map lists `@intecion/ipal-kit/admin#TotpRedirectProvider`); `pnpm dev`, `/admin`: first-user screen → after saving, TOTP setup is enforced (`/admin/setup-totp?back=%2Fadmin`, QR, no reloading);
the panel shows Site settings, Site integrations, Cookie banner, Notifications, the Forms group, Consent records.
`curl -s -o /dev/null -w '%{http_code}' -X POST localhost:3000/api/ipal/consent -H 'content-type: application/json'
-d '{"id":"0123456789abcdef","version":1,"state":{"necessary":true,"functional":false,"analytics":false,"marketing":false}}'` → `201`.
@@ -326,23 +326,36 @@ and `rel="alternate" type="text/markdown"`; `/pl/nie-ma-takiej` → 404 with con
| `src/app/robots.ts` | `export { getRobots as default } from '@/lib/content'` + `force-dynamic` (AI crawler policy from Site settings → Search engines; `robots` = code only) |
| `src/app/manifest.ts` | `export { manifest as default } from '@/lib/content'` + `force-dynamic` |
| `src/app/api/health/route.ts` | `export { healthRoute as GET } from '@/lib/content'` + `force-dynamic` |
| `src/app/api/csp-report/route.ts` | `import { createCspReportRoute } from '@intecion/ipal-kit'` + `export const POST = createCspReportRoute()` (CSP violation reports → `[csp]` lines in the logs) |
```ts
// next.config.ts
import { withPayload } from '@payloadcms/next/withPayload'
import { buildCsp, buildImagesConfig, buildSecurityHeaders, buildUploadSecurityHeaders } from '@intecion/ipal-kit'
import {
buildAdminCspHeaders, buildImagesConfig, buildSecurityHeaders, buildUploadSecurityHeaders, withSecurityConfig,
} from '@intecion/ipal-kit'
const csp = buildCsp({ mode: 'report-only', r2Url: process.env.R2_PUBLIC_URL, turnstile: true, analytics: true })
const securityHeaders = buildSecurityHeaders({ hsts: process.env.NODE_ENV === 'production', additional: [csp] })
// CSP step 1: report-only. After the reports are clean (security.md → "ROLL OUT CSP"): mode 'enforce'.
const csp = { mode: 'report-only', reportUri: '/api/csp-report', r2Url: process.env.R2_PUBLIC_URL } as const
const securityHeaders = buildSecurityHeaders({
hsts: process.env.NODE_ENV === 'production',
// flags for what the site loads: analytics, metaPixel, linkedIn, tiktok, clarity, turnstile, youtube, googleMaps
csp: { ...csp, turnstile: true, analytics: true },
})
export default withPayload({
// withSecurityConfig: no X-Powered-By (Next's and Payload's)
export default withPayload(withSecurityConfig({
images: { ...buildImagesConfig() },
htmlLimitedBots:
/Googlebot|Google-InspectionTool|Storebot-Google|Bingbot|Yandex|DuckDuckBot|Baiduspider|Screaming Frog|AhrefsBot|SemrushBot/i,
async headers() {
return [{ source: '/:path*', headers: securityHeaders }, ...buildUploadSecurityHeaders()]
return [
{ source: '/:path*', headers: securityHeaders },
{ source: '/admin/:path*', headers: buildAdminCspHeaders(csp) }, // after the site-wide rule
...buildUploadSecurityHeaders(),
]
},
})
}))
```
```ts
// src/instrumentation.ts — import from /env (the root pulls in Payload → Edge/Turbopack crash)
@@ -362,13 +375,17 @@ export function register() {
the "XML Sitemap" style; `curl -s localhost:3000/robots.txt` → `Sitemap:`, `Disallow: /admin`, AI bots (GPTBot,
ClaudeBot…) with `Allow` (a policy picked in Site settings → Search engines → AI assistants shows up after a reload);
`curl -sI localhost:3000/sitemap.xml | grep -i cache-control` → `s-maxage=3600`; `/manifest.webmanifest` → JSON with the name from Site settings; `/api/health` → `200`
(`503` without a database); `curl -sI localhost:3000/pl | grep -i 'x-frame-options\|content-security-policy-report-only'`;
(`503` without a database); `curl -sI localhost:3000/pl | grep -iE 'x-frame-options|content-security-policy-report-only|reporting-endpoints|x-powered-by'`
→ the first three, NO `x-powered-by`; `/pl` and `/admin` in the browser → no `[Report Only]` CSP lines in the console
(each one → a flag or `extra`, see security.md); `curl -si -X POST localhost:3000/api/csp-report -H 'content-type: application/csp-report' -d '{"csp-report":{}}' | head -1` → `204`;
an empty `PAYLOAD_SECRET` in `.env` → `pnpm dev` exits with a list of missing variables (restore it).
**Turn off / override.** `robots`: `aiBots: 'block-training' | 'disallow' | false` (only on a client decision →
`ipal-audit-skip: aibots`), `adminRoute: false` (hidden panel), `extraDisallow`; `sitemapStyle: false` (raw XML)
or your own text; `buildSecurityHeaders({ frameOptions, coop, hsts, additional })` — an `additional` entry with the same key
overrides the default; CSP: `buildCsp` flags (`youtube`, `googleMaps`, `extra`), after a clean console `mode: 'enforce'`;
overrides the default; CSP: `buildCsp` flags (`youtube`, `googleMaps`, `metaPixel`, `linkedIn`, …), `extra`, `override`, no `csp`
= no policy; after clean reports `mode: 'enforce'` (site and admin); nonces only for pages that already render per request
(`createProxy({ csp })` + `<SiteProviders nonce>`); `withSecurityConfig(config, { hidePoweredBy: false })` keeps `X-Powered-By`;
`buildImagesConfig({ extraHosts })`; env validation is fully opt-in — filter/add rules
(`ipalEnvRules(…).filter(…)`). Staging: `IPAL_NOINDEX=1` (also stops IndexNow). Search engines: `robots` instead of
`getRobots` ignores the panel; `ipalKit({ searchSettings: false })` removes the tab; per-bot exceptions in code:
+36
View File
@@ -112,6 +112,42 @@ the banner → `<CookieBanner settings="detailed">` and remove the copy. With `d
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.
**→ 1.14.2 (PROGRAMISTA §6, item 51; 2FA setup loop; security.md) — required with 2FA on:**
1. `pnpm payload generate:importmap` — the plugin swaps `@clocklimited/payload-2fa/rsc#TOTPProvider` for
`@intecion/ipal-kit/admin#TotpRedirectProvider`; commit `importMap.js`, `rm -rf .next`, redeploy on Coolify.
**Check:** log in as a new admin (or a throwaway one) → `/admin/setup-totp?back=%2Fadmin` with the QR code, no
reloading; after the code → back on `/admin`. A project that wrote its own `x-pathname` proxy rule for `/admin`
as a workaround can drop it.
**→ 1.14.1 (PROGRAMISTA §6, item 50; X-Powered-By, CSP; security.md) — nothing required, recommended in this order:**
1. **Hide `X-Powered-By`** — `next.config.ts`: `export default withPayload(withSecurityConfig(nextConfig))`
(import `withSecurityConfig` from `@intecion/ipal-kit`); remove a hand-written `poweredByHeader: false` or a header
override if the project had one. **Check:** `curl -sI localhost:3000/pl | grep -i x-powered-by` → nothing (also on
`/admin` and `/api/health`).
2. **CSP, report-only first** — no CSP yet, or a hand-written one → `buildSecurityHeaders({ csp: { mode: 'report-only',
reportUri: '/api/csp-report', r2Url: process.env.R2_PUBLIC_URL, <flags for what the site loads> } })`, the admin rule
`{ source: '/admin/:path*', headers: buildAdminCspHeaders({ mode: 'report-only', reportUri: '/api/csp-report' }) }`
after the site-wide one, and `src/app/api/csp-report/route.ts` = `export const POST = createCspReportRoute()`.
Flags: what the panel's Site integrations and the code load (analytics, metaPixel, linkedIn, tiktok, clarity,
turnstile, youtube, googleMaps); anything else → `extra`. **Check:** `curl -sI localhost:3000/pl | grep -iE
'content-security-policy-report-only|reporting-endpoints'`; the main pages and `/admin` in a browser, accept the
cookie banner → no `[Report Only]` lines in the console. Deploy.
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 Cookie banner →
Cookies in every language; the dashboard shows the reminder while cookies wait. Without `cookieScanner`: nothing.
## 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.
+5 -3
View File
@@ -257,7 +257,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".
@@ -349,7 +349,7 @@ independent consent state).
(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,
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 +396,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
+63 -30
View File
@@ -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)).
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.
@@ -33,23 +35,33 @@ Then, in the project:
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.
**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 → 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.
use" (e.g. Cookie banner, Admin panel login, Google Analytics 4). Click **Scan cookies**: the box
says "Waiting for approval: N" with **Review and approve**. Open it (`/admin/cookie-approval`): the
cookies are grouped by category. Click **Approve and add**, then open *Cookie banner → Cookie
list*: the cookies are there, with purpose and retention in every language.
## How editors use it
| Step | What happens |
|---|---|
| **Scan cookies** | One draft per cookie of the integrations in use. Cookies already in Cookie 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 *Approve cookies* view (`/admin/cookie-approval`, linked from the box and the dashboard): 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 *Cookie banner → Cookie list* in every language, with the plugin's English and Polish texts (other languages get the English 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,7 +143,10 @@ 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) |
A project declaration:
@@ -175,16 +190,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 +222,34 @@ 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`) |
| `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 +303,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 +325,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 +420,16 @@ as unknown into **More cookie names**.
## Turn off, override, extend
- **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
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
+3
View File
@@ -647,6 +647,9 @@ Do one item at a time, build, check. Order by importance:
| 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 |
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`.
+231 -109
View File
@@ -2,15 +2,16 @@
Generic HTTP security headers (HSTS, X-Frame-Options, nosniff,
Referrer-Policy, Permissions-Policy, Cross-Origin-Opener-Policy; `X-Robots-Tag` on staging)
as a function for `next.config`. CSP is DELIBERATELY
left out — it depends on the project's domains, so it stays in the project.
as a function for `next.config`, `withSecurityConfig` to hide `X-Powered-By`, and an opt-in
Content-Security-Policy (`buildCsp`, report-only first, a separate admin policy, optional nonces and a
report collector).
## Rule
Headers that are IDENTICAL across projects are provided once by the plugin. CSP
(Content-Security-Policy) needs to know the domains of a specific project (where
scripts, images, fonts and analytics load from), so it cannot be generic —
it stays in the project and is added through `additional`.
Headers that are IDENTICAL across projects are provided once by the plugin and are on by default. CSP
(Content-Security-Policy) needs to know the domains of a specific project (where scripts, images, fonts
and analytics load from), so it is OFF until the project turns on the `buildCsp` flags for what it
loads — through `buildSecurityHeaders({ csp })`, or its own policy through `additional`.
## Usage — next.config.ts
@@ -21,23 +22,28 @@ application (including `/admin` and static files), and the proxy skips those rou
// next.config.ts
import { withPayload } from '@payloadcms/next/withPayload'
import type { NextConfig } from 'next'
import { buildSecurityHeaders } from '@intecion/ipal-kit'
import { buildAdminCspHeaders, buildSecurityHeaders, buildUploadSecurityHeaders, withSecurityConfig } from '@intecion/ipal-kit'
const prod = process.env.NODE_ENV === 'production'
const csp = { mode: 'report-only', reportUri: '/api/csp-report' } as const // later: mode 'enforce'
const securityHeaders = buildSecurityHeaders({
hsts: process.env.NODE_ENV === 'production', // IMPORTANT: off in dev (http)
additional: [
// the project's CSP — it knows its own domains:
// { key: 'Content-Security-Policy', value: "default-src 'self'; ..." },
],
hsts: prod, // IMPORTANT: off in dev (http)
csp: { ...csp, r2Url: process.env.R2_PUBLIC_URL, analytics: true, turnstile: true },
})
const nextConfig: NextConfig = {
async headers() {
return [{ source: '/:path*', headers: securityHeaders }]
return [
{ source: '/:path*', headers: securityHeaders },
{ source: '/admin/:path*', headers: buildAdminCspHeaders({ ...csp, r2Url: process.env.R2_PUBLIC_URL }) },
...buildUploadSecurityHeaders(),
]
},
}
export default withPayload(nextConfig)
// withSecurityConfig: no X-Powered-By (Next's and Payload's)
export default withPayload(withSecurityConfig(nextConfig))
```
## Options
@@ -52,7 +58,8 @@ export default withPayload(nextConfig)
| `referrerPolicy` | `'strict-origin-when-cross-origin'` | Referrer-Policy; `null` = no header |
| `permissionsPolicy` | blocks camera/mic/geolocation | Permissions-Policy; your own string, or `null` = no header |
| `coop` | `'same-origin'` | Cross-Origin-Opener-Policy; `'same-origin-allow-popups'`, or `false` = no header |
| `additional` | `[]` | extra headers (e.g. CSP); the same key overrides |
| `csp` | `false` | `buildCsp` args → the CSP header (+ `Reporting-Endpoints` with `reportUri`) |
| `additional` | `[]` | extra headers; the same key overrides (also the `csp` ones) |
With `IPAL_NOINDEX=1` (staging), `X-Robots-Tag: noindex, nofollow` is added to every response.
@@ -65,133 +72,204 @@ domain. Wire it alongside: `[{ source: '/:path*', headers: securityHeaders }, ..
HSTS over HTTP on localhost can lock the browser into HTTPS for localhost.
ALWAYS turn it off in dev: `hsts: process.env.NODE_ENV === 'production'`.
## Overriding and CSP
## X-Powered-By — hide it (`withSecurityConfig`)
`additional` with the same key OVERRIDES the default (e.g. change X-Frame-Options
to SAMEORIGIN). A new key (like CSP) is added. CSP always goes through `additional` —
the plugin does not generate it, because it depends on the project.
A response header `X-Powered-By: Next.js, Payload` tells scanners which software (and which known
advisories) to try. Audits flag it. Where it comes from:
### Why CSP stays in the project (not the plugin)
- **Next.js** sends `X-Powered-By: Next.js` unless the config says `poweredByHeader: false`.
- **Payload's `withPayload`** switches Next's header off and adds its own `X-Powered-By: Next.js, Payload`
for `/:path*` through `headers()` — also unless the config it wraps says `poweredByHeader: false`.
Payload's REST/GraphQL handlers add nothing of their own.
`withSecurityConfig(nextConfig, { hidePoweredBy = true })` sets `poweredByHeader: false` AND drops any
`X-Powered-By` entry from `headers()` rules, so both orders work:
`withPayload(withSecurityConfig(nextConfig))` (recommended) or `withSecurityConfig(withPayload(nextConfig))`.
Turn off: `withSecurityConfig(nextConfig, { hidePoweredBy: false })`, or do not call it. Without the helper,
`poweredByHeader: false` in the config passed to `withPayload` has the same effect.
Check: `curl -sI https://<DOMAIN>/pl | grep -i x-powered-by` prints nothing. Behind Coolify the proxy
(Traefik or Caddy) adds no `X-Powered-By`; if the header comes back in production, look for a
"Custom labels" header middleware in the Coolify app, or a Cloudflare Transform Rule.
Keep the software updated as well — hiding the header does not remove the advisories (the minimum safe
Next.js is listed in the agent guide, §4).
## Content-Security-Policy
### Why CSP is opt-in
HSTS, nosniff and Referrer-Policy are IDENTICAL for every project → the plugin
generates them. CSP lists the SPECIFIC domains the project loads from (its R2,
analytics, Turnstile, fonts). A generic CSP would be either too loose (`*` =
useless) or would break the site. So the plugin provides the mechanism (`additional`),
and the project supplies a CSP that fits it.
useless) or would break the site. So the plugin provides the hardened skeleton and one flag per
integration it ships (`buildCsp`), and the project turns on what it uses.
### buildCsp — CSP generator (recommended over writing it by hand)
Instead of writing a raw CSP in every project (risk of forgetting base-uri,
object-src), use `buildCsp` — it has hard OWASP/Lighthouse rules built in, and you
turn on only the flags for what the project loads:
```ts
// next.config.ts
import { buildCsp, buildSecurityHeaders } from '@intecion/ipal-kit'
import { buildCsp } from '@intecion/ipal-kit'
const csp = buildCsp({
mode: 'report-only', // start here; 'enforce' once the console is clean
r2Url: process.env.R2_PUBLIC_URL, // R2 media → img-src
turnstile: true, // challenges.cloudflare.com → script/frame/connect
analytics: true, // GTM + GA
youtube: true, // youtube → frame-src
mode: 'report-only', // start here; 'enforce' once the reports are clean
reportUri: '/api/csp-report', // where browsers send violations (createCspReportRoute)
r2Url: process.env.R2_PUBLIC_URL, // R2 media → img-src, media-src
turnstile: true, // Cloudflare Turnstile
analytics: true, // GA4 / GTM
metaPixel: true, linkedIn: true, tiktok: true, clarity: true, // the pixels the plugin loads
youtube: true, // YouTubeEmbed
googleMaps: true, // Google Maps
// extra: { 'script-src': ['https://other-script.example'] }, // extra sources
})
const securityHeaders = buildSecurityHeaders({
hsts: process.env.NODE_ENV === 'production',
additional: [csp],
// extra: { 'script-src': ['https://other-script.example'] }, // add sources to any directive
// override: { 'frame-ancestors': ["'self'"], 'style-src': null }, // replace / drop a directive
})
// → { key: 'Content-Security-Policy-Report-Only', value: "default-src 'self'; …" }
```
**Hard rules built in** (always on, impossible to forget): `base-uri 'self'`,
`object-src 'none'`, `frame-ancestors 'none'`. These are the ones Lighthouse/OWASP
require and that are easy to miss when writing CSP by hand.
`buildCspHeaders(args)` returns `[csp, Reporting-Endpoints]` (the second only with `reportUri`);
`buildSecurityHeaders({ csp: args })` does the same inside the site-wide list.
Base sources: `default-src 'self'`, `form-action 'self'`, `script-src 'self' 'unsafe-inline'`
(Next / analytics), `style-src 'self' 'unsafe-inline' https://fonts.googleapis.com`. `r2Url` goes into
`img-src` only as an absolute address (`https://…`); `youtube` also adds `i.ytimg.com` (the
`YouTubeEmbed` poster); `googleMaps` adds `*.googleapis.com`, `*.gstatic.com`, `*.google.com`, `*.ggpht.com`,
`*.googleusercontent.com` (iframe and Maps JS).
**Hard rules built in** (always on unless you `override` them): `base-uri 'self'`,
`object-src 'none'`, `frame-ancestors 'none'`, `form-action 'self'`.
`buildCsp` does NOT add `'unsafe-eval'` (it weakens CSP) — add it through `extra` only
if a library requires it. `mode` defaults to `'enforce'` (`Content-Security-Policy`);
`'report-only'` gives `…-Report-Only` — start with it when rolling out.
**What each flag allows** — the plugin's own components need exactly these:
CSP is still "in the project" (you pick the flags for what you load), but the skeleton
comes from the plugin — every project has the same hardened foundation.
| Flag | Plugin part | Sources |
|---|---|---|
| (always) | Next, Tailwind, next/font, `ThemeScript`, `JsonLdGraph`, consent banner, lightbox, `MediaPreconnect` | `'self'`, `'unsafe-inline'` (script, style), `data:`/`blob:` images, Google Fonts |
| `r2Url` | media on R2 | the URL → `img-src`, `media-src` (a site-relative `/media` is already `'self'`) |
| `analytics` | `Analytics` GA4 / GTM | `script-src *.googletagmanager.com`; `connect-src`/`img-src` `*.google-analytics.com`, `*.analytics.google.com`, `*.googletagmanager.com`, `*.g.doubleclick.net`, `www.google.com` |
| `metaPixel` | `loadMetaPixel`, fbevents via `ConsentScript` | `connect.facebook.net` (script, connect), `www.facebook.com` (connect, img, frame) |
| `linkedIn` | `loadLinkedIn` | `snap.licdn.com` (script); `px.ads.linkedin.com`, `px4.ads.linkedin.com`, `www.linkedin.com` (connect, img) |
| `tiktok` | `loadTikTok` | `analytics.tiktok.com` (script, connect, img) |
| `clarity` | `loadClarity` | `*.clarity.ms` (script, connect, img), `c.bing.com` (img) |
| `turnstile` | `Turnstile` | `challenges.cloudflare.com` (script, frame, connect) |
| `youtube` | `YouTubeEmbed` | `www.youtube.com`, `www.youtube-nocookie.com` (frame), `i.ytimg.com` (img) |
| `googleMaps` | Maps iframe / Maps JS | `*.googleapis.com`, `*.gstatic.com`, `*.google.com`, `*.ggpht.com`, `*.googleusercontent.com`, `blob:` workers |
| `dev` | `next dev` | `'unsafe-eval'` (React dev tooling). Default `process.env.NODE_ENV === 'development'` |
### Building CSP by hand (if you need full control)
Plausible or another script through `ConsentScript` → add its host with `extra`. GTM tags you add in
the GTM panel (Hotjar, Ads…) load their own hosts → add them with `extra` as the reports show them.
Read the media domain from `R2_PUBLIC_URL` (env), do not hard-code it. Match the other
sources to what the project actually loads:
**Why `'unsafe-inline'` stays without a nonce.** Next streams the page's RSC payload in inline
`<script>` tags (`self.__next_f.push(…)`) that differ per page and per render — a static header cannot
list their hashes, and static/ISR HTML cannot carry a per-request nonce. So a header-only CSP keeps
`'unsafe-inline'` in `script-src`; it still blocks every script from a host you did not list, `<object>`,
`<base>` hijacking, framing and form posts to other sites. `style-src 'unsafe-inline'` stays in every mode:
React, Next and the plugin set inline `style` attributes, which a nonce cannot cover. `buildCsp` never adds
`'unsafe-eval'` in production.
### Nonces (stricter; dynamic pages only)
Next adds a per-request nonce to its own scripts when the request carries a CSP header with
`'nonce-…'` (enforcing or report-only). `createProxy(i18nConfig, { NextResponse, csp: { … } })` does it:
a fresh nonce per request, the policy on the request (for Next) and the response, and the nonce as the
`x-nonce` request header. The policy then gets `'nonce-…' 'strict-dynamic'`: scripts the nonced Next
bootstrap loads (the plugin's analytics, pixels, Turnstile) are trusted, and CSP3 browsers ignore the
host list and `'unsafe-inline'` (both stay as a fallback for old browsers). `strictDynamic: false`
keeps host-based checks.
```ts
// next.config.ts
const r2Url = process.env.R2_PUBLIC_URL || ''
const csp = [
"default-src 'self'",
// scripts: self + Turnstile (Cloudflare) + analytics (GTM/GA if you use them)
"script-src 'self' 'unsafe-inline' https://challenges.cloudflare.com https://*.googletagmanager.com",
// styles: self + inline (Tailwind) + Google Fonts
"style-src 'self' 'unsafe-inline' https://fonts.googleapis.com",
// images: self + R2 media (from env!) + data:
`img-src 'self' data: https://*.google-analytics.com https://*.googletagmanager.com ${r2Url}`.trim(),
"font-src 'self' https://fonts.gstatic.com data:",
// GA4: wildcards are required — EU traffic goes to region1.google-analytics.com
"connect-src 'self' https://*.google-analytics.com https://*.analytics.google.com https://*.googletagmanager.com",
// frames: Turnstile (captcha widget)
"frame-src https://challenges.cloudflare.com",
"form-action 'self'",
"frame-ancestors 'none'", // replaces X-Frame-Options in modern browsers
].join('; ')
const securityHeaders = buildSecurityHeaders({
hsts: process.env.NODE_ENV === 'production',
additional: [{ key: 'Content-Security-Policy', value: csp }],
// proxy.ts
export const proxy = createProxy(i18nConfig, {
NextResponse, markdown: true,
csp: { mode: 'report-only', reportUri: '/api/csp-report', analytics: true, r2Url: process.env.R2_PUBLIC_URL },
})
// app/(frontend)/[locale]/layout.tsx
import { headers } from 'next/headers'
const nonce = (await headers()).get('x-nonce') // CSP_NONCE_HEADER
<SiteProviders shell={shell} theme nonce={nonce}>… // ThemeScript + GA4/GTM tag get the nonce
```
Match the sources to the project: Google Maps (`https://maps.googleapis.com`,
`https://*.google.com`), other embeds, other analytics. Anything you do not list
will be blocked.
Costs and rules:
- Reading `headers()` makes every page under the proxy matcher **dynamic** — no ISR, no static HTML, a
render per request. That is why nonces are opt-in; ISR sites keep the header-only policy.
- The proxy matcher skips `/api`, `/admin`, `/_next` and files — those keep the `next.config` headers. Do
NOT also send the site CSP from `next.config` for the frontend paths (two policies = both apply); keep
only the admin rule and `buildUploadSecurityHeaders` there.
- Your own proxy: `createCspNonce()` + `buildCsp({ nonce })`, set the policy on the request headers
(`NextResponse.next({ request: { headers } })`) and on the response, like `createProxy` does.
- `ConsentScript nonce`, `ThemeScript nonce`, `Analytics nonce` exist for policies without `'strict-dynamic'`.
### Payload admin — its own, looser policy
The admin (`/admin`, or your `adminRoute`) is a large client app the project does not control: inline
scripts and styles, the Monaco code editor loaded from `cdn.jsdelivr.net` with `blob:` workers, image
previews from any `https:` host, and the Live Preview iframe (`frame-src 'self'`). `buildAdminCsp(args)` /
`buildAdminCspHeaders(args)` give that policy with the same hard rules, `frame-ancestors 'self'`, and the
same `mode`, `reportUri`, `extra`, `override`. Put its rule AFTER the site-wide one — Next uses the
last matching rule for the same header key:
```ts
{ source: '/:path*', headers: securityHeaders },
{ source: '/admin/:path*', headers: buildAdminCspHeaders({ mode: 'report-only', reportUri: '/api/csp-report' }) },
```
With a custom `adminRoute` (e.g. `/its`), use that path in `source`.
### Collecting reports
`createCspReportRoute({ onReport?, maxBytes = 16384 })` — a `POST` handler for `reportUri`. It accepts
both formats (`application/csp-report` from `report-uri`, `application/reports+json` from `report-to`),
caps the body, always answers `204`, and by default logs one `console.warn` line per violation:
`[csp] report script-src-elem blocked=https://x.example/a.js page=https://site/pl`. Read them in the
Coolify app's **Logs**. Plug `onReport` into `payload.logger`, Sentry or a database for more.
```ts
// app/api/csp-report/route.ts (a fixed route wins over Payload's /api/[...slug])
import { createCspReportRoute } from '@intecion/ipal-kit'
export const POST = createCspReportRoute()
```
Third-party option: point `reportUri` at a collector (report-uri.com, Sentry's security endpoint,
uriports) and skip the route. `parseCspReports(body)` normalises both formats for your own handler.
### ROLL OUT CSP CAREFULLY — Report-Only first
A CSP that is too strict **breaks the site** (blocks scripts/styles/images). NEVER deploy
an enforcing CSP blindly. The safe method:
1. **Reporting first** — use the key `Content-Security-Policy-Report-Only`
(not `Content-Security-Policy`). The browser REPORTS violations in the console
but does NOT block — the site works as usual.
```ts
additional: [{ key: 'Content-Security-Policy-Report-Only', value: csp }]
```
2. **Open the site** → DevTools → Console → look for "Content Security Policy"
violations. Each violation = a missing domain. Add it to the matching CSP
directive.
3. **Go through the whole site** — home page, forms (Turnstile!),
gallery (R2 images), pages with maps/embeds. Collect every violation.
4. **Only when the console is clean** → change the key to `Content-Security-Policy`
(enforcing). Now CSP protects without breaking anything.
1. **Report-only** — `mode: 'report-only'` with `reportUri`. The browser REPORTS violations (console +
the report route) but does NOT block — the site works as usual. Deploy it.
2. **Read the reports** — DevTools → Console ("Content Security Policy" / "[Report Only]") on every page
type, and the `[csp]` lines in the Coolify logs (real visitors, other browsers). Go through the whole
site — home page, forms (Turnstile!), gallery (R2 images), embeds, cookie banner accept (analytics and
pixels load only after consent), the admin. Give it a few days of real traffic.
3. **Fix each violation** — a missing host of yours → the matching flag or `extra`; noise from browser
extensions (`chrome-extension://`, `moz-extension://`) → ignore.
4. **Enforce** — when the reports are clean, change `mode: 'report-only'` to `mode: 'enforce'` (site and
admin). Keep `reportUri`: enforced violations keep being reported. Check the pages once more.
### Building CSP by hand (if you need full control)
Pass your own string through `additional` (same key overrides `csp`):
```ts
const securityHeaders = buildSecurityHeaders({
hsts: process.env.NODE_ENV === 'production',
additional: [{ key: 'Content-Security-Policy-Report-Only', value: "default-src 'self'; base-uri 'self'; object-src 'none'; …" }],
})
```
Read the media domain from `R2_PUBLIC_URL` (env), do not hard-code it. Anything you do not list will be
blocked once enforced.
### Checking headers in production
```bash
# check which headers actually go out:
curl -sI https://<DOMAIN>/pl | grep -i "strict-transport\|content-type-options\|referrer\|content-security\|x-frame"
curl -sI https://<DOMAIN>/pl | grep -iE "strict-transport|content-type-options|referrer|content-security|reporting-endpoints|x-frame|x-powered-by"
```
If HSTS/nosniff/Referrer are there but CSP is missing → add CSP (above). If ALL of them
are missing despite buildSecurityHeaders in the config → check that `headers()` is
wired and that Cloudflare (if it sits in front of the app) does not filter headers.
Expected: HSTS, nosniff, Referrer, `content-security-policy-report-only` (or `content-security-policy`
after enforcing), and NO `x-powered-by`. If ALL of them are missing despite buildSecurityHeaders in the
config → check that `headers()` is wired and that Cloudflare (if it sits in front of the app) does not
filter headers.
> Cloudflare note: if CF sits in front of the app, it may override/filter
> Cloudflare / Coolify note: if CF sits in front of the app, it may override/filter
> headers. Then set them in CF as well (Transform Rules → Modify Response Header),
> or make sure CF passes the origin's headers through.
> or make sure CF passes the origin's headers through. Coolify's proxy passes the app's headers
> through unchanged; a header middleware added in the app's "Custom labels" can add or drop them.
## COOP (Cross-Origin-Opener-Policy) — on by default
@@ -312,6 +390,37 @@ gets the injected plugin.
The plugin sets `forceSetup: true` — every user MUST set up TOTP after
logging in. There is no per-user "on/off" option.
### Import map (required)
The 2FA screens and the redirect to them are admin components. After adding `twoFactor`, and after every
ipal-kit upgrade, run:
```bash
pnpm generate:importmap
```
`src/app/(payload)/admin/importMap.js` must list `@intecion/ipal-kit/admin#TotpRedirectProvider` and
`@clocklimited/payload-2fa/rsc#TOTPSetup` / `#TOTPVerify` / `#TOTPField`. Commit the file.
### The redirect to the 2FA screens (`twoFactor.provider`)
The package's own admin provider decides on the server where to send the user, from an `x-pathname`
request header. Nothing sets that header on `/admin` (the `createProxy` matcher skips `/admin`), so up to
1.14.1 a user without TOTP was sent to `/admin/setup-totp?back=null`, and the setup screen redirected
to itself forever. Since 1.14.2, ipal-kit swaps in its own provider,
`TotpRedirectProvider`: it reads the path in the browser, never redirects away from the setup or verify
screen or from logout, and renders nothing while a redirect is pending, so the panel does not flash.
No project change is needed apart from `generate:importmap`.
- `twoFactor.provider: '@/components/MyTotp#MyTotp'` (or a `{ path, clientProps, serverProps }` object):
your own component. It gets clientProps `forceSetup` and the package's serverProps `pluginOptions`.
The pure logic is exported: `totpRedirectTarget({ adminRoute, forceSetup, pathname, user })` returns
the URL to send the user to, or `null`.
- `twoFactor.provider: false`: keep the package's provider. Then a proxy must set `x-pathname` on every
`/admin` request, or the loop comes back.
The provider only steers the UI. Data access is still checked by the package's access wrapper.
### Turning it off (DISCOURAGED)
```ts
@@ -323,10 +432,14 @@ twoFactor: false // ONLY when the project really cannot use 2FA (rare)
### How it works for the user
1. Logs in (email + password)
2. On first login: redirected to TOTP Setup (QR + secret)
2. On first login: redirected to TOTP Setup (`/admin/setup-totp?back=%2Fadmin`, QR + secret)
3. Scans the QR with an app (Google Authenticator, Authy, 1Password, Microsoft Authenticator)
4. Enters the code → 2FA is active
5. Next logins: email + password + TOTP code
4. Enters the code → 2FA is active, back to the page from `back`
5. Next logins: email + password + TOTP code (`/admin/verify-totp?back=…`)
**Check:** log in as a new admin. The address must end at `/admin/setup-totp?back=%2Fadmin` and the page must
show the QR code. `back=null` or a page that keeps reloading means the import map is stale (run
`pnpm generate:importmap`) or `provider: false` without an `x-pathname` header on `/admin`.
### Resetting 2FA (admin)
@@ -370,10 +483,19 @@ data access, not just the UI.
## Turn off, override, extend
- **Turn off:** headers — do not call `buildSecurityHeaders`, or `null` / `false` per header (`frameOptions`,
`referrerPolicy`, `permissionsPolicy`, `coop`), `hsts: false`; 2FA — `twoFactor: false` (discouraged).
- **Override:** `additional` (the same key overrides the plugin's header), `buildCsp({ extra })`, `mode`;
2FA — `collectionSlug`, `allowCollectionMismatch`, your own TOTP options by wrapping `plugin`;
`referrerPolicy`, `permissionsPolicy`, `coop`), `hsts: false`; CSP — leave out `csp` (the default);
X-Powered-By hiding — `withSecurityConfig(config, { hidePoweredBy: false })` or do not call it;
2FA — `twoFactor: false` (discouraged).
- **Override:** `additional` (the same key overrides the plugin's header and the `csp` ones),
`buildCsp({ extra, override, mode, strictDynamic })`, `buildAdminCsp({ extra, override })`,
`createCspReportRoute({ onReport, maxBytes })`;
2FA — `collectionSlug`, `allowCollectionMismatch`, your own TOTP options by wrapping `plugin`,
`provider` (your own redirect component, or `false` for the package's);
access — `access.authAccess`, `access.firstUserAdmin`, `globalOverrides` ([access.md](./access.md)).
- **Extend:** `buildCsp`, `buildUploadSecurityHeaders({ collections })` for your own upload collections.
- **Check:** `curl -sI https://domain/ | grep -iE "strict-transport|x-frame|referrer|permissions|cross-origin|content-security"`;
- **Extend:** `totpRedirectTarget` / `totpAdminPath` (2FA redirect rules) for your own provider;
`buildCsp` / `buildCspHeaders` / `buildReportingEndpoints` / `cspHeaderKey` /
`parseCspReports` / `createCspNonce` (`CSP_NONCE_HEADER`, `DEFAULT_CSP_REPORT_GROUP`) for your own proxy
or collector; `buildUploadSecurityHeaders({ collections })` for your own upload collections.
- **Check:** `curl -sI https://domain/pl | grep -iE "strict-transport|x-frame|referrer|permissions|cross-origin|content-security|x-powered-by"`
(no `x-powered-by`; `content-security-policy-report-only` while rolling out);
on staging also `x-robots-tag`; startup with a wrong `twoFactor.collectionSlug` fails with `[ipal] twoFactor…`.
+1 -1
View File
@@ -1,6 +1,6 @@
{
"name": "@intecion/ipal-kit",
"version": "1.14.0",
"version": "1.14.3",
"description": "Intecion Payload Advanced Library — a Payload CMS 3 plugin: i18n, SEO, forms, consent, analytics, blog/archives.",
"license": "MIT",
"repository": {
+4
View File
@@ -10,10 +10,14 @@ 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 { CookieScanButton } from '../modules/consent/scanner/CookieScanButton.js'
export { CookieCrawlAlert } from '../modules/consent/scanner/crawl/CookieCrawlAlert.js'
export { IntegrationAlerts } from '../modules/integrations/IntegrationAlerts.js'
export { IntegrationStatusBanner } from '../modules/integrations/IntegrationStatusBanner.js'
export { TotpRedirectProvider } from '../modules/security/totp/TotpRedirectProvider.js'
export type { TotpRedirectProviderProps } from '../modules/security/totp/TotpRedirectProvider.js'
export { FaviconCheck } from '../modules/seo/FaviconCheck.js'
export type { FaviconCheckProps } from '../modules/seo/FaviconCheck.js'
export { MetaDescriptionCheck } from '../modules/seo/MetaDescriptionCheck.js'
+1
View File
@@ -10,3 +10,4 @@
export { createProxy, DEFAULT_PROXY_MATCHER } from '../modules/i18n/createProxy.js'
export { createLocaleMiddleware, DEFAULT_MIDDLEWARE_MATCHER } from '../modules/i18n/localeMiddleware.js'
export type { LocaleMiddlewareResult } from '../modules/i18n/localeMiddleware.js'
export { createCspNonce, CSP_NONCE_HEADER } from '../modules/security/cspNonce.js'
+45 -3
View File
@@ -63,12 +63,16 @@ export type { ConsentCategory, ConsentLogOptions, ConsentState, ConsentTexts, Co
export {
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 +83,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,
@@ -254,9 +270,35 @@ export { buildTableOfContentsField, extractHeadings, headingText } from './modul
export type { ExtractHeadingsOptions, HeadingItem, HeadingLevel } from './modules/richtext/headings.js'
// Lexical → Markdown (pure, no React) — for AI-readable output.
export { lexicalToMarkdown } from './modules/richtext/lexicalToMarkdown.js'
export { buildSecurityHeaders, buildUploadSecurityHeaders } from './modules/security/index.js'
export { buildCsp } from './modules/security/index.js'
export type { BuildCspArgs } from './modules/security/index.js'
export {
buildAdminCsp,
buildAdminCspHeaders,
buildCsp,
buildCspHeaders,
buildReportingEndpoints,
buildSecurityHeaders,
buildUploadSecurityHeaders,
createCspNonce,
createCspReportRoute,
CSP_NONCE_HEADER,
cspHeaderKey,
DEFAULT_CSP_REPORT_GROUP,
parseCspReports,
totpAdminPath,
totpRedirectTarget,
withSecurityConfig,
} from './modules/security/index.js'
export type {
BuildAdminCspArgs,
BuildCspArgs,
CreateCspReportRouteArgs,
CspDirective,
CspSources,
CspViolation,
TotpRedirectArgs,
TotpUser,
WithSecurityConfigOptions,
} from './modules/security/index.js'
export type { BuildSecurityHeadersArgs, SecurityHeader } from './modules/security/index.js'
export type { OgImage } from './modules/seo/buildMetadata.js'
+9 -4
View File
@@ -32,11 +32,13 @@ function readConsent(version: number | undefined) {
return parseConsent(raw, version) ?? DEFAULT_CONSENT
}
function injectScript(src: string) {
function injectScript(src: string, nonce?: string) {
if (document.querySelector(`script[src="${src}"]`)) {return}
const s = document.createElement('script')
s.src = src
s.async = true
// GTM reads its own script's nonce and passes it to Custom HTML tags.
if (nonce) {s.nonce = nonce}
document.head.appendChild(s)
}
@@ -68,6 +70,8 @@ export type AnalyticsProps = {
defer?: boolean
/** Fallback delay after window `load`, in ms. Default 3500. */
deferTimeoutMs?: number
/** CSP nonce (nonce-based policy) — set on the GA4 / GTM script tag. */
nonce?: string
} & AnalyticsConfig
const INTERACTION_EVENTS = ['scroll', 'pointerdown', 'touchstart', 'keydown'] as const
@@ -135,6 +139,7 @@ export function Analytics(props: AnalyticsProps) {
gtmContainerId,
linkedInPartnerId,
metaPixelId,
nonce,
tiktokPixelId,
} = props
@@ -162,13 +167,13 @@ export function Analytics(props: AnalyticsProps) {
if (gtmContainerId) {
window.dataLayer = window.dataLayer || []
window.dataLayer.push({ event: 'gtm.js', 'gtm.start': Date.now() })
injectScript(GTM_SCRIPT(gtmContainerId))
injectScript(GTM_SCRIPT(gtmContainerId), nonce)
} else if (ga4MeasurementId) {
injectScript(GA4_SCRIPT(ga4MeasurementId))
injectScript(GA4_SCRIPT(ga4MeasurementId), nonce)
gtag('js', new Date())
gtag('config', ga4MeasurementId)
}
}, [googleAllowed, ga4MeasurementId, gtmContainerId])
}, [googleAllowed, ga4MeasurementId, gtmContainerId, nonce])
// --- Non-Google: each when `ready` AND its consent category is granted ---
// Loaders are idempotent, so re-running on state changes is safe; a tag loads
+9 -1
View File
@@ -25,6 +25,11 @@ type ConsentScriptProps = {
defer?: boolean
/** Stable id used to dedupe — the script is injected at most once. */
id?: string
/**
* CSP nonce for both the external and the inline script. Only needed with a
* nonce policy WITHOUT 'strict-dynamic' (with it, scripts the app adds are trusted).
*/
nonce?: string
/** External script URL. Injected only once the category is granted. */
src?: string
}
@@ -60,6 +65,7 @@ export function ConsentScript({
category,
code,
defer,
nonce,
src,
}: ConsentScriptProps) {
const { state } = useConsentContext()
@@ -82,6 +88,7 @@ export function ConsentScript({
if (!code) {return}
const inline = document.createElement('script')
if (dedupeId) {inline.id = `${dedupeId}-inline`}
if (nonce) {inline.nonce = nonce}
inline.textContent = code
document.head.appendChild(inline)
}
@@ -92,6 +99,7 @@ export function ConsentScript({
if (dedupeId) {el.id = dedupeId}
if (asyncAttr) {el.async = true}
if (defer) {el.defer = true}
if (nonce) {el.nonce = nonce}
if (attributes) {for (const [k, v] of Object.entries(attributes)) {el.setAttribute(k, v)}}
// eslint-disable-next-line @eslint-react/web-api/no-leaked-event-listener -- one-shot, and the script is never unloaded (see below)
el.addEventListener('load', runInline, { once: true })
@@ -102,7 +110,7 @@ export function ConsentScript({
// Deliberately no removal on cleanup: a loaded third-party script can't be
// meaningfully unloaded. Withdrawal is handled by not re-injecting (and, for
// vendors that support it, Consent Mode). See the component doc.
}, [granted, src, code, id, attributes, asyncAttr, defer])
}, [granted, src, code, id, attributes, asyncAttr, defer, nonce])
return null
}
@@ -0,0 +1,189 @@
'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',
gone,
labels = COOKIE_SCAN_LABELS,
pending,
unknownCategory,
}: {
adminRoute?: string
gone: CookieApprovalItem[]
labels?: Record<string, CookieScanLabels>
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())
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} 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>
</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
@@ -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,16 @@ 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,
}: {
/** Cookie approval is on: show how many cookies wait and link to the approval view. */
approval?: boolean
crawl?: boolean
labels?: Record<string, CookieScanLabels>
}) {
const { i18n } = useTranslation()
const { config } = useConfig()
const router = useRouter()
@@ -49,6 +58,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 +81,10 @@ 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()
}
wasRunning = data.status === 'running'
} catch {
// offline — try again on the next tick
@@ -73,7 +96,7 @@ export function CookieScanButton({ crawl = false, labels = COOKIE_SCAN_LABELS }:
stopped = true
clearInterval(timer)
}
}, [crawl, crawlEndpoint, router])
}, [crawl, crawlEndpoint, refreshPending, router])
const startCrawl = async () => {
setCrawlStarting(true)
@@ -106,6 +129,7 @@ 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()
} catch {
setStatus({ kind: 'error' })
}
@@ -138,6 +162,14 @@ export function CookieScanButton({ crawl = false, labels = COOKIE_SCAN_LABELS }:
{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}
+191
View File
@@ -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 Cookie banner → 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 Cookie banner → 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,
},
]
}
+25 -2
View File
@@ -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)
+16 -3
View File
@@ -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 })
}
}
+12 -5
View File
@@ -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)}`)
+15 -3
View File
@@ -1,4 +1,15 @@
// Cookie scanner — server-safe building blocks. The admin button is in /admin.
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 +37,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,
+94 -4
View File
@@ -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,10 +54,16 @@ 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
@@ -50,14 +72,20 @@ export type CookieScanLabels = {
listedDescription: 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
openCookieBanner: string
plural: string
project: string
purpose: string
@@ -81,6 +109,8 @@ export type CookieScanLabels = {
status: string
statusDescription: string
storage: string
uncategorized: string
uncategorizedNote: string
unknown: string
vendor: string
violation: string
@@ -97,10 +127,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,10 +171,16 @@ 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.',
@@ -137,13 +189,19 @@ export const COOKIE_SCAN_LABELS: Record<'en' | 'pl', CookieScanLabels> = {
listedDescription: 'Already in the cookie list of the cookie banner.',
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].',
openCookieBanner: 'Open cookie banner',
plural: 'Cookie review',
project: 'Site configuration',
purpose: 'Purpose',
@@ -151,7 +209,7 @@ export const COOKIE_SCAN_LABELS: Record<'en' | 'pl', CookieScanLabels> = {
retention: 'Duration',
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,6 +224,8 @@ 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',
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',
@@ -180,10 +240,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,10 +284,16 @@ 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.',
@@ -220,13 +302,19 @@ export const COOKIE_SCAN_LABELS: Record<'en' | 'pl', CookieScanLabels> = {
listedDescription: 'Już jest na liście cookies banera.',
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].',
openCookieBanner: 'Otwórz baner cookies',
plural: 'Przegląd cookies',
project: 'Konfiguracja witryny',
purpose: 'Cel',
@@ -234,7 +322,7 @@ export const COOKIE_SCAN_LABELS: Record<'en' | 'pl', CookieScanLabels> = {
retention: 'Okres',
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,6 +337,8 @@ 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',
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',
+77 -5
View File
@@ -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 }
}
+9 -1
View File
@@ -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
@@ -45,7 +53,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
+16
View File
@@ -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,12 @@ 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>
/**
* 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 +164,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
}
+9 -2
View File
@@ -39,6 +39,12 @@ export type SiteProvidersProps = {
lightbox?: boolean | Omit<LightboxProviderProps, 'children' | 'renderDialog' | 'renderImage'>
/** Consent log endpoint, e.g. '/api/ipal/consent' (ipalKit consentLog: true). */
logEndpoint?: string
/**
* CSP nonce for a nonce-based policy (createProxy `csp`): read it in the layout
* with `(await headers()).get('x-nonce')`. Goes on the theme script and on the
* analytics tags the plugin injects (GTM passes it on to its own tags).
*/
nonce?: null | string
/** <link rel=preconnect> to the media origin (R2_PUBLIC_URL). Default true. */
preconnect?: boolean
/** getSiteShell(locale) from lib/content. */
@@ -81,6 +87,7 @@ export function SiteProviders({
jsonLd = [],
lightbox = false,
logEndpoint,
nonce,
preconnect = true,
shell,
stats = false,
@@ -88,7 +95,7 @@ export function SiteProviders({
}: SiteProvidersProps) {
return (
<>
{theme ? <ThemeScript {...shell.theme} /> : null}
{theme ? <ThemeScript {...shell.theme} nonce={nonce ?? undefined} /> : null}
{preconnect ? <MediaPreconnect /> : null}
<JsonLdGraph schemas={[...shell.jsonLd, ...jsonLd]} />
<ConsentProvider cookieMap={cookieMap} logEndpoint={logEndpoint} texts={shell.consent}>
@@ -103,7 +110,7 @@ export function SiteProviders({
</TurnstileProvider>
{banner === undefined ? <CookieBanner /> : banner || null}
{cookieButton === undefined ? <CookieButton /> : cookieButton || null}
{analytics === false ? null : <Analytics {...shell.analytics} {...analytics} />}
{analytics === false ? null : <Analytics {...shell.analytics} nonce={nonce ?? undefined} {...analytics} />}
{stats ? <PageStats {...(stats === true ? {} : stats)} /> : null}
</ConsentProvider>
</>
+30 -1
View File
@@ -1,6 +1,9 @@
import type { BuildCspArgs } from '../security/buildCsp.js'
import type { I18nConfig } from './types.js'
import { MARKDOWN_PREFIX, markdownHref, prefersMarkdown } from '../content/markdownNegotiation.js'
import { buildCsp, buildReportingEndpoints } from '../security/buildCsp.js'
import { createCspNonce, CSP_NONCE_HEADER } from '../security/cspNonce.js'
import { isValidLocale } from './helpers.js'
import { createLocaleMiddleware, DEFAULT_MIDDLEWARE_MATCHER } from './localeMiddleware.js'
@@ -23,6 +26,8 @@ type ProxyRequest = {
type ProxyResponse = {
cookies: { set: (name: string, value: string, opts?: Record<string, unknown>) => void }
/** Needed for `csp`; Next's NextResponse has it. */
headers?: Headers
}
/**
@@ -40,6 +45,16 @@ type CreateProxyOptions = {
consentCategory?: 'functional' | 'necessary'
consentCookieName?: string
cookieName?: string
/**
* Content-Security-Policy with a per-request nonce (buildCsp args, no `nonce`).
* The proxy creates the nonce, puts the policy on the request (Next reads the
* nonce from it and adds it to its own scripts) and on the response, and
* exposes the nonce as the `x-nonce` request header for <SiteProviders nonce>.
* Nonces need dynamic rendering: every page under the matcher renders per
* request (no ISR / static HTML). Static sites keep the header-only CSP from
* buildSecurityHeaders `csp` instead. Default off.
*/
csp?: Omit<BuildCspArgs, 'nonce'>
/** Expose x-locale / x-pathname request headers to RSC. Default true. */
exposeHeaders?: boolean
/**
@@ -72,7 +87,7 @@ export function createProxy(
config: I18nConfig,
deps: { NextResponse: NextResponseLike } & CreateProxyOptions,
): (request: ProxyRequest) => ProxyResponse {
const { exposeHeaders = true, markdown, NextResponse, ...mwOptions } = deps
const { csp, exposeHeaders = true, markdown, NextResponse, ...mwOptions } = deps
const run = createLocaleMiddleware({ config, ...mwOptions })
const mdPrefix = markdown ? (typeof markdown === 'string' ? markdown : MARKDOWN_PREFIX).replace(/\/$/, '') : null
@@ -92,6 +107,12 @@ export function createProxy(
const result = run(request)
const requestHeaders = new Headers(request.headers)
const nonce = csp ? createCspNonce() : undefined
const policy = csp ? buildCsp({ ...csp, nonce }) : null
if (policy && nonce) {
requestHeaders.set(policy.key, policy.value)
requestHeaders.set(CSP_NONCE_HEADER, nonce)
}
if (exposeHeaders) {
const seg = pathname.split('/').filter(Boolean)[0] ?? ''
const locale = isValidLocale(seg, config) ? seg : config.defaultLocale
@@ -104,6 +125,14 @@ export function createProxy(
? NextResponse.redirect(new URL(result.location, request.url))
: NextResponse.next({ request: { headers: requestHeaders } })
if (policy) {
response.headers?.set(policy.key, policy.value)
if (csp?.reportUri) {
const re = buildReportingEndpoints(csp.reportUri, csp.reportGroup)
response.headers?.set(re.key, re.value)
}
}
if (result.cookie) {
response.cookies.set(result.cookie.name, result.cookie.value, {
path: '/',
+225 -32
View File
@@ -1,22 +1,8 @@
export type BuildCspArgs = {
/** Google Analytics / GTM — adds googletagmanager + google-analytics. */
analytics?: boolean
/** Extra sources per directive, merged with the built-ins. */
extra?: Partial<Record<CspDirective, string[]>>
/** Google Maps — embeds (iframe) and the Maps JavaScript API, full domain set. Google Fonts are allowed by default. */
googleMaps?: boolean
/** 'enforce' → Content-Security-Policy; 'report-only' → …-Report-Only header. */
mode?: 'enforce' | 'report-only'
/** Media/R2 public URL (from R2_PUBLIC_URL) — added to img-src. */
r2Url?: string
/** Cloudflare Turnstile — adds challenges.cloudflare.com to script/frame/connect. */
turnstile?: boolean
/** YouTube embeds — adds youtube to frame-src. */
youtube?: boolean
}
import type { SecurityHeader } from './buildSecurityHeaders.js'
type CspDirective =
export type CspDirective =
| 'base-uri'
| 'child-src'
| 'connect-src'
| 'default-src'
| 'font-src'
@@ -24,12 +10,76 @@ type CspDirective =
| 'frame-ancestors'
| 'frame-src'
| 'img-src'
| 'manifest-src'
| 'media-src'
| 'object-src'
| 'script-src'
| 'style-src'
| 'worker-src'
/** Sources per directive. Any directive name is accepted (also ones not in CspDirective). */
export type CspSources = Partial<Record<({} & string) | CspDirective, string[]>>
export type BuildCspArgs = {
/** Google Analytics / GTM — adds googletagmanager + google-analytics (+ Google Signals hosts). */
analytics?: boolean
/** Microsoft Clarity (plugin's loadClarity). */
clarity?: boolean
/**
* Development mode: adds 'unsafe-eval' to script-src (React / Next dev tooling
* needs it; production does not). Default `process.env.NODE_ENV === 'development'`.
*/
dev?: boolean
/** Extra sources per directive, merged with the built-ins. */
extra?: CspSources
/** Google Maps — embeds (iframe) and the Maps JavaScript API, full domain set. Google Fonts are allowed by default. */
googleMaps?: boolean
/** LinkedIn Insight Tag (plugin's loadLinkedIn). */
linkedIn?: boolean
/** Meta (Facebook) Pixel (plugin's loadMetaPixel / ConsentScript with fbevents.js). */
metaPixel?: boolean
/** 'enforce' → Content-Security-Policy; 'report-only' → …-Report-Only header. */
mode?: 'enforce' | 'report-only'
/**
* Per-request nonce (from the proxy — createProxy `csp`, or createCspNonce).
* Adds `'nonce-…'` to script-src and, with `strictDynamic` (default on with a
* nonce), `'strict-dynamic'`: scripts the nonced Next bootstrap loads are
* trusted, so host lists and 'unsafe-inline' stop mattering in CSP3 browsers
* (both stay as a fallback for old ones). Needs dynamic rendering — see docs.
*/
nonce?: string
/**
* Replace a directive completely (`null` drops it). Applied after everything
* else — the escape hatch when a built-in source does not fit the project.
*/
override?: Partial<Record<({} & string) | CspDirective, null | string[]>>
/** Media/R2 public URL (from R2_PUBLIC_URL) — added to img-src and media-src. */
r2Url?: string
/** Reporting API group name for `report-to` (and the Reporting-Endpoints header). Default 'csp-endpoint'. */
reportGroup?: string
/**
* Where browsers send violation reports, e.g. '/api/csp-report'
* (createCspReportRoute) or a third-party collector URL. Adds `report-uri`
* and `report-to`; buildCspHeaders also returns the Reporting-Endpoints header.
*/
reportUri?: string
/** With a nonce: add 'strict-dynamic'. Default true. */
strictDynamic?: boolean
/** TikTok Pixel (plugin's loadTikTok). */
tiktok?: boolean
/** Cloudflare Turnstile — adds challenges.cloudflare.com to script/frame/connect. */
turnstile?: boolean
/** YouTube embeds — adds youtube to frame-src. */
youtube?: boolean
}
export const DEFAULT_CSP_REPORT_GROUP = 'csp-endpoint'
/** Header name for the mode — the request header Next reads the nonce from is the same. */
export function cspHeaderKey(mode: BuildCspArgs['mode'] = 'enforce'): string {
return mode === 'report-only' ? 'Content-Security-Policy-Report-Only' : 'Content-Security-Policy'
}
/**
* Builds a Content-Security-Policy string with the hard OWASP/Lighthouse-required
* directives baked in, and opt-in sources for common third parties. Solves the
@@ -40,7 +90,8 @@ type CspDirective =
* helper standardizes the skeleton so every project's CSP has the same hardened
* base — you only flip flags for what the project actually loads.
*
* Returns { key, value } ready for buildSecurityHeaders `additional`:
* Returns { key, value } ready for buildSecurityHeaders `additional`
* (or pass the args as buildSecurityHeaders `csp`, which also adds Reporting-Endpoints):
*
* import { buildCsp, buildSecurityHeaders } from '@intecion/ipal-kit'
* const csp = buildCsp({
@@ -55,29 +106,61 @@ type CspDirective =
* missing sources via `extra`, THEN switch to 'enforce'. See docs/security.md.
*/
export function buildCsp(args: BuildCspArgs = {}): { key: string; value: string } {
const { analytics, extra = {}, googleMaps, mode = 'enforce', r2Url, turnstile, youtube } = args
const {
analytics,
clarity,
dev = process.env.NODE_ENV === 'development',
extra = {},
googleMaps,
linkedIn,
metaPixel,
mode = 'enforce',
nonce,
override = {},
r2Url,
reportGroup = DEFAULT_CSP_REPORT_GROUP,
reportUri,
strictDynamic = true,
tiktok,
turnstile,
youtube,
} = args
const src: Record<CspDirective, string[]> = {
'default-src': ["'self'"],
// 'unsafe-inline' is hard to avoid with Next/analytics; 'unsafe-eval' is NOT
// added by default (weakens CSP) — add via extra only if a library needs it.
const src: Record<string, string[]> = {
'connect-src': ["'self'"],
'default-src': ["'self'"],
'font-src': ["'self'", 'https://fonts.gstatic.com', 'data:'],
'form-action': ["'self'"],
'frame-src': [],
'img-src': ["'self'", 'data:', 'blob:'],
'media-src': [], // video/audio sources — filled via extra when needed
'media-src': [], // video/audio sources — filled via r2Url / extra
// Without a nonce: 'unsafe-inline' is required — Next streams its RSC payload
// in inline <script> tags that differ per page and per render, so neither a
// static header nor hashes can list them. With a nonce it is only a CSP2
// fallback (CSP3 browsers ignore it once a nonce is present).
// 'unsafe-eval' is NOT added in production (weakens CSP) — `dev` adds it.
'script-src': ["'self'", "'unsafe-inline'"],
// Styles: React/Next and the plugin set inline style attributes (positions,
// CSS variables) and next/font + experimental.inlineCss emit <style> tags —
// attributes cannot carry a nonce, so 'unsafe-inline' stays for style-src.
'style-src': ["'self'", "'unsafe-inline'", 'https://fonts.googleapis.com'],
'worker-src': [], // web workers — filled via extra when needed
'worker-src': [], // web workers — filled via googleMaps / extra
// HARD defaults (OWASP/Lighthouse) — always on, no reason to omit:
'base-uri': ["'self'"], // block <base> hijacking
'frame-ancestors': ["'none'"], // clickjacking protection (replaces X-Frame-Options)
'object-src': ["'none'"], // block <object>/<embed> (Flash-era attack surface)
}
if (nonce) {
src['script-src'].unshift(`'nonce-${nonce}'`, ...(strictDynamic ? ["'strict-dynamic'"] : []))
}
if (dev) {src['script-src'].push("'unsafe-eval'")}
// Site-relative R2_PUBLIC_URL ('/media', dev) is same-origin — already covered by 'self'.
if (r2Url && /^https?:\/\//i.test(r2Url)) {src['img-src'].push(r2Url)}
if (r2Url && /^https?:\/\//i.test(r2Url)) {
src['img-src'].push(r2Url)
src['media-src'].push("'self'", r2Url)
}
if (turnstile) {
src['script-src'].push('https://challenges.cloudflare.com')
@@ -89,9 +172,42 @@ export function buildCsp(args: BuildCspArgs = {}): { key: string; value: string
// Google's GA4/GTM CSP set. Wildcards are required: GA4 sends EU hits to
// region1.google-analytics.com and some to *.analytics.google.com — allowing
// only www.google-analytics.com blocks every hit ("data collection not active").
// doubleclick + www.google.com: Google Signals / Ads conversion pings.
src['script-src'].push('https://*.googletagmanager.com')
src['connect-src'].push('https://*.google-analytics.com', 'https://*.analytics.google.com', 'https://*.googletagmanager.com')
src['img-src'].push('https://*.google-analytics.com', 'https://*.googletagmanager.com')
src['connect-src'].push(
'https://*.google-analytics.com',
'https://*.analytics.google.com',
'https://*.googletagmanager.com',
'https://*.g.doubleclick.net',
'https://www.google.com',
)
src['img-src'].push('https://*.google-analytics.com', 'https://*.googletagmanager.com', 'https://*.g.doubleclick.net', 'https://www.google.com')
}
if (metaPixel) {
src['script-src'].push('https://connect.facebook.net')
src['connect-src'].push('https://www.facebook.com', 'https://connect.facebook.net')
src['img-src'].push('https://www.facebook.com')
src['frame-src'].push('https://www.facebook.com')
}
if (linkedIn) {
src['script-src'].push('https://snap.licdn.com')
src['connect-src'].push('https://px.ads.linkedin.com', 'https://px4.ads.linkedin.com', 'https://www.linkedin.com')
src['img-src'].push('https://px.ads.linkedin.com', 'https://px4.ads.linkedin.com', 'https://www.linkedin.com')
}
if (tiktok) {
src['script-src'].push('https://analytics.tiktok.com')
src['connect-src'].push('https://analytics.tiktok.com')
src['img-src'].push('https://analytics.tiktok.com')
}
if (clarity) {
// The tag loads from www.clarity.ms, then scripts.clarity.ms; data goes to *.clarity.ms.
src['script-src'].push('https://*.clarity.ms')
src['connect-src'].push('https://*.clarity.ms')
src['img-src'].push('https://*.clarity.ms', 'https://c.bing.com')
}
if (youtube) {
@@ -111,15 +227,92 @@ export function buildCsp(args: BuildCspArgs = {}): { key: string; value: string
}
// Merge caller extras.
for (const [dir, values] of Object.entries(extra) as Array<[CspDirective, string[]]>) {
for (const [dir, values] of Object.entries(extra)) {
if (values && values.length) {src[dir] = [...(src[dir] ?? []), ...values]}
}
const value = (Object.entries(src) as Array<[CspDirective, string[]]>)
if (reportUri) {
src['report-uri'] = [reportUri]
src['report-to'] = [reportGroup]
}
// Replace whole directives last.
for (const [dir, values] of Object.entries(override)) {
if (values === null) {delete src[dir]}
else if (values) {src[dir] = values}
}
const value = Object.entries(src)
.filter(([, values]) => values.length > 0)
.map(([dir, values]) => `${dir} ${[...new Set(values)].join(' ')}`)
.join('; ')
const key = mode === 'report-only' ? 'Content-Security-Policy-Report-Only' : 'Content-Security-Policy'
return { key, value }
return { key: cspHeaderKey(mode), value }
}
/**
* The CSP header plus, with `reportUri`, the Reporting-Endpoints header that
* `report-to` points at (Chrome/Edge use report-to; Firefox/Safari still use
* report-uri — the policy carries both).
*/
export function buildCspHeaders(args: BuildCspArgs = {}): SecurityHeader[] {
const headers: SecurityHeader[] = [buildCsp(args)]
if (args.reportUri) {headers.push(buildReportingEndpoints(args.reportUri, args.reportGroup))}
return headers
}
/** `Reporting-Endpoints: <group>="<url>"` — the target of CSP `report-to`. */
export function buildReportingEndpoints(url: string, group: string = DEFAULT_CSP_REPORT_GROUP): SecurityHeader {
return { key: 'Reporting-Endpoints', value: `${group}="${url}"` }
}
export type BuildAdminCspArgs = Pick<
BuildCspArgs,
'dev' | 'extra' | 'mode' | 'override' | 'r2Url' | 'reportGroup' | 'reportUri'
>
/**
* A separate, looser policy for Payload's admin (`/admin/:path*`). The admin is
* a large client app the project does not control: it needs inline scripts and
* styles, loads the Monaco code editor (code/JSON fields) from cdn.jsdelivr.net
* with blob: workers, and frames the site itself for Live Preview. The hard
* rules (base-uri, object-src, form-action) stay.
*
* async headers() {
* return [
* { source: '/:path*', headers: securityHeaders },
* { source: '/admin/:path*', headers: buildAdminCspHeaders({ mode: 'report-only' }) },
* ]
* }
*
* Next applies the last matching rule for the same header key, so the admin
* rule must come after the site-wide one.
*/
export function buildAdminCsp(args: BuildAdminCspArgs = {}): { key: string; value: string } {
const monaco = 'https://cdn.jsdelivr.net'
const adminExtra: CspSources = {
'connect-src': [monaco],
'font-src': [monaco],
'frame-src': ["'self'"], // Live Preview iframe
'img-src': ['https:'], // avatars, external upload previews
'script-src': [monaco],
'style-src': [monaco],
'worker-src': ["'self'", 'blob:'],
}
for (const [dir, values] of Object.entries(args.extra ?? {})) {
if (values) {adminExtra[dir] = [...(adminExtra[dir] ?? []), ...values]}
}
return buildCsp({
...args,
extra: adminExtra,
// Admin is never framed by another origin; Live Preview frames the SITE, not the admin.
override: { 'frame-ancestors': ["'self'"], ...args.override },
})
}
/** buildAdminCsp plus Reporting-Endpoints (with `reportUri`). */
export function buildAdminCspHeaders(args: BuildAdminCspArgs = {}): SecurityHeader[] {
const headers: SecurityHeader[] = [buildAdminCsp(args)]
if (args.reportUri) {headers.push(buildReportingEndpoints(args.reportUri, args.reportGroup))}
return headers
}
+19 -11
View File
@@ -1,4 +1,7 @@
import type { BuildCspArgs } from './buildCsp.js'
import { isSiteNoindex } from '../seo/siteNoindex.js'
import { buildCspHeaders } from './buildCsp.js'
/**
* A single HTTP header, in the shape Next.js next.config headers() expects.
@@ -7,10 +10,8 @@ export type SecurityHeader = { key: string; value: string }
export type BuildSecurityHeadersArgs = {
/**
* Extra headers to append or override. Same-key entries replace the default,
* so you can e.g. add your project's Content-Security-Policy here — CSP is
* intentionally NOT a default because it depends on the project's own
* domains (scripts, images, fonts, analytics). Keep CSP in your project.
* Extra headers to append or override. Same-key entries replace the default
* (and the `csp` headers), so a hand-written Content-Security-Policy fits here too.
*/
additional?: SecurityHeader[]
/**
@@ -21,6 +22,13 @@ export type BuildSecurityHeadersArgs = {
* that need window.opener; false to omit.
*/
coop?: 'same-origin' | 'same-origin-allow-popups' | false
/**
* Content-Security-Policy from buildCsp args — off by default, because a CSP
* lists the project's own domains. With `reportUri` the Reporting-Endpoints
* header is added too. Roll-out: `mode: 'report-only'` first, read the
* reports, then `mode: 'enforce'` (the only change). See docs/security.md.
*/
csp?: BuildCspArgs | false
/**
* X-Frame-Options value. 'DENY' (default) blocks all framing; 'SAMEORIGIN'
* allows same-origin framing. Note: CSP frame-ancestors supersedes this in
@@ -56,19 +64,16 @@ export type BuildSecurityHeadersArgs = {
* Permissions-Policy. These are identical across projects, so the plugin owns
* the boilerplate; the client spreads the result into next.config's headers().
*
* Content-Security-Policy is deliberately excluded: a useful CSP enumerates the
* exact domains a project loads from (its CDN, analytics, embeds), so it can't
* be generic without being either too loose (useless) or too strict (breaks the
* site). Add your project's CSP via `additional`.
* Content-Security-Policy is opt-in: a useful CSP enumerates the exact domains
* a project loads from (its CDN, analytics, embeds), so the project turns on the
* buildCsp flags it needs through `csp` (or passes its own via `additional`).
*
* @example
* // next.config.ts
* import { buildSecurityHeaders } from '@intecion/ipal-kit'
* const securityHeaders = buildSecurityHeaders({
* hsts: process.env.NODE_ENV === 'production', // off in dev over http
* additional: [
* { key: 'Content-Security-Policy', value: "default-src 'self'; ..." },
* ],
* csp: { mode: 'report-only', reportUri: '/api/csp-report', analytics: true },
* })
* const nextConfig = {
* async headers() {
@@ -80,6 +85,7 @@ export function buildSecurityHeaders(args: BuildSecurityHeadersArgs = {}): Secur
const {
additional = [],
coop = 'same-origin',
csp = false,
frameOptions = 'DENY',
hsts = true,
hstsIncludeSubDomains = true,
@@ -123,6 +129,8 @@ export function buildSecurityHeaders(args: BuildSecurityHeadersArgs = {}): Secur
headers.push({ key: 'X-Robots-Tag', value: 'noindex, nofollow' })
}
if (csp) {headers.push(...buildCspHeaders(csp))}
// Merge additional: same-key entries override the defaults above.
for (const extra of additional) {
const i = headers.findIndex((h) => h.key.toLowerCase() === extra.key.toLowerCase())
@@ -0,0 +1,121 @@
/** One CSP violation, normalised from either report format. */
export type CspViolation = {
blockedUri?: string
disposition?: string
documentUri?: string
effectiveDirective?: string
lineNumber?: number
originalPolicy?: string
sample?: string
sourceFile?: string
}
export type CreateCspReportRouteArgs = {
/** Largest accepted body in bytes; bigger requests get 413. Default 16 KB. */
maxBytes?: number
/**
* What to do with each violation. Default: one `console.warn` line per
* violation (Coolify keeps container logs — read them there). Plug in
* payload.logger, Sentry or a database write here.
*/
onReport?: (violation: CspViolation) => Promise<void> | void
}
type Raw = Record<string, unknown>
const str = (v: unknown): string | undefined => (typeof v === 'string' && v ? v : undefined)
function fromLegacy(r: Raw): CspViolation {
// report-uri: { "csp-report": { "document-uri", "violated-directive", … } }
return {
blockedUri: str(r['blocked-uri']),
disposition: str(r['disposition']),
documentUri: str(r['document-uri']),
effectiveDirective: str(r['effective-directive']) ?? str(r['violated-directive']),
lineNumber: typeof r['line-number'] === 'number' ? r['line-number'] : undefined,
originalPolicy: str(r['original-policy']),
sample: str(r['script-sample']),
sourceFile: str(r['source-file']),
}
}
function fromReportingApi(b: Raw): CspViolation {
// report-to: [{ type: 'csp-violation', body: { documentURL, effectiveDirective, … } }]
return {
blockedUri: str(b.blockedURL),
disposition: str(b.disposition),
documentUri: str(b.documentURL),
effectiveDirective: str(b.effectiveDirective),
lineNumber: typeof b.lineNumber === 'number' ? b.lineNumber : undefined,
originalPolicy: str(b.originalPolicy),
sample: str(b.sample),
sourceFile: str(b.sourceFile),
}
}
/** Parses a report body in either format (report-uri JSON or Reporting API array). */
export function parseCspReports(body: unknown): CspViolation[] {
if (Array.isArray(body)) {
return body
.filter((r): r is Raw => !!r && typeof r === 'object' && (r as Raw).type === 'csp-violation')
.map((r) => fromReportingApi(((r.body ?? {}) as Raw)))
}
if (body && typeof body === 'object' && 'csp-report' in body) {
const inner = (body as Raw)['csp-report']
return inner && typeof inner === 'object' ? [fromLegacy(inner as Raw)] : []
}
return []
}
/**
* A small collector for CSP violation reports — the `reportUri` target while
* the policy runs in report-only mode. Accepts both formats browsers send
* (`application/csp-report` from report-uri, `application/reports+json` from
* report-to), caps the body size, always answers 204, and never stores
* anything itself: by default each violation is one `console.warn` line.
*
* // app/api/csp-report/route.ts (outside Payload's /api/[...slug] — a fixed route wins)
* import { createCspReportRoute } from '@intecion/ipal-kit'
* export const POST = createCspReportRoute()
*
* Third-party alternative: point `reportUri` at report-uri.com, Sentry
* (security endpoint) or similar, and skip this route.
*/
export function createCspReportRoute(args: CreateCspReportRouteArgs = {}): (request: Request) => Promise<Response> {
const {
maxBytes = 16 * 1024,
onReport = (v: CspViolation) => {
console.warn(
`[csp] ${v.disposition ?? 'report'} ${v.effectiveDirective ?? '?'} blocked=${v.blockedUri ?? '?'} page=${v.documentUri ?? '?'}${v.sourceFile ? ` src=${v.sourceFile}:${v.lineNumber ?? ''}` : ''}`,
)
},
} = args
return async (request: Request) => {
const length = Number(request.headers.get('content-length') ?? 0)
if (length > maxBytes) {return new Response(null, { status: 413 })}
let text: string
try {
text = await request.text()
} catch {
return new Response(null, { status: 400 })
}
if (text.length > maxBytes) {return new Response(null, { status: 413 })}
let body: unknown
try {
body = JSON.parse(text)
} catch {
return new Response(null, { status: 400 })
}
for (const violation of parseCspReports(body).slice(0, 50)) {
try {
await onReport(violation)
} catch {
// a failing sink must not turn reports into errors in the browser
}
}
return new Response(null, { status: 204 })
}
}
+10
View File
@@ -0,0 +1,10 @@
/** Request header the proxy uses to hand the nonce to server components. */
export const CSP_NONCE_HEADER = 'x-nonce'
/**
* A fresh per-request nonce (base64 of a random UUID, 128 bits of randomness).
* Works in the Edge and Node runtimes (Web Crypto + btoa are globals in both).
*/
export function createCspNonce(): string {
return btoa(crypto.randomUUID())
}
+18 -3
View File
@@ -1,4 +1,19 @@
export { buildCsp } from './buildCsp.js'
export type { BuildCspArgs } from './buildCsp.js'
export {
buildAdminCsp,
buildAdminCspHeaders,
buildCsp,
buildCspHeaders,
buildReportingEndpoints,
cspHeaderKey,
DEFAULT_CSP_REPORT_GROUP,
} from './buildCsp.js'
export type { BuildAdminCspArgs, BuildCspArgs, CspDirective, CspSources } from './buildCsp.js'
export { buildSecurityHeaders, buildUploadSecurityHeaders } from './buildSecurityHeaders.js'
export type { BuildSecurityHeadersArgs, SecurityHeader, } from './buildSecurityHeaders.js'
export type { BuildSecurityHeadersArgs, SecurityHeader } from './buildSecurityHeaders.js'
export { createCspReportRoute, parseCspReports } from './createCspReportRoute.js'
export type { CreateCspReportRouteArgs, CspViolation } from './createCspReportRoute.js'
export { createCspNonce, CSP_NONCE_HEADER } from './cspNonce.js'
export { totpAdminPath, totpRedirectTarget } from './totp/totpRedirect.js'
export type { TotpRedirectArgs, TotpUser } from './totp/totpRedirect.js'
export { withSecurityConfig } from './withSecurityConfig.js'
export type { WithSecurityConfigOptions } from './withSecurityConfig.js'
@@ -0,0 +1,48 @@
'use client'
import type { ReactNode } from 'react'
import { useAuth, useConfig } from '@payloadcms/ui'
import { usePathname, useRouter } from 'next/navigation.js'
import { useEffect } from 'react'
import type { TotpUser } from './totpRedirect.js'
import { totpRedirectTarget } from './totpRedirect.js'
export type TotpRedirectProviderProps = {
children?: ReactNode
/** pluginOptions.forceSetup — set by the plugin (true: 2FA is enforced). */
forceSetup?: boolean
}
/**
* Admin provider that sends users to the 2FA setup / verify screens. Replaces
* @clocklimited/payload-2fa's TOTPProvider, which read the path from an
* `x-pathname` request header: on /admin no proxy sets it, so the path was
* null and the setup screen redirected to itself (`setup-totp?back=null`).
* Renders nothing while a redirect is pending, so the panel does not flash.
* Swap it with `twoFactor.provider`.
*/
export function TotpRedirectProvider({ children, forceSetup = true }: TotpRedirectProviderProps) {
const { user } = useAuth()
const { config } = useConfig()
const pathname = usePathname()
const router = useRouter()
const routes = config.admin?.routes
const target = totpRedirectTarget({
adminRoute: config.routes?.admin ?? '/admin',
excludePaths: [routes?.logout ?? '/logout', routes?.inactivity ?? '/logout-inactivity'],
forceSetup,
pathname,
user: user as null | TotpUser,
})
useEffect(() => {
if (target) {router.replace(target)}
}, [router, target])
return target ? null : children
}
export default TotpRedirectProvider
+53
View File
@@ -0,0 +1,53 @@
/** The admin user fields @clocklimited/payload-2fa adds (and Payload's `_strategy`). */
export type TotpUser = {
_strategy?: null | string
forceTotp?: boolean | null
hasTotp?: boolean | null
}
export type TotpRedirectArgs = {
/** config.routes.admin, e.g. '/admin' or '/'. */
adminRoute: string
/** Admin paths the redirect leaves alone (logout must still work). Default: '/logout', '/logout-inactivity'. */
excludePaths?: string[]
/** pluginOptions.forceSetup: every user without TOTP goes to the setup screen. */
forceSetup?: boolean
/** The current path, without origin or query (usePathname()). */
pathname: null | string | undefined
user: null | TotpUser | undefined
}
/** '/admin' + '/setup-totp' → '/admin/setup-totp'; an origin or trailing slash is dropped. */
export function totpAdminPath(adminRoute: string, path: string): string {
return normalize(`${adminRoute === '/' ? '' : adminRoute}${path}`)
}
function normalize(pathname: string): string {
const path = pathname.replace(/^[a-z][a-z\d+.-]*:\/\/[^/]+/i, '').replace(/[?#].*$/, '')
return path.replace(/\/+$/, '') || '/'
}
/**
* Where the admin should send this user for 2FA, or null to stay. Same rules as
* @clocklimited/payload-2fa's TOTPProvider — verify when TOTP is set up but this
* session has not passed it, setup when it is required but missing — with two
* fixes: the current path comes from the browser, never a request header the
* project may not set (its absence made the package's provider redirect to
* `setup-totp?back=null` forever), and the TOTP screens themselves (and logout)
* never redirect, whether the setup URL is relative or absolute (serverURL).
*/
export function totpRedirectTarget(args: TotpRedirectArgs): null | string {
const { adminRoute, excludePaths = ['/logout', '/logout-inactivity'], forceSetup, pathname, user } = args
if (!user || !pathname || user._strategy === 'api-key') {return null}
const here = normalize(pathname)
const setupUrl = totpAdminPath(adminRoute, '/setup-totp')
const verifyUrl = totpAdminPath(adminRoute, '/verify-totp')
const stay = [setupUrl, verifyUrl, ...excludePaths.map((p) => totpAdminPath(adminRoute, p))]
if (stay.includes(here)) {return null}
const back = `?back=${encodeURIComponent(here)}`
if (user.hasTotp) {return user._strategy && user._strategy !== 'totp' ? verifyUrl + back : null}
if (user.forceTotp || forceSetup) {return setupUrl + back}
return null
}
@@ -0,0 +1,55 @@
/**
* Minimal structural shape of a Next config — the plugin does not import `next`
* types into this helper; Next's real NextConfig satisfies it at the call site.
*/
type HeaderRule = { headers: { key: string; value: string }[] } & Record<string, unknown>
type NextConfigLike = {
headers?: () => HeaderRule[] | Promise<HeaderRule[]>
poweredByHeader?: boolean
}
export type WithSecurityConfigOptions = {
/**
* Remove `X-Powered-By` (Next's own "Next.js" and the "Next.js, Payload" that
* withPayload adds) — it tells scanners which software to target. Default true;
* `false` leaves the config's poweredByHeader as it is.
*/
hidePoweredBy?: boolean
}
/**
* Next config wrapper for the security settings that are not response headers
* the project adds itself. Today: hides `X-Powered-By`.
*
* Where the header comes from: Next sends `X-Powered-By: Next.js` unless
* `poweredByHeader: false`; Payload's withPayload switches Next's off and adds
* `X-Powered-By: Next.js, Payload` through headers() — also unless the config it
* wraps says `poweredByHeader: false`. This helper sets that flag AND drops the
* header from headers() rules, so it works on either side of withPayload:
*
* // next.config.ts
* import { withSecurityConfig } from '@intecion/ipal-kit'
* export default withPayload(withSecurityConfig(nextConfig))
*/
export function withSecurityConfig<T extends object>(
config: T,
options: WithSecurityConfigOptions = {},
): { poweredByHeader?: boolean } & T {
const { hidePoweredBy = true } = options
if (!hidePoweredBy) {return config}
const original = (config as NextConfigLike).headers
return {
...config,
poweredByHeader: false,
...(original
? {
headers: async () =>
(await original()).map((rule) => ({
...rule,
headers: rule.headers.filter((h) => h.key.toLowerCase() !== 'x-powered-by'),
})),
}
: {}),
}
}
+7 -3
View File
@@ -2,7 +2,10 @@ import type { ThemeConfig } from './theme.js'
import { themeScript } from './theme.js'
export type ThemeScriptProps = Partial<Pick<ThemeConfig, 'allowToggle' | 'defaultTheme'>>
export type ThemeScriptProps = {
/** CSP nonce (createProxy `csp` → `x-nonce` header) — needed when the policy uses nonces. */
nonce?: string
} & Partial<Pick<ThemeConfig, 'allowToggle' | 'defaultTheme'>>
/**
* Sets the theme on <html> BEFORE anything is painted — no flash of the light
@@ -12,6 +15,7 @@ export type ThemeScriptProps = Partial<Pick<ThemeConfig, 'allowToggle' | 'defaul
* const shell = await getSiteShell(locale)
* <html lang={locale} suppressHydrationWarning><body><ThemeScript {...shell.theme} />…
*/
export function ThemeScript({ allowToggle = false, defaultTheme = null }: ThemeScriptProps) {
return <script dangerouslySetInnerHTML={{ __html: themeScript({ allowToggle, defaultTheme }) }} />
export function ThemeScript({ allowToggle = false, defaultTheme = null, nonce }: ThemeScriptProps) {
// suppressHydrationWarning: browsers hide the nonce attribute from the DOM (nonce hiding).
return <script dangerouslySetInnerHTML={{ __html: themeScript({ allowToggle, defaultTheme }) }} nonce={nonce} suppressHydrationWarning />
}
+71 -15
View File
@@ -11,6 +11,7 @@ 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 { 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'
@@ -30,6 +31,9 @@ import { searchSettingsFields } from './modules/seo/searchSettings.js'
import { applyCollectionOverride } from './modules/shared/collectionOverride.js'
import { buildStatsCollection, buildStatsEndpoint } from './modules/stats/index.js'
/** The admin provider @clocklimited/payload-2fa registers; ipal-kit swaps it (twoFactor.provider). */
const TOTP_PACKAGE_PROVIDER = '@clocklimited/payload-2fa/rsc#TOTPProvider'
/**
* IPAL (Intecion Payload Advanced Library) plugin for Payload CMS 3.
*
@@ -181,6 +185,32 @@ export const ipalKit = (options: IpalOptions): Plugin => {
forceSetup: true, // ENFORCED — every user must set up TOTP; no opt-out
totp: { issuer: tf.issuer },
})(config)
// The package's TOTPProvider reads the path from an `x-pathname` header
// no proxy sets on /admin, so it redirected the setup screen to itself
// (`setup-totp?back=null`). Swap in ipal-kit's client-side provider, or
// the project's (`provider`); `provider: false` keeps the package's.
if (tf.provider !== false) {
const custom = tf.provider
const ours =
typeof custom === 'object' ? custom : { path: custom ?? '@intecion/ipal-kit/admin#TotpRedirectProvider' }
const providers = config.admin?.components?.providers ?? []
config.admin = {
...config.admin,
components: {
...config.admin?.components,
providers: providers.map((p) =>
p && (typeof p === 'string' ? p : p.path) === TOTP_PACKAGE_PROVIDER
? {
...ours,
clientProps: { forceSetup: true, ...ours.clientProps },
serverProps: { ...(typeof p === 'object' ? p.serverProps : {}), ...ours.serverProps },
}
: p,
),
},
}
}
}
// --- white-label admin branding ---
@@ -322,13 +352,36 @@ export const ipalKit = (options: IpalOptions): Plugin => {
// --- cookie scanner: review list + "Scan cookies" (opt-in) ---
if (options.cookieScanner) {
const scannerOptions = options.cookieScanner === true ? {} : options.cookieScanner
const adminRoute = options.adminRoute ?? '/admin'
const labels = mergeCookieScanLabels(scannerOptions.labels)
config.collections = [...(config.collections ?? []), applyCollectionOverride(buildCookieReviewCollection(scannerOptions), scannerOptions.collectionOverrides)]
const scanPlugin = { localeCount: options.i18n.locales.length, stats: Boolean(options.stats) }
config.endpoints = [...(config.endpoints ?? []), ...buildCookieScanEndpoints(scannerOptions, scanPlugin)]
// Browser crawl through the scanner service (opt-in): latest-result global, endpoints, dashboard warning.
if (scannerOptions.crawl) {
const crawl = scannerOptions.crawl === true ? {} : scannerOptions.crawl
const labels = mergeCookieScanLabels(scannerOptions.labels)
// 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 = buildCookieCrawlGlobal(labels)
const override = crawl.globalOverride
config.globals = [
@@ -336,17 +389,20 @@ export const ipalKit = (options: IpalOptions): Plugin => {
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 } },
],
},
}
}
// 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 } },
],
},
}
}
}
+12 -1
View File
@@ -1,4 +1,4 @@
import type { CollectionSlug, Field, Plugin } from 'payload'
import type { CollectionSlug, Field, PayloadComponent, Plugin } from 'payload'
/**
* Factory shape of @clocklimited/payload-2fa's `payloadTotp` export — injected
@@ -200,6 +200,17 @@ export type IpalOptions = {
* injected factory too. See docs/security.md.
*/
plugin: TotpPluginFactory
/**
* Admin provider that sends users to the TOTP setup / verify screens.
* Default: ipal-kit's `@intecion/ipal-kit/admin#TotpRedirectProvider`
* (reads the path in the browser). The package's own provider needs an
* `x-pathname` request header on every /admin request; without it the
* setup screen redirects to itself (`setup-totp?back=null`). Pass your
* own component path (it gets clientProps `forceSetup` and the package's
* serverProps `pluginOptions`), or `false` to keep the package's provider
* (then set `x-pathname` on /admin yourself). Run generate:importmap.
*/
provider?: false | PayloadComponent
}
| false
+206
View File
@@ -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)
})
})
+3 -1
View File
@@ -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 () => {
+250
View File
@@ -0,0 +1,250 @@
import type { NextConfig } from 'next'
import { withPayload } from '@payloadcms/next/withPayload'
import { describe, expect, test, vi } from 'vitest'
import type { I18nConfig } from '../src/modules/i18n/types.js'
import { createProxy } from '../src/modules/i18n/createProxy.js'
import {
buildAdminCsp,
buildAdminCspHeaders,
buildCsp,
buildCspHeaders,
buildSecurityHeaders,
createCspNonce,
createCspReportRoute,
parseCspReports,
withSecurityConfig,
} from '../src/modules/security/index.js'
const directive = (value: string, name: string) =>
value
.split('; ')
.find((d) => d.startsWith(`${name} `))
?.split(' ')
.slice(1) ?? null
describe('withSecurityConfig (X-Powered-By)', () => {
const payloadLike = { headers: [{ key: 'X-Powered-By', value: 'Next.js, Payload' }, { key: 'Vary', value: 'x' }], source: '/:path*' }
test('sets poweredByHeader: false (Next and withPayload both honour it)', () => {
expect(withSecurityConfig({}).poweredByHeader).toBe(false)
expect(withSecurityConfig({ poweredByHeader: true }).poweredByHeader).toBe(false)
})
test('strips X-Powered-By from headers() — works outside withPayload too', async () => {
const config: NextConfig = withSecurityConfig<NextConfig>({ headers: async () => [payloadLike, { headers: [{ key: 'x-powered-by', value: 'a' }], source: '/a' }] })
const rules = await config.headers!()
expect(rules.flatMap((r) => r.headers.map((h) => h.key))).toEqual(['Vary'])
expect(rules[0]?.source).toBe('/:path*')
})
test('real withPayload: no X-Powered-By on either side of the wrapper', async () => {
const keys = async (c: NextConfig) =>
(await c.headers!()).flatMap((r) => r.headers.map((h) => h.key.toLowerCase()))
expect(await keys(withPayload({}))).toContain('x-powered-by') // the problem being fixed
const inner = withPayload(withSecurityConfig({}))
expect(inner.poweredByHeader).toBe(false)
expect(await keys(inner)).not.toContain('x-powered-by')
const outer = withSecurityConfig(withPayload({}))
expect(outer.poweredByHeader).toBe(false)
expect(await keys(outer)).not.toContain('x-powered-by')
})
test('hidePoweredBy: false leaves the config untouched', () => {
const config = { poweredByHeader: true }
expect(withSecurityConfig(config, { hidePoweredBy: false })).toBe(config)
})
test('keeps the rest of the config', () => {
expect(withSecurityConfig<NextConfig>({ images: { formats: ['image/avif'] } })).toMatchObject({ images: { formats: ['image/avif'] } })
})
})
describe('buildCsp', () => {
test('mode picks the header; report-only first, enforce with one option', () => {
expect(buildCsp({ mode: 'report-only' }).key).toBe('Content-Security-Policy-Report-Only')
expect(buildCsp({ mode: 'enforce' }).key).toBe('Content-Security-Policy')
expect(buildCsp().key).toBe('Content-Security-Policy')
})
test('hard rules are always there', () => {
const { value } = buildCsp({ dev: false })
expect(directive(value, 'base-uri')).toEqual(["'self'"])
expect(directive(value, 'object-src')).toEqual(["'none'"])
expect(directive(value, 'frame-ancestors')).toEqual(["'none'"])
expect(directive(value, 'script-src')).toEqual(["'self'", "'unsafe-inline'"])
})
test('dev adds unsafe-eval; production does not', () => {
expect(directive(buildCsp({ dev: true }).value, 'script-src')).toContain("'unsafe-eval'")
expect(directive(buildCsp({ dev: false }).value, 'script-src')).not.toContain("'unsafe-eval'")
})
test('reportUri adds report-uri and report-to', () => {
const { value } = buildCsp({ reportUri: '/api/csp-report' })
expect(directive(value, 'report-uri')).toEqual(['/api/csp-report'])
expect(directive(value, 'report-to')).toEqual(['csp-endpoint'])
expect(directive(buildCsp({ reportGroup: 'g', reportUri: '/r' }).value, 'report-to')).toEqual(['g'])
})
test('nonce: nonce + strict-dynamic first in script-src; strictDynamic: false drops it', () => {
const script = directive(buildCsp({ dev: false, nonce: 'abc' }).value, 'script-src')
expect(script?.slice(0, 2)).toEqual(["'nonce-abc'", "'strict-dynamic'"])
expect(directive(buildCsp({ nonce: 'abc', strictDynamic: false }).value, 'script-src')).not.toContain("'strict-dynamic'")
})
test('every third party the plugin loads has a flag', () => {
const { value } = buildCsp({ analytics: true, clarity: true, linkedIn: true, metaPixel: true, r2Url: 'https://media.acme.pl', tiktok: true, turnstile: true, youtube: true })
const script = directive(value, 'script-src')!
for (const host of ['https://*.googletagmanager.com', 'https://connect.facebook.net', 'https://snap.licdn.com', 'https://analytics.tiktok.com', 'https://*.clarity.ms', 'https://challenges.cloudflare.com']) {
expect(script).toContain(host)
}
expect(directive(value, 'connect-src')).toEqual(expect.arrayContaining(['https://*.google-analytics.com', 'https://px.ads.linkedin.com', 'https://www.facebook.com']))
expect(directive(value, 'frame-src')).toEqual(expect.arrayContaining(['https://www.youtube-nocookie.com', 'https://challenges.cloudflare.com']))
expect(directive(value, 'img-src')).toEqual(expect.arrayContaining(['https://media.acme.pl', 'https://i.ytimg.com']))
expect(directive(value, 'media-src')).toEqual(["'self'", 'https://media.acme.pl'])
})
test('site-relative r2Url is covered by self', () => {
expect(directive(buildCsp({ r2Url: '/media' }).value, 'img-src')).toEqual(["'self'", 'data:', 'blob:'])
})
test('extra extends any directive, override replaces or drops one', () => {
const { value } = buildCsp({
extra: { 'manifest-src': ["'self'"], 'script-src': ['https://x.example'] },
override: { 'frame-ancestors': ["'self'"], 'style-src': null },
})
expect(directive(value, 'script-src')).toContain('https://x.example')
expect(directive(value, 'manifest-src')).toEqual(["'self'"])
expect(directive(value, 'frame-ancestors')).toEqual(["'self'"])
expect(directive(value, 'style-src')).toBeNull()
})
test('buildCspHeaders adds Reporting-Endpoints only with reportUri', () => {
expect(buildCspHeaders({}).map((h) => h.key)).toEqual(['Content-Security-Policy'])
expect(buildCspHeaders({ mode: 'report-only', reportUri: '/api/csp-report' })).toEqual([
expect.objectContaining({ key: 'Content-Security-Policy-Report-Only' }),
{ key: 'Reporting-Endpoints', value: 'csp-endpoint="/api/csp-report"' },
])
})
})
describe('buildAdminCsp', () => {
test('looser policy for Payload admin: Monaco CDN, blob workers, framed by self', () => {
const { value } = buildAdminCsp({ dev: false, r2Url: 'https://media.acme.pl' })
expect(directive(value, 'script-src')).toEqual(["'self'", "'unsafe-inline'", 'https://cdn.jsdelivr.net'])
expect(directive(value, 'worker-src')).toEqual(["'self'", 'blob:'])
expect(directive(value, 'frame-ancestors')).toEqual(["'self'"])
expect(directive(value, 'object-src')).toEqual(["'none'"])
expect(directive(value, 'img-src')).toContain('https://media.acme.pl')
})
test('extra merges with the admin sources instead of replacing them', () => {
expect(directive(buildAdminCsp({ extra: { 'script-src': ['https://y.example'] } }).value, 'script-src')).toEqual(
expect.arrayContaining(['https://cdn.jsdelivr.net', 'https://y.example']),
)
})
test('report-only + Reporting-Endpoints', () => {
expect(buildAdminCspHeaders({ mode: 'report-only', reportUri: '/r' }).map((h) => h.key)).toEqual([
'Content-Security-Policy-Report-Only',
'Reporting-Endpoints',
])
})
})
describe('buildSecurityHeaders csp', () => {
test('off by default', () => {
expect(buildSecurityHeaders().some((h) => /content-security/i.test(h.key))).toBe(false)
})
test('csp args add the policy and Reporting-Endpoints; additional still overrides', () => {
const headers = buildSecurityHeaders({ csp: { mode: 'report-only', reportUri: '/api/csp-report' } })
expect(headers.map((h) => h.key)).toEqual(expect.arrayContaining(['Content-Security-Policy-Report-Only', 'Reporting-Endpoints']))
const own = buildSecurityHeaders({
additional: [{ key: 'Content-Security-Policy-Report-Only', value: "default-src 'self'" }],
csp: { mode: 'report-only' },
})
expect(own.filter((h) => h.key === 'Content-Security-Policy-Report-Only')).toEqual([{ key: 'Content-Security-Policy-Report-Only', value: "default-src 'self'" }])
})
})
describe('createCspReportRoute', () => {
const post = (body: string, type = 'application/csp-report') =>
new Request('https://acme.pl/api/csp-report', { body, headers: { 'content-type': type }, method: 'POST' })
test('report-uri format', async () => {
const onReport = vi.fn()
const res = await createCspReportRoute({ onReport })(
post(JSON.stringify({ 'csp-report': { 'blocked-uri': 'https://evil.example/x.js', 'document-uri': 'https://acme.pl/pl', 'violated-directive': 'script-src-elem' } })),
)
expect(res.status).toBe(204)
expect(onReport).toHaveBeenCalledWith(expect.objectContaining({ blockedUri: 'https://evil.example/x.js', effectiveDirective: 'script-src-elem' }))
})
test('Reporting API format, other report types ignored', async () => {
const onReport = vi.fn()
await createCspReportRoute({ onReport })(
post(
JSON.stringify([
{ type: 'csp-violation', body: { blockedURL: 'inline', disposition: 'report', documentURL: 'https://acme.pl/', effectiveDirective: 'script-src-elem' } },
{ type: 'deprecation', body: {} },
]),
'application/reports+json',
),
)
expect(onReport).toHaveBeenCalledTimes(1)
expect(onReport.mock.calls[0][0]).toMatchObject({ blockedUri: 'inline', disposition: 'report' })
})
test('bad JSON → 400, too big → 413, failing sink still 204', async () => {
expect((await createCspReportRoute()(post('{nope'))).status).toBe(400)
expect((await createCspReportRoute({ maxBytes: 10 })(post(JSON.stringify({ 'csp-report': { a: 'x'.repeat(50) } })))).status).toBe(413)
const throwing = createCspReportRoute({ onReport: () => { throw new Error('x') } })
expect((await throwing(post(JSON.stringify({ 'csp-report': {} })))).status).toBe(204)
})
test('parseCspReports ignores unknown shapes', () => {
expect(parseCspReports(null)).toEqual([])
expect(parseCspReports({ foo: 1 })).toEqual([])
})
})
describe('createProxy csp (nonce)', () => {
const config: I18nConfig = { defaultLocale: 'pl', locales: [{ code: 'pl', label: 'Polski' }] }
type Res = { cookies: { set: () => void }; headers: Headers; init?: { request?: { headers: Headers } } }
const NextResponse = {
next: (init?: { request?: { headers: Headers } }): Res => ({ cookies: { set: () => {} }, headers: new Headers(), init }),
redirect: (): Res => ({ cookies: { set: () => {} }, headers: new Headers() }),
}
const request = (path: string) => {
const url = new URL(`https://acme.pl${path}`)
return { cookies: { get: () => undefined }, headers: new Headers(), nextUrl: { clone: () => new URL(url), pathname: url.pathname, search: url.search }, url: url.toString() }
}
test('fresh nonce per request on the request (for Next) and response, x-nonce for the layout', () => {
const proxy = createProxy(config, { csp: { mode: 'report-only', reportUri: '/api/csp-report' }, NextResponse })
const a = proxy(request('/pl')) as unknown as Res
const b = proxy(request('/pl')) as unknown as Res
const nonce = a.init!.request!.headers.get('x-nonce')!
expect(nonce).toMatch(/^[A-Z0-9+/=]{20,}$/i)
expect(b.init!.request!.headers.get('x-nonce')).not.toBe(nonce)
const policy = a.headers.get('Content-Security-Policy-Report-Only')!
expect(policy).toContain(`'nonce-${nonce}'`)
expect(a.init!.request!.headers.get('Content-Security-Policy-Report-Only')).toBe(policy)
expect(a.headers.get('Reporting-Endpoints')).toBe('csp-endpoint="/api/csp-report"')
})
test('no csp → no CSP headers', () => {
const res = createProxy(config, { NextResponse })(request('/pl')) as unknown as Res
expect(res.headers.get('Content-Security-Policy')).toBeNull()
expect(res.init!.request!.headers.get('x-nonce')).toBeNull()
})
test('createCspNonce is unique base64', () => {
expect(createCspNonce()).not.toBe(createCspNonce())
expect(atob(createCspNonce())).toMatch(/^[0-9a-f-]{36}$/)
})
})
+85
View File
@@ -0,0 +1,85 @@
import type { Config } from 'payload'
import { payloadTotp } from '@clocklimited/payload-2fa'
import { describe, expect, it } from 'vitest'
import { ipalKit } from '../src/index.js'
import { totpRedirectTarget } from '../src/modules/security/totp/totpRedirect.js'
const i18n = { defaultLocale: 'pl', locales: [{ code: 'pl', label: 'Polski' }] }
const fresh = { _strategy: 'local-jwt', hasTotp: false }
const base = (): Config =>
({ admin: { user: 'users' }, collections: [{ slug: 'users', auth: true, fields: [] }] }) as unknown as Config
const providerPaths = (config: Config) =>
(config.admin?.components?.providers ?? []).map((p) => (typeof p === 'object' && p ? p.path : p))
/** Follows the redirects the provider would make, the way a browser would. */
function walk(start: string, user: typeof fresh, adminRoute = '/admin') {
const visited = [start]
let url = start
for (let i = 0; i < 5; i++) {
const next = totpRedirectTarget({ adminRoute, forceSetup: true, pathname: url.split('?')[0], user })
if (!next) {return visited}
url = next
visited.push(url)
}
throw new Error(`redirect loop: ${visited.join(' → ')}`)
}
describe('2FA setup redirect (fresh admin, forceSetup)', () => {
it('lands on the setup screen once, with the page to return to — no loop, no back=null', () => {
expect(walk('/admin', fresh)).toEqual(['/admin', '/admin/setup-totp?back=%2Fadmin'])
expect(walk('/admin/collections/pages', fresh).at(-1)).toBe('/admin/setup-totp?back=%2Fadmin%2Fcollections%2Fpages')
})
it('stays on the setup and verify screens, with or without a trailing slash', () => {
for (const pathname of ['/admin/setup-totp', '/admin/setup-totp/', '/admin/verify-totp']) {
expect(totpRedirectTarget({ adminRoute: '/admin', forceSetup: true, pathname, user: fresh })).toBeNull()
}
})
it('never redirects on an unknown path (the package read a missing header as null → back=null)', () => {
expect(totpRedirectTarget({ adminRoute: '/admin', forceSetup: true, pathname: null, user: fresh })).toBeNull()
})
it('works with a custom admin route and lets logout through', () => {
expect(walk('/its', fresh, '/its')).toEqual(['/its', '/its/setup-totp?back=%2Fits'])
expect(walk('/', fresh, '/')).toEqual(['/', '/setup-totp?back=%2F'])
expect(totpRedirectTarget({ adminRoute: '/admin', forceSetup: true, pathname: '/admin/logout', user: fresh })).toBeNull()
})
it('sends a user with TOTP to verify until this session passed it; api keys pass', () => {
const user = { _strategy: 'local-jwt', hasTotp: true }
expect(walk('/admin', user)).toEqual(['/admin', '/admin/verify-totp?back=%2Fadmin'])
expect(walk('/admin', { _strategy: 'totp', hasTotp: true })).toEqual(['/admin'])
expect(walk('/admin', { _strategy: 'api-key', hasTotp: false })).toEqual(['/admin'])
})
it('leaves users alone when setup is not forced', () => {
expect(totpRedirectTarget({ adminRoute: '/admin', pathname: '/admin', user: fresh })).toBeNull()
})
})
describe('twoFactor.provider', () => {
const run = (provider?: unknown) =>
ipalKit({ i18n, twoFactor: { issuer: 'Test', plugin: payloadTotp, ...(provider === undefined ? {} : { provider }) } } as never)(base())
it("replaces the package's header-based provider with ipal-kit's by default", async () => {
const config = await run()
expect(providerPaths(config)).toContain('@intecion/ipal-kit/admin#TotpRedirectProvider')
expect(providerPaths(config)).not.toContain('@clocklimited/payload-2fa/rsc#TOTPProvider')
const ours = config.admin?.components?.providers?.find(
(p) => typeof p === 'object' && p && p.path === '@intecion/ipal-kit/admin#TotpRedirectProvider',
)
expect(ours).toMatchObject({ clientProps: { forceSetup: true } })
})
it('takes a project component, or false to keep the package provider', async () => {
expect(providerPaths(await run('@/components/MyTotp#MyTotp'))).toContain('@/components/MyTotp#MyTotp')
const kept = await run(false)
expect(providerPaths(kept)).toContain('@clocklimited/payload-2fa/rsc#TOTPProvider')
expect(providerPaths(kept)).not.toContain('@intecion/ipal-kit/admin#TotpRedirectProvider')
})
})