From ecf03c8dc0ed96a2e645aeeef374b1b1311ceaa7 Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?Rados=C5=82aw=20Smoli=C5=84ski?= Date: Thu, 26 Nov 2026 20:25:26 +0100 Subject: [PATCH] IAWL ideas, group B: sizes before work, one link rule, no stand-in locale, strict switches - Request bodies from strangers are read only up to a cap, declared length or not: mail-service confirm, CSP reports, page views, MCP (maxBytes, 413). readCappedBody moves to shared/ (the consent log keeps exporting it). - searchContent / createSearchRoute / MCP search: queryLimit (default 200 characters, 10 words) before the database; an unknown ?locale is the default locale throughout. - Rich text: autolinks and links marked internal pass safeHref too; lexicalToMarkdown drops unsafe link targets. - truncate() never returns more than its limit (summary / meta autofill after validation). - resolveRoute answers null for a locale the site does not have (xx, all, *): no default-locale page under another code (page route past the proxy, /md/xx, MCP). - A 404 page that is a draft is not shown (resolveNotFoundPage, getNotFoundPage). - readPublished() access rule (exported); Site integrations readVersions: admin. - Plugin switches, buildCsp, buildSecurityHeaders and the seed guard refuse nonsense values at start; an unknown role name is met by nobody, requireRole throws on one. - Docs, AGENT.md, iapl-collection and iapl-audit skills. Co-Authored-By: Claude Opus 5.5 --- docs/access.md | 13 +- docs/agent/AGENT.md | 9 +- docs/agent/skills/iapl-audit/SKILL.md | 5 + docs/agent/skills/iapl-collection/SKILL.md | 3 + docs/content.md | 14 +- docs/mcp.md | 1 + docs/pages.md | 1 + docs/richtext.md | 6 +- docs/security.md | 39 +++- src/globals/SiteIntegrations/index.ts | 2 + src/index.ts | 4 + src/modules/access/access.ts | 37 +++- src/modules/access/index.ts | 1 + src/modules/access/predicates.ts | 8 +- src/modules/consent/consentLog.ts | 33 +-- src/modules/content/createSearchRoute.ts | 10 +- src/modules/content/index.ts | 4 +- src/modules/content/resolveNotFoundPage.ts | 5 +- src/modules/content/resolveRoute.ts | 13 ++ src/modules/content/searchContent.ts | 24 ++- src/modules/email/relay/confirm.ts | 13 +- src/modules/frontend/createContentHelpers.ts | 4 +- src/modules/mcp/createMcpRoute.ts | 9 +- src/modules/richtext/lexicalToMarkdown.ts | 6 +- src/modules/richtext/sanitizeLinks.ts | 4 +- src/modules/security/buildCsp.ts | 23 +++ src/modules/security/buildSecurityHeaders.ts | 13 ++ src/modules/security/createCspReportRoute.ts | 11 +- src/modules/seed/seeder.ts | 4 + src/modules/seo/plainText.ts | 3 +- src/modules/shared/readCappedBody.ts | 32 +++ src/modules/shared/switches.ts | 117 +++++++++++ src/modules/stats/endpoint.ts | 9 +- src/plugin.ts | 3 + test/iawlIdeasB.test.ts | 199 +++++++++++++++++++ test/iawlIdeasBContent.test.ts | 99 +++++++++ test/iawlIdeasBHttp.test.ts | 170 ++++++++++++++++ test/richTextLinks.test.ts | 32 +++ 38 files changed, 914 insertions(+), 69 deletions(-) create mode 100644 src/modules/shared/readCappedBody.ts create mode 100644 src/modules/shared/switches.ts create mode 100644 test/iawlIdeasB.test.ts create mode 100644 test/iawlIdeasBContent.test.ts create mode 100644 test/iawlIdeasBHttp.test.ts diff --git a/docs/access.md b/docs/access.md index 4f4f6ed..17a9752 100644 --- a/docs/access.md +++ b/docs/access.md @@ -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 diff --git a/docs/agent/AGENT.md b/docs/agent/AGENT.md index 22450ce..19c1690 100644 --- a/docs/agent/AGENT.md +++ b/docs/agent/AGENT.md @@ -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//?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 /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` | diff --git a/docs/agent/skills/iapl-audit/SKILL.md b/docs/agent/skills/iapl-audit/SKILL.md index f4eef8c..8616853 100644 --- a/docs/agent/skills/iapl-audit/SKILL.md +++ b/docs/agent/skills/iapl-audit/SKILL.md @@ -69,4 +69,9 @@ names, env, admin, AGENTS.md, skills, seeds and — with `--url` / `--deep` — rolled out). Report-only for more than a few weeks with clean reports → WARNING (switch to `mode: 'enforce'`). 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/?draft=true&limit=100" | grep -c '"_status":"draft"'` → `0`, else ERROR: give it + `access: { read: readPublished(), readVersions: readPublished() }` (access.md). `curl -sI "$U/md/xx"` → `404` + (no stand-in locale); a 404 page assigned in System pages must be published. + Do not say "done" until the full audit (without `--quick`) has no errors. diff --git a/docs/agent/skills/iapl-collection/SKILL.md b/docs/agent/skills/iapl-collection/SKILL.md index 84e5400..98a5b87 100644 --- a/docs/agent/skills/iapl-collection/SKILL.md +++ b/docs/agent/skills/iapl-collection/SKILL.md @@ -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 (`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 /api//?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 diff --git a/docs/content.md b/docs/content.md index fd9665a..f1a0592 100644 --- a/docs/content.md +++ b/docs/content.md @@ -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 diff --git a/docs/mcp.md b/docs/mcp.md index f7b3614..51b08fa 100644 --- a/docs/mcp.md +++ b/docs/mcp.md @@ -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`, diff --git a/docs/pages.md b/docs/pages.md index ab10936..e4fb324 100644 --- a/docs/pages.md +++ b/docs/pages.md @@ -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 diff --git a/docs/richtext.md b/docs/richtext.md index efe42f9..83b3cd7 100644 --- a/docs/richtext.md +++ b/docs/richtext.md @@ -56,8 +56,10 @@ Spread `defaultConverters` — you override only the nodes you want. The rest **Links are filtered as in `` (`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): ``. +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): ``. ## Table of contents and heading anchors (1.11.1) diff --git a/docs/security.md b/docs/security.md index 05e6a40..0fc3a88 100644 --- a/docs/security.md +++ b/docs/security.md @@ -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//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. @@ -1020,7 +1052,10 @@ later option, not part of this release. **Versions.** The global has no versions by default. A project that turns them on (`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. diff --git a/src/globals/SiteIntegrations/index.ts b/src/globals/SiteIntegrations/index.ts index 97a814e..62dea7f 100644 --- a/src/globals/SiteIntegrations/index.ts +++ b/src/globals/SiteIntegrations/index.ts @@ -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: { diff --git a/src/index.ts b/src/index.ts index cfdf136..0fca720 100644 --- a/src/index.ts +++ b/src/index.ts @@ -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' diff --git a/src/modules/access/access.ts b/src/modules/access/access.ts index a29dfda..b8af21f 100644 --- a/src/modules/access/access.ts +++ b/src/modules/access/access.ts @@ -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(', ')}.`) + } +} diff --git a/src/modules/access/index.ts b/src/modules/access/index.ts index 1ac0d06..1bac610 100644 --- a/src/modules/access/index.ts +++ b/src/modules/access/index.ts @@ -6,6 +6,7 @@ export { adminOrSelf, adminOrSelfIn, authenticated, + readPublished, requireRole, requireRoleField, } from './access.js' diff --git a/src/modules/access/predicates.ts b/src/modules/access/predicates.ts index 0ad21da..05433d0 100644 --- a/src/modules/access/predicates.ts +++ b/src/modules/access/predicates.ts @@ -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} diff --git a/src/modules/consent/consentLog.ts b/src/modules/consent/consentLog.ts index 0ce5e21..940c5db 100644 --- a/src/modules/consent/consentLog.ts +++ b/src/modules/consent/consentLog.ts @@ -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() /** 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 { - 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 { + return readCapped(request, max) } /** Cookie Settings → Policy version per Payload instance, cached for a minute. */ diff --git a/src/modules/content/createSearchRoute.ts b/src/modules/content/createSearchRoute.ts index 4f9e174..4e94136 100644 --- a/src/modules/content/createSearchRoute.ts +++ b/src/modules/content/createSearchRoute.ts @@ -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 /** 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 { - 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, }) diff --git a/src/modules/content/index.ts b/src/modules/content/index.ts index 387725d..5e43b63 100644 --- a/src/modules/content/index.ts +++ b/src/modules/content/index.ts @@ -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' diff --git a/src/modules/content/resolveNotFoundPage.ts b/src/modules/content/resolveNotFoundPage.ts index 7ef0f84..3f3c8c3 100644 --- a/src/modules/content/resolveNotFoundPage.ts +++ b/src/modules/content/resolveNotFoundPage.ts @@ -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) ?? 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) : null } catch (error) { console.warn('[iapl] resolveNotFoundPage: falling back to built-in 404 view:', error) return null diff --git a/src/modules/content/resolveRoute.ts b/src/modules/content/resolveRoute.ts index 46efc0b..8af1746 100644 --- a/src/modules/content/resolveRoute.ts +++ b/src/modules/content/resolveRoute.ts @@ -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 { + // 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({ diff --git a/src/modules/content/searchContent.ts b/src/modules/content/searchContent.ts index 3ca6eb0..33385eb 100644 --- a/src/modules/content/searchContent.ts +++ b/src/modules/content/searchContent.ts @@ -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 { - const q = query.trim() + const q = limitQuery(query, queryLimit) if (!q) {return []} const loc = locale && isValidLocale(locale, config) ? locale : getDefaultLocale(config) diff --git a/src/modules/email/relay/confirm.ts b/src/modules/email/relay/confirm.ts index cad9f8a..3bd272d 100644 --- a/src/modules/email/relay/confirm.ts +++ b/src/modules/email/relay/confirm.ts @@ -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 { - 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 }).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 } diff --git a/src/modules/frontend/createContentHelpers.ts b/src/modules/frontend/createContentHelpers.ts index 8a6d725..b64aa71 100644 --- a/src/modules/frontend/createContentHelpers.ts +++ b/src/modules/frontend/createContentHelpers.ts @@ -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) ?? 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) : null } catch { return null // DB unreachable (container build) or page deleted — fallback view } diff --git a/src/modules/mcp/createMcpRoute.ts b/src/modules/mcp/createMcpRoute.ts index db67797..c5c12a3 100644 --- a/src/modules/mcp/createMcpRoute.ts +++ b/src/modules/mcp/createMcpRoute.ts @@ -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 { 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 }) } diff --git a/src/modules/richtext/lexicalToMarkdown.ts b/src/modules/richtext/lexicalToMarkdown.ts index 0fa5031..502a4c6 100644 --- a/src/modules/richtext/lexicalToMarkdown.ts +++ b/src/modules/richtext/lexicalToMarkdown.ts @@ -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 - const url = + const raw = typeof fields.url === 'string' ? fields.url : typeof (fields.doc as Record)?.value === 'string' ? ((fields.doc as Record).value as string) : '' + // the same rule as and : 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) { diff --git a/src/modules/richtext/sanitizeLinks.ts b/src/modules/richtext/sanitizeLinks.ts index 2efef1b..5ec1529 100644 --- a/src/modules/richtext/sanitizeLinks.ts +++ b/src/modules/richtext/sanitizeLinks.ts @@ -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: '#' } }} } diff --git a/src/modules/security/buildCsp.ts b/src/modules/security/buildCsp.ts index 3f8b81d..2f7ed03 100644 --- a/src/modules/security/buildCsp.ts +++ b/src/modules/security/buildCsp.ts @@ -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)) { + 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, diff --git a/src/modules/security/buildSecurityHeaders.ts b/src/modules/security/buildSecurityHeaders.ts index 6d4a92a..90fcd17 100644 --- a/src/modules/security/buildSecurityHeaders.ts +++ b/src/modules/security/buildSecurityHeaders.ts @@ -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', diff --git a/src/modules/security/createCspReportRoute.ts b/src/modules/security/createCspReportRoute.ts index 6c99701..64d83d8 100644 --- a/src/modules/security/createCspReportRoute.ts +++ b/src/modules/security/createCspReportRoute.ts @@ -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 { diff --git a/src/modules/seed/seeder.ts b/src/modules/seed/seeder.ts index f71c7a7..c887c06 100644 --- a/src/modules/seed/seeder.ts +++ b/src/modules/seed/seeder.ts @@ -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)[name])}} const label = options.label ?? '[seed]' const log = options.log ?? defaultLog const hashField = options.editCheck?.hashField ?? defaultHashField() diff --git a/src/modules/seo/plainText.ts b/src/modules/seo/plainText.ts index 12f1a77..6d68c1d 100644 --- a/src/modules/seo/plainText.ts +++ b/src/modules/seo/plainText.ts @@ -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()}…` } diff --git a/src/modules/shared/readCappedBody.ts b/src/modules/shared/readCappedBody.ts new file mode 100644 index 0000000..01a85ff --- /dev/null +++ b/src/modules/shared/readCappedBody.ts @@ -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 { + 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) +} diff --git a/src/modules/shared/switches.ts b/src/modules/shared/switches.ts new file mode 100644 index 0000000..3d59555 --- /dev/null +++ b/src/modules/shared/switches.ts @@ -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 | undefined +const bag = (value: unknown): Bag => (value && typeof value === 'object' && !Array.isArray(value) ? (value as Record) : 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): 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 }) + } + } +} diff --git a/src/modules/stats/endpoint.ts b/src/modules/stats/endpoint.ts index f5b7e75..3b8cf21 100644 --- a/src/modules/stats/endpoint.ts +++ b/src/modules/stats/endpoint.ts @@ -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 } diff --git a/src/plugin.ts b/src/plugin.ts index 8e44c9b..999deca 100644 --- a/src/plugin.ts +++ b/src/plugin.ts @@ -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) return async (incomingConfig: Config): Promise => { const config = await transform(incomingConfig) diff --git a/test/iawlIdeasB.test.ts b/test/iawlIdeasB.test.ts new file mode 100644 index 0000000..9777faf --- /dev/null +++ b/test/iawlIdeasB.test.ts @@ -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({ + 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) => { + 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) +}) diff --git a/test/iawlIdeasBContent.test.ts b/test/iawlIdeasBContent.test.ts new file mode 100644 index 0000000..c8b2e72 --- /dev/null +++ b/test/iawlIdeasBContent.test.ts @@ -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') + }) +}) diff --git a/test/iawlIdeasBHttp.test.ts b/test/iawlIdeasBHttp.test.ts new file mode 100644 index 0000000..7e7f8d4 --- /dev/null +++ b/test/iawlIdeasBHttp.test.ts @@ -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; 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 } + 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') + } + }) +}) diff --git a/test/richTextLinks.test.ts b/test/richTextLinks.test.ts index 8d0b77e..226cc44 100644 --- a/test/richTextLinks.test.ts +++ b/test/richTextLinks.test.ts @@ -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 and the plain link. + */ +describe('a second way to write the same link', () => { + const bad = 'data:text/html,' + + 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)') + }) +})