From c6bfb621f563530bb08586b0b15733b95289f7b9 Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?Rados=C5=82aw=20Smoli=C5=84ski?= Date: Tue, 1 Dec 2026 17:07:04 +0100 Subject: [PATCH] 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 --- docs/CHANGELOG.md | 9 +- docs/agent/AGENT.md | 2 +- docs/agent/skills/iapl-doctor/SKILL.md | 3 +- docs/agent/skills/iapl-reference/SKILL.md | 1 + .../skills/iapl-reference/resources/api.md | 1 + docs/agent/skills/iapl-upgrade/SKILL.md | 4 +- docs/cookie-scanner.md | 2 +- docs/doctor.md | 2 +- docs/security.md | 21 +- reference/.agents/skills/iapl-doctor/SKILL.md | 3 +- .../.agents/skills/iapl-reference/SKILL.md | 1 + .../skills/iapl-reference/resources/api.md | 1 + .../.agents/skills/iapl-upgrade/SKILL.md | 4 +- reference/src/payload-types.ts | 1303 ++++++++++++++++- src/index.ts | 3 +- src/modules/consent/scanner/approval.ts | 4 +- .../consent/scanner/crawl/endpoints.ts | 4 +- src/modules/consent/scanner/endpoint.ts | 4 +- src/modules/doctor/status.ts | 4 +- src/modules/shared/accessAnswer.ts | 42 +- src/modules/shared/switches.ts | 13 + src/plugin.ts | 5 + src/types.ts | 10 +- test/accessAnswer.test.ts | 58 +- test/iawlIdeasB.test.ts | 8 + 25 files changed, 1450 insertions(+), 62 deletions(-) diff --git a/docs/CHANGELOG.md b/docs/CHANGELOG.md index 77ae442..6c51a57 100644 --- a/docs/CHANGELOG.md +++ b/docs/CHANGELOG.md @@ -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: `. > > **Recommended for projects:** a text field of your own whose value goes into `href` (social profiles, a website) diff --git a/docs/agent/AGENT.md b/docs/agent/AGENT.md index ba22d06..c5358a4 100644 --- a/docs/agent/AGENT.md +++ b/docs/agent/AGENT.md @@ -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` | diff --git a/docs/agent/skills/iapl-doctor/SKILL.md b/docs/agent/skills/iapl-doctor/SKILL.md index 4c6a540..db4a4f4 100644 --- a/docs/agent/skills/iapl-doctor/SKILL.md +++ b/docs/agent/skills/iapl-doctor/SKILL.md @@ -75,7 +75,8 @@ Existing client sites are not gated on it; run it there as a report only. Then `Authorization: Bearer `; counts and states only (`usersWithout2fa`, `usersSetupClosed` = of those, blocked because the 2FA setup window has passed, `pendingCookies`, `openSignUp` = slugs of auth collections with open sign-up, `turnstile` = the recorded state of the Turnstile check, `turnstileSecretFromEnv`, `plugin`, `node`) — never a key or a name. With the same `IAPL_DOCTOR_TOKEN` in the doctor's environment, `--url` reads it. Off: `iapl({ doctor: false })`; adapt: `iapl({ doctor: { tokenVar, access } })`. `access` returns a boolean (`({ req }) => isAdmin(req.user, req.payload)`): -since 1.18.0 any other answer is reported once in the server log, and from 1.19.0 only `true` allows. +since 1.18.0 only a literal `true` allows — `({ req }) => req.user` (an object) refuses — and any other answer is +reported once in the server log (`strictAccessAnswers: false` gives the old truthy reading back). ## Env the doctor reads diff --git a/docs/agent/skills/iapl-reference/SKILL.md b/docs/agent/skills/iapl-reference/SKILL.md index 75d896e..f05933f 100644 --- a/docs/agent/skills/iapl-reference/SKILL.md +++ b/docs/agent/skills/iapl-reference/SKILL.md @@ -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 } }` | diff --git a/docs/agent/skills/iapl-reference/resources/api.md b/docs/agent/skills/iapl-reference/resources/api.md index 7a55d95..fa691e3 100644 --- a/docs/agent/skills/iapl-reference/resources/api.md +++ b/docs/agent/skills/iapl-reference/resources/api.md @@ -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`. | diff --git a/docs/agent/skills/iapl-upgrade/SKILL.md b/docs/agent/skills/iapl-upgrade/SKILL.md index 529d13e..7fe2a01 100644 --- a/docs/agent/skills/iapl-upgrade/SKILL.md +++ b/docs/agent/skills/iapl-upgrade/SKILL.md @@ -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: `. **Check:** `curl -s '/api/pages?limit=100000' | jq .limit` → `100`; `curl -s -o /dev/null -w '%{http_code}' '/api/pages?sort=%24where'` → `400`; `pnpm exec iapl-doctor --url --only live-probes` → no finding. diff --git a/docs/cookie-scanner.md b/docs/cookie-scanner.md index 4027d3d..a1a890c 100644 --- a/docs/cookie-scanner.md +++ b/docs/cookie-scanner.md @@ -176,7 +176,7 @@ run the tests, commit. | `integrations` | built-ins | `(defaults) => integrations` — filter, change or add `CookieIntegration`s (each: `key`, `label` — one string or `{ en, pl, … }` per admin language, `declarations`, `isEnabled(ctx)`) | | `database` | `true` | `false` = no Open Cookie Database lookup | | `databaseCategories` | table above | Partial map from database category to consent category | -| `access` | editor and up | `({ req }) => boolean` — who may scan, start a crawl and read its status | +| `access` | editor and up | `({ req }) => boolean` — who may scan, start a crawl and read its status. Only a literal `true` allows (1.18.0): `({ req }) => req.user` refuses — return `Boolean(req.user)`; `iapl({ strictAccessAnswers: false })` gives the old truthy reading back (security.md "Access callbacks") | | `collectionOverrides` | — | Change `cookie-review`: an object merges `access` / `admin` / `hooks` key by key (your keys win), a function takes over (keep the slug) | | `labels` | `en`, `pl` | `{ de: { scanButton: 'Cookies scannen', … } }` — merged over the plugin's labels (`CookieScanLabels`) | | `syncAccepted` | `true` | `false` = accepting or approving only marks the entry; nothing is written to Cookie banner | diff --git a/docs/doctor.md b/docs/doctor.md index 86aeaaf..501fead 100644 --- a/docs/doctor.md +++ b/docs/doctor.md @@ -82,7 +82,7 @@ each plugin log — counts, sizes and dates only. Intecion mail service — states and codes only, never a token, a password or an address; `relay` is `null` when the mail service is switched off. -Turn off: `iapl({ doctor: false })`. Adapt: `iapl({ doctor: { tokenVar: 'MY_TOKEN', access: ({ req }) => isAdmin(req.user, req.payload) } })` (a logged-in staff admin may read it too; the second factor is checked for you — never test `req.user.roles` by hand, an account of another collection can carry the same value) +Turn off: `iapl({ doctor: false })`. Adapt: `iapl({ doctor: { tokenVar: 'MY_TOKEN', access: ({ req }) => isAdmin(req.user, req.payload) } })` (only a literal `true` allows since 1.18.0 — `req.user` refuses; `strictAccessAnswers: false` = the old truthy reading) (a logged-in staff admin may read it too; the second factor is checked for you — never test `req.user.roles` by hand, an account of another collection can carry the same value) (`access` lets a logged-in admin read it without the token). Building blocks: `buildDoctorEndpoint`, `collectDoctorStatus` from `@intecion/ipal-kit/doctor`. diff --git a/docs/security.md b/docs/security.md index efe43bb..d9e1527 100644 --- a/docs/security.md +++ b/docs/security.md @@ -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 diff --git a/reference/.agents/skills/iapl-doctor/SKILL.md b/reference/.agents/skills/iapl-doctor/SKILL.md index 4c6a540..db4a4f4 100644 --- a/reference/.agents/skills/iapl-doctor/SKILL.md +++ b/reference/.agents/skills/iapl-doctor/SKILL.md @@ -75,7 +75,8 @@ Existing client sites are not gated on it; run it there as a report only. Then `Authorization: Bearer `; counts and states only (`usersWithout2fa`, `usersSetupClosed` = of those, blocked because the 2FA setup window has passed, `pendingCookies`, `openSignUp` = slugs of auth collections with open sign-up, `turnstile` = the recorded state of the Turnstile check, `turnstileSecretFromEnv`, `plugin`, `node`) — never a key or a name. With the same `IAPL_DOCTOR_TOKEN` in the doctor's environment, `--url` reads it. Off: `iapl({ doctor: false })`; adapt: `iapl({ doctor: { tokenVar, access } })`. `access` returns a boolean (`({ req }) => isAdmin(req.user, req.payload)`): -since 1.18.0 any other answer is reported once in the server log, and from 1.19.0 only `true` allows. +since 1.18.0 only a literal `true` allows — `({ req }) => req.user` (an object) refuses — and any other answer is +reported once in the server log (`strictAccessAnswers: false` gives the old truthy reading back). ## Env the doctor reads diff --git a/reference/.agents/skills/iapl-reference/SKILL.md b/reference/.agents/skills/iapl-reference/SKILL.md index 75d896e..f05933f 100644 --- a/reference/.agents/skills/iapl-reference/SKILL.md +++ b/reference/.agents/skills/iapl-reference/SKILL.md @@ -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 } }` | diff --git a/reference/.agents/skills/iapl-reference/resources/api.md b/reference/.agents/skills/iapl-reference/resources/api.md index 7a55d95..fa691e3 100644 --- a/reference/.agents/skills/iapl-reference/resources/api.md +++ b/reference/.agents/skills/iapl-reference/resources/api.md @@ -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`. | diff --git a/reference/.agents/skills/iapl-upgrade/SKILL.md b/reference/.agents/skills/iapl-upgrade/SKILL.md index 529d13e..7fe2a01 100644 --- a/reference/.agents/skills/iapl-upgrade/SKILL.md +++ b/reference/.agents/skills/iapl-upgrade/SKILL.md @@ -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: `. **Check:** `curl -s '/api/pages?limit=100000' | jq .limit` → `100`; `curl -s -o /dev/null -w '%{http_code}' '/api/pages?sort=%24where'` → `400`; `pnpm exec iapl-doctor --url --only live-probes` → no finding. diff --git a/reference/src/payload-types.ts b/reference/src/payload-types.ts index bf02d4a..c554251 100644 --- a/reference/src/payload-types.ts +++ b/reference/src/payload-types.ts @@ -63,7 +63,20 @@ export type SupportedTimezones = export interface Config { auth: { + 'e2e-crew': E2ECrewAuthOperations; + 'e2e-staff': E2EStaffAuthOperations; + 'e2e-team': E2ETeamAuthOperations; users: UserAuthOperations; + 'e2e-copy': E2ECopyAuthOperations; + 'e2e-copy-own-rules': E2ECopyOwnRuleAuthOperations; + 'e2e-copy-cross-op': E2ECopyCrossOpAuthOperations; + 'e2e-copy-values': E2ECopyValueAuthOperations; + 'e2e-copy-team-admin': E2ECopyTeamAdminAuthOperations; + 'e2e-copy-opt-out': E2ECopyOptOutAuthOperations; + 'e2e-copy-not-staff': E2ECopyNotStaffAuthOperations; + 'late-staff': LateStaffAuthOperations; + 'e2e-late-text': E2ELateTextAuthOperations; + 'e2e-visitors': E2EVisitorAuthOperations; }; blocks: {}; collections: { @@ -71,12 +84,26 @@ export interface Config { posts: Post; caseStudies: CaseStudy; media: Media; + 'e2e-crew': E2ECrew; + 'e2e-staff': E2EStaff; + 'e2e-team': E2ETeam; users: User; forms: Form; 'form-submissions': FormSubmission; 'consent-records': ConsentRecord; 'cookie-review': CookieReview; + 'e2e-copy': E2ECopy; + 'e2e-copy-own-rules': E2ECopyOwnRule; + 'e2e-copy-cross-op': E2ECopyCrossOp; + 'e2e-copy-values': E2ECopyValue; + 'e2e-copy-team-admin': E2ECopyTeamAdmin; + 'e2e-copy-opt-out': E2ECopyOptOut; + 'e2e-copy-not-staff': E2ECopyNotStaff; + 'late-staff': LateStaff; + 'e2e-late-text': E2ELateText; + 'e2e-visitors': E2EVisitor; 'payload-kv': PayloadKv; + 'payload-jobs': PayloadJob; 'payload-locked-documents': PayloadLockedDocument; 'payload-preferences': PayloadPreference; 'payload-migrations': PayloadMigration; @@ -87,12 +114,26 @@ export interface Config { posts: PostsSelect | PostsSelect; caseStudies: CaseStudiesSelect | CaseStudiesSelect; media: MediaSelect | MediaSelect; + 'e2e-crew': E2ECrewSelect | E2ECrewSelect; + 'e2e-staff': E2EStaffSelect | E2EStaffSelect; + 'e2e-team': E2ETeamSelect | E2ETeamSelect; users: UsersSelect | UsersSelect; forms: FormsSelect | FormsSelect; 'form-submissions': FormSubmissionsSelect | FormSubmissionsSelect; 'consent-records': ConsentRecordsSelect | ConsentRecordsSelect; 'cookie-review': CookieReviewSelect | CookieReviewSelect; + 'e2e-copy': E2ECopySelect | E2ECopySelect; + 'e2e-copy-own-rules': E2ECopyOwnRulesSelect | E2ECopyOwnRulesSelect; + 'e2e-copy-cross-op': E2ECopyCrossOpSelect | E2ECopyCrossOpSelect; + 'e2e-copy-values': E2ECopyValuesSelect | E2ECopyValuesSelect; + 'e2e-copy-team-admin': E2ECopyTeamAdminSelect | E2ECopyTeamAdminSelect; + 'e2e-copy-opt-out': E2ECopyOptOutSelect | E2ECopyOptOutSelect; + 'e2e-copy-not-staff': E2ECopyNotStaffSelect | E2ECopyNotStaffSelect; + 'late-staff': LateStaffSelect | LateStaffSelect; + 'e2e-late-text': E2ELateTextSelect | E2ELateTextSelect; + 'e2e-visitors': E2EVisitorsSelect | E2EVisitorsSelect; 'payload-kv': PayloadKvSelect | PayloadKvSelect; + 'payload-jobs': PayloadJobsSelect | PayloadJobsSelect; 'payload-locked-documents': PayloadLockedDocumentsSelect | PayloadLockedDocumentsSelect; 'payload-preferences': PayloadPreferencesSelect | PayloadPreferencesSelect; 'payload-migrations': PayloadMigrationsSelect | PayloadMigrationsSelect; @@ -125,12 +166,86 @@ export interface Config { widgets: { collections: CollectionsWidget; }; - user: User; + user: + | E2ECrew + | E2EStaff + | E2ETeam + | User + | E2ECopy + | E2ECopyOwnRule + | E2ECopyCrossOp + | E2ECopyValue + | E2ECopyTeamAdmin + | E2ECopyOptOut + | E2ECopyNotStaff + | LateStaff + | E2ELateText + | E2EVisitor; jobs: { - tasks: unknown; + tasks: { + e2eNoop: TaskE2ENoop; + inline: { + input: unknown; + output: unknown; + }; + }; workflows: unknown; }; } +export interface E2ECrewAuthOperations { + forgotPassword: { + email: string; + password: string; + }; + login: { + email: string; + password: string; + }; + registerFirstUser: { + email: string; + password: string; + }; + unlock: { + email: string; + password: string; + }; +} +export interface E2EStaffAuthOperations { + forgotPassword: { + email: string; + password: string; + }; + login: { + email: string; + password: string; + }; + registerFirstUser: { + email: string; + password: string; + }; + unlock: { + email: string; + password: string; + }; +} +export interface E2ETeamAuthOperations { + forgotPassword: { + email: string; + password: string; + }; + login: { + email: string; + password: string; + }; + registerFirstUser: { + email: string; + password: string; + }; + unlock: { + email: string; + password: string; + }; +} export interface UserAuthOperations { forgotPassword: { email: string; @@ -149,6 +264,186 @@ export interface UserAuthOperations { password: string; }; } +export interface E2ECopyAuthOperations { + forgotPassword: { + email: string; + password: string; + }; + login: { + email: string; + password: string; + }; + registerFirstUser: { + email: string; + password: string; + }; + unlock: { + email: string; + password: string; + }; +} +export interface E2ECopyOwnRuleAuthOperations { + forgotPassword: { + email: string; + password: string; + }; + login: { + email: string; + password: string; + }; + registerFirstUser: { + email: string; + password: string; + }; + unlock: { + email: string; + password: string; + }; +} +export interface E2ECopyCrossOpAuthOperations { + forgotPassword: { + email: string; + password: string; + }; + login: { + email: string; + password: string; + }; + registerFirstUser: { + email: string; + password: string; + }; + unlock: { + email: string; + password: string; + }; +} +export interface E2ECopyValueAuthOperations { + forgotPassword: { + email: string; + password: string; + }; + login: { + email: string; + password: string; + }; + registerFirstUser: { + email: string; + password: string; + }; + unlock: { + email: string; + password: string; + }; +} +export interface E2ECopyTeamAdminAuthOperations { + forgotPassword: { + email: string; + password: string; + }; + login: { + email: string; + password: string; + }; + registerFirstUser: { + email: string; + password: string; + }; + unlock: { + email: string; + password: string; + }; +} +export interface E2ECopyOptOutAuthOperations { + forgotPassword: { + email: string; + password: string; + }; + login: { + email: string; + password: string; + }; + registerFirstUser: { + email: string; + password: string; + }; + unlock: { + email: string; + password: string; + }; +} +export interface E2ECopyNotStaffAuthOperations { + forgotPassword: { + email: string; + password: string; + }; + login: { + email: string; + password: string; + }; + registerFirstUser: { + email: string; + password: string; + }; + unlock: { + email: string; + password: string; + }; +} +export interface LateStaffAuthOperations { + forgotPassword: { + email: string; + password: string; + }; + login: { + email: string; + password: string; + }; + registerFirstUser: { + email: string; + password: string; + }; + unlock: { + email: string; + password: string; + }; +} +export interface E2ELateTextAuthOperations { + forgotPassword: { + email: string; + password: string; + }; + login: { + email: string; + password: string; + }; + registerFirstUser: { + email: string; + password: string; + }; + unlock: { + email: string; + password: string; + }; +} +export interface E2EVisitorAuthOperations { + forgotPassword: { + email: string; + password: string; + }; + login: { + email: string; + password: string; + }; + registerFirstUser: { + email: string; + password: string; + }; + unlock: { + email: string; + password: string; + }; +} /** * This interface was referenced by `Config`'s JSON-Schema * via the `definition` "pages". @@ -1284,6 +1579,99 @@ export interface CaseStudy { updatedAt: string; createdAt: string; } +/** + * This interface was referenced by `Config`'s JSON-Schema + * via the `definition` "e2e-crew". + */ +export interface E2ECrew { + id: string; + roles?: ('user' | 'editor' | 'admin' | 'boss')[] | null; + /** + * Needed only to change your own e-mail address or password. + */ + currentPassword?: string | null; + updatedAt: string; + createdAt: string; + email: string; + resetPasswordToken?: string | null; + resetPasswordExpiration?: string | null; + salt?: string | null; + hash?: string | null; + resetPasswordRequestedAt?: string | null; + loginAttempts?: number | null; + lockUntil?: string | null; + sessions?: + | { + id: string; + createdAt?: string | null; + expiresAt: string; + }[] + | null; + password?: string | null; + collection: 'e2e-crew'; +} +/** + * This interface was referenced by `Config`'s JSON-Schema + * via the `definition` "e2e-staff". + */ +export interface E2EStaff { + id: string; + roles?: ('user' | 'editor' | 'admin')[] | null; + /** + * Needed only to change your own e-mail address or password. + */ + currentPassword?: string | null; + updatedAt: string; + createdAt: string; + email: string; + resetPasswordToken?: string | null; + resetPasswordExpiration?: string | null; + salt?: string | null; + hash?: string | null; + resetPasswordRequestedAt?: string | null; + loginAttempts?: number | null; + lockUntil?: string | null; + sessions?: + | { + id: string; + createdAt?: string | null; + expiresAt: string; + }[] + | null; + password?: string | null; + collection: 'e2e-staff'; +} +/** + * This interface was referenced by `Config`'s JSON-Schema + * via the `definition` "e2e-team". + */ +export interface E2ETeam { + id: string; + roles?: ('lead' | 'member')[] | null; + /** + * Needed only to change your own e-mail address or password. + */ + currentPassword?: string | null; + updatedAt: string; + createdAt: string; + email: string; + resetPasswordToken?: string | null; + resetPasswordExpiration?: string | null; + salt?: string | null; + hash?: string | null; + resetPasswordRequestedAt?: string | null; + loginAttempts?: number | null; + lockUntil?: string | null; + sessions?: + | { + id: string; + createdAt?: string | null; + expiresAt: string; + }[] + | null; + password?: string | null; + collection: 'e2e-team'; +} /** * This interface was referenced by `Config`'s JSON-Schema * via the `definition` "users". @@ -1433,6 +1821,291 @@ export interface CookieReview { updatedAt: string; createdAt: string; } +/** + * This interface was referenced by `Config`'s JSON-Schema + * via the `definition` "e2e-copy". + */ +export interface E2ECopy { + id: string; + roles?: ('user' | 'editor' | 'admin')[] | null; + /** + * Needed only to change your own e-mail address or password. + */ + currentPassword?: string | null; + updatedAt: string; + createdAt: string; + email: string; + resetPasswordToken?: string | null; + resetPasswordExpiration?: string | null; + salt?: string | null; + hash?: string | null; + resetPasswordRequestedAt?: string | null; + loginAttempts?: number | null; + lockUntil?: string | null; + sessions?: + | { + id: string; + createdAt?: string | null; + expiresAt: string; + }[] + | null; + password?: string | null; + collection: 'e2e-copy'; +} +/** + * This interface was referenced by `Config`'s JSON-Schema + * via the `definition` "e2e-copy-own-rules". + */ +export interface E2ECopyOwnRule { + id: string; + roles?: ('user' | 'editor' | 'admin')[] | null; + /** + * Needed only to change your own e-mail address or password. + */ + currentPassword?: string | null; + updatedAt: string; + createdAt: string; + email: string; + resetPasswordToken?: string | null; + resetPasswordExpiration?: string | null; + salt?: string | null; + hash?: string | null; + resetPasswordRequestedAt?: string | null; + loginAttempts?: number | null; + lockUntil?: string | null; + sessions?: + | { + id: string; + createdAt?: string | null; + expiresAt: string; + }[] + | null; + password?: string | null; + collection: 'e2e-copy-own-rules'; +} +/** + * This interface was referenced by `Config`'s JSON-Schema + * via the `definition` "e2e-copy-cross-op". + */ +export interface E2ECopyCrossOp { + id: string; + roles?: ('user' | 'editor' | 'admin')[] | null; + /** + * Needed only to change your own e-mail address or password. + */ + currentPassword?: string | null; + updatedAt: string; + createdAt: string; + email: string; + resetPasswordToken?: string | null; + resetPasswordExpiration?: string | null; + salt?: string | null; + hash?: string | null; + resetPasswordRequestedAt?: string | null; + loginAttempts?: number | null; + lockUntil?: string | null; + sessions?: + | { + id: string; + createdAt?: string | null; + expiresAt: string; + }[] + | null; + password?: string | null; + collection: 'e2e-copy-cross-op'; +} +/** + * This interface was referenced by `Config`'s JSON-Schema + * via the `definition` "e2e-copy-values". + */ +export interface E2ECopyValue { + id: string; + roles?: ('user' | 'editor' | 'admin' | 'boss')[] | null; + updatedAt: string; + createdAt: string; + email: string; + resetPasswordToken?: string | null; + resetPasswordExpiration?: string | null; + salt?: string | null; + hash?: string | null; + resetPasswordRequestedAt?: string | null; + loginAttempts?: number | null; + lockUntil?: string | null; + sessions?: + | { + id: string; + createdAt?: string | null; + expiresAt: string; + }[] + | null; + password?: string | null; + collection: 'e2e-copy-values'; +} +/** + * This interface was referenced by `Config`'s JSON-Schema + * via the `definition` "e2e-copy-team-admin". + */ +export interface E2ECopyTeamAdmin { + id: string; + roles?: ('user' | 'editor' | 'admin')[] | null; + updatedAt: string; + createdAt: string; + email: string; + resetPasswordToken?: string | null; + resetPasswordExpiration?: string | null; + salt?: string | null; + hash?: string | null; + resetPasswordRequestedAt?: string | null; + loginAttempts?: number | null; + lockUntil?: string | null; + sessions?: + | { + id: string; + createdAt?: string | null; + expiresAt: string; + }[] + | null; + password?: string | null; + collection: 'e2e-copy-team-admin'; +} +/** + * This interface was referenced by `Config`'s JSON-Schema + * via the `definition` "e2e-copy-opt-out". + */ +export interface E2ECopyOptOut { + id: string; + roles?: ('user' | 'editor' | 'admin')[] | null; + updatedAt: string; + createdAt: string; + email: string; + resetPasswordToken?: string | null; + resetPasswordExpiration?: string | null; + salt?: string | null; + hash?: string | null; + resetPasswordRequestedAt?: string | null; + loginAttempts?: number | null; + lockUntil?: string | null; + sessions?: + | { + id: string; + createdAt?: string | null; + expiresAt: string; + }[] + | null; + password?: string | null; + collection: 'e2e-copy-opt-out'; +} +/** + * This interface was referenced by `Config`'s JSON-Schema + * via the `definition` "e2e-copy-not-staff". + */ +export interface E2ECopyNotStaff { + id: string; + roles?: ('user' | 'editor' | 'admin')[] | null; + /** + * Needed only to change your own e-mail address or password. + */ + currentPassword?: string | null; + updatedAt: string; + createdAt: string; + email: string; + resetPasswordToken?: string | null; + resetPasswordExpiration?: string | null; + salt?: string | null; + hash?: string | null; + resetPasswordRequestedAt?: string | null; + loginAttempts?: number | null; + lockUntil?: string | null; + sessions?: + | { + id: string; + createdAt?: string | null; + expiresAt: string; + }[] + | null; + password?: string | null; + collection: 'e2e-copy-not-staff'; +} +/** + * This interface was referenced by `Config`'s JSON-Schema + * via the `definition` "late-staff". + */ +export interface LateStaff { + id: string; + roles?: ('user' | 'editor' | 'admin')[] | null; + updatedAt: string; + createdAt: string; + email: string; + resetPasswordToken?: string | null; + resetPasswordExpiration?: string | null; + salt?: string | null; + hash?: string | null; + resetPasswordRequestedAt?: string | null; + loginAttempts?: number | null; + lockUntil?: string | null; + sessions?: + | { + id: string; + createdAt?: string | null; + expiresAt: string; + }[] + | null; + password?: string | null; + collection: 'late-staff'; +} +/** + * This interface was referenced by `Config`'s JSON-Schema + * via the `definition` "e2e-late-text". + */ +export interface E2ELateText { + id: string; + roles?: string[] | null; + updatedAt: string; + createdAt: string; + email: string; + resetPasswordToken?: string | null; + resetPasswordExpiration?: string | null; + salt?: string | null; + hash?: string | null; + resetPasswordRequestedAt?: string | null; + loginAttempts?: number | null; + lockUntil?: string | null; + sessions?: + | { + id: string; + createdAt?: string | null; + expiresAt: string; + }[] + | null; + password?: string | null; + collection: 'e2e-late-text'; +} +/** + * This interface was referenced by `Config`'s JSON-Schema + * via the `definition` "e2e-visitors". + */ +export interface E2EVisitor { + id: string; + updatedAt: string; + createdAt: string; + email: string; + resetPasswordToken?: string | null; + resetPasswordExpiration?: string | null; + salt?: string | null; + hash?: string | null; + resetPasswordRequestedAt?: string | null; + loginAttempts?: number | null; + lockUntil?: string | null; + sessions?: + | { + id: string; + createdAt?: string | null; + expiresAt: string; + }[] + | null; + password?: string | null; + collection: 'e2e-visitors'; +} /** * This interface was referenced by `Config`'s JSON-Schema * via the `definition` "payload-kv". @@ -1450,6 +2123,98 @@ export interface PayloadKv { | boolean | null; } +/** + * This interface was referenced by `Config`'s JSON-Schema + * via the `definition` "payload-jobs". + */ +export interface PayloadJob { + id: string; + /** + * Input data provided to the job + */ + input?: + | { + [k: string]: unknown; + } + | unknown[] + | string + | number + | boolean + | null; + taskStatus?: + | { + [k: string]: unknown; + } + | unknown[] + | string + | number + | boolean + | null; + completedAt?: string | null; + totalTried?: number | null; + /** + * If hasError is true this job will not be retried + */ + hasError?: boolean | null; + /** + * If hasError is true, this is the error that caused it + */ + error?: + | { + [k: string]: unknown; + } + | unknown[] + | string + | number + | boolean + | null; + /** + * Task execution log + */ + log?: + | { + executedAt: string; + completedAt: string; + taskSlug: 'inline' | 'e2eNoop'; + taskID: string; + input?: + | { + [k: string]: unknown; + } + | unknown[] + | string + | number + | boolean + | null; + output?: + | { + [k: string]: unknown; + } + | unknown[] + | string + | number + | boolean + | null; + state: 'failed' | 'succeeded'; + error?: + | { + [k: string]: unknown; + } + | unknown[] + | string + | number + | boolean + | null; + id?: string | null; + }[] + | null; + taskSlug?: ('inline' | 'e2eNoop') | null; + queue?: string | null; + waitUntil?: string | null; + processing?: boolean | null; + updatedAt: string; + createdAt: string; +} /** * This interface was referenced by `Config`'s JSON-Schema * via the `definition` "payload-locked-documents". @@ -1473,6 +2238,18 @@ export interface PayloadLockedDocument { relationTo: 'media'; value: string | Media; } | null) + | ({ + relationTo: 'e2e-crew'; + value: string | E2ECrew; + } | null) + | ({ + relationTo: 'e2e-staff'; + value: string | E2EStaff; + } | null) + | ({ + relationTo: 'e2e-team'; + value: string | E2ETeam; + } | null) | ({ relationTo: 'users'; value: string | User; @@ -1492,12 +2269,105 @@ export interface PayloadLockedDocument { | ({ relationTo: 'cookie-review'; value: string | CookieReview; + } | null) + | ({ + relationTo: 'e2e-copy'; + value: string | E2ECopy; + } | null) + | ({ + relationTo: 'e2e-copy-own-rules'; + value: string | E2ECopyOwnRule; + } | null) + | ({ + relationTo: 'e2e-copy-cross-op'; + value: string | E2ECopyCrossOp; + } | null) + | ({ + relationTo: 'e2e-copy-values'; + value: string | E2ECopyValue; + } | null) + | ({ + relationTo: 'e2e-copy-team-admin'; + value: string | E2ECopyTeamAdmin; + } | null) + | ({ + relationTo: 'e2e-copy-opt-out'; + value: string | E2ECopyOptOut; + } | null) + | ({ + relationTo: 'e2e-copy-not-staff'; + value: string | E2ECopyNotStaff; + } | null) + | ({ + relationTo: 'late-staff'; + value: string | LateStaff; + } | null) + | ({ + relationTo: 'e2e-late-text'; + value: string | E2ELateText; + } | null) + | ({ + relationTo: 'e2e-visitors'; + value: string | E2EVisitor; } | null); globalSlug?: string | null; - user: { - relationTo: 'users'; - value: string | User; - }; + user: + | { + relationTo: 'e2e-crew'; + value: string | E2ECrew; + } + | { + relationTo: 'e2e-staff'; + value: string | E2EStaff; + } + | { + relationTo: 'e2e-team'; + value: string | E2ETeam; + } + | { + relationTo: 'users'; + value: string | User; + } + | { + relationTo: 'e2e-copy'; + value: string | E2ECopy; + } + | { + relationTo: 'e2e-copy-own-rules'; + value: string | E2ECopyOwnRule; + } + | { + relationTo: 'e2e-copy-cross-op'; + value: string | E2ECopyCrossOp; + } + | { + relationTo: 'e2e-copy-values'; + value: string | E2ECopyValue; + } + | { + relationTo: 'e2e-copy-team-admin'; + value: string | E2ECopyTeamAdmin; + } + | { + relationTo: 'e2e-copy-opt-out'; + value: string | E2ECopyOptOut; + } + | { + relationTo: 'e2e-copy-not-staff'; + value: string | E2ECopyNotStaff; + } + | { + relationTo: 'late-staff'; + value: string | LateStaff; + } + | { + relationTo: 'e2e-late-text'; + value: string | E2ELateText; + } + | { + relationTo: 'e2e-visitors'; + value: string | E2EVisitor; + }; updatedAt: string; createdAt: string; } @@ -1507,10 +2377,63 @@ export interface PayloadLockedDocument { */ export interface PayloadPreference { id: string; - user: { - relationTo: 'users'; - value: string | User; - }; + user: + | { + relationTo: 'e2e-crew'; + value: string | E2ECrew; + } + | { + relationTo: 'e2e-staff'; + value: string | E2EStaff; + } + | { + relationTo: 'e2e-team'; + value: string | E2ETeam; + } + | { + relationTo: 'users'; + value: string | User; + } + | { + relationTo: 'e2e-copy'; + value: string | E2ECopy; + } + | { + relationTo: 'e2e-copy-own-rules'; + value: string | E2ECopyOwnRule; + } + | { + relationTo: 'e2e-copy-cross-op'; + value: string | E2ECopyCrossOp; + } + | { + relationTo: 'e2e-copy-values'; + value: string | E2ECopyValue; + } + | { + relationTo: 'e2e-copy-team-admin'; + value: string | E2ECopyTeamAdmin; + } + | { + relationTo: 'e2e-copy-opt-out'; + value: string | E2ECopyOptOut; + } + | { + relationTo: 'e2e-copy-not-staff'; + value: string | E2ECopyNotStaff; + } + | { + relationTo: 'late-staff'; + value: string | LateStaff; + } + | { + relationTo: 'e2e-late-text'; + value: string | E2ELateText; + } + | { + relationTo: 'e2e-visitors'; + value: string | E2EVisitor; + }; key?: string | null; value?: | { @@ -2075,6 +2998,81 @@ export interface MediaSelect { focalX?: T; focalY?: T; } +/** + * This interface was referenced by `Config`'s JSON-Schema + * via the `definition` "e2e-crew_select". + */ +export interface E2ECrewSelect { + roles?: T; + currentPassword?: T; + updatedAt?: T; + createdAt?: T; + email?: T; + resetPasswordToken?: T; + resetPasswordExpiration?: T; + salt?: T; + hash?: T; + resetPasswordRequestedAt?: T; + loginAttempts?: T; + lockUntil?: T; + sessions?: + | T + | { + id?: T; + createdAt?: T; + expiresAt?: T; + }; +} +/** + * This interface was referenced by `Config`'s JSON-Schema + * via the `definition` "e2e-staff_select". + */ +export interface E2EStaffSelect { + roles?: T; + currentPassword?: T; + updatedAt?: T; + createdAt?: T; + email?: T; + resetPasswordToken?: T; + resetPasswordExpiration?: T; + salt?: T; + hash?: T; + resetPasswordRequestedAt?: T; + loginAttempts?: T; + lockUntil?: T; + sessions?: + | T + | { + id?: T; + createdAt?: T; + expiresAt?: T; + }; +} +/** + * This interface was referenced by `Config`'s JSON-Schema + * via the `definition` "e2e-team_select". + */ +export interface E2ETeamSelect { + roles?: T; + currentPassword?: T; + updatedAt?: T; + createdAt?: T; + email?: T; + resetPasswordToken?: T; + resetPasswordExpiration?: T; + salt?: T; + hash?: T; + resetPasswordRequestedAt?: T; + loginAttempts?: T; + lockUntil?: T; + sessions?: + | T + | { + id?: T; + createdAt?: T; + expiresAt?: T; + }; +} /** * This interface was referenced by `Config`'s JSON-Schema * via the `definition` "users_select". @@ -2475,6 +3473,249 @@ export interface CookieReviewSelect { updatedAt?: T; createdAt?: T; } +/** + * This interface was referenced by `Config`'s JSON-Schema + * via the `definition` "e2e-copy_select". + */ +export interface E2ECopySelect { + roles?: T; + currentPassword?: T; + updatedAt?: T; + createdAt?: T; + email?: T; + resetPasswordToken?: T; + resetPasswordExpiration?: T; + salt?: T; + hash?: T; + resetPasswordRequestedAt?: T; + loginAttempts?: T; + lockUntil?: T; + sessions?: + | T + | { + id?: T; + createdAt?: T; + expiresAt?: T; + }; +} +/** + * This interface was referenced by `Config`'s JSON-Schema + * via the `definition` "e2e-copy-own-rules_select". + */ +export interface E2ECopyOwnRulesSelect { + roles?: T; + currentPassword?: T; + updatedAt?: T; + createdAt?: T; + email?: T; + resetPasswordToken?: T; + resetPasswordExpiration?: T; + salt?: T; + hash?: T; + resetPasswordRequestedAt?: T; + loginAttempts?: T; + lockUntil?: T; + sessions?: + | T + | { + id?: T; + createdAt?: T; + expiresAt?: T; + }; +} +/** + * This interface was referenced by `Config`'s JSON-Schema + * via the `definition` "e2e-copy-cross-op_select". + */ +export interface E2ECopyCrossOpSelect { + roles?: T; + currentPassword?: T; + updatedAt?: T; + createdAt?: T; + email?: T; + resetPasswordToken?: T; + resetPasswordExpiration?: T; + salt?: T; + hash?: T; + resetPasswordRequestedAt?: T; + loginAttempts?: T; + lockUntil?: T; + sessions?: + | T + | { + id?: T; + createdAt?: T; + expiresAt?: T; + }; +} +/** + * This interface was referenced by `Config`'s JSON-Schema + * via the `definition` "e2e-copy-values_select". + */ +export interface E2ECopyValuesSelect { + roles?: T; + updatedAt?: T; + createdAt?: T; + email?: T; + resetPasswordToken?: T; + resetPasswordExpiration?: T; + salt?: T; + hash?: T; + resetPasswordRequestedAt?: T; + loginAttempts?: T; + lockUntil?: T; + sessions?: + | T + | { + id?: T; + createdAt?: T; + expiresAt?: T; + }; +} +/** + * This interface was referenced by `Config`'s JSON-Schema + * via the `definition` "e2e-copy-team-admin_select". + */ +export interface E2ECopyTeamAdminSelect { + roles?: T; + updatedAt?: T; + createdAt?: T; + email?: T; + resetPasswordToken?: T; + resetPasswordExpiration?: T; + salt?: T; + hash?: T; + resetPasswordRequestedAt?: T; + loginAttempts?: T; + lockUntil?: T; + sessions?: + | T + | { + id?: T; + createdAt?: T; + expiresAt?: T; + }; +} +/** + * This interface was referenced by `Config`'s JSON-Schema + * via the `definition` "e2e-copy-opt-out_select". + */ +export interface E2ECopyOptOutSelect { + roles?: T; + updatedAt?: T; + createdAt?: T; + email?: T; + resetPasswordToken?: T; + resetPasswordExpiration?: T; + salt?: T; + hash?: T; + resetPasswordRequestedAt?: T; + loginAttempts?: T; + lockUntil?: T; + sessions?: + | T + | { + id?: T; + createdAt?: T; + expiresAt?: T; + }; +} +/** + * This interface was referenced by `Config`'s JSON-Schema + * via the `definition` "e2e-copy-not-staff_select". + */ +export interface E2ECopyNotStaffSelect { + roles?: T; + currentPassword?: T; + updatedAt?: T; + createdAt?: T; + email?: T; + resetPasswordToken?: T; + resetPasswordExpiration?: T; + salt?: T; + hash?: T; + resetPasswordRequestedAt?: T; + loginAttempts?: T; + lockUntil?: T; + sessions?: + | T + | { + id?: T; + createdAt?: T; + expiresAt?: T; + }; +} +/** + * This interface was referenced by `Config`'s JSON-Schema + * via the `definition` "late-staff_select". + */ +export interface LateStaffSelect { + roles?: T; + updatedAt?: T; + createdAt?: T; + email?: T; + resetPasswordToken?: T; + resetPasswordExpiration?: T; + salt?: T; + hash?: T; + resetPasswordRequestedAt?: T; + loginAttempts?: T; + lockUntil?: T; + sessions?: + | T + | { + id?: T; + createdAt?: T; + expiresAt?: T; + }; +} +/** + * This interface was referenced by `Config`'s JSON-Schema + * via the `definition` "e2e-late-text_select". + */ +export interface E2ELateTextSelect { + roles?: T; + updatedAt?: T; + createdAt?: T; + email?: T; + resetPasswordToken?: T; + resetPasswordExpiration?: T; + salt?: T; + hash?: T; + resetPasswordRequestedAt?: T; + loginAttempts?: T; + lockUntil?: T; + sessions?: + | T + | { + id?: T; + createdAt?: T; + expiresAt?: T; + }; +} +/** + * This interface was referenced by `Config`'s JSON-Schema + * via the `definition` "e2e-visitors_select". + */ +export interface E2EVisitorsSelect { + updatedAt?: T; + createdAt?: T; + email?: T; + resetPasswordToken?: T; + resetPasswordExpiration?: T; + salt?: T; + hash?: T; + resetPasswordRequestedAt?: T; + loginAttempts?: T; + lockUntil?: T; + sessions?: + | T + | { + id?: T; + createdAt?: T; + expiresAt?: T; + }; +} /** * This interface was referenced by `Config`'s JSON-Schema * via the `definition` "payload-kv_select". @@ -2483,6 +3724,37 @@ export interface PayloadKvSelect { key?: T; data?: T; } +/** + * This interface was referenced by `Config`'s JSON-Schema + * via the `definition` "payload-jobs_select". + */ +export interface PayloadJobsSelect { + input?: T; + taskStatus?: T; + completedAt?: T; + totalTried?: T; + hasError?: T; + error?: T; + log?: + | T + | { + executedAt?: T; + completedAt?: T; + taskSlug?: T; + taskID?: T; + input?: T; + output?: T; + state?: T; + error?: T; + id?: T; + }; + taskSlug?: T; + queue?: T; + waitUntil?: T; + processing?: T; + updatedAt?: T; + createdAt?: T; +} /** * This interface was referenced by `Config`'s JSON-Schema * via the `definition` "payload-locked-documents_select". @@ -2596,6 +3868,9 @@ export interface Company { socials?: | { label: string; + /** + * A full address, e.g. https://example.com + */ url: string; id?: string | null; }[] @@ -3378,6 +4653,14 @@ export interface CollectionsWidget { }; width: 'full'; } +/** + * This interface was referenced by `Config`'s JSON-Schema + * via the `definition` "TaskE2eNoop". + */ +export interface TaskE2ENoop { + input?: unknown; + output?: unknown; +} /** * This interface was referenced by `Config`'s JSON-Schema * via the `definition` "auth". diff --git a/src/index.ts b/src/index.ts index efa8fe7..2252dd2 100644 --- a/src/index.ts +++ b/src/index.ts @@ -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`. diff --git a/src/modules/consent/scanner/approval.ts b/src/modules/consent/scanner/approval.ts index a9315bc..365570e 100644 --- a/src/modules/consent/scanner/approval.ts +++ b/src/modules/consent/scanner/approval.ts @@ -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) => { diff --git a/src/modules/consent/scanner/crawl/endpoints.ts b/src/modules/consent/scanner/crawl/endpoints.ts index ec6cdc9..2c4a269 100644 --- a/src/modules/consent/scanner/crawl/endpoints.ts +++ b/src/modules/consent/scanner/crawl/endpoints.ts @@ -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) => diff --git a/src/modules/consent/scanner/endpoint.ts b/src/modules/consent/scanner/endpoint.ts index 476133c..c5c90cd 100644 --- a/src/modules/consent/scanner/endpoint.ts +++ b/src/modules/consent/scanner/endpoint.ts @@ -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) => diff --git a/src/modules/doctor/status.ts b/src/modules/doctor/status.ts index 73b9a1e..73a3afe 100644 --- a/src/modules/doctor/status.ts +++ b/src/modules/doctor/status.ts @@ -14,7 +14,7 @@ import { IMAGE_RULES } from '../performance/budgets.js' import { countPendingEnrolments, mailConfigured } from '../security/totp/enrolmentConfirm.js' import { secondFactorPassed, SETUP_FROM_FIELD } from '../security/totp/secondFactor.js' import { countAccountsWithoutTotp } from '../security/totp/setupRequired.js' -import { accessAllowed } from '../shared/accessAnswer.js' +import { accessAllowed, strictAccessAnswers } from '../shared/accessAnswer.js' import { readEnv } from '../shared/envName.js' import { clientIp, consumeRateLimit, tooManyRequests } from '../shared/rateLimit.js' import { retentionMap } from '../shared/retention.js' @@ -194,7 +194,7 @@ export function buildDoctorEndpoint(options: DoctorEndpointOptions = {}): Endpoi const limit = await consumeRateLimit({ key: clientIp(req.headers), max: 10, scope: 'iapl-doctor', windowMs: 60_000 }) if (!limit.ok) {return tooManyRequests(limit.retryAfter, { error: 'Too many requests' })} const given = (req.headers.get('authorization') ?? '').replace(/^Bearer\s+/i, '').trim() - const allowed = (given && sameToken(given, token)) || (options.access ? secondFactorPassed(req) && accessAllowed('doctor.access', await options.access({ req })) : false) + const allowed = (given && sameToken(given, token)) || (options.access ? secondFactorPassed(req) && accessAllowed('doctor.access', await options.access({ req }), { strict: strictAccessAnswers(req) }) : false) if (!allowed) {return Response.json({ error: 'Unauthorized' }, { status: 401 })} const status = await collectDoctorStatus(req.payload) return Response.json(status, { headers: { 'cache-control': 'no-store' } }) diff --git a/src/modules/shared/accessAnswer.ts b/src/modules/shared/accessAnswer.ts index 285cc1c..2737d57 100644 --- a/src/modules/shared/accessAnswer.ts +++ b/src/modules/shared/accessAnswer.ts @@ -1,30 +1,50 @@ /** * The answer of a project's access callback (`cookieScanner.access`, the doctor's `access`), read the same way - * everywhere (owner's decision Q4, 1.18.0). + * everywhere (owner's decisions Q4 and "Tak, w 1.18.0"). * - * Today any truthy answer lets the request in, as before: `({ req }) => req.user` returns an account object, and - * a function that returns `'no'` or `{}` lets the request in too. From the next minor version only `true` will - * allow. Until then the first answer that is not a boolean is reported once per option in the server log, so a - * project sees it before the change. (A callback needs a request to be asked, so this cannot be checked at start: - * the warning comes with the first call.) + * Since 1.18.0 only a literal `true` allows. `({ req }) => req.user` returns an account object and is now REFUSED; + * so are `1`, `'yes'`, `{}` and a Promise that was not awaited. The first answer that is not a boolean is reported + * once per option in the server log, naming the option and the fix. (A callback needs a request to be asked, so + * this cannot be checked at start: the report comes with the first call.) + * + * A project that needs the old reading back sets `iapl({ strictAccessAnswers: false })`: any truthy answer allows + * again (still reported once per option). */ const warned = new Set() export type AccessAnswerOptions = { + /** Only a literal `true` allows (default). `false` = any truthy answer allows, as before 1.18.0. */ + strict?: boolean /** Where to report (default `console.warn`). */ warn?: (message: string) => void } -/** True when the request may pass; warns once per `option` when the answer is not a boolean. */ -export function accessAllowed(option: string, answer: unknown, { warn = (m) => console.warn(m) }: AccessAnswerOptions = {}): boolean { +const kindOf = (answer: unknown): string => { + if (answer === null) {return 'null'} + if (Array.isArray(answer)) {return 'an array'} + if (answer && typeof (answer as { then?: unknown }).then === 'function') {return 'a Promise (not awaited)'} + if (typeof answer === 'object') {return 'an object'} + return /^[aeiou]/.test(typeof answer) ? `an ${typeof answer}` : `a ${typeof answer}` +} + +/** True when the request may pass; reports once per `option` when the answer is not a boolean. */ +export function accessAllowed(option: string, answer: unknown, { strict = true, warn = (m) => console.warn(m) }: AccessAnswerOptions = {}): boolean { + const allowed = strict ? answer === true : Boolean(answer) if (typeof answer !== 'boolean' && !warned.has(option)) { warned.add(option) - const kind = answer === null ? 'null' : Array.isArray(answer) ? 'an array' : typeof answer === 'object' ? 'an object' : `a ${typeof answer}` warn( - `[iapl] ${option} returned ${kind}, not true or false. It is still read as ${answer ? 'allowed' : 'refused'}; from the next minor version only \`true\` allows. Return a boolean, e.g. \`({ req }) => Boolean(req.user)\` (docs/security.md "Access callbacks").`, + `[iapl] ${option} returned ${kindOf(answer)}, not true or false, so the request was ${allowed ? 'allowed' : 'refused'}` + + `${strict ? ' (only `true` allows since 1.18.0)' : ' (strictAccessAnswers: false reads any truthy answer as allowed)'}. ` + + 'Return a boolean, e.g. `({ req }) => Boolean(req.user)` (docs/security.md "Access callbacks").', ) } - return Boolean(answer) + return allowed +} + +/** Whether the config behind this request reads access answers strictly (`strictAccessAnswers`, default true). */ +export function strictAccessAnswers(req: { payload?: { config?: { custom?: Record } } } | undefined): boolean { + const iapl = req?.payload?.config?.custom?.iapl as { strictAccessAnswers?: boolean } | undefined + return iapl?.strictAccessAnswers !== false } /** For tests: forget which options were reported. */ diff --git a/src/modules/shared/switches.ts b/src/modules/shared/switches.ts index 2210e15..774eaeb 100644 --- a/src/modules/shared/switches.ts +++ b/src/modules/shared/switches.ts @@ -80,6 +80,19 @@ export function assertPluginSwitches(options: Record): void { assertSwitchOrObject(name, options[name]) } assertBooleanSwitch('indexNow', options.indexNow) + // 1.18.0 (security audit): `listLimit: 0` / `'false'` must not read as off; a max below 1 caps every list to nothing + assertSwitchOrObject('listLimit', options.listLimit, { allowTrue: false }) + const listLimit = bag(options.listLimit) + if (listLimit) { + assertNumberSwitch('listLimit.max', listLimit.max, { min: 1 }) + assertBooleanSwitch('listLimit.staff', listLimit.staff) + if (listLimit.exclude !== undefined && !(Array.isArray(listLimit.exclude) && listLimit.exclude.every((c) => typeof c === 'string'))) { + throw new Error(`${where('listLimit.exclude')} must be a list of collection slugs such as ['products'] (received ${JSON.stringify(listLimit.exclude)}).`) + } + } + assertBooleanSwitch('refuseOperatorSort', options.refuseOperatorSort) + assertSwitchOrObject('lockedDocuments', options.lockedDocuments, { allowTrue: false }) + assertBooleanSwitch('strictAccessAnswers', options.strictAccessAnswers) // 1.17.2: `adminSameOrigin: 0` / `'false'` must not read as off (it took the origin check off the panel actions) assertSwitchOrObject('adminSameOrigin', options.adminSameOrigin) const adminSameOrigin = bag(options.adminSameOrigin) diff --git a/src/plugin.ts b/src/plugin.ts index fcd6c25..dd7c78a 100644 --- a/src/plugin.ts +++ b/src/plugin.ts @@ -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 }) diff --git a/src/types.ts b/src/types.ts index d4202f8..3c347c1 100644 --- a/src/types.ts +++ b/src/types.ts @@ -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 diff --git a/test/accessAnswer.test.ts b/test/accessAnswer.test.ts index 99dc14b..92d753a 100644 --- a/test/accessAnswer.test.ts +++ b/test/accessAnswer.test.ts @@ -1,12 +1,12 @@ /** - * Access callbacks of a project (`cookieScanner.access`, the doctor's `access`), owner's decision Q4, 1.18.0: - * still allowed on any truthy answer, but an answer that is not a boolean is reported once per option, so a - * project sees it before the next minor version allows only `true`. Every call site goes through one function. + * Access callbacks of a project (`cookieScanner.access`, the doctor's `access`), owner's decision for 1.18.0: only a + * literal `true` allows; an answer that is not a boolean is reported once per option; `strictAccessAnswers: false` + * gives the old truthy reading back. Every call site goes through one function. */ import { readFileSync } from 'node:fs' import { beforeEach, describe, expect, test, vi } from 'vitest' -import { accessAllowed, resetAccessWarnings } from '../src/modules/shared/accessAnswer.js' +import { accessAllowed, resetAccessWarnings, strictAccessAnswers } from '../src/modules/shared/accessAnswer.js' beforeEach(() => resetAccessWarnings()) @@ -18,19 +18,47 @@ describe('accessAllowed', () => { expect(warn).not.toHaveBeenCalled() }) - test.each([ - [{ id: 1 }, true, 'an object'], - ['no', true, 'a string'], - [1, true, 'a number'], - [null, false, 'null'], - [undefined, false, 'a undefined'], - ])('%j is read as before (%s) and reported once', (answer, allowed, kind) => { + // the owner's decision for 1.18.0: only a literal `true` allows (the old reading in the third column) + const answers: [string, unknown, boolean, string][] = [ + ['an object (req.user)', { id: 1 }, true, 'an object'], + ['1', 1, true, 'a number'], + ['a string', 'yes', true, 'a string'], + ['null', null, false, 'null'], + ['undefined', undefined, false, 'an undefined'], + ] + + test.each(answers)('%s refuses (strict, the default) and is reported once, naming the option and the fix', (_, answer, _old, kind) => { const warn = vi.fn() - expect(accessAllowed('doctor.access', answer, { warn })).toBe(allowed) - expect(accessAllowed('doctor.access', answer, { warn })).toBe(allowed) + expect(accessAllowed('doctor.access', answer, { warn })).toBe(false) + expect(accessAllowed('doctor.access', answer, { warn })).toBe(false) expect(warn).toHaveBeenCalledTimes(1) expect(warn.mock.calls[0][0]).toContain(`doctor.access returned ${kind}`) - expect(warn.mock.calls[0][0]).toContain('only `true` allows') + expect(warn.mock.calls[0][0]).toContain('Boolean(req.user)') + }) + + test.each(answers)('%s with strictAccessAnswers: false is read as before 1.18.0 (truthy allows)', (_, answer, old) => { + expect(accessAllowed('cookieScanner.access', answer, { strict: false, warn: vi.fn() })).toBe(old) + }) + + test('a Promise is never `true`: an un-awaited answer refuses, whatever it holds', () => { + const warn = vi.fn() + for (const value of [true, { id: 1 }, 1, 'yes']) { + const p = Promise.resolve(value) + expect(accessAllowed('doctor.access', p, { warn })).toBe(false) + } + expect(warn.mock.calls[0][0]).toContain('a Promise (not awaited)') + }) + + test('async callbacks: the call sites await the answer, so a Promise of each reads like the value itself', async () => { + const asCalled = async (cb: () => Promise) => accessAllowed('cookieScanner.access', await cb(), { warn: vi.fn() }) + expect(await asCalled(async () => true)).toBe(true) + for (const value of [{ id: 1 }, 1, 'yes', false, null]) {expect(await asCalled(async () => value)).toBe(false)} + }) + + test('strictAccessAnswers(req) reads the option from the request\'s config', () => { + expect(strictAccessAnswers(undefined)).toBe(true) + expect(strictAccessAnswers({ payload: { config: { custom: {} } } })).toBe(true) + expect(strictAccessAnswers({ payload: { config: { custom: { iapl: { strictAccessAnswers: false } } } } })).toBe(false) }) test('each option is reported on its own', () => { @@ -47,6 +75,6 @@ test('every call of a project access callback goes through accessAllowed', () => const text = readFileSync(file, 'utf8') const calls = text.match(/await options\.access\(\{ req \}\)/g) ?? [] expect(calls.length, file).toBeGreaterThan(0) - expect(text.match(/accessAllowed\('[\w.]+', await options\.access\(\{ req \}\)\)/g)?.length, file).toBe(calls.length) + expect(text.match(/accessAllowed\('[\w.]+', await options\.access\(\{ req \}\), \{ strict: strictAccessAnswers\(req\) \}\)/g)?.length, file).toBe(calls.length) } }) diff --git a/test/iawlIdeasB.test.ts b/test/iawlIdeasB.test.ts index 9777faf..9333ea4 100644 --- a/test/iawlIdeasB.test.ts +++ b/test/iawlIdeasB.test.ts @@ -130,6 +130,14 @@ describe('switches refuse nonsense at start', () => { ['mail.relay', { mail: { relay: 'off' } }], ['storageNames', { storageNames: 'IAPL' }], ['forms.attachments.submit.maxPerMinute', { forms: { attachments: { submit: { maxPerMinute: 'off' } } } }], + // 1.18.0, security audit fixes: none of these may read as "off" + ['listLimit', { listLimit: 0 }], + ['listLimit', { listLimit: 'false' }], + ['listLimit.max', { listLimit: { max: 0 } }], + ['listLimit.exclude', { listLimit: { exclude: 'products' } }], + ['refuseOperatorSort', { refuseOperatorSort: 'false' }], + ['lockedDocuments', { lockedDocuments: 0 }], + ['strictAccessAnswers', { strictAccessAnswers: 'false' }], ])('%s: %j fails at start', async (name, options) => { expect(await start(options)).toThrow(name) })