From 10da62ea4c3ae00ffa5461a5709b979937f5af8d Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?Rados=C5=82aw=20Smoli=C5=84ski?= Date: Thu, 22 Oct 2026 16:58:00 +0200 Subject: [PATCH 01/27] Lock down injected users, 2FA slug, forms and globals writes - Injected auth collection with roles: admins manage all accounts, others only themselves (Payload's default let any account edit or delete any other) - 2FA defaults to the resolved auth collection instead of 'users' - SiteSettings, CookieSettings, Notifications, Forms: write needs editor+; form Emails tab readable by editor+ only Co-Authored-By: Claude Opus 5.5 --- docs/access.md | 16 ++++ docs/forms.md | 5 ++ docs/notifications.md | 2 +- docs/security.md | 12 ++- src/globals/CookieSettings/index.ts | 2 + src/globals/Notifications/index.ts | 2 + src/globals/SiteSettings/index.ts | 4 + src/modules/forms/formsPluginConfig.ts | 16 +++- src/plugin.ts | 23 ++++- test/accessControl.test.ts | 119 +++++++++++++++++++++++++ 10 files changed, 194 insertions(+), 7 deletions(-) create mode 100644 test/accessControl.test.ts diff --git a/docs/access.md b/docs/access.md index 1a751cf..0841278 100644 --- a/docs/access.md +++ b/docs/access.md @@ -22,6 +22,22 @@ Ekran pierwszego użytkownika i Local API (seed) działają z `overrideAccess`, pierwszego admina nadal da się utworzyć. Kolekcja należy do Ciebie (create-payload-app) — plugin tylko dokłada pole. +## Co plugin zamyka sam + +| Zasób | Odczyt | Zapis | +|---|---|---| +| kolekcja auth **wstrzyknięta** przez plugin (gdy projekt nie ma własnej) i z rolami | admin: wszyscy; inni: tylko siebie | `create`/`delete`: admin; `update`: admin albo siebie | +| Site Settings, Cookie Settings, Notifications | publiczny | `editor+` | +| Site Integrations | admin | admin | +| Forms | publiczny (bez zakładki Emails — ta tylko `editor+`) | `editor+` | +| Form submissions | `editor+` | REST `create`: zalogowani; `delete`: admin | + +Własna kolekcja auth projektu zachowuje własne `access` — plugin dokłada tylko pole +`roles`. Ustaw jej co najmniej `update: adminOrSelf`, `delete: adminOnly`, `create: adminOnly`: +domyślny Payload pozwala każdemu zalogowanemu zmienić e-mail i hasło innego konta. +Kolekcja wstrzyknięta **bez** `access` (brak ról) zostaje przy domyślnych regułach Payloada — +bez ról wszystkie konta są równe. + > Po dodaniu: zadbaj, by seed / pierwszy user miał `roles: ['admin']`, inaczej > stracisz dostęp do zasobów admin-only (np. SiteIntegrations). diff --git a/docs/forms.md b/docs/forms.md index ad508e0..cab334d 100644 --- a/docs/forms.md +++ b/docs/forms.md @@ -298,6 +298,11 @@ wysyła przez `submitForm` (server action → Local API), więc to go nie dotycz `forms: { formSubmissionOverrides: { access: { create: () => true } } }` — wtedy zabezpieczenia `submitForm` na tej drodze nie działają. +**Formularze edytuje tylko `editor+`.** Kolekcja `forms` jest publiczna do odczytu (pola renderują +formularz), ale `create`/`update`/`delete` i odczyt zakładki Emails (odbiorcy, BCC) wymagają roli +`editor` lub `admin` — konto `user` nie dopisze sobie BCC do każdego zgłoszenia. Nadpisanie: +`forms: { formOverrides: { access: { … } } }`. + Walidacja jest istotna, bo server action to publiczny endpoint — da się go wołać z pominięciem formularza. Plugin ładuje definicję formularza i: odrzuca nieznane klucze, wymusza pola `required`, tnie długość (5000 znaków). Do bazy trafia tylko diff --git a/docs/notifications.md b/docs/notifications.md index aea0d89..e31c70e 100644 --- a/docs/notifications.md +++ b/docs/notifications.md @@ -67,5 +67,5 @@ fallback. `getNotificationTexts` resolwuje, co istnieje. ## Dostęp Global ma `read: () => true` — teksty są publiczne (pokazywane użytkownikom -końcowym), więc front czyta je bez sesji. Inaczej niż SiteIntegrations +końcowym), więc front czyta je bez sesji. Zapis: `editor+`. Inaczej niż SiteIntegrations (`read: isAdmin` — tam sekrety). diff --git a/docs/security.md b/docs/security.md index 02769e7..d0cafbb 100644 --- a/docs/security.md +++ b/docs/security.md @@ -274,7 +274,7 @@ ipalKit({ twoFactor: { issuer: 'Nazwa Firmy', // pokazywane w aplikacji authenticator plugin: payloadTotp, // ← WSTRZYKNIJ — patrz niżej dlaczego - // collectionSlug: 'users', + // collectionSlug: 'users', // domyślnie kolekcja auth: access.authCollection → admin.user → 'users' }, }) ``` @@ -334,3 +334,13 @@ dostęp do danych, nie tylko UI. - Zgłoszenia formularzy: odczyt `editor+`; adresy z zakładki Emails niewidoczne publicznie. - Uploady: `buildUploadSecurityHeaders()` w `next.config.ts` (SVG nie uruchomi skryptu na domenie strony). - `users`: plugin wstrzykuje kolekcję auth, gdy projekt jej nie ma (role i 2FA zawsze się wpinają). + +## Kontrola dostępu (od wersji po 1.12.3) + +- Wstrzyknięta kolekcja auth z rolami: konto `user` czyta i edytuje tylko siebie, tworzy i usuwa + tylko admin. Wcześniej każdy zalogowany mógł zmienić e-mail/hasło admina. +- 2FA bez `collectionSlug` wrapuje kolekcję, którą faktycznie się logujesz (`access.authCollection`, + potem `admin.user`), a nie literał `'users'` — inaczej TOTP po cichu nie działał. +- Site Settings, Cookie Settings, Notifications i kolekcja Forms: zapis tylko `editor+`; zakładka + Emails formularza (odbiorcy, BCC) czytelna tylko dla `editor+`. +- Pełna tabela: [access.md](./access.md#co-plugin-zamyka-sam). diff --git a/src/globals/CookieSettings/index.ts b/src/globals/CookieSettings/index.ts index 587650d..7f88079 100644 --- a/src/globals/CookieSettings/index.ts +++ b/src/globals/CookieSettings/index.ts @@ -1,5 +1,6 @@ import type { GlobalConfig } from 'payload' +import { adminOrEditor } from '../../modules/access/index.js' import { cookieSettingsFields } from './fields.js' /** @@ -11,6 +12,7 @@ export function buildCookieSettings(): GlobalConfig { slug: 'cookie-settings', access: { read: () => true, + update: adminOrEditor, // consent texts are legal copy — not for plain 'user' accounts }, admin: { group: 'Settings', diff --git a/src/globals/Notifications/index.ts b/src/globals/Notifications/index.ts index 308b23f..e8b918f 100644 --- a/src/globals/Notifications/index.ts +++ b/src/globals/Notifications/index.ts @@ -1,5 +1,6 @@ import type { GlobalConfig } from 'payload' +import { adminOrEditor } from '../../modules/access/index.js' import { notificationsFields } from './fields.js' /** @@ -12,6 +13,7 @@ export function buildNotifications(): GlobalConfig { slug: 'notifications', access: { read: () => true, // texts are public-facing (shown to end users) + update: adminOrEditor, }, admin: { group: 'Settings' }, fields: notificationsFields, diff --git a/src/globals/SiteSettings/index.ts b/src/globals/SiteSettings/index.ts index c373ce9..4222038 100644 --- a/src/globals/SiteSettings/index.ts +++ b/src/globals/SiteSettings/index.ts @@ -1,5 +1,6 @@ import type { Field, GlobalConfig } from 'payload' +import { adminOrEditor } from '../../modules/access/index.js' import { generalFields } from './fields/general.js' import { themeFields } from './fields/theme.js' @@ -42,6 +43,9 @@ export function buildSiteSettings({ slug: 'site-settings', access: { read: () => true, + // Editors and admins only — a plain 'user' account (open sign-up) must + // not rewrite the brand, homepage or construction mode. + update: adminOrEditor, }, admin: { group: 'Settings', diff --git a/src/modules/forms/formsPluginConfig.ts b/src/modules/forms/formsPluginConfig.ts index 08dd69b..eab94a4 100644 --- a/src/modules/forms/formsPluginConfig.ts +++ b/src/modules/forms/formsPluginConfig.ts @@ -26,10 +26,15 @@ const submissionsCreateAccess = ({ req }: AccessArgs) => Boolean(req.user) */ const submissionsReadAccess = ({ req }: AccessArgs) => hasMinimumRole(req.user as never, 'editor') const submissionsDeleteAccess = ({ req }: AccessArgs) => isAdmin(req.user as never) +/** + * Forms carry recipient addresses (Emails → To/BCC): a plain 'user' account + * editing a form could BCC every submission to itself. Editors and admins only. + */ +const staffAccess = ({ req }: AccessArgs) => hasMinimumRole(req.user as never, 'editor') /** * Forms stay publicly readable (their fields render the form), but the Emails - * tab — recipient addresses, templates — is for logged-in staff only, so + * tab — recipient addresses, templates — is for editors and admins only, so * GET /api/forms doesn't hand out the company's inboxes to spammers. */ function hideEmails(fields: Field[]): Field[] { @@ -37,7 +42,7 @@ function hideEmails(fields: Field[]): Field[] { 'name' in field && field.name === 'emails' ? ({ ...field, - access: { ...(field as { access?: object }).access, read: ({ req }: AccessArgs) => Boolean(req.user) }, + access: { ...(field as { access?: object }).access, read: staffAccess }, } as Field) : field, ) @@ -104,6 +109,13 @@ export function buildFormsPlugin(forms: FormsOption): Plugin { formOverrides: { labels: { plural: 'Forms', singular: 'Form' }, ...forms.formOverrides, + access: { + create: staffAccess, + delete: staffAccess, + read: () => true, + update: staffAccess, + ...forms.formOverrides?.access, + }, admin: { ...group, ...forms.formOverrides?.admin }, fields: ({ defaultFields }) => hideEmails(forms.formOverrides?.fields ? forms.formOverrides.fields({ defaultFields }) : defaultFields), diff --git a/src/plugin.ts b/src/plugin.ts index a2df254..e0124a2 100644 --- a/src/plugin.ts +++ b/src/plugin.ts @@ -7,7 +7,7 @@ import { migrateCookieSettingsSaveButton } from './globals/CookieSettings/migrat import { buildNotifications } from './globals/Notifications/index.js' import { buildSiteIntegrations } from './globals/SiteIntegrations/index.js' import { buildSiteSettings } from './globals/SiteSettings/index.js' -import { injectRoles } from './modules/access/index.js' +import { adminOnly, adminOrSelf, injectRoles } from './modules/access/index.js' import { buildConsentLogCollection, buildConsentLogEndpoint } from './modules/consent/consentLog.js' import { buildConstructionFields } from './modules/construction/fields.js' import { buildArchiveFields } from './modules/content/index.js' @@ -65,10 +65,23 @@ export const ipalKit = (options: IpalOptions): Plugin => { (options.twoFactor ? options.twoFactor.collectionSlug : undefined) ?? config.admin?.user ?? 'users' + // With roles on it (access.authCollection), the injected collection is + // locked down: Payload's default lets ANY logged-in account read, edit + // (email, password) or delete every other account — a plain 'user' could + // take over an admin. Admins manage everyone; others only themselves. if (!(config.collections ?? []).some((c) => c.slug === authSlug)) { + const hasRoles = options.access?.authCollection === authSlug config.collections = [ ...(config.collections ?? []), - { slug: authSlug, admin: { useAsTitle: 'email' }, auth: true, fields: [] }, + { + slug: authSlug, + ...(hasRoles + ? { access: { create: adminOnly, delete: adminOnly, read: adminOrSelf, update: adminOrSelf } } + : {}), + admin: { useAsTitle: 'email' }, + auth: true, + fields: [], + }, ] } @@ -108,8 +121,12 @@ export const ipalKit = (options: IpalOptions): Plugin => { ) } + // Default to the resolved auth collection (access.authCollection / + // admin.user), not a literal 'users': wrapping a slug nobody logs in with + // leaves the real collection without TOTP fields, and the TOTP access + // wrapper lets users without those fields through — 2FA silently off. config = await totp({ - collection: tf.collectionSlug ?? 'users', + collection: tf.collectionSlug ?? authSlug, forceSetup: true, // ENFORCED — every user must set up TOTP; no opt-out totp: { issuer: tf.issuer }, })(config) diff --git a/test/accessControl.test.ts b/test/accessControl.test.ts new file mode 100644 index 0000000..5306bdd --- /dev/null +++ b/test/accessControl.test.ts @@ -0,0 +1,119 @@ +import type { Access, CollectionConfig, Config, Field, GlobalConfig } from 'payload' + +import { describe, expect, test, vi } from 'vitest' + +import type { I18nConfig } from '../src/modules/i18n/types.js' + +import { ipalKit } from '../src/plugin.js' + +const i18n: I18nConfig = { + defaultLocale: 'pl', + locales: [ + { code: 'pl', label: 'Polski' }, + { code: 'en', label: 'English' }, + ], +} + +const empty = (extra: Partial = {}): Config => + ({ collections: [], secret: 'x', ...extra }) as unknown as Config + +const admin = { id: 1, roles: ['admin'] } +const editor = { id: 2, roles: ['editor'] } +const user = { id: 3, roles: ['user'] } + +/** Runs a collection/global access function the way Payload does. */ +const run = (fn: Access | undefined, u: unknown) => + fn ? fn({ req: { user: u } } as never) : 'payload-default' + +describe('injected auth collection', () => { + test('with roles: a plain user can only see and edit itself, never create or delete', async () => { + const config = await ipalKit({ access: { authCollection: 'users' }, i18n, twoFactor: false })(empty()) + const access = config.collections?.find((c) => c.slug === 'users')?.access ?? {} + + expect(run(access.update, user)).toEqual({ id: { equals: 3 } }) + expect(run(access.read, user)).toEqual({ id: { equals: 3 } }) + expect(run(access.delete, user)).toBe(false) + expect(run(access.create, user)).toBe(false) + expect(run(access.delete, editor)).toBe(false) + expect(run(access.update, null)).toBe(false) + + expect(run(access.update, admin)).toBe(true) + expect(run(access.delete, admin)).toBe(true) + expect(run(access.create, admin)).toBe(true) + }) + + test("the project's own auth collection keeps its own access", async () => { + const own = { slug: 'users', access: { read: () => true }, auth: true, fields: [] } + const config = await ipalKit({ access: { authCollection: 'users' }, i18n, twoFactor: false })( + empty({ collections: [own] as CollectionConfig[] }), + ) + expect(config.collections?.find((c) => c.slug === 'users')?.access).toBe(own.access) + }) +}) + +describe('2FA wraps the auth collection people log in with', () => { + const totp = () => vi.fn((_: unknown) => (c: Config) => c) + + test('defaults to access.authCollection, not a literal "users"', async () => { + const plugin = totp() + await ipalKit({ access: { authCollection: 'admins' }, i18n, twoFactor: { issuer: 'A', plugin: plugin as never } })( + empty(), + ) + expect(plugin).toHaveBeenCalledWith(expect.objectContaining({ collection: 'admins' })) + }) + + test('defaults to admin.user when access is not configured', async () => { + const plugin = totp() + await ipalKit({ i18n, twoFactor: { issuer: 'A', plugin: plugin as never } })( + empty({ admin: { user: 'staff' } } as Partial), + ) + expect(plugin).toHaveBeenCalledWith(expect.objectContaining({ collection: 'staff' })) + }) + + test('an explicit collectionSlug still wins', async () => { + const plugin = totp() + await ipalKit({ + access: { authCollection: 'users' }, + i18n, + twoFactor: { collectionSlug: 'admins', issuer: 'A', plugin: plugin as never }, + })(empty()) + expect(plugin).toHaveBeenCalledWith(expect.objectContaining({ collection: 'admins' })) + }) +}) + +describe('globals: public read, editor+ write', () => { + test.each(['site-settings', 'cookie-settings', 'notifications'])('%s', async (slug) => { + const config = await ipalKit({ access: { authCollection: 'users' }, i18n, twoFactor: false })(empty()) + const access = (config.globals?.find((g) => g.slug === slug) as GlobalConfig).access ?? {} + expect(run(access.read, null)).toBe(true) + expect(run(access.update, user)).toBe(false) + expect(run(access.update, null)).toBe(false) + expect(run(access.update, editor)).toBe(true) + expect(run(access.update, admin)).toBe(true) + }) +}) + +describe('forms collection: public read, editor+ write, Emails hidden from plain users', () => { + const build = async () => { + const config = await ipalKit({ access: { authCollection: 'users' }, forms: {}, i18n, twoFactor: false })(empty()) + return config.collections?.find((c) => c.slug === 'forms') as CollectionConfig + } + + test('create / update / delete need editor', async () => { + const { access = {} } = await build() + expect(run(access.read, null)).toBe(true) + for (const op of ['create', 'update', 'delete'] as const) { + expect(run(access[op], user)).toBe(false) + expect(run(access[op], editor)).toBe(true) + } + }) + + test('the Emails field (recipients, BCC) is unreadable for a plain user', async () => { + const forms = await build() + const emails = forms.fields.find((f: Field) => 'name' in f && f.name === 'emails') as { + access?: { read?: (a: unknown) => boolean } + } + expect(emails.access?.read?.({ req: { user } })).toBe(false) + expect(emails.access?.read?.({ req: { user: editor } })).toBe(true) + }) +}) From 8e10232765f37a816c0babbfd069d404c5c2695a Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?Rados=C5=82aw=20Smoli=C5=84ski?= Date: Thu, 22 Oct 2026 16:59:51 +0200 Subject: [PATCH 02/27] Rate limit: no IP shares a capped bucket; optional Turnstile hostname check A request without a usable client IP used to skip every limiter. It now counts against one shared 'unknown-ip' bucket at 20x the limit. submitForm, createSubmitAction and verifyTurnstile accept turnstileHostnames/hostnames to reject tokens solved on another domain. Co-Authored-By: Claude Opus 5.5 --- docs/forms.md | 7 ++++++ docs/turnstile.md | 7 ++++++ src/modules/forms/createSubmitAction.ts | 4 +++- src/modules/forms/submitForm.ts | 8 +++++-- src/modules/shared/rateLimit.ts | 32 ++++++++++++++++++------- src/modules/turnstile/verify.ts | 12 ++++++++++ test/rateLimit.test.ts | 7 ++++-- test/submitForm.test.ts | 23 ++++++++++++++++++ 8 files changed, 86 insertions(+), 14 deletions(-) diff --git a/docs/forms.md b/docs/forms.md index cab334d..5e0fc4c 100644 --- a/docs/forms.md +++ b/docs/forms.md @@ -210,6 +210,13 @@ za Cloudflare. Bez tego klient, który trafi do aplikacji z pominięciem proxy, podstawić dowolny z tych nagłówków. Ta sama opcja `clientIp` jest w `createSearchRoute` i `createMcpRoute`. +Brak IP (proxy obcina nagłówek, zły `IPAL_IP_HEADER`) **nie** omija limitu: takie żądania +dzielą jeden wspólny kubełek `unknown-ip` z limitem ×20 (`UNKNOWN_IP_FACTOR`) — prawdziwi +odwiedzający przechodzą, flood bez nagłówka nie. Bez przypięcia nagłówka kolejność +`cf-connecting-ip` → `x-real-ip` → XFF zostaje (zmiana na XFF-od-prawej złączyłaby za Cloudflare +wszystkich odwiedzających w kubełek węzła brzegowego) — dlatego `IPAL_IP_HEADER` na produkcji +jest obowiązkowe (`ipalEnvRules({ ipHeader: true })`). + Limity domyślnie trzymane są w pamięci, osobno dla każdej instancji. Kilka instancji → wspólny store (np. Redis) raz przy starcie: `setRateLimitStore({ hit })` (przykład w JSDoc `RateLimitStore`). Gdy store padnie, żądanie przechodzi (log ostrzeżenia). diff --git a/docs/turnstile.md b/docs/turnstile.md index cd02481..d63f235 100644 --- a/docs/turnstile.md +++ b/docs/turnstile.md @@ -91,6 +91,13 @@ Status zapisuje serwer przy weryfikacji formularza (bez crona), najwyżej raz na przy trwającym błędzie i od razu przy zmianie stanu. Zapis nowych kluczy w panelu czyści status; po następnym wysłaniu formularza pojawi się aktualny. Twardo (fail closed): `submitForm({ …, turnstileOnConfigError: 'reject' })`. +Domyślne `allow` jest świadome: `degraded` wywołuje tylko nasza konfiguracja albo awaria +Cloudflare — odwiedzający nie może go wymusić, a formularze nie padają razem z Cloudflare. + +**Hostname tokenu (opcjonalnie):** `createSubmitAction({ …, turnstileHostnames: ['www.firma.pl', 'firma.pl'] })` +(albo `submitForm` / `verifyTurnstile({ hostnames })`) odrzuca token rozwiązany na innej domenie +(`reason: 'turnstile'`, log `token solved on "…"`). Przydatne, gdy widget dopuszcza dowolny hostname. +Testowe klucze Cloudflare zwracają `example.com` — w dev zostaw puste. Po aktualizacji pluginu: `pnpm payload generate:importmap` (nowe komponenty panelu); Postgres: `pnpm payload migrate:create` (pole `turnstileStatus` w SiteIntegrations). diff --git a/src/modules/forms/createSubmitAction.ts b/src/modules/forms/createSubmitAction.ts index f216801..880ea82 100644 --- a/src/modules/forms/createSubmitAction.ts +++ b/src/modules/forms/createSubmitAction.ts @@ -21,7 +21,7 @@ type CreateSubmitActionArgs = { headers: () => Headers | Promise /** Honeypot field name. Default HONEYPOT_FIELD. */ honeypotField?: string -} & Pick +} & Pick export type SubmitActionResult = { field?: string @@ -55,6 +55,7 @@ export function createSubmitAction({ headers, honeypotField = HONEYPOT_FIELD, maxPerMinute, + turnstileHostnames, turnstileOnConfigError, }: CreateSubmitActionArgs) { return async function sendForm( @@ -78,6 +79,7 @@ export function createSubmitAction({ locale, maxPerMinute, payload, + turnstileHostnames, turnstileOnConfigError, turnstileToken: typeof turnstileToken === 'string' ? turnstileToken.trim() || undefined : undefined, }) diff --git a/src/modules/forms/submitForm.ts b/src/modules/forms/submitForm.ts index e9bcca3..539e74d 100644 --- a/src/modules/forms/submitForm.ts +++ b/src/modules/forms/submitForm.ts @@ -27,6 +27,8 @@ export type SubmitFormArgs = { */ maxPerMinute?: number payload: BasePayload + /** Hostnames a Turnstile token must come from (see verifyTurnstile `hostnames`). Unset = not checked. */ + turnstileHostnames?: string[] /** * Turnstile can't be verified because of OUR side (missing/wrong secret, * Cloudflare unreachable): 'allow' (default) accepts the submission and shows @@ -101,11 +103,13 @@ export async function submitForm({ locale, maxPerMinute = 5, payload, + turnstileHostnames, turnstileOnConfigError = 'allow', turnstileToken, }: SubmitFormArgs): Promise { // 1. Rate limit — cheapest gate, drops a flood before any real work. - if (maxPerMinute > 0 && ip) { + // No IP → the limiter's shared "unknown" bucket, never a free pass. + if (maxPerMinute > 0) { if (!(await consumeRateLimit({ key: ip, max: maxPerMinute })).ok) { return { reason: 'rate_limited', success: false } } @@ -117,7 +121,7 @@ export async function submitForm({ if ((await getTurnstileConfig(payload)).enabled) { const ok = Boolean(turnstileToken) && - (await verifyTurnstile({ ip, onConfigError: turnstileOnConfigError, payload, token: turnstileToken! })) + (await verifyTurnstile({ hostnames: turnstileHostnames, ip, onConfigError: turnstileOnConfigError, payload, token: turnstileToken! })) if (!ok) { return { reason: 'turnstile', success: false } } diff --git a/src/modules/shared/rateLimit.ts b/src/modules/shared/rateLimit.ts index bf720bd..39c9fe8 100644 --- a/src/modules/shared/rateLimit.ts +++ b/src/modules/shared/rateLimit.ts @@ -69,6 +69,20 @@ export type RateLimitArgs = { type CheckArgs = { cost?: number } & RateLimitArgs +/** + * Requests with no usable client IP (a proxy that strips the header, a + * misconfigured IPAL_IP_HEADER) share one bucket with a roomier limit. Letting + * them through unlimited meant a client that simply omits the header walked + * past every limiter; one shared bucket keeps real visitors flowing while + * capping the flood. + */ +export const UNKNOWN_IP_KEY = 'unknown-ip' +export const UNKNOWN_IP_FACTOR = 20 + +function resolveKey(key: string, max: number): { key: string; max: number } { + return key ? { key, max } : { key: UNKNOWN_IP_KEY, max: max * UNKNOWN_IP_FACTOR } +} + function hitMemory(id: string, cost: number, windowMs: number): Bucket { const now = Date.now() sweep(now) @@ -87,11 +101,11 @@ function hitMemory(id: string, cost: number, windowMs: number): Bucket { * backwards compatibility; the plugin's own routes use consumeRateLimit. * * Returns true when the request is within the limit, false when it should be - * rejected. A missing key (no IP) is allowed through — better to accept a - * submission than to block everyone behind a proxy that strips the header. + * rejected. A missing key (no IP) counts against one shared bucket with + * UNKNOWN_IP_FACTOR × max. */ -export function checkRateLimit({ cost = 1, key, max = 5, scope = 'form', windowMs = 60_000 }: CheckArgs): boolean { - if (!key) {return true} +export function checkRateLimit({ cost = 1, key: rawKey, max: rawMax = 5, scope = 'form', windowMs = 60_000 }: CheckArgs): boolean { + const { key, max } = resolveKey(rawKey, rawMax) const id = `${scope}:${key}` const current = buckets.get(id) const used = current && current.resetAt > Date.now() ? current.count : 0 @@ -108,12 +122,12 @@ export function checkRateLimit({ cost = 1, key, max = 5, scope = 'form', windowM */ export async function consumeRateLimit({ cost = 1, - key, - max = 5, + key: rawKey, + max: rawMax = 5, scope = 'form', windowMs = 60_000, }: CheckArgs): Promise<{ ok: boolean; retryAfter: number }> { - if (!key) {return { ok: true, retryAfter: 0 }} + const { key, max } = resolveKey(rawKey, rawMax) const id = `${scope}:${key}` let bucket: Bucket @@ -164,8 +178,8 @@ export type ClientIpOptions = { * and walk past the rate limit; each proxy appends the address it saw, so the * rightmost entries are the trustworthy ones. * - * Empty string when nothing usable is present — the limiter then lets the - * request through. + * Empty string when nothing usable is present — the limiter then counts it in + * the shared UNKNOWN_IP_KEY bucket. */ let warnedUnpinned = false diff --git a/src/modules/turnstile/verify.ts b/src/modules/turnstile/verify.ts index 8a6b38d..f89461d 100644 --- a/src/modules/turnstile/verify.ts +++ b/src/modules/turnstile/verify.ts @@ -19,6 +19,13 @@ type IntegrationsWithTurnstile = { } type VerifyTurnstileArgs = { + /** + * Hostnames the token must have been solved on (siteverify's `hostname`), e.g. + * ['www.example.com', 'example.com']. Unset = not checked. Guards against a + * token solved on another site that shares the widget (a sitekey allowing any + * hostname). Cloudflare's test keys report 'example.com' — leave unset in dev. + */ + hostnames?: string[] /** Client IP. Sent to Cloudflare only with `sendRemoteIp: true`. */ ip?: string /** @@ -73,6 +80,7 @@ const PLUGIN_ERRORS: Record = { * SiteIntegrations is updated (throttled) so the panel shows failures. */ export async function checkTurnstile({ + hostnames, ip, payload, sendRemoteIp = false, @@ -112,6 +120,10 @@ export async function checkTurnstile({ if (typeof data?.success !== 'boolean') {return degraded('bad-response')} if (data.success) { + if (hostnames?.length && !hostnames.some((h) => h.toLowerCase() === data.hostname?.toLowerCase())) { + console.warn(`[ipal] Turnstile rejected: token solved on "${data.hostname ?? '?'}", expected ${hostnames.join(', ')}`) + return { code: 'hostname-mismatch', outcome: 'reject' } + } await recordIntegrationStatus(payload, STATUS_FIELD, previous, { state: 'ok' }) return { outcome: 'pass' } } diff --git a/test/rateLimit.test.ts b/test/rateLimit.test.ts index 8b0ccbc..a5bf341 100644 --- a/test/rateLimit.test.ts +++ b/test/rateLimit.test.ts @@ -3,6 +3,7 @@ import { afterEach, describe, expect, test, vi } from 'vitest' import { checkRateLimit, clientIp, + UNKNOWN_IP_FACTOR, consumeRateLimit, setRateLimitStore, } from '../src/modules/shared/rateLimit.js' @@ -64,8 +65,10 @@ describe('checkRateLimit (in memory)', () => { expect(checkRateLimit({ cost: 4, key: `k-${Math.random()}`, max: 3 })).toBe(false) }) - test('no key → allowed', () => { - expect(checkRateLimit({ key: '', max: 0 })).toBe(true) + test('no key → one shared bucket with a roomier limit, not a free pass', () => { + const scope = `s-${Math.random()}` + for (let i = 0; i < 2 * UNKNOWN_IP_FACTOR; i++) {expect(checkRateLimit({ key: '', max: 2, scope })).toBe(true)} + expect(checkRateLimit({ key: '', max: 2, scope })).toBe(false) }) }) diff --git a/test/submitForm.test.ts b/test/submitForm.test.ts index cfa39ee..6bf9d17 100644 --- a/test/submitForm.test.ts +++ b/test/submitForm.test.ts @@ -1,6 +1,7 @@ import { afterEach, beforeEach, describe, expect, test, vi } from 'vitest' import { submitForm } from '../src/modules/forms/submitForm.js' +import { UNKNOWN_IP_FACTOR } from '../src/modules/shared/rateLimit.js' import { fakePayload } from './helpers.js' vi.mock('server-only', () => ({})) @@ -82,6 +83,19 @@ describe('submitForm — Turnstile', () => { expect(create).not.toHaveBeenCalled() }) + test('turnstileHostnames: a token solved on another host is rejected', async () => { + mockSiteverify({ hostname: 'evil.example', success: true }) + const { create, payload } = fakePayload({ forms, integrations: keys }) + const base = { data, formId: 'contact', payload, turnstileToken: 'tok' } + expect(await submitForm({ ...base, ip: nextIp(), turnstileHostnames: ['www.firma.pl'] })).toEqual({ + reason: 'turnstile', + success: false, + }) + expect(create).not.toHaveBeenCalled() + mockSiteverify({ hostname: 'WWW.firma.pl', success: true }) + expect((await submitForm({ ...base, ip: nextIp(), turnstileHostnames: ['www.firma.pl'] })).success).toBe(true) + }) + test('configured + Cloudflare rejects OUR secret → allowed by default, refused with reject', async () => { mockSiteverify({ 'error-codes': ['invalid-input-secret'], success: false }) const { payload } = fakePayload({ forms, integrations: keys }) @@ -97,6 +111,15 @@ describe('submitForm — Turnstile', () => { describe('submitForm — other gates', () => { afterEach(() => vi.restoreAllMocks()) + test('no client IP is not a free pass — it shares one capped bucket', async () => { + const { payload } = fakePayload({ forms }) + let accepted = 0 + for (let i = 0; i < 50; i++) { + if ((await submitForm({ data, formId: 'contact', maxPerMinute: 1, payload })).success) {accepted++} + } + expect(accepted).toBe(UNKNOWN_IP_FACTOR) + }) + test('rate limit per IP', async () => { const { payload } = fakePayload({ forms }) const ip = nextIp() From 561a9e2bb7e524078186dd82dc5607b4175c3129 Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?Rados=C5=82aw=20Smoli=C5=84ski?= Date: Thu, 22 Oct 2026 17:02:07 +0200 Subject: [PATCH 03/27] Site Settings read at depth 1; archive page re-fetched at page depth getSettings ran findGlobal at depth 2 on every request, pulling the relations of every page a project field links to (menus). Depth 1 keeps slug/title. The archive page itself was rendered from the settings copy, which maxDepth caps at 1, so its media never populated; resolveRoute now re-fetches it at depth 2 like the homepage. Co-Authored-By: Claude Opus 5.5 --- docs/content.md | 6 ++ src/modules/content/resolveRoute.ts | 14 +++- src/modules/frontend/createContentHelpers.ts | 7 +- test/settingsDepth.test.ts | 84 ++++++++++++++++++++ 4 files changed, 108 insertions(+), 3 deletions(-) create mode 100644 test/settingsDepth.test.ts diff --git a/docs/content.md b/docs/content.md index ebeb2ba..721e8c1 100644 --- a/docs/content.md +++ b/docs/content.md @@ -104,6 +104,12 @@ fabryce i jest współdzielona — dlatego to fabryka, nie luźne funkcje. Bez t `cache()` nie dedupikowałby między helperami, a Next woła generateMetadata i komponent strony osobno. +`getSettings(locale)` czyta Site Settings z **`depth: 1`** — relacje (logo, strony w menu, +strony systemowe) przychodzą jako dokumenty (`slug`, `title`), ale **ich** relacje już jako ID. +Strona, którą `resolveRoute` renderuje (homepage, archiwum, zwykła strona), jest pobierana +osobno z `depth: 2`. Potrzebujesz głębiej w layoucie (np. obraz strony podlinkowanej w menu)? +Pobierz ten jeden dokument sam, zamiast podnosić głębokość całego globala na każdym żądaniu. + `resolveRoute` z fabryki przyjmuje `(locale, segments, page)` — rozstrzyga trasę. Pobranie wpisów to osobna funkcja `getEntries` (patrz niżej), bo routing i pobieranie danych to dwie różne odpowiedzialności. diff --git a/src/modules/content/resolveRoute.ts b/src/modules/content/resolveRoute.ts index d7afe46..46efc0b 100644 --- a/src/modules/content/resolveRoute.ts +++ b/src/modules/content/resolveRoute.ts @@ -143,12 +143,22 @@ export async function resolveRoute({ if (archiveDoc.slug !== first) {continue} if (!isPublic(archiveDoc, draft)) {return null} - // /pl/artykuly → the archive page itself. + // /pl/artykuly → the archive page itself. Settings hold it shallow (depth + // 1); re-fetch it at page depth so its blocks render like any other page. if (rest.length === 0) { + const doc = await payload.findByID({ + id: archiveDoc.id, + collection: pagesSlug as never, + depth: 2, + disableErrors: true, + draft, + locale: locale as never, + }) + if (!doc || !isPublic(doc, draft)) {return null} return { type: 'archive', collection: collection.slug, - doc: archiveDoc as Record, + doc: doc as Record, page, perPage: collection.perPage ?? 10, } diff --git a/src/modules/frontend/createContentHelpers.ts b/src/modules/frontend/createContentHelpers.ts index 584c8b5..2a8ec21 100644 --- a/src/modules/frontend/createContentHelpers.ts +++ b/src/modules/frontend/createContentHelpers.ts @@ -188,10 +188,15 @@ export function createContentHelpers({ /** * SiteSettings for a locale — ONE query per locale per request, shared by the * layout, generatePageMetadata, resolveRoute and anything else that asks. + * + * Depth 1: logos and assigned pages arrive as documents (slug, title), but + * not THEIR relations. Depth 2 pulled every assigned page's blocks and media + * (homepage, archives, system pages) into every request; resolveRoute + * re-fetches the one page it actually renders. */ const getSettings = cache(async (locale: string) => { const payload = await getCachedPayload() - return payload.findGlobal({ slug: settingsSlug as never, depth: 2, locale: locale as never }) + return payload.findGlobal({ slug: settingsSlug as never, depth: 1, locale: locale as never }) }) /** What does this URL point at? Routing only — no listing data. */ diff --git a/test/settingsDepth.test.ts b/test/settingsDepth.test.ts new file mode 100644 index 0000000..d66880b --- /dev/null +++ b/test/settingsDepth.test.ts @@ -0,0 +1,84 @@ +/** Site Settings must stay shallow on every request; the rendered page is re-fetched at page depth. */ +import type { Payload } from 'payload' + +import { sqliteAdapter } from '@payloadcms/db-sqlite' +import { lexicalEditor } from '@payloadcms/richtext-lexical' +import os from 'os' +import path from 'path' +import { buildConfig, getPayload } from 'payload' +import { afterAll, beforeAll, describe, expect, test } from 'vitest' + +import { resolveRoute } from '../src/modules/content/resolveRoute.js' +import { createContentHelpers } from '../src/modules/frontend/createContentHelpers.js' +import { ipalKit } from '../src/plugin.js' + +let payload: Payload +let configPromise: ReturnType +let mediaId: number | string + +beforeAll(async () => { + configPromise = buildConfig({ + collections: [ + { + slug: 'pages', + fields: [ + { name: 'title', type: 'text' }, + { name: 'slug', type: 'text', localized: true }, + { name: 'hero', type: 'upload', relationTo: 'media' }, + ], + }, + { slug: 'posts', fields: [{ name: 'title', type: 'text' }, { name: 'slug', type: 'text', localized: true }] }, + { slug: 'media', fields: [{ name: 'alt', type: 'text' }], upload: { staticDir: path.join(os.tmpdir(), 'ipal-test-media') } }, + ], + db: sqliteAdapter({ client: { url: 'file::memory:' }, push: true }), + editor: lexicalEditor(), + plugins: [ + ipalKit({ + access: { authCollection: 'users' }, + content: { collections: [{ slug: 'posts' }] }, + i18n: { defaultLocale: 'pl', locales: [{ code: 'pl', label: 'Polski' }] }, + pages: { slug: 'pages' }, + // a project field, e.g. a menu linking pages — not capped by maxDepth + siteSettingsFields: [{ name: 'featured', type: 'relationship', relationTo: 'pages' }], + twoFactor: false, + }), + ], + secret: 'depth-test', + telemetry: false, + }) + payload = await getPayload({ config: configPromise }) + const png = Buffer.from('iVBORw0KGgoAAAANSUhEUgAAAAEAAAABCAYAAAAfFcSJAAAADUlEQVR42mNk+M9QDwADhgGAWjR9awAAAABJRU5ErkJggg==', 'base64') + const media = await payload.create({ + collection: 'media' as never, + data: { alt: 'hero' } as never, + file: { data: png, mimetype: 'image/png', name: 'hero.png', size: png.length }, + }) + mediaId = media.id + const home = await payload.create({ collection: 'pages' as never, data: { slug: 'home', hero: mediaId, title: 'Home' } as never }) + const blog = await payload.create({ collection: 'pages' as never, data: { slug: 'blog', hero: mediaId, title: 'Blog' } as never }) + await payload.updateGlobal({ slug: 'site-settings' as never, data: { homepage: home.id, featured: home.id, postsArchive: blog.id, siteName: 'Acme' } as never }) +}, 60_000) + +afterAll(async () => { + await payload?.destroy() +}) + +describe('Site Settings depth', () => { + test('getSettings populates related pages one level only (their media stays an id)', async () => { + const { getSettings } = createContentHelpers({ config: configPromise }) + const settings = (await getSettings('pl')) as { featured: { hero: unknown; slug: string } } + expect(settings.featured.slug).toBe('home') + expect(settings.featured.hero).toBe(mediaId) + }) + + test('the archive page is re-fetched at page depth, so its blocks and media render', async () => { + const route = await resolveRoute({ + content: { collections: [{ slug: 'posts' }] }, + locale: 'pl', + payload, + segments: ['blog'], + }) + expect(route?.type).toBe('archive') + expect((route?.doc as { hero: { alt?: string } }).hero).toMatchObject({ alt: 'hero' }) + }) +}) From 78f4f5c16b08a3e075096fffef2d4184c8ca9d97 Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?Rados=C5=82aw=20Smoli=C5=84ski?= Date: Thu, 22 Oct 2026 17:02:25 +0200 Subject: [PATCH 04/27] First account of the auth collection always becomes admin Co-Authored-By: Claude Opus 5.5 --- docs/access.md | 3 ++- src/modules/access/rolesField.ts | 13 +++++++++++++ test/accessControl.test.ts | 23 +++++++++++++++++++++++ 3 files changed, 38 insertions(+), 1 deletion(-) diff --git a/docs/access.md b/docs/access.md index 0841278..b09b99d 100644 --- a/docs/access.md +++ b/docs/access.md @@ -19,7 +19,8 @@ Wstrzykuje pole `roles` (select hasMany, `saveToJWT`, tylko admin może nadawać i zmieniać role — także przy tworzeniu konta, więc otwarta rejestracja nie przepuści `roles: ['admin']`; nie-admin dostaje `defaultRole`) do wskazanej kolekcji. Ekran pierwszego użytkownika i Local API (seed) działają z `overrideAccess`, więc -pierwszego admina nadal da się utworzyć. Kolekcja należy do Ciebie +pierwszego admina nadal da się utworzyć. **Pierwsze konto w kolekcji zawsze dostaje +`roles: ['admin']`** (hook pola), nawet gdy ekran pierwszego użytkownika nie pokazuje pola ról. Kolekcja należy do Ciebie (create-payload-app) — plugin tylko dokłada pole. ## Co plugin zamyka sam diff --git a/src/modules/access/rolesField.ts b/src/modules/access/rolesField.ts index 45e647e..1434b5d 100644 --- a/src/modules/access/rolesField.ts +++ b/src/modules/access/rolesField.ts @@ -14,6 +14,10 @@ import { ROLE_HIERARCHY } from './types.js' * A non-admin's new account gets `defaultRole`. The first-user screen and * Local API calls (seed scripts) run with overrideAccess, so they can still * create the first admin. + * + * The very first account of the collection always becomes admin: the + * first-user screen may not show this field, and a site whose only account is + * a plain 'user' has nobody who can manage users, integrations or roles. */ export function buildRolesField(defaultRole: Role = 'user'): Field { return { @@ -29,6 +33,15 @@ export function buildRolesField(defaultRole: Role = 'user'): Field { }, defaultValue: [defaultRole], hasMany: true, + hooks: { + beforeChange: [ + async ({ collection, operation, req, value }) => { + if (operation !== 'create' || !collection) {return value} + const { totalDocs } = await req.payload.count({ collection: collection.slug, overrideAccess: true, req }) + return totalDocs === 0 ? ['admin'] : value + }, + ], + }, options: ROLE_HIERARCHY.map((role) => ({ label: role.charAt(0).toUpperCase() + role.slice(1), value: role, diff --git a/test/accessControl.test.ts b/test/accessControl.test.ts index 5306bdd..f07ce17 100644 --- a/test/accessControl.test.ts +++ b/test/accessControl.test.ts @@ -117,3 +117,26 @@ describe('forms collection: public read, editor+ write, Emails hidden from plain expect(emails.access?.read?.({ req: { user: editor } })).toBe(true) }) }) + +describe('roles field: the first account becomes admin', () => { + const hook = async (totalDocs: number, value: string[]) => { + const config = await ipalKit({ access: { authCollection: 'users' }, i18n, twoFactor: false })(empty()) + const users = config.collections?.find((c) => c.slug === 'users') as CollectionConfig + const roles = users.fields.find((f) => 'name' in f && f.name === 'roles') as { hooks?: { beforeChange?: ((a: unknown) => unknown)[] } } + const count = vi.fn(async () => ({ totalDocs })) + return roles.hooks?.beforeChange?.[0]?.({ + collection: { slug: 'users' }, + operation: 'create', + req: { payload: { count } }, + value, + }) + } + + test('empty collection → admin, whatever was sent', async () => { + expect(await hook(0, ['user'])).toEqual(['admin']) + }) + + test('later accounts keep what access allowed', async () => { + expect(await hook(1, ['user'])).toEqual(['user']) + }) +}) From 0bfc509102764b7c09710e43209a2415b93d4b7d Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?Rados=C5=82aw=20Smoli=C5=84ski?= Date: Thu, 22 Oct 2026 17:04:09 +0200 Subject: [PATCH 05/27] Run stats and consent-log retention purges off the request The daily purge was awaited inside the visitor's request via payload.delete, which loads and deletes expired documents one by one. It now runs as one db.deleteMany in the background; failures are logged and retried. Co-Authored-By: Claude Opus 5.5 --- docs/consent.md | 2 +- docs/stats.md | 4 +- src/modules/consent/consentLog.ts | 13 ++---- src/modules/shared/purge.ts | 29 +++++++++++++ src/modules/stats/endpoint.ts | 12 ++---- test/retentionPurge.test.ts | 70 +++++++++++++++++++++++++++++++ 6 files changed, 109 insertions(+), 21 deletions(-) create mode 100644 src/modules/shared/purge.ts create mode 100644 test/retentionPurge.test.ts diff --git a/docs/consent.md b/docs/consent.md index 6d2c0ea..e56e50b 100644 --- a/docs/consent.md +++ b/docs/consent.md @@ -305,7 +305,7 @@ chcesz zachować sprzątanie locale (albo zaimportuj `LOCALE_COOKIE_NAME` i doda - **Rejestr zgód (dowód zgody, art. 7 ust. 1 RODO):** `ipalKit({ consentLog: true })` + ``. Zapisuje losowy identyfikator (ten sam co w ciasteczku), wybory, wersję polityki i czas — **bez IP i user-agenta**. Kolekcja *Consent records* - (tylko admin), automatyczne czyszczenie po `retentionDays` (domyślnie 1095). Postgres: `migrate:create`. + (tylko admin), automatyczne czyszczenie po `retentionDays` (domyślnie 1095; raz na dobę, w tle — zapis zgody na nie nie czeka). Postgres: `migrate:create`. - **Tabela ciasteczek** dla strony polityki: Cookie Settings → *Cookies* (wypełniana skanem, skill `ipal-consent-check` → cookie-scan) + `getCookieTable` + `` z `/rsc`. - Ciasteczko zgody ma `Secure` na HTTPS. diff --git a/docs/stats.md b/docs/stats.md index 9e781f2..fbc29f4 100644 --- a/docs/stats.md +++ b/docs/stats.md @@ -87,7 +87,9 @@ Ciąg odsłon z przerwami poniżej 30 minut, w ramach jednego dnia. Restart serw (każda ma własną sól) mogą rozbić trwającą wizytę na dwie — dla statystyk bez znaczenia. **Nie** zapisuj soli w bazie, żeby to „naprawić”: wtedy wczorajsze hashe dałoby się odwrócić do IP. -Wizyty starsze niż `retentionDays` są usuwane automatycznie (raz na dobę, przy pierwszej odsłonie). +Wizyty starsze niż `retentionDays` są usuwane automatycznie (raz na dobę na proces, przy pierwszej odsłonie) +jednym zapytaniem `db.deleteMany`, **w tle** — odsłona nie czeka na czyszczenie; błąd trafia do logu i +czyszczenie ponawia się przy następnej odsłonie. ## Prawa odwiedzającego (RODO) diff --git a/src/modules/consent/consentLog.ts b/src/modules/consent/consentLog.ts index 83e0337..8f1f72b 100644 --- a/src/modules/consent/consentLog.ts +++ b/src/modules/consent/consentLog.ts @@ -1,6 +1,7 @@ import type { CollectionConfig, Endpoint, PayloadRequest } from 'payload' import { isAdmin } from '../access/predicates.js' +import { createDailyPurge } from '../shared/purge.js' import { clientIp, consumeRateLimit } from '../shared/rateLimit.js' import { CONSENT_CATEGORIES } from './categories.js' @@ -53,7 +54,7 @@ export function buildConsentLogCollection(): CollectionConfig { } } -let lastPurge = 0 +const purge = createDailyPurge(CONSENT_LOG_SLUG) export function buildConsentLogEndpoint({ retentionDays = 1095 }: ConsentLogOptions = {}): Endpoint { return { @@ -89,15 +90,7 @@ export function buildConsentLogEndpoint({ retentionDays = 1095 }: ConsentLogOpti } as never, overrideAccess: true, }) - const now = Date.now() - if (now - lastPurge > 24 * 60 * 60 * 1000) { - lastPurge = now - await req.payload.delete({ - collection: CONSENT_LOG_SLUG as never, - overrideAccess: true, - where: { createdAt: { less_than: new Date(now - retentionDays * 86_400_000).toISOString() } }, - }) - } + purge(req.payload, { createdAt: { less_than: new Date(Date.now() - retentionDays * 86_400_000).toISOString() } }) return Response.json({ ok: true }, { status: 201 }) } catch (err) { req.payload.logger.error(`[ipal] consent log write failed: ${err instanceof Error ? err.message : String(err)}`) diff --git a/src/modules/shared/purge.ts b/src/modules/shared/purge.ts new file mode 100644 index 0000000..7367ee7 --- /dev/null +++ b/src/modules/shared/purge.ts @@ -0,0 +1,29 @@ +import type { BasePayload, Where } from 'payload' + +const DAY_MS = 24 * 60 * 60 * 1000 + +/** + * Retention purge for a log collection (stats visits, consent records): at + * most once a day per process, and OFF the visitor's request. + * + * It used to be awaited inside the hit / consent request through + * `payload.delete`, which loads every expired document and deletes them one by + * one — the first purge after months of traffic held a visitor's request for + * as long as that took. `db.deleteMany` is a single query (these collections + * have no hooks to run), started and left to finish on its own; a failure is + * logged and retried on the next request. + */ +export function createDailyPurge(collection: string) { + let lastPurge = 0 + return (payload: BasePayload, where: Where): void => { + const now = Date.now() + if (now - lastPurge < DAY_MS) {return} + lastPurge = now + void Promise.resolve() + .then(() => payload.db.deleteMany({ collection: collection as never, where })) + .catch((err: unknown) => { + lastPurge = 0 + payload.logger.error(`[ipal] ${collection} retention purge failed: ${err instanceof Error ? err.message : String(err)}`) + }) + } +} diff --git a/src/modules/stats/endpoint.ts b/src/modules/stats/endpoint.ts index 1d268ed..5857257 100644 --- a/src/modules/stats/endpoint.ts +++ b/src/modules/stats/endpoint.ts @@ -3,6 +3,7 @@ import type { Endpoint, PayloadRequest } from 'payload' import type { StatsOptions, StatsPage, StatsVisit } from './collection.js' import { CONSENT_COOKIE, CONSENT_VERSION, parseConsent } from '../consent/storage.js' +import { createDailyPurge } from '../shared/purge.js' import { clientIp, consumeRateLimit } from '../shared/rateLimit.js' import { STATS_SLUG } from './collection.js' import { dayOf, deviceFromUa, isBot, referrerHost, sanitizePath, VISITOR_ID_PATTERN } from './parse.js' @@ -11,7 +12,7 @@ import { visitKey } from './visitKey.js' const VISIT_GAP_MS = 30 * 60 * 1000 const MAX_PAGES = 200 -let lastPurge = 0 +const purge = createDailyPurge(STATS_SLUG) let policy: { at: number; version: number } | null = null /** Cookie Settings → Policy version, cached for a minute (read on every hit). */ @@ -139,14 +140,7 @@ export function buildStatsEndpoint({ retentionDays = 90, timeZone = 'Europe/Wars }) } - if (now.getTime() - lastPurge > 24 * 60 * 60 * 1000) { - lastPurge = now.getTime() - await req.payload.delete({ - collection: STATS_SLUG as never, - overrideAccess: true, - where: { lastAt: { less_than: new Date(now.getTime() - retentionDays * 86_400_000).toISOString() } }, - }) - } + purge(req.payload, { lastAt: { less_than: new Date(now.getTime() - retentionDays * 86_400_000).toISOString() } }) } catch (err) { req.payload.logger.error(`[ipal] stats hit failed: ${err instanceof Error ? err.message : String(err)}`) } diff --git a/test/retentionPurge.test.ts b/test/retentionPurge.test.ts new file mode 100644 index 0000000..da5f656 --- /dev/null +++ b/test/retentionPurge.test.ts @@ -0,0 +1,70 @@ +/** Retention purges must never hold a visitor's request. */ +import type { PayloadRequest } from 'payload' + +import { describe, expect, test, vi } from 'vitest' + +import { buildConsentLogEndpoint } from '../src/modules/consent/consentLog.js' +import { buildStatsEndpoint } from '../src/modules/stats/endpoint.js' + +const CHROME = 'Mozilla/5.0 (Macintosh; Intel Mac OS X 10_15_7) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/130.0 Safari/537.36' + +/** A purge that never finishes — the request must still answer. */ +function fakePayload() { + return { + create: vi.fn(async ({ data }: { data: object }) => ({ id: 1, ...data })), + db: { deleteMany: vi.fn(() => new Promise(() => {})) }, + delete: vi.fn(() => new Promise(() => {})), + find: vi.fn(async () => ({ docs: [] })), + findGlobal: vi.fn(async () => ({})), + logger: { error: vi.fn() }, + } +} + +const call = (endpoint: { handler: unknown }, payload: unknown, body: unknown) => + (endpoint.handler as (r: PayloadRequest) => Promise)( + Object.assign( + new Request('http://acme.pl/api/x', { + body: JSON.stringify(body), + headers: { 'content-type': 'application/json', host: 'acme.pl', 'user-agent': CHROME, 'x-real-ip': '203.0.113.9' }, + method: 'POST', + }), + { payload, user: null }, + ) as unknown as PayloadRequest, + ) + +const settle = (p: Promise) => Promise.race([p, new Promise<'hung'>((r) => setTimeout(() => r('hung'), 200))]) + +describe('retention purge runs off the request', () => { + test('stats hit answers while the purge is still running; one bulk query, once a day', async () => { + const payload = fakePayload() + const endpoint = buildStatsEndpoint({ timeZone: 'UTC' }) + const res = await settle(call(endpoint, payload, { p: '/pl' })) + expect(res).not.toBe('hung') + expect((res as Response).status).toBe(204) + await new Promise((r) => setTimeout(r, 0)) + expect(payload.db.deleteMany).toHaveBeenCalledOnce() + expect(payload.delete).not.toHaveBeenCalled() + await call(endpoint, payload, { p: '/pl/oferta' }) + expect(payload.db.deleteMany).toHaveBeenCalledOnce() + }) + + test('consent log answers while the purge is still running', async () => { + const payload = fakePayload() + const body = { id: 'ab'.repeat(16), state: { analytics: true, functional: true, marketing: false, necessary: true }, version: 1 } + const res = await settle(call(buildConsentLogEndpoint(), payload, body)) + expect(res).not.toBe('hung') + expect((res as Response).status).toBe(201) + await new Promise((r) => setTimeout(r, 0)) + expect(payload.db.deleteMany).toHaveBeenCalledOnce() + }) + + test('a failed purge is logged, not thrown at the visitor', async () => { + const payload = { ...fakePayload(), db: { deleteMany: vi.fn(async () => { throw new Error('db down') }) } } + vi.useFakeTimers({ now: Date.now() + 2 * 86_400_000, toFake: ['Date'] }) + const res = await call(buildStatsEndpoint({ timeZone: 'UTC' }), payload, { p: '/pl' }) + vi.useRealTimers() + expect(res.status).toBe(204) + await new Promise((r) => setTimeout(r, 0)) + expect(payload.logger.error).toHaveBeenCalledWith(expect.stringContaining('retention purge failed')) + }) +}) From 9a72ebfaff3a860c74ed83dbd9e139c233b87e31 Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?Rados=C5=82aw=20Smoli=C5=84ski?= Date: Thu, 22 Oct 2026 17:05:14 +0200 Subject: [PATCH 06/27] Analytics: consentMode 'basic' keeps Google tags out until consent Opt-in; the default stays 'advanced' (tag loads with denied signals). shouldLoadGoogle holds the rule so it is testable without a DOM. Co-Authored-By: Claude Opus 5.5 --- docs/analytics.md | 12 +++++++-- src/modules/analytics/Analytics.tsx | 41 ++++++++++++++++++++++++++--- test/analyticsConsent.test.ts | 19 +++++++++++++ 3 files changed, 66 insertions(+), 6 deletions(-) create mode 100644 test/analyticsConsent.test.ts diff --git a/docs/analytics.md b/docs/analytics.md index cf5e966..94527af 100644 --- a/docs/analytics.md +++ b/docs/analytics.md @@ -3,8 +3,10 @@ Ładuje tagi analityczne i marketingowe wpisane w panelu, każdy zgodnie ze zgodą z modułu consent: -- **Google (GA4 / GTM)** — przez Consent Mode v2: tag ładuje się od razu, ale - dostaje decyzję odwiedzającego, zanim cokolwiek zmierzy. +- **Google (GA4 / GTM)** — przez Consent Mode v2. Domyślnie (`consentMode: 'advanced'`) tag + ładuje się od razu, ale dostaje decyzję odwiedzającego (przed zgodą: wszystko `denied`), zanim + cokolwiek zmierzy — Google dostaje wtedy pingi bez cookies. `consentMode: 'basic'` → **zero + żądań do Google przed zgodą** na analytics lub marketing (patrz niżej). - **Pozostałe (Meta Pixel, Microsoft Clarity, LinkedIn Insight, TikTok Pixel)** — nie mają Consent Mode, więc ładują się **dopiero po zgodzie** na właściwą kategorię. Reagują na żywo: klik „Akceptuj” → tag startuje bez przeładowania. @@ -104,6 +106,12 @@ w ipal-kit (core = engine). ## Jak działa Consent Mode +**Tryb `basic` vs `advanced`.** `` (albo +``): skrypt `googletagmanager.com` nie ładuje się, dopóki +odwiedzający nie zgodzi się na analytics lub marketing — wymóg „zero tagów przed zgodą”. Kosztem +jest brak modelowania konwersji dla osób bez zgody. Domyślne `advanced` ładuje tag od razu z +sygnałami `denied`. Wybór trybu to decyzja klienta — zapisz ją w „Ustaleniach projektu”. + 1. Przed załadowaniem tagu: `gtag('consent', 'default', …)` z zapisaną decyzją odwiedzającego (albo wszystko `denied`, gdy jeszcze nie zdecydował). 2. Tag się ładuje i respektuje ten stan od pierwszego trafienia. diff --git a/src/modules/analytics/Analytics.tsx b/src/modules/analytics/Analytics.tsx index 83c6e5d..0eeab0c 100644 --- a/src/modules/analytics/Analytics.tsx +++ b/src/modules/analytics/Analytics.tsx @@ -40,6 +40,17 @@ function injectScript(src: string) { } export type AnalyticsProps = { + /** + * Google Consent Mode flavour. + * - `'advanced'` (default): the Google tag (GA4 / GTM) loads before the + * visitor decides, with every signal `denied`; Google gets cookieless + * pings and models conversions. + * - `'basic'`: no request to Google at all until the visitor grants analytics + * or marketing — "zero tags before consent", like the non-Google pixels. + * The Consent Mode default is still set first, so the tag starts with the + * stored choice. + */ + consentMode?: 'advanced' | 'basic' /** * Core Web Vitals mode: hold back every tag's NETWORK load until the first * user interaction (scroll, pointer, touch, key) or `deferTimeoutMs` after the @@ -58,6 +69,24 @@ 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). */ @@ -101,7 +130,8 @@ function useDeferredReady(defer: boolean, timeoutMs: number): boolean { * - **Google (GA4 / GTM)** — Consent Mode: the visitor's stored choice is set as * the default BEFORE the tag loads (always immediately, even with `defer`), * and useConsent pushes an update the moment they decide. GTM wins if both - * IDs are set. + * IDs are set. With `consentMode: 'basic'` the tag itself waits for an + * analytics or marketing grant. * - **Non-Google (Meta Pixel, Clarity, LinkedIn, TikTok)** — no Consent Mode, so * each loads ONLY after its category is granted (marketing for * Pixel/LinkedIn/TikTok, analytics for Clarity). Reacts live to the banner. @@ -115,6 +145,7 @@ function useDeferredReady(defer: boolean, timeoutMs: number): boolean { export function Analytics(props: AnalyticsProps) { const { clarityProjectId, + consentMode = 'advanced', defer = false, deferTimeoutMs = 3500, ga4MeasurementId, @@ -139,9 +170,11 @@ export function Analytics(props: AnalyticsProps) { defaultConsentSet.current = true }, [ga4MeasurementId, gtmContainerId, texts.version]) - // --- Google: load once `ready`; Consent Mode handles gating --- + // --- Google: load once `ready` (and, in 'basic' mode, once consented); + // Consent Mode handles what the tag may store --- + const googleAllowed = shouldLoadGoogle({ consentMode, ready, state }) useEffect(() => { - if (!ready) {return} + if (!googleAllowed) {return} if (!ga4MeasurementId && !gtmContainerId) {return} if (gtmContainerId) { window.dataLayer = window.dataLayer || [] @@ -152,7 +185,7 @@ export function Analytics(props: AnalyticsProps) { gtag('js', new Date()) gtag('config', ga4MeasurementId) } - }, [ready, ga4MeasurementId, gtmContainerId]) + }, [googleAllowed, ga4MeasurementId, gtmContainerId]) // --- 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 diff --git a/test/analyticsConsent.test.ts b/test/analyticsConsent.test.ts new file mode 100644 index 0000000..2890e35 --- /dev/null +++ b/test/analyticsConsent.test.ts @@ -0,0 +1,19 @@ +import { describe, expect, test } from 'vitest' + +import { shouldLoadGoogle } from '../src/modules/analytics/Analytics.js' + +const none = { analytics: false, marketing: false } + +describe("Google tag and consent", () => { + test("'basic': no Google request before an analytics or marketing grant", () => { + expect(shouldLoadGoogle({ consentMode: 'basic', ready: true, state: none })).toBe(false) + expect(shouldLoadGoogle({ consentMode: 'basic', ready: true, state: { ...none, analytics: true } })).toBe(true) + expect(shouldLoadGoogle({ consentMode: 'basic', ready: true, state: { ...none, marketing: true } })).toBe(true) + }) + + test("'advanced' (default) loads with denied signals; `defer` still holds both back", () => { + expect(shouldLoadGoogle({ consentMode: 'advanced', ready: true, state: none })).toBe(true) + expect(shouldLoadGoogle({ consentMode: 'advanced', ready: false, state: none })).toBe(false) + expect(shouldLoadGoogle({ consentMode: 'basic', ready: false, state: { analytics: true } })).toBe(false) + }) +}) From 7c05a1dba91cd0e086008ca6b969974dc7971182 Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?Rados=C5=82aw=20Smoli=C5=84ski?= Date: Thu, 22 Oct 2026 17:07:45 +0200 Subject: [PATCH 07/27] Construction mode hides pages from Markdown, MCP and search; MCP rejects non-object messages createContentHelpers exposes isPathVisible (built from getConstructionMode) and passes it to markdownRoute and mcpPOST; createSearchRoute, createMcpRoute and createMarkdownRoute accept it. A null/number/string JSON-RPC message now gets -32600 instead of crashing the route. Co-Authored-By: Claude Opus 5.5 --- docs/construction.md | 4 +++ docs/content.md | 3 +- docs/mcp.md | 3 +- src/modules/construction/visibility.ts | 10 +++++++ src/modules/content/createMarkdownRenderer.ts | 14 +++++++-- src/modules/content/createSearchRoute.ts | 10 +++++-- src/modules/forms/submitForm.ts | 2 +- src/modules/frontend/createContentHelpers.ts | 16 ++++++++-- src/modules/mcp/createMcpRoute.ts | 29 ++++++++++++++++--- test/construction.test.ts | 28 ++++++++++++++++++ test/mcp.test.ts | 10 +++++++ 11 files changed, 116 insertions(+), 13 deletions(-) create mode 100644 src/modules/construction/visibility.ts diff --git a/docs/construction.md b/docs/construction.md index cdc8262..6f4344b 100644 --- a/docs/construction.md +++ b/docs/construction.md @@ -25,6 +25,10 @@ normalne działanie strony. `next/link`) i pokazuje popup. Linki zewnętrzne, kotwice na tej samej stronie, `target="_blank"` i kliknięcia z modyfikatorem (Ctrl/⌘) działają normalnie. - Po przekierowaniu popup otwiera się raz, a parametr znika z paska adresu. +- **Markdown i MCP** z `createContentHelpers` (`markdownRoute`, `mcpPOST`) ukrywają te same strony: + `/md/…` → 404, `list_pages` / `search_content` ich nie pokazują, `get_page` → „No page found”. + Własny `createSearchRoute` / `createMcpRoute` / `createMarkdownRoute` → przekaż + `isPathVisible` z `lib/content` (`createSearchRoute({ …, isPathVisible })`). - **Jedna reguła dla wszystkich odwiedzających** — strony zostają statyczne (ISR), bez sprawdzania sesji. Po zmianie ustawień strony odświeżają się po rewalidacji (jak inne zmiany w Site Settings). diff --git a/docs/content.md b/docs/content.md index 721e8c1..563f53c 100644 --- a/docs/content.md +++ b/docs/content.md @@ -330,7 +330,8 @@ Query: `?q=` (wymagane), `?locale=`, `?limit=`. Odpowiedź: "results": [{ "title": "O nas", "url": "https://x/pl/o-nas", "description": "…", "slug": "o-nas" }] } ``` -Brak `q` → 400. Tylko opublikowane, bez `noindex`, maks. 50 wyników. Błąd/baza +Brak `q` → 400. Tylko opublikowane, bez `noindex`, maks. 50 wyników. Tryb „w budowie”: +przekaż `isPathVisible` z `createContentHelpers`, a ukryte strony znikną z wyników. Błąd/baza offline → pusty wynik (200), nie 500. **Limit zapytań:** 120/min na IP (w pamięci, per instancja) → `429` z `Retry-After`; zmiana: `rateLimit: { max, windowMs }`, wyłączenie (limiter z przodu, np. Cloudflare WAF): `rateLimit: false`. diff --git a/docs/mcp.md b/docs/mcp.md index 8a0f30c..9f5416d 100644 --- a/docs/mcp.md +++ b/docs/mcp.md @@ -85,6 +85,7 @@ wykona `initialize` → `tools/list` → i będzie mógł wołać `get_site_info Pojedynczy obiekt JSON-RPC albo batch (tablica). Notyfikacje (`notifications/*`, bez `id`) → HTTP 202 bez ciała. Żądania → `{ jsonrpc:'2.0', id, result }` albo -`error` (`-32601` nieznana metoda, `-32700` parse error, `-32600` batch za duży, +`error` (`-32601` nieznana metoda, `-32700` parse error, `-32600` batch za duży albo wiadomość, +która nie jest obiektem — `null`, liczba, tekst; `-32000` limit zapytań). `initialize` odbija `protocolVersion` klienta (fallback `2025-06-18`). diff --git a/src/modules/construction/visibility.ts b/src/modules/construction/visibility.ts new file mode 100644 index 0000000..cdad4aa --- /dev/null +++ b/src/modules/construction/visibility.ts @@ -0,0 +1,10 @@ +/** + * Is this public page path served right now? createContentHelpers builds it from + * Site Settings → Under construction (`isPathVisible`), so the Markdown, MCP and + * search routes hide exactly what the page route hides. Paths are page paths as + * a visitor sees them ('/pl/o-nas', or '/o-nas' on a single-language site). + */ +export type PathVisibility = (path: string, locale: string) => boolean | Promise + +/** Pathname of a result URL (absolute or relative), for a PathVisibility check. */ +export const pathOf = (url: string): string => new URL(url, 'http://localhost').pathname diff --git a/src/modules/content/createMarkdownRenderer.ts b/src/modules/content/createMarkdownRenderer.ts index 191e0ae..5952715 100644 --- a/src/modules/content/createMarkdownRenderer.ts +++ b/src/modules/content/createMarkdownRenderer.ts @@ -1,5 +1,6 @@ import type { BasePayload } from 'payload' +import type { PathVisibility } from '../construction/visibility.js' import type { ContentOption } from './types.js' import { blocksToMarkdown } from './blocksToMarkdown.js' @@ -187,14 +188,23 @@ function routeOf( * (details only in the server log). */ export function createMarkdownRoute( - args: { getCachedPayload: () => Promise } & CreateMarkdownRendererArgs, + args: { + getCachedPayload: () => Promise + /** Hide pages the site hides (construction mode) — 404 like an unknown page. */ + isPathVisible?: PathVisibility + } & CreateMarkdownRendererArgs, ): { GET: (req: Request, ctx: MarkdownRouteContext) => Promise } { - const { getCachedPayload, ...rendererArgs } = args + const { getCachedPayload, isPathVisible, ...rendererArgs } = args const render = createMarkdownRenderer(rendererArgs) return { GET: async (_req, { params }) => { try { const { slug, locale } = routeOf(await params, rendererArgs.config) + if (isPathVisible) { + const multilingual = (rendererArgs.config?.locales.length ?? 0) > 1 + const path = `/${[...(multilingual ? [locale] : []), ...(slug ?? [])].join('/')}` + if (!(await isPathVisible(path, locale))) {return markdownResponse(null, {})} + } const md = await render({ slug, locale, payload: await getCachedPayload() }) return markdownResponse(md, { canonical: canonicalOf(rendererArgs.baseUrl, rendererArgs.config, locale, slug) }) } catch (err) { diff --git a/src/modules/content/createSearchRoute.ts b/src/modules/content/createSearchRoute.ts index 3daf5c5..251a504 100644 --- a/src/modules/content/createSearchRoute.ts +++ b/src/modules/content/createSearchRoute.ts @@ -3,6 +3,7 @@ import type { BasePayload } from 'payload' import type { I18nConfig } from '../i18n/index.js' import type { ClientIpOptions } from '../shared/rateLimit.js' +import { type PathVisibility, pathOf } from '../construction/visibility.js' import { clientIp, consumeRateLimit, tooManyRequests } from '../shared/rateLimit.js' import { searchContent } from './searchContent.js' @@ -26,6 +27,8 @@ type CreateSearchRouteArgs = { rateLimit?: { max?: number; windowMs?: number } | false /** Field holding a richer AI summary (buildSummaryField) to prefer as description. */ summaryField?: string + /** Hide pages the site hides (construction mode) — pass `isPathVisible` from createContentHelpers. */ + isPathVisible?: PathVisibility } /** @@ -47,7 +50,7 @@ type CreateSearchRouteArgs = { * Uses the global Request/Response — no next/server import. */ export function createSearchRoute(args: CreateSearchRouteArgs): (req: Request) => Promise { - const { baseUrl, collection = 'pages', config, defaultLimit = 10, getCachedPayload, homeSlug, summaryField } = args + const { baseUrl, collection = 'pages', config, defaultLimit = 10, getCachedPayload, homeSlug, isPathVisible, summaryField } = args // 120/min: a debounced search-as-you-type box stays well under it; a scraper doesn't. const rl = args.rateLimit === false ? null : { max: 120, windowMs: 60_000, ...args.rateLimit } @@ -73,7 +76,7 @@ export function createSearchRoute(args: CreateSearchRouteArgs): (req: Request) = try { const payload = await getCachedPayload() - const results = await searchContent({ + const found = await searchContent({ baseUrl, collection, config, @@ -84,6 +87,9 @@ export function createSearchRoute(args: CreateSearchRouteArgs): (req: Request) = query, summaryField, }) + const shownLocale = locale ?? config.defaultLocale + const keep = isPathVisible ? await Promise.all(found.map((r) => isPathVisible(pathOf(r.url), shownLocale))) : null + const results = keep ? found.filter((_, i) => keep[i]) : found return Response.json( { count: results.length, locale: locale ?? config.defaultLocale, query, results }, { headers: { 'cache-control': 'public, max-age=0, s-maxage=60, stale-while-revalidate=600' } }, diff --git a/src/modules/forms/submitForm.ts b/src/modules/forms/submitForm.ts index 539e74d..8e360b3 100644 --- a/src/modules/forms/submitForm.ts +++ b/src/modules/forms/submitForm.ts @@ -110,7 +110,7 @@ export async function submitForm({ // 1. Rate limit — cheapest gate, drops a flood before any real work. // No IP → the limiter's shared "unknown" bucket, never a free pass. if (maxPerMinute > 0) { - if (!(await consumeRateLimit({ key: ip, max: maxPerMinute })).ok) { + if (!(await consumeRateLimit({ key: ip ?? '', max: maxPerMinute })).ok) { return { reason: 'rate_limited', success: false } } } diff --git a/src/modules/frontend/createContentHelpers.ts b/src/modules/frontend/createContentHelpers.ts index 2a8ec21..1f730e4 100644 --- a/src/modules/frontend/createContentHelpers.ts +++ b/src/modules/frontend/createContentHelpers.ts @@ -6,6 +6,7 @@ import { cache } from 'react' import type { AnalyticsConfig } from '../analytics/types.js' import type { ConsentTexts } from '../consent/texts.js' import type { ConstructionMode } from '../construction/types.js' +import type { PathVisibility } from '../construction/visibility.js' import type { ArchiveEntries, ContentOption, ResolvedRoute } from '../content/index.js' import type { I18nConfig } from '../i18n/index.js' import type { LinkValue, NavItem, ResolvedLink, ResolveLinkHrefOptions, SystemLink } from '../links/index.js' @@ -15,6 +16,7 @@ import type { PageMetadata, RobotsOptions, RobotsRules, SitemapEntry, SitemapSty import { getAnalyticsConfig } from '../analytics/getAnalyticsConfig.js' import { getConsentTexts } from '../consent/getConsentTexts.js' +import { isPathAllowed } from '../construction/logic.js' import { createMarkdownRoute } from '../content/createMarkdownRenderer.js' import { getArchiveEntries, resolveRoute as resolveRouteRaw } from '../content/index.js' import { MARKDOWN_PREFIX, markdownHref } from '../content/markdownNegotiation.js' @@ -685,6 +687,15 @@ export function createContentHelpers({ } }) + /** + * Is this page path public right now? False for pages construction mode + * hides. The Markdown and MCP routes use it; pass it to createSearchRoute. + */ + const isPathVisible: PathVisibility = async (path, locale) => { + const construction = await getConstructionMode(locale) + return !construction.enabled || isPathAllowed(path, construction.allowedPaths) + } + // ── Layout ──────────────────────────────────────────────────────────────── /** Notifications → form texts in this locale (BuilderForm / RenderForm `texts`). */ const getFormTexts = cache(async (locale: string): Promise => @@ -737,8 +748,8 @@ export function createContentHelpers({ } const llms = lazy(() => createLlmsTxtRoute({ baseUrl: origin, config: needI18n('llmsRoute'), content, getCachedPayload, pagesSlug, settingsSlug, summaryField })) const llmsFull = lazy(() => createLlmsTxtRoute({ baseUrl: origin, config: needI18n('llmsFullRoute'), content, full: true, getCachedPayload, pagesSlug, settingsSlug, summaryField })) - const md = lazy(() => createMarkdownRoute({ baseUrl: origin || undefined, collection: pagesSlug, config: i18n, content, getCachedPayload, settingsSlug, ...markdownOptions })) - const mcp = lazy(() => createMcpRoute({ baseUrl: origin, collection: pagesSlug, config: needI18n('mcpRoute'), content, getCachedPayload, settingsSlug, summaryField, ...mcpOptions })) + const md = lazy(() => createMarkdownRoute({ baseUrl: origin || undefined, collection: pagesSlug, config: i18n, content, getCachedPayload, isPathVisible, settingsSlug, ...markdownOptions })) + const mcp = lazy(() => createMcpRoute({ baseUrl: origin, collection: pagesSlug, config: needI18n('mcpRoute'), content, getCachedPayload, isPathVisible, settingsSlug, summaryField, ...mcpOptions })) const health = lazy(() => createHealthRoute({ collection: pagesSlug, getCachedPayload })) const indexNowKey = lazy(() => createIndexNowKeyRoute({ getCachedPayload })) const manifestHandler = lazy(() => createManifestHandler({ config: needI18n('manifest'), getCachedPayload, settingsSlug })) @@ -765,6 +776,7 @@ export function createContentHelpers({ getCachedPayload, getConfiguredLocales, getConstructionMode, + isPathVisible, getEntries, getFormTexts, getHomeSlug, diff --git a/src/modules/mcp/createMcpRoute.ts b/src/modules/mcp/createMcpRoute.ts index 5ab004b..0dd27a4 100644 --- a/src/modules/mcp/createMcpRoute.ts +++ b/src/modules/mcp/createMcpRoute.ts @@ -1,9 +1,11 @@ import type { BasePayload } from 'payload' +import type { PathVisibility } from '../construction/visibility.js' import type { ContentOption } from '../content/index.js' import type { I18nConfig } from '../i18n/index.js' import type { ClientIpOptions } from '../shared/rateLimit.js' +import { pathOf } from '../construction/visibility.js' import { createMarkdownRenderer, searchContent } from '../content/index.js' import { getDefaultLocale, isValidLocale } from '../i18n/index.js' import { readSiteMetaConfig } from '../seo/readSiteMetaConfig.js' @@ -72,6 +74,11 @@ export type CreateMcpRouteArgs = { settingsSlug?: string /** Field holding a richer AI summary (buildSummaryField) to prefer in search results. */ summaryField?: string + /** + * Hide pages the site hides (construction mode): filtered out of list_pages + * and search_content, "not found" in get_page. createContentHelpers passes it. + */ + isPathVisible?: PathVisibility } type JsonRpcId = null | number | string @@ -95,6 +102,7 @@ export function createMcpRoute(args: CreateMcpRouteArgs) { config, content, getCachedPayload, + isPathVisible, maxBatch = 10, serverName = 'ipal-site', serverVersion = '1.0.0', @@ -160,6 +168,13 @@ export function createMcpRoute(args: CreateMcpRouteArgs) { ? params.locale : getDefaultLocale(config) + /** Drops results whose page is hidden right now (construction mode). */ + async function visible(items: T[], locale: string): Promise { + if (!isPathVisible) {return items} + const keep = await Promise.all(items.map((item) => isPathVisible(pathOf(item.url), locale))) + return items.filter((_, i) => keep[i]) + } + const formatResults = (results: { description?: string; title: string; url: string }[]) => results.map((r) => `- ${r.title} (${r.url})${r.description ? ` — ${r.description}` : ''}`).join('\n') @@ -193,7 +208,7 @@ export function createMcpRoute(args: CreateMcpRouteArgs) { const limit = Math.min(Math.max(Math.trunc(typeof params.limit === 'number' ? params.limit : 50) || 50, 1), 200) const payload = await getCachedPayload() // Same index as llms.txt and the sitemap rules: pages AND archive entries (blog…). - const index = await collectSiteIndex({ + const index = await visible(await collectSiteIndex({ baseUrl: origin, config, content, @@ -202,7 +217,7 @@ export function createMcpRoute(args: CreateMcpRouteArgs) { payload, settingsSlug, summaryField, - }) + }), locale) if (index.length === 0) {return 'No published pages.'} const shown = index.slice(0, limit) const lines = shown.map( @@ -221,7 +236,7 @@ export function createMcpRoute(args: CreateMcpRouteArgs) { const payload = await getCachedPayload() const meta = await siteMeta(payload, locale) // Shared with the JSON search route — one ranking everywhere. - const results = await searchContent({ + const results = await visible(await searchContent({ baseUrl: origin, collection, config, @@ -231,7 +246,7 @@ export function createMcpRoute(args: CreateMcpRouteArgs) { payload, query, summaryField, - }) + }), locale) if (results.length === 0) {return `No pages matched "${query}".`} return formatResults(results) } @@ -246,12 +261,18 @@ export function createMcpRoute(args: CreateMcpRouteArgs) { locale = segments[0] slug = segments.slice(1) } + if (isPathVisible) { + const path = `/${[...(config.locales.length > 1 ? [locale] : []), ...slug].join('/')}` + if (!(await isPathVisible(path, locale))) {return `No page found at ${raw}.`} + } const payload = await getCachedPayload() const md = await renderMarkdown({ slug, locale, payload }) return md ?? `No page found at ${raw}.` } async function handleOne(msg: JsonRpcRequest): Promise { + // `null`, a number, a string… is not a JSON-RPC request — answer, don't crash. + if (!msg || typeof msg !== 'object' || Array.isArray(msg)) {return rpcError(null, -32600, 'Invalid Request')} const { id = null, method, params } = msg // Notifications (no id) get no response body. diff --git a/test/construction.test.ts b/test/construction.test.ts index 8fd19ba..7a23f1a 100644 --- a/test/construction.test.ts +++ b/test/construction.test.ts @@ -87,4 +87,32 @@ describe('under construction — Site Settings → createPageRoute', () => { await expect(open('pl', ['o-nas'])).rejects.toThrow('REDIRECT /pl?notice=construction') await expect(open('pl', ['nie-ma'])).rejects.toThrow('REDIRECT /pl?notice=construction') }) + + test('on: Markdown, MCP and search hide the same pages the page route hides', async () => { + const helpers = createContentHelpers({ baseUrl: 'https://acme.pl', config: configPromise, i18n }) + expect((await helpers.getConstructionMode('pl')).enabled).toBe(true) + + const md = (slug: string[]) => helpers.markdownRoute(new Request('https://acme.pl/md'), { params: Promise.resolve({ locale: 'pl', slug }) }) + expect((await md(['o-nas'])).status).toBe(404) + expect((await md(['brief'])).status).toBe(200) + + const rpc = async (name: string, args: Record) => { + const res = await helpers.mcpPOST( + new Request('https://acme.pl/api/mcp', { + body: JSON.stringify({ id: 1, jsonrpc: '2.0', method: 'tools/call', params: { arguments: args, name } }), + headers: { 'content-type': 'application/json', 'x-real-ip': '198.51.100.4' }, + method: 'POST', + }), + ) + return ((await res.json()) as { result: { content: { text: string }[] } }).result.content[0].text + } + const list = await rpc('list_pages', { locale: 'pl' }) + expect(list).toContain('/pl/brief') + expect(list).not.toContain('/pl/o-nas') + expect(await rpc('get_page', { path: '/pl/o-nas' })).toMatch(/No page found/) + expect(await rpc('search_content', { locale: 'pl', query: 'nas' })).not.toContain('/pl/o-nas') + + expect(await helpers.isPathVisible('/pl/o-nas', 'pl')).toBe(false) + expect(await helpers.isPathVisible('/pl/brief', 'pl')).toBe(true) + }) }) diff --git a/test/mcp.test.ts b/test/mcp.test.ts index e5e04e1..00d3356 100644 --- a/test/mcp.test.ts +++ b/test/mcp.test.ts @@ -104,6 +104,16 @@ describe('createMcpRoute', () => { expect((await mcp.GET()).status).toBe(405) }) + test('a null, number or string message gets Invalid Request, not a 500', async () => { + for (const body of [null, 42, 'x']) { + const res = await rpc(body) + expect(res.status).toBe(200) + expect(res.body.error.code).toBe(-32600) + } + const batch = await rpc([null, { id: 2, jsonrpc: '2.0', method: 'ping' }]) + expect(batch.body.map((m: { error?: { code: number } }) => m.error?.code ?? 'ok')).toEqual([-32600, 'ok']) + }) + test('rate limit counts every message in a batch', async () => { const ip = '10.9.9.9' const batch = Array.from({ length: 10 }, (_, i) => ({ id: i, jsonrpc: '2.0', method: 'ping' })) From 7967453f574cbded076797837b4de171ad7eea0d Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?Rados=C5=82aw=20Smoli=C5=84ski?= Date: Thu, 22 Oct 2026 17:09:00 +0200 Subject: [PATCH 08/27] Revalidate the site layout when a global is saved buildGlobalRevalidateHook + ipalKit({ revalidatePath }) wires it into the plugin's globals; menus, consent texts and analytics IDs no longer stay stale for the whole ISR window. Co-Authored-By: Claude Opus 5.5 --- docs/hooks.md | 18 +++++++++++++ src/index.ts | 2 +- src/modules/hooks/buildRevalidateHook.ts | 24 ++++++++++++++++- src/modules/hooks/index.ts | 3 ++- src/plugin.ts | 12 +++++++-- src/types.ts | 10 +++++++ test/revalidateGlobals.test.ts | 34 ++++++++++++++++++++++++ 7 files changed, 98 insertions(+), 5 deletions(-) create mode 100644 test/revalidateGlobals.test.ts diff --git a/docs/hooks.md b/docs/hooks.md index 9bae9d7..de1965c 100644 --- a/docs/hooks.md +++ b/docs/hooks.md @@ -42,6 +42,24 @@ brak `process.env.NEXT_RUNTIME`. Wcześniej Next rzucał `Invariant: static gene i seed padał. Celowe pominięcie (masowy import w aplikacji): `context: { disableRevalidate: true }` w wywołaniu Local API. +### Globale — buildGlobalRevalidateHook / `ipalKit({ revalidatePath })` + +Global (Site Settings, Cookie Settings, menu projektu) zasila layout **każdej** strony — logo, menu, +teksty zgody, ID analityki. Bez rewalidacji strony ISR trzymały stare wartości do końca okna +`revalidate`. Zapis globala → `revalidatePath('/', 'layout')` (cała strona). + +```ts +// payload.config.ts — globale pluginu (Site Settings, Site Integrations, Cookie Settings, Notifications) +import { revalidatePath } from 'next/cache' +ipalKit({ …, revalidatePath }) + +// własny global projektu (np. menu) +import { buildGlobalRevalidateHook } from '@intecion/ipal-kit' +hooks: { afterChange: [buildGlobalRevalidateHook({ revalidatePath })] } +``` + +Te same reguły co wyżej: bez `NEXT_RUNTIME` i z `context: { disableRevalidate: true }` nic nie robi. + --- ## setPublishedAtHook — auto-data publikacji diff --git a/src/index.ts b/src/index.ts index d905d80..b801ebf 100644 --- a/src/index.ts +++ b/src/index.ts @@ -112,7 +112,7 @@ export type { ContentHelpers, EntryJsonLdContext, PageJsonLdOptions, SiteShell } export { createContentHelpers } from './modules/frontend/index.js' // Healthcheck route (Coolify/Docker liveness with a real DB round-trip). export { createHealthRoute } from './modules/health/index.js' -export { buildCrossLocaleFieldSync, buildPreventDeleteSystemPage, buildRevalidateHook, buildValidateUniqueRole, setPublishedAtHook, trackSlugHistoryHook } from './modules/hooks/index.js' +export { buildCrossLocaleFieldSync, buildGlobalRevalidateHook, buildPreventDeleteSystemPage, buildRevalidateHook, buildValidateUniqueRole, setPublishedAtHook, trackSlugHistoryHook } from './modules/hooks/index.js' export type { I18nConfig, LocaleDefinition, LocalizedSlugs } from './modules/i18n/index.js' export { buildLocalizedPath, diff --git a/src/modules/hooks/buildRevalidateHook.ts b/src/modules/hooks/buildRevalidateHook.ts index 1a51f09..f3cad40 100644 --- a/src/modules/hooks/buildRevalidateHook.ts +++ b/src/modules/hooks/buildRevalidateHook.ts @@ -1,10 +1,12 @@ -import type { CollectionAfterChangeHook, CollectionAfterDeleteHook } from 'payload' +import type { CollectionAfterChangeHook, CollectionAfterDeleteHook, GlobalAfterChangeHook } from 'payload' import type { I18nConfig } from '../i18n/index.js' import { buildLocalizedPath, getLocaleCodes } from '../i18n/index.js' type RevalidateFn = (path: string) => void +/** next/cache revalidatePath — the `type` argument is used for 'layout'. */ +export type RevalidatePathFn = (path: string, type?: 'layout' | 'page') => void type BuildRevalidateHookArgs = { config: I18nConfig @@ -114,3 +116,23 @@ export function buildRevalidateHook({ return { afterChange, afterDelete } } + +/** + * afterChange for a GLOBAL (Site Settings, Cookie Settings, a menu…): a global + * feeds the layout of every page — logo, menu, consent texts, analytics IDs — + * so a save revalidates the whole site (`revalidatePath('/', 'layout')`). + * Without it, every ISR page kept the old values until its revalidate window + * ran out. Same rules as buildRevalidateHook: injected revalidatePath, no-op + * outside a Next server or with `context: { disableRevalidate: true }`. + * + * import { revalidatePath } from 'next/cache' + * hooks: { afterChange: [buildGlobalRevalidateHook({ revalidatePath })] } + * + * ipalKit({ revalidatePath }) attaches it to the plugin's own globals. + */ +export function buildGlobalRevalidateHook({ revalidatePath }: { revalidatePath: RevalidatePathFn }): GlobalAfterChangeHook { + return ({ context, doc }) => { + if (shouldRevalidate(context)) {revalidatePath('/', 'layout')} + return doc + } +} diff --git a/src/modules/hooks/index.ts b/src/modules/hooks/index.ts index 0766415..73e6e6f 100644 --- a/src/modules/hooks/index.ts +++ b/src/modules/hooks/index.ts @@ -3,7 +3,8 @@ export { normalizeFilenameHook } from '../media/index.js' export { buildAutoFillMetaHook, validateFaviconField } from '../seo/index.js' export { buildCrossLocaleFieldSync } from './buildCrossLocaleFieldSync.js' -export { buildRevalidateHook } from './buildRevalidateHook.js' +export { buildGlobalRevalidateHook, buildRevalidateHook } from './buildRevalidateHook.js' +export type { RevalidatePathFn } from './buildRevalidateHook.js' export { buildPreventDeleteSystemPage } from './preventDeleteSystemPage.js' export { setPublishedAtHook } from './setPublishedAt.js' diff --git a/src/plugin.ts b/src/plugin.ts index e0124a2..2aaea8f 100644 --- a/src/plugin.ts +++ b/src/plugin.ts @@ -17,6 +17,7 @@ import { buildFormsPlugin } from './modules/forms/formsPluginConfig.js' import { buildLocalizationConfig, validateI18nConfig } from './modules/i18n/index.js' import { buildSystemPagesFields } from './modules/pages/index.js' import { buildSeoPlugin, injectAutoFillMeta, injectSeoTabs } from './modules/seo/index.js' +import { buildGlobalRevalidateHook } from './modules/hooks/buildRevalidateHook.js' import { buildIndexNowHook } from './modules/seo/indexNow.js' import { buildStatsCollection, buildStatsEndpoint } from './modules/stats/index.js' @@ -229,8 +230,7 @@ export const ipalKit = (options: IpalOptions): Plugin => { : []), ] - config.globals = [ - ...(config.globals ?? []), + const pluginGlobals = [ buildSiteSettings({ additionalFields: options.siteSettingsFields, ...(options.pages ? { constructionFields: buildConstructionFields(options.pages.slug) } : {}), @@ -241,6 +241,14 @@ export const ipalKit = (options: IpalOptions): Plugin => { buildCookieSettings(), buildNotifications(), ] + // A global feeds every page's layout — revalidate the site on save. + const revalidateGlobal = options.revalidatePath ? buildGlobalRevalidateHook({ revalidatePath: options.revalidatePath }) : null + config.globals = [ + ...(config.globals ?? []), + ...(revalidateGlobal + ? pluginGlobals.map((g) => ({ ...g, hooks: { ...g.hooks, afterChange: [...(g.hooks?.afterChange ?? []), revalidateGlobal] } })) + : pluginGlobals), + ] config.endpoints = [...(config.endpoints ?? []), testEmailEndpoint] diff --git a/src/types.ts b/src/types.ts index b6ffb61..fe646dd 100644 --- a/src/types.ts +++ b/src/types.ts @@ -12,6 +12,7 @@ export type TotpPluginFactory = (options: { forceSetup: boolean totp: { issuer: string } }) => Plugin +import type { RevalidatePathFn } from './modules/hooks/buildRevalidateHook.js' import type { AccessOption } from './modules/access/types.js' import type { ContentOption } from './modules/content/types.js' import type { FormsOption } from './modules/forms/types.js' @@ -88,6 +89,15 @@ export type IpalOptions = { */ pages?: PagesOption + /** + * next/cache `revalidatePath`, INJECTED (the plugin never imports next/cache). + * When given, saving any of the plugin's globals (Site Settings, Site + * Integrations, Cookie Settings, Notifications) revalidates the whole site + * layout, so logo, menu, consent texts and analytics IDs change at once + * instead of after the ISR window. See buildGlobalRevalidateHook. + */ + revalidatePath?: RevalidatePathFn + /** * SEO — adds meta fields to chosen collections (via @payloadcms/plugin-seo) * and enables locale-aware metadata helpers. diff --git a/test/revalidateGlobals.test.ts b/test/revalidateGlobals.test.ts new file mode 100644 index 0000000..f1ff0d9 --- /dev/null +++ b/test/revalidateGlobals.test.ts @@ -0,0 +1,34 @@ +import type { Config, GlobalConfig } from 'payload' + +import { afterEach, describe, expect, test, vi } from 'vitest' + +import { buildGlobalRevalidateHook } from '../src/modules/hooks/buildRevalidateHook.js' +import { ipalKit } from '../src/plugin.js' + +const i18n = { defaultLocale: 'pl', locales: [{ code: 'pl', label: 'Polski' }] } +const run = (g: GlobalConfig | undefined, context: object = {}) => + g?.hooks?.afterChange?.forEach((h) => h({ context, doc: {}, global: g, previousDoc: {}, req: {} } as never)) + +describe('globals revalidate the site layout on save', () => { + afterEach(() => vi.unstubAllEnvs()) + + test('ipalKit({ revalidatePath }) wires every plugin global', async () => { + vi.stubEnv('NEXT_RUNTIME', 'nodejs') + const revalidatePath = vi.fn() + const config = await ipalKit({ i18n, revalidatePath, twoFactor: false })({ collections: [], secret: 'x' } as unknown as Config) + for (const slug of ['site-settings', 'site-integrations', 'cookie-settings', 'notifications']) { + revalidatePath.mockClear() + run(config.globals?.find((g) => g.slug === slug)) + expect(revalidatePath, slug).toHaveBeenCalledWith('/', 'layout') + } + }) + + test('outside a Next server, or with disableRevalidate, nothing happens', () => { + const revalidatePath = vi.fn() + const hook = buildGlobalRevalidateHook({ revalidatePath }) + hook({ context: {}, doc: {} } as never) + vi.stubEnv('NEXT_RUNTIME', 'nodejs') + hook({ context: { disableRevalidate: true }, doc: {} } as never) + expect(revalidatePath).not.toHaveBeenCalled() + }) +}) From 94e563055f34fd9b34b9ac7a0ec005ceb042a2d3 Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?Rados=C5=82aw=20Smoli=C5=84ski?= Date: Thu, 22 Oct 2026 17:09:01 +0200 Subject: [PATCH 09/27] SEO/GEO/GSC: sitemap index + caching, Search & AI settings, getRobots MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit - Sitemap: batched reads (500), published-only where, field select; sitemap index over maxUrls (default 10k) with ?part=N; Cache-Control; in-process memo; runtime errors → 503 Retry-After (empty urlset only during next build) - Site Settings → Search & AI tab (seo.searchSettings: false removes it): Google/Bing/Yandex verification (paste code or whole meta tag) added to page metadata; AI crawler policy + per-bot exceptions; llms.txt note - buildRobots aiBotRules; getRobots helper reads the panel; more AI agents - Under construction: sitemap and llms.txt list only open pages - collectSiteIndex: no silent 1000 cap; llms routes send Cache-Control - IndexNow: nothing sent with IPAL_NOINDEX - Unknown route metadata is noindex - Tests (unit + SQLite integration) and docs/seo.md Co-Authored-By: Claude Opus 5.5 --- docs/seo.md | 146 ++++++++- src/globals/SiteSettings/index.ts | 4 + src/index.ts | 5 +- src/modules/frontend/createContentHelpers.ts | 79 ++++- src/modules/mcp/createMcpRoute.ts | 1 + src/modules/seo/buildLlmsTxt.ts | 12 +- src/modules/seo/buildMetadata.ts | 7 + src/modules/seo/buildRobots.ts | 48 ++- src/modules/seo/buildSitemapEntries.ts | 69 +++- src/modules/seo/buildSitemapXml.ts | 48 ++- src/modules/seo/createPageMetadata.ts | 4 +- src/modules/seo/index.ts | 7 +- src/modules/seo/indexNow.ts | 8 +- src/modules/seo/readSiteMetaConfig.ts | 7 + src/modules/seo/routeHandlers.ts | 115 ++++++- src/modules/seo/searchSettings.ts | 170 ++++++++++ src/modules/seo/siteIndex.ts | 42 ++- src/modules/seo/sitemapStyle.ts | 10 +- src/modules/seo/types.ts | 6 + src/plugin.ts | 2 + test/indexNow.test.ts | 6 + test/seoIntegration.test.ts | 104 +++++++ test/seoSearch.test.ts | 311 +++++++++++++++++++ 23 files changed, 1144 insertions(+), 67 deletions(-) create mode 100644 src/modules/seo/searchSettings.ts create mode 100644 test/seoIntegration.test.ts create mode 100644 test/seoSearch.test.ts diff --git a/docs/seo.md b/docs/seo.md index e455d59..d588502 100644 --- a/docs/seo.md +++ b/docs/seo.md @@ -306,7 +306,16 @@ Co zawiera sitemapa: - `lastModified` z realnego `updatedAt` dokumentu - wpisy bloga z prefiksem archiwum (`/pl/artykuly/moj-post`) -Pomija: drafty (`_status !== 'published'`) i dokumenty z `meta.noindex`. +Pomija: drafty (`_status !== 'published'`) i dokumenty z `meta.noindex`. Gdy +**Site Settings → Under construction** jest włączone — wszystko poza stronami, które +zostają otwarte (strona główna + „Pages still available”), bo reszta przekierowuje na +komunikat i crawler zaindeksowałby go zamiast treści. To samo robi `llms.txt`. + +Duże kolekcje (1.13): dokumenty czytane partiami po 500 (`SITEMAP_BATCH_SIZE`), tylko +opublikowane (`where _status` przy kolekcji z draftami) i tylko potrzebne pola +(`select`: slug, updatedAt, noindex, meta). Własne `sitemapImages` może czytać dowolne +pole, więc wtedy czytany jest cały dokument (`buildSitemapEntries({ select: true })` +wymusza select). Niskopoziomowo (własna trasa zamiast handlera z fabryki): @@ -318,8 +327,35 @@ const entries = await buildSitemapEntries({ }) ``` -Przy dziesiątkach tysięcy URL-i Next ma `generateSitemaps` do dzielenia na -części — dodasz, gdyby realnie było ich tyle. Jedna sitemapa wystarcza do ~50k. +### Duży serwis — sitemap index, cache, błędy (1.13) + +`sitemapRoute` (`createSitemapRouteHandler`) dzieli sitemapę sam, gdy URL-i jest więcej +niż `maxUrls` (domyślnie 10 000 — protokół pozwala 50 000 / 50 MB, ale hreflang robi +z każdego URL-a kilka linii): + +- `/sitemap.xml` → `` z częściami `/sitemap.xml?part=1`, `?part=2`…; + każda część ma `lastmod` = najnowszy `lastmod` jej URL-i. +- robots.txt i Search Console zostają przy jednym adresie `/sitemap.xml`. +- Nieistniejąca część → 404. + +| Opcja | Domyślnie | Co robi | +|---|---|---| +| `maxUrls` | `10000` | URL-i w jednym pliku; powyżej — index + części | +| `cacheControl` | `public, max-age=0, s-maxage=3600, stale-while-revalidate=86400` | CDN trzyma godzinę, przeglądarka sprawdza za każdym razem; `false` = bez nagłówka | +| `memoSeconds` | `300` | ile sekund proces trzyma zbudowaną listę (index i części nie budują jej od nowa); `0` = wyłączone | + +```ts +createSitemapRouteHandler(sitemap, { maxUrls: 5000, memoSeconds: 0 }) +``` + +Błąd bazy w runtime → **503 + `Retry-After: 300`** (crawler wróci), nie pusta sitemapa +z 200 („strona nie ma podstron”). Pusta odpowiedź i błąd nigdy nie idą z cache. +Wyjątek: `next build` (`NEXT_PHASE=phase-production-build`) dalej dostaje pustą, +poprawną sitemapę, żeby build bez bazy nie padł. `sitemap()` z `createContentHelpers` +też rzuca błąd w runtime (wcześniej zwracał `[]`). + +`app/sitemap.ts` (MetadataRoute) nie dzieli — przy dużym serwisie użyj `sitemapRoute`. +Własna trasa: `buildSitemapIndexXml([{ url, lastModified }], { cssUrl })` składa sam index. ## Favicon w Google + Organization (branding w wyszukiwarce) @@ -557,7 +593,7 @@ export const revalidate = 3600 // cache 1h, regeneracja w tle > pokaże zmian redaktora od razu (czeka do rewalidacji). Dla treści zmienianej > rzadko OK. Jeśli redaktor ma widzieć zmiany natychmiast — użyj **on-demand > revalidation**: hook `afterChange` w kolekcji → `revalidatePath(path)` (patrz -> HOOKS.md). Albo krótszy `revalidate` (np. 300 = 5 min). NIE łącz ISR z +> [hooks.md](./hooks.md)). Albo krótszy `revalidate` (np. 300 = 5 min). NIE łącz ISR z > `force-dynamic` — wykluczają się. ### Rozwiązanie DRUGIE — usuń jawny z layoutu @@ -1036,6 +1072,15 @@ Wymaga wypełnionego siteDescription i sensownych meta.description stron (inaczej llms.txt będzie ubogi) — albo pola `aiSummary` (niżej), bogatszego niż meta description. +Od 1.13: +- pod opisem trafia notka redaktora z **Site Settings → Search & AI → About the site for + AI assistants** (fakty do cytowania, per język) — sekcja „Search & AI” niżej; +- lista nie jest już ucinana na 1000 dokumentów (czytanie partiami; `collectSiteIndex({ limit })` + dalej przycina, jeśli chcesz); +- `llmsRoute` / `llmsFullRoute` z `createContentHelpers` przy włączonym „Under construction” + pokazują tylko otwarte strony (`createLlmsTxtRoute({ getIncludedPaths })` niskopoziomowo); +- odpowiedź ma `Cache-Control` jak sitemap (CDN godzinę), awaryjna — `no-store`. + ### buildSummaryField — streszczenie dla AI (bogatsze niż meta) Pole `aiSummary` (localized textarea) — zwięzły opis strony dla agentów, @@ -1111,7 +1156,41 @@ Tryby `aiBots`: Listy botów: `AI_ASSISTANT_BOTS`, `AI_TRAINING_BOTS` (eksportowane; nadpisujesz przez `aiAssistantAgents` / `aiTrainingAgents`). `Next` akceptuje `rules` jako -tablicę — przy aktywnych botach AI zwracana jest tablica reguł. +tablicę — przy aktywnych botach AI zwracana jest tablica reguł. 1.13 dopisało +asystentów `Claude-User`, `MistralAI-User`, `DuckAssistBot`. + +Wyjątki per bot — `aiBotRules` wygrywa z `aiBots`: bot z listy wychodzi ze swojej grupy +i dostaje własną regułę (można dopisać bota spoza list): + +```ts +buildRobots({ + baseUrl, + aiBots: 'block-training', + aiBotRules: [ + { userAgent: 'GPTBot', access: 'allow' }, // trening OpenAI jednak tak + { userAgent: 'Bytespider', access: 'disallow' }, + ], +}) +``` + +### Boty AI z panelu — getRobots (1.13) + +Redaktor ustawia politykę i wyjątki w **Site Settings → Search & AI → AI crawlers**. +Żeby robots.txt je czytał, zamień `robots` na `getRobots` (async, czyta Site Settings +per żądanie): + +```ts +// app/robots.ts +export { getRobots as default } from '@/lib/content' +export const dynamic = 'force-dynamic' +``` + +- Polityka „As set by the developer” (domyślna) = to, co w `createContentHelpers({ robots })`. +- Wyjątki z panelu dochodzą do `robots.aiBotRules` z kodu (panel na końcu, więc wygrywa). +- User agent z panelu: jeden token (`[\w\-.*/]`), bez spacji i nowych linii — wpis + „Bot\nDisallow: /” jest odrzucany, nie wstrzyknie reguły. +- Baza niedostępna → opcje z kodu. `IPAL_NOINDEX=1` dalej wygrywa ze wszystkim. +- `robots` (sync) zostaje bez zmian — ignoruje panel. ## Sitemap — czytelny w przeglądarce, zero plików w projekcie @@ -1154,6 +1233,60 @@ Dwa sitemapy pod różnymi ścieżkami mylą crawlery. Wybierz jeden: Oba tak samo dobre dla Google — to kwestia czytelności dla człowieka, nie SEO. +## Search & AI — weryfikacja Search Console, boty AI, notka llms.txt (1.13) + +Zakładka **Site Settings → Search & AI** (włączona domyślnie; puste pola nic nie +zmieniają; `ipalKit({ seo: { …, searchSettings: false } })` ją usuwa): + +| Pole | Gdzie trafia | +|---|---| +| `searchVerification.google` | `` na każdej stronie | +| `searchVerification.bing` | `` (Bing Webmaster — indeks Binga zasila ChatGPT Search i Copilot) | +| `searchVerification.yandex` | `` | +| `aiCrawlers.policy`, `aiCrawlers.rules` | robots.txt przez `getRobots` (wyżej) | +| `llmsIntro` (per język) | `/llms.txt` pod opisem strony | + +Weryfikacja: redaktor wkleja sam kod **albo cały tag** `` z Search +Console — zapisuje się tylko kod; coś, co nie jest prostym tokenem, jest odrzucane +(wartość ląduje w `` każdej strony). `generatePageMetadata` / `createPageMetadata` +dodają `verification` same — zero kodu w projekcie. Własny generator: +`verificationFrom(settings)` → `Metadata.verification`; robots: `robotsOptionsFrom(settings)`. + +Po wklejeniu kodu: Search Console → Zweryfikuj. Strona musi być zbudowana dynamicznie +albo po rewalidacji (ISR), żeby nowy tag był w HTML. Weryfikacja DNS dalej działa +niezależnie — pola zostaw puste. + +Migracja: nowe kolumny w `site_settings` — projekt na Postgresie generuje migrację +(`payload migrate:create`) jak przy każdej aktualizacji z nowymi polami. + +### Search Console API (dane w panelu) — nie wbudowane + +Kliknięcia/zapytania z Search Console w adminie wymagają konta usługi Google (JSON z +kluczem prywatnym) dodanego jako użytkownik w usłudze GSC, i biblioteki `googleapis` +albo podpisu JWT. Plugin tego (jeszcze) nie robi — dane czytasz w samej Search Console. + +## GEO — co plugin rozumie przez „widoczność w AI” (założenia) + +GEO (generative engine optimization) = strona jest **znaleziona, przeczytana i +zacytowana** przez asystentów AI (ChatGPT, Claude, Perplexity, Gemini, Copilot). Plugin +przyjmuje, że realnie działają cztery rzeczy — nie ma ukrytych „rankingów AI”: + +1. **Dostęp** — bot AI może pobrać stronę: robots.txt z jawnymi regułami (`aiBots`, + panel), brak blokady w CDN/WAF (tego plugin nie widzi — sprawdź Cloudflare + „Block AI bots”). Asystent (pobiera na żądanie użytkownika) ≠ crawler treningowy. +2. **Indeks, z którego asystent szuka** — Bing (ChatGPT Search, Copilot) → IndexNow + + weryfikacja Bing; Google (AI Overviews, Gemini) → sitemap + Search Console. +3. **Czytelna treść** — HTML renderowany na serwerze, Markdown (`/md/…`, `Link + rel=alternate`), `llms.txt` / `llms-full.txt` jako spis i pełna treść. `llms.txt` to + konwencja (llmstxt.org), nie standard — nic nie szkodzi, nie obiecuje ruchu. +4. **Sygnały do cytowania** — jednoznaczne fakty: Organization/LocalBusiness z `sameAs`, + `dateModified`/`datePublished` (Article, WebPage), okruszki, FAQ, `speakable`, + `aiSummary`, notka `llmsIntro` (kto, co, gdzie, od kiedy — zdania, które da się + zacytować bez kontekstu). + +Plugin NIE: generuje treści „pod AI”, ukrywa treści przed ludźmi, serwuje botom AI innej +wersji niż ludziom (cloaking) ani mierzy cytowań (brak publicznego API). + ## JsonLdGraph — opakowanie @graph (bez modelu firmy) Plugin dostarcza klocki Schema.org (buildWebSiteJsonLd, buildOrganizationJsonLd, @@ -1255,7 +1388,8 @@ Dopełnia Markdown/llms: asystent łatwiej wyciąga kluczową treść strony. obsługuje IndexNow — dla niego sitemap. Trasa klucza z `lib/content`: `export { indexNowKeyRoute as GET } from '@/lib/content'`. Ręcznie (np. import treści skryptem): `submitToIndexNow({ payload, urls })` (klucz: `getIndexNowKey(payload)`) - — nigdy nie rzuca, tylko loguje. + — nigdy nie rzuca, tylko loguje. Z `IPAL_NOINDEX=1` (staging) nic nie wysyła, nawet przy + `NODE_ENV=production` (1.13). - **llms.txt / llms-full.txt** obejmują wpisy kolekcji treści (`content`) i wszystkie języki; MCP `list_pages` też. Wspólne źródło: `collectSiteIndex`. diff --git a/src/globals/SiteSettings/index.ts b/src/globals/SiteSettings/index.ts index c373ce9..66b4e54 100644 --- a/src/globals/SiteSettings/index.ts +++ b/src/globals/SiteSettings/index.ts @@ -10,6 +10,8 @@ type BuildSiteSettingsArgs = { constructionFields?: Field[] /** "Emails" tab — given with `forms: { emailLayout: true }`. */ emailFields?: Field[] + /** "Search & AI" tab — search-engine verification, AI crawlers, llms.txt note (seo module). */ + searchFields?: Field[] /** * Fields for the "System Pages" tab — page assignments by role (homepage, * privacy policy, collection archives). Assembled by the caller, which is the @@ -36,6 +38,7 @@ export function buildSiteSettings({ additionalFields, constructionFields, emailFields, + searchFields, systemPageFields, }: BuildSiteSettingsArgs = {}): GlobalConfig { return { @@ -61,6 +64,7 @@ export function buildSiteSettings({ ...(systemPageFields?.length ? [{ fields: systemPageFields, label: 'System Pages' }] : []), + ...(searchFields?.length ? [{ fields: searchFields, label: 'Search & AI' }] : []), ...(emailFields?.length ? [{ fields: emailFields, label: 'Emails' }] : []), ...(constructionFields?.length ? [{ fields: constructionFields, label: 'Under construction' }] : []), ...(additionalFields?.length ? [{ fields: additionalFields, label: 'Custom' }] : []), diff --git a/src/index.ts b/src/index.ts index d905d80..a867b7f 100644 --- a/src/index.ts +++ b/src/index.ts @@ -222,7 +222,10 @@ export { buildBreadcrumbJsonLd, buildNavigationJsonLd, buildSiteNavigationJsonLd export { buildFaqJsonLd, buildLocalBusinessJsonLd, buildServiceJsonLd } from './modules/seo/index.js' export { buildArticleJsonLd, buildProductJsonLd, buildWebPageJsonLd, formatOpeningHours } from './modules/seo/index.js' export { buildLlmsTxt } from './modules/seo/index.js' -export { buildSitemapCss, buildSitemapXml, DEFAULT_SITEMAP_CREDIT, SITEMAP_STYLE_PARAM } from './modules/seo/index.js' +// Site Settings → Search & AI: verification codes and AI crawler rules, for custom metadata/robots routes. +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 { clientIp, setRateLimitStore } from './modules/shared/rateLimit.js' export type { ClientIpOptions, RateLimitStore } from './modules/shared/rateLimit.js' diff --git a/src/modules/frontend/createContentHelpers.ts b/src/modules/frontend/createContentHelpers.ts index 584c8b5..f4404a8 100644 --- a/src/modules/frontend/createContentHelpers.ts +++ b/src/modules/frontend/createContentHelpers.ts @@ -15,6 +15,7 @@ import type { PageMetadata, RobotsOptions, RobotsRules, SitemapEntry, SitemapSty import { getAnalyticsConfig } from '../analytics/getAnalyticsConfig.js' import { getConsentTexts } from '../consent/getConsentTexts.js' +import { normalizePath } from '../construction/logic.js' import { createMarkdownRoute } from '../content/createMarkdownRenderer.js' import { getArchiveEntries, resolveRoute as resolveRouteRaw } from '../content/index.js' import { MARKDOWN_PREFIX, markdownHref } from '../content/markdownNegotiation.js' @@ -30,9 +31,19 @@ import { buildWebSiteJsonLd } from '../seo/buildWebSiteJsonLd.js' import { buildArticleJsonLd, buildBreadcrumbJsonLd, buildFaqJsonLd, buildRobots, buildSitemapEntries, createManifestHandler, createPageMetadata, createSitemapRouteHandler } from '../seo/index.js' import { createIndexNowKeyRoute } from '../seo/indexNow.js' import { createLlmsTxtRoute } from '../seo/routeHandlers.js' +import { robotsOptionsFrom } from '../seo/searchSettings.js' import { type ThemeConfig, themeConfigFrom } from '../theme/theme.js' import { getTurnstileConfig } from '../turnstile/config.js' +/** Path of an absolute or relative URL: 'https://acme.pl/pl/o-nas' → '/pl/o-nas'. */ +const pathOf = (url: string): string => { + try { + return new URL(url, 'http://local').pathname + } catch { + return url + } +} + type CreateContentHelpersArgs = { /** * Absolute site origin for sitemap/robots URLs. Falls back to @@ -424,7 +435,7 @@ export function createContentHelpers({ ) } try { - return await buildSitemapEntries({ + const entries = await buildSitemapEntries({ baseUrl: origin, config: i18n, content, @@ -433,10 +444,19 @@ export function createContentHelpers({ payload: await getCachedPayload(), settingsSlug, }) + // Under construction: list only the pages visitors can still open — the + // rest redirect to the homepage notice, which crawlers would index. + const open = await constructionPaths() + if (!open) {return entries} + const allowed = new Set(open.map(normalizePath)) + return entries.filter((e) => allowed.has(normalizePath(pathOf(e.url)))) } catch (error) { - // DB unreachable (typically a container build with no DB network) — return - // an empty sitemap instead of failing the build. Runtime regeneration will - // produce the real one once the DB is reachable. See dynamic='force-dynamic'. + // At runtime a failure is an error (the sitemap route answers 503, so + // crawlers retry) — an empty sitemap would read as "no pages". + if (process.env.NEXT_PHASE !== 'phase-production-build') {throw error} + // DB unreachable during `next build` (container with no DB network) — + // return an empty sitemap instead of failing the build. Runtime regeneration + // produces the real one. See dynamic='force-dynamic'. console.warn( '[ipal] sitemap: could not reach the database, returning empty entries ' + "(add `export const dynamic = 'force-dynamic'` to app/sitemap.ts to " + @@ -457,6 +477,37 @@ export function createContentHelpers({ */ const robots = (): RobotsRules => buildRobots({ ...robotsOptions, baseUrl: origin }) + /** + * `robots` plus what editors set in Site Settings → Search & AI (AI bot policy + * and per-bot exceptions), read per request. Use it instead of `robots` to + * let the panel manage AI crawlers: + * + * ```ts + * // app/robots.ts + * export { getRobots as default } from '@/lib/content' + * export const dynamic = 'force-dynamic' + * ``` + * + * Database unreachable → the options from code, as `robots` returns. + */ + const getRobots = async (): Promise => { + let fromPanel: ReturnType = {} + try { + const payload = await getCachedPayload() + fromPanel = robotsOptionsFrom( + (await payload.findGlobal({ slug: settingsSlug as never, depth: 0 })) as Record, + ) + } catch { + // keep the code options + } + return buildRobots({ + ...robotsOptions, + ...fromPanel, + aiBotRules: [...(robotsOptions?.aiBotRules ?? []), ...(fromPanel.aiBotRules ?? [])], + baseUrl: origin, + }) + } + /** * Next.js generateStaticParams for the [[...slug]] route (or * [locale]/[[...slug]]). Returns every routable page as a params object, so @@ -680,6 +731,21 @@ export function createContentHelpers({ } }) + /** + * While Site Settings → Under construction is on: the paths still open (every + * language), which the sitemap and llms.txt list instead of everything. + * null when the site is open or the setting can't be read. + */ + const constructionPaths = async (): Promise => { + if (!i18n) {return null} + try { + const mode = await getConstructionMode(i18n.defaultLocale) + return mode.enabled ? mode.allowedPaths : null + } catch { + return null + } + } + // ── Layout ──────────────────────────────────────────────────────────────── /** Notifications → form texts in this locale (BuilderForm / RenderForm `texts`). */ const getFormTexts = cache(async (locale: string): Promise => @@ -730,8 +796,8 @@ export function createContentHelpers({ let value: T | undefined return () => (value ??= make()) } - const llms = lazy(() => createLlmsTxtRoute({ baseUrl: origin, config: needI18n('llmsRoute'), content, getCachedPayload, pagesSlug, settingsSlug, summaryField })) - const llmsFull = lazy(() => createLlmsTxtRoute({ baseUrl: origin, config: needI18n('llmsFullRoute'), content, full: true, getCachedPayload, pagesSlug, settingsSlug, summaryField })) + const llms = lazy(() => createLlmsTxtRoute({ baseUrl: origin, config: needI18n('llmsRoute'), content, getCachedPayload, getIncludedPaths: constructionPaths, pagesSlug, settingsSlug, summaryField })) + const llmsFull = lazy(() => createLlmsTxtRoute({ baseUrl: origin, config: needI18n('llmsFullRoute'), content, full: true, getCachedPayload, getIncludedPaths: constructionPaths, pagesSlug, settingsSlug, summaryField })) const md = lazy(() => createMarkdownRoute({ baseUrl: origin || undefined, collection: pagesSlug, config: i18n, content, getCachedPayload, settingsSlug, ...markdownOptions })) const mcp = lazy(() => createMcpRoute({ baseUrl: origin, collection: pagesSlug, config: needI18n('mcpRoute'), content, getCachedPayload, settingsSlug, summaryField, ...mcpOptions })) const health = lazy(() => createHealthRoute({ collection: pagesSlug, getCachedPayload })) @@ -766,6 +832,7 @@ export function createContentHelpers({ getLinkOptions, getNotFoundPage, getPageJsonLd, + getRobots, getSettings, getSiteShell, getSystemLinks, diff --git a/src/modules/mcp/createMcpRoute.ts b/src/modules/mcp/createMcpRoute.ts index 5ab004b..b15b429 100644 --- a/src/modules/mcp/createMcpRoute.ts +++ b/src/modules/mcp/createMcpRoute.ts @@ -197,6 +197,7 @@ export function createMcpRoute(args: CreateMcpRouteArgs) { baseUrl: origin, config, content, + limit: 1000, // list_pages shows at most 200 — no need to read a huge site whole locales: [locale], pagesSlug: collection, payload, diff --git a/src/modules/seo/buildLlmsTxt.ts b/src/modules/seo/buildLlmsTxt.ts index 8f9d647..3f9050b 100644 --- a/src/modules/seo/buildLlmsTxt.ts +++ b/src/modules/seo/buildLlmsTxt.ts @@ -6,6 +6,7 @@ import type { SiteIndexEntry } from './siteIndex.js' import { blocksToMarkdown } from '../content/blocksToMarkdown.js' import { getLocaleDefinition, isValidLocale } from '../i18n/index.js' +import { llmsIntroFrom } from './searchSettings.js' import { collectSiteIndex } from './siteIndex.js' type BuildLlmsTxtArgs = { @@ -25,6 +26,8 @@ type BuildLlmsTxtArgs = { * convention. Default false = the compact index (links + descriptions). */ full?: boolean + /** Only pages whose path passes — e.g. those open while the site is under construction. */ + include?: (path: string) => boolean /** Field holding the block layout (full mode only). Default 'layout'. */ layoutField?: string /** @@ -45,6 +48,7 @@ type BuildLlmsTxtArgs = { } type SettingsShape = { + [key: string]: unknown siteDescription?: null | string siteName?: null | string } @@ -57,7 +61,8 @@ const day = (iso?: string) => (iso ? iso.slice(0, 10) : undefined) * buildSitemapEntries: the plugin already knows the site's name, description, * and pages, so it can generate this automatically. * - * Structure (llmstxt.org): H1 site name, a blockquote summary, then — per + * Structure (llmstxt.org): H1 site name, a blockquote summary, the editor's + * note from Site Settings → Search & AI (when set), then — per * language when the site has several — one list per collection (pages first, * then archive collections such as a blog) of Markdown links with descriptions. * Section names are the project's own locale and collection labels; the plugin @@ -74,6 +79,7 @@ export async function buildLlmsTxt({ config, content, full = false, + include, layoutField = 'layout', locale, pagesSlug = 'pages', @@ -99,6 +105,7 @@ export async function buildLlmsTxt({ config, content, depth: full ? 1 : 0, + include, locales, pagesSlug, payload, @@ -108,6 +115,9 @@ export async function buildLlmsTxt({ const lines: string[] = [`# ${name}`, ''] if (description) {lines.push(`> ${description}`, '')} + // Site Settings → Search & AI: facts the editor wants assistants to know and quote. + const intro = llmsIntroFrom(settings) + if (intro) {lines.push(intro, '')} const multi = locales.length > 1 for (const loc of locales) { diff --git a/src/modules/seo/buildMetadata.ts b/src/modules/seo/buildMetadata.ts index 19a145b..876a68e 100644 --- a/src/modules/seo/buildMetadata.ts +++ b/src/modules/seo/buildMetadata.ts @@ -1,5 +1,6 @@ import type { I18nConfig, LocalizedSlugs } from '../i18n/index.js' import type { TitleOrder } from './composeTitle.js' +import type { VerificationMetadata } from './searchSettings.js' import type { SeoMeta } from './types.js' import { buildLocalizedPath } from '../i18n/index.js' @@ -59,6 +60,8 @@ export type PageMetadata = { images?: string[] title: string } + /** Search console ownership tags (google-site-verification, msvalidate.01, yandex-verification). */ + verification?: VerificationMetadata } type BuildMetadataArgs = { @@ -122,6 +125,8 @@ type BuildMetadataArgs = { siteName?: null | string /** slug per locale for this document — drives canonical + hreflang. */ slugs: LocalizedSlugs + /** Site Settings → Search & AI verification codes; rendered as tags by Next. */ + verification?: VerificationMetadata } /** @@ -151,6 +156,7 @@ export function buildMetadata({ siteDescription, siteName, slugs, + verification, }: BuildMetadataArgs): PageMetadata { // Title source priority: titleOverride (exact, wins outright) > meta.title // (SEO title an editor set) > pageTitle (the document's own name). This means @@ -203,6 +209,7 @@ export function buildMetadata({ ...(description && { description }), ...(ogImage ? { images: [ogImage.url] } : {}), }, + ...(verification ? { verification } : {}), // robots: noindex pages are excluded (follow keeps link authority). Indexed // pages get generous snippet/preview limits so Google can show rich results // (long snippets, large image previews, full video previews). diff --git a/src/modules/seo/buildRobots.ts b/src/modules/seo/buildRobots.ts index 61e6017..2a84f8c 100644 --- a/src/modules/seo/buildRobots.ts +++ b/src/modules/seo/buildRobots.ts @@ -12,12 +12,15 @@ type RobotRule = { allow?: string; disallow?: string[]; userAgent: string | stri */ export const AI_ASSISTANT_BOTS = [ 'ClaudeBot', + 'Claude-User', 'Claude-Web', 'Claude-SearchBot', 'ChatGPT-User', 'OAI-SearchBot', 'PerplexityBot', 'Perplexity-User', + 'MistralAI-User', + 'DuckAssistBot', ] as const export const AI_TRAINING_BOTS = [ @@ -30,7 +33,10 @@ export const AI_TRAINING_BOTS = [ 'Meta-ExternalAgent', ] as const -type AiBotsPolicy = 'allow' | 'block-training' | 'disallow' | false +export type AiBotsPolicy = 'allow' | 'block-training' | 'disallow' | false + +/** One bot treated differently from the policy, e.g. { userAgent: 'Bytespider', access: 'disallow' }. */ +export type AiBotRule = { access: 'allow' | 'disallow'; userAgent: string } export type RobotsOptions = { /** @@ -41,6 +47,12 @@ export type RobotsOptions = { adminRoute?: false | string /** Override the assistant/search bot list. */ aiAssistantAgents?: readonly string[] + /** + * Per-bot exceptions that win over `aiBots` — a listed bot leaves its policy + * group and gets its own allow or block. Unknown bots can be added this way. + * Site Settings → Search & AI fills it when you use `getRobots`. + */ + aiBotRules?: readonly AiBotRule[] /** * How to treat AI crawlers (assistant/search + training). Default 'allow' — * explicitly welcome them so the site stays visible to Claude, ChatGPT, @@ -118,6 +130,7 @@ export type RobotsRules = { export function buildRobots({ adminRoute = '/admin', aiAssistantAgents = AI_ASSISTANT_BOTS, + aiBotRules = [], aiBots = 'allow', aiTrainingAgents = AI_TRAINING_BOTS, baseUrl, @@ -139,15 +152,32 @@ export function buildRobots({ const baseRule: RobotRule = { allow: '/', disallow, userAgent: '*' } - const aiRules: RobotRule[] = [] - if (aiBots === 'allow') { - aiRules.push({ allow: '/', disallow, userAgent: [...aiAssistantAgents, ...aiTrainingAgents] }) - } else if (aiBots === 'block-training') { - aiRules.push({ allow: '/', disallow, userAgent: [...aiAssistantAgents] }) - aiRules.push({ disallow: ['/'], userAgent: [...aiTrainingAgents] }) - } else if (aiBots === 'disallow') { - aiRules.push({ disallow: ['/'], userAgent: [...aiAssistantAgents, ...aiTrainingAgents] }) + // Exceptions: last rule per bot wins; those bots leave the policy groups. + const exceptions = new Map() + for (const r of aiBotRules) { + const ua = r.userAgent.trim() + if (ua) {exceptions.set(ua.toLowerCase(), { access: r.access, userAgent: ua })} } + const notExcepted = (list: readonly string[]) => list.filter((ua) => !exceptions.has(ua.toLowerCase())) + const assistants = notExcepted(aiAssistantAgents) + const training = notExcepted(aiTrainingAgents) + + const aiRules: RobotRule[] = [] + const push = (rule: RobotRule) => { + if (rule.userAgent.length) {aiRules.push(rule)} + } + if (aiBots === 'allow') { + push({ allow: '/', disallow, userAgent: [...assistants, ...training] }) + } else if (aiBots === 'block-training') { + push({ allow: '/', disallow, userAgent: assistants }) + push({ disallow: ['/'], userAgent: training }) + } else if (aiBots === 'disallow') { + push({ disallow: ['/'], userAgent: [...assistants, ...training] }) + } + const allowed = [...exceptions.values()].filter((r) => r.access === 'allow').map((r) => r.userAgent) + const blocked = [...exceptions.values()].filter((r) => r.access === 'disallow').map((r) => r.userAgent) + push({ allow: '/', disallow, userAgent: allowed }) + push({ disallow: ['/'], userAgent: blocked }) return { rules: aiRules.length > 0 ? [baseRule, ...aiRules] : baseRule, diff --git a/src/modules/seo/buildSitemapEntries.ts b/src/modules/seo/buildSitemapEntries.ts index b1524f6..888104c 100644 --- a/src/modules/seo/buildSitemapEntries.ts +++ b/src/modules/seo/buildSitemapEntries.ts @@ -52,10 +52,19 @@ type BuildSitemapArgs = { /** Pages collection slug. Defaults to 'pages'. */ pagesSlug?: string payload: BasePayload + /** + * Read only the fields the sitemap needs (slug, dates, status, noindex, meta). + * Default: on with the default `images`, off with a custom `images` (it may + * read any field). `false` reads whole documents. + */ + select?: boolean /** SiteSettings global slug. Defaults to 'site-settings'. */ settingsSlug?: string } +/** Documents read per query — keeps memory flat on large collections. */ +export const SITEMAP_BATCH_SIZE = 500 + type DocRow = { [key: string]: unknown _status?: string @@ -140,6 +149,51 @@ function defaultImages(doc: Record): (null | string | undefined return image && typeof image === 'object' ? [(image as { url?: string }).url] : [] } +type CollectionConfigShape = { + flattenedFields?: { name?: string }[] + versions?: { drafts?: unknown } | false +} + +/** + * Query shape for one collection: published only (when it has drafts) and, + * with `select`, just the fields entryFor/isIndexable read. Fields the + * collection doesn't have are left out of the select. + */ +function queryFor(payload: BasePayload, slug: string, select: boolean) { + const cfg = (payload.collections as Record | undefined)?.[slug]?.config + const hasDrafts = Boolean(cfg?.versions && cfg.versions.drafts) + const names = new Set((cfg?.flattenedFields ?? []).map((f) => f.name)) + const pick = select && cfg?.flattenedFields + ? Object.fromEntries( + ['slug', 'updatedAt', 'noindex', 'meta'] + .filter((n) => n === 'updatedAt' || names.has(n)) + .concat(hasDrafts ? ['_status'] : []) + .map((n) => [n, true]), + ) + : undefined + return { + ...(hasDrafts ? { where: { _status: { equals: 'published' } } } : {}), + ...(pick ? { select: pick } : {}), + } +} + +/** Every document of a collection, SITEMAP_BATCH_SIZE at a time. */ +async function* readAll(payload: BasePayload, slug: string, select: boolean): AsyncGenerator { + const query = queryFor(payload, slug, select) + for (let page = 1; ; page++) { + const result = await payload.find({ + collection: slug as never, + depth: 1, // populate uploads so image URLs are available + limit: SITEMAP_BATCH_SIZE, + locale: 'all' as never, + page, + ...(query as object), + }) + yield* result.docs as DocRow[] + if (!result.hasNextPage) {return} + } +} + /** * Collects every public URL — pages and archive entries — as sitemap entries * with per-URL hreflang and lastmod. @@ -170,6 +224,7 @@ export async function buildSitemapEntries({ images: imagesOf = defaultImages, pagesSlug = 'pages', payload, + select = imagesOf === defaultImages, settingsSlug = 'site-settings', }: BuildSitemapArgs): Promise { const origin = baseUrl.replace(/\/$/, '') @@ -212,16 +267,10 @@ export async function buildSitemapEntries({ for (const collection of collections) { // Read every doc once, across locales, so one row yields all its language - // alternates without re-querying per locale. - const result = await payload.find({ - collection: collection.slug as never, - depth: 1, // populate uploads so image URLs are available - limit: 0, // no pagination — sitemap wants everything - locale: 'all' as never, - pagination: false as never, - }) - - for (const raw of result.docs as DocRow[]) { + // alternates without re-querying per locale. Batched, published only, and + // (by default) only the fields used here — a 20k-entry blog no longer + // loads every block of every post into memory at once. + for await (const raw of readAll(payload, collection.slug, select)) { if (!isIndexable(raw)) {continue} const images = [...new Set(imagesOf(raw).map(absolute).filter((u): u is string => Boolean(u)))] diff --git a/src/modules/seo/buildSitemapXml.ts b/src/modules/seo/buildSitemapXml.ts index f4fa8a8..fe891cf 100644 --- a/src/modules/seo/buildSitemapXml.ts +++ b/src/modules/seo/buildSitemapXml.ts @@ -43,27 +43,53 @@ type BuildSitemapXmlOptions = { * NOTE: if you use this custom route, DON'T also keep app/sitemap.ts — pick one. * Two sitemaps confuse crawlers. */ +const esc = (s: string): string => + s + .replace(/&/g, '&') + .replace(//g, '>') + .replace(/"/g, '"') + .replace(/'/g, ''') + +const isoOf = (d: Date | string): string => (d instanceof Date ? d.toISOString() : String(d)) + +/** One child sitemap listed in a sitemap index. */ +export type SitemapIndexItem = { lastModified?: Date | string; url: string } + +/** + * Sitemap index (``) — what /sitemap.xml returns once a site has + * more URLs than one file should hold. Each child carries the newest lastmod + * of its URLs, so crawlers re-read only the parts that changed. + */ +export function buildSitemapIndexXml(items: SitemapIndexItem[], opts: BuildSitemapXmlOptions = {}): string { + const stylesheet = opts.cssUrl ? `\n` : '' + const body = items + .map((i) => { + const parts = [` ${esc(i.url)}`] + if (i.lastModified) {parts.push(` ${esc(isoOf(i.lastModified))}`)} + return ` \n${parts.join('\n')}\n ` + }) + .join('\n') + return ( + `\n` + + stylesheet + + `\n` + + body + + `\n` + ) +} + export function buildSitemapXml( entries: SitemapEntry[], opts: BuildSitemapXmlOptions = {}, ): string { const { cssUrl } = opts - const esc = (s: string): string => - s - .replace(/&/g, '&') - .replace(//g, '>') - .replace(/"/g, '"') - .replace(/'/g, ''') - const urls = entries .map((e) => { const parts = [` ${esc(e.url)}`] if (e.lastModified) { - const iso = - e.lastModified instanceof Date ? e.lastModified.toISOString() : String(e.lastModified) - parts.push(` ${esc(iso)}`) + parts.push(` ${esc(isoOf(e.lastModified))}`) } if (e.changeFrequency) {parts.push(` ${e.changeFrequency}`)} if (typeof e.priority === 'number') {parts.push(` ${e.priority}`)} diff --git a/src/modules/seo/createPageMetadata.ts b/src/modules/seo/createPageMetadata.ts index 16e243e..a3277c9 100644 --- a/src/modules/seo/createPageMetadata.ts +++ b/src/modules/seo/createPageMetadata.ts @@ -145,6 +145,7 @@ export function createPageMetadata(args: CreatePageMetadataArgs) { // fallback opisu: strona bez meta.description dostaje Site Settings → siteDescription (seo.md) siteDescription: site.siteDescription, siteName: site.siteName, + verification: site.verification, } const route = loaders?.resolveRoute @@ -162,8 +163,9 @@ export function createPageMetadata(args: CreatePageMetadataArgs) { // Unknown route (the page component will 404) — still return something // coherent rather than throwing during metadata generation. + // noindex: a 404 must never be indexed, even if a host serves it with 200. if (!route) { - return buildMetadata({ ...base, meta: null, slugs: {} }) + return buildMetadata({ ...base, meta: null, noindex: true, slugs: {} }) } const doc = route.doc as DocShape diff --git a/src/modules/seo/index.ts b/src/modules/seo/index.ts index 1aadd78..96bccf4 100644 --- a/src/modules/seo/index.ts +++ b/src/modules/seo/index.ts @@ -13,11 +13,12 @@ export { buildNoindexField } from './buildNoindexField.js' export { buildOrganizationJsonLd, sameAsUrls } from './buildOrganizationJsonLd.js' export { buildProductJsonLd } from './buildProductJsonLd.js' export { AI_ASSISTANT_BOTS, AI_TRAINING_BOTS, buildRobots } from './buildRobots.js' +export type { AiBotRule, AiBotsPolicy } from './buildRobots.js' export type { RobotsOptions, RobotsRules } from './buildRobots.js' export { buildServiceJsonLd } from './buildServiceJsonLd.js' export { buildSitemapEntries } from './buildSitemapEntries.js' export type { SitemapEntry } from './buildSitemapEntries.js' -export { buildSitemapXml } from './buildSitemapXml.js' +export { buildSitemapIndexXml, buildSitemapXml } from './buildSitemapXml.js' export { buildNavigationJsonLd, buildSiteNavigationJsonLd } from './buildSiteNavigationJsonLd.js' export { buildSpeakableJsonLd } from './buildSpeakableJsonLd.js' export { buildSummaryField } from './buildSummaryField.js' @@ -42,8 +43,10 @@ export { injectSeoTabs } from './injectSeoTabs.js' export { JsonLdGraph } from './JsonLdGraph.js' export { readSiteMetaConfig } from './readSiteMetaConfig.js' export type { SiteMetaConfig } from './readSiteMetaConfig.js' -export { createLlmsTxtRoute, createSitemapRouteHandler } from './routeHandlers.js' +export { createLlmsTxtRoute, createSitemapRouteHandler, DEFAULT_SITEMAP_CACHE_CONTROL, DEFAULT_SITEMAP_MAX_URLS, SITEMAP_PART_PARAM } from './routeHandlers.js' export type { SitemapRouteOptions } from './routeHandlers.js' +export { normalizeVerificationToken, robotsOptionsFrom, searchSettingsFields, verificationFrom } from './searchSettings.js' +export type { VerificationMetadata } from './searchSettings.js' export { buildSeoPlugin } from './seoPluginConfig.js' export { collectSiteIndex } from './siteIndex.js' export type { CollectSiteIndexArgs, SiteIndexEntry } from './siteIndex.js' diff --git a/src/modules/seo/indexNow.ts b/src/modules/seo/indexNow.ts index 156507f..3009570 100644 --- a/src/modules/seo/indexNow.ts +++ b/src/modules/seo/indexNow.ts @@ -4,6 +4,7 @@ import type { I18nConfig } from '../i18n/index.js' import { archiveFieldName } from '../content/types.js' import { buildLocalizedPath, getLocaleCodes, getLocalizedSlugs } from '../i18n/index.js' +import { isSiteNoindex } from './siteNoindex.js' /** * IndexNow — tell search engines a URL changed the moment it's published @@ -76,9 +77,14 @@ export function createIndexNowKeyRoute({ getCachedPayload }: { getCachedPayload: } } -/** True when submissions may leave this machine: production + a public https origin. */ +/** + * True when submissions may leave this machine: production + a public https + * origin, and not a staging copy (IPAL_NOINDEX) — a staging build runs with + * NODE_ENV=production too, and its URLs must not reach Bing. + */ function publicOrigin(baseUrl?: string): null | string { const origin = (baseUrl ?? process.env.NEXT_PUBLIC_SERVER_URL ?? '').replace(/\/$/, '') + if (isSiteNoindex()) {return null} if (process.env.NODE_ENV !== 'production' || !/^https:\/\//i.test(origin)) {return null} if (/localhost|127\.0\.0\.1|\.local\b|\.test\b/i.test(origin)) {return null} return origin diff --git a/src/modules/seo/readSiteMetaConfig.ts b/src/modules/seo/readSiteMetaConfig.ts index 2086b25..89d3bb7 100644 --- a/src/modules/seo/readSiteMetaConfig.ts +++ b/src/modules/seo/readSiteMetaConfig.ts @@ -1,6 +1,9 @@ import type { BasePayload } from 'payload' import type { TitleOrder } from './composeTitle.js' +import type { VerificationMetadata } from './searchSettings.js' + +import { verificationFrom } from './searchSettings.js' type SettingsShape = { [key: string]: unknown @@ -25,6 +28,8 @@ export type SiteMetaConfig = { /** Global fallback meta description. */ siteDescription?: null | string siteName: null | string + /** Site Settings → Search & AI → verification codes (Search Console, Bing, Yandex). */ + verification?: VerificationMetadata } /** @@ -102,7 +107,9 @@ export async function readSiteMetaConfig({ } const share = settings.defaultShareImage + const verification = verificationFrom(settings) return { + ...(verification ? { verification } : {}), defaultShareImage: share && typeof share === 'object' ? (share as Record) : null, siteDescription: (settings.siteDescription as string | undefined) ?? null, siteName: (settings[siteNameField] as string | undefined) ?? null, diff --git a/src/modules/seo/routeHandlers.ts b/src/modules/seo/routeHandlers.ts index 80f530a..a63f552 100644 --- a/src/modules/seo/routeHandlers.ts +++ b/src/modules/seo/routeHandlers.ts @@ -4,8 +4,9 @@ import type { ContentOption } from '../content/index.js' import type { I18nConfig } from '../i18n/index.js' import type { SitemapEntry } from './buildSitemapEntries.js' +import { normalizePath } from '../construction/logic.js' import { buildLlmsTxt } from './buildLlmsTxt.js' -import { buildSitemapXml } from './buildSitemapXml.js' +import { buildSitemapIndexXml, buildSitemapXml } from './buildSitemapXml.js' import { buildSitemapCss, SITEMAP_STYLE_PARAM, type SitemapStyleOptions } from './sitemapStyle.js' /** @@ -35,6 +36,11 @@ export function createLlmsTxtRoute(opts: { /** Inline every page's full Markdown (llms-full.txt). Default false. */ full?: boolean getCachedPayload: () => Promise + /** + * Paths to list, read per request — null lists everything. createContentHelpers + * passes the pages still open while the site is under construction. + */ + getIncludedPaths?: () => Promise pagesSlug?: string settingsSlug?: string /** Field holding a richer AI summary (buildSummaryField) to prefer as description. */ @@ -43,11 +49,14 @@ export function createLlmsTxtRoute(opts: { return async () => { try { const payload = await opts.getCachedPayload() + const paths = opts.getIncludedPaths ? await opts.getIncludedPaths() : null + const allowed = paths ? new Set(paths.map(normalizePath)) : null const body = await buildLlmsTxt({ baseUrl: opts.baseUrl, config: opts.config, content: opts.content, full: opts.full, + ...(allowed ? { include: (path: string) => allowed.has(normalizePath(path)) } : {}), pagesSlug: opts.pagesSlug, payload, settingsSlug: opts.settingsSlug, @@ -56,22 +65,61 @@ export function createLlmsTxtRoute(opts: { return new Response(body, { // For AI agents, not a search result: keep it (and the full-content // copy, a duplicate of every page) out of search indexes. - headers: { 'Content-Type': 'text/plain; charset=utf-8', 'X-Robots-Tag': 'noindex' }, + headers: { + // Same as the sitemap: a CDN keeps it an hour; llms-full renders every page. + 'Cache-Control': DEFAULT_SITEMAP_CACHE_CONTROL, + 'Content-Type': 'text/plain; charset=utf-8', + 'X-Robots-Tag': 'noindex', + }, }) } catch (err) { // DB unreachable at build (container) — return a minimal valid file so the // route doesn't 500; it fills in at runtime. No per-project try/catch. console.warn('[ipal] createLlmsTxtRoute: could not build llms.txt:', err) return new Response('# llms.txt\n', { - headers: { 'Content-Type': 'text/plain; charset=utf-8' }, + headers: { 'Cache-Control': 'no-store', 'Content-Type': 'text/plain; charset=utf-8', 'X-Robots-Tag': 'noindex' }, }) } } } +/** Query parameter of a sitemap part: /sitemap.xml?part=2. */ +export const SITEMAP_PART_PARAM = 'part' +export const DEFAULT_SITEMAP_MAX_URLS = 10_000 +export const DEFAULT_SITEMAP_CACHE_CONTROL = 'public, max-age=0, s-maxage=3600, stale-while-revalidate=86400' + +/** Newest lastModified of a batch — the part's own lastmod in the index. */ +function newest(entries: SitemapEntry[]): string | undefined { + let best: number | undefined + for (const e of entries) { + const t = e.lastModified ? new Date(e.lastModified).getTime() : NaN + if (!Number.isNaN(t) && (best === undefined || t > best)) {best = t} + } + return best === undefined ? undefined : new Date(best).toISOString() +} + export type SitemapRouteOptions = { + /** + * Cache-Control of the XML. Default: browsers revalidate, shared caches (CDN) + * keep it an hour and may serve a stale copy for a day while refreshing. + * `false` sends no header. An error response is never cached. + */ + cacheControl?: false | string /** Legacy: your own stylesheet URL (e.g. '/sitemap.css'). Overrides `style`. */ cssUrl?: string + /** + * Max URLs in one file. Above it /sitemap.xml becomes a sitemap index of + * parts at `?part=1`, `?part=2`… (the protocol allows 50 000 URLs / 50 MB; + * hreflang alternates make each URL large, hence the lower default). + * Default 10 000. + */ + maxUrls?: number + /** + * Seconds the built entries are reused inside this server process, so the + * index and its parts (and repeated crawler hits) don't rebuild from the + * database each time. Default 300; 0 turns it off. + */ + memoSeconds?: number /** * Built-in browser look (default ON): the XML points at `?style` * and the same handler serves the CSS — nothing to copy into /public. @@ -90,6 +138,8 @@ export type SitemapRouteOptions = { * export const dynamic = 'force-dynamic' * * `GET /sitemap.xml` → XML (crawlers), `GET /sitemap.xml?style` → its CSS. + * Over `maxUrls` URLs, /sitemap.xml is an index and the URLs sit in + * `/sitemap.xml?part=N` — robots.txt and Search Console keep the one address. * Don't keep app/sitemap.ts next to it — two sitemaps confuse crawlers. */ export function createSitemapRouteHandler( @@ -97,6 +147,25 @@ export function createSitemapRouteHandler( opts: SitemapRouteOptions = {}, ): (req: Request) => Promise { const style = opts.cssUrl ? false : opts.style === false ? false : (opts.style ?? {}) + const maxUrls = Math.max(1, Math.floor(opts.maxUrls ?? DEFAULT_SITEMAP_MAX_URLS)) + const memoMs = Math.max(0, opts.memoSeconds ?? 300) * 1000 + const cacheControl = opts.cacheControl === undefined ? DEFAULT_SITEMAP_CACHE_CONTROL : opts.cacheControl + const xmlHeaders = { + 'Content-Type': 'application/xml; charset=utf-8', + ...(cacheControl ? { 'Cache-Control': cacheControl } : {}), + } + + let memo: { at: number; entries: Promise } | undefined + const entries = (): Promise => { + if (memoMs && memo && Date.now() - memo.at < memoMs) {return memo.entries} + const fresh = sitemap() + // A failed or empty build (sitemap() returns [] when the database is + // unreachable) is not reused — the next request tries again. + const forget = () => { if (memo?.entries === fresh) {memo = undefined} } + fresh.then((list) => { if (!list.length) {forget()} }, forget) + if (memoMs) {memo = { at: Date.now(), entries: fresh }} + return fresh + } // `req` is required: Next 16 type-checks the first argument of a route handler // (`Request | undefined` fails the build). A zero-argument call is not supported. @@ -121,19 +190,47 @@ export function createSitemapRouteHandler( const cssUrl = opts.cssUrl ?? (style ? `${url.pathname}?${SITEMAP_STYLE_PARAM}` : undefined) try { - const entries = await sitemap() - const xml = buildSitemapXml(entries, { cssUrl }) - return new Response(xml, { - headers: { 'Content-Type': 'application/xml; charset=utf-8' }, - }) + const all = await entries() + const parts = Math.ceil(all.length / maxUrls) + const partParam = url.searchParams.get(SITEMAP_PART_PARAM) + + if (partParam !== null) { + const part = Number(partParam) + if (!Number.isInteger(part) || part < 1 || part > Math.max(parts, 1)) { + return new Response('Not found', { headers: { 'Cache-Control': 'no-store' }, status: 404 }) + } + const slice = all.slice((part - 1) * maxUrls, part * maxUrls) + return new Response(buildSitemapXml(slice, { cssUrl }), { headers: xmlHeaders }) + } + + if (parts > 1) { + const items = Array.from({ length: parts }, (_, i) => { + const slice = all.slice(i * maxUrls, (i + 1) * maxUrls) + return { lastModified: newest(slice), url: `${url.origin}${url.pathname}?${SITEMAP_PART_PARAM}=${i + 1}` } + }) + return new Response(buildSitemapIndexXml(items, { cssUrl }), { headers: xmlHeaders }) + } + + // Empty usually means the database was unreachable — don't let a CDN keep it. + const headers = all.length ? xmlHeaders : { ...xmlHeaders, 'Cache-Control': 'no-store' } + return new Response(buildSitemapXml(all, { cssUrl }), { headers }) } catch (err) { console.warn('[ipal] createSitemapRouteHandler: could not build sitemap:', err) + // At runtime: 503 + Retry-After — crawlers come back later, while an empty + // sitemap with 200 would tell them the site has no pages. + if (process.env.NEXT_PHASE !== 'phase-production-build') { + return new Response('Sitemap temporarily unavailable', { + headers: { 'Cache-Control': 'no-store', 'Content-Type': 'text/plain; charset=utf-8', 'Retry-After': '300' }, + status: 503, + }) + } // Valid empty urlset so the route doesn't 500 during a DB-less build. const empty = '\n' + '' return new Response(empty, { - headers: { 'Content-Type': 'application/xml; charset=utf-8' }, + // Never let a CDN keep the empty fallback. + headers: { 'Cache-Control': 'no-store', 'Content-Type': 'application/xml; charset=utf-8' }, }) } } diff --git a/src/modules/seo/searchSettings.ts b/src/modules/seo/searchSettings.ts new file mode 100644 index 0000000..f24fba4 --- /dev/null +++ b/src/modules/seo/searchSettings.ts @@ -0,0 +1,170 @@ +import type { Field } from 'payload' + +import type { AiBotRule, AiBotsPolicy, RobotsOptions } from './buildRobots.js' + +/** + * Site Settings → Search & AI: what editors set for search engines and AI + * assistants without a deploy — Search Console / Bing verification codes, the + * AI crawler policy for robots.txt, and a note for llms.txt. Empty fields + * change nothing: verification tags appear only once a code is pasted, and the + * robots policy stays the one set in code until an editor picks another. + */ + +export const SEARCH_VERIFICATION_FIELD = 'searchVerification' +export const AI_CRAWLERS_FIELD = 'aiCrawlers' +export const LLMS_INTRO_FIELD = 'llmsIntro' + +/** Next `Metadata.verification` — site ownership tags for search consoles. */ +export type VerificationMetadata = { + google?: string + other?: Record + yandex?: string +} + +/** + * Accepts the bare code or the whole tag an editor copies from Search Console + * (``) and keeps only + * the code. Anything that isn't a plain token is dropped — the value ends up + * in every page's . + */ +export function normalizeVerificationToken(raw: unknown): string { + if (typeof raw !== 'string') {return ''} + let value = raw.trim() + const content = /content\s*=\s*["']([^"']*)["']/i.exec(value) + if (content) {value = content[1].trim()} + value = value.replace(/^["']|["']$/g, '') + return /^[\w\-.:+/=]{1,200}$/.test(value) ? value : '' +} + +const tokenField = (name: string, label: string, description: string): Field => ({ + name, + type: 'text', + admin: { description }, + hooks: { beforeChange: [({ value }) => normalizeVerificationToken(value) || null] }, + label, +}) + +const AI_POLICY_OPTIONS = [ + { label: 'As set by the developer (default)', value: 'default' }, + { label: 'Allow all AI assistants and AI training', value: 'allow' }, + { label: 'Allow AI assistants and AI search, block AI training', value: 'block-training' }, + { label: 'Block all known AI bots', value: 'disallow' }, +] as const + +/** The "Search & AI" tab fields. Not localized, except the llms.txt note. */ +export const searchSettingsFields: Field[] = [ + { + name: SEARCH_VERIFICATION_FIELD, + type: 'group', + admin: { + description: + 'Proves to search engines that you own this site. Paste the code (or the whole tag) from the search engine; it is added to every page. Leave empty if you verify another way (DNS, file).', + }, + fields: [ + tokenField('google', 'Google Search Console', 'Search Console → Settings → Ownership verification → HTML tag.'), + tokenField('bing', 'Bing Webmaster Tools', 'Bing Webmaster Tools → Add site → HTML Meta Tag (msvalidate.01). Bing also powers ChatGPT Search and Copilot.'), + tokenField('yandex', 'Yandex Webmaster', 'Yandex Webmaster → Site verification → Meta tag.'), + ], + label: 'Search engine verification', + }, + { + name: AI_CRAWLERS_FIELD, + type: 'group', + admin: { + description: + 'Which AI bots may read the site (robots.txt). Assistants (ClaudeBot, ChatGPT-User, PerplexityBot…) fetch pages to answer questions and cite you; training crawlers (GPTBot, Google-Extended, CCBot…) collect pages to train models. Blocking assistants removes the site from AI answers.', + }, + fields: [ + { + name: 'policy', + type: 'select', + defaultValue: 'default', + label: 'AI bots', + options: AI_POLICY_OPTIONS.map((o) => ({ ...o })), + }, + { + name: 'rules', + type: 'array', + admin: { + description: + 'Exceptions for single bots, by user agent exactly as the bot announces itself (e.g. GPTBot, Bytespider). Wins over the setting above.', + initCollapsed: true, + }, + fields: [ + { name: 'userAgent', type: 'text', label: 'User agent', required: true }, + { + name: 'access', + type: 'select', + defaultValue: 'disallow', + options: [ + { label: 'Allow', value: 'allow' }, + { label: 'Block', value: 'disallow' }, + ], + required: true, + }, + ], + label: 'Per-bot exceptions', + }, + ], + label: 'AI crawlers', + }, + { + name: LLMS_INTRO_FIELD, + type: 'textarea', + admin: { + description: + 'Shown at the top of /llms.txt, under the site description: key facts an AI assistant should know and may quote — what you do, where, for whom, since when. Plain sentences, no marketing slogans.', + }, + label: 'About the site for AI assistants (llms.txt)', + localized: true, + }, +] + +type SettingsLike = null | Record | undefined + +/** Site Settings → verification codes as Next `Metadata.verification`; undefined when none is set. */ +export function verificationFrom(settings: SettingsLike): undefined | VerificationMetadata { + const group = settings?.[SEARCH_VERIFICATION_FIELD] as null | Record | undefined + if (!group || typeof group !== 'object') {return undefined} + const google = normalizeVerificationToken(group.google) + const bing = normalizeVerificationToken(group.bing) + const yandex = normalizeVerificationToken(group.yandex) + if (!google && !bing && !yandex) {return undefined} + return { + ...(google ? { google } : {}), + ...(yandex ? { yandex } : {}), + ...(bing ? { other: { 'msvalidate.01': bing } } : {}), + } +} + +const POLICIES = new Set(['allow', 'block-training', 'disallow']) + +/** + * Site Settings → AI crawlers as buildRobots options. Only what the editor + * changed: policy 'default' keeps the option from code, no rules adds none. + */ +export function robotsOptionsFrom(settings: SettingsLike): Pick { + const group = settings?.[AI_CRAWLERS_FIELD] as { policy?: unknown; rules?: unknown } | null | undefined + if (!group || typeof group !== 'object') {return {}} + const policy = typeof group.policy === 'string' && POLICIES.has(group.policy) ? (group.policy as AiBotsPolicy) : undefined + const rules: AiBotRule[] = Array.isArray(group.rules) + ? group.rules.flatMap((r: unknown) => { + const row = r as { access?: unknown; userAgent?: unknown } | null + // A user agent is one token — no spaces, colons or newlines that could + // inject other robots.txt lines. + const ua = typeof row?.userAgent === 'string' ? row.userAgent.trim() : '' + if (!/^[\w\-.*/]{1,100}$/.test(ua)) {return []} + return [{ access: row?.access === 'allow' ? ('allow' as const) : ('disallow' as const), userAgent: ua }] + }) + : [] + return { + ...(policy ? { aiBots: policy } : {}), + ...(rules.length ? { aiBotRules: rules } : {}), + } +} + +/** Site Settings → llms.txt note in the locale it was read in. Empty string when unset. */ +export function llmsIntroFrom(settings: SettingsLike): string { + const v = settings?.[LLMS_INTRO_FIELD] + return typeof v === 'string' ? v.trim() : '' +} diff --git a/src/modules/seo/siteIndex.ts b/src/modules/seo/siteIndex.ts index a724364..9fdea71 100644 --- a/src/modules/seo/siteIndex.ts +++ b/src/modules/seo/siteIndex.ts @@ -38,7 +38,12 @@ export type CollectSiteIndexArgs = { content?: ContentOption /** Population depth of `doc`. Default 0 (1 when you render blocks with images). */ depth?: number - /** Max documents per collection and locale. Default 1000. */ + /** + * Only paths this returns true for — e.g. the pages still open while the site + * is under construction. Default: every path. + */ + include?: (path: string) => boolean + /** Max documents per collection and locale. Default: no limit (read in batches of 500). */ limit?: number /** Only these locales. Default: every configured locale. */ locales?: string[] @@ -80,6 +85,33 @@ function slugMap(rel: unknown, locales: string[]): Record | unde return Object.keys(map).length ? map : undefined } +const BATCH = 500 + +/** Published documents of one collection in one locale, BATCH at a time, up to `limit`. */ +async function readDocs( + payload: BasePayload, + collection: string, + { depth, limit, locale }: { depth: number; limit?: number; locale: string }, +): Promise { + const cfg = (payload.collections as Record | undefined)?.[collection]?.config + const drafts = Boolean(cfg?.versions && cfg.versions.drafts) + const docs: Row[] = [] + const size = limit === undefined ? BATCH : Math.max(1, Math.min(BATCH, limit)) + for (let page = 1; limit === undefined || docs.length < limit; page++) { + const res = await payload.find({ + collection: collection as never, + depth, + limit: size, + locale: locale as never, + page, + ...(drafts ? { where: { _status: { equals: 'published' } } } : {}), + }) + docs.push(...((res?.docs ?? []) as Row[])) + if (!res?.hasNextPage) {break} + } + return limit === undefined ? docs : docs.slice(0, limit) +} + /** * Every public page and archive entry, per language, with its URL, title, * description and dates — ONE source for everything that lists the site to @@ -95,7 +127,8 @@ export async function collectSiteIndex({ config, content, depth = 0, - limit = 1000, + include, + limit, locales, pagesSlug = 'pages', payload, @@ -127,8 +160,7 @@ export async function collectSiteIndex({ if (collection !== pagesSlug && !prefix?.[locale]) {continue} let docs: Row[] = [] try { - const res = await payload.find({ collection: collection as never, depth, limit, locale: locale as never }) - docs = (res?.docs ?? []) as Row[] + docs = await readDocs(payload, collection, { depth, limit, locale }) } catch { continue } @@ -142,7 +174,7 @@ export async function collectSiteIndex({ const slug = typeof doc.slug === 'string' ? doc.slug : '' if (!title || !slug || EXCLUDED_SLUGS.has(slug)) {continue} const path = buildLocalizedPath({ config, homeSlug, locale, prefix, slugs: { [locale]: slug } }) - if (!path) {continue} + if (!path || (include && !include(path))) {continue} const summary = summaryField && typeof doc[summaryField] === 'string' ? (doc[summaryField]).trim() : '' const metaDescription = typeof doc.meta?.description === 'string' ? doc.meta.description.trim() : '' const description = summary || metaDescription diff --git a/src/modules/seo/sitemapStyle.ts b/src/modules/seo/sitemapStyle.ts index f3876a5..dd802d4 100644 --- a/src/modules/seo/sitemapStyle.ts +++ b/src/modules/seo/sitemapStyle.ts @@ -46,28 +46,28 @@ export function buildSitemapCss({ accent, credit, title }: SitemapStyleOptions = --badge-bg: #1a1c26; --badge-border: #282b3d; --badge-text: #9ca3af; } } -urlset { +urlset, sitemapindex { display: flex; flex-direction: column; box-sizing: border-box; min-height: 100vh; max-width: 1040px; margin: 0 auto; padding: 3rem 1.5rem; line-height: 1.5; font-family: -apple-system, BlinkMacSystemFont, "Segoe UI", Roboto, Inter, Helvetica, Arial, sans-serif; background-color: var(--bg); color: var(--text-main); } -urlset::before { +urlset::before, sitemapindex::before { content: ${cssString(heading)}; display: block; order: -2; font-size: 1.35rem; font-weight: 600; letter-spacing: -0.02em; color: var(--text-main); ${note ? 'padding-bottom: 0.4rem;' : divider} } -${note ? `urlset::after { +${note ? `urlset::after, sitemapindex::after { content: ${cssString(note)}; display: block; order: -1; font-size: 0.8rem; color: var(--text-muted); ${divider} } -` : ''}url { +` : ''}url, sitemap { display: block; width: 100%; order: 0; box-sizing: border-box; background-color: var(--card); border: 1px solid var(--border); border-radius: 8px; padding: 1rem 1.25rem; margin-bottom: 0.65rem; transition: border-color 0.15s ease, box-shadow 0.15s ease; } -url:hover { border-color: var(--accent); box-shadow: 0 2px 6px rgba(0, 0, 0, 0.03); } +url:hover, sitemap:hover { border-color: var(--accent); box-shadow: 0 2px 6px rgba(0, 0, 0, 0.03); } loc { display: block; margin-bottom: 0.45rem; word-break: break-all; line-height: 1.45; font-family: ui-monospace, SFMono-Regular, Menlo, Monaco, Consolas, "Liberation Mono", monospace; diff --git a/src/modules/seo/types.ts b/src/modules/seo/types.ts index e421748..bbcc8d6 100644 --- a/src/modules/seo/types.ts +++ b/src/modules/seo/types.ts @@ -36,6 +36,12 @@ export type SeoOption = { generateDescription?: (args: { doc: Record }) => string /** Optional: customize how meta titles are generated in the admin preview. */ generateTitle?: (args: { doc: Record }) => string + /** + * Site Settings → "Search & AI" tab: Search Console / Bing / Yandex + * verification, AI crawler policy for robots.txt (getRobots), llms.txt note. + * On by default (empty fields change nothing); false removes the tab. + */ + searchSettings?: false } /** diff --git a/src/plugin.ts b/src/plugin.ts index a2df254..6e04014 100644 --- a/src/plugin.ts +++ b/src/plugin.ts @@ -18,6 +18,7 @@ import { buildLocalizationConfig, validateI18nConfig } from './modules/i18n/inde 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 { buildStatsCollection, buildStatsEndpoint } from './modules/stats/index.js' /** @@ -218,6 +219,7 @@ export const ipalKit = (options: IpalOptions): Plugin => { additionalFields: options.siteSettingsFields, ...(options.pages ? { constructionFields: buildConstructionFields(options.pages.slug) } : {}), ...(options.forms?.emailLayout ? { emailFields: emailSettingsFields } : {}), + ...(options.seo?.searchSettings === false ? {} : { searchFields: searchSettingsFields }), systemPageFields, }), buildSiteIntegrations({ additionalFields: options.integrationsFields }), diff --git a/test/indexNow.test.ts b/test/indexNow.test.ts index ba9def3..9841e72 100644 --- a/test/indexNow.test.ts +++ b/test/indexNow.test.ts @@ -74,6 +74,12 @@ describe('IndexNow hook', () => { await run({}) expect(fetchSpy).not.toHaveBeenCalled() }) + + test('staging copy (IPAL_NOINDEX) sends nothing even in production', async () => { + vi.stubEnv('IPAL_NOINDEX', '1') + await run({ _status: 'published' }) + expect(fetchSpy).not.toHaveBeenCalled() + }) }) describe('IndexNow key', () => { diff --git a/test/seoIntegration.test.ts b/test/seoIntegration.test.ts new file mode 100644 index 0000000..498d916 --- /dev/null +++ b/test/seoIntegration.test.ts @@ -0,0 +1,104 @@ +import type { Payload } from 'payload' + +import { sqliteAdapter } from '@payloadcms/db-sqlite' +import { lexicalEditor } from '@payloadcms/richtext-lexical' +import os from 'node:os' +import path from 'node:path' +import { buildConfig, getPayload } from 'payload' +import { afterAll, beforeAll, describe, expect, test, vi } from 'vitest' + +import { createContentHelpers } from '../src/modules/frontend/createContentHelpers.js' +import { ipalKit } from '../src/plugin.js' + +vi.mock('server-only', () => ({})) + +/** + * Sitemap, llms.txt and robots against a real (SQLite) Payload: the batched, + * `select`-ed, published-only reads must work with the database adapter, and + * Site Settings → Search & AI / Under construction must reach the output. + */ +describe('SEO outputs against a real database', () => { + let payload: Payload + let configPromise: Parameters[0]['config'] + const i18n = { defaultLocale: 'pl', locales: [{ code: 'pl', label: 'Polski' }, { code: 'en', label: 'English' }] } as const + const helpers = () => createContentHelpers({ baseUrl: 'https://acme.pl', config: configPromise, i18n }) + const urls = async () => (await helpers().sitemap()).map((e) => e.url).sort() + + beforeAll(async () => { + configPromise = buildConfig({ + collections: [ + { slug: 'users', auth: true, fields: [] }, + { + slug: 'pages', + fields: [ + { name: 'title', type: 'text' }, + { name: 'slug', type: 'text', index: true, localized: true }, + { name: 'noindex', type: 'checkbox' }, + ], + versions: { drafts: true }, + }, + { slug: 'media', fields: [], upload: { staticDir: path.join(os.tmpdir(), 'ipal-test-media-seo') } }, + ], + db: sqliteAdapter({ client: { url: 'file::memory:' }, push: true }), + editor: lexicalEditor(), + plugins: [ipalKit({ access: { authCollection: 'users' }, i18n, pages: { slug: 'pages' }, twoFactor: false })], + secret: 'seo-integration-test-secret', + telemetry: false, + }) + payload = await getPayload({ config: configPromise }) + + const create = async (slug: Record, extra: Record = {}) => { + const doc = await payload.create({ + collection: 'pages' as never, + data: { slug: slug.pl, _status: 'published', title: slug.pl, ...extra } as never, + locale: 'pl' as never, + }) + await payload.update({ id: doc.id, collection: 'pages' as never, data: { slug: slug.en } as never, locale: 'en' as never }) + return doc + } + const home = await create({ en: 'home', pl: 'start' }) + await create({ en: 'about', pl: 'o-nas' }) + await create({ en: 'hidden', pl: 'ukryta' }, { noindex: true }) + await create({ en: 'draft', pl: 'szkic' }, { _status: 'draft' }) + await payload.updateGlobal({ slug: 'site-settings' as never, data: { homepage: home.id, siteName: 'Acme' } as never }) + }, 60_000) + + afterAll(async () => { + await payload?.destroy() + }) + + test('sitemap: published and indexable pages in every language', async () => { + expect(await urls()).toEqual(['https://acme.pl/en', 'https://acme.pl/en/about', 'https://acme.pl/pl', 'https://acme.pl/pl/o-nas']) + }) + + test('verification codes and AI crawler rules from Site Settings → Search & AI', async () => { + await payload.updateGlobal({ + slug: 'site-settings' as never, + data: { + aiCrawlers: { policy: 'block-training', rules: [{ access: 'disallow', userAgent: 'PerplexityBot' }] }, + searchVerification: { google: '' }, + } as never, + }) + const stored = (await payload.findGlobal({ slug: 'site-settings' as never })) as { searchVerification?: { google?: string } } + expect(stored.searchVerification?.google).toBe('G-tok_1') + + const meta = await helpers().generatePageMetadata('pl', ['o-nas']) + expect(meta.verification).toEqual({ google: 'G-tok_1' }) + + const rules = (await helpers().getRobots()).rules as { disallow?: string[]; userAgent: string | string[] }[] + expect(rules).toContainEqual({ disallow: ['/'], userAgent: ['PerplexityBot'] }) + const assistants = rules.find((r) => Array.isArray(r.userAgent) && r.userAgent.includes('ClaudeBot')) + expect(assistants?.userAgent).not.toContain('PerplexityBot') + // the code-only handler ignores the panel + expect(helpers().robots().rules).not.toContainEqual({ disallow: ['/'], userAgent: ['PerplexityBot'] }) + }) + + test('under construction: sitemap and llms.txt list only the open pages', async () => { + await payload.updateGlobal({ slug: 'site-settings' as never, data: { construction: { enabled: true } } as never, locale: 'pl' as never }) + expect(await urls()).toEqual(['https://acme.pl/en', 'https://acme.pl/pl']) + const llms = await (await helpers().llmsRoute()).text() + expect(llms).not.toContain('o-nas') + await payload.updateGlobal({ slug: 'site-settings' as never, data: { construction: { enabled: false } } as never, locale: 'pl' as never }) + expect(await urls()).toHaveLength(4) + }) +}) diff --git a/test/seoSearch.test.ts b/test/seoSearch.test.ts new file mode 100644 index 0000000..bd5c2eb --- /dev/null +++ b/test/seoSearch.test.ts @@ -0,0 +1,311 @@ +import type { Config } from 'payload' + +import { afterEach, describe, expect, test, vi } from 'vitest' + +import type { I18nConfig } from '../src/modules/i18n/types.js' +import type { SitemapEntry } from '../src/modules/seo/buildSitemapEntries.js' + +import { buildLlmsTxt } from '../src/modules/seo/buildLlmsTxt.js' +import { buildMetadata } from '../src/modules/seo/buildMetadata.js' +import { AI_TRAINING_BOTS, buildRobots } from '../src/modules/seo/buildRobots.js' +import { buildSitemapEntries } from '../src/modules/seo/buildSitemapEntries.js' +import { buildSitemapIndexXml } from '../src/modules/seo/buildSitemapXml.js' +import { createPageMetadata } from '../src/modules/seo/createPageMetadata.js' +import { createLlmsTxtRoute, createSitemapRouteHandler, DEFAULT_SITEMAP_CACHE_CONTROL } from '../src/modules/seo/routeHandlers.js' +import { llmsIntroFrom, normalizeVerificationToken, robotsOptionsFrom, verificationFrom } from '../src/modules/seo/searchSettings.js' +import { collectSiteIndex } from '../src/modules/seo/siteIndex.js' +import { ipalKit } from '../src/plugin.js' + +const config: I18nConfig = { + defaultLocale: 'pl', + locales: [ + { code: 'pl', label: 'Polski' }, + { code: 'en', label: 'English' }, + ], +} +const single: I18nConfig = { defaultLocale: 'pl', locales: [{ code: 'pl', label: 'Polski' }] } + +type Rule = { allow?: string; disallow?: string[]; userAgent: string | string[] } + +afterEach(() => { + vi.restoreAllMocks() + vi.unstubAllEnvs() +}) + +describe('search verification (Site Settings → Search & AI)', () => { + test('keeps the code from a bare value or a pasted tag', () => { + expect(normalizeVerificationToken(' abc-123_XYZ ')).toBe('abc-123_XYZ') + expect(normalizeVerificationToken('')).toBe('Tok_9-x') + expect(normalizeVerificationToken("")).toBe('ABCDEF0123') + }) + + test('drops anything that is not a plain token', () => { + expect(normalizeVerificationToken('">')).toBe('') + expect(normalizeVerificationToken('two words')).toBe('') + expect(normalizeVerificationToken(42)).toBe('') + }) + + test('maps to Next Metadata.verification; empty group → undefined', () => { + expect(verificationFrom({ searchVerification: { bing: 'B1', google: 'G1', yandex: null } })).toEqual({ + google: 'G1', + other: { 'msvalidate.01': 'B1' }, + }) + expect(verificationFrom({ searchVerification: { bing: '', google: null } })).toBeUndefined() + expect(verificationFrom({})).toBeUndefined() + }) + + test('every page gets the tags from Site Settings', async () => { + const pageMetadata = createPageMetadata({ + baseUrl: 'https://acme.pl', + config, + loaders: { + getSettings: async () => ({ homepage: null, searchVerification: { google: 'G1' }, siteName: 'Acme' }), + resolveRoute: async () => null, + }, + }) + const metadata = await pageMetadata({ slug: ['x'], locale: 'pl', payload: {} as never }) + expect(metadata.verification).toEqual({ google: 'G1' }) + }) + + test('an unknown route is noindex', async () => { + const pageMetadata = createPageMetadata({ + config, + loaders: { getSettings: async () => ({ homepage: null, siteName: 'Acme' }), resolveRoute: async () => null }, + }) + const metadata = await pageMetadata({ slug: ['nope'], locale: 'pl', payload: {} as never }) + expect(metadata.robots?.index).toBe(false) + }) + + test('no verification → no key in metadata', () => { + const m = buildMetadata({ config, locale: 'pl', slugs: { pl: 'a' } }) + expect('verification' in m).toBe(false) + }) +}) + +describe('AI crawlers (robots)', () => { + test('panel policy and exceptions become buildRobots options; "default" changes nothing', () => { + expect(robotsOptionsFrom({ aiCrawlers: { policy: 'default', rules: [] } })).toEqual({}) + expect( + robotsOptionsFrom({ + aiCrawlers: { + policy: 'block-training', + rules: [ + { access: 'allow', userAgent: ' GPTBot ' }, + { access: 'disallow', userAgent: 'Evil\nDisallow: /' }, + { access: 'disallow', userAgent: 'Bad Bot' }, + ], + }, + }), + ).toEqual({ aiBotRules: [{ access: 'allow', userAgent: 'GPTBot' }], aiBots: 'block-training' }) + }) + + test('an exception takes the bot out of its policy group', () => { + const rules = buildRobots({ + aiBotRules: [ + { access: 'allow', userAgent: 'gptbot' }, + { access: 'disallow', userAgent: 'SomeNewBot' }, + ], + aiBots: 'block-training', + baseUrl: 'https://acme.pl', + }).rules as Rule[] + const training = rules.find((r) => Array.isArray(r.userAgent) && r.userAgent.includes(AI_TRAINING_BOTS[1])) + expect(training?.disallow).toEqual(['/']) + expect(training?.userAgent).not.toContain('GPTBot') + expect(rules).toContainEqual({ allow: '/', disallow: ['/admin', '/api'], userAgent: ['gptbot'] }) + expect(rules).toContainEqual({ disallow: ['/'], userAgent: ['SomeNewBot'] }) + }) + + test('exceptions still apply with aiBots: false', () => { + const rules = buildRobots({ aiBotRules: [{ access: 'disallow', userAgent: 'Bytespider' }], aiBots: false, baseUrl: 'https://acme.pl' }) + .rules as Rule[] + expect(rules).toHaveLength(2) + expect(rules[1]).toEqual({ disallow: ['/'], userAgent: ['Bytespider'] }) + }) + + test('IPAL_NOINDEX still wins over every exception', () => { + vi.stubEnv('IPAL_NOINDEX', '1') + const r = buildRobots({ aiBotRules: [{ access: 'allow', userAgent: 'GPTBot' }], baseUrl: 'https://acme.pl' }) + expect(r.rules).toEqual({ disallow: ['/'], userAgent: '*' }) + }) +}) + +/** Payload stub: `docs` per collection, served in pages of the requested limit. */ +function fakePayload(docs: Record[]>, opts: { drafts?: string[]; fields?: string[] } = {}) { + const find = vi.fn(async ({ collection, limit, page = 1 }: { collection: string; limit: number; page?: number }) => { + const all = docs[collection] ?? [] + const start = (page - 1) * limit + return { docs: all.slice(start, start + limit), hasNextPage: start + limit < all.length } + }) + const collections = Object.fromEntries( + Object.keys(docs).map((slug) => [ + slug, + { + config: { + flattenedFields: (opts.fields ?? ['slug', 'title', 'meta']).map((name) => ({ name })), + labels: { plural: slug }, + versions: opts.drafts?.includes(slug) ? { drafts: true } : false, + }, + }, + ]), + ) + return { collections, find, findGlobal: vi.fn(async () => ({})) } +} + +describe('buildSitemapEntries at scale', () => { + const pages = Array.from({ length: 1203 }, (_, i) => ({ + id: i, + slug: { en: `p${i}`, pl: `s${i}` }, + _status: 'published', + updatedAt: '2026-01-01T00:00:00.000Z', + })) + + test('reads in batches, published only, selected fields', async () => { + const payload = fakePayload({ pages }, { drafts: ['pages'], fields: ['slug', 'title', 'meta', 'noindex', 'layout'] }) + const entries = await buildSitemapEntries({ baseUrl: 'https://acme.pl', config, payload: payload as never }) + expect(entries).toHaveLength(1203 * 2) + expect(payload.find).toHaveBeenCalledTimes(3) + const args = payload.find.mock.calls[0][0] as unknown as Record + expect(args.limit).toBe(500) + expect(args.where).toEqual({ _status: { equals: 'published' } }) + expect(args.select).toEqual({ slug: true, _status: true, meta: true, noindex: true, updatedAt: true }) + }) + + test('custom images → whole documents (no select)', async () => { + const payload = fakePayload({ pages: pages.slice(0, 2) }) + await buildSitemapEntries({ baseUrl: 'https://acme.pl', config, images: () => [], payload: payload as never }) + const args = payload.find.mock.calls[0][0] as unknown as Record + expect(args.select).toBeUndefined() + expect(args.where).toBeUndefined() + }) +}) + +describe('sitemap route: split, cache, errors', () => { + const make = (n: number): SitemapEntry[] => + Array.from({ length: n }, (_, i) => ({ lastModified: `2026-01-${String((i % 28) + 1).padStart(2, '0')}T00:00:00.000Z`, url: `https://acme.pl/p${i}` })) + + test('small site: one urlset with the default Cache-Control', async () => { + const res = await createSitemapRouteHandler(async () => make(3), { style: false })(new Request('https://acme.pl/sitemap.xml')) + expect(res.headers.get('cache-control')).toBe(DEFAULT_SITEMAP_CACHE_CONTROL) + const xml = await res.text() + expect(xml).toContain('/g)).toHaveLength(3) + }) + + test('over maxUrls: an index, parts by ?part=N, unknown part 404', async () => { + const handler = createSitemapRouteHandler(async () => make(5), { maxUrls: 2, style: false }) + const index = await (await handler(new Request('https://acme.pl/sitemap.xml'))).text() + expect(index).toContain('/g)).toHaveLength(3) + expect(index).toContain('https://acme.pl/sitemap.xml?part=3') + expect(index).toContain('2026-01-02T00:00:00.000Z') + + const part = await (await handler(new Request('https://acme.pl/sitemap.xml?part=3'))).text() + expect(part.match(//g)).toHaveLength(1) + expect(part).toContain('https://acme.pl/p4') + expect((await handler(new Request('https://acme.pl/sitemap.xml?part=4'))).status).toBe(404) + expect((await handler(new Request('https://acme.pl/sitemap.xml?part=x'))).status).toBe(404) + }) + + test('entries are reused within memoSeconds, rebuilt when 0', async () => { + const source = vi.fn(async () => make(1)) + const memo = createSitemapRouteHandler(source, { style: false }) + await memo(new Request('https://acme.pl/sitemap.xml')) + await memo(new Request('https://acme.pl/sitemap.xml')) + expect(source).toHaveBeenCalledTimes(1) + + const fresh = vi.fn(async () => make(1)) + const noMemo = createSitemapRouteHandler(fresh, { memoSeconds: 0, style: false }) + await noMemo(new Request('https://acme.pl/sitemap.xml')) + await noMemo(new Request('https://acme.pl/sitemap.xml')) + expect(fresh).toHaveBeenCalledTimes(2) + }) + + test('runtime error → 503 Retry-After; empty → not cached and not reused', async () => { + vi.spyOn(console, 'warn').mockImplementation(() => {}) + const failing = await createSitemapRouteHandler(async () => { + throw new Error('db down') + })(new Request('https://acme.pl/sitemap.xml')) + expect(failing.status).toBe(503) + expect(failing.headers.get('retry-after')).toBe('300') + + const empty = vi.fn(async () => [] as SitemapEntry[]) + const handler = createSitemapRouteHandler(empty, { style: false }) + const res = await handler(new Request('https://acme.pl/sitemap.xml')) + expect(res.headers.get('cache-control')).toBe('no-store') + await handler(new Request('https://acme.pl/sitemap.xml')) + expect(empty).toHaveBeenCalledTimes(2) + }) + + test('during next build an error still gives an empty urlset', async () => { + vi.spyOn(console, 'warn').mockImplementation(() => {}) + vi.stubEnv('NEXT_PHASE', 'phase-production-build') + const res = await createSitemapRouteHandler(async () => { + throw new Error('no db') + })(new Request('https://acme.pl/sitemap.xml')) + expect(res.status).toBe(200) + expect(await res.text()).toContain(' { + expect(buildSitemapIndexXml([{ url: 'https://acme.pl/s.xml?a=1&b=2' }])).toContain('?a=1&b=2') + }) +}) + +describe('collectSiteIndex and llms.txt', () => { + const pages = Array.from({ length: 1205 }, (_, i) => ({ id: i, slug: `p${i}`, title: `Page ${i}` })) + + test('no silent 1000 cap; limit still caps', async () => { + const payload = fakePayload({ pages }) + expect(await collectSiteIndex({ config: single, payload: payload as never })).toHaveLength(1205) + expect(await collectSiteIndex({ config: single, limit: 10, payload: payload as never })).toHaveLength(10) + }) + + test('include filters by path', async () => { + const payload = fakePayload({ pages: pages.slice(0, 5) }) + const index = await collectSiteIndex({ config: single, include: (p) => p === '/p2', payload: payload as never }) + expect(index.map((e) => e.path)).toEqual(['/p2']) + }) + + test('llms.txt carries the editor note under the summary', async () => { + const payload = fakePayload({ pages: pages.slice(0, 1) }) + payload.findGlobal.mockResolvedValue({ llmsIntro: 'Acme repairs boilers in Kraków since 1998.', siteDescription: 'Boilers', siteName: 'Acme' }) + const body = await buildLlmsTxt({ baseUrl: 'https://acme.pl', config: single, payload: payload as never }) + expect(body.startsWith('# Acme\n\n> Boilers\n\nAcme repairs boilers in Kraków since 1998.\n')).toBe(true) + expect(llmsIntroFrom({ llmsIntro: ' ' })).toBe('') + }) + + test('llms route: only included paths, cached for a CDN', async () => { + const payload = fakePayload({ pages: pages.slice(0, 3) }) + const res = await createLlmsTxtRoute({ + baseUrl: 'https://acme.pl', + config: single, + getCachedPayload: async () => payload as never, + getIncludedPaths: async () => ['/p1/'], + })() + const body = await res.text() + expect(body).toContain('(https://acme.pl/p1)') + expect(body).not.toContain('/p0') + expect(res.headers.get('cache-control')).toBe(DEFAULT_SITEMAP_CACHE_CONTROL) + }) +}) + +describe('plugin: Search & AI tab', () => { + const base = (): Config => ({ collections: [{ slug: 'users', auth: true, fields: [] }], secret: 'test' }) as unknown as Config + const tabs = (c: Config) => { + const settings = c.globals?.find((g) => g.slug === 'site-settings') + const field = settings?.fields[0] as { tabs: { label: string }[] } + return field.tabs.map((t) => t.label) + } + + test('on by default, off with seo.searchSettings: false', async () => { + const on = await ipalKit({ access: { authCollection: 'users' }, i18n: config, twoFactor: false })(base()) + expect(tabs(on)).toContain('Search & AI') + const off = await ipalKit({ + access: { authCollection: 'users' }, + i18n: config, + seo: { collections: [], searchSettings: false }, + twoFactor: false, + })(base()) + expect(tabs(off)).not.toContain('Search & AI') + }) +}) From 1beb0edb7f9c4b47f6b085da68746529f8a9fa31 Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?Rados=C5=82aw=20Smoli=C5=84ski?= Date: Thu, 22 Oct 2026 17:09:44 +0200 Subject: [PATCH 10/27] RenderRichText neutralises unsafe link URLs (safeHref) Payload's link converter rendered fields.url as is; javascript:/data: URLs stored via import or API reached the href. They now become '#'. Co-Authored-By: Claude Opus 5.5 --- docs/richtext.md | 4 +++ docs/security.md | 3 +- src/modules/richtext/RenderRichText.tsx | 7 ++-- src/modules/richtext/sanitizeLinks.ts | 43 +++++++++++++++++++++++++ test/richTextLinks.test.ts | 30 +++++++++++++++++ 5 files changed, 84 insertions(+), 3 deletions(-) create mode 100644 src/modules/richtext/sanitizeLinks.ts create mode 100644 test/richTextLinks.test.ts diff --git a/docs/richtext.md b/docs/richtext.md index a4a9fd6..e40e821 100644 --- a/docs/richtext.md +++ b/docs/richtext.md @@ -53,6 +53,10 @@ const converters: JSXConvertersFunction = ({ defaultConverters }) => ({ Spread `defaultConverters` — nadpisujesz tylko te węzły, które chcesz. Reszta (listy, tabele, obrazy, linki) działa z oficjalnej obsługi Payload. +**Linki są filtrowane jak w `` (`safeHref`).** Własny link z adresem spoza `http(s)`, +`mailto`, `tel`, `sms`, `#`, `/` (np. `javascript:`, `data:`) dostaje `href="#"` — także gdy trafił +do bazy importem, seedem albo przez API, z pominięciem pola w panelu. + ## Spis treści i kotwice nagłówków (1.11.1) Długie dokumenty (polityka prywatności, regulamin) — spis treści z linkami do sekcji. diff --git a/docs/security.md b/docs/security.md index d0cafbb..fc23772 100644 --- a/docs/security.md +++ b/docs/security.md @@ -329,7 +329,8 @@ dostęp do danych, nie tylko UI. - Drafty nigdy nieopublikowane nie są już dostępne publicznie (`resolveRoute`, Markdown, MCP, metadata) ani na listach archiwów (`getArchiveEntries`). Podgląd: `resolveRoute({ draft: true })`, `getArchiveEntries({ draft: true })` w trybie `draftMode()`. -- Linki z CMS: tylko `http(s)`, `mailto`, `tel`, `sms`, `#`, `/` (`safeHref`); `javascript:` i `data:` odrzucane. +- Linki z CMS: tylko `http(s)`, `mailto`, `tel`, `sms`, `#`, `/` (`safeHref`); `javascript:` i `data:` odrzucane — + także w rich text (`RenderRichText` zamienia je na `#`). - ID analityki walidowane (panel i przed wysłaniem do przeglądarki). - Zgłoszenia formularzy: odczyt `editor+`; adresy z zakładki Emails niewidoczne publicznie. - Uploady: `buildUploadSecurityHeaders()` w `next.config.ts` (SVG nie uruchomi skryptu na domenie strony). diff --git a/src/modules/richtext/RenderRichText.tsx b/src/modules/richtext/RenderRichText.tsx index 709be2b..e29cf16 100644 --- a/src/modules/richtext/RenderRichText.tsx +++ b/src/modules/richtext/RenderRichText.tsx @@ -5,6 +5,7 @@ import { RichText as PayloadRichText } from '@payloadcms/richtext-lexical/react' import { cloneElement, isValidElement, type ReactElement, type ReactNode } from 'react' import { headingIds as computeHeadingIds, type HeadingLevel } from './headings.js' +import { sanitizeRichTextLinks } from './sanitizeLinks.js' export type RenderRichTextProps = { /** Wrapper class (e.g. Tailwind prose classes). */ @@ -96,8 +97,10 @@ function withHeadingIds( * // /client * */ -export function RenderRichText({ className, converters, data, headingIds }: RenderRichTextProps) { - if (!data) {return null} +export function RenderRichText({ className, converters, data: raw, headingIds }: RenderRichTextProps) { + if (!raw) {return null} + // javascript:/data: link URLs from stored content never reach an href + const data = sanitizeRichTextLinks(raw) if (headingIds) { const opts = headingIds === true ? {} : headingIds const ids = computeHeadingIds(data, opts.levels ? { levels: opts.levels } : {}) diff --git a/src/modules/richtext/sanitizeLinks.ts b/src/modules/richtext/sanitizeLinks.ts new file mode 100644 index 0000000..2efef1b --- /dev/null +++ b/src/modules/richtext/sanitizeLinks.ts @@ -0,0 +1,43 @@ +import { safeHref } from '../links/resolveLinkHref.js' + +type LexicalNode = { [key: string]: unknown; children?: unknown[]; fields?: { [key: string]: unknown; url?: unknown }; type?: string } + +/** + * Rich text with custom links whose URL isn't a safe target (`javascript:`, + * `data:`, "java\tscript:") gets them neutralised to '#' — the same rule as + * (safeHref). Payload's link converter renders `fields.url` as is, + * and stored content can come from imports, seeds or the API, not only the + * editor's link drawer. + * + * Returns the SAME object when nothing needed changing (no copy per render); + * otherwise only the path to each unsafe link is copied. + */ +export function sanitizeRichTextLinks(data: T): T { + return walk(data) as T +} + +function walk(value: unknown): unknown { + if (Array.isArray(value)) { + let changed = false + const next = value.map((item) => { + const out = walk(item) + if (out !== item) {changed = true} + return out + }) + return changed ? next : value + } + if (!value || typeof value !== 'object') {return value} + const node = value as LexicalNode + let result: LexicalNode = node + + if ((node.type === 'link' || node.type === 'autolink') && node.fields && node.fields.linkType !== 'internal') { + const url = typeof node.fields.url === 'string' ? node.fields.url : '' + if (url && safeHref(url) === null) {result = { ...node, fields: { ...node.fields, url: '#' } }} + } + for (const key of ['root', 'children'] as const) { + if (!(key in result)) {continue} + const out = walk(result[key]) + if (out !== result[key]) {result = { ...result, [key]: out }} + } + return result +} diff --git a/test/richTextLinks.test.ts b/test/richTextLinks.test.ts new file mode 100644 index 0000000..9329d1a --- /dev/null +++ b/test/richTextLinks.test.ts @@ -0,0 +1,30 @@ +import { describe, expect, test } from 'vitest' + +import { sanitizeRichTextLinks } from '../src/modules/richtext/sanitizeLinks.js' + +const link = (url: string, type = 'link', linkType = 'custom') => ({ type, children: [{ type: 'text', text: 'x' }], fields: { linkType, url } }) +const doc = (...nodes: object[]) => ({ root: { type: 'root', children: [{ type: 'paragraph', children: nodes }] } }) +const urls = (d: ReturnType) => + (d.root.children[0].children as { fields: { url: string } }[]).map((n) => n.fields.url) + +describe('rich text links', () => { + test.each(['javascript:alert(1)', ' JaVaScRiPt:alert(1)', 'java\tscript:alert(1)', 'data:text/html,', 'vbscript:x'])( + '%j is neutralised to #', + (bad) => { + expect(urls(sanitizeRichTextLinks(doc(link(bad), link(bad, 'autolink'))))).toEqual(['#', '#']) + }, + ) + + test('safe links are kept and an untouched document is returned as is', () => { + const d = doc(link('https://acme.pl'), link('/pl/kontakt'), link('mailto:a@acme.pl'), link('tel:+48123'), link('#faq')) + expect(sanitizeRichTextLinks(d)).toBe(d) + }) + + test('only the path to an unsafe link is copied; the input is not mutated', () => { + const d = doc(link('https://acme.pl'), link('javascript:alert(1)')) + const out = sanitizeRichTextLinks(d) + expect(urls(d)).toEqual(['https://acme.pl', 'javascript:alert(1)']) + expect(urls(out)).toEqual(['https://acme.pl', '#']) + expect(out.root.children[0].children[0]).toBe(d.root.children[0].children[0]) + }) +}) From 67e96553763f01ff570d147f1f0a631f554d4e1c Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?Rados=C5=82aw=20Smoli=C5=84ski?= Date: Thu, 22 Oct 2026 17:10:42 +0200 Subject: [PATCH 11/27] Hooks run Local API calls with req; cross-locale sync restores req.locale buildCrossLocaleFieldSync read other locales outside the save's transaction and its update(req) left req.locale on the last target locale. buildPreventDeleteSystemPage now reads Site Settings with req. Co-Authored-By: Claude Opus 5.5 --- docs/hooks.md | 5 ++ .../hooks/buildCrossLocaleFieldSync.ts | 8 ++++ src/modules/hooks/preventDeleteSystemPage.ts | 2 +- test/hooksReq.test.ts | 46 +++++++++++++++++++ 4 files changed, 60 insertions(+), 1 deletion(-) create mode 100644 test/hooksReq.test.ts diff --git a/docs/hooks.md b/docs/hooks.md index de1965c..a7b167e 100644 --- a/docs/hooks.md +++ b/docs/hooks.md @@ -89,6 +89,8 @@ import { buildPreventDeleteSystemPage } from '@intecion/ipal-kit' hooks: { beforeDelete: [buildPreventDeleteSystemPage({ settingsSlug: 'site-settings' })] } ``` +Site Settings czyta w tym samym `req` (transakcja usuwania). + Żeby usunąć — najpierw odłącz rolę w Site Settings (świadoma decyzja). --- @@ -184,6 +186,9 @@ hooks: { - **Tylko wypełnione pola** — wyczyszczenie obrazka w jednym języku nie zeruje go w innych (zachowawczo). - Guard `_ipalSyncingCrossLocale` zrywa pętlę `afterChange`→`update`. +- **W transakcji zapisu:** odczyt i zapis innych języków idą z `req` (Postgres/Mongo — rollback + obejmuje też synchronizację); `req.locale` / `req.fallbackLocale` wracają po hooku do wartości z + zapisu, więc odpowiedź API zostaje w języku redaktora. Parametry: `arrayField` (domyślnie `'layout'`), `guardFlag`. diff --git a/src/modules/hooks/buildCrossLocaleFieldSync.ts b/src/modules/hooks/buildCrossLocaleFieldSync.ts index 87bd2c6..54aadf4 100644 --- a/src/modules/hooks/buildCrossLocaleFieldSync.ts +++ b/src/modules/hooks/buildCrossLocaleFieldSync.ts @@ -103,6 +103,11 @@ export function buildCrossLocaleFieldSync( if (otherLocales.length === 0) {return doc} // single-locale site: nothing to sync const payload = req.payload + // Passing `req` keeps the reads and writes in the save's transaction, but + // the Local API sets req.locale / req.fallbackLocale to the call's locale — + // restored in `finally`, or the rest of the save (afterRead, the response) + // would run in the last target locale. + const { fallbackLocale, locale: requestLocale } = req reqAny[guardFlag] = true try { @@ -114,6 +119,7 @@ export function buildCrossLocaleFieldSync( collection: collection as never, depth: 0, locale: locale as never, + req, })) as Record } catch { continue // locale not yet created for this doc — nothing to sync into @@ -167,6 +173,8 @@ export function buildCrossLocaleFieldSync( payload.logger?.error?.({ err, msg: `[ipal] cross-locale ${arrayField} sync failed` }) } finally { reqAny[guardFlag] = false + req.locale = requestLocale + req.fallbackLocale = fallbackLocale } return doc diff --git a/src/modules/hooks/preventDeleteSystemPage.ts b/src/modules/hooks/preventDeleteSystemPage.ts index b6b7460..2f85ddd 100644 --- a/src/modules/hooks/preventDeleteSystemPage.ts +++ b/src/modules/hooks/preventDeleteSystemPage.ts @@ -25,7 +25,7 @@ export function buildPreventDeleteSystemPage( return async ({ id, req }) => { const settings = (await req.payload - .findGlobal({ slug: settingsSlug as never, depth: 0 }) + .findGlobal({ slug: settingsSlug as never, depth: 0, req }) .catch(() => null)) as null | Record if (!settings) {return} diff --git a/test/hooksReq.test.ts b/test/hooksReq.test.ts new file mode 100644 index 0000000..ff5540c --- /dev/null +++ b/test/hooksReq.test.ts @@ -0,0 +1,46 @@ +/** Hooks run their Local API calls inside the save's request (transaction) without corrupting it. */ +import { describe, expect, test, vi } from 'vitest' + +import { buildCrossLocaleFieldSync } from '../src/modules/hooks/buildCrossLocaleFieldSync.js' +import { buildPreventDeleteSystemPage } from '../src/modules/hooks/preventDeleteSystemPage.js' + +const config = { defaultLocale: 'pl', locales: [{ code: 'pl', label: 'PL' }, { code: 'en', label: 'EN' }] } + +/** Mimics the Local API: a call with `req` sets req.locale / req.fallbackLocale to its own. */ +function fakeReq() { + const req: Record = { fallbackLocale: 'pl', locale: 'pl' } + const adopt = (args: { locale?: string; req?: Record }) => { + if (args.req && args.locale) { + args.req.locale = args.locale + args.req.fallbackLocale = 'null' + } + } + const findByID = vi.fn(async (args: { locale?: string; req?: Record }) => { + adopt(args) + return { id: 1, layout: [{ id: 'r1', blockType: 'hero', image: 7 }] } + }) + const update = vi.fn(async (args: { locale?: string; req?: Record }) => { + adopt(args) + return {} + }) + req.payload = { findByID, findGlobal: vi.fn(async () => ({})), logger: { error: vi.fn() }, update } + return { findByID, req, update } +} + +describe('hooks pass req', () => { + test('cross-locale sync reads and writes in the request, then restores its locale', async () => { + const { findByID, req, update } = fakeReq() + const hook = buildCrossLocaleFieldSync({ collection: 'pages', config, fields: ['image'] }) + await hook({ doc: { id: 1, layout: [{ id: 'r1', blockType: 'hero', image: 9 }] }, req } as never) + expect(findByID).toHaveBeenCalledWith(expect.objectContaining({ locale: 'en', req })) + expect(update).toHaveBeenCalledWith(expect.objectContaining({ locale: 'en', req })) + expect(req.locale).toBe('pl') + expect(req.fallbackLocale).toBe('pl') + }) + + test('preventDeleteSystemPage reads Site Settings in the request', async () => { + const { req } = fakeReq() + await buildPreventDeleteSystemPage()({ id: 3, req } as never) + expect((req.payload as { findGlobal: ReturnType }).findGlobal).toHaveBeenCalledWith(expect.objectContaining({ req })) + }) +}) From 4c199acdfd104cc1a3161eb0194f0b63aee69f1f Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?Rados=C5=82aw=20Smoli=C5=84ski?= Date: Thu, 22 Oct 2026 17:11:13 +0200 Subject: [PATCH 12/27] Old-slug redirects skip never-published drafts Co-Authored-By: Claude Opus 5.5 --- docs/content.md | 3 ++- src/modules/content/resolveRedirect.ts | 6 +++++- test/redirectDrafts.test.ts | 25 +++++++++++++++++++++++++ 3 files changed, 32 insertions(+), 2 deletions(-) create mode 100644 test/redirectDrafts.test.ts diff --git a/docs/content.md b/docs/content.md index 563f53c..0b60a6b 100644 --- a/docs/content.md +++ b/docs/content.md @@ -221,7 +221,8 @@ Zwraca docelową ścieżkę (zlokalizowaną, z collapsowaniem home przez `homeSl albo `null`. Plugin tylko liczy — `permanentRedirect` woła projekt (plugin nie importuje `next/navigation`). Każda kolekcja bez pola historii jest pomijana bezpiecznie. `collections[].historyField` (domyślnie `'slugHistory'`) i -`slugField` (domyślnie `'slug'`) konfigurowalne. +`slugField` (domyślnie `'slug'`) konfigurowalne. Dokument nigdy nieopublikowany (`_status: 'draft'`) +nie przekierowuje — jego nowy slug nie wycieka przez redirect. Ograniczenia: tylko kolekcje „płaskie" (slug → ścieżka). Wpisy w archiwach (`/artykuly/`) nie są jeszcze obsługiwane. Jeśli `slug` jest `localized`, diff --git a/src/modules/content/resolveRedirect.ts b/src/modules/content/resolveRedirect.ts index 1343543..ac03f4b 100644 --- a/src/modules/content/resolveRedirect.ts +++ b/src/modules/content/resolveRedirect.ts @@ -34,7 +34,7 @@ type ResolveRedirectArgs = { segments: string[] | undefined } -type DocShape = { slug?: unknown } +type DocShape = { _status?: unknown; slug?: unknown } /** * Resolves a 301/308 destination for a URL that no longer matches any current @@ -90,6 +90,10 @@ export async function resolveRedirect({ where: { [`${historyField}.slug`]: { equals: oldSlug } } as never, }) const doc = (res?.docs?.[0] ?? null) as DocShape | null + // A never-published draft must not be reachable — nor its new slug + // revealed — through a redirect (same rule as resolveRoute). + const status = doc?._status + if (doc && status !== undefined && status !== null && status !== 'published') {continue} if (doc && typeof doc[slugField as keyof DocShape] === 'string') { currentSlug = doc[slugField as keyof DocShape] as string } diff --git a/test/redirectDrafts.test.ts b/test/redirectDrafts.test.ts new file mode 100644 index 0000000..0a228af --- /dev/null +++ b/test/redirectDrafts.test.ts @@ -0,0 +1,25 @@ +import type { BasePayload } from 'payload' + +import { describe, expect, test, vi } from 'vitest' + +import { resolveRedirect } from '../src/modules/content/resolveRedirect.js' + +const config = { defaultLocale: 'pl', locales: [{ code: 'pl', label: 'PL' }] } +const payloadWith = (doc: object) => ({ find: vi.fn(async () => ({ docs: [doc] })) }) as unknown as BasePayload + +describe('old-slug redirects and drafts', () => { + test('a published page redirects from its old slug', async () => { + const payload = payloadWith({ _status: 'published', slug: 'nowa-oferta' }) + expect(await resolveRedirect({ config, locale: 'pl', payload, segments: ['oferta'] })).toBe('/nowa-oferta') + }) + + test('a never-published draft does not redirect (its new slug stays private)', async () => { + const payload = payloadWith({ _status: 'draft', slug: 'tajny-projekt' }) + expect(await resolveRedirect({ config, locale: 'pl', payload, segments: ['oferta'] })).toBeNull() + }) + + test('collections without drafts still redirect', async () => { + const payload = payloadWith({ slug: 'kontakt-2' }) + expect(await resolveRedirect({ config, locale: 'pl', payload, segments: ['kontakt'] })).toBe('/kontakt-2') + }) +}) From dc761164d9909ef63d9202f7856a8ab753236d13 Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?Rados=C5=82aw=20Smoli=C5=84ski?= Date: Thu, 22 Oct 2026 17:13:57 +0200 Subject: [PATCH 13/27] SEO: project overrides (sitemapEntries, sitemapOptions, underConstructionSeo, searchSettings fn); seo-check follows sitemap index - createContentHelpers: sitemapEntries transform has the last word, sitemapOptions passes maxUrls/cacheControl/memoSeconds to sitemapRoute, underConstructionSeo: false turns the construction filter off - seo.searchSettings accepts a function over the default fields - ipal-seo-check: reads sitemap index parts, reports 503 sitemap, warns on missing Google/Bing verification (skip key: verification) - docs/seo.md updated Co-Authored-By: Claude Opus 5.5 --- docs/agent/skills/ipal-seo-check/SKILL.md | 13 +++++-- .../ipal-seo-check/scripts/seo-check.mjs | 34 ++++++++++++++++--- docs/seo.md | 18 ++++++++-- src/modules/frontend/createContentHelpers.ts | 31 +++++++++++++---- src/modules/seo/types.ts | 7 ++-- src/plugin.ts | 9 ++++- test/seoIntegration.test.ts | 14 ++++++++ test/seoSearch.test.ts | 9 +++++ 8 files changed, 117 insertions(+), 18 deletions(-) diff --git a/docs/agent/skills/ipal-seo-check/SKILL.md b/docs/agent/skills/ipal-seo-check/SKILL.md index 037ef1b..af5b1b6 100644 --- a/docs/agent/skills/ipal-seo-check/SKILL.md +++ b/docs/agent/skills/ipal-seo-check/SKILL.md @@ -1,6 +1,6 @@ --- name: ipal-seo-check -description: Checks a running ipal-kit site the way Googlebot and AI agents see it — metadata inside (not streamed to body), title, description, self canonical, hreflang with x-default, noindex pages leaking into the sitemap, error pages in the sitemap, robots.txt, soft 404s, favicon, JSON-LD, and GEO (llms.txt, llms-full.txt, Markdown version, text/markdown alternate, MCP server, AI bots in robots, health). Use after building pages, before handing over, after deploys, after an ipal-kit upgrade, and whenever SEO, indexing, Search Console or "Google doesn't see" problems come up. +description: Checks a running ipal-kit site the way Googlebot and AI agents see it — metadata inside (not streamed to body), title, description, self canonical, hreflang with x-default, noindex pages leaking into the sitemap, error pages in the sitemap, sitemap index parts, Search Console / Bing verification tags, robots.txt, soft 404s, favicon, JSON-LD, and GEO (llms.txt, llms-full.txt, Markdown version, text/markdown alternate, MCP server, AI bots in robots, health). Use after building pages, before handing over, after deploys, after an ipal-kit upgrade, and whenever SEO, indexing, Search Console or "Google doesn't see" problems come up. --- # ipal-seo-check @@ -31,11 +31,18 @@ Sprawdza **działającą** aplikację, nie kod — dokładnie to, co dostaje Goo | no JSON-LD structured data | brak `` / `` w `[locale]/layout.tsx` albo pusta nazwa w Site Settings | | `/llms.txt` / `/llms-full.txt` → 404 | brak trasy (`export { llmsRoute as GET }` / `llmsFullRoute` z `lib/content`) | | Markdown version `/md/…` → 404 | brak `src/app/md/[locale]/[[...slug]]/route.ts`; strona noindex/draft | +| `sitemap.xml → 503` | baza niedostępna przy budowaniu sitemapy (`sitemapRoute` zwraca 503 + Retry-After zamiast pustej) — sprawdź `DATABASE_URL` / zdrowie bazy | +| sitemap index parts not 200 | serwis > `maxUrls` (10 000) → `/sitemap.xml` to index; części `?part=N` muszą odpowiadać 200 — własna trasa bez obsługi `part` albo cache CDN ze starą liczbą części | | MCP not answering initialize | brak `src/app/api/mcp/route.ts` albo Cloudflare Access bez Bypass (mcp.md) | -3. `[WARNING]` oceń: brak opisu / zduplikowane tytuły to **treść w panelu** — +3. `no search-console verification meta tag` (WARNING) — wklej kod w **Site Settings → + Search & AI** (Google Search Console, Bing Webmaster). Weryfikacja przez DNS → dopisz + `verification` do `ipal-audit-skip:` w `AGENTS.md`. + `robots.txt blocks AI bots` — sprawdź też Site Settings → Search & AI → AI crawlers + (gdy projekt używa `getRobots`, redaktor mógł zmienić politykę). +4. `[WARNING]` oceń: brak opisu / zduplikowane tytuły to **treść w panelu** — uzupełnij z briefu albo wypisz w raporcie dla klienta. -4. Uruchom ponownie aż `0 error(s)`. +5. Uruchom ponownie aż `0 error(s)`. ## Czego skrypt nie sprawdzi Search Console (indeksacja, ręczne działania), Core Web Vitals, poprawność diff --git a/docs/agent/skills/ipal-seo-check/scripts/seo-check.mjs b/docs/agent/skills/ipal-seo-check/scripts/seo-check.mjs index 10e8d95..110341c 100644 --- a/docs/agent/skills/ipal-seo-check/scripts/seo-check.mjs +++ b/docs/agent/skills/ipal-seo-check/scripts/seo-check.mjs @@ -73,14 +73,30 @@ else { const sitemap = await get('/sitemap.xml') let urls = [] let hasAlternates = false -if (sitemap.res.status !== 200) report('ERROR', `sitemap.xml → ${sitemap.res.status}`, 'export sitemap from lib/content + force-dynamic') +const locs = (xml) => [...xml.matchAll(/\s*([^<\s]+)\s*<\/loc>/g)].map((m) => m[1].replace(/&/g, '&')) +if (sitemap.res.status === 503) report('ERROR', 'sitemap.xml → 503', 'the database was unreachable while building it (sitemapRoute answers 503 + Retry-After) — check DATABASE_URL / DB health') +else if (sitemap.res.status !== 200) report('ERROR', `sitemap.xml → ${sitemap.res.status}`, 'export sitemapRoute (or sitemap) from lib/content + force-dynamic') else { - urls = [...new Set([...sitemap.text.matchAll(/\s*([^<\s]+)\s*<\/loc>/g)].map((m) => m[1]))] - hasAlternates = /hreflang=/.test(sitemap.text) + let xml = sitemap.text + // Large sites: /sitemap.xml is a of parts (?part=N) — read every part. + if (/ null) + if (!r || r.res.status !== 200) broken.push(`${part} → ${r?.res.status ?? 'unreachable'}`) + else xml += r.text + } + console.log(`sitemap index: ${parts.length} part(s)`) + if (broken.length) report('ERROR', 'sitemap index parts not 200', 'every must answer 200 (seo.md → Duży serwis)', broken) + } + urls = [...new Set(locs(xml))] + hasAlternates = /hreflang=/.test(xml) if (urls.length === 0) report('ERROR', 'sitemap.xml is empty', 'DB unreachable at build without force-dynamic, or no published pages') const foreign = urls.filter((u) => !u.startsWith('http') || /localhost|127\.0\.0\.1/.test(u) !== /localhost|127\.0\.0\.1/.test(origin)) if (foreign.length) report('ERROR', 'sitemap URLs relative or on another host', 'NEXT_PUBLIC_SERVER_URL / baseUrl', foreign.slice(0, 5)) - if (/(\/404|\/500|not-found)(\/|<|$)/.test(sitemap.text)) report('ERROR', 'error pages listed in the sitemap', 'pages.md — 404 page is excluded by ID') + if (/(\/404|\/500|not-found)(\/|<|$)/.test(xml)) report('ERROR', 'error pages listed in the sitemap', 'pages.md — 404 page is excluded by ID') } // --- 4. sampled pages ----------------------------------------------------- @@ -209,6 +225,16 @@ if (issues.noLinks.length) report('WARNING', 'pages without internal links', 'li if (!skipped('jsonld') && issues.jsonLd.length) report('ERROR', 'no JSON-LD structured data', ' WebSite + Organization in [locale]/layout.tsx (AGENT.md §0b.4)', issues.jsonLd.slice(0, 5)) if (!skipped('markdown') && issues.mdAlt.length) report('WARNING', 'no text/markdown alternate link in head', 'createContentHelpers({ markdownAlternate: true }) (AGENT.md §0b.6)', issues.mdAlt.slice(0, 3)) +// --- 4b. Search Console / Bing verification (Site Settings → Search & AI) ---- +if (!skipped('verification') && sample.length) { + const page = await get(sample[0]).catch(() => null) + const head = page?.text.split(/<\/head>/i)[0] ?? '' + const missing = [['google-site-verification', 'Google Search Console'], ['msvalidate.01', 'Bing Webmaster Tools']] + .filter(([name]) => !new RegExp(`]+name="${name}"`, 'i').test(head)) + .map(([, label]) => label) + if (missing.length) report('WARNING', 'no search-console verification meta tag', 'paste the code in Site Settings → Search & AI (or verify by DNS and add `verification` to ipal-audit-skip)', missing) +} + // --- 5. 404 --------------------------------------------------------------- const firstLocale = [...byLocale.keys()].find((l) => l && l.length <= 5) ?? '' for (const path of [`/${firstLocale ? firstLocale + '/' : ''}ipal-seo-check-${Date.now()}`]) { diff --git a/docs/seo.md b/docs/seo.md index d588502..8a6d9bd 100644 --- a/docs/seo.md +++ b/docs/seo.md @@ -345,9 +345,21 @@ z każdego URL-a kilka linii): | `memoSeconds` | `300` | ile sekund proces trzyma zbudowaną listę (index i części nie budują jej od nowa); `0` = wyłączone | ```ts -createSitemapRouteHandler(sitemap, { maxUrls: 5000, memoSeconds: 0 }) +createContentHelpers({ …, sitemapOptions: { maxUrls: 5000, memoSeconds: 0 } }) // sitemapRoute +createSitemapRouteHandler(sitemap, { maxUrls: 5000, memoSeconds: 0 }) // własna trasa ``` +Ostatnie słowo ma projekt — `sitemapEntries` dostaje wpisy pluginu i zwraca listę do +publikacji (dodaj adresy własnych tras, usuń, ustaw `priority`): + +```ts +createContentHelpers({ …, + sitemapEntries: (entries) => [...entries, { url: `${origin}/kalkulator`, lastModified: new Date() }], +}) +``` + +Filtr „Under construction” w sitemapie i llms.txt wyłączasz `underConstructionSeo: false`. + Błąd bazy w runtime → **503 + `Retry-After: 300`** (crawler wróci), nie pusta sitemapa z 200 („strona nie ma podstron”). Pusta odpowiedź i błąd nigdy nie idą z cache. Wyjątek: `next build` (`NEXT_PHASE=phase-production-build`) dalej dostaje pustą, @@ -1236,7 +1248,9 @@ Oba tak samo dobre dla Google — to kwestia czytelności dla człowieka, nie SE ## Search & AI — weryfikacja Search Console, boty AI, notka llms.txt (1.13) Zakładka **Site Settings → Search & AI** (włączona domyślnie; puste pola nic nie -zmieniają; `ipalKit({ seo: { …, searchSettings: false } })` ją usuwa): +zmieniają; `ipalKit({ seo: { …, searchSettings: false } })` ją usuwa; funkcja +`searchSettings: (fields) => fields` dostaje pola pluginu i zwraca własne — dodaj, usuń, +zmień etykiety; nazwy `searchVerification` / `aiCrawlers` / `llmsIntro` czytają helpery): | Pole | Gdzie trafia | |---|---| diff --git a/src/modules/frontend/createContentHelpers.ts b/src/modules/frontend/createContentHelpers.ts index f4404a8..9ac9eae 100644 --- a/src/modules/frontend/createContentHelpers.ts +++ b/src/modules/frontend/createContentHelpers.ts @@ -11,7 +11,7 @@ import type { I18nConfig } from '../i18n/index.js' import type { LinkValue, NavItem, ResolvedLink, ResolveLinkHrefOptions, SystemLink } from '../links/index.js' import type { CreateMcpRouteArgs } from '../mcp/createMcpRoute.js' import type { FormNotificationTexts } from '../notifications/types.js' -import type { PageMetadata, RobotsOptions, RobotsRules, SitemapEntry, SitemapStyleOptions } from '../seo/index.js' +import type { PageMetadata, RobotsOptions, RobotsRules, SitemapEntry, SitemapRouteOptions, SitemapStyleOptions } from '../seo/index.js' import { getAnalyticsConfig } from '../analytics/getAnalyticsConfig.js' import { getConsentTexts } from '../consent/getConsentTexts.js' @@ -96,8 +96,19 @@ type CreateContentHelpersArgs = { * LocalBusiness from the Company global); `false` = none. */ siteJsonLd?: ((ctx: { baseUrl: string; locale: string; settings: Record }) => Promise[]> | Record[]) | false + /** + * Last word on the sitemap: gets the plugin's entries (after the construction + * filter) and returns the list to publish — add URLs from your own routes, + * drop or reorder some, set priority. Used by `sitemap` and `sitemapRoute`. + */ + sitemapEntries?: (entries: SitemapEntry[]) => Promise | SitemapEntry[] /** Image URLs of a document for the sitemap (Google Images). Default: its SEO share image. */ sitemapImages?: (doc: Record) => (null | string | undefined)[] + /** + * `sitemapRoute` behaviour: `maxUrls` (split into an index, default 10 000), + * `cacheControl` (string or false), `memoSeconds` (default 300, 0 = off). + */ + sitemapOptions?: Pick /** * Browser look of `sitemapRoute` (/sitemap.xml). Default: built-in style, * header "XML Sitemap", credit "Technology by Intecion.com". `false` = raw XML. @@ -105,6 +116,11 @@ type CreateContentHelpersArgs = { sitemapStyle?: false | SitemapStyleOptions /** Field with the AI summary (buildSummaryField) — llms.txt and MCP prefer it. */ summaryField?: string + /** + * While Site Settings → Under construction is on, the sitemap and llms.txt + * list only the pages still open. Default true; false lists everything. + */ + underConstructionSeo?: boolean } /** What an entry's own JSON-LD builder gets (PageJsonLdOptions.entries). */ @@ -182,9 +198,12 @@ export function createContentHelpers({ robots: robotsOptions, settingsSlug = 'site-settings', siteJsonLd, + sitemapEntries: transformSitemap, sitemapImages, + sitemapOptions, sitemapStyle, summaryField, + underConstructionSeo = true, }: CreateContentHelpersArgs) { const origin = baseUrl ?? process.env.NEXT_PUBLIC_SERVER_URL ?? '' const getCachedPayload = cache( @@ -447,9 +466,9 @@ export function createContentHelpers({ // Under construction: list only the pages visitors can still open — the // rest redirect to the homepage notice, which crawlers would index. const open = await constructionPaths() - if (!open) {return entries} - const allowed = new Set(open.map(normalizePath)) - return entries.filter((e) => allowed.has(normalizePath(pathOf(e.url)))) + const allowed = open ? new Set(open.map(normalizePath)) : null + const visible = allowed ? entries.filter((e) => allowed.has(normalizePath(pathOf(e.url)))) : entries + return transformSitemap ? await transformSitemap(visible) : visible } catch (error) { // At runtime a failure is an error (the sitemap route answers 503, so // crawlers retry) — an empty sitemap would read as "no pages". @@ -636,7 +655,7 @@ export function createContentHelpers({ * export { sitemapRoute as GET } from '@/lib/content' * export const dynamic = 'force-dynamic' */ - const sitemapRoute = createSitemapRouteHandler(sitemap, { style: sitemapStyle ?? {} }) + const sitemapRoute = createSitemapRouteHandler(sitemap, { ...sitemapOptions, style: sitemapStyle ?? {} }) const needI18n = (what: string): I18nConfig => { if (!i18n) {throw new Error(`[ipal] createContentHelpers: pass \`i18n\` to use ${what}.`)} @@ -737,7 +756,7 @@ export function createContentHelpers({ * null when the site is open or the setting can't be read. */ const constructionPaths = async (): Promise => { - if (!i18n) {return null} + if (!i18n || !underConstructionSeo) {return null} try { const mode = await getConstructionMode(i18n.defaultLocale) return mode.enabled ? mode.allowedPaths : null diff --git a/src/modules/seo/types.ts b/src/modules/seo/types.ts index bbcc8d6..be15a84 100644 --- a/src/modules/seo/types.ts +++ b/src/modules/seo/types.ts @@ -39,9 +39,12 @@ export type SeoOption = { /** * Site Settings → "Search & AI" tab: Search Console / Bing / Yandex * verification, AI crawler policy for robots.txt (getRobots), llms.txt note. - * On by default (empty fields change nothing); false removes the tab. + * On by default (empty fields change nothing); false removes the tab; a + * function gets the plugin's fields and returns the tab's fields (add, drop, + * relabel). Keep the field names the readers use (searchVerification, + * aiCrawlers, llmsIntro) or read your own fields in your routes. */ - searchSettings?: false + searchSettings?: ((defaults: Field[]) => Field[]) | false } /** diff --git a/src/plugin.ts b/src/plugin.ts index 6e04014..d42ec02 100644 --- a/src/plugin.ts +++ b/src/plugin.ts @@ -219,7 +219,14 @@ export const ipalKit = (options: IpalOptions): Plugin => { additionalFields: options.siteSettingsFields, ...(options.pages ? { constructionFields: buildConstructionFields(options.pages.slug) } : {}), ...(options.forms?.emailLayout ? { emailFields: emailSettingsFields } : {}), - ...(options.seo?.searchSettings === false ? {} : { searchFields: searchSettingsFields }), + ...(options.seo?.searchSettings === false + ? {} + : { + searchFields: + typeof options.seo?.searchSettings === 'function' + ? options.seo.searchSettings(searchSettingsFields) + : searchSettingsFields, + }), systemPageFields, }), buildSiteIntegrations({ additionalFields: options.integrationsFields }), diff --git a/test/seoIntegration.test.ts b/test/seoIntegration.test.ts index 498d916..53687d6 100644 --- a/test/seoIntegration.test.ts +++ b/test/seoIntegration.test.ts @@ -71,6 +71,18 @@ describe('SEO outputs against a real database', () => { expect(await urls()).toEqual(['https://acme.pl/en', 'https://acme.pl/en/about', 'https://acme.pl/pl', 'https://acme.pl/pl/o-nas']) }) + test('project overrides: sitemapEntries has the last word', async () => { + const h = createContentHelpers({ + baseUrl: 'https://acme.pl', + config: configPromise, + i18n, + sitemapEntries: (entries) => [...entries.filter((e) => !e.url.endsWith('/en')), { url: 'https://acme.pl/custom' }], + }) + const list = (await h.sitemap()).map((e) => e.url) + expect(list).toContain('https://acme.pl/custom') + expect(list).not.toContain('https://acme.pl/en') + }) + test('verification codes and AI crawler rules from Site Settings → Search & AI', async () => { await payload.updateGlobal({ slug: 'site-settings' as never, @@ -98,6 +110,8 @@ describe('SEO outputs against a real database', () => { expect(await urls()).toEqual(['https://acme.pl/en', 'https://acme.pl/pl']) const llms = await (await helpers().llmsRoute()).text() expect(llms).not.toContain('o-nas') + const unfiltered = createContentHelpers({ baseUrl: 'https://acme.pl', config: configPromise, i18n, underConstructionSeo: false }) + expect(await unfiltered.sitemap()).toHaveLength(4) await payload.updateGlobal({ slug: 'site-settings' as never, data: { construction: { enabled: false } } as never, locale: 'pl' as never }) expect(await urls()).toHaveLength(4) }) diff --git a/test/seoSearch.test.ts b/test/seoSearch.test.ts index bd5c2eb..2fa829e 100644 --- a/test/seoSearch.test.ts +++ b/test/seoSearch.test.ts @@ -307,5 +307,14 @@ describe('plugin: Search & AI tab', () => { twoFactor: false, })(base()) expect(tabs(off)).not.toContain('Search & AI') + const custom = await ipalKit({ + access: { authCollection: 'users' }, + i18n: config, + seo: { collections: [], searchSettings: (fields) => fields.filter((f) => 'name' in f && f.name !== 'llmsIntro') }, + twoFactor: false, + })(base()) + const settings = custom.globals?.find((g) => g.slug === 'site-settings') + const tab = (settings?.fields[0] as { tabs: { fields: { name?: string }[]; label: string }[] }).tabs.find((t) => t.label === 'Search & AI') + expect(tab?.fields.map((f) => f.name)).toEqual(['searchVerification', 'aiCrawlers']) }) }) From e5d86b8afe73fc970fb5d07c885a2505c2255403 Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?Rados=C5=82aw=20Smoli=C5=84ski?= Date: Thu, 22 Oct 2026 17:17:42 +0200 Subject: [PATCH 14/27] Promote to admin only on the first-register screen, not any first create An open sign-up on an empty collection would otherwise become admin. Co-Authored-By: Claude Opus 5.5 --- docs/access.md | 5 +++-- src/modules/access/rolesField.ts | 10 ++++++---- test/accessControl.test.ts | 10 +++++++--- 3 files changed, 16 insertions(+), 9 deletions(-) diff --git a/docs/access.md b/docs/access.md index b09b99d..ac066bb 100644 --- a/docs/access.md +++ b/docs/access.md @@ -19,8 +19,9 @@ Wstrzykuje pole `roles` (select hasMany, `saveToJWT`, tylko admin może nadawać i zmieniać role — także przy tworzeniu konta, więc otwarta rejestracja nie przepuści `roles: ['admin']`; nie-admin dostaje `defaultRole`) do wskazanej kolekcji. Ekran pierwszego użytkownika i Local API (seed) działają z `overrideAccess`, więc -pierwszego admina nadal da się utworzyć. **Pierwsze konto w kolekcji zawsze dostaje -`roles: ['admin']`** (hook pola), nawet gdy ekran pierwszego użytkownika nie pokazuje pola ról. Kolekcja należy do Ciebie +pierwszego admina nadal da się utworzyć. **Konto z ekranu „Create first user” +(`…/first-register` na pustej kolekcji) zawsze dostaje `roles: ['admin']`** (hook pola), nawet gdy ekran +nie pokazuje pola ról. Otwarta rejestracja (zwykłe `create`) na pustej kolekcji dostaje `defaultRole`. Kolekcja należy do Ciebie (create-payload-app) — plugin tylko dokłada pole. ## Co plugin zamyka sam diff --git a/src/modules/access/rolesField.ts b/src/modules/access/rolesField.ts index 1434b5d..d9621c1 100644 --- a/src/modules/access/rolesField.ts +++ b/src/modules/access/rolesField.ts @@ -15,9 +15,11 @@ import { ROLE_HIERARCHY } from './types.js' * Local API calls (seed scripts) run with overrideAccess, so they can still * create the first admin. * - * The very first account of the collection always becomes admin: the - * first-user screen may not show this field, and a site whose only account is - * a plain 'user' has nobody who can manage users, integrations or roles. + * The account made on Payload's "create first user" screen (POST + * …/first-register on an empty collection) always becomes admin: that screen + * may not show this field, and a site whose only account is a plain 'user' has + * nobody who can manage users, integrations or roles. An open sign-up (plain + * create) on an empty collection still gets `defaultRole`. */ export function buildRolesField(defaultRole: Role = 'user'): Field { return { @@ -36,7 +38,7 @@ export function buildRolesField(defaultRole: Role = 'user'): Field { hooks: { beforeChange: [ async ({ collection, operation, req, value }) => { - if (operation !== 'create' || !collection) {return value} + if (operation !== 'create' || !collection || !req.pathname?.endsWith('/first-register')) {return value} const { totalDocs } = await req.payload.count({ collection: collection.slug, overrideAccess: true, req }) return totalDocs === 0 ? ['admin'] : value }, diff --git a/test/accessControl.test.ts b/test/accessControl.test.ts index f07ce17..b348064 100644 --- a/test/accessControl.test.ts +++ b/test/accessControl.test.ts @@ -118,8 +118,8 @@ describe('forms collection: public read, editor+ write, Emails hidden from plain }) }) -describe('roles field: the first account becomes admin', () => { - const hook = async (totalDocs: number, value: string[]) => { +describe('roles field: the first-register account becomes admin', () => { + const hook = async (totalDocs: number, value: string[], pathname = '/api/users/first-register') => { const config = await ipalKit({ access: { authCollection: 'users' }, i18n, twoFactor: false })(empty()) const users = config.collections?.find((c) => c.slug === 'users') as CollectionConfig const roles = users.fields.find((f) => 'name' in f && f.name === 'roles') as { hooks?: { beforeChange?: ((a: unknown) => unknown)[] } } @@ -127,7 +127,7 @@ describe('roles field: the first account becomes admin', () => { return roles.hooks?.beforeChange?.[0]?.({ collection: { slug: 'users' }, operation: 'create', - req: { payload: { count } }, + req: { pathname, payload: { count } }, value, }) } @@ -139,4 +139,8 @@ describe('roles field: the first account becomes admin', () => { test('later accounts keep what access allowed', async () => { expect(await hook(1, ['user'])).toEqual(['user']) }) + + test('an open sign-up on an empty collection is not promoted', async () => { + expect(await hook(0, ['user'], '/api/users')).toEqual(['user']) + }) }) From 14fd2c497f35295e2f5f67851c06656f76d5d1a1 Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?Rados=C5=82aw=20Smoli=C5=84ski?= Date: Thu, 22 Oct 2026 17:17:42 +0200 Subject: [PATCH 15/27] Server entries no longer load 'use client' modules The main entry and next/middleware re-exported module barrels that also export React client components (LanguageSwitcher, AlternateLinks*, AccessibilityWidget), so payload.config, the CLI and the proxy bundle evaluated React UI. They now import concrete files; i18n client components moved to modules/i18n/client.ts. test/entryGraph guards it. Also lint fixes in tests added on this branch. Co-Authored-By: Claude Opus 5.5 --- src/exports/client.ts | 16 +++---- src/exports/next-middleware.ts | 8 ++-- src/index.ts | 33 ++++++--------- src/modules/consent/index.ts | 1 - src/modules/content/createSearchRoute.ts | 6 +-- src/modules/frontend/createContentHelpers.ts | 2 +- src/modules/i18n/client.ts | 11 +++++ src/modules/i18n/index.ts | 10 +---- src/modules/mcp/createMcpRoute.ts | 10 ++--- src/plugin.ts | 2 +- src/types.ts | 2 +- test/construction.test.ts | 4 +- test/entryGraph.test.ts | 44 ++++++++++++++++++++ test/hooksReq.test.ts | 2 +- test/rateLimit.test.ts | 2 +- test/redirectDrafts.test.ts | 6 +-- test/revalidateGlobals.test.ts | 2 +- test/settingsDepth.test.ts | 4 +- 18 files changed, 102 insertions(+), 63 deletions(-) create mode 100644 src/modules/i18n/client.ts create mode 100644 test/entryGraph.test.ts diff --git a/src/exports/client.ts b/src/exports/client.ts index 40ba644..bb0ba85 100644 --- a/src/exports/client.ts +++ b/src/exports/client.ts @@ -58,6 +58,14 @@ export { required, } from '../modules/forms/validators.js' export type { Rule } from '../modules/forms/validators.js' +export { + AlternateLinksProvider, + AlternateLinksUpdater, + LanguageSwitcher, + useAlternateLinks, + useSetAlternateLinks, +} from '../modules/i18n/client.js' +export type { AlternateLinks, LanguageSwitcherClassNames } from '../modules/i18n/client.js' // Pure i18n path helpers — no server/RSC deps, safe to import in client // components (e.g. a LanguageSwitcher that computes locale URLs on the client). export { @@ -67,14 +75,6 @@ export { switchLocalePath, } from '../modules/i18n/index.js' export type { I18nConfig, LocalizedSlugs } from '../modules/i18n/index.js' -export { - AlternateLinksProvider, - AlternateLinksUpdater, - LanguageSwitcher, - useAlternateLinks, - useSetAlternateLinks, -} from '../modules/i18n/index.js' -export type { AlternateLinks, LanguageSwitcherClassNames } from '../modules/i18n/index.js' export { LocaleView } from '../modules/pages/LocaleView.js' export { NotFoundLoader } from '../modules/pages/NotFoundLoader.js' export { TableOfContents } from '../modules/richtext/TableOfContents.js' diff --git a/src/exports/next-middleware.ts b/src/exports/next-middleware.ts index 93f50d3..bfa9e17 100644 --- a/src/exports/next-middleware.ts +++ b/src/exports/next-middleware.ts @@ -5,6 +5,8 @@ * client project's middleware.ts. Kept as a thin re-export so the Next-facing * surface is separate from the main package export. */ -export { createLocaleMiddleware, DEFAULT_MIDDLEWARE_MATCHER } from '../modules/i18n/index.js' -export type { LocaleMiddlewareResult } from '../modules/i18n/index.js' -export { createProxy, DEFAULT_PROXY_MATCHER } from '../modules/i18n/index.js' +// Concrete files, not the i18n barrel — it re-exports client components, which +// have no place in the proxy bundle (test/entryGraph). +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' diff --git a/src/index.ts b/src/index.ts index b801ebf..42b056c 100644 --- a/src/index.ts +++ b/src/index.ts @@ -13,8 +13,10 @@ export { requireRoleField, ROLE_HIERARCHY, } from './modules/access/index.js' -export { A11Y_COOKIE, A11Y_DEFAULT, a11yAttributes, parseA11y, serializeA11y } from './modules/accessibility/index.js' -export type { A11yState } from './modules/accessibility/index.js' +// Concrete files, not module barrels: a barrel that also re-exports 'use client' +// components would load React UI into payload.config / the CLI (test/entryGraph). +export { A11Y_COOKIE, A11Y_DEFAULT, a11yAttributes, parseA11y, serializeA11y } from './modules/accessibility/state.js' +export type { A11yState } from './modules/accessibility/state.js' 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' @@ -113,26 +115,15 @@ export { createContentHelpers } from './modules/frontend/index.js' // Healthcheck route (Coolify/Docker liveness with a real DB round-trip). export { createHealthRoute } from './modules/health/index.js' export { buildCrossLocaleFieldSync, buildGlobalRevalidateHook, buildPreventDeleteSystemPage, buildRevalidateHook, buildValidateUniqueRole, setPublishedAtHook, trackSlugHistoryHook } from './modules/hooks/index.js' +export { createProxy, DEFAULT_PROXY_MATCHER } from './modules/i18n/createProxy.js' +export { getLocalizedSlugs } from './modules/i18n/getLocalizedSlugs.js' +export { getDefaultLocale, getLocaleCodes, getLocaleDefinition, isValidLocale } from './modules/i18n/helpers.js' export type { I18nConfig, LocaleDefinition, LocalizedSlugs } from './modules/i18n/index.js' -export { - buildLocalizedPath, - getDefaultLocale, - getLocaleCodes, - getLocaleDefinition, - getLocalizedSlugs, - isValidLocale, - LOCALE_COOKIE_NAME, - matchAcceptLanguage, - negotiateLocale, - switchLocalePath, -} from './modules/i18n/index.js' -export type { LocaleMiddlewareResult } from './modules/i18n/index.js' -export { - createLocaleMiddleware, - DEFAULT_MIDDLEWARE_MATCHER, -} from './modules/i18n/index.js' -export { createProxy, DEFAULT_PROXY_MATCHER } from './modules/i18n/index.js' -export { resolveLocalized } from './modules/i18n/index.js' +export { createLocaleMiddleware, DEFAULT_MIDDLEWARE_MATCHER } from './modules/i18n/localeMiddleware.js' +export type { LocaleMiddlewareResult } from './modules/i18n/localeMiddleware.js' +export { buildLocalizedPath, switchLocalePath } from './modules/i18n/localizedPath.js' +export { LOCALE_COOKIE_NAME, matchAcceptLanguage, negotiateLocale } from './modules/i18n/negotiateLocale.js' +export { resolveLocalized } from './modules/i18n/resolveLocalized.js' export { buildIntegrationStatusBanner, buildIntegrationStatusField, recordIntegrationStatus } from './modules/integrations/index.js' export type { IntegrationState, IntegrationStatus } from './modules/integrations/index.js' export { buildLinkField, buildLinksField, homeSlugFrom, resolveLink, resolveLinkHref, resolveNav, resolveSystemLinks, safeHref } from './modules/links/index.js' diff --git a/src/modules/consent/index.ts b/src/modules/consent/index.ts index bc06c7e..b6265da 100644 --- a/src/modules/consent/index.ts +++ b/src/modules/consent/index.ts @@ -23,4 +23,3 @@ export { serializeConsent, } from './storage.js' export type { ConsentTexts } from './texts.js' -export { useIsMounted } from './useIsMounted.js' diff --git a/src/modules/content/createSearchRoute.ts b/src/modules/content/createSearchRoute.ts index 251a504..a236604 100644 --- a/src/modules/content/createSearchRoute.ts +++ b/src/modules/content/createSearchRoute.ts @@ -3,7 +3,7 @@ import type { BasePayload } from 'payload' import type { I18nConfig } from '../i18n/index.js' import type { ClientIpOptions } from '../shared/rateLimit.js' -import { type PathVisibility, pathOf } from '../construction/visibility.js' +import { pathOf, type PathVisibility } from '../construction/visibility.js' import { clientIp, consumeRateLimit, tooManyRequests } from '../shared/rateLimit.js' import { searchContent } from './searchContent.js' @@ -20,6 +20,8 @@ type CreateSearchRouteArgs = { getCachedPayload: () => Promise /** Home slug map/string so the home result collapses to root. */ homeSlug?: Record | string + /** Hide pages the site hides (construction mode) — pass `isPathVisible` from createContentHelpers. */ + isPathVisible?: PathVisibility /** * Per-IP limit (in memory per instance, or the store from setRateLimitStore). Default { max: 120, windowMs: 60_000 }. * `false` = off (a limiter in front, e.g. Cloudflare WAF rate limiting). @@ -27,8 +29,6 @@ type CreateSearchRouteArgs = { rateLimit?: { max?: number; windowMs?: number } | false /** Field holding a richer AI summary (buildSummaryField) to prefer as description. */ summaryField?: string - /** Hide pages the site hides (construction mode) — pass `isPathVisible` from createContentHelpers. */ - isPathVisible?: PathVisibility } /** diff --git a/src/modules/frontend/createContentHelpers.ts b/src/modules/frontend/createContentHelpers.ts index 1f730e4..25094e7 100644 --- a/src/modules/frontend/createContentHelpers.ts +++ b/src/modules/frontend/createContentHelpers.ts @@ -776,7 +776,6 @@ export function createContentHelpers({ getCachedPayload, getConfiguredLocales, getConstructionMode, - isPathVisible, getEntries, getFormTexts, getHomeSlug, @@ -789,6 +788,7 @@ export function createContentHelpers({ healthRoute, i18n, indexNowKeyRoute, + isPathVisible, llmsFullRoute, llmsRoute, manifest, diff --git a/src/modules/i18n/client.ts b/src/modules/i18n/client.ts new file mode 100644 index 0000000..86cf63c --- /dev/null +++ b/src/modules/i18n/client.ts @@ -0,0 +1,11 @@ +// Client components of the i18n module — kept out of ./index.ts so server +// code importing i18n helpers never loads React UI (test/entryGraph). +export { + AlternateLinksProvider, + useAlternateLinks, + useSetAlternateLinks, +} from './AlternateLinksContext.js' +export type { AlternateLinks } from './AlternateLinksContext.js' +export { AlternateLinksUpdater } from './AlternateLinksUpdater.js' +export { LanguageSwitcher } from './LanguageSwitcher.js' +export type { LanguageSwitcherClassNames } from './LanguageSwitcher.js' diff --git a/src/modules/i18n/index.ts b/src/modules/i18n/index.ts index f0436d6..bfa101f 100644 --- a/src/modules/i18n/index.ts +++ b/src/modules/i18n/index.ts @@ -1,15 +1,7 @@ -export { - AlternateLinksProvider, - useAlternateLinks, - useSetAlternateLinks, -} from './AlternateLinksContext.js' -export type { AlternateLinks } from './AlternateLinksContext.js' -export { AlternateLinksUpdater } from './AlternateLinksUpdater.js' +// Client components (LanguageSwitcher, AlternateLinks*) live in ./client.ts. export { createProxy, DEFAULT_PROXY_MATCHER } from './createProxy.js' export { getLocalizedSlugs } from './getLocalizedSlugs.js' export { getDefaultLocale, getLocaleCodes, getLocaleDefinition, isValidLocale } from './helpers.js' -export { LanguageSwitcher } from './LanguageSwitcher.js' -export type { LanguageSwitcherClassNames } from './LanguageSwitcher.js' export { createLocaleMiddleware, DEFAULT_MIDDLEWARE_MATCHER } from './localeMiddleware.js' export type { LocaleMiddlewareResult } from './localeMiddleware.js' export { buildLocalizationConfig } from './localizationConfig.js' diff --git a/src/modules/mcp/createMcpRoute.ts b/src/modules/mcp/createMcpRoute.ts index 0dd27a4..8046042 100644 --- a/src/modules/mcp/createMcpRoute.ts +++ b/src/modules/mcp/createMcpRoute.ts @@ -59,6 +59,11 @@ export type CreateMcpRouteArgs = { /** Archive-backed collections (same as the plugin option) for get_page. */ content?: ContentOption getCachedPayload: () => Promise + /** + * Hide pages the site hides (construction mode): filtered out of list_pages + * and search_content, "not found" in get_page. createContentHelpers passes it. + */ + isPathVisible?: PathVisibility /** Max messages in one JSON-RPC batch. Default 10. */ maxBatch?: number /** @@ -74,11 +79,6 @@ export type CreateMcpRouteArgs = { settingsSlug?: string /** Field holding a richer AI summary (buildSummaryField) to prefer in search results. */ summaryField?: string - /** - * Hide pages the site hides (construction mode): filtered out of list_pages - * and search_content, "not found" in get_page. createContentHelpers passes it. - */ - isPathVisible?: PathVisibility } type JsonRpcId = null | number | string diff --git a/src/plugin.ts b/src/plugin.ts index 2aaea8f..3a10e71 100644 --- a/src/plugin.ts +++ b/src/plugin.ts @@ -14,10 +14,10 @@ import { buildArchiveFields } from './modules/content/index.js' import { testEmailEndpoint } from './modules/email/test/testEmailEndpoint.js' import { emailSettingsFields } from './modules/forms/emailLayout.js' import { buildFormsPlugin } from './modules/forms/formsPluginConfig.js' +import { buildGlobalRevalidateHook } from './modules/hooks/buildRevalidateHook.js' import { buildLocalizationConfig, validateI18nConfig } from './modules/i18n/index.js' import { buildSystemPagesFields } from './modules/pages/index.js' import { buildSeoPlugin, injectAutoFillMeta, injectSeoTabs } from './modules/seo/index.js' -import { buildGlobalRevalidateHook } from './modules/hooks/buildRevalidateHook.js' import { buildIndexNowHook } from './modules/seo/indexNow.js' import { buildStatsCollection, buildStatsEndpoint } from './modules/stats/index.js' diff --git a/src/types.ts b/src/types.ts index fe646dd..5a48cae 100644 --- a/src/types.ts +++ b/src/types.ts @@ -12,10 +12,10 @@ export type TotpPluginFactory = (options: { forceSetup: boolean totp: { issuer: string } }) => Plugin -import type { RevalidatePathFn } from './modules/hooks/buildRevalidateHook.js' import type { AccessOption } from './modules/access/types.js' import type { ContentOption } from './modules/content/types.js' import type { FormsOption } from './modules/forms/types.js' +import type { RevalidatePathFn } from './modules/hooks/buildRevalidateHook.js' import type { I18nConfig } from './modules/i18n/types.js' import type { PagesOption } from './modules/pages/types.js' import type { SeoOption } from './modules/seo/types.js' diff --git a/test/construction.test.ts b/test/construction.test.ts index 7a23f1a..b1878c6 100644 --- a/test/construction.test.ts +++ b/test/construction.test.ts @@ -92,14 +92,14 @@ describe('under construction — Site Settings → createPageRoute', () => { const helpers = createContentHelpers({ baseUrl: 'https://acme.pl', config: configPromise, i18n }) expect((await helpers.getConstructionMode('pl')).enabled).toBe(true) - const md = (slug: string[]) => helpers.markdownRoute(new Request('https://acme.pl/md'), { params: Promise.resolve({ locale: 'pl', slug }) }) + const md = (slug: string[]) => helpers.markdownRoute(new Request('https://acme.pl/md'), { params: Promise.resolve({ slug, locale: 'pl' }) }) expect((await md(['o-nas'])).status).toBe(404) expect((await md(['brief'])).status).toBe(200) const rpc = async (name: string, args: Record) => { const res = await helpers.mcpPOST( new Request('https://acme.pl/api/mcp', { - body: JSON.stringify({ id: 1, jsonrpc: '2.0', method: 'tools/call', params: { arguments: args, name } }), + body: JSON.stringify({ id: 1, jsonrpc: '2.0', method: 'tools/call', params: { name, arguments: args } }), headers: { 'content-type': 'application/json', 'x-real-ip': '198.51.100.4' }, method: 'POST', }), diff --git a/test/entryGraph.test.ts b/test/entryGraph.test.ts new file mode 100644 index 0000000..e7d04e4 --- /dev/null +++ b/test/entryGraph.test.ts @@ -0,0 +1,44 @@ +/** + * The main entry (payload.config, the payload CLI, server code) and the proxy + * entry must not load 'use client' modules: in plain Node every re-exported + * module is evaluated, and the proxy bundle should stay free of React UI. + */ +import { existsSync, readFileSync } from 'node:fs' +import path from 'node:path' +import { describe, expect, test } from 'vitest' + +const root = path.resolve(import.meta.dirname, '..') + +function resolve(from: string, spec: string): null | string { + if (!spec.startsWith('.')) {return null} + const base = path.resolve(path.dirname(from), spec).replace(/\.js$/, '') + for (const ext of ['.ts', '.tsx', '/index.ts']) { + if (existsSync(base + ext)) {return base + ext} + } + return null +} + +/** Runtime (non-type) imports and re-exports reachable from `entry`; returns the 'use client' ones. */ +function clientModulesReachable(entry: string): string[] { + const seen = new Set() + const hits: string[] = [] + const stack = [path.join(root, entry)] + while (stack.length) { + const file = stack.pop()! + if (seen.has(file)) {continue} + seen.add(file) + const src = readFileSync(file, 'utf8') + if (/^\s*['"]use client['"]/.test(src)) {hits.push(path.relative(root, file))} + for (const m of src.matchAll(/^(?:import|export) (?!type\b)[^'"]*?from ['"]([^'"]+)['"]/gm)) { + const next = resolve(file, m[1]) + if (next) {stack.push(next)} + } + } + return hits.sort() +} + +describe('server entries load no client modules', () => { + test.each(['src/exports/next-middleware.ts', 'src/index.ts'])('%s', (entry) => { + expect(clientModulesReachable(entry)).toEqual([]) + }) +}) diff --git a/test/hooksReq.test.ts b/test/hooksReq.test.ts index ff5540c..362f6f0 100644 --- a/test/hooksReq.test.ts +++ b/test/hooksReq.test.ts @@ -4,7 +4,7 @@ import { describe, expect, test, vi } from 'vitest' import { buildCrossLocaleFieldSync } from '../src/modules/hooks/buildCrossLocaleFieldSync.js' import { buildPreventDeleteSystemPage } from '../src/modules/hooks/preventDeleteSystemPage.js' -const config = { defaultLocale: 'pl', locales: [{ code: 'pl', label: 'PL' }, { code: 'en', label: 'EN' }] } +const config = { defaultLocale: 'pl', locales: [{ code: 'pl', label: 'PL' }, { code: 'en', label: 'EN' }] } as const /** Mimics the Local API: a call with `req` sets req.locale / req.fallbackLocale to its own. */ function fakeReq() { diff --git a/test/rateLimit.test.ts b/test/rateLimit.test.ts index a5bf341..d727618 100644 --- a/test/rateLimit.test.ts +++ b/test/rateLimit.test.ts @@ -3,9 +3,9 @@ import { afterEach, describe, expect, test, vi } from 'vitest' import { checkRateLimit, clientIp, - UNKNOWN_IP_FACTOR, consumeRateLimit, setRateLimitStore, + UNKNOWN_IP_FACTOR, } from '../src/modules/shared/rateLimit.js' const req = (headers: Record) => new Request('http://x/', { headers }) diff --git a/test/redirectDrafts.test.ts b/test/redirectDrafts.test.ts index 0a228af..79575ff 100644 --- a/test/redirectDrafts.test.ts +++ b/test/redirectDrafts.test.ts @@ -4,17 +4,17 @@ import { describe, expect, test, vi } from 'vitest' import { resolveRedirect } from '../src/modules/content/resolveRedirect.js' -const config = { defaultLocale: 'pl', locales: [{ code: 'pl', label: 'PL' }] } +const config = { defaultLocale: 'pl', locales: [{ code: 'pl', label: 'PL' }] } as const const payloadWith = (doc: object) => ({ find: vi.fn(async () => ({ docs: [doc] })) }) as unknown as BasePayload describe('old-slug redirects and drafts', () => { test('a published page redirects from its old slug', async () => { - const payload = payloadWith({ _status: 'published', slug: 'nowa-oferta' }) + const payload = payloadWith({ slug: 'nowa-oferta', _status: 'published' }) expect(await resolveRedirect({ config, locale: 'pl', payload, segments: ['oferta'] })).toBe('/nowa-oferta') }) test('a never-published draft does not redirect (its new slug stays private)', async () => { - const payload = payloadWith({ _status: 'draft', slug: 'tajny-projekt' }) + const payload = payloadWith({ slug: 'tajny-projekt', _status: 'draft' }) expect(await resolveRedirect({ config, locale: 'pl', payload, segments: ['oferta'] })).toBeNull() }) diff --git a/test/revalidateGlobals.test.ts b/test/revalidateGlobals.test.ts index f1ff0d9..7f46200 100644 --- a/test/revalidateGlobals.test.ts +++ b/test/revalidateGlobals.test.ts @@ -5,7 +5,7 @@ import { afterEach, describe, expect, test, vi } from 'vitest' import { buildGlobalRevalidateHook } from '../src/modules/hooks/buildRevalidateHook.js' import { ipalKit } from '../src/plugin.js' -const i18n = { defaultLocale: 'pl', locales: [{ code: 'pl', label: 'Polski' }] } +const i18n = { defaultLocale: 'pl', locales: [{ code: 'pl', label: 'Polski' }] } as const const run = (g: GlobalConfig | undefined, context: object = {}) => g?.hooks?.afterChange?.forEach((h) => h({ context, doc: {}, global: g, previousDoc: {}, req: {} } as never)) diff --git a/test/settingsDepth.test.ts b/test/settingsDepth.test.ts index d66880b..fe6b392 100644 --- a/test/settingsDepth.test.ts +++ b/test/settingsDepth.test.ts @@ -51,12 +51,12 @@ beforeAll(async () => { const media = await payload.create({ collection: 'media' as never, data: { alt: 'hero' } as never, - file: { data: png, mimetype: 'image/png', name: 'hero.png', size: png.length }, + file: { name: 'hero.png', data: png, mimetype: 'image/png', size: png.length }, }) mediaId = media.id const home = await payload.create({ collection: 'pages' as never, data: { slug: 'home', hero: mediaId, title: 'Home' } as never }) const blog = await payload.create({ collection: 'pages' as never, data: { slug: 'blog', hero: mediaId, title: 'Blog' } as never }) - await payload.updateGlobal({ slug: 'site-settings' as never, data: { homepage: home.id, featured: home.id, postsArchive: blog.id, siteName: 'Acme' } as never }) + await payload.updateGlobal({ slug: 'site-settings' as never, data: { featured: home.id, homepage: home.id, postsArchive: blog.id, siteName: 'Acme' } as never }) }, 60_000) afterAll(async () => { From 104cdbfd4cc19d9a25cb6f91b39672ba59288473 Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?Rados=C5=82aw=20Smoli=C5=84ski?= Date: Thu, 22 Oct 2026 17:20:37 +0200 Subject: [PATCH 16/27] SEO: use construction/visibility pathOf (identical to security-perf branch) for the sitemap filter Co-Authored-By: Claude Opus 5.5 --- src/modules/construction/visibility.ts | 10 ++++++++++ src/modules/frontend/createContentHelpers.ts | 15 +++++---------- 2 files changed, 15 insertions(+), 10 deletions(-) create mode 100644 src/modules/construction/visibility.ts diff --git a/src/modules/construction/visibility.ts b/src/modules/construction/visibility.ts new file mode 100644 index 0000000..cdad4aa --- /dev/null +++ b/src/modules/construction/visibility.ts @@ -0,0 +1,10 @@ +/** + * Is this public page path served right now? createContentHelpers builds it from + * Site Settings → Under construction (`isPathVisible`), so the Markdown, MCP and + * search routes hide exactly what the page route hides. Paths are page paths as + * a visitor sees them ('/pl/o-nas', or '/o-nas' on a single-language site). + */ +export type PathVisibility = (path: string, locale: string) => boolean | Promise + +/** Pathname of a result URL (absolute or relative), for a PathVisibility check. */ +export const pathOf = (url: string): string => new URL(url, 'http://localhost').pathname diff --git a/src/modules/frontend/createContentHelpers.ts b/src/modules/frontend/createContentHelpers.ts index 9ac9eae..8800809 100644 --- a/src/modules/frontend/createContentHelpers.ts +++ b/src/modules/frontend/createContentHelpers.ts @@ -16,6 +16,7 @@ import type { PageMetadata, RobotsOptions, RobotsRules, SitemapEntry, SitemapRou import { getAnalyticsConfig } from '../analytics/getAnalyticsConfig.js' import { getConsentTexts } from '../consent/getConsentTexts.js' import { normalizePath } from '../construction/logic.js' +import { pathOf } from '../construction/visibility.js' import { createMarkdownRoute } from '../content/createMarkdownRenderer.js' import { getArchiveEntries, resolveRoute as resolveRouteRaw } from '../content/index.js' import { MARKDOWN_PREFIX, markdownHref } from '../content/markdownNegotiation.js' @@ -35,15 +36,6 @@ import { robotsOptionsFrom } from '../seo/searchSettings.js' import { type ThemeConfig, themeConfigFrom } from '../theme/theme.js' import { getTurnstileConfig } from '../turnstile/config.js' -/** Path of an absolute or relative URL: 'https://acme.pl/pl/o-nas' → '/pl/o-nas'. */ -const pathOf = (url: string): string => { - try { - return new URL(url, 'http://local').pathname - } catch { - return url - } -} - type CreateContentHelpersArgs = { /** * Absolute site origin for sitemap/robots URLs. Falls back to @@ -753,7 +745,10 @@ export function createContentHelpers({ /** * While Site Settings → Under construction is on: the paths still open (every * language), which the sitemap and llms.txt list instead of everything. - * null when the site is open or the setting can't be read. + * null when the site is open or the setting can't be read. Same rule as + * `isPathVisible`, but resolved ONCE per list: the sitemap may hold tens of + * thousands of URLs, and in a route handler React `cache` doesn't dedupe a + * per-URL settings read. */ const constructionPaths = async (): Promise => { if (!i18n || !underConstructionSeo) {return null} From b15e82546eff6d985983e5b53db7f29703a9a8bd Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?Rados=C5=82aw=20Smoli=C5=84ski?= Date: Thu, 22 Oct 2026 17:21:43 +0200 Subject: [PATCH 17/27] SEO: DNS domain verification is the default path; seo-check reports a missing verification tag as INFO only Co-Authored-By: Claude Opus 5.5 --- docs/agent/skills/ipal-seo-check/SKILL.md | 6 +++--- docs/agent/skills/ipal-seo-check/scripts/seo-check.mjs | 8 +++++--- docs/seo.md | 6 +++++- 3 files changed, 13 insertions(+), 7 deletions(-) diff --git a/docs/agent/skills/ipal-seo-check/SKILL.md b/docs/agent/skills/ipal-seo-check/SKILL.md index af5b1b6..aa8b912 100644 --- a/docs/agent/skills/ipal-seo-check/SKILL.md +++ b/docs/agent/skills/ipal-seo-check/SKILL.md @@ -35,9 +35,9 @@ Sprawdza **działającą** aplikację, nie kod — dokładnie to, co dostaje Goo | sitemap index parts not 200 | serwis > `maxUrls` (10 000) → `/sitemap.xml` to index; części `?part=N` muszą odpowiadać 200 — własna trasa bez obsługi `part` albo cache CDN ze starą liczbą części | | MCP not answering initialize | brak `src/app/api/mcp/route.ts` albo Cloudflare Access bez Bypass (mcp.md) | -3. `no search-console verification meta tag` (WARNING) — wklej kod w **Site Settings → - Search & AI** (Google Search Console, Bing Webmaster). Weryfikacja przez DNS → dopisz - `verification` do `ipal-audit-skip:` w `AGENTS.md`. +3. `no verification meta tag` (INFO — nie liczy się do błędów ani ostrzeżeń) — przy + weryfikacji domeny przez DNS (zalecana) to poprawny stan, nic nie rób. Tylko przy + weryfikacji „prefiks URL” wklej kod w **Site Settings → Search & AI**. `robots.txt blocks AI bots` — sprawdź też Site Settings → Search & AI → AI crawlers (gdy projekt używa `getRobots`, redaktor mógł zmienić politykę). 4. `[WARNING]` oceń: brak opisu / zduplikowane tytuły to **treść w panelu** — diff --git a/docs/agent/skills/ipal-seo-check/scripts/seo-check.mjs b/docs/agent/skills/ipal-seo-check/scripts/seo-check.mjs index 110341c..c736e73 100644 --- a/docs/agent/skills/ipal-seo-check/scripts/seo-check.mjs +++ b/docs/agent/skills/ipal-seo-check/scripts/seo-check.mjs @@ -29,7 +29,8 @@ let warnings = 0 const findings = [] const report = (level, title, rule, items = []) => { if (level === 'ERROR') errors += Math.max(items.length, 1) - else warnings += Math.max(items.length, 1) + else if (level === 'WARNING') warnings += Math.max(items.length, 1) + // INFO: shown, never counted — a note, not a problem findings.push({ level, title, rule, items }) } const get = async (path, opts = {}) => { @@ -225,14 +226,15 @@ if (issues.noLinks.length) report('WARNING', 'pages without internal links', 'li if (!skipped('jsonld') && issues.jsonLd.length) report('ERROR', 'no JSON-LD structured data', ' WebSite + Organization in [locale]/layout.tsx (AGENT.md §0b.4)', issues.jsonLd.slice(0, 5)) if (!skipped('markdown') && issues.mdAlt.length) report('WARNING', 'no text/markdown alternate link in head', 'createContentHelpers({ markdownAlternate: true }) (AGENT.md §0b.6)', issues.mdAlt.slice(0, 3)) -// --- 4b. Search Console / Bing verification (Site Settings → Search & AI) ---- +// --- 4b. Search Console / Bing verification tags (Site Settings → Search & AI) ---- +// INFO only: domain (DNS) verification — the recommended route — leaves the tags empty. if (!skipped('verification') && sample.length) { const page = await get(sample[0]).catch(() => null) const head = page?.text.split(/<\/head>/i)[0] ?? '' const missing = [['google-site-verification', 'Google Search Console'], ['msvalidate.01', 'Bing Webmaster Tools']] .filter(([name]) => !new RegExp(`]+name="${name}"`, 'i').test(head)) .map(([, label]) => label) - if (missing.length) report('WARNING', 'no search-console verification meta tag', 'paste the code in Site Settings → Search & AI (or verify by DNS and add `verification` to ipal-audit-skip)', missing) + if (missing.length) report('INFO', 'no verification meta tag (fine with DNS / domain verification)', 'only for URL-prefix verification: paste the code in Site Settings → Search & AI', missing) } // --- 5. 404 --------------------------------------------------------------- diff --git a/docs/seo.md b/docs/seo.md index 8a6d9bd..458b88f 100644 --- a/docs/seo.md +++ b/docs/seo.md @@ -1266,6 +1266,10 @@ Console — zapisuje się tylko kod; coś, co nie jest prostym tokenem, jest odr dodają `verification` same — zero kodu w projekcie. Własny generator: `verificationFrom(settings)` → `Metadata.verification`; robots: `robotsOptionsFrom(settings)`. +**Weryfikacja domeny przez DNS (zalecana)** — rekord TXT u rejestratora, plugin nic +nie robi, pola weryfikacji zostają puste i nic nie ostrzega. Pola są tylko dla +weryfikacji „prefiks URL” (tag HTML). + Po wklejeniu kodu: Search Console → Zweryfikuj. Strona musi być zbudowana dynamicznie albo po rewalidacji (ISR), żeby nowy tag był w HTML. Weryfikacja DNS dalej działa niezależnie — pola zostaw puste. @@ -1277,7 +1281,7 @@ Migracja: nowe kolumny w `site_settings` — projekt na Postgresie generuje migr Kliknięcia/zapytania z Search Console w adminie wymagają konta usługi Google (JSON z kluczem prywatnym) dodanego jako użytkownik w usłudze GSC, i biblioteki `googleapis` -albo podpisu JWT. Plugin tego (jeszcze) nie robi — dane czytasz w samej Search Console. +albo podpisu JWT. Plugin tego nie robi (decyzja: weryfikacja domeny, dane w samej Search Console). ## GEO — co plugin rozumie przez „widoczność w AI” (założenia) From da3a0c9a85bc20680f72a31e13254713bcf8df0e Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?Rados=C5=82aw=20Smoli=C5=84ski?= Date: Thu, 22 Oct 2026 17:22:02 +0200 Subject: [PATCH 18/27] SEO docs: DNS verification notes in English Co-Authored-By: Claude Opus 5.5 --- docs/agent/skills/ipal-seo-check/SKILL.md | 6 +++--- docs/seo.md | 6 +++--- 2 files changed, 6 insertions(+), 6 deletions(-) diff --git a/docs/agent/skills/ipal-seo-check/SKILL.md b/docs/agent/skills/ipal-seo-check/SKILL.md index aa8b912..ec2e2b6 100644 --- a/docs/agent/skills/ipal-seo-check/SKILL.md +++ b/docs/agent/skills/ipal-seo-check/SKILL.md @@ -35,9 +35,9 @@ Sprawdza **działającą** aplikację, nie kod — dokładnie to, co dostaje Goo | sitemap index parts not 200 | serwis > `maxUrls` (10 000) → `/sitemap.xml` to index; części `?part=N` muszą odpowiadać 200 — własna trasa bez obsługi `part` albo cache CDN ze starą liczbą części | | MCP not answering initialize | brak `src/app/api/mcp/route.ts` albo Cloudflare Access bez Bypass (mcp.md) | -3. `no verification meta tag` (INFO — nie liczy się do błędów ani ostrzeżeń) — przy - weryfikacji domeny przez DNS (zalecana) to poprawny stan, nic nie rób. Tylko przy - weryfikacji „prefiks URL” wklej kod w **Site Settings → Search & AI**. +3. `no verification meta tag` (INFO — not counted as an error or warning) — with domain + verification by DNS (recommended) this is the correct state; do nothing. Only for + URL-prefix verification, paste the code in **Site Settings → Search & AI**. `robots.txt blocks AI bots` — sprawdź też Site Settings → Search & AI → AI crawlers (gdy projekt używa `getRobots`, redaktor mógł zmienić politykę). 4. `[WARNING]` oceń: brak opisu / zduplikowane tytuły to **treść w panelu** — diff --git a/docs/seo.md b/docs/seo.md index 458b88f..d6be7a4 100644 --- a/docs/seo.md +++ b/docs/seo.md @@ -1266,9 +1266,9 @@ Console — zapisuje się tylko kod; coś, co nie jest prostym tokenem, jest odr dodają `verification` same — zero kodu w projekcie. Własny generator: `verificationFrom(settings)` → `Metadata.verification`; robots: `robotsOptionsFrom(settings)`. -**Weryfikacja domeny przez DNS (zalecana)** — rekord TXT u rejestratora, plugin nic -nie robi, pola weryfikacji zostają puste i nic nie ostrzega. Pola są tylko dla -weryfikacji „prefiks URL” (tag HTML). +**Domain verification by DNS (recommended)** — a TXT record at the registrar. It needs +nothing from the plugin: leave the verification fields empty, and nothing warns. The +fields are only for URL-prefix verification (HTML tag). Po wklejeniu kodu: Search Console → Zweryfikuj. Strona musi być zbudowana dynamicznie albo po rewalidacji (ISR), żeby nowy tag był w HTML. Weryfikacja DNS dalej działa From a87742621adff978019ef380d133a67f20d737b3 Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?Rados=C5=82aw=20Smoli=C5=84ski?= Date: Thu, 22 Oct 2026 17:23:14 +0200 Subject: [PATCH 19/27] Access defaults overridable; unlock admin-only; 2FA target validated - access.authAccess merges over the injected auth collection's access; unlock is admin-only by default - access.firstUserAdmin (default true) makes the first-register promotion optional - globalOverrides: object merges access/admin/hooks, function takes over - form Emails protection is applied before formOverrides.fields, so a project can change it there - 2FA defaults to admin.user and fails at init when the target is not an auth collection or differs from admin.user (twoFactor.allowCollectionMismatch) - buildRolesField, injectRoles, applyGlobalOverrides exported Co-Authored-By: Claude Opus 5.5 --- docs/access.md | 102 +++++++++++++++++------- docs/security.md | 10 ++- src/globals/overrides.ts | 44 +++++++++++ src/index.ts | 4 + src/modules/access/injectRoles.ts | 2 +- src/modules/access/rolesField.ts | 27 ++++--- src/modules/access/types.ts | 16 ++++ src/modules/forms/formsPluginConfig.ts | 10 ++- src/plugin.ts | 56 +++++++++---- src/types.ts | 23 +++++- test/accessControl.test.ts | 105 +++++++++++++++++++++++-- 11 files changed, 334 insertions(+), 65 deletions(-) create mode 100644 src/globals/overrides.ts diff --git a/docs/access.md b/docs/access.md index ac066bb..64617ac 100644 --- a/docs/access.md +++ b/docs/access.md @@ -9,39 +9,63 @@ predykaty oraz gotowe funkcje dostępu (collection-level i field-level). ```ts ipalKit({ access: { - authCollection: 'users', // slug Twojej kolekcji auth - // defaultRole: 'user', // rola nowych użytkowników, domyślnie 'user' + authCollection: 'users', // slug Twojej kolekcji auth (wymagane) + // defaultRole: 'user', // rola nowych kont + // firstUserAdmin: true, // konto z „Create first user” → admin + // authAccess: { … }, // access wstrzykniętej kolekcji auth (Twoje klucze wygrywają) + }, + // globalOverrides: { … }, // access / admin / hooks / pola globali pluginu +}) +``` + +| Opcja | Domyślnie | Co robi | +|---|---|---| +| `access.authCollection` | — (wymagane) | kolekcja auth, do której trafia pole `roles` | +| `access.defaultRole` | `'user'` | rola nowego konta, gdy nie nadał jej admin | +| `access.firstUserAdmin` | `true` | konto z ekranu „Create first user” (`…/first-register` na pustej kolekcji) dostaje `['admin']`, nawet gdy formularz wybrał `user`; `false` = dostaje to, co wysłano | +| `access.authAccess` | patrz tabela niżej | `access` **wstrzykniętej** kolekcji auth, scalany z domyślnym (Twoje klucze wygrywają) | +| `globalOverrides` | — | zmiana globali pluginu: obiekt scala `access` / `admin` / `hooks` (Twoje klucze wygrywają), funkcja `(global) => global` przejmuje całość | + +Pole `roles` (select hasMany, wymagane, `saveToJWT`): odczyt bez ograniczeń, nadawanie i +zmiana tylko przez admina — także przy tworzeniu konta, więc otwarta rejestracja nie +przepuści `roles: ['admin']`. Ekran pierwszego użytkownika i Local API (seed) działają z +`overrideAccess`. Konto bez ról nie spełnia żadnego progu (nawet `'user'`); `authenticated` +sprawdza tylko zalogowanie. + +**Kolekcja auth, gdy projekt jej nie ma.** Plugin dokłada minimalną kolekcję (`auth: true`, +`admin.useAsTitle: 'email'`) o slugu `access.authCollection` (albo `twoFactor.collectionSlug`, +`admin.user`, `'users'`). Własna kolekcja projektu o tym slugu zawsze wygrywa w całości. + +## Co plugin zamyka sam + +| Zasób | Odczyt | Zapis | Jak zmienić | +|---|---|---|---| +| kolekcja auth **wstrzyknięta** przez plugin, z rolami | admin: wszyscy; inni: tylko siebie | `create` / `delete` / `unlock`: admin; `update`: admin albo siebie | `access.authAccess`, albo własna kolekcja | +| Site Settings, Cookie Settings, Notifications | publiczny | `editor+` | `globalOverrides` | +| Site Integrations | admin | admin | `globalOverrides` | +| Forms | publiczny (zakładka Emails tylko `editor+`) | `editor+` | `forms.formOverrides.access`, pole Emails w `formOverrides.fields` | +| Form submissions | `editor+` | REST `create`: zalogowani; `delete`: admin | `forms.formSubmissionOverrides.access` | + +```ts +import { authenticated } from '@intecion/ipal-kit' +ipalKit({ + access: { authCollection: 'users', authAccess: { read: authenticated } }, // edytorzy widzą listę kont + globalOverrides: { + notifications: { access: { update: authenticated } }, // każdy zalogowany edytuje teksty + 'site-settings': (g) => ({ ...g, admin: { ...g.admin, group: 'Ustawienia' } }), }, }) ``` -Wstrzykuje pole `roles` (select hasMany, `saveToJWT`, tylko admin może -nadawać i zmieniać role — także przy tworzeniu konta, więc otwarta rejestracja nie -przepuści `roles: ['admin']`; nie-admin dostaje `defaultRole`) do wskazanej kolekcji. -Ekran pierwszego użytkownika i Local API (seed) działają z `overrideAccess`, więc -pierwszego admina nadal da się utworzyć. **Konto z ekranu „Create first user” -(`…/first-register` na pustej kolekcji) zawsze dostaje `roles: ['admin']`** (hook pola), nawet gdy ekran -nie pokazuje pola ról. Otwarta rejestracja (zwykłe `create`) na pustej kolekcji dostaje `defaultRole`. Kolekcja należy do Ciebie -(create-payload-app) — plugin tylko dokłada pole. - -## Co plugin zamyka sam - -| Zasób | Odczyt | Zapis | -|---|---|---| -| kolekcja auth **wstrzyknięta** przez plugin (gdy projekt nie ma własnej) i z rolami | admin: wszyscy; inni: tylko siebie | `create`/`delete`: admin; `update`: admin albo siebie | -| Site Settings, Cookie Settings, Notifications | publiczny | `editor+` | -| Site Integrations | admin | admin | -| Forms | publiczny (bez zakładki Emails — ta tylko `editor+`) | `editor+` | -| Form submissions | `editor+` | REST `create`: zalogowani; `delete`: admin | - Własna kolekcja auth projektu zachowuje własne `access` — plugin dokłada tylko pole -`roles`. Ustaw jej co najmniej `update: adminOrSelf`, `delete: adminOnly`, `create: adminOnly`: -domyślny Payload pozwala każdemu zalogowanemu zmienić e-mail i hasło innego konta. -Kolekcja wstrzyknięta **bez** `access` (brak ról) zostaje przy domyślnych regułach Payloada — -bez ról wszystkie konta są równe. +`roles`. Ustaw jej co najmniej `update: adminOrSelf`, `delete: adminOnly`, `create: adminOnly`, +`unlock: adminOnly`: domyślny Payload pozwala każdemu zalogowanemu zmienić e-mail i hasło +innego konta i odblokować dowolne konto. Kolekcja wstrzyknięta **bez** `access` (brak ról) +zostaje przy domyślnych regułach Payloada — bez ról wszystkie konta są równe. -> Po dodaniu: zadbaj, by seed / pierwszy user miał `roles: ['admin']`, inaczej -> stracisz dostęp do zasobów admin-only (np. SiteIntegrations). +> **Bez `access` nie ma pola `roles`**, więc `isAdmin` zawsze zwraca `false`: global Site +> Integrations i endpoint `/api/ipal/test-email` działają wtedy tylko przez Local API +> (`overrideAccess`). Seed / pierwszy user musi mieć `roles: ['admin']`. ## Predykaty (front / hooki / access) @@ -98,3 +122,27 @@ import { adminOnlyField, adminOrEditorField, requireRoleField } from '@intecion/ import { ROLE_HIERARCHY } from '@intecion/ipal-kit' // ['user', 'editor', 'admin'] — wyższa rola spełnia wymóg niższej ``` + +## Klocki: buildRolesField, injectRoles, applyGlobalOverrides + +```ts +import { applyGlobalOverrides, buildRolesField, injectRoles } from '@intecion/ipal-kit' + +buildRolesField('user', { firstUserAdmin: true }) // samo pole roles — do własnej kolekcji +injectRoles(config, { authCollection: 'members' }) // dołóż pole do kolekcji w gotowym configu +applyGlobalOverrides(globals, { notifications: { … } }) // ta sama logika co opcja globalOverrides +``` + +Typy: `AccessOption`, `Role`, `GlobalOverride`, `GlobalOverrides`, `IpalGlobalSlug`. + +## Wyłączenie, nadpisanie, rozszerzenie + +- **Wyłączenie:** pomiń `access` — brak pola `roles`, kolekcja auth zostaje przy regułach Payloada + (albo Twoich). `access.firstUserAdmin: false` wyłącza nadawanie admina pierwszemu kontu. +- **Nadpisanie:** `access.authAccess` (kolekcja wstrzyknięta), własna kolekcja auth (wygrywa w całości), + `globalOverrides` (globale), `forms.formOverrides` / `formSubmissionOverrides` (formularze), + `defaultRole`. Hierarchia ról (`ROLE_HIERARCHY`) jest stała. +- **Rozszerzenie:** `requireRole` / `requireRoleField`, predykaty, `buildRolesField`, `injectRoles`, + `applyGlobalOverrides` we własnych kolekcjach i globalach. +- **Sprawdzenie:** zaloguj się kontem `user` → `PATCH /api/globals/site-settings` = 403, + `DELETE /api/users/` = 403; konto z „Create first user” ma rolę `admin`. diff --git a/docs/security.md b/docs/security.md index fc23772..2ae8e6b 100644 --- a/docs/security.md +++ b/docs/security.md @@ -274,7 +274,8 @@ ipalKit({ twoFactor: { issuer: 'Nazwa Firmy', // pokazywane w aplikacji authenticator plugin: payloadTotp, // ← WSTRZYKNIJ — patrz niżej dlaczego - // collectionSlug: 'users', // domyślnie kolekcja auth: access.authCollection → admin.user → 'users' + // collectionSlug: 'users', // domyślnie kolekcja logowania do panelu (admin.user, inaczej pierwsza kolekcja auth) + // allowCollectionMismatch: true, // tylko świadomie: 2FA na innej kolekcji niż admin.user }, }) ``` @@ -340,8 +341,11 @@ dostęp do danych, nie tylko UI. - Wstrzyknięta kolekcja auth z rolami: konto `user` czyta i edytuje tylko siebie, tworzy i usuwa tylko admin. Wcześniej każdy zalogowany mógł zmienić e-mail/hasło admina. -- 2FA bez `collectionSlug` wrapuje kolekcję, którą faktycznie się logujesz (`access.authCollection`, - potem `admin.user`), a nie literał `'users'` — inaczej TOTP po cichu nie działał. +- 2FA bez `collectionSlug` wrapuje kolekcję logowania do panelu (`admin.user`, inaczej pierwszą kolekcję + auth), a nie literał `'users'`. Start pluginu kończy się błędem `[ipal] twoFactor…`, gdy cel nie jest + kolekcją auth albo różni się od `admin.user` — świadomy wyjątek: `twoFactor.allowCollectionMismatch: true`. +- Kolekcja auth wstrzyknięta z rolami: także `unlock` tylko dla admina. Wszystko nadpiszesz: + `access.authAccess`, `access.firstUserAdmin: false`, `globalOverrides`, `forms.formOverrides`. - Site Settings, Cookie Settings, Notifications i kolekcja Forms: zapis tylko `editor+`; zakładka Emails formularza (odbiorcy, BCC) czytelna tylko dla `editor+`. - Pełna tabela: [access.md](./access.md#co-plugin-zamyka-sam). diff --git a/src/globals/overrides.ts b/src/globals/overrides.ts new file mode 100644 index 0000000..3e68d58 --- /dev/null +++ b/src/globals/overrides.ts @@ -0,0 +1,44 @@ +import type { GlobalConfig } from 'payload' + +/** Slugs of the globals the plugin adds. */ +export type IpalGlobalSlug = 'cookie-settings' | 'notifications' | 'site-integrations' | 'site-settings' + +/** + * A project's change to one plugin global: + * - 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 (label, fields, …) replaces the plugin's value; + * - a function gets the plugin's global and returns the one to use — full + * control, e.g. dropping a plugin hook or appending fields. + */ +export type GlobalOverride = ((global: GlobalConfig) => GlobalConfig) | Partial + +export type GlobalOverrides = Partial> + +type Hooks = NonNullable + +function mergeHooks(base: GlobalConfig['hooks'], extra: GlobalConfig['hooks']): GlobalConfig['hooks'] { + if (!extra) {return base} + const out: Record = { ...(base as Record) } + for (const [key, list] of Object.entries(extra)) { + out[key] = [...(out[key] ?? []), ...((list as unknown[]) ?? [])] + } + return out as Hooks +} + +/** Applies `globalOverrides` to the plugin's globals. */ +export function applyGlobalOverrides(globals: GlobalConfig[], overrides: GlobalOverrides | undefined): GlobalConfig[] { + if (!overrides) {return globals} + return globals.map((global) => { + const override = overrides[global.slug as IpalGlobalSlug] + if (!override) {return global} + if (typeof override === 'function') {return override(global)} + return { + ...global, + ...override, + access: { ...global.access, ...override.access }, + admin: { ...global.admin, ...override.admin }, + hooks: mergeHooks(global.hooks, override.hooks), + } + }) +} diff --git a/src/index.ts b/src/index.ts index 42b056c..0659f34 100644 --- a/src/index.ts +++ b/src/index.ts @@ -6,7 +6,9 @@ export { adminOrEditorField, adminOrSelf, authenticated, + buildRolesField, hasMinimumRole, + injectRoles, isAdmin, isEditor, requireRole, @@ -231,3 +233,5 @@ export { getTurnstileConfig } from './modules/turnstile/config.js' export type { TurnstileConfig } from './modules/turnstile/config.js' export { ipalKit } from './plugin.js' export type { IpalOptions } from './types.js' +export { applyGlobalOverrides } from './globals/overrides.js' +export type { GlobalOverride, GlobalOverrides, IpalGlobalSlug } from './globals/overrides.js' diff --git a/src/modules/access/injectRoles.ts b/src/modules/access/injectRoles.ts index 040588c..438564c 100644 --- a/src/modules/access/injectRoles.ts +++ b/src/modules/access/injectRoles.ts @@ -12,7 +12,7 @@ import { buildRolesField } from './rolesField.js' * stack, so no conflict handling is needed — the field is simply added. */ export function injectRoles(config: Config, access: AccessOption): Config { - const rolesField = buildRolesField(access.defaultRole) + const rolesField = buildRolesField(access.defaultRole, { firstUserAdmin: access.firstUserAdmin }) return { ...config, diff --git a/src/modules/access/rolesField.ts b/src/modules/access/rolesField.ts index d9621c1..fd58410 100644 --- a/src/modules/access/rolesField.ts +++ b/src/modules/access/rolesField.ts @@ -19,9 +19,10 @@ import { ROLE_HIERARCHY } from './types.js' * …/first-register on an empty collection) always becomes admin: that screen * may not show this field, and a site whose only account is a plain 'user' has * nobody who can manage users, integrations or roles. An open sign-up (plain - * create) on an empty collection still gets `defaultRole`. + * create) on an empty collection still gets `defaultRole`. `firstUserAdmin: + * false` turns this off. */ -export function buildRolesField(defaultRole: Role = 'user'): Field { +export function buildRolesField(defaultRole: Role = 'user', { firstUserAdmin = true }: { firstUserAdmin?: boolean } = {}): Field { return { name: 'roles', type: 'select', @@ -35,15 +36,19 @@ export function buildRolesField(defaultRole: Role = 'user'): Field { }, defaultValue: [defaultRole], hasMany: true, - hooks: { - beforeChange: [ - async ({ collection, operation, req, value }) => { - if (operation !== 'create' || !collection || !req.pathname?.endsWith('/first-register')) {return value} - const { totalDocs } = await req.payload.count({ collection: collection.slug, overrideAccess: true, req }) - return totalDocs === 0 ? ['admin'] : value - }, - ], - }, + ...(firstUserAdmin + ? { + hooks: { + beforeChange: [ + async ({ collection, operation, req, value }) => { + if (operation !== 'create' || !collection || !req.pathname?.endsWith('/first-register')) {return value} + const { totalDocs } = await req.payload.count({ collection: collection.slug, overrideAccess: true, req }) + return totalDocs === 0 ? ['admin'] : value + }, + ], + }, + } + : {}), options: ROLE_HIERARCHY.map((role) => ({ label: role.charAt(0).toUpperCase() + role.slice(1), value: role, diff --git a/src/modules/access/types.ts b/src/modules/access/types.ts index b78da05..ecba3b5 100644 --- a/src/modules/access/types.ts +++ b/src/modules/access/types.ts @@ -1,3 +1,5 @@ +import type { CollectionConfig } from 'payload' + /** * Role hierarchy, lowest to highest privilege. * A higher role satisfies any requirement met by a lower one. @@ -14,8 +16,22 @@ export type Role = (typeof ROLE_HIERARCHY)[number] * role definition belongs to the plugin. */ export type AccessOption = { + /** + * Access for the auth collection the plugin INJECTS when the project has none + * (a project's own collection keeps its own access untouched). Merged over the + * plugin's defaults — admin manages everyone, others only themselves: + * `{ create: adminOnly, delete: adminOnly, read: adminOrSelf, unlock: adminOnly, update: adminOrSelf }`. + * Your keys win, e.g. `{ read: authenticated }` to let editors list accounts. + */ + authAccess?: CollectionConfig['access'] /** Slug of the client's auth collection, e.g. 'users'. */ authCollection: string /** Role assigned to new users. Defaults to 'user'. */ defaultRole?: Role + /** + * The account made on Payload's "create first user" screen gets + * `roles: ['admin']`, whatever the form preselected. Default true; + * `false` = that account gets what was submitted (`defaultRole` by default). + */ + firstUserAdmin?: boolean } diff --git a/src/modules/forms/formsPluginConfig.ts b/src/modules/forms/formsPluginConfig.ts index eab94a4..7997c1a 100644 --- a/src/modules/forms/formsPluginConfig.ts +++ b/src/modules/forms/formsPluginConfig.ts @@ -35,7 +35,9 @@ const staffAccess = ({ req }: AccessArgs) => hasMinimumRole(req.user as never, ' /** * Forms stay publicly readable (their fields render the form), but the Emails * tab — recipient addresses, templates — is for editors and admins only, so - * GET /api/forms doesn't hand out the company's inboxes to spammers. + * GET /api/forms doesn't hand out the company's inboxes to spammers. Applied to + * the default fields BEFORE formOverrides.fields sees them, so a project can + * still change the rule there. */ function hideEmails(fields: Field[]): Field[] { return fields.map((field) => @@ -117,8 +119,10 @@ export function buildFormsPlugin(forms: FormsOption): Plugin { ...forms.formOverrides?.access, }, admin: { ...group, ...forms.formOverrides?.admin }, - fields: ({ defaultFields }) => - hideEmails(forms.formOverrides?.fields ? forms.formOverrides.fields({ defaultFields }) : defaultFields), + fields: ({ defaultFields }) => { + const protectedFields = hideEmails(defaultFields) + return forms.formOverrides?.fields ? forms.formOverrides.fields({ defaultFields: protectedFields }) : protectedFields + }, }, formSubmissionOverrides: { labels: { plural: 'Submissions', singular: 'Submission' }, diff --git a/src/plugin.ts b/src/plugin.ts index 3a10e71..036efce 100644 --- a/src/plugin.ts +++ b/src/plugin.ts @@ -8,6 +8,7 @@ import { buildNotifications } from './globals/Notifications/index.js' import { buildSiteIntegrations } from './globals/SiteIntegrations/index.js' import { buildSiteSettings } from './globals/SiteSettings/index.js' import { adminOnly, adminOrSelf, injectRoles } from './modules/access/index.js' +import { applyGlobalOverrides } from './globals/overrides.js' import { buildConsentLogCollection, buildConsentLogEndpoint } from './modules/consent/consentLog.js' import { buildConstructionFields } from './modules/construction/fields.js' import { buildArchiveFields } from './modules/content/index.js' @@ -68,8 +69,9 @@ export const ipalKit = (options: IpalOptions): Plugin => { 'users' // With roles on it (access.authCollection), the injected collection is // locked down: Payload's default lets ANY logged-in account read, edit - // (email, password) or delete every other account — a plain 'user' could - // take over an admin. Admins manage everyone; others only themselves. + // (email, password), unlock or delete every other account — a plain 'user' + // could take over an admin. Admins manage everyone; others only themselves. + // access.authAccess overrides any of it; a project's own collection wins whole. if (!(config.collections ?? []).some((c) => c.slug === authSlug)) { const hasRoles = options.access?.authCollection === authSlug config.collections = [ @@ -77,7 +79,16 @@ export const ipalKit = (options: IpalOptions): Plugin => { { slug: authSlug, ...(hasRoles - ? { access: { create: adminOnly, delete: adminOnly, read: adminOrSelf, update: adminOrSelf } } + ? { + access: { + create: adminOnly, + delete: adminOnly, + read: adminOrSelf, + unlock: adminOnly, + update: adminOrSelf, + ...options.access?.authAccess, + }, + } : {}), admin: { useAsTitle: 'email' }, auth: true, @@ -122,12 +133,30 @@ export const ipalKit = (options: IpalOptions): Plugin => { ) } - // Default to the resolved auth collection (access.authCollection / - // admin.user), not a literal 'users': wrapping a slug nobody logs in with - // leaves the real collection without TOTP fields, and the TOTP access - // wrapper lets users without those fields through — 2FA silently off. + // TOTP must wrap the collection people log in to the panel with + // (admin.user, else Payload's pick: the first auth collection). Wrapping + // another slug leaves the real one without TOTP fields, and the TOTP + // access wrapper lets users without those fields through — 2FA silently + // off. So: default to it, and refuse a target that isn't an auth + // collection, or differs from it unless allowCollectionMismatch says so. + const authSlugs = (config.collections ?? []).filter((c) => c.auth).map((c) => c.slug) + const adminSlug = config.admin?.user ?? authSlugs[0] ?? authSlug + const target = tf.collectionSlug ?? adminSlug + if (!authSlugs.includes(target)) { + throw new Error( + `[ipal] twoFactor: "${target}" is not an auth collection, so 2FA would protect nothing. ` + + `Auth collections: ${authSlugs.join(', ') || 'none'}. Fix twoFactor.collectionSlug.`, + ) + } + if (target !== adminSlug && !tf.allowCollectionMismatch) { + throw new Error( + `[ipal] twoFactor wraps "${target}" but the admin panel logs in with "${adminSlug}" ` + + '(admin.user) — those accounts would skip 2FA. Point twoFactor.collectionSlug at ' + + `"${adminSlug}", or pass twoFactor.allowCollectionMismatch: true if that is deliberate.`, + ) + } config = await totp({ - collection: tf.collectionSlug ?? authSlug, + collection: target, forceSetup: true, // ENFORCED — every user must set up TOTP; no opt-out totp: { issuer: tf.issuer }, })(config) @@ -243,12 +272,11 @@ export const ipalKit = (options: IpalOptions): Plugin => { ] // A global feeds every page's layout — revalidate the site on save. const revalidateGlobal = options.revalidatePath ? buildGlobalRevalidateHook({ revalidatePath: options.revalidatePath }) : null - config.globals = [ - ...(config.globals ?? []), - ...(revalidateGlobal - ? pluginGlobals.map((g) => ({ ...g, hooks: { ...g.hooks, afterChange: [...(g.hooks?.afterChange ?? []), revalidateGlobal] } })) - : pluginGlobals), - ] + const withRevalidate = revalidateGlobal + ? pluginGlobals.map((g) => ({ ...g, hooks: { ...g.hooks, afterChange: [...(g.hooks?.afterChange ?? []), revalidateGlobal] } })) + : pluginGlobals + // The project's globalOverrides win (access, admin, hooks merged; a function = full control). + config.globals = [...(config.globals ?? []), ...applyGlobalOverrides(withRevalidate, options.globalOverrides)] config.endpoints = [...(config.endpoints ?? []), testEmailEndpoint] diff --git a/src/types.ts b/src/types.ts index 5a48cae..4ec9941 100644 --- a/src/types.ts +++ b/src/types.ts @@ -12,6 +12,7 @@ export type TotpPluginFactory = (options: { forceSetup: boolean totp: { issuer: string } }) => Plugin +import type { GlobalOverrides } from './globals/overrides.js' import type { AccessOption } from './modules/access/types.js' import type { ContentOption } from './modules/content/types.js' import type { FormsOption } from './modules/forms/types.js' @@ -89,6 +90,15 @@ export type IpalOptions = { */ pages?: PagesOption + /** + * Change any of the plugin's globals (site-settings, site-integrations, + * cookie-settings, notifications): an object merges over the plugin's + * (`access` / `admin` / `hooks` key by key, your keys win), a function gets + * the global and returns the one to use. E.g. let any logged-in user edit + * Notifications: `{ notifications: { access: { update: authenticated } } }`. + */ + globalOverrides?: GlobalOverrides + /** * next/cache `revalidatePath`, INJECTED (the plugin never imports next/cache). * When given, saving any of the plugin's globals (Site Settings, Site @@ -129,7 +139,18 @@ export type IpalOptions = { */ twoFactor?: | { - /** Auth collection slug. Defaults to 'users'. */ + /** + * Let `collectionSlug` differ from the panel's login collection + * (admin.user). Off by default: a mismatch means panel users skip 2FA, + * so the plugin refuses to start. Set true only when you protect a + * second auth collection on purpose. + */ + allowCollectionMismatch?: boolean + /** + * Auth collection TOTP wraps. Default: the panel's login collection — + * admin.user, else the first auth collection (with the one the plugin + * injects). Must be an auth collection. + */ collectionSlug?: CollectionSlug /** Name shown in the authenticator app (e.g. company/site name). */ issuer: string diff --git a/test/accessControl.test.ts b/test/accessControl.test.ts index b348064..bf48848 100644 --- a/test/accessControl.test.ts +++ b/test/accessControl.test.ts @@ -70,14 +70,46 @@ describe('2FA wraps the auth collection people log in with', () => { expect(plugin).toHaveBeenCalledWith(expect.objectContaining({ collection: 'staff' })) }) - test('an explicit collectionSlug still wins', async () => { + const twoAuth = () => + empty({ + admin: { user: 'admins' }, + collections: [ + { slug: 'admins', auth: true, fields: [] }, + { slug: 'users', auth: true, fields: [] }, + { slug: 'pages', fields: [] }, + ], + } as Partial) + + test('admin.user wins over access.authCollection as the default target', async () => { + const plugin = totp() + await ipalKit({ access: { authCollection: 'users' }, i18n, twoFactor: { issuer: 'A', plugin: plugin as never } })(twoAuth()) + expect(plugin).toHaveBeenCalledWith(expect.objectContaining({ collection: 'admins' })) + }) + + test('a target other than the panel login collection fails at init…', async () => { + const plugin = totp() + await expect( + ipalKit({ i18n, twoFactor: { collectionSlug: 'users', issuer: 'A', plugin: plugin as never } })(twoAuth()), + ).rejects.toThrow(/admin panel logs in with "admins"/) + }) + + test('…unless allowCollectionMismatch says it is deliberate', async () => { const plugin = totp() await ipalKit({ - access: { authCollection: 'users' }, i18n, - twoFactor: { collectionSlug: 'admins', issuer: 'A', plugin: plugin as never }, - })(empty()) - expect(plugin).toHaveBeenCalledWith(expect.objectContaining({ collection: 'admins' })) + twoFactor: { allowCollectionMismatch: true, collectionSlug: 'users', issuer: 'A', plugin: plugin as never }, + })(twoAuth()) + expect(plugin).toHaveBeenCalledWith(expect.objectContaining({ collection: 'users' })) + }) + + test('a target that is not an auth collection always fails', async () => { + const plugin = totp() + await expect( + ipalKit({ + i18n, + twoFactor: { allowCollectionMismatch: true, collectionSlug: 'pages', issuer: 'A', plugin: plugin as never }, + })(twoAuth()), + ).rejects.toThrow(/"pages" is not an auth collection/) }) }) @@ -144,3 +176,66 @@ describe('roles field: the first-register account becomes admin', () => { expect(await hook(0, ['user'], '/api/users')).toEqual(['user']) }) }) + +describe('every access default can be overridden by the project', () => { + test('injected users: unlock is admin-only by default; access.authAccess keys win', async () => { + const base = await ipalKit({ access: { authCollection: 'users' }, i18n, twoFactor: false })(empty()) + const def = base.collections?.find((c) => c.slug === 'users')?.access ?? {} + expect(run(def.unlock, user)).toBe(false) + expect(run(def.unlock, admin)).toBe(true) + + const config = await ipalKit({ + access: { authAccess: { read: () => true }, authCollection: 'users' }, + i18n, + twoFactor: false, + })(empty()) + const access = config.collections?.find((c) => c.slug === 'users')?.access ?? {} + expect(run(access.read, user)).toBe(true) + expect(run(access.delete, user)).toBe(false) // the rest keeps the plugin default + }) + + test('access.firstUserAdmin: false keeps what the first-register form sent', async () => { + const config = await ipalKit({ access: { authCollection: 'users', firstUserAdmin: false }, i18n, twoFactor: false })(empty()) + const users = config.collections?.find((c) => c.slug === 'users') as CollectionConfig + const roles = users.fields.find((f) => 'name' in f && f.name === 'roles') as { hooks?: unknown } + expect(roles.hooks).toBeUndefined() + }) + + test('globalOverrides: an object merges access (project wins), a function takes over', async () => { + const config = await ipalKit({ + access: { authCollection: 'users' }, + globalOverrides: { + 'cookie-settings': (g) => ({ ...g, label: 'Cookies' }), + notifications: { access: { update: ({ req }) => Boolean(req.user) } }, + }, + i18n, + twoFactor: false, + })(empty()) + const notifications = config.globals?.find((g) => g.slug === 'notifications') as GlobalConfig + expect(run(notifications.access?.update, user)).toBe(true) + expect(run(notifications.access?.read, null)).toBe(true) + expect(config.globals?.find((g) => g.slug === 'cookie-settings')?.label).toBe('Cookies') + // untouched globals keep the secure default + expect(run((config.globals?.find((g) => g.slug === 'site-settings') as GlobalConfig).access?.update, user)).toBe(false) + }) + + test('forms: formOverrides.access wins; a read rule on the Emails field wins', async () => { + const config = await ipalKit({ + access: { authCollection: 'users' }, + forms: { + formOverrides: { + access: { update: () => true }, + fields: ({ defaultFields }) => + defaultFields.map((f) => ('name' in f && f.name === 'emails' ? ({ ...f, access: { read: () => true } } as Field) : f)), + }, + }, + i18n, + twoFactor: false, + })(empty()) + const forms = config.collections?.find((c) => c.slug === 'forms') as CollectionConfig + expect(run(forms.access?.update, user)).toBe(true) + expect(run(forms.access?.delete, user)).toBe(false) + const emails = forms.fields.find((f: Field) => 'name' in f && f.name === 'emails') as { access?: { read?: (a: unknown) => boolean } } + expect(emails.access?.read?.({ req: { user } })).toBe(true) + }) +}) From f65c6580e125218f057ed1506f65956d01624328 Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?Rados=C5=82aw=20Smoli=C5=84ski?= Date: Thu, 22 Oct 2026 17:29:49 +0200 Subject: [PATCH 20/27] SEO: sitemap construction filter uses isPathAllowed + pathOf (same rule as isPathVisibleIn) Co-Authored-By: Claude Opus 5.5 --- src/modules/frontend/createContentHelpers.ts | 7 ++++--- 1 file changed, 4 insertions(+), 3 deletions(-) diff --git a/src/modules/frontend/createContentHelpers.ts b/src/modules/frontend/createContentHelpers.ts index 8800809..f70aaa4 100644 --- a/src/modules/frontend/createContentHelpers.ts +++ b/src/modules/frontend/createContentHelpers.ts @@ -15,7 +15,7 @@ import type { PageMetadata, RobotsOptions, RobotsRules, SitemapEntry, SitemapRou import { getAnalyticsConfig } from '../analytics/getAnalyticsConfig.js' import { getConsentTexts } from '../consent/getConsentTexts.js' -import { normalizePath } from '../construction/logic.js' +import { isPathAllowed } from '../construction/logic.js' import { pathOf } from '../construction/visibility.js' import { createMarkdownRoute } from '../content/createMarkdownRenderer.js' import { getArchiveEntries, resolveRoute as resolveRouteRaw } from '../content/index.js' @@ -457,9 +457,10 @@ export function createContentHelpers({ }) // Under construction: list only the pages visitors can still open — the // rest redirect to the homepage notice, which crawlers would index. + // Same check as isPathVisibleIn(mode, pathOf(url)) (security-perf branch), with the + // mode read once for the whole list. const open = await constructionPaths() - const allowed = open ? new Set(open.map(normalizePath)) : null - const visible = allowed ? entries.filter((e) => allowed.has(normalizePath(pathOf(e.url)))) : entries + const visible = open ? entries.filter((e) => isPathAllowed(pathOf(e.url), open)) : entries return transformSitemap ? await transformSitemap(visible) : visible } catch (error) { // At runtime a failure is an error (the sitemap route answers 503, so From 38c1d9215e05952692d6253c65bcbc58ed49b133 Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?Rados=C5=82aw=20Smoli=C5=84ski?= Date: Thu, 22 Oct 2026 17:35:08 +0200 Subject: [PATCH 21/27] enabled: false keeps the plugin's schema, drops only its behaviour Returning the incoming config dropped the plugin's collections and globals, so a Postgres migration would drop their tables. Now collections, globals and fields stay; endpoints, onInit and admin components are left out. Also: ipalKit({ forms: { consentFieldName } }) is stored in config.custom.ipal. Co-Authored-By: Claude Opus 5.5 --- docs/forms.md | 96 +++++++++++++++++++++++++++++++++++---------- src/plugin.ts | 23 +++++++++-- src/types.ts | 24 +++++++----- test/plugin.test.ts | 15 +++++-- 4 files changed, 121 insertions(+), 37 deletions(-) diff --git a/docs/forms.md b/docs/forms.md index 5e0fc4c..2d308c3 100644 --- a/docs/forms.md +++ b/docs/forms.md @@ -35,6 +35,7 @@ Jeśli formularz wymaga pola, którego builder nie ma — dodaj je przez konfigu ```json "dependencies": { "@payloadcms/plugin-form-builder": "3.90.2" } // ta sama wersja co payload ``` +(peer dependency pluginu: `^3.90.2`) ## Config (payload.config.ts) @@ -42,12 +43,28 @@ Jeśli formularz wymaga pola, którego builder nie ma — dodaj je przez konfigu ipalKit({ forms: { redirectRelationships: ['pages'], // formularz może przekierować na Page - // fields: { date: false, payment: true, … }, // domyślnie: text, textarea, email, number, date, - // // time, select, radio, checkbox, checkboxGroup, message, step + // fields: { date: false, … }, // domyślnie: text, textarea, email, number, date, + // // time, select, radio, checkbox, checkboxGroup, message, step }, }) ``` +Opcje `forms` (`FormsOption`): + +| Opcja | Domyślnie | Opis | +|---|---|---| +| `adminGroup` | `'Forms'` | grupa w panelu; `false` = domyślna Payloada; `admin.group` w overrides wygrywa | +| `fields` | patrz niżej | typy pól buildera; `false` wyłącza typ, obiekt (blok) podmienia; `true` = domyślny blok ipal | +| `redirectRelationships` | — | kolekcje, na które formularz może przekierować | +| `formOverrides` / `formSubmissionOverrides` | — | nadpisania kolekcji (`fields` jako funkcja + dowolne ustawienia kolekcji) | +| `emailLayout` | `false` | ładne maile + zakładka Site Settings → Emails | +| `beforeEmail` | — | `beforeEmail` form-buildera (po layoucie, gdy `emailLayout`) | +| `consentFieldName` | `'consent'` | **uwaga:** obecnie nie jest nigdzie czytana — nazwę pola zgody zmienia się przez `submitForm({ consentFieldName })` / `createSubmitAction({ consentFieldName })` | + +`payment` jest zawsze wyłączony — `fields: { payment: true }` go **nie** włącza (wartość `true` +jest pomijana); włączyć można tylko podając obiekt-blok. `country` / `state` zostają z domyślnych +ustawień form-buildera. + Dodaje kolekcje **Forms** (edytor buduje formularze) i **Form Submissions** (zgłoszenia) — w panelu w grupie **Forms** z etykietami „Form/Forms” i „Submission/Submissions” (bez nadpisań w projekcie). Inna grupa: @@ -70,9 +87,10 @@ import { RenderForm } from '@intecion/ipal-kit/rsc' plugin nie ma żadnych stylów. Klucze: `form, progress, step, stepTitle, stepDescription, fields, field, fieldHalf, fieldFull, label, input, textarea, select, checkbox, checkboxLabel, choices, legend, choice, choiceInput, choiceLabel, message, error, formError, turnstile, actions, back, - next, submit, success, required`. Do CSS są też `data-ipal="form"`, `data-type`, `data-width`, `data-step`. + next, submit, success, required, fixed`. Do CSS są też `data-ipal="form"`, `data-type`, `data-width`, `data-step`. - opcje: `requiredMark` (np. `" *"`), `converters` / `richTextClassName` (wygląd rich text), - `linkOptions` (`await getLinkOptions(locale)` — redirect na stronę z panelu), `turnstileTheme`. + `linkOptions` (`await getLinkOptions(locale)` — redirect na stronę z panelu), `turnstileTheme` + (domyślnie `'page'`), `values` (niżej). `RenderForm` (serwer) renderuje bloki **message** i potwierdzenie przez `RenderRichText`, wiąże akcję z formularzem i językiem, rozwiązuje redirect i podaje przeglądarce **tylko publiczną część @@ -154,7 +172,7 @@ przekazuj do przeglądarki surowego dokumentu formularza. `renderField={({ field, defaultRender }) => field.name === 'budget' ? : undefined}`. 2. `useBuilderForm({ form, action, texts })` — cała logika, markup Twój: `steps`, `step`, `stepIndex`, `total`, `isFirst/isLast`, `next()`, `back()`, `goTo(i)`, `submit`, `values`, - `errors`, `errorMessage`, `isSubmitting`, `isSuccess`, `resultMessage`, `getFieldProps`, + `errors`, `errorMessage`, `isSubmitting`, `isSuccess`, `resultMessage`, `isFixed`, `getFieldProps`, `getInputProps`, `getTextareaProps`, `getSelectProps`, `getOptionProps`, `fieldId`, `errorId`, `TurnstileWidget`. Przykład: `ipal-form/resources/CustomForm.example.tsx`. 3. Czysta logika (też na serwerze / w testach): `splitSteps`, `initialBuilderValues`, @@ -198,16 +216,27 @@ const f = useForm({ initialValues, validate, submitAction: sendForm.bind(null, f ``` Wynik `submitForm`: `{ success: true, submissionId }` albo `{ success: false, reason, … }` -(kody niżej). Opcje: `maxPerMinute` (domyślnie 5, `0` wyłącza), `consentFieldName`. +(kody niżej). Opcje: `payload`, `formId`, `data` (wymagane), `ip`, `locale`, `turnstileToken`, +`maxPerMinute` (domyślnie 5, `0` wyłącza; bez `ip` limit jest pomijany), `consentFieldName` +(`'consent'`), `turnstileOnConfigError` (`'allow'` | `'reject'`, domyślnie `'allow'` — patrz +[turnstile.md](./turnstile.md)). + +Prościej: `createSubmitAction({ getCachedPayload, headers })` z `/server` (sekcja 1.9.1 niżej) — +opcje dodatkowe: `clientIp`, `honeypotField`, `consentFieldName`, `maxPerMinute`, +`turnstileOnConfigError`. ### IP klienta i rate limit -`clientIp(req | headers, { header?, trustedProxies? })` czyta kolejno -`cf-connecting-ip`, `x-real-ip`, a z `X-Forwarded-For` bierze wpis **od prawej** -(lewy wpisuje sam klient, więc mógłby podawać nowe IP przy każdym żądaniu i omijać -limit). Na produkcji przypnij nagłówek, któremu ufasz, np. `IPAL_IP_HEADER=cf-connecting-ip` -za Cloudflare. Bez tego klient, który trafi do aplikacji z pominięciem proxy, może -podstawić dowolny z tych nagłówków. Ta sama opcja `clientIp` jest w `createSearchRoute` +`clientIp(req | headers, { header?, trustedProxies? })` (z `@intecion/ipal-kit`): + +- **Przypięty nagłówek** — `header` albo env **`IPAL_IP_HEADER`**: czytany jest tylko on (brak → pusty + string). Dla `x-forwarded-for` bierze wpis `trustedProxies` (domyślnie 1) od prawej. +- **Bez przypięcia** (domyślnie) ufa **każdemu** z nagłówków, w kolejności: `cf-connecting-ip`, + `x-real-ip`, potem `X-Forwarded-For` liczony **od prawej** (lewy wpisuje sam klient). Klient, + który trafi do aplikacji z pominięciem proxy, może więc podstawić `cf-connecting-ip` / + `x-real-ip` i omijać limit. Na produkcji bez `IPAL_IP_HEADER` jest jednorazowe ostrzeżenie w logu. + Ustaw np. `IPAL_IP_HEADER=cf-connecting-ip` za Cloudflare, `x-forwarded-for` tylko za Traefik/nginx. +- Brak rozpoznanego IP → limit jest **pomijany** (żądanie przechodzi). Ta sama opcja `clientIp` jest w `createSearchRoute` i `createMcpRoute`. Brak IP (proxy obcina nagłówek, zły `IPAL_IP_HEADER`) **nie** omija limitu: takie żądania @@ -315,9 +344,12 @@ z pominięciem formularza. Plugin ładuje definicję formularza i: odrzuca niezn klucze, wymusza pola `required`, tnie długość (5000 znaków). Do bazy trafia tylko to, co formularz definiuje. -Rate limit: 5/min/IP domyślnie, `maxPerMinute` zmienia, `0` wyłącza (gdy limiter -jest z przodu). In-memory — przy wielu instancjach licznik jest per-proces, więc -efektywny limit to per-instancja. Do formularza kontaktowego wystarcza. +Rate limit: 5/min/IP domyślnie (okno 60 s, licznik `form` osobny od wyszukiwarki i MCP), +`maxPerMinute` zmienia, `0` wyłącza (gdy limiter jest z przodu). In-memory — przy wielu +instancjach licznik jest per-proces (chyba że `setRateLimitStore`). + +Nieznane klucze w `data` (poza polami formularza i `cf-turnstile-response` / +`g-recaptcha-response`) odrzucają **całe** zgłoszenie (`kind: 'unknown_fields'`). ### Honeypot — darmowa druga warstwa antyspam @@ -352,7 +384,7 @@ type SubmitFormResult = | { success: true; submissionId: string | number } | { success: false; reason: 'rate_limited' } | { success: false; reason: 'turnstile' } - | { success: false; reason: 'validation'; field?: string; kind?: 'required' | 'too_long' | 'unknown_fields' } + | { success: false; reason: 'validation'; field?: string; kind?: 'invalid_format' | 'required' | 'too_long' | 'unknown_fields' } | { success: false; reason: 'not_found' } | { success: false; reason: 'consent'; field?: string } | { success: false; reason: 'error' } @@ -376,9 +408,10 @@ Ten sam wzorzec co consent: plugin nie zaszywa języka, oddaje dane. ## Zgoda RODO (consent field) -Pole zgody RODO to checkbox o nazwie `consent` (konfigurowalna przez -`FormsOption.consentFieldName`). Plugin WYMUSZA jego zaznaczenie SERVER-SIDE — -niezależnie od tego, jak redaktor ustawił pole w panelu. +Pole zgody RODO to pole o nazwie `consent` (nazwę zmienia argument `consentFieldName` +w `submitForm` / `createSubmitAction`). Plugin WYMUSZA jego zaznaczenie SERVER-SIDE +(wartość musi być dokładnie `true`) — niezależnie od tego, jak redaktor ustawił pole +w panelu i od warunku „Show only when”. ### Dlaczego server-side @@ -399,9 +432,13 @@ inaczej `submitForm` zwraca `reason: 'consent'`. Zmiana nazwy pola: ```ts -ipalKit({ forms: { consentFieldName: 'zgoda' } }) +export const sendForm = createSubmitAction({ getCachedPayload, headers, consentFieldName: 'zgoda' }) +// albo: submitForm({ …, consentFieldName: 'zgoda' }) ``` +> `ipalKit({ forms: { consentFieldName } })` istnieje w typie `FormsOption`, ale obecnie +> nie jest przekazywana do `submitForm` — nie działa. + ## Komunikaty — resolveFormMessage (zalecane) Zamiast ręcznego switcha po `reason`, użyj `resolveFormMessage` z modułu @@ -569,7 +606,7 @@ Rozwiązywanie wartości lokalizowanej (topics, etykiety) to jeden import, nie kopiowany `(v as any)[locale]`: ```ts -import { resolveLocalized } from '@intecion/ipal-kit' // lub /client +import { resolveLocalized } from '@intecion/ipal-kit' // tylko root (nie ma w /client) const label = resolveLocalized(topic.label, locale) ``` @@ -592,3 +629,20 @@ filtrować w kliencie. sterujące i bidi usuwane. Błąd: `reason: 'validation'`, `kind: 'invalid_format'`, `field`. - **Dostęp:** zgłoszenia czytają tylko `editor`/`admin` (wcześniej każde konto), usuwa `admin`; zakładka Emails formularza (adresy odbiorców) ukryta w publicznym `GET /api/forms`. + +## Wyłączenie, nadpisanie, rozszerzenie + +- **Wyłączenie:** bez opcji `forms` plugin nie wpina form-buildera (brak kolekcji Forms / Form Submissions). + Pojedyncze typy pól: `forms.fields.: false`. +- **Nadpisanie kolekcji:** `formOverrides` / `formSubmissionOverrides` — pola (funkcja `fields`), `labels`, + `admin`, `access`, `hooks`. Domyślny dostęp zgłoszeń (`create`: zalogowani, `read`: editor+, `delete`: admin) + nadpisujesz kluczami w `formSubmissionOverrides.access`. Ukrycie zakładki Emails w publicznym API + (`hideEmails`) jest obecnie zawsze nakładane na pole `emails`. +- **Nadpisanie typu pola:** `forms.fields.: ` podmienia blok; własne bloki z „Placeholder” / + godziną: `withPlaceholder`, `placeholderField`, `timeBlock`, `stepBlock`, `checkboxGroupBlock` (root). +- **Bramki wysyłki:** `submitForm` / `createSubmitAction` — `maxPerMinute` (`0` = bez limitu), + `turnstileOnConfigError`, `consentFieldName`, `clientIp`, `honeypotField`; wspólny store limitów: + `setRateLimitStore`. +- **Maile:** `forms.beforeEmail` modyfikuje maile (po layoucie), `emailLayout: true` włącza szablon. +- **Własny front:** `BuilderForm` (`renderField`), `useBuilderForm`, czysta logika (`splitSteps`, + `visibleFields`, `validateBuilderFields`…), `useForm` / `useContactForm`, walidatory, `buildFormsPlugin` (root). diff --git a/src/plugin.ts b/src/plugin.ts index 036efce..8a1913b 100644 --- a/src/plugin.ts +++ b/src/plugin.ts @@ -5,10 +5,10 @@ import type { IpalOptions, TotpPluginFactory } from './types.js' import { buildCookieSettings } from './globals/CookieSettings/index.js' import { migrateCookieSettingsSaveButton } from './globals/CookieSettings/migrateSaveButton.js' import { buildNotifications } from './globals/Notifications/index.js' +import { applyGlobalOverrides } from './globals/overrides.js' import { buildSiteIntegrations } from './globals/SiteIntegrations/index.js' import { buildSiteSettings } from './globals/SiteSettings/index.js' import { adminOnly, adminOrSelf, injectRoles } from './modules/access/index.js' -import { applyGlobalOverrides } from './globals/overrides.js' import { buildConsentLogCollection, buildConsentLogEndpoint } from './modules/consent/consentLog.js' import { buildConstructionFields } from './modules/construction/fields.js' import { buildArchiveFields } from './modules/content/index.js' @@ -50,10 +50,23 @@ export const ipalKit = (options: IpalOptions): Plugin => { validateI18nConfig(options.i18n) return async (incomingConfig: Config): Promise => { - // Early return when disabled — schema stays, behavior off + const config = await transform(incomingConfig) + // Disabled: schema stays (collections, globals, fields — so a Postgres + // migration doesn't drop the plugin's tables), behaviour goes: no plugin + // endpoints, onInit work or admin components. Returning the incoming + // config untouched used to drop the plugin's collections and globals. if (options.enabled === false) { - return incomingConfig + return { + ...config, + admin: { ...config.admin, components: incomingConfig.admin?.components }, + endpoints: incomingConfig.endpoints, + onInit: incomingConfig.onInit, + } } + return config + } + + async function transform(incomingConfig: Config): Promise { let config = { ...incomingConfig } @@ -246,6 +259,10 @@ export const ipalKit = (options: IpalOptions): Plugin => { // --- forms: apply @payloadcms/plugin-form-builder directly --- if (options.forms) { config = await buildFormsPlugin(options.forms)(config) + // submitForm reads it from payload.config when the call doesn't pass one + if (options.forms.consentFieldName) { + config.custom = { ...config.custom, ipal: { ...config.custom?.ipal, consentFieldName: options.forms.consentFieldName } } + } } // --- globals --- diff --git a/src/types.ts b/src/types.ts index 4ec9941..698aa22 100644 --- a/src/types.ts +++ b/src/types.ts @@ -62,7 +62,11 @@ export type IpalOptions = { */ content?: ContentOption - /** Disable the plugin without uninstalling (keeps DB schema intact) */ + /** + * `false` = plugin off without uninstalling: its collections, globals and + * fields stay (DB schema and migrations unchanged), but it adds no endpoints, + * onInit work or admin components. + */ enabled?: boolean /** @@ -71,6 +75,15 @@ export type IpalOptions = { */ forms?: FormsOption + /** + * Change any of the plugin's globals (site-settings, site-integrations, + * cookie-settings, notifications): an object merges over the plugin's + * (`access` / `admin` / `hooks` key by key, your keys win), a function gets + * the global and returns the one to use. E.g. let any logged-in user edit + * Notifications: `{ notifications: { access: { update: authenticated } } }`. + */ + globalOverrides?: GlobalOverrides + i18n: I18nConfig /** @@ -90,15 +103,6 @@ export type IpalOptions = { */ pages?: PagesOption - /** - * Change any of the plugin's globals (site-settings, site-integrations, - * cookie-settings, notifications): an object merges over the plugin's - * (`access` / `admin` / `hooks` key by key, your keys win), a function gets - * the global and returns the one to use. E.g. let any logged-in user edit - * Notifications: `{ notifications: { access: { update: authenticated } } }`. - */ - globalOverrides?: GlobalOverrides - /** * next/cache `revalidatePath`, INJECTED (the plugin never imports next/cache). * When given, saving any of the plugin's globals (Site Settings, Site diff --git a/test/plugin.test.ts b/test/plugin.test.ts index 8d9675a..87cea61 100644 --- a/test/plugin.test.ts +++ b/test/plugin.test.ts @@ -45,9 +45,18 @@ describe('ipalKit — config transform', () => { expect(totp).toHaveBeenCalledWith(expect.objectContaining({ forceSetup: true, totp: { issuer: 'Acme' } })) }) - test('enabled: false leaves the config untouched', async () => { - const config = base() - expect(await ipalKit({ enabled: false, i18n, twoFactor: false })(config)).toBe(config) + test('enabled: false keeps the schema (collections, globals) but adds no endpoints, onInit or admin components', async () => { + const config = await ipalKit({ access: { authCollection: 'users' }, consentLog: true, enabled: false, i18n, stats: true, twoFactor: false })(base()) + expect(config.globals?.map((g) => g.slug)).toEqual(expect.arrayContaining(['site-settings', 'site-integrations', 'cookie-settings', 'notifications'])) + expect(config.collections?.map((c) => c.slug)).toEqual(expect.arrayContaining(['users', 'consent-records', 'stats-visits'])) + expect(config.endpoints ?? []).toEqual([]) + expect(config.onInit).toBeUndefined() + expect(config.admin?.components).toBeUndefined() + }) + + test('forms.consentFieldName reaches submitForm through config.custom.ipal', async () => { + const config = await ipalKit({ forms: { consentFieldName: 'zgoda' }, i18n, twoFactor: false })(base()) + expect((config.custom as { ipal?: { consentFieldName?: string } }).ipal?.consentFieldName).toBe('zgoda') }) test('invalid i18n fails fast', () => { From 4585e0fc691d82ebbd4d513d463875d325da0c02 Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?Rados=C5=82aw=20Smoli=C5=84ski?= Date: Thu, 22 Oct 2026 17:35:08 +0200 Subject: [PATCH 22/27] submitForm reads forms.consentFieldName from ipalKit options The option was typed but never read. An explicit argument still wins. Co-Authored-By: Claude Opus 5.5 --- src/modules/forms/submitForm.ts | 8 ++++++-- test/submitForm.test.ts | 12 ++++++++++++ 2 files changed, 18 insertions(+), 2 deletions(-) diff --git a/src/modules/forms/submitForm.ts b/src/modules/forms/submitForm.ts index 8e360b3..7eb18dc 100644 --- a/src/modules/forms/submitForm.ts +++ b/src/modules/forms/submitForm.ts @@ -10,7 +10,8 @@ import { validateSubmission } from './validateSubmission.js' export type SubmitFormArgs = { /** * Name of the GDPR consent checkbox. A field with this name must be checked - * for the submission to succeed (enforced server-side). Defaults to 'consent'. + * for the submission to succeed (enforced server-side). Defaults to + * ipalKit({ forms: { consentFieldName } }), then 'consent'. */ consentFieldName?: string /** Submitted field data — shape matches the form's fields. */ @@ -129,7 +130,10 @@ export async function submitForm({ // 3. Validate against the form's schema. A public endpoint can't trust the // shape of `data` — drop unknown keys, enforce required, cap length. - const validation = await validateSubmission(payload, formId, data, consentFieldName) + // Explicit argument → ipalKit({ forms: { consentFieldName } }) → 'consent'. + const configured = (payload.config?.custom as { ipal?: { consentFieldName?: unknown } } | undefined)?.ipal?.consentFieldName + const consentField = consentFieldName ?? (typeof configured === 'string' && configured ? configured : undefined) + const validation = await validateSubmission(payload, formId, data, consentField) if (!validation.ok) { if (validation.reason === 'not_found') { return { reason: 'not_found', success: false } diff --git a/test/submitForm.test.ts b/test/submitForm.test.ts index 6bf9d17..d953475 100644 --- a/test/submitForm.test.ts +++ b/test/submitForm.test.ts @@ -132,6 +132,18 @@ describe('submitForm — other gates', () => { }) }) + test('ipalKit forms.consentFieldName (payload.config.custom) names the consent field', async () => { + const { payload } = fakePayload({ forms: { f: { fields: [{ name: 'zgoda', blockType: 'checkbox' }] } } }) + Object.assign(payload, { config: { custom: { ipal: { consentFieldName: 'zgoda' } } } }) + expect(await submitForm({ data: { zgoda: false }, formId: 'f', ip: nextIp(), payload })).toEqual({ + field: 'zgoda', + reason: 'consent', + success: false, + }) + // an explicit argument still wins + expect((await submitForm({ consentFieldName: 'other', data: { zgoda: false }, formId: 'f', ip: nextIp(), payload })).success).toBe(true) + }) + test('consent must be checked', async () => { const { payload } = fakePayload({ forms }) expect(await submitForm({ data: { ...data, consent: false }, formId: 'contact', ip: nextIp(), payload })).toEqual({ From 0fd57c1d6a08d8a548a0abec400ad4cfe1c5dd61 Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?Rados=C5=82aw=20Smoli=C5=84ski?= Date: Thu, 22 Oct 2026 17:35:08 +0200 Subject: [PATCH 23/27] Opt-outs for the secure defaults; isPathVisibleIn in construction/logic - setUnknownIpFactor (0 = old free pass), UNKNOWN_IP_FACTOR exported - createContentHelpers({ settingsDepth }) and markdown/mcp isPathVisible overrides - - resolveRedirect({ draft: true }) for preview - isPathVisibleIn(mode, path), pathOf, PathVisibility exported; page route uses it Co-Authored-By: Claude Opus 5.5 --- src/index.ts | 12 +++++--- src/modules/construction/logic.ts | 11 +++++++ src/modules/content/resolveRedirect.ts | 8 ++++- src/modules/forms/rateLimit.ts | 1 + src/modules/frontend/createContentHelpers.ts | 20 +++++++----- src/modules/frontend/pageRoute.tsx | 4 +-- src/modules/richtext/RenderRichText.tsx | 10 ++++-- src/modules/shared/rateLimit.ts | 28 ++++++++++++++--- test/construction.test.ts | 32 +++++++++++++++++++- test/rateLimit.test.ts | 8 +++++ test/redirectDrafts.test.ts | 5 +++ test/richTextLinks.test.ts | 21 +++++++++++++ test/settingsDepth.test.ts | 8 +++++ 13 files changed, 144 insertions(+), 24 deletions(-) diff --git a/src/index.ts b/src/index.ts index 0659f34..be2efe6 100644 --- a/src/index.ts +++ b/src/index.ts @@ -1,3 +1,5 @@ +export { applyGlobalOverrides } from './globals/overrides.js' +export type { GlobalOverride, GlobalOverrides, IpalGlobalSlug } from './globals/overrides.js' export type { AccessOption, Role } from './modules/access/index.js' export { adminOnly, @@ -46,9 +48,11 @@ export { updateConsent, } from './modules/consent/index.js' export type { ConsentCategory, ConsentLogOptions, ConsentState, ConsentTexts, CookieTableRow } from './modules/consent/index.js' -export { constructionNoticeHref, isPathAllowed } from './modules/construction/logic.js' +export { constructionNoticeHref, isPathAllowed, isPathVisibleIn } from './modules/construction/logic.js' export type { ConstructionMode } from './modules/construction/types.js' export { CONSTRUCTION_NOTICE_PARAM } from './modules/construction/types.js' +export { pathOf } from './modules/construction/visibility.js' +export type { PathVisibility } from './modules/construction/visibility.js' export type { ContentCollectionOption, ContentOption, ResolvedRoute } from './modules/content/index.js' export { archiveFieldName, @@ -170,9 +174,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' @@ -217,7 +221,7 @@ export { buildArticleJsonLd, buildProductJsonLd, buildWebPageJsonLd, formatOpeni export { buildLlmsTxt } from './modules/seo/index.js' export { buildSitemapCss, buildSitemapXml, DEFAULT_SITEMAP_CREDIT, SITEMAP_STYLE_PARAM } from './modules/seo/index.js' export type { SitemapRouteOptions, SitemapStyleOptions } from './modules/seo/index.js' -export { clientIp, setRateLimitStore } from './modules/shared/rateLimit.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' export { STATS_SLUG } from './modules/stats/index.js' @@ -233,5 +237,3 @@ export { getTurnstileConfig } from './modules/turnstile/config.js' export type { TurnstileConfig } from './modules/turnstile/config.js' export { ipalKit } from './plugin.js' export type { IpalOptions } from './types.js' -export { applyGlobalOverrides } from './globals/overrides.js' -export type { GlobalOverride, GlobalOverrides, IpalGlobalSlug } from './globals/overrides.js' diff --git a/src/modules/construction/logic.ts b/src/modules/construction/logic.ts index cd0a4cc..ebec881 100644 --- a/src/modules/construction/logic.ts +++ b/src/modules/construction/logic.ts @@ -1,3 +1,5 @@ +import type { ConstructionMode } from './types.js' + import { CONSTRUCTION_NOTICE_PARAM, CONSTRUCTION_NOTICE_VALUE } from './types.js' /** `/pl/` → `/pl`, `` → `/` — paths compare without a trailing slash. */ @@ -15,3 +17,12 @@ export function isPathAllowed(pathname: string, allowedPaths: readonly string[]) /** Where a blocked address goes: the homepage with the notice parameter. */ export const constructionNoticeHref = (homePath: string): string => `${homePath}?${CONSTRUCTION_NOTICE_PARAM}=${CONSTRUCTION_NOTICE_VALUE}` + +/** + * Is this public page path served under this construction mode? True when the + * mode is off or the path is allowed. One rule for the page route, Markdown, + * MCP, search, the sitemap and llms.txt — feed it getConstructionMode(locale). + */ +export function isPathVisibleIn(mode: Pick, pathname: string): boolean { + return !mode.enabled || isPathAllowed(pathname, mode.allowedPaths) +} diff --git a/src/modules/content/resolveRedirect.ts b/src/modules/content/resolveRedirect.ts index ac03f4b..653146d 100644 --- a/src/modules/content/resolveRedirect.ts +++ b/src/modules/content/resolveRedirect.ts @@ -25,6 +25,11 @@ type ResolveRedirectArgs = { */ collections?: RedirectCollection[] config: I18nConfig + /** + * Preview (draftMode): also redirect from a never-published draft's old + * slug. Default false — public redirects never reveal a draft's new slug. + */ + draft?: boolean /** Home slug map/string, so a renamed homepage still collapses to the root. */ homeSlug?: Record | string /** Active locale (the request's locale). */ @@ -66,6 +71,7 @@ type DocShape = { _status?: unknown; slug?: unknown } export async function resolveRedirect({ collections = [{ slug: 'pages' }], config, + draft = false, homeSlug, locale, payload, @@ -93,7 +99,7 @@ export async function resolveRedirect({ // A never-published draft must not be reachable — nor its new slug // revealed — through a redirect (same rule as resolveRoute). const status = doc?._status - if (doc && status !== undefined && status !== null && status !== 'published') {continue} + if (!draft && doc && status !== undefined && status !== null && status !== 'published') {continue} if (doc && typeof doc[slugField as keyof DocShape] === 'string') { currentSlug = doc[slugField as keyof DocShape] as string } diff --git a/src/modules/forms/rateLimit.ts b/src/modules/forms/rateLimit.ts index 9ac2d97..bb1505e 100644 --- a/src/modules/forms/rateLimit.ts +++ b/src/modules/forms/rateLimit.ts @@ -5,6 +5,7 @@ export { consumeRateLimit, retryAfterSeconds, setRateLimitStore, + setUnknownIpFactor, tooManyRequests, } from '../shared/rateLimit.js' export type { ClientIpOptions, RateLimitArgs, RateLimitStore } from '../shared/rateLimit.js' diff --git a/src/modules/frontend/createContentHelpers.ts b/src/modules/frontend/createContentHelpers.ts index 25094e7..12ac2a4 100644 --- a/src/modules/frontend/createContentHelpers.ts +++ b/src/modules/frontend/createContentHelpers.ts @@ -16,7 +16,7 @@ import type { PageMetadata, RobotsOptions, RobotsRules, SitemapEntry, SitemapSty import { getAnalyticsConfig } from '../analytics/getAnalyticsConfig.js' import { getConsentTexts } from '../consent/getConsentTexts.js' -import { isPathAllowed } from '../construction/logic.js' +import { isPathVisibleIn } from '../construction/logic.js' import { createMarkdownRoute } from '../content/createMarkdownRenderer.js' import { getArchiveEntries, resolveRoute as resolveRouteRaw } from '../content/index.js' import { MARKDOWN_PREFIX, markdownHref } from '../content/markdownNegotiation.js' @@ -55,7 +55,7 @@ type CreateContentHelpersArgs = { */ i18n?: I18nConfig /** Markdown route (`markdownRoute`): per-block overrides, frontmatter, layout field. */ - markdown?: { frontmatter?: boolean; layoutField?: string; overrides?: Record) => string> } + markdown?: { frontmatter?: boolean; isPathVisible?: PathVisibility; layoutField?: string; overrides?: Record) => string> } /** * Advertise each page's Markdown version from generatePageMetadata: * `` (GEO — @@ -65,7 +65,7 @@ type CreateContentHelpersArgs = { */ markdownAlternate?: boolean | string /** MCP route (`mcpRoute`): server name/version, rate limit, batch size. */ - mcp?: Pick + mcp?: Pick /** Defaults for getPageJsonLd — each call can override them. */ pageJsonLd?: PageJsonLdOptions /** Pages collection slug. Defaults to 'pages'. */ @@ -78,6 +78,12 @@ type CreateContentHelpersArgs = { * `{ adminRoute: false }` when the admin path is hidden (ipalKit adminRoute). */ robots?: RobotsOptions + /** + * Depth of the Site Settings read behind getSettings / getSiteShell. Default + * 1 (relations as documents, their relations as ids). Raise it only if your + * layout reads deeper — every request pays for it. + */ + settingsDepth?: number /** SiteSettings global slug. Defaults to 'site-settings'. */ settingsSlug?: string /** @@ -171,6 +177,7 @@ export function createContentHelpers({ pagesSlug = 'pages', redirectCollections, robots: robotsOptions, + settingsDepth = 1, settingsSlug = 'site-settings', siteJsonLd, sitemapImages, @@ -198,7 +205,7 @@ export function createContentHelpers({ */ const getSettings = cache(async (locale: string) => { const payload = await getCachedPayload() - return payload.findGlobal({ slug: settingsSlug as never, depth: 1, locale: locale as never }) + return payload.findGlobal({ slug: settingsSlug as never, depth: settingsDepth, locale: locale as never }) }) /** What does this URL point at? Routing only — no listing data. */ @@ -691,10 +698,7 @@ export function createContentHelpers({ * Is this page path public right now? False for pages construction mode * hides. The Markdown and MCP routes use it; pass it to createSearchRoute. */ - const isPathVisible: PathVisibility = async (path, locale) => { - const construction = await getConstructionMode(locale) - return !construction.enabled || isPathAllowed(path, construction.allowedPaths) - } + const isPathVisible: PathVisibility = async (path, locale) => isPathVisibleIn(await getConstructionMode(locale), path) // ── Layout ──────────────────────────────────────────────────────────────── /** Notifications → form texts in this locale (BuilderForm / RenderForm `texts`). */ diff --git a/src/modules/frontend/pageRoute.tsx b/src/modules/frontend/pageRoute.tsx index 35120cb..9a64645 100644 --- a/src/modules/frontend/pageRoute.tsx +++ b/src/modules/frontend/pageRoute.tsx @@ -5,7 +5,7 @@ import type { ResolvedRoute } from '../content/index.js' import type { ContentHelpers, PageJsonLdOptions } from './createContentHelpers.js' import { RenderBlocks } from '../blocks/RenderBlocks.js' -import { constructionNoticeHref, isPathAllowed } from '../construction/logic.js' +import { constructionNoticeHref, isPathVisibleIn } from '../construction/logic.js' import { LocaleView } from '../pages/LocaleView.js' import { NotFoundLoader } from '../pages/NotFoundLoader.js' import { JsonLdGraph } from '../seo/JsonLdGraph.js' @@ -116,7 +116,7 @@ export function createPageRoute(helpers: Helpers, options: PageRouteOptions) { const construction = await helpers.getConstructionMode(locale) const multilingual = (helpers.i18n?.locales.length ?? 0) > 1 const path = `/${[...(multilingual ? [locale] : []), ...segments].join('/')}` - if (construction.enabled && !isPathAllowed(path, construction.allowedPaths)) {return redirect(constructionNoticeHref(construction.homePath))} + if (!isPathVisibleIn(construction, path)) {return redirect(constructionNoticeHref(construction.homePath))} } const route = await helpers.resolveRoute(locale, segments, 1) if (!route) { diff --git a/src/modules/richtext/RenderRichText.tsx b/src/modules/richtext/RenderRichText.tsx index e29cf16..321fc84 100644 --- a/src/modules/richtext/RenderRichText.tsx +++ b/src/modules/richtext/RenderRichText.tsx @@ -31,6 +31,12 @@ export type RenderRichTextProps = { * converter still renders the heading; the id is added to what it returns. */ headingIds?: { className?: string; levels?: readonly HeadingLevel[] } | boolean + /** + * Links whose URL isn't a safe target (`javascript:`, `data:`…) render as + * '#'. Default true; `false` renders stored URLs as they are (only for + * content you fully trust). + */ + safeLinks?: boolean } type HeadingNode = { children?: unknown[]; tag: HeadingLevel } @@ -97,10 +103,10 @@ function withHeadingIds( * // /client * */ -export function RenderRichText({ className, converters, data: raw, headingIds }: RenderRichTextProps) { +export function RenderRichText({ className, converters, data: raw, headingIds, safeLinks = true }: RenderRichTextProps) { if (!raw) {return null} // javascript:/data: link URLs from stored content never reach an href - const data = sanitizeRichTextLinks(raw) + const data = safeLinks ? sanitizeRichTextLinks(raw) : raw if (headingIds) { const opts = headingIds === true ? {} : headingIds const ids = computeHeadingIds(data, opts.levels ? { levels: opts.levels } : {}) diff --git a/src/modules/shared/rateLimit.ts b/src/modules/shared/rateLimit.ts index 39c9fe8..ea1c202 100644 --- a/src/modules/shared/rateLimit.ts +++ b/src/modules/shared/rateLimit.ts @@ -77,10 +77,24 @@ type CheckArgs = { cost?: number } & RateLimitArgs * capping the flood. */ export const UNKNOWN_IP_KEY = 'unknown-ip' +/** Default multiplier for the shared no-IP bucket. */ export const UNKNOWN_IP_FACTOR = 20 -function resolveKey(key: string, max: number): { key: string; max: number } { - return key ? { key, max } : { key: UNKNOWN_IP_KEY, max: max * UNKNOWN_IP_FACTOR } +let unknownIpFactor = UNKNOWN_IP_FACTOR + +/** + * How requests with no client IP are limited, for every limiter in the plugin: + * the shared bucket's limit is `factor` × max. `0` = let them through + * unlimited (the behaviour before 1.13 — only when a limiter in front, e.g. + * Cloudflare, already covers them). Default UNKNOWN_IP_FACTOR. + */ +export function setUnknownIpFactor(factor: number): void { + unknownIpFactor = Math.max(0, factor) +} + +function resolveKey(key: string, max: number): { key: string; max: number } | null { + if (key) {return { key, max }} + return unknownIpFactor > 0 ? { key: UNKNOWN_IP_KEY, max: max * unknownIpFactor } : null } function hitMemory(id: string, cost: number, windowMs: number): Bucket { @@ -102,10 +116,12 @@ function hitMemory(id: string, cost: number, windowMs: number): Bucket { * * Returns true when the request is within the limit, false when it should be * rejected. A missing key (no IP) counts against one shared bucket with - * UNKNOWN_IP_FACTOR × max. + * UNKNOWN_IP_FACTOR × max (setUnknownIpFactor). */ export function checkRateLimit({ cost = 1, key: rawKey, max: rawMax = 5, scope = 'form', windowMs = 60_000 }: CheckArgs): boolean { - const { key, max } = resolveKey(rawKey, rawMax) + const resolved = resolveKey(rawKey, rawMax) + if (!resolved) {return true} + const { key, max } = resolved const id = `${scope}:${key}` const current = buckets.get(id) const used = current && current.resetAt > Date.now() ? current.count : 0 @@ -127,7 +143,9 @@ export async function consumeRateLimit({ scope = 'form', windowMs = 60_000, }: CheckArgs): Promise<{ ok: boolean; retryAfter: number }> { - const { key, max } = resolveKey(rawKey, rawMax) + const resolved = resolveKey(rawKey, rawMax) + if (!resolved) {return { ok: true, retryAfter: 0 }} + const { key, max } = resolved const id = `${scope}:${key}` let bucket: Bucket diff --git a/test/construction.test.ts b/test/construction.test.ts index b1878c6..51ac158 100644 --- a/test/construction.test.ts +++ b/test/construction.test.ts @@ -7,7 +7,7 @@ import path from 'node:path' import { buildConfig, getPayload } from 'payload' import { afterAll, beforeAll, describe, expect, test, vi } from 'vitest' -import { constructionNoticeHref, isPathAllowed, normalizePath } from '../src/modules/construction/logic.js' +import { constructionNoticeHref, isPathAllowed, isPathVisibleIn, normalizePath } from '../src/modules/construction/logic.js' import { createContentHelpers } from '../src/modules/frontend/createContentHelpers.js' import { createPageRoute } from '../src/modules/frontend/pageRoute.js' import { ipalKit } from '../src/plugin.js' @@ -22,6 +22,12 @@ describe('under construction — path logic', () => { expect(isPathAllowed('/pl/o-nas', ['/pl', '/pl/brief'])).toBe(false) expect(constructionNoticeHref('/pl')).toBe('/pl?notice=construction') }) + + test('isPathVisibleIn: off → everything; on → allowed paths only', () => { + expect(isPathVisibleIn({ allowedPaths: [], enabled: false }, '/pl/o-nas')).toBe(true) + expect(isPathVisibleIn({ allowedPaths: ['/pl', '/pl/brief'], enabled: true }, '/pl/brief/')).toBe(true) + expect(isPathVisibleIn({ allowedPaths: ['/pl', '/pl/brief'], enabled: true }, '/pl/o-nas')).toBe(false) + }) }) describe('under construction — Site Settings → createPageRoute', () => { @@ -116,3 +122,27 @@ describe('under construction — Site Settings → createPageRoute', () => { expect(await helpers.isPathVisible('/pl/brief', 'pl')).toBe(true) }) }) + +describe('under construction — opting out per route', () => { + test('a project can pass its own isPathVisible to Markdown / MCP', async () => { + const { createMcpRoute } = await import('../src/modules/mcp/createMcpRoute.js') + const seen: string[] = [] + const mcp = createMcpRoute({ + config: { defaultLocale: 'pl', locales: [{ code: 'pl', label: 'PL' }, { code: 'en', label: 'EN' }] }, + getCachedPayload: async () => ({}) as never, + isPathVisible: (path) => { + seen.push(path) + return false + }, + rateLimit: false, + }) + const res = await mcp.POST( + new Request('https://x/api/mcp', { + body: JSON.stringify({ id: 1, jsonrpc: '2.0', method: 'tools/call', params: { name: 'get_page', arguments: { path: '/pl/o-nas' } } }), + method: 'POST', + }), + ) + expect(JSON.stringify(await res.json())).toContain('No page found') + expect(seen).toEqual(['/pl/o-nas']) + }) +}) diff --git a/test/rateLimit.test.ts b/test/rateLimit.test.ts index d727618..afdf8dd 100644 --- a/test/rateLimit.test.ts +++ b/test/rateLimit.test.ts @@ -5,6 +5,7 @@ import { clientIp, consumeRateLimit, setRateLimitStore, + setUnknownIpFactor, UNKNOWN_IP_FACTOR, } from '../src/modules/shared/rateLimit.js' @@ -65,6 +66,13 @@ describe('checkRateLimit (in memory)', () => { expect(checkRateLimit({ cost: 4, key: `k-${Math.random()}`, max: 3 })).toBe(false) }) + test('setUnknownIpFactor(0) restores the old free pass; the default comes back', () => { + setUnknownIpFactor(0) + expect(checkRateLimit({ key: '', max: 0, scope: `z-${Math.random()}` })).toBe(true) + setUnknownIpFactor(UNKNOWN_IP_FACTOR) + expect(checkRateLimit({ key: '', max: 0, scope: `z-${Math.random()}` })).toBe(false) + }) + test('no key → one shared bucket with a roomier limit, not a free pass', () => { const scope = `s-${Math.random()}` for (let i = 0; i < 2 * UNKNOWN_IP_FACTOR; i++) {expect(checkRateLimit({ key: '', max: 2, scope })).toBe(true)} diff --git a/test/redirectDrafts.test.ts b/test/redirectDrafts.test.ts index 79575ff..a420226 100644 --- a/test/redirectDrafts.test.ts +++ b/test/redirectDrafts.test.ts @@ -18,6 +18,11 @@ describe('old-slug redirects and drafts', () => { expect(await resolveRedirect({ config, locale: 'pl', payload, segments: ['oferta'] })).toBeNull() }) + test('draft: true (preview) redirects drafts too', async () => { + const payload = payloadWith({ slug: 'tajny-projekt', _status: 'draft' }) + expect(await resolveRedirect({ config, draft: true, locale: 'pl', payload, segments: ['oferta'] })).toBe('/tajny-projekt') + }) + test('collections without drafts still redirect', async () => { const payload = payloadWith({ slug: 'kontakt-2' }) expect(await resolveRedirect({ config, locale: 'pl', payload, segments: ['kontakt'] })).toBe('/kontakt-2') diff --git a/test/richTextLinks.test.ts b/test/richTextLinks.test.ts index 9329d1a..8d0b77e 100644 --- a/test/richTextLinks.test.ts +++ b/test/richTextLinks.test.ts @@ -28,3 +28,24 @@ describe('rich text links', () => { expect(out.root.children[0].children[0]).toBe(d.root.children[0].children[0]) }) }) + +describe('RenderRichText', () => { + const state = { + root: { + type: 'root', children: [{ type: 'paragraph', children: [{ type: 'link', children: [{ type: 'text', detail: 0, format: 0, mode: 'normal', style: '', text: 'klik', version: 1 }], fields: { linkType: 'custom', url: 'data:text/html,' }, version: 3 }], version: 1 }], + direction: null, format: '', indent: 0, version: 1, + }, + } + + // React 19 already blocks javascript: hrefs; data: URLs it renders as is. + test('renders unsafe links as # by default; safeLinks={false} keeps them', async () => { + const { renderToStaticMarkup } = await import('react-dom/server') + const { createElement } = await import('react') + const { RenderRichText } = await import('../src/modules/richtext/RenderRichText.js') + const html = renderToStaticMarkup(createElement(RenderRichText, { data: state as never })) + expect(html).toContain('href="#"') + expect(html).not.toContain('data:') + const raw = renderToStaticMarkup(createElement(RenderRichText, { data: state as never, safeLinks: false })) + expect(raw).toContain('href="data:text/html') + }) +}) diff --git a/test/settingsDepth.test.ts b/test/settingsDepth.test.ts index fe6b392..d59dbd5 100644 --- a/test/settingsDepth.test.ts +++ b/test/settingsDepth.test.ts @@ -82,3 +82,11 @@ describe('Site Settings depth', () => { expect((route?.doc as { hero: { alt?: string } }).hero).toMatchObject({ alt: 'hero' }) }) }) + +describe('settingsDepth option', () => { + test('a project that needs deeper settings can raise the depth', async () => { + const { getSettings } = createContentHelpers({ config: configPromise, settingsDepth: 2 }) + const settings = (await getSettings('pl')) as { featured: { hero: { alt?: string } } } + expect(settings.featured.hero).toMatchObject({ alt: 'hero' }) + }) +}) From 7d835bdc499bfe573bd70532bd617f9c43009e16 Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?Rados=C5=82aw=20Smoli=C5=84ski?= Date: Thu, 22 Oct 2026 17:35:08 +0200 Subject: [PATCH 24/27] Locale cookie honours consent saved under a bumped policy version The proxy parsed the consent cookie as version 1, so after an editor bumped the policy version NEXT_LOCALE was never saved. It now accepts the stored record's own version; policyVersion pins one. Co-Authored-By: Claude Opus 5.5 --- src/modules/i18n/createProxy.ts | 2 ++ src/modules/i18n/localeMiddleware.ts | 22 +++++++++++++++++- test/localeConsentVersion.test.ts | 34 ++++++++++++++++++++++++++++ 3 files changed, 57 insertions(+), 1 deletion(-) create mode 100644 test/localeConsentVersion.test.ts diff --git a/src/modules/i18n/createProxy.ts b/src/modules/i18n/createProxy.ts index a689744..c987357 100644 --- a/src/modules/i18n/createProxy.ts +++ b/src/modules/i18n/createProxy.ts @@ -49,6 +49,8 @@ type CreateProxyOptions = { * requested with `Accept: text/markdown` is rewritten to its Markdown version. */ markdown?: boolean | string + /** Consent policy version to require for saving the locale cookie (createLocaleMiddleware). */ + policyVersion?: number } /** diff --git a/src/modules/i18n/localeMiddleware.ts b/src/modules/i18n/localeMiddleware.ts index 05d58b7..94b4627 100644 --- a/src/modules/i18n/localeMiddleware.ts +++ b/src/modules/i18n/localeMiddleware.ts @@ -37,6 +37,13 @@ type CreateLocaleMiddlewareArgs = { consentCookieName?: string /** Cookie name for the locale choice. Defaults to LOCALE_COOKIE_NAME. */ cookieName?: string + /** + * Cookie Settings → Policy version to require. The proxy can't read the + * panel, so by default a stored consent counts under its OWN version — + * reading it as version 1 meant that after an editor bumped the policy the + * locale cookie was never saved again. Pin it to require that version. + */ + policyVersion?: number } /** @@ -74,17 +81,30 @@ function firstSegment(pathname: string): string { * return res * } */ +/** The policy version a consent cookie was saved under (undefined when unreadable). */ +function storedVersion(raw: string | undefined): number | undefined { + if (!raw) {return undefined} + try { + const version = (JSON.parse(decodeURIComponent(raw)) as { version?: unknown }).version + return typeof version === 'number' ? version : undefined + } catch { + return undefined + } +} + export function createLocaleMiddleware({ config, consentCategory = 'functional', consentCookieName = CONSENT_COOKIE, cookieName = LOCALE_COOKIE_NAME, + policyVersion, }: CreateLocaleMiddlewareArgs) { // Whether the locale cookie may be written: 'necessary' is always granted; // 'functional' (default) requires the visitor to have consented. function mayPersistLocale(request: MiddlewareRequest): boolean { if (consentCategory === 'necessary') {return true} - const consent = parseConsent(request.cookies.get(consentCookieName)?.value) + const raw = request.cookies.get(consentCookieName)?.value + const consent = parseConsent(raw, policyVersion ?? storedVersion(raw)) return consent?.[consentCategory] === true } diff --git a/test/localeConsentVersion.test.ts b/test/localeConsentVersion.test.ts new file mode 100644 index 0000000..1afa8ea --- /dev/null +++ b/test/localeConsentVersion.test.ts @@ -0,0 +1,34 @@ +import { describe, expect, test } from 'vitest' + +import { CONSENT_COOKIE, serializeConsent } from '../src/modules/consent/storage.js' +import { createLocaleMiddleware } from '../src/modules/i18n/localeMiddleware.js' +import { LOCALE_COOKIE_NAME } from '../src/modules/i18n/negotiateLocale.js' + +const config = { defaultLocale: 'pl', locales: [{ code: 'pl', label: 'PL' }, { code: 'en', label: 'EN' }] } as const +const state = { analytics: false, functional: true, marketing: false, necessary: true } + +function request(path: string, cookies: Record) { + const url = new URL(`https://acme.pl${path}`) + return { + cookies: { get: (name: string) => (name in cookies ? { value: cookies[name] } : undefined) }, + headers: new Headers(), + nextUrl: { clone: () => new URL(url), pathname: url.pathname, search: url.search }, + url: url.toString(), + } +} + +describe('locale cookie and the consent policy version', () => { + const switchToEn = (version: number, policyVersion?: number) => + createLocaleMiddleware({ config, ...(policyVersion ? { policyVersion } : {}) })( + request('/en/o-nas', { [CONSENT_COOKIE]: decodeURIComponent(serializeConsent(state, version)), [LOCALE_COOKIE_NAME]: 'pl' }) as never, + ) + + test('a consent saved under a bumped policy version still lets the locale be saved', () => { + expect(switchToEn(3).cookie).toMatchObject({ name: LOCALE_COOKIE_NAME, value: 'en' }) + }) + + test('policyVersion pins the version the proxy requires', () => { + expect(switchToEn(3, 4).cookie).toBeUndefined() + expect(switchToEn(4, 4).cookie).toMatchObject({ value: 'en' }) + }) +}) From d45175739f5eafb9ebf1a863ebdf1f83eb897f45 Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?Rados=C5=82aw=20Smoli=C5=84ski?= Date: Thu, 22 Oct 2026 17:35:08 +0200 Subject: [PATCH 25/27] Docs: forms, security, access, construction and others match the branch Applies the docs session's forms.md diff and fixes, corrected for this branch; adds the override sections and new options. Co-Authored-By: Claude Opus 5.5 --- docs/construction.md | 21 ++++++++++++++++++++ docs/content.md | 6 ++++-- docs/forms.md | 31 ++++++++++++++++------------- docs/i18n.md | 4 +++- docs/richtext.md | 3 ++- docs/security.md | 46 +++++++++++++++++++++++++++++++++++--------- 6 files changed, 85 insertions(+), 26 deletions(-) diff --git a/docs/construction.md b/docs/construction.md index 6f4344b..7df80d9 100644 --- a/docs/construction.md +++ b/docs/construction.md @@ -29,6 +29,27 @@ normalne działanie strony. `/md/…` → 404, `list_pages` / `search_content` ich nie pokazują, `get_page` → „No page found”. Własny `createSearchRoute` / `createMcpRoute` / `createMarkdownRoute` → przekaż `isPathVisible` z `lib/content` (`createSearchRoute({ …, isPathVisible })`). +- **Proxy nie sprawdza trybu** — to wymagałoby zapytania do bazy przy każdym żądaniu; blokują + trasy, które i tak czytają treść (strona, Markdown, MCP, wyszukiwarka, sitemap, llms.txt). + +## Klocki + +```ts +import { isPathVisibleIn, pathOf } from '@intecion/ipal-kit' +isPathVisibleIn(await getConstructionMode(locale), '/pl/o-nas') // false, gdy tryb ukrywa stronę +pathOf('https://acme.pl/pl/o-nas?x=1') // '/pl/o-nas' — ścieżka z URL wyniku +``` + +`isPathVisible(path, locale)` z `createContentHelpers` = to samo z odczytem trybu (typ `PathVisibility`). + +## Wyłączenie, nadpisanie, rozszerzenie + +- **Wyłączenie:** przełącznik w Site Settings → Under construction. Markdown / MCP bez filtra mimo + włączonego trybu: `createContentHelpers({ markdown: { isPathVisible: () => true }, mcp: { isPathVisible: () => true } })`. +- **Nadpisanie:** własna reguła = własna funkcja `isPathVisible` w tych opcjach albo w `createSearchRoute`. +- **Rozszerzenie:** `isPathVisibleIn` / `isPathAllowed` / `pathOf` we własnych trasach. +- **Sprawdzenie:** tryb włączony → `/md/pl/` = 404, MCP `get_page` = „No page found”, + `list_pages` jej nie pokazuje. - **Jedna reguła dla wszystkich odwiedzających** — strony zostają statyczne (ISR), bez sprawdzania sesji. Po zmianie ustawień strony odświeżają się po rewalidacji (jak inne zmiany w Site Settings). diff --git a/docs/content.md b/docs/content.md index 0b60a6b..881ec71 100644 --- a/docs/content.md +++ b/docs/content.md @@ -108,7 +108,8 @@ komponent strony osobno. strony systemowe) przychodzą jako dokumenty (`slug`, `title`), ale **ich** relacje już jako ID. Strona, którą `resolveRoute` renderuje (homepage, archiwum, zwykła strona), jest pobierana osobno z `depth: 2`. Potrzebujesz głębiej w layoucie (np. obraz strony podlinkowanej w menu)? -Pobierz ten jeden dokument sam, zamiast podnosić głębokość całego globala na każdym żądaniu. +Pobierz ten jeden dokument sam, zamiast podnosić głębokość całego globala na każdym żądaniu — albo, +świadomie, `createContentHelpers({ settingsDepth: 2 })` (koszt na każdym żądaniu). `resolveRoute` z fabryki przyjmuje `(locale, segments, page)` — rozstrzyga trasę. Pobranie wpisów to osobna funkcja `getEntries` (patrz niżej), bo @@ -222,7 +223,8 @@ albo `null`. Plugin tylko liczy — `permanentRedirect` woła projekt (plugin ni importuje `next/navigation`). Każda kolekcja bez pola historii jest pomijana bezpiecznie. `collections[].historyField` (domyślnie `'slugHistory'`) i `slugField` (domyślnie `'slug'`) konfigurowalne. Dokument nigdy nieopublikowany (`_status: 'draft'`) -nie przekierowuje — jego nowy slug nie wycieka przez redirect. +nie przekierowuje — jego nowy slug nie wycieka przez redirect. Podgląd (`draftMode()`): +`resolveRedirect({ …, draft: true })`. Ograniczenia: tylko kolekcje „płaskie" (slug → ścieżka). Wpisy w archiwach (`/artykuly/`) nie są jeszcze obsługiwane. Jeśli `slug` jest `localized`, diff --git a/docs/forms.md b/docs/forms.md index 2d308c3..d619e04 100644 --- a/docs/forms.md +++ b/docs/forms.md @@ -59,7 +59,7 @@ Opcje `forms` (`FormsOption`): | `formOverrides` / `formSubmissionOverrides` | — | nadpisania kolekcji (`fields` jako funkcja + dowolne ustawienia kolekcji) | | `emailLayout` | `false` | ładne maile + zakładka Site Settings → Emails | | `beforeEmail` | — | `beforeEmail` form-buildera (po layoucie, gdy `emailLayout`) | -| `consentFieldName` | `'consent'` | **uwaga:** obecnie nie jest nigdzie czytana — nazwę pola zgody zmienia się przez `submitForm({ consentFieldName })` / `createSubmitAction({ consentFieldName })` | +| `consentFieldName` | `'consent'` | nazwa pola zgody RODO dla `submitForm` / `createSubmitAction` (argument wywołania wygrywa) | `payment` jest zawsze wyłączony — `fields: { payment: true }` go **nie** włącza (wartość `true` jest pomijana); włączyć można tylko podając obiekt-blok. `country` / `state` zostają z domyślnych @@ -217,13 +217,13 @@ const f = useForm({ initialValues, validate, submitAction: sendForm.bind(null, f Wynik `submitForm`: `{ success: true, submissionId }` albo `{ success: false, reason, … }` (kody niżej). Opcje: `payload`, `formId`, `data` (wymagane), `ip`, `locale`, `turnstileToken`, -`maxPerMinute` (domyślnie 5, `0` wyłącza; bez `ip` limit jest pomijany), `consentFieldName` -(`'consent'`), `turnstileOnConfigError` (`'allow'` | `'reject'`, domyślnie `'allow'` — patrz -[turnstile.md](./turnstile.md)). +`maxPerMinute` (domyślnie 5, `0` wyłącza; bez `ip` — wspólny kubełek `unknown-ip`, niżej), +`consentFieldName` (domyślnie z `ipalKit({ forms })`, potem `'consent'`), `turnstileOnConfigError` +(`'allow'` | `'reject'`, domyślnie `'allow'`), `turnstileHostnames` (patrz [turnstile.md](./turnstile.md)). Prościej: `createSubmitAction({ getCachedPayload, headers })` z `/server` (sekcja 1.9.1 niżej) — opcje dodatkowe: `clientIp`, `honeypotField`, `consentFieldName`, `maxPerMinute`, -`turnstileOnConfigError`. +`turnstileOnConfigError`, `turnstileHostnames`. ### IP klienta i rate limit @@ -236,12 +236,14 @@ opcje dodatkowe: `clientIp`, `honeypotField`, `consentFieldName`, `maxPerMinute` który trafi do aplikacji z pominięciem proxy, może więc podstawić `cf-connecting-ip` / `x-real-ip` i omijać limit. Na produkcji bez `IPAL_IP_HEADER` jest jednorazowe ostrzeżenie w logu. Ustaw np. `IPAL_IP_HEADER=cf-connecting-ip` za Cloudflare, `x-forwarded-for` tylko za Traefik/nginx. -- Brak rozpoznanego IP → limit jest **pomijany** (żądanie przechodzi). Ta sama opcja `clientIp` jest w `createSearchRoute` +- Brak rozpoznanego IP → wspólny kubełek (niżej). Ta sama opcja `clientIp` jest w `createSearchRoute` i `createMcpRoute`. Brak IP (proxy obcina nagłówek, zły `IPAL_IP_HEADER`) **nie** omija limitu: takie żądania dzielą jeden wspólny kubełek `unknown-ip` z limitem ×20 (`UNKNOWN_IP_FACTOR`) — prawdziwi -odwiedzający przechodzą, flood bez nagłówka nie. Bez przypięcia nagłówka kolejność +odwiedzający przechodzą, flood bez nagłówka nie. `setUnknownIpFactor(n)` (root, raz przy starcie) +zmienia mnożnik; `setUnknownIpFactor(0)` = dawne zachowanie (bez limitu), gdy limiter stoi z przodu. +Bez przypięcia nagłówka kolejność `cf-connecting-ip` → `x-real-ip` → XFF zostaje (zmiana na XFF-od-prawej złączyłaby za Cloudflare wszystkich odwiedzających w kubełek węzła brzegowego) — dlatego `IPAL_IP_HEADER` na produkcji jest obowiązkowe (`ipalEnvRules({ ipHeader: true })`). @@ -436,8 +438,8 @@ export const sendForm = createSubmitAction({ getCachedPayload, headers, consentF // albo: submitForm({ …, consentFieldName: 'zgoda' }) ``` -> `ipalKit({ forms: { consentFieldName } })` istnieje w typie `FormsOption`, ale obecnie -> nie jest przekazywana do `submitForm` — nie działa. +Albo raz dla całej strony: `ipalKit({ forms: { consentFieldName: 'zgoda' } })` — `submitForm` +czyta ją z `payload.config.custom.ipal`, gdy wywołanie jej nie podaje. ## Komunikaty — resolveFormMessage (zalecane) @@ -636,13 +638,16 @@ filtrować w kliencie. Pojedyncze typy pól: `forms.fields.: false`. - **Nadpisanie kolekcji:** `formOverrides` / `formSubmissionOverrides` — pola (funkcja `fields`), `labels`, `admin`, `access`, `hooks`. Domyślny dostęp zgłoszeń (`create`: zalogowani, `read`: editor+, `delete`: admin) - nadpisujesz kluczami w `formSubmissionOverrides.access`. Ukrycie zakładki Emails w publicznym API - (`hideEmails`) jest obecnie zawsze nakładane na pole `emails`. + nadpisujesz kluczami w `formSubmissionOverrides.access`; dostęp do formularzy (`create`/`update`/`delete`: + editor+, `read`: publiczny) — w `formOverrides.access`. Ochrona zakładki Emails (`read`: editor+) jest + nakładana na domyślne pola **przed** `formOverrides.fields`, więc zmienisz ją tam. - **Nadpisanie typu pola:** `forms.fields.: ` podmienia blok; własne bloki z „Placeholder” / godziną: `withPlaceholder`, `placeholderField`, `timeBlock`, `stepBlock`, `checkboxGroupBlock` (root). - **Bramki wysyłki:** `submitForm` / `createSubmitAction` — `maxPerMinute` (`0` = bez limitu), - `turnstileOnConfigError`, `consentFieldName`, `clientIp`, `honeypotField`; wspólny store limitów: - `setRateLimitStore`. + `turnstileOnConfigError`, `turnstileHostnames`, `consentFieldName`, `clientIp`, `honeypotField`; + wspólny store limitów: `setRateLimitStore`; brak IP: `setUnknownIpFactor`. +- **Sprawdzenie:** `POST /api/form-submissions` bez sesji = 403; konto `user` → `PATCH /api/forms/` = 403; + 50 wysyłek bez nagłówka IP → po `maxPerMinute × 20` przychodzi `rate_limited`. - **Maile:** `forms.beforeEmail` modyfikuje maile (po layoucie), `emailLayout: true` włącza szablon. - **Własny front:** `BuilderForm` (`renderField`), `useBuilderForm`, czysta logika (`splitSteps`, `visibleFields`, `validateBuilderFields`…), `useForm` / `useContactForm`, walidatory, `buildFormsPlugin` (root). diff --git a/docs/i18n.md b/docs/i18n.md index 1addc3c..71f56a4 100644 --- a/docs/i18n.md +++ b/docs/i18n.md @@ -155,7 +155,9 @@ zapis podlega zgodzie: to cookie kategorii **functional**, więc: - **Zapis TYLKO za zgodą.** Middleware zapisuje `NEXT_LOCALE` jedynie, gdy użytkownik zgodził się na kategorię functional (`mayPersistLocale` sprawdza zgodę). Bez zgody język działa per żądanie (negocjacja z Accept-Language), - ale nie jest utrwalany. + ale nie jest utrwalany. Proxy nie zna wersji polityki z panelu, więc zgoda liczy się w wersji, w której + ją zapisano (po podbiciu wersji język dalej się zapisuje). Wymuszenie wersji: + `createLocaleMiddleware({ policyVersion })` / `createProxy(config, { policyVersion, … })`. - **Sprzątanie po cofnięciu zgody.** Gdy użytkownik cofnie zgodę na functional, cookie `NEXT_LOCALE` jest usuwane automatycznie (consent zna tę cookie przez `DEFAULT_COOKIE_MAP` — patrz [consent.md](./consent.md)). diff --git a/docs/richtext.md b/docs/richtext.md index e40e821..df495b8 100644 --- a/docs/richtext.md +++ b/docs/richtext.md @@ -55,7 +55,8 @@ Spread `defaultConverters` — nadpisujesz tylko te węzły, które chcesz. Resz **Linki są filtrowane jak w `` (`safeHref`).** Własny link z adresem spoza `http(s)`, `mailto`, `tel`, `sms`, `#`, `/` (np. `javascript:`, `data:`) dostaje `href="#"` — także gdy trafił -do bazy importem, seedem albo przez API, z pominięciem pola w panelu. +do bazy importem, seedem albo przez API, z pominięciem pola w panelu. Wyłączenie (tylko w pełni zaufana +treść): ``. ## Spis treści i kotwice nagłówków (1.11.1) diff --git a/docs/security.md b/docs/security.md index 2ae8e6b..599e037 100644 --- a/docs/security.md +++ b/docs/security.md @@ -1,7 +1,8 @@ # security Generyczne nagłówki bezpieczeństwa HTTP (HSTS, X-Frame-Options, nosniff, -Referrer-Policy, Permissions-Policy) jako funkcja do `next.config`. CSP CELOWO +Referrer-Policy, Permissions-Policy, Cross-Origin-Opener-Policy; `X-Robots-Tag` na stagingu) +jako funkcja do `next.config`. CSP CELOWO pominięte — zależy od domen projektu, zostaje w projekcie. ## Zasada @@ -47,11 +48,18 @@ export default withPayload(nextConfig) | `hstsMaxAge` | `63072000` (2 lata) | max-age HSTS w sekundach | | `hstsIncludeSubDomains` | `true` | HSTS na subdomeny | | `hstsPreload` | `false` | preload (tylko jeśli zgłaszasz do listy) | -| `frameOptions` | `'DENY'` | X-Frame-Options (anty-clickjacking) | -| `referrerPolicy` | `'strict-origin-when-cross-origin'` | Referrer-Policy | -| `permissionsPolicy` | blokuje camera/mic/geolocation | Permissions-Policy | +| `frameOptions` | `'DENY'` | X-Frame-Options (anty-clickjacking); `null` = bez nagłówka | +| `referrerPolicy` | `'strict-origin-when-cross-origin'` | Referrer-Policy; `null` = bez nagłówka | +| `permissionsPolicy` | blokuje camera/mic/geolocation | Permissions-Policy; własny string albo `null` = bez nagłówka | +| `coop` | `'same-origin'` | Cross-Origin-Opener-Policy; `'same-origin-allow-popups'` albo `false` = bez nagłówka | | `additional` | `[]` | dodatkowe nagłówki (np. CSP); same-key nadpisuje | +Przy `IPAL_NOINDEX=1` (staging) dochodzi `X-Robots-Tag: noindex, nofollow` na każdej odpowiedzi. + +**Uploady:** `buildUploadSecurityHeaders({ collections = ['media'] })` zwraca reguły `headers()` dla +`/api//file/*` (sandbox, bez skryptów) — SVG z dysku lokalnego nie uruchomi skryptu na domenie +strony. Wpinasz obok: `[{ source: '/:path*', headers: securityHeaders }, ...buildUploadSecurityHeaders()]`. + ## PUŁAPKA — HSTS w dev HSTS nad HTTP na localhost może zablokować przeglądarkę na HTTPS dla localhost. @@ -101,9 +109,15 @@ const securityHeaders = buildSecurityHeaders({ `object-src 'none'`, `frame-ancestors 'none'`. To te, które Lighthouse/OWASP wymagają, a łatwo je pominąć pisząc CSP ręcznie. +Bazowe źródła: `default-src 'self'`, `form-action 'self'`, `script-src 'self' 'unsafe-inline'` +(Next / analityka), `style-src 'self' 'unsafe-inline' https://fonts.googleapis.com`. `r2Url` trafia do +`img-src` tylko jako adres absolutny (`https://…`); `youtube` dokłada też `i.ytimg.com` (plakat +`YouTubeEmbed`); `googleMaps` — `*.googleapis.com`, `*.gstatic.com`, `*.google.com`, `*.ggpht.com`, +`*.googleusercontent.com` (iframe i Maps JS). + `buildCsp` NIE dodaje `'unsafe-eval'` (osłabia CSP) — dodaj przez `extra` tylko -jeśli biblioteka tego wymaga. `mode: 'report-only'` daje nagłówek -`…-Report-Only`; `'enforce'` daje `Content-Security-Policy`. +jeśli biblioteka tego wymaga. `mode` domyślnie `'enforce'` (`Content-Security-Policy`); +`'report-only'` daje `…-Report-Only` — zacznij od niego przy wdrożeniu. CSP dalej „w projekcie" (Ty wybierasz flagi wg tego, co ładujesz), ale skeleton jest z pluginu — każdy projekt ma ten sam zahardowany fundament. @@ -239,7 +253,7 @@ Bez przeniesienia folderu: `config.routes.admin = '/its'`, ale `/its` daje 404 Zmiana ścieżki utrudnia automatyczne skany, ale NIE jest zabezpieczeniem. Prawdziwa ochrona panelu: -- **2FA** dla każdego użytkownika (planowane — wymuszenie przez plugin) +- **2FA** dla każdego użytkownika (wymuszone przez plugin — sekcja niżej) - Silne hasła - Rate limiting na logowaniu - IP allowlist (jeśli panel tylko dla zespołu) @@ -303,7 +317,8 @@ zalogowaniu. Nie ma opcji „włącz/wyłącz" dla użytkownika. ```ts twoFactor: false // TYLKO gdy projekt naprawdę nie może użyć 2FA (rzadkie) ``` -Domyślnie 2FA jest WYMUSZONE. `false` to świadoma rezygnacja — unikaj. +Domyślnie 2FA jest WYMUSZONE. `false` to świadoma rezygnacja — unikaj. Pominięcie `twoFactor` +(mimo że typ jest opcjonalny) kończy start błędem `twoFactor.issuer is required` — decyzja ma być jawna. ### Jak działa dla użytkownika @@ -316,7 +331,9 @@ Domyślnie 2FA jest WYMUSZONE. `false` to świadoma rezygnacja — unikaj. ### Reset 2FA (admin) Admin może zresetować 2FA innego użytkownika (gdy zgubi telefon) — przez -`adminManageAccess` w konfiguracji @clocklimited. Patrz jego dokumentacja. +`adminManageAccess` w konfiguracji @clocklimited. ipalKit przekazuje do niego tylko `collection`, +`forceSetup` i `issuer`; inne opcje podasz, owijając wstrzykiwaną fabrykę: +`plugin: (opts) => payloadTotp({ ...opts, adminManageAccess: ({ req }) => isAdmin(req.user) })`. ### Dlaczego @clocklimited, nie inne @@ -349,3 +366,14 @@ dostęp do danych, nie tylko UI. - Site Settings, Cookie Settings, Notifications i kolekcja Forms: zapis tylko `editor+`; zakładka Emails formularza (odbiorcy, BCC) czytelna tylko dla `editor+`. - Pełna tabela: [access.md](./access.md#co-plugin-zamyka-sam). + +## Wyłączenie, nadpisanie, rozszerzenie + +- **Wyłączenie:** nagłówki — nie wołaj `buildSecurityHeaders` albo `null` / `false` per nagłówek (`frameOptions`, + `referrerPolicy`, `permissionsPolicy`, `coop`), `hsts: false`; 2FA — `twoFactor: false` (odradzane). +- **Nadpisanie:** `additional` (ten sam klucz nadpisuje nagłówek pluginu), `buildCsp({ extra })`, `mode`; + 2FA — `collectionSlug`, `allowCollectionMismatch`, własne opcje TOTP przez owinięcie `plugin`; + dostęp — `access.authAccess`, `access.firstUserAdmin`, `globalOverrides` ([access.md](./access.md)). +- **Rozszerzenie:** `buildCsp`, `buildUploadSecurityHeaders({ collections })` dla własnych kolekcji uploadów. +- **Sprawdzenie:** `curl -sI https://domena/ | grep -iE "strict-transport|x-frame|referrer|permissions|cross-origin|content-security"`; + na stagingu także `x-robots-tag`; start z błędnym `twoFactor.collectionSlug` kończy się błędem `[ipal] twoFactor…`. From 54c9d3ec107c8c41ce1fc86d177e7f88aa549e9f Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?Rados=C5=82aw=20Smoli=C5=84ski?= Date: Thu, 22 Oct 2026 17:40:02 +0200 Subject: [PATCH 26/27] isPathVisible shares one construction-mode read per list MCP and search call it once per result; React cache doesn't dedupe in route handlers, so a 50-result list read Site Settings 300 times. Concurrent calls now share one in-flight read per locale (6 reads). Co-Authored-By: Claude Opus 5.5 --- src/modules/frontend/createContentHelpers.ts | 15 ++++++++++++++- test/construction.test.ts | 10 ++++++++++ 2 files changed, 24 insertions(+), 1 deletion(-) diff --git a/src/modules/frontend/createContentHelpers.ts b/src/modules/frontend/createContentHelpers.ts index 12ac2a4..391bc65 100644 --- a/src/modules/frontend/createContentHelpers.ts +++ b/src/modules/frontend/createContentHelpers.ts @@ -697,8 +697,21 @@ export function createContentHelpers({ /** * Is this page path public right now? False for pages construction mode * hides. The Markdown and MCP routes use it; pass it to createSearchRoute. + * + * Lists call it once per result (Promise.all). React `cache` doesn't dedupe + * in route handlers, so concurrent calls share ONE in-flight mode read per + * locale — a list of 200 pages costs one Site Settings read, not 200. The + * entry is dropped once it settles, so the next request reads fresh. */ - const isPathVisible: PathVisibility = async (path, locale) => isPathVisibleIn(await getConstructionMode(locale), path) + const inflightMode = new Map>() + const isPathVisible: PathVisibility = async (path, locale) => { + let mode = inflightMode.get(locale) + if (!mode) { + mode = getConstructionMode(locale).finally(() => inflightMode.delete(locale)) + inflightMode.set(locale, mode) + } + return isPathVisibleIn(await mode, path) + } // ── Layout ──────────────────────────────────────────────────────────────── /** Notifications → form texts in this locale (BuilderForm / RenderForm `texts`). */ diff --git a/test/construction.test.ts b/test/construction.test.ts index 51ac158..15412f6 100644 --- a/test/construction.test.ts +++ b/test/construction.test.ts @@ -118,6 +118,16 @@ describe('under construction — Site Settings → createPageRoute', () => { expect(await rpc('get_page', { path: '/pl/o-nas' })).toMatch(/No page found/) expect(await rpc('search_content', { locale: 'pl', query: 'nas' })).not.toContain('/pl/o-nas') + // a whole list shares one construction-mode read (React cache doesn't dedupe in route handlers) + const readsFor = async (n: number) => { + const spy = vi.spyOn(payload, 'findGlobal') + await Promise.all(Array.from({ length: n }, (_, i) => helpers.isPathVisible(`/pl/p-${i}`, 'pl'))) + const count = spy.mock.calls.length + spy.mockRestore() + return count + } + expect(await readsFor(50)).toBe(await readsFor(1)) + expect(await helpers.isPathVisible('/pl/o-nas', 'pl')).toBe(false) expect(await helpers.isPathVisible('/pl/brief', 'pl')).toBe(true) }) From 8646585b7e270d0c8199be96d087dc27eced2cf0 Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?Rados=C5=82aw=20Smoli=C5=84ski?= Date: Thu, 22 Oct 2026 17:48:26 +0200 Subject: [PATCH 27/27] CLAUDE.md: main rule (the plugin helps projects, never limits them) and complete agent guide rule Co-Authored-By: Claude Opus 5.5 --- CLAUDE.md | 17 +++++++++++++++++ 1 file changed, 17 insertions(+) diff --git a/CLAUDE.md b/CLAUDE.md index 3e76769..d4d50e8 100644 --- a/CLAUDE.md +++ b/CLAUDE.md @@ -2,3 +2,20 @@ This project uses the Payload CMS skill at `.claude/skills/payload/`. Start with `.claude/skills/payload/SKILL.md` for a quick reference, then see `.claude/skills/payload/reference/` for detailed docs. + +## Main rule: the plugin helps projects, never limits them + +ipal-kit is a plugin. Every change must leave the consuming project free to adapt it. + +- Every module and feature can be turned off on its own. Turning one off never takes away anything the project still needs. +- Every default can be overridden: access rules, fields, hooks, labels, routes, collections and globals. The project's own config is merged with the plugin's and wins. +- Secure defaults are welcome. They come with an option to loosen or extend them, never as a hard lock. +- Export the building blocks (helpers, builders, hooks), not only finished features. +- Never force a dependency, route, UI or data shape where an option or an exported piece would do. + +## Rule: an agent that adds the plugin gets the complete guide + +When an agent adds ipal-kit to a project, `docs/agent/AGENT.md` and the `ipal-*` skills (installed by `ipal-skills`) must tell it how to set up and use every function the plugin supports. + +- Every export, option, env var, route, middleware, layout component, admin import-map entry and hook a project must wire is documented, with steps and a way to verify it. +- A change that adds or alters a feature updates the agent guide and the matching skill in the same change.