Merge claude/security-b-content-state-cc308e: sizes before work, one link rule, no stand-in locale, strict switches, write-only secrets cannot be queried

AGENT.md conflict: the 2FA rows from A, the stored-secrets row from B (its check answers 400 QueryError, not 403).

Co-Authored-By: Claude Opus 5.5 <[email protected]>
This commit is contained in:
Radosław Smoliński
2026-11-26 21:43:03 +01:00
co-authored by Claude Opus 5.5
40 changed files with 1148 additions and 72 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)
```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 = {
slug: 'articles',
@@ -191,8 +191,19 @@ access: { read: adminOrSelf } // fine with a single auth collection
// any minimum threshold
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)
```ts
+8 -3
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 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 |
| 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 |
**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 |
| 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 |
| 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**
| 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 |
| 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` |
| 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` |
| 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` |
@@ -1222,7 +1227,7 @@ add missing hosts with flags / `extra`; (3) change `mode` to `'enforce'` in both
| The second factor on every collection and global, whichever plugin added it, and on the plugin's endpoints; an unrecognised 2FA package = startup error | per entity: `custom.ipal.secondFactor: false` or `{ read: false }` (or the package's `custom.totp.disableAccessWrapper`); everywhere: `twoFactor.guard: false` (not recommended) | `requireSecondFactor` / `secondFactorPassed` in your own access functions and endpoints |
| At most 5 **wrong** verify codes per account in 10 minutes (`POST /api/verify-totp` → `429`); a right code gives its place back (1.17.1), so correct logins are never refused; an attempt held out only by others still being checked gets `429` + `Retry-After: 2` ("try again in a moment"); the count is kept in memory and in the database (`payload.kv`), so a restart or a second instance does not reset it. **Verify:** log in correctly 7 times in a row → all in; 5 wrong codes → the next gets `429` with a long `Retry-After` | `twoFactor.verifyLimit: false` | `verifyLimit: { max, windowMinutes, store: 'memory' }`; own wiring: `buildVerifyLimit(...)` + `limit.settle(req, correct)` |
| 2FA verify and setup attempts only from the site's own origin: a request a browser marks as coming from elsewhere (`Origin`, `Sec-Fetch-Site`) gets `403` and is not counted. The admin's reset `POST /api/ipal/two-factor/reset` follows the same rule (1.17.1). **Verify:** `curl -X POST <site>/api/ipal/two-factor/reset -H 'Origin: https://other.example' -H 'Content-Type: text/plain' -b <admin cookies> -d '{"userId":1}'` → `403`; the panel's button still works. **Set `serverURL`**: behind a proxy that rewrites `Host` and sends no `X-Forwarded-Host` the site's own page is refused without it (logged once per origin: `[iapl] 2FA: a code from origin … was refused`) | `twoFactor.sameOrigin: false` | `sameOrigin: { origins: ['https://app.example.com'] }`; `requestFromOwnOrigin`, `reportRefusedOrigin` |
| Stored secrets are write-only: `smtpPassword` and `turnstileSecretKey` come back as `'********'` over REST, GraphQL and in the panel; an empty save keeps the value, `'[[clear]]'` removes it; server code reads the real value with the Local API. **The panel is the source — never add an env variable for them** (`TURNSTILE_SECRET_KEY` is deprecated) | `secrets: { writeOnly: false }` | `writeOnlySecret(field)` / `writeOnlySecrets(fields, names)` for your own secret fields; with versions on the entity add `hooks.afterRead: [maskSecretsOnRestore]` |
| Stored secrets are write-only: `smtpPassword` and `turnstileSecretKey` come back as `'********'` over REST, GraphQL and in the panel; an empty save keeps the value, `'[[clear]]'` removes it; server code reads the real value with the Local API. A query cannot name a secret (1.17.1): `where` / `sort` on it — REST, GraphQL, versions — is refused (`secretReadAccess`, the field's `read` rule; verify: `GET /api/globals/site-integrations/versions?where[version.smtpPassword][exists]=true` as an admin → 400 `QueryError`, no `totalDocs`). **The panel is the source — never add an env variable for them** (`TURNSTILE_SECRET_KEY` is deprecated) | `secrets: { writeOnly: false }` | `writeOnlySecret(field)` / `writeOnlySecrets(fields, names)` for your own secret fields; with versions on the entity add `hooks.afterRead: [maskSecretsOnRestore]` |
| The SMTP password stays with its server: a save in the panel or over the API that changes the server, port or user name without the password is refused (`400` "Enter the password again…"), whatever the transport says — otherwise an admin session points the server at its own machine and a test e-mail hands the password over. A change of the transport alone asks for nothing. Seeds and scripts (Local API, access control off) are not asked | `secrets: { reenterOnChange: false }` | `writeOnlySecret(field, { boundTo: [...] })`, `buildKeepSecret`, `SMTP_PASSWORD_BOUND_TO` |
| The admin panel opens for `editor` and above; an account with only `user` sees "Unauthorized" (the API is not touched). First start logs how many accounts are below the role | `accounts: { panelRole: 'user' }` (or `false`) | `panelRole: 'admin'`; your own `access.admin`; `panelAccess(role)` |
| Nobody creates an account for themselves, or takes one over. A staff collection (also the project's own, also one a later plugin adds) without a `create` / `update` / `delete` / `unlock` / `read` / `readVersions` rule gets one (on a collection a later plugin adds the plugin's rule is put in front of its own and both must allow; `custom: { ipal: { accountRules: false } }` on it keeps its own): with the plugin's roles, or wherever an account of it can hold `editor` or `admin` (`user, editor, admin, boss`; `viewer, editor`; a `roles` field that is text, json or a relationship holding a list — the value in the account's `roles` array makes a plugin admin or editor; a single-valued `roles` field is not affected: its value never counts) — create, delete, unlock: an admin; update: an admin or the account itself; the `roles` field: only an admin. With roles of its own that hold neither `editor` nor `admin`, or none: an account of that same collection, or a plugin admin, and an account never changes its own roles — **the plugin cannot rank a project's own roles: write that collection's rules** (`iapl-doctor` → `staff-own-roles`). `read`: a staff account. Payload's first-user route answers only for the panel's login collection (the first account, which becomes admin), in any spelling of the URL. `access.firstUserAdmin: false` with a default role below the panel role: the default panel role is not applied (logged), an explicit one is refused at start. With a slug in `access.staffCollections` that is not an auth collection Payload does not start (`/api/health` 503) | `accounts: { adminOnlyCreate: false, adminOnlyWrite: false, staffOnlyRead: false, firstUserRoute: 'all' }` | your own rule wins; `firstUserRoute: ['users', 'partners']`; a collection with open sign-up keeps its routes; `staffCreateAccess`, `staffUpdateAccess(slug)`, `staffReadAccess`, `sameStaffCollectionAccess(slug)`, `rolesByAdminOnly`, `rolesNotOwn(slug)`, `hasPluginRoles`, `applyStaffAccountAccess`, `adoptLateAuthCollections`, `buildFirstUserEndpoint` |
+9
View File
@@ -76,4 +76,13 @@ 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'`).
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.
- **Secrets out of queries** (as an admin, with versions on for Site integrations or a collection using
`writeOnlySecret`): `curl -s -H "Authorization: JWT $T" "$U/api/globals/site-integrations/versions?where[version.smtpPassword][exists]=true"`
answers an error with no `totalDocs`, else ERROR (the field lost `secretReadAccess`, e.g. an override replaced its
`access`).
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
Site settings (`<slug>Archive`). The plugin handles routing, sitemap,
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
`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
+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`
(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
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
@@ -391,7 +396,8 @@ Query: `?q=` (required), `?locale=`, `?limit=`. Response:
"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`),
10 by default (`defaultLimit`), max 50 results. Under-construction mode:
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`
(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
`buildSummaryField` over `meta.description`; see [seo.md](./seo.md)). Never throws
(error → `[]`).
`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:
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 |
| `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 |
| `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`,
`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) |
| `generateStaticParams` | skipped (it is not a separate URL) |
| `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
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)`,
`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'`)
are not touched. Turn off (fully trusted content only): `<RenderRichText data={…} safeLinks={false} />`.
the database through an import, a seed or the API, bypassing the panel field. Since 1.17.1 one rule covers every
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)
+45 -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.
**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
`/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()]`.
@@ -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
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
Coolify app's **Logs**. Plug `onReport` into `payload.logger`, Sentry or a database for more.
@@ -1048,7 +1080,10 @@ later option, not part of this release.
**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
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
`maskSecretsOnRestore` masks them there too. A restore brings back the password of that version.
@@ -1056,6 +1091,14 @@ document, the fields under `version`, where field hooks do not run: the global's
value is set"; the API returns the mask. Code of your own that read the secret over REST / GraphQL as an admin
must read it on the server with the Local API instead.
- **Off:** `iapl({ secrets: { writeOnly: false } })` — the value is returned to whoever may read the global.
- **A query cannot name a secret (1.17.1).** A `where` or `sort` on a write-only field answers by the stored value
(`where[version.smtpPassword][like]=Zq` gave a count), so an admin could read the secret back one character at a
time. `writeOnlySecret` now gives the field a `read` rule, `secretReadAccess`, that refuses a query naming it —
REST and GraphQL, `like` / `equals` / `exists` / `sort`, on the document and its versions (an error, no count) — while
every read of a document still answers the mask and the panel shows and saves the field as before. Payload checks a
query's fields without a document and asks rules that depend on one to deny then; the panel always passes the
document. The field's own `access.read` is kept and decides for a document. Not in collection list columns or
list filters. Server code with `overrideAccess` (the Local API) may still query it.
- **Your own secret fields:** `writeOnlySecret({ name: 'apiToken', type: 'text', admin: { components: { Field:
'@intecion/ipal-kit/admin#MaskedField' } } })`, or `writeOnlySecrets(fields, ['apiToken'])` for fields inside
tabs / rows / groups; the hooks `maskSecretAfterRead` / `keepSecretBeforeValidate`, `SECRET_MASK`,
+2
View File
@@ -56,6 +56,8 @@ export function buildSiteIntegrations({
// 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.
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'),
},
admin: {
+5
View File
@@ -15,6 +15,7 @@ export {
injectRoles,
isAdmin,
isEditor,
readPublished,
requireRole,
requireRoleField,
ROLE_HIERARCHY,
@@ -203,6 +204,8 @@ export {
createMarkdownRoute,
createSearchRoute,
getArchiveEntries,
isSiteLocale,
limitQuery,
listContent,
MARKDOWN_PREFIX,
markdownHref,
@@ -212,6 +215,7 @@ export {
resolveNotFoundPage,
resolveRedirect,
resolveRoute,
SEARCH_QUERY_LIMIT,
searchContent,
} from './modules/content/index.js'
export type { ArchiveEntries } from './modules/content/index.js'
@@ -417,6 +421,7 @@ export {
maskWriteOnlySecrets,
SECRET_CLEAR,
SECRET_MASK,
secretReadAccess,
SMTP_PASSWORD_BOUND_TO,
writeOnlySecret,
writeOnlySecrets,
+29 -8
View File
@@ -3,6 +3,7 @@ import type { Access, FieldAccess } from 'payload'
import type { Role } from './types.js'
import { hasMinimumRole, isAdmin } from './predicates.js'
import { ROLE_HIERARCHY } from './types.js'
/**
* 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)
/** Requires at least the given role. */
export const requireRole =
(minimum: Role): Access =>
({ req }) =>
hasMinimumRole(req.user, minimum, req.payload)
export const requireRole = (minimum: Role): Access => {
assertKnownRole('requireRole', minimum)
return ({ req }) => 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.
@@ -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)
/** Requires at least the given role, for field-level access. */
export const requireRoleField =
(minimum: Role): FieldAccess =>
({ req }) =>
hasMinimumRole(req.user, minimum, req.payload)
export const requireRoleField = (minimum: Role): FieldAccess => {
assertKnownRole('requireRoleField', minimum)
return ({ req }) => 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,
adminOrSelfIn,
authenticated,
readPublished,
requireRole,
requireRoleField,
} 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 {
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. */
@@ -158,7 +160,9 @@ export function userMeetsRole({ payload, user }: { payload?: BasePayload; user?:
const slug = (user as { collection?: unknown }).collection
if (typeof slug !== 'string' || !staffCollectionSlugs(payload).includes(slug)) {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 fields = (collection?.flattenedFields ?? collection?.fields) as Array<{ name?: string }> | undefined
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 { createDailyPurge } from '../shared/purge.js'
import { clientIp, consumeRateLimit } from '../shared/rateLimit.js'
import { readCappedBody as readCapped } from '../shared/readCappedBody.js'
import { CONSENT_CATEGORIES } from './categories.js'
import { CONSENT_CATEGORY_LABELS } from './categoryLabels.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. */
export const CONSENT_LOG_MAX_BYTES = 4096
/**
* 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 = 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)
/** The request body as text, or null when it is larger than `max` bytes (shared/readCappedBody.ts). */
export function readCappedBody(request: Request, max: number = CONSENT_LOG_MAX_BYTES): Promise<null | string> {
return readCapped(request, max)
}
/** 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 { pathOf, type PathVisibility } from '../construction/visibility.js'
import { isValidLocale } from '../i18n/index.js'
import { clientIp, consumeRateLimit, tooManyRequests } from '../shared/rateLimit.js'
import { searchContent } from './searchContent.js'
@@ -22,6 +23,8 @@ type CreateSearchRouteArgs = {
homeSlug?: Record<string, string> | string
/** Hide pages the site hides (construction mode) — pass `isPathVisible` from createContentHelpers. */
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 }.
* `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.
*/
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.
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 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 limit = limitParam ? Number(limitParam) : defaultLimit
@@ -87,6 +92,7 @@ export function createSearchRoute(args: CreateSearchRouteArgs): (req: Request) =
locale,
payload,
query,
queryLimit,
settingsSlug,
summaryField,
})
+2 -2
View File
@@ -8,9 +8,9 @@ export { MARKDOWN_PREFIX, markdownHref, prefersMarkdown } from './markdownNegoti
export { buildArchivePath, buildEntryPath, parsePageParam } from './paths.js'
export { resolveNotFoundPage } from './resolveNotFoundPage.js'
export { resolveRedirect } from './resolveRedirect.js'
export { resolveRoute } from './resolveRoute.js'
export { isSiteLocale, resolveRoute } 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 { ContentCollectionOption, ContentOption } from './types.js'
export { archiveFieldName } from './types.js'
+4 -1
View File
@@ -1,5 +1,7 @@
import type { BasePayload } from 'payload'
import { isPublishedDoc } from './resolveRoute.js'
type ResolveNotFoundPageArgs = {
locale: string
/** Client's Pages collection slug. Defaults to 'pages'. */
@@ -49,7 +51,8 @@ export async function resolveNotFoundPage({
depth: 2,
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) {
console.warn('[iapl] resolveNotFoundPage: falling back to built-in 404 view:', error)
return null
+13
View File
@@ -89,6 +89,16 @@ function isPublic(doc: unknown, draft: boolean): boolean {
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({
content,
draft = false,
@@ -100,6 +110,9 @@ export async function resolveRoute({
settings: preloaded,
settingsSlug = 'site-settings',
}: 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 =
preloaded ??
((await payload.findGlobal({
+23 -1
View File
@@ -28,6 +28,11 @@ type SearchContentArgs = {
payload: BasePayload
/** Keywords. */
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'. */
settingsSlug?: string
/**
@@ -58,6 +63,22 @@ type PageRow = {
* Degrades to [] (never throws) when the collection's fields aren't queryable —
* 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({
baseUrl,
collection = 'pages',
@@ -67,10 +88,11 @@ export async function searchContent({
locale,
payload,
query,
queryLimit,
settingsSlug,
summaryField,
}: SearchContentArgs): Promise<SearchResult[]> {
const q = query.trim()
const q = limitQuery(query, queryLimit)
if (!q) {return []}
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 { clientIp, consumeRateLimit, tooManyRequests } from '../../shared/rateLimit.js'
import { readCappedBody } from '../../shared/readCappedBody.js'
import { RELAY_CONFIRM_PATH, RELAY_DEFAULTS } from './constants.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 })
async function readBody(req: PayloadRequest): Promise<unknown> {
const length = Number(req.headers.get('content-length') ?? 0)
if (length > MAX_BODY) {return null}
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
if (typeof read !== 'function') {return (await req.json?.()) as unknown}
const text = await read.call(req)
return text.length <= MAX_BODY ? (JSON.parse(text) as unknown) : null
const whole = await read.call(req)
return whole.length <= MAX_BODY ? (JSON.parse(whole) as unknown) : null
} catch {
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 { MARKDOWN_PREFIX, markdownHref } from '../content/markdownNegotiation.js'
import { resolveRedirect as resolveRedirectRaw } from '../content/resolveRedirect.js'
import { isPublishedDoc } from '../content/resolveRoute.js'
import { archiveFieldName } from '../content/types.js'
import { createHealthRoute } from '../health/createHealthRoute.js'
import { homeSlugFrom, resolveLink as resolveLinkRaw, resolveNav as resolveNavRaw, resolveSystemLinks } from '../links/resolveNav.js'
@@ -414,7 +415,8 @@ export function createContentHelpers({
depth: 2,
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 {
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 { collectSiteIndex } from '../seo/siteIndex.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
@@ -66,6 +67,8 @@ export type CreateMcpRouteArgs = {
isPathVisible?: PathVisibility
/** Max messages in one JSON-RPC batch. Default 10. */
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 }.
* `false` = off (a limiter in front, e.g. Cloudflare WAF rate limiting).
@@ -104,6 +107,7 @@ export function createMcpRoute(args: CreateMcpRouteArgs) {
getCachedPayload,
isPathVisible,
maxBatch = 10,
maxBytes = 64 * 1024,
serverName = 'ipal-site',
serverVersion = '1.0.0',
settingsSlug = 'site-settings',
@@ -321,7 +325,10 @@ export function createMcpRoute(args: CreateMcpRouteArgs) {
async function POST(req: Request): Promise<Response> {
let body: unknown
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 {
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 { safeHref } from '../links/resolveLinkHref.js'
/**
* Converts a Payload Lexical richText value to Markdown — a small, dependency-
* free walker over the serialized node tree. Self-contained on purpose: it does
@@ -53,12 +55,14 @@ function inline(nodes: unknown): string {
out += '\n'
} else if (type === 'link') {
const fields = (node.fields ?? {}) as Record<string, unknown>
const url =
const raw =
typeof fields.url === 'string'
? fields.url
: typeof (fields.doc as Record<string, unknown>)?.value === '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)
out += url ? `[${label}](${url})` : label
} else if (node.children) {
+3 -1
View File
@@ -30,7 +30,9 @@ function walk(value: unknown): unknown {
const node = value as LexicalNode
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 : ''
if (url && safeHref(url) === null) {result = { ...node, fields: { ...node.fields, url: '#' } }}
}
+23 -2
View File
@@ -1,4 +1,4 @@
import type { CollectionAfterReadHook, Field, FieldHook, GlobalAfterReadHook } from 'payload'
import type { CollectionAfterReadHook, Field, FieldAccess, FieldHook, GlobalAfterReadHook } from 'payload'
import { ValidationError } from 'payload'
@@ -130,11 +130,32 @@ export function buildKeepSecret({ appliesWhen, boundTo = [] }: WriteOnlySecretOp
*/
export const keepSecretBeforeValidate: FieldHook = buildKeepSecret()
/** Adds the two hooks to a field (a text field as a rule). The field's own hooks stay, and run around them. */
/**
* The field `read` rule of a write-only secret: a document may be read (the value comes back masked), a query may
* not name the field. A `where` / `sort` on the field answers by the stored value — `like: "Zq"` gives a count —
* so it would read the secret back one character at a time (review B-R1). Payload checks a query's fields with
* permissions built WITHOUT a document and asks rules that depend on one to deny then; the panel's edit and create
* views always pass the document (a global's stored data, a collection's `{ _status: 'draft', … }`), so the field
* stays visible and editable there. The field's own `read` rule, if any, still decides for a document.
*/
export function secretReadAccess(own?: FieldAccess): FieldAccess {
return (args) => {
const { data, doc, siblingData } = args as { data?: unknown; doc?: unknown; siblingData?: unknown }
if (doc === undefined && data === undefined && siblingData === undefined) {return false}
return own ? own(args) : true
}
}
/**
* Adds the two hooks to a field (a text field as a rule), and a `read` rule that keeps it out of queries
* (`secretReadAccess`). The field's own hooks stay, and run around them; its own `access` is kept.
*/
export function writeOnlySecret<F extends Field>(field: F, options: WriteOnlySecretOptions = {}): F {
const own = (field as { hooks?: { afterRead?: FieldHook[]; beforeValidate?: FieldHook[] } }).hooks ?? {}
const access = (field as { access?: { create?: FieldAccess; read?: FieldAccess; update?: FieldAccess } }).access
return {
...field,
access: { ...access, read: secretReadAccess(access?.read) },
custom: { ...(field as { custom?: Record<string, unknown> }).custom, ipalWriteOnly: true },
hooks: {
...own,
+23
View File
@@ -1,5 +1,7 @@
import type { SecurityHeader } from './buildSecurityHeaders.js'
import { assertBooleanSwitch, assertOneOf } from '../shared/switches.js'
export type CspDirective =
| 'base-uri'
| 'child-src'
@@ -76,6 +78,26 @@ export type BuildCspArgs = {
export const DEFAULT_CSP_REPORT_GROUP = 'csp-endpoint'
/** 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 {
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.
*/
export function buildCsp(args: BuildCspArgs = {}): { key: string; value: string } {
assertCspArgs(args)
const {
analytics,
clarity,
@@ -1,6 +1,7 @@
import type { BuildCspArgs } from './buildCsp.js'
import { isSiteNoindex } from '../seo/siteNoindex.js'
import { assertBooleanSwitch, assertNumberSwitch, assertOneOf } from '../shared/switches.js'
import { buildCspHeaders } from './buildCsp.js'
/**
@@ -82,6 +83,18 @@ export type BuildSecurityHeadersArgs = {
* }
*/
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 {
additional = [],
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. */
export type CspViolation = {
blockedUri?: string
@@ -92,15 +94,14 @@ export function createCspReportRoute(args: CreateCspReportRouteArgs = {}): (requ
} = args
return async (request: Request) => {
const length = Number(request.headers.get('content-length') ?? 0)
if (length > maxBytes) {return new Response(null, { status: 413 })}
let text: string
// read only up to the cap, whether or not the browser declared the length (a chunked body has none)
let text: null | string
try {
text = await request.text()
text = await readCappedBody(request, maxBytes)
} catch {
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
try {
+4
View File
@@ -3,6 +3,7 @@ import type { BasePayload } from 'payload'
import type { SeedTarget } from './values.js'
import { readEnv } from '../shared/envName.js'
import { assertBooleanSwitch, assertSwitchOrObject } from '../shared/switches.js'
import { activeSeedExitGuard } from './exitGuard.js'
import { isLocalDatabase, seedDatabaseUrl } from './guard.js'
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 update = options.update ?? env.SEED_UPDATE === '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 ?? {})
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 log = options.log ?? defaultLog
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. */
export function truncate(text: string, max: number): string {
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(' ')
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 { createDailyPurge } from '../shared/purge.js'
import { clientIp, consumeRateLimit } from '../shared/rateLimit.js'
import { readCappedBody } from '../shared/readCappedBody.js'
import { STATS_SLUG } from './collection.js'
import { dayOf, deviceFromUa, isBot, referrerHost, sanitizePath, VISITOR_ID_PATTERN } from './parse.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.
* 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 {
return {
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 }
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 {
return done
}
+3
View File
@@ -67,6 +67,7 @@ import { searchSettingsFields } from './modules/seo/searchSettings.js'
import { migrateTitleSeparator } from './modules/seo/titleSeparator.js'
import { applyCollectionOverride } from './modules/shared/collectionOverride.js'
import { assertDevelopmentHosts } from './modules/shared/developmentHosts.js'
import { assertPluginSwitches } from './modules/shared/switches.js'
import { buildStatsCollection, buildStatsEndpoint } from './modules/stats/index.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 => {
// Validate eagerly — fail fast before Payload boots
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> => {
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')
})
})
/**
* 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)')
})
})
+197
View File
@@ -0,0 +1,197 @@
/**
* A write-only secret cannot be read back through a query (review B-R1 of the IAWL ideas, item 22).
*
* Every read masks the value, but a `where` (or a `sort`) on the field answers by the stored value:
* `where[version.smtpPassword][like]=Zq` gave totalDocs 2 against 0 for a wrong prefix, so an admin (or a stolen
* admin session) read the password back one character at a time. The field now refuses to be named in a query —
* REST and GraphQL, `like` / `equals` / `exists` / `sort`, on the global, its versions and a collection with
* `writeOnlySecret` (with and without versions) — while the panel keeps showing it (masked) and saving it.
* Real HTTP; SQLite by default, Postgres / MongoDB with IPAL_TEST_POSTGRES_URI / IPAL_TEST_MONGO_URI.
*/
import type { Access, Payload } from 'payload'
import { lexicalEditor } from '@payloadcms/richtext-lexical'
import os from 'os'
import path from 'path'
import { docAccessOperation, docAccessOperationGlobal, getPayload } from 'payload'
import { afterAll, beforeAll, describe, expect, test, vi } from 'vitest'
import { userMeetsRole } from '../src/modules/access/predicates.js'
import { SECRET_MASK, writeOnlySecret } 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 = 'Correct-horse-battery-9'
const SECRET = 'Zq-SMTP-SECRET-777'
const TOKEN = 'Zq-API-TOKEN-555'
let server: TestServer
let payload: Payload
let auth: Record<string, string>
const admin: Access = ({ req }) => userMeetsRole(req, 'admin')
const vault = (slug: string, versions: boolean) => ({
slug,
access: { create: admin, read: admin, readVersions: admin, update: admin },
fields: [{ name: 'label', type: 'text' as const }, writeOnlySecret({ name: 'apiToken', type: 'text' as const })],
...(versions ? { versions: { maxPerDoc: 5 } } : {}),
})
const get = async (pathname: string) => {
const res = await fetch(`${server.url}/api${pathname}`, { headers: auth })
return { body: await res.text(), status: res.status }
}
const gql = async (query: string) => {
const res = await fetch(`${server.url}/api/graphql`, { body: JSON.stringify({ query }), headers: { ...auth, 'content-type': 'application/json' }, method: 'POST' })
return (await res.json()) as { data?: null | Record<string, unknown>; errors?: { message: string }[] }
}
/** A field's read permission, wherever it sits in the permission tree (`true` = everything allowed). */
const readOf = (fields: unknown, name: string): unknown => {
if (fields === true) {return true}
if (!fields || typeof fields !== 'object') {return undefined}
const own = (fields as Record<string, unknown>)[name]
if (own !== undefined) {return own === true ? true : (own as { read?: unknown }).read}
for (const value of Object.values(fields as Record<string, unknown>)) {
const inner = value && typeof value === 'object' ? readOf((value as { fields?: unknown }).fields, name) : undefined
if (inner !== undefined) {return inner}
}
return undefined
}
/** What a query lets an admin learn: the number of matches, or nothing (refused). */
const total = (body: string) => body.match(/"totalDocs":(\d+)/)?.[1]
beforeAll(async () => {
const config = buildTestConfig({
admin: { user: 'users' },
collections: [vault('vaults', true), vault('keys', false), { slug: 'media', fields: [], upload: { staticDir: path.join(os.tmpdir(), 'iapl-secret-queries') } }],
db: testDatabase('secret_queries'),
editor: lexicalEditor(),
plugins: [
iapl({
access: { authCollection: 'users' },
globalOverrides: { 'site-integrations': { versions: { max: 5 } } as never },
i18n: { defaultLocale: 'pl', locales: [{ code: 'pl', label: 'Polski' }, { code: 'en', label: 'English' }] },
mail: { relay: false },
twoFactor: false,
}),
],
secret: 'secret-queries-0123456789-0123456789',
telemetry: false,
})
payload = await getPayload({ config })
server = await startPayloadServer(config)
await payload.create({ collection: 'users' as never, data: { email: '[email protected]', password: PASSWORD, roles: ['admin'] } as never })
await payload.updateGlobal({ slug: 'site-integrations' as never, data: { smtpHost: 'smtp.example.com', smtpPassword: SECRET, smtpUser: 'u' } as never })
await payload.updateGlobal({ slug: 'site-integrations' as never, data: { smtpHost: 'smtp2.example.com' } as never })
for (const slug of ['vaults', 'keys']) {
const doc = await payload.create({ collection: slug as never, data: { apiToken: TOKEN, label: 'one' } as never })
await payload.update({ id: doc.id, collection: slug as never, data: { label: 'two' } as never })
}
const login = (await (await fetch(`${server.url}/api/users/login`, { body: JSON.stringify({ email: '[email protected]', password: PASSWORD }), headers: { 'content-type': 'application/json' }, method: 'POST' })).json()) as { token: string }
auth = { authorization: `JWT ${login.token}` }
}, 120_000)
afterAll(async () => {
await server?.close()
await payload?.destroy?.()
})
describe('reads stay masked (unchanged)', () => {
test.each([
'/globals/site-integrations',
'/globals/site-integrations?locale=all&depth=3',
'/globals/site-integrations?select[smtpPassword]=true',
'/globals/site-integrations/versions?limit=5',
'/vaults?limit=5',
'/vaults/versions?limit=5',
'/keys?limit=5',
])('%s answers the mask, never the value', async (pathname) => {
const { body, status } = await get(pathname)
expect(status).toBe(200)
expect(body).not.toContain(SECRET)
expect(body).not.toContain(TOKEN)
expect(body).toContain(SECRET_MASK)
})
test('GraphQL reads answer the mask', async () => {
const res = await gql('{ SiteIntegration { smtpPassword } versionsSiteIntegration { docs { version { smtpPassword } } } Vaults { docs { apiToken } } }')
expect(res.errors).toBeUndefined()
const text = JSON.stringify(res.data)
expect(text).toContain(SECRET_MASK)
expect(text).not.toContain(SECRET)
expect(text).not.toContain(TOKEN)
})
})
describe('a query cannot name a write-only field (REST)', () => {
const guesses = (field: string, right: string) => [
`where[${field}][like]=${right.slice(0, 2)}`,
`where[${field}][like]=NOPE`,
`where[${field}][equals]=${right}`,
`where[${field}][exists]=true`,
`where[or][0][${field}][like]=${right.slice(0, 2)}`,
`sort=${field}`,
`sort=-${field}`,
]
test.each([
...guesses('version.smtpPassword', SECRET).map((q) => ['/globals/site-integrations/versions', q]),
...guesses('apiToken', TOKEN).map((q) => ['/vaults', q]),
...guesses('version.apiToken', TOKEN).map((q) => ['/vaults/versions', q]),
...guesses('apiToken', TOKEN).map((q) => ['/keys', q]),
])('%s?%s is refused, with no count', async (pathname, query) => {
const { body, status } = await get(`${pathname}?${query}`)
expect(status).toBeGreaterThanOrEqual(400)
expect(total(body)).toBeUndefined()
expect(body).not.toContain(SECRET)
expect(body).not.toContain(TOKEN)
})
test('the same queries on an ordinary field still work', async () => {
expect(total((await get('/globals/site-integrations/versions?where[version.smtpHost][like]=smtp2')).body)).toBe('1')
expect(total((await get('/vaults?where[label][equals]=two')).body)).toBe('1')
expect((await get('/keys?sort=-label')).status).toBe(200)
})
test('a count by the secret is refused too', async () => {
const { body, status } = await get('/vaults/count?where[apiToken][like]=Zq')
expect(status).toBeGreaterThanOrEqual(400)
expect(body).not.toMatch(/"totalDocs":\d/)
})
})
describe('a query cannot name a write-only field (GraphQL)', () => {
test.each([
'{ versionsSiteIntegration(where: { version__smtpPassword: { like: "Zq" } }) { totalDocs } }',
'{ versionsSiteIntegration(where: { version__smtpPassword: { equals: "Zq-SMTP-SECRET-777" } }) { totalDocs } }',
'{ Vaults(where: { apiToken: { like: "Zq" } }) { totalDocs } }',
'{ Keys(where: { apiToken: { exists: true } }) { totalDocs } }',
'{ versionsVaults(where: { version__apiToken: { like: "Zq" } }) { totalDocs } }',
])('%s gives no count', async (query) => {
const res = await gql(query)
expect(res.errors?.length).toBeGreaterThan(0)
expect(JSON.stringify(res.data ?? {})).not.toMatch(/"totalDocs":\d/)
})
})
describe('the panel keeps the field', () => {
test('the edit view of the global may read and change the secret field', async () => {
const req = { payload, user: { ...(await payload.find({ collection: 'users' as never, limit: 1 })).docs[0], collection: 'users' } } as never
const perms = await docAccessOperationGlobal({ data: {}, globalConfig: payload.globals.config.find((g) => g.slug === 'site-integrations')!, req })
expect(readOf(perms.fields, 'smtpPassword')).toBe(true)
})
test('the create view of a collection shows the secret field (the panel passes { _status: "draft" })', async () => {
const req = { payload, user: { ...(await payload.find({ collection: 'users' as never, limit: 1 })).docs[0], collection: 'users' } } as never
const perms = await docAccessOperation({ collection: payload.collections['keys' as never], data: { _status: 'draft' }, req })
expect(readOf(perms.fields, 'apiToken')).toBe(true)
})
test('an admin still saves a new secret and the stored value is the new one', async () => {
const res = await fetch(`${server.url}/api/globals/site-integrations`, { body: JSON.stringify({ smtpPassword: 'Zq-NEW-1' }), headers: { ...auth, 'content-type': 'application/json' }, method: 'POST' })
expect(res.status).toBe(200)
expect(((await payload.findGlobal({ slug: 'site-integrations' as never })) as { smtpPassword?: string }).smtpPassword).toBe('Zq-NEW-1')
})
})