Merge security and performance track (audit fixes, secure defaults with overrides)

Co-Authored-By: Claude Opus 5.5 <[email protected]>
This commit is contained in:
Radosław Smoliński
2026-10-22 17:48:17 +02:00
co-authored by Claude Opus 5.5
71 changed files with 1769 additions and 181 deletions
+76 -10
View File
@@ -9,21 +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ć. Kolekcja należy do Ciebie
(create-payload-app) — plugin tylko dokłada pole.
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`,
`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)
@@ -80,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/<id admina>` = 403; konto z „Create first user” ma rolę `admin`.
+10 -2
View File
@@ -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`.** `<SiteProviders analytics={{ consentMode: 'basic' }}>` (albo
`<Analytics consentMode="basic" />`): 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.
+1 -1
View File
@@ -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 })` +
`<ConsentProvider logEndpoint="/api/ipal/consent">`. 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` + `<CookieTable>` z `/rsc`.
- Ciasteczko zgody ma `Secure` na HTTPS.
+25
View File
@@ -25,6 +25,31 @@ 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 })`).
- **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/<ukryta>` = 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).
+12 -2
View File
@@ -104,6 +104,13 @@ 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 — 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
routing i pobieranie danych to dwie różne odpowiedzialności.
@@ -215,7 +222,9 @@ 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. Podgląd (`draftMode()`):
`resolveRedirect({ …, draft: true })`.
Ograniczenia: tylko kolekcje „płaskie" (slug → ścieżka). Wpisy w archiwach
(`/artykuly/<wpis>`) nie są jeszcze obsługiwane. Jeśli `slug` jest `localized`,
@@ -324,7 +333,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`.
+92 -21
View File
@@ -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'` | 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
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' ? <Cards …/> : 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,18 +216,38 @@ 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` — 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`, `turnstileHostnames`.
### 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 → 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. `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 })`).
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).
@@ -298,14 +336,22 @@ 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
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
@@ -340,7 +386,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' }
@@ -364,9 +410,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
@@ -387,9 +434,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' })
```
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)
Zamiast ręcznego switcha po `reason`, użyj `resolveFormMessage` z modułu
@@ -557,7 +608,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)
```
@@ -580,3 +631,23 @@ 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.<typ>: 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`; 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.<typ>: <Block>` podmienia blok; własne bloki z „Placeholder” /
godziną: `withPlaceholder`, `placeholderField`, `timeBlock`, `stepBlock`, `checkboxGroupBlock` (root).
- **Bramki wysyłki:** `submitForm` / `createSubmitAction` — `maxPerMinute` (`0` = bez limitu),
`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/<id>` = 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).
+23
View File
@@ -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
@@ -71,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).
---
@@ -166,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`.
+3 -1
View File
@@ -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)).
+2 -1
View File
@@ -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`).
+1 -1
View File
@@ -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).
+5
View File
@@ -53,6 +53,11 @@ 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 `<CMSLink>` (`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. Wyłączenie (tylko w pełni zaufana
treść): `<RenderRichText data={…} safeLinks={false} />`.
## 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.
+54 -11
View File
@@ -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/<kolekcja>/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)
@@ -274,7 +288,8 @@ ipalKit({
twoFactor: {
issuer: 'Nazwa Firmy', // pokazywane w aplikacji authenticator
plugin: payloadTotp, // ← WSTRZYKNIJ — patrz niżej dlaczego
// collectionSlug: '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
},
})
```
@@ -302,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
@@ -315,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
@@ -329,8 +347,33 @@ 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).
- `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ę 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).
## 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…`.
+3 -1
View File
@@ -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)
+7
View File
@@ -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).
+8 -8
View File
@@ -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'
+5 -3
View File
@@ -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'
+2
View File
@@ -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',
+2
View File
@@ -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,
+4
View File
@@ -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',
+44
View File
@@ -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<GlobalConfig>
export type GlobalOverrides = Partial<Record<IpalGlobalSlug, GlobalOverride>>
type Hooks = NonNullable<GlobalConfig['hooks']>
function mergeHooks(base: GlobalConfig['hooks'], extra: GlobalConfig['hooks']): GlobalConfig['hooks'] {
if (!extra) {return base}
const out: Record<string, unknown[]> = { ...(base as Record<string, unknown[]>) }
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),
}
})
}
+22 -25
View File
@@ -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,
@@ -6,15 +8,19 @@ export {
adminOrEditorField,
adminOrSelf,
authenticated,
buildRolesField,
hasMinimumRole,
injectRoles,
isAdmin,
isEditor,
requireRole,
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'
@@ -42,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,
@@ -112,27 +120,16 @@ 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 { 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'
@@ -177,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'
@@ -224,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'
+1 -1
View File
@@ -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,
+21 -1
View File
@@ -14,8 +14,15 @@ 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 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`. `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',
@@ -29,6 +36,19 @@ export function buildRolesField(defaultRole: Role = 'user'): Field {
},
defaultValue: [defaultRole],
hasMany: true,
...(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,
+16
View File
@@ -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
}
+37 -4
View File
@@ -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
+3 -10
View File
@@ -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)}`)
-1
View File
@@ -23,4 +23,3 @@ export {
serializeConsent,
} from './storage.js'
export type { ConsentTexts } from './texts.js'
export { useIsMounted } from './useIsMounted.js'
+11
View File
@@ -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<ConstructionMode, 'allowedPaths' | 'enabled'>, pathname: string): boolean {
return !mode.enabled || isPathAllowed(pathname, mode.allowedPaths)
}
+10
View File
@@ -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<boolean>
/** Pathname of a result URL (absolute or relative), for a PathVisibility check. */
export const pathOf = (url: string): string => new URL(url, 'http://localhost').pathname
+12 -2
View File
@@ -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<BasePayload> } & CreateMarkdownRendererArgs,
args: {
getCachedPayload: () => Promise<BasePayload>
/** Hide pages the site hides (construction mode) — 404 like an unknown page. */
isPathVisible?: PathVisibility
} & CreateMarkdownRendererArgs,
): { GET: (req: Request, ctx: MarkdownRouteContext) => Promise<Response> } {
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) {
+8 -2
View File
@@ -3,6 +3,7 @@ import type { BasePayload } from 'payload'
import type { I18nConfig } from '../i18n/index.js'
import type { ClientIpOptions } from '../shared/rateLimit.js'
import { pathOf, type PathVisibility } from '../construction/visibility.js'
import { clientIp, consumeRateLimit, tooManyRequests } from '../shared/rateLimit.js'
import { searchContent } from './searchContent.js'
@@ -19,6 +20,8 @@ type CreateSearchRouteArgs = {
getCachedPayload: () => Promise<BasePayload>
/** Home slug map/string so the home result collapses to root. */
homeSlug?: Record<string, string> | 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).
@@ -47,7 +50,7 @@ type CreateSearchRouteArgs = {
* Uses the global Request/Response — no next/server import.
*/
export function createSearchRoute(args: CreateSearchRouteArgs): (req: Request) => Promise<Response> {
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' } },
+11 -1
View File
@@ -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, string> | string
/** Active locale (the request's locale). */
@@ -34,7 +39,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
@@ -66,6 +71,7 @@ type DocShape = { slug?: unknown }
export async function resolveRedirect({
collections = [{ slug: 'pages' }],
config,
draft = false,
homeSlug,
locale,
payload,
@@ -90,6 +96,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 (!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
}
+12 -2
View File
@@ -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<string, unknown>,
doc: doc as Record<string, unknown>,
page,
perPage: collection.perPage ?? 10,
}
+3 -1
View File
@@ -21,7 +21,7 @@ type CreateSubmitActionArgs = {
headers: () => Headers | Promise<Headers>
/** Honeypot field name. Default HONEYPOT_FIELD. */
honeypotField?: string
} & Pick<SubmitFormArgs, 'consentFieldName' | 'maxPerMinute' | 'turnstileOnConfigError'>
} & Pick<SubmitFormArgs, 'consentFieldName' | 'maxPerMinute' | 'turnstileHostnames' | 'turnstileOnConfigError'>
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,
})
+21 -5
View File
@@ -26,18 +26,25 @@ 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
* GET /api/forms doesn't hand out the company's inboxes to spammers.
* tab — recipient addresses, templates — is for editors and admins only, so
* 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) =>
'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,9 +111,18 @@ 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),
fields: ({ defaultFields }) => {
const protectedFields = hideEmails(defaultFields)
return forms.formOverrides?.fields ? forms.formOverrides.fields({ defaultFields: protectedFields }) : protectedFields
},
},
formSubmissionOverrides: {
labels: { plural: 'Submissions', singular: 'Submission' },
+1
View File
@@ -5,6 +5,7 @@ export {
consumeRateLimit,
retryAfterSeconds,
setRateLimitStore,
setUnknownIpFactor,
tooManyRequests,
} from '../shared/rateLimit.js'
export type { ClientIpOptions, RateLimitArgs, RateLimitStore } from '../shared/rateLimit.js'
+13 -5
View File
@@ -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. */
@@ -27,6 +28,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,12 +104,14 @@ export async function submitForm({
locale,
maxPerMinute = 5,
payload,
turnstileHostnames,
turnstileOnConfigError = 'allow',
turnstileToken,
}: SubmitFormArgs): Promise<SubmitFormResult> {
// 1. Rate limit — cheapest gate, drops a flood before any real work.
if (maxPerMinute > 0 && ip) {
if (!(await consumeRateLimit({ key: ip, max: maxPerMinute })).ok) {
// 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 +122,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 }
}
@@ -125,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 }
+39 -5
View File
@@ -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 { 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'
@@ -53,7 +55,7 @@ type CreateContentHelpersArgs = {
*/
i18n?: I18nConfig
/** Markdown route (`markdownRoute`): per-block overrides, frontmatter, layout field. */
markdown?: { frontmatter?: boolean; layoutField?: string; overrides?: Record<string, (block: Record<string, unknown>) => string> }
markdown?: { frontmatter?: boolean; isPathVisible?: PathVisibility; layoutField?: string; overrides?: Record<string, (block: Record<string, unknown>) => string> }
/**
* Advertise each page's Markdown version from generatePageMetadata:
* `<link rel="alternate" type="text/markdown" href="/md/pl/o-nas">` (GEO —
@@ -63,7 +65,7 @@ type CreateContentHelpersArgs = {
*/
markdownAlternate?: boolean | string
/** MCP route (`mcpRoute`): server name/version, rate limit, batch size. */
mcp?: Pick<CreateMcpRouteArgs, 'clientIp' | 'maxBatch' | 'rateLimit' | 'serverName' | 'serverVersion'>
mcp?: Pick<CreateMcpRouteArgs, 'clientIp' | 'isPathVisible' | 'maxBatch' | 'rateLimit' | 'serverName' | 'serverVersion'>
/** Defaults for getPageJsonLd — each call can override them. */
pageJsonLd?: PageJsonLdOptions
/** Pages collection slug. Defaults to 'pages'. */
@@ -76,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
/**
@@ -169,6 +177,7 @@ export function createContentHelpers({
pagesSlug = 'pages',
redirectCollections,
robots: robotsOptions,
settingsDepth = 1,
settingsSlug = 'site-settings',
siteJsonLd,
sitemapImages,
@@ -188,10 +197,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: settingsDepth, locale: locale as never })
})
/** What does this URL point at? Routing only — no listing data. */
@@ -680,6 +694,25 @@ 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 inflightMode = new Map<string, Promise<ConstructionMode>>()
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`). */
const getFormTexts = cache(async (locale: string): Promise<FormNotificationTexts> =>
@@ -732,8 +765,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 }))
@@ -772,6 +805,7 @@ export function createContentHelpers({
healthRoute,
i18n,
indexNowKeyRoute,
isPathVisible,
llmsFullRoute,
llmsRoute,
manifest,
+2 -2
View File
@@ -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) {
@@ -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<string, unknown>
} 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
+23 -1
View File
@@ -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
}
}
+2 -1
View File
@@ -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'
+1 -1
View File
@@ -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<string, unknown>
if (!settings) {return}
+11
View File
@@ -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'
+2
View File
@@ -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
}
/**
+1 -9
View File
@@ -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'
+21 -1
View File
@@ -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
}
+25 -4
View File
@@ -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'
@@ -57,6 +59,11 @@ export type CreateMcpRouteArgs = {
/** Archive-backed collections (same as the plugin option) for get_page. */
content?: ContentOption
getCachedPayload: () => Promise<BasePayload>
/**
* 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
/**
@@ -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<T extends { url: string }>(items: T[], locale: string): Promise<T[]> {
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 | object> {
// `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.
+11 -2
View File
@@ -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). */
@@ -30,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 }
@@ -96,8 +103,10 @@ function withHeadingIds(
* <TableOfContents items={extractHeadings(page.content)} label={toc.label} /> // /client
* <RenderRichText data={page.content} headingIds={{ className: 'scroll-mt-24' }} />
*/
export function RenderRichText({ className, converters, data, headingIds }: RenderRichTextProps) {
if (!data) {return null}
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 = safeLinks ? sanitizeRichTextLinks(raw) : raw
if (headingIds) {
const opts = headingIds === true ? {} : headingIds
const ids = computeHeadingIds(data, opts.levels ? { levels: opts.levels } : {})
+43
View File
@@ -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
* <CMSLink> (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<T>(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
}
+29
View File
@@ -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)}`)
})
}
}
+41 -9
View File
@@ -69,6 +69,34 @@ 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'
/** Default multiplier for the shared no-IP bucket. */
export const UNKNOWN_IP_FACTOR = 20
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 {
const now = Date.now()
sweep(now)
@@ -87,11 +115,13 @@ 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 (setUnknownIpFactor).
*/
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 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
@@ -108,12 +138,14 @@ 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 resolved = resolveKey(rawKey, rawMax)
if (!resolved) {return { ok: true, retryAfter: 0 }}
const { key, max } = resolved
const id = `${scope}:${key}`
let bucket: Bucket
@@ -164,8 +196,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
+3 -9
View File
@@ -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)}`)
}
+12
View File
@@ -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<string, string> = {
* 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' }
}
+77 -7
View File
@@ -5,15 +5,17 @@ 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 { 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'
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'
@@ -48,10 +50,23 @@ export const ipalKit = (options: IpalOptions): Plugin => {
validateI18nConfig(options.i18n)
return async (incomingConfig: Config): Promise<Config> => {
// 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<Config> {
let config = { ...incomingConfig }
@@ -65,10 +80,33 @@ 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), 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 = [
...(config.collections ?? []),
{ slug: authSlug, admin: { useAsTitle: 'email' }, auth: true, fields: [] },
{
slug: authSlug,
...(hasRoles
? {
access: {
create: adminOnly,
delete: adminOnly,
read: adminOrSelf,
unlock: adminOnly,
update: adminOrSelf,
...options.access?.authAccess,
},
}
: {}),
admin: { useAsTitle: 'email' },
auth: true,
fields: [],
},
]
}
@@ -108,8 +146,30 @@ export const ipalKit = (options: IpalOptions): Plugin => {
)
}
// 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 ?? 'users',
collection: target,
forceSetup: true, // ENFORCED — every user must set up TOTP; no opt-out
totp: { issuer: tf.issuer },
})(config)
@@ -199,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 ---
@@ -212,8 +276,7 @@ export const ipalKit = (options: IpalOptions): Plugin => {
: []),
]
config.globals = [
...(config.globals ?? []),
const pluginGlobals = [
buildSiteSettings({
additionalFields: options.siteSettingsFields,
...(options.pages ? { constructionFields: buildConstructionFields(options.pages.slug) } : {}),
@@ -224,6 +287,13 @@ 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
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]
+37 -2
View File
@@ -12,9 +12,11 @@ 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'
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'
@@ -60,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
/**
@@ -69,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
/**
@@ -88,6 +103,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.
@@ -119,7 +143,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
+241
View File
@@ -0,0 +1,241 @@
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> = {}): 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<Config>),
)
expect(plugin).toHaveBeenCalledWith(expect.objectContaining({ collection: 'staff' }))
})
const twoAuth = () =>
empty({
admin: { user: 'admins' },
collections: [
{ slug: 'admins', auth: true, fields: [] },
{ slug: 'users', auth: true, fields: [] },
{ slug: 'pages', fields: [] },
],
} as Partial<Config>)
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({
i18n,
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/)
})
})
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)
})
})
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)[] } }
const count = vi.fn(async () => ({ totalDocs }))
return roles.hooks?.beforeChange?.[0]?.({
collection: { slug: 'users' },
operation: 'create',
req: { pathname, 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'])
})
test('an open sign-up on an empty collection is not promoted', async () => {
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)
})
})
+19
View File
@@ -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)
})
})
+69 -1
View File
@@ -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', () => {
@@ -87,4 +93,66 @@ 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({ 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<string, unknown>) => {
const res = await helpers.mcpPOST(
new Request('https://acme.pl/api/mcp', {
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',
}),
)
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')
// 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)
})
})
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'])
})
})
+44
View File
@@ -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<string>()
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([])
})
})
+46
View File
@@ -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' }] } as const
/** Mimics the Local API: a call with `req` sets req.locale / req.fallbackLocale to its own. */
function fakeReq() {
const req: Record<string, unknown> = { fallbackLocale: 'pl', locale: 'pl' }
const adopt = (args: { locale?: string; req?: Record<string, unknown> }) => {
if (args.req && args.locale) {
args.req.locale = args.locale
args.req.fallbackLocale = 'null'
}
}
const findByID = vi.fn(async (args: { locale?: string; req?: Record<string, unknown> }) => {
adopt(args)
return { id: 1, layout: [{ id: 'r1', blockType: 'hero', image: 7 }] }
})
const update = vi.fn(async (args: { locale?: string; req?: Record<string, unknown> }) => {
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<typeof vi.fn> }).findGlobal).toHaveBeenCalledWith(expect.objectContaining({ req }))
})
})
+34
View File
@@ -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<string, string>) {
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' })
})
})
+10
View File
@@ -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' }))
+12 -3
View File
@@ -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', () => {
+13 -2
View File
@@ -5,6 +5,8 @@ import {
clientIp,
consumeRateLimit,
setRateLimitStore,
setUnknownIpFactor,
UNKNOWN_IP_FACTOR,
} from '../src/modules/shared/rateLimit.js'
const req = (headers: Record<string, string>) => new Request('http://x/', { headers })
@@ -64,8 +66,17 @@ 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('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)}
expect(checkRateLimit({ key: '', max: 2, scope })).toBe(false)
})
})
+30
View File
@@ -0,0 +1,30 @@
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' }] } 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({ 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({ slug: 'tajny-projekt', _status: 'draft' })
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')
})
})
+70
View File
@@ -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<void>(() => {})) },
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<Response>)(
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 = <T>(p: Promise<T>) => 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'))
})
})
+34
View File
@@ -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' }] } as const
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()
})
})
+51
View File
@@ -0,0 +1,51 @@
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<typeof doc>) =>
(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,<script>alert(1)</script>', '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:[email protected]'), 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])
})
})
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,<script>alert(1)</script>' }, 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')
})
})
+92
View File
@@ -0,0 +1,92 @@
/** 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<typeof buildConfig>
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: { 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: { featured: home.id, homepage: 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' })
})
})
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' })
})
})
+35
View File
@@ -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()
@@ -109,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({