Merge claude/security-audit-1180-fixes: security audit fixes F1–F5, document locks for staff, strict access callbacks, the security suites and gate
Co-Authored-By: Claude Opus 5.5 <[email protected]>
This commit is contained in:
@@ -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: <why>`.
|
||||
>
|
||||
> **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://<domain> --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 <url>` 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
|
||||
|
||||
+22
-6
@@ -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 `<meta>` itself; sitemap `https://<domain>/sitemap.xml` submitted in GSC and Bing | panel (optional), `verificationFrom` | P |
|
||||
| 4 | **SEO** — structured data | layout: `<SiteProviders shell={…}>` gives `WebSite` + `Organization` (`sameAs`) from Site settings; local business → `createContentHelpers({ siteJsonLd })` with `buildLocalBusinessJsonLd` (`type`, hours → `formatOpeningHours`); navigation: `<SiteProviders jsonLd={[buildNavigationJsonLd(…)]}>`; 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 `<head>`); `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 `<head>`); `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`; `<MediaPreconnect/>`; `images: buildImagesConfig()` and `buildUploadSecurityHeaders()` in `next.config.ts`; the project's `<Media>` 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) | `<SiteProviders lightbox>` + `<LightboxTrigger group image={lightboxImage(media, { size })}>` (`/client`), `RenderRichText lightbox`, `useLightbox`; labels: `iapl({ lightbox: true })` → Form messages → Image viewer | lightbox.md |
|
||||
| YouTube without cookies before a click | `<YouTubeEmbed poster={…}>` (`/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 })` + `<SiteProviders nonce>` (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 })` + `<SiteProviders nonce>` (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 <site>/api/ipal/test-email -H 'Origin: https://other.example' -H 'Content-Type: text/plain' -b <admin cookies> -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 '<site>/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}' '<site>/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 <site>/api/ipal/two-factor/reset -H 'Origin: https://other.example' -H 'Content-Type: text/plain' -b <admin cookies> -d '{"userId":1}'` → `403`; the panel's button still works. **Set `serverURL`**: behind a proxy that rewrites `Host` and sends no `X-Forwarded-Host` the site's own page is refused without it (logged once per origin: `[iapl] 2FA: a code from origin … was refused`) | `twoFactor.sameOrigin: false` | `sameOrigin: { origins: ['https://app.example.com'] }`; `requestFromOwnOrigin`, `reportRefusedOrigin` |
|
||||
| Stored secrets are write-only: `smtpPassword` and `turnstileSecretKey` come back as `'********'` over REST, GraphQL and in the panel; an empty save keeps the value, `'[[clear]]'` removes it; server code reads the real value with the Local API. 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: <why>` (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://<domain> --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 |
|
||||
|
||||
|
||||
@@ -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) |
|
||||
|
||||
@@ -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://<domain> --only live-probes`. The code side:
|
||||
`pnpm exec iapl-doctor --only security` (`code-patterns`, `config-dangerous`); a correct place gets
|
||||
`// iapl-security-ok: <why>`. 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
|
||||
|
||||
@@ -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://<domain> --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)
|
||||
})
|
||||
}
|
||||
@@ -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/<collection>?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` |
|
||||
|
||||
@@ -46,6 +46,19 @@ Full reference: `node_modules/@intecion/ipal-kit/docs/doctor.md`.
|
||||
`--url <url>` · `--staging` (must be noindex) · `--admin-route <path>` · `--deep` · `--env-file <prod export>` (checks
|
||||
`<domain>_prod`) · `--only` / `--skip <ids,groups>` · `--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://<domain>` 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: <why>`. 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 <token>`; 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
|
||||
|
||||
|
||||
@@ -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)/<route>/` 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` |
|
||||
|
||||
@@ -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 <secret>` 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: <why>`. 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`
|
||||
|
||||
@@ -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.
|
||||
|
||||
|
||||
@@ -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: <why>`. **Check:** `curl -s '<site>/api/pages?limit=100000' | jq .limit` → `100`;
|
||||
`curl -s -o /dev/null -w '%{http_code}' '<site>/api/pages?sort=%24where'` → `400`;
|
||||
`pnpm exec iapl-doctor --url <site> --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
|
||||
|
||||
+24
-5
@@ -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://<domain>/pl | grep -iE 'content-type|cache-control|vary'`
|
||||
→ `text/markdown`, `private, no-store`, `Vary` with `Accept`; or `pnpm exec iapl-doctor --url https://<domain> --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
|
||||
}
|
||||
```
|
||||
|
||||
|
||||
@@ -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 |
|
||||
|
||||
+4
-1
@@ -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 `<script>` without escaping `<` (`code-inner-html`); `eval` / `new Function` / `vm` (`code-eval`); a shell command from a template string (`code-shell`); a `NEXT_PUBLIC_` secret, or a server secret read in a `'use client'` file (`code-public-secret`); `overrideAccess: true` where a request reaches (`code-override-access`); the Local API given a `user` without `overrideAccess: false` — Payload then ignores the user (`code-local-api-user`); a `where` taken from the request (`code-raw-where`); a redirect (`code-open-redirect`) or a server-side `fetch` (`code-ssrf`) to an address from the request. One finding per rule and file. A correct place: `// iapl-security-ok: <why>` on the line or the line above; a file or folder: `iapl-doctor.json` `rules: { "code-override-access": { "files": ["src/lib/admin/**"], "off": true, "reason": "…" } }` (security.md "Security suites") |
|
||||
| | `config-dangerous` | error / warning | `next.config`: `images.dangerouslyAllowSVG` without `images.contentSecurityPolicy` (error), `remotePatterns` hostname `**` / `*`, `serverActions.allowedOrigins` with `*` (error), `productionBrowserSourceMaps: true`; `payload.config`: `cors: '*'`, `debug: true`, GraphQL playground / introspection on in production, `maxDepth` above 20 |
|
||||
| | `live-probes` | error / warning | (live, `--url`) the plugin's attack probes that change nothing: source / env / git files, secrets in the page scripts and public source maps, `x-middleware-subrequest` proxy bypass, open redirects, `X-Forwarded-Host` in redirects and links, Markdown / RSC answers a cache could store as the page, `$ne` operators in a sign-in, anonymous `where` / draft / versions / GraphQL reads, stack traces, unbounded `limit`, `/_next/image` to inner hosts or SVG, headers on every kind of answer, odd methods and an unknown Server Action. Reported as `live-probes:<id>`; the 8 MB-body probe runs only in the Playwright spec (security.md "Security suites") |
|
||||
| | `storage-names` | warning | the visitor cookie the layout sets (`<PageStats visitorCookie>`, default `ipal_vid`) is the one the config makes the cookie scanner declare (`storageNames`, stats.md) |
|
||||
| | `cookie-scanner` | error / warning / info | `cookieScanner` on (with `crawl`, else info); deep: nothing waits for approval (warning) |
|
||||
| mail | `mail-method` | error / info | (deep) the chosen "Sending method" can be used — "Own SMTP server" with server, user name and password, "Microsoft Graph" with the `GRAPH_*` variables; otherwise e-mails are not sent and nothing is sent another way (error). On Postgres / SQLite: the column of `emailMethod` exists — the 1.17.1 migration has run (error). Nobody has chosen yet: the site picks a method from what is filled in until Site integrations is saved (info) |
|
||||
|
||||
+1
-1
@@ -141,7 +141,7 @@ See [proxy in this section](#proxy-formerly-middleware) below.
|
||||
| Option | Default | What it does |
|
||||
|---|---|---|
|
||||
| `NextResponse` | — (required) | injected from `next/server` (the plugin does not import it) |
|
||||
| `markdown` | off | `true` = prefix `/md`, a string = a different one; paths under the prefix pass without a redirect, `Accept: text/markdown` → rewrite (content.md) |
|
||||
| `markdown` | off | `true` = prefix `/md`, a string = a different one, `{ prefix?, negotiate? }` the object form; paths under the prefix pass without a redirect, `Accept: text/markdown` → rewrite answered `private, no-store` + `Vary: Accept` (1.18.0); `negotiate: false` = no rewrite (content.md "content negotiation") |
|
||||
| `exposeHeaders` | `true` | request headers `x-locale` (language from the URL or `defaultLocale`) and `x-pathname` |
|
||||
| `consentCategory` | `'functional'` | consent category required to write the language cookie; `'necessary'` = always write |
|
||||
| `consentCookieName` | `CONSENT_COOKIE` | consent cookie to read |
|
||||
|
||||
+161
-18
@@ -287,12 +287,23 @@ With a custom `adminRoute` (e.g. `/its`), use that path in `source`.
|
||||
|
||||
### Collecting reports
|
||||
|
||||
`createCspReportRoute({ onReport?, maxBytes = 16384 })` — a `POST` handler for `reportUri`. It accepts
|
||||
both formats (`application/csp-report` from `report-uri`, `application/reports+json` from `report-to`),
|
||||
caps the body (a larger one → `413`; since 1.17.1 the stream is read only up to `maxBytes`, also when the browser
|
||||
sends no `content-length`), always answers `204`, and by default logs one `console.warn` line per violation:
|
||||
`[csp] report script-src-elem blocked=https://x.example/a.js page=https://site/pl`. Read them in the
|
||||
Coolify app's **Logs**. Plug `onReport` into `payload.logger`, Sentry or a database for more.
|
||||
`createCspReportRoute({ onReport?, maxBytes = 16384, maxReports = 10, rateLimit })` — a `POST` handler for
|
||||
`reportUri`. It accepts both formats (`application/csp-report` from `report-uri`, `application/reports+json` from
|
||||
`report-to`), caps the body (a larger one → `413`; since 1.17.1 the stream is read only up to `maxBytes`, also when
|
||||
the browser sends no `content-length`), always answers `204`, and by default logs one `console.warn` line per
|
||||
violation: `[csp] report script-src-elem blocked=https://x.example page=/pl src=https://site/_next/a.js:3`. Read them
|
||||
in the Coolify app's **Logs**. Plug `onReport` into `payload.logger`, Sentry or a database for more.
|
||||
|
||||
**What the default line holds (1.18.0, security audit F1).** Anyone can post a report, so its strings never reach the
|
||||
log as sent: the blocked resource is reduced to its origin (`inline`, `eval` stay), the page to its path (no query — it
|
||||
may hold an e-mail address), the script to origin and path; control characters and line separators are removed and
|
||||
every value is cut at `CSP_LOG_VALUE_MAX` (128) — a report cannot write a forged line of its own. One request handles
|
||||
at most `maxReports` (10) violations, and one client (`clientIp`, IPv6 per /64) at most 60 requests a minute
|
||||
(`rateLimit: { max, windowMs }`; `false` = no limit); over it the route answers `204` and handles nothing. A project's
|
||||
own `onReport` still gets every value exactly as the browser sent it — escape it before you log it, or call
|
||||
`cspLogLine(violation)` for the plugin's line. **What changes for an existing site:** the log lines show origins and
|
||||
paths instead of full URLs (a log parser that read full URLs must adapt), and at most 10 violations per request reach
|
||||
`onReport` (was 50: `maxReports: 50` keeps it).
|
||||
|
||||
```ts
|
||||
// app/api/csp-report/route.ts (a fixed route wins over Payload's /api/[...slug])
|
||||
@@ -1336,20 +1347,142 @@ globals are yours to rule. On a site that has (or may get) a visitor login colle
|
||||
`create` / `update` / `delete` and every global `update` a rule of its own — the reference site and every new site
|
||||
from `iapl create` do (`adminOrEditor`, since 1.17.2). `iapl-doctor --url` (deep) lists what such an account may
|
||||
write (`visitor-writes`, warning), checked by behaviour: it asks every rule with a stand-in visitor account. Payload's
|
||||
own `payload-locked-documents` (who edits which document) also runs on Payload's default and is listed there; a
|
||||
plugin-wide default for it is planned for 2.0. Verify: the doctor shows no `visitor-writes` finding, and the
|
||||
closed-doors spec's customer gets 403 on every write door.
|
||||
own `payload-locked-documents` (who edits which document) is for staff accounts only since 1.18.0 (`lockedDocuments`,
|
||||
"Lists and sorting" below). Verify: the doctor shows no `visitor-writes` finding, and the closed-doors spec's customer
|
||||
gets 403 on every write door.
|
||||
|
||||
## Lists and sorting (`listLimit`, `refuseOperatorSort`, `lockedDocuments`, 1.18.0)
|
||||
|
||||
Three defaults for what a caller from outside (REST, GraphQL) may ask of a collection. The Local API — the frontend,
|
||||
seeds, the project's own code (`req.payloadAPI === 'local'`) — is never touched.
|
||||
|
||||
- **`listLimit` (security audit F4).** A list (`find`, versions, distinct values) asked by a caller that is not staff
|
||||
gets at most **100** documents per request; `pagination=false` and `limit=0` become one page of 100. Before, one
|
||||
anonymous `GET /api/posts?limit=100000&depth=10` read a whole collection with its relations. Staff accounts (any
|
||||
role) are not capped — the panel asks for at most 100 per page itself. Adapt: `listLimit: { max: 250 }`,
|
||||
`{ exclude: ['products'] }` (that collection as Payload has it), `{ staff: true }` (staff capped too);
|
||||
`listLimit: false` = Payload's behaviour. **What changes for an existing site:** a client-side script that reads more
|
||||
than 100 documents anonymously over REST or GraphQL now gets the first 100 and `hasNextPage: true` — page through
|
||||
(`page=2`) or raise `max`.
|
||||
- **`refuseOperatorSort` (security audit F5).** A `sort` that names a database operator (`?sort=$where`, `-$natural`,
|
||||
`title.$ne`) answers **400** "This sort field is not allowed." for everyone, staff too — before, MongoDB got it and
|
||||
the request ended in a 500 with a stack trace in the log. The refusal is logged as one `info` line
|
||||
(`RefusedSortError`; `loggingLevels: { RefusedSortError: false }` in the Payload config hides it). A field name sorts
|
||||
as before. `refuseOperatorSort: false` = Payload's behaviour. Reported upstream to Payload (the MongoDB adapter).
|
||||
- **`lockedDocuments`.** Payload's document locks ("who edits what", `payload-locked-documents`) run on Payload's
|
||||
default — any signed-in account — so a visitor account (a shop's customer) could read who edits which document and
|
||||
write or delete locks. Since 1.18.0 they are for staff accounts only, with the second factor when 2FA is on
|
||||
(`staffOnlyLocks`). The panel works as before. Payload adds this collection after every plugin has run, so the
|
||||
rule is set on the live config (at start and after a dev reload). Your own rule per operation:
|
||||
`lockedDocuments: { access: { read: myRule } }` (the others stay staff only); `lockedDocuments: false` = Payload's
|
||||
default.
|
||||
|
||||
Both hooks are added to every collection in the config when iapl runs — the project's, the plugin's and those of
|
||||
plugins listed before iapl. A collection a plugin listed **after** iapl adds has neither: put
|
||||
`buildQueryGuardHook({ listLimit, refuseOperatorSort })` into its `hooks.beforeOperation`, or list iapl last.
|
||||
Exported: `buildQueryGuardHook`, `applyQueryGuard`, `capListLimit`, `isOperatorSort`, `isStaffRequest`,
|
||||
`isQueryGuardHook` / `QUERY_GUARD_MARK` (to tell the hook apart when you count a collection's hooks),
|
||||
`RefusedSortError`, `DEFAULT_LIST_LIMIT`, `applyLockedDocumentsAccess`, `staffOnlyLocks`, `LOCKED_DOCUMENTS_SLUG`.
|
||||
Verify: `curl -s 'https://<domain>/api/pages?limit=100000' | jq .limit` → `100`;
|
||||
`curl -s -o /dev/null -w '%{http_code}' 'https://<domain>/api/pages?sort=%24where'` → `400`; the closed-doors spec's
|
||||
customer gets 403 on `/api/payload-locked-documents`; `iapl-doctor --url … --only live-probes` passes
|
||||
`unbounded-list` and `sort-operator`.
|
||||
|
||||
## Addresses rendered into `href` (`buildUrlField`, 1.18.0)
|
||||
|
||||
A text field whose value goes into `<a href>` (a social profile, a website, a map link) must refuse `javascript:`,
|
||||
`data:` and `vbscript:` — an editor's link would otherwise run script as whoever clicks it on the public site, an
|
||||
admin included (security audit F2: the reference site's Company → Profiles was a plain text field).
|
||||
`buildUrlField({ name?, label?, required?, schemes?, description?, overrides? })` is that field: `https://` and
|
||||
`http://` pass, plus the kinds you list in `schemes` (`mailto`, `tel`, `sms`, `hash`, `relative`); protocol-relative
|
||||
`//host` never passes. `isAllowedUrl(value, schemes)` is the same check for your own code. Render the stored value
|
||||
through `safeHref()` as well — an import, a seed or an older version may hold anything. The reference site and every
|
||||
new site from `iapl create` use both (`src/globals/Company.ts`, `Footer.tsx`, the `sameAs` of the JSON-LD).
|
||||
**For an existing site:** nothing changes by itself; replace `{ name: 'url', type: 'text' }` in your own globals with
|
||||
`buildUrlField()` (no schema change: still a text column) and wrap the render in `safeHref`. Verify: entering
|
||||
`javascript:alert(1)` in the field shows "Enter a full address" and nothing is saved.
|
||||
|
||||
## Access callbacks (`cookieScanner.access`, the doctor's `access`)
|
||||
|
||||
A project's callback says who may use the cookie scanner's endpoints or read the doctor's status. Today any truthy
|
||||
answer lets the request in: `({ req }) => req.user` returns an account object and passes, and so does a function
|
||||
that returns `'no'` or `{}`. **From the next minor version (1.19.0) only `true` allows** — like
|
||||
`twoFactor.requireSetup.resetAccess` already does. Since 1.18.0 the first answer that is not a boolean is reported
|
||||
once per option in the server log:
|
||||
`[iapl] cookieScanner.access returned an object, not true or false. It is still read as allowed; …`.
|
||||
Return a boolean: `({ req }) => Boolean(req.user)`, `({ req }) => isAdmin(req.user, req.payload)`. One function reads
|
||||
every answer: `accessAllowed(option, answer)` (exported). The second factor is checked before the callback, as before.
|
||||
A project's callback says who may use the cookie scanner's endpoints or read the doctor's status. **Since 1.18.0 only
|
||||
a literal `true` allows** — like `twoFactor.requireSetup.resetAccess` already did. A callback that returns
|
||||
`req.user` (an account object), `1`, `'yes'`, `{}` or a Promise it did not await now **refuses** the request; before
|
||||
1.18.0 any truthy answer let it in. The first answer that is not a boolean is reported once per option in the server
|
||||
log, with the fix:
|
||||
`[iapl] cookieScanner.access returned an object, not true or false, so the request was refused (only true allows since 1.18.0). Return a boolean, e.g. ({ req }) => Boolean(req.user) …`.
|
||||
Return a boolean: `({ req }) => Boolean(req.user)`, `({ req }) => isAdmin(req.user, req.payload)`; an `async`
|
||||
callback is awaited, so `async ({ req }) => true` works. A project that needs the old reading back:
|
||||
`iapl({ strictAccessAnswers: false })` — any truthy answer allows again (still reported once). One function reads
|
||||
every answer: `accessAllowed(option, answer, { strict })`, and `strictAccessAnswers(req)` tells which reading the
|
||||
request's config uses (both exported). The second factor is checked before the callback, as before. **Verify:** call
|
||||
the doctor status (`GET /api/ipal/doctor` as an admin with its code) with a callback that returns `req.user`: `403` and
|
||||
one `[iapl] doctor.access returned an object …` line; with `Boolean(req.user)`: `200`.
|
||||
## Threat list (security audit 2026-12)
|
||||
|
||||
What most often hits Payload / Next.js / Node sites, ranked by how often it appeared in the advisories of the last three
|
||||
years (Dec 2023 – Dec 2026: 71 for `next`, 9 for React Server Components, 58 for `payload` / `@payloadcms/*`, 147 in the
|
||||
usual transitive dependencies; GitHub Security Advisories, NVD) and by what it costs a client site. OWASP Top 10:2025
|
||||
and ASVS 5.0 name the categories. Each row says where IAPL covers it and which suite checks it.
|
||||
|
||||
| # | Class | Seen in | IAPL covers it with | Checked by |
|
||||
|---|---|---|---|---|
|
||||
| 1 | Denial of service (body size, ReDoS, Server Actions, image optimizer, unbounded lists, GraphQL) | 27 core + 46 deps; Next GHSA-p3m5-59mp-jv5r (Server Actions, Oct 2026) | body caps on every public plugin route (`readCappedBody`), MCP batch cap, rate limits; Payload `maxDepth`; public lists capped at 100 (`listLimit`, audit F4, 1.18.0) | probes `body-size`, `unbounded-list`; per-class tests |
|
||||
| 2 | Access control (REST / GraphQL / Local API `overrideAccess`, drafts, versions, field access) | 17 Payload (A01) | account rules, `readPublished`, 2FA wrapper, jobs rule, `visitor-writes` | closed-doors spec, `routes:check`, probes `rest-where`, `graphql`; rules `code-override-access`, `code-local-api-user` |
|
||||
| 3 | Cache poisoning and cross-user leaks (ISR, RSC, CDN, host headers) | 18 Next (CVE-2024-46982 …) | no host header read for URLs (`NEXT_PUBLIC_SERVER_URL`), `no-store` on personal answers; the negotiated Markdown at an HTML URL is `private, no-store` + `Vary: Accept` (audit F3, 1.18.0) | probes `host-header`, `markdown-vary`, `rsc-vary` |
|
||||
| 4 | Remote code execution (RSC Flight, `use cache`, image optimizer + libvips/librsvg) | 10 core (React2Shell CVE-2025-55182, GHSA-2464-fhr4-w9xw, GHSA-673q-mjm6-r5xr, GHSA-xqc2-xf4c-x3h3) | minimum Next / sharp in AGENT.md §4; no `eval` | `deps-audit`, `code-eval` |
|
||||
| 5 | Information disclosure (errors, source maps, secrets in bundles and files) | 14 core | no stack traces in plugin answers, write-only secrets, no manifest in `.next/static` | probes `error-leak`, `bundle-secrets`, `secret-files`; rule `code-public-secret` |
|
||||
| 6 | SSRF (Server Actions Host header, middleware redirects, image optimizer, URL uploads) | 9 core (CVE-2024-34351, CVE-2025-57822) | `buildImagesConfig` (listed hosts only), `safeFetch` for brand images, the crawl only of the site's own URL | probe `image-optimizer`; rule `code-ssrf` |
|
||||
| 7 | Authentication and session (JWT after logout, fixation, 2FA bypass, enumeration, CSRF) | 8 + 3 (CVE-2025-4643, CVE-2025-4644) | 2FA enforced and wrapped around plugin entities, own-origin checks, `serverURL` for Payload's CSRF list, verify limit | spec "attack probes with a session" (CSRF, cookie flags), 2FA specs |
|
||||
| 8 | XSS (rich text, links, JSON-LD, SVG uploads, `dangerouslySetInnerHTML`) | 7 core + 39 deps (dompurify, sanitize-html) | `RenderRichText` / `safeHref` drop `javascript:`, `buildUrlField` refuses it on save (audit F2), `JsonLdGraph` escapes `<`, upload CSP `sandbox`, CSP | per-class tests; rule `code-inner-html`; `config-dangerous` (`dangerouslyAllowSVG`) |
|
||||
| 9 | Middleware / proxy bypass (`x-middleware-subrequest`, path normalisation) | 7 Next (CVE-2025-29927) | the plugin makes NO access decision in the proxy (locale and CSP nonce only); matcher ends at `/` | probe `middleware-subrequest`; doctor `proxy-matcher` |
|
||||
| 10 | Injection (NoSQL operators, `$where`, SQL in raw queries, CRLF, logs) | 5 Payload + 16 deps (mongoose CVE-2024-53900, CVE-2025-23061) | no `where` from request input in plugin routes; typed values in queries; operator names in `sort` refused (`refuseOperatorSort`, audit F5); CSP report log lines normalised and capped (audit F1); both 1.18.0 | probes `login-operators`, `sort-operator`; rule `code-raw-where`; per-class tests |
|
||||
| 11 | Supply chain (npm worms: Shai-Hulud 2025, chalk/debug 2025, Mini Shai-Hulud 2026) | 13 incidents | exact pins of the plugin's own deps, lockfile, `pnpm.overrides` advice (AGENT.md §4 item 12) | `deps-audit` (doctor), `pnpm security:gate` |
|
||||
| 12 | Open redirect | 1 Payload | `safeAdminBack`, `adminPathFromReferer`, locale redirect keeps the host | probe `open-redirect`; rule `code-open-redirect` |
|
||||
| 13 | Security headers and CSP | — (misconfiguration, A02) | `buildSecurityHeaders`, `buildCsp`, `withSecurityConfig` | probe `headers-everywhere`; doctor `security-headers`, `csp`, `config-dangerous` |
|
||||
|
||||
## Security suites
|
||||
|
||||
Four suites, each runnable by a project on its own site. The plugin repository runs all of them before a release.
|
||||
|
||||
| Suite | In a project | In the plugin repository |
|
||||
|---|---|---|
|
||||
| **Static rules** over the project's own code and config | `pnpm exec iapl-doctor --only security` (rules `code-patterns`, `config-dangerous`) | `test/securityPatterns.test.ts`: every hit in `src/`, `bin/`, `scripts/` and the reference site must be judged in `test/security-patterns.allow.json` (one reason per file and rule; a new place or a higher count fails) |
|
||||
| **Per-class tests** of the building blocks | — (the plugin's own) | `test/securityClasses.test.ts`: XSS payloads into JSON-LD, first-paint scripts, links, rich text, sitemap; open redirects; prototype pollution; log injection; body and batch caps; cache poisoning |
|
||||
| **HTTP attack probes** against a running site | live: `pnpm exec iapl-doctor --url https://<domain> --only live-probes` (changes nothing); local / staging: `.agents/skills/iapl-audit/resources/attack-probes.spec.template.ts` → `tests/attack-probes.spec.ts` | `reference/e2e/attack-probes.spec.ts` in `pnpm e2e:built`, after a webpack and a Turbopack production build, beside the closed-doors spec |
|
||||
| **Dependency audit** | the doctor's `deps-audit` (`pnpm audit --prod`, error on high / critical) | `pnpm security:gate` (also in `prepublishOnly`): `pnpm audit --prod` with no high / critical, then the two vitest suites; `--zap <url>` adds an OWASP ZAP baseline scan when the image `ghcr.io/zaproxy/zaproxy:stable` is already on the machine (offline; never pulled by the script) |
|
||||
|
||||
**Static rules** (`code-*`, one finding per rule and file, seeds / migrations / scripts / tests left out where the
|
||||
rule is about requests):
|
||||
|
||||
| Rule | Severity | Finds |
|
||||
|---|---|---|
|
||||
| `code-inner-html` | error | `dangerouslySetInnerHTML` / `innerHTML` / `insertAdjacentHTML` / `document.write` with a value no sanitizer passed; JSON in a `<script>` without `.replace(/</g, '\\u003c')` (use `JsonLdGraph`) |
|
||||
| `code-eval` | error | `eval`, `new Function`, `vm.run*`, `setTimeout("…")` |
|
||||
| `code-shell` | error (warning offline) | `exec` / `execSync` with a template string |
|
||||
| `code-public-secret` | error | a `NEXT_PUBLIC_…SECRET / PASSWORD / TOKEN / PRIVATE / DATABASE…` name; a server secret read in a `'use client'` file |
|
||||
| `code-override-access` | warning | `overrideAccess: true` in code a request reaches |
|
||||
| `code-local-api-user` | warning | `payload.find({ user })` without `overrideAccess: false` — Payload then IGNORES the user's rules |
|
||||
| `code-raw-where` | error | `where:` taken from `req.query`, a body, `searchParams` or `JSON.parse` |
|
||||
| `code-open-redirect` | warning | `redirect()` / `NextResponse.redirect()` to an address from the request (`?next=`, `?redirect=`) |
|
||||
| `code-ssrf` | warning | a server-side `fetch()` of an address from the request |
|
||||
| `config-dangerous` | error / warning | `dangerouslyAllowSVG` without `contentSecurityPolicy`, `remotePatterns` `**`, `serverActions.allowedOrigins` `*`, public source maps; `cors: '*'`, `debug: true`, GraphQL introspection or playground on in production, `maxDepth` above 20 |
|
||||
|
||||
A place that is correct on purpose: `// iapl-security-ok: <why>` on the same line or the line above. A whole file or
|
||||
folder: `iapl-doctor.json` → `"rules": { "code-override-access": { "files": ["src/lib/admin/**"], "off": true, "reason": "…" } }`.
|
||||
Verify: add `eval(x)` to a page and `pnpm exec iapl-doctor --only code-patterns` reports `code-eval` with the line.
|
||||
|
||||
**Attack probes** (`ATTACK_PROBES` in `@intecion/ipal-kit/doctor`; each answers on status codes and headers, a 500 is
|
||||
never "closed"): `secret-files`, `bundle-secrets` (with the spec: also the site's own secret values), `middleware-subrequest`,
|
||||
`open-redirect`, `host-header`, `markdown-vary`, `rsc-vary`, `login-operators`, `sort-operator`, `rest-where`, `graphql`,
|
||||
`error-leak`, `unbounded-list`, `image-optimizer`, `headers-everywhere`, `methods`, `body-size` (spec only: 8 MB
|
||||
bodies). The spec adds, with a signed-in editor: the session cookie is `HttpOnly` and `SameSite`, and from another
|
||||
origin the same cookie neither reads `/api/users/me`, writes a global, nor runs a GraphQL mutation. A probe tied to an
|
||||
open audit finding carries `finding` and is expected to fail (`test.fail`) until the fix lands; every finding of the
|
||||
2026-12 audit is fixed in 1.18.0, so none carries it now. Your own probe: an object `{ id, class, title, live, run(ctx) }`
|
||||
in the template's `EXTRA`. Verify: run the doctor with `--url` against `pnpm start` of a fresh starter site — no
|
||||
`live-probes` finding. A site that turned a fix off (`listLimit: false`, `refuseOperatorSort: false`,
|
||||
`markdown: { negotiate }` with a proxy of its own) gets that probe's finding back: silence it in `iapl-doctor.json`
|
||||
with the reason.
|
||||
|
||||
## Turn off, override, extend
|
||||
|
||||
@@ -1369,6 +1502,13 @@ every answer: `accessAllowed(option, answer)` (exported). The second factor is c
|
||||
`safeAdminBack`, `wrapTotpViews`, `copyViews`, `changedViewKeys`, `SAFE_TOTP_VIEW`, `SafeTotpView` are exported.
|
||||
The stale import-map notice that comes with it: `twoFactor.importMapCheck: false`; its parts
|
||||
(`findImportMapFile`, `missingImportMapEntries`) are exported too.
|
||||
- **Lists and sorting:** `listLimit: false` or `{ max, staff, exclude }`; `refuseOperatorSort: false`;
|
||||
`lockedDocuments: false` or `{ access }`; the hooks and rules above for collections added after iapl.
|
||||
- **Markdown negotiation:** `createProxy(…, { markdown: { negotiate: false } })` (Markdown only at `/md/…`);
|
||||
`MARKDOWN_NEGOTIATED_HEADER`, `NEGOTIATED_CACHE_CONTROL`, `appendVary` for your own proxy ([content.md](./content.md)).
|
||||
- **CSP report log:** `createCspReportRoute({ maxReports, rateLimit: false | { max, windowMs }, onReport })`;
|
||||
`cspLogLine` for the plugin's line in your own sink.
|
||||
- **Addresses in `href`:** `buildUrlField({ schemes, overrides })`, `isAllowedUrl`, `safeHref`.
|
||||
- **Set-up confirmed by e-mail:** `twoFactor.confirmByEmail: false` (off), or `{ linkMinutes, sameBrowser, adminConfirm,
|
||||
logLinkWhenMailFails, notices, maxMailsPerHour }`; the building blocks above.
|
||||
- **Setup required:** `twoFactor.requireSetup: false` (off), `{ windowHours }` (another window, `false` / `0` = none),
|
||||
@@ -1387,7 +1527,7 @@ every answer: `accessAllowed(option, answer)` (exported). The second factor is c
|
||||
2FA — `twoFactor: false` (discouraged).
|
||||
- **Override:** `additional` (the same key overrides the plugin's header and the `csp` ones),
|
||||
`buildCsp({ extra, override, mode, strictDynamic })`, `buildAdminCsp({ extra, override })`,
|
||||
`createCspReportRoute({ onReport, maxBytes })`;
|
||||
`createCspReportRoute({ onReport, maxBytes, maxReports, rateLimit })`;
|
||||
2FA — `collectionSlug`, `allowCollectionMismatch`, your own TOTP options by wrapping `plugin`,
|
||||
`provider` (your own redirect component, or `false` for the package's);
|
||||
access — `access.authAccess`, `access.firstUserAdmin`, `globalOverrides` ([access.md](./access.md)).
|
||||
@@ -1395,6 +1535,9 @@ every answer: `accessAllowed(option, answer)` (exported). The second factor is c
|
||||
`buildCsp` / `buildCspHeaders` / `buildReportingEndpoints` / `cspHeaderKey` /
|
||||
`parseCspReports` / `createCspNonce` (`CSP_NONCE_HEADER`, `DEFAULT_CSP_REPORT_GROUP`) for your own proxy
|
||||
or collector; `buildUploadSecurityHeaders({ collections })` for your own upload collections.
|
||||
- **Security suites:** `iapl-doctor --skip code-patterns,config-dangerous,live-probes`, or one rule per file / folder in
|
||||
`iapl-doctor.json`; the building blocks `ATTACK_PROBES`, `runAttackProbes`, `createProbeContext`, `scanCode`,
|
||||
`scanConfigs` (`@intecion/ipal-kit/doctor`) for your own CI.
|
||||
- **Check:** `curl -sI https://domain/pl | grep -iE "strict-transport|x-frame|referrer|permissions|cross-origin|content-security|x-powered-by"`
|
||||
(no `x-powered-by`; `content-security-policy-report-only` while rolling out);
|
||||
on staging also `x-robots-tag`; startup with a wrong `twoFactor.collectionSlug` fails with `[iapl] twoFactor…`.
|
||||
|
||||
+2
-1
@@ -134,9 +134,10 @@
|
||||
"lint:fix": "eslint ./src ./test --fix",
|
||||
"perf:measure": "node scripts/perf-measure.mjs",
|
||||
"prepare": "pnpm build",
|
||||
"prepublishOnly": "pnpm clean && pnpm build && pnpm build:starter && pnpm test:int && pnpm starter:gate",
|
||||
"prepublishOnly": "pnpm clean && pnpm build && pnpm build:starter && pnpm test:int && pnpm starter:gate && pnpm security:gate",
|
||||
"reference:index": "node scripts/reference-index.mjs",
|
||||
"routes:check": "node scripts/routes-check.mjs",
|
||||
"security:gate": "node scripts/security-gate.mjs",
|
||||
"starter:gate": "node scripts/starter-gate.mjs",
|
||||
"test": "pnpm test:int && pnpm test:e2e",
|
||||
"test:e2e": "playwright test",
|
||||
|
||||
@@ -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://<domain> --only live-probes`. The code side:
|
||||
`pnpm exec iapl-doctor --only security` (`code-patterns`, `config-dangerous`); a correct place gets
|
||||
`// iapl-security-ok: <why>`. 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
|
||||
|
||||
@@ -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://<domain> --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)
|
||||
})
|
||||
}
|
||||
@@ -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/<collection>?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` |
|
||||
|
||||
@@ -46,6 +46,19 @@ Full reference: `node_modules/@intecion/ipal-kit/docs/doctor.md`.
|
||||
`--url <url>` · `--staging` (must be noindex) · `--admin-route <path>` · `--deep` · `--env-file <prod export>` (checks
|
||||
`<domain>_prod`) · `--only` / `--skip <ids,groups>` · `--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://<domain>` 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: <why>`. 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 <token>`; 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
|
||||
|
||||
|
||||
@@ -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)/<route>/` 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` |
|
||||
|
||||
@@ -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 <secret>` 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: <why>`. 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`
|
||||
|
||||
@@ -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.
|
||||
|
||||
|
||||
@@ -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: <why>`. **Check:** `curl -s '<site>/api/pages?limit=100000' | jq .limit` → `100`;
|
||||
`curl -s -o /dev/null -w '%{http_code}' '<site>/api/pages?sort=%24where'` → `400`;
|
||||
`pnpm exec iapl-doctor --url <site> --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
|
||||
|
||||
@@ -0,0 +1,68 @@
|
||||
import { ATTACK_PROBES, createProbeContext } from '@intecion/ipal-kit/doctor'
|
||||
import { expect, test } from '@playwright/test'
|
||||
|
||||
import { editorTestAccount, totp } from './totp'
|
||||
|
||||
/**
|
||||
* Attack probes on the BUILT site (security audit 2026-12; docs/security.md → "Security suites"): every probe of
|
||||
* the plugin's ATTACK_PROBES, the live-safe ones and those only for a local build (8 MB bodies), then what needs a
|
||||
* signed-in session: CSRF on the API and the session cookie's flags. `pnpm e2e:built` runs it after a webpack and a
|
||||
* Turbopack build. A probe tied to an open audit finding is expected to fail (test.fail) until the fix lands.
|
||||
*
|
||||
* The secrets the bundle check looks for are this site's own values from reference/.env.
|
||||
*/
|
||||
const env = process.env
|
||||
const dbPassword = (() => {
|
||||
try {
|
||||
return decodeURIComponent(new URL(env.DATABASE_URI ?? '').password)
|
||||
} catch {
|
||||
return ''
|
||||
}
|
||||
})()
|
||||
const secrets = [env.PAYLOAD_SECRET, env.CRON_SECRET, env.IAPL_COOKIE_SCAN_TOKEN, env.IAPL_DOCTOR_TOKEN, env.R2_SECRET_ACCESS_KEY, env.E2E_ADMIN_PASSWORD, env.E2E_TOTP_SECRET, dbPassword].filter((s): s is string => !!s && s.length >= 8)
|
||||
|
||||
test.describe('attack probes', () => {
|
||||
for (const probe of ATTACK_PROBES) {
|
||||
test(`${probe.class}: ${probe.title}`, async ({ baseURL }) => {
|
||||
if (probe.finding) {test.fail(true, `audit finding ${probe.finding} is open (security-audit-2026-12-findings.md)`)}
|
||||
const { result } = { result: await probe.run(createProbeContext(baseURL!, { page: '/pl', secrets })) }
|
||||
test.skip(!!result.skipped, result.skipped)
|
||||
expect(result.ok, result.detail).toBe(true)
|
||||
})
|
||||
}
|
||||
})
|
||||
|
||||
test.describe('attack probes with a session', () => {
|
||||
test('CSRF: the editor\'s cookie does not work from another origin (REST write, GraphQL mutation)', async ({ baseURL, playwright }) => {
|
||||
const { E2E_ADMIN_EMAIL: adminEmail, E2E_ADMIN_PASSWORD: password, E2E_TOTP_SECRET: secret } = env
|
||||
test.skip(!adminEmail || !password || !secret, 'E2E_* test admin not configured')
|
||||
const api = await playwright.request.newContext({ baseURL, extraHTTPHeaders: { origin: baseURL! } })
|
||||
expect((await api.post('/api/users/login', { data: { email: editorTestAccount(adminEmail!), password } })).status()).toBe(200)
|
||||
expect((await (await api.post('/api/verify-totp', { data: { token: totp(secret!) } })).json()).ok).toBe(true)
|
||||
// the same session, same origin: the write is allowed (proves the cookie works), with a body that changes nothing
|
||||
const own = await api.get('/api/users/me')
|
||||
expect(((await own.json()) as { user?: unknown }).user).toBeTruthy()
|
||||
const foreign = { origin: 'https://evil.example', referer: 'https://evil.example/', 'sec-fetch-site': 'cross-site' }
|
||||
const me = await api.get('/api/users/me', { headers: foreign })
|
||||
expect([me.status(), ((await me.json()) as { user?: unknown }).user ?? null], 'a cross-site request must not be signed in').toEqual([200, null])
|
||||
const write = await api.post('/api/globals/header', { data: {}, headers: foreign })
|
||||
expect([401, 403]).toContain(write.status())
|
||||
const gql = await api.post('/api/graphql', { data: { query: 'mutation { updateHeader(data: {}) { id } }' }, headers: foreign })
|
||||
expect(gql.status()).toBeLessThan(500)
|
||||
expect(await gql.text()).not.toMatch(/"updateHeader"\s*:\s*\{/)
|
||||
await api.dispose()
|
||||
})
|
||||
|
||||
test('session cookie: HttpOnly and SameSite, never readable by script', async ({ baseURL, playwright }) => {
|
||||
const { E2E_ADMIN_EMAIL: adminEmail, E2E_ADMIN_PASSWORD: password } = env
|
||||
test.skip(!adminEmail || !password, 'E2E_* test admin not configured')
|
||||
const api = await playwright.request.newContext({ baseURL, extraHTTPHeaders: { origin: baseURL! } })
|
||||
const res = await api.post('/api/users/login', { data: { email: editorTestAccount(adminEmail!), password } })
|
||||
expect(res.status()).toBe(200)
|
||||
const cookie = res.headersArray().filter((h) => h.name.toLowerCase() === 'set-cookie').map((h) => h.value).find((v) => /-token=/.test(v))
|
||||
expect(cookie, 'the login sets the session cookie').toBeTruthy()
|
||||
expect(cookie).toMatch(/;\s*HttpOnly/i)
|
||||
expect(cookie).toMatch(/;\s*SameSite=(?:Lax|Strict)/i)
|
||||
await api.dispose()
|
||||
})
|
||||
})
|
||||
@@ -112,11 +112,10 @@ export const DOORS: Door[] = [
|
||||
{ body: {}, closedFor: OUTSIDERS, method: 'POST', name: 'the header (navigation) cannot be saved', path: '/api/globals/header', closed: forbidden },
|
||||
{ body: {}, closedFor: OUTSIDERS, method: 'POST', name: 'the company data cannot be saved', path: '/api/globals/company', closed: forbidden },
|
||||
{
|
||||
closedFor: ['anonymous'],
|
||||
closedFor: OUTSIDERS,
|
||||
name: 'who edits what (Payload\'s document locks, with the editor\'s account)',
|
||||
// Payload's own collection: the plugin-wide default for it is the owner's Q3 answer (a), recorded for 2.0; the doctor's
|
||||
// `visitor-writes` rule lists it on a site with a visitor login collection
|
||||
openFor: { callers: ['customer'], question: 'Q3 (a), 2.0: payload-locked-documents runs on Payload\'s default (any signed-in account)' },
|
||||
// Payload's own collection: staff only since 1.18.0 (iapl `lockedDocuments`, the owner's Q3 answer (a)); Payload's
|
||||
// default let any signed-in account in
|
||||
path: '/api/payload-locked-documents',
|
||||
closed: forbidden,
|
||||
},
|
||||
|
||||
@@ -17,8 +17,8 @@
|
||||
"DELETE /api/pages/:id": "deleteByID: editor+ (adminOrEditor, the site's own rule since 1.17.2; Payload's default would let any signed-in account in)",
|
||||
"DELETE /api/payload-kv": "delete: nobody (every rule false)",
|
||||
"DELETE /api/payload-kv/:id": "deleteByID: nobody (every rule false)",
|
||||
"DELETE /api/payload-locked-documents": "delete: Payload default: any signed-in account (the plugin-wide default is owner's Q3 (a), 2.0; the doctor's visitor-writes lists it)",
|
||||
"DELETE /api/payload-locked-documents/:id": "deleteByID: Payload default: any signed-in account (the plugin-wide default is owner's Q3 (a), 2.0; the doctor's visitor-writes lists it)",
|
||||
"DELETE /api/payload-locked-documents": "delete: staff accounts with the second factor (iapl lockedDocuments, 1.18.0; set at start, Payload's default was any signed-in account)",
|
||||
"DELETE /api/payload-locked-documents/:id": "deleteByID: staff accounts with the second factor (iapl lockedDocuments, 1.18.0; set at start, Payload's default was any signed-in account)",
|
||||
"DELETE /api/payload-preferences": "delete: own preferences only (Payload)",
|
||||
"DELETE /api/payload-preferences/:id": "deleteByID: own preferences only (Payload)",
|
||||
"DELETE /api/payload-preferences/:key": "deleteByID: own preferences only (Payload)",
|
||||
@@ -102,11 +102,11 @@
|
||||
"GET /api/payload-kv/count": "count: nobody (Payload: every rule false; the plugin keeps 2FA counts and the mail-service token here)",
|
||||
"GET /api/payload-kv/versions": "versions: readVersions = read (nobody (Payload: every rule false; the plugin keeps 2FA counts and the mail-service token here)); no version history kept here",
|
||||
"GET /api/payload-kv/versions/:id": "versionByID: readVersions = read (nobody (Payload: every rule false; the plugin keeps 2FA counts and the mail-service token here)); no version history kept here",
|
||||
"GET /api/payload-locked-documents": "find: Payload default: any signed-in account (the plugin-wide default is owner's Q3 (a), 2.0; the doctor's visitor-writes lists it)",
|
||||
"GET /api/payload-locked-documents/:id": "findByID: Payload default: any signed-in account (the plugin-wide default is owner's Q3 (a), 2.0; the doctor's visitor-writes lists it)",
|
||||
"GET /api/payload-locked-documents/count": "count: Payload default: any signed-in account (the plugin-wide default is owner's Q3 (a), 2.0; the doctor's visitor-writes lists it)",
|
||||
"GET /api/payload-locked-documents/versions": "versions: readVersions = read (Payload default: any signed-in account (the plugin-wide default is owner's Q3 (a), 2.0; the doctor's visitor-writes lists it)); no version history kept here",
|
||||
"GET /api/payload-locked-documents/versions/:id": "versionByID: readVersions = read (Payload default: any signed-in account (the plugin-wide default is owner's Q3 (a), 2.0; the doctor's visitor-writes lists it)); no version history kept here",
|
||||
"GET /api/payload-locked-documents": "find: staff accounts with the second factor (iapl lockedDocuments, 1.18.0; set at start, Payload's default was any signed-in account)",
|
||||
"GET /api/payload-locked-documents/:id": "findByID: staff accounts with the second factor (iapl lockedDocuments, 1.18.0; set at start, Payload's default was any signed-in account)",
|
||||
"GET /api/payload-locked-documents/count": "count: staff accounts with the second factor (iapl lockedDocuments, 1.18.0; set at start, Payload's default was any signed-in account)",
|
||||
"GET /api/payload-locked-documents/versions": "versions: readVersions = read (staff accounts with the second factor (iapl lockedDocuments, 1.18.0; set at start, Payload's default was any signed-in account)); no version history kept here",
|
||||
"GET /api/payload-locked-documents/versions/:id": "versionByID: readVersions = read (staff accounts with the second factor (iapl lockedDocuments, 1.18.0; set at start, Payload's default was any signed-in account)); no version history kept here",
|
||||
"GET /api/payload-preferences": "find: the signed-in account's own preferences only (Payload)",
|
||||
"GET /api/payload-preferences/:id": "findByID: the signed-in account's own preferences only (Payload)",
|
||||
"GET /api/payload-preferences/:key": "findByID: the signed-in account's own preferences only (Payload)",
|
||||
@@ -141,8 +141,8 @@
|
||||
"PATCH /api/pages/:id": "updateByID: editor+ (adminOrEditor, the site's own rule since 1.17.2; Payload's default would let any signed-in account in)",
|
||||
"PATCH /api/payload-kv": "update: nobody (every rule false)",
|
||||
"PATCH /api/payload-kv/:id": "updateByID: nobody (every rule false)",
|
||||
"PATCH /api/payload-locked-documents": "update: Payload default: any signed-in account (the plugin-wide default is owner's Q3 (a), 2.0; the doctor's visitor-writes lists it)",
|
||||
"PATCH /api/payload-locked-documents/:id": "updateByID: Payload default: any signed-in account (the plugin-wide default is owner's Q3 (a), 2.0; the doctor's visitor-writes lists it)",
|
||||
"PATCH /api/payload-locked-documents": "update: staff accounts with the second factor (iapl lockedDocuments, 1.18.0; set at start, Payload's default was any signed-in account)",
|
||||
"PATCH /api/payload-locked-documents/:id": "updateByID: staff accounts with the second factor (iapl lockedDocuments, 1.18.0; set at start, Payload's default was any signed-in account)",
|
||||
"PATCH /api/payload-preferences": "update: own preferences only (Payload)",
|
||||
"PATCH /api/payload-preferences/:id": "updateByID: own preferences only (Payload)",
|
||||
"PATCH /api/posts": "update: editor+ (adminOrEditor, the site's own rule since 1.17.2; Payload's default would let any signed-in account in)",
|
||||
@@ -220,10 +220,10 @@
|
||||
"POST /api/payload-kv/:id/duplicate": "duplicate: nobody (every rule false)",
|
||||
"POST /api/payload-kv/access/:id?": "the signed-in account's own permissions on payload-kv",
|
||||
"POST /api/payload-kv/versions/:id": "restore a version: nobody (every rule false)",
|
||||
"POST /api/payload-locked-documents": "create: Payload default: any signed-in account (the plugin-wide default is owner's Q3 (a), 2.0; the doctor's visitor-writes lists it)",
|
||||
"POST /api/payload-locked-documents/:id/duplicate": "duplicate: Payload default: any signed-in account (the plugin-wide default is owner's Q3 (a), 2.0; the doctor's visitor-writes lists it)",
|
||||
"POST /api/payload-locked-documents": "create: staff accounts with the second factor (iapl lockedDocuments, 1.18.0; set at start, Payload's default was any signed-in account)",
|
||||
"POST /api/payload-locked-documents/:id/duplicate": "duplicate: staff accounts with the second factor (iapl lockedDocuments, 1.18.0; set at start, Payload's default was any signed-in account)",
|
||||
"POST /api/payload-locked-documents/access/:id?": "the signed-in account's own permissions on payload-locked-documents",
|
||||
"POST /api/payload-locked-documents/versions/:id": "restore a version: Payload default: any signed-in account (the plugin-wide default is owner's Q3 (a), 2.0; the doctor's visitor-writes lists it)",
|
||||
"POST /api/payload-locked-documents/versions/:id": "restore a version: staff accounts with the second factor (iapl lockedDocuments, 1.18.0; set at start, Payload's default was any signed-in account)",
|
||||
"POST /api/payload-preferences": "create: own preferences only (Payload)",
|
||||
"POST /api/payload-preferences/:id/duplicate": "duplicate: own preferences only (Payload)",
|
||||
"POST /api/payload-preferences/:key": "updateByID: own preferences only (Payload)",
|
||||
@@ -259,7 +259,7 @@
|
||||
"graphql mutation createMedia": "GraphQL create: editor+ (adminOrEditor, the site's own rule since 1.17.2; Payload's default would let any signed-in account in)",
|
||||
"graphql mutation createPage": "GraphQL create: editor+ (adminOrEditor, the site's own rule since 1.17.2; Payload's default would let any signed-in account in)",
|
||||
"graphql mutation createPayloadKv": "GraphQL create: nobody (every rule false)",
|
||||
"graphql mutation createPayloadLockedDocument": "GraphQL create: Payload default: any signed-in account (the plugin-wide default is owner's Q3 (a), 2.0; the doctor's visitor-writes lists it)",
|
||||
"graphql mutation createPayloadLockedDocument": "GraphQL create: staff accounts with the second factor (iapl lockedDocuments, 1.18.0; set at start, Payload's default was any signed-in account)",
|
||||
"graphql mutation createPayloadPreference": "GraphQL create: own preferences only (Payload)",
|
||||
"graphql mutation createPost": "GraphQL create: editor+ (adminOrEditor, the site's own rule since 1.17.2; Payload's default would let any signed-in account in)",
|
||||
"graphql mutation createUser": "GraphQL create: create/delete/unlock: an admin with the second factor; update: admin or self; roles field: admin",
|
||||
@@ -271,7 +271,7 @@
|
||||
"graphql mutation deleteMedia": "GraphQL delete: editor+ (adminOrEditor, the site's own rule since 1.17.2; Payload's default would let any signed-in account in)",
|
||||
"graphql mutation deletePage": "GraphQL delete: editor+ (adminOrEditor, the site's own rule since 1.17.2; Payload's default would let any signed-in account in)",
|
||||
"graphql mutation deletePayloadKv": "GraphQL delete: nobody (every rule false)",
|
||||
"graphql mutation deletePayloadLockedDocument": "GraphQL delete: Payload default: any signed-in account (the plugin-wide default is owner's Q3 (a), 2.0; the doctor's visitor-writes lists it)",
|
||||
"graphql mutation deletePayloadLockedDocument": "GraphQL delete: staff accounts with the second factor (iapl lockedDocuments, 1.18.0; set at start, Payload's default was any signed-in account)",
|
||||
"graphql mutation deletePayloadPreference": "GraphQL delete: own preferences only (Payload)",
|
||||
"graphql mutation deletePost": "GraphQL delete: editor+ (adminOrEditor, the site's own rule since 1.17.2; Payload's default would let any signed-in account in)",
|
||||
"graphql mutation deleteUser": "GraphQL delete: create/delete/unlock: an admin with the second factor; update: admin or self; roles field: admin",
|
||||
@@ -283,7 +283,7 @@
|
||||
"graphql mutation duplicateMedia": "GraphQL duplicate: editor+ (adminOrEditor, the site's own rule since 1.17.2; Payload's default would let any signed-in account in)",
|
||||
"graphql mutation duplicatePage": "GraphQL duplicate: editor+ (adminOrEditor, the site's own rule since 1.17.2; Payload's default would let any signed-in account in)",
|
||||
"graphql mutation duplicatePayloadKv": "GraphQL duplicate: nobody (every rule false)",
|
||||
"graphql mutation duplicatePayloadLockedDocument": "GraphQL duplicate: Payload default: any signed-in account (the plugin-wide default is owner's Q3 (a), 2.0; the doctor's visitor-writes lists it)",
|
||||
"graphql mutation duplicatePayloadLockedDocument": "GraphQL duplicate: staff accounts with the second factor (iapl lockedDocuments, 1.18.0; set at start, Payload's default was any signed-in account)",
|
||||
"graphql mutation duplicatePayloadPreference": "GraphQL duplicate: own preferences only (Payload)",
|
||||
"graphql mutation duplicatePost": "GraphQL duplicate: editor+ (adminOrEditor, the site's own rule since 1.17.2; Payload's default would let any signed-in account in)",
|
||||
"graphql mutation forgotPasswordUser": "public by design: the same answer for a real and an invented address",
|
||||
@@ -306,7 +306,7 @@
|
||||
"graphql mutation updateNotification": "GraphQL update: editor+",
|
||||
"graphql mutation updatePage": "GraphQL update: editor+ (adminOrEditor, the site's own rule since 1.17.2; Payload's default would let any signed-in account in)",
|
||||
"graphql mutation updatePayloadKv": "GraphQL update: nobody (every rule false)",
|
||||
"graphql mutation updatePayloadLockedDocument": "GraphQL update: Payload default: any signed-in account (the plugin-wide default is owner's Q3 (a), 2.0; the doctor's visitor-writes lists it)",
|
||||
"graphql mutation updatePayloadLockedDocument": "GraphQL update: staff accounts with the second factor (iapl lockedDocuments, 1.18.0; set at start, Payload's default was any signed-in account)",
|
||||
"graphql mutation updatePayloadPreference": "GraphQL update: own preferences only (Payload)",
|
||||
"graphql mutation updatePost": "GraphQL update: editor+ (adminOrEditor, the site's own rule since 1.17.2; Payload's default would let any signed-in account in)",
|
||||
"graphql mutation updateSiteIntegration": "GraphQL update: admin; secrets write-only",
|
||||
@@ -335,8 +335,8 @@
|
||||
"graphql query Pages": "GraphQL find: anyone (published content, no drafts)",
|
||||
"graphql query PayloadKv": "GraphQL find: nobody (Payload: every rule false; the plugin keeps 2FA counts and the mail-service token here)",
|
||||
"graphql query PayloadKvs": "GraphQL find: nobody (Payload: every rule false; the plugin keeps 2FA counts and the mail-service token here)",
|
||||
"graphql query PayloadLockedDocument": "GraphQL find: Payload default: any signed-in account (the plugin-wide default is owner's Q3 (a), 2.0; the doctor's visitor-writes lists it)",
|
||||
"graphql query PayloadLockedDocuments": "GraphQL find: Payload default: any signed-in account (the plugin-wide default is owner's Q3 (a), 2.0; the doctor's visitor-writes lists it)",
|
||||
"graphql query PayloadLockedDocument": "GraphQL find: staff accounts with the second factor (iapl lockedDocuments, 1.18.0; set at start, Payload's default was any signed-in account)",
|
||||
"graphql query PayloadLockedDocuments": "GraphQL find: staff accounts with the second factor (iapl lockedDocuments, 1.18.0; set at start, Payload's default was any signed-in account)",
|
||||
"graphql query PayloadPreference": "GraphQL find: the signed-in account's own preferences only (Payload)",
|
||||
"graphql query PayloadPreferences": "GraphQL find: the signed-in account's own preferences only (Payload)",
|
||||
"graphql query Post": "GraphQL find: anyone (published content, no drafts)",
|
||||
@@ -353,7 +353,7 @@
|
||||
"graphql query countForms": "GraphQL count: anyone (the form renders from it; the Emails tab is staff-only by field access)",
|
||||
"graphql query countPages": "GraphQL count: anyone (published content, no drafts)",
|
||||
"graphql query countPayloadKvs": "GraphQL count: nobody (Payload: every rule false; the plugin keeps 2FA counts and the mail-service token here)",
|
||||
"graphql query countPayloadLockedDocuments": "GraphQL count: Payload default: any signed-in account (the plugin-wide default is owner's Q3 (a), 2.0; the doctor's visitor-writes lists it)",
|
||||
"graphql query countPayloadLockedDocuments": "GraphQL count: staff accounts with the second factor (iapl lockedDocuments, 1.18.0; set at start, Payload's default was any signed-in account)",
|
||||
"graphql query countPayloadPreferences": "GraphQL count: the signed-in account's own preferences only (Payload)",
|
||||
"graphql query countPosts": "GraphQL count: anyone (published content, no drafts)",
|
||||
"graphql query countUsers": "GraphQL count: an admin, or the account itself (adminOrSelfIn users)",
|
||||
|
||||
@@ -1,4 +1,5 @@
|
||||
import { Container } from '@intecion/ipal-kit/blocks/rsc'
|
||||
import { safeHref } from '@intecion/ipal-kit'
|
||||
import { NoSnippet } from '@intecion/ipal-kit/rsc'
|
||||
import Link from 'next/link'
|
||||
|
||||
@@ -47,11 +48,15 @@ export async function Footer({ company, footer, locale }: Props) {
|
||||
<Link className="hover:text-link-hover" href={link.href}>{link.label}</Link>
|
||||
</li>
|
||||
))}
|
||||
{(company.socials ?? []).map((s) => (
|
||||
<li key={s.url}>
|
||||
<a className="hover:text-link-hover" href={s.url} rel="noopener noreferrer" target="_blank">{s.label}</a>
|
||||
</li>
|
||||
))}
|
||||
{(company.socials ?? []).flatMap((s) => {
|
||||
// the field validates; the render checks again (an import or an older version may hold anything)
|
||||
const href = safeHref(s.url)
|
||||
return href ? [
|
||||
<li key={href}>
|
||||
<a className="hover:text-link-hover" href={href} rel="noopener noreferrer" target="_blank">{s.label}</a>
|
||||
</li>,
|
||||
] : []
|
||||
})}
|
||||
</ul>
|
||||
</Container>
|
||||
</NoSnippet>
|
||||
|
||||
@@ -1,6 +1,6 @@
|
||||
import type { GlobalConfig } from 'payload'
|
||||
|
||||
import { adminOrEditor, buildGlobalRevalidateHook, rowLabel } from '@intecion/ipal-kit'
|
||||
import { adminOrEditor, buildGlobalRevalidateHook, buildUrlField, rowLabel } from '@intecion/ipal-kit'
|
||||
import { revalidatePath } from 'next/cache'
|
||||
|
||||
/** Company data for a PL market site: footer, contact block details, LocalBusiness JSON-LD. */
|
||||
@@ -33,7 +33,8 @@ export const Company: GlobalConfig = {
|
||||
labels: { plural: 'Profiles', singular: 'Profile' },
|
||||
fields: [
|
||||
{ name: 'label', type: 'text', required: true },
|
||||
{ name: 'url', type: 'text', required: true },
|
||||
// rendered into href: https:// only, never javascript: or data: (security.md "Addresses rendered into href")
|
||||
buildUrlField({ required: true }),
|
||||
],
|
||||
},
|
||||
],
|
||||
|
||||
@@ -1,6 +1,6 @@
|
||||
import { faqItemsFromLayout } from '@intecion/ipal-kit/blocks'
|
||||
// @starter:if localBusiness
|
||||
import { buildLocalBusinessJsonLd, createContentHelpers } from '@intecion/ipal-kit'
|
||||
import { buildLocalBusinessJsonLd, createContentHelpers, isAllowedUrl } from '@intecion/ipal-kit'
|
||||
|
||||
import { contentConfig } from '@/content.config'
|
||||
import { i18nConfig } from '@/i18n.config'
|
||||
@@ -72,7 +72,7 @@ export const {
|
||||
address: { city: company.address?.city ?? undefined, country: company.address?.country ?? 'PL', postalCode: company.address?.postalCode ?? undefined, street: company.address?.street ?? undefined },
|
||||
name: company.name,
|
||||
openingHours: company.hours ?? undefined,
|
||||
sameAs: (company.socials ?? []).map((s) => s.url),
|
||||
sameAs: (company.socials ?? []).map((s) => s.url).filter((url) => isAllowedUrl(url)),
|
||||
telephone: company.phone ?? undefined,
|
||||
type: 'ProfessionalService',
|
||||
url: baseUrl,
|
||||
|
||||
+1293
-10
File diff suppressed because it is too large
Load Diff
@@ -19,7 +19,10 @@
|
||||
* staff sign-in from another origin refused);
|
||||
* e2e/sign-in-answers.spec.ts (1.17.2: a locked staff account answers like a wrong password; the panel actions refuse
|
||||
* another origin), e2e/two-factor-enrolment.spec.ts (1.18.0: the first 2FA set-up waits for the e-mailed link,
|
||||
* read from the mail sink; the password alone no longer enrols a factor).
|
||||
* read from the mail sink; the password alone no longer enrols a factor), e2e/attack-probes.spec.ts (security audit
|
||||
* 2026-12: the plugin's ATTACK_PROBES — secret files, bundle secrets, proxy bypass, open redirect, host-header and
|
||||
* negotiation cache poisoning, NoSQL operators, where/draft/GraphQL access, error leaks, unbounded lists, the image
|
||||
* optimizer, headers, methods, 8 MB bodies — plus CSRF and the session cookie's flags).
|
||||
* 4. e2e/performance.spec.ts (1.18.0): the performance budgets — LCP, CLS, Total Blocking Time, the response to a tap,
|
||||
* JS / CSS / font bytes, requests, render-blocking resources and third parties before consent for every page type,
|
||||
* on a throttled phone and a desktop, and the MongoDB queries of one render (docs/performance.md).
|
||||
@@ -100,7 +103,7 @@ for (const bundler of bundlers) {
|
||||
process.exit(1)
|
||||
}
|
||||
console.log(`[e2e:built] ✓ ${bundler}: no package manifest among ${files.length} public files`)
|
||||
run(`${bundler}: the built site — late-staff spec, the mail service, closed doors, the published-files check, the client hints, consent, the sign-in look, the sign-in answers, the own account and the unused-files notice`, 'pnpm', ['exec', 'playwright', 'test', 'late-staff', 'mail-relay', 'closed-doors', 'smoke', 'sign-in-look', 'sign-in-answers', 'own-account', 'two-factor-enrolment', 'unused-media', '--grep', 'unused-files notice|2FA enrolment|late staff collection|the mail service|closed doors|no package.json is published|client hints|consent|sign-in look|locked staff account|panel actions|own account|staff sign-in'], site, { ALLOW_LOCAL_MEDIA: process.env.ALLOW_LOCAL_MEDIA ?? '1', CRON_SECRET: cronSecret, E2E_LATE_STAFF: '1' })
|
||||
run(`${bundler}: the built site — late-staff spec, the mail service, closed doors, the attack probes, the published-files check, the client hints, consent, the sign-in look, the sign-in answers, the own account and the unused-files notice`, 'pnpm', ['exec', 'playwright', 'test', 'late-staff', 'mail-relay', 'closed-doors', 'attack-probes', 'smoke', 'sign-in-look', 'sign-in-answers', 'own-account', 'two-factor-enrolment', 'unused-media', '--grep', 'unused-files notice|2FA enrolment|late staff collection|the mail service|closed doors|attack probes|no package.json is published|client hints|consent|sign-in look|locked staff account|panel actions|own account|staff sign-in'], site, { ALLOW_LOCAL_MEDIA: process.env.ALLOW_LOCAL_MEDIA ?? '1', CRON_SECRET: cronSecret, E2E_LATE_STAFF: '1' })
|
||||
// the budgets are the built site's own numbers: they hold for each bundler (docs/performance.md, docs/dev/perf/)
|
||||
run(`${bundler}: performance budgets — every page type on a phone and a desktop, queries per render`, 'pnpm', ['exec', 'playwright', 'test', 'e2e/performance.spec'] /* a regex on the file path: a checkout path may hold "performance" */, site, { ALLOW_LOCAL_MEDIA: process.env.ALLOW_LOCAL_MEDIA ?? '1', E2E_LATE_STAFF: '1' })
|
||||
passed.push(bundler)
|
||||
|
||||
@@ -63,6 +63,7 @@ export const DESCRIPTIONS = {
|
||||
'e2e/late-staff-fixture.ts': 'test fixture, on only with E2E_LATE_STAFF=1: one plugin before iapl (staff collections of the config: roles with one more value, the plugin\'s roles, roles of the project\'s own) and one after it (a staff collection without rules, one whose roles field is text, copies of staff collections under new slugs — plain, with rules of their own, one rule used for another operation, other role values, the opt-out, not staff — and a visitor collection with open sign-up)',
|
||||
'e2e/enrolment.ts': 'reads the two-step verification confirmation link (twoFactor.confirmByEmail, 1.18.0) from the mail sink: quoted-printable undone, the latest message to an address, waited for',
|
||||
'e2e/two-factor-enrolment.spec.ts': 'the first 2FA set-up confirmed by e-mail on the built site (run by `pnpm e2e:built` in both bundlers): the password alone no longer enrols an attacker\'s factor (the link goes to the owner and is refused in another browser), and the panel flow — code, notice, link from the mail sink, sign in again',
|
||||
'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/late-staff.spec.ts': 'the account rules on a BUILT site (run by `pnpm e2e:built` after a webpack and a Turbopack build): a staff collection a later plugin adds, staff collections whose accounts can hold `admin`, and copies of staff collections — a visitor account gets nothing, nobody raises its own role or makes an admin, a copy is never wider than the plugin\'s rule',
|
||||
|
||||
@@ -0,0 +1,73 @@
|
||||
#!/usr/bin/env node
|
||||
/**
|
||||
* pnpm security:gate — the security suites that need no built site (docs/security.md → "Security suites"):
|
||||
* 1. dependency audit: `pnpm audit --prod` must show no high or critical advisory (the plugin's own production
|
||||
* dependency tree; dev tooling is reported, not failed);
|
||||
* 2. static rules over the plugin, its scripts and the reference site, every hit judged in
|
||||
* test/security-patterns.allow.json (test/securityPatterns.test.ts), and the per-class tests
|
||||
* (test/securityClasses.test.ts);
|
||||
* 3. optional, `--zap <url>`: an OWASP ZAP baseline scan (passive, spiders 1 minute) of a running site, ONLY when
|
||||
* the image `ghcr.io/zaproxy/zaproxy:stable` is already on this machine — the scan runs offline (`-I` keeps
|
||||
* warnings from failing; failures fail). Pull the image once yourself: `docker pull ghcr.io/zaproxy/zaproxy:stable`.
|
||||
* The built-site part (attack probes, closed doors) is `pnpm e2e:built`.
|
||||
* Options: --offline (skip the audit, it needs the registry), --zap <url>.
|
||||
*/
|
||||
import { spawnSync } from 'node:child_process'
|
||||
import path from 'node:path'
|
||||
import { fileURLToPath } from 'node:url'
|
||||
|
||||
const root = path.resolve(path.dirname(fileURLToPath(import.meta.url)), '..')
|
||||
const args = process.argv.slice(2)
|
||||
const zapAt = args.indexOf('--zap')
|
||||
const zapUrl = zapAt >= 0 ? args[zapAt + 1] : null
|
||||
const results = []
|
||||
|
||||
const step = (label, command, commandArgs, { allowFail = false } = {}) => {
|
||||
console.log(`\n[security:gate] ${label}`)
|
||||
const r = spawnSync(command, commandArgs, { cwd: root, encoding: 'utf8', maxBuffer: 64 * 1024 * 1024 })
|
||||
results.push({ label, ok: r.status === 0 || allowFail })
|
||||
return r
|
||||
}
|
||||
|
||||
if (!args.includes('--offline')) {
|
||||
const audit = step('dependency audit (pnpm audit --prod)', 'pnpm', ['audit', '--prod', '--json', '--ignore-workspace'], { allowFail: true })
|
||||
let v = null
|
||||
try {
|
||||
v = JSON.parse(audit.stdout).metadata?.vulnerabilities ?? null
|
||||
} catch {
|
||||
// no JSON: the registry did not answer
|
||||
}
|
||||
if (!v) {
|
||||
console.error(` pnpm audit gave no result: ${(audit.stderr || audit.stdout).trim().split('\n')[0]}`)
|
||||
results.at(-1).ok = false
|
||||
} else {
|
||||
console.log(` production tree: ${v.critical ?? 0} critical, ${v.high ?? 0} high, ${v.moderate ?? 0} moderate, ${v.low ?? 0} low`)
|
||||
results.at(-1).ok = !(v.critical || v.high)
|
||||
const dev = spawnSync('pnpm', ['audit', '--json', '--ignore-workspace'], { cwd: root, encoding: 'utf8', maxBuffer: 64 * 1024 * 1024 })
|
||||
try {
|
||||
const d = JSON.parse(dev.stdout).metadata?.vulnerabilities
|
||||
console.log(` with dev tooling (reported, not failed): ${d.critical ?? 0} critical, ${d.high ?? 0} high, ${d.moderate ?? 0} moderate, ${d.low ?? 0} low`)
|
||||
} catch {
|
||||
// ignore
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
const tests = step('static rules + per-class tests (vitest)', 'pnpm', ['exec', 'vitest', 'run', 'test/securityPatterns.test.ts', 'test/securityClasses.test.ts'])
|
||||
process.stdout.write(tests.stdout.split('\n').filter((l) => /Tests |✓|×|FAIL|NOT JUDGED|MORE THAN/.test(l)).join('\n') + '\n')
|
||||
if (tests.status !== 0) {process.stdout.write(tests.stdout.slice(-4000))}
|
||||
|
||||
if (zapUrl) {
|
||||
const image = 'ghcr.io/zaproxy/zaproxy:stable'
|
||||
const has = spawnSync('docker', ['image', 'inspect', image], { encoding: 'utf8' })
|
||||
if (has.status !== 0) {
|
||||
console.log(`\n[security:gate] ZAP baseline skipped: ${image} is not on this machine (docker pull it once)`)
|
||||
} else {
|
||||
const target = zapUrl.replace('localhost', 'host.docker.internal').replace('127.0.0.1', 'host.docker.internal')
|
||||
const zap = step(`OWASP ZAP baseline of ${zapUrl}`, 'docker', ['run', '--rm', '--add-host=host.docker.internal:host-gateway', image, 'zap-baseline.py', '-t', target, '-m', '1', '-I', '--autooff'])
|
||||
process.stdout.write(zap.stdout.split('\n').filter((l) => /^(?:FAIL|WARN|PASS):|FAIL-NEW|WARN-NEW/.test(l)).slice(0, 80).join('\n') + '\n')
|
||||
}
|
||||
}
|
||||
|
||||
console.log('\n[security:gate] ' + results.map((r) => `${r.ok ? '✓' : '✗'} ${r.label}`).join('\n[security:gate] '))
|
||||
process.exit(results.every((r) => r.ok) ? 0 : 1)
|
||||
@@ -18,6 +18,8 @@ export { DEFAULT_SRC_ALLOW, findFrontend } from '../modules/doctor/rules/layout.
|
||||
export type { FrontendLayout } from '../modules/doctor/rules/layout.js'
|
||||
export { createLiveFetcher } from '../modules/doctor/rules/live.js'
|
||||
export { performanceRules } from '../modules/doctor/rules/performance.js'
|
||||
export { codeFindings, listCodeFiles, LIVE_PROBE_IDS, scanCode, scanConfigs, SECURITY_OK_MARKER, securityCodeRules } from '../modules/doctor/rules/securityCode.js'
|
||||
export type { CodeHit, CodePatternId } from '../modules/doctor/rules/securityCode.js'
|
||||
export { AUDIT_RULE_MAP, parseToolOutput } from '../modules/doctor/rules/tooling.js'
|
||||
export { applySettings, AUDIT_SKIP_RULES, doctorRules, globToRegExp, runDeepProbe, runDoctor } from '../modules/doctor/run.js'
|
||||
export type { RunDoctorOptions } from '../modules/doctor/run.js'
|
||||
@@ -38,6 +40,9 @@ export type { GrowthThresholds } from '../modules/doctor/types.js'
|
||||
// Performance budgets (docs/performance.md): the defaults, a project's own on top, and the check the gate runs
|
||||
export { IMAGE_RULES, overBudget, PERF_BUDGETS, perfBudgets, SERVER_BUDGET } from '../modules/performance/budgets.js'
|
||||
export type { PerfBudget, PerfMeasurement, PerfProfile, ServerBudget } from '../modules/performance/budgets.js'
|
||||
// HTTP attack probes (docs/security.md "Security suites")
|
||||
export { ATTACK_PROBES, createProbeContext, runAttackProbes } from '../modules/security/attackProbes.js'
|
||||
export type { AttackProbe, ProbeAnswer, ProbeContext, ProbeResult } from '../modules/security/attackProbes.js'
|
||||
// routes:check — the site's public routes against the judged snapshot (docs/security.md "Routes nobody has judged")
|
||||
export { runRouteCheck } from '../modules/security/routeCheck.js'
|
||||
export type { RunRouteCheckOptions } from '../modules/security/routeCheck.js'
|
||||
|
||||
+26
-2
@@ -241,6 +241,7 @@ export { pathOf } from './modules/construction/visibility.js'
|
||||
export type { PathVisibility } from './modules/construction/visibility.js'
|
||||
export type { ContentCollectionOption, ContentOption, ResolvedRoute } from './modules/content/index.js'
|
||||
export {
|
||||
appendVary,
|
||||
applyDraftRelations,
|
||||
archiveFieldName,
|
||||
blocksToMarkdown,
|
||||
@@ -253,9 +254,11 @@ export {
|
||||
isSiteLocale,
|
||||
limitQuery,
|
||||
listContent,
|
||||
MARKDOWN_NEGOTIATED_HEADER,
|
||||
MARKDOWN_PREFIX,
|
||||
markdownHref,
|
||||
markdownResponse,
|
||||
NEGOTIATED_CACHE_CONTROL,
|
||||
parsePageParam,
|
||||
prefersMarkdown,
|
||||
resolveNotFoundPage,
|
||||
@@ -420,7 +423,8 @@ export type { IntegrationBannerTexts, IntegrationLabel, IntegrationState, Integr
|
||||
// Image lightbox — pure helpers (components live in /client).
|
||||
export { formatLightboxCounter, LIGHTBOX_FALLBACK, LIGHTBOX_FALLBACK_PL, lightboxFallback, lightboxImage, lightboxIndex, resolveLightboxTexts } from './modules/lightbox/index.js'
|
||||
export type { LightboxClassNames, LightboxImage, LightboxImageOptions, LightboxRenderImage, LightboxTexts } from './modules/lightbox/index.js'
|
||||
export { buildLinkField, buildLinksField, homeSlugFrom, resolveLink, resolveLinkHref, resolveNav, resolveSystemLinks, safeHref } from './modules/links/index.js'
|
||||
export { buildLinkField, buildLinksField, buildUrlField, homeSlugFrom, isAllowedUrl, resolveLink, resolveLinkHref, resolveNav, resolveSystemLinks, safeHref } from './modules/links/index.js'
|
||||
export type { BuildUrlFieldOptions, UrlScheme } from './modules/links/index.js'
|
||||
export type {
|
||||
BuildLinkFieldOptions,
|
||||
BuildLinksFieldOptions,
|
||||
@@ -493,8 +497,10 @@ export {
|
||||
COLOR_SCHEME_CLIENT_HINT,
|
||||
createCspNonce,
|
||||
createCspReportRoute,
|
||||
CSP_LOG_VALUE_MAX,
|
||||
CSP_NONCE_HEADER,
|
||||
cspHeaderKey,
|
||||
cspLogLine,
|
||||
DEFAULT_CSP_REPORT_GROUP,
|
||||
parseCspReports,
|
||||
scopeColorSchemeClientHints,
|
||||
@@ -518,6 +524,23 @@ export type { BuildSecurityHeadersArgs, SecurityHeader } from './modules/securit
|
||||
// Payload's job queue over HTTP: an admin with the second factor or Bearer CRON_SECRET (security.md "Payload's job queue")
|
||||
export { CRON_SECRET_ENV, CRON_SECRET_MIN_LENGTH, cronSecretMatches, jobsRunAccess, jobsRunNotice, withJobsRunAccess } from './modules/security/jobsAccess.js'
|
||||
export type { JobsRunAccessOptions } from './modules/security/jobsAccess.js'
|
||||
// Lists from outside (security.md "Lists and sorting"): page size capped for non-staff, operator sort names refused,
|
||||
// Payload's document locks for staff only.
|
||||
export {
|
||||
applyLockedDocumentsAccess,
|
||||
applyQueryGuard,
|
||||
buildQueryGuardHook,
|
||||
capListLimit,
|
||||
DEFAULT_LIST_LIMIT,
|
||||
isOperatorSort,
|
||||
isQueryGuardHook,
|
||||
isStaffRequest,
|
||||
LOCKED_DOCUMENTS_SLUG,
|
||||
QUERY_GUARD_MARK,
|
||||
RefusedSortError,
|
||||
staffOnlyLocks,
|
||||
} from './modules/security/queryGuard.js'
|
||||
export type { ListLimitOptions, LockedDocumentsAccess } from './modules/security/queryGuard.js'
|
||||
// The doors a built config opens (REST, GraphQL, Next route files) and the judged snapshot they are checked against.
|
||||
export { compareRouteSnapshot, listNextRouteFiles, listPublicRoutes, updateRouteSnapshot } from './modules/security/routeInventory.js'
|
||||
export type { GraphqlSchemaLike, RouteInventoryOptions, RouteSnapshot, RouteSnapshotDiff } from './modules/security/routeInventory.js'
|
||||
@@ -610,7 +633,8 @@ export { robotsOptionsFrom, verificationFrom } from './modules/seo/index.js'
|
||||
export type { AiBotRule, AiBotsPolicy, VerificationMetadata } from './modules/seo/index.js'
|
||||
export { buildSitemapCss, buildSitemapIndexXml, buildSitemapXml, DEFAULT_SITEMAP_CREDIT, SITEMAP_STYLE_PARAM } from './modules/seo/index.js'
|
||||
export type { SitemapRouteOptions, SitemapStyleOptions } from './modules/seo/index.js'
|
||||
export { accessAllowed } from './modules/shared/accessAnswer.js'
|
||||
export { accessAllowed, strictAccessAnswers } from './modules/shared/accessAnswer.js'
|
||||
export type { AccessAnswerOptions } from './modules/shared/accessAnswer.js'
|
||||
export { applyCollectionOverride } from './modules/shared/collectionOverride.js'
|
||||
export type { CollectionOverride } from './modules/shared/collectionOverride.js'
|
||||
// Development addresses by pattern (no env): the built-in list and the matcher behind `developmentHosts`.
|
||||
|
||||
@@ -7,7 +7,7 @@ import type { CookieScannerOptions, CookieStorage } from './types.js'
|
||||
|
||||
import { userMeetsRole } from '../../access/predicates.js'
|
||||
import { secondFactorPassed } from '../../security/totp/secondFactor.js'
|
||||
import { accessAllowed } from '../../shared/accessAnswer.js'
|
||||
import { accessAllowed, strictAccessAnswers } from '../../shared/accessAnswer.js'
|
||||
import { CONSENT_CATEGORIES } from '../categories.js'
|
||||
import { COOKIE_REVIEW_SLUG } from './collection.js'
|
||||
import { textFor } from './merge.js'
|
||||
@@ -157,7 +157,7 @@ export async function approveCookies({
|
||||
export function buildCookieApprovalEndpoints(options: CookieScannerOptions): Endpoint[] {
|
||||
const approval = typeof options.approval === 'object' ? options.approval : {}
|
||||
const allowed = async (req: PayloadRequest) =>
|
||||
options.access ? secondFactorPassed(req) && accessAllowed('cookieScanner.access', await options.access({ req })) : userMeetsRole(req, 'editor')
|
||||
options.access ? secondFactorPassed(req) && accessAllowed('cookieScanner.access', await options.access({ req }), { strict: strictAccessAnswers(req) }) : userMeetsRole(req, 'editor')
|
||||
return [
|
||||
{
|
||||
handler: async (req) => {
|
||||
|
||||
@@ -7,7 +7,7 @@ import type { CookieCrawlOptions, CookieScanContext, CookieScannerOptions } from
|
||||
|
||||
import { userMeetsRole } from '../../../access/predicates.js'
|
||||
import { secondFactorPassed } from '../../../security/totp/secondFactor.js'
|
||||
import { accessAllowed } from '../../../shared/accessAnswer.js'
|
||||
import { accessAllowed, strictAccessAnswers } from '../../../shared/accessAnswer.js'
|
||||
import {
|
||||
COOKIE_CRAWL_PATH,
|
||||
COOKIE_CRAWL_RESULTS_PATH,
|
||||
@@ -61,7 +61,7 @@ export function buildCookieCrawlEndpoints({
|
||||
}): Endpoint[] {
|
||||
const crawl: CookieCrawlOptions = typeof options.crawl === 'object' ? options.crawl : {}
|
||||
const isStaff = async (req: PayloadRequest) =>
|
||||
options.access ? secondFactorPassed(req) && accessAllowed('cookieScanner.access', await options.access({ req })) : userMeetsRole(req, 'editor')
|
||||
options.access ? secondFactorPassed(req) && accessAllowed('cookieScanner.access', await options.access({ req }), { strict: strictAccessAnswers(req) }) : userMeetsRole(req, 'editor')
|
||||
const read = async (req: PayloadRequest) =>
|
||||
(await req.payload.findGlobal({ slug: COOKIE_CRAWL_SLUG as never, depth: 0, overrideAccess: true, req })) as CrawlDoc
|
||||
const write = (req: PayloadRequest, data: Partial<CrawlDoc>) =>
|
||||
|
||||
@@ -4,7 +4,7 @@ import type { CookieIntegration, CookieScanContext, CookieScannerOptions } from
|
||||
|
||||
import { userMeetsRole } from '../../access/predicates.js'
|
||||
import { secondFactorPassed } from '../../security/totp/secondFactor.js'
|
||||
import { accessAllowed } from '../../shared/accessAnswer.js'
|
||||
import { accessAllowed, strictAccessAnswers } from '../../shared/accessAnswer.js'
|
||||
import { DEFAULT_COOKIE_INTEGRATIONS, integrationLabel } from './integrations.js'
|
||||
import { cookieScanContext, enabledCookieIntegrations, parseCookieNames, runCookieScan } from './scan.js'
|
||||
|
||||
@@ -18,7 +18,7 @@ export const COOKIE_SCAN_PATH = '/ipal/cookie-scan'
|
||||
*/
|
||||
export function buildCookieScanEndpoints(options: CookieScannerOptions, plugin: CookieScanContext['plugin']): Endpoint[] {
|
||||
const allowed = async (req: PayloadRequest) =>
|
||||
options.access ? secondFactorPassed(req) && accessAllowed('cookieScanner.access', await options.access({ req })) : userMeetsRole(req, 'editor')
|
||||
options.access ? secondFactorPassed(req) && accessAllowed('cookieScanner.access', await options.access({ req }), { strict: strictAccessAnswers(req) }) : userMeetsRole(req, 'editor')
|
||||
const integrations = options.integrations ? options.integrations(DEFAULT_COOKIE_INTEGRATIONS) : DEFAULT_COOKIE_INTEGRATIONS
|
||||
// Names in the admin language of the editor who asks.
|
||||
const list = (items: CookieIntegration[], req: PayloadRequest) =>
|
||||
|
||||
@@ -4,6 +4,7 @@ import type { PathVisibility } from '../construction/visibility.js'
|
||||
import type { ContentOption } from './types.js'
|
||||
|
||||
import { blocksToMarkdown } from './blocksToMarkdown.js'
|
||||
import { MARKDOWN_NEGOTIATED_HEADER, NEGOTIATED_CACHE_CONTROL } from './markdownNegotiation.js'
|
||||
import { resolveRoute } from './resolveRoute.js'
|
||||
|
||||
type CreateMarkdownRendererArgs = {
|
||||
@@ -126,9 +127,11 @@ export function createMarkdownRenderer(args: CreateMarkdownRendererArgs = {}) {
|
||||
* Wraps a Markdown string in a `text/markdown` Response, or a 404 when null.
|
||||
* Uses the global Response — no next/server import.
|
||||
*/
|
||||
export function markdownResponse(md: null | string, options: { canonical?: string } = {}): Response {
|
||||
export function markdownResponse(md: null | string, options: { canonical?: string; negotiated?: boolean } = {}): Response {
|
||||
// Negotiated at an HTML URL (the proxy's marker): never stored by a shared cache as that page (audit F3).
|
||||
const negotiatedHeaders: Record<string, string> = options.negotiated ? { 'cache-control': NEGOTIATED_CACHE_CONTROL, vary: 'Accept' } : {}
|
||||
if (md == null) {
|
||||
return new Response('Not found', { headers: { 'content-type': 'text/plain' }, status: 404 })
|
||||
return new Response('Not found', { headers: { 'content-type': 'text/plain', ...negotiatedHeaders }, status: 404 })
|
||||
}
|
||||
return new Response(md, {
|
||||
headers: {
|
||||
@@ -138,6 +141,7 @@ export function markdownResponse(md: null | string, options: { canonical?: strin
|
||||
// index it as a duplicate — and should credit the HTML page instead.
|
||||
'x-robots-tag': 'noindex',
|
||||
...(options.canonical ? { link: `<${options.canonical}>; rel="canonical"` } : {}),
|
||||
...negotiatedHeaders,
|
||||
},
|
||||
status: 200,
|
||||
})
|
||||
@@ -197,16 +201,17 @@ export function createMarkdownRoute(
|
||||
const { getCachedPayload, isPathVisible, ...rendererArgs } = args
|
||||
const render = createMarkdownRenderer(rendererArgs)
|
||||
return {
|
||||
GET: async (_req, { params }) => {
|
||||
GET: async (req, { params }) => {
|
||||
const negotiated = req.headers?.get(MARKDOWN_NEGOTIATED_HEADER) === '1'
|
||||
try {
|
||||
const { slug, locale } = routeOf(await params, rendererArgs.config)
|
||||
if (isPathVisible) {
|
||||
const multilingual = (rendererArgs.config?.locales.length ?? 0) > 1
|
||||
const path = `/${[...(multilingual ? [locale] : []), ...(slug ?? [])].join('/')}`
|
||||
if (!(await isPathVisible(path, locale))) {return markdownResponse(null, {})}
|
||||
if (!(await isPathVisible(path, locale))) {return markdownResponse(null, { negotiated })}
|
||||
}
|
||||
const md = await render({ slug, locale, payload: await getCachedPayload() })
|
||||
return markdownResponse(md, { canonical: canonicalOf(rendererArgs.baseUrl, rendererArgs.config, locale, slug) })
|
||||
return markdownResponse(md, { canonical: canonicalOf(rendererArgs.baseUrl, rendererArgs.config, locale, slug), negotiated })
|
||||
} catch (err) {
|
||||
console.warn('[iapl] createMarkdownRoute: render failed:', err)
|
||||
return new Response('Service unavailable', { headers: { 'content-type': 'text/plain' }, status: 503 })
|
||||
|
||||
@@ -5,7 +5,7 @@ export { createSearchRoute } from './createSearchRoute.js'
|
||||
export { applyDraftRelations, type DraftRelations, withoutDraftRelations } from './draftRelations.js'
|
||||
export { getArchiveEntries } from './getArchiveEntries.js'
|
||||
export type { ArchiveEntries } from './getArchiveEntries.js'
|
||||
export { MARKDOWN_PREFIX, markdownHref, prefersMarkdown } from './markdownNegotiation.js'
|
||||
export { appendVary, MARKDOWN_NEGOTIATED_HEADER, MARKDOWN_PREFIX, markdownHref, NEGOTIATED_CACHE_CONTROL, prefersMarkdown } from './markdownNegotiation.js'
|
||||
export { buildArchivePath, buildEntryPath, parsePageParam } from './paths.js'
|
||||
export { resolveNotFoundPage } from './resolveNotFoundPage.js'
|
||||
export { resolveRedirect } from './resolveRedirect.js'
|
||||
|
||||
@@ -13,6 +13,24 @@
|
||||
/** Default URL prefix the Markdown route is mounted at (see createMarkdownRenderer). */
|
||||
export const MARKDOWN_PREFIX = '/md'
|
||||
|
||||
/**
|
||||
* Request header the proxy sets when it rewrites an HTML URL to the Markdown route (content negotiation). The route
|
||||
* then answers {@link NEGOTIATED_CACHE_CONTROL} with `Vary: Accept`: the answer shares the page's URL, so no shared
|
||||
* cache may store it (security audit 2026-12, F3). A client sending it itself only makes its own answer private.
|
||||
*/
|
||||
export const MARKDOWN_NEGOTIATED_HEADER = 'x-iapl-markdown-negotiated'
|
||||
|
||||
/** Cache-Control of a Markdown answer given at an HTML URL. */
|
||||
export const NEGOTIATED_CACHE_CONTROL = 'private, no-store'
|
||||
|
||||
/** Adds a token to `Vary` once (case-insensitive), keeping what is there. */
|
||||
export function appendVary(headers: Headers | undefined, token: string): void {
|
||||
if (!headers) {return}
|
||||
const current = (headers.get('vary') ?? '').split(',').map((v) => v.trim()).filter(Boolean)
|
||||
if (current.some((v) => v === '*' || v.toLowerCase() === token.toLowerCase())) {return}
|
||||
headers.set('vary', [...current, token].join(', '))
|
||||
}
|
||||
|
||||
/**
|
||||
* The Markdown URL for a given page path. Keeps the `/md` prefix in ONE place so
|
||||
* the discovery link and the route agree.
|
||||
|
||||
@@ -0,0 +1,310 @@
|
||||
import { readdirSync, statSync } from 'node:fs'
|
||||
import { join, relative } from 'node:path'
|
||||
|
||||
import type { DoctorContext } from '../project.js'
|
||||
import type { DoctorRule, DoctorSeverity, RuleFinding } from '../types.js'
|
||||
|
||||
import { ATTACK_PROBES, createProbeContext, runAttackProbes } from '../../security/attackProbes.js'
|
||||
import { configFile, nextConfigFile } from '../project.js'
|
||||
import { stripComments } from '../util.js'
|
||||
|
||||
/**
|
||||
* Static security rules over the project's own code (security.md → "Security suites"). Each pattern is a class that
|
||||
* hits Payload / Next.js sites again and again: HTML or JSON printed into the page without escaping, the Local API
|
||||
* run with access switched off where a visitor reaches it, a query built from what the request sent, code built from
|
||||
* strings, secrets in the browser bundle, redirects and server-side fetches to an address the request chose.
|
||||
*
|
||||
* Patterns, not proof: a finding is a place to look. A place that is right on purpose carries a comment on the same
|
||||
* line or the line above — `// iapl-security-ok: <why>` — and the finding goes; a whole file or rule is silenced in
|
||||
* iapl-doctor.json (`rules: { "code-override-access": { files: ["src/lib/admin/**"], off: true, reason: "…" } }`).
|
||||
*/
|
||||
|
||||
/** The marker that accepts one place, with its reason: `// iapl-security-ok: the value is a number`. */
|
||||
export const SECURITY_OK_MARKER = 'iapl-security-ok'
|
||||
|
||||
const CODE_EXT = /\.[cm]?[jt]sx?$/
|
||||
/** Never scanned: generated, built or vendored code, and the project's tests. */
|
||||
const SKIP_DIR = new Set(['.agents', '.git', '.next', '.turbo', 'build', 'coverage', 'dist', 'node_modules', 'out'])
|
||||
const SKIP_FILE = /(?:^|\/)(?:payload-types\.ts|importMap\.js|next-env\.d\.ts)$|\.(?:test|spec)\.[cm]?[jt]sx?$|\.d\.ts$/
|
||||
/** Code no visitor reaches: seeds, migrations, scripts, tests. Rules about request input and access skip it. */
|
||||
const OFFLINE_PATH = /(?:^|\/)(?:seed|seeds|migrations|scripts|e2e|tests?|__tests__|fixtures)(?:\/|$)/
|
||||
|
||||
export type CodePatternId =
|
||||
| 'code-eval'
|
||||
| 'code-inner-html'
|
||||
| 'code-local-api-user'
|
||||
| 'code-open-redirect'
|
||||
| 'code-override-access'
|
||||
| 'code-public-secret'
|
||||
| 'code-raw-where'
|
||||
| 'code-shell'
|
||||
| 'code-ssrf'
|
||||
|
||||
export type CodeHit = { file: string; line: number; message: string; rule: CodePatternId; severity: DoctorSeverity; text: string }
|
||||
|
||||
/** Files to scan, relative to the project root: `src/` (or the root's app, lib, components… when there is none). */
|
||||
export function listCodeFiles(root: string, start: string): string[] {
|
||||
const out: string[] = []
|
||||
const walk = (dir: string) => {
|
||||
let names: string[]
|
||||
try {
|
||||
names = readdirSync(dir)
|
||||
} catch {
|
||||
return
|
||||
}
|
||||
for (const name of names) {
|
||||
if (SKIP_DIR.has(name)) {continue}
|
||||
const full = join(dir, name)
|
||||
let isDir = false
|
||||
try {
|
||||
isDir = statSync(full).isDirectory()
|
||||
} catch {
|
||||
continue
|
||||
}
|
||||
const rel = relative(root, full).split('\\').join('/')
|
||||
if (isDir) {walk(full)} else if (CODE_EXT.test(name) && !SKIP_FILE.test(rel)) {out.push(rel)}
|
||||
}
|
||||
}
|
||||
walk(join(root, start))
|
||||
return out.sort()
|
||||
}
|
||||
|
||||
/** The text of the `{ … }` (or `( … )`) that opens at `open`, up to `max` characters. */
|
||||
function balanced(code: string, open: number, max = 1500): string {
|
||||
const pairs: Record<string, string> = { '(': ')', '[': ']', '{': '}' }
|
||||
const stack: string[] = []
|
||||
let quote: null | string = null
|
||||
for (let i = open; i < code.length && i < open + max; i++) {
|
||||
const c = code[i]
|
||||
if (quote) {
|
||||
if (c === '\\') {i++; continue}
|
||||
if (c === quote) {quote = null}
|
||||
continue
|
||||
}
|
||||
if (c === '"' || c === "'" || c === '`') {quote = c; continue}
|
||||
if (pairs[c]) {stack.push(pairs[c])} else if (c === stack.at(-1)) {
|
||||
stack.pop()
|
||||
if (!stack.length) {return code.slice(open, i + 1)}
|
||||
}
|
||||
}
|
||||
return code.slice(open, open + max)
|
||||
}
|
||||
|
||||
const lineOf = (code: string, index: number) => code.slice(0, index).split('\n').length
|
||||
|
||||
/** True when the line, or the line above, carries `iapl-security-ok`. Read from the raw text (comments kept). */
|
||||
function accepted(raw: string[], line: number): boolean {
|
||||
return [raw[line - 1], raw[line - 2]].some((l) => l?.includes(SECURITY_OK_MARKER))
|
||||
}
|
||||
|
||||
/** What a request handed in: query, body, params, headers, search params. */
|
||||
const REQUEST_INPUT = String.raw`(?:req|request)\s*\.\s*(?:query|body|data|params|headers|json\s*\(|formData\s*\(|text\s*\()|searchParams\b|\bparams\s*\.|\bbody\s*\.|\bformData\s*\.\s*get\s*\(|nextUrl\s*\.\s*searchParams|routeParams\b`
|
||||
const FROM_REQUEST = new RegExp(REQUEST_INPUT)
|
||||
|
||||
/** __html values the plugin and common sanitizers make safe. */
|
||||
const SAFE_HTML = /\.replace\(\s*\/<\/g|sanitize|DOMPurify|xss\(|consentBannerScript|consentDecidedScript|themeScript|cookieButtonSpaceScript|jsonLdScript|serializeJsonLd|escapeHtml|escapeJson/
|
||||
|
||||
/** Secrets whose name says so; the public keys of browser tools are not secrets. */
|
||||
const SECRET_NAME = /NEXT_PUBLIC_[A-Z0-9_]*(?:SECRET|PASSWORD|PASSWD|PRIVATE|_TOKEN|DATABASE|DB_URI|MONGO|POSTGRES|SMTP_PASS|API_KEY_SECRET)[A-Z0-9_]*/g
|
||||
const SERVER_ONLY_ENV = /process\.env\.(?:PAYLOAD_SECRET|DATABASE_URI|DATABASE_URL|POSTGRES_URL|MONGODB_URI|R2_SECRET_ACCESS_KEY|R2_ACCESS_KEY_ID|TURNSTILE_SECRET_KEY|CRON_SECRET|IAPL_DOCTOR_TOKEN|IAPL_COOKIE_SCAN_TOKEN|SMTP_PASS(?:WORD)?|GRAPH_CLIENT_SECRET|RESEND_API_KEY)\b/g
|
||||
|
||||
/**
|
||||
* Every pattern hit in one file's code. `path` decides whether the file is reachable from the web (seeds, migrations,
|
||||
* scripts and tests are not). Exported for a project's own test or another scanner.
|
||||
*/
|
||||
export function scanCode(path: string, rawCode: string): CodeHit[] {
|
||||
const raw = rawCode.split('\n')
|
||||
// comments out, line count kept (block comments keep their newlines)
|
||||
const code = rawCode.replace(/\/\*[\s\S]*?\*\//g, (m) => m.replace(/[^\n]/g, ' ')).replace(/(^|[^:'"`\\])\/\/.*$/gm, '$1')
|
||||
const web = !OFFLINE_PATH.test(path)
|
||||
const client = /^\s*['"]use client['"]/m.test(code)
|
||||
const hits: CodeHit[] = []
|
||||
const add = (rule: CodePatternId, index: number, severity: DoctorSeverity, message: string) => {
|
||||
const line = lineOf(code, index)
|
||||
if (accepted(raw, line)) {return}
|
||||
hits.push({ file: path, line, message, rule, severity, text: (raw[line - 1] ?? '').trim().slice(0, 160) })
|
||||
}
|
||||
|
||||
// 1. HTML into the page: dangerouslySetInnerHTML / innerHTML with a value nothing escaped
|
||||
for (const m of code.matchAll(/dangerouslySetInnerHTML\s*=\s*\{/g)) {
|
||||
const value = balanced(code, m.index + m[0].length - 1, 800)
|
||||
if (SAFE_HTML.test(value)) {continue}
|
||||
const json = /JSON\.stringify/.test(value)
|
||||
add('code-inner-html', m.index, 'error', json
|
||||
? 'JSON printed into a <script> without escaping "<": a value with </script> ends the script (JsonLdGraph, or .replace(/</g, "\\\\u003c"))'
|
||||
: 'dangerouslySetInnerHTML with a value that no sanitizer passed (RenderRichText, or a sanitizer such as DOMPurify)')
|
||||
}
|
||||
for (const m of code.matchAll(/\.(?:innerHTML|outerHTML)\s*=(?!=)|\.insertAdjacentHTML\s*\(|document\.write(?:ln)?\s*\(/g)) {
|
||||
const rest = code.slice(m.index, m.index + 300).split('\n')[0]
|
||||
if (SAFE_HTML.test(rest) || /=\s*(?:''|""|``)\s*;?$/.test(rest)) {continue}
|
||||
add('code-inner-html', m.index, 'error', 'HTML written into the DOM from a string (innerHTML / insertAdjacentHTML / document.write)')
|
||||
}
|
||||
|
||||
// 2. code built from strings
|
||||
for (const m of code.matchAll(/(?<![\w.])eval\s*\(|new\s+Function\s*\(|\bvm\s*\.\s*(?:runInNewContext|runInThisContext|runInContext|compileFunction)\s*\(|\bset(?:Timeout|Interval)\s*\(\s*['"`]/g)) {
|
||||
add('code-eval', m.index, 'error', 'code built from a string (eval / new Function / vm / setTimeout with a string)')
|
||||
}
|
||||
for (const m of code.matchAll(/\b(?:exec|execSync)\s*\(\s*`[^`]*\$\{/g)) {
|
||||
add('code-shell', m.index, web ? 'error' : 'warning', 'a shell command built from a template string: pass arguments with execFile / spawn instead')
|
||||
}
|
||||
|
||||
// 3. secrets that reach the browser
|
||||
for (const m of code.matchAll(SECRET_NAME)) {
|
||||
add('code-public-secret', m.index, 'error', `${m[0]}: a NEXT_PUBLIC_ variable is copied into the browser bundle; a secret must never have that prefix`)
|
||||
}
|
||||
if (client) {
|
||||
for (const m of code.matchAll(SERVER_ONLY_ENV)) {
|
||||
add('code-public-secret', m.index, 'error', `${m[0]} read in a 'use client' file: rendered on the server, the value can end up in the HTML`)
|
||||
}
|
||||
}
|
||||
|
||||
if (!web) {return hits}
|
||||
|
||||
// 4. the Local API with access off where a visitor reaches it
|
||||
for (const m of code.matchAll(/overrideAccess\s*:\s*true\b/g)) {
|
||||
add('code-override-access', m.index, 'warning', 'overrideAccess: true in code a request reaches: every access rule is skipped; pass the user and overrideAccess: false, or say why with iapl-security-ok')
|
||||
}
|
||||
for (const m of code.matchAll(/\bpayload\s*\.\s*(?:find|findByID|findGlobal|count|create|update|updateGlobal|delete|duplicate|findVersions|findVersionByID|findGlobalVersions)\s*\(\s*\{/g)) {
|
||||
const args = balanced(code, m.index + m[0].length - 1)
|
||||
if (/\buser\s*[:,}]/.test(args) && !/overrideAccess\s*:/.test(args)) {
|
||||
add('code-local-api-user', m.index, 'warning', "the Local API gets a user but no overrideAccess: false — Payload then IGNORES the user's rules (overrideAccess defaults to true)")
|
||||
}
|
||||
}
|
||||
|
||||
// 5. a query built from what the request sent (operators, other fields, other people's records)
|
||||
for (const m of code.matchAll(/\bwhere\s*:\s*/g)) {
|
||||
const start = m.index + m[0].length
|
||||
const value = code[start] === '{' ? balanced(code, start, 600) : code.slice(start, start + 200).split(/[,\n})]/)[0]
|
||||
const direct = code[start] !== '{'
|
||||
if ((direct && (FROM_REQUEST.test(value) || /^(?:JSON\.parse|qs\.parse|parse)\s*\(/.test(value))) || (!direct && /:\s*(?:req|request)\s*\.\s*(?:query|body)\s*(?:[,}\n]|\.where)/.test(value))) {
|
||||
add('code-raw-where', m.index, 'error', 'a where clause taken from the request: the visitor picks operators and fields ($ne, exists, other users\' records). Build it from checked values')
|
||||
}
|
||||
}
|
||||
|
||||
// 6. redirects and server-side fetches to an address the request chose
|
||||
for (const m of code.matchAll(/\b(?:redirect|permanentRedirect|NextResponse\s*\.\s*redirect|Response\s*\.\s*redirect)\s*\(/g)) {
|
||||
const args = balanced(code, m.index + m[0].length - 1, 300)
|
||||
if (FROM_REQUEST.test(args) || /\.get\(\s*['"](?:next|redirect|redirectTo|returnTo|return|back|url|to|callbackUrl)['"]\s*\)/.test(args)) {
|
||||
if (/safeAdminBack|safeRedirect|isSafe|startsWith\(\s*['"]\/['"]\s*\)/.test(args)) {continue}
|
||||
add('code-open-redirect', m.index, 'warning', 'a redirect to an address from the request: accept a path of this site only (one leading "/", not "//" or "/\\\\")')
|
||||
}
|
||||
}
|
||||
for (const m of code.matchAll(/\bfetch\s*\(/g)) {
|
||||
const args = balanced(code, m.index + m[0].length - 1, 300)
|
||||
const target = args.slice(1).split(/,(?![^(]*\))/)[0] ?? ''
|
||||
if (FROM_REQUEST.test(target) || /\b(?:body|data|input|args)\s*\.\s*(?:url|href|endpoint|webhook|callback)\b/.test(target)) {
|
||||
add('code-ssrf', m.index, 'warning', 'a server-side fetch of an address the request chose (SSRF): allow a fixed list of hosts, refuse private addresses')
|
||||
}
|
||||
}
|
||||
return hits
|
||||
}
|
||||
|
||||
/** next.config / payload.config settings that open a known door. */
|
||||
export function scanConfigs(next: { code: string; file: string } | null, payload: { code: string; file: string } | null): RuleFinding[] {
|
||||
const out: RuleFinding[] = []
|
||||
if (next) {
|
||||
const c = stripComments(next.code)
|
||||
if (/dangerouslyAllowSVG\s*:\s*true/.test(c) && !/contentSecurityPolicy\s*:/.test(c)) {
|
||||
out.push({ file: next.file, fix: "images.contentSecurityPolicy: \"default-src 'self'; script-src 'none'; sandbox;\" and contentDispositionType: 'attachment'", message: 'images.dangerouslyAllowSVG without images.contentSecurityPolicy: an uploaded SVG runs script on the site\'s domain through /_next/image', severity: 'error' })
|
||||
}
|
||||
if (/hostname\s*:\s*['"]\*\*?['"]/.test(c)) {
|
||||
out.push({ file: next.file, fix: 'list the media hosts (buildImagesConfig)', message: 'images.remotePatterns allows every host: /_next/image fetches and resizes any image on the internet for anyone (cost, SSRF to inner addresses on old Next)', severity: 'warning' })
|
||||
}
|
||||
if (/allowedOrigins\s*:\s*\[[^\]]*['"]\*['"]/.test(c)) {
|
||||
out.push({ file: next.file, fix: 'name the origins', message: 'serverActions.allowedOrigins contains "*": Server Actions accept posts from any site (CSRF)', severity: 'error' })
|
||||
}
|
||||
if (/productionBrowserSourceMaps\s*:\s*true/.test(c)) {
|
||||
out.push({ file: next.file, fix: 'productionBrowserSourceMaps: false (upload maps to the error tracker instead)', message: 'productionBrowserSourceMaps: true publishes the source of every client file', severity: 'warning' })
|
||||
}
|
||||
}
|
||||
if (payload) {
|
||||
const c = stripComments(payload.code)
|
||||
if (/\bcors\s*:\s*['"]\*['"]/.test(c)) {
|
||||
out.push({ file: payload.file, fix: 'cors: [process.env.NEXT_PUBLIC_SERVER_URL]', message: "cors: '*': any site may call the API from a visitor's browser", severity: 'warning' })
|
||||
}
|
||||
if (/\bdebug\s*:\s*true/.test(c)) {
|
||||
out.push({ file: payload.file, fix: 'debug: process.env.NODE_ENV !== "production"', message: 'debug: true: Payload answers errors with their stack traces', severity: 'warning' })
|
||||
}
|
||||
if (/disablePlaygroundInProduction\s*:\s*false|disableIntrospectionInProduction\s*:\s*false/.test(c)) {
|
||||
out.push({ file: payload.file, fix: 'leave the GraphQL defaults on', message: 'the GraphQL playground or introspection is switched on in production: the whole schema is public', severity: 'warning' })
|
||||
}
|
||||
if (/maxDepth\s*:\s*(?:[2-9]\d|\d{3,})/.test(c)) {
|
||||
out.push({ file: payload.file, fix: 'maxDepth: 10 or less', message: 'maxDepth above 20: one request can populate a very deep tree (memory, time)', severity: 'warning' })
|
||||
}
|
||||
}
|
||||
return out
|
||||
}
|
||||
|
||||
const RULE_TEXT: Record<CodePatternId, string> = {
|
||||
'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<DoctorContext, 'read' | 'root' | 'src'>): 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<string, CodeHit[]>()
|
||||
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}: <why> (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:<id>` style settings in iapl-doctor.json. */
|
||||
export const LIVE_PROBE_IDS = ATTACK_PROBES.filter((p) => p.live).map((p) => p.id)
|
||||
@@ -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,
|
||||
|
||||
@@ -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' } })
|
||||
|
||||
@@ -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: '/',
|
||||
|
||||
@@ -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<Omit<TextField, 'type'>>
|
||||
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<UrlScheme, RegExp> = {
|
||||
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
|
||||
}
|
||||
@@ -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'
|
||||
|
||||
@@ -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<string, string>; method?: string }) => Promise<ProbeAnswer>
|
||||
/** 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<ProbeResult>
|
||||
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(/<script[^>]+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<string>()
|
||||
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: '[email protected]', 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 <img> 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: '[email protected]', 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<Array<{ probe: AttackProbe; result: ProbeResult }>> {
|
||||
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
|
||||
}
|
||||
@@ -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> | 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<string, unknown>
|
||||
@@ -86,14 +154,19 @@ export function parseCspReports(body: unknown): CspViolation[] {
|
||||
export function createCspReportRoute(args: CreateCspReportRouteArgs = {}): (request: Request) => Promise<Response> {
|
||||
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 {
|
||||
|
||||
@@ -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'
|
||||
|
||||
@@ -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<CollectionBeforeOperationHook>[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<PayloadRequest, 'payload' | 'user'> | 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<T extends ListArgs>(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<symbol, unknown>)[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']>), ...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<Pick<NonNullable<CollectionConfig['access']>, '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<SanitizedConfig, 'collections'>, 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
|
||||
}
|
||||
@@ -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<string>()
|
||||
|
||||
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<string, unknown> } } } | undefined): boolean {
|
||||
const iapl = req?.payload?.config?.custom?.iapl as { strictAccessAnswers?: boolean } | undefined
|
||||
return iapl?.strictAccessAnswers !== false
|
||||
}
|
||||
|
||||
/** For tests: forget which options were reported. */
|
||||
|
||||
@@ -80,6 +80,19 @@ export function assertPluginSwitches(options: Record<string, unknown>): 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)
|
||||
|
||||
@@ -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) => {
|
||||
|
||||
+34
-1
@@ -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
|
||||
|
||||
+43
-15
@@ -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<unknown>) => 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)
|
||||
}
|
||||
})
|
||||
|
||||
@@ -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, unknown>)[Symbol.for('iapl.accountMailMark')] && !(hook as Record<symbol, unknown>)[Symbol.for('iapl.accountMailAfterCommit')] && !(hook as Record<symbol, unknown>)[Symbol.for('iapl.signInRules')]
|
||||
const ruleHook = (hook: unknown) => !(hook as Record<symbol, unknown>)[Symbol.for('iapl.accountMailMark')] && !(hook as Record<symbol, unknown>)[Symbol.for('iapl.accountMailAfterCommit')] && !(hook as Record<symbol, unknown>)[Symbol.for('iapl.signInRules')] && !(hook as Record<symbol, unknown>)[Symbol.for('iapl.queryGuard')]
|
||||
|
||||
const TOTP_SECRET = 'JBSWY3DPEHPK3PXP'
|
||||
|
||||
|
||||
@@ -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)
|
||||
})
|
||||
|
||||
@@ -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: '[email protected]', password: PASSWORD, roles: ['editor'] } as never })
|
||||
await payload.create({ collection: 'customers' as never, data: { email: '[email protected]', password: PASSWORD } as never, overrideAccess: true })
|
||||
editor = await signIn('users', '[email protected]')
|
||||
customer = await signIn('customers', '[email protected]')
|
||||
}, 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)
|
||||
})
|
||||
})
|
||||
@@ -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: '<rule> <file>' → { 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)" }
|
||||
}
|
||||
}
|
||||
@@ -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 = ['</script><script>alert(1)</script>', '<img src=x onerror=alert(1)>', '"><svg onload=alert(1)>', '
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,<script>alert(1)</script>', '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 <script> (</script>, <!--, U+2028)', () => {
|
||||
const html = renderToStaticMarkup(createElement(JsonLdGraph, { schemas: XSS.map((name) => ({ name, '@type': 'Thing' })) as never }))
|
||||
expect(html.match(/<\/script>/gi)).toHaveLength(1)
|
||||
expect(html).not.toMatch(/<img|<svg|<!--/i)
|
||||
// what reaches the browser is still the same data
|
||||
const json = html.replace(/^<script[^>]*>/, '').replace(/<\/script>$/, '')
|
||||
expect(JSON.stringify(JSON.parse(json))).toContain('</script><script>alert(1)')
|
||||
})
|
||||
|
||||
it('first-paint scripts: a cookie name with </script> stays inside its string', () => {
|
||||
for (const cookieName of XSS) {
|
||||
const js = consentDecidedScript({ cookieName })
|
||||
expect(js).not.toMatch(/<\/script|<img|<svg/i)
|
||||
expect(() => new Script(js)).not.toThrow() // compiled, never run
|
||||
}
|
||||
})
|
||||
|
||||
// dev-config input only (the storage key is set in code, not by visitors): hardening, not a finding
|
||||
it('theme script: the storage key is a JSON string literal', () => {
|
||||
expect(() => new Script(themeScript({ allowToggle: true, defaultTheme: 'system', storageKey: 'a"b\\c' }))).not.toThrow()
|
||||
})
|
||||
|
||||
it('links: javascript:, data:, protocol-relative and control-character tricks never become an href', () => {
|
||||
// a link to another host is an editor's right (https://…); only schemes that run script are dropped
|
||||
for (const url of UNSAFE_URLS.filter((u) => !/^(?:\/\/|\/\\|\\\\)/.test(u))) {expect(safeHref(url), url).toBeNull()}
|
||||
for (const url of ['https://example.com', '/pl/o-nas', '#top', 'mailto:[email protected]', 'tel:+48123']) {expect(safeHref(url)).toBe(url)}
|
||||
})
|
||||
|
||||
it('rich text: a stored javascript: link loses its URL, keeps its text', () => {
|
||||
const data = { root: { type: 'root', children: [{ type: 'link', children: [{ type: 'text', text: 'click' }], fields: { linkType: 'custom', url: 'javascript:alert(1)' } }] } }
|
||||
expect(JSON.stringify(sanitizeRichTextLinks(data))).not.toContain('javascript:')
|
||||
expect(JSON.stringify(sanitizeRichTextLinks(data))).toContain('click')
|
||||
})
|
||||
|
||||
it('sitemap: a URL with markup is escaped in the XML', () => {
|
||||
const xml = buildSitemapXml([{ url: 'https://s.pl/a"><script>alert(1)</script>&' } as never])
|
||||
expect(xml).not.toContain('<script>')
|
||||
expect(xml).toContain('<script>')
|
||||
})
|
||||
})
|
||||
|
||||
describe('open redirect and header injection', () => {
|
||||
it('2FA back link: only a path inside the panel', () => {
|
||||
for (const back of [...UNSAFE_URLS, 'https://evil.example/admin', '/admin/../../evil', 'https:evil.example']) {
|
||||
const to = safeAdminBack(back, { adminRoute: '/admin', origin: 'https://site.pl' })
|
||||
expect(to, back).toMatch(/^\/admin(?:\/|$)/)
|
||||
expect(to).not.toMatch(/^\/\/|\\/)
|
||||
}
|
||||
})
|
||||
|
||||
it('admin language link: the way back is a path of this panel, never a host; no CR/LF reaches Location', () => {
|
||||
for (const referer of ['https://evil.example/admin/x', 'https://site.pl//evil.example', 'https://site.pl/admin\\..\\x', 'https://site.pl/admin/%0d%0aSet-Cookie:x=1', 'not a url', 'javascript:alert(1)']) {
|
||||
const to = adminPathFromReferer(referer, '/admin')
|
||||
expect(to, referer).toMatch(/^\/admin(?:\/|$)/)
|
||||
expect(to).not.toMatch(/[\r\n\\]|^\/\//)
|
||||
}
|
||||
})
|
||||
|
||||
it('locale redirect: a path that looks like a host stays on this site', () => {
|
||||
const NextResponse = { next: () => ({ cookies: { set: () => {} }, headers: new Headers() }), redirect: (u: string | URL) => ({ cookies: { set: () => {} }, headers: new Headers({ location: String(u) }) }) }
|
||||
const proxy = createProxy({ defaultLocale: 'pl', locales: [{ code: 'pl' }, { code: 'en' }] } as never, { NextResponse })
|
||||
for (const p of ['//evil.example', '/\\evil.example', '/%2F%2Fevil.example', '/.evil.example']) {
|
||||
const url = new URL(`https://site.pl${p}`)
|
||||
const res = proxy({ cookies: { get: () => undefined }, headers: new Headers(), nextUrl: { clone: () => new URL(url), pathname: url.pathname, search: '' }, url: url.toString() }) as unknown as { headers: Headers }
|
||||
expect(new URL(res.headers.get('location')!).host, p).toBe('site.pl')
|
||||
}
|
||||
})
|
||||
})
|
||||
|
||||
describe('injection — prototype pollution and operators in stored or sent JSON', () => {
|
||||
it('a consent cookie carrying __proto__ / constructor pollutes nothing', () => {
|
||||
const raw = encodeURIComponent('{"version":1,"__proto__":{"polluted":true},"constructor":{"prototype":{"polluted2":true}},"state":{"analytics":true,"__proto__":{"x":1}}}')
|
||||
const record = readConsentRecord(raw, 1)
|
||||
parseConsent(raw, 1)
|
||||
expect(({} as Record<string, unknown>).polluted).toBeUndefined()
|
||||
expect(({} as Record<string, unknown>).polluted2).toBeUndefined()
|
||||
expect(Object.getPrototypeOf(record)).toBe(Object.prototype)
|
||||
expect(record?.state.analytics).toBe(true)
|
||||
})
|
||||
})
|
||||
|
||||
describe('log injection', () => {
|
||||
// F1 (security-audit-2026-12-findings.md), fixed in 1.18.0: the default line holds origins and paths, no control characters.
|
||||
it('F1: a CSP report cannot write a forged line into the server log', async () => {
|
||||
const lines: string[] = []
|
||||
const warn = vi.spyOn(console, 'warn').mockImplementation((...a: unknown[]) => {lines.push(a.join(' '))})
|
||||
try {
|
||||
const route = createCspReportRoute({ rateLimit: false })
|
||||
await route(new Request('http://localhost/api/csp-report', { body: JSON.stringify({ 'csp-report': { 'blocked-uri': 'x\n[iapl] admin signed in: [email protected] from 10.0.0.1', 'document-uri': 'https://s.pl/', 'effective-directive': 'script-src' } }), method: 'POST' }))
|
||||
} finally {
|
||||
warn.mockRestore()
|
||||
}
|
||||
expect(lines.join('\n').split('\n')).toHaveLength(1)
|
||||
})
|
||||
|
||||
it('F1: the default line keeps the blocked origin and the page path (no query), every value capped', () => {
|
||||
const line = cspLogLine({
|
||||
blockedUri: 'https://cdn.evil.example/x.js?token=secret',
|
||||
documentUri: 'https://s.pl/pl/[email protected]#form',
|
||||
effectiveDirective: 'script-src-elem',
|
||||
lineNumber: 3,
|
||||
sourceFile: `https://s.pl/_next/static/a.js?v=1\u2028${'x'.repeat(500)}`,
|
||||
})
|
||||
expect(line).toContain('blocked=https://cdn.evil.example ')
|
||||
expect(line).toContain('page=/pl/kontakt')
|
||||
expect(line).not.toMatch(/secret|a@b\.pl|\u2028/)
|
||||
expect(line.length).toBeLessThan(4 * CSP_LOG_VALUE_MAX)
|
||||
expect(cspLogLine({ blockedUri: 'inline' })).toContain('blocked=inline')
|
||||
})
|
||||
|
||||
it('F1: one request handles at most maxReports violations; a project\'s onReport gets the raw values', async () => {
|
||||
const seen: string[] = []
|
||||
const route = createCspReportRoute({ maxReports: 3, onReport: (v) => {seen.push(v.blockedUri ?? '')}, rateLimit: false })
|
||||
const many = Array.from({ length: 40 }, (_, i) => ({ type: 'csp-violation', body: { blockedURL: `x\n${i}`, documentURL: 'https://s.pl/' } }))
|
||||
expect((await route(new Request('http://localhost/api/csp-report', { body: JSON.stringify(many), method: 'POST' }))).status).toBe(204)
|
||||
expect(seen).toEqual(['x\n0', 'x\n1', 'x\n2'])
|
||||
})
|
||||
|
||||
it('F1: over the per-client limit the route answers 204 and handles nothing', async () => {
|
||||
const seen: number[] = []
|
||||
const route = createCspReportRoute({ onReport: () => {seen.push(1)}, rateLimit: { max: 2, windowMs: 60_000 } })
|
||||
const send = () => route(new Request('http://localhost/api/csp-report', { body: JSON.stringify({ 'csp-report': { 'blocked-uri': 'inline' } }), headers: { 'x-forwarded-for': '203.0.113.77' }, method: 'POST' }))
|
||||
for (let i = 0; i < 4; i++) {expect((await send()).status).toBe(204)}
|
||||
expect(seen).toHaveLength(2)
|
||||
})
|
||||
})
|
||||
|
||||
describe('denial of service — bodies and batches', () => {
|
||||
it('CSP reports: a chunked body without content-length is cut at the cap (413)', async () => {
|
||||
const res = await createCspReportRoute({ maxBytes: 1024 })(chunked('x'.repeat(200_000)))
|
||||
expect(res.status).toBe(413)
|
||||
})
|
||||
|
||||
it('MCP: a body over the cap is 413 and a batch over the cap is refused before any database work', async () => {
|
||||
const getCachedPayload = vi.fn()
|
||||
const { POST } = createMcpRoute({ config: { defaultLocale: 'pl', locales: ['pl'] } as never, getCachedPayload, rateLimit: false } as never)
|
||||
expect((await POST(chunked(`[${'1,'.repeat(40_000)}1]`))).status).toBe(413)
|
||||
const batch = Array.from({ length: 11 }, (_, i) => ({ id: i, jsonrpc: '2.0', method: 'tools/list' }))
|
||||
expect((await POST(new Request('http://localhost/api/mcp', { body: JSON.stringify(batch), method: 'POST' }))).status).toBe(400)
|
||||
expect(getCachedPayload).not.toHaveBeenCalled()
|
||||
})
|
||||
})
|
||||
|
||||
describe('cache poisoning — one URL, two bodies', () => {
|
||||
// F3, fixed in 1.18.0: `Accept: text/markdown` on an HTML URL gets the Markdown copy at the SAME URL — now private,
|
||||
// never stored by a shared cache, with Vary: Accept on both answers.
|
||||
it('F3: the Markdown answer given at an HTML URL says it varies by Accept (or is not stored by shared caches)', () => {
|
||||
const rewrites: string[] = []
|
||||
const response = () => ({ cookies: { set: () => {} }, headers: new Headers() })
|
||||
const NextResponse = { next: response, redirect: response, rewrite: (u: string | URL) => {rewrites.push(String(u)); return response()} }
|
||||
const proxy = createProxy({ defaultLocale: 'pl', locales: [{ code: 'pl' }, { code: 'en' }] } as never, { markdown: true, NextResponse })
|
||||
const url = new URL('https://site.pl/pl/o-nas')
|
||||
const res = proxy({ cookies: { get: () => undefined }, headers: new Headers({ accept: 'text/markdown' }), nextUrl: { clone: () => new URL(url), pathname: url.pathname, search: '' }, url: url.toString() }) as unknown as { headers: Headers }
|
||||
expect(rewrites).toHaveLength(1)
|
||||
const md = markdownResponse('# x', { negotiated: true })
|
||||
const varies = /accept/i.test(res.headers.get('vary') ?? '') || /accept/i.test(md.headers.get('vary') ?? '')
|
||||
const private_ = /private|no-store/.test(md.headers.get('cache-control') ?? '')
|
||||
expect(varies || private_).toBe(true)
|
||||
expect(res.headers.get('cache-control')).toBe('private, no-store')
|
||||
expect(res.headers.get('vary')).toBe('Accept')
|
||||
})
|
||||
|
||||
it('F3: the route answers private + Vary: Accept only when the proxy marked the request; /md/… stays public', async () => {
|
||||
expect(markdownResponse('# x').headers.get('cache-control')).toMatch(/public/)
|
||||
expect(markdownResponse('# x').headers.get('vary')).toBeNull()
|
||||
expect(markdownResponse(null, { negotiated: true }).headers.get('cache-control')).toBe('private, no-store')
|
||||
})
|
||||
|
||||
it('F3: the proxy passes the marker to the route, adds Vary: Accept to pages, and markdown.negotiate: false turns negotiation off', () => {
|
||||
const seen: { headers?: Headers; url: string }[] = []
|
||||
const response = () => ({ cookies: { set: () => {} }, headers: new Headers() })
|
||||
const NextResponse = { next: response, redirect: response, rewrite: (u: string | URL, init?: { request?: { headers: Headers } }) => {seen.push({ headers: init?.request?.headers, url: String(u) }); return response()} }
|
||||
const ask = (accept: string, markdown: unknown) => {
|
||||
const url = new URL('https://site.pl/pl/o-nas')
|
||||
return createProxy({ defaultLocale: 'pl', locales: [{ code: 'pl' }, { code: 'en' }] } as never, { markdown: markdown as never, NextResponse })({ cookies: { get: () => undefined }, headers: new Headers({ accept }), nextUrl: { clone: () => new URL(url), pathname: url.pathname, search: '' }, url: url.toString() }) as unknown as { headers: Headers }
|
||||
}
|
||||
ask('text/markdown', true)
|
||||
expect(seen[0].headers?.get(MARKDOWN_NEGOTIATED_HEADER)).toBe('1')
|
||||
expect(ask('text/html', true).headers.get('vary')).toBe('Accept')
|
||||
seen.length = 0
|
||||
const off = ask('text/markdown', { negotiate: false })
|
||||
expect(seen).toHaveLength(0)
|
||||
expect(off.headers.get('vary')).toBeNull()
|
||||
expect(ask('text/markdown', { prefix: '/ai' }) && seen[0].url).toBe('https://site.pl/ai/pl/o-nas')
|
||||
})
|
||||
})
|
||||
|
||||
describe('denial of service and injection — lists from outside (F4, F5)', () => {
|
||||
const hook = buildQueryGuardHook({})
|
||||
const run = (args: Record<string, unknown>, req: Record<string, unknown>, operation = 'read', h = hook) =>
|
||||
h({ args, collection: { slug: 'pages' }, context: {}, operation, req } as never) as Record<string, unknown>
|
||||
const visitor = { payload: { config: { admin: { user: 'users' }, custom: {} } }, payloadAPI: 'REST', user: null }
|
||||
const staff = { ...visitor, user: { id: 1, collection: 'users' } }
|
||||
|
||||
it('F4: a caller that is not staff gets at most 100 per request; pagination=false and limit=0 become one page', () => {
|
||||
expect(run({ limit: 100000 }, visitor)).toMatchObject({ limit: 100, pagination: true })
|
||||
expect(run({ pagination: false }, visitor)).toMatchObject({ limit: 100, pagination: true })
|
||||
expect(run({ limit: 0 }, visitor)).toMatchObject({ limit: 100, pagination: true })
|
||||
expect(run({ limit: 20 }, visitor)).toEqual({ limit: 20 })
|
||||
expect(run({ limit: 5000 }, { ...visitor, user: { id: 1, collection: 'customers' } })).toMatchObject({ limit: 100 })
|
||||
expect(run({ limit: 5000 }, visitor, 'findVersions')).toMatchObject({ limit: 100 })
|
||||
})
|
||||
|
||||
it('F4: staff, the Local API, one document by id and listLimit: false are left alone; max / exclude / staff adapt it', () => {
|
||||
expect(run({ limit: 5000 }, staff)).toEqual({ limit: 5000 })
|
||||
expect(run({ limit: 5000 }, { ...visitor, payloadAPI: 'local' })).toEqual({ limit: 5000 })
|
||||
expect(run({ id: 'a', limit: 5000 }, visitor)).toEqual({ id: 'a', limit: 5000 })
|
||||
expect(run({ limit: 5000 }, visitor, 'read', buildQueryGuardHook({ listLimit: false }))).toEqual({ limit: 5000 })
|
||||
expect(run({ limit: 5000 }, visitor, 'read', buildQueryGuardHook({ listLimit: { max: 20 } }))).toMatchObject({ limit: 20 })
|
||||
expect(run({ limit: 5000 }, visitor, 'read', buildQueryGuardHook({ listLimit: { exclude: ['pages'] } }))).toEqual({ limit: 5000 })
|
||||
expect(run({ limit: 5000 }, staff, 'read', buildQueryGuardHook({ listLimit: { staff: true } }))).toMatchObject({ limit: 100 })
|
||||
expect(capListLimit({ limit: 7 }, 5)).toEqual({ limit: 5, pagination: true })
|
||||
})
|
||||
|
||||
it('F5: a sort that names a database operator is refused with 400, for staff too; the Local API and refuseOperatorSort: false are not touched', () => {
|
||||
for (const sort of ['$where', '-$where', '$natural', 'title.$ne', ['title', '-$where'], 'title,-$where']) {
|
||||
expect(isOperatorSort(sort), String(sort)).toBe(true)
|
||||
expect(() => run({ sort }, staff), String(sort)).toThrow(expect.objectContaining({ status: 400 }))
|
||||
}
|
||||
for (const sort of ['title', '-createdAt', 'meta.title', ['title', '-date']]) {expect(isOperatorSort(sort)).toBe(false)}
|
||||
expect(run({ sort: '$where' }, { ...visitor, payloadAPI: 'local' })).toEqual({ sort: '$where' })
|
||||
expect(run({ sort: '$where' }, visitor, 'read', buildQueryGuardHook({ refuseOperatorSort: false }))).toEqual({ sort: '$where' })
|
||||
})
|
||||
|
||||
it('the document locks: staff only by default, the project\'s rule per operation wins, a config without them is left alone', () => {
|
||||
const config = { collections: [{ slug: LOCKED_DOCUMENTS_SLUG, access: {} }] } as never as { collections: { access: Record<string, unknown>; slug: string }[] }
|
||||
expect(applyLockedDocumentsAccess(config as never)).toBe(true)
|
||||
const rule = config.collections[0].access.read as (a: unknown) => boolean
|
||||
expect(rule({ req: { payload: visitor.payload, user: { id: 1, collection: 'customers' } } })).toBe(false)
|
||||
expect(rule({ req: { payload: visitor.payload, user: null } })).toBe(false)
|
||||
expect(rule({ req: { payload: visitor.payload, user: { id: 1, collection: 'users' } } })).toBe(true)
|
||||
const own = () => true
|
||||
applyLockedDocumentsAccess(config as never, { read: own })
|
||||
expect(config.collections[0].access.read).toBe(own)
|
||||
expect(applyLockedDocumentsAccess({ collections: [] } as never)).toBe(false)
|
||||
})
|
||||
})
|
||||
|
||||
describe('XSS — addresses rendered into href (F2)', () => {
|
||||
it('buildUrlField refuses javascript:, data: and protocol-relative addresses; https passes; other kinds only when listed', () => {
|
||||
const field = buildUrlField({ required: true })
|
||||
const validate = field.validate as (v: unknown, o?: unknown) => string | true
|
||||
for (const url of UNSAFE_URLS) {expect(validate(url), url).not.toBe(true)}
|
||||
expect(validate('https://instagram.com/studio')).toBe(true)
|
||||
expect(validate('')).not.toBe(true)
|
||||
expect(validate('mailto:[email protected]')).not.toBe(true)
|
||||
expect(isAllowedUrl('mailto:[email protected]', ['mailto'])).toBe(true)
|
||||
expect(isAllowedUrl('/pl/o-nas', ['relative'])).toBe(true)
|
||||
expect(isAllowedUrl('//evil.example', ['relative'])).toBe(false)
|
||||
expect(buildUrlField({ name: 'website', overrides: { localized: true } })).toMatchObject({ name: 'website', type: 'text', localized: true })
|
||||
})
|
||||
})
|
||||
@@ -0,0 +1,143 @@
|
||||
/**
|
||||
* Static security rules (src/modules/doctor/rules/securityCode.ts): each pattern found and not found, the
|
||||
* accept marker, the config checks, the doctor wiring — and the GATE: the plugin's own code and the reference site
|
||||
* hold no place that matches a rule unless test/security-patterns.allow.json judges it.
|
||||
*/
|
||||
import { mkdirSync, mkdtempSync, readFileSync, rmSync, writeFileSync } from 'node:fs'
|
||||
import { tmpdir } from 'node:os'
|
||||
import path from 'node:path'
|
||||
import { afterAll, describe, expect, test } from 'vitest'
|
||||
|
||||
import { listCodeFiles, scanCode, scanConfigs } from '../src/modules/doctor/rules/securityCode.js'
|
||||
import { runDoctor } from '../src/modules/doctor/run.js'
|
||||
|
||||
const root = path.resolve(import.meta.dirname, '..')
|
||||
const rules = (file: string, code: string) => scanCode(file, code).map((h) => h.rule)
|
||||
|
||||
describe('static security rules — each pattern', () => {
|
||||
test('HTML and JSON printed into the page', () => {
|
||||
expect(rules('src/a.tsx', '<div dangerouslySetInnerHTML={{ __html: post.body }} />')).toEqual(['code-inner-html'])
|
||||
expect(rules('src/a.tsx', '<script dangerouslySetInnerHTML={{ __html: JSON.stringify(schema) }} />')).toEqual(['code-inner-html'])
|
||||
expect(scanCode('src/a.tsx', '<script dangerouslySetInnerHTML={{ __html: JSON.stringify(schema) }} />')[0].message).toMatch(/<\/script>/)
|
||||
expect(rules('src/a.tsx', "<script dangerouslySetInnerHTML={{ __html: JSON.stringify(s).replace(/</g, '\\\\u003c') }} />")).toEqual([])
|
||||
expect(rules('src/a.tsx', '<div dangerouslySetInnerHTML={{ __html: DOMPurify.sanitize(html) }} />')).toEqual([])
|
||||
expect(rules('src/a.ts', 'el.innerHTML = text')).toEqual(['code-inner-html'])
|
||||
expect(rules('src/a.ts', "el.innerHTML = ''")).toEqual([])
|
||||
expect(rules('src/a.ts', 'el.insertAdjacentHTML("beforeend", x)')).toEqual(['code-inner-html'])
|
||||
})
|
||||
|
||||
test('code from strings and shell commands', () => {
|
||||
expect(rules('src/a.ts', 'eval(code)')).toEqual(['code-eval'])
|
||||
expect(rules('src/a.ts', 'const f = new Function("a", body)')).toEqual(['code-eval'])
|
||||
expect(rules('src/a.ts', 'setTimeout("go()", 10)')).toEqual(['code-eval'])
|
||||
expect(rules('src/a.ts', 'setTimeout(() => go(), 10); retrieval(x)')).toEqual([])
|
||||
expect(rules('src/a.ts', 'execSync(`convert ${file} out.png`)')).toEqual(['code-shell'])
|
||||
expect(rules('src/a.ts', "execFileSync('convert', [file, 'out.png'])")).toEqual([])
|
||||
})
|
||||
|
||||
test('secrets that reach the browser', () => {
|
||||
expect(rules('src/a.ts', 'const k = process.env.NEXT_PUBLIC_STRIPE_SECRET_KEY')).toEqual(['code-public-secret'])
|
||||
expect(rules('src/a.ts', 'const k = process.env.NEXT_PUBLIC_TURNSTILE_SITE_KEY')).toEqual([])
|
||||
expect(rules('src/a.tsx', "'use client'\nconst s = process.env.PAYLOAD_SECRET")).toEqual(['code-public-secret'])
|
||||
expect(rules('src/a.tsx', 'const s = process.env.PAYLOAD_SECRET')).toEqual([])
|
||||
})
|
||||
|
||||
test('the Local API with access off where a request reaches it', () => {
|
||||
expect(rules('src/app/api/x/route.ts', "await payload.find({ collection: 'orders', overrideAccess: true })")).toEqual(['code-override-access'])
|
||||
expect(rules('src/seed/run.ts', "await payload.find({ collection: 'orders', overrideAccess: true })")).toEqual([])
|
||||
expect(rules('src/app/page.tsx', "await payload.find({ collection: 'orders', user: req.user })")).toEqual(['code-local-api-user'])
|
||||
expect(rules('src/app/page.tsx', "await payload.find({ collection: 'orders', user, overrideAccess: false })")).toEqual([])
|
||||
expect(rules('src/app/page.tsx', "await payload.find({ collection: 'pages', where: { slug: { equals: slug } } })")).toEqual([])
|
||||
})
|
||||
|
||||
test('a where clause from the request', () => {
|
||||
expect(rules('src/app/api/x/route.ts', "payload.find({ collection: 'pages', where: req.query.where })")).toEqual(['code-raw-where'])
|
||||
expect(rules('src/app/api/x/route.ts', "payload.find({ collection: 'pages', where: JSON.parse(searchParams.get('w')) })")).toEqual(['code-raw-where'])
|
||||
expect(rules('src/app/api/x/route.ts', "payload.find({ collection: 'pages', where: { slug: { equals: String(params.slug) } } })")).toEqual([])
|
||||
})
|
||||
|
||||
test('redirects and fetches to an address from the request', () => {
|
||||
expect(rules('src/app/x/page.tsx', "redirect(searchParams.get('next'))")).toEqual(['code-open-redirect'])
|
||||
expect(rules('src/app/x/route.ts', "return NextResponse.redirect(new URL(req.nextUrl.searchParams.get('to'), req.url))")).toEqual(['code-open-redirect'])
|
||||
expect(rules('src/app/x/page.tsx', "redirect('/pl')")).toEqual([])
|
||||
expect(rules('src/app/x/route.ts', 'const r = await fetch(body.url)')).toEqual(['code-ssrf'])
|
||||
expect(rules('src/app/x/route.ts', "const r = await fetch(searchParams.get('u'))")).toEqual(['code-ssrf'])
|
||||
expect(rules('src/app/x/route.ts', "const r = await fetch('https://api.example.com/x', { body: JSON.stringify(body) })")).toEqual([])
|
||||
})
|
||||
|
||||
test('a place accepted with its reason; comments do not count', () => {
|
||||
expect(rules('src/a.tsx', '// iapl-security-ok: escaped by toSafeHtml above\n<div dangerouslySetInnerHTML={{ __html: html }} />')).toEqual([])
|
||||
expect(rules('src/a.ts', 'eval(x) // iapl-security-ok: build-time only')).toEqual([])
|
||||
expect(rules('src/a.ts', '// eval(x) in a comment\n/* new Function() */')).toEqual([])
|
||||
})
|
||||
|
||||
test('config settings that open a door', () => {
|
||||
const next = (code: string) => scanConfigs({ code, file: 'next.config.ts' }, null).map((f) => f.severity)
|
||||
expect(next("images: { dangerouslyAllowSVG: true }")).toEqual(['error'])
|
||||
expect(next("images: { dangerouslyAllowSVG: true, contentSecurityPolicy: \"sandbox\" }")).toEqual([])
|
||||
expect(next("images: { remotePatterns: [{ hostname: '**' }] }")).toEqual(['warning'])
|
||||
expect(next("experimental: { serverActions: { allowedOrigins: ['*'] } }")).toEqual(['error'])
|
||||
const payload = (code: string) => scanConfigs(null, { code, file: 'src/payload.config.ts' }).length
|
||||
expect(payload("cors: '*', debug: true, graphQL: { disableIntrospectionInProduction: false }, maxDepth: 50")).toBe(4)
|
||||
expect(payload('cors: [process.env.NEXT_PUBLIC_SERVER_URL], maxDepth: 10')).toBe(0)
|
||||
})
|
||||
})
|
||||
|
||||
describe('static security rules — in the doctor', () => {
|
||||
const dirs: string[] = []
|
||||
afterAll(() => {for (const d of dirs) {rmSync(d, { force: true, recursive: true })}})
|
||||
|
||||
test('iapl-doctor --only security reports a project\'s own unsafe code, and an iapl-doctor.json entry silences one file', async () => {
|
||||
const dir = mkdtempSync(path.join(tmpdir(), 'iapl-sec-'))
|
||||
dirs.push(dir)
|
||||
const files: Record<string, string> = {
|
||||
'package.json': JSON.stringify({ name: 'x', dependencies: {} }),
|
||||
'src/app/(frontend)/[locale]/page.tsx': '<div dangerouslySetInnerHTML={{ __html: page.html }} />',
|
||||
'src/app/api/orders/route.ts': "export const GET = async (req) => Response.json(await payload.find({ collection: 'orders', where: req.query.where, overrideAccess: true }))",
|
||||
'src/seed/index.ts': "await payload.find({ collection: 'orders', overrideAccess: true })",
|
||||
}
|
||||
for (const [rel, content] of Object.entries(files)) {
|
||||
mkdirSync(path.dirname(path.join(dir, rel)), { recursive: true })
|
||||
writeFileSync(path.join(dir, rel), content)
|
||||
}
|
||||
const report = await runDoctor({ offline: true, only: ['code-patterns'], packageRoot: root, root: dir, writeSeen: false })
|
||||
const found = report.findings.filter((f) => !f.silenced).map((f) => `${f.rule} ${f.file}`).sort()
|
||||
expect(found).toEqual([
|
||||
'code-inner-html src/app/(frontend)/[locale]/page.tsx',
|
||||
'code-override-access src/app/api/orders/route.ts',
|
||||
'code-raw-where src/app/api/orders/route.ts',
|
||||
])
|
||||
const silenced = await runDoctor({
|
||||
config: { rules: { 'code-override-access': { files: ['src/app/api/**'], off: true, reason: 'orders are public in this shop' } } },
|
||||
offline: true, only: ['security'], packageRoot: root, root: dir, writeSeen: false,
|
||||
})
|
||||
expect(silenced.findings.find((f) => f.rule === 'code-override-access')?.silenced, JSON.stringify(silenced.findings.map((f) => [f.rule, f.message.slice(0, 80)]))).toBe(true)
|
||||
})
|
||||
})
|
||||
|
||||
describe('GATE: the plugin and the reference site hold only judged places', () => {
|
||||
test('every hit is in test/security-patterns.allow.json with a reason, and no count grew', () => {
|
||||
const allow = (JSON.parse(readFileSync(path.join(root, 'test/security-patterns.allow.json'), 'utf8')) as { entries: Record<string, { count: number; reason: string }> }).entries
|
||||
const counts = new Map<string, number>()
|
||||
const where = new Map<string, string[]>()
|
||||
for (const [base, start, prefix] of [[root, 'src', ''], [path.join(root, 'reference'), 'src', 'reference/'], [root, 'bin', ''], [root, 'scripts', '']] as const) {
|
||||
for (const file of listCodeFiles(base, start)) {
|
||||
for (const hit of scanCode(file, readFileSync(path.join(base, file), 'utf8'))) {
|
||||
const key = `${hit.rule} ${prefix}${hit.file}`
|
||||
counts.set(key, (counts.get(key) ?? 0) + 1)
|
||||
where.set(key, [...(where.get(key) ?? []), `${prefix}${hit.file}:${hit.line} ${hit.text}`])
|
||||
}
|
||||
}
|
||||
}
|
||||
const problems: string[] = []
|
||||
for (const [key, n] of counts) {
|
||||
const entry = allow[key]
|
||||
if (!entry) {problems.push(`NOT JUDGED ${key} (${n}):\n ${where.get(key)!.join('\n ')}`)} else if (n > entry.count) {problems.push(`MORE THAN JUDGED ${key}: ${n} > ${entry.count}\n ${where.get(key)!.join('\n ')}`)}
|
||||
}
|
||||
for (const [key, entry] of Object.entries(allow)) {
|
||||
if (!entry.reason?.trim() || /TODO/i.test(entry.reason)) {problems.push(`no reason: ${key}`)}
|
||||
if ((counts.get(key) ?? 0) < entry.count) {console.warn(`[security-patterns] ${key}: ${counts.get(key) ?? 0} now, ${entry.count} judged — lower the count`)}
|
||||
}
|
||||
expect(problems, problems.join('\n')).toEqual([])
|
||||
})
|
||||
})
|
||||
@@ -11,6 +11,7 @@ import { describe, expect, test, vi } from 'vitest'
|
||||
|
||||
import { adminOrEditor } from '../src/modules/access/access.js'
|
||||
import { visitorWritableEntities } from '../src/modules/doctor/visitorWrites.js'
|
||||
import { applyLockedDocumentsAccess } from '../src/modules/security/queryGuard.js'
|
||||
import { iapl } from '../src/plugin.js'
|
||||
import { buildTestConfig } from './helpers.js'
|
||||
|
||||
@@ -49,6 +50,13 @@ describe('visitorWritableEntities', () => {
|
||||
}
|
||||
}, 30_000)
|
||||
|
||||
test('Payload\'s document locks are not listed once iapl\'s staff-only rule is on (lockedDocuments, 1.18.0)', async () => {
|
||||
const config = await build([{ slug: 'customers', access: { create: () => false }, auth: true, fields: [] }])
|
||||
expect(await visitorWritableEntities(live(config))).toContain('payload-locked-documents:create')
|
||||
applyLockedDocumentsAccess(config)
|
||||
expect((await visitorWritableEntities(live(config))).filter((e) => e.startsWith('payload-locked-documents'))).toEqual([])
|
||||
}, 30_000)
|
||||
|
||||
test('a site with only the staff login collection: nothing to report', async () => {
|
||||
const config = await build([{ slug: 'pages', access: { read: () => true }, fields: [{ name: 'title', type: 'text' }] }])
|
||||
expect(await visitorWritableEntities(live(config))).toEqual([])
|
||||
|
||||
Reference in New Issue
Block a user