diff --git a/docs/CHANGELOG.md b/docs/CHANGELOG.md index aeb4d64..6c51a57 100644 --- a/docs/CHANGELOG.md +++ b/docs/CHANGELOG.md @@ -94,6 +94,78 @@ once there are more than 20. > gate template. **Recommended for projects:** `index: true` on `slugHistory.slug`; the heading font with > `preload: false` (the starter's default now); a placeholder of the 404 content's height. +### Security audit 2026-12: fixes and suites (docs/security.md) + +> **What changes for an existing site** (no migration, no import-map change; each with its opt-out): +> +> 1. **Public lists are capped at 100** (`listLimit`, finding F4). A REST / GraphQL list (`find`, versions, distinct +> values) asked by a caller that is not staff gets at most 100 documents; `pagination=false` and `limit=0` become one +> page of 100. Before, one anonymous `GET /api/posts?limit=100000` read a whole collection with its relations. +> Staff accounts, the panel and the Local API (the frontend, seeds) are not capped. **A client-side script that reads +> more than 100 documents anonymously now gets the first 100 and `hasNextPage: true`** — page through, or adapt: +> `listLimit: { max: 500 }`, `{ exclude: ['products'] }`, `{ staff: true }`; off: `listLimit: false`. +> 2. **An operator name in `?sort=` answers 400** (`refuseOperatorSort`, F5): `$where`, `-$natural`, `title.$ne` — +> for everyone, staff too — instead of reaching MongoDB and ending in a 500 with a stack trace in the log. Logged as +> one `info` line (`RefusedSortError`; `loggingLevels: { RefusedSortError: false }` hides it). Off: +> `refuseOperatorSort: false`. Reported to Payload upstream. +> 3. **Payload's document locks are for staff only** (`lockedDocuments`). `payload-locked-documents` ("who edits +> what") ran on Payload's default, any signed-in account — a visitor account of a login collection for customers +> could read who edits which document and write or delete locks. Now staff accounts with the second factor; the +> panel works as before. Off: `lockedDocuments: false`; your own rule: `lockedDocuments: { access: { read } }`. +> 4. **The Markdown negotiated at a page URL is never cached as the page** (F3). `createProxy({ markdown: true })` +> marks the rewrite, the Markdown route answers `cache-control: private, no-store` with `Vary: Accept`, and the +> pages under the proxy matcher get `Vary: Accept`. Before, a CDN that caches HTML (Cloudflare "Cache Everything", +> Varnish) could store the Markdown copy after one anonymous `Accept: text/markdown` request and serve it to every +> visitor of that page. `/md/…` keeps its public caching. A proxy of your own that rewrites to `/md/…` copies the +> headers (`MARKDOWN_NEGOTIATED_HEADER`, `NEGOTIATED_CACHE_CONTROL`, `appendVary`; content.md). Off: +> `markdown: { negotiate: false }` (Markdown only at `/md/…`). +> 5. **CSP report log lines change shape** (F1): `blocked=` is the origin (`https://cdn.example`, or `inline` / +> `eval`), `page=` the path without its query, `src=` origin and path; control characters are removed and each +> value is cut at 128 characters, so a posted report can no longer write a forged line into the Coolify log. One +> request handles at most 10 violations (was 50), one client at most 60 requests a minute (the answer stays `204`). +> **A log parser that read full URLs must adapt.** Your own `onReport` still gets the raw values. Adapt: +> `createCspReportRoute({ maxReports: 50, rateLimit: false | { max, windowMs } })`; the line: `cspLogLine`. +> 6. **Access callbacks allow only on a literal `true`** (`cookieScanner.access`, the doctor's `access`). A callback +> that returns `req.user` — `cookieScanner: { access: ({ req }) => req.user }` — returned an account object, which +> let the request in; **now it is refused (`403`)**, and so are `1`, `'yes'`, `{}` and a Promise that was not +> awaited. The server log names the option once: `[iapl] cookieScanner.access returned an object, not true or +> false, so the request was refused …`. Fix: `({ req }) => Boolean(req.user)` (or a role check such as +> `isAdmin(req.user, req.payload)`). The old reading back: `iapl({ strictAccessAnswers: false })`. New exports: +> `strictAccessAnswers(req)`, type `AccessAnswerOptions`; `accessAllowed(option, answer, { strict })`. +> 7. **New doctor findings the first time** (the suites below): `iapl-doctor --only security` reads the project's own +> code and configs. Judge each; a correct place gets `// iapl-security-ok: `. +> +> **Recommended for projects:** a text field of your own whose value goes into `href` (social profiles, a website) +> becomes `buildUrlField()` and its render goes through `safeHref()` (F2) — no schema change, it stays a text column. +> The reference site and every new site from `iapl create` do it for Company → Profiles (also in the `sameAs` of the +> JSON-LD). Not exploitable as the reference site wrote it (`target="_blank"`), but a copy without it would run an +> editor's `javascript:` link as the admin who clicks it. +> +> **New checks a project can run on its own site:** +> +> - **Static security rules** in the doctor: `iapl-doctor --only security` now also reads the project's own code +> (`code-patterns`: unescaped HTML / JSON-LD, `overrideAccess: true` and a Local API `user` without +> `overrideAccess: false` where a request reaches, a `where` from the request, `eval`, `NEXT_PUBLIC_` secrets, +> redirects and fetches to an address from the request) and its configs (`config-dangerous`). +> - **Attack probes**: `iapl-doctor --url https:// --only live-probes` (requests that change nothing) and the +> Playwright template `iapl-audit/resources/attack-probes.spec.template.ts`. Exported: `ATTACK_PROBES`, +> `runAttackProbes`, `createProbeContext`, `scanCode`, `scanConfigs` (`@intecion/ipal-kit/doctor`). A site on the +> 1.18.0 defaults passes every probe; `markdown-vary`, `unbounded-list` or `sort-operator` mean a fix above is off. +> - **For the plugin's own release:** `pnpm security:gate` (in `prepublishOnly`): `pnpm audit --prod` with no high / +> critical, the static-rule gate and the per-class tests; `--zap ` adds an optional OWASP ZAP baseline scan. +> +> **New exports:** `buildQueryGuardHook`, `applyQueryGuard`, `capListLimit`, `isOperatorSort`, `isStaffRequest`, +> `RefusedSortError`, `DEFAULT_LIST_LIMIT`, `isQueryGuardHook`, `QUERY_GUARD_MARK`, `applyLockedDocumentsAccess`, +> `staffOnlyLocks`, `LOCKED_DOCUMENTS_SLUG` (types `ListLimitOptions`, `LockedDocumentsAccess`); `buildUrlField`, +> `isAllowedUrl` (types `BuildUrlFieldOptions`, `UrlScheme`); `cspLogLine`, `CSP_LOG_VALUE_MAX`; +> `MARKDOWN_NEGOTIATED_HEADER`, `NEGOTIATED_CACHE_CONTROL`, `appendVary`. New options: `listLimit`, +> `refuseOperatorSort`, `lockedDocuments`; `createProxy({ markdown: { prefix, negotiate } })`; +> `createCspReportRoute({ maxReports, rateLimit })`; `markdownResponse(md, { negotiated })`. +> +> **Watch (no change in this release):** React's RSC advisory GHSA-xqc2-xf4c-x3h3 is fixed in React 19.3.1; whether +> Next 16.4.6 carries the fix is not confirmed by any Next release note or advisory. The minimum safe Next version in +> AGENT.md §4 is raised when Next publishes one that names it. + ## 1.17.2 — version history with readPublished, sign-in and panel actions, staff-only REST submissions and jobs, the cookie button > **Read before upgrading.** No schema change, no migration on any database, no import-map change. What changes for diff --git a/docs/agent/AGENT.md b/docs/agent/AGENT.md index 203589b..c5358a4 100644 --- a/docs/agent/AGENT.md +++ b/docs/agent/AGENT.md @@ -240,7 +240,7 @@ site), **P** = a test in the panel. Full code: PROGRAMISTA.md §2. | 3a | **Search Console / Bing** | recommended: **domain verification via DNS** (TXT record, deployment.md §6) — the plugin does nothing, the verification fields stay empty; only for URL-prefix verification: code in **Site settings → Search engines** (Google, Bing, Yandex), `generatePageMetadata` adds the `` itself; sitemap `https:///sitemap.xml` submitted in GSC and Bing | panel (optional), `verificationFrom` | P | | 4 | **SEO** — structured data | layout: `` gives `WebSite` + `Organization` (`sameAs`) from Site settings; local business → `createContentHelpers({ siteJsonLd })` with `buildLocalBusinessJsonLd` (`type`, hours → `formatOpeningHours`); navigation: ``; page: `createPageRoute` adds `getPageJsonLd` (WebPage/BlogPosting, breadcrumbs, FAQ — `pageJsonLd: { faq }`) | `getSiteShell`, `SiteProviders`, `build*JsonLd`, `getPageJsonLd` | A, S | | 5 | **GEO** — llms | `src/app/llms.txt/route.ts` (`llmsRoute`) and `src/app/llms-full.txt/route.ts` (`llmsFullRoute`) from `lib/content`; the `buildSummaryField()` field in Pages, `summaryField: 'aiSummary'` in `createContentHelpers` | `llmsRoute`, `llmsFullRoute`, `buildSummaryField` | A, S | -| 6 | **GEO** — Markdown | `src/app/md/[locale]/[[...slug]]/route.ts` (single-language: `src/app/md/[[...slug]]/route.ts`) = `export { markdownRoute as GET } from '@/lib/content'`; `createContentHelpers({ markdownAlternate: true })` (link in ``); `createProxy(…, { NextResponse, markdown: true })` (without it `/md/…` gets redirected to a language) | `markdownRoute`, `markdownAlternate`, `createProxy({ markdown })` | A, S | +| 6 | **GEO** — Markdown | `src/app/md/[locale]/[[...slug]]/route.ts` (single-language: `src/app/md/[[...slug]]/route.ts`) = `export { markdownRoute as GET } from '@/lib/content'`; `createContentHelpers({ markdownAlternate: true })` (link in ``); `createProxy(…, { NextResponse, markdown: true })` (without it `/md/…` gets redirected to a language; the `Accept: text/markdown` answer at a page URL is `private, no-store` + `Vary: Accept` since 1.18.0 — check: `curl -sD- -o/dev/null -H 'Accept: text/markdown' localhost:3000/pl \| grep -i cache-control` → `private, no-store`) | `markdownRoute`, `markdownAlternate`, `createProxy({ markdown })`, `markdown: { negotiate: false }` | A, S | | 7 | **GEO** — MCP | `src/app/api/mcp/route.ts` = `export { mcpGET as GET, mcpPOST as POST } from '@/lib/content'` (public — AI browses the site: `get_site_info`, `list_pages`, `search_content`, `get_page`); name: `createContentHelpers({ mcp: { serverName } })` | `mcpGET`, `mcpPOST` | A, S | | 8 | **GEO** — AI bots + IndexNow | robots **lets in** AI bots (default `aiBots: 'allow'`; block only on a client decision); AI bot policy and per-bot exceptions — Site settings → Search engines → AI assistants (works only with `getRobots`); `iapl({ indexNow: true })` + `src/app/indexnow-key.txt/route.ts` (`indexNowKeyRoute`; publishing → Bing/ChatGPT Search within minutes; IndexNow sends nothing with `IAPL_NOINDEX=1`) | `buildRobots`, `getRobots`, `indexNowKeyRoute` | A, S | | 9 | **Media / R2 / speed** | `Media` with `focalPoint`, `normalizeFilenameHook`, `buildOptimizeUploadHook`, `buildMediaPlaceholderHook` + field; **always** `buildR2Storage(['media'], { s3Storage })` + `@payloadcms/storage-s3`; `R2_*` in `.env.example`; ``; `images: buildImagesConfig()` and `buildUploadSecurityHeaders()` in `next.config.ts`; the project's `` via `mediaImageProps`/`videoProps` (§6.11b) | `buildR2Storage`, `mediaImageProps`, `videoProps`, `buildImagesConfig` | A, S | @@ -562,6 +562,10 @@ No abbreviations (`HeroSection`, not `HeroSec`). Do not create `lib/pages.ts`, (`pnpm why sharp`). The plugin's peer range stays open (`next >=15`) — the minimum is yours to keep. **Check:** `pnpm ls next sharp` → next ≥ 16.4.5, sharp ≥ 0.35.5; `pnpm exec iapl-doctor` → no `next-min` finding; `pnpm dev` prints no security-upgrade warning. + **Watch (security audit 2026-12, O1):** React's RSC advisory GHSA-xqc2-xf4c-x3h3 (critical) is fixed in + `react-server-dom-*` 19.3.1; Next vendors its own React copy, and no Next release note or advisory says yet whether + 16.4.6 carries the fix. When Next publishes one that names it, move to the version it names and raise this + minimum; until then `deps-audit` does not flag `next` for it. 12. **No open production advisories.** Node.js 20 or later for the plugin itself (its `nodemailer` 10 requires it); **Payload 3.94 needs Node.js 22.23.5 or later** on the 22 line (`engines`: `">=22.23.5 <23"`, `.nvmrc` `22`), locally, in CI and in Coolify (Nixpacks takes the major from `engines` / `.nvmrc` and the patch from its own release: check @@ -638,7 +642,9 @@ for visitors. Then, all four: 4. Payload's default for a collection or global without `access` is "any logged-in account" — a customer too. Give every collection and global explicit `access` (writes: `adminOrEditor`, as the reference site's collections and globals do since 1.17.2). Verify with `iapl-doctor --url …` (deep): no `visitor-writes` finding. 2FA covers - the panel's collection only. + the panel's collection only. Payload's document locks (`payload-locked-documents`) are staff only since 1.18.0 + (`lockedDocuments`), and lists from outside are capped at 100 for non-staff (`listLimit`) — security.md + "Lists and sorting". 5. Never let a sign-up write a field that grants rights (`roles`, `isAdmin`, …): give such a field `access: { create: adminOnlyField, update: adminOnlyField }`. 6. Check: log in as such an account (`POST /api/customers/login`), then `GET /api/globals/site-integrations`, @@ -1129,7 +1135,9 @@ project → **plugin gap**, not a copy. | Legal links in the footer (href + page title) | `getSystemLinks(locale)` / `resolveSystemLinks` | links.md | | Highlighted item, button variant | `buildLinkField({ appearances: [...] })` — the project's names | links.md | | Language paths, switcher, hreflang | `getLocalizedSlugs`, `switchLocalePath`, `LanguageSwitcher`, `buildLocalizedPath` | i18n.md | -| Safe URL (no `javascript:`) | `safeHref` | links.md | +| Safe URL (no `javascript:`) | `safeHref`; a text field for an address rendered into `href`: `buildUrlField({ schemes })`, `isAllowedUrl`, types `BuildUrlFieldOptions`, `UrlScheme` (security.md "Addresses rendered into `href`") | links.md, security.md | +| Lists and sorting from outside | `listLimit`, `refuseOperatorSort`, `lockedDocuments` (options); `buildQueryGuardHook`, `applyQueryGuard`, `capListLimit`, `isOperatorSort`, `isStaffRequest`, `isQueryGuardHook`, `QUERY_GUARD_MARK`, `RefusedSortError`, `DEFAULT_LIST_LIMIT`, `applyLockedDocumentsAccess`, `staffOnlyLocks`, `LOCKED_DOCUMENTS_SLUG`; types `ListLimitOptions`, `LockedDocumentsAccess` | security.md | +| Markdown negotiation, cache-safe | `MARKDOWN_NEGOTIATED_HEADER`, `NEGOTIATED_CACHE_CONTROL`, `appendVary`, `markdownResponse(md, { negotiated })` | content.md | **Forms** | Need | Use | Doc | @@ -1166,7 +1174,7 @@ project → **plugin gap**, not a copy. | Enlarge an image (card, gallery, product, rich text) | `` + `` (`/client`), `RenderRichText lightbox`, `useLightbox`; labels: `iapl({ lightbox: true })` → Form messages → Image viewer | lightbox.md | | YouTube without cookies before a click | `` (`/client`) — always pass an uploaded poster (without it the thumbnail comes from Google before any choice; a development warning says so) | storage.md | | `next.config` | `buildImagesConfig`, `buildSecurityHeaders` (`csp`), `buildCsp`, `buildCspHeaders`, `buildAdminCsp` / `buildAdminCspHeaders`, `buildUploadSecurityHeaders`, `withSecurityConfig` (the OUTER wrapper: hides `X-Powered-By`, keeps Payload's `Accept-CH` / `Critical-CH` / `Vary` colour-scheme hints on the admin only; `adminClientHints: { route, sources } \| false`), `scopeColorSchemeClientHints`, `adminClientHintSources`, `COLOR_SCHEME_CLIENT_HINT` | storage.md, security.md | -| CSP reports, nonces | `createCspReportRoute` (`parseCspReports`, type `CspViolation`), `createProxy({ csp })` + `` (dynamic pages only), `createCspNonce`, `CSP_NONCE_HEADER`, `buildReportingEndpoints`, `cspHeaderKey`, `DEFAULT_CSP_REPORT_GROUP`; types `BuildAdminCspArgs`, `CspDirective`, `CspSources`, `CreateCspReportRouteArgs`, `WithSecurityConfigOptions` | security.md | +| CSP reports, nonces | `createCspReportRoute` (`parseCspReports`, `cspLogLine`, `CSP_LOG_VALUE_MAX`, type `CspViolation`), `createProxy({ csp })` + `` (dynamic pages only), `createCspNonce`, `CSP_NONCE_HEADER`, `buildReportingEndpoints`, `cspHeaderKey`, `DEFAULT_CSP_REPORT_GROUP`; types `BuildAdminCspArgs`, `CspDirective`, `CspSources`, `CreateCspReportRouteArgs`, `WithSecurityConfigOptions` | security.md | | Fluid typography and spacing | `fluid.css` / `fluid-wide.css` (`--ipal-*` variables); your own sizes: `fluidClamp`, `FLUID_SCALE`, `FLUID_RANGES` | design-tokens.md | | Brand colours, fonts, radii, motion, dark mode | `tokens.css` + `tailwind.css`, `src/design/tokens.ts` (`defineTokens`, types `TokensInput`, `ColorInput`, `ColorRole`), `pnpm exec iapl-tokens` (`--check`, `--report`, `--warn-only`); building blocks `tokensToCss`, `defaultTokensCss`, `contrastReport` (`ContrastRow`), `contrastRatio`, `parseColor`, `resolveColors`, `IAPL_TOKENS`, `iaplVar`, `IaplTokenName`, `IAPL_BREAKPOINTS`, `COLOR_DEFAULTS`, `STATIC_DEFAULTS`, `FLUID_TOKENS`, `INVERSE_SCOPE`, `LEGACY_DARK_ROLES`, `LIGHT_SELECTOR`, `DARK_SELECTOR`, `INVERSE_SELECTOR`, `RemValue`, `FluidRange` | design-tokens.md | | Accessibility widget CSS | `@intecion/ipal-kit/a11y.css` (works through the tokens) | accessibility.md | @@ -1236,7 +1244,7 @@ add missing hosts with flags / `extra`; (3) change `mode` to `'enforce'` in both | Consent version only goes up (1.17.2): a save through access control with a lower Cookies → *Consent version* is refused with a message (old consent would count again); the Local API with `overrideAccess` may still | `iapl({ cookieSettings: { allowLowerPolicyVersion: true } })` | `policyVersionNeverDown`, `buildCookieSettingsFields` (type `CookieSettingsFieldOptions`), `buildCookieSettings(options)`; verify: lower it in the panel → the error under the field | | Drafts as related documents are left out (1.18.0): a block, menu or System pages link pointing at a page never published no longer brings its title, slug or text into the helpers' answers (`null` alone, removed from a list, `value: null` in a polymorphic one) — pages, Site settings, archive entries, the 404 page, Markdown, MCP, llms-full; a preview keeps them | `createContentHelpers({ draftRelations: 'keep' })`; `draftRelations: 'keep'` on `resolveRoute` / `getArchiveEntries` / `resolveNotFoundPage` / `collectSiteIndex` / `buildLlmsTxt` | `withoutDraftRelations`, `applyDraftRelations`, type `DraftRelations`; content.md "Drafts as related documents"; verify: a menu link to an unpublished page is gone on the site | | Integration status written alone (1.18.0): `emailStatus` / `turnstileStatus` go through the database adapter on their own, so a visitor's form submit can no longer put back an admin's SMTP or Turnstile change saved at the same moment; the cookie list is checked again right before the scanner writes it (a row an editor saved in between stays) | — | `writeGlobalFields(payload, slug, data)` for your own bookkeeping fields (no hooks, no version); `addToCookieList` | -| Access callbacks (`cookieScanner.access`, the doctor's `access`): any truthy answer still allows in 1.18.0, but an answer that is not a boolean is reported once per option in the server log; **from 1.19.0 only `true` allows** | — | return a boolean (`({ req }) => Boolean(req.user)`); `accessAllowed(option, answer)`; security.md "Access callbacks" | +| Access callbacks (`cookieScanner.access`, the doctor's `access`): **only a literal `true` allows (1.18.0)** — a callback returning `req.user` (an object), `1`, a string or an un-awaited Promise refuses; an answer that is not a boolean is reported once per option in the server log with the fix. **Verify:** a callback returning `req.user` → `403` and one `[iapl] … returned an object` line | `strictAccessAnswers: false` (any truthy answer allows, as before 1.18.0) | return a boolean (`({ req }) => Boolean(req.user)`); `accessAllowed(option, answer, { strict })`, `strictAccessAnswers(req)`, type `AccessAnswerOptions`; security.md "Access callbacks" | | 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` | @@ -1248,6 +1256,11 @@ add missing hosts with flags / `extra`; (3) change `mode` to `'enforce'` in both | The second factor on every collection and global, whichever plugin added it, and on the plugin's endpoints; an unrecognised 2FA package = startup error | per entity: `custom.ipal.secondFactor: false` or `{ read: false }` (or the package's `custom.totp.disableAccessWrapper`); everywhere: `twoFactor.guard: false` (not recommended) | `requireSecondFactor` / `secondFactorPassed` in your own access functions and endpoints | | At most 5 **wrong** verify codes per account in 10 minutes (`POST /api/verify-totp` → `429`); a right code gives its place back (1.17.1), so correct logins are never refused; an attempt held out only by others still being checked gets `429` + `Retry-After: 2` ("try again in a moment"); the count is kept in memory and in the database (`payload.kv`), so a restart or a second instance does not reset it. **Verify:** log in correctly 7 times in a row → all in; 5 wrong codes → the next gets `429` with a long `Retry-After` | `twoFactor.verifyLimit: false` | `verifyLimit: { max, windowMinutes, store: 'memory' }`; own wiring: `buildVerifyLimit(...)` + `limit.settle(req, correct)` | | The plugin's panel actions (`POST` mail service connect / disconnect, test e-mail, cookie scan / approval / crawl) refuse a request a browser marks as coming from another origin (`403`, before anything is read; 1.17.2). The panel's buttons are not affected; set `serverURL` (doctor `csrf-empty` warns without it). **Verify:** `curl -X POST /api/ipal/test-email -H 'Origin: https://other.example' -H 'Content-Type: text/plain' -b -d '{}'` → `403` | `adminSameOrigin: false` | `adminSameOrigin: { origins: [...] }`; `requireOwnOrigin(endpoint, origins?)` for your own endpoints | +| Public lists capped (1.18.0, audit F4): a REST / GraphQL list from a caller that is not staff gets at most 100 documents; `pagination=false` / `limit=0` become one page of 100; staff and the Local API untouched. **Verify:** `curl -s '/api/pages?limit=100000' \| jq .limit` → `100` | `listLimit: false` | `listLimit: { max, staff, exclude }`; `buildQueryGuardHook` for a collection a plugin adds after iapl; `capListLimit` | +| Operator names in `sort` refused (1.18.0, audit F5): `?sort=$where`, `-$natural`, `a.$ne` → `400` for everyone (logged as one `info` line, `RefusedSortError`) instead of a database error. **Verify:** `curl -s -o /dev/null -w '%{http_code}' '/api/pages?sort=%24where'` → `400` | `refuseOperatorSort: false` | `loggingLevels: { RefusedSortError: false }`; `isOperatorSort` | +| Payload's document locks (`payload-locked-documents`) for staff accounts only, with the second factor (1.18.0); Payload's default was any signed-in account, a customer too. **Verify:** a visitor account gets `403` on `/api/payload-locked-documents`; the panel still shows who edits a document | `lockedDocuments: false` | `lockedDocuments: { access: { read, create, update, delete } }`; `staffOnlyLocks`, `applyLockedDocumentsAccess` | +| CSP report log lines normalised (1.18.0, audit F1): origin of the blocked resource, path of the page, no control characters, every value ≤ 128 characters; at most 10 violations per request, 60 requests per client a minute (answer stays `204`) | `rateLimit: false`; your own `onReport` (gets the raw values) | `createCspReportRoute({ maxReports, rateLimit: { max, windowMs }, onReport })`, `cspLogLine` | +| Markdown negotiated at a page URL is `private, no-store` + `Vary: Accept`; pages under the proxy matcher get `Vary: Accept` (1.18.0, audit F3); `/md/…` stays publicly cacheable | `markdown: { negotiate: false }` (Markdown only at `/md/…`) | `markdown: { prefix }`; `MARKDOWN_NEGOTIATED_HEADER`, `appendVary` for your own proxy | | 2FA first set-up confirmed by e-mail (1.18.0): the code only starts it; a link to the account's own address, opened in the same browser within 30 min, turns it on and ends the account's sessions; notice mails on every enrolment, change, removal / reset; without working mail the link goes to the server log and an admin confirms on the account page ("Confirm the waiting set-up", `POST /api/iapl/two-factor/confirm-pending`). **Verify:** security.md "Set-up confirmed by e-mail" → Verify; doctor `2fa-enrolment-mail` | `twoFactor.confirmByEmail: false` | `confirmByEmail: { linkMinutes, sameBrowser, adminConfirm, logLinkWhenMailFails, notices, maxMailsPerHour }`; `startEnrolment`, `buildEnrolmentEndpoints`, `buildTotpNoticeHooks`, `sendTwoFactorNotice`, `verifyTotpCode`, `readPendingEnrolment`, `pendingEnrolmentInfo`, `countPendingEnrolments`, `mailConfigured` | | 2FA verify and setup attempts only from the site's own origin: a request a browser marks as coming from elsewhere (`Origin`, `Sec-Fetch-Site`) gets `403` and is not counted. The admin's reset `POST /api/ipal/two-factor/reset` follows the same rule (1.17.1). **Verify:** `curl -X POST /api/ipal/two-factor/reset -H 'Origin: https://other.example' -H 'Content-Type: text/plain' -b -d '{"userId":1}'` → `403`; the panel's button still works. **Set `serverURL`**: behind a proxy that rewrites `Host` and sends no `X-Forwarded-Host` the site's own page is refused without it (logged once per origin: `[iapl] 2FA: a code from origin … was refused`) | `twoFactor.sameOrigin: false` | `sameOrigin: { origins: ['https://app.example.com'] }`; `requestFromOwnOrigin`, `reportRefusedOrigin` | | Stored secrets are write-only: `smtpPassword` and `turnstileSecretKey` come back as `'********'` over REST, GraphQL and in the panel; an empty save keeps the value, `'[[clear]]'` removes it; server code reads the real value with the Local API. A query cannot name a secret (1.17.1): `where` / `sort` on it — REST, GraphQL, versions — is refused (`secretReadAccess`, the field's `read` rule; verify: `GET /api/globals/site-integrations/versions?where[version.smtpPassword][exists]=true` as an admin → 400 `QueryError`, no `totalDocs`). **The panel is the source — never add an env variable for them** (`TURNSTILE_SECRET_KEY` is deprecated) | `secrets: { writeOnly: false }` | `writeOnlySecret(field)` / `writeOnlySecrets(fields, names)` for your own secret fields; with versions on the entity add `hooks.afterRead: [maskSecretsOnRestore]` | @@ -1272,7 +1285,7 @@ add missing hosts with flags / `extra`; (3) change `mode` to `'enforce'` in both | Locale cookie: consent read under its own stored version | — | `createProxy(config, { policyVersion })` / `createLocaleMiddleware({ policyVersion })` | | No `X-Powered-By` (with `withSecurityConfig`) | `withSecurityConfig(config, { hidePoweredBy: false })` | — | | Payload's colour-scheme client hints only on `/admin/:path*` (with `withSecurityConfig` outside `withPayload`) | `withSecurityConfig(config, { adminClientHints: false })` | `{ adminClientHints: { route, sources } }`, `scopeColorSchemeClientHints(rules, sources)` | -| CSP off until `buildSecurityHeaders({ csp })`; then hard rules, `'unsafe-eval'` only in dev | leave out `csp` | `buildCsp({ extra, override, strictDynamic, dev })`, `buildAdminCsp({ extra, override })`, `createCspReportRoute({ onReport, maxBytes })`, your own string via `additional` | +| CSP off until `buildSecurityHeaders({ csp })`; then hard rules, `'unsafe-eval'` only in dev | leave out `csp` | `buildCsp({ extra, override, strictDynamic, dev })`, `buildAdminCsp({ extra, override })`, `createCspReportRoute({ onReport, maxBytes, maxReports, rateLimit })`, your own string via `additional` | | Construction mode hides pages in Markdown, MCP | `markdown: { isPathVisible: () => true }`, `mcp: { isPathVisible: () => true }` | `isPathVisible`, `isPathVisibleIn(mode, path)`, `pathOf(url)`, type `PathVisibility` | | Construction mode filters the sitemap and llms.txt | `underConstructionSeo: false` | `include` / `getIncludedPaths` in the low-level builders | | `getSettings` at `depth: 1` | — | `createContentHelpers({ settingsDepth: 2 })` (every request pays) | @@ -1462,6 +1475,9 @@ its own tests). Order from the cheapest: | Site in the browser | `iapl-seo-check`, `iapl-consent-check`, `cookie-scan` | before handover, after deploy | | Closed doors (Playwright) | `iapl-audit/resources/closed-doors.spec.template.ts` → `tests/closed-doors.spec.ts`: every door that must stay closed, asked on a production build as anonymous, customer and editor; add the project's own doors (security.md "Closed doors from outside") | before every release and after every IAPL / Payload update | | Routes judged | `iapl-audit/resources/routes.template.ts` → `tests/routes.ts`; `pnpm payload run tests/routes.ts` against the committed `tests/routes.snapshot.json`, one reason per route; `… update` after an upgrade (security.md "Routes nobody has judged") | in CI, and after every IAPL / Payload / plugin update | +| Security, code | `pnpm exec iapl-doctor --only security`: headers, CSP, 2FA, account rules and the static rules over your code (`code-patterns`: unescaped HTML / JSON-LD, `overrideAccess: true` or a Local API `user` without `overrideAccess: false` where a request reaches, a `where` from the request, `eval`, `NEXT_PUBLIC_` secrets, redirects and fetches to an address from the request; `config-dangerous`). A correct place: `// iapl-security-ok: ` (security.md "Security suites") | before every "done", in CI | +| Attack probes (Playwright / doctor) | `iapl-audit/resources/attack-probes.spec.template.ts` → `tests/attack-probes.spec.ts` on a production build or staging (secret files, bundle secrets, proxy bypass, open redirect, cache poisoning, NoSQL operators, anonymous where / draft / GraphQL reads, error leaks, unbounded lists, `/_next/image`, 8 MB bodies); add a probe per custom endpoint in `EXTRA`. On the live site: `pnpm exec iapl-doctor --url https:// --only live-probes` (changes nothing) | before every release, after every IAPL / Payload / Next update, and after deploy (live) | +| Dependencies | `pnpm audit --prod` (the doctor's `deps-audit`): no high or critical; see §4 for the minimum Next / sharp / Payload | before every deploy | | Project logic | vitest for your own functions (mapping company data to JSON-LD, helpers, hooks, migration scripts with `--dry-run`) | when you write logic the plugin does not have | | Panel | the editor test (§11) and the empty-block test (§6.5a) | every new block / global | diff --git a/docs/agent/reference-site/INDEX.md b/docs/agent/reference-site/INDEX.md index 1766d0a..efadd7c 100644 --- a/docs/agent/reference-site/INDEX.md +++ b/docs/agent/reference-site/INDEX.md @@ -1132,6 +1132,7 @@ Rules: AGENT.md §8a. | File | What it shows | |---|---| +| `e2e/attack-probes.spec.ts` | attack probes on the built site (run by `pnpm e2e:built` in both bundlers): every probe of the plugin's ATTACK_PROBES (security.md "Security suites") with this site's secret values for the bundle check, plus CSRF with the editor's cookie from another origin and the session cookie's flags; probes tied to an open audit finding are expected to fail (`test.fail`) | | `e2e/closed-doors.spec.ts` | closed doors from outside (run by `pnpm e2e:built` in both bundlers): every door of e2e/closed-doors.ts asked on the production build as an anonymous visitor, a customer (the fixture's `e2e-visitors`) and an editor; doors still open while the owner decides are asserted open (`test.fail`) | | `e2e/closed-doors.ts` | the doors that must stay closed, who each is closed for and how a closed answer looks; a project adds its own (security.md "Closed doors from outside") | | `e2e/create-test-admin.ts` | two test admins with a known TOTP secret (the specs share out the five 2FA verify attempts per account), their stored verify counts cleared, and e-mail sending pointed at the tests' mail sink (local / CI database only) | diff --git a/docs/agent/skills/iapl-audit/SKILL.md b/docs/agent/skills/iapl-audit/SKILL.md index e6aea47..72d2ef2 100644 --- a/docs/agent/skills/iapl-audit/SKILL.md +++ b/docs/agent/skills/iapl-audit/SKILL.md @@ -65,6 +65,15 @@ names, env, admin, AGENTS.md, skills, seeds and — with `--url` / `--deep` — `pnpm payload run tests/routes.ts` fails on a route nobody has judged). A new custom endpoint, collection or route file of the project = a new snapshot entry with its reason, and a door in `DOORS` if it must stay closed. +- **Attack probes and static security rules** (security.md "Security suites"): `resources/attack-probes.spec.template.ts` + → `tests/attack-probes.spec.ts`, run on a production build or staging (`BASE_URL=… PAGE=/pl pnpm exec playwright test + tests/attack-probes.spec.ts`): the plugin's ATTACK_PROBES, plus the project's own in `EXTRA` for every custom + endpoint. On the live site: `pnpm exec iapl-doctor --url https:// --only live-probes`. The code side: + `pnpm exec iapl-doctor --only security` (`code-patterns`, `config-dangerous`); a correct place gets + `// iapl-security-ok: `. Dependencies: `pnpm audit --prod` (the doctor's `deps-audit`) — no high or critical. + Every address field rendered into `href` (social profiles, a website) is `buildUrlField()` and rendered through + `safeHref()` (security.md "Addresses rendered into `href`"); the static rules do not flag an `href` from data. + - **Editor test** (AGENT.md §11): every text, image, button, section, menu, footer and SEO field can be changed in the panel, in every language. - **Cookie consent:** in Network, before accepting, there are no requests to diff --git a/docs/agent/skills/iapl-audit/resources/attack-probes.spec.template.ts b/docs/agent/skills/iapl-audit/resources/attack-probes.spec.template.ts new file mode 100644 index 0000000..6b46dd8 --- /dev/null +++ b/docs/agent/skills/iapl-audit/resources/attack-probes.spec.template.ts @@ -0,0 +1,30 @@ +/** + * Attack probes from outside — the requests attackers send to Payload / Next.js sites, asked on a PRODUCTION build + * (`pnpm build && pnpm start`) or a staging copy (IAPL docs/security.md "Security suites"). Copy to + * tests/attack-probes.spec.ts and run: + * + * BASE_URL=http://localhost:3000 PAGE=/pl pnpm exec playwright test tests/attack-probes.spec.ts + * + * The probes come from the plugin (ATTACK_PROBES, @intecion/ipal-kit/doctor), so an IAPL upgrade brings new ones. + * On a LIVE site use `pnpm exec iapl-doctor --url https:// --only live-probes` instead: it runs only the + * probes that change nothing (no 8 MB bodies). This spec runs all of them — local or staging only. + * The bundle check looks for this site's own secret VALUES: they are read from the environment (.env of the local + * build) and never printed. Add the project's own probes to EXTRA. + */ +import { ATTACK_PROBES, type AttackProbe, createProbeContext } from '@intecion/ipal-kit/doctor' +import { expect, test } from '@playwright/test' + +const BASE = (process.env.BASE_URL ?? 'http://localhost:3000').replace(/\/$/, '') +const PAGE = process.env.PAGE ?? '/' +const secrets = ['PAYLOAD_SECRET', 'CRON_SECRET', 'R2_SECRET_ACCESS_KEY', 'TURNSTILE_SECRET_KEY', 'IAPL_DOCTOR_TOKEN', 'IAPL_COOKIE_SCAN_TOKEN'].map((k) => process.env[k]).filter((v): v is string => !!v && v.length >= 8) + +/** The project's own probes, e.g. a custom endpoint that must refuse an 8 MB body or an operator in its query. */ +const EXTRA: AttackProbe[] = [] + +for (const probe of [...ATTACK_PROBES, ...EXTRA]) { + test(`${probe.class}: ${probe.title}`, async () => { + const result = await probe.run(createProbeContext(BASE, { page: PAGE, secrets })) + test.skip(!!result.skipped, result.skipped) + expect(result.ok, result.detail).toBe(true) + }) +} diff --git a/docs/agent/skills/iapl-debug/SKILL.md b/docs/agent/skills/iapl-debug/SKILL.md index d7875fd..7803602 100644 --- a/docs/agent/skills/iapl-debug/SKILL.md +++ b/docs/agent/skills/iapl-debug/SKILL.md @@ -44,6 +44,12 @@ through this procedure. Ask only when you are missing something you cannot get y | `isAdmin(user)` / `isEditor(user)` is always `false` in a client component or in `proxy.ts` | the staff collections are not known there (no config in the browser bundle / middleware), and the predicates fail closed | `isAdmin(user, config)` with `useConfig()`, imported from `@intecion/ipal-kit/client`; in middleware `isAdmin(user, { staffCollections: ['users'] })` | | `next build --webpack`: `'server-only' cannot be imported from a Client Component module … caused by importing '@intecion/ipal-kit/dist/index.js'` | a `'use client'` file imports the main entry (Turbopack lets it pass) | import from `@intecion/ipal-kit/client` (role predicates are there since 1.16.7; types: `import type` from the main entry is fine); data the browser needs → a prop from a server component | | an account logs in but every page and request answers 403 / the setup screen says "The time to set up two-step verification has passed" | 2FA setup required: the account did not set TOTP up within the window (72 h from its creation, an admin's reset, or the first start after the upgrade) | an administrator opens the account in the panel → Two-step verification → "Reopen setup" (or `POST /api/ipal/two-factor/reset` `{ userId }`); every administrator is blocked: security.md "Every administrator is blocked" — a script with the Local API, `payload.update({ collection: 'users', id, data: { totpSetupFrom: new Date().toISOString() } })` (`pnpm payload run`), then log in and set TOTP up; or `requireSetup: { windowHours: false }`, redeploy, set up, put it back | +| a REST / GraphQL list from the front end returns only 100 documents (`hasNextPage: true`) although `limit` asks for more | `listLimit` (1.18.0, audit F4): callers that are not staff get at most 100 per request; staff and the Local API are not capped | page through (`page=2`), read on the server with the Local API, or `iapl({ listLimit: { max: 500 } })` / `{ exclude: ['slug'] }` / `false` (security.md "Lists and sorting") | +| `GET /api/?sort=$…` answers `400` "This sort field is not allowed." | `refuseOperatorSort` (1.18.0, audit F5): a sort naming a database operator is refused | sort by a field name; `refuseOperatorSort: false` = Payload's behaviour | +| a visitor account (customer) gets `403` on `/api/payload-locked-documents` | `lockedDocuments` (1.18.0): Payload's document locks are for staff only | intended; your own rule: `lockedDocuments: { access: { read } }`, or `false` | +| `[csp]` log lines show only `blocked=https://host` and `page=/path` (no query), or some reports are missing | `createCspReportRoute` (1.18.0, audit F1): the default line keeps origins and paths, at most 10 violations per request and 60 requests per client a minute | your own `onReport` gets the raw values; `maxReports`, `rateLimit: false` | +| a CDN or Varnish serves Markdown to visitors of an HTML page, or `Accept: text/markdown` answers `public, s-maxage` | a proxy of your own rewrites to `/md/…` without the 1.18.0 headers, or IAPL < 1.18.0 | `createProxy({ markdown: true })`, or copy `MARKDOWN_NEGOTIATED_HEADER` / `appendVary` into your proxy (content.md "content negotiation"); purge the CDN | +| saving a social profile / website address answers "Enter a full address, e.g. https://example.com." | `buildUrlField` (1.18.0, audit F2) accepts `https://` / `http://` and the `schemes` you list | type the full address; `buildUrlField({ schemes: ['mailto', 'tel'] })` for more kinds | | after typing the code the setup screen says "we sent a link to …" / "the confirmation e-mail could not be sent", and nothing opens | 1.18.0 `twoFactor.confirmByEmail`: the first set-up waits for the link sent to the account's e-mail, opened in the browser that scanned the code | open the link in that browser, then sign in again; no mail: the link is in the server log (`[iapl] 2FA: … Link`), or an admin opens the account → "Confirm the waiting set-up"; fix e-mail (doctor `2fa-enrolment-mail`); "open this link in the browser where you scanned the code" = scan again in the browser you read mail in | | a new account gets `403` from the API although its role allows the request | 2FA setup required: until TOTP is set up the account reaches only the setup screen | set TOTP up (log in to the panel); an integration: use an API key, or `twoFactor.requireSetup.exempt` | | after an upgrade EVERY panel login answers `500` (also `/api/users/init`), administrators with 2FA included; log: `[iapl] 2FA: the column for "totpSetupFrom" is missing … NOBODY CAN LOG IN` or `column users.totp_setup_from does not exist` | Postgres/SQLite: the migration that adds the 2FA column has not run (needed whenever 2FA is on) | `pnpm payload migrate:create` if no migration has it, commit, and redeploy with migrations run when the new container starts — `prodMigrations` in the adapter or the start command `pnpm payload migrate && pnpm start` (deployment.md §4.3; not Coolify's Pre-deployment command, which runs in the old container); nothing is lost. `iapl-doctor` reports a project whose migrations lack `totp_setup_from` | diff --git a/docs/agent/skills/iapl-doctor/SKILL.md b/docs/agent/skills/iapl-doctor/SKILL.md index f2f6a05..db4a4f4 100644 --- a/docs/agent/skills/iapl-doctor/SKILL.md +++ b/docs/agent/skills/iapl-doctor/SKILL.md @@ -46,6 +46,19 @@ Full reference: `node_modules/@intecion/ipal-kit/docs/doctor.md`. `--url ` · `--staging` (must be noindex) · `--admin-route ` · `--deep` · `--env-file ` (checks `_prod`) · `--only` / `--skip ` · `--sites '../*-web'` (a read-only rule × site table, exit 0). +**Security checks only** (security.md "Security suites"): `pnpm exec iapl-doctor --only security` — headers, CSP, +2FA, account rules, plus the static rules over the project's own code (`code-patterns`: unescaped HTML / JSON-LD, +`overrideAccess: true` or a Local API `user` without `overrideAccess: false` where a request reaches, a `where` from +the request, `eval`, `NEXT_PUBLIC_` secrets, redirects and fetches to an address from the request) and its configs +(`config-dangerous`). With `--url https://` also `live-probes`: the plugin's attack probes that change +nothing, run against the real site (secret files, bundle secrets, proxy bypass, open redirects, cache poisoning, +NoSQL operators, anonymous where / draft / GraphQL reads, error leaks, unbounded lists, `/_next/image`). Verify: on a +fresh starter site the run lists no `code-*` finding; add `eval(x)` to a page and `code-eval` appears. A correct +place is marked `// iapl-security-ok: `. From 1.18.0 a site on IAPL's defaults passes every probe; `markdown-vary`, +`unbounded-list` or `sort-operator` on such a site means a fix was turned off (`markdown: { negotiate }` with a proxy +of its own, `listLimit: false`, `refuseOperatorSort: false`) — security.md "Lists and sorting"; silence the rule with +the reason when that was the decision. + Exit `0` ok · `1` findings at or above `--fail-on` · `2` could not run · `3` a rule crashed. ## CI of a new site (starter, reference site) @@ -62,7 +75,8 @@ Existing client sites are not gated on it; run it there as a report only. Then `Authorization: Bearer `; counts and states only (`usersWithout2fa`, `usersSetupClosed` = of those, blocked because the 2FA setup window has passed, `pendingCookies`, `openSignUp` = slugs of auth collections with open sign-up, `turnstile` = the recorded state of the Turnstile check, `turnstileSecretFromEnv`, `plugin`, `node`) — never a key or a name. With the same `IAPL_DOCTOR_TOKEN` in the doctor's environment, `--url` reads it. Off: `iapl({ doctor: false })`; adapt: `iapl({ doctor: { tokenVar, access } })`. `access` returns a boolean (`({ req }) => isAdmin(req.user, req.payload)`): -since 1.18.0 any other answer is reported once in the server log, and from 1.19.0 only `true` allows. +since 1.18.0 only a literal `true` allows — `({ req }) => req.user` (an object) refuses — and any other answer is +reported once in the server log (`strictAccessAnswers: false` gives the old truthy reading back). ## Env the doctor reads diff --git a/docs/agent/skills/iapl-reference/SKILL.md b/docs/agent/skills/iapl-reference/SKILL.md index 0371a05..f05933f 100644 --- a/docs/agent/skills/iapl-reference/SKILL.md +++ b/docs/agent/skills/iapl-reference/SKILL.md @@ -46,6 +46,10 @@ description: Complete map of everything @intecion/ipal-kit provides — every ia | "Sending method" (`emailMethod`; `getMailMethod` / `setMailMethod`) | nobody has chosen: the order of 1.17.0, shown as selected | `relay` (IWSN), `smtp`, `graph` (deprecated): what is chosen is what is used, no fallback; a stored field (Postgres / SQLite: one migration) | | `secrets.reenterOnChange` | on | a save through access control that changes `smtpHost`, `smtpPort` or `smtpUser` while a password is stored must send the password again or remove it (`400` on the field otherwise), whatever `emailTransport` says — so an admin session cannot send the stored password to a server of its own. A change of the transport alone, and the Local API with access control off, are not asked | `false` = the stored password follows the new server | | `dashboardAlerts` | `{ integrations: 'admin', cookies: 'editor' }` | who sees the plugin's dashboard alerts: integration details (error text, link) for `integrations` and above, a neutral "ask an administrator" for editors below it, nothing for others; the cookie crawl / approval alert for `cookies` and above. With a role, a session that owes its second factor sees none | `integrations: 'editor' | 'all'`, `cookies: 'all'` (`'all'` = as before: no role and no second factor is checked) | +| `strictAccessAnswers` | `true` (1.18.0) | a project's access callback (`cookieScanner.access`, the doctor's `access`) allows only on a literal `true`; `req.user`, `1`, a string, an un-awaited Promise refuse; a non-boolean answer is reported once per option | `false` = any truthy answer allows (as before 1.18.0) | +| `listLimit` | `{ max: 100, staff: false }` (1.18.0, audit F4) | a REST / GraphQL list (`find`, versions, distinct) from a caller that is not staff gets at most `max` documents; `pagination=false` / `limit=0` become one page; staff and the Local API untouched | `false` (Payload's behaviour); `{ max, staff: true, exclude: ['slug'] }`; `buildQueryGuardHook` for a collection added after iapl | +| `refuseOperatorSort` | `true` (1.18.0, audit F5) | a `sort` naming a database operator (`$where`, `-$natural`, `a.$ne`) → `400` for everyone, logged as one `info` line (`RefusedSortError`) | `false`; `loggingLevels: { RefusedSortError: false }` hides the log line | +| `lockedDocuments` | staff only (1.18.0) | Payload's document locks (`payload-locked-documents`) for staff accounts with the second factor; Payload's default was any signed-in account | `false` (Payload's default); `{ access: { read, create, update, delete } }` | | `adminSameOrigin` | on (1.17.2) | `POST` mail service connect / disconnect, test e-mail, cookie scan / approval / crawl refuse (`403`) a request a browser marks as coming from another origin; own origins: the request's host, `serverURL`, `csrf`, `cors`, `origins` | `{ origins: [...] }` adds origins; `false` = no check; any other value stops the start | | `adminRoute` | `'/admin'` | `config.routes.admin`; stats link and views, `IntegrationAlerts` | the project moves `app/(payload)//` itself and adds the route to the proxy matcher (security.md) | | `twoFactor` | **none = error** | `@clocklimited/payload-2fa` with `forceSetup: true` (TOTP enforced, also checked in the API) | `twoFactor: false` (discouraged); omitting the option throws `[iapl] twoFactor.issuer is required` | diff --git a/docs/agent/skills/iapl-reference/resources/api.md b/docs/agent/skills/iapl-reference/resources/api.md index 87cab14..fa691e3 100644 --- a/docs/agent/skills/iapl-reference/resources/api.md +++ b/docs/agent/skills/iapl-reference/resources/api.md @@ -301,6 +301,7 @@ Opt-in with `iapl({ cookieScanner: true })`; the plugin wires the collection, en | `MARKDOWN_PREFIX` | `@intecion/ipal-kit` | constant `'/md'` — default prefix of Markdown routes | | `markdownHref(pathname, prefix?)` | `@intecion/ipal-kit` | page path → Markdown version address (`/pl/o-nas` → `/md/pl/o-nas`), e.g. for `alternates.types` | | `prefersMarkdown(request \| headers \| accept)` | `@intecion/ipal-kit` | whether the `Accept` header prefers `text/markdown` (q-values); for your own proxy — `createProxy({ markdown: true })` does it itself | +| `MARKDOWN_NEGOTIATED_HEADER`, `NEGOTIATED_CACHE_CONTROL`, `appendVary(headers, token)` | `@intecion/ipal-kit` | 1.18.0 (audit F3): the request marker the proxy sets on a negotiated rewrite (the route then answers `private, no-store` + `Vary: Accept`), that cache-control, and `Vary` with a token added once — for your own proxy (content.md "content negotiation"). `markdownResponse(md, { negotiated: true })` gives the same headers. `createProxy({ markdown: { prefix?, negotiate? } })`: `negotiate: false` = no rewrite. | | `searchContent({ payload, query, config, locale?, limit?, baseUrl?, collection?, summaryField? })` | `@intecion/ipal-kit` | searches published, indexable pages by title/description → `SearchResult[]`; does not throw | | `listContent({ payload, config, locale?, limit? })` | `@intecion/ipal-kit` | list of published, indexable pages (no query) — used by MCP `list_pages` | | `createSearchRoute({ getCachedPayload, config, baseUrl, defaultLimit?, rateLimit?, clientIp?, isPathVisible? })` | `@intecion/ipal-kit` | `GET` handler for the JSON search endpoint (`?q=&locale=&limit=`), with a per-IP rate limit; pass `isPathVisible` from `@/lib/content` so construction mode hides pages here too | @@ -503,6 +504,7 @@ The editor builds forms in the panel (Forms collection). The project does NOT wr | `resolveSystemLinks(settings, { locale, config, roles?, … })` | `@intecion/ipal-kit` | Links to system pages from Site settings (privacy/cookies/terms) with the page title as the label → `SystemLink[]`; in a project usually `getSystemLinks` from `lib/content` | | `homeSlugFrom(settings, field?)` | `@intecion/ipal-kit` | Homepage slug from `SiteSettings.homepage` (populated) or `undefined` | | `safeHref(url)` | `@intecion/ipal-kit` | The URL when safe (http(s), mailto, tel, sms, #, `/` path), otherwise `null` — blocks `javascript:`/`data:` | +| `buildUrlField({ name?, label?, required?, schemes?, description?, overrides? })`, `isAllowedUrl(value, schemes?)` | `@intecion/ipal-kit` | 1.18.0 (audit F2): a text field for an address rendered into `href` — `https://` / `http://` pass, plus the `schemes` you list (`mailto`, `tel`, `sms`, `hash`, `relative`); `javascript:`, `data:`, `//host` never. Render the value with `safeHref` too. Types `BuildUrlFieldOptions`, `UrlScheme`. | **Types:** `BuildLinkFieldOptions`, `BuildLinksFieldOptions`, `LinkAppearance`, `LinkAppearanceOption` — link field options and styles; `LinkValue`, `ResolveLinkHrefOptions`, `ResolvedLink`, `NavItem`, `ResolveNavOptions`, `SystemLink` — panel link value, resolver options and results. @@ -650,7 +652,11 @@ Server only (`pnpm payload run`); never import it from client code, the Payload | `buildCsp({ mode?, reportUri?, reportGroup?, r2Url?, analytics?, metaPixel?, linkedIn?, tiktok?, clarity?, turnstile?, youtube?, googleMaps?, nonce?, strictDynamic?, dev?, extra?, override? })` | `@intecion/ipal-kit` | Returns `{ key, value }` with a hardened CSP (`base-uri`, `object-src`, `frame-ancestors`, `form-action`) + sources for the enabled integrations. `mode: 'report-only'` → `…-Report-Only` (start here), `'enforce'` later. `extra` adds to any directive, `override` replaces / drops one (`null`). `dev` (default `NODE_ENV === 'development'`) adds `'unsafe-eval'`. `nonce` → `'nonce-…' 'strict-dynamic'`. | | `buildCspHeaders(args)` | `@intecion/ipal-kit` | `[csp, Reporting-Endpoints]` (the second only with `reportUri`). | | `buildAdminCsp(args)` / `buildAdminCspHeaders(args)` | `@intecion/ipal-kit` | Looser policy for Payload's admin: Monaco from `cdn.jsdelivr.net`, `blob:` workers, `https:` images, Live Preview `frame-src 'self'`, `frame-ancestors 'self'`. Rule `{ source: '/admin/:path*', headers: buildAdminCspHeaders({ mode, reportUri }) }` AFTER the site-wide rule. | -| `createCspReportRoute({ onReport?, maxBytes? })` | `@intecion/ipal-kit` | `POST` handler for `reportUri` (`src/app/api/csp-report/route.ts`): both report formats, body cap 16 KB, always `204`; default sink = one `[csp] …` `console.warn` line per violation (Coolify logs). | +| `createCspReportRoute({ onReport?, maxBytes?, maxReports?, rateLimit? })` | `@intecion/ipal-kit` | `POST` handler for `reportUri` (`src/app/api/csp-report/route.ts`): both report formats, body cap 16 KB, always `204`; default sink = one `[csp] …` `console.warn` line per violation (Coolify logs) made by `cspLogLine` — origin / path only, no control characters, values ≤ `CSP_LOG_VALUE_MAX` (128) (1.18.0, audit F1); at most `maxReports` (10) per request, `rateLimit` 60 / min per client (`false` = none); your `onReport` gets the raw values. | +| `accessAllowed(option, answer, { strict?, warn? })`, `strictAccessAnswers(req)` | `@intecion/ipal-kit` | how the plugin reads a project's access callback (`cookieScanner.access`, the doctor's `access`): since 1.18.0 only a literal `true` allows (`strict`, default; `iapl({ strictAccessAnswers: false })` = any truthy answer); a non-boolean answer is reported once per option with the fix `Boolean(req.user)`. `strictAccessAnswers(req)` = the reading of the request's config. Type `AccessAnswerOptions`. | +| `cspLogLine(violation)`, `CSP_LOG_VALUE_MAX` | `@intecion/ipal-kit` | the default CSP log line (safe to log) for your own sink, and its value cap. | +| `buildQueryGuardHook({ listLimit?, refuseOperatorSort? })`, `applyQueryGuard(config, options)`, `capListLimit(args, max?)`, `isOperatorSort(sort)`, `isStaffRequest(req)`, `RefusedSortError`, `DEFAULT_LIST_LIMIT`, `isQueryGuardHook`, `QUERY_GUARD_MARK` | `@intecion/ipal-kit` | 1.18.0 (audit F4, F5; security.md "Lists and sorting"): the `beforeOperation` hook iapl adds to every collection — lists from a non-staff caller over REST / GraphQL capped at 100 (`pagination=false`, `limit=0` included), a `sort` naming a database operator → `400` (logged as `info`). Options `listLimit: false \| { max, staff, exclude }`, `refuseOperatorSort: false`. Put the hook on a collection a plugin adds after iapl. Type `ListLimitOptions`. | +| `applyLockedDocumentsAccess(config, access?)`, `staffOnlyLocks`, `LOCKED_DOCUMENTS_SLUG` | `@intecion/ipal-kit` | 1.18.0: Payload's document locks (`payload-locked-documents`) for staff accounts only (with the second factor); iapl sets it at start (`lockedDocuments: false` = Payload's default, `{ access }` = your rule per operation). Type `LockedDocumentsAccess`. | | `parseCspReports(body)` | `@intecion/ipal-kit` | Normalises a report body (`csp-report` object or Reporting API array) to `CspViolation[]` — for your own collector. | | `buildReportingEndpoints(url, group?)`, `cspHeaderKey(mode?)`, `DEFAULT_CSP_REPORT_GROUP` | `@intecion/ipal-kit` | Building blocks: the `Reporting-Endpoints` header, the header name for a mode, the default `report-to` group (`'csp-endpoint'`). | | `createCspNonce()`, `CSP_NONCE_HEADER` | `@intecion/ipal-kit/next/middleware`, `@intecion/ipal-kit` | A per-request nonce and the request header (`x-nonce`) `createProxy({ csp })` passes it in — for your own proxy. Nonces make pages dynamic (no ISR). | @@ -896,11 +902,13 @@ Bin: `iapl-doctor` (`pnpm exec iapl-doctor [dir] [--json] [--md] [--strict] [--f | `withJobsRunAccess(config, options \| false)` / `jobsRunNotice(config)` | `@intecion/ipal-kit` | The config with that rule (only when `jobs.access.run` is missing; marks `custom.iapl.jobsRunDefault`); the start-up line when the queue is on and the secret is missing (null otherwise). | | `cronSecretMatches(req, secret)`, `CRON_SECRET_ENV`, `CRON_SECRET_MIN_LENGTH` | `@intecion/ipal-kit` | `Authorization: Bearer ` compared in constant time; an unset or shorter-than-16 secret never matches. Default variable `CRON_SECRET`. | | `runRouteCheck({ config, appDir?, snapshot?, update?, graphql?, cwd?, log? })` | `@intecion/ipal-kit/doctor` | `routes:check`: every public route (REST, GraphQL, Next route files) against the judged snapshot (default `e2e/routes.snapshot.json`); returns 1 on a route nobody judged or an entry without a reason; `update` writes new routes with an empty reason. Template: `iapl-audit/resources/routes.template.ts` (security.md "Routes nobody has judged"). Type `RunRouteCheckOptions`. | +| `ATTACK_PROBES`, `runAttackProbes(ctx, probes?)`, `createProbeContext(base, { page?, secrets?, timeoutMs?, userAgent? })` | `@intecion/ipal-kit/doctor` | The HTTP attack probes (secret files, bundle secrets, proxy bypass, open redirect, host-header and negotiation cache poisoning, NoSQL operators in sign-in and sort, anonymous where / draft / GraphQL reads, error leaks, unbounded lists, `/_next/image`, headers, methods, 8 MB bodies). Each `{ id, class, title, live, finding?, run(ctx) → { ok, detail, skipped? } }`; `runAttackProbes` runs the `live` ones by default. The doctor's `live-probes` rule; the Playwright template `iapl-audit/resources/attack-probes.spec.template.ts`; your own probe = an object of the same shape (security.md "Security suites"). Types `AttackProbe`, `ProbeContext`, `ProbeAnswer`, `ProbeResult`. | +| `scanCode(path, code)`, `listCodeFiles(root, start)`, `codeFindings(ctx)`, `scanConfigs(next, payload)`, `securityCodeRules`, `SECURITY_OK_MARKER`, `LIVE_PROBE_IDS` | `@intecion/ipal-kit/doctor` | The static security rules behind `code-patterns` and `config-dangerous`: every hit `{ rule, file, line, severity, message, text }` (types `CodeHit`, `CodePatternId`). A correct place is marked `// iapl-security-ok: `. Use `scanCode` in a test of your own to keep a judged allow-list, as the plugin does (`test/security-patterns.allow.json`). | | `listPublicRoutes(config, { graphqlSchema?, routeFiles? })` | `@intecion/ipal-kit` | Stable ids of every door a built config opens: `GET /api/users/me`, `graphql mutation loginUser`, `next GET /sitemap.xml`. From the config only (same on every database). Types `RouteInventoryOptions`, `GraphqlSchemaLike` (`getQueryType` / `getMutationType`). | | `listNextRouteFiles(files, read)` | `@intecion/ipal-kit` | Next route handlers of an app directory (`route.ts` with the methods it exports, `robots.ts`, `sitemap.ts`, `manifest.ts`; route groups left out). | | `compareRouteSnapshot(current, snapshot)` / `updateRouteSnapshot(current, snapshot)` | `@intecion/ipal-kit` | `{ unjudged, unexplained, gone }` against a `RouteSnapshot` (route id → reason); the snapshot after `--update` (new routes with `''`, gone ones dropped). Type `RouteSnapshotDiff`. | -**Types:** `DoctorRule`, `DoctorFinding`, `RuleFinding`, `DoctorReport`, `DoctorConfig`, `DoctorRuleSetting`, `DoctorSeverity`, +**Types:** `AttackProbe`, `ProbeContext`, `ProbeAnswer`, `ProbeResult`, `CodeHit`, `CodePatternId`, `DoctorRule`, `DoctorFinding`, `RuleFinding`, `DoctorReport`, `DoctorConfig`, `DoctorRuleSetting`, `DoctorSeverity`, `DoctorSource`, `DoctorStatus`, `DoctorContext`, `RunDoctorOptions`, `DoctorEndpointOptions`, `FrontendLayout`. ## Turnstile (`turnstile`) — details: `node_modules/@intecion/ipal-kit/docs/turnstile.md` diff --git a/docs/agent/skills/iapl-setup/SKILL.md b/docs/agent/skills/iapl-setup/SKILL.md index e40a8b4..4583bad 100644 --- a/docs/agent/skills/iapl-setup/SKILL.md +++ b/docs/agent/skills/iapl-setup/SKILL.md @@ -487,7 +487,7 @@ and `rel="alternate" type="text/markdown"`; `/pl/nie-ma-takiej` → 404 with con | `src/app/robots.ts` | `export { getRobots as default } from '@/lib/content'` + `force-dynamic` (AI crawler policy from Site settings → Search engines; `robots` = code only) | | `src/app/manifest.ts` | `export { manifest as default } from '@/lib/content'` + `force-dynamic` | | `src/app/api/health/route.ts` | `export { healthRoute as GET } from '@/lib/content'` + `force-dynamic` | -| `src/app/api/csp-report/route.ts` | `import { createCspReportRoute } from '@intecion/ipal-kit'` + `export const POST = createCspReportRoute()` (CSP violation reports → `[csp]` lines in the logs) | +| `src/app/api/csp-report/route.ts` | `import { createCspReportRoute } from '@intecion/ipal-kit'` + `export const POST = createCspReportRoute()` (CSP violation reports → `[csp]` lines in the logs: origins and paths only, 10 per request, 60 requests per client a minute; security.md "Collecting reports") | ```ts // next.config.ts @@ -581,7 +581,8 @@ Already wired and required: `markdown: true` (stage 6 proxy), `markdownAlternate **Check.** `curl -s localhost:3000/llms.txt` → site name and a list of pages with descriptions (`aiSummary`); `/llms-full.txt` → page content; `curl -s localhost:3000/md/pl` → Markdown of the home page; `curl -s -H 'Accept: -text/markdown' localhost:3000/pl` → the same Markdown; `curl -s -X POST localhost:3000/api/mcp -H 'content-type: +text/markdown' localhost:3000/pl` → the same Markdown, sent `cache-control: private, no-store` with `Vary: Accept` +(`curl -sD- -o/dev/null -H 'Accept: text/markdown' localhost:3000/pl`; 1.18.0, so no CDN stores it as the page); `curl -s -X POST localhost:3000/api/mcp -H 'content-type: application/json' -d '{"jsonrpc":"2.0","id":1,"method":"tools/list"}'` → `get_site_info`, `list_pages`, `search_content`, `get_page`; `/indexnow-key.txt` → `404` until the key is generated in the panel, then the key. diff --git a/docs/agent/skills/iapl-upgrade/SKILL.md b/docs/agent/skills/iapl-upgrade/SKILL.md index cc89557..7fe2a01 100644 --- a/docs/agent/skills/iapl-upgrade/SKILL.md +++ b/docs/agent/skills/iapl-upgrade/SKILL.md @@ -47,6 +47,24 @@ are not affected. Nothing to wire, no migration, no import-map change. Off: `two **Check:** `pnpm exec iapl-doctor --deep` shows no `2fa-enrolment-mail` error; a test editor scans the code → the screen says "we sent a link to …", the link opened in the same browser → "Two-step verification is on". +**→ 1.18.0, security audit fixes (CHANGELOG 1.18.0 "Security audit 2026-12"; security.md "Lists and sorting") — no +migration, no import-map change; check before deploying:** (1) **public lists are capped at 100** for callers that are +not staff (REST / GraphQL; the Local API and the panel are not touched): a client-side script that reads more than +100 documents anonymously gets `hasNextPage: true` — page through, or `listLimit: { max }` / `{ exclude: ['slug'] }` +/ `false`; (2) a `?sort=$…` answers `400` (`refuseOperatorSort: false` = Payload's way); (3) Payload's document locks +are staff only (`lockedDocuments: false` = Payload's default); (4) the negotiated Markdown at a page URL is +`private, no-store` + `Vary: Accept`, and pages under the proxy matcher get `Vary: Accept` — a proxy of your own that +rewrites to `/md/…` copies the headers (content.md); `markdown: { negotiate: false }` turns negotiation off; (5) CSP +report log lines show origins and paths, at most 10 per request and 60 requests per client a minute (a log parser +that read full URLs adapts; `createCspReportRoute({ maxReports, rateLimit })`); (6) a text field of your own whose +value goes into `href` (social profiles, a website): `buildUrlField()` and `safeHref()` at render (no schema change); +(7) **access callbacks are strict:** `cookieScanner.access` and the doctor's `access` allow only on a literal `true` +— a callback that returns `req.user` now refuses (`403`): return `Boolean(req.user)` or a role check; the old reading +back: `iapl({ strictAccessAnswers: false })`; (8) the first `iapl-doctor --only security` run shows the new `code-*` / `config-dangerous` rules — judge each, mark a +correct place `// iapl-security-ok: `. **Check:** `curl -s '/api/pages?limit=100000' | jq .limit` → `100`; +`curl -s -o /dev/null -w '%{http_code}' '/api/pages?sort=%24where'` → `400`; +`pnpm exec iapl-doctor --url --only live-probes` → no finding. + **→ 1.17.2, security (CHANGELOG 1.17.2; PROGRAMISTA §6, items 84–87) — nothing required, check:** `readVersions: readPublished()` now works (a wrapper of your own around it: use `readPublishedVersions()` inside); behind a proxy that rewrites `Host` without `X-Forwarded-Host`, set `serverURL` or the panel's mail / cookie buttons answer 403 diff --git a/docs/content.md b/docs/content.md index 71a875c..f52746f 100644 --- a/docs/content.md +++ b/docs/content.md @@ -344,8 +344,11 @@ blocksToMarkdown(page.layout, { (default true — a YAML block with `locale`, `title`, `description`, `url`, `updated`), `baseUrl` (gives `url:` — the canonical HTML address), `config` (i18n — with one language `url:` has no `/pl`). -`markdownResponse(md, { canonical? })` — `null` → 404 `text/plain`; otherwise `text/markdown`, -`x-robots-tag: noindex`, `s-maxage=3600`, optional `Link: <…>; rel="canonical"` header. +`markdownResponse(md, { canonical?, negotiated? })` — `null` → 404 `text/plain`; otherwise `text/markdown`, +`x-robots-tag: noindex`, `s-maxage=3600`, optional `Link: <…>; rel="canonical"` header. `negotiated: true` (the +answer goes out at the page's own URL, see "content negotiation" below) sends `cache-control: private, no-store` and +`Vary: Accept` instead of the public lifetime; `createMarkdownRoute` sets it by itself when the proxy marked the +request (`MARKDOWN_NEGOTIATED_HEADER`). Shorter — the whole route in one line: @@ -385,14 +388,30 @@ Without it, on a multi-language site the proxy redirects `/md/pl/o-nas` to `/pl/md/pl/o-nas` (it treats `md` as a path without a language), so the Markdown route does not work. The option lets `/md/…` paths through and does the `Accept` negotiation below. +**The negotiated answer is never cached as the page (1.18.0, security audit F3).** It shares the page's URL, so a +CDN that caches HTML ("Cache Everything" on Cloudflare, Varnish) would otherwise store the Markdown and serve it to +every visitor of that page. The proxy marks the rewritten request, the route answers `private, no-store` with +`Vary: Accept`, the rewrite carries the same headers, and the pages under the proxy matcher get `Vary: Accept`. +`/md/…` keeps its public caching. Cloudflare ignores `Vary` for HTML — `no-store` is what keeps it out of the cache +there. Options: `markdown: { prefix: '/ai', negotiate: false }` — `negotiate: false` serves Markdown only at `/md/…` +(no rewrite, no `Vary: Accept` on pages). Verify: +`curl -sD- -o/dev/null -H 'Accept: text/markdown' https:///pl | grep -iE 'content-type|cache-control|vary'` +→ `text/markdown`, `private, no-store`, `Vary` with `Accept`; or `pnpm exec iapl-doctor --url https:// --only live-probes` +(probe `markdown-vary`). + Manually (when you have your own proxy): the same URL serves Markdown on negotiation with the `Accept` header (a rewrite in the proxy): ```ts -// proxy.ts -import { prefersMarkdown, markdownHref } from '@intecion/ipal-kit' +// proxy.ts — keep the answer out of shared caches: mark the request for createMarkdownRoute and say Vary: Accept +import { appendVary, MARKDOWN_NEGOTIATED_HEADER, markdownHref, NEGOTIATED_CACHE_CONTROL, prefersMarkdown } from '@intecion/ipal-kit' if (prefersMarkdown(request)) { - return NextResponse.rewrite(new URL(markdownHref(request.nextUrl.pathname), request.url)) + const headers = new Headers(request.headers) + headers.set(MARKDOWN_NEGOTIATED_HEADER, '1') + const res = NextResponse.rewrite(new URL(markdownHref(request.nextUrl.pathname), request.url), { request: { headers } }) + res.headers.set('cache-control', NEGOTIATED_CACHE_CONTROL) + appendVary(res.headers, 'Accept') + return res } ``` diff --git a/docs/cookie-scanner.md b/docs/cookie-scanner.md index 4027d3d..a1a890c 100644 --- a/docs/cookie-scanner.md +++ b/docs/cookie-scanner.md @@ -176,7 +176,7 @@ run the tests, commit. | `integrations` | built-ins | `(defaults) => integrations` — filter, change or add `CookieIntegration`s (each: `key`, `label` — one string or `{ en, pl, … }` per admin language, `declarations`, `isEnabled(ctx)`) | | `database` | `true` | `false` = no Open Cookie Database lookup | | `databaseCategories` | table above | Partial map from database category to consent category | -| `access` | editor and up | `({ req }) => boolean` — who may scan, start a crawl and read its status | +| `access` | editor and up | `({ req }) => boolean` — who may scan, start a crawl and read its status. Only a literal `true` allows (1.18.0): `({ req }) => req.user` refuses — return `Boolean(req.user)`; `iapl({ strictAccessAnswers: false })` gives the old truthy reading back (security.md "Access callbacks") | | `collectionOverrides` | — | Change `cookie-review`: an object merges `access` / `admin` / `hooks` key by key (your keys win), a function takes over (keep the slug) | | `labels` | `en`, `pl` | `{ de: { scanButton: 'Cookies scannen', … } }` — merged over the plugin's labels (`CookieScanLabels`) | | `syncAccepted` | `true` | `false` = accepting or approving only marks the entry; nothing is written to Cookie banner | diff --git a/docs/doctor.md b/docs/doctor.md index b49c4aa..501fead 100644 --- a/docs/doctor.md +++ b/docs/doctor.md @@ -82,7 +82,7 @@ each plugin log — counts, sizes and dates only. Intecion mail service — states and codes only, never a token, a password or an address; `relay` is `null` when the mail service is switched off. -Turn off: `iapl({ doctor: false })`. Adapt: `iapl({ doctor: { tokenVar: 'MY_TOKEN', access: ({ req }) => isAdmin(req.user, req.payload) } })` (a logged-in staff admin may read it too; the second factor is checked for you — never test `req.user.roles` by hand, an account of another collection can carry the same value) +Turn off: `iapl({ doctor: false })`. Adapt: `iapl({ doctor: { tokenVar: 'MY_TOKEN', access: ({ req }) => isAdmin(req.user, req.payload) } })` (only a literal `true` allows since 1.18.0 — `req.user` refuses; `strictAccessAnswers: false` = the old truthy reading) (a logged-in staff admin may read it too; the second factor is checked for you — never test `req.user.roles` by hand, an account of another collection can carry the same value) (`access` lets a logged-in admin read it without the token). Building blocks: `buildDoctorEndpoint`, `collectDoctorStatus` from `@intecion/ipal-kit/doctor`. @@ -123,6 +123,9 @@ Turn off: `iapl({ doctor: false })`. Adapt: `iapl({ doctor: { tokenVar: 'MY_TOKE | | `staff-accounts-open` | error (warning for `read`, `readVersions`) | (deep) a staff collection that an account of another, non-staff auth collection may create in, read (also its versions), update, delete from or unlock — it can make itself staff, change a staff password, list the accounts or lift a login lock. The account rules are off (`accounts: false`, `adminOnlyCreate` / `adminOnlyWrite` / `staffOnlyRead: false`) or the project's own rule is wider. Asked with a made-up outside account; a rule that throws counts as closed | | | `turnstile-degraded` | warning / error | (deep) Turnstile is checking forms; while it is not (wrong or missing secret, Cloudflare down) a warning, an error once it has lasted 24 hours (counted from the recorded start to now) | | | `turnstile-env-key` | warning | (deep) the Turnstile secret key is in the panel, not in the deprecated `TURNSTILE_SECRET_KEY` environment variable | +| | `code-patterns` | error / warning | the project's own code (`src/`, seeds, migrations, scripts and tests left out where the rule is about requests): `dangerouslySetInnerHTML` / `innerHTML` with a value no sanitizer passed, JSON in a ` ends the script (JsonLdGraph, or .replace(/ = { + 'code-eval': 'Code built from strings', + 'code-inner-html': 'HTML or JSON printed without escaping (XSS)', + 'code-local-api-user': 'Local API given a user without overrideAccess: false', + 'code-open-redirect': 'Redirect to an address from the request', + 'code-override-access': 'overrideAccess: true where a request reaches', // iapl-security-ok: the rule's own title + 'code-public-secret': 'A secret that can reach the browser', + 'code-raw-where': 'A query (where) taken from the request', + 'code-shell': 'A shell command built from a string', + 'code-ssrf': 'A server-side fetch of an address the request chose', +} + +/** Every hit of a project, grouped as doctor findings (one per rule and file). */ +export function codeFindings(ctx: Pick): RuleFinding[] { + const start = ctx.src ? ctx.src.replace(/\/$/, '') : '.' + const files = listCodeFiles(ctx.root, start).filter((f) => ctx.src || /^(?:app|lib|components|blocks|collections|globals|hooks|endpoints|utilities|access|fields|plugins)\//.test(f) || /^(?:payload\.config|proxy|middleware)\.[cm]?[jt]s$/.test(f)) + const byKey = new Map() + for (const file of files) { + for (const hit of scanCode(file, ctx.read(file))) { + const key = `${hit.rule}\u0000${hit.file}` + byKey.set(key, [...(byKey.get(key) ?? []), hit]) + } + } + return [...byKey.values()].map((hits) => ({ + file: hits[0].file, + fix: `${RULE_TEXT[hits[0].rule]} — fix it, or mark a correct place with // ${SECURITY_OK_MARKER}: (security.md → Security suites)`, + message: `${hits[0].message}: ${hits.slice(0, 3).map((h) => `${h.file}:${h.line}`).join(', ')}${hits.length > 3 ? ` … +${hits.length - 3}` : ''}`, + rule: hits[0].rule, + severity: hits.some((h) => h.severity === 'error') ? 'error' : hits[0].severity, + })) +} + +export const securityCodeRules: DoctorRule[] = [ + { + id: 'code-patterns', + check: (ctx) => codeFindings(ctx), + docs: 'docs/security.md', + group: 'security', + source: 'static', + }, + { + id: 'config-dangerous', + check: (ctx) => { + const n = nextConfigFile(ctx) + const p = configFile(ctx) + return scanConfigs(n ? { code: ctx.read(n), file: n } : null, p ? { code: ctx.read(p), file: p } : null) + }, + docs: 'docs/security.md', + group: 'security', + source: 'static', + }, + { + // The HTTP attack probes safe on a live site (security/attackProbes.ts): `iapl-doctor --url https://site --only live-probes` + id: 'live-probes', + check: async (ctx) => { + if (!ctx.live) {return []} + const severe = new Set(['bundle-secrets', 'graphql', 'login-operators', 'middleware-subrequest', 'rest-where', 'secret-files']) + const results = await runAttackProbes(createProbeContext(ctx.live.url)) + return results.filter(({ result }) => !result.ok).map(({ probe, result }) => ({ + fix: `${probe.title}${probe.finding ? ` (a known IAPL issue, ${probe.finding} of the 2026-12 audit: see the changelog)` : ''} — security.md → Security suites`, + message: `${probe.class}: ${result.detail}`, + rule: `live-probes:${probe.id}`, + severity: severe.has(probe.id) ? 'error' : 'warning', + })) + }, + docs: 'docs/security.md', + group: 'security', + source: 'live', + }, +] + +/** Probe ids, for `--skip live-probes:` style settings in iapl-doctor.json. */ +export const LIVE_PROBE_IDS = ATTACK_PROBES.filter((p) => p.live).map((p) => p.id) diff --git a/src/modules/doctor/run.ts b/src/modules/doctor/run.ts index 2081504..10752a5 100644 --- a/src/modules/doctor/run.ts +++ b/src/modules/doctor/run.ts @@ -17,6 +17,7 @@ import { createLiveFetcher, liveRules } from './rules/live.js' import { mailRules } from './rules/mail.js' import { performanceRules } from './rules/performance.js' import { securityRules } from './rules/security.js' +import { securityCodeRules } from './rules/securityCode.js' import { seedRules } from './rules/seeds.js' import { toolingRules } from './rules/tooling.js' import { versionRules } from './rules/versions.js' @@ -37,6 +38,7 @@ export const doctorRules: DoctorRule[] = [ ...layoutRules, ...envRules, ...securityRules, + ...securityCodeRules, ...consentRules, ...mailRules, ...agentRules, diff --git a/src/modules/doctor/status.ts b/src/modules/doctor/status.ts index 73b9a1e..73a3afe 100644 --- a/src/modules/doctor/status.ts +++ b/src/modules/doctor/status.ts @@ -14,7 +14,7 @@ import { IMAGE_RULES } from '../performance/budgets.js' import { countPendingEnrolments, mailConfigured } from '../security/totp/enrolmentConfirm.js' import { secondFactorPassed, SETUP_FROM_FIELD } from '../security/totp/secondFactor.js' import { countAccountsWithoutTotp } from '../security/totp/setupRequired.js' -import { accessAllowed } from '../shared/accessAnswer.js' +import { accessAllowed, strictAccessAnswers } from '../shared/accessAnswer.js' import { readEnv } from '../shared/envName.js' import { clientIp, consumeRateLimit, tooManyRequests } from '../shared/rateLimit.js' import { retentionMap } from '../shared/retention.js' @@ -194,7 +194,7 @@ export function buildDoctorEndpoint(options: DoctorEndpointOptions = {}): Endpoi const limit = await consumeRateLimit({ key: clientIp(req.headers), max: 10, scope: 'iapl-doctor', windowMs: 60_000 }) if (!limit.ok) {return tooManyRequests(limit.retryAfter, { error: 'Too many requests' })} const given = (req.headers.get('authorization') ?? '').replace(/^Bearer\s+/i, '').trim() - const allowed = (given && sameToken(given, token)) || (options.access ? secondFactorPassed(req) && accessAllowed('doctor.access', await options.access({ req })) : false) + const allowed = (given && sameToken(given, token)) || (options.access ? secondFactorPassed(req) && accessAllowed('doctor.access', await options.access({ req }), { strict: strictAccessAnswers(req) }) : false) if (!allowed) {return Response.json({ error: 'Unauthorized' }, { status: 401 })} const status = await collectDoctorStatus(req.payload) return Response.json(status, { headers: { 'cache-control': 'no-store' } }) diff --git a/src/modules/i18n/createProxy.ts b/src/modules/i18n/createProxy.ts index 72e6f4d..e1f45e4 100644 --- a/src/modules/i18n/createProxy.ts +++ b/src/modules/i18n/createProxy.ts @@ -1,7 +1,7 @@ import type { BuildCspArgs } from '../security/buildCsp.js' import type { I18nConfig } from './types.js' -import { MARKDOWN_PREFIX, markdownHref, prefersMarkdown } from '../content/markdownNegotiation.js' +import { appendVary, MARKDOWN_NEGOTIATED_HEADER, MARKDOWN_PREFIX, markdownHref, NEGOTIATED_CACHE_CONTROL, prefersMarkdown } from '../content/markdownNegotiation.js' import { buildCsp, buildReportingEndpoints } from '../security/buildCsp.js' import { createCspNonce, CSP_NONCE_HEADER } from '../security/cspNonce.js' import { isValidLocale } from './helpers.js' @@ -38,7 +38,7 @@ type NextResponseLike = { next: (init?: { request?: { headers: Headers } }) => ProxyResponse redirect: (url: string | URL) => ProxyResponse /** Needed for `markdown` content negotiation; Next's NextResponse has it. */ - rewrite?: (url: string | URL) => ProxyResponse + rewrite?: (url: string | URL, init?: { request?: { headers: Headers } }) => ProxyResponse } type CreateProxyOptions = { @@ -62,8 +62,13 @@ type CreateProxyOptions = { * sets another one. Paths under the prefix pass through untouched (no locale * redirect — /md/pl/o-nas must not become /pl/md/pl/o-nas), and a page * requested with `Accept: text/markdown` is rewritten to its Markdown version. + * + * The negotiated answer shares the page's URL, so it is sent `private, no-store` with `Vary: Accept` (and the + * pages under the matcher get `Vary: Accept`): a cache in front never stores the Markdown as the page (security + * audit 2026-12, F3). `/md/…` itself keeps its public caching. The object form adapts it: + * `{ prefix?: string, negotiate?: boolean }` — `negotiate: false` serves Markdown only at `/md/…`. */ - markdown?: boolean | string + markdown?: { negotiate?: boolean; prefix?: string } | boolean | string /** Consent policy version to require for saving the locale cookie (createLocaleMiddleware). */ policyVersion?: number } @@ -89,7 +94,11 @@ export function createProxy( ): (request: ProxyRequest) => ProxyResponse { const { csp, exposeHeaders = true, markdown, NextResponse, ...mwOptions } = deps const run = createLocaleMiddleware({ config, ...mwOptions }) - const mdPrefix = markdown ? (typeof markdown === 'string' ? markdown : MARKDOWN_PREFIX).replace(/\/$/, '') : null + const mdOptions = typeof markdown === 'object' && markdown ? markdown : {} + const mdPrefix = markdown + ? (typeof markdown === 'string' ? markdown : (mdOptions.prefix ?? MARKDOWN_PREFIX)).replace(/\/$/, '') + : null + const negotiate = Boolean(mdPrefix) && mdOptions.negotiate !== false return (request: ProxyRequest): ProxyResponse => { const { pathname } = request.nextUrl @@ -99,8 +108,15 @@ export function createProxy( // Markdown route; the rest gets the locale redirect first, then negotiates. const seg = pathname.split('/').filter(Boolean)[0] ?? '' const routable = config.locales.length === 1 || isValidLocale(seg, config) - if (routable && NextResponse.rewrite && prefersMarkdown(request.headers)) { - return NextResponse.rewrite(new URL(markdownHref(pathname, mdPrefix), request.url)) + if (negotiate && routable && NextResponse.rewrite && prefersMarkdown(request.headers)) { + // The route reads the marker and answers private + Vary: Accept; the same headers on the rewrite itself + // for a route that is not the plugin's (security audit 2026-12, F3). + const mdHeaders = new Headers(request.headers) + mdHeaders.set(MARKDOWN_NEGOTIATED_HEADER, '1') + const rewritten = NextResponse.rewrite(new URL(markdownHref(pathname, mdPrefix), request.url), { request: { headers: mdHeaders } }) + rewritten.headers?.set('cache-control', NEGOTIATED_CACHE_CONTROL) + appendVary(rewritten.headers, 'Accept') + return rewritten } } @@ -133,6 +149,9 @@ export function createProxy( } } + // The same URL answers HTML or (negotiated) Markdown: say so to any cache in front. + if (negotiate && result.type !== 'redirect') {appendVary(response.headers, 'Accept')} + if (result.cookie) { response.cookies.set(result.cookie.name, result.cookie.value, { path: '/', diff --git a/src/modules/links/buildUrlField.ts b/src/modules/links/buildUrlField.ts new file mode 100644 index 0000000..113a16c --- /dev/null +++ b/src/modules/links/buildUrlField.ts @@ -0,0 +1,74 @@ +import type { TextField } from 'payload' + +import type { AdminText } from '../admin-i18n/define.js' + +import { safeHref } from './resolveLinkHref.js' + +/** Schemes {@link buildUrlField} may allow besides `https:` / `http:`. */ +export type UrlScheme = 'hash' | 'mailto' | 'relative' | 'sms' | 'tel' + +export type BuildUrlFieldOptions = { + /** Help under the field. Default: what the field accepts. */ + description?: AdminText | string + /** Panel label. Default "Address". */ + label?: AdminText | string + /** Field name. Default `url`. */ + name?: string + /** Anything else of Payload's text field (admin, access, hooks, localized…); wins over the defaults. */ + overrides?: Partial> + required?: boolean + /** + * Besides `https://` and `http://`: `mailto:`, `tel:`, `sms:`, `#section`, `/a/path` on this site. + * Default none — a profile or a website. `javascript:`, `data:`, `vbscript:` and `//host` never pass. + */ + schemes?: readonly UrlScheme[] +} + +const ALLOWED: Record = { + hash: /^#/, + mailto: /^mailto:/i, + relative: /^\/(?!\/)/, + sms: /^sms:/i, + tel: /^tel:/i, +} + +/** True when `value` is an address the field accepts: safe as an `href` ({@link safeHref}) and of an allowed kind. */ +export function isAllowedUrl(value: null | string | undefined, schemes: readonly UrlScheme[] = []): boolean { + const safe = safeHref(value) + if (!safe) {return false} + if (/^https?:\/\/[^\s/?#]+/i.test(safe)) {return true} + return schemes.some((s) => ALLOWED[s].test(safe)) +} + +/** + * A text field for an address that is rendered into `href` (a profile, a website, a map link): it accepts + * `https://…` (and the schemes you list) and refuses `javascript:`, `data:` and other addresses that would run script + * when clicked (security audit 2026-12, F2). Render the stored value with `safeHref()` as well: data can come from an + * import, a seed or an older version. + * + * fields: [{ name: 'label', type: 'text' }, buildUrlField({ required: true })] + */ +export function buildUrlField(options: BuildUrlFieldOptions = {}): TextField { + const { name = 'url', description, label, overrides = {}, required, schemes = [] } = options + const { admin, ...rest } = overrides + const pl = (req?: { i18n?: { language?: string } }) => req?.i18n?.language === 'pl' + return { + name, + type: 'text', + label: label ?? { en: 'Address', pl: 'Adres' }, + required, + validate: (v: null | string | undefined, { req }: { req?: { i18n?: { language?: string } } } = {}) => { + if (!v) {return required ? (pl(req) ? 'To pole jest wymagane.' : 'This field is required.') : true} + return isAllowedUrl(v, schemes) || (pl(req) ? 'Wpisz pełny adres, np. https://example.com.' : 'Enter a full address, e.g. https://example.com.') + }, + ...rest, + admin: { + description: + description ?? + (schemes.length + ? { en: 'A full address (https://…) or one of the other kinds this field allows.', pl: 'Pełny adres (https://…) albo inny rodzaj, na który pozwala to pole.' } + : { en: 'A full address, e.g. https://example.com', pl: 'Pełny adres, np. https://example.com' }), + ...admin, + }, + } as TextField +} diff --git a/src/modules/links/index.ts b/src/modules/links/index.ts index 922b2cd..598cc67 100644 --- a/src/modules/links/index.ts +++ b/src/modules/links/index.ts @@ -1,5 +1,7 @@ export { buildLinkField, buildLinksField } from './buildLinkField.js' export type { BuildLinkFieldOptions, BuildLinksFieldOptions, LinkAppearance, LinkAppearanceOption } from './buildLinkField.js' +export { buildUrlField, isAllowedUrl } from './buildUrlField.js' +export type { BuildUrlFieldOptions, UrlScheme } from './buildUrlField.js' export { resolveLinkHref, safeHref } from './resolveLinkHref.js' export type { LinkValue, ResolveLinkHrefOptions } from './resolveLinkHref.js' export { homeSlugFrom, resolveLink, resolveNav, resolveSystemLinks } from './resolveNav.js' diff --git a/src/modules/security/attackProbes.ts b/src/modules/security/attackProbes.ts new file mode 100644 index 0000000..5bbbe97 --- /dev/null +++ b/src/modules/security/attackProbes.ts @@ -0,0 +1,404 @@ +/** + * HTTP attack probes (security audit 2026-12): the requests attackers send to Payload / Next.js sites, each with the + * answer a safe site gives. One list, two users: + * - `iapl-doctor --url https://site --only live-probes` runs the probes marked `live` against a project's own site: + * GET requests, plus requests that change nothing (a refused sign-in with operators in it); + * - the plugin's reference site runs every probe on a production build in both bundlers + * (reference/e2e/attack-probes.spec.ts, part of `pnpm e2e:built`); a project copies + * `.agents/skills/iapl-audit/resources/attack-probes.spec.template.ts`. + * Exported (`@intecion/ipal-kit/doctor`) so a project adds its own probes or runs a subset in its CI. + * + * A probe answers on STATUS CODES and headers first: a 500 page is never counted as "closed" (a test that passes on + * an error page proves nothing). + */ + +export type ProbeAnswer = { error?: string; headers: Headers; ms: number; status: number; text: string } + +export type ProbeContext = { + /** Site origin, no trailing slash. */ + base: string + /** One request; never follows redirects unless asked. */ + fetch: (path: string, init?: { body?: string; follow?: boolean; headers?: Record; method?: string }) => Promise + /** A public page path of the site (default `/`), e.g. `/pl`. */ + page?: string + /** Values that must never appear in a public file (the test knows the real secrets; a live run passes none). */ + secrets?: string[] +} + +export type ProbeResult = { detail: string; ok: boolean; skipped?: string } + +export type AttackProbe = { + /** The vulnerability class (security.md → "Threat list"). */ + class: string + /** A finding of the audit that is not fixed yet (security-audit-2026-12-findings.md): expected to fail until it is. */ + finding?: string + id: string + /** Safe on a live site: reads only, or a request the site refuses without writing. */ + live: boolean + run: (ctx: ProbeContext) => Promise + title: string +} + +const ok = (detail = ''): ProbeResult => ({ detail, ok: true }) +const bad = (detail: string): ProbeResult => ({ detail, ok: false }) +const skip = (why: string): ProbeResult => ({ detail: '', ok: true, skipped: why }) + +/** A stack trace or a server path in an answer. */ +const LEAK = /\n\s+at [\w$.<>]+ \(|\bat (?:async )?[\w$.]+ \((?:\/|[A-Z]:\\|file:)|\/node_modules\/|webpack-internal:|\/\.next\/server\// +/** What a secret looks like, without knowing it. */ +const SECRET_SHAPES: Array<[string, RegExp]> = [ + ['a private key', /-----BEGIN (?:RSA |EC |OPENSSH )?PRIVATE KEY-----/], + ['a database URL with a password', /\b(?:mongodb(?:\+srv)?|postgres(?:ql)?|mysql):\/\/[^\s"'`:@/]+:[^\s"'`@/]+@/], + ['a live Stripe key', /\bsk_live_[0-9a-zA-Z]{10,}/], + ['an AWS secret', /\baws_secret_access_key\b|\bAKIA[0-9A-Z]{16}\b/], + ['a variable assignment of a server secret', /\b(?:PAYLOAD_SECRET|DATABASE_URI|R2_SECRET_ACCESS_KEY|TURNSTILE_SECRET_KEY|CRON_SECRET|SMTP_PASS(?:WORD)?)\s*[=:]\s*["'`][^"'`]{8,}/], +] +const EVIL = 'evil.example' +const sameHost = (location: null | string, base: string) => { + if (!location) {return true} + try { + return new URL(location, base).host === new URL(base).host + } catch { + return false + } +} +const describe = (a: ProbeAnswer) => (a.error ? `no answer (${a.error})` : `${a.status}`) +const scriptSrcs = (html: string) => [...html.matchAll(/]+src="([^"]+)"/g)].map((m) => m[1].replace(/&/g, '&')) + +export const ATTACK_PROBES: AttackProbe[] = [ + { + id: 'secret-files', + class: 'secrets in public files', + live: true, + run: async ({ fetch }) => { + const paths = ['/.env', '/.env.local', '/.env.production', '/.git/config', '/.git/HEAD', '/package.json', '/pnpm-lock.yaml', '/next.config.ts', '/payload.config.ts', '/src/payload.config.ts', '/Dockerfile', '/docker-compose.yml', '/.DS_Store', '/api/media/file/..%2F..%2F.env', '/api/media/file/%2e%2e%2f%2e%2e%2fpackage.json', '/_next/static/..%2F..%2F.env', '/_next/../package.json'] + const open: string[] = [] + for (const path of paths) { + const a = await fetch(path) + if (a.status === 200 && /PAYLOAD_SECRET|DATABASE_URI|"dependencies"\s*:|\[core\]|^ref: refs\/|lockfileVersion|FROM node|buildConfig\(/m.test(a.text)) {open.push(path)} + if (a.status >= 500) {open.push(`${path} → ${a.status}`)} + } + return open.length ? bad(`served: ${open.join(', ')}`) : ok(`${paths.length} paths refused`) + }, + title: 'source, env and git files are not served (also through ../ in a file route)', + }, + { + id: 'bundle-secrets', + class: 'secrets in client bundles', + live: true, + run: async ({ fetch, page = '/', secrets = [] }) => { + const pages = [page, '/admin/login'] + const files = new Set() + for (const p of pages) { + const a = await fetch(p, { follow: true }) + for (const src of scriptSrcs(a.text)) {if (src.startsWith('/') && !src.startsWith('//')) {files.add(src)}} + } + if (!files.size) {return skip('no script files found on the pages')} + const found: string[] = [] + let maps = 0 + for (const file of files) { + const a = await fetch(file) + for (const [what, re] of SECRET_SHAPES) {if (re.test(a.text)) {found.push(`${file}: ${what}`)}} + for (const s of secrets) {if (s && s.length >= 8 && a.text.includes(s)) {found.push(`${file}: a server secret's value`)}} + if (maps < 3 && /\/_next\/static\/.+\.js$/.test(file)) { + maps++ + const map = await fetch(`${file.split('?')[0]}.map`) + if (map.status === 200 && /"sources"\s*:/.test(map.text)) {found.push(`${file}.map: source map is public (productionBrowserSourceMaps)`)} + } + } + return found.length ? bad(found.join('; ')) : ok(`${files.size} script files clean`) + }, + title: 'no secret (or a secret-shaped value) in the JavaScript the pages load; no public source maps', + }, + { + id: 'middleware-subrequest', + class: 'middleware / proxy bypass', + live: true, + run: async ({ fetch }) => { + const plain = await fetch('/') + if (plain.status < 300 || plain.status >= 400) {return skip(`/ answers ${describe(plain)} without the proxy redirecting (single locale?): nothing to compare`)} + const values = ['middleware:middleware:middleware:middleware:middleware', 'src/middleware:src/middleware:src/middleware:src/middleware:src/middleware', 'proxy:proxy:proxy:proxy:proxy', 'src/proxy:src/proxy:src/proxy:src/proxy:src/proxy', 'pages/_middleware'] + for (const v of values) { + const a = await fetch('/', { headers: { 'x-middleware-subrequest': v } }) + if (a.status !== plain.status) {return bad(`x-middleware-subrequest: ${v} changed / from ${plain.status} to ${describe(a)}: the proxy was skipped (CVE-2025-29927 class — upgrade Next)`)} + } + return ok(`the proxy ran for all ${values.length} header values`) + }, + title: 'x-middleware-subrequest does not skip the proxy (CVE-2025-29927 class)', + }, + { + id: 'open-redirect', + class: 'open redirect', + live: true, + run: async ({ base, fetch }) => { + const paths = [`//${EVIL}/`, `/%2F%2F${EVIL}`, `/\\${EVIL}`, `/%5C${EVIL}`, `/%09/${EVIL}`, `/admin/login?redirect=https://${EVIL}/`, `/admin?redirect=//${EVIL}`, `/api/ipal/admin-language?lng=en`] + const away: string[] = [] + for (const path of paths) { + const a = await fetch(path, { headers: path.includes('admin-language') ? { referer: `https://${EVIL}/admin` } : {} }) + const location = a.headers.get('location') + if (a.status >= 300 && a.status < 400 && !sameHost(location, base)) {away.push(`${path} → ${location}`)} + if (a.status >= 500) {away.push(`${path} → ${a.status}`)} + } + return away.length ? bad(away.join('; ')) : ok(`${paths.length} paths stay on the site`) + }, + title: 'no path, parameter or Referer sends the browser to another host', + }, + { + id: 'host-header', + class: 'cache poisoning (host headers)', + live: true, + run: async ({ fetch, page = '/' }) => { + const headers = { forwarded: `host=${EVIL}`, 'x-forwarded-host': EVIL, 'x-host': EVIL, 'x-original-host': EVIL } + const redirect = await fetch('/', { headers }) + const location = redirect.headers.get('location') ?? '' + if (location.includes(EVIL)) {return bad(`/ redirects to ${location}: the redirect trusts X-Forwarded-Host`)} + const html = await fetch(page, { follow: true, headers }) + if (html.text.includes(EVIL)) {return bad(`${page} prints ${EVIL} (canonical, og:url, hreflang or a link): a cached page would carry it for everyone`)} + return ok('neither the redirect nor the page uses a host the request named') + }, + title: 'X-Forwarded-Host / Forwarded do not reach redirects or links in the page', + }, + { + id: 'markdown-vary', + class: 'cache poisoning (content negotiation)', + live: true, + run: async ({ fetch, page = '/' }) => { + const a = await fetch(page, { follow: true, headers: { accept: 'text/markdown' } }) + if (!/text\/markdown/.test(a.headers.get('content-type') ?? '')) {return skip(`${page} with Accept: text/markdown answers ${a.headers.get('content-type') ?? describe(a)} (no Markdown negotiation)`)} + const cc = a.headers.get('cache-control') ?? '' + const shared = /s-maxage|public/.test(cc) && !/private|no-store/.test(cc) + const vary = (a.headers.get('vary') ?? '').split(',').map((v) => v.trim().toLowerCase()) + if (shared && !vary.includes('accept') && !vary.includes('*')) {return bad(`${page} answers Markdown to Accept: text/markdown with "${cc}" and no Vary: Accept: a shared cache stores it under the HTML URL (IAPL 1.18.0's createProxy sends private + Vary: Accept; a proxy of your own must too)`)} + return ok('the Markdown answer at the HTML URL varies by Accept or is not shared') + }, + title: 'the Markdown copy at an HTML URL cannot be cached as the page', + }, + { + id: 'rsc-vary', + class: 'cache poisoning (RSC)', + live: true, + run: async ({ fetch, page = '/' }) => { + const a = await fetch(page, { follow: true, headers: { rsc: '1' } }) + if (!/text\/x-component/.test(a.headers.get('content-type') ?? '')) {return skip(`${page} with RSC: 1 is not a flight answer`)} + return /\brsc\b/i.test(a.headers.get('vary') ?? '') ? ok() : bad(`the flight answer of ${page} has no Vary: RSC (vary: ${a.headers.get('vary') ?? 'none'})`) + }, + title: 'the RSC (flight) answer of a page varies by the RSC header', + }, + { + id: 'login-operators', + class: 'injection (NoSQL operators)', + live: true, + run: async ({ fetch }) => { + const bodies = [{ email: { $ne: null }, password: { $ne: null } }, { email: { $gt: '' }, password: 'x' }, { email: 'a@b.pl', password: { $ne: 'x' } }] + for (const body of bodies) { + const a = await fetch('/api/users/login', { body: JSON.stringify(body), headers: { 'content-type': 'application/json' }, method: 'POST' }) + if (a.status === 200 || /"token"\s*:\s*"/.test(a.text)) {return bad(`login with ${JSON.stringify(body)} answered ${a.status} with a token`)} + if (a.status >= 500) {return bad(`login with ${JSON.stringify(body)} answered ${a.status}`)} + if (LEAK.test(a.text)) {return bad('the refused login answer carries a stack trace or a server path')} + } + return ok('operators in the e-mail or password are refused') + }, + title: 'a sign-in with $ne / $gt in it is refused (no account, no 500)', + }, + { + id: 'rest-where', + class: 'access control (REST where / drafts)', + live: true, + run: async ({ fetch }) => { + const problems: string[] = [] + for (const path of ['/api/users?where[email][exists]=true&limit=1', '/api/users?where[password][exists]=true&limit=1', '/api/users?where[or][0][roles][equals]=admin&limit=1', '/api/form-submissions?limit=1', '/api/payload-preferences?limit=1', '/api/payload-kv?limit=1']) { + const a = await fetch(path) + if (a.status === 404) {continue} + if (a.status >= 500) {problems.push(`${path} → ${a.status}`); continue} + if (a.status === 200 && /"docs"\s*:\s*\[\s*\{/.test(a.text)) {problems.push(`${path} → 200 with documents`)} + } + const drafts = await fetch('/api/pages?draft=true&where[_status][equals]=draft&limit=5&depth=0') + if (drafts.status === 200 && /"_status"\s*:\s*"draft"/.test(drafts.text)) {problems.push('/api/pages?draft=true returns drafts to an anonymous visitor')} + if (drafts.status >= 500) {problems.push(`/api/pages?draft=true… → ${drafts.status}`)} + const versions = await fetch('/api/pages/versions?limit=1&depth=0') + if (versions.status === 200 && /"docs"\s*:\s*\[\s*\{/.test(versions.text)) {problems.push('/api/pages/versions lists versions to an anonymous visitor')} + return problems.length ? bad(problems.join('; ')) : ok('accounts, submissions, preferences, drafts and versions stay closed to a where query') + }, + title: 'an anonymous where / draft / versions query reads no accounts, submissions or drafts', + }, + { + id: 'graphql', + class: 'access control (GraphQL)', + live: true, + run: async ({ fetch }) => { + const post = (query: string) => fetch('/api/graphql', { body: JSON.stringify({ query }), headers: { 'content-type': 'application/json' }, method: 'POST' }) + const intro = await post('{ __schema { types { name } } }') + if (intro.status === 404) {return skip('no GraphQL route')} + if (intro.status === 200 && /"__schema"\s*:\s*\{/.test(intro.text)) {return bad('introspection answers in production: the whole schema is public')} + const syntax = await post('{ Pages(where: { ') + if (syntax.status >= 500 || LEAK.test(syntax.text)) {return bad(`a broken query answers ${syntax.status}${LEAK.test(syntax.text) ? ' with a stack trace' : ''}`)} + const get = await fetch(`/api/graphql?query=${encodeURIComponent('mutation { __typename }')}`) + if (get.status === 200 && /"data"\s*:\s*\{\s*"__typename"/.test(get.text)) {return bad('a mutation runs over GET (CSRF: a link or can run it with the visitor\'s cookie)')} + const users = await post('{ Users(limit: 1) { docs { email } } }') + if (users.status === 200 && /"email"\s*:\s*"/.test(users.text)) {return bad('an anonymous GraphQL query lists account e-mails')} + return ok('no introspection, no stack traces, no mutation over GET, no accounts') + }, + title: 'GraphQL: no introspection in production, no mutation over GET, no accounts, no stack traces', + }, + { + id: 'error-leak', + class: 'information disclosure (errors)', + live: true, + run: async ({ fetch }) => { + const paths = ['/api/pages/%27%22%3C%3E', '/api/pages?where[id][equals]=not-an-id', '/api/pages?depth=abc&limit=-1', '/api/pages?where[title][like][$regex]=.*', '/api/users/me', '/api/globals/does-not-exist', '/does-not-exist-%00'] + const problems: string[] = [] + for (const path of paths) { + const a = await fetch(path) + if (a.status >= 500) {problems.push(`${path} → ${a.status}`)} + if (LEAK.test(a.text)) {problems.push(`${path}: stack trace or server path in the answer`)} + } + return problems.length ? bad(problems.join('; ')) : ok(`${paths.length} malformed requests answered without a 500 or a stack trace`) + }, + title: 'malformed ids, sorts, depths and operators give a 4xx without a stack trace', + }, + { + id: 'sort-operator', + class: 'injection (operators in sort)', + live: true, + run: async ({ fetch }) => { + const problems: string[] = [] + for (const sort of ['%24where', '-%24where', '%24natural', 'title.%24ne']) { + const a = await fetch(`/api/pages?sort=${sort}&limit=1&depth=0`) + if (a.status >= 500 || LEAK.test(a.text)) {problems.push(`sort=${decodeURIComponent(sort)} → ${a.status}`)} + } + return problems.length ? bad(`${problems.join('; ')}: an operator name reaches the database as a sort field (an error and a logged stack trace per request; IAPL 1.18.0 refuses it unless refuseOperatorSort is false)`) : ok('operator names in sort are refused with a 4xx') + }, + title: 'an operator name in ?sort= is refused, not passed to the database', + }, + { + id: 'unbounded-list', + class: 'denial of service (unbounded queries)', + live: true, + run: async ({ fetch }) => { + const a = await fetch('/api/pages?limit=100000&depth=50') + if (a.status !== 200) {return skip(`/api/pages answers ${describe(a)}`)} + let body: { limit?: number } = {} + try { + body = JSON.parse(a.text) as typeof body + } catch { + return skip('not JSON') + } + return (body.limit ?? 0) > 1000 ? bad(`/api/pages?limit=100000 is honoured (limit ${body.limit}, ${a.ms} ms, ${a.text.length} bytes): one anonymous request reads a whole collection (IAPL 1.18.0 caps it unless listLimit is false or the collection is excluded)`) : ok(`limit capped at ${body.limit}`) + }, + title: 'a public list caps limit (and depth) so one request cannot read a whole collection', + }, + { + id: 'image-optimizer', + class: 'SSRF / image optimizer', + live: true, + run: async ({ fetch }) => { + const problems: string[] = [] + for (const url of ['http://169.254.169.254/latest/meta-data/', 'http://127.0.0.1:22/', `https://${EVIL}/x.png`, '//evil.example/x.png', '/api/media/file/x.svg']) { + const a = await fetch(`/_next/image?url=${encodeURIComponent(url)}&w=64&q=75`) + if (a.status === 200 && !/^image\/(?:png|jpe?g|webp|avif|gif)/.test(a.headers.get('content-type') ?? '')) {problems.push(`${url} → 200 ${a.headers.get('content-type')}`)} + if (a.status === 200 && /169\.254|127\.0\.0\.1|evil\.example/.test(url)) {problems.push(`${url} → 200: the optimizer fetched it`)} + // a missing local file is a 500 from Next's optimizer (it reports the upstream 404 so): not a door + if (a.status >= 500 && !url.startsWith('/api/media/')) {problems.push(`${url} → ${a.status}`)} + } + return problems.length ? bad(problems.join('; ')) : ok('inner addresses, foreign hosts and SVG are refused') + }, + title: '/_next/image refuses inner addresses, unlisted hosts and SVG', + }, + { + id: 'headers-everywhere', + class: 'security headers', + live: true, + run: async ({ fetch, page = '/' }) => { + const missing: string[] = [] + for (const path of [page, '/this-page-does-not-exist-iapl', '/api/health', '/api/pages?limit=1', '/admin/login']) { + const a = await fetch(path, { follow: true }) + if (!a.status) {continue} + const h = a.headers + const lacks = [ + ...(/nosniff/i.test(h.get('x-content-type-options') ?? '') ? [] : ['nosniff']), + ...(h.get('x-frame-options') || /frame-ancestors/.test(h.get('content-security-policy') ?? '') ? [] : ['frame protection']), + ...(h.get('x-powered-by') ? [`X-Powered-By: ${h.get('x-powered-by')}`] : []), + ] + if (lacks.length) {missing.push(`${path}: ${lacks.join(', ')}`)} + } + return missing.length ? bad(missing.join('; ')) : ok() + }, + title: 'pages, the 404 page, the API and the admin all carry nosniff and frame protection, no X-Powered-By', + }, + { + id: 'methods', + class: 'unexpected methods', + live: true, + run: async ({ fetch, page = '/' }) => { + const problems: string[] = [] + for (const method of ['TRACE', 'PUT', 'DELETE', 'PATCH']) { + const a = await fetch(page, { method }) + if (a.status >= 500) {problems.push(`${method} ${page} → ${a.status}`)} + if (method === 'TRACE' && a.status === 200 && /TRACE \//.test(a.text)) {problems.push('TRACE echoes the request')} + } + const action = await fetch(page, { body: '[]', headers: { 'content-type': 'text/plain;charset=UTF-8', 'next-action': '0'.repeat(42) }, method: 'POST' }) + if (action.status >= 500 || LEAK.test(action.text)) {problems.push(`an unknown Server Action id → ${action.status}`)} + return problems.length ? bad(problems.join('; ')) : ok() + }, + title: 'TRACE / PUT / DELETE on a page and an unknown Server Action id give no 500', + }, + { + id: 'body-size', + class: 'denial of service (body size)', + live: false, + run: async ({ fetch }) => { + const problems: string[] = [] + const big = JSON.stringify({ email: 'a@b.pl', pad: 'x'.repeat(8 * 1024 * 1024), password: 'x' }) + for (const path of ['/api/ipal/consent', '/api/csp-report', '/api/mcp', '/api/users/login', '/api/graphql']) { + const a = await fetch(path, { body: big, headers: { 'content-type': 'application/json' }, method: 'POST' }) + if (a.status === 404 || a.status === 405) {continue} + if (a.status >= 500 || a.status === 0) {problems.push(`${path} → ${describe(a)} after ${a.ms} ms`)} + else if (a.ms > 5000) {problems.push(`${path} took ${a.ms} ms for an 8 MB body`)} + } + return problems.length ? bad(problems.join('; ')) : ok('8 MB bodies refused or answered quickly') + }, + title: 'an 8 MB body to the public POST routes is refused quickly, never a 500', + }, +] + +/** Plain-fetch context for a site. */ +export function createProbeContext(base: string, options: { page?: string; secrets?: string[]; timeoutMs?: number; userAgent?: string } = {}): ProbeContext { + const origin = base.replace(/\/+$/, '') + return { + base: origin, + fetch: async (path, init = {}) => { + const started = Date.now() + try { + const res = await fetch(origin + path, { + body: init.body, + headers: { 'user-agent': options.userAgent ?? 'iapl-doctor probes (read-only)', ...init.headers }, + method: init.method ?? 'GET', + redirect: init.follow ? 'follow' : 'manual', + signal: AbortSignal.timeout(options.timeoutMs ?? 20_000), + }) + const text = init.method === 'HEAD' ? '' : await res.text() + return { headers: res.headers, ms: Date.now() - started, status: res.status, text } + } catch (err) { + const e = err as { cause?: { code?: string }; message?: string } + return { error: e.cause?.code ?? e.message ?? 'unreachable', headers: new Headers(), ms: Date.now() - started, status: 0, text: '' } + } + }, + page: options.page, + secrets: options.secrets, + } +} + +/** Runs the probes (default: those safe on a live site) and returns each result. */ +export async function runAttackProbes(ctx: ProbeContext, probes: AttackProbe[] = ATTACK_PROBES.filter((p) => p.live)): Promise> { + const out: Array<{ probe: AttackProbe; result: ProbeResult }> = [] + for (const probe of probes) { + let result: ProbeResult + try { + result = await probe.run(ctx) + } catch (err) { + result = bad(`probe crashed: ${err instanceof Error ? err.message : String(err)}`) + } + out.push({ probe, result }) + } + return out +} diff --git a/src/modules/security/createCspReportRoute.ts b/src/modules/security/createCspReportRoute.ts index 64d83d8..562d17a 100644 --- a/src/modules/security/createCspReportRoute.ts +++ b/src/modules/security/createCspReportRoute.ts @@ -1,3 +1,4 @@ +import { clientIp, consumeRateLimit } from '../shared/rateLimit.js' import { readCappedBody } from '../shared/readCappedBody.js' /** One CSP violation, normalised from either report format. */ @@ -15,12 +16,79 @@ export type CspViolation = { export type CreateCspReportRouteArgs = { /** Largest accepted body in bytes; bigger requests get 413. Default 16 KB. */ maxBytes?: number + /** Most violations handled from one request (a body may hold many). Default 10; the rest are dropped. */ + maxReports?: number /** * What to do with each violation. Default: one `console.warn` line per - * violation (Coolify keeps container logs — read them there). Plug in - * payload.logger, Sentry or a database write here. + * violation (Coolify keeps container logs — read them there), made by + * {@link cspLogLine}: origins and paths only, no control characters, every value + * capped — a report cannot write a line of its own into the log. Your own + * `onReport` gets the values exactly as the browser sent them: escape them + * before you log them. Plug in payload.logger, Sentry or a database write here. */ onReport?: (violation: CspViolation) => Promise | void + /** + * Requests per client (`clientIp`, IPv6 per /64) and window that are handled; over it the route still answers 204 + * and handles nothing. Default `{ max: 60, windowMs: 60_000 }`; `false` = no limit. + */ + rateLimit?: { max?: number; windowMs?: number } | false +} + +/** Longest value {@link cspLogLine} writes. */ +export const CSP_LOG_VALUE_MAX = 128 + +/** Control characters (new lines among them) and the Unicode line separators: never in a log line. */ +// eslint-disable-next-line no-control-regex +const CONTROL = /[\u0000-\u001f\u007f-\u009f\u2028\u2029]/g + +const clean = (value: string | undefined, max = CSP_LOG_VALUE_MAX): string => { + if (!value) {return '?'} + const text = value.replace(CONTROL, ' ').trim() + return text.length > max ? `${text.slice(0, max)}…` : text || '?' +} + +/** `https://cdn.x/a.js?q` → `https://cdn.x`; a keyword (`inline`, `eval`, `data`) stays as it is. */ +const originOf = (value: string | undefined): string | undefined => { + if (!value) {return undefined} + try { + const url = new URL(value) + return url.origin === 'null' ? `${url.protocol}` : url.origin + } catch { + return value + } +} + +/** `https://site.pl/pl/o-nas?x=1#y` → `/pl/o-nas` (no query: it may hold personal data). */ +const pathOf = (value: string | undefined): string | undefined => { + if (!value) {return undefined} + try { + return new URL(value).pathname + } catch { + return value.split(/[?#]/)[0] + } +} + +/** `https://cdn.x/a.js?q` → `https://cdn.x/a.js`: where the script lives, without its query. */ +const scriptOf = (value: string): string => { + try { + const url = new URL(value) + return url.origin === 'null' ? url.protocol : `${url.origin}${url.pathname}` + } catch { + return value.split(/[?#]/)[0] + } +} + +/** + * The default log line of one violation: the blocked resource's origin, the page's path, the script's origin and path + * with its line — control characters removed, every value at most {@link CSP_LOG_VALUE_MAX} characters (security + * audit 2026-12, F1). Use it in your own `onReport` for the same line. + */ +export function cspLogLine(v: CspViolation): string { + const source = v.sourceFile ? scriptOf(v.sourceFile) : '' + return ( + `[csp] ${clean(v.disposition ?? 'report', 16)} ${clean(v.effectiveDirective, 32)} blocked=${clean(originOf(v.blockedUri))} ` + + `page=${clean(pathOf(v.documentUri))}${source ? ` src=${clean(source)}:${typeof v.lineNumber === 'number' ? v.lineNumber : ''}` : ''}` + ) } type Raw = Record @@ -86,14 +154,19 @@ export function parseCspReports(body: unknown): CspViolation[] { export function createCspReportRoute(args: CreateCspReportRouteArgs = {}): (request: Request) => Promise { const { maxBytes = 16 * 1024, + maxReports = 10, onReport = (v: CspViolation) => { - console.warn( - `[csp] ${v.disposition ?? 'report'} ${v.effectiveDirective ?? '?'} blocked=${v.blockedUri ?? '?'} page=${v.documentUri ?? '?'}${v.sourceFile ? ` src=${v.sourceFile}:${v.lineNumber ?? ''}` : ''}`, - ) + console.warn(cspLogLine(v)) }, + rateLimit = {}, } = args return async (request: Request) => { + if (rateLimit) { + const { ok } = await consumeRateLimit({ key: clientIp(request), max: rateLimit.max ?? 60, scope: 'csp-report', windowMs: rateLimit.windowMs ?? 60_000 }) + // the browser does not read the answer: 204 either way, nothing handled + if (!ok) {return new Response(null, { status: 204 })} + } // read only up to the cap, whether or not the browser declared the length (a chunked body has none) let text: null | string try { @@ -110,7 +183,7 @@ export function createCspReportRoute(args: CreateCspReportRouteArgs = {}): (requ return new Response(null, { status: 400 }) } - for (const violation of parseCspReports(body).slice(0, 50)) { + for (const violation of parseCspReports(body).slice(0, Math.max(0, maxReports))) { try { await onReport(violation) } catch { diff --git a/src/modules/security/index.ts b/src/modules/security/index.ts index 48ad412..31b0ad5 100644 --- a/src/modules/security/index.ts +++ b/src/modules/security/index.ts @@ -10,7 +10,7 @@ export { export type { BuildAdminCspArgs, BuildCspArgs, CspDirective, CspSources } from './buildCsp.js' export { buildSecurityHeaders, buildUploadSecurityHeaders, UPLOAD_SECURITY_HEADERS } from './buildSecurityHeaders.js' export type { BuildSecurityHeadersArgs, SecurityHeader } from './buildSecurityHeaders.js' -export { createCspReportRoute, parseCspReports } from './createCspReportRoute.js' +export { createCspReportRoute, CSP_LOG_VALUE_MAX, cspLogLine, parseCspReports } from './createCspReportRoute.js' export type { CreateCspReportRouteArgs, CspViolation } from './createCspReportRoute.js' export { createCspNonce, CSP_NONCE_HEADER } from './cspNonce.js' export { totpAdminPath, totpRedirectTarget } from './totp/totpRedirect.js' diff --git a/src/modules/security/queryGuard.ts b/src/modules/security/queryGuard.ts new file mode 100644 index 0000000..d54235a --- /dev/null +++ b/src/modules/security/queryGuard.ts @@ -0,0 +1,143 @@ +import type { Access, CollectionBeforeOperationHook, CollectionConfig, Config, PayloadRequest, SanitizedConfig } from 'payload' + +import { APIError } from 'payload' + +import { staffCollectionSlugs } from '../access/predicates.js' +import { secondFactorPassed } from './totp/secondFactor.js' + +/** + * Guards for what a REST / GraphQL caller may ask of a collection list (security audit 2026-12, F4 and F5), and + * Payload's document locks closed to visitor accounts (the "document locks" door). Each is on by default, each can be + * turned off or adapted, and every piece is exported for a project's own use (docs/security.md "Lists and sorting"). + * + * Local API calls (`req.payloadAPI === 'local'`: the frontend, seeds, the project's own code) are never touched. + */ + +export type ListLimitOptions = { + /** Collections left as Payload has them (their lists take any `limit`). */ + exclude?: string[] + /** Largest page a caller that is not staff gets. Default 100. */ + max?: number + /** Cap staff accounts too (the panel asks for at most 100 per page itself). Default false. */ + staff?: boolean +} + +export const DEFAULT_LIST_LIMIT = 100 + +type HookArgs = Parameters[0] +type ListArgs = { id?: unknown; limit?: number | string; pagination?: boolean | string; sort?: unknown } + +const fromOutside = (req: PayloadRequest | undefined): boolean => + Boolean(req) && (req as { payloadAPI?: string }).payloadAPI !== 'local' + +/** True when the request's account belongs to a staff collection (any role). */ +export function isStaffRequest(req: Pick | undefined): boolean { + const slug = (req?.user as { collection?: unknown } | null | undefined)?.collection + return typeof slug === 'string' && staffCollectionSlugs(req?.payload).includes(slug) +} + +/** + * The list arguments with `limit` at most `max` and pagination on — what a caller that is not staff gets. Pure: the + * hook below calls it, a project's own endpoint can too. + */ +export function capListLimit(args: T, max: number = DEFAULT_LIST_LIMIT): T { + // REST hands the query string over as text: '100000', 'false' + const raw = typeof args.limit === 'string' && (args.limit).trim() !== '' ? Number(args.limit) : args.limit + const limit = typeof raw === 'number' && Number.isFinite(raw) ? raw : undefined + const noPages = args.pagination === false || (args.pagination as unknown) === 'false' + // pagination: false and limit 0 both mean "everything" to Payload + if (noPages || limit === 0 || (limit !== undefined && limit > max)) { + return { ...args, limit: limit && limit > 0 ? Math.min(limit, max) : max, pagination: true } + } + return args +} + +/** A sort field that names a database operator (`$where`, `-$natural`, `title.$ne`): never a field of a document. */ +export function isOperatorSort(sort: unknown): boolean { + const names = Array.isArray(sort) ? sort : typeof sort === 'string' ? sort.split(',') : [] + return names.some((n) => typeof n === 'string' && /(?:^-?|\.)\$/.test(n.trim())) +} + +/** + * The 400 for an operator sort name. Its own name so Payload logs it as one `info` line without a stack (the plugin + * sets `loggingLevels.RefusedSortError: 'info'` unless the project set it; `false` logs nothing). + */ +export class RefusedSortError extends APIError { + constructor() { + super('This sort field is not allowed.', 400, null, true) + this.name = 'RefusedSortError' + } +} + +/** Marks the hook {@link buildQueryGuardHook} made, like the plugin's other hooks (`Symbol.for('iapl.…')`). */ +export const QUERY_GUARD_MARK = Symbol.for('iapl.queryGuard') + +const LIST_OPERATIONS = new Set(['findVersions', 'read', 'readDistinct']) + +/** + * One `beforeOperation` hook for lists from outside: refuses a database operator as a sort field with 400 (instead of + * a 500 and a logged stack trace, F5) and caps `limit` for callers that are not staff (F4). `listLimit: false` or + * `refuseOperatorSort: false` turns that half off. + */ +export function buildQueryGuardHook(options: { + listLimit?: false | ListLimitOptions + refuseOperatorSort?: boolean +}): CollectionBeforeOperationHook { + const limit = options.listLimit === false ? null : { max: DEFAULT_LIST_LIMIT, staff: false, ...options.listLimit } + const refuseSort = options.refuseOperatorSort !== false + const iaplQueryGuard = (({ args, collection, operation, req }: HookArgs) => { + if (!LIST_OPERATIONS.has(operation) || !fromOutside(req)) {return args} + const list = args as ListArgs + if (refuseSort && isOperatorSort(list.sort)) { + throw new RefusedSortError() + } + if (!limit || list.id != null || limit.exclude?.includes(collection.slug)) {return args} + if (!limit.staff && isStaffRequest(req)) {return args} + return capListLimit(list, limit.max) + }) as CollectionBeforeOperationHook + return Object.assign(iaplQueryGuard, { [QUERY_GUARD_MARK]: true }) +} + +/** True for a hook {@link buildQueryGuardHook} made: for tests and tools that count a collection's hooks. */ +export const isQueryGuardHook = (hook: unknown): boolean => typeof hook === 'function' && Boolean((hook as unknown as Record)[QUERY_GUARD_MARK]) + +/** The hook added to every collection of the config (the project's, the plugin's, other plugins' before iapl). */ +export function applyQueryGuard( + config: Config, + options: { listLimit?: false | ListLimitOptions; refuseOperatorSort?: boolean }, +): Config { + if (options.listLimit === false && options.refuseOperatorSort === false) {return config} + const hook = buildQueryGuardHook(options) + return { + ...config, + collections: (config.collections ?? []).map((c) => ({ + ...c, + hooks: { ...c.hooks, beforeOperation: [...(c.hooks?.beforeOperation ?? []), hook] }, + })), + // Payload's ErrorName union knows only its own errors; the name is looked up by string at log time + loggingLevels: { ...({ RefusedSortError: 'info' } as NonNullable), ...config.loggingLevels }, + } +} + +/** Payload's collection of document locks ("who edits what"). */ +export const LOCKED_DOCUMENTS_SLUG = 'payload-locked-documents' + +/** + * Staff accounts (with their second factor, when 2FA is on) — who edits in the panel. Payload's default for its + * document locks is any signed-in account, so a visitor account (a shop's customers) could read who edits what and + * write or delete locks. + */ +export const staffOnlyLocks: Access = ({ req }) => isStaffRequest(req) && secondFactorPassed({ payload: req.payload, user: req.user }) + +export type LockedDocumentsAccess = Partial, 'create' | 'delete' | 'read' | 'update'>> + +/** + * Payload adds its document-lock collection after every plugin has run, so its rules are set on the live config + * (onInit and after a dev reload). `access` keys the project gives win; the rest is {@link staffOnlyLocks}. + */ +export function applyLockedDocumentsAccess(config: Pick, access: LockedDocumentsAccess = {}): boolean { + const locks = config.collections?.find((c) => c.slug === LOCKED_DOCUMENTS_SLUG) + if (!locks) {return false} + locks.access = { ...locks.access, create: staffOnlyLocks, delete: staffOnlyLocks, read: staffOnlyLocks, update: staffOnlyLocks, ...access } + return true +} diff --git a/src/modules/shared/accessAnswer.ts b/src/modules/shared/accessAnswer.ts index 285cc1c..2737d57 100644 --- a/src/modules/shared/accessAnswer.ts +++ b/src/modules/shared/accessAnswer.ts @@ -1,30 +1,50 @@ /** * The answer of a project's access callback (`cookieScanner.access`, the doctor's `access`), read the same way - * everywhere (owner's decision Q4, 1.18.0). + * everywhere (owner's decisions Q4 and "Tak, w 1.18.0"). * - * Today any truthy answer lets the request in, as before: `({ req }) => req.user` returns an account object, and - * a function that returns `'no'` or `{}` lets the request in too. From the next minor version only `true` will - * allow. Until then the first answer that is not a boolean is reported once per option in the server log, so a - * project sees it before the change. (A callback needs a request to be asked, so this cannot be checked at start: - * the warning comes with the first call.) + * Since 1.18.0 only a literal `true` allows. `({ req }) => req.user` returns an account object and is now REFUSED; + * so are `1`, `'yes'`, `{}` and a Promise that was not awaited. The first answer that is not a boolean is reported + * once per option in the server log, naming the option and the fix. (A callback needs a request to be asked, so + * this cannot be checked at start: the report comes with the first call.) + * + * A project that needs the old reading back sets `iapl({ strictAccessAnswers: false })`: any truthy answer allows + * again (still reported once per option). */ const warned = new Set() export type AccessAnswerOptions = { + /** Only a literal `true` allows (default). `false` = any truthy answer allows, as before 1.18.0. */ + strict?: boolean /** Where to report (default `console.warn`). */ warn?: (message: string) => void } -/** True when the request may pass; warns once per `option` when the answer is not a boolean. */ -export function accessAllowed(option: string, answer: unknown, { warn = (m) => console.warn(m) }: AccessAnswerOptions = {}): boolean { +const kindOf = (answer: unknown): string => { + if (answer === null) {return 'null'} + if (Array.isArray(answer)) {return 'an array'} + if (answer && typeof (answer as { then?: unknown }).then === 'function') {return 'a Promise (not awaited)'} + if (typeof answer === 'object') {return 'an object'} + return /^[aeiou]/.test(typeof answer) ? `an ${typeof answer}` : `a ${typeof answer}` +} + +/** True when the request may pass; reports once per `option` when the answer is not a boolean. */ +export function accessAllowed(option: string, answer: unknown, { strict = true, warn = (m) => console.warn(m) }: AccessAnswerOptions = {}): boolean { + const allowed = strict ? answer === true : Boolean(answer) if (typeof answer !== 'boolean' && !warned.has(option)) { warned.add(option) - const kind = answer === null ? 'null' : Array.isArray(answer) ? 'an array' : typeof answer === 'object' ? 'an object' : `a ${typeof answer}` warn( - `[iapl] ${option} returned ${kind}, not true or false. It is still read as ${answer ? 'allowed' : 'refused'}; from the next minor version only \`true\` allows. Return a boolean, e.g. \`({ req }) => Boolean(req.user)\` (docs/security.md "Access callbacks").`, + `[iapl] ${option} returned ${kindOf(answer)}, not true or false, so the request was ${allowed ? 'allowed' : 'refused'}` + + `${strict ? ' (only `true` allows since 1.18.0)' : ' (strictAccessAnswers: false reads any truthy answer as allowed)'}. ` + + 'Return a boolean, e.g. `({ req }) => Boolean(req.user)` (docs/security.md "Access callbacks").', ) } - return Boolean(answer) + return allowed +} + +/** Whether the config behind this request reads access answers strictly (`strictAccessAnswers`, default true). */ +export function strictAccessAnswers(req: { payload?: { config?: { custom?: Record } } } | undefined): boolean { + const iapl = req?.payload?.config?.custom?.iapl as { strictAccessAnswers?: boolean } | undefined + return iapl?.strictAccessAnswers !== false } /** For tests: forget which options were reported. */ diff --git a/src/modules/shared/switches.ts b/src/modules/shared/switches.ts index 2210e15..774eaeb 100644 --- a/src/modules/shared/switches.ts +++ b/src/modules/shared/switches.ts @@ -80,6 +80,19 @@ export function assertPluginSwitches(options: Record): void { assertSwitchOrObject(name, options[name]) } assertBooleanSwitch('indexNow', options.indexNow) + // 1.18.0 (security audit): `listLimit: 0` / `'false'` must not read as off; a max below 1 caps every list to nothing + assertSwitchOrObject('listLimit', options.listLimit, { allowTrue: false }) + const listLimit = bag(options.listLimit) + if (listLimit) { + assertNumberSwitch('listLimit.max', listLimit.max, { min: 1 }) + assertBooleanSwitch('listLimit.staff', listLimit.staff) + if (listLimit.exclude !== undefined && !(Array.isArray(listLimit.exclude) && listLimit.exclude.every((c) => typeof c === 'string'))) { + throw new Error(`${where('listLimit.exclude')} must be a list of collection slugs such as ['products'] (received ${JSON.stringify(listLimit.exclude)}).`) + } + } + assertBooleanSwitch('refuseOperatorSort', options.refuseOperatorSort) + assertSwitchOrObject('lockedDocuments', options.lockedDocuments, { allowTrue: false }) + assertBooleanSwitch('strictAccessAnswers', options.strictAccessAnswers) // 1.17.2: `adminSameOrigin: 0` / `'false'` must not read as off (it took the origin check off the panel actions) assertSwitchOrObject('adminSameOrigin', options.adminSameOrigin) const adminSameOrigin = bag(options.adminSameOrigin) diff --git a/src/plugin.ts b/src/plugin.ts index 903c9ec..dd7c78a 100644 --- a/src/plugin.ts +++ b/src/plugin.ts @@ -53,6 +53,7 @@ import { serverText } from './modules/integrations/texts.js' import { buildSystemPagesFields } from './modules/pages/index.js' import { guardAdminEndpoints } from './modules/security/adminSameOrigin.js' import { jobsRunNotice, withJobsRunAccess } from './modules/security/jobsAccess.js' +import { applyLockedDocumentsAccess, applyQueryGuard } from './modules/security/queryGuard.js' import { buildEnrolmentEndpoints, buildTotpNoticeHooks, resolveConfirmByEmail, startEnrolment } from './modules/security/totp/enrolmentConfirm.js' import { missingImportMapEntries } from './modules/security/totp/importMapCheck.js' import { changedViewKeys, copyViews, SAFE_TOTP_VIEW, wrapTotpViews } from './modules/security/totp/safeBack.js' @@ -229,6 +230,8 @@ export const iapl = (options: IaplOptions): Plugin => { const adoptConfig = (payload: BasePayload) => { const token = (payload.config.custom as { ipal?: { staffToken?: object } } | undefined)?.ipal?.staffToken registerStaffCollections(payload, staffCollectionSlugs(payload), token) + // Payload adds its document-lock collection after every plugin: its rules are set on the live config. + if (options.lockedDocuments !== false) {applyLockedDocumentsAccess(payload.config, options.lockedDocuments?.access)} // Auth collections a plugin listed after iapl added: the account rules for them too — BEFORE the // 2FA guard below wraps their access (it needs the rule inside its wrapper). if (accounts) { @@ -1064,6 +1067,14 @@ export const iapl = (options: IaplOptions): Plugin => { config = guardConfigAccess(config) } + // --- access callbacks read strictly (only `true` allows) unless the project asked for the old reading --- + if (options.strictAccessAnswers === false) { + config.custom = { ...config.custom, iapl: { ...(config.custom as { iapl?: object } | undefined)?.iapl, strictAccessAnswers: false } } + } + + // --- lists from outside: operator sort names refused, page size capped for non-staff (audit F5, F4) --- + config = applyQueryGuard(config, { listLimit: options.listLimit, refuseOperatorSort: options.refuseOperatorSort }) + // --- hooks: onInit --- const incomingOnInit = config.onInit config.onInit = async (payload) => { diff --git a/src/types.ts b/src/types.ts index 7f6247e..3c347c1 100644 --- a/src/types.ts +++ b/src/types.ts @@ -1,6 +1,7 @@ import type { CollectionSlug, Field, PayloadComponent, PayloadRequest, Plugin } from 'payload' import type { SignInLookOptions } from './modules/branding/signIn/options.js' +import type { ListLimitOptions, LockedDocumentsAccess } from './modules/security/queryGuard.js' /** * Factory shape of @clocklimited/payload-2fa's `payloadTotp` export — injected @@ -237,6 +238,23 @@ export type IaplOptions = { */ lightbox?: boolean + /** + * Public lists are capped (security audit 2026-12, F4): a REST / GraphQL `find` (also versions and distinct values) + * from a caller that is not staff gets at most `max` (100) documents per request, and `pagination=false` / `limit=0` + * become one page of `max`. Staff accounts and the Local API (the frontend, seeds) are not touched. + * `false` = Payload's behaviour (any limit); `{ max, staff: true, exclude: ['slug'] }` adapts it. + * docs/security.md "Lists and sorting". + */ + listLimit?: false | ListLimitOptions + + /** + * Payload's document locks ("who edits what", `payload-locked-documents`) are for staff accounts only (with the + * second factor when 2FA is on). Payload's default lets any signed-in account in — also a visitor account of a + * login collection for customers. `false` = Payload's default; `{ access: { read, create, update, delete } }` + * sets your own rule per operation (the rest stays staff only). docs/security.md "Lists and sorting". + */ + lockedDocuments?: { access?: LockedDocumentsAccess } | false + /** * E-mail (docs/email.md). A site with no SMTP server in Site integrations sends through the * Intecion Notifications Webservice: it enrols by itself on its first send (an outbound call with @@ -259,6 +277,13 @@ export type IaplOptions = { */ pages?: PagesOption + /** + * A REST / GraphQL `sort` that names a database operator (`$where`, `-$natural`, `title.$ne`) is refused with 400 + * instead of reaching the database (a 500 and a logged stack trace on MongoDB; security audit 2026-12, F5). Default + * true; `false` = Payload's behaviour. The Local API is not touched. + */ + refuseOperatorSort?: boolean + /** * next/cache `revalidatePath`, INJECTED (the plugin never imports next/cache). * When given, saving any of the plugin's globals (Site Settings, Site @@ -297,8 +322,8 @@ export type IaplOptions = { * follows the new server. docs/security.md "Stored secrets". */ secrets?: { reenterOnChange?: false; writeOnly?: false } - seo?: SeoOption + seo?: SeoOption /** Additional fields injected into SiteSettings global */ siteSettingsFields?: Field[] @@ -326,6 +351,14 @@ export type IaplOptions = { */ storageNames?: StorageNames + /** + * How a project's access callback is read (`cookieScanner.access`, the doctor's `access`): since 1.18.0 only a + * literal `true` allows; `({ req }) => req.user` (an object), `1`, `'yes'` or an un-awaited Promise refuse. An answer + * that is not a boolean is reported once per option in the server log. `false` = any truthy answer allows, as before + * 1.18.0 (still reported). docs/security.md "Access callbacks". + */ + strictAccessAnswers?: boolean + /** * Light / dark theme. `storageKey`: the localStorage key of the visitor's * choice — default `theme` (the next-themes key and values, so a project using diff --git a/test/accessAnswer.test.ts b/test/accessAnswer.test.ts index 99dc14b..92d753a 100644 --- a/test/accessAnswer.test.ts +++ b/test/accessAnswer.test.ts @@ -1,12 +1,12 @@ /** - * Access callbacks of a project (`cookieScanner.access`, the doctor's `access`), owner's decision Q4, 1.18.0: - * still allowed on any truthy answer, but an answer that is not a boolean is reported once per option, so a - * project sees it before the next minor version allows only `true`. Every call site goes through one function. + * Access callbacks of a project (`cookieScanner.access`, the doctor's `access`), owner's decision for 1.18.0: only a + * literal `true` allows; an answer that is not a boolean is reported once per option; `strictAccessAnswers: false` + * gives the old truthy reading back. Every call site goes through one function. */ import { readFileSync } from 'node:fs' import { beforeEach, describe, expect, test, vi } from 'vitest' -import { accessAllowed, resetAccessWarnings } from '../src/modules/shared/accessAnswer.js' +import { accessAllowed, resetAccessWarnings, strictAccessAnswers } from '../src/modules/shared/accessAnswer.js' beforeEach(() => resetAccessWarnings()) @@ -18,19 +18,47 @@ describe('accessAllowed', () => { expect(warn).not.toHaveBeenCalled() }) - test.each([ - [{ id: 1 }, true, 'an object'], - ['no', true, 'a string'], - [1, true, 'a number'], - [null, false, 'null'], - [undefined, false, 'a undefined'], - ])('%j is read as before (%s) and reported once', (answer, allowed, kind) => { + // the owner's decision for 1.18.0: only a literal `true` allows (the old reading in the third column) + const answers: [string, unknown, boolean, string][] = [ + ['an object (req.user)', { id: 1 }, true, 'an object'], + ['1', 1, true, 'a number'], + ['a string', 'yes', true, 'a string'], + ['null', null, false, 'null'], + ['undefined', undefined, false, 'an undefined'], + ] + + test.each(answers)('%s refuses (strict, the default) and is reported once, naming the option and the fix', (_, answer, _old, kind) => { const warn = vi.fn() - expect(accessAllowed('doctor.access', answer, { warn })).toBe(allowed) - expect(accessAllowed('doctor.access', answer, { warn })).toBe(allowed) + expect(accessAllowed('doctor.access', answer, { warn })).toBe(false) + expect(accessAllowed('doctor.access', answer, { warn })).toBe(false) expect(warn).toHaveBeenCalledTimes(1) expect(warn.mock.calls[0][0]).toContain(`doctor.access returned ${kind}`) - expect(warn.mock.calls[0][0]).toContain('only `true` allows') + expect(warn.mock.calls[0][0]).toContain('Boolean(req.user)') + }) + + test.each(answers)('%s with strictAccessAnswers: false is read as before 1.18.0 (truthy allows)', (_, answer, old) => { + expect(accessAllowed('cookieScanner.access', answer, { strict: false, warn: vi.fn() })).toBe(old) + }) + + test('a Promise is never `true`: an un-awaited answer refuses, whatever it holds', () => { + const warn = vi.fn() + for (const value of [true, { id: 1 }, 1, 'yes']) { + const p = Promise.resolve(value) + expect(accessAllowed('doctor.access', p, { warn })).toBe(false) + } + expect(warn.mock.calls[0][0]).toContain('a Promise (not awaited)') + }) + + test('async callbacks: the call sites await the answer, so a Promise of each reads like the value itself', async () => { + const asCalled = async (cb: () => Promise) => accessAllowed('cookieScanner.access', await cb(), { warn: vi.fn() }) + expect(await asCalled(async () => true)).toBe(true) + for (const value of [{ id: 1 }, 1, 'yes', false, null]) {expect(await asCalled(async () => value)).toBe(false)} + }) + + test('strictAccessAnswers(req) reads the option from the request\'s config', () => { + expect(strictAccessAnswers(undefined)).toBe(true) + expect(strictAccessAnswers({ payload: { config: { custom: {} } } })).toBe(true) + expect(strictAccessAnswers({ payload: { config: { custom: { iapl: { strictAccessAnswers: false } } } } })).toBe(false) }) test('each option is reported on its own', () => { @@ -47,6 +75,6 @@ test('every call of a project access callback goes through accessAllowed', () => const text = readFileSync(file, 'utf8') const calls = text.match(/await options\.access\(\{ req \}\)/g) ?? [] expect(calls.length, file).toBeGreaterThan(0) - expect(text.match(/accessAllowed\('[\w.]+', await options\.access\(\{ req \}\)\)/g)?.length, file).toBe(calls.length) + expect(text.match(/accessAllowed\('[\w.]+', await options\.access\(\{ req \}\), \{ strict: strictAccessAnswers\(req\) \}\)/g)?.length, file).toBe(calls.length) } }) diff --git a/test/accountRulesSuite.ts b/test/accountRulesSuite.ts index 081deec..6fc54eb 100644 --- a/test/accountRulesSuite.ts +++ b/test/accountRulesSuite.ts @@ -34,7 +34,7 @@ import { totp } from './http/totp.js' * service what Payload's own account mail is (modules/email/relay/accountMail.ts): that one is not counted here. */ // the account-mail hooks (the relay's kind mark, the after-commit hold) and the sign-in rules (1.18.0) are not the password rule -const ruleHook = (hook: unknown) => !(hook as Record)[Symbol.for('iapl.accountMailMark')] && !(hook as Record)[Symbol.for('iapl.accountMailAfterCommit')] && !(hook as Record)[Symbol.for('iapl.signInRules')] +const ruleHook = (hook: unknown) => !(hook as Record)[Symbol.for('iapl.accountMailMark')] && !(hook as Record)[Symbol.for('iapl.accountMailAfterCommit')] && !(hook as Record)[Symbol.for('iapl.signInRules')] && !(hook as Record)[Symbol.for('iapl.queryGuard')] const TOTP_SECRET = 'JBSWY3DPEHPK3PXP' diff --git a/test/iawlIdeasB.test.ts b/test/iawlIdeasB.test.ts index 9777faf..9333ea4 100644 --- a/test/iawlIdeasB.test.ts +++ b/test/iawlIdeasB.test.ts @@ -130,6 +130,14 @@ describe('switches refuse nonsense at start', () => { ['mail.relay', { mail: { relay: 'off' } }], ['storageNames', { storageNames: 'IAPL' }], ['forms.attachments.submit.maxPerMinute', { forms: { attachments: { submit: { maxPerMinute: 'off' } } } }], + // 1.18.0, security audit fixes: none of these may read as "off" + ['listLimit', { listLimit: 0 }], + ['listLimit', { listLimit: 'false' }], + ['listLimit.max', { listLimit: { max: 0 } }], + ['listLimit.exclude', { listLimit: { exclude: 'products' } }], + ['refuseOperatorSort', { refuseOperatorSort: 'false' }], + ['lockedDocuments', { lockedDocuments: 0 }], + ['strictAccessAnswers', { strictAccessAnswers: 'false' }], ])('%s: %j fails at start', async (name, options) => { expect(await start(options)).toThrow(name) }) diff --git a/test/queryGuardHttp.test.ts b/test/queryGuardHttp.test.ts new file mode 100644 index 0000000..16e38ce --- /dev/null +++ b/test/queryGuardHttp.test.ts @@ -0,0 +1,112 @@ +/** + * Lists from outside (1.18.0; security audit 2026-12, findings F4 and F5) and Payload's document locks for staff only + * (the "document locks" door), over real HTTP: Payload's REST and GraphQL handlers behind a server, a visitor login + * collection next to the staff one. + */ +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 { iapl } from '../src/plugin.js' +import { buildTestConfig } from './helpers.js' +import { testDatabase } from './http/db.js' +import { cookiesOf, startPayloadServer, type TestServer } from './http/server.js' + +vi.mock('server-only', () => ({})) +vi.mock('next/headers.js', async () => (await import('./http/server.js')).nextHeadersMock) + +const PASSWORD = 'a-long-test-password-1' +let server: TestServer +let payload: Payload +let base = '' +let editor = '' +let customer = '' + +const signIn = async (collection: string, email: string) => { + const res = await fetch(`${base}/api/${collection}/login`, { body: JSON.stringify({ email, password: PASSWORD }), headers: { 'content-type': 'application/json', origin: base }, method: 'POST' }) + expect(res.status).toBe(200) + return cookiesOf(res).join('; ') +} +const get = async (path: string, cookie = '') => { + const res = await fetch(`${base}${path}`, { headers: { cookie, origin: base } }) + return { body: (await res.json().catch(() => ({}))) as { docs?: unknown[]; limit?: number }, status: res.status } +} + +beforeAll(async () => { + const config = buildTestConfig({ + admin: { user: 'users' }, + collections: [ + { slug: 'notes', access: { read: () => true }, fields: [{ name: 'title', type: 'text' }] }, + { slug: 'customers', access: { create: () => false }, auth: true, fields: [] }, + { slug: 'media', fields: [], upload: { staticDir: path.join(os.tmpdir(), 'ipal-test-media') } }, + ], + db: testDatabase('query_guard'), + editor: lexicalEditor(), + plugins: [iapl({ access: { authCollection: 'users' }, i18n: { defaultLocale: 'pl', locales: [{ code: 'pl', label: 'Polski' }] }, twoFactor: false })], + secret: 'integration-test-secret-0123456789', + telemetry: false, + }) + payload = await getPayload({ config }) + server = await startPayloadServer(config) + base = server.url + for (let i = 0; i < 130; i++) {await payload.create({ collection: 'notes' as never, data: { title: `n${i}` } as never })} + await payload.create({ collection: 'users' as never, data: { email: 'editor@example.com', password: PASSWORD, roles: ['editor'] } as never }) + await payload.create({ collection: 'customers' as never, data: { email: 'customer@example.com', password: PASSWORD } as never, overrideAccess: true }) + editor = await signIn('users', 'editor@example.com') + customer = await signIn('customers', 'customer@example.com') +}, 180_000) + +afterAll(async () => { + await server?.close() + await payload?.destroy?.() +}) + +describe('F4: public lists are capped for callers that are not staff', () => { + test('anonymous and a customer get at most 100; pagination=false and limit=0 too', async () => { + for (const cookie of ['', customer]) { + for (const q of ['limit=100000', 'pagination=false', 'limit=0']) { + const { body, status } = await get(`/api/notes?${q}&depth=0`, cookie) + expect([q, status, body.docs?.length]).toEqual([q, 200, 100]) + } + } + expect((await get('/api/notes?limit=5')).body.docs).toHaveLength(5) + }) + + test('staff and the Local API are not capped', async () => { + expect((await get('/api/notes?limit=1000&depth=0', editor)).body.docs).toHaveLength(130) + expect((await payload.find({ collection: 'notes' as never, limit: 1000 })).docs).toHaveLength(130) + }) + + test('GraphQL lists from outside are capped as well', async () => { + const res = await fetch(`${base}/api/graphql`, { body: JSON.stringify({ query: '{ Notes(limit: 100000) { docs { id } } }' }), headers: { 'content-type': 'application/json', origin: base }, method: 'POST' }) + const body = (await res.json()) as { data?: { Notes?: { docs: unknown[] } } } + expect(body.data?.Notes?.docs).toHaveLength(100) + }) +}) + +describe('F5: an operator name in ?sort= is refused', () => { + test('$where, -$where, $natural and a.$ne answer 400 — anonymous and staff alike; a field name still sorts', async () => { + for (const cookie of ['', editor]) { + for (const sort of ['%24where', '-%24where', '%24natural', 'title.%24ne']) { + expect([sort, (await get(`/api/notes?sort=${sort}&limit=1`, cookie)).status]).toEqual([sort, 400]) + } + } + expect((await get('/api/notes?sort=-title&limit=1')).status).toBe(200) + }) +}) + +describe('Payload\'s document locks are for staff only', () => { + test('a customer is refused on every operation; an editor works as before', async () => { + const page = (await payload.find({ collection: 'notes' as never, limit: 1 })).docs[0] as { id: number | string } + const lock = { document: { relationTo: 'notes', value: page.id }, user: { relationTo: 'customers', value: 1 } } + const asCustomer = { 'content-type': 'application/json', cookie: customer, origin: base } + expect((await fetch(`${base}/api/payload-locked-documents`, { headers: asCustomer })).status).toBe(403) + expect((await fetch(`${base}/api/payload-locked-documents`, { body: JSON.stringify(lock), headers: asCustomer, method: 'POST' })).status).toBe(403) + expect((await fetch(`${base}/api/payload-locked-documents`, { headers: { cookie: '', origin: base } })).status).toBe(403) + expect((await fetch(`${base}/api/payload-locked-documents`, { headers: { cookie: editor, origin: base } })).status).toBe(200) + }) +}) diff --git a/test/security-patterns.allow.json b/test/security-patterns.allow.json new file mode 100644 index 0000000..bcd62ab --- /dev/null +++ b/test/security-patterns.allow.json @@ -0,0 +1,27 @@ +{ + "$comment": "Places in the plugin and the reference site that match a static security rule (src/modules/doctor/rules/securityCode.ts) on purpose. Key: ' ' → { count, reason }. test/securityPatterns.test.ts fails on a new place, a raised count or an empty reason; a lowered count is reported so the entry can shrink. Judge a new entry before adding it (security.md → Security suites).", + "entries": { + "code-override-access src/modules/access/panelRole.ts": { "count": 2, "reason": "counts staff accounts at start / in the doctor; no request data, counts only" }, + "code-override-access src/modules/access/passwordRule.ts": { "count": 1, "reason": "the password rule looks up the account being changed; the where is built from req.user's id or a string-checked reset token (typeof === 'string'), never an object from the body" }, + "code-override-access src/modules/access/rolesField.ts": { "count": 1, "reason": "first-account check (is the collection empty?): a count, no data returned" }, + "code-override-access src/modules/access/selfRegistration.ts": { "count": 3, "reason": "start-time inventory of auth collections (count / admin ids); never reached by a request" }, + "code-override-access src/modules/consent/consentLog.ts": { "count": 1, "reason": "POST /api/ipal/consent writes the visitor's own record: the collection's create is false over the API on purpose; body capped at 4 KiB, fields whitelisted" }, + "code-override-access src/modules/consent/scanner/approval.ts": { "count": 3, "reason": "cookie approval endpoint: runs after cookieScanner.access (editor+ with the second factor) has passed" }, + "code-override-access src/modules/consent/scanner/collection.ts": { "count": 2, "reason": "hooks of the cookie-review collection writing the scanner's own fields (context ipalCookieScan)" }, + "code-override-access src/modules/consent/scanner/crawl/endpoints.ts": { "count": 2, "reason": "crawl endpoints: after the editor+/second-factor check or the IAPL_COOKIE_SCAN_TOKEN + jobId check" }, + "code-override-access src/modules/consent/scanner/crawl/ingest.ts": { "count": 2, "reason": "crawler call-back ingest: only after the token and running jobId are checked" }, + "code-override-access src/modules/consent/scanner/scan.ts": { "count": 3, "reason": "cookie scan endpoint: after cookieScanner.access; writes the scanner's own collection" }, + "code-override-access src/modules/consent/scanner/sync.ts": { "count": 1, "reason": "copies approved cookies into Cookie settings after the approval check" }, + "code-override-access src/modules/doctor/growth.ts": { "count": 7, "reason": "doctor growth figures (1.18.0): counts, the oldest date, upload file names and references for the unused-media count; reached only through the doctor status (IAPL_DOCTOR_TOKEN or doctor.access) and the Media list notice in the panel (staff); returns numbers and names, no document data" }, + "code-override-access src/modules/doctor/status.ts": { "count": 7, "reason": "doctor status: counts and states only (no secrets returned; image counts by size since 1.18.0); the endpoint needs IAPL_DOCTOR_TOKEN or doctor.access" }, + "code-override-access src/modules/email/method.ts": { "count": 1, "reason": "records the sending method chosen in the panel by an admin (the panel action checks the admin first)" }, + "code-override-access src/modules/email/relay/adapter.ts": { "count": 1, "reason": "reads the site name for the mail sender; no request data" }, + "code-override-access src/modules/forms/emailLayout.ts": { "count": 1, "reason": "reads the form's e-mail settings (staff-only fields) to send the notification of a submission; the visitor never sees them" }, + "code-override-access src/modules/hooks/fillEmptyLocales.ts": { "count": 1, "reason": "afterChange hook of a save the editor's own access already allowed; fills empty locales of the same document" }, + "code-override-access src/modules/security/totp/TwoFactorStatusField.tsx": { "count": 1, "reason": "admin field component: shows the 2FA state of an account the viewer may already open" }, + "code-override-access src/modules/security/totp/enrolmentConfirm.ts": { "count": 2, "reason": "2FA first set-up confirmed by e-mail (1.18.0): reads and writes the account's own totpSecret only after the single-use link token (sha256-compared), the same-browser cookie and the own-origin check, or an admin with the second factor (confirm-pending)" }, + "code-override-access src/modules/security/totp/setupRequired.ts": { "count": 5, "reason": "2FA set-up window: start-time backfill, counts, and stamping the signed-in account's own record" }, + "code-override-access src/modules/stats/admin/loadStats.ts": { "count": 3, "reason": "the stats admin view, behind the stats access rule" }, + "code-override-access src/modules/stats/endpoint.ts": { "count": 3, "reason": "POST /api/ipal/hit (opt-in stats): writes the visit counters; body capped, fields parsed (stats/parse.ts)" } + } +} diff --git a/test/securityClasses.test.ts b/test/securityClasses.test.ts new file mode 100644 index 0000000..40843d2 --- /dev/null +++ b/test/securityClasses.test.ts @@ -0,0 +1,297 @@ +/** + * Security audit 2026-12: one block per vulnerability class, each asking the plugin's own building blocks with the + * payloads that class is known for (docs/security.md → "Security suites"). The HTTP side of the same classes runs + * against a BUILT site in reference/e2e/attack-probes.spec.ts. + * + * A finding of the audit that is not fixed yet is an `it.fails` naming it (security-audit-2026-12-findings.md): + * the test states the SAFE behaviour, so the day the fix lands vitest says the test "passed unexpectedly" and the + * `.fails` goes. The same convention as `openFor` in the closed-doors spec. Every finding of the 2026-12 audit is + * fixed in 1.18.0: no `.fails` is left. + */ +import { Script } from 'node:vm' +import { createElement } from 'react' +import { renderToStaticMarkup } from 'react-dom/server' +import { describe, expect, it, vi } from 'vitest' + +import { adminPathFromReferer } from '../src/modules/branding/signIn/languageEndpoint.js' +import { consentDecidedScript } from '../src/modules/consent/firstPaint.js' +import { parseConsent, readConsentRecord } from '../src/modules/consent/storage.js' +import { markdownResponse } from '../src/modules/content/createMarkdownRenderer.js' +import { MARKDOWN_NEGOTIATED_HEADER } from '../src/modules/content/markdownNegotiation.js' +import { createProxy } from '../src/modules/i18n/createProxy.js' +import { buildUrlField, isAllowedUrl } from '../src/modules/links/buildUrlField.js' +import { safeHref } from '../src/modules/links/resolveLinkHref.js' +import { createMcpRoute } from '../src/modules/mcp/createMcpRoute.js' +import { sanitizeRichTextLinks } from '../src/modules/richtext/sanitizeLinks.js' +import { createCspReportRoute, CSP_LOG_VALUE_MAX, cspLogLine } from '../src/modules/security/createCspReportRoute.js' +import { applyLockedDocumentsAccess, buildQueryGuardHook, capListLimit, isOperatorSort, LOCKED_DOCUMENTS_SLUG } from '../src/modules/security/queryGuard.js' +import { safeAdminBack } from '../src/modules/security/totp/safeBack.js' +import { buildSitemapXml } from '../src/modules/seo/buildSitemapXml.js' +import { JsonLdGraph } from '../src/modules/seo/JsonLdGraph.js' +import { themeScript } from '../src/modules/theme/theme.js' + +/** Strings that end a script, open markup, or run as a URL — the XSS payloads used below. */ +const XSS = ['', '', '">', '
alert(1)//'] +const UNSAFE_URLS = ['javascript:alert(1)', 'JaVaScRiPt:alert(1)', ' javascript:alert(1)', 'java\tscript:alert(1)', 'java\nscript:alert(1)', 'data:text/html,', 'vbscript:msgbox(1)', '//evil.example/x', '/\\evil.example', '\\\\evil.example'] + +const chunked = (text: string) => new Request('http://localhost/x', { + body: new ReadableStream({ start(c) { c.enqueue(new TextEncoder().encode(text)); c.close() } }), + // @ts-expect-error Node's fetch needs it for a stream body + duplex: 'half', + headers: { 'content-type': 'application/json' }, + method: 'POST', +}) + +describe('XSS — output into HTML, scripts and URLs', () => { + it('JSON-LD: no value can end the ,