diff --git a/docs/agent/AGENT.md b/docs/agent/AGENT.md index 9163eb3..a487039 100644 --- a/docs/agent/AGENT.md +++ b/docs/agent/AGENT.md @@ -881,7 +881,7 @@ project → **plugin gap**, not a copy. |---|---|---| | Metadata, canonical, hreflang, OG, X | `generatePageMetadata` (`createPageRoute` does it itself) | seo.md | | sitemap / robots / manifest | `sitemapRoute` (splits into a sitemap index above 10 000 URLs; `sitemapOptions`, `sitemapEntries`), `getRobots` (panel) / `robots` (code only), `manifest` | seo.md | -| Search Console / Bing verification, AI crawler policy, llms.txt note | Site Settings → Search & AI (`seo.searchSettings`); building blocks `verificationFrom`, `robotsOptionsFrom` | seo.md | +| Search Console / Bing verification, AI crawler policy, llms.txt note | Site Settings → Search & AI (`searchSettings`); building blocks `verificationFrom`, `robotsOptionsFrom` | seo.md | | JSON-LD | `getSiteShell().jsonLd`, `getPageJsonLd`, `build*JsonLd`, `formatOpeningHours`, `sameAsUrls`, `` | seo.md | | Product / category JSON-LD (an entry that is not an article) | `pageJsonLd.entries` + `buildProductJsonLd` | seo.md | | llms.txt / llms-full / Markdown / MCP | `llmsRoute`, `llmsFullRoute`, `markdownRoute`, `mcpGET`/`mcpPOST`; `markdownAlternate: true`; `createProxy({ markdown: true })` | seo.md, content.md, mcp.md | @@ -926,6 +926,8 @@ payloadTotp } })`, never `twoFactor: false` without a client decision). CSP: fir |---|---|---| | Plugin globals: write editor+ (Site Integrations: admin) | — | `ipalKit({ globalOverrides: { : { access, admin, hooks } } })`; a function `(global) => global` takes over (`applyGlobalOverrides`) | | Global saves revalidate the layout (with `ipalKit({ revalidatePath })`) | omit `revalidatePath`; once: `context: { disableRevalidate: true }` | `buildGlobalRevalidateHook` on your own globals | +| Staff features without `access` (no roles field): every logged-in account passes (`userMeetsRole`) | add `access` (roles decide) | `globalOverrides`, `forms.formSubmissionOverrides`, `consentLog.collectionOverrides`, `stats.collectionOverrides` | +| 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` | @@ -938,7 +940,7 @@ payloadTotp } })`, never `twoFactor: false` without a client decision). CSP: fir | 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) | | `RenderRichText` renders unsafe link URLs as `#` | `safeLinks={false}` (fully trusted content only) | your own `converters` | -| Search & AI tab in Site Settings | `seo.searchSettings: false` | `searchSettings: (fields) => fields`; `verificationFrom`, `robotsOptionsFrom` | +| Search & AI tab in Site Settings | `searchSettings: false` (top level, works without `seo`; `seo.searchSettings` still works) | `searchSettings: (fields) => fields`; `verificationFrom`, `robotsOptionsFrom` | | Verification `` from the panel | empty fields = no tag | `const { verification, ...meta } = await generatePageMetadata(…)` | | AI crawler policy from the panel | `robots` instead of `getRobots`; policy `default` | `buildRobots({ ...robotsOptionsFrom(settings), aiBotRules })`; `AI_ASSISTANT_BOTS`, `AI_TRAINING_BOTS` | | Sitemap split / CDN cache / memo | `sitemapOptions: { maxUrls: Infinity, cacheControl: false, memoSeconds: 0 }` | `sitemapEntries`, `createSitemapRouteHandler`, `buildSitemapIndexXml`, `buildSitemapEntries` | diff --git a/docs/agent/skills/ipal-reference/SKILL.md b/docs/agent/skills/ipal-reference/SKILL.md index 3aff430..3aae002 100644 --- a/docs/agent/skills/ipal-reference/SKILL.md +++ b/docs/agent/skills/ipal-reference/SKILL.md @@ -50,7 +50,8 @@ description: Complete map of everything @intecion/ipal-kit provides — every ip | `seo.fields` | `[]` | extra fields in the SEO group | — | | `seo.uploadsCollection` | `'media'` | upload collection `meta.image` relates to | any upload collection slug | | `seo.generateTitle` / `generateDescription` | plugin-seo | preview / generation in the panel | your own function `({ doc }) => string` | -| `seo.searchSettings` | on (also without `seo`) | Site Settings → **Search & AI** tab: `searchVerification.google/bing/yandex` (→ `` via `generatePageMetadata`), `aiCrawlers.policy` + `aiCrawlers.rules[]` (→ robots.txt via `getRobots`), localized `llmsIntro` (→ top of `/llms.txt`); empty fields change nothing. Postgres: `migrate:create` after upgrading | `false` = no tab (without `seo`: `globalOverrides['site-settings']` function); `(fields) => fields` = your own set (keep the names `searchVerification`, `aiCrawlers`, `llmsIntro` or read your own fields in your routes) | +| `seo.searchSettings` | on (also without `seo`) | Site Settings → **Search & AI** tab: `searchVerification.google/bing/yandex` (→ `` via `generatePageMetadata`), `aiCrawlers.policy` + `aiCrawlers.rules[]` (→ robots.txt via `getRobots`), localized `llmsIntro` (→ top of `/llms.txt`); empty fields change nothing. Postgres: `migrate:create` after upgrading | `false` = no tab (needs `seo`; without `seo` use the top-level `searchSettings`); `(fields) => fields` = your own set (keep the names `searchVerification`, `aiCrawlers`, `llmsIntro` or read your own fields in your routes) | +| `searchSettings` | on | same tab as `seo.searchSettings`, but works **without `seo`**; wins over `seo.searchSettings` | `false` = no tab; `(fields) => fields` = your own set | | — (no option) | `uploadsCollection: 'media'` | meta image from the `media` collection | currently always `media` (gap) | | `forms` | none | `@payloadcms/plugin-form-builder`: `forms`, `form-submissions` collections | omit | | `forms.adminGroup` | `'Forms'` | sidebar group | `false` = Payload default; `admin.group` in overrides wins | @@ -62,7 +63,9 @@ description: Complete map of everything @intecion/ipal-kit provides — every ip | `forms.beforeEmail` | none | your own e-mail changes (after the layout) | form-builder function | | `forms.consentFieldName` | `'consent'` | name of the GDPR consent field `submitForm` requires (read from `config.custom.ipal`) | `createSubmitAction({ consentFieldName })` / `submitForm` argument wins | | `consentLog` | off | `consent-records` collection + `POST /api/ipal/consent` (rate limit 20/min) | `true` / `{ retentionDays }` (default 1095) | +| `consentLog.collectionOverrides` | none | changes `consent-records`: an object merges `access` / `admin` / `hooks` key by key (your keys win), a function `(collection) => collection` takes over (keep the slug) | e.g. `{ access: { read: ({ req }) => req.user?.email === 'dpo@acme.pl' } }` — narrows who reads records in a project without roles | | `stats` | off | `stats-visits` collection, `POST /api/ipal/hit`, `//stats` view, nav link, dashboard chart | `true` / object | +| `stats.collectionOverrides` | none | changes `stats-visits` like `consentLog.collectionOverrides`; its `access.read` also decides who sees the stats view and dashboard chart | object or function | | `stats.retentionDays` / `timeZone` / `dashboard` | 90 / `'Europe/Warsaw'` / `true` | retention, day boundary, `StatsWidget` | `dashboard: false` hides the chart | | `indexNow` | `false` | `afterChange` hook (publish → IndexNow, production + https only) in the `pages.slug ?? 'pages'` collection and each one from `content` | `true` + `indexnow-key.txt` route | | `siteSettingsFields` | none | **Custom** tab in Site Settings | `Field[]` | @@ -77,9 +80,9 @@ description: Complete map of everything @intecion/ipal-kit provides — every ip |---|---|---|---| | auth collection (`users`) | `{ slug, auth: true, useAsTitle: 'email' }`, when the project has none (slug: `access.authCollection` → `twoFactor.collectionSlug` → `admin.user` → `'users'`); with `access`: create/delete/unlock admin only, read/update admin or self | `access.authAccess`; your own collection with that slug | yours wins | | `forms`, `form-submissions` | form-builder + ipal blocks `step`, `checkboxGroup`, `time` | `forms` | omit `forms` | -| `consent-records` | proof of consent (id, choices, policy version) | `consentLog` | off by default | -| `stats-visits` | visits without IP (admin reads/deletes) | `stats` | off by default | -| global `site-settings` | General, Theme, [System Pages], [Emails], [Under construction], Search & AI, [Custom]; public read, write editor+ | `pages`, `content`, `forms.emailLayout`, `seo.searchSettings`, `siteSettingsFields` | always present; access/hooks/fields: `globalOverrides` | +| `consent-records` | proof of consent (id, choices, policy version; `consentLog.collectionOverrides`) | `consentLog` | off by default | +| `stats-visits` | visits without IP (admin reads/deletes; `stats.collectionOverrides`) | `stats` | off by default | +| global `site-settings` | General, Theme, [System Pages], [Emails], [Under construction], Search & AI, [Custom]; public read, write editor+ | `pages`, `content`, `forms.emailLayout`, `searchSettings` / `seo.searchSettings`, `siteSettingsFields` | always present; access/hooks/fields: `globalOverrides` | | global `site-integrations` | Analytics, Turnstile, SMTP, IndexNow, [Custom]; admin only | `integrationsFields` | always present; `globalOverrides` | | global `cookie-settings` | banner texts, categories, cookie list; public read, write editor+ | `globalOverrides` | always present; `globalOverrides` | | global `notifications` | form messages per language; public read, write editor+ | `globalOverrides` | always present; `globalOverrides` | diff --git a/docs/agent/skills/ipal-reference/resources/api.md b/docs/agent/skills/ipal-reference/resources/api.md index ffc5290..10b545d 100644 --- a/docs/agent/skills/ipal-reference/resources/api.md +++ b/docs/agent/skills/ipal-reference/resources/api.md @@ -12,7 +12,7 @@ project wires: `../SKILL.md`. Module details: `node_modules/@intecion/ipal-kit/d |---|---|---| | `ipalKit(options)` | `@intecion/ipal-kit` | Payload 3 plugin (`plugins: [ipalKit({...})]`) — the only wiring point: adds globals (SiteSettings, SiteIntegrations, CookieSettings, Notifications), roles, enforced 2FA, SEO, forms, i18n (localization), white-label, stats, consent log, `/api/ipal/*` endpoints; no auth collection → injects a simple `users`. Validates `i18n` right away (fail fast). `enabled: false` = schema stays, behaviour off. | -**Types:** `IpalOptions` — `ipalKit()` options: `i18n`, `access`, `twoFactor` (`{ issuer, plugin: payloadTotp }` or `false`), `whiteLabel`, `adminRoute`, `consentLog`, `content`, `forms`, `pages`, `seo`, `stats`, `indexNow`, `siteSettingsFields`, `integrationsFields`, `globalOverrides`, `revalidatePath`, `enabled`. `GlobalOverride`, `GlobalOverrides`, `IpalGlobalSlug` — see Payload globals below. +**Types:** `IpalOptions` — `ipalKit()` options: `i18n`, `access`, `twoFactor` (`{ issuer, plugin: payloadTotp }` or `false`), `whiteLabel`, `adminRoute`, `consentLog`, `content`, `forms`, `pages`, `seo`, `searchSettings`, `stats`, `indexNow`, `siteSettingsFields`, `integrationsFields`, `globalOverrides`, `revalidatePath`, `enabled`. `GlobalOverride`, `GlobalOverrides`, `IpalGlobalSlug` — see Payload globals below. ## Admin (import map) (`admin`, `branding`, `admin-ui`, `globals/SiteIntegrations`) — details: `node_modules/@intecion/ipal-kit/docs/white-label.md`, `…/docs/integrations.md`, `…/docs/email.md`, `…/docs/links.md` @@ -77,6 +77,7 @@ Admin panel components from `@intecion/ipal-kit/admin` — the project does NOT | Export | Import from | What it does / when | |---|---|---| | `getAnalyticsConfig(payload)` | `@intecion/ipal-kit` | Server: reads public tag IDs (GA4, GTM, Meta Pixel, Clarity, LinkedIn, TikTok) from SiteIntegrations, validates the format → `Promise`; pass the result to ``. | +| `shouldLoadGoogle({ consentMode, ready, state })` | `@intecion/ipal-kit/client`, `@intecion/ipal-kit` | Pure consent gate (no React/DOM) → `boolean`: may the Google tag load now? `'basic'` waits for an analytics or marketing grant, `'advanced'` loads once `ready`. `` uses it; apply the same rule to your own Google-dependent code. | | `Analytics` | `@intecion/ipal-kit/client` | Loads all configured tags respecting consent: Google through Consent Mode, the rest only after consent for the category (marketing / analytics). Props = `AnalyticsConfig` + `defer`, `deferTimeoutMs`, `consentMode` (`'advanced'` default: the Google tag loads at once with every signal `denied`; `'basic'`: no request to Google before analytics or marketing consent). Renders nothing; mount once inside `ConsentProvider`. Do not add tags by hand. | | `pushDataLayer(event, params?)` | `@intecion/ipal-kit/client` | Pushes an event to the GTM `window.dataLayer` (SSR-safe, buffers before GTM loads). E.g. `form_submit` after a form is sent (`docs/gtm-meta-pixel.md`). | | `loadMetaPixel(id)` | `@intecion/ipal-kit/client` | Low-level Meta Pixel loader (idempotent, PageView). `Analytics` calls it itself after marketing consent — call by hand only in unusual cases, and only after consent. | @@ -401,8 +402,9 @@ The editor builds forms in the panel (Forms collection). The project does NOT wr | `SITE_SETTINGS_SLUG` | `@intecion/ipal-kit` | Constant: global slug `'site-settings'` | | `SITE_INTEGRATIONS_SLUG` | `@intecion/ipal-kit` | Constant: global slug `'site-integrations'` | | `applyGlobalOverrides(globals, overrides)` | `@intecion/ipal-kit` | Applies `ipalKit({ globalOverrides })` to the plugin's globals: an object merges `access` / `admin` / `hooks` key by key (your keys win, your hooks run after the plugin's), other keys replace; a function `(global) => global` takes over. The plugin calls it itself — pass `globalOverrides`, do not call. | +| `applyCollectionOverride(collection, override)` | `@intecion/ipal-kit` | Same rules for one collection: an object merges `access` / `admin` / `hooks` key by key, other keys replace; a function takes over. The plugin applies `consentLog.collectionOverrides` and `stats.collectionOverrides` with it; use it on your own builder output (e.g. `buildConsentLogCollection()`). | -**Types:** `GlobalQueryOptions` — `{ locale?, depth? }` of the global helpers; `IpalGlobalSlug` (`'site-settings' \| 'site-integrations' \| 'cookie-settings' \| 'notifications'`), `GlobalOverride` (object or function), `GlobalOverrides` (map slug → override) — the `globalOverrides` option. +**Types:** `GlobalQueryOptions` — `{ locale?, depth? }` of the global helpers; `IpalGlobalSlug` (`'site-settings' \| 'site-integrations' \| 'cookie-settings' \| 'notifications'`), `GlobalOverride` (object or function), `GlobalOverrides` (map slug → override) — the `globalOverrides` option. `CollectionOverride` (object or function) — `consentLog.collectionOverrides` / `stats.collectionOverrides`. ## Rich text (`richtext`) — details: `node_modules/@intecion/ipal-kit/docs/richtext.md` diff --git a/docs/agent/skills/ipal-setup/SKILL.md b/docs/agent/skills/ipal-setup/SKILL.md index caa6158..e93711d 100644 --- a/docs/agent/skills/ipal-setup/SKILL.md +++ b/docs/agent/skills/ipal-setup/SKILL.md @@ -366,7 +366,7 @@ or your own text; `buildSecurityHeaders({ frameOptions, coop, hsts, additional } overrides the default; CSP: `buildCsp` flags (`youtube`, `googleMaps`, `extra`), after a clean console `mode: 'enforce'`; `buildImagesConfig({ extraHosts })`; env validation is fully opt-in — filter/add rules (`ipalEnvRules(…).filter(…)`). Staging: `IPAL_NOINDEX=1` (also stops IndexNow). Search & AI: `robots` instead of -`getRobots` ignores the panel; `seo: { …, searchSettings: false }` removes the tab; per-bot exceptions in code: +`getRobots` ignores the panel; `ipalKit({ searchSettings: false })` removes the tab; per-bot exceptions in code: `createContentHelpers({ robots: { aiBotRules: [{ userAgent, access }] } })`. Sitemap: `sitemapOptions: { maxUrls, cacheControl, memoSeconds }`, `sitemapEntries: (entries) => entries` (add/remove URLs), `underConstructionSeo: false`. diff --git a/docs/analytics.md b/docs/analytics.md index f9d64bf..66b9920 100644 --- a/docs/analytics.md +++ b/docs/analytics.md @@ -136,6 +136,16 @@ no conversion modelling for visitors without consent. The default `advanced` loa with `denied` signals. In both modes the Consent Mode default is set first. The mode is the client's decision — record it in `AGENTS.md` → "Project decisions". +The rule itself is `shouldLoadGoogle({ consentMode, ready, state })` — a pure function (no React, no DOM) +exported from `@intecion/ipal-kit/client` and `@intecion/ipal-kit`. Use it for your own Google-dependent +code (a Maps embed, a YouTube player with Google Ads), so it follows the same consent rule as ``: + +```ts +import { shouldLoadGoogle } from '@intecion/ipal-kit/client' + +const allowed = shouldLoadGoogle({ consentMode: 'basic', ready: true, state: consent }) +``` + 1. Before the tag loads: `gtag('consent', 'default', { …, wait_for_update: 500 })` with the visitor's stored decision (or everything `denied` when they have not decided yet or the consent is from another policy version — `texts.version`). diff --git a/docs/consent.md b/docs/consent.md index 1602108..1c05653 100644 --- a/docs/consent.md +++ b/docs/consent.md @@ -354,10 +354,11 @@ independent consent state). | Item | Value | |---|---| -| Option | `consentLog?: boolean \| { retentionDays?: number }` (type `ConsentLogOptions`) | +| Option | `consentLog?: boolean \| { retentionDays?: number; collectionOverrides?: CollectionOverride }` (type `ConsentLogOptions`) | | `retentionDays` | default `1095` (3 years) | +| `collectionOverrides` | changes `consent-records`: an object merges `access` / `admin` / `hooks` key by key (your keys win), other keys replace; a function `(collection) => collection` takes over (keep the slug — the endpoint writes to it) | | Collection | `consent-records` (`CONSENT_LOG_SLUG`), group *Settings*; fields `consentId` (index), `version`, `choices.{necessary,functional,analytics,marketing}`, `createdAt` | -| Collection access | `read` / `delete` — admin; `create` / `update` — nobody through the API (written only by the endpoint, `overrideAccess`) | +| Collection access | `read` / `delete` — admin (without `access`, i.e. no roles: any logged-in account — narrow it with `collectionOverrides`); `create` / `update` — nobody through the API (written only by the endpoint, `overrideAccess`) | | Endpoint | `POST /api/ipal/consent`, public (no login) | | Body | `{ id: string (hex 16–64), version: int ≥ 1, state: { necessary, functional, analytics, marketing: boolean } }` | | Responses | `201 { ok: true }`, `400` (bad JSON/validation), `429` (limit 20 requests/min per IP, scope `consent`), `500` | @@ -367,6 +368,16 @@ The provider sends a record after every decision (`fetch` with `keepalive`, erro the banner never waits). By hand: `buildConsentLogCollection()` / `buildConsentLogEndpoint(opts)` from `@intecion/ipal-kit`. +Narrow who reads the records (e.g. a project without roles, only the data protection officer): + +```ts +ipalKit({ + consentLog: { + collectionOverrides: { access: { read: ({ req }) => req.user?.email === 'dpo@acme.pl' } }, + }, +}) +``` + ## Turn off, override, extend - **Turn off:** do not mount `CookieBanner` / `CookieButton` (or `SiteProviders banner={false} diff --git a/docs/seo.md b/docs/seo.md index 88fb2ce..738c313 100644 --- a/docs/seo.md +++ b/docs/seo.md @@ -1251,7 +1251,7 @@ Both are equally good for Google — it is about readability for humans, not SEO ## Search & AI — Search Console verification, AI bots, llms.txt note (1.13) The **Site Settings → Search & AI** tab (on by default; empty fields change -nothing; `ipalKit({ seo: { …, searchSettings: false } })` removes it; the function +nothing; `ipalKit({ searchSettings: false })` removes it — also without `seo` (`seo: { searchSettings }` still works; the top-level option wins); the function `searchSettings: (fields) => fields` gets the plugin's fields and returns your own — add, remove, relabel; the helpers read the names `searchVerification` / `aiCrawlers` / `llmsIntro`): @@ -1426,14 +1426,14 @@ It complements Markdown/llms: the assistant extracts the page's key content more ## Turn off, override, extend - **Turn off the module:** leave out `seo` in `ipalKit()` — no SEO tab and no auto-fill. The Site Settings → - Search & AI tab stays (it is removed only by `seo: { searchSettings: false }`). The front helpers (`buildMetadata`, `buildRobots`, the JSON-LD builders) are plain functions and work without it. + Search & AI tab stays (remove it with the top-level `searchSettings: false`). The front helpers (`buildMetadata`, `buildRobots`, the JSON-LD builders) are plain functions and work without it. - **Auto-fill:** `autoFill: false` turns it off; `autoFill: { title, description, content, descriptionLength }` remaps the source fields. Skip it for one save with `context: { [SKIP_AUTO_FILL]: true }`. - **Description hint:** `descriptionCheck: false` removes it; `descriptionCheck: { settingsSlug, siteDescriptionField }` points it at another global/field. - **Titles and descriptions:** `generateTitle` / `generateDescription` replace plugin-seo's generators; `fields` adds your own fields to the SEO group. Per page, **Title Override** beats the composed title. -- **Search & AI tab:** `searchSettings: false` removes it; `searchSettings: (fields) => fields` adds, removes or +- **Search & AI tab:** `ipalKit({ searchSettings: false })` removes it (with or without `seo`); `searchSettings: (fields) => fields` adds, removes or relabels fields (keep `searchVerification` / `aiCrawlers` / `llmsIntro`, or read your own fields in your routes). - **The Site Settings global itself** (where the SEO fields live): `ipalKit({ globalOverrides: { 'site-settings': … } })` — an object is merged over the plugin's global (`access`, `admin` and `hooks` key by key: your access rules win, diff --git a/docs/stats.md b/docs/stats.md index 5f55406..46e0972 100644 --- a/docs/stats.md +++ b/docs/stats.md @@ -45,6 +45,7 @@ ipalKit({ | `retentionDays` | `90` | older visits (by `lastAt`) are deleted | | `timeZone` | `'Europe/Warsaw'` | day boundary (`day` field, salt rotation, charts) | | `dashboard` | `true` | `false` removes only `StatsWidget` from the dashboard — the view and the nav link stay | +| `collectionOverrides` | none | changes `stats-visits`: an object merges `access` / `admin` / `hooks` key by key (your keys win), a function `(collection) => collection` takes over (keep the slug). Its `access.read` also decides who sees the stats view and the dashboard chart | Adds: - the `stats-visits` collection (group *Statistics*, read and delete: admin; `create`/`update` via API @@ -161,7 +162,7 @@ przechowujemy przez 90 dni. - **Turn off:** without the `stats` option nothing is added; `stats: { dashboard: false }` hides only the dashboard chart; without `` (or with `SiteProviders stats` = `false`) nothing is sent. -- **Override:** `retentionDays`, `timeZone`; `` for your own endpoint path. +- **Override:** `retentionDays`, `timeZone`, `collectionOverrides` (e.g. `{ access: { read: ({ req }) => req.user?.email === 'owner@acme.pl' } }` in a project without roles); `` for your own endpoint path. The counting rules (bots, prefetch, 30 min, 10 s) currently cannot be changed with an option. - **Extend:** `STATS_SLUG` + the types `StatsOptions` / `StatsVisit` / `StatsPage` (from `@intecion/ipal-kit`) for your own queries and reports (Local API); `StatsView` / `StatsWidget` from diff --git a/src/exports/client.ts b/src/exports/client.ts index bb0ba85..c310580 100644 --- a/src/exports/client.ts +++ b/src/exports/client.ts @@ -3,9 +3,10 @@ export { AccessibilityProvider, AccessibilityWidget, useAccessibility } from '.. export type { A11yClassNames, A11yState, A11yTexts } from '../modules/accessibility/client.js' export { Analytics } from '../modules/analytics/client.js' export type { AnalyticsProps } from '../modules/analytics/client.js' - export { pushDataLayer } from '../modules/analytics/client.js' + export { loadClarity, loadLinkedIn, loadMetaPixel, loadTikTok } from '../modules/analytics/client.js' +export { shouldLoadGoogle } from '../modules/analytics/shouldLoadGoogle.js' /** * Entry point: ipal-kit/client * diff --git a/src/index.ts b/src/index.ts index c56f986..504d047 100644 --- a/src/index.ts +++ b/src/index.ts @@ -26,6 +26,7 @@ export { rowLabel } from './modules/admin-ui/index.js' export type { RowLabelProps } from './modules/admin-ui/index.js' export type { AnalyticsConfig } from './modules/analytics/index.js' export { getAnalyticsConfig } from './modules/analytics/index.js' +export { shouldLoadGoogle } from './modules/analytics/shouldLoadGoogle.js' // Shared section fields (header: eyebrow/heading/intro, settings: anchor/background). export { buildSectionHeaderField, buildSectionSettingsField } from './modules/blocks/sectionFields.js' export type { SectionHeaderFieldOptions, SectionSettingsFieldOptions } from './modules/blocks/sectionFields.js' @@ -175,9 +176,9 @@ export type { ExtractHeadingsOptions, HeadingItem, HeadingLevel } from './module // Lexical → Markdown (pure, no React) — for AI-readable output. export { lexicalToMarkdown } from './modules/richtext/index.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 type { BuildSecurityHeadersArgs, SecurityHeader } from './modules/security/index.js' export type { OgImage } from './modules/seo/buildMetadata.js' export type { PageMetadata, SeoMeta, SeoOption } from './modules/seo/index.js' @@ -225,6 +226,8 @@ export { robotsOptionsFrom, verificationFrom } from './modules/seo/index.js' export type { AiBotRule, AiBotsPolicy, VerificationMetadata } from './modules/seo/index.js' export { buildSitemapCss, buildSitemapIndexXml, buildSitemapXml, DEFAULT_SITEMAP_CREDIT, SITEMAP_STYLE_PARAM } from './modules/seo/index.js' export type { SitemapRouteOptions, SitemapStyleOptions } from './modules/seo/index.js' +export { applyCollectionOverride } from './modules/shared/collectionOverride.js' +export type { CollectionOverride } from './modules/shared/collectionOverride.js' export { clientIp, setRateLimitStore, setUnknownIpFactor, UNKNOWN_IP_FACTOR } from './modules/shared/rateLimit.js' export type { ClientIpOptions, RateLimitStore } from './modules/shared/rateLimit.js' export { buildSlugField, toSlug } from './modules/slug/index.js' diff --git a/src/modules/analytics/Analytics.tsx b/src/modules/analytics/Analytics.tsx index 0eeab0c..1c62cdc 100644 --- a/src/modules/analytics/Analytics.tsx +++ b/src/modules/analytics/Analytics.tsx @@ -7,6 +7,7 @@ import { useConsentContext } from '../consent/client.js' import { gtag } from '../consent/googleConsent.js' import { CONSENT_COOKIE, DEFAULT_CONSENT, parseConsent, setDefaultConsent } from '../consent/index.js' import { loadClarity, loadLinkedIn, loadMetaPixel, loadTikTok } from './pixels.js' +import { shouldLoadGoogle } from './shouldLoadGoogle.js' declare global { interface Window { @@ -69,24 +70,6 @@ export type AnalyticsProps = { deferTimeoutMs?: number } & AnalyticsConfig -/** - * Whether the Google tag may load now. Pure, so the consent rule is testable - * without a DOM: 'basic' waits for an analytics or marketing grant, 'advanced' - * relies on the Consent Mode default and loads as soon as `ready`. - */ -export function shouldLoadGoogle({ - consentMode, - ready, - state, -}: { - consentMode: 'advanced' | 'basic' - ready: boolean - state: { analytics?: boolean; marketing?: boolean } -}): boolean { - if (!ready) {return false} - return consentMode === 'advanced' || Boolean(state.analytics || state.marketing) -} - const INTERACTION_EVENTS = ['scroll', 'pointerdown', 'touchstart', 'keydown'] as const /** True once third-party tags may load (immediately, or per `defer` rules). */ diff --git a/src/modules/analytics/shouldLoadGoogle.ts b/src/modules/analytics/shouldLoadGoogle.ts new file mode 100644 index 0000000..b31a411 --- /dev/null +++ b/src/modules/analytics/shouldLoadGoogle.ts @@ -0,0 +1,23 @@ +/** + * Pure consent gate for the Google tag — no React, no DOM, safe on the server + * and in the client bundle. uses it; export it to apply the same + * rule to your own Google-dependent code. + */ + +/** + * Whether the Google tag may load now. Pure, so the consent rule is testable + * without a DOM: 'basic' waits for an analytics or marketing grant, 'advanced' + * relies on the Consent Mode default and loads as soon as `ready`. + */ +export function shouldLoadGoogle({ + consentMode, + ready, + state, +}: { + consentMode: 'advanced' | 'basic' + ready: boolean + state: { analytics?: boolean; marketing?: boolean } +}): boolean { + if (!ready) {return false} + return consentMode === 'advanced' || Boolean(state.analytics || state.marketing) +} diff --git a/src/modules/consent/consentLog.ts b/src/modules/consent/consentLog.ts index abcd8ba..8df8412 100644 --- a/src/modules/consent/consentLog.ts +++ b/src/modules/consent/consentLog.ts @@ -1,5 +1,7 @@ import type { CollectionConfig, Endpoint, PayloadRequest } from 'payload' +import type { CollectionOverride } from '../shared/collectionOverride.js' + import { userMeetsRole } from '../access/predicates.js' import { createDailyPurge } from '../shared/purge.js' import { clientIp, consumeRateLimit } from '../shared/rateLimit.js' @@ -20,6 +22,13 @@ import { CONSENT_CATEGORIES } from './categories.js' export const CONSENT_LOG_SLUG = 'consent-records' export type ConsentLogOptions = { + /** + * Change the `consent-records` collection: an object merges over it + * (`access` / `admin` / `hooks` key by key, your keys win), a function gets it + * and returns the one to use. E.g. narrow who reads the records in a project + * without roles: `{ access: { read: ({ req }) => req.user?.email === 'dpo@acme.pl' } }`. + */ + collectionOverrides?: CollectionOverride /** Days a record is kept. Default 1095 (3 years). */ retentionDays?: number } diff --git a/src/modules/shared/collectionOverride.ts b/src/modules/shared/collectionOverride.ts new file mode 100644 index 0000000..a04b431 --- /dev/null +++ b/src/modules/shared/collectionOverride.ts @@ -0,0 +1,32 @@ +import type { CollectionConfig } from 'payload' + +/** + * A project's change to a collection the plugin adds (consent records, stats): + * - an object is merged over the plugin's: `access`, `admin` and `hooks` key by + * key (your access rules win, your hooks run after the plugin's), anything + * else (labels, fields, …) replaces the plugin's value; + * - a function gets the plugin's collection and returns the one to use — full + * control. Keep the slug: the plugin's endpoints and views write and read it. + * + * Same rules as `globalOverrides`. + */ +export type CollectionOverride = ((collection: CollectionConfig) => CollectionConfig) | Partial + +type Hooks = NonNullable + +/** Applies one CollectionOverride to a plugin collection. */ +export function applyCollectionOverride(collection: CollectionConfig, override: CollectionOverride | undefined): CollectionConfig { + if (!override) {return collection} + if (typeof override === 'function') {return override(collection)} + const hooks: Record = { ...(collection.hooks as Record) } + for (const [key, list] of Object.entries(override.hooks ?? {})) { + hooks[key] = [...(hooks[key] ?? []), ...((list as unknown[]) ?? [])] + } + return { + ...collection, + ...override, + access: { ...collection.access, ...override.access }, + admin: { ...collection.admin, ...override.admin }, + hooks: hooks as Hooks, + } +} diff --git a/src/modules/stats/admin/StatsView.tsx b/src/modules/stats/admin/StatsView.tsx index f4d6924..d2993cf 100644 --- a/src/modules/stats/admin/StatsView.tsx +++ b/src/modules/stats/admin/StatsView.tsx @@ -5,8 +5,8 @@ import { Gutter } from '@payloadcms/ui' import type { StatsVisit } from '../collection.js' -import { userMeetsRole } from '../../access/predicates.js' import { VISITOR_ID_PATTERN } from '../parse.js' +import { canReadStats } from './canReadStats.js' import { loadRecentVisitors, loadStats, loadVisitor } from './loadStats.js' import { STATS_CSS, VisitsChart } from './VisitsChart.js' @@ -77,7 +77,7 @@ function VisitorHistory({ base, timeZone, visitorId, visits }: { base: string; t * Admin view at /admin/stats (ipalKit({ stats: true })): visits per day for the * last 30 days, top pages, entry pages, referrers, devices, and — for visitors * who accepted analytics cookies — a per-visitor history (?visitor=). - * Admins only. + * For users the stats-visits collection lets read (admins by default). */ export async function StatsView(props: Props) { const { adminRoute = '/admin', initPageResult, searchParams, timeZone = 'Europe/Warsaw' } = props @@ -88,8 +88,8 @@ export async function StatsView(props: Props) { const visitorId = visitorParam && VISITOR_ID_PATTERN.test(visitorParam) ? visitorParam : undefined let content: React.ReactNode - if (!userMeetsRole(req, 'admin')) { - content =

Statistics are available to administrators only.

+ if (!(await canReadStats(req.payload, req))) { + content =

You do not have access to the statistics.

} else if (visitorId) { content = } else { diff --git a/src/modules/stats/admin/StatsWidget.tsx b/src/modules/stats/admin/StatsWidget.tsx index ed64423..399974d 100644 --- a/src/modules/stats/admin/StatsWidget.tsx +++ b/src/modules/stats/admin/StatsWidget.tsx @@ -1,6 +1,6 @@ import type { Payload, PayloadRequest } from 'payload' -import { userMeetsRole } from '../../access/predicates.js' +import { canReadStats } from './canReadStats.js' import { loadStats } from './loadStats.js' import { STATS_CSS, VisitsChart } from './VisitsChart.js' @@ -15,11 +15,12 @@ type Props = { /** * Dashboard card (admin.components.beforeDashboard): visits per day for the - * last 30 days with a link to the full view. Admins only; renders nothing on + * last 30 days with a link to the full view. For users the stats-visits + * collection lets read (admins by default); renders nothing on * any error (DB not ready, collection missing). */ export async function StatsWidget({ adminRoute = '/admin', payload, req, timeZone = 'Europe/Warsaw', user }: Props) { - if (!payload || !userMeetsRole({ payload, user: req?.user ?? user }, 'admin')) {return null} + if (!payload || !(await canReadStats(payload, req, user))) {return null} let stats try { stats = await loadStats(payload, { timeZone }) diff --git a/src/modules/stats/admin/canReadStats.ts b/src/modules/stats/admin/canReadStats.ts new file mode 100644 index 0000000..4f39733 --- /dev/null +++ b/src/modules/stats/admin/canReadStats.ts @@ -0,0 +1,19 @@ +import type { Payload, PayloadRequest } from 'payload' + +import { STATS_SLUG } from '../collection.js' + +/** + * Whether the user may see the stats view and dashboard chart: the + * `stats-visits` collection's own `access.read` decides, so + * `stats.collectionOverrides` narrows the panel too. A `Where` result counts + * as allowed (the view shows totals, not single records). + */ +export async function canReadStats(payload: Payload, req: Partial | undefined, user?: unknown): Promise { + const read = payload.collections[STATS_SLUG as never]?.config.access?.read + if (!read) {return false} + try { + return Boolean(await read({ req: { ...req, payload, user: (req?.user ?? user) as never } as PayloadRequest })) + } catch { + return false + } +} diff --git a/src/modules/stats/collection.ts b/src/modules/stats/collection.ts index 478b307..437430f 100644 --- a/src/modules/stats/collection.ts +++ b/src/modules/stats/collection.ts @@ -1,5 +1,7 @@ import type { CollectionConfig } from 'payload' +import type { CollectionOverride } from '../shared/collectionOverride.js' + import { userMeetsRole } from '../access/predicates.js' /** @@ -15,6 +17,13 @@ import { userMeetsRole } from '../access/predicates.js' export const STATS_SLUG = 'stats-visits' export type StatsOptions = { + /** + * Change the `stats-visits` collection: an object merges over it + * (`access` / `admin` / `hooks` key by key, your keys win), a function gets it + * and returns the one to use. Its `access.read` also decides who sees the + * dashboard chart and the stats view. + */ + collectionOverrides?: CollectionOverride /** Show the 30-day chart on the admin dashboard. Default true. */ dashboard?: boolean /** Days a visit is kept. Default 90 (the dashboard shows 30). */ diff --git a/src/plugin.ts b/src/plugin.ts index d38fc33..a329ac0 100644 --- a/src/plugin.ts +++ b/src/plugin.ts @@ -21,6 +21,7 @@ import { buildSystemPagesFields } from './modules/pages/index.js' import { buildSeoPlugin, injectAutoFillMeta, injectSeoTabs } from './modules/seo/index.js' import { buildIndexNowHook } from './modules/seo/indexNow.js' import { searchSettingsFields } from './modules/seo/searchSettings.js' +import { applyCollectionOverride } from './modules/shared/collectionOverride.js' import { buildStatsCollection, buildStatsEndpoint } from './modules/stats/index.js' /** @@ -277,19 +278,16 @@ export const ipalKit = (options: IpalOptions): Plugin => { : []), ] + // Top-level option first (works without `seo`), then the older seo.searchSettings. + const searchSettings = options.searchSettings ?? options.seo?.searchSettings const pluginGlobals = [ buildSiteSettings({ additionalFields: options.siteSettingsFields, ...(options.pages ? { constructionFields: buildConstructionFields(options.pages.slug) } : {}), ...(options.forms?.emailLayout ? { emailFields: emailSettingsFields } : {}), - ...(options.seo?.searchSettings === false + ...(searchSettings === false ? {} - : { - searchFields: - typeof options.seo?.searchSettings === 'function' - ? options.seo.searchSettings(searchSettingsFields) - : searchSettingsFields, - }), + : { searchFields: typeof searchSettings === 'function' ? searchSettings(searchSettingsFields) : searchSettingsFields }), systemPageFields, }), buildSiteIntegrations({ additionalFields: options.integrationsFields }), @@ -309,7 +307,7 @@ export const ipalKit = (options: IpalOptions): Plugin => { // --- consent log: proof of consent (opt-in) --- if (options.consentLog) { const logOptions = options.consentLog === true ? {} : options.consentLog - config.collections = [...(config.collections ?? []), buildConsentLogCollection()] + config.collections = [...(config.collections ?? []), applyCollectionOverride(buildConsentLogCollection(), logOptions.collectionOverrides)] config.endpoints = [...(config.endpoints ?? []), buildConsentLogEndpoint(logOptions)] } @@ -318,7 +316,7 @@ export const ipalKit = (options: IpalOptions): Plugin => { const statsOptions = options.stats === true ? {} : options.stats const adminRoute = options.adminRoute ?? '/admin' const viewProps = { adminRoute, ...(statsOptions.timeZone ? { timeZone: statsOptions.timeZone } : {}) } - config.collections = [...(config.collections ?? []), buildStatsCollection()] + config.collections = [...(config.collections ?? []), applyCollectionOverride(buildStatsCollection(), statsOptions.collectionOverrides)] config.endpoints = [...(config.endpoints ?? []), buildStatsEndpoint(statsOptions)] config.admin = { ...(config.admin ?? {}), diff --git a/src/types.ts b/src/types.ts index 698aa22..a75b0e6 100644 --- a/src/types.ts +++ b/src/types.ts @@ -14,6 +14,7 @@ export type TotpPluginFactory = (options: { }) => Plugin import type { GlobalOverrides } from './globals/overrides.js' import type { AccessOption } from './modules/access/types.js' +import type { ConsentLogOptions } from './modules/consent/consentLog.js' import type { ContentOption } from './modules/content/types.js' import type { FormsOption } from './modules/forms/types.js' import type { RevalidatePathFn } from './modules/hooks/buildRevalidateHook.js' @@ -50,9 +51,9 @@ export type IpalOptions = { * Consent log (proof of consent, GDPR Art. 7(1)): adds the `consent-records` * collection and POST /api/ipal/consent. Pass ``. * Stores a random id, choices, policy version and time — no personal data. - * `true` or `{ retentionDays }` (default 1095). Default off. + * `true` or `{ retentionDays, collectionOverrides }` (default 1095 days). Default off. */ - consentLog?: { retentionDays?: number } | boolean + consentLog?: boolean | ConsentLogOptions /** * Collections whose entries live under an archive page — blog posts, case @@ -112,6 +113,14 @@ export type IpalOptions = { */ revalidatePath?: RevalidatePathFn + /** + * Site Settings → "Search & AI" tab (verification codes, AI crawler policy, + * llms.txt intro). On by default; `false` removes it; a function gets the + * plugin's fields and returns the tab's fields. Works without `seo`; wins + * over `seo.searchSettings`. + */ + searchSettings?: ((defaults: Field[]) => Field[]) | false + /** * SEO — adds meta fields to chosen collections (via @payloadcms/plugin-seo) * and enables locale-aware metadata helpers. diff --git a/test/analyticsConsent.test.ts b/test/analyticsConsent.test.ts index 2890e35..bba697e 100644 --- a/test/analyticsConsent.test.ts +++ b/test/analyticsConsent.test.ts @@ -1,6 +1,6 @@ import { describe, expect, test } from 'vitest' -import { shouldLoadGoogle } from '../src/modules/analytics/Analytics.js' +import { shouldLoadGoogle } from '../src/modules/analytics/shouldLoadGoogle.js' const none = { analytics: false, marketing: false } @@ -17,3 +17,13 @@ describe("Google tag and consent", () => { expect(shouldLoadGoogle({ consentMode: 'basic', ready: false, state: { analytics: true } })).toBe(false) }) }) + +describe('shouldLoadGoogle is public', () => { + test('exported from the root and /client, from a module without React', async () => { + const { readFileSync } = await import('node:fs') + const read = (p: string) => readFileSync(new URL(`../${p}`, import.meta.url), 'utf8') + expect(read('src/index.ts')).toMatch(/export \{ shouldLoadGoogle \} from '\.\/modules\/analytics\/shouldLoadGoogle\.js'/) + expect(read('src/exports/client.ts')).toMatch(/export \{ shouldLoadGoogle \} from '\.\.\/modules\/analytics\/shouldLoadGoogle\.js'/) + expect(read('src/modules/analytics/shouldLoadGoogle.ts')).not.toMatch(/^import|'use client'/m) + }) +}) diff --git a/test/plugin.test.ts b/test/plugin.test.ts index fa07f72..5c6df52 100644 --- a/test/plugin.test.ts +++ b/test/plugin.test.ts @@ -143,3 +143,58 @@ describe('options that keep features reachable and overridable', () => { expect(read({ req: { payload: { collections: {} }, user: { id: 1, collection: 'other' } } })).toBe(false) }) }) + +describe('gap fixes: searchSettings, collection overrides', () => { + const tabsOf = (config: Config) => { + const settings = config.globals!.find((g) => g.slug === 'site-settings')! + const tabs = settings.fields.find((f) => f.type === 'tabs') as { tabs: { label?: unknown }[] } + return tabs.tabs.map((t) => String(t.label)) + } + + test('searchSettings: false removes the Search & AI tab without `seo`', async () => { + expect(tabsOf(await ipalKit({ i18n, twoFactor: false })(base()))).toContain('Search & AI') + expect(tabsOf(await ipalKit({ i18n, searchSettings: false, twoFactor: false })(base()))).not.toContain('Search & AI') + }) + + test('searchSettings: a function shapes the fields; the top-level option wins over seo.searchSettings', async () => { + const config = await ipalKit({ + i18n, + searchSettings: (fields) => fields.filter((f) => 'name' in f && f.name === 'llmsIntro'), + seo: { collections: [], searchSettings: false }, + twoFactor: false, + })(base()) + const settings = config.globals!.find((g) => g.slug === 'site-settings')! + const tab = (settings.fields.find((f) => f.type === 'tabs') as { tabs: { fields: { name?: string }[]; label?: unknown }[] }).tabs.find( + (t) => t.label === 'Search & AI', + )! + expect(tab.fields.map((f) => f.name)).toEqual(['llmsIntro']) + // the older seo.searchSettings still works alone + expect(tabsOf(await ipalKit({ i18n, seo: { collections: [], searchSettings: false }, twoFactor: false })(base()))).not.toContain('Search & AI') + }) + + test('consentLog / stats collectionOverrides: an object merges access, a function takes over', async () => { + const dpoOnly = ({ req }: { req: { user?: { email?: string } } }) => req.user?.email === 'dpo@acme.pl' + const config = await ipalKit({ + consentLog: { collectionOverrides: { access: { read: dpoOnly as never }, admin: { group: 'Privacy' } } }, + i18n, + stats: { collectionOverrides: (c) => ({ ...c, labels: { plural: 'Visits', singular: 'Visit' } }) }, + twoFactor: false, + })(base()) + const consent = config.collections!.find((c) => c.slug === 'consent-records')! + expect(consent.access!.read).toBe(dpoOnly) + expect(consent.access!.create).toBeTypeOf('function') // plugin's rule kept + expect(consent.admin).toMatchObject({ group: 'Privacy', useAsTitle: 'consentId' }) + const stats = config.collections!.find((c) => c.slug === 'stats-visits')! + expect(stats.labels).toEqual({ plural: 'Visits', singular: 'Visit' }) + expect(stats.access!.read).toBeTypeOf('function') + }) + + test('the stats view and widget follow the collection read access', async () => { + const { canReadStats } = await import('../src/modules/stats/admin/canReadStats.js') + const payload = (read: unknown) => ({ collections: { 'stats-visits': { config: { access: { read } } } } }) as never + const onlyAnna = ({ req }: { req: { user?: { email?: string } } }) => req.user?.email === 'anna@acme.pl' + expect(await canReadStats(payload(onlyAnna), undefined, { email: 'anna@acme.pl' })).toBe(true) + expect(await canReadStats(payload(onlyAnna), { user: { email: 'bob@acme.pl' } } as never)).toBe(false) + expect(await canReadStats({ collections: {} } as never, undefined, { email: 'x' })).toBe(false) + }) +})