Access callbacks allow only on a literal true (owner's decision for 1.18.0), strictAccessAnswers: false for the old reading; the new 1.18.0 security options checked strictly at start; docs, skills, changelog

Co-Authored-By: Claude Opus 5.5 <[email protected]>
This commit is contained in:
Radosław Smoliński
2026-12-01 17:07:04 +01:00
co-authored by Claude Opus 5.5
parent d90825a396
commit c6bfb621f5
25 changed files with 1450 additions and 62 deletions
+8 -1
View File
@@ -125,7 +125,14 @@ once there are more than 20.
> 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. **New doctor findings the first time** (the suites below): `iapl-doctor --only security` reads the project's own
> 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)
+1 -1
View File
@@ -1244,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` |
+2 -1
View File
@@ -75,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,7 @@ 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 } }` |
@@ -653,6 +653,7 @@ Server only (`pnpm payload run`); never import it from client code, the Payload
| `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?, 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`. |
+3 -1
View File
@@ -58,7 +58,9 @@ rewrites to `/md/…` copies the headers (content.md); `markdown: { negotiate: f
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) the first `iapl-doctor --only security` run shows the new `code-*` / `config-dangerous` rules — judge each, mark a
(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 -1
View File
@@ -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 |
+1 -1
View File
@@ -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`.
+13 -8
View File
@@ -1404,14 +1404,19 @@ new site from `iapl create` use both (`src/globals/Company.ts`, `Footer.tsx`, th
## 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
@@ -75,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,7 @@ 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 } }` |
@@ -653,6 +653,7 @@ Server only (`pnpm payload run`); never import it from client code, the Payload
| `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?, 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`. |
@@ -58,7 +58,9 @@ rewrites to `/md/…` copies the headers (content.md); `markdown: { negotiate: f
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) the first `iapl-doctor --only security` run shows the new `code-*` / `config-dangerous` rules — judge each, mark a
(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.
File diff suppressed because it is too large Load Diff
+2 -1
View File
@@ -633,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`.
+2 -2
View File
@@ -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>) =>
+2 -2
View File
@@ -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) =>
+2 -2
View File
@@ -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' } })
+31 -11
View File
@@ -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. */
+13
View File
@@ -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)
+5
View File
@@ -1067,6 +1067,11 @@ 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 })
+9 -1
View File
@@ -322,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[]
@@ -351,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
View File
@@ -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)
}
})
+8
View File
@@ -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)
})