IAWL ideas, group B: sizes before work, one link rule, no stand-in locale, strict switches

- Request bodies from strangers are read only up to a cap, declared length or not:
  mail-service confirm, CSP reports, page views, MCP (maxBytes, 413). readCappedBody moves
  to shared/ (the consent log keeps exporting it).
- searchContent / createSearchRoute / MCP search: queryLimit (default 200 characters,
  10 words) before the database; an unknown ?locale is the default locale throughout.
- Rich text: autolinks and links marked internal pass safeHref too; lexicalToMarkdown
  drops unsafe link targets.
- truncate() never returns more than its limit (summary / meta autofill after validation).
- resolveRoute answers null for a locale the site does not have (xx, all, *): no
  default-locale page under another code (page route past the proxy, /md/xx, MCP).
- A 404 page that is a draft is not shown (resolveNotFoundPage, getNotFoundPage).
- readPublished() access rule (exported); Site integrations readVersions: admin.
- Plugin switches, buildCsp, buildSecurityHeaders and the seed guard refuse nonsense
  values at start; an unknown role name is met by nobody, requireRole throws on one.
- Docs, AGENT.md, iapl-collection and iapl-audit skills.

Co-Authored-By: Claude Opus 5.5 <[email protected]>
This commit is contained in:
Radosław Smoliński
2026-11-26 20:25:26 +01:00
co-authored by Claude Opus 5.5
parent e821d52d19
commit ecf03c8dc0
38 changed files with 914 additions and 69 deletions
+12 -1
View File
@@ -169,7 +169,7 @@ They fail closed: where the staff collections are not known, nobody is staff, an
### Collection-level (return boolean | Where) ### Collection-level (return boolean | Where)
```ts ```ts
import { adminOnly, adminOrEditor, adminOrSelf, adminOrSelfIn, requireRole, authenticated } from '@intecion/ipal-kit' import { adminOnly, adminOrEditor, adminOrSelf, adminOrSelfIn, readPublished, requireRole, authenticated } from '@intecion/ipal-kit'
export const Articles = { export const Articles = {
slug: 'articles', slug: 'articles',
@@ -191,8 +191,19 @@ access: { read: adminOrSelf } // fine with a single auth collection
// any minimum threshold // any minimum threshold
access: { update: requireRole('editor') } access: { update: requireRole('editor') }
// a collection with drafts: editors (or the role you name) read everything; visitors, plain `user` accounts and a
// session that still owes its second factor read published documents only — by id, in lists, with ?draft=true and
// over GraphQL. Payload's open `read: () => true` answers ?draft=true with the draft itself (1.17.1).
access: { read: readPublished(), readVersions: readPublished() }
access: { read: readPublished('admin') }
``` ```
A role name the plugin does not know (`requireRole('Admin')`, `readPublished('superadmin')`) throws where the rule
is written; `hasMinimumRole` / `userMeetsRole` answer `false` for it (before 1.17.1 every staff account met it).
`readPublished` with `?draft=true` on a page whose newest version is a draft answers a visitor `404` (Payload applies
the rule to that version), never the draft.
### Field-level (return boolean) ### Field-level (return boolean)
```ts ```ts
+7 -2
View File
@@ -1103,7 +1103,7 @@ project → **plugin gap**, not a copy.
| ISR after save, old slug → 308, images across languages | `buildRevalidateHook`, `trackSlugHistoryHook`, `buildCrossLocaleFieldSync` | hooks.md | | ISR after save, old slug → 308, images across languages | `buildRevalidateHook`, `trackSlugHistoryHook`, `buildCrossLocaleFieldSync` | hooks.md |
| ISR after a global is saved | plugin globals: `iapl({ revalidatePath })`; your own globals: `buildGlobalRevalidateHook({ revalidatePath })` | hooks.md | | ISR after a global is saved | plugin globals: `iapl({ revalidatePath })`; your own globals: `buildGlobalRevalidateHook({ revalidatePath })` | hooks.md |
| Change a plugin global (access, hooks, fields) | `iapl({ globalOverrides })` | access.md | | Change a plugin global (access, hooks, fields) | `iapl({ globalOverrides })` | access.md |
| Roles and access | `adminOnly`, `adminOrEditor`, `adminOrSelf`, `adminOrSelfIn(slug)` (several auth collections), `authenticated`, `requireRole`, `hasMinimumRole` (+ `…Field`); staff checks: `userMeetsRole(req, role)`, `isAdmin(req.user, req.payload)` (roles count only for accounts of a staff collection; in a client component `isAdmin(user, config)` with `useConfig()`, imported from **`@intecion/ipal-kit/client`** (the main entry does not build there with webpack), in middleware `isAdmin(user, { staffCollections: ['users'] })` — without the last argument there it is always `false`), `staffCollectionSlugs(payload)`, `access.staffCollections`; second factor in your own code: `secondFactorPassed(req)`, `requireSecondFactor(access)`; injected `users`: `access.authAccess`, first user = admin (`access.firstUserAdmin`) | access.md, security.md | | Roles and access | `adminOnly`, `adminOrEditor`, `adminOrSelf`, `adminOrSelfIn(slug)` (several auth collections), `authenticated`, `requireRole`, `hasMinimumRole` (+ `…Field`); a collection with drafts: `access: { read: readPublished(), readVersions: readPublished() }` (editors read drafts, everybody else published only — Payload's open `read: () => true` answers `?draft=true` with the draft; verify: `GET /api/<slug>/<draft id>?draft=true` without a session → 404); an unknown role name throws where the rule is written; staff checks: `userMeetsRole(req, role)`, `isAdmin(req.user, req.payload)` (roles count only for accounts of a staff collection; in a client component `isAdmin(user, config)` with `useConfig()`, imported from **`@intecion/ipal-kit/client`** (the main entry does not build there with webpack), in middleware `isAdmin(user, { staffCollections: ['users'] })` — without the last argument there it is always `false`), `staffCollectionSlugs(payload)`, `access.staffCollections`; second factor in your own code: `secondFactorPassed(req)`, `requireSecondFactor(access)`; injected `users`: `access.authAccess`, first user = admin (`access.firstUserAdmin`) | access.md, security.md |
| Data from globals | `getGlobal`, `getSiteSettings`, `getSiteIntegrations` | payload-helpers.md | | Data from globals | `getGlobal`, `getSiteSettings`, `getSiteIntegrations` | payload-helpers.md |
**Links and navigation** **Links and navigation**
@@ -1141,7 +1141,7 @@ project → **plugin gap**, not a copy.
| Product / category JSON-LD (an entry that is not an article) | `pageJsonLd.entries` + `buildProductJsonLd` | seo.md | | Product / category JSON-LD (an entry that is not an article) | `pageJsonLd.entries` + `buildProductJsonLd` | seo.md |
| llms.txt / llms-full / Markdown / MCP | `llmsRoute`, `llmsFullRoute`, `markdownRoute`, `mcpGET`/`mcpPOST`; `markdownAlternate: true`; `createProxy({ markdown: true })` | seo.md, content.md, mcp.md | | llms.txt / llms-full / Markdown / MCP | `llmsRoute`, `llmsFullRoute`, `markdownRoute`, `mcpGET`/`mcpPOST`; `markdownAlternate: true`; `createProxy({ markdown: true })` | seo.md, content.md, mcp.md |
| IndexNow | `iapl({ indexNow: true })` + `indexNowKeyRoute` | seo.md | | IndexNow | `iapl({ indexNow: true })` + `indexNowKeyRoute` | seo.md |
| Search | `createSearchRoute({ …, isPathVisible })` | content.md | | Search | `createSearchRoute({ …, isPathVisible })`; `queryLimit` (default `SEARCH_QUERY_LIMIT` = `{ length: 200, words: 10 }`, `limitQuery(query, limit)` shows the cut — a longer query is cut before the database; `false` = whole query); an unknown `?locale` is the default locale | content.md |
**Media, look, speed** **Media, look, speed**
| Need | Use | Doc | | Need | Use | Doc |
@@ -1211,6 +1211,11 @@ add missing hosts with flags / `extra`; (3) change `mode` to `'enforce'` in both
| Text written in one language fills the empty languages (cookie list, cookie review), never over a language's own text | `fillEmptyLocales: false` | `fillEmptyLocales: { 'cookie-settings': [...], 'cookie-review': [...] }`; `buildFillEmptyLocalesGlobalHook` / `…CollectionHook` for your own globals and collections | | Text written in one language fills the empty languages (cookie list, cookie review), never over a language's own text | `fillEmptyLocales: false` | `fillEmptyLocales: { 'cookie-settings': [...], 'cookie-review': [...] }`; `buildFillEmptyLocalesGlobalHook` / `…CollectionHook` for your own globals and collections |
| Cookie approval: one summary + **Approve and add** (editor+), unknown cookies approved as `marketing` + "Needs description", dashboard reminder while cookies wait; nothing reaches the cookie banner before approval | `cookieScanner.approval: false` (per-entry review) | `approval.unknownCategory`, `approval.dashboard: false`; building blocks `approveCookies`, `loadCookieApproval`, `countPendingCookies`, `flagGoneEntries`, `sameCookie` | | Cookie approval: one summary + **Approve and add** (editor+), unknown cookies approved as `marketing` + "Needs description", dashboard reminder while cookies wait; nothing reaches the cookie banner before approval | `cookieScanner.approval: false` (per-entry review) | `approval.unknownCategory`, `approval.dashboard: false`; building blocks `approveCookies`, `loadCookieApproval`, `countPendingCookies`, `flagGoneEntries`, `sameCookie` |
| Cookie review: scan + review editor+, delete admin; Open Cookie Database "Functional" → `functional` | omit `cookieScanner` | `cookieScanner.access`, `collectionOverrides`, `databaseCategories`, `integrations`, `declarations`, `labels`, `syncAccepted: false`; building blocks `runCookieScan`, `collectCookieFindings`, `applyCookieFindings` | | Cookie review: scan + review editor+, delete admin; Open Cookie Database "Functional" → `functional` | omit `cookieScanner` | `cookieScanner.access`, `collectionOverrides`, `databaseCategories`, `integrations`, `declarations`, `labels`, `syncAccepted: false`; building blocks `runCookieScan`, `collectCookieFindings`, `applyCookieFindings` |
| Plugin switches read strictly (1.17.1): a nonsense value (`accounts: 0`, `stats: 'false'`, `consentLog: { retentionDays: null }`, `dashboardAlerts.integrations: 'Admin'`, a 0 window in `mail.relay`, `storageNames: 'IAPL'`, …) stops the start with the option's name; `buildSecurityHeaders` / `buildCsp` likewise (`extra` values are arrays) | — (pass a real value: `true` / `false`, an object, a number in range) | security.md "Switches are read strictly"; verify: `pnpm build` starts, or the error names the option |
| Request bodies from strangers are read only up to a cap, declared length or not (1.17.1): consent log 4 KiB, page views 4 KiB, mail-service confirm 2 KiB, CSP reports `maxBytes` 16 KiB, MCP `maxBytes` 64 KiB → `413` | — | `createMcpRoute({ maxBytes })`, `createCspReportRoute({ maxBytes })`, `readCappedBody(request, max)` |
| Rich-text links: one rule for every stored URL — `link`, `autolink` (also marked internal) and the Markdown output (`lexicalToMarkdown`) drop `javascript:` / `data:` targets | `safeLinks={false}` (trusted content only) | `sanitizeRichTextLinks`, `safeHref` |
| Locales: no stand-in — `resolveRoute` (page route, `/md/…`, MCP `get_page`) answers `null` for a locale the site does not have (`xx`, `all`); a 404 page that is a draft is not shown (built-in view instead) | — | `isSiteLocale(payload, locale)`; verify: `curl -i <site>/md/xx` → 404 |
| Site integrations versions (when a project turns them on) are read by admins only (`readVersions`) | — | `globalOverrides: { 'site-integrations': { access: { readVersions } } }` |
| Consent log on (since 1.17.0; Postgres / SQLite: a migration in the same deploy) | `consentLog: false`; one layout: `logEndpoint={false}` | `consentLog: { retentionDays, collectionOverrides }`; `buildConsentLogCollection` / `buildConsentLogEndpoint`, `CONSENT_LOG_PATH` | | Consent log on (since 1.17.0; Postgres / SQLite: a migration in the same deploy) | `consentLog: false`; one layout: `logEndpoint={false}` | `consentLog: { retentionDays, collectionOverrides }`; `buildConsentLogCollection` / `buildConsentLogEndpoint`, `CONSENT_LOG_PATH` |
| Global Privacy Control honoured: no banner, analytics and marketing off, no Google request also in Consent Mode `advanced`; a grant made without the signal is switched off when it appears | `gpc={false}` (doctor warns) | `gpc="ask"`; `resolveConsent`, `gpcFromHeaders`, `consentBannerScript({ gpc })` | | Global Privacy Control honoured: no banner, analytics and marketing off, no Google request also in Consent Mode `advanced`; a grant made without the signal is switched off when it appears | `gpc={false}` (doctor warns) | `gpc="ask"`; `resolveConsent`, `gpcFromHeaders`, `consentBannerScript({ gpc })` |
| "Reject" styled like "Accept all" (`equalChoice`) | `equalChoice={false}` (doctor warns) | `classNames.rejectButton` | | "Reject" styled like "Accept all" (`equalChoice`) | `equalChoice={false}` (doctor warns) | `classNames.rejectButton` |
+5
View File
@@ -69,4 +69,9 @@ names, env, admin, AGENTS.md, skills, seeds and — with `--url` / `--deep` —
rolled out). Report-only for more than a few weeks with clean reports → WARNING (switch to `mode: 'enforce'`). rolled out). Report-only for more than a few weeks with clean reports → WARNING (switch to `mode: 'enforce'`).
Then open `/pl` and `/admin` in the browser: CSP lines in the console = missing sources (flags / `extra`). Then open `/pl` and `/admin` in the browser: CSP lines in the console = missing sources (flags / `extra`).
- **Drafts and locales over the API** (a collection with `versions: { drafts: true }`): without a session,
`curl -s "$U/api/<slug>?draft=true&limit=100" | grep -c '"_status":"draft"'` → `0`, else ERROR: give it
`access: { read: readPublished(), readVersions: readPublished() }` (access.md). `curl -sI "$U/md/xx"` → `404`
(no stand-in locale); a 404 page assigned in System pages must be published.
Do not say "done" until the full audit (without `--quick`) has no errors. Do not say "done" until the full audit (without `--quick`) has no errors.
@@ -46,6 +46,9 @@ Ask only when the brief leaves a business question open (e.g. "do posts have aut
**No URL prefix in code** — the editor assigns the archive page in **No URL prefix in code** — the editor assigns the archive page in
Site settings (`<slug>Archive`). The plugin handles routing, sitemap, Site settings (`<slug>Archive`). The plugin handles routing, sitemap,
generateStaticParams, hreflang. generateStaticParams, hreflang.
**With drafts** (`versions: { drafts: true }`): `access: { read: readPublished(), readVersions: readPublished() }`
— Payload's open `read: () => true` answers `?draft=true` with the draft over REST and GraphQL. Check:
`curl -i <site>/api/<slug>/<draft id>?draft=true` without a session → `404`; the same with an editor's token → the draft.
3. Entry list = a block (EntriesList) with `getEntries`; the entry page uses 3. Entry list = a block (EntriesList) with `getEntries`; the entry page uses
`resolveRoute` (type `entry`); JSON-LD per seo.md (e.g. Article). `resolveRoute` (type `entry`); JSON-LD per seo.md (e.g. Article).
4. **An auth collection for visitors** (`auth: true`: customers, members) only when the client requires it 4. **An auth collection for visitors** (`auth: true`: customers, members) only when the client requires it
+12 -2
View File
@@ -89,6 +89,11 @@ Without `draft: true`, documents with a `_status` other than `published` (page,
entry) give `null`. The page assigned as 404 in System pages also gives `null` entry) give `null`. The page assigned as 404 in System pages also gives `null`
(a real 404 instead of a soft 404). (a real 404 instead of a soft 404).
**A locale the site does not have gives `null` (1.17.1).** `xx`, `all` or `*` — from a URL that went past the
proxy (a dotted path, the Markdown route `/md/xx`) or a caller — used to resolve the default locale's page under that
code; now it is "not found". `isSiteLocale(payload, locale)` is the same check for your own code. A site without
localization is not affected.
Logic: the first segment is matched against the slugs of the archive pages from System Logic: the first segment is matched against the slugs of the archive pages from System
Pages. A match → we know which collection it is about. `['artykuly']` → listing of Pages. A match → we know which collection it is about. `['artykuly']` → listing of
`posts`; `['artykuly','moj-post']` → an entry in `posts`; no match → a regular `posts`; `['artykuly','moj-post']` → an entry in `posts`; no match → a regular
@@ -391,7 +396,8 @@ Query: `?q=` (required), `?locale=`, `?limit=`. Response:
"results": [{ "title": "O nas", "url": "https://x/pl/o-nas", "description": "…", "slug": "o-nas" }] } "results": [{ "title": "O nas", "url": "https://x/pl/o-nas", "description": "…", "slug": "o-nas" }] }
``` ```
No `q` → 400. Published only, without `noindex` (`noindex` or `meta.noindex`) and without the page assigned as the No `q` → 400. An unknown `?locale=` is the default locale — in the search, the under-construction check and the
answer alike (1.17.1). Published only, without `noindex` (`noindex` or `meta.noindex`) and without the page assigned as the
404 page (Site settings → System pages, read through `settingsSlug`, default `site-settings`), 404 page (Site settings → System pages, read through `settingsSlug`, default `site-settings`),
10 by default (`defaultLimit`), max 50 results. Under-construction mode: 10 by default (`defaultLimit`), max 50 results. Under-construction mode:
pass `isPathVisible` from `createContentHelpers`, and hidden pages drop out of the results. Error/database pass `isPathVisible` from `createContentHelpers`, and hidden pages drop out of the results. Error/database
@@ -411,12 +417,16 @@ const results = await searchContent({ payload, query, config, locale, limit, bas
`searchContent` options: `collection` (`'pages'`), `baseUrl`, `homeSlug`, `settingsSlug` (`'site-settings'`, for the 404 page), `locale` `searchContent` options: `collection` (`'pages'`), `baseUrl`, `homeSlug`, `settingsSlug` (`'site-settings'`, for the 404 page), `locale`
(default/invalid → `defaultLocale`), `limit` (10, clamped to 1–50), (default/invalid → `defaultLocale`), `limit` (10, clamped to 1–50),
`queryLimit` (1.17.1; default `{ length: 200, words: 10 }` — `SEARCH_QUERY_LIMIT`): how much of the query reaches
the database. Each word is one more `LIKE` on two columns and the text comes from a stranger, so a longer query is
cut to its first words (`limitQuery(query, queryLimit)` shows the result); `false` = the whole query, as before.
`summaryField` (e.g. `'aiSummary'` — prefers the richer description from `summaryField` (e.g. `'aiSummary'` — prefers the richer description from
`buildSummaryField` over `meta.description`; see [seo.md](./seo.md)). Never throws `buildSummaryField` over `meta.description`; see [seo.md](./seo.md)). Never throws
(error → `[]`). (error → `[]`).
`createSearchRoute` additionally takes `getCachedPayload`, `config` (required), `createSearchRoute` additionally takes `getCachedPayload`, `config` (required),
`defaultLimit` (10), `rateLimit`, `clientIp` (see `clientIp()` in security.md), `isPathVisible`. `defaultLimit` (10), `rateLimit`, `clientIp` (see `clientIp()` in security.md), `isPathVisible`, `queryLimit`
(passed to `searchContent`; the MCP `search_content` tool uses the default).
`listContent({ payload, config, locale, limit, … })` — the same results without a query: `listContent({ payload, config, locale, limit, … })` — the same results without a query:
all published, indexable pages by title (`limit` 50, max 200). A list all published, indexable pages by title (`limit` 50, max 200). A list
+1
View File
@@ -84,6 +84,7 @@ runs `initialize` → `tools/list` → and can then call `get_site_info`,
| `rateLimit` | `{ max: 60, windowMs: 60_000 }` | per-IP limit; `false` = off | | `rateLimit` | `{ max: 60, windowMs: 60_000 }` | per-IP limit; `false` = off |
| `clientIp` | — | `{ header?, trustedProxies? }` — where to read the IP from (see [forms.md](./forms.md#client-ip-and-rate-limit)) | | `clientIp` | — | `{ header?, trustedProxies? }` — where to read the IP from (see [forms.md](./forms.md#client-ip-and-rate-limit)) |
| `maxBatch` | `10` | max messages in one batch | | `maxBatch` | `10` | max messages in one batch |
| `maxBytes` | `65536` | largest request body read; a larger one (declared or streamed) → `413` before it is parsed (1.17.1) |
Through `createContentHelpers({ mcp })` you pass only `serverName`, `serverVersion`, Through `createContentHelpers({ mcp })` you pass only `serverName`, `serverVersion`,
`rateLimit`, `maxBatch`, `clientIp`, `isPathVisible`; `baseUrl`, `collection`, `content`, `rateLimit`, `maxBatch`, `clientIp`, `isPathVisible`; `baseUrl`, `collection`, `content`,
+1
View File
@@ -219,6 +219,7 @@ What the plugin does automatically with an assigned 404 page:
| sitemap | excluded by ID (the slug can be anything) | | sitemap | excluded by ID (the slug can be anything) |
| `generateStaticParams` | skipped (it is not a separate URL) | | `generateStaticParams` | skipped (it is not a separate URL) |
| `getNotFoundPage` / `resolveNotFoundPage` | never throws — no database during the build = fallback | | `getNotFoundPage` / `resolveNotFoundPage` | never throws — no database during the build = fallback |
| a 404 page that is a draft (never published, or unpublished) | `null` → the built-in view, never the draft's text (1.17.1) |
When 404 = the home page, none of the above hides the home page — it still When 404 = the home page, none of the above hides the home page — it still
works under `/{locale}` and is in the sitemap; on top of that its content shows under works under `/{locale}` and is in the sitemap; on top of that its content shows under
+4 -2
View File
@@ -56,8 +56,10 @@ Spread `defaultConverters` — you override only the nodes you want. The rest
**Links are filtered as in `<CMSLink>` (`safeHref`).** A custom link with an address outside `http(s)`, **Links are filtered as in `<CMSLink>` (`safeHref`).** A custom link with an address outside `http(s)`,
`mailto`, `tel`, `sms`, `#`, `/` (e.g. `javascript:`, `data:`) gets `href="#"` — also when it reached `mailto`, `tel`, `sms`, `#`, `/` (e.g. `javascript:`, `data:`) gets `href="#"` — also when it reached
the database through an import, a seed or the API, bypassing the panel field. Internal links (`linkType: 'internal'`) the database through an import, a seed or the API, bypassing the panel field. Since 1.17.1 one rule covers every
are not touched. Turn off (fully trusted content only): `<RenderRichText data={…} safeLinks={false} />`. stored link URL: an `autolink`, and a link marked `linkType: 'internal'`, are checked too (Payload's autolink
converter prints `fields.url` whatever the link type), and `lexicalToMarkdown` (the `.md` routes, llms-full.txt)
drops an unsafe target and keeps the label. Turn off (fully trusted content only): `<RenderRichText data={…} safeLinks={false} />`.
## Table of contents and heading anchors (1.11.1) ## Table of contents and heading anchors (1.11.1)
+37 -2
View File
@@ -65,6 +65,37 @@ export default withSecurityConfig(withPayload(nextConfig))
With `IAPL_NOINDEX=1` (staging), `X-Robots-Tag: noindex, nofollow` is added to every response. With `IAPL_NOINDEX=1` (staging), `X-Robots-Tag: noindex, nofollow` is added to every response.
**A value the browser would not understand fails at start (1.17.1).** `hsts`, `hstsIncludeSubDomains` and
`hstsPreload` take `true` / `false`, `hstsMaxAge` a number of seconds, `frameOptions` `'DENY'` / `'SAMEORIGIN'` /
`null`, `coop` a COOP value or `false`, `referrerPolicy` / `permissionsPolicy` a header value or `null`. Before,
`hsts: null` dropped HSTS and `hstsMaxAge: 'abc'` or `frameOptions: 'false'` sent a header the browser ignores.
`buildCsp` the same way: `dev` and `strictDynamic` are booleans (`dev: 'false'` used to add `'unsafe-eval'` in
production), `mode` is `'enforce'` / `'report-only'`, and every `extra` / `override` value is an array of sources
(a string was spread into single characters — a lone `*` among them is a wildcard).
## Switches are read strictly (1.17.1)
A JavaScript config is not type-checked. A plugin option whose nonsense value used to switch a protection off,
widen who sees something, or switch an opt-in feature (a public endpoint) on, now stops the start with a message
naming the option — like `twoFactor.requireSetup.windowHours` since 1.16.6. Real values work as before.
| Option | Refused now | What it did before |
|---|---|---|
| `accounts` | `0`, `''`, anything not `false` / an object | `0` or `''` dropped every account rule |
| `cookieScanner`, `stats`, `consentLog`, `adminMeta`, `whiteLabel`, `forms.attachments`, `cookieScanner.crawl`, `mail.relay` | a string, a number, `null` | `'false'` switched an opt-in feature on (or was ignored) |
| `indexNow`, `lightbox`, `enabled`, `twoFactor.allowCollectionMismatch` | anything but `true` / `false` | `'false'` meant on — for the mismatch: panel users without 2FA |
| `consentLog.retentionDays` | not a number above 0 | `null`, `0` or a negative number purged every proof of consent daily |
| `adminMeta.robots.index` / `.follow` | anything but `true` / `false` | `'false'`, `0` or `null` took the noindex off the panel |
| `dashboardAlerts.integrations` / `.cookies` | a name outside `'admin' / 'editor' / 'all'` (`'editor' / 'all'`) | an unknown name showed the details to every staff account |
| `mail.relay.accountMail.windowMinutes`, `mail.relay.confirmRateLimit.windowMs` | not a number above 0 | a window of 0 is a limit that never fills |
| `mail.relay.accountMail.perAddress` / `.perVisitor`, `confirmRateLimit.max` | not a number of at least 1 | — |
| `forms.attachments.submit.maxPerMinute`, `.timeoutMs`, `.idleTimeoutMs` | not a number of at least 0 (`0` = off, as documented) | `'off'`, `null` or `{}` turned the limit off |
| `storageNames` | anything but `'ipal'` / `'iapl'` | an unknown name meant `'ipal'` |
| seed `guard` (`createSeeder`) | `0`, `''`; `allowFull` / `allowProdUpdate` / `production` not booleans | `guard: 0` dropped the production guard; `allowFull: 'false'` allowed a full seed |
Role names are strict too: `requireRole`, `requireRoleField` and `readPublished` throw on a name outside
`ROLE_HIERARCHY`, and `hasMinimumRole` / `userMeetsRole` answer `false` for one (before, every staff account met it).
**Uploads:** `buildUploadSecurityHeaders({ collections = ['media'] })` returns `headers()` rules for **Uploads:** `buildUploadSecurityHeaders({ collections = ['media'] })` returns `headers()` rules for
`/api/<collection>/file/*` (sandbox, no scripts) — an SVG from local disk cannot run a script on the site's `/api/<collection>/file/*` (sandbox, no scripts) — an SVG from local disk cannot run a script on the site's
domain. Wire it alongside: `[{ source: '/:path*', headers: securityHeaders }, ...buildUploadSecurityHeaders()]`. domain. Wire it alongside: `[{ source: '/:path*', headers: securityHeaders }, ...buildUploadSecurityHeaders()]`.
@@ -258,7 +289,8 @@ With a custom `adminRoute` (e.g. `/its`), use that path in `source`.
`createCspReportRoute({ onReport?, maxBytes = 16384 })` — a `POST` handler for `reportUri`. It accepts `createCspReportRoute({ onReport?, maxBytes = 16384 })` — a `POST` handler for `reportUri`. It accepts
both formats (`application/csp-report` from `report-uri`, `application/reports+json` from `report-to`), both formats (`application/csp-report` from `report-uri`, `application/reports+json` from `report-to`),
caps the body, always answers `204`, and by default logs one `console.warn` line per violation: caps the body (a larger one → `413`; since 1.17.1 the stream is read only up to `maxBytes`, also when the browser
sends no `content-length`), always answers `204`, and by default logs one `console.warn` line per violation:
`[csp] report script-src-elem blocked=https://x.example/a.js page=https://site/pl`. Read them in the `[csp] report script-src-elem blocked=https://x.example/a.js page=https://site/pl`. Read them in the
Coolify app's **Logs**. Plug `onReport` into `payload.logger`, Sentry or a database for more. Coolify app's **Logs**. Plug `onReport` into `payload.logger`, Sentry or a database for more.
@@ -1020,7 +1052,10 @@ later option, not part of this release.
**Versions.** The global has no versions by default. A project that turns them on **Versions.** The global has no versions by default. A project that turns them on
(`globalOverrides: { 'site-integrations': { versions: … } }`) stores the secret in every version — as in the (`globalOverrides: { 'site-integrations': { versions: … } }`) stores the secret in every version — as in the
document itself — and reads of versions are masked like any read. A **restore** answers with the version document itself — and reads of versions are masked like any read. Since 1.17.1 the versions are read by the same
people as the global (`readVersions`: admin): Payload's own default lets every signed-in account list them, an
editor or a plain `user` account included, with the server, user name and status texts. Your own rule:
`globalOverrides: { 'site-integrations': { access: { readVersions: … } } }`. A **restore** answers with the version
document, the fields under `version`, where field hooks do not run: the global's `afterRead` hook document, the fields under `version`, where field hooks do not run: the global's `afterRead` hook
`maskSecretsOnRestore` masks them there too. A restore brings back the password of that version. `maskSecretsOnRestore` masks them there too. A restore brings back the password of that version.
+2
View File
@@ -56,6 +56,8 @@ export function buildSiteIntegrations({
// nothing through the API; admins read/edit in the panel and via Local API. // nothing through the API; admins read/edit in the panel and via Local API.
// Without roles (no `access` option) every logged-in account is admin. // Without roles (no `access` option) every logged-in account is admin.
read: ({ req }) => userMeetsRole(req, 'admin'), read: ({ req }) => userMeetsRole(req, 'admin'),
// With versions on (globalOverrides), Payload lets every signed-in account list them unless told otherwise.
readVersions: ({ req }) => userMeetsRole(req, 'admin'),
update: ({ req }) => userMeetsRole(req, 'admin'), update: ({ req }) => userMeetsRole(req, 'admin'),
}, },
admin: { admin: {
+4
View File
@@ -15,6 +15,7 @@ export {
injectRoles, injectRoles,
isAdmin, isAdmin,
isEditor, isEditor,
readPublished,
requireRole, requireRole,
requireRoleField, requireRoleField,
ROLE_HIERARCHY, ROLE_HIERARCHY,
@@ -203,6 +204,8 @@ export {
createMarkdownRoute, createMarkdownRoute,
createSearchRoute, createSearchRoute,
getArchiveEntries, getArchiveEntries,
isSiteLocale,
limitQuery,
listContent, listContent,
MARKDOWN_PREFIX, MARKDOWN_PREFIX,
markdownHref, markdownHref,
@@ -212,6 +215,7 @@ export {
resolveNotFoundPage, resolveNotFoundPage,
resolveRedirect, resolveRedirect,
resolveRoute, resolveRoute,
SEARCH_QUERY_LIMIT,
searchContent, searchContent,
} from './modules/content/index.js' } from './modules/content/index.js'
export type { ArchiveEntries } from './modules/content/index.js' export type { ArchiveEntries } from './modules/content/index.js'
+29 -8
View File
@@ -3,6 +3,7 @@ import type { Access, FieldAccess } from 'payload'
import type { Role } from './types.js' import type { Role } from './types.js'
import { hasMinimumRole, isAdmin } from './predicates.js' import { hasMinimumRole, isAdmin } from './predicates.js'
import { ROLE_HIERARCHY } from './types.js'
/** /**
* Collection-level access (returns boolean | Where). * Collection-level access (returns boolean | Where).
@@ -15,10 +16,23 @@ export const adminOrEditor: Access = ({ req }) => hasMinimumRole(req.user, 'edit
export const authenticated: Access = ({ req: { user } }) => Boolean(user) export const authenticated: Access = ({ req: { user } }) => Boolean(user)
/** Requires at least the given role. */ /** Requires at least the given role. */
export const requireRole = export const requireRole = (minimum: Role): Access => {
(minimum: Role): Access => assertKnownRole('requireRole', minimum)
({ req }) => return ({ req }) => hasMinimumRole(req.user, minimum, req.payload)
hasMinimumRole(req.user, minimum, req.payload) }
/**
* Read rule for a collection with drafts: staff of `minimum` role or higher (default editor) read everything,
* drafts and versions included; everybody else (visitors, plain `user` accounts, a session that still owes its
* second factor) reads published documents only — by id, in lists, with `?draft=true` and over GraphQL. Payload's
* open `read: () => true` answers `?draft=true` with the draft itself (IAWL idea 23).
*
* access: { read: readPublished(), readVersions: readPublished() }
*/
export const readPublished = (minimum: Role = 'editor'): Access => {
assertKnownRole('readPublished', minimum)
return ({ req }) => (hasMinimumRole(req.user, minimum, req.payload) ? true : { _status: { equals: 'published' } })
}
/** /**
* Admins see all; others are constrained to their own document. * Admins see all; others are constrained to their own document.
@@ -59,7 +73,14 @@ export const adminOnlyField: FieldAccess = ({ req }) => isAdmin(req.user, req.pa
export const adminOrEditorField: FieldAccess = ({ req }) => hasMinimumRole(req.user, 'editor', req.payload) export const adminOrEditorField: FieldAccess = ({ req }) => hasMinimumRole(req.user, 'editor', req.payload)
/** Requires at least the given role, for field-level access. */ /** Requires at least the given role, for field-level access. */
export const requireRoleField = export const requireRoleField = (minimum: Role): FieldAccess => {
(minimum: Role): FieldAccess => assertKnownRole('requireRoleField', minimum)
({ req }) => return ({ req }) => hasMinimumRole(req.user, minimum, req.payload)
hasMinimumRole(req.user, minimum, req.payload) }
/** A role name the plugin does not know fails where the rule is written, not silently at every request. */
function assertKnownRole(where: string, role: unknown): void {
if (typeof role !== 'string' || !(ROLE_HIERARCHY as readonly string[]).includes(role)) {
throw new Error(`[iapl] ${where}(${JSON.stringify(role)}): the role must be one of ${ROLE_HIERARCHY.map((r) => `'${r}'`).join(', ')}.`)
}
}
+1
View File
@@ -6,6 +6,7 @@ export {
adminOrSelf, adminOrSelf,
adminOrSelfIn, adminOrSelfIn,
authenticated, authenticated,
readPublished,
requireRole, requireRole,
requireRoleField, requireRoleField,
} from './access.js' } from './access.js'
+6 -2
View File
@@ -123,7 +123,9 @@ function highestRoleIndex(user: MaybeUser): number {
*/ */
export function hasMinimumRole(user: MaybeUser, minimum: Role, payload?: MaybePayload): boolean { export function hasMinimumRole(user: MaybeUser, minimum: Role, payload?: MaybePayload): boolean {
if (!isStaffAccount(user, payload)) {return false} if (!isStaffAccount(user, payload)) {return false}
return highestRoleIndex(user) >= ROLE_HIERARCHY.indexOf(minimum) // a role name the plugin does not know ('Admin', 'admins') is met by nobody (it used to be met by everybody)
const needed = ROLE_HIERARCHY.indexOf(minimum)
return needed >= 0 && highestRoleIndex(user) >= needed
} }
/** True if the user is a staff account with the admin role. */ /** True if the user is a staff account with the admin role. */
@@ -158,7 +160,9 @@ export function userMeetsRole({ payload, user }: { payload?: BasePayload; user?:
const slug = (user as { collection?: unknown }).collection const slug = (user as { collection?: unknown }).collection
if (typeof slug !== 'string' || !staffCollectionSlugs(payload).includes(slug)) {return false} if (typeof slug !== 'string' || !staffCollectionSlugs(payload).includes(slug)) {return false}
if (!secondFactorPassed({ payload, user })) {return false} if (!secondFactorPassed({ payload, user })) {return false}
if (highestRoleIndex(user as MaybeUser) >= ROLE_HIERARCHY.indexOf(minimum)) {return true} const needed = ROLE_HIERARCHY.indexOf(minimum)
if (needed < 0) {return false} // an unknown role name is met by nobody
if (highestRoleIndex(user as MaybeUser) >= needed) {return true}
const collection = payload?.collections?.[slug as never]?.config const collection = payload?.collections?.[slug as never]?.config
const fields = (collection?.flattenedFields ?? collection?.fields) as Array<{ name?: string }> | undefined const fields = (collection?.flattenedFields ?? collection?.fields) as Array<{ name?: string }> | undefined
if (!fields) {return false} if (!fields) {return false}
+4 -29
View File
@@ -5,6 +5,7 @@ import type { CollectionOverride } from '../shared/collectionOverride.js'
import { userMeetsRole } from '../access/predicates.js' import { userMeetsRole } from '../access/predicates.js'
import { createDailyPurge } from '../shared/purge.js' import { createDailyPurge } from '../shared/purge.js'
import { clientIp, consumeRateLimit } from '../shared/rateLimit.js' import { clientIp, consumeRateLimit } from '../shared/rateLimit.js'
import { readCappedBody as readCapped } from '../shared/readCappedBody.js'
import { CONSENT_CATEGORIES } from './categories.js' import { CONSENT_CATEGORIES } from './categories.js'
import { CONSENT_CATEGORY_LABELS } from './categoryLabels.js' import { CONSENT_CATEGORY_LABELS } from './categoryLabels.js'
import { CONSENT_VERSION } from './storage.js' import { CONSENT_VERSION } from './storage.js'
@@ -89,35 +90,9 @@ const missingTableLogged = new WeakSet<object>()
/** Largest body the endpoint reads. A decision is about 200 bytes; anything near this is not one. */ /** Largest body the endpoint reads. A decision is about 200 bytes; anything near this is not one. */
export const CONSENT_LOG_MAX_BYTES = 4096 export const CONSENT_LOG_MAX_BYTES = 4096
/** /** The request body as text, or null when it is larger than `max` bytes (shared/readCappedBody.ts). */
* The request body as text, or null when it is larger than `max` bytes: a declared `content-length` over the cap export function readCappedBody(request: Request, max: number = CONSENT_LOG_MAX_BYTES): Promise<null | string> {
* is refused before anything is read, and the stream is read only up to the cap (a body without a length, or with return readCapped(request, max)
* a false one, cannot make the server hold more).
*/
export async function readCappedBody(request: Request, max: number = CONSENT_LOG_MAX_BYTES): Promise<null | string> {
const declared = Number(request.headers.get('content-length'))
if (Number.isFinite(declared) && declared > max) {return null}
if (!request.body) {return ''}
const reader = request.body.getReader()
const chunks: Uint8Array[] = []
let size = 0
for (;;) {
const { done, value } = await reader.read()
if (done) {break}
size += value.byteLength
if (size > max) {
await reader.cancel().catch(() => {})
return null
}
chunks.push(value)
}
const all = new Uint8Array(size)
let at = 0
for (const chunk of chunks) {
all.set(chunk, at)
at += chunk.byteLength
}
return new TextDecoder().decode(all)
} }
/** Cookie Settings → Policy version per Payload instance, cached for a minute. */ /** Cookie Settings → Policy version per Payload instance, cached for a minute. */
+8 -2
View File
@@ -4,6 +4,7 @@ import type { I18nConfig } from '../i18n/index.js'
import type { ClientIpOptions } from '../shared/rateLimit.js' import type { ClientIpOptions } from '../shared/rateLimit.js'
import { pathOf, type PathVisibility } from '../construction/visibility.js' import { pathOf, type PathVisibility } from '../construction/visibility.js'
import { isValidLocale } from '../i18n/index.js'
import { clientIp, consumeRateLimit, tooManyRequests } from '../shared/rateLimit.js' import { clientIp, consumeRateLimit, tooManyRequests } from '../shared/rateLimit.js'
import { searchContent } from './searchContent.js' import { searchContent } from './searchContent.js'
@@ -22,6 +23,8 @@ type CreateSearchRouteArgs = {
homeSlug?: Record<string, string> | string homeSlug?: Record<string, string> | string
/** Hide pages the site hides (construction mode) — pass `isPathVisible` from createContentHelpers. */ /** Hide pages the site hides (construction mode) — pass `isPathVisible` from createContentHelpers. */
isPathVisible?: PathVisibility isPathVisible?: PathVisibility
/** How much of `q` reaches the database (searchContent). Default `{ length: 200, words: 10 }`; `false` = all of it. */
queryLimit?: { length?: number; words?: number } | false
/** /**
* Per-IP limit (in memory per instance, or the store from setRateLimitStore). Default { max: 120, windowMs: 60_000 }. * 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). * `false` = off (a limiter in front, e.g. Cloudflare WAF rate limiting).
@@ -52,7 +55,7 @@ type CreateSearchRouteArgs = {
* Uses the global Request/Response — no next/server import. * Uses the global Request/Response — no next/server import.
*/ */
export function createSearchRoute(args: CreateSearchRouteArgs): (req: Request) => Promise<Response> { export function createSearchRoute(args: CreateSearchRouteArgs): (req: Request) => Promise<Response> {
const { baseUrl, collection = 'pages', config, defaultLimit = 10, getCachedPayload, homeSlug, isPathVisible, settingsSlug, summaryField } = args const { baseUrl, collection = 'pages', config, defaultLimit = 10, getCachedPayload, homeSlug, isPathVisible, queryLimit, settingsSlug, summaryField } = args
// 120/min: a debounced search-as-you-type box stays well under it; a scraper doesn't. // 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 } const rl = args.rateLimit === false ? null : { max: 120, windowMs: 60_000, ...args.rateLimit }
@@ -65,7 +68,9 @@ export function createSearchRoute(args: CreateSearchRouteArgs): (req: Request) =
} }
const url = new URL(req.url) const url = new URL(req.url)
const query = url.searchParams.get('q')?.trim() ?? '' const query = url.searchParams.get('q')?.trim() ?? ''
const locale = url.searchParams.get('locale') ?? undefined // one locale for the search, the visibility check and the answer: a code the site does not have is the default
const asked = url.searchParams.get('locale')
const locale = asked && isValidLocale(asked, config) ? asked : undefined
const limitParam = url.searchParams.get('limit') const limitParam = url.searchParams.get('limit')
const limit = limitParam ? Number(limitParam) : defaultLimit const limit = limitParam ? Number(limitParam) : defaultLimit
@@ -87,6 +92,7 @@ export function createSearchRoute(args: CreateSearchRouteArgs): (req: Request) =
locale, locale,
payload, payload,
query, query,
queryLimit,
settingsSlug, settingsSlug,
summaryField, summaryField,
}) })
+2 -2
View File
@@ -8,9 +8,9 @@ export { MARKDOWN_PREFIX, markdownHref, prefersMarkdown } from './markdownNegoti
export { buildArchivePath, buildEntryPath, parsePageParam } from './paths.js' export { buildArchivePath, buildEntryPath, parsePageParam } from './paths.js'
export { resolveNotFoundPage } from './resolveNotFoundPage.js' export { resolveNotFoundPage } from './resolveNotFoundPage.js'
export { resolveRedirect } from './resolveRedirect.js' export { resolveRedirect } from './resolveRedirect.js'
export { resolveRoute } from './resolveRoute.js' export { isSiteLocale, resolveRoute } from './resolveRoute.js'
export type { ResolvedRoute } from './resolveRoute.js' export type { ResolvedRoute } from './resolveRoute.js'
export { listContent, searchContent } from './searchContent.js' export { limitQuery, listContent, SEARCH_QUERY_LIMIT, searchContent } from './searchContent.js'
export type { SearchResult } from './searchContent.js' export type { SearchResult } from './searchContent.js'
export type { ContentCollectionOption, ContentOption } from './types.js' export type { ContentCollectionOption, ContentOption } from './types.js'
export { archiveFieldName } from './types.js' export { archiveFieldName } from './types.js'
+4 -1
View File
@@ -1,5 +1,7 @@
import type { BasePayload } from 'payload' import type { BasePayload } from 'payload'
import { isPublishedDoc } from './resolveRoute.js'
type ResolveNotFoundPageArgs = { type ResolveNotFoundPageArgs = {
locale: string locale: string
/** Client's Pages collection slug. Defaults to 'pages'. */ /** Client's Pages collection slug. Defaults to 'pages'. */
@@ -49,7 +51,8 @@ export async function resolveNotFoundPage({
depth: 2, depth: 2,
locale: locale as never, locale: locale as never,
}) })
return (doc as null | Record<string, unknown>) ?? null // a page never published (or unpublished) is a draft: the built-in view, not its text (IAWL idea 23)
return isPublishedDoc(doc) ? (doc as Record<string, unknown>) : null
} catch (error) { } catch (error) {
console.warn('[iapl] resolveNotFoundPage: falling back to built-in 404 view:', error) console.warn('[iapl] resolveNotFoundPage: falling back to built-in 404 view:', error)
return null return null
+13
View File
@@ -89,6 +89,16 @@ function isPublic(doc: unknown, draft: boolean): boolean {
return status === undefined || status === null || status === 'published' return status === undefined || status === null || status === 'published'
} }
/** True for a document a visitor may be shown: published, or from a collection without drafts. */
export const isPublishedDoc = (doc: unknown): boolean => isPublic(doc, false)
/** True when `locale` is one of the site's locale codes (always true on a site without localization). */
export function isSiteLocale(payload: { config?: { localization?: unknown } }, locale: unknown): boolean {
const localization = payload.config?.localization as { localeCodes?: string[] } | false | undefined
if (!localization || !Array.isArray(localization.localeCodes)) {return true}
return typeof locale === 'string' && localization.localeCodes.includes(locale)
}
export async function resolveRoute({ export async function resolveRoute({
content, content,
draft = false, draft = false,
@@ -100,6 +110,9 @@ export async function resolveRoute({
settings: preloaded, settings: preloaded,
settingsSlug = 'site-settings', settingsSlug = 'site-settings',
}: ResolveRouteArgs): Promise<null | ResolvedRoute> { }: ResolveRouteArgs): Promise<null | ResolvedRoute> {
// No stand-in locale: a code the site does not have (`xx`, `all`, `*` from a URL that went past the proxy, the
// Markdown route) is "not found" — never the default locale's page shown under another code (IAWL idea 25).
if (!isSiteLocale(payload, locale)) {return null}
const settings = const settings =
preloaded ?? preloaded ??
((await payload.findGlobal({ ((await payload.findGlobal({
+23 -1
View File
@@ -28,6 +28,11 @@ type SearchContentArgs = {
payload: BasePayload payload: BasePayload
/** Keywords. */ /** Keywords. */
query: string query: string
/**
* How much of the query reaches the database: `{ length: 200, words: 10 }` by default — every word is one more
* `LIKE` on two columns, and the text comes from a stranger. `false` = the whole query, as before 1.17.1.
*/
queryLimit?: { length?: number; words?: number } | false
/** SiteSettings global — the assigned 404 page is left out (unlistedPageIds). Default 'site-settings'. */ /** SiteSettings global — the assigned 404 page is left out (unlistedPageIds). Default 'site-settings'. */
settingsSlug?: string settingsSlug?: string
/** /**
@@ -58,6 +63,22 @@ type PageRow = {
* Degrades to [] (never throws) when the collection's fields aren't queryable — * Degrades to [] (never throws) when the collection's fields aren't queryable —
* same guard class as the drafts/_status lesson. * same guard class as the drafts/_status lesson.
*/ */
/** Default share of a search query that reaches the database (searchContent `queryLimit`). */
export const SEARCH_QUERY_LIMIT = { length: 200, words: 10 } as const
/** The query as searched: trimmed, then cut to `limit` words and characters (whole words where it can). */
export function limitQuery(query: string, limit: SearchContentArgs['queryLimit'] = SEARCH_QUERY_LIMIT): string {
const q = query.trim()
if (limit === false) {return q}
const length = limit.length ?? SEARCH_QUERY_LIMIT.length
const words = limit.words ?? SEARCH_QUERY_LIMIT.words
const kept = q.split(/\s+/).slice(0, Math.max(1, words)).join(' ')
if (kept.length <= length) {return kept}
const cut = kept.slice(0, length)
const space = cut.lastIndexOf(' ')
return (space > 0 ? cut.slice(0, space) : cut).trim()
}
export async function searchContent({ export async function searchContent({
baseUrl, baseUrl,
collection = 'pages', collection = 'pages',
@@ -67,10 +88,11 @@ export async function searchContent({
locale, locale,
payload, payload,
query, query,
queryLimit,
settingsSlug, settingsSlug,
summaryField, summaryField,
}: SearchContentArgs): Promise<SearchResult[]> { }: SearchContentArgs): Promise<SearchResult[]> {
const q = query.trim() const q = limitQuery(query, queryLimit)
if (!q) {return []} if (!q) {return []}
const loc = locale && isValidLocale(locale, config) ? locale : getDefaultLocale(config) const loc = locale && isValidLocale(locale, config) ? locale : getDefaultLocale(config)
+9 -4
View File
@@ -3,6 +3,7 @@ import type { Endpoint, PayloadRequest } from 'payload'
import type { RelayOptions } from './options.js' import type { RelayOptions } from './options.js'
import { clientIp, consumeRateLimit, tooManyRequests } from '../../shared/rateLimit.js' import { clientIp, consumeRateLimit, tooManyRequests } from '../../shared/rateLimit.js'
import { readCappedBody } from '../../shared/readCappedBody.js'
import { RELAY_CONFIRM_PATH, RELAY_DEFAULTS } from './constants.js' import { RELAY_CONFIRM_PATH, RELAY_DEFAULTS } from './constants.js'
import { sha256Hex, takeNonce, writeRelayCandidate } from './store.js' import { sha256Hex, takeNonce, writeRelayCandidate } from './store.js'
@@ -14,13 +15,17 @@ const MAX_BODY = 2048
const notFound = () => new Response(null, { headers: { 'cache-control': 'no-store' }, status: 404 }) const notFound = () => new Response(null, { headers: { 'cache-control': 'no-store' }, status: 404 })
async function readBody(req: PayloadRequest): Promise<unknown> { async function readBody(req: PayloadRequest): Promise<unknown> {
const length = Number(req.headers.get('content-length') ?? 0)
if (length > MAX_BODY) {return null}
try { try {
// read only up to the cap, whether or not the call declares its length (a chunked body has none)
const text = (req as unknown as Request).body ? await readCappedBody(req as unknown as Request, MAX_BODY) : null
if (text !== null) {return JSON.parse(text) as unknown}
if ((req as unknown as Request).body) {return null}
// a request without a stream (a double in a test, a body Payload already read)
if (Number(req.headers.get('content-length') ?? 0) > MAX_BODY) {return null}
const read = (req as { text?: () => Promise<string> }).text const read = (req as { text?: () => Promise<string> }).text
if (typeof read !== 'function') {return (await req.json?.()) as unknown} if (typeof read !== 'function') {return (await req.json?.()) as unknown}
const text = await read.call(req) const whole = await read.call(req)
return text.length <= MAX_BODY ? (JSON.parse(text) as unknown) : null return whole.length <= MAX_BODY ? (JSON.parse(whole) as unknown) : null
} catch { } catch {
return null return null
} }
+3 -1
View File
@@ -24,6 +24,7 @@ import { createMarkdownRoute } from '../content/createMarkdownRenderer.js'
import { getArchiveEntries, resolveRoute as resolveRouteRaw } from '../content/index.js' import { getArchiveEntries, resolveRoute as resolveRouteRaw } from '../content/index.js'
import { MARKDOWN_PREFIX, markdownHref } from '../content/markdownNegotiation.js' import { MARKDOWN_PREFIX, markdownHref } from '../content/markdownNegotiation.js'
import { resolveRedirect as resolveRedirectRaw } from '../content/resolveRedirect.js' import { resolveRedirect as resolveRedirectRaw } from '../content/resolveRedirect.js'
import { isPublishedDoc } from '../content/resolveRoute.js'
import { archiveFieldName } from '../content/types.js' import { archiveFieldName } from '../content/types.js'
import { createHealthRoute } from '../health/createHealthRoute.js' import { createHealthRoute } from '../health/createHealthRoute.js'
import { homeSlugFrom, resolveLink as resolveLinkRaw, resolveNav as resolveNavRaw, resolveSystemLinks } from '../links/resolveNav.js' import { homeSlugFrom, resolveLink as resolveLinkRaw, resolveNav as resolveNavRaw, resolveSystemLinks } from '../links/resolveNav.js'
@@ -414,7 +415,8 @@ export function createContentHelpers({
depth: 2, depth: 2,
locale: locale as never, locale: locale as never,
}) })
return (doc as null | Record<string, unknown>) ?? null // a page never published (or unpublished) is a draft: the built-in view, not its text (IAWL idea 23)
return isPublishedDoc(doc) ? (doc as Record<string, unknown>) : null
} catch { } catch {
return null // DB unreachable (container build) or page deleted — fallback view return null // DB unreachable (container build) or page deleted — fallback view
} }
+8 -1
View File
@@ -11,6 +11,7 @@ import { getDefaultLocale, isValidLocale } from '../i18n/index.js'
import { readSiteMetaConfig } from '../seo/readSiteMetaConfig.js' import { readSiteMetaConfig } from '../seo/readSiteMetaConfig.js'
import { collectSiteIndex } from '../seo/siteIndex.js' import { collectSiteIndex } from '../seo/siteIndex.js'
import { clientIp, consumeRateLimit, tooManyRequests } from '../shared/rateLimit.js' import { clientIp, consumeRateLimit, tooManyRequests } from '../shared/rateLimit.js'
import { readCappedBody } from '../shared/readCappedBody.js'
/** /**
* A read-only MCP (Model Context Protocol) server for the client site, as a Next * A read-only MCP (Model Context Protocol) server for the client site, as a Next
@@ -66,6 +67,8 @@ export type CreateMcpRouteArgs = {
isPathVisible?: PathVisibility isPathVisible?: PathVisibility
/** Max messages in one JSON-RPC batch. Default 10. */ /** Max messages in one JSON-RPC batch. Default 10. */
maxBatch?: number maxBatch?: number
/** Largest request body read, in bytes; a larger one gets `413` before it is parsed. Default 65536 (64 KiB). */
maxBytes?: number
/** /**
* Per-IP limit on JSON-RPC messages (a batch counts every message) (in memory per instance, or the store from setRateLimitStore). Default { max: 60, windowMs: 60_000 }. * Per-IP limit on JSON-RPC messages (a batch counts every message) (in memory per instance, or the store from setRateLimitStore). Default { max: 60, windowMs: 60_000 }.
* `false` = off (a limiter in front, e.g. Cloudflare WAF rate limiting). * `false` = off (a limiter in front, e.g. Cloudflare WAF rate limiting).
@@ -104,6 +107,7 @@ export function createMcpRoute(args: CreateMcpRouteArgs) {
getCachedPayload, getCachedPayload,
isPathVisible, isPathVisible,
maxBatch = 10, maxBatch = 10,
maxBytes = 64 * 1024,
serverName = 'ipal-site', serverName = 'ipal-site',
serverVersion = '1.0.0', serverVersion = '1.0.0',
settingsSlug = 'site-settings', settingsSlug = 'site-settings',
@@ -321,7 +325,10 @@ export function createMcpRoute(args: CreateMcpRouteArgs) {
async function POST(req: Request): Promise<Response> { async function POST(req: Request): Promise<Response> {
let body: unknown let body: unknown
try { try {
body = await req.json() // read only up to the cap, declared length or not: a stranger's body is measured before it is parsed
const text = req.body ? await readCappedBody(req, maxBytes) : ''
if (text === null) {return Response.json(rpcError(null, -32600, `Request too large (max ${maxBytes} bytes)`), { status: 413 })}
body = JSON.parse(text)
} catch { } catch {
return Response.json(rpcError(null, -32700, 'Parse error'), { status: 400 }) return Response.json(rpcError(null, -32700, 'Parse error'), { status: 400 })
} }
+5 -1
View File
@@ -1,5 +1,7 @@
import type { SerializedEditorState } from '@payloadcms/richtext-lexical/lexical' import type { SerializedEditorState } from '@payloadcms/richtext-lexical/lexical'
import { safeHref } from '../links/resolveLinkHref.js'
/** /**
* Converts a Payload Lexical richText value to Markdown — a small, dependency- * Converts a Payload Lexical richText value to Markdown — a small, dependency-
* free walker over the serialized node tree. Self-contained on purpose: it does * free walker over the serialized node tree. Self-contained on purpose: it does
@@ -53,12 +55,14 @@ function inline(nodes: unknown): string {
out += '\n' out += '\n'
} else if (type === 'link') { } else if (type === 'link') {
const fields = (node.fields ?? {}) as Record<string, unknown> const fields = (node.fields ?? {}) as Record<string, unknown>
const url = const raw =
typeof fields.url === 'string' typeof fields.url === 'string'
? fields.url ? fields.url
: typeof (fields.doc as Record<string, unknown>)?.value === 'string' : typeof (fields.doc as Record<string, unknown>)?.value === 'string'
? ((fields.doc as Record<string, unknown>).value as string) ? ((fields.doc as Record<string, unknown>).value as string)
: '' : ''
// the same rule as <RenderRichText> and <CMSLink>: a `javascript:` / `data:` target is dropped, the label stays
const url = raw && (typeof fields.url === 'string' ? safeHref(raw) : raw)
const label = inline(node.children) const label = inline(node.children)
out += url ? `[${label}](${url})` : label out += url ? `[${label}](${url})` : label
} else if (node.children) { } else if (node.children) {
+3 -1
View File
@@ -30,7 +30,9 @@ function walk(value: unknown): unknown {
const node = value as LexicalNode const node = value as LexicalNode
let result: LexicalNode = node let result: LexicalNode = node
if ((node.type === 'link' || node.type === 'autolink') && node.fields && node.fields.linkType !== 'internal') { // Whatever the linkType: Payload's autolink converter prints `fields.url` even on an "internal" one, and a
// project's internalDocToHref may fall back to it — one check for every stored link URL.
if ((node.type === 'link' || node.type === 'autolink') && node.fields) {
const url = typeof node.fields.url === 'string' ? node.fields.url : '' const url = typeof node.fields.url === 'string' ? node.fields.url : ''
if (url && safeHref(url) === null) {result = { ...node, fields: { ...node.fields, url: '#' } }} if (url && safeHref(url) === null) {result = { ...node, fields: { ...node.fields, url: '#' } }}
} }
+23
View File
@@ -1,5 +1,7 @@
import type { SecurityHeader } from './buildSecurityHeaders.js' import type { SecurityHeader } from './buildSecurityHeaders.js'
import { assertBooleanSwitch, assertOneOf } from '../shared/switches.js'
export type CspDirective = export type CspDirective =
| 'base-uri' | 'base-uri'
| 'child-src' | 'child-src'
@@ -76,6 +78,26 @@ export type BuildCspArgs = {
export const DEFAULT_CSP_REPORT_GROUP = 'csp-endpoint' export const DEFAULT_CSP_REPORT_GROUP = 'csp-endpoint'
/** Header name for the mode — the request header Next reads the nonce from is the same. */ /** Header name for the mode — the request header Next reads the nonce from is the same. */
/**
* A CSP option the policy cannot read fails at start (IAWL idea 21): `dev: 'false'` used to add 'unsafe-eval' in
* production, and a string in `extra` / `override` was spread into single characters (a lone `*` is a wildcard).
*/
function assertCspArgs(args: BuildCspArgs): void {
assertBooleanSwitch('buildCsp.dev', args.dev)
assertBooleanSwitch('buildCsp.strictDynamic', (args as { strictDynamic?: unknown }).strictDynamic)
assertOneOf('buildCsp.mode', args.mode, ['enforce', 'report-only'])
for (const [key, list] of [['extra', args.extra], ['override', args.override]] as const) {
if (list === undefined) {continue}
if (!list || typeof list !== 'object' || Array.isArray(list)) {throw new Error(`[iapl] buildCsp.${key} must be an object of directive → array of sources.`)}
for (const [dir, values] of Object.entries(list as Record<string, unknown>)) {
if (values === undefined || (key === 'override' && values === null)) {continue}
if (!Array.isArray(values) || values.some((v) => typeof v !== 'string')) {
throw new Error(`[iapl] buildCsp.${key}['${dir}'] must be an array of sources, e.g. ['https://cdn.example.com'] (received ${JSON.stringify(values)}).`)
}
}
}
}
export function cspHeaderKey(mode: BuildCspArgs['mode'] = 'enforce'): string { export function cspHeaderKey(mode: BuildCspArgs['mode'] = 'enforce'): string {
return mode === 'report-only' ? 'Content-Security-Policy-Report-Only' : 'Content-Security-Policy' return mode === 'report-only' ? 'Content-Security-Policy-Report-Only' : 'Content-Security-Policy'
} }
@@ -106,6 +128,7 @@ export function cspHeaderKey(mode: BuildCspArgs['mode'] = 'enforce'): string {
* missing sources via `extra`, THEN switch to 'enforce'. See docs/security.md. * missing sources via `extra`, THEN switch to 'enforce'. See docs/security.md.
*/ */
export function buildCsp(args: BuildCspArgs = {}): { key: string; value: string } { export function buildCsp(args: BuildCspArgs = {}): { key: string; value: string } {
assertCspArgs(args)
const { const {
analytics, analytics,
clarity, clarity,
@@ -1,6 +1,7 @@
import type { BuildCspArgs } from './buildCsp.js' import type { BuildCspArgs } from './buildCsp.js'
import { isSiteNoindex } from '../seo/siteNoindex.js' import { isSiteNoindex } from '../seo/siteNoindex.js'
import { assertBooleanSwitch, assertNumberSwitch, assertOneOf } from '../shared/switches.js'
import { buildCspHeaders } from './buildCsp.js' import { buildCspHeaders } from './buildCsp.js'
/** /**
@@ -82,6 +83,18 @@ export type BuildSecurityHeadersArgs = {
* } * }
*/ */
export function buildSecurityHeaders(args: BuildSecurityHeadersArgs = {}): SecurityHeader[] { export function buildSecurityHeaders(args: BuildSecurityHeadersArgs = {}): SecurityHeader[] {
// A value the browser would not understand fails at start instead of being sent (IAWL idea 21): `hsts: null`
// dropped HSTS, `hstsMaxAge: 'abc'` and `frameOptions: 'false'` produced headers browsers ignore.
for (const name of ['hsts', 'hstsIncludeSubDomains', 'hstsPreload'] as const) {assertBooleanSwitch(`buildSecurityHeaders.${name}`, args[name])}
assertNumberSwitch('buildSecurityHeaders.hstsMaxAge', args.hstsMaxAge, { min: 0 })
if (args.frameOptions !== null) {assertOneOf('buildSecurityHeaders.frameOptions', args.frameOptions, ['DENY', 'SAMEORIGIN'])}
if (args.coop !== false) {assertOneOf('buildSecurityHeaders.coop', args.coop, ['same-origin', 'same-origin-allow-popups', 'noopener-allow-popups', 'unsafe-none'])}
for (const name of ['permissionsPolicy', 'referrerPolicy'] as const) {
const v = args[name] as unknown
if (v !== undefined && v !== null && (typeof v !== 'string' || !v.trim() || v === 'false')) {
throw new Error(`[iapl] buildSecurityHeaders.${name} must be a header value or null (received ${JSON.stringify(v)}).`)
}
}
const { const {
additional = [], additional = [],
coop = 'same-origin', coop = 'same-origin',
+6 -5
View File
@@ -1,3 +1,5 @@
import { readCappedBody } from '../shared/readCappedBody.js'
/** One CSP violation, normalised from either report format. */ /** One CSP violation, normalised from either report format. */
export type CspViolation = { export type CspViolation = {
blockedUri?: string blockedUri?: string
@@ -92,15 +94,14 @@ export function createCspReportRoute(args: CreateCspReportRouteArgs = {}): (requ
} = args } = args
return async (request: Request) => { return async (request: Request) => {
const length = Number(request.headers.get('content-length') ?? 0) // read only up to the cap, whether or not the browser declared the length (a chunked body has none)
if (length > maxBytes) {return new Response(null, { status: 413 })} let text: null | string
let text: string
try { try {
text = await request.text() text = await readCappedBody(request, maxBytes)
} catch { } catch {
return new Response(null, { status: 400 }) return new Response(null, { status: 400 })
} }
if (text.length > maxBytes) {return new Response(null, { status: 413 })} if (text === null) {return new Response(null, { status: 413 })}
let body: unknown let body: unknown
try { try {
+4
View File
@@ -3,6 +3,7 @@ import type { BasePayload } from 'payload'
import type { SeedTarget } from './values.js' import type { SeedTarget } from './values.js'
import { readEnv } from '../shared/envName.js' import { readEnv } from '../shared/envName.js'
import { assertBooleanSwitch, assertSwitchOrObject } from '../shared/switches.js'
import { activeSeedExitGuard } from './exitGuard.js' import { activeSeedExitGuard } from './exitGuard.js'
import { isLocalDatabase, seedDatabaseUrl } from './guard.js' import { isLocalDatabase, seedDatabaseUrl } from './guard.js'
import { import {
@@ -197,7 +198,10 @@ export function createSeeder(payload: BasePayload, options: SeederOptions = {}):
const dryRun = options.dryRun ?? (process.argv.includes('--dry-run') || env.SEED_DRY_RUN === '1') const dryRun = options.dryRun ?? (process.argv.includes('--dry-run') || env.SEED_DRY_RUN === '1')
const update = options.update ?? env.SEED_UPDATE === '1' const update = options.update ?? env.SEED_UPDATE === '1'
const force = update && (options.force ?? env.SEED_FORCE === '1') const force = update && (options.force ?? env.SEED_FORCE === '1')
// `guard: 0` used to drop the production guard, `allowFull: 'false'` to allow a full seed (IAWL idea 21)
assertSwitchOrObject('seed guard', options.guard, { allowTrue: false })
const guard = options.guard === false ? false : (options.guard ?? {}) const guard = options.guard === false ? false : (options.guard ?? {})
if (guard) {for (const name of ['allowFull', 'allowProdUpdate', 'production'] as const) {assertBooleanSwitch(`seed guard.${name}`, (guard as Record<string, unknown>)[name])}}
const label = options.label ?? '[seed]' const label = options.label ?? '[seed]'
const log = options.log ?? defaultLog const log = options.log ?? defaultLog
const hashField = options.editCheck?.hashField ?? defaultHashField() const hashField = options.editCheck?.hashField ?? defaultHashField()
+2 -1
View File
@@ -13,7 +13,8 @@ export function mdToPlain(md: string): string {
/** Truncate at a word boundary, adding an ellipsis when cut. */ /** Truncate at a word boundary, adding an ellipsis when cut. */
export function truncate(text: string, max: number): string { export function truncate(text: string, max: number): string {
if (text.length <= max) {return text} if (text.length <= max) {return text}
const slice = text.slice(0, max) // one place kept for the "…": the result is never longer than `max` (a field's maxLength, a summary limit)
const slice = text.slice(0, Math.max(0, max - 1))
const lastSpace = slice.lastIndexOf(' ') const lastSpace = slice.lastIndexOf(' ')
return `${(lastSpace > max * 0.6 ? slice.slice(0, lastSpace) : slice).trimEnd()}…` return `${(lastSpace > max * 0.6 ? slice.slice(0, lastSpace) : slice).trimEnd()}…`
} }
+32
View File
@@ -0,0 +1,32 @@
/**
* One rule for every body the plugin reads from strangers (IAWL idea 1: count the size before the work).
*
* The request body as text, or null when it is larger than `max` bytes: a declared `content-length` over the cap
* is refused before anything is read, and the stream is read only up to the cap (a body without a length, or with
* a false one, cannot make the server hold more).
*/
export async function readCappedBody(request: Request, max: number): Promise<null | string> {
const declared = Number(request.headers.get('content-length'))
if (Number.isFinite(declared) && declared > max) {return null}
if (!request.body) {return ''}
const reader = request.body.getReader()
const chunks: Uint8Array[] = []
let size = 0
for (;;) {
const { done, value } = await reader.read()
if (done) {break}
size += value.byteLength
if (size > max) {
await reader.cancel().catch(() => {})
return null
}
chunks.push(value)
}
const all = new Uint8Array(size)
let at = 0
for (const chunk of chunks) {
all.set(chunk, at)
at += chunk.byteLength
}
return new TextDecoder().decode(all)
}
+117
View File
@@ -0,0 +1,117 @@
/**
* IAWL idea 21: a switch must never read a value nobody understands as "off" or "open".
*
* A JavaScript config is not type-checked, so `accounts: 0`, `stats: 'false'` or
* `consentLog: { retentionDays: null }` reach the plugin as they are. Where such a value would switch a
* protection off, widen who sees something, or switch an opt-in feature (a public endpoint) on, the plugin stops
* at start with a message that names the option — like `twoFactor.requireSetup.windowHours` since 1.16.6.
* Real values (`true`, `false`, an object, a number in range, a known name) are unchanged.
*
* Exported so a project (or another plugin) can check its own switches the same way.
*/
const where = (path: string) => `[iapl] ${path}`
/** Throws unless `value` is `undefined`, `true` or `false`. */
export function assertBooleanSwitch(path: string, value: unknown): void {
if (value === undefined || typeof value === 'boolean') {return}
throw new Error(`${where(path)} must be true or false (received ${JSON.stringify(value)}). A string such as "false" is not read as off.`)
}
/** Throws unless `value` is `undefined`, `true`, `false` or an object (the option's settings). */
export function assertSwitchOrObject(path: string, value: unknown, { allowTrue = true }: { allowTrue?: boolean } = {}): void {
if (value === undefined || value === false || (allowTrue && value === true)) {return}
if (value && typeof value === 'object' && !Array.isArray(value)) {return}
const allowed = allowTrue ? 'true, false or an object' : 'false or an object'
throw new Error(`${where(path)} must be ${allowed} (received ${JSON.stringify(value)}). A value like 0, "" or "false" is not read as off.`)
}
/** Throws unless `value` is `undefined` or a finite number that is at least `min` (above it when `exclusive`). */
export function assertNumberSwitch(path: string, value: unknown, { exclusive = false, min }: { exclusive?: boolean; min: number }): void {
if (value === undefined) {return}
if (typeof value === 'number' && Number.isFinite(value) && (exclusive ? value > min : value >= min)) {return}
throw new Error(`${where(path)} must be a number ${exclusive ? 'above' : 'of at least'} ${min} (received ${JSON.stringify(value)}).`)
}
/** Throws unless `value` is `undefined` or one of `allowed`. */
export function assertOneOf(path: string, value: unknown, allowed: readonly string[]): void {
if (value === undefined || (typeof value === 'string' && allowed.includes(value))) {return}
throw new Error(`${where(path)} must be one of ${allowed.map((a) => `"${a}"`).join(', ')} (received ${JSON.stringify(value)}).`)
}
type Bag = Record<string, unknown> | undefined
const bag = (value: unknown): Bag => (value && typeof value === 'object' && !Array.isArray(value) ? (value as Record<string, unknown>) : undefined)
/**
* The plugin options whose nonsense values used to read as off or open. Called by iapl() before anything is built.
* Each line names what a bad value did before 1.17.1.
*/
export function assertPluginSwitches(options: Record<string, unknown>): void {
// `accounts: 0` / `''` dropped every account rule (staff-only reads, admin-only writes, the panel role,
// the password rule, the closed first-user route).
assertSwitchOrObject('accounts', options.accounts, { allowTrue: false })
// Opt-in features that add public endpoints or outbound calls: `'false'` switched them ON.
for (const name of ['cookieScanner', 'stats', 'consentLog', 'adminMeta', 'whiteLabel'] as const) {
assertSwitchOrObject(name, options[name])
}
assertBooleanSwitch('indexNow', options.indexNow)
// an unknown name ('IAPL') used to mean 'ipal': the scanner declared one visitor cookie while the site set another
assertOneOf('storageNames', options.storageNames, ['ipal', 'iapl'])
assertBooleanSwitch('lightbox', options.lightbox)
assertBooleanSwitch('enabled', options.enabled)
const forms = bag(options.forms)
if (forms) {assertSwitchOrObject('forms.attachments', forms.attachments)}
// `maxPerMinute: 'off'` / `null` / `{}` turned the upload endpoint's limit off; only 0 is documented as off.
const submit = bag(bag(forms?.attachments)?.submit)
if (submit) {
assertNumberSwitch('forms.attachments.submit.maxPerMinute', submit.maxPerMinute, { min: 0 })
assertNumberSwitch('forms.attachments.submit.timeoutMs', submit.timeoutMs, { min: 0 })
assertNumberSwitch('forms.attachments.submit.idleTimeoutMs', submit.idleTimeoutMs, { min: 0 })
}
const scanner = bag(options.cookieScanner)
if (scanner) {assertSwitchOrObject('cookieScanner.crawl', scanner.crawl)}
// `'false'` accepted a 2FA target that is not the admin collection (panel users without 2FA).
const twoFactor = bag(options.twoFactor)
if (twoFactor) {assertBooleanSwitch('twoFactor.allowCollectionMismatch', twoFactor.allowCollectionMismatch)}
// `null` / `0` / a negative number purged every proof of consent once a day.
const consentLog = bag(options.consentLog)
if (consentLog) {assertNumberSwitch('consentLog.retentionDays', consentLog.retentionDays, { exclusive: true, min: 0 })}
// `robots.index: 'false'` / `0` / `null` took the noindex off the admin panel.
const adminMeta = bag(options.adminMeta)
const robots = bag(adminMeta?.robots)
if (robots) {
assertBooleanSwitch('adminMeta.robots.index', robots.index)
assertBooleanSwitch('adminMeta.robots.follow', robots.follow)
}
// An unknown role name ('Admin', 'admins') showed the failure details to every staff account.
const alerts = bag(options.dashboardAlerts)
if (alerts) {
assertOneOf('dashboardAlerts.integrations', alerts.integrations, ['admin', 'editor', 'all'])
assertOneOf('dashboardAlerts.cookies', alerts.cookies, ['editor', 'all'])
}
// A window of 0 minutes (or 0 ms) is a limit that never fills.
const mail = bag(options.mail)
if (mail) {assertSwitchOrObject('mail.relay', mail.relay)}
const relay = bag(mail?.relay)
if (relay) {
const accountMail = relay.accountMail
if (accountMail !== false && accountMail !== undefined) {
const limits = bag(accountMail)
if (!limits) {throw new Error(`${where('mail.relay.accountMail')} must be false or an object (received ${JSON.stringify(accountMail)}).`)}
assertNumberSwitch('mail.relay.accountMail.windowMinutes', limits.windowMinutes, { exclusive: true, min: 0 })
assertNumberSwitch('mail.relay.accountMail.perAddress', limits.perAddress, { min: 1 })
assertNumberSwitch('mail.relay.accountMail.perVisitor', limits.perVisitor, { min: 1 })
}
const confirm = bag(relay.confirmRateLimit)
if (confirm) {
assertNumberSwitch('mail.relay.confirmRateLimit.windowMs', confirm.windowMs, { exclusive: true, min: 0 })
assertNumberSwitch('mail.relay.confirmRateLimit.max', confirm.max, { min: 1 })
}
}
}
+8 -1
View File
@@ -6,6 +6,7 @@ import { gpcFromHeaders, resolveConsent } from '../consent/gpc.js'
import { CONSENT_COOKIE, CONSENT_VERSION, readConsentRecord } from '../consent/storage.js' import { CONSENT_COOKIE, CONSENT_VERSION, readConsentRecord } from '../consent/storage.js'
import { createDailyPurge } from '../shared/purge.js' import { createDailyPurge } from '../shared/purge.js'
import { clientIp, consumeRateLimit } from '../shared/rateLimit.js' import { clientIp, consumeRateLimit } from '../shared/rateLimit.js'
import { readCappedBody } from '../shared/readCappedBody.js'
import { STATS_SLUG } from './collection.js' import { STATS_SLUG } from './collection.js'
import { dayOf, deviceFromUa, isBot, referrerHost, sanitizePath, VISITOR_ID_PATTERN } from './parse.js' import { dayOf, deviceFromUa, isBot, referrerHost, sanitizePath, VISITOR_ID_PATTERN } from './parse.js'
import { visitKey } from './visitKey.js' import { visitKey } from './visitKey.js'
@@ -46,6 +47,9 @@ function readCookie(header: null | string, name: string): string | undefined {
* version — the server checks, it doesn't take the browser's word for it. * version — the server checks, it doesn't take the browser's word for it.
* Logged-in panel users, bots and prefetches aren't counted. * Logged-in panel users, bots and prefetches aren't counted.
*/ */
/** Largest page-view body the endpoint reads (a path of 300 characters, a referrer, a locale, an id). */
export const STATS_MAX_BYTES = 4096
export function buildStatsEndpoint({ retentionDays = 90, timeZone = 'Europe/Warsaw' }: StatsOptions = {}): Endpoint { export function buildStatsEndpoint({ retentionDays = 90, timeZone = 'Europe/Warsaw' }: StatsOptions = {}): Endpoint {
return { return {
handler: async (req: PayloadRequest) => { handler: async (req: PayloadRequest) => {
@@ -63,7 +67,10 @@ export function buildStatsEndpoint({ retentionDays = 90, timeZone = 'Europe/Wars
let body: { l?: unknown; p?: unknown; r?: unknown; v?: unknown } let body: { l?: unknown; p?: unknown; r?: unknown; v?: unknown }
try { try {
body = (await request.json()) as typeof body // a page view is about 200 bytes: read no more than STATS_MAX_BYTES of whatever is sent
const text = request.body ? await readCappedBody(request, STATS_MAX_BYTES) : null
if (text === null) {return done}
body = JSON.parse(text) as typeof body
} catch { } catch {
return done return done
} }
+3
View File
@@ -67,6 +67,7 @@ import { searchSettingsFields } from './modules/seo/searchSettings.js'
import { migrateTitleSeparator } from './modules/seo/titleSeparator.js' import { migrateTitleSeparator } from './modules/seo/titleSeparator.js'
import { applyCollectionOverride } from './modules/shared/collectionOverride.js' import { applyCollectionOverride } from './modules/shared/collectionOverride.js'
import { assertDevelopmentHosts } from './modules/shared/developmentHosts.js' import { assertDevelopmentHosts } from './modules/shared/developmentHosts.js'
import { assertPluginSwitches } from './modules/shared/switches.js'
import { buildStatsCollection, buildStatsEndpoint } from './modules/stats/index.js' import { buildStatsCollection, buildStatsEndpoint } from './modules/stats/index.js'
import { visitorCookieFor } from './modules/stats/visitorCookie.js' import { visitorCookieFor } from './modules/stats/visitorCookie.js'
@@ -101,6 +102,8 @@ const TOTP_REDIRECT_PROVIDER = '@intecion/ipal-kit/admin#TotpRedirectProvider'
export const iapl = (options: IaplOptions): Plugin => { export const iapl = (options: IaplOptions): Plugin => {
// Validate eagerly — fail fast before Payload boots // Validate eagerly — fail fast before Payload boots
validateI18nConfig(options.i18n) validateI18nConfig(options.i18n)
// a switch never reads a value nobody understands as off or open (IAWL idea 21)
assertPluginSwitches(options as unknown as Record<string, unknown>)
return async (incomingConfig: Config): Promise<Config> => { return async (incomingConfig: Config): Promise<Config> => {
const config = await transform(incomingConfig) const config = await transform(incomingConfig)
+199
View File
@@ -0,0 +1,199 @@
/**
* IAWL security ideas, group B (locales, save and state, signatures, switches, secret fields, HTML) — the unit
* proofs of what was fixed. The HTTP proofs are in iawlIdeasBHttp.test.ts.
*/
import { describe, expect, test } from 'vitest'
import { describeFromMarkdown, truncate } from '../src/modules/seo/plainText.js'
/** Idea 2: a value the plugin writes after validation must still fit the limit it was cut to. */
describe('a cut value fits its limit', () => {
test.each([10, 155, 300])('truncate(…, %i) is never longer than the limit', (max) => {
for (const text of ['x'.repeat(max * 2), `${'word '.repeat(max)}`, `${'y'.repeat(max - 1)} ${'z'.repeat(max)}`]) {
const out = truncate(text, max)
expect(out.length).toBeLessThanOrEqual(max)
expect(out.endsWith('…')).toBe(true)
}
})
test('describeFromMarkdown keeps to its length when it has to cut', () => {
expect(describeFromMarkdown('a'.repeat(400), 155).length).toBeLessThanOrEqual(155)
})
test('a text within the limit is left as it is', () => {
expect(truncate('short text', 155)).toBe('short text')
})
})
/** A body sent without a content-length (chunked): the stream is the only thing that tells its size. */
const chunked = (url: string, size: number, init: RequestInit = {}) => {
const chunk = new TextEncoder().encode('x'.repeat(1024))
let sent = 0
let pulled = 0
const body = new ReadableStream<Uint8Array>({
pull(controller) {
pulled += 1
if (sent >= size) {return controller.close()}
sent += chunk.byteLength
controller.enqueue(chunk)
},
})
const request = new Request(url, { ...init, body, duplex: 'half', method: 'POST' } as RequestInit)
return { pulled: () => pulled, request }
}
/** Idea 1: the size of a request is checked before it is read whole, the length of a query before it is searched. */
describe('request size and list length before the work', () => {
test('the CSP report route stops reading a chunked body at its cap', async () => {
const { createCspReportRoute } = await import('../src/modules/security/createCspReportRoute.js')
const reports: unknown[] = []
const route = createCspReportRoute({ maxBytes: 4096, onReport: (v) => void reports.push(v) })
const big = chunked('http://site.test/api/csp-report', 1024 * 1024)
expect((await route(big.request)).status).toBe(413)
expect(big.pulled()).toBeLessThan(16)
})
test('the mail service confirm call stops reading a chunked body at its cap', async () => {
const { relayConfirmEndpoint } = await import('../src/modules/email/relay/confirm.js')
const endpoint = relayConfirmEndpoint()
const big = chunked('http://site.test/api/iapl/mail-relay/confirm', 1024 * 1024, { headers: { 'x-forwarded-for': '203.0.113.9' } })
const res = await endpoint.handler(big.request as never)
expect(res.status).toBe(404)
expect(big.pulled()).toBeLessThan(16)
})
test('the MCP route refuses a body over its cap before parsing it', async () => {
const { createMcpRoute } = await import('../src/modules/mcp/createMcpRoute.js')
const { POST } = createMcpRoute({
config: { defaultLocale: 'pl', locales: [{ code: 'pl', label: 'Polski' }] },
getCachedPayload: () => Promise.reject(new Error('must not be reached')),
rateLimit: false,
})
const big = chunked('http://site.test/api/mcp', 4 * 1024 * 1024)
const res = await POST(big.request)
expect(res.status).toBe(413)
expect(big.pulled()).toBeLessThan(200)
})
test('searchContent cuts a huge query before it reaches the database', async () => {
const { searchContent } = await import('../src/modules/content/searchContent.js')
const seen: string[] = []
const payload = {
find: async ({ where }: { where: { or: { title: { like: string } }[] } }) => {
seen.push(where.or[0].title.like)
return { docs: [] }
},
findGlobal: async () => ({}),
}
const query = Array.from({ length: 5000 }, (_, i) => `w${i}`).join(' ')
await searchContent({ config: { defaultLocale: 'pl', locales: [{ code: 'pl', label: 'Polski' }] }, payload: payload as never, query })
expect(seen).toHaveLength(1)
expect(seen[0].length).toBeLessThanOrEqual(200)
expect(seen[0].split(' ').length).toBeLessThanOrEqual(10)
// a normal query is passed as it is
await searchContent({ config: { defaultLocale: 'pl', locales: [{ code: 'pl', label: 'Polski' }] }, payload: payload as never, query: 'cennik usług' })
expect(seen[1]).toBe('cennik usług')
})
test('the visit counter does not read a chunked body past its cap', async () => {
const { buildStatsEndpoint } = await import('../src/modules/stats/endpoint.js')
const endpoint = buildStatsEndpoint({} as never)
const big = chunked('http://site.test/api/ipal/hit', 1024 * 1024, { headers: { 'user-agent': 'Mozilla/5.0', 'x-forwarded-for': '203.0.113.10' } })
const res = await endpoint.handler(Object.assign(big.request, { payload: {} }) as never)
expect(res.status).toBe(204)
expect(big.pulled()).toBeLessThan(16)
})
})
/** Idea 21: a value nobody understands as off is refused at start, never read as off or open. */
describe('switches refuse nonsense at start', () => {
const i18n = { defaultLocale: 'pl', locales: [{ code: 'pl', label: 'Polski' }] } as const
const start = async (options: Record<string, unknown>) => {
const { iapl } = await import('../src/plugin.js')
return () => iapl({ i18n, ...options } as never)
}
test.each([
['accounts', { accounts: 0 }],
['accounts', { accounts: '' }],
['stats', { stats: 'false' }],
['cookieScanner', { cookieScanner: 'off' }],
['indexNow', { indexNow: 'false' }],
['forms.attachments', { forms: { attachments: 'false' } }],
['twoFactor.allowCollectionMismatch', { twoFactor: { allowCollectionMismatch: 'false', collection: 'users', totp: { issuer: 'x' } } }],
['consentLog.retentionDays', { consentLog: { retentionDays: null } }],
['consentLog.retentionDays', { consentLog: { retentionDays: 0 } }],
['adminMeta.robots.index', { adminMeta: { robots: { index: 'false' } } }],
['dashboardAlerts.integrations', { dashboardAlerts: { integrations: 'Admin' } }],
['mail.relay.accountMail.windowMinutes', { mail: { relay: { accountMail: { windowMinutes: 0 } } } }],
['mail.relay.confirmRateLimit.windowMs', { mail: { relay: { confirmRateLimit: { windowMs: 0 } } } }],
['mail.relay', { mail: { relay: 'off' } }],
['storageNames', { storageNames: 'IAPL' }],
['forms.attachments.submit.maxPerMinute', { forms: { attachments: { submit: { maxPerMinute: 'off' } } } }],
])('%s: %j fails at start', async (name, options) => {
expect(await start(options)).toThrow(name)
})
test.each([
[{}],
[{ accounts: false, consentLog: { retentionDays: 30 }, cookieScanner: false, indexNow: true, stats: true }],
[{ dashboardAlerts: { cookies: 'all', integrations: 'editor' }, mail: { relay: { accountMail: false } } }],
[{ adminMeta: { robots: { follow: false, index: false } }, forms: { attachments: { submit: { maxPerMinute: 0 } } } }],
])('real values start as before: %j', async (options) => {
expect(await start(options)).not.toThrow()
})
test('an unknown role name is met by nobody, and requireRole refuses it where it is written', async () => {
const { hasMinimumRole, userMeetsRole } = await import('../src/modules/access/predicates.js')
const { requireRole, requireRoleField } = await import('../src/modules/access/access.js')
const payload = { collections: { users: { config: { fields: [{ name: 'roles' }] } } }, config: { admin: { user: 'users' }, collections: [{ slug: 'users', auth: true }] } }
const admin = { id: 1, collection: 'users', roles: ['admin'] }
expect(hasMinimumRole(admin as never, 'admin', payload as never)).toBe(true)
expect(hasMinimumRole(admin as never, 'Admin' as never, payload as never)).toBe(false)
expect(userMeetsRole({ payload: payload as never, user: { ...admin, roles: [] } }, 'admins' as never)).toBe(false)
expect(() => requireRole('superadmin' as never)).toThrow('requireRole')
expect(() => requireRoleField('Editor' as never)).toThrow('requireRoleField')
expect(() => requireRole('editor')).not.toThrow()
})
test('buildCsp refuses a string where sources are a list, and a dev flag that is not a boolean', async () => {
const { buildCsp } = await import('../src/modules/security/buildCsp.js')
expect(() => buildCsp({ extra: { 'img-src': 'https://*.cdn.com' as never } })).toThrow("extra['img-src']")
expect(() => buildCsp({ dev: 'false' as never })).toThrow('buildCsp.dev')
expect(buildCsp({ dev: false, extra: { 'img-src': ['https://cdn.example.com'] } }).value).toContain('img-src')
})
test('buildSecurityHeaders refuses values a browser would drop', async () => {
const { buildSecurityHeaders } = await import('../src/modules/security/buildSecurityHeaders.js')
expect(() => buildSecurityHeaders({ hsts: null as never })).toThrow('hsts')
expect(() => buildSecurityHeaders({ hstsMaxAge: 'abc' as never })).toThrow('hstsMaxAge')
expect(() => buildSecurityHeaders({ frameOptions: 'false' as never })).toThrow('frameOptions')
expect(buildSecurityHeaders({ frameOptions: null, permissionsPolicy: null }).map((h) => h.key)).not.toContain('X-Frame-Options')
expect(buildSecurityHeaders().map((h) => h.key)).toContain('Strict-Transport-Security')
})
test('the seed guard cannot be switched off by 0 or allowed by "false"', async () => {
const { createSeeder } = await import('../src/modules/seed/seeder.js')
const payload = { logger: { info: () => {} } } as never
expect(() => createSeeder(payload, { guard: 0 as never })).toThrow('seed guard')
expect(() => createSeeder(payload, { guard: { allowFull: 'false' as never } })).toThrow('seed guard.allowFull')
})
})
/** Idea 25 at the search route: a code the site does not have is the default locale, in the search and the answer. */
test('createSearchRoute never passes an unknown ?locale on', async () => {
const { createSearchRoute } = await import('../src/modules/content/createSearchRoute.js')
const asked: string[] = []
const route = createSearchRoute({
config: { defaultLocale: 'pl', locales: [{ code: 'pl', label: 'Polski' }, { code: 'en', label: 'English' }] },
getCachedPayload: async () => ({ find: async () => ({ docs: [{ id: 1, slug: 'o-nas', title: 'O nas' }] }), findGlobal: async () => ({}) }) as never,
isPathVisible: async (_path, locale) => {
asked.push(locale)
return true
},
rateLimit: false,
})
const body = (await (await route(new Request('http://site.test/api/search?q=nas&locale=../xx'))).json()) as { locale: string }
expect(body.locale).toBe('pl')
expect(asked.every((l) => l === 'pl')).toBe(true)
})
+99
View File
@@ -0,0 +1,99 @@
/**
* IAWL ideas 23–25 against a running Payload (SQLite): what a visitor's URL can make the content helpers serve.
* 23 — a draft is shown only where it is asked for: never as the site's 404 page.
* 24/25 — IAPL has no hidden locales; the stand-in it must not invent is a page in a locale the site does not
* have (`/md/xx`, `/xx/…` past the proxy, `all`): those are "not found", not the default locale's page.
*/
import type { Payload } from 'payload'
import { lexicalEditor } from '@payloadcms/richtext-lexical'
import os from 'os'
import path from 'path'
import { getPayload } from 'payload'
import { afterAll, beforeAll, describe, expect, test, vi } from 'vitest'
import { createMarkdownRoute } from '../src/modules/content/createMarkdownRenderer.js'
import { resolveNotFoundPage } from '../src/modules/content/resolveNotFoundPage.js'
import { resolveRoute } from '../src/modules/content/resolveRoute.js'
import { iapl } from '../src/plugin.js'
import { buildTestConfig } from './helpers.js'
import { testDatabase } from './http/db.js'
vi.mock('server-only', () => ({}))
const i18n = { defaultLocale: 'pl', locales: [{ code: 'pl', label: 'Polski' }, { code: 'en', label: 'English' }] } as const
let payload: Payload
let draft404: number | string
let published404: number | string
beforeAll(async () => {
const config = buildTestConfig({
collections: [
{
slug: 'pages',
access: { read: () => true },
fields: [
{ name: 'title', type: 'text', localized: true },
{ name: 'slug', type: 'text', localized: true },
{ name: 'layout', type: 'blocks', blocks: [{ slug: 'text', fields: [{ name: 'body', type: 'textarea', localized: true }] }] },
],
versions: { drafts: true },
},
{ slug: 'media', fields: [], upload: { staticDir: path.join(os.tmpdir(), 'iawlb-content-media') } },
],
db: testDatabase('iawlb_content'),
editor: lexicalEditor(),
plugins: [iapl({ access: { authCollection: 'users' }, i18n, pages: { slug: 'pages' }, twoFactor: false })],
secret: 'iawl-ideas-b-content',
telemetry: false,
})
payload = await getPayload({ config })
const home = await payload.create({ collection: 'pages' as never, data: { slug: 'start', _status: 'published', layout: [{ blockType: 'text', body: 'Witamy' }], title: 'Start' } as never, locale: 'pl' })
await payload.update({ id: home.id, collection: 'pages' as never, data: { slug: 'home', _status: 'published', title: 'Home' } as never, locale: 'en' })
draft404 = (await payload.create({ collection: 'pages' as never, data: { slug: 'nie-znaleziono', _status: 'draft', title: 'Szkic: nowa cena 999 zł' } as never, draft: true, locale: 'pl' })).id
published404 = (await payload.create({ collection: 'pages' as never, data: { slug: 'brak', _status: 'published', title: 'Nie ma takiej strony' } as never, locale: 'pl' })).id
await payload.updateGlobal({ slug: 'site-settings' as never, data: { homepage: home.id, notFound: draft404, siteName: 'Test' } as never })
}, 60_000)
afterAll(async () => {
await payload?.destroy()
})
describe('idea 23: a never-published page is not the 404 page', () => {
test('resolveNotFoundPage gives the built-in view (null) while the assigned page is a draft', async () => {
expect(await resolveNotFoundPage({ locale: 'pl', payload })).toBeNull()
})
test('once a published page is assigned, it is the 404 page', async () => {
await payload.updateGlobal({ slug: 'site-settings' as never, data: { notFound: published404 } as never })
expect(await resolveNotFoundPage({ locale: 'pl', payload })).toMatchObject({ title: 'Nie ma takiej strony' })
await payload.updateGlobal({ slug: 'site-settings' as never, data: { notFound: draft404 } as never })
})
test('createContentHelpers().getNotFoundPage keeps the draft out too', async () => {
const { createContentHelpers } = await import('../src/modules/frontend/createContentHelpers.js')
const helpers = createContentHelpers({ config: payload.config, i18n })
expect(await helpers.getNotFoundPage('pl')).toBeNull()
})
})
describe('ideas 24/25: no stand-in locale', () => {
test('a configured locale resolves its own page', async () => {
expect(await resolveRoute({ locale: 'en', payload, segments: [] })).toMatchObject({ doc: { title: 'Home' } })
})
test.each(['xx', 'all', '*', 'de'])('locale %j resolves nothing (not the default locale\'s page)', async (locale) => {
expect(await resolveRoute({ locale, payload, segments: [] })).toBeNull()
})
test('the Markdown route answers 404 for /md/xx and /md/all', async () => {
const { GET } = createMarkdownRoute({ config: i18n, getCachedPayload: async () => payload })
for (const locale of ['xx', 'all']) {
const res = await GET(new Request(`http://site.test/md/${locale}`), { params: Promise.resolve({ locale }) })
expect(res.status).toBe(404)
}
const ok = await GET(new Request('http://site.test/md/pl'), { params: Promise.resolve({ locale: 'pl' }) })
expect(ok.status).toBe(200)
expect(await ok.text()).toContain('Witamy')
})
})
+170
View File
@@ -0,0 +1,170 @@
/**
* IAWL security ideas, group B, through real HTTP (REST and GraphQL) against a running Payload.
* SQLite by default; Postgres / MongoDB with IPAL_TEST_POSTGRES_URI / IPAL_TEST_MONGO_URI (test/http/db.ts).
*
* 22/37 — the versions of Site integrations (a project may turn them on) are read by the people who read the
* global, not by every signed-in account; the secrets stay masked there.
* 23 — drafts over REST / GraphQL follow the collection's `read` rule: Payload's open `read: () => true`
* answers `?draft=true` with the draft; readPublished() (exported) keeps drafts for the editors.
* 24/25 — locales: every locale IAPL configures is public; an unknown `?locale=` is the default locale's text,
* never another locale's draft.
*/
import type { Payload } from 'payload'
import { lexicalEditor } from '@payloadcms/richtext-lexical'
import os from 'os'
import path from 'path'
import { getPayload } from 'payload'
import { afterAll, beforeAll, describe, expect, test, vi } from 'vitest'
import { readPublished } from '../src/modules/access/access.js'
import { SECRET_MASK } from '../src/modules/secrets/writeOnly.js'
import { iapl } from '../src/plugin.js'
import { buildTestConfig } from './helpers.js'
import { testDatabase } from './http/db.js'
import { startPayloadServer, type TestServer } from './http/server.js'
vi.mock('server-only', () => ({}))
const PASSWORD = 'a-long-test-password-1'
const SMTP = 'S3CRET-smtp-value'
let server: TestServer
let payload: Payload
const tokens: Record<'admin' | 'editor' | 'user', string> = { admin: '', editor: '', user: '' }
let openDraftId: number | string
let guardedDraftId: number | string
let guardedPublishedId: number | string
const api = (pathname: string, as?: keyof typeof tokens, init: RequestInit = {}) =>
fetch(`${server.url}/api${pathname}`, { ...init, headers: { 'content-type': 'application/json', ...(as ? { authorization: `JWT ${tokens[as]}` } : {}) } })
const gql = async (query: string, as?: keyof typeof tokens) =>
(await (await api('/graphql', as, { body: JSON.stringify({ query }), method: 'POST' })).json()) as { data?: Record<string, unknown>; errors?: { message: string }[] }
const pageFields = [
{ name: 'title', type: 'text' as const, localized: true },
{ name: 'secretNote', type: 'text' as const },
]
beforeAll(async () => {
const config = buildTestConfig({
admin: { user: 'users' },
collections: [
// a project collection with drafts and Payload's open read rule
{ slug: 'open-pages', access: { read: () => true }, fields: pageFields, versions: { drafts: true } },
// the same with the exported rule
{ slug: 'guarded-pages', access: { read: readPublished(), readVersions: readPublished() }, fields: pageFields, versions: { drafts: true } },
{ slug: 'media', fields: [], upload: { staticDir: path.join(os.tmpdir(), 'iawlb-http-media') } },
],
db: testDatabase('iawlb_http'),
editor: lexicalEditor(),
plugins: [
iapl({
access: { authCollection: 'users' },
globalOverrides: { 'site-integrations': { versions: { drafts: true } } as never },
i18n: { defaultLocale: 'pl', locales: [{ code: 'pl', label: 'Polski' }, { code: 'en', label: 'English' }] },
twoFactor: false,
}),
],
secret: 'iawl-ideas-b-http-0123456789',
telemetry: false,
})
payload = await getPayload({ config })
server = await startPayloadServer(config)
for (const role of ['admin', 'editor', 'user'] as const) {
await payload.create({ collection: 'users' as never, data: { email: `${role}@example.com`, password: PASSWORD, roles: [role] } as never })
const login = (await (await fetch(`${server.url}/api/users/login`, { body: JSON.stringify({ email: `${role}@example.com`, password: PASSWORD }), headers: { 'content-type': 'application/json' }, method: 'POST' })).json()) as { token: string }
tokens[role] = login.token
}
await payload.updateGlobal({ slug: 'site-integrations' as never, data: { emailTransport: 'smtp', smtpHost: 'smtp.example.com', smtpPassword: SMTP, smtpPort: 587, smtpUser: 'mailer' } as never })
await payload.updateGlobal({ slug: 'site-integrations' as never, data: { smtpHost: 'smtp2.example.com', smtpPassword: `${SMTP}-2` } as never })
const draft = { _status: 'draft', secretNote: 'draft only', title: 'Nowy cennik (szkic)' }
openDraftId = (await payload.create({ collection: 'open-pages' as never, data: draft as never, draft: true, locale: 'pl' })).id
guardedDraftId = (await payload.create({ collection: 'guarded-pages' as never, data: draft as never, draft: true, locale: 'pl' })).id
guardedPublishedId = (await payload.create({ collection: 'guarded-pages' as never, data: { _status: 'published', secretNote: 'v1', title: 'Cennik' } as never, locale: 'pl' })).id
await payload.update({ id: guardedPublishedId, collection: 'guarded-pages' as never, data: { _status: 'published', title: 'Prices' } as never, locale: 'en' })
// a newer draft on top of the published page
await payload.update({ id: guardedPublishedId, collection: 'guarded-pages' as never, data: { _status: 'draft', title: 'Cennik — szkic podwyżki' } as never, draft: true, locale: 'pl' })
}, 120_000)
afterAll(async () => {
await server?.close()
await payload?.destroy?.()
})
describe('ideas 22/37: versions of Site integrations', () => {
test.each(['user', 'editor'] as const)('a %s account cannot list them (REST)', async (as) => {
expect((await api('/globals/site-integrations/versions', as)).status).toBe(403)
})
test('an anonymous visitor cannot list them (REST)', async () => {
expect((await api('/globals/site-integrations/versions')).status).toBe(403)
})
test.each(['user', 'editor'] as const)('a %s account gets nothing over GraphQL', async (as) => {
const res = await gql('{ versionsSiteIntegrations { docs { id version { smtpHost smtpUser } } } }', as)
expect(JSON.stringify(res.data ?? {})).not.toContain('smtp')
expect(res.errors?.length).toBeGreaterThan(0)
})
test('an admin lists them, with every stored secret masked', async () => {
const res = await api('/globals/site-integrations/versions?depth=0&limit=50', 'admin')
expect(res.status).toBe(200)
const body = JSON.stringify(await res.json())
expect(body).toContain('smtp2.example.com')
expect(body).not.toContain(SMTP)
expect(body).toContain(SECRET_MASK)
})
})
describe('idea 23: drafts over REST and GraphQL', () => {
test("Payload's open read rule answers ?draft=true with the draft (the project's rule, shown for the record)", async () => {
const res = (await (await api(`/open-pages/${openDraftId}?draft=true`)).json()) as { secretNote?: string }
expect(res.secretNote).toBe('draft only')
})
test('readPublished(): a never-published page is not found for a visitor, by id, list, draft=true or GraphQL', async () => {
expect((await api(`/guarded-pages/${guardedDraftId}`)).status).toBe(404)
expect((await api(`/guarded-pages/${guardedDraftId}?draft=true`)).status).toBe(404)
const list = (await (await api('/guarded-pages?draft=true&limit=50')).json()) as { docs: { id: unknown }[] }
expect(list.docs.map((d) => d.id)).not.toContain(guardedDraftId)
const res = await gql(`{ GuardedPages(draft: true, limit: 50) { docs { id title } } }`)
expect(JSON.stringify(res.data)).not.toContain('szkic')
})
test('readPublished(): a published page shows its published text, never the newer draft', async () => {
const res = (await (await api(`/guarded-pages/${guardedPublishedId}?locale=pl`)).json()) as { title?: string }
expect(res.title).toBe('Cennik')
// asking for the draft: Payload applies the rule to the newest version, which is a draft — not found, no text
const asked = await api(`/guarded-pages/${guardedPublishedId}?draft=true&locale=pl`)
expect(asked.status).toBe(404)
expect(await asked.text()).not.toContain('szkic')
// the version list: a visitor sees published versions only
expect(await (await api('/guarded-pages/versions?limit=50')).text()).not.toContain('szkic')
})
test('readPublished(): an editor still sees the draft', async () => {
const res = (await (await api(`/guarded-pages/${guardedPublishedId}?draft=true&locale=pl`, 'editor')).json()) as { title?: string }
expect(res.title).toBe('Cennik — szkic podwyżki')
expect((await api(`/guarded-pages/${guardedDraftId}`, 'editor')).status).toBe(200)
})
test('readPublished(): a plain user account is a visitor', async () => {
expect((await api(`/guarded-pages/${guardedDraftId}`, 'user')).status).toBe(404)
})
})
describe('ideas 24/25: locales', () => {
test('every configured locale is public; locale=all gives the published text of each', async () => {
const res = (await (await api(`/guarded-pages/${guardedPublishedId}?locale=all`)).json()) as { title?: Record<string, string> }
expect(res.title).toEqual({ en: 'Prices', pl: 'Cennik' })
})
test('an unknown ?locale= and ?fallback-locale= give the default locale, never a draft', async () => {
for (const q of ['locale=xx', 'locale=xx&fallback-locale=en', 'locale=en&fallback-locale=xx']) {
const res = (await (await api(`/guarded-pages/${guardedPublishedId}?${q}`)).json()) as { title?: string }
expect(['Cennik', 'Prices']).toContain(res.title)
expect(await (await api(`/guarded-pages/${guardedPublishedId}?${q}&draft=true`)).text()).not.toContain('szkic')
}
})
})
+32
View File
@@ -49,3 +49,35 @@ describe('RenderRichText', () => {
expect(raw).toContain('href="data:text/html') expect(raw).toContain('href="data:text/html')
}) })
}) })
/**
* One rule, one function (IAWL idea 19): an `autolink` marked `linkType: 'internal'` is rendered by Payload from
* `fields.url` all the same, and the Markdown output (llms / `.md` routes) prints link URLs too — both must pass
* the same safeHref check as <CMSLink> and the plain link.
*/
describe('a second way to write the same link', () => {
const bad = 'data:text/html,<script>alert(1)</script>'
test('an autolink marked internal is neutralised like any other', () => {
expect(urls(sanitizeRichTextLinks(doc(link(bad, 'autolink', 'internal'))))).toEqual(['#'])
})
test('a link marked internal loses an unsafe stored url too (Payload renders its own href)', () => {
expect(urls(sanitizeRichTextLinks(doc(link(bad, 'link', 'internal'))))).toEqual(['#'])
})
test('RenderRichText never prints the unsafe URL of an internal autolink', 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: doc(link(bad, 'autolink', 'internal')) as never }))
expect(html).not.toContain('data:')
})
test('the Markdown output drops an unsafe link target and keeps the label', async () => {
const { lexicalToMarkdown } = await import('../src/modules/richtext/lexicalToMarkdown.js')
const md = lexicalToMarkdown(doc(link('javascript:alert(1)'), link(bad, 'autolink'), link('https://acme.pl')) as never)
expect(md).not.toMatch(/javascript:|data:/)
expect(md).toContain('[x](https://acme.pl)')
})
})