Merge local main (1.17.2) into security-a-118

Conflicts resolved by keeping both sides: lockedAnswer + sign-in rules in plugin.ts and switches.ts, IPv6 grouping in the
mail service's new per-visitor address count, both built-site specs in e2e:built, docs and skills (reference copies
synced). The lockedAnswer suite and the sign-in-answers spec now reach Payload's lock the 1.18.0 way: a spray from
50 IPs, one failure each (one IP alone gets 429 after five).

Co-Authored-By: Claude Opus 5.5 <[email protected]>
This commit is contained in:
Radosław Smoliński
2026-12-01 12:57:52 +01:00
co-authored by Claude Opus 5.5
113 changed files with 3468 additions and 317 deletions
+92
View File
@@ -9,6 +9,98 @@ versions at once, go through every "Requires project changes" section in order,
version you have. A new release = a new section at the top; we remove the oldest ones only
once there are more than 20.
## 1.17.2 — version history with readPublished, sign-in and panel actions, staff-only REST submissions and jobs, the cookie button
> **Read before upgrading.** No schema change, no migration on any database, no import-map change. What changes for
> an existing site, most important first:
>
> 1. **Fix: `readPublished()` on version history.** The form 1.17.1 documented, `readVersions: readPublished()`,
> answered every version read by a visitor or a plain account with **500** (MongoDB, Postgres and SQLite alike).
> It now works by itself: iapl() gives that `readVersions` the new `readPublishedVersions()` with the same role.
> Visitors see published versions only; a draft version by id is `403`; staff see everything, as before. A
> `readVersions` of your own that **wraps** `readPublished()` is not changed: use `readPublishedVersions()` inside it.
> 2. **A locked staff account is told "The email or password provided is incorrect."** (REST, GraphQL, the panel),
> so five wrong passwords no longer tell a stranger that an address has a staff account. A locked editor with the
> right password sees "incorrect" too until the lock ends (10 minutes); an admin can unlock it. Payload's message
> back: `accounts: { lockedAnswer: 'payload' }`. Known: the answer's **time** still differs for an existing
> account (Payload hashes only then); that is for 1.18.0.
> 3. **The plugin's panel actions refuse other origins** (mail service Connect / Disconnect, Send test e-mail, cookie
> scan, approval, site check): `403` for a request a browser marks as coming from elsewhere. The panel's buttons
> work. **Behind a proxy that rewrites `Host` and sends no `X-Forwarded-Host`, set `serverURL`**, or those buttons
> are refused too (the log says so once; `iapl-doctor` warns). Off: `adminSameOrigin: false`.
> 4. **A customer account can no longer create form submissions over REST / GraphQL** (staff only). The site's own
> forms (`submitForm`, `createSubmitAction`, the file endpoint) are not affected. Way back:
> `forms.formSubmissionOverrides.access.create`.
> 5. **Payload's job queue over HTTP: only an admin or `Authorization: Bearer <CRON_SECRET>`** (16+ characters), when
> the project wrote no `jobs.access.run`. **A cron that calls `/api/payload-jobs/run` must set `CRON_SECRET` and
> send the header**, or it gets `401`. In-process runs and a project's own rule are not affected;
> `jobsRunAccess: false` keeps Payload's default.
> 6. **The cookie button stays in the bottom corner and never moves**; while it is shown the footer gets a little
> room under its last row (about 43 px on the reference site) so the button covers nothing. No layout shift.
> No room: `<CookieButton reserve={false} />`; the placement before: `<CookieButton avoid={COOKIE_BUTTON_AVOID} />`.
> 7. **The consent version only goes up** through the panel, REST and GraphQL (a lower number would make old consent
> count again). The Local API with `overrideAccess` may still lower it; `cookieSettings: { allowLowerPolicyVersion: true }`
> restores the old freedom.
> 8. **IPv6 visitors are counted per /64** by every plugin rate limit (one home network shares a budget, as an
> IPv4 home behind one router always did). Per address: `setIpv6Grouping({ prefix: 128 })`.
### Security
- **Version history with `readPublished()`** (point 1): new `readPublishedVersions(minimum)` for `readVersions`;
`withVersionReadRules(entities)` swaps a marked `readPublished()` on `readVersions` (iapl() runs it on the
collections and globals it sees; a plugin listed after iapl() uses `readPublishedVersions()` itself).
- **Locked staff accounts answer like a wrong password** (point 2): `lockedLooksWrong`, `withLockedAnswer`,
`graphqlLoginName`; type `LockedAnswerOption`.
- **Panel actions from the site's own origin only** (point 3): `requireOwnOrigin`, `guardAdminEndpoints`,
`ADMIN_POST_ENDPOINTS`; type `AdminSameOriginOption`; `reportRefusedOrigin(req, origins?, context?)` takes a third
argument; `iapl-doctor` warns (`csrf-empty`) without `serverURL` or `csrf`.
- **A customer account can no longer create submissions over REST.** `POST /api/form-submissions` (and GraphQL
`createFormSubmission`) needed only a signed-in account of any login collection, so a customer of a visitor
collection could skip the rate limit, Turnstile, the consent tick and the validation, and the form's e-mails went
out. Now: a staff account with its second factor. The site's own forms (`submitForm`, `createSubmitAction`, the file
endpoint) are not affected. Way back: `forms.formSubmissionOverrides.access.create`.
- **Payload's job queue over HTTP: only an admin or the cron secret.** When the project writes no
`jobs.access.run`, `/api/payload-jobs/run` and `/handle-schedules` now answer only an admin signed in with the second
factor (an admin's API key counts) or `Authorization: Bearer <CRON_SECRET>` (16+ characters); before, any signed-in
account of any login collection. **A site whose cron calls the run route:** set `CRON_SECRET` in the app's
environment and send the header; the start log says so when it is missing. In-process runs (`jobs.autoRun`,
`payload jobs:run`) and a project's own rule are not affected; `iapl({ jobsRunAccess: false })` keeps Payload's
default (security.md "Payload's job queue").
- **The consent version only goes up** (point 7): `policyVersionNeverDown`, `buildCookieSettingsFields`,
`buildCookieSettings(options)`; type `CookieSettingsFieldOptions`.
- **IPv6 per network** (point 8): `setIpv6Grouping`, `ipRateKey`; type `Ipv6Grouping`. A second counter per /48 is
available (`wide: 48`), off by default.
### Added
- `iapl-doctor` deep rule **`visitor-writes`** (warning): on a site with a visitor login collection, every collection
and global whose write rule lets such an account in, Payload's default included.
- `jobsRunAccess`, `withJobsRunAccess`, `jobsRunNotice`, `cronSecretMatches`, `CRON_SECRET_ENV`,
`CRON_SECRET_MIN_LENGTH`; option `jobsRunAccess`; env `CRON_SECRET`.
- `CookieButton` prop `reserve` (the block that gets the room; `false` = off); `COOKIE_BUTTON_RESERVE`,
`COOKIE_BUTTON_SPACE_ATTRIBUTE`, `reserveCookieButtonSpace` (`/client`, type `CookieButtonSpaceOptions`);
`consentDecidedScript` (root); the token `--ipal-cookie-button-space`.
### Changed
- **What an existing site's visitors see: the "cookie settings" button stays in the bottom corner of the window and
never moves; the footer is a little taller while it is shown**
([consent.md → Where the cookie button sits](./consent.md#where-the-cookie-button-sits-1172)). Until now the button
moved up by the visible part of the footer: on a phone with a tall footer it ended at the top of the screen (over
the header), on a short page in the middle of it. Now it is in the same corner on every page and at every scroll
position. So that it covers nothing at the very end of a page, the footer gets bottom padding while the button is
shown — just enough for its last row to end above the button (measured: the footer's own padding counts, an empty
corner gets nothing; on the reference site 42–43 px on phones and desktop). Not before a decision, not while the
banner is open. No layout shift: for a returning visitor the room is made before the first paint. Same look,
keyboard and screen-reader access unchanged; the side inset now adds the device's safe-area inset.
**Nothing to do; an existing site gets it by updating.** No room: `<CookieButton reserve={false} />`; an amount of
your own: `--ipal-cookie-button-space` on the footer (`0` = none, also per breakpoint); the placement before:
`<CookieButton avoid={COOKIE_BUTTON_AVOID} />` (on `SiteProviders`: `cookieButton={…}`). A site that passes a
selector in `avoid` keeps its behaviour. A project e2e test that expects the button above the footer, or an exact
footer height after a decision, needs an update.
- The reference site (and every new site from `iapl create`): `Pages`, `Posts`, `CaseStudies`, `Media` and the
`Header`, `Footer`, `Company` globals have their own write rules (`adminOrEditor`) instead of Payload's default.
Existing sites: nothing changes; the doctor's `visitor-writes` names what to add where it matters.
- Not built (owner's Q3 answer (a), planned for 2.0): a plugin-wide default for the project's own entities and for
Payload's `payload-locked-documents`.
## 1.17.1 — security fixes from the IAWL review; the panel's sign-in look; the sending method is chosen
> **Read before upgrading.** **MongoDB: no migration. Postgres / SQLite: one migration** — a new column for the
+40 -3
View File
@@ -195,10 +195,26 @@ access: { update: requireRole('editor') }
// a collection with drafts: editors (or the role you name) read everything; visitors, plain `user` accounts and a
// session that still owes its second factor read published documents only — by id, in lists, with ?draft=true and
// over GraphQL. Payload's open `read: () => true` answers ?draft=true with the draft itself (1.17.1).
access: { read: readPublished(), readVersions: readPublished() }
access: { read: readPublished('admin') }
// Version history asks for the status at another path: readPublishedVersions() goes on readVersions (1.17.2).
access: { read: readPublished(), readVersions: readPublishedVersions() }
access: { read: readPublished('admin'), readVersions: readPublishedVersions('admin') }
```
**Where each rule may be used.**
| Rule | Where | What a visitor gets |
|---|---|---|
| `readPublished()` | `access.read` of a collection or global with `versions: { drafts: true }` | published documents: by id, lists, `?draft=true`, GraphQL |
| `readPublishedVersions()` | `access.readVersions` of the same collection or global | published versions: the version list, one version by id (a draft one: `403`), the count, GraphQL, the panel's version view |
The two answer with different paths: a document has `_status`, a version has `version._status`. In 1.17.1,
`readVersions: readPublished()` (the form these docs showed) answered every version read with **500** on MongoDB,
Postgres and SQLite. Since 1.17.2, iapl() swaps a `readPublished()` it finds on `readVersions` of a collection or
global for `readPublishedVersions()` with the same role, so that form works too. A collection added by a plugin
listed **after** iapl() is not seen: use `readPublishedVersions()` there, or `withVersionReadRules(collections)`.
Neither rule belongs on a collection without drafts (no `_status`: every read would fail). Check: without a session,
`GET /api/<slug>/versions?limit=10` → `200` with published versions only, never `500`.
A role name the plugin does not know (`requireRole('Admin')`, `readPublished('superadmin')`) throws where the rule
is written; `hasMinimumRole` / `userMeetsRole` answer `false` for it (before 1.17.1 every staff account met it).
`readPublished` with `?draft=true` on a page whose newest version is a draft answers a visitor `404` (Payload applies
@@ -250,6 +266,7 @@ iapl({
// accounts: { firstUserRoute: 'all' }, // Payload's first-user route for every empty auth collection
// accounts: { firstUserRoute: ['users', 'partners'] },
// accounts: { password: { minLength: 16 } }, // or password: false
// accounts: { lockedAnswer: 'payload' }, // a locked staff account is told it is locked (Payload's answer)
// accounts: { signInLimit: { perAddress: 10, windowMinutes: 15 } }, // or signInLimit: false (Payload's lock as before)
// accounts: { signInSameOrigin: { origins: ['https://panel.example.com'] } }, // or signInSameOrigin: false
// accounts: { confirmOwnChanges: false }, // own e-mail / password without the current password (as before)
@@ -480,6 +497,26 @@ characters."; texts `passwordTooShort`, `passwordIsEmail` in `i18n.translations.
`DEFAULT_PASSWORD_MIN_LENGTH`.
- **Check:** create an account with an 11-character password → "The password must have at least 12 characters.".
### A locked staff account answers like a wrong password (`accounts.lockedAnswer`, 1.17.2)
Payload locks an account after `maxLoginAttempts` wrong passwords (5 by default; on staff collections 50 for an hour
since 1.18.0, `signInLimit` below) for `lockTime` (10 minutes by default), and
it checks the lock **before** the password: the locked account then gets `401 "This user is locked due to having too
many failed login attempts."` for any password, while an address with no account always gets `401 "The email or
password provided is incorrect."`. Five wrong guesses told anybody, without a password, whether an address has a
staff account. Now a staff collection's login answers a locked account exactly like a wrong password — the same
status, body and GraphQL `extensions.name` (`AuthenticationError`) — over REST, GraphQL and the panel's sign-in
form. The lock itself is unchanged: the owner's correct password is still refused until it ends, and the owner is
then told "wrong e-mail or password" (an administrator sees `lockUntil` on the account and can unlock it). Visitor
collections (not staff) keep Payload's answer.
- **Turn off:** `accounts: { lockedAnswer: 'payload' }` (Payload's message), or `accounts: false`. Any other value
stops the start.
- **Building blocks:** `lockedLooksWrong` (the config-level `afterError` hook), `withLockedAnswer(config)`,
`graphqlLoginName(collection)` (`login<SingularName>`, as GraphQL names the mutation).
- **Check:** five wrong passwords for an admin's address, then `POST /api/users/login` with the right one → the same
`401` body as for `nobody@example.com`; GraphQL `loginUser` → `extensions.name: "AuthenticationError"`.
### A stranger cannot lock a staff account out (`accounts.signInLimit`, 1.18.0)
Payload locks an account after `maxLoginAttempts` wrong passwords (5) for `lockTime` (10 minutes) — wrong passwords
@@ -548,7 +585,7 @@ current passwords count like failed sign-ins (`signInLimit`). The field is virtu
## Turn off, override, extend
- **Account rules:** `accounts: false`, or one by one — `panelRole`, `adminOnlyCreate`, `adminOnlyWrite`,
`staffOnlyRead`, `firstUserRoute`, `password`, `signInLimit`, `signInSameOrigin`, `confirmOwnChanges` (above).
`staffOnlyRead`, `firstUserRoute`, `password`, `lockedAnswer`, `signInLimit`, `signInSameOrigin`, `confirmOwnChanges` (above).
- **Turn off:** leave out `access` — no `roles` field, the auth collection keeps Payload's rules
(or yours). `access.firstUserAdmin: false` stops giving admin to the first account.
- **Override:** `access.staffCollections` (who is staff), `access.authAccess` (injected collection), your own auth collection (wins whole),
+17 -3
View File
@@ -636,12 +636,18 @@ for visitors. Then, all four:
`access.staffCollections` is for a second collection of STAFF (access.md → "Who is staff").
3. In every auth collection use `adminOrSelfIn('<its slug>')`, not `adminOrSelf`, for "only my own record".
4. Payload's default for a collection or global without `access` is "any logged-in account" — a customer too.
Give every collection and global explicit `access`. 2FA covers the panel's collection only.
Give every collection and global explicit `access` (writes: `adminOrEditor`, as the reference site's collections
and globals do since 1.17.2). Verify with `iapl-doctor --url …` (deep): no `visitor-writes` finding. 2FA covers
the panel's collection only.
5. Never let a sign-up write a field that grants rights (`roles`, `isAdmin`, …): give such a field
`access: { create: adminOnlyField, update: adminOnlyField }`.
6. Check: log in as such an account (`POST /api/customers/login`), then `GET /api/globals/site-integrations`,
`GET /api/form-submissions` and `GET /api/users` with its token must answer `403`, and so must
`POST /api/setup-totp`.
`POST /api/setup-totp`, `POST /api/form-submissions` and (a site with Payload jobs) `GET /api/payload-jobs/run`
(`401`).
7. Payload jobs run over HTTP: since 1.17.2 only an admin or `Authorization: Bearer <CRON_SECRET>` (when the project
writes no `jobs.access.run`). A Coolify scheduled task that calls `/api/payload-jobs/run` sends that header;
`CRON_SECRET` goes into the app's environment (security.md "Payload's job queue").
**NEVER:** a second `media`, `daneFirmy`/`settings`/
`navigation`/`footer` as collections (they are globals), FAQ/hero/features as collections
@@ -1103,7 +1109,7 @@ project → **plugin gap**, not a copy.
| ISR after save, old slug → 308, images across languages | `buildRevalidateHook`, `trackSlugHistoryHook`, `buildCrossLocaleFieldSync` | hooks.md |
| ISR after a global is saved | plugin globals: `iapl({ revalidatePath })`; your own globals: `buildGlobalRevalidateHook({ revalidatePath })` | hooks.md |
| Change a plugin global (access, hooks, fields) | `iapl({ globalOverrides })` | access.md |
| Roles and access | `adminOnly`, `adminOrEditor`, `adminOrSelf`, `adminOrSelfIn(slug)` (several auth collections), `authenticated`, `requireRole`, `hasMinimumRole` (+ `…Field`); a collection with drafts: `access: { read: readPublished(), readVersions: readPublished() }` (editors read drafts, everybody else published only — Payload's open `read: () => true` answers `?draft=true` with the draft; verify: `GET /api/<slug>/<draft id>?draft=true` without a session → 404); an unknown role name throws where the rule is written; staff checks: `userMeetsRole(req, role)`, `isAdmin(req.user, req.payload)` (roles count only for accounts of a staff collection; in a client component `isAdmin(user, config)` with `useConfig()`, imported from **`@intecion/ipal-kit/client`** (the main entry does not build there with webpack), in middleware `isAdmin(user, { staffCollections: ['users'] })` — without the last argument there it is always `false`), `staffCollectionSlugs(payload)`, `access.staffCollections`; second factor in your own code: `secondFactorPassed(req)`, `requireSecondFactor(access)`; injected `users`: `access.authAccess`, first user = admin (`access.firstUserAdmin`) | access.md, security.md |
| Roles and access | `adminOnly`, `adminOrEditor`, `adminOrSelf`, `adminOrSelfIn(slug)` (several auth collections), `authenticated`, `requireRole`, `hasMinimumRole` (+ `…Field`); a collection or global with drafts: `access: { read: readPublished(), readVersions: readPublishedVersions() }` (editors read drafts and every version, everybody else published only — Payload's open `read: () => true` answers `?draft=true` with the draft; `readPublished` is for `read` only, `readPublishedVersions` for `readVersions` only — `readVersions: readPublished()` answered 500 in 1.17.1 and is swapped for you since 1.17.2 on entities iapl() sees, `withVersionReadRules(entities)` for a plugin listed after it, `READ_PUBLISHED` marks the rule; neither on a collection without drafts; verify: without a session `GET /api/<slug>/<draft id>?draft=true` → 404 and `GET /api/<slug>/versions?limit=10` → 200, published only); an unknown role name throws where the rule is written; staff checks: `userMeetsRole(req, role)`, `isAdmin(req.user, req.payload)` (roles count only for accounts of a staff collection; in a client component `isAdmin(user, config)` with `useConfig()`, imported from **`@intecion/ipal-kit/client`** (the main entry does not build there with webpack), in middleware `isAdmin(user, { staffCollections: ['users'] })` — without the last argument there it is always `false`), `staffCollectionSlugs(payload)`, `access.staffCollections`; second factor in your own code: `secondFactorPassed(req)`, `requireSecondFactor(access)`; injected `users`: `access.authAccess`, first user = admin (`access.firstUserAdmin`) | access.md, security.md |
| Data from globals | `getGlobal`, `getSiteSettings`, `getSiteIntegrations` | payload-helpers.md |
**Links and navigation**
@@ -1161,6 +1167,7 @@ project → **plugin gap**, not a copy.
|---|---|---|
| Banner, settings, cookie button | `<SiteProviders banner={<CookieBanner …/>}>`, `CookieButton`, `useConsent` | consent.md |
| Compliance defaults (1.17.0): Global Privacy Control honoured (no banner, no tracker request, opt-in from the cookie button wins), "Reject" like "Accept all", consent log on, withdrawal tells Meta / TikTok / Clarity and clears listed storage keys | built in; opt-outs: `SiteProviders gpc="ask"` / `gpc={false}`, `CookieBanner equalChoice={false}`, `iapl({ consentLog: false })` / `logEndpoint={false}`, `maxAgeDays` (re-ask, default 180); building blocks `resolveConsent`, `gpcFromHeaders`, `gpcFromNavigator`, `GPC_CATEGORIES`, `GPC_HEADER`, `CONSENT_LOG_PATH`, `gpcWellKnown` (`/.well-known/gpc.json`), `readEffectiveConsent`, `signalVendors`, `clarityConsent` (`/client`). Check: `iapl-consent-check` (5 runs incl. GPC, equal prominence, withdrawal), `iapl-doctor` (`consent-banner`, `consent-log-migration`) | consent.md → "Compliance defaults", consent-behaviour-spec.md |
| Cookie button placement | built in: bottom corner of the window on every page, never moves, never in or above the footer; the footer gets room under its last row while the button is shown, so nothing is covered at the page end. `CookieButton side` / `reserve` (`false` = no room) / `avoid` (`avoid={COOKIE_BUTTON_AVOID}` = above the footer, as before 1.17.2), tokens `--ipal-cookie-button-offset` / `-inset`, amount by hand `--ipal-cookie-button-space` on the footer. Do not render the button inside the footer, write a scroll handler for it, or add bottom padding for it by hand | consent.md → "Where the cookie button sits" |
| Banner at first paint (not after hydration; LCP) | built in: `CookieBanner firstPaint` (default on), `SiteProviders nonce` under a nonce CSP; off: `firstPaint={false}`; server-exact HTML on a dynamic site: `SiteProviders consentCookie` / `ConsentProvider cookieValue`; your own banner: `consentBannerScript`. Check: `curl -s <page> \| grep -c 'data-ipal="banner-script"'` → 1 and the response still has `s-maxage` | consent.md → "First paint" |
| Settings window: in the bar / small / large with cookie details | `<CookieBanner settings="inline" \| "modal" \| "detailed">` — do not build your own window or cookie list | consent.md → "Large window with details" |
| A consent-dependent script | `ConsentScript` | consent.md |
@@ -1217,6 +1224,10 @@ add missing hosts with flags / `extra`; (3) change `mode` to `'enforce'` in both
| Rich-text links: one rule for every stored URL — `link`, `autolink` (also marked internal) and the Markdown output (`lexicalToMarkdown`) drop `javascript:` / `data:` targets | `safeLinks={false}` (trusted content only) | `sanitizeRichTextLinks`, `safeHref` |
| Locales: no stand-in — `resolveRoute` (page route, `/md/…`, MCP `get_page`) answers `null` for a locale the site does not have (`xx`, `all`); a 404 page that is a draft is not shown (built-in view instead) | — | `isSiteLocale(payload, locale)`; verify: `curl -i <site>/md/xx` → 404 |
| Site integrations versions (when a project turns them on) are read by admins only (`readVersions`) | — | `globalOverrides: { 'site-integrations': { access: { readVersions } } }` |
| 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" |
| 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` |
@@ -1227,11 +1238,13 @@ add missing hosts with flags / `extra`; (3) change `mode` to `'enforce'` in both
| 2FA setup required: an account without TOTP reaches only the setup screen; 72 h window from creation / admin reset, then blocked; status and "Reopen setup" on the account page, notice on the dashboard, `POST /api/ipal/two-factor/reset` | `twoFactor.requireSetup: false`; parts: `requireSetup: { dashboardNotice: false, statusField: false, setupNotice: false }` | `requireSetup: { windowHours, exempt }` (`exempt` returns exactly `true`, never `async`; decide it from a field only admins write, e.g. a `serviceAccount` checkbox with `adminOnlyField` — never from the e-mail, which every account may change itself; security.md "Decide `exempt` from a field only an administrator can write"), `twoFactor.resetAccess` (default: an admin who entered its own code; the reset ends the account's sessions), texts `twoFactor*`; `twoFactorSetupState(req)`, `buildSetupFields`, `backfillSetupFrom`, `buildTwoFactorResetEndpoint`. **Postgres/SQLite: migration for `totp_setup_from` applied when the new container starts (`prodMigrations` or `pnpm payload migrate && pnpm start`; never a pre-deployment command — deployment.md §4.3), or every login answers 500** |
| The second factor on every collection and global, whichever plugin added it, and on the plugin's endpoints; an unrecognised 2FA package = startup error | per entity: `custom.ipal.secondFactor: false` or `{ read: false }` (or the package's `custom.totp.disableAccessWrapper`); everywhere: `twoFactor.guard: false` (not recommended) | `requireSecondFactor` / `secondFactorPassed` in your own access functions and endpoints |
| At most 5 **wrong** verify codes per account in 10 minutes (`POST /api/verify-totp` → `429`); a right code gives its place back (1.17.1), so correct logins are never refused; an attempt held out only by others still being checked gets `429` + `Retry-After: 2` ("try again in a moment"); the count is kept in memory and in the database (`payload.kv`), so a restart or a second instance does not reset it. **Verify:** log in correctly 7 times in a row → all in; 5 wrong codes → the next gets `429` with a long `Retry-After` | `twoFactor.verifyLimit: false` | `verifyLimit: { max, windowMinutes, store: 'memory' }`; own wiring: `buildVerifyLimit(...)` + `limit.settle(req, correct)` |
| The plugin's panel actions (`POST` mail service connect / disconnect, test e-mail, cookie scan / approval / crawl) refuse a request a browser marks as coming from another origin (`403`, before anything is read; 1.17.2). The panel's buttons are not affected; set `serverURL` (doctor `csrf-empty` warns without it). **Verify:** `curl -X POST <site>/api/ipal/test-email -H 'Origin: https://other.example' -H 'Content-Type: text/plain' -b <admin cookies> -d '{}'` → `403` | `adminSameOrigin: false` | `adminSameOrigin: { origins: [...] }`; `requireOwnOrigin(endpoint, origins?)` for your own endpoints |
| 2FA verify and setup attempts only from the site's own origin: a request a browser marks as coming from elsewhere (`Origin`, `Sec-Fetch-Site`) gets `403` and is not counted. The admin's reset `POST /api/ipal/two-factor/reset` follows the same rule (1.17.1). **Verify:** `curl -X POST <site>/api/ipal/two-factor/reset -H 'Origin: https://other.example' -H 'Content-Type: text/plain' -b <admin cookies> -d '{"userId":1}'` → `403`; the panel's button still works. **Set `serverURL`**: behind a proxy that rewrites `Host` and sends no `X-Forwarded-Host` the site's own page is refused without it (logged once per origin: `[iapl] 2FA: a code from origin … was refused`) | `twoFactor.sameOrigin: false` | `sameOrigin: { origins: ['https://app.example.com'] }`; `requestFromOwnOrigin`, `reportRefusedOrigin` |
| Stored secrets are write-only: `smtpPassword` and `turnstileSecretKey` come back as `'********'` over REST, GraphQL and in the panel; an empty save keeps the value, `'[[clear]]'` removes it; server code reads the real value with the Local API. A query cannot name a secret (1.17.1): `where` / `sort` on it — REST, GraphQL, versions — is refused (`secretReadAccess`, the field's `read` rule; verify: `GET /api/globals/site-integrations/versions?where[version.smtpPassword][exists]=true` as an admin → 400 `QueryError`, no `totalDocs`). **The panel is the source — never add an env variable for them** (`TURNSTILE_SECRET_KEY` is deprecated) | `secrets: { writeOnly: false }` | `writeOnlySecret(field)` / `writeOnlySecrets(fields, names)` for your own secret fields; with versions on the entity add `hooks.afterRead: [maskSecretsOnRestore]` |
| The SMTP password stays with its server: a save in the panel or over the API that changes the server, port or user name without the password is refused (`400` "Enter the password again…"), whatever the transport says — otherwise an admin session points the server at its own machine and a test e-mail hands the password over. A change of the transport alone asks for nothing. Seeds and scripts (Local API, access control off) are not asked | `secrets: { reenterOnChange: false }` | `writeOnlySecret(field, { boundTo: [...] })`, `buildKeepSecret`, `SMTP_PASSWORD_BOUND_TO` |
| The admin panel opens for `editor` and above; an account with only `user` sees "Unauthorized" (the API is not touched). First start logs how many accounts are below the role | `accounts: { panelRole: 'user' }` (or `false`) | `panelRole: 'admin'`; your own `access.admin`; `panelAccess(role)` |
| Nobody creates an account for themselves, or takes one over. A staff collection (also the project's own, also one a later plugin adds) without a `create` / `update` / `delete` / `unlock` / `read` / `readVersions` rule gets one (on a collection a later plugin adds the plugin's rule is put in front of its own and both must allow; `custom: { ipal: { accountRules: false } }` on it keeps its own): with the plugin's roles, or wherever an account of it can hold `editor` or `admin` (`user, editor, admin, boss`; `viewer, editor`; a `roles` field that is text, json or a relationship holding a list — the value in the account's `roles` array makes a plugin admin or editor; a single-valued `roles` field is not affected: its value never counts) — create, delete, unlock: an admin; update: an admin or the account itself; the `roles` field: only an admin. With roles of its own that hold neither `editor` nor `admin`, or none: an account of that same collection, or a plugin admin, and an account never changes its own roles — **the plugin cannot rank a project's own roles: write that collection's rules** (`iapl-doctor` → `staff-own-roles`). `read`: a staff account. Payload's first-user route answers only for the panel's login collection (the first account, which becomes admin), in any spelling of the URL. `access.firstUserAdmin: false` with a default role below the panel role: the default panel role is not applied (logged), an explicit one is refused at start. With a slug in `access.staffCollections` that is not an auth collection Payload does not start (`/api/health` 503) | `accounts: { adminOnlyCreate: false, adminOnlyWrite: false, staffOnlyRead: false, firstUserRoute: 'all' }` | your own rule wins; `firstUserRoute: ['users', 'partners']`; a collection with open sign-up keeps its routes; `staffCreateAccess`, `staffUpdateAccess(slug)`, `staffReadAccess`, `sameStaffCollectionAccess(slug)`, `rolesByAdminOnly`, `rolesNotOwn(slug)`, `hasPluginRoles`, `applyStaffAccountAccess`, `adoptLateAuthCollections`, `buildFirstUserEndpoint` |
| A locked staff account (Payload's `maxLoginAttempts`) answers its login exactly like a wrong password — REST body and status, GraphQL `extensions.name: AuthenticationError`, the panel's sign-in (1.17.2); visitor collections keep Payload's answer. **Verify:** 5 wrong passwords for an admin, then the right one → the same `401` body as for an unknown address | `accounts: { lockedAnswer: 'payload' }` | `lockedLooksWrong`, `withLockedAnswer(config)`, `graphqlLoginName` |
| Failed staff sign-ins counted per client IP and typed address (folded: case, width, NFKC): 5 in 15 min, then `429` for that IP and address; only failures count; Payload's per-account lock raised to 50 failures / 1 hour where the project did not set `maxLoginAttempts` / `lockTime` (1.18.0). Pin `IAPL_IP_HEADER`. **Verify:** 5 wrong passwords with `X-Forwarded-For: 198.51.100.1`, then the right one from there → `429`, from another address → `200` | `accounts: { signInLimit: false }` | `signInLimit: { perAddress, windowMinutes, accountLock: { maxLoginAttempts, lockTime } \| false }`; `applySignInRules`, `releaseRateLimit` |
| Staff login, forgot password and reset password refuse a request a browser marks as coming from another origin (`403`, REST and GraphQL; 1.18.0); visitor collections untouched. **Verify:** `curl -X POST <site>/api/users/login -H 'Origin: https://other.example' …` → `403` | `accounts: { signInSameOrigin: false }` | `signInSameOrigin: { origins: [...] }` |
| Changing one's OWN e-mail, username or password needs the current password: panel field "Current password" on the account page (`MaskedField`, no import-map change), `currentPassword` over REST / GraphQL; admins changing others, server code and API keys are not asked; wrong ones count like failed sign-ins (1.18.0). **Verify:** `PATCH /api/users/<own id> {"email":"…"}` → `400`, with `"currentPassword"` → `200` | `accounts: { confirmOwnChanges: false }` | `buildCurrentPasswordField`, `passwordMatches`, `CURRENT_PASSWORD_FIELD` (access.md) |
@@ -1243,6 +1256,7 @@ add missing hosts with flags / `extra`; (3) change `mode` to `'enforce'` in both
| Roles count only for accounts of a staff collection, in every predicate and access function | — | `access.staffCollections` |
| `enabled: false` keeps the schema | — | — (no endpoints, `onInit` or admin components; no DROP TABLE in `migrate:create`) |
| No client IP = one shared `unknown-ip` bucket at 20× the limit | `setUnknownIpFactor(0)` (only with a limiter in front) | `setUnknownIpFactor(n)`; `UNKNOWN_IP_FACTOR` |
| IPv6 counted per /64 in every plugin limiter (1.17.2): one /64 = one client, `::ffff:a.b.c.d` = its IPv4; no /48 counter by default. **Verify:** 50 requests with `X-Real-IP: 2001:db8:1:1::<n>` → `429` after the limit | `setIpv6Grouping({ prefix: 128 })` (per address, as before) | `setIpv6Grouping({ prefix, wide: 48, wideFactor })`; `ipRateKey(ip)` for your own limiter (forms.md "IPv6 is counted per network") |
| Turnstile token domain not checked | (default) | `createSubmitAction({ turnstileHostnames })`, `verifyTurnstile({ hostnames })` — leave empty in dev |
| Consent Mode `advanced` | `consentMode: 'basic'` | your own `<Analytics>` props (`SiteProviders analytics={false}`) |
| Locale cookie: consent read under its own stored version | — | `createProxy(config, { policyVersion })` / `createLocaleMiddleware({ policyVersion })` |
+21 -57
View File
@@ -2,7 +2,7 @@
<!-- Generated by scripts/reference-index.mjs from reference/ — do not edit by hand (pnpm reference:index). -->
The reference site is one complete client site on IAPL 1.17.1 ("Example Studio", made up) that uses
The reference site is one complete client site on IAPL 1.17.2 ("Example Studio", made up) that uses
every convention in AGENT.md. It lives in the plugin repo (`reference/`, not in the npm package). Copy the
PATTERN of the file you need; change only the project's content. Files up to
40 lines are below in full; open the rest in the repo at the tag of your plugin version:
@@ -279,7 +279,7 @@ Rules: AGENT.md §5, iapl-nav, iapl-collection.
| `src/collections/Pages.ts` | Pages: slug, blocks layout, AI summary, noindex, slug history, revalidation, system-page delete guard (below) |
| `src/collections/Posts.ts` | the blog collection (archive in System pages) (below) |
| `src/collections/entryFields.ts` | shared fields of archive collections (names the entry card reads) (below) |
| `src/globals/Company.ts` | company data (PL market): footer, contact details, LocalBusiness JSON-LD (below) |
| `src/globals/Company.ts` | company data (PL market): footer, contact details, LocalBusiness JSON-LD |
| `src/globals/Footer.ts` | footer navigation global (below) |
| `src/globals/Header.ts` | header navigation global (below) |
@@ -288,7 +288,7 @@ Rules: AGENT.md §5, iapl-nav, iapl-collection.
```ts
import type { CollectionConfig } from 'payload'
import { buildRevalidateHook } from '@intecion/ipal-kit'
import { adminOrEditor, buildRevalidateHook } from '@intecion/ipal-kit'
import { revalidatePath } from 'next/cache'
import { i18nConfig } from '@/i18n.config'
@@ -301,7 +301,8 @@ const revalidate = buildRevalidateHook({ config: i18nConfig, revalidatePath })
export const CaseStudies: CollectionConfig = {
slug: 'caseStudies',
admin: { defaultColumns: ['title', 'publishedAt', 'updatedAt'], useAsTitle: 'title' },
access: { read: () => true },
// write rules of its own: Payload's default is "any signed-in account" — a visitor login collection would reach it (security.md "Visitor accounts")
access: { create: adminOrEditor, delete: adminOrEditor, read: () => true, update: adminOrEditor },
defaultSort: '-publishedAt',
fields: entryFields,
hooks: { afterChange: [revalidate.afterChange], afterDelete: [revalidate.afterDelete] },
@@ -315,6 +316,7 @@ export const CaseStudies: CollectionConfig = {
import type { CollectionConfig } from 'payload'
import {
adminOrEditor,
buildMediaPlaceholderField,
buildMediaPlaceholderHook,
buildOptimizeUploadField,
@@ -325,7 +327,8 @@ import {
/** media.md "Full collection", 1:1. */
export const Media: CollectionConfig = {
slug: 'media',
access: { read: () => true }, // public files; media are served by the app (/api/media/file/…)
// write rules of its own: Payload's default is "any signed-in account" — a visitor login collection would reach it (security.md "Visitor accounts")
access: { create: adminOrEditor, delete: adminOrEditor, read: () => true, update: adminOrEditor }, // public files; media are served by the app (/api/media/file/…)
upload: { focalPoint: true, mimeTypes: ['image/*', 'application/pdf', 'video/mp4', 'video/webm'] },
hooks: {
beforeOperation: [normalizeFilenameHook, buildOptimizeUploadHook(), buildMediaPlaceholderHook()],
@@ -344,6 +347,7 @@ export const Media: CollectionConfig = {
import type { CollectionConfig } from 'payload'
import {
adminOrEditor,
buildNoindexField,
buildPreventDeleteSystemPage,
buildRevalidateHook,
@@ -362,7 +366,8 @@ const revalidate = buildRevalidateHook({ config: i18nConfig, revalidatePath })
export const Pages: CollectionConfig = {
slug: 'pages',
admin: { defaultColumns: ['title', 'slug', 'updatedAt'], useAsTitle: 'title' },
access: { read: () => true },
// write rules of its own: Payload's default is "any signed-in account" — a visitor login collection would reach it (security.md "Visitor accounts")
access: { create: adminOrEditor, delete: adminOrEditor, read: () => true, update: adminOrEditor },
fields: [
{ name: 'title', type: 'text', localized: true, required: true },
buildSlugField({ from: 'title' }),
@@ -385,7 +390,7 @@ export const Pages: CollectionConfig = {
```ts
import type { CollectionConfig } from 'payload'
import { buildRevalidateHook } from '@intecion/ipal-kit'
import { adminOrEditor, buildRevalidateHook } from '@intecion/ipal-kit'
import { revalidatePath } from 'next/cache'
import { i18nConfig } from '@/i18n.config'
@@ -398,7 +403,8 @@ const revalidate = buildRevalidateHook({ config: i18nConfig, revalidatePath })
export const Posts: CollectionConfig = {
slug: 'posts',
admin: { defaultColumns: ['title', 'publishedAt', 'updatedAt'], useAsTitle: 'title' },
access: { read: () => true },
// write rules of its own: Payload's default is "any signed-in account" — a visitor login collection would reach it (security.md "Visitor accounts")
access: { create: adminOrEditor, delete: adminOrEditor, read: () => true, update: adminOrEditor },
defaultSort: '-publishedAt',
fields: entryFields,
hooks: { afterChange: [revalidate.afterChange], afterDelete: [revalidate.afterDelete] },
@@ -431,63 +437,19 @@ export const entryFields: Field[] = [
]
```
### `src/globals/Company.ts`
```ts
import type { GlobalConfig } from 'payload'
import { buildGlobalRevalidateHook, rowLabel } from '@intecion/ipal-kit'
import { revalidatePath } from 'next/cache'
/** Company data for a PL market site: footer, contact block details, LocalBusiness JSON-LD. */
export const Company: GlobalConfig = {
slug: 'company',
access: { read: () => true },
fields: [
{ name: 'name', type: 'text', required: true },
{ name: 'legalName', type: 'text' },
{ name: 'taxId', type: 'text', label: 'NIP' },
{ name: 'taxIdLabel', type: 'text', admin: { description: 'Shown before the tax ID in the footer.' }, defaultValue: 'NIP', label: 'Tax ID label', localized: true },
{
name: 'address',
type: 'group',
fields: [
{ name: 'street', type: 'text' },
{ name: 'postalCode', type: 'text' },
{ name: 'city', type: 'text' },
{ name: 'country', type: 'text', defaultValue: 'PL' },
],
},
{ name: 'phone', type: 'text' },
{ name: 'email', type: 'email' },
{ name: 'hours', type: 'text', localized: true, admin: { description: 'Shown next to the contact form, e.g. "Mon–Fri 9:00–17:00".' } },
{
name: 'socials',
type: 'array',
admin: { components: rowLabel('label', 'Profile'), initCollapsed: true },
labels: { plural: 'Profiles', singular: 'Profile' },
fields: [
{ name: 'label', type: 'text', required: true },
{ name: 'url', type: 'text', required: true },
],
},
],
hooks: { afterChange: [buildGlobalRevalidateHook({ revalidatePath })] },
}
```
### `src/globals/Footer.ts`
```ts
import type { GlobalConfig } from 'payload'
import { buildGlobalRevalidateHook, buildLinkField, rowLabel } from '@intecion/ipal-kit'
import { adminOrEditor, buildGlobalRevalidateHook, buildLinkField, rowLabel } from '@intecion/ipal-kit'
import { revalidatePath } from 'next/cache'
/** iapl-nav: link columns and a note. Legal links come from System pages (getSystemLinks), not from here. */
export const Footer: GlobalConfig = {
slug: 'footer',
access: { read: () => true },
// write rules of its own: Payload's default is "any signed-in account" — a visitor login collection would reach it (security.md "Visitor accounts")
access: { read: () => true, update: adminOrEditor },
fields: [
{
name: 'columns',
@@ -517,13 +479,14 @@ export const Footer: GlobalConfig = {
```ts
import type { GlobalConfig } from 'payload'
import { buildGlobalRevalidateHook, buildLinkField, buildLinksField, rowLabel } from '@intecion/ipal-kit'
import { adminOrEditor, buildGlobalRevalidateHook, buildLinkField, buildLinksField, rowLabel } from '@intecion/ipal-kit'
import { revalidatePath } from 'next/cache'
/** iapl-nav: menu with one submenu level, a CTA button, the mobile menu label. Logo comes from Site settings. */
export const Header: GlobalConfig = {
slug: 'header',
access: { read: () => true },
// write rules of its own: Payload's default is "any signed-in account" — a visitor login collection would reach it (security.md "Visitor accounts")
access: { read: () => true, update: adminOrEditor },
fields: [
{
name: 'navItems',
@@ -1176,6 +1139,7 @@ Rules: AGENT.md §8a.
| `e2e/own-account.spec.ts` | built-site test (pnpm e2e:built, 1.18.0): the account page asks for the current password before a new e-mail is saved (accounts.confirmOwnChanges); five failed staff sign-ins from one place answer 429 there, not elsewhere (accounts.signInLimit); a staff sign-in from another origin gets 403 (accounts.signInSameOrigin) |
| `e2e/routes.snapshot.json` | every public route of the site (REST, GraphQL, Next route files) with one line saying who may use it and why — the judged list `routes:check` compares with |
| `e2e/routes.ts` | `routes:check`: the site's public routes against e2e/routes.snapshot.json (`pnpm payload run e2e/routes.ts [update]`; from the repository `pnpm routes:check`) (below) |
| `e2e/sign-in-answers.spec.ts` | built-site test (pnpm e2e:built, 1.17.2): a locked staff account gets the wrong-password answer over REST and GraphQL (accounts.lockedAnswer); the plugin's panel actions refuse another origin and take the site's own (adminSameOrigin) |
| `e2e/sign-in-look.spec.ts` | browser test of the sign-in look (whiteLabel.signIn): the panel comes with the form, sits above it on a phone in both themes, is on forgot / reset / logout too, the language links work, the 2FA code screen keeps its boxes (now named) |
| `e2e/smoke.spec.ts` | the smoke tests every release must pass: pages, showcase, forms (also a file sent by e-mail), sitemap, SEO/GEO, headers, consent, 2FA |
| `e2e/smtp-sink.ts` | a local mail sink for the smoke tests: reads what the site really sent (recipients, attachments) |
+2 -1
View File
@@ -78,7 +78,8 @@ names, env, admin, AGENTS.md, skills, seeds and — with `--url` / `--deep` —
- **Drafts and locales over the API** (a collection with `versions: { drafts: true }`): without a session,
`curl -s "$U/api/<slug>?draft=true&limit=100" | grep -c '"_status":"draft"'` → `0`, else ERROR: give it
`access: { read: readPublished(), readVersions: readPublished() }` (access.md). `curl -sI "$U/md/xx"` → `404`
`access: { read: readPublished(), readVersions: readPublishedVersions() }` (access.md). `curl -s -o /dev/null -w '%{http_code}' "$U/api/<slug>/versions?limit=10"`
→ `200` (a `500` = a rule with the document's `_status` path on `readVersions`: ERROR). `curl -sI "$U/md/xx"` → `404`
(no stand-in locale); a 404 page assigned in System pages must be published.
- **Secrets out of queries** (as an admin, with versions on for Site integrations or a collection using
`writeOnlySecret`): `curl -s -H "Authorization: JWT $T" "$U/api/globals/site-integrations/versions?where[version.smtpPassword][exists]=true"`
@@ -46,12 +46,16 @@ const DOORS: Door[] = [
{ closedFor: ALL, method: 'POST', name: 'the crawler\'s call-back without its token', path: '/api/ipal/cookie-crawl/results', body: { jobId: 'x', ok: true } },
{ closedFor: OUTSIDERS, method: 'POST', name: 'a crawl without the schedule\'s token', path: '/api/ipal/cookie-crawl' },
{ closedFor: OUTSIDERS, name: 'form submissions', path: '/api/form-submissions' },
// IAPL 1.17.2: a staff account only; an open door answers 400 (validation) instead of 403
{ body: { form: NO_ID, submissionData: [] }, closedFor: OUTSIDERS, method: 'POST', name: 'a submission past submitForm', path: '/api/form-submissions', closed: status(403) },
{ body: { email: '[email protected]', password: 'Door-Password-1234', roles: ['admin'] }, closedFor: ALL, method: 'POST', name: 'nobody creates a staff account', path: '/api/users', closed: status(403) },
{ body: { email: '[email protected]', password: 'Door-Password-1234' }, closedFor: ALL, method: 'POST', name: 'the first-user route once an account exists', path: '/api/users/first-register', closed: status(403) },
{ body: {}, closedFor: OUTSIDERS, method: 'POST', name: 'Site settings cannot be saved', path: '/api/globals/site-settings', closed: status(403) },
{ closedFor: ALL, name: 'the GraphQL playground (production)', path: '/api/graphql-playground', closed: status(404) },
{ closedFor: ALL, graphql: '{ __schema { queryType { name } } }', closed: ({ body }) => Boolean((body as { errors?: unknown[] })?.errors?.length), name: 'GraphQL introspection (production)' },
{ closedFor: ALL, name: 'Payload\'s job queue (a site without jobs)', path: '/api/payload-jobs/run', closed: status(404) },
// a site without jobs: 404. A site WITH jobs (IAPL 1.17.2): refused (401) for everybody but an admin and
// `Authorization: Bearer <CRON_SECRET>` — drop `closed: status(404)` there
{ closedFor: ALL, name: 'Payload\'s job queue', path: '/api/payload-jobs/run', closed: status(404) },
// the project's own doors: add them here
// { closedFor: OUTSIDERS, body: {}, method: 'PATCH', name: 'pages cannot be changed', path: `/api/pages/${NO_ID}`, closed: status(403) },
]
+4 -2
View File
@@ -46,9 +46,11 @@ Ask only when the brief leaves a business question open (e.g. "do posts have aut
**No URL prefix in code** — the editor assigns the archive page in
Site settings (`<slug>Archive`). The plugin handles routing, sitemap,
generateStaticParams, hreflang.
**With drafts** (`versions: { drafts: true }`): `access: { read: readPublished(), readVersions: readPublished() }`
**With drafts** (`versions: { drafts: true }`): `access: { read: readPublished(), readVersions: readPublishedVersions() }`
(`readPublished` is for `read`, `readPublishedVersions` for `readVersions` — the version list asks for `version._status`)
— Payload's open `read: () => true` answers `?draft=true` with the draft over REST and GraphQL. Check:
`curl -i <site>/api/<slug>/<draft id>?draft=true` without a session → `404`; the same with an editor's token → the draft.
`curl -i <site>/api/<slug>/<draft id>?draft=true` without a session → `404`; the same with an editor's token → the draft;
`curl -s -o /dev/null -w '%{http_code}' <site>/api/<slug>/versions?limit=10` without a session → `200`, never `500`.
3. Entry list = a block (EntriesList) with `getEntries`; the entry page uses
`resolveRoute` (type `entry`); JSON-LD per seo.md (e.g. Article).
4. **An auth collection for visitors** (`auth: true`: customers, members) only when the client requires it
@@ -55,6 +55,14 @@ before analytics or marketing consent — check the project's choice in "Project
`nonce` to `<SiteProviders>`. A visitor who decided must never see the banner on reload; one whose
decision is from an older Policy version must see it at once. A click on a button before hydration
counts (the checks above click as soon as the button is visible).
7. Cookie button (1.17.2, consent.md → "Where the cookie button sits"): after a decision, on a long page, a short
page and a page with a form, desktop and phone width (also 360 px) — the button is in the bottom corner of the
window at the top, in the middle, with the footer in view and at the very end: it must not move at all. At the
very end nothing of the footer is under it and the last footer link can be tapped (the footer has grown a little:
`[data-ipal-cookie-space]` on it). Before a decision and while the banner is open the footer has its own padding
only. Tab reaches the button and Enter reopens the banner. A project scroll handler, a button rendered inside
the footer or hand-made bottom padding for it → remove (AGENT.md §7). Too much or too little room:
`--ipal-cookie-button-space` on the footer; none: `reserve={false}`.
The script needs buttons with `data-ipal="accept"` / `"reject"` — the plugin's
`CookieBanner` has them in every `settings` mode (`inline`, `modal`, `detailed`). A custom banner in the project violates AGENT.md §7.
+2
View File
@@ -34,6 +34,8 @@ through this procedure. Ask only when you are missing something you cannot get y
### Build / TypeScript
| Symptom | Cause | Fix |
|---|---|---|
| a panel button (mail service Connect / Disconnect, Send test e-mail, cookie scan / approve / check site) answers `403` "Not allowed from this origin."; log `[iapl] a panel action from origin "…" was refused` | the request's origin is not one the site knows (1.17.2, `adminSameOrigin`): a reverse proxy that rewrites `Host` and sends no `X-Forwarded-Host`, and no `serverURL` | set `serverURL: process.env.NEXT_PUBLIC_SERVER_URL` in the Payload config, or make the proxy send `X-Forwarded-Host`, or `adminSameOrigin: { origins: ['https://…'] }`; `iapl-doctor` `csrf-empty` |
| a staff account's correct password gets "The email or password provided is incorrect." | the account is locked by Payload after `maxLoginAttempts` wrong passwords (5, for `lockTime`, 10 min); since 1.17.2 a locked staff account gets the wrong-password answer (`accounts.lockedAnswer`) | wait for the lock to end, or an admin unlocks it (the account in the panel, or `POST /api/users/unlock`); `lockUntil` on the account shows it. Payload's own message back: `accounts: { lockedAnswer: 'payload' }` |
| a sign-in answers `429` "Too many failed sign-ins to this address from here" | 5 failed sign-ins for that address from that client IP in 15 minutes (`accounts.signInLimit`, 1.18.0); everybody behind one IP shares it (an office NAT); without `IAPL_IP_HEADER` everybody may share the no-IP bucket | wait the minutes it names, or sign in from elsewhere; pin `IAPL_IP_HEADER`; more room: `signInLimit: { perAddress: 10 }` |
| staff login / "forgot password" answers `403` and the log says `[iapl] a staff sign-in from origin "…" was refused` | the request came from another origin (`accounts.signInSameOrigin`, 1.18.0): a front end on another domain, or a proxy that rewrites `Host` without `serverURL` | set `serverURL`, or `signInSameOrigin: { origins: ['https://…'] }` |
| saving one's own account answers "Enter your current password to change your e-mail address or password." | `accounts.confirmOwnChanges` (1.18.0): own e-mail / username / password changes need the current password | type it in "Current password" on the account page; scripts send `currentPassword`; off: `confirmOwnChanges: false` |
+2 -1
View File
@@ -56,7 +56,8 @@ Existing client sites are not gated on it; run it there as a report only.
`GET /api/ipal/doctor` is added by `iapl` and answers 404 until the site has `IAPL_DOCTOR_TOKEN` (≥ 32 characters).
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 } })`.
`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.
## Env the doctor reads
+3 -1
View File
@@ -35,4 +35,6 @@ Requires the UI primitives from `../iapl-block/resources/section-code.md` (like
## Verification
The **iapl-audit** skill. By hand: a menu item added in the panel is visible right after
saving; the mobile menu works with the keyboard (Tab, Enter, Esc).
saving; the mobile menu works with the keyboard (Tab, Enter, Esc). A menu item that points at a page never
published is not shown (since 1.18.0 the helpers leave draft pages out; `createContentHelpers({ draftRelations:
'keep' })` shows it as before): publish the page and the item appears.
+5 -1
View File
@@ -38,6 +38,7 @@ description: Complete map of everything @intecion/ipal-kit provides — every ia
| `accounts.staffOnlyRead` | on | `read` and `readVersions` on a staff collection without those rules: a fully signed-in account of a staff collection (Payload's default let a visitor account list the staff accounts) | `false` = Payload's default; a `read` rule you wrote wins |
| `accounts.firstUserRoute` | `'panel'` | which auth collections `POST /api/<slug>/first-register` answers for while they are empty: only the one the panel logs in with (the first account of a site → admin). Others get `403`, a second staff collection included, in any spelling of the URL (the plugin's own endpoint sits in front of Payload's); a collection whose own `create` allows an anonymous request keeps its route. With `access.firstUserAdmin: false` and a default role below the panel role, the default `panelRole` is not applied (logged) and an explicit one is refused at start | a list of slugs; `'all'` = Payload's behaviour |
| `accounts.password` | `{ minLength: 12 }` | when a password is SET on a staff collection (create, first-user screen, change, reset by e-mail; panel, API and Local API): at least `minLength` characters, not the account's e-mail address. Existing passwords are never checked — a shorter one keeps logging in | `{ minLength }`; `false` = Payload's rule (3 characters) |
| `accounts.lockedAnswer` | `'wrong'` (1.17.2) | a staff account Payload has locked (too many wrong passwords) gets exactly the wrong-password answer on login (REST, GraphQL, the panel): nobody tells which addresses have an account; the lock itself is unchanged | `'payload'` = Payload's "This user is locked…"; any other value stops the start |
| `accounts.signInLimit` | `{ perAddress: 5, windowMinutes: 15, accountLock: { maxLoginAttempts: 50, lockTime: 3_600_000 } }` (1.18.0) | failed staff sign-ins per client IP + typed address (folded): over the limit `429` for that IP and address only; only failures count; Payload's per-account lock raised where the project set none | `{ perAddress, windowMinutes, accountLock }`; `accountLock: false` = Payload's lock; `false` = as before 1.18 |
| `accounts.signInSameOrigin` | on (1.18.0) | staff login / forgot / reset password: `403` for a request a browser marks as coming from another origin | `{ origins: [...] }`; `false` |
| `accounts.confirmOwnChanges` | on (1.18.0) | own e-mail / username / password change needs `currentPassword` (panel field, REST, GraphQL) | `false` |
@@ -45,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) |
| `adminSameOrigin` | on (1.17.2) | `POST` mail service connect / disconnect, test e-mail, cookie scan / approval / crawl refuse (`403`) a request a browser marks as coming from another origin; own origins: the request's host, `serverURL`, `csrf`, `cors`, `origins` | `{ origins: [...] }` adds origins; `false` = no check; any other value stops the start |
| `adminRoute` | `'/admin'` | `config.routes.admin`; stats link and views, `IntegrationAlerts` | the project moves `app/(payload)/<route>/` itself and adds the route to the proxy matcher (security.md) |
| `twoFactor` | **none = error** | `@clocklimited/payload-2fa` with `forceSetup: true` (TOTP enforced, also checked in the API) | `twoFactor: false` (discouraged); omitting the option throws `[iapl] twoFactor.issuer is required` |
| `twoFactor.issuer` | — (required) | name in the authenticator app | — |
@@ -96,7 +98,7 @@ description: Complete map of everything @intecion/ipal-kit provides — every ia
| `forms.adminGroup` | `'Forms'` | sidebar group | `false` = Payload default; `admin.group` in overrides wins |
| `forms.fields.*` | on: `checkbox`, `checkboxGroup`, `country`, `date`, `email`, `message`, `number`, `radio`, `select`, `state`, `step`, `text`, `textarea`, `time`; off: `payment` | block types in the builder (all with "Show only when") | `<type>: false`; a block object replaces it; `payment: true` **does nothing** (filtered out) — pass a block object |
| `forms.formOverrides` | Form/Forms labels, `emails` readable by logged-in users only | overrides the `forms` collection (`fields: ({ defaultFields }) => …`, `slug`, `admin`, `access`…) | any `CollectionConfig` |
| `forms.formSubmissionOverrides` | create: logged-in, read: editor+, delete: admin | overrides `form-submissions` | `access.create` etc. wins |
| `forms.formSubmissionOverrides` | create: a staff account with its second factor (since 1.17.2; before: any signed-in account), read: editor+, delete: admin | overrides `form-submissions` | `access.create` etc. wins |
| `forms.redirectRelationships` | none | collections a form can redirect to | `['pages']` |
| `forms.emailLayout` | `false` | `beforeEmail` with a layout (logo, colour, footer) + Site settings → **Emails** tab; `{{*:table}}` readable | `true` |
| `forms.beforeEmail` | none | your own e-mail changes (after the layout) | form-builder function |
@@ -105,6 +107,7 @@ description: Complete map of everything @intecion/ipal-kit provides — every ia
| `forms.consentFieldName` | `'consent'` | name of the GDPR consent field `submitForm` requires (read from `config.custom.ipal`) | `createSubmitAction({ consentFieldName })` / `submitForm` argument wins |
| `consentLog` | **on** (since 1.17.0) | `consent-records` collection + `POST /api/ipal/consent` (rate limit 20/min); Postgres / SQLite: a table, migration in the same deploy | `false` / `{ retentionDays }` (default 1095) |
| `consentLog.collectionOverrides` | none | changes `consent-records`: an object merges `access` / `admin` / `hooks` key by key (your keys win), a function `(collection) => collection` takes over (keep the slug) | e.g. `{ access: { read: ({ req }) => req.user?.email === '[email protected]' } }` — narrows who reads records in a project without roles |
| `jobsRunAccess` | on (since 1.17.2), only when the project writes no `jobs.access.run` | Payload's job queue over HTTP (`/api/payload-jobs/run`, `/handle-schedules`): an admin with the second factor (an admin API key counts) or `Authorization: Bearer <CRON_SECRET>` (16+ chars); before: any signed-in account of any auth collection. In-process runs (`jobs.autoRun`, `payload jobs:run`) unaffected | `false` = Payload's default; `{ secretVar }` = another variable; your own `jobs.access.run` wins. Check: `curl -H "Authorization: Bearer $CRON_SECRET" $URL/api/payload-jobs/run` → 200, without it 401 (security.md "Payload's job queue") |
| `doctor` | on (404 until `IAPL_DOCTOR_TOKEN` is set) | `GET /api/ipal/doctor` — read-only counts for `iapl-doctor --url` (users without TOTP, cookies waiting for approval, versions); Bearer token ≥ 32 characters, rate-limited, never names or values | `false` = no endpoint; `{ tokenVar, access }` (doctor.md) |
| `cookieScanner` | off | `cookie-review` collection, "Scan cookies" box above its list (`CookieScanButton`), `GET`/`POST /api/ipal/cookie-scan`, and (unless `approval: false`) the *Approve cookies* view `/admin/cookie-approval` (`CookieApprovalView`) + `GET`/`POST /api/ipal/cookie-approval` + the dashboard reminder; a scan lists the cookies of the integrations switched on + names looked up in the bundled Open Cookie Database; one **Approve and add** puts the ticked cookies into Cookies → Cookie list (so `<CookieTable>` and the detailed window); never deletes, never overwrites edited text, never duplicates, nothing reaches the banner before approval | `true` / object; after switching on: `pnpm generate:importmap` + `migrate:create`. Check: *Privacy → Cookie review* → **Scan cookies** → "Waiting for approval: N" → **Review and approve** → **Approve and add** → the cookies are in Cookies → Cookie list (cookie-scanner.md) |
| `cookieScanner.adminLayout` | `'combined'` | one *Cookies* entry: *Review and approve* and (with `crawl`) *Site check* tabs on the `cookie-settings` global (`ui` fields, `CookieReviewTab` / `CookieSiteCheckTab`); `cookie-review` and `cookie-crawl` get `admin.group: false` (out of the nav, pages and API kept) | `'separate'`; no migration, `generate:importmap` |
@@ -280,6 +283,7 @@ The plugin's own variables are `IAPL_<NAME>`; a deploy that sets the spelling fr
| `IAPL_IP_HEADER` | `ipHeader: true` + production | rate limit trusts any IP header (spoofing) + warning in prod | env: `cf-connecting-ip` (Cloudflare) / `x-forwarded-for` (Traefik/nginx) |
| `IAPL_COOKIE_SCAN_URL`, `IAPL_COOKIE_SCAN_TOKEN` | `cookieScanner.crawl` (`iaplEnvRules({ cookieCrawl: true })` requires both in production; token ≥ 16 chars) | **Check site** disabled, the box names the missing variable | env; the token also goes into the scanner service's `IAPL_CRAWLER_SITES` as `host=token` |
| `IAPL_DOCTOR_TOKEN` | no; ≥ 32 characters | `GET /api/ipal/doctor` answers 404; with it the endpoint answers a Bearer token, and `iapl-doctor --url` with the same variable reads the deep counts | env (Coolify) and the doctor's shell; also read by the doctor: `CI`, `NO_COLOR`, `PAYLOAD_CONFIG_PATH` (`--deep`), `IAPL_DOCTOR_IMPORT_MAP` (internal) — doctor.md |
| `CRON_SECRET` | no; ≥ 16 characters (name: `jobsRunAccess.secretVar`) | Payload's job queue runs over HTTP only for an admin; the start log says so when the queue is on | env (Coolify); the cron sends `Authorization: Bearer <CRON_SECRET>` to `/api/payload-jobs/run` |
| `IAPL_NOINDEX` | no; `1`/`true`/`yes` **staging/preview only** | — (when set: robots Disallow, meta noindex, `X-Robots-Tag`, IndexNow sends nothing) | staging env |
| `NEXT_PHASE` | set by Next | only tells `next build` from runtime: during the build an unreachable database gives an empty sitemap; at runtime the sitemap throws (route → 503) | do not set by hand |
| `NEXT_RUNTIME` | set by Next | `instrumentation.ts` checks for `nodejs`; missing (scripts, seed) → `buildRevalidateHook` does not revalidate | do not set by hand |
@@ -85,10 +85,12 @@ Admin panel components from `@intecion/ipal-kit/admin` — the project does NOT
| `buildRolesField(defaultRole?, { firstUserAdmin? })` | `@intecion/ipal-kit` | The `roles` select field the plugin injects (only admins set roles; `firstUserAdmin` default `true` = the account made on "Create first user" gets `admin`). The plugin wires it itself — use it only for an auth collection the plugin does not manage. |
| `injectRoles(config, accessOption)` | `@intecion/ipal-kit` | Adds `roles` to `accessOption.authCollection` in a config. The plugin calls it itself with `access` — do not call. |
| `requireOwnOrigin(endpoint, origins?)`, `guardAdminEndpoints(config, projectEndpoints, option)`, `ADMIN_POST_ENDPOINTS`, type `AdminSameOriginOption` | `@intecion/ipal-kit` | `adminSameOrigin` (1.17.2): wraps an endpoint so a request a browser marks as coming from another origin gets `403` (logged once per origin); applies it to the plugin's panel actions it added; the list of `[method, path]` covered. `reportRefusedOrigin(req, origins?, { what, option, docs }?)` names your option in the log line. |
| `lockedLooksWrong`, `withLockedAnswer(config)`, `graphqlLoginName(collection)` | `@intecion/ipal-kit` | `accounts.lockedAnswer` (1.17.2): the config-level `afterError` hook that answers Payload's `LockedAuth` on a staff collection's login (REST, GraphQL) exactly like `AuthenticationError`; adding it to a config (idempotent); the GraphQL login mutation's name of a collection. |
| `applySignInRules(collection, accounts?)`, `buildSignInBeforeOperation(slug, rules)`, `releaseSignInPlace`, `settleFailedSignIn`, `buildCurrentPasswordField()`, `resolveSignInRules(accounts?)`, `foldSignInName(value)`, `passwordMatches({ hash, salt }, password)`, `CURRENT_PASSWORD_FIELD`, `SIGN_IN_RULES_MARK` (the mark on the `beforeOperation` hook); types `SignInRulesOptions`, `SignInLimitOptions`, `SignInSameOriginOptions` | `@intecion/ipal-kit` | 1.18.0, `accounts.signInLimit` / `signInSameOrigin` / `confirmOwnChanges`: the three rules on one staff collection (hooks, field, Payload lock defaults); the `beforeOperation` hook; the `afterLogin` hook that gives a sign-in's place back; the config `afterError` hook that ends a failed one; the virtual "Current password" field; the options with defaults; the address folding (NFKC, lower case, trim); Payload's stored-hash check (unknown formats refused). |
| `releaseRateLimit({ key, scope, max?, windowMs?, cost? })` | `@intecion/ipal-kit` | Gives back a place `consumeRateLimit` took (memory: never below 0; a store: `hit(id, -cost)`) — for a limiter that counts failures only. |
**Types:** `AccountsOptions` (`accounts`: `panelRole`, `adminOnlyCreate`, `adminOnlyWrite`, `staffOnlyRead`, `firstUserRoute`, `password`, `signInLimit`, `signInSameOrigin`, `confirmOwnChanges`), `StaffAccountAccessOptions` (`{ create?, write?, read?, pluginRoles? }`), `StaffRuleMark` (`{ slug, self }`), `AccountsMarker` (`{ slug, staff, own? }`, in `custom.ipalAccounts`; `own`: the operations that had a rule of the project's at config time, kept when the collection becomes staff later), `LateAdoption` (`{ slug, applied, kept, known, password, firstUser }`; `known`: in the config when iapl ran and staff only afterwards, `kept`: its operations whose own rule was left as written), `StaffAccountRules` (what the plugin put on a staff collection, in `custom.ipalAccountRules`: `{ applied, ownRoles }`), `WriteOnlySecretOptions` (`{ boundTo?, appliesWhen? }`), `PasswordRuleOptions` (`{ minLength? }`), `FirstUserRouteOption` (`'panel' \| 'all' \| string[]`), `TurnstileOnConfigError` / `TurnstileOnConfigErrorOption` / `TurnstileFormKind` (`@intecion/ipal-kit/server`), `VerifyLimitOptions` (`twoFactor.verifyLimit`: `{ max?, windowMinutes?, store? }`), `RequireSetupOptions` (`twoFactor.requireSetup`), `TwoFactorResetOptions`, `TwoFactorSetupState`, `SafeBackRule` / `SafeBackContext` (`twoFactor.safeBack` as a function: `(back, { adminRoute, origin? }) => string`), `TotpViewComponent` (a view component as registered: a path or `{ path, exportName?, clientProps?, serverProps? }`), `SafeTotpViewProps` (`@intecion/ipal-kit/admin`), `Role` (`'user' \| 'editor' \| 'admin'`), `AccessOption` (the plugin's `access` option: `authCollection`, `defaultRole`, `authAccess`, `firstUserAdmin`, `staffCollections`).
**Types:** `AccountsOptions` (`accounts`: `panelRole`, `adminOnlyCreate`, `adminOnlyWrite`, `staffOnlyRead`, `firstUserRoute`, `password`, `lockedAnswer`, `signInLimit`, `signInSameOrigin`, `confirmOwnChanges`), `LockedAnswerOption`, `StaffAccountAccessOptions` (`{ create?, write?, read?, pluginRoles? }`), `StaffRuleMark` (`{ slug, self }`), `AccountsMarker` (`{ slug, staff, own? }`, in `custom.ipalAccounts`; `own`: the operations that had a rule of the project's at config time, kept when the collection becomes staff later), `LateAdoption` (`{ slug, applied, kept, known, password, firstUser }`; `known`: in the config when iapl ran and staff only afterwards, `kept`: its operations whose own rule was left as written), `StaffAccountRules` (what the plugin put on a staff collection, in `custom.ipalAccountRules`: `{ applied, ownRoles }`), `WriteOnlySecretOptions` (`{ boundTo?, appliesWhen? }`), `PasswordRuleOptions` (`{ minLength? }`), `FirstUserRouteOption` (`'panel' \| 'all' \| string[]`), `TurnstileOnConfigError` / `TurnstileOnConfigErrorOption` / `TurnstileFormKind` (`@intecion/ipal-kit/server`), `VerifyLimitOptions` (`twoFactor.verifyLimit`: `{ max?, windowMinutes?, store? }`), `RequireSetupOptions` (`twoFactor.requireSetup`), `TwoFactorResetOptions`, `TwoFactorSetupState`, `SafeBackRule` / `SafeBackContext` (`twoFactor.safeBack` as a function: `(back, { adminRoute, origin? }) => string`), `TotpViewComponent` (a view component as registered: a path or `{ path, exportName?, clientProps?, serverProps? }`), `SafeTotpViewProps` (`@intecion/ipal-kit/admin`), `Role` (`'user' \| 'editor' \| 'admin'`), `AccessOption` (the plugin's `access` option: `authCollection`, `defaultRole`, `authAccess`, `firstUserAdmin`, `staffCollections`).
## Accessibility — widget (`accessibility`) — details: `node_modules/@intecion/ipal-kit/docs/accessibility.md`
@@ -168,8 +170,10 @@ Fifteen ready blocks and ten page templates. **Use a library block (or a variant
|---|---|---|
| `ConsentProvider` | `@intecion/ipal-kit/client` | Consent provider: `{ texts, cookieMap?, logEndpoint?, nonce?, cookieValue?, gpc?, maxAgeDays? }` (`gpc`: Global Privacy Control `'honour'` default / `'ask'` / `false`; `maxAgeDays`: re-ask period, default 180; withdrawal also removes the panel's listed storage keys and tells Meta / TikTok / Clarity) (`nonce`: CSP nonce for the banner's first-paint script; `cookieValue`: optional server-read consent cookie → exact HTML, dynamic pages) — consent state, cookie, Consent Mode, deleting cookies after consent is withdrawn, optional POST of the decision to the log (`'/api/ipal/consent'`). Wrap the layout once; required by the banner, `Analytics`, `ConsentScript`. |
| `CookieBanner` | `@intecion/ipal-kit/client` | Consent banner + category settings: `settings: 'inline' \| 'modal' \| 'detailed'`, `controls`, `equalChoice` (recommended `true`), `order`, `settingsActions`, `icon`, `classNames`, `firstPaint` (default `true`: in the server HTML, decided before the first paint by an inline script; pages stay static), `nonce`; colours from `--ipal-*` CSS vars. Do not write your own banner. |
| `CookieButton` | `@intecion/ipal-kit/client` | Floating button that reopens the cookie settings (withdrawing consent); hidden while the banner is visible. Props `className`, `side` (`'left' \| 'right'`), `avoid` (selector it lifts above, default `COOKIE_BUTTON_AVOID` = footer; `false`). Tokens `--ipal-cookie-button-offset`, `--ipal-cookie-button-inset`. Type `CookieButtonProps`. |
| `COOKIE_BUTTON_AVOID`, `bottomOverlap(tops, viewportHeight)` | `@intecion/ipal-kit/client` | Default footer selector; pixels the footer covers at the bottom of the screen (how far the button moves up) |
| `CookieButton` | `@intecion/ipal-kit/client` | Floating button that reopens the cookie settings (withdrawing consent); hidden while the banner is visible. Fixed in the bottom corner of the window on every page and never moves (1.17.2: it no longer climbs above the footer). While it is shown the footer gets just enough bottom padding for its last row to end above the button (measured; the footer's own padding counts; nothing where the corner is empty; made before the first paint for a returning visitor). Props `className`, `side` (`'left' \| 'right'`), `reserve` (selector of the block that gets the room, default `COOKIE_BUTTON_RESERVE` = footer; `false` = none), `avoid` (placement before 1.17.2: selector it lifts above — `COOKIE_BUTTON_AVOID`). Amount by hand: `--ipal-cookie-button-space` on the footer (`0` = none). Tokens `--ipal-cookie-button-offset`, `--ipal-cookie-button-inset`. Type `CookieButtonProps`. |
| `COOKIE_BUTTON_AVOID`, `bottomOverlap(tops, viewportHeight)` | `@intecion/ipal-kit/client` | Footer selector for the placement before 1.17.2 (`<CookieButton avoid={COOKIE_BUTTON_AVOID} />`); pixels the footer covers at the bottom of the screen (how far the button moves up then) |
| `COOKIE_BUTTON_RESERVE`, `COOKIE_BUTTON_SPACE_ATTRIBUTE`, `reserveCookieButtonSpace(options)` | `@intecion/ipal-kit/client` | Default selector of the block that gets room for the cookie button (the footer); the attribute that marks it while the room is there; the function that measures and applies (or, with `release: true`, removes) it — options type `CookieButtonSpaceOptions` (`selector`, `side`, `button?`, `release?`, `sheet?`). For a button of your own |
| `consentDecidedScript({ version?, gpc?, cookieName? })` | `@intecion/ipal-kit` | JavaScript statements for an inline script: leave `true` in `d` when the browser holds a current consent decision (as `readConsentRecord` decides). The shared start of the plugin's pre-paint scripts |
| `TOTP_TEXTS`, `TOTP_VIEW_TITLE` | `@intecion/ipal-kit` | en/pl texts of the 2FA screens (`totpPlugin:*`, merged by `twoFactor`) and their tab title |
| `ConsentScript` | `@intecion/ipal-kit/client` | Loads an external script (`src` or `code`) only after consent for `category` — for vendors without Consent Mode (chat, Plausible etc.). Inside `ConsentProvider`. |
| `CookieTable` | `@intecion/ipal-kit/rsc` | Server Component: cookie table for the cookie policy page — `{ rows, labels?, locale?, categories?, caption?, classNames?, storageColumn?, storageTypes? }`; `rows` from `getCookieTable()`; a **Type** column when a row is local / session storage (`storageColumn: 'auto' \| boolean`). |
@@ -747,6 +751,7 @@ Most routes and metadata are already ready in `createContentHelpers` (`generateP
| `setRateLimitStore(store \| null)` | `@intecion/ipal-kit` | Shared store (e.g. Redis) for all plugin limiters (forms, consents, MCP…); `null` = process memory. Call once at startup when several instances run. |
| `setUnknownIpFactor(n)` | `@intecion/ipal-kit` | Requests with no client IP share one `unknown-ip` bucket with `n` × the limit (every plugin limiter). Call once at startup; `0` = unlimited (only with a limiter in front, e.g. Cloudflare). |
| `UNKNOWN_IP_FACTOR` | `@intecion/ipal-kit` | `20` — the default factor of the no-IP bucket. |
| `setIpv6Grouping({ prefix?, wide?, wideFactor? })`, `ipRateKey(ip)`, type `Ipv6Grouping` | `@intecion/ipal-kit` | 1.17.2: how every plugin limiter counts IPv6 — default one client per /64 (`prefix: 64`), no wide counter; `wide: 48` adds a counter per /48 at `wideFactor` (10) × the limit; `prefix: 128` = per address. Out-of-range values throw. `ipRateKey`: an IPv4 as it is, `::ffff:a.b.c.d` as the IPv4, an IPv6 as its network (`2001:db8:1:2:0:0:0:0/64`), anything else unchanged. |
**Types:** `ClientIpOptions` — `clientIp` options; `RateLimitStore` — store contract (`hit(id, cost, windowMs)` → `{ count, resetAt }`).
@@ -875,6 +880,9 @@ Bin: `iapl-doctor` (`pnpm exec iapl-doctor [dir] [--json] [--md] [--strict] [--f
| `runDeepProbe(ctx)` | `@intecion/ipal-kit/doctor` | `pnpm exec payload run …/dist/modules/doctor/probe.js` in the project → `DoctorStatus`. |
| `collectDoctorStatus(payload)` | `@intecion/ipal-kit/doctor` | Read-only counts: `usersWithout2fa`, `pendingCookies`, `plugin`, `node`. |
| `buildDoctorEndpoint({ tokenVar, access })` | `@intecion/ipal-kit/doctor` | `GET /ipal/doctor` (`/api/ipal/doctor`): 404 until the token variable (default `IAPL_DOCTOR_TOKEN`, ≥ 32 chars) is set, Bearer token or `access`, rate-limited. Added by `iapl` unless `doctor: false`. |
| `jobsRunAccess({ secretVar? })` | `@intecion/ipal-kit` | The rule iapl puts on `jobs.access.run` when the project writes none: `cronSecretMatches(req, process.env[secretVar])` or an admin with the second factor. Reuse it in your own rule: `run: (a) => jobsRunAccess()(a) \|\| myCheck(a)`. Type `JobsRunAccessOptions`. |
| `withJobsRunAccess(config, options \| false)` / `jobsRunNotice(config)` | `@intecion/ipal-kit` | The config with that rule (only when `jobs.access.run` is missing; marks `custom.iapl.jobsRunDefault`); the start-up line when the queue is on and the secret is missing (null otherwise). |
| `cronSecretMatches(req, secret)`, `CRON_SECRET_ENV`, `CRON_SECRET_MIN_LENGTH` | `@intecion/ipal-kit` | `Authorization: Bearer <secret>` compared in constant time; an unset or shorter-than-16 secret never matches. Default variable `CRON_SECRET`. |
| `runRouteCheck({ config, appDir?, snapshot?, update?, graphql?, cwd?, log? })` | `@intecion/ipal-kit/doctor` | `routes:check`: every public route (REST, GraphQL, Next route files) against the judged snapshot (default `e2e/routes.snapshot.json`); returns 1 on a route nobody judged or an entry without a reason; `update` writes new routes with an empty reason. Template: `iapl-audit/resources/routes.template.ts` (security.md "Routes nobody has judged"). Type `RunRouteCheckOptions`. |
| `listPublicRoutes(config, { graphqlSchema?, routeFiles? })` | `@intecion/ipal-kit` | Stable ids of every door a built config opens: `GET /api/users/me`, `graphql mutation loginUser`, `next GET /sitemap.xml`. From the config only (same on every database). Types `RouteInventoryOptions`, `GraphqlSchemaLike` (`getQueryType` / `getMutationType`). |
| `listNextRouteFiles(files, read)` | `@intecion/ipal-kit` | Next route handlers of an app directory (`route.ts` with the methods it exports, `robots.ts`, `sitemap.ts`, `manifest.ts`; route groups left out). |
+27 -1
View File
@@ -39,6 +39,32 @@ no migration, no import-map change; read before deploying:**
**Check:** five wrong passwords for an editor from one address → `429` there, `200` from another; the account page
shows "Current password"; `curl -X POST <site>/api/users/login -H 'Origin: https://other.example' …` → `403`.
**→ 1.17.2, security (CHANGELOG 1.17.2; PROGRAMISTA §6, items 84–87) — nothing required, check:** `readVersions:
readPublished()` now works (a wrapper of your own around it: use `readPublishedVersions()` inside); behind a proxy
that rewrites `Host` without `X-Forwarded-Host`, set `serverURL` or the panel's mail / cookie buttons answer 403
(`iapl-doctor` warns); a locked editor sees "incorrect" until the lock ends (`accounts.lockedAnswer: 'payload'` for
Payload's text); saving Cookies with a lower consent version is refused (`cookieSettings.allowLowerPolicyVersion`).
**Check:** `curl -s <site>/api/pages/versions` as a visitor → 200 (published only), not 500.
**→ 1.17.2:** (1) Payload jobs: if the project has tasks or workflows and a cron calls `/api/payload-jobs/run` (or
`/handle-schedules`) without its own `jobs.access.run`, set `CRON_SECRET` (16+ characters) in the app's environment
and send `Authorization: Bearer <CRON_SECRET>` from the cron; in-process runs (`jobs.autoRun`, `payload jobs:run`)
and an admin's API key need nothing (security.md "Payload's job queue"). Verify: the run route answers 401 without
the header, 200 with it. (2) A front end that posted to `/api/form-submissions` as a customer account (not through
`submitForm`): move it to `submitForm` / `createSubmitAction`, or set `forms.formSubmissionOverrides.access.create`.
(3) A site with a visitor login collection: `iapl-doctor --url …` lists `visitor-writes`; give each listed collection
and global its own write rule (`adminOrEditor`). (4) If the project has `tests/routes.ts`: `update`, judge, commit.
**→ 1.17.2, cookie button (CHANGELOG 1.17.2; PROGRAMISTA §6, item 83; consent.md "Where the cookie button sits") — nothing is required:**
visitors now see the "cookie settings" button in the bottom corner of the window on every page; it never moves and
no longer rides up above the footer. While it is shown the footer is a little taller (about 40 px on the reference
site), so its last row ends above the button. Check the end of a page on a phone and on desktop: nothing under the
button, the last footer link can be tapped. Bottom padding a project added by hand for the button: remove it (the
plugin counts existing padding, so it is not doubled, but it is no longer needed). Amount by hand:
`--ipal-cookie-button-space` on the footer (`0` = none); no room: `reserve={false}`. The placement before:
`cookieButton={<CookieButton avoid={COOKIE_BUTTON_AVOID} />}` on `SiteProviders`. A project e2e that expects the button
above the footer, or an exact footer height after a decision: update it.
**→ 1.17.1:** (1) `src/proxy.ts`: replace the matcher literal with
`['/((?!(?:api|admin|_next)(?:/|$)|.*\\..*).*)']` (i18n.md "Next matcher"; `iapl-doctor` rule `proxy-matcher`).
The old one skipped every page whose first segment only starts with `api`, `admin` or `_next` (`/administracja`):
@@ -266,7 +292,7 @@ and the browser tab shows the same separator.
cookie banner only through `--ipal-*-dark`: check the banner in the dark theme.
4. Optional: the block library, block by block (block-library.md); after turning blocks on: `pnpm generate:types`,
`pnpm payload generate:importmap`, Postgres/SQLite `migrate:create`.
5. **CookieButton** lifts above the footer — check a site with its own fixed footer bar; `avoid={false}` keeps it fixed.
5. **CookieButton** lifts above the footer — check a site with its own fixed footer bar; `avoid={false}` keeps it fixed. (Since 1.17.2 it stays in the bottom corner by default; the lift is `avoid={COOKIE_BUTTON_AVOID}`.)
6. `pnpm exec iapl-skills` (new **iapl-doctor**; updated iapl-reference, iapl-setup, iapl-site, iapl-audit).
7. Run `pnpm exec iapl-doctor` (and `--url https://<site>`), fix or silence each finding with a reason in
`iapl-doctor.json`. `IAPL_DOCTOR_TOKEN` (≥ 32 characters) only if the deep check runs against production.
+53 -7
View File
@@ -113,12 +113,51 @@ takes `locale` and optional `labels`; defaults: `COOKIE_TABLE_LABELS` (`@intecio
| `controls` | `'checkbox'` | `'checkbox' \| 'switch'` |
| `settingsActions` | `['back', 'save']` | buttons under the categories (`'accept' \| 'back' \| 'reject' \| 'save'`) |
`CookieButton` props: `className` (replaces the default classes; position is then yours too),
`side` (`'left'` default or `'right'`), `avoid` (CSS selector, default `COOKIE_BUTTON_AVOID` =
`'footer, [role="contentinfo"]'`; `false` = never move). While the footer is on screen the button
moves up by its visible part (`bottomOverlap`), so it never covers footer links. Position tokens:
`--ipal-cookie-button-offset` (from the bottom, default `1rem`), `--ipal-cookie-button-inset` (from the
side, default `1rem`); z-index `--ipal-z-header`. Type `CookieButtonProps`.
### Where the cookie button sits (1.17.2)
`CookieButton` is fixed in the **bottom corner of the window** — on every page, long or short, at every scroll
position, on desktop and phone — and it **never moves**. It is a child of `<body>` (never inside the footer) and it
no longer climbs above the footer when the footer scrolls into view (1.12.x–1.17.1 did that: on a phone with a tall
footer the button ended at the top of the screen, on a short page in the middle of it).
**Room under the footer.** A fixed button would, at the very end of a page, lie on whatever is in that corner — the
first link of the footer's last row — and a visitor could not scroll it free. So while the button is shown, the
plugin gives the page's last block (the footer) **bottom padding: just enough for its last row to end above the
button** (`reserveCookieButtonSpace`). The footer's background continues through it.
| | |
|---|---|
| How much | measured, not fixed: the button's height + its distance from the bottom + the device's safe area + 8 px, **minus what is already free** under the lowest text or control in the button's column. The footer's own bottom padding counts first — never double space. On the reference site: 42–43 px on phones and desktop |
| Where nothing is in the corner | nothing is added (a centred footer on a wide screen, the button on the other side) — so there is no breakpoint to configure |
| When | only while the button is shown: not before a decision, not while the banner is open (the footer is as the project made it), gone when the button is turned off (`cookieButton={false}`) |
| No layout shift | on a static page the HTML carries a small inline script next to the button's place: for a visitor who already decided it makes the room **before the first paint** (in a style sheet, so React hydrates the server's markup untouched), and the button's own measurement after hydration gives the same size. After a click in the banner the room appears with the button. Later changes (fonts, a form that grows, a resize) are followed |
| Which block | the last element matching `reserve` (default `COOKIE_BUTTON_RESERVE` = `'footer, [role="contentinfo"]'`); none on the page → `<body>` |
| Prop | Default | What it does |
|---|---|---|
| `side` | `'left'` | corner: `'left'` or `'right'` |
| `reserve` | `COOKIE_BUTTON_RESERVE` | CSS selector of the block that gets the room (the last match); `false` = no room — the button then covers what is in the corner at the end of the page |
| `avoid` | — | placement before 1.17.2: a CSS selector the button lifts above while it is on screen — `avoid={COOKIE_BUTTON_AVOID}` (`'footer, [role="contentinfo"]'`) is exactly the old default (`bottomOverlap`); no room is reserved then. `false` = the default (kept for sites that set it) |
| `className` | — | replaces the default classes; position is then yours too (room is measured from the real button once it is on the page, and only while it is `position: fixed`) |
**Set the amount yourself:** `--ipal-cookie-button-space` on the footer — any length, added to the footer's own
padding instead of the measured amount; `0` = none, also per breakpoint:
```css
footer { --ipal-cookie-button-space: 4rem; }
@media (min-width: 64rem) { footer { --ipal-cookie-button-space: 0; } } /* nothing on desktop */
```
Position tokens: `--ipal-cookie-button-offset` (from the bottom, default `1rem`), `--ipal-cookie-button-inset`
(from the side, default `1rem`); the device's safe-area insets (bottom and the chosen side) are added. z-index
`--ipal-z-header` (default 40): above the page, below the banner, the settings window and the lightbox (50).
Hidden while the banner is showing. Keyboard: a `<button>` in the tab order with an `aria-label` from the panel.
Type `CookieButtonProps`.
Nonce CSP: the inline script takes the nonce given to `SiteProviders` / `ConsentProvider`; refused, the room is made
when the button appears (a footer pinned to the bottom of a page shorter than the window then moves once).
Building blocks: `reserveCookieButtonSpace({ selector, side, button?, release? })`, `COOKIE_BUTTON_SPACE_ATTRIBUTE`
(`/client`), `consentDecidedScript` (root).
## Compliance defaults (1.17.0)
@@ -449,7 +488,7 @@ New fields in the global = a migration in projects on Postgres/SQLite (`payload
The elements also have stable `data-ipal` handles for CSS and e2e tests (used by
`iapl-consent-check`): `banner` (while it waits for the first-paint script it carries `hidden`; a button clicked before hydration:
`data-ipal-pending`; live: `data-ipal-ready`), `banner-script`, `cookie-button` and the buttons `settings`, `reject`,
`data-ipal-pending`; live: `data-ipal-ready`), `banner-script`, `cookie-button` (`cookie-button-script`: its inline script in the server HTML; `data-ipal-cookie-space` on the footer while it holds the button's room) and the buttons `settings`, `reject`,
`accept`, `back`, `save`; in modal mode also `consent-overlay`, `consent-dialog`, `close`; in detailed mode
additionally `category-<category>` (card) and `cookies` (expandable list).
@@ -542,6 +581,13 @@ to add the hook to a config. Nothing to migrate.
- **New consent after a policy change:** Cookies → *Consent version* (sidebar). Raise it by 1
after adding a tool or changing the policy — every visitor will see the banner again.
`getConsentTexts` passes the version to `<ConsentProvider texts>` automatically.
- **The consent version only goes up (1.17.2).** A stored consent counts only under the version it was given for,
so a lower number would make consent given under an older policy valid again. Saving Cookies with a lower
*Consent version* through the panel, REST or GraphQL is refused: "The consent version cannot go down: it is 3
now…" (Polish in a Polish panel). The same number, a higher one, or a save without it pass. A script an admin runs
with the Local API and `overrideAccess` may still lower it. Turn the rule off: `iapl({ cookieSettings:
{ allowLowerPolicyVersion: true } })`. Building blocks: `policyVersionNeverDown` (the field hook),
`buildCookieSettingsFields({ allowLowerPolicyVersion })`, `buildCookieSettings(options)`.
- **Withdrawing consent deletes the tools' cookies** (`_ga`, `_ga_*`, `_gid`, `_fbp`, `_gcl_*`, Clarity,
LinkedIn, TikTok, Hotjar…) — also on the parent domain (`.client.com`), where GA stores them.
The project's own cookies: `<ConsentProvider cookieMap={{ marketing: ['_my*'] }}>` (added to the
+27
View File
@@ -108,6 +108,33 @@ ambiguous (the same entry under many URLs), so `/a/b/c` → null.
**Slug collision:** two collections with an archive with the same slug → the first one
in the `collections` list wins. A configuration error; the router does not warn.
## Drafts as related documents (1.18.0)
A page is read at depth 2, Site settings and archive entries at depth 1, and Payload fills in every related document
whatever its status. Before 1.18.0 a block, a menu or a System pages link that pointed at a page never published
brought that page's title, slug and text into what the helpers answered (and llms-full printed it). Now the helpers
leave such a related document out, as if it did not exist:
| Shape | Becomes |
|---|---|
| a single relationship | `null` — a link resolves to nothing, a menu item drops out |
| a list of relationships | the draft is removed from it |
| a polymorphic one `{ relationTo, value }` | `value: null` |
A related document counts as a draft when it carries `_status` other than `'published'` (a never-published or
unpublished document of a collection with drafts). Documents without `_status` (collections without drafts, media)
are never touched; the document itself is judged as before (only published pages are served). Applies to
`createContentHelpers` (`getSettings`, `resolveRoute`, `getEntries`, `getNotFoundPage`, the page route, Markdown,
MCP, llms-full), `resolveRoute`, `getArchiveEntries`, `resolveNotFoundPage`, `collectSiteIndex` and
`buildLlmsTxt` / `createLlmsTxtRoute`. A preview (`draft: true`) keeps them.
- **What an existing site sees:** a menu item, a card or a link whose page was never published disappears for
visitors instead of showing a title that leads to a 404. Publish the page, or point the link elsewhere.
- **Keep the old behaviour:** `createContentHelpers({ draftRelations: 'keep' })`, or `draftRelations: 'keep'` on
`resolveRoute` / `getArchiveEntries` / `resolveNotFoundPage` / `collectSiteIndex` / `buildLlmsTxt`.
- **Building blocks:** `withoutDraftRelations(value)` (returns the same object when nothing changes, copies only
the changed path), `applyDraftRelations(value, { draft, draftRelations })`, type `DraftRelations`.
## Front-end helpers — createContentHelpers
Instead of writing cached wrappers in every project:
+1 -1
View File
@@ -259,7 +259,7 @@ All from `@intecion/ipal-kit` (server-safe), for your own admin view, a CLI or a
| `cookieScanContext(payload, plugin, req?)` | the `CookieScanContext` a scan uses |
| `parseCookieNames(input)` | the panel's text box → clean names |
| `mergeCookieReview(current, previous, next)`, `suggestionFor(finding, locales)` | the "never overwrite an edit" rule, pure |
| `addToCookieList({ payload, entry, req? })` | what accepting does: add the row or fill its empty text → `'added' \| 'filled' \| 'unchanged'`; a row with the same name or a covering pattern counts as the same cookie (`sameCookie(a, b)`) |
| `addToCookieList({ payload, entry, req? })` | what accepting does: add the row or fill its empty text → `'added' \| 'filled' \| 'unchanged'`; a row with the same name or a covering pattern counts as the same cookie (`sameCookie(a, b)`). The list is written whole: since 1.18.0 it is read again right before writing and, when an editor's save changed it since, the change is worked out again on what is there now (up to 5 times), so a row saved in between is not lost. A Cookies form left open in the panel and saved later still writes the whole list it shows (Payload's document lock warns the second editor) |
| `loadCookieApproval({ payload, locale, req? })` | the approval list → `CookieApprovalList` (`pending`, `gone`) |
| `approveCookies({ payload, ids?, unknownCategory?, addToList?, req? })` | what **Approve and add** does → `CookieApprovalResult` |
| `countPendingCookies(payload)`, `PENDING_WHERE` | how many wait / the query for them (drafts, and accepted cookies marked changed) |
+5
View File
@@ -690,6 +690,11 @@ Do one item at a time, build, check. Order by importance:
| 80 | **1.17.1 — the sign-in look** — after the update the login and 2FA screens show a dark panel with the logo or the site's name; an editor cannot change the logo or name; forgot / reset password look as before | Nothing required. `whiteLabel: { signIn: false }` (old screens), `{ brandAccess: 'editor' }`, `{ signIn: { logoPlate: true } }` (a dark logo), `{ signIn: { svgLogo: false } }`; the other screens: `signIn: { allScreens: true }` + `pnpm payload generate:importmap`. No `serverURL` → no logo in the link preview: set it | `iapl-upgrade` "→ 1.17.1, the sign-in look", white-label.md "The sign-in screens" |
| 81 | **1.17.1 — proxy matcher** — `iapl-doctor` warns `proxy-matcher`; pages such as `/administracja` or `/apis` get no locale redirect or proxy CSP | `src/proxy.ts`: `matcher: ['/((?!(?:api|admin|_next)(?:/|$)|.*\\..*).*)']` (i18n.md "Next matcher") | `iapl-upgrade` "→ 1.17.1" |
| 82 | **1.17.1 — e-mail: "Sending method" is a choice** — Site integrations → E-mail sending shows "IWSN (built-in)", "Own SMTP server" or "Microsoft Graph (deprecated)" as selected; or, on Postgres / SQLite, the start log says the column for `emailMethod` is missing and the Site integrations page does not open; or mail fails with `smtp-incomplete` / `graph-not-set-up` | MongoDB: nothing. Postgres / SQLite: `pnpm payload migrate:create`, commit, apply at start. Nothing changes until another option is picked and saved; a chosen method that cannot be used fails loudly (no other transport): fill in SMTP, set `GRAPH_*`, or pick another method | `iapl-upgrade` "→ 1.17.1, e-mail", email.md "Which transport a send takes" |
| 83 | **1.17.2 — cookie button** — after the update the "cookie settings" button no longer sits above the footer; or the footer is about 40 px taller after a decision | Intended: the button stays in the bottom corner of the window on every page and never moves; while it is shown the footer gets just enough bottom padding for its last row to end above the button (measured; own padding counts; nothing before a decision or while the banner is open). Nothing to run. No room: `<CookieButton reserve={false} />`; amount by hand: `--ipal-cookie-button-space` on the footer; the placement before: `avoid={COOKIE_BUTTON_AVOID}`; other corner: `side="right"`; distance: `--ipal-cookie-button-offset` | consent.md "Where the cookie button sits", `iapl-upgrade` "→ 1.17.2, cookie button" |
| 84 | **1.17.2 — version history** — `GET /api/<collection>/versions` as a visitor answered 500 (`Cannot find field for path at _status`, MongoDB `reading 'type'`) with `readVersions: readPublished()` | Update; nothing else. New code: `readVersions: readPublishedVersions()`; a `readVersions` of your own that wraps `readPublished()` must use `readPublishedVersions()` inside | CHANGELOG 1.17.2 point 1, access.md |
| 85 | **1.17.2 — sign-in and panel actions** — a locked editor is told "incorrect" with the right password; or a panel button (mail Connect / Disconnect, test e-mail, cookie scan / approval) answers 403 behind a proxy; or rate limits now count an IPv6 home network as one visitor | Locked: wait 10 minutes or an admin unlocks; Payload's text back: `accounts: { lockedAnswer: 'payload' }`. 403 behind a proxy: set `serverURL`; off: `adminSameOrigin: false`. IPv6 per address: `setIpv6Grouping({ prefix: 128 })` | CHANGELOG 1.17.2 points 2, 3, 8; security.md |
| 86 | **1.17.2 — REST submissions and jobs** — a customer account gets 403 on `POST /api/form-submissions`; a cron gets 401 on `/api/payload-jobs/run` | Submissions: use `submitForm` / `createSubmitAction`, or `formSubmissionOverrides.access.create`. Jobs: `CRON_SECRET` (16+ characters) in the app's env and `Authorization: Bearer …` from the cron, or an admin's API key; `jobsRunAccess: false` = Payload's default | CHANGELOG 1.17.2 points 4–5, `iapl-upgrade` "→ 1.17.2" |
| 87 | **1.17.2 — consent version** — saving Cookies with a lower "Consent version" is refused ("cannot go down") | Raise it or leave it; a script with the Local API and `overrideAccess` may lower it; `cookieSettings: { allowLowerPolicyVersion: true }` restores the old freedom | CHANGELOG 1.17.2 point 7, consent.md |
After updating the package: `pnpm exec iapl-skills` (new skill versions), `pnpm payload generate:importmap`, `rm -rf .next`, restart dev, grep for the new symbol in
`node_modules/@intecion/ipal-kit/dist`.
+2 -1
View File
@@ -101,12 +101,13 @@ Turn off: `iapl({ doctor: false })`. Adapt: `iapl({ doctor: { tokenVar: 'MY_TOKE
| | `env-live` | error | (deep) the project's env rules pass in the real environment |
| security | `security-headers` | error | `buildSecurityHeaders`; live: HSTS, nosniff, Referrer-Policy, Permissions-Policy, frame protection |
| | `powered-by` | error | `withSecurityConfig`; live: no `X-Powered-By` on `/` and the admin |
| | `visitor-writes` | warning | (deep) on a site with a visitor login collection (an auth collection that is not staff): every collection whose `create` / `update` / `delete`, or global whose `update`, lets such an account in — Payload's default "any signed-in account" included. Give it its own rule (`adminOrEditor`, …); asked by behaviour, never by a rule's name (1.17.2) |
| | `proxy-matcher` | warning | `src/proxy.ts`: a matcher that skips `api`, `admin` or `_next` without ending them at "/" (`(?!api|admin|…)`) also skips every page whose first segment only starts with them (`/administracja`): no locale redirect, no proxy CSP. Fix: the literal in i18n.md (1.17.1) |
| | `client-hints` | info | `withSecurityConfig` is the outer wrapper (`withSecurityConfig(withPayload(…))`), so Payload's colour-scheme client hints go to the admin only; live: `/` sends no `Critical-CH: Sec-CH-Prefers-Color-Scheme`. Not reported with `adminClientHints: false` |
| | `csp` | warning / info | CSP on the site and the admin; report-only is info, a warning after 4 weeks (`seen`) |
| | `2fa` | error | `twoFactor: { plugin: payloadTotp }` + the package; deep: 0 users without TOTP (the message says how many of them are blocked because their setup window has passed); error: a Postgres / SQLite project whose migrations do not mention the 2FA column `totp_setup_from` (every login would answer 500; a warning when there is no migrations folder — the doctor cannot see a schema that gets there another way); warning: `twoFactor.requireSetup: false`; info: no setup window (`windowHours: false`) |
| | `access-missing` | warning | `iapl` has an `access` option — without it there are no roles and every panel account is an admin |
| | `csrf-empty` | warning | the config sets `serverURL` or `csrf` — otherwise Payload accepts the login cookie from any origin |
| | `csrf-empty` | warning | the config sets `serverURL` or `csrf` — otherwise Payload accepts the login cookie from any origin, and behind a proxy that rewrites `Host` the plugin's own-origin checks (2FA, panel actions) refuse the site's own panel. With `--url` (deep) the running config decides (`originKnown` in the status), not the file |
| | `open-signup` | info | (deep) auth collections whose `create` rule lets an anonymous request through: sign-up is open there (intended for a customer zone — silence with a reason) |
| | `staff-own-roles` | warning | (deep) a staff collection with role values of its own, neither `editor` nor `admin` among them, that runs on the plugin's default account rules: the plugin cannot rank those roles, so inside the collection every account may create an account with any role and change or delete another. Write the collection's own rules |
| | `staff-accounts-open` | error (warning for `read`, `readVersions`) | (deep) a staff collection that an account of another, non-staff auth collection may create in, read (also its versions), update, delete from or unlock — it can make itself staff, change a staff password, list the accounts or lift a login lock. The account rules are off (`accounts: false`, `adminOnlyCreate` / `adminOnlyWrite` / `staffOnlyRead: false`) or the project's own rule is wider. Asked with a made-up outside account; a rule that throws counts as closed |
+2 -1
View File
@@ -113,7 +113,8 @@ finding the names it was written for. Both accept both spellings in the environm
The plugin also reads (outside the preset — add your own rules if you want to validate them):
`INDEXNOW_KEY` (seo.md), `IAPL_NOINDEX` (`1`/`true`/`yes` — staging, seo.md), `IAPL_DOCTOR_TOKEN` (≥ 32 characters —
turns `GET /api/ipal/doctor` on, doctor.md). Full table:
turns `GET /api/ipal/doctor` on, doctor.md), `CRON_SECRET` (≥ 16 characters — a cron runs Payload's job queue over
HTTP with `Authorization: Bearer <CRON_SECRET>`, security.md "Payload's job queue"). Full table:
[deployment.md](./deployment.md).
Extending with your own variables — spread:
+14 -2
View File
@@ -436,6 +436,18 @@ A missing IP (the proxy strips the header, a wrong `IAPL_IP_HEADER`) does **not*
share one `unknown-ip` bucket with a ×20 limit (`UNKNOWN_IP_FACTOR`) — real
visitors get through, a flood without the header does not. `setUnknownIpFactor(n)` (root, once at startup)
changes the multiplier; `setUnknownIpFactor(0)` = the old behaviour (no limit), when a limiter sits in front.
**IPv6 is counted per network (1.17.2).** A host with IPv6 holds a whole /64 — 2^64 addresses, every home
connection and every server — so counting per address gave one visitor as many budgets as it had addresses. Every
limiter of the plugin (forms, the file upload endpoint, search, MCP, the consent log, stats, the doctor status, the
mail service's confirm route and account-mail limit) counts a **/64 as one client**; an IPv4-mapped address
(`::ffff:1.2.3.4`) counts as its IPv4. One home network shares the budget, as an IPv4 home behind one router always
did. Change it once at start (root export): `setIpv6Grouping({ prefix: 128 })` = per address (as before);
`setIpv6Grouping({ prefix: 56 })` another network size; `setIpv6Grouping({ wide: 48, wideFactor: 10 })` adds a
second counter per /48 at 10× the limit (a hosting customer often holds a /48 — off by default, because a mobile
carrier can put many phones in one /48). A value out of range throws. `ipRateKey(ip)` gives the key a limiter of
your own should count by (`consumeRateLimit` already applies it to a key that is an IP address).
**Check:** fifty requests to a limited route with `X-Real-IP: 2001:db8:1:1::1` … `::32` → `429` after the limit.
Without a pinned header the order
`cf-connecting-ip` → `x-real-ip` → XFF stays (switching to XFF-only, from the right, would put every visitor
behind Cloudflare into the bucket of the edge node) — that is why `IAPL_IP_HEADER` is mandatory in production
@@ -547,7 +559,7 @@ then does it store. A flood dies before it touches the network or the database.
**REST is closed.** By default the form-builder lets anyone create submissions through
`POST /api/form-submissions` — skipping all the gates below. IAPL
sets `access.create` of the `form-submissions` collection to "logged-in users only"; the front end
sets `access.create` of the `form-submissions` collection to "a staff account with its second factor" (since 1.17.2; before: any signed-in account, a customer of a visitor login collection included); the front end
submits through `submitForm` (server action → Local API), so this does not affect it.
A deliberately public REST (e.g. an external app) →
`forms: { formSubmissionOverrides: { access: { create: () => true } } }` — then
@@ -861,7 +873,7 @@ filter it out on the client.
- **Turn off:** without the `forms` option the plugin does not wire the form-builder (no Forms / Form Submissions collections).
Single field types: `forms.fields.<type>: false`. Files: `forms.attachments` is off unless you set it ("Files").
- **Override the collections:** `formOverrides` / `formSubmissionOverrides` — fields (the `fields` function), `labels`,
`admin`, `access`, `hooks`. The default submissions access (`create`: logged-in users, `read`: editor+, `delete`: admin)
`admin`, `access`, `hooks`. The default submissions access (`create`: a staff account with its second factor since 1.17.2, `read`: editor+, `delete`: admin)
is overridden by keys in `formSubmissionOverrides.access`; forms access (`create`/`update`/`delete`:
editor+, `read`: public) — in `formOverrides.access`. The Emails tab protection (`read`: editor+) is
applied to the default fields **before** `formOverrides.fields`, so you change it there.
+1
View File
@@ -38,6 +38,7 @@ and shared by the helpers (generateMetadata and the page share queries).
| `mcp` | — | `{ serverName, serverVersion, rateLimit, maxBatch, clientIp, isPathVisible }` for `mcpGET`/`mcpPOST` (mcp.md) |
| `pageJsonLd` | — | default `getPageJsonLd` options: `breadcrumbs`, `entryType`, `entries`, `faq`, `pageType` |
| `robots` | — | `RobotsOptions` for `robots` and `getRobots` (seo.md); `aiBotRules: [{ userAgent, access }]` = per-bot exceptions from code (the panel's rules come after them) |
| `draftRelations` | `'hide'` | related documents that are drafts are left out of what the helpers answer (1.18.0); `'keep'` as before (content.md "Drafts as related documents") |
| `settingsDepth` | `1` | depth of `getSettings`: Site settings relations arrive as documents, theirs as ids (the archive page is read separately at depth 2); `2` = every request pays for more |
| `siteJsonLd` | WebSite + Organization from Site settings | a function replaces it, `false` = none |
| `sitemapEntries` | — | `(entries) => entries` — final sitemap list: add URLs of your own routes, remove some, set `priority` |
+5
View File
@@ -37,6 +37,11 @@ The state block above it reads `GET /api/iapl/mail-relay/status` and acts throug
or at most every 10 min while an error lasts; it never throws. The same change already being written (many sends
failing at once) is written once; while every transaction place of a Postgres pool is taken
([deployment.md](./deployment.md) §4.3a) the write goes on in the background instead of holding the caller.
- **The status is written alone (1.18.0).** `updateGlobal` reads the whole document, merges and writes it whole: a
status written after a visitor's form submit put back an admin's SMTP or Turnstile change saved in the same
moment. The status field is now written through the database adapter on its own (`writeGlobalFields(payload,
slug, data)`, exported): no read of the rest, no hooks, no new version (fit for bookkeeping fields only). A global
that does not exist yet is created the usual way.
- **Changing keys in the admin panel** (Turnstile, the sending method / `smtp*`) clears that integration's old status.
- **`emailStatus.code`** of a send through the Intecion mail service is one of the `relay-…` codes (`relay-pending`,
`relay-quota`, `relay-unreachable`, …), each with a text in the editor's language — the list and what to do:
+79
View File
@@ -421,6 +421,40 @@ Real panel protection:
`/admin → /its` is a layer (it filters out dumb bots), not a lock. Treat it as an
addition to real safeguards, not a replacement for them.
## Panel actions only from the site's own origin (`adminSameOrigin`, 1.17.2)
The plugin's panel actions act with the panel's login cookie and read their body whatever its `Content-Type`
says: `POST /api/iapl/mail-relay/connect` and `/disconnect` (the mail service), `/api/ipal/test-email`,
`/api/ipal/cookie-scan`, `/api/ipal/cookie-approval`, `/api/ipal/cookie-crawl`. A `text/plain` POST needs no CORS
preflight, a page on a sibling subdomain is "same site" (the browser sends the `SameSite=Lax` cookie), and
Payload's own CSRF list is empty unless `serverURL` or `csrf` is set. So before 1.17.2 such a page could make a
signed-in administrator disconnect the mail service, send test mails, run scans and crawls, or approve every
waiting cookie. Now each of them refuses (`403`, before anything is read) a request a browser marks as coming
from elsewhere — the same rule as the 2FA endpoints: the `Origin` header, else `Sec-Fetch-Site`. Own origins: the
host the request came in on (`Host`, `X-Forwarded-Host`), `serverURL`, Payload's `csrf` and `cors` lists, and
`adminSameOrigin.origins`. A request with neither header (a script, `curl`, a server) passes: it rides on nobody's
cookie. The panel's own buttons are on the site's origin and are not affected. A project's own endpoint on one of
these paths is left as it is. The 2FA endpoints keep their own switch (`twoFactor.sameOrigin`).
```ts
iapl({
// adminSameOrigin: { origins: ['https://panel.example.com'] }, // the panel served from another origin
// adminSameOrigin: false, // no check (as before 1.17.2)
})
```
- **Behind a proxy that rewrites `Host`** and sends no `X-Forwarded-Host`, without `serverURL`, the site's own
panel buttons are refused. It is not silent: the first refusal of each origin is logged
(`[iapl] a panel action from origin "…" was refused … pass iapl({ adminSameOrigin: { origins: [...] } })`), and
`iapl-doctor` warns when the running config has neither `serverURL` nor `csrf` (`csrf-empty`). Set
`serverURL: process.env.NEXT_PUBLIC_SERVER_URL`.
- **Any other value** than `true`, `false` or an object with `origins` (a list of strings) stops the start.
- **Building blocks:** `requireOwnOrigin(endpoint, origins?)` for an endpoint of your own,
`guardAdminEndpoints(config, projectEndpoints, option)`, `ADMIN_POST_ENDPOINTS` (the list), and the 2FA ones:
`requestFromOwnOrigin`, `ownOrigins`, `reportRefusedOrigin(req, origins?, { what, option, docs }?)`.
- **Check:** `curl -X POST <site>/api/ipal/test-email -H 'Origin: https://other.example' -H 'Content-Type: text/plain'
-b <admin cookies> -d '{"to":"a@example.com"}'` → `403`; "Send test e-mail" in the panel still works.
## 2FA (TOTP) — ENFORCED for every user
The plugin enforces two-factor authentication (TOTP) for ALL panel users —
@@ -1199,6 +1233,51 @@ a root endpoint to the config and the check names it as "not judged".
**In the plugin repository:** `pnpm routes:check` (`--update` after a Payload upgrade) on the reference site, also
the first step of `pnpm e2e:built`; the test fixtures are switched off for it.
## Payload's job queue (`jobsRunAccess`, 1.17.2)
Payload runs its queue over HTTP at `GET /api/payload-jobs/run` and `/api/payload-jobs/handle-schedules`, checked by
`jobs.access.run`. Payload's default is **any signed-in account of any auth collection** — a shop's customer could
run the queue whenever they like. Since 1.17.2, when the project writes **no** `jobs.access.run`, iapl sets: an
**admin signed in with the second factor** (an admin's API key counts), or **`Authorization: Bearer <CRON_SECRET>`**
(16+ characters, compared in constant time). It is set even when the config has no `jobs` (Payload turns the queue on
by itself for scheduled publishing). A route that does not exist (no tasks, no workflows) stays 404.
**A project with jobs keeps its cron working** — check which of these it uses:
- jobs run **in-process** (`jobs.autoRun`, `pnpm payload jobs:run`, `payload.jobs.run()` in code): nothing changes;
- a **Coolify scheduled task** (or any cron) that calls the run route: set `CRON_SECRET` in the app's environment and
in the task, and send the header —
`curl -fsS -H "Authorization: Bearer $CRON_SECRET" "$NEXT_PUBLIC_SERVER_URL/api/payload-jobs/run"`;
- a cron that signs in with an **admin's API key**: works as before; with a **non-admin** account's key: switch to
`CRON_SECRET`, or write your own rule;
- the project's **own** `jobs.access.run`: always wins, nothing changes.
At start, when the queue is on, the rule is iapl's and `CRON_SECRET` is missing or short, the log says so in one
line. Overrides: `iapl({ jobsRunAccess: false })` keeps Payload's default; `{ secretVar: 'MY_VAR' }` reads another
variable; `jobsRunAccess()` is exported to reuse in a rule of your own. Verify: without the header
`/api/payload-jobs/run` answers 401, with it 200 (the closed-doors spec does both on the built reference site).
## Visitor accounts (customers, members) and Payload's default write rules
Payload fills every missing access rule with **"any signed-in account"** — an account of a visitor login collection
included. The plugin narrows its own collections and globals and the staff accounts; **your** collections and
globals are yours to rule. On a site that has (or may get) a visitor login collection, give every collection
`create` / `update` / `delete` and every global `update` a rule of its own — the reference site and every new site
from `iapl create` do (`adminOrEditor`, since 1.17.2). `iapl-doctor --url` (deep) lists what such an account may
write (`visitor-writes`, warning), checked by behaviour: it asks every rule with a stand-in visitor account. Payload's
own `payload-locked-documents` (who edits which document) also runs on Payload's default and is listed there; a
plugin-wide default for it is planned for 2.0. Verify: the doctor shows no `visitor-writes` finding, and the
closed-doors spec's customer gets 403 on every write door.
## 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.
## Turn off, override, extend
- **Stored secrets:** `secrets: { writeOnly: false }`, `secrets: { reenterOnChange: false }`; `writeOnlySecret` /
+1 -1
View File
@@ -1,6 +1,6 @@
{
"name": "@intecion/ipal-kit",
"version": "1.17.1",
"version": "1.17.2",
"description": "Intecion Advanced Payload Library — a Payload CMS 3 plugin: i18n, SEO, forms, consent, analytics, blog/archives.",
"license": "MIT",
"repository": {
+2 -1
View File
@@ -78,7 +78,8 @@ names, env, admin, AGENTS.md, skills, seeds and — with `--url` / `--deep` —
- **Drafts and locales over the API** (a collection with `versions: { drafts: true }`): without a session,
`curl -s "$U/api/<slug>?draft=true&limit=100" | grep -c '"_status":"draft"'` → `0`, else ERROR: give it
`access: { read: readPublished(), readVersions: readPublished() }` (access.md). `curl -sI "$U/md/xx"` → `404`
`access: { read: readPublished(), readVersions: readPublishedVersions() }` (access.md). `curl -s -o /dev/null -w '%{http_code}' "$U/api/<slug>/versions?limit=10"`
→ `200` (a `500` = a rule with the document's `_status` path on `readVersions`: ERROR). `curl -sI "$U/md/xx"` → `404`
(no stand-in locale); a 404 page assigned in System pages must be published.
- **Secrets out of queries** (as an admin, with versions on for Site integrations or a collection using
`writeOnlySecret`): `curl -s -H "Authorization: JWT $T" "$U/api/globals/site-integrations/versions?where[version.smtpPassword][exists]=true"`
@@ -46,12 +46,16 @@ const DOORS: Door[] = [
{ closedFor: ALL, method: 'POST', name: 'the crawler\'s call-back without its token', path: '/api/ipal/cookie-crawl/results', body: { jobId: 'x', ok: true } },
{ closedFor: OUTSIDERS, method: 'POST', name: 'a crawl without the schedule\'s token', path: '/api/ipal/cookie-crawl' },
{ closedFor: OUTSIDERS, name: 'form submissions', path: '/api/form-submissions' },
// IAPL 1.17.2: a staff account only; an open door answers 400 (validation) instead of 403
{ body: { form: NO_ID, submissionData: [] }, closedFor: OUTSIDERS, method: 'POST', name: 'a submission past submitForm', path: '/api/form-submissions', closed: status(403) },
{ body: { email: '[email protected]', password: 'Door-Password-1234', roles: ['admin'] }, closedFor: ALL, method: 'POST', name: 'nobody creates a staff account', path: '/api/users', closed: status(403) },
{ body: { email: '[email protected]', password: 'Door-Password-1234' }, closedFor: ALL, method: 'POST', name: 'the first-user route once an account exists', path: '/api/users/first-register', closed: status(403) },
{ body: {}, closedFor: OUTSIDERS, method: 'POST', name: 'Site settings cannot be saved', path: '/api/globals/site-settings', closed: status(403) },
{ closedFor: ALL, name: 'the GraphQL playground (production)', path: '/api/graphql-playground', closed: status(404) },
{ closedFor: ALL, graphql: '{ __schema { queryType { name } } }', closed: ({ body }) => Boolean((body as { errors?: unknown[] })?.errors?.length), name: 'GraphQL introspection (production)' },
{ closedFor: ALL, name: 'Payload\'s job queue (a site without jobs)', path: '/api/payload-jobs/run', closed: status(404) },
// a site without jobs: 404. A site WITH jobs (IAPL 1.17.2): refused (401) for everybody but an admin and
// `Authorization: Bearer <CRON_SECRET>` — drop `closed: status(404)` there
{ closedFor: ALL, name: 'Payload\'s job queue', path: '/api/payload-jobs/run', closed: status(404) },
// the project's own doors: add them here
// { closedFor: OUTSIDERS, body: {}, method: 'PATCH', name: 'pages cannot be changed', path: `/api/pages/${NO_ID}`, closed: status(403) },
]
@@ -46,9 +46,11 @@ Ask only when the brief leaves a business question open (e.g. "do posts have aut
**No URL prefix in code** — the editor assigns the archive page in
Site settings (`<slug>Archive`). The plugin handles routing, sitemap,
generateStaticParams, hreflang.
**With drafts** (`versions: { drafts: true }`): `access: { read: readPublished(), readVersions: readPublished() }`
**With drafts** (`versions: { drafts: true }`): `access: { read: readPublished(), readVersions: readPublishedVersions() }`
(`readPublished` is for `read`, `readPublishedVersions` for `readVersions` — the version list asks for `version._status`)
— Payload's open `read: () => true` answers `?draft=true` with the draft over REST and GraphQL. Check:
`curl -i <site>/api/<slug>/<draft id>?draft=true` without a session → `404`; the same with an editor's token → the draft.
`curl -i <site>/api/<slug>/<draft id>?draft=true` without a session → `404`; the same with an editor's token → the draft;
`curl -s -o /dev/null -w '%{http_code}' <site>/api/<slug>/versions?limit=10` without a session → `200`, never `500`.
3. Entry list = a block (EntriesList) with `getEntries`; the entry page uses
`resolveRoute` (type `entry`); JSON-LD per seo.md (e.g. Article).
4. **An auth collection for visitors** (`auth: true`: customers, members) only when the client requires it
@@ -55,6 +55,14 @@ before analytics or marketing consent — check the project's choice in "Project
`nonce` to `<SiteProviders>`. A visitor who decided must never see the banner on reload; one whose
decision is from an older Policy version must see it at once. A click on a button before hydration
counts (the checks above click as soon as the button is visible).
7. Cookie button (1.17.2, consent.md → "Where the cookie button sits"): after a decision, on a long page, a short
page and a page with a form, desktop and phone width (also 360 px) — the button is in the bottom corner of the
window at the top, in the middle, with the footer in view and at the very end: it must not move at all. At the
very end nothing of the footer is under it and the last footer link can be tapped (the footer has grown a little:
`[data-ipal-cookie-space]` on it). Before a decision and while the banner is open the footer has its own padding
only. Tab reaches the button and Enter reopens the banner. A project scroll handler, a button rendered inside
the footer or hand-made bottom padding for it → remove (AGENT.md §7). Too much or too little room:
`--ipal-cookie-button-space` on the footer; none: `reserve={false}`.
The script needs buttons with `data-ipal="accept"` / `"reject"` — the plugin's
`CookieBanner` has them in every `settings` mode (`inline`, `modal`, `detailed`). A custom banner in the project violates AGENT.md §7.
@@ -34,6 +34,11 @@ through this procedure. Ask only when you are missing something you cannot get y
### Build / TypeScript
| Symptom | Cause | Fix |
|---|---|---|
| a panel button (mail service Connect / Disconnect, Send test e-mail, cookie scan / approve / check site) answers `403` "Not allowed from this origin."; log `[iapl] a panel action from origin "…" was refused` | the request's origin is not one the site knows (1.17.2, `adminSameOrigin`): a reverse proxy that rewrites `Host` and sends no `X-Forwarded-Host`, and no `serverURL` | set `serverURL: process.env.NEXT_PUBLIC_SERVER_URL` in the Payload config, or make the proxy send `X-Forwarded-Host`, or `adminSameOrigin: { origins: ['https://…'] }`; `iapl-doctor` `csrf-empty` |
| a staff account's correct password gets "The email or password provided is incorrect." | the account is locked by Payload after `maxLoginAttempts` wrong passwords (5, for `lockTime`, 10 min); since 1.17.2 a locked staff account gets the wrong-password answer (`accounts.lockedAnswer`) | wait for the lock to end, or an admin unlocks it (the account in the panel, or `POST /api/users/unlock`); `lockUntil` on the account shows it. Payload's own message back: `accounts: { lockedAnswer: 'payload' }` |
| a sign-in answers `429` "Too many failed sign-ins to this address from here" | 5 failed sign-ins for that address from that client IP in 15 minutes (`accounts.signInLimit`, 1.18.0); everybody behind one IP shares it (an office NAT); without `IAPL_IP_HEADER` everybody may share the no-IP bucket | wait the minutes it names, or sign in from elsewhere; pin `IAPL_IP_HEADER`; more room: `signInLimit: { perAddress: 10 }` |
| staff login / "forgot password" answers `403` and the log says `[iapl] a staff sign-in from origin "…" was refused` | the request came from another origin (`accounts.signInSameOrigin`, 1.18.0): a front end on another domain, or a proxy that rewrites `Host` without `serverURL` | set `serverURL`, or `signInSameOrigin: { origins: ['https://…'] }` |
| saving one's own account answers "Enter your current password to change your e-mail address or password." | `accounts.confirmOwnChanges` (1.18.0): own e-mail / username / password changes need the current password | type it in "Current password" on the account page; scripts send `currentPassword`; off: `confirmOwnChanges: false` |
| the 2FA code screen answers "Too many codes were tried…" (`429` from `/api/verify-totp`) | more than 5 wrong codes for that account in 10 minutes (`twoFactor.verifyLimit`; right codes do not count since 1.17.1). "…being checked right now. Try again in a moment." (`Retry-After: 2`) = several attempts of one account at the same moment, nothing is locked; repeated lines `[iapl] 2FA: too many verify attempts` in the log without the owner trying = someone has the password | wait for the window, enter the current code once; unexplained attempts: change that account's password. Tests that log in often: `verifyLimit: { max: … }` for that environment |
| `isAdmin(req.user)` says `false` for a real administrator on the server, in a process that loads two Payload configs (tests, a multi-site script) | a call without a source counts only collections that are staff in **every** config of the process | pass the source: `isAdmin(req.user, req.payload)` — with it each config gets its own answer |
| `isAdmin(user)` / `isEditor(user)` is always `false` in a client component or in `proxy.ts` | the staff collections are not known there (no config in the browser bundle / middleware), and the predicates fail closed | `isAdmin(user, config)` with `useConfig()`, imported from `@intecion/ipal-kit/client`; in middleware `isAdmin(user, { staffCollections: ['users'] })` |
@@ -38,10 +38,15 @@ description: Complete map of everything @intecion/ipal-kit provides — every ia
| `accounts.staffOnlyRead` | on | `read` and `readVersions` on a staff collection without those rules: a fully signed-in account of a staff collection (Payload's default let a visitor account list the staff accounts) | `false` = Payload's default; a `read` rule you wrote wins |
| `accounts.firstUserRoute` | `'panel'` | which auth collections `POST /api/<slug>/first-register` answers for while they are empty: only the one the panel logs in with (the first account of a site → admin). Others get `403`, a second staff collection included, in any spelling of the URL (the plugin's own endpoint sits in front of Payload's); a collection whose own `create` allows an anonymous request keeps its route. With `access.firstUserAdmin: false` and a default role below the panel role, the default `panelRole` is not applied (logged) and an explicit one is refused at start | a list of slugs; `'all'` = Payload's behaviour |
| `accounts.password` | `{ minLength: 12 }` | when a password is SET on a staff collection (create, first-user screen, change, reset by e-mail; panel, API and Local API): at least `minLength` characters, not the account's e-mail address. Existing passwords are never checked — a shorter one keeps logging in | `{ minLength }`; `false` = Payload's rule (3 characters) |
| `accounts.lockedAnswer` | `'wrong'` (1.17.2) | a staff account Payload has locked (too many wrong passwords) gets exactly the wrong-password answer on login (REST, GraphQL, the panel): nobody tells which addresses have an account; the lock itself is unchanged | `'payload'` = Payload's "This user is locked…"; any other value stops the start |
| `accounts.signInLimit` | `{ perAddress: 5, windowMinutes: 15, accountLock: { maxLoginAttempts: 50, lockTime: 3_600_000 } }` (1.18.0) | failed staff sign-ins per client IP + typed address (folded): over the limit `429` for that IP and address only; only failures count; Payload's per-account lock raised where the project set none | `{ perAddress, windowMinutes, accountLock }`; `accountLock: false` = Payload's lock; `false` = as before 1.18 |
| `accounts.signInSameOrigin` | on (1.18.0) | staff login / forgot / reset password: `403` for a request a browser marks as coming from another origin | `{ origins: [...] }`; `false` |
| `accounts.confirmOwnChanges` | on (1.18.0) | own e-mail / username / password change needs `currentPassword` (panel field, REST, GraphQL) | `false` |
| `secrets.writeOnly` | on | `smtpPassword` and `turnstileSecretKey` (Site integrations) are never returned: REST, GraphQL and the panel get `'********'` when a value is stored; a save with nothing / empty / the mask keeps it, a new value replaces it, `'[[clear]]'` removes it; the Local API with access control off reads the real value. The panel is the source of these secrets — no env variable. A restore of a version is masked too | `false` = returned to whoever may read the global, as before |
| "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) |
| `adminSameOrigin` | on (1.17.2) | `POST` mail service connect / disconnect, test e-mail, cookie scan / approval / crawl refuse (`403`) a request a browser marks as coming from another origin; own origins: the request's host, `serverURL`, `csrf`, `cors`, `origins` | `{ origins: [...] }` adds origins; `false` = no check; any other value stops the start |
| `adminRoute` | `'/admin'` | `config.routes.admin`; stats link and views, `IntegrationAlerts` | the project moves `app/(payload)/<route>/` itself and adds the route to the proxy matcher (security.md) |
| `twoFactor` | **none = error** | `@clocklimited/payload-2fa` with `forceSetup: true` (TOTP enforced, also checked in the API) | `twoFactor: false` (discouraged); omitting the option throws `[iapl] twoFactor.issuer is required` |
| `twoFactor.issuer` | — (required) | name in the authenticator app | — |
@@ -93,7 +98,7 @@ description: Complete map of everything @intecion/ipal-kit provides — every ia
| `forms.adminGroup` | `'Forms'` | sidebar group | `false` = Payload default; `admin.group` in overrides wins |
| `forms.fields.*` | on: `checkbox`, `checkboxGroup`, `country`, `date`, `email`, `message`, `number`, `radio`, `select`, `state`, `step`, `text`, `textarea`, `time`; off: `payment` | block types in the builder (all with "Show only when") | `<type>: false`; a block object replaces it; `payment: true` **does nothing** (filtered out) — pass a block object |
| `forms.formOverrides` | Form/Forms labels, `emails` readable by logged-in users only | overrides the `forms` collection (`fields: ({ defaultFields }) => …`, `slug`, `admin`, `access`…) | any `CollectionConfig` |
| `forms.formSubmissionOverrides` | create: logged-in, read: editor+, delete: admin | overrides `form-submissions` | `access.create` etc. wins |
| `forms.formSubmissionOverrides` | create: a staff account with its second factor (since 1.17.2; before: any signed-in account), read: editor+, delete: admin | overrides `form-submissions` | `access.create` etc. wins |
| `forms.redirectRelationships` | none | collections a form can redirect to | `['pages']` |
| `forms.emailLayout` | `false` | `beforeEmail` with a layout (logo, colour, footer) + Site settings → **Emails** tab; `{{*:table}}` readable | `true` |
| `forms.beforeEmail` | none | your own e-mail changes (after the layout) | form-builder function |
@@ -102,6 +107,7 @@ description: Complete map of everything @intecion/ipal-kit provides — every ia
| `forms.consentFieldName` | `'consent'` | name of the GDPR consent field `submitForm` requires (read from `config.custom.ipal`) | `createSubmitAction({ consentFieldName })` / `submitForm` argument wins |
| `consentLog` | **on** (since 1.17.0) | `consent-records` collection + `POST /api/ipal/consent` (rate limit 20/min); Postgres / SQLite: a table, migration in the same deploy | `false` / `{ retentionDays }` (default 1095) |
| `consentLog.collectionOverrides` | none | changes `consent-records`: an object merges `access` / `admin` / `hooks` key by key (your keys win), a function `(collection) => collection` takes over (keep the slug) | e.g. `{ access: { read: ({ req }) => req.user?.email === '[email protected]' } }` — narrows who reads records in a project without roles |
| `jobsRunAccess` | on (since 1.17.2), only when the project writes no `jobs.access.run` | Payload's job queue over HTTP (`/api/payload-jobs/run`, `/handle-schedules`): an admin with the second factor (an admin API key counts) or `Authorization: Bearer <CRON_SECRET>` (16+ chars); before: any signed-in account of any auth collection. In-process runs (`jobs.autoRun`, `payload jobs:run`) unaffected | `false` = Payload's default; `{ secretVar }` = another variable; your own `jobs.access.run` wins. Check: `curl -H "Authorization: Bearer $CRON_SECRET" $URL/api/payload-jobs/run` → 200, without it 401 (security.md "Payload's job queue") |
| `doctor` | on (404 until `IAPL_DOCTOR_TOKEN` is set) | `GET /api/ipal/doctor` — read-only counts for `iapl-doctor --url` (users without TOTP, cookies waiting for approval, versions); Bearer token ≥ 32 characters, rate-limited, never names or values | `false` = no endpoint; `{ tokenVar, access }` (doctor.md) |
| `cookieScanner` | off | `cookie-review` collection, "Scan cookies" box above its list (`CookieScanButton`), `GET`/`POST /api/ipal/cookie-scan`, and (unless `approval: false`) the *Approve cookies* view `/admin/cookie-approval` (`CookieApprovalView`) + `GET`/`POST /api/ipal/cookie-approval` + the dashboard reminder; a scan lists the cookies of the integrations switched on + names looked up in the bundled Open Cookie Database; one **Approve and add** puts the ticked cookies into Cookies → Cookie list (so `<CookieTable>` and the detailed window); never deletes, never overwrites edited text, never duplicates, nothing reaches the banner before approval | `true` / object; after switching on: `pnpm generate:importmap` + `migrate:create`. Check: *Privacy → Cookie review* → **Scan cookies** → "Waiting for approval: N" → **Review and approve** → **Approve and add** → the cookies are in Cookies → Cookie list (cookie-scanner.md) |
| `cookieScanner.adminLayout` | `'combined'` | one *Cookies* entry: *Review and approve* and (with `crawl`) *Site check* tabs on the `cookie-settings` global (`ui` fields, `CookieReviewTab` / `CookieSiteCheckTab`); `cookie-review` and `cookie-crawl` get `admin.group: false` (out of the nav, pages and API kept) | `'separate'`; no migration, `generate:importmap` |
@@ -277,6 +283,7 @@ The plugin's own variables are `IAPL_<NAME>`; a deploy that sets the spelling fr
| `IAPL_IP_HEADER` | `ipHeader: true` + production | rate limit trusts any IP header (spoofing) + warning in prod | env: `cf-connecting-ip` (Cloudflare) / `x-forwarded-for` (Traefik/nginx) |
| `IAPL_COOKIE_SCAN_URL`, `IAPL_COOKIE_SCAN_TOKEN` | `cookieScanner.crawl` (`iaplEnvRules({ cookieCrawl: true })` requires both in production; token ≥ 16 chars) | **Check site** disabled, the box names the missing variable | env; the token also goes into the scanner service's `IAPL_CRAWLER_SITES` as `host=token` |
| `IAPL_DOCTOR_TOKEN` | no; ≥ 32 characters | `GET /api/ipal/doctor` answers 404; with it the endpoint answers a Bearer token, and `iapl-doctor --url` with the same variable reads the deep counts | env (Coolify) and the doctor's shell; also read by the doctor: `CI`, `NO_COLOR`, `PAYLOAD_CONFIG_PATH` (`--deep`), `IAPL_DOCTOR_IMPORT_MAP` (internal) — doctor.md |
| `CRON_SECRET` | no; ≥ 16 characters (name: `jobsRunAccess.secretVar`) | Payload's job queue runs over HTTP only for an admin; the start log says so when the queue is on | env (Coolify); the cron sends `Authorization: Bearer <CRON_SECRET>` to `/api/payload-jobs/run` |
| `IAPL_NOINDEX` | no; `1`/`true`/`yes` **staging/preview only** | — (when set: robots Disallow, meta noindex, `X-Robots-Tag`, IndexNow sends nothing) | staging env |
| `NEXT_PHASE` | set by Next | only tells `next build` from runtime: during the build an unreachable database gives an empty sitemap; at runtime the sitemap throws (route → 503) | do not set by hand |
| `NEXT_RUNTIME` | set by Next | `instrumentation.ts` checks for `nodejs`; missing (scripts, seed) → `buildRevalidateHook` does not revalidate | do not set by hand |
@@ -85,7 +85,12 @@ Admin panel components from `@intecion/ipal-kit/admin` — the project does NOT
| `buildRolesField(defaultRole?, { firstUserAdmin? })` | `@intecion/ipal-kit` | The `roles` select field the plugin injects (only admins set roles; `firstUserAdmin` default `true` = the account made on "Create first user" gets `admin`). The plugin wires it itself — use it only for an auth collection the plugin does not manage. |
| `injectRoles(config, accessOption)` | `@intecion/ipal-kit` | Adds `roles` to `accessOption.authCollection` in a config. The plugin calls it itself with `access` — do not call. |
**Types:** `AccountsOptions` (`accounts`: `panelRole`, `adminOnlyCreate`, `adminOnlyWrite`, `staffOnlyRead`, `firstUserRoute`, `password`), `StaffAccountAccessOptions` (`{ create?, write?, read?, pluginRoles? }`), `StaffRuleMark` (`{ slug, self }`), `AccountsMarker` (`{ slug, staff, own? }`, in `custom.ipalAccounts`; `own`: the operations that had a rule of the project's at config time, kept when the collection becomes staff later), `LateAdoption` (`{ slug, applied, kept, known, password, firstUser }`; `known`: in the config when iapl ran and staff only afterwards, `kept`: its operations whose own rule was left as written), `StaffAccountRules` (what the plugin put on a staff collection, in `custom.ipalAccountRules`: `{ applied, ownRoles }`), `WriteOnlySecretOptions` (`{ boundTo?, appliesWhen? }`), `PasswordRuleOptions` (`{ minLength? }`), `FirstUserRouteOption` (`'panel' \| 'all' \| string[]`), `TurnstileOnConfigError` / `TurnstileOnConfigErrorOption` / `TurnstileFormKind` (`@intecion/ipal-kit/server`), `VerifyLimitOptions` (`twoFactor.verifyLimit`: `{ max?, windowMinutes?, store? }`), `RequireSetupOptions` (`twoFactor.requireSetup`), `TwoFactorResetOptions`, `TwoFactorSetupState`, `SafeBackRule` / `SafeBackContext` (`twoFactor.safeBack` as a function: `(back, { adminRoute, origin? }) => string`), `TotpViewComponent` (a view component as registered: a path or `{ path, exportName?, clientProps?, serverProps? }`), `SafeTotpViewProps` (`@intecion/ipal-kit/admin`), `Role` (`'user' \| 'editor' \| 'admin'`), `AccessOption` (the plugin's `access` option: `authCollection`, `defaultRole`, `authAccess`, `firstUserAdmin`, `staffCollections`).
| `requireOwnOrigin(endpoint, origins?)`, `guardAdminEndpoints(config, projectEndpoints, option)`, `ADMIN_POST_ENDPOINTS`, type `AdminSameOriginOption` | `@intecion/ipal-kit` | `adminSameOrigin` (1.17.2): wraps an endpoint so a request a browser marks as coming from another origin gets `403` (logged once per origin); applies it to the plugin's panel actions it added; the list of `[method, path]` covered. `reportRefusedOrigin(req, origins?, { what, option, docs }?)` names your option in the log line. |
| `lockedLooksWrong`, `withLockedAnswer(config)`, `graphqlLoginName(collection)` | `@intecion/ipal-kit` | `accounts.lockedAnswer` (1.17.2): the config-level `afterError` hook that answers Payload's `LockedAuth` on a staff collection's login (REST, GraphQL) exactly like `AuthenticationError`; adding it to a config (idempotent); the GraphQL login mutation's name of a collection. |
| `applySignInRules(collection, accounts?)`, `buildSignInBeforeOperation(slug, rules)`, `releaseSignInPlace`, `settleFailedSignIn`, `buildCurrentPasswordField()`, `resolveSignInRules(accounts?)`, `foldSignInName(value)`, `passwordMatches({ hash, salt }, password)`, `CURRENT_PASSWORD_FIELD`, `SIGN_IN_RULES_MARK` (the mark on the `beforeOperation` hook); types `SignInRulesOptions`, `SignInLimitOptions`, `SignInSameOriginOptions` | `@intecion/ipal-kit` | 1.18.0, `accounts.signInLimit` / `signInSameOrigin` / `confirmOwnChanges`: the three rules on one staff collection (hooks, field, Payload lock defaults); the `beforeOperation` hook; the `afterLogin` hook that gives a sign-in's place back; the config `afterError` hook that ends a failed one; the virtual "Current password" field; the options with defaults; the address folding (NFKC, lower case, trim); Payload's stored-hash check (unknown formats refused). |
| `releaseRateLimit({ key, scope, max?, windowMs?, cost? })` | `@intecion/ipal-kit` | Gives back a place `consumeRateLimit` took (memory: never below 0; a store: `hit(id, -cost)`) — for a limiter that counts failures only. |
**Types:** `AccountsOptions` (`accounts`: `panelRole`, `adminOnlyCreate`, `adminOnlyWrite`, `staffOnlyRead`, `firstUserRoute`, `password`, `lockedAnswer`, `signInLimit`, `signInSameOrigin`, `confirmOwnChanges`), `LockedAnswerOption`, `StaffAccountAccessOptions` (`{ create?, write?, read?, pluginRoles? }`), `StaffRuleMark` (`{ slug, self }`), `AccountsMarker` (`{ slug, staff, own? }`, in `custom.ipalAccounts`; `own`: the operations that had a rule of the project's at config time, kept when the collection becomes staff later), `LateAdoption` (`{ slug, applied, kept, known, password, firstUser }`; `known`: in the config when iapl ran and staff only afterwards, `kept`: its operations whose own rule was left as written), `StaffAccountRules` (what the plugin put on a staff collection, in `custom.ipalAccountRules`: `{ applied, ownRoles }`), `WriteOnlySecretOptions` (`{ boundTo?, appliesWhen? }`), `PasswordRuleOptions` (`{ minLength? }`), `FirstUserRouteOption` (`'panel' \| 'all' \| string[]`), `TurnstileOnConfigError` / `TurnstileOnConfigErrorOption` / `TurnstileFormKind` (`@intecion/ipal-kit/server`), `VerifyLimitOptions` (`twoFactor.verifyLimit`: `{ max?, windowMinutes?, store? }`), `RequireSetupOptions` (`twoFactor.requireSetup`), `TwoFactorResetOptions`, `TwoFactorSetupState`, `SafeBackRule` / `SafeBackContext` (`twoFactor.safeBack` as a function: `(back, { adminRoute, origin? }) => string`), `TotpViewComponent` (a view component as registered: a path or `{ path, exportName?, clientProps?, serverProps? }`), `SafeTotpViewProps` (`@intecion/ipal-kit/admin`), `Role` (`'user' \| 'editor' \| 'admin'`), `AccessOption` (the plugin's `access` option: `authCollection`, `defaultRole`, `authAccess`, `firstUserAdmin`, `staffCollections`).
## Accessibility — widget (`accessibility`) — details: `node_modules/@intecion/ipal-kit/docs/accessibility.md`
@@ -165,8 +170,10 @@ Fifteen ready blocks and ten page templates. **Use a library block (or a variant
|---|---|---|
| `ConsentProvider` | `@intecion/ipal-kit/client` | Consent provider: `{ texts, cookieMap?, logEndpoint?, nonce?, cookieValue?, gpc?, maxAgeDays? }` (`gpc`: Global Privacy Control `'honour'` default / `'ask'` / `false`; `maxAgeDays`: re-ask period, default 180; withdrawal also removes the panel's listed storage keys and tells Meta / TikTok / Clarity) (`nonce`: CSP nonce for the banner's first-paint script; `cookieValue`: optional server-read consent cookie → exact HTML, dynamic pages) — consent state, cookie, Consent Mode, deleting cookies after consent is withdrawn, optional POST of the decision to the log (`'/api/ipal/consent'`). Wrap the layout once; required by the banner, `Analytics`, `ConsentScript`. |
| `CookieBanner` | `@intecion/ipal-kit/client` | Consent banner + category settings: `settings: 'inline' \| 'modal' \| 'detailed'`, `controls`, `equalChoice` (recommended `true`), `order`, `settingsActions`, `icon`, `classNames`, `firstPaint` (default `true`: in the server HTML, decided before the first paint by an inline script; pages stay static), `nonce`; colours from `--ipal-*` CSS vars. Do not write your own banner. |
| `CookieButton` | `@intecion/ipal-kit/client` | Floating button that reopens the cookie settings (withdrawing consent); hidden while the banner is visible. Props `className`, `side` (`'left' \| 'right'`), `avoid` (selector it lifts above, default `COOKIE_BUTTON_AVOID` = footer; `false`). Tokens `--ipal-cookie-button-offset`, `--ipal-cookie-button-inset`. Type `CookieButtonProps`. |
| `COOKIE_BUTTON_AVOID`, `bottomOverlap(tops, viewportHeight)` | `@intecion/ipal-kit/client` | Default footer selector; pixels the footer covers at the bottom of the screen (how far the button moves up) |
| `CookieButton` | `@intecion/ipal-kit/client` | Floating button that reopens the cookie settings (withdrawing consent); hidden while the banner is visible. Fixed in the bottom corner of the window on every page and never moves (1.17.2: it no longer climbs above the footer). While it is shown the footer gets just enough bottom padding for its last row to end above the button (measured; the footer's own padding counts; nothing where the corner is empty; made before the first paint for a returning visitor). Props `className`, `side` (`'left' \| 'right'`), `reserve` (selector of the block that gets the room, default `COOKIE_BUTTON_RESERVE` = footer; `false` = none), `avoid` (placement before 1.17.2: selector it lifts above — `COOKIE_BUTTON_AVOID`). Amount by hand: `--ipal-cookie-button-space` on the footer (`0` = none). Tokens `--ipal-cookie-button-offset`, `--ipal-cookie-button-inset`. Type `CookieButtonProps`. |
| `COOKIE_BUTTON_AVOID`, `bottomOverlap(tops, viewportHeight)` | `@intecion/ipal-kit/client` | Footer selector for the placement before 1.17.2 (`<CookieButton avoid={COOKIE_BUTTON_AVOID} />`); pixels the footer covers at the bottom of the screen (how far the button moves up then) |
| `COOKIE_BUTTON_RESERVE`, `COOKIE_BUTTON_SPACE_ATTRIBUTE`, `reserveCookieButtonSpace(options)` | `@intecion/ipal-kit/client` | Default selector of the block that gets room for the cookie button (the footer); the attribute that marks it while the room is there; the function that measures and applies (or, with `release: true`, removes) it — options type `CookieButtonSpaceOptions` (`selector`, `side`, `button?`, `release?`, `sheet?`). For a button of your own |
| `consentDecidedScript({ version?, gpc?, cookieName? })` | `@intecion/ipal-kit` | JavaScript statements for an inline script: leave `true` in `d` when the browser holds a current consent decision (as `readConsentRecord` decides). The shared start of the plugin's pre-paint scripts |
| `TOTP_TEXTS`, `TOTP_VIEW_TITLE` | `@intecion/ipal-kit` | en/pl texts of the 2FA screens (`totpPlugin:*`, merged by `twoFactor`) and their tab title |
| `ConsentScript` | `@intecion/ipal-kit/client` | Loads an external script (`src` or `code`) only after consent for `category` — for vendors without Consent Mode (chat, Plausible etc.). Inside `ConsentProvider`. |
| `CookieTable` | `@intecion/ipal-kit/rsc` | Server Component: cookie table for the cookie policy page — `{ rows, labels?, locale?, categories?, caption?, classNames?, storageColumn?, storageTypes? }`; `rows` from `getCookieTable()`; a **Type** column when a row is local / session storage (`storageColumn: 'auto' \| boolean`). |
@@ -744,6 +751,7 @@ Most routes and metadata are already ready in `createContentHelpers` (`generateP
| `setRateLimitStore(store \| null)` | `@intecion/ipal-kit` | Shared store (e.g. Redis) for all plugin limiters (forms, consents, MCP…); `null` = process memory. Call once at startup when several instances run. |
| `setUnknownIpFactor(n)` | `@intecion/ipal-kit` | Requests with no client IP share one `unknown-ip` bucket with `n` × the limit (every plugin limiter). Call once at startup; `0` = unlimited (only with a limiter in front, e.g. Cloudflare). |
| `UNKNOWN_IP_FACTOR` | `@intecion/ipal-kit` | `20` — the default factor of the no-IP bucket. |
| `setIpv6Grouping({ prefix?, wide?, wideFactor? })`, `ipRateKey(ip)`, type `Ipv6Grouping` | `@intecion/ipal-kit` | 1.17.2: how every plugin limiter counts IPv6 — default one client per /64 (`prefix: 64`), no wide counter; `wide: 48` adds a counter per /48 at `wideFactor` (10) × the limit; `prefix: 128` = per address. Out-of-range values throw. `ipRateKey`: an IPv4 as it is, `::ffff:a.b.c.d` as the IPv4, an IPv6 as its network (`2001:db8:1:2:0:0:0:0/64`), anything else unchanged. |
**Types:** `ClientIpOptions` — `clientIp` options; `RateLimitStore` — store contract (`hit(id, cost, windowMs)` → `{ count, resetAt }`).
@@ -872,6 +880,9 @@ Bin: `iapl-doctor` (`pnpm exec iapl-doctor [dir] [--json] [--md] [--strict] [--f
| `runDeepProbe(ctx)` | `@intecion/ipal-kit/doctor` | `pnpm exec payload run …/dist/modules/doctor/probe.js` in the project → `DoctorStatus`. |
| `collectDoctorStatus(payload)` | `@intecion/ipal-kit/doctor` | Read-only counts: `usersWithout2fa`, `pendingCookies`, `plugin`, `node`. |
| `buildDoctorEndpoint({ tokenVar, access })` | `@intecion/ipal-kit/doctor` | `GET /ipal/doctor` (`/api/ipal/doctor`): 404 until the token variable (default `IAPL_DOCTOR_TOKEN`, ≥ 32 chars) is set, Bearer token or `access`, rate-limited. Added by `iapl` unless `doctor: false`. |
| `jobsRunAccess({ secretVar? })` | `@intecion/ipal-kit` | The rule iapl puts on `jobs.access.run` when the project writes none: `cronSecretMatches(req, process.env[secretVar])` or an admin with the second factor. Reuse it in your own rule: `run: (a) => jobsRunAccess()(a) \|\| myCheck(a)`. Type `JobsRunAccessOptions`. |
| `withJobsRunAccess(config, options \| false)` / `jobsRunNotice(config)` | `@intecion/ipal-kit` | The config with that rule (only when `jobs.access.run` is missing; marks `custom.iapl.jobsRunDefault`); the start-up line when the queue is on and the secret is missing (null otherwise). |
| `cronSecretMatches(req, secret)`, `CRON_SECRET_ENV`, `CRON_SECRET_MIN_LENGTH` | `@intecion/ipal-kit` | `Authorization: Bearer <secret>` compared in constant time; an unset or shorter-than-16 secret never matches. Default variable `CRON_SECRET`. |
| `runRouteCheck({ config, appDir?, snapshot?, update?, graphql?, cwd?, log? })` | `@intecion/ipal-kit/doctor` | `routes:check`: every public route (REST, GraphQL, Next route files) against the judged snapshot (default `e2e/routes.snapshot.json`); returns 1 on a route nobody judged or an entry without a reason; `update` writes new routes with an empty reason. Template: `iapl-audit/resources/routes.template.ts` (security.md "Routes nobody has judged"). Type `RunRouteCheckOptions`. |
| `listPublicRoutes(config, { graphqlSchema?, routeFiles? })` | `@intecion/ipal-kit` | Stable ids of every door a built config opens: `GET /api/users/me`, `graphql mutation loginUser`, `next GET /sitemap.xml`. From the config only (same on every database). Types `RouteInventoryOptions`, `GraphqlSchemaLike` (`getQueryType` / `getMutationType`). |
| `listNextRouteFiles(files, read)` | `@intecion/ipal-kit` | Next route handlers of an app directory (`route.ts` with the methods it exports, `robots.ts`, `sitemap.ts`, `manifest.ts`; route groups left out). |
+41 -1
View File
@@ -25,6 +25,46 @@ the MANDATORY SET (GEO: llms-full, Markdown, MCP; R2; Turnstile through
`getTurnstileConfig`…). Wire each one according to PROGRAMISTA §2 — it is part of the update,
not an extra. Skip one only with a client decision in `AGENTS.md` (`iapl-audit-skip:`).
**→ 1.18.0, sign-in (CHANGELOG 1.18.0; access.md "A stranger cannot lock a staff account out", "Staff sign-in only
from the site's own origin", "Changing one's own e-mail or password asks for the current password") — no schema change,
no migration, no import-map change; read before deploying:**
1. `IAPL_IP_HEADER` must be pinned in production (`x-forwarded-for` behind Coolify/Traefik): failed staff sign-ins are
counted per client IP and address. Without it every visitor shares one bucket (20× the limit).
2. A staff collection with its own `auth.maxLoginAttempts` / `lockTime` keeps them; otherwise Payload's lock is now 50
failures for an hour (beside 5 per IP and address in 15 minutes). Payload's behaviour back: `accounts: { signInLimit: false }`.
3. A panel or front end that signs **staff** in from another domain: `accounts: { signInSameOrigin: { origins: ['https://…'] } }`
(or `false`). A proxy that rewrites `Host`: set `serverURL`. Customer / visitor logins are not affected.
4. Scripts or integrations that change their OWN e-mail or password over the API send `currentPassword`; editors
see "Current password" on their account page. Off: `accounts: { confirmOwnChanges: false }`.
**Check:** five wrong passwords for an editor from one address → `429` there, `200` from another; the account page
shows "Current password"; `curl -X POST <site>/api/users/login -H 'Origin: https://other.example' …` → `403`.
**→ 1.17.2, security (CHANGELOG 1.17.2; PROGRAMISTA §6, items 84–87) — nothing required, check:** `readVersions:
readPublished()` now works (a wrapper of your own around it: use `readPublishedVersions()` inside); behind a proxy
that rewrites `Host` without `X-Forwarded-Host`, set `serverURL` or the panel's mail / cookie buttons answer 403
(`iapl-doctor` warns); a locked editor sees "incorrect" until the lock ends (`accounts.lockedAnswer: 'payload'` for
Payload's text); saving Cookies with a lower consent version is refused (`cookieSettings.allowLowerPolicyVersion`).
**Check:** `curl -s <site>/api/pages/versions` as a visitor → 200 (published only), not 500.
**→ 1.17.2:** (1) Payload jobs: if the project has tasks or workflows and a cron calls `/api/payload-jobs/run` (or
`/handle-schedules`) without its own `jobs.access.run`, set `CRON_SECRET` (16+ characters) in the app's environment
and send `Authorization: Bearer <CRON_SECRET>` from the cron; in-process runs (`jobs.autoRun`, `payload jobs:run`)
and an admin's API key need nothing (security.md "Payload's job queue"). Verify: the run route answers 401 without
the header, 200 with it. (2) A front end that posted to `/api/form-submissions` as a customer account (not through
`submitForm`): move it to `submitForm` / `createSubmitAction`, or set `forms.formSubmissionOverrides.access.create`.
(3) A site with a visitor login collection: `iapl-doctor --url …` lists `visitor-writes`; give each listed collection
and global its own write rule (`adminOrEditor`). (4) If the project has `tests/routes.ts`: `update`, judge, commit.
**→ 1.17.2, cookie button (CHANGELOG 1.17.2; PROGRAMISTA §6, item 83; consent.md "Where the cookie button sits") — nothing is required:**
visitors now see the "cookie settings" button in the bottom corner of the window on every page; it never moves and
no longer rides up above the footer. While it is shown the footer is a little taller (about 40 px on the reference
site), so its last row ends above the button. Check the end of a page on a phone and on desktop: nothing under the
button, the last footer link can be tapped. Bottom padding a project added by hand for the button: remove it (the
plugin counts existing padding, so it is not doubled, but it is no longer needed). Amount by hand:
`--ipal-cookie-button-space` on the footer (`0` = none); no room: `reserve={false}`. The placement before:
`cookieButton={<CookieButton avoid={COOKIE_BUTTON_AVOID} />}` on `SiteProviders`. A project e2e that expects the button
above the footer, or an exact footer height after a decision: update it.
**→ 1.17.1:** (1) `src/proxy.ts`: replace the matcher literal with
`['/((?!(?:api|admin|_next)(?:/|$)|.*\\..*).*)']` (i18n.md "Next matcher"; `iapl-doctor` rule `proxy-matcher`).
The old one skipped every page whose first segment only starts with `api`, `admin` or `_next` (`/administracja`):
@@ -252,7 +292,7 @@ and the browser tab shows the same separator.
cookie banner only through `--ipal-*-dark`: check the banner in the dark theme.
4. Optional: the block library, block by block (block-library.md); after turning blocks on: `pnpm generate:types`,
`pnpm payload generate:importmap`, Postgres/SQLite `migrate:create`.
5. **CookieButton** lifts above the footer — check a site with its own fixed footer bar; `avoid={false}` keeps it fixed.
5. **CookieButton** lifts above the footer — check a site with its own fixed footer bar; `avoid={false}` keeps it fixed. (Since 1.17.2 it stays in the bottom corner by default; the lift is `avoid={COOKIE_BUTTON_AVOID}`.)
6. `pnpm exec iapl-skills` (new **iapl-doctor**; updated iapl-reference, iapl-setup, iapl-site, iapl-audit).
7. Run `pnpm exec iapl-doctor` (and `--url https://<site>`), fix or silence each finding with a reason in
`iapl-doctor.json`. `IAPL_DOCTOR_TOKEN` (≥ 32 characters) only if the deep check runs against production.
+1 -1
View File
@@ -47,7 +47,7 @@ Write everything in this file in English.
<!-- /starter:decisions -->
<!-- iapl:start -->
## IAPL 1.17.1 — agent guide
## IAPL 1.17.2 — agent guide
<!-- Managed by `pnpm exec iapl-skills` — edits between the markers are overwritten. -->
This project is built on `@intecion/ipal-kit` (a Payload CMS 3 plugin). Before you write code:
+11 -1
View File
@@ -36,7 +36,7 @@ async function signIn(caller: Caller, baseURL: string, playwright: { request: {
async function ask(api: APIRequestContext, door: (typeof DOORS)[number]): Promise<DoorAnswer> {
const res = door.graphql
? await api.post('/api/graphql', { data: { query: door.graphql } })
: await api.fetch(door.path!, { data: door.body, maxRedirects: 0, method: door.method ?? 'GET' })
: await api.fetch(door.path!, { data: door.body, headers: door.headers, maxRedirects: 0, method: door.method ?? 'GET' })
const text = await res.text()
let body: unknown = text
try {
@@ -72,6 +72,16 @@ for (const caller of ['anonymous', 'customer', 'editor'] as const) {
})
}
test.describe('closed doors: the cron secret opens the job queue (IAWL idea 35, 1.17.2)', () => {
test('Authorization: Bearer <CRON_SECRET> runs the queue; nothing else changes', async ({ baseURL, playwright }) => {
test.skip(lateStaff !== '1' || !process.env.CRON_SECRET, 'needs the fixture\'s job queue (E2E_LATE_STAFF=1) and CRON_SECRET (pnpm e2e:built sets both)')
const cron = await playwright.request.newContext({ baseURL, extraHTTPHeaders: { authorization: `Bearer ${process.env.CRON_SECRET}` } })
const res = await cron.get('/api/payload-jobs/run?limit=1')
expect([res.status(), await res.text()]).toEqual([200, expect.any(String)])
await cron.dispose()
})
})
test.describe('closed doors: the proxy skips /api, /admin and /_next as whole segments only (IAWL idea 36)', () => {
test('the admin and the API are not sent to a locale; a page that only starts with those letters is', async ({ request }) => {
for (const path of ['/admin', '/api/health']) {
+17 -20
View File
@@ -24,6 +24,8 @@ export type Door = {
closed?: (answer: DoorAnswer, ctx: { email?: string }) => boolean
closedFor: Caller[]
graphql?: string
/** Extra request headers (e.g. a wrong bearer token). */
headers?: Record<string, string>
method?: 'DELETE' | 'GET' | 'PATCH' | 'POST'
name: string
/** Open for these callers while the owner decides (the finding's question). */
@@ -56,7 +58,11 @@ export const DOORS: Door[] = [
{ closedFor: ALL, name: 'the deep doctor status answers 404 without its token', path: '/api/ipal/doctor', closed: notFound },
// ---- jobs, schedules and call-backs (IAWL idea 35) ---------------------------------------------------------
{ closedFor: ALL, name: 'Payload\'s job queue has no run route (no jobs on this site)', path: '/api/payload-jobs/run', closed: notFound },
// the fixture's do-nothing task turns the queue on; since 1.17.2 (owner's Q2) only an admin or Bearer CRON_SECRET runs it
// (the "with the secret" case is its own test in closed-doors.spec.ts). Payload answers 401 when refused.
{ closedFor: ALL, name: 'Payload\'s job queue cannot be run (only an admin or the cron secret)', path: '/api/payload-jobs/run' },
{ closedFor: ALL, name: 'Payload\'s job schedules cannot be handled (only an admin or the cron secret)', path: '/api/payload-jobs/handle-schedules' },
{ closedFor: ALL, name: 'a wrong cron secret runs nothing', path: '/api/payload-jobs/run', headers: { authorization: 'Bearer not-the-cron-secret-not-the-cron-secret' } },
{ closedFor: ALL, method: 'POST', name: 'the crawler\'s call-back without its token', path: '/api/ipal/cookie-crawl/results', body: { jobId: 'x', ok: true } },
{ closedFor: OUTSIDERS, method: 'POST', name: 'a crawl cannot be started without the schedule\'s token', path: '/api/ipal/cookie-crawl' },
{ closedFor: OUTSIDERS, name: 'the crawl status', path: '/api/ipal/cookie-crawl' },
@@ -94,30 +100,21 @@ export const DOORS: Door[] = [
// ---- content and visitors' data --------------------------------------------------------------------------
{ closedFor: OUTSIDERS, name: 'form submissions (visitors\' personal data)', path: '/api/form-submissions' },
{ closedFor: OUTSIDERS, graphql: '{ FormSubmissions { docs { id } } }', closed: noData('FormSubmissions'), name: 'form submissions over GraphQL' },
{
body: { form: NO_ID, submissionData: [] },
closedFor: ['anonymous'],
method: 'POST',
name: 'a submission cannot be posted past submitForm (rate limit, Turnstile, consent, validation)',
openFor: { callers: ['customer'], question: 'Q1 (iawl-ideas-c-findings.md): any signed-in account may POST /api/form-submissions' },
path: '/api/form-submissions',
closed: forbidden,
},
// since 1.17.2 (owner's Q1): a staff account with its second factor only — an editor may (it reaches validation)
{ body: { form: NO_ID, submissionData: [] }, closedFor: OUTSIDERS, method: 'POST', name: 'a submission cannot be posted past submitForm (rate limit, Turnstile, consent, validation)', path: '/api/form-submissions', closed: forbidden },
{ body: {}, closedFor: OUTSIDERS, method: 'POST', name: 'Site settings cannot be saved', path: '/api/globals/site-settings', closed: forbidden },
{ body: {}, closedFor: OUTSIDERS, method: 'POST', name: 'Cookie settings (legal texts) cannot be saved', path: '/api/globals/cookie-settings', closed: forbidden },
{
body: {},
closedFor: ['anonymous'],
method: 'PATCH',
name: 'pages cannot be changed',
openFor: { callers: ['customer'], question: 'Q3: collections without their own write rules run on Payload\'s default (any signed-in account)' },
path: `/api/pages/${NO_ID}`,
closed: forbidden,
},
// the reference site's content has write rules of its own since 1.17.2 (owner's Q3, answer (b)): editors and admins
{ body: {}, closedFor: OUTSIDERS, method: 'PATCH', name: 'pages cannot be changed', path: `/api/pages/${NO_ID}`, closed: forbidden },
{ body: {}, closedFor: OUTSIDERS, method: 'PATCH', name: 'media cannot be changed', path: `/api/media/${NO_ID}`, closed: forbidden },
{ body: {}, closedFor: OUTSIDERS, method: 'POST', name: 'the header (navigation) cannot be saved', path: '/api/globals/header', closed: forbidden },
{ body: {}, closedFor: OUTSIDERS, method: 'POST', name: 'the company data cannot be saved', path: '/api/globals/company', closed: forbidden },
{
closedFor: ['anonymous'],
name: 'who edits what (Payload\'s document locks, with the editor\'s account)',
openFor: { callers: ['customer'], question: 'Q3: payload-locked-documents runs on Payload\'s default (any signed-in account)' },
// Payload's own collection: the plugin-wide default for it is the owner's Q3 answer (a), recorded for 2.0; the doctor's
// `visitor-writes` rule lists it on a site with a visitor login collection
openFor: { callers: ['customer'], question: 'Q3 (a), 2.0: payload-locked-documents runs on Payload\'s default (any signed-in account)' },
path: '/api/payload-locked-documents',
closed: forbidden,
},
+3
View File
@@ -20,6 +20,9 @@ export const e2eEarlyStaff: Plugin = (config: Config) =>
E2E_LATE_STAFF
? {
...config,
// one do-nothing task turns Payload's job queue on, so the closed-doors spec can ask its run route
// (no `jobs.access.run` here: iapl's default applies — an admin with the second factor, or Bearer CRON_SECRET)
jobs: { ...config.jobs, tasks: [...(config.jobs?.tasks ?? []), { slug: 'e2eNoop', handler: () => ({ output: {} }) }] },
collections: [
...(config.collections ?? []),
{ slug: 'e2e-crew', auth: true, fields: [{ name: 'roles', type: 'select', hasMany: true, options: ['user', 'editor', 'admin', 'boss'], saveToJWT: true }] },
+83 -83
View File
@@ -1,29 +1,29 @@
{
"$comment": "Every public door of this site: REST routes, GraphQL operations, Next route files. One line per entry: who may use it and why it is open (or that it is closed and to whom). A new route fails `routes:check` until somebody judges it here. `--update` adds new routes with an empty reason and drops gone ones. docs/security.md \"Routes nobody has judged\".",
"routes": {
"DELETE /api/caseStudies": "delete: Payload default (any signed-in account; one login collection here, so staff only — a visitor collection would reach it: owner Q3)",
"DELETE /api/caseStudies/:id": "deleteByID: Payload default (any signed-in account; one login collection here, so staff only — a visitor collection would reach it: owner Q3)",
"DELETE /api/caseStudies": "delete: editor+ (adminOrEditor, the site's own rule since 1.17.2; Payload's default would let any signed-in account in)",
"DELETE /api/caseStudies/:id": "deleteByID: editor+ (adminOrEditor, the site's own rule since 1.17.2; Payload's default would let any signed-in account in)",
"DELETE /api/consent-records": "delete: nobody over the API (create/update false); delete: admin; visitors write through POST /api/ipal/consent",
"DELETE /api/consent-records/:id": "deleteByID: nobody over the API (create/update false); delete: admin; visitors write through POST /api/ipal/consent",
"DELETE /api/cookie-review": "delete: create/update: editor+; delete: admin",
"DELETE /api/cookie-review/:id": "deleteByID: create/update: editor+; delete: admin",
"DELETE /api/form-submissions": "delete: create: any signed-in account (owner Q1); update: Payload default; delete: admin",
"DELETE /api/form-submissions/:id": "deleteByID: create: any signed-in account (owner Q1); update: Payload default; delete: admin",
"DELETE /api/form-submissions": "delete: create: a staff account with its second factor (1.17.2; the site submits through submitForm); update: nobody (form-builder); delete: admin",
"DELETE /api/form-submissions/:id": "deleteByID: create: a staff account with its second factor (1.17.2; the site submits through submitForm); update: nobody (form-builder); delete: admin",
"DELETE /api/forms": "delete: editor+ (staffAccess)",
"DELETE /api/forms/:id": "deleteByID: editor+ (staffAccess)",
"DELETE /api/media": "delete: Payload default (any signed-in account; one login collection here, so staff only — a visitor collection would reach it: owner Q3)",
"DELETE /api/media/:id": "deleteByID: Payload default (any signed-in account; one login collection here, so staff only — a visitor collection would reach it: owner Q3)",
"DELETE /api/pages": "delete: Payload default (any signed-in account; one login collection here, so staff only — a visitor collection would reach it: owner Q3)",
"DELETE /api/pages/:id": "deleteByID: Payload default (any signed-in account; one login collection here, so staff only — a visitor collection would reach it: owner Q3)",
"DELETE /api/media": "delete: editor+ (adminOrEditor, the site's own rule since 1.17.2; Payload's default would let any signed-in account in)",
"DELETE /api/media/:id": "deleteByID: editor+ (adminOrEditor, the site's own rule since 1.17.2; Payload's default would let any signed-in account in)",
"DELETE /api/pages": "delete: editor+ (adminOrEditor, the site's own rule since 1.17.2; Payload's default would let any signed-in account in)",
"DELETE /api/pages/:id": "deleteByID: editor+ (adminOrEditor, the site's own rule since 1.17.2; Payload's default would let any signed-in account in)",
"DELETE /api/payload-kv": "delete: nobody (every rule false)",
"DELETE /api/payload-kv/:id": "deleteByID: nobody (every rule false)",
"DELETE /api/payload-locked-documents": "delete: Payload default: any signed-in account (owner Q3)",
"DELETE /api/payload-locked-documents/:id": "deleteByID: Payload default: any signed-in account (owner Q3)",
"DELETE /api/payload-locked-documents": "delete: Payload default: any signed-in account (the plugin-wide default is owner's Q3 (a), 2.0; the doctor's visitor-writes lists it)",
"DELETE /api/payload-locked-documents/:id": "deleteByID: Payload default: any signed-in account (the plugin-wide default is owner's Q3 (a), 2.0; the doctor's visitor-writes lists it)",
"DELETE /api/payload-preferences": "delete: own preferences only (Payload)",
"DELETE /api/payload-preferences/:id": "deleteByID: own preferences only (Payload)",
"DELETE /api/payload-preferences/:key": "deleteByID: own preferences only (Payload)",
"DELETE /api/posts": "delete: Payload default (any signed-in account; one login collection here, so staff only — a visitor collection would reach it: owner Q3)",
"DELETE /api/posts/:id": "deleteByID: Payload default (any signed-in account; one login collection here, so staff only — a visitor collection would reach it: owner Q3)",
"DELETE /api/posts": "delete: editor+ (adminOrEditor, the site's own rule since 1.17.2; Payload's default would let any signed-in account in)",
"DELETE /api/posts/:id": "deleteByID: editor+ (adminOrEditor, the site's own rule since 1.17.2; Payload's default would let any signed-in account in)",
"DELETE /api/users": "delete: create/delete/unlock: an admin with the second factor; update: admin or self; roles field: admin",
"DELETE /api/users/:id": "deleteByID: create/delete/unlock: an admin with the second factor; update: admin or self; roles field: admin",
"GET /api/access": "Payload: the signed-in account's permissions (what the panel may show); anonymous gets an empty map",
@@ -101,11 +101,11 @@
"GET /api/payload-kv/count": "count: nobody (Payload: every rule false; the plugin keeps 2FA counts and the mail-service token here)",
"GET /api/payload-kv/versions": "versions: readVersions = read (nobody (Payload: every rule false; the plugin keeps 2FA counts and the mail-service token here)); no version history kept here",
"GET /api/payload-kv/versions/:id": "versionByID: readVersions = read (nobody (Payload: every rule false; the plugin keeps 2FA counts and the mail-service token here)); no version history kept here",
"GET /api/payload-locked-documents": "find: Payload default: any signed-in account (owner Q3)",
"GET /api/payload-locked-documents/:id": "findByID: Payload default: any signed-in account (owner Q3)",
"GET /api/payload-locked-documents/count": "count: Payload default: any signed-in account (owner Q3)",
"GET /api/payload-locked-documents/versions": "versions: readVersions = read (Payload default: any signed-in account (owner Q3)); no version history kept here",
"GET /api/payload-locked-documents/versions/:id": "versionByID: readVersions = read (Payload default: any signed-in account (owner Q3)); no version history kept here",
"GET /api/payload-locked-documents": "find: Payload default: any signed-in account (the plugin-wide default is owner's Q3 (a), 2.0; the doctor's visitor-writes lists it)",
"GET /api/payload-locked-documents/:id": "findByID: Payload default: any signed-in account (the plugin-wide default is owner's Q3 (a), 2.0; the doctor's visitor-writes lists it)",
"GET /api/payload-locked-documents/count": "count: Payload default: any signed-in account (the plugin-wide default is owner's Q3 (a), 2.0; the doctor's visitor-writes lists it)",
"GET /api/payload-locked-documents/versions": "versions: readVersions = read (Payload default: any signed-in account (the plugin-wide default is owner's Q3 (a), 2.0; the doctor's visitor-writes lists it)); no version history kept here",
"GET /api/payload-locked-documents/versions/:id": "versionByID: readVersions = read (Payload default: any signed-in account (the plugin-wide default is owner's Q3 (a), 2.0; the doctor's visitor-writes lists it)); no version history kept here",
"GET /api/payload-preferences": "find: the signed-in account's own preferences only (Payload)",
"GET /api/payload-preferences/:id": "findByID: the signed-in account's own preferences only (Payload)",
"GET /api/payload-preferences/:key": "findByID: the signed-in account's own preferences only (Payload)",
@@ -124,36 +124,36 @@
"GET /api/users/me": "Payload: the signed-in account itself, or null; no other account",
"GET /api/users/versions": "versions: readVersions = read (an admin, or the account itself (adminOrSelfIn users)); no version history kept here",
"GET /api/users/versions/:id": "versionByID: readVersions = read (an admin, or the account itself (adminOrSelfIn users)); no version history kept here",
"PATCH /api/caseStudies": "update: Payload default (any signed-in account; one login collection here, so staff only — a visitor collection would reach it: owner Q3)",
"PATCH /api/caseStudies/:id": "updateByID: Payload default (any signed-in account; one login collection here, so staff only — a visitor collection would reach it: owner Q3)",
"PATCH /api/caseStudies": "update: editor+ (adminOrEditor, the site's own rule since 1.17.2; Payload's default would let any signed-in account in)",
"PATCH /api/caseStudies/:id": "updateByID: editor+ (adminOrEditor, the site's own rule since 1.17.2; Payload's default would let any signed-in account in)",
"PATCH /api/consent-records": "update: nobody over the API (create/update false); delete: admin; visitors write through POST /api/ipal/consent",
"PATCH /api/consent-records/:id": "updateByID: nobody over the API (create/update false); delete: admin; visitors write through POST /api/ipal/consent",
"PATCH /api/cookie-review": "update: create/update: editor+; delete: admin",
"PATCH /api/cookie-review/:id": "updateByID: create/update: editor+; delete: admin",
"PATCH /api/form-submissions": "update: create: any signed-in account (owner Q1); update: Payload default; delete: admin",
"PATCH /api/form-submissions/:id": "updateByID: create: any signed-in account (owner Q1); update: Payload default; delete: admin",
"PATCH /api/form-submissions": "update: create: a staff account with its second factor (1.17.2; the site submits through submitForm); update: nobody (form-builder); delete: admin",
"PATCH /api/form-submissions/:id": "updateByID: create: a staff account with its second factor (1.17.2; the site submits through submitForm); update: nobody (form-builder); delete: admin",
"PATCH /api/forms": "update: editor+ (staffAccess)",
"PATCH /api/forms/:id": "updateByID: editor+ (staffAccess)",
"PATCH /api/media": "update: Payload default (any signed-in account; one login collection here, so staff only — a visitor collection would reach it: owner Q3)",
"PATCH /api/media/:id": "updateByID: Payload default (any signed-in account; one login collection here, so staff only — a visitor collection would reach it: owner Q3)",
"PATCH /api/pages": "update: Payload default (any signed-in account; one login collection here, so staff only — a visitor collection would reach it: owner Q3)",
"PATCH /api/pages/:id": "updateByID: Payload default (any signed-in account; one login collection here, so staff only — a visitor collection would reach it: owner Q3)",
"PATCH /api/media": "update: editor+ (adminOrEditor, the site's own rule since 1.17.2; Payload's default would let any signed-in account in)",
"PATCH /api/media/:id": "updateByID: editor+ (adminOrEditor, the site's own rule since 1.17.2; Payload's default would let any signed-in account in)",
"PATCH /api/pages": "update: editor+ (adminOrEditor, the site's own rule since 1.17.2; Payload's default would let any signed-in account in)",
"PATCH /api/pages/:id": "updateByID: editor+ (adminOrEditor, the site's own rule since 1.17.2; Payload's default would let any signed-in account in)",
"PATCH /api/payload-kv": "update: nobody (every rule false)",
"PATCH /api/payload-kv/:id": "updateByID: nobody (every rule false)",
"PATCH /api/payload-locked-documents": "update: Payload default: any signed-in account (owner Q3)",
"PATCH /api/payload-locked-documents/:id": "updateByID: Payload default: any signed-in account (owner Q3)",
"PATCH /api/payload-locked-documents": "update: Payload default: any signed-in account (the plugin-wide default is owner's Q3 (a), 2.0; the doctor's visitor-writes lists it)",
"PATCH /api/payload-locked-documents/:id": "updateByID: Payload default: any signed-in account (the plugin-wide default is owner's Q3 (a), 2.0; the doctor's visitor-writes lists it)",
"PATCH /api/payload-preferences": "update: own preferences only (Payload)",
"PATCH /api/payload-preferences/:id": "updateByID: own preferences only (Payload)",
"PATCH /api/posts": "update: Payload default (any signed-in account; one login collection here, so staff only — a visitor collection would reach it: owner Q3)",
"PATCH /api/posts/:id": "updateByID: Payload default (any signed-in account; one login collection here, so staff only — a visitor collection would reach it: owner Q3)",
"PATCH /api/posts": "update: editor+ (adminOrEditor, the site's own rule since 1.17.2; Payload's default would let any signed-in account in)",
"PATCH /api/posts/:id": "updateByID: editor+ (adminOrEditor, the site's own rule since 1.17.2; Payload's default would let any signed-in account in)",
"PATCH /api/users": "update: create/delete/unlock: an admin with the second factor; update: admin or self; roles field: admin",
"PATCH /api/users/:id": "updateByID: create/delete/unlock: an admin with the second factor; update: admin or self; roles field: admin",
"POST /api/admin/remove-user-totp": "2FA: an admin removes another account's second factor",
"POST /api/admin/reset-user-totp": "2FA: an admin resets another account's second factor",
"POST /api/caseStudies": "create: Payload default (any signed-in account; one login collection here, so staff only — a visitor collection would reach it: owner Q3)",
"POST /api/caseStudies/:id/duplicate": "duplicate: Payload default (any signed-in account; one login collection here, so staff only — a visitor collection would reach it: owner Q3)",
"POST /api/caseStudies": "create: editor+ (adminOrEditor, the site's own rule since 1.17.2; Payload's default would let any signed-in account in)",
"POST /api/caseStudies/:id/duplicate": "duplicate: editor+ (adminOrEditor, the site's own rule since 1.17.2; Payload's default would let any signed-in account in)",
"POST /api/caseStudies/access/:id?": "the signed-in account's own permissions on caseStudies",
"POST /api/caseStudies/versions/:id": "restore a version: Payload default (any signed-in account; one login collection here, so staff only — a visitor collection would reach it: owner Q3)",
"POST /api/caseStudies/versions/:id": "restore a version: editor+ (adminOrEditor, the site's own rule since 1.17.2; Payload's default would let any signed-in account in)",
"POST /api/consent-records": "create: nobody over the API (create/update false); delete: admin; visitors write through POST /api/ipal/consent",
"POST /api/consent-records/:id/duplicate": "duplicate: nobody over the API (create/update false); delete: admin; visitors write through POST /api/ipal/consent",
"POST /api/consent-records/access/:id?": "the signed-in account's own permissions on consent-records",
@@ -162,29 +162,29 @@
"POST /api/cookie-review/:id/duplicate": "duplicate: create/update: editor+; delete: admin",
"POST /api/cookie-review/access/:id?": "the signed-in account's own permissions on cookie-review",
"POST /api/cookie-review/versions/:id": "restore a version: create/update: editor+; delete: admin",
"POST /api/form-submissions": "create: create: any signed-in account (owner Q1); update: Payload default; delete: admin",
"POST /api/form-submissions/:id/duplicate": "duplicate: create: any signed-in account (owner Q1); update: Payload default; delete: admin",
"POST /api/form-submissions": "create: a staff account with its second factor (1.17.2; the site submits through submitForm); update: nobody (form-builder); delete: admin",
"POST /api/form-submissions/:id/duplicate": "duplicate: create: a staff account with its second factor (1.17.2; the site submits through submitForm); update: nobody (form-builder); delete: admin",
"POST /api/form-submissions/access/:id?": "the signed-in account's own permissions on form-submissions",
"POST /api/form-submissions/versions/:id": "restore a version: create: any signed-in account (owner Q1); update: Payload default; delete: admin",
"POST /api/form-submissions/versions/:id": "restore a version: create: a staff account with its second factor (1.17.2; the site submits through submitForm); update: nobody (form-builder); delete: admin",
"POST /api/forms": "create: editor+ (staffAccess)",
"POST /api/forms/:id/duplicate": "duplicate: editor+ (staffAccess)",
"POST /api/forms/access/:id?": "the signed-in account's own permissions on forms",
"POST /api/forms/versions/:id": "restore a version: editor+ (staffAccess)",
"POST /api/globals/company": "update: Payload default (any signed-in account; one login collection here, so staff only — a visitor collection would reach it: owner Q3)",
"POST /api/globals/company": "update: editor+ (adminOrEditor, the site's own rule since 1.17.2; Payload's default would let any signed-in account in)",
"POST /api/globals/company/access": "the signed-in account's own permissions on globals/company",
"POST /api/globals/company/versions/:id": "restore a version: Payload default (any signed-in account; one login collection here, so staff only — a visitor collection would reach it: owner Q3)",
"POST /api/globals/company/versions/:id": "restore a version: editor+ (adminOrEditor, the site's own rule since 1.17.2; Payload's default would let any signed-in account in)",
"POST /api/globals/cookie-crawl": "update: admin; the crawl endpoints write it after their own checks",
"POST /api/globals/cookie-crawl/access": "the signed-in account's own permissions on globals/cookie-crawl",
"POST /api/globals/cookie-crawl/versions/:id": "restore a version: admin; the crawl endpoints write it after their own checks",
"POST /api/globals/cookie-settings": "update: editor+",
"POST /api/globals/cookie-settings/access": "the signed-in account's own permissions on globals/cookie-settings",
"POST /api/globals/cookie-settings/versions/:id": "restore a version: editor+",
"POST /api/globals/footer": "update: Payload default (any signed-in account; one login collection here, so staff only — a visitor collection would reach it: owner Q3)",
"POST /api/globals/footer": "update: editor+ (adminOrEditor, the site's own rule since 1.17.2; Payload's default would let any signed-in account in)",
"POST /api/globals/footer/access": "the signed-in account's own permissions on globals/footer",
"POST /api/globals/footer/versions/:id": "restore a version: Payload default (any signed-in account; one login collection here, so staff only — a visitor collection would reach it: owner Q3)",
"POST /api/globals/header": "update: Payload default (any signed-in account; one login collection here, so staff only — a visitor collection would reach it: owner Q3)",
"POST /api/globals/footer/versions/:id": "restore a version: editor+ (adminOrEditor, the site's own rule since 1.17.2; Payload's default would let any signed-in account in)",
"POST /api/globals/header": "update: editor+ (adminOrEditor, the site's own rule since 1.17.2; Payload's default would let any signed-in account in)",
"POST /api/globals/header/access": "the signed-in account's own permissions on globals/header",
"POST /api/globals/header/versions/:id": "restore a version: Payload default (any signed-in account; one login collection here, so staff only — a visitor collection would reach it: owner Q3)",
"POST /api/globals/header/versions/:id": "restore a version: editor+ (adminOrEditor, the site's own rule since 1.17.2; Payload's default would let any signed-in account in)",
"POST /api/globals/notifications": "update: editor+",
"POST /api/globals/notifications/access": "the signed-in account's own permissions on globals/notifications",
"POST /api/globals/notifications/versions/:id": "restore a version: editor+",
@@ -205,22 +205,22 @@
"POST /api/ipal/forms/submit": "public by design: a form with files; the submitForm pipeline (rate limit, Turnstile, consent, validation, file checks)",
"POST /api/ipal/test-email": "send a test e-mail: admin",
"POST /api/ipal/two-factor/reset": "reset another account's 2FA set-up window: admin signed in with the second factor",
"POST /api/media": "create: Payload default (any signed-in account; one login collection here, so staff only — a visitor collection would reach it: owner Q3)",
"POST /api/media/:id/duplicate": "duplicate: Payload default (any signed-in account; one login collection here, so staff only — a visitor collection would reach it: owner Q3)",
"POST /api/media": "create: editor+ (adminOrEditor, the site's own rule since 1.17.2; Payload's default would let any signed-in account in)",
"POST /api/media/:id/duplicate": "duplicate: editor+ (adminOrEditor, the site's own rule since 1.17.2; Payload's default would let any signed-in account in)",
"POST /api/media/access/:id?": "the signed-in account's own permissions on media",
"POST /api/media/versions/:id": "restore a version: Payload default (any signed-in account; one login collection here, so staff only — a visitor collection would reach it: owner Q3)",
"POST /api/pages": "create: Payload default (any signed-in account; one login collection here, so staff only — a visitor collection would reach it: owner Q3)",
"POST /api/pages/:id/duplicate": "duplicate: Payload default (any signed-in account; one login collection here, so staff only — a visitor collection would reach it: owner Q3)",
"POST /api/media/versions/:id": "restore a version: editor+ (adminOrEditor, the site's own rule since 1.17.2; Payload's default would let any signed-in account in)",
"POST /api/pages": "create: editor+ (adminOrEditor, the site's own rule since 1.17.2; Payload's default would let any signed-in account in)",
"POST /api/pages/:id/duplicate": "duplicate: editor+ (adminOrEditor, the site's own rule since 1.17.2; Payload's default would let any signed-in account in)",
"POST /api/pages/access/:id?": "the signed-in account's own permissions on pages",
"POST /api/pages/versions/:id": "restore a version: Payload default (any signed-in account; one login collection here, so staff only — a visitor collection would reach it: owner Q3)",
"POST /api/pages/versions/:id": "restore a version: editor+ (adminOrEditor, the site's own rule since 1.17.2; Payload's default would let any signed-in account in)",
"POST /api/payload-kv": "create: nobody (every rule false)",
"POST /api/payload-kv/:id/duplicate": "duplicate: nobody (every rule false)",
"POST /api/payload-kv/access/:id?": "the signed-in account's own permissions on payload-kv",
"POST /api/payload-kv/versions/:id": "restore a version: nobody (every rule false)",
"POST /api/payload-locked-documents": "create: Payload default: any signed-in account (owner Q3)",
"POST /api/payload-locked-documents/:id/duplicate": "duplicate: Payload default: any signed-in account (owner Q3)",
"POST /api/payload-locked-documents": "create: Payload default: any signed-in account (the plugin-wide default is owner's Q3 (a), 2.0; the doctor's visitor-writes lists it)",
"POST /api/payload-locked-documents/:id/duplicate": "duplicate: Payload default: any signed-in account (the plugin-wide default is owner's Q3 (a), 2.0; the doctor's visitor-writes lists it)",
"POST /api/payload-locked-documents/access/:id?": "the signed-in account's own permissions on payload-locked-documents",
"POST /api/payload-locked-documents/versions/:id": "restore a version: Payload default: any signed-in account (owner Q3)",
"POST /api/payload-locked-documents/versions/:id": "restore a version: Payload default: any signed-in account (the plugin-wide default is owner's Q3 (a), 2.0; the doctor's visitor-writes lists it)",
"POST /api/payload-preferences": "create: own preferences only (Payload)",
"POST /api/payload-preferences/:id/duplicate": "duplicate: own preferences only (Payload)",
"POST /api/payload-preferences/:key": "updateByID: own preferences only (Payload)",
@@ -230,10 +230,10 @@
"POST /api/plugin-seo/generate-image": "SEO plugin (panel button): Payload default (signed-in account); nothing stored",
"POST /api/plugin-seo/generate-title": "SEO plugin (panel button): Payload default (signed-in account); nothing stored",
"POST /api/plugin-seo/generate-url": "SEO plugin (panel button): Payload default (signed-in account); nothing stored",
"POST /api/posts": "create: Payload default (any signed-in account; one login collection here, so staff only — a visitor collection would reach it: owner Q3)",
"POST /api/posts/:id/duplicate": "duplicate: Payload default (any signed-in account; one login collection here, so staff only — a visitor collection would reach it: owner Q3)",
"POST /api/posts": "create: editor+ (adminOrEditor, the site's own rule since 1.17.2; Payload's default would let any signed-in account in)",
"POST /api/posts/:id/duplicate": "duplicate: editor+ (adminOrEditor, the site's own rule since 1.17.2; Payload's default would let any signed-in account in)",
"POST /api/posts/access/:id?": "the signed-in account's own permissions on posts",
"POST /api/posts/versions/:id": "restore a version: Payload default (any signed-in account; one login collection here, so staff only — a visitor collection would reach it: owner Q3)",
"POST /api/posts/versions/:id": "restore a version: editor+ (adminOrEditor, the site's own rule since 1.17.2; Payload's default would let any signed-in account in)",
"POST /api/remove-totp": "2FA: the signed-in account's own second factor, fully signed in",
"POST /api/setup-totp": "2FA: sets up the signed-in account's own authenticator; same-origin only",
"POST /api/users": "create: create/delete/unlock: an admin with the second factor; update: admin or self; roles field: admin",
@@ -248,64 +248,64 @@
"POST /api/users/verify/:id": "public by design: needs the e-mailed verification token (verify is off on users)",
"POST /api/users/versions/:id": "restore a version: create/delete/unlock: an admin with the second factor; update: admin or self; roles field: admin",
"POST /api/verify-totp": "2FA (payload-2fa): the signed-in account's own code; same-origin only, 5 tries per account in 10 min",
"graphql mutation createCaseStudy": "GraphQL create: Payload default (any signed-in account; one login collection here, so staff only — a visitor collection would reach it: owner Q3)",
"graphql mutation createCaseStudy": "GraphQL create: editor+ (adminOrEditor, the site's own rule since 1.17.2; Payload's default would let any signed-in account in)",
"graphql mutation createConsentRecord": "GraphQL create: nobody over the API (create/update false); delete: admin; visitors write through POST /api/ipal/consent",
"graphql mutation createCookieReview": "GraphQL create: create/update: editor+; delete: admin",
"graphql mutation createForm": "GraphQL create: editor+ (staffAccess)",
"graphql mutation createFormSubmission": "GraphQL create: create: any signed-in account (owner Q1); update: Payload default; delete: admin",
"graphql mutation createMedia": "GraphQL create: Payload default (any signed-in account; one login collection here, so staff only — a visitor collection would reach it: owner Q3)",
"graphql mutation createPage": "GraphQL create: Payload default (any signed-in account; one login collection here, so staff only — a visitor collection would reach it: owner Q3)",
"graphql mutation createFormSubmission": "GraphQL create: a staff account with its second factor (1.17.2; the site submits through submitForm); update: nobody (form-builder); delete: admin",
"graphql mutation createMedia": "GraphQL create: editor+ (adminOrEditor, the site's own rule since 1.17.2; Payload's default would let any signed-in account in)",
"graphql mutation createPage": "GraphQL create: editor+ (adminOrEditor, the site's own rule since 1.17.2; Payload's default would let any signed-in account in)",
"graphql mutation createPayloadKv": "GraphQL create: nobody (every rule false)",
"graphql mutation createPayloadLockedDocument": "GraphQL create: Payload default: any signed-in account (owner Q3)",
"graphql mutation createPayloadLockedDocument": "GraphQL create: Payload default: any signed-in account (the plugin-wide default is owner's Q3 (a), 2.0; the doctor's visitor-writes lists it)",
"graphql mutation createPayloadPreference": "GraphQL create: own preferences only (Payload)",
"graphql mutation createPost": "GraphQL create: Payload default (any signed-in account; one login collection here, so staff only — a visitor collection would reach it: owner Q3)",
"graphql mutation createPost": "GraphQL create: editor+ (adminOrEditor, the site's own rule since 1.17.2; Payload's default would let any signed-in account in)",
"graphql mutation createUser": "GraphQL create: create/delete/unlock: an admin with the second factor; update: admin or self; roles field: admin",
"graphql mutation deleteCaseStudy": "GraphQL delete: Payload default (any signed-in account; one login collection here, so staff only — a visitor collection would reach it: owner Q3)",
"graphql mutation deleteCaseStudy": "GraphQL delete: editor+ (adminOrEditor, the site's own rule since 1.17.2; Payload's default would let any signed-in account in)",
"graphql mutation deleteConsentRecord": "GraphQL delete: nobody over the API (create/update false); delete: admin; visitors write through POST /api/ipal/consent",
"graphql mutation deleteCookieReview": "GraphQL delete: create/update: editor+; delete: admin",
"graphql mutation deleteForm": "GraphQL delete: editor+ (staffAccess)",
"graphql mutation deleteFormSubmission": "GraphQL delete: create: any signed-in account (owner Q1); update: Payload default; delete: admin",
"graphql mutation deleteMedia": "GraphQL delete: Payload default (any signed-in account; one login collection here, so staff only — a visitor collection would reach it: owner Q3)",
"graphql mutation deletePage": "GraphQL delete: Payload default (any signed-in account; one login collection here, so staff only — a visitor collection would reach it: owner Q3)",
"graphql mutation deleteFormSubmission": "GraphQL delete: create: a staff account with its second factor (1.17.2; the site submits through submitForm); update: nobody (form-builder); delete: admin",
"graphql mutation deleteMedia": "GraphQL delete: editor+ (adminOrEditor, the site's own rule since 1.17.2; Payload's default would let any signed-in account in)",
"graphql mutation deletePage": "GraphQL delete: editor+ (adminOrEditor, the site's own rule since 1.17.2; Payload's default would let any signed-in account in)",
"graphql mutation deletePayloadKv": "GraphQL delete: nobody (every rule false)",
"graphql mutation deletePayloadLockedDocument": "GraphQL delete: Payload default: any signed-in account (owner Q3)",
"graphql mutation deletePayloadLockedDocument": "GraphQL delete: Payload default: any signed-in account (the plugin-wide default is owner's Q3 (a), 2.0; the doctor's visitor-writes lists it)",
"graphql mutation deletePayloadPreference": "GraphQL delete: own preferences only (Payload)",
"graphql mutation deletePost": "GraphQL delete: Payload default (any signed-in account; one login collection here, so staff only — a visitor collection would reach it: owner Q3)",
"graphql mutation deletePost": "GraphQL delete: editor+ (adminOrEditor, the site's own rule since 1.17.2; Payload's default would let any signed-in account in)",
"graphql mutation deleteUser": "GraphQL delete: create/delete/unlock: an admin with the second factor; update: admin or self; roles field: admin",
"graphql mutation duplicateCaseStudy": "GraphQL duplicate: Payload default (any signed-in account; one login collection here, so staff only — a visitor collection would reach it: owner Q3)",
"graphql mutation duplicateCaseStudy": "GraphQL duplicate: editor+ (adminOrEditor, the site's own rule since 1.17.2; Payload's default would let any signed-in account in)",
"graphql mutation duplicateConsentRecord": "GraphQL duplicate: nobody over the API (create/update false); delete: admin; visitors write through POST /api/ipal/consent",
"graphql mutation duplicateCookieReview": "GraphQL duplicate: create/update: editor+; delete: admin",
"graphql mutation duplicateForm": "GraphQL duplicate: editor+ (staffAccess)",
"graphql mutation duplicateFormSubmission": "GraphQL duplicate: create: any signed-in account (owner Q1); update: Payload default; delete: admin",
"graphql mutation duplicateMedia": "GraphQL duplicate: Payload default (any signed-in account; one login collection here, so staff only — a visitor collection would reach it: owner Q3)",
"graphql mutation duplicatePage": "GraphQL duplicate: Payload default (any signed-in account; one login collection here, so staff only — a visitor collection would reach it: owner Q3)",
"graphql mutation duplicateFormSubmission": "GraphQL duplicate: create: a staff account with its second factor (1.17.2; the site submits through submitForm); update: nobody (form-builder); delete: admin",
"graphql mutation duplicateMedia": "GraphQL duplicate: editor+ (adminOrEditor, the site's own rule since 1.17.2; Payload's default would let any signed-in account in)",
"graphql mutation duplicatePage": "GraphQL duplicate: editor+ (adminOrEditor, the site's own rule since 1.17.2; Payload's default would let any signed-in account in)",
"graphql mutation duplicatePayloadKv": "GraphQL duplicate: nobody (every rule false)",
"graphql mutation duplicatePayloadLockedDocument": "GraphQL duplicate: Payload default: any signed-in account (owner Q3)",
"graphql mutation duplicatePayloadLockedDocument": "GraphQL duplicate: Payload default: any signed-in account (the plugin-wide default is owner's Q3 (a), 2.0; the doctor's visitor-writes lists it)",
"graphql mutation duplicatePayloadPreference": "GraphQL duplicate: own preferences only (Payload)",
"graphql mutation duplicatePost": "GraphQL duplicate: Payload default (any signed-in account; one login collection here, so staff only — a visitor collection would reach it: owner Q3)",
"graphql mutation duplicatePost": "GraphQL duplicate: editor+ (adminOrEditor, the site's own rule since 1.17.2; Payload's default would let any signed-in account in)",
"graphql mutation forgotPasswordUser": "public by design: the same answer for a real and an invented address",
"graphql mutation loginUser": "public by design: sign-in (as POST /api/users/login)",
"graphql mutation logoutUser": "public by design: ends the caller's own session",
"graphql mutation refreshTokenUser": "the signed-in account's own token only",
"graphql mutation resetPasswordUser": "public by design: needs the e-mailed reset token",
"graphql mutation unlockUser": "admin with the second factor (accounts.adminOnlyWrite)",
"graphql mutation updateCaseStudy": "GraphQL update: Payload default (any signed-in account; one login collection here, so staff only — a visitor collection would reach it: owner Q3)",
"graphql mutation updateCompany": "GraphQL update: Payload default (any signed-in account; one login collection here, so staff only — a visitor collection would reach it: owner Q3)",
"graphql mutation updateCaseStudy": "GraphQL update: editor+ (adminOrEditor, the site's own rule since 1.17.2; Payload's default would let any signed-in account in)",
"graphql mutation updateCompany": "GraphQL update: editor+ (adminOrEditor, the site's own rule since 1.17.2; Payload's default would let any signed-in account in)",
"graphql mutation updateConsentRecord": "GraphQL update: nobody over the API (create/update false); delete: admin; visitors write through POST /api/ipal/consent",
"graphql mutation updateCookieCrawl": "GraphQL update: admin; the crawl endpoints write it after their own checks",
"graphql mutation updateCookieReview": "GraphQL update: create/update: editor+; delete: admin",
"graphql mutation updateCookieSetting": "GraphQL update: editor+",
"graphql mutation updateFooter": "GraphQL update: Payload default (any signed-in account; one login collection here, so staff only — a visitor collection would reach it: owner Q3)",
"graphql mutation updateFooter": "GraphQL update: editor+ (adminOrEditor, the site's own rule since 1.17.2; Payload's default would let any signed-in account in)",
"graphql mutation updateForm": "GraphQL update: editor+ (staffAccess)",
"graphql mutation updateFormSubmission": "GraphQL update: create: any signed-in account (owner Q1); update: Payload default; delete: admin",
"graphql mutation updateHeader": "GraphQL update: Payload default (any signed-in account; one login collection here, so staff only — a visitor collection would reach it: owner Q3)",
"graphql mutation updateMedia": "GraphQL update: Payload default (any signed-in account; one login collection here, so staff only — a visitor collection would reach it: owner Q3)",
"graphql mutation updateFormSubmission": "GraphQL update: create: a staff account with its second factor (1.17.2; the site submits through submitForm); update: nobody (form-builder); delete: admin",
"graphql mutation updateHeader": "GraphQL update: editor+ (adminOrEditor, the site's own rule since 1.17.2; Payload's default would let any signed-in account in)",
"graphql mutation updateMedia": "GraphQL update: editor+ (adminOrEditor, the site's own rule since 1.17.2; Payload's default would let any signed-in account in)",
"graphql mutation updateNotification": "GraphQL update: editor+",
"graphql mutation updatePage": "GraphQL update: Payload default (any signed-in account; one login collection here, so staff only — a visitor collection would reach it: owner Q3)",
"graphql mutation updatePage": "GraphQL update: editor+ (adminOrEditor, the site's own rule since 1.17.2; Payload's default would let any signed-in account in)",
"graphql mutation updatePayloadKv": "GraphQL update: nobody (every rule false)",
"graphql mutation updatePayloadLockedDocument": "GraphQL update: Payload default: any signed-in account (owner Q3)",
"graphql mutation updatePayloadLockedDocument": "GraphQL update: Payload default: any signed-in account (the plugin-wide default is owner's Q3 (a), 2.0; the doctor's visitor-writes lists it)",
"graphql mutation updatePayloadPreference": "GraphQL update: own preferences only (Payload)",
"graphql mutation updatePost": "GraphQL update: Payload default (any signed-in account; one login collection here, so staff only — a visitor collection would reach it: owner Q3)",
"graphql mutation updatePost": "GraphQL update: editor+ (adminOrEditor, the site's own rule since 1.17.2; Payload's default would let any signed-in account in)",
"graphql mutation updateSiteIntegration": "GraphQL update: admin; secrets write-only",
"graphql mutation updateSiteSetting": "GraphQL update: editor+",
"graphql mutation updateUser": "GraphQL update: create/delete/unlock: an admin with the second factor; update: admin or self; roles field: admin",
@@ -332,8 +332,8 @@
"graphql query Pages": "GraphQL find: anyone (published content, no drafts)",
"graphql query PayloadKv": "GraphQL find: nobody (Payload: every rule false; the plugin keeps 2FA counts and the mail-service token here)",
"graphql query PayloadKvs": "GraphQL find: nobody (Payload: every rule false; the plugin keeps 2FA counts and the mail-service token here)",
"graphql query PayloadLockedDocument": "GraphQL find: Payload default: any signed-in account (owner Q3)",
"graphql query PayloadLockedDocuments": "GraphQL find: Payload default: any signed-in account (owner Q3)",
"graphql query PayloadLockedDocument": "GraphQL find: Payload default: any signed-in account (the plugin-wide default is owner's Q3 (a), 2.0; the doctor's visitor-writes lists it)",
"graphql query PayloadLockedDocuments": "GraphQL find: Payload default: any signed-in account (the plugin-wide default is owner's Q3 (a), 2.0; the doctor's visitor-writes lists it)",
"graphql query PayloadPreference": "GraphQL find: the signed-in account's own preferences only (Payload)",
"graphql query PayloadPreferences": "GraphQL find: the signed-in account's own preferences only (Payload)",
"graphql query Post": "GraphQL find: anyone (published content, no drafts)",
@@ -350,7 +350,7 @@
"graphql query countForms": "GraphQL count: anyone (the form renders from it; the Emails tab is staff-only by field access)",
"graphql query countPages": "GraphQL count: anyone (published content, no drafts)",
"graphql query countPayloadKvs": "GraphQL count: nobody (Payload: every rule false; the plugin keeps 2FA counts and the mail-service token here)",
"graphql query countPayloadLockedDocuments": "GraphQL count: Payload default: any signed-in account (owner Q3)",
"graphql query countPayloadLockedDocuments": "GraphQL count: Payload default: any signed-in account (the plugin-wide default is owner's Q3 (a), 2.0; the doctor's visitor-writes lists it)",
"graphql query countPayloadPreferences": "GraphQL count: the signed-in account's own preferences only (Payload)",
"graphql query countPosts": "GraphQL count: anyone (published content, no drafts)",
"graphql query countUsers": "GraphQL count: an admin, or the account itself (adminOrSelfIn users)",
+62
View File
@@ -0,0 +1,62 @@
import { type APIRequestContext, expect, test } from '@playwright/test'
import { randomUUID } from 'node:crypto'
import { totp } from './totp'
/**
* On the BUILT site (pnpm e2e:built, webpack and Turbopack), what 1.17.2 changed at the sign-in and in the panel:
* - a locked staff account answers its login exactly like a wrong password (accounts.lockedAnswer) — the hook
* recognises Payload's error by the name Payload gives it, which a minified bundle must keep;
* - the plugin's panel actions refuse a request from another origin (adminSameOrigin), the site's own still works.
* Needs the E2E_* test admin (e2e/create-test-admin.ts). The locked account is a fresh one made here, so the test
* admins are never locked.
*/
const { E2E_ADMIN_EMAIL: adminEmail, E2E_ADMIN_PASSWORD: password, E2E_TOTP_SECRET: secret } = process.env
let admin: APIRequestContext
test.beforeAll(async ({ baseURL, playwright }) => {
test.skip(!adminEmail || !password || !secret, 'E2E_ADMIN_* values are not set')
admin = await playwright.request.newContext({ baseURL, extraHTTPHeaders: { origin: baseURL! } })
expect((await admin.post('/api/users/login', { data: { email: adminEmail, password } })).status()).toBe(200)
expect((await (await admin.post('/api/verify-totp', { data: { token: totp(secret!) } })).json()).ok).toBe(true)
})
test.afterAll(async () => {
await admin?.dispose()
})
test('a locked staff account gets the wrong-password answer, REST and GraphQL', async ({ baseURL, playwright }) => {
const email = `locked-${randomUUID().slice(0, 8)}@example.com`
const own = `L-${randomUUID()}`
expect((await admin.post('/api/users', { data: { email, password: own, roles: ['editor'] } })).status()).toBe(201)
const anon = await playwright.request.newContext({ baseURL })
// the site reads the client address from IAPL_IP_HEADER (reference/.env: x-forwarded-for, one proxy)
const login = async (address: string, pass: string, ip = '203.0.113.150') => {
const res = await anon.post('/api/users/login', { data: { email: address, password: pass }, headers: { 'x-forwarded-for': ip } })
return { body: await res.text(), status: res.status() }
}
// 1.18.0 (accounts.signInLimit): one IP fails at most 5 times per address and Payload locks a staff account at 50
// failures — a spray from 50 IPs, one failure each, locks it
for (let i = 0; i < 50; i++) {await login(email, 'a-wrong-password-1', `198.51.100.${i + 1}`)}
const invented = await login(`nobody-${randomUUID().slice(0, 8)}@example.com`, 'a-wrong-password-1')
expect(invented.status).toBe(401)
expect(await login(email, own)).toEqual(invented)
const gql = async (address: string, pass: string) => {
const res = await anon.post('/api/graphql', { data: { query: `mutation { loginUser(email: ${JSON.stringify(address)}, password: ${JSON.stringify(pass)}) { token } }` } })
const error = ((await res.json()) as { errors?: { extensions?: { name?: string }; message: string }[] }).errors?.[0]
return { message: error?.message, name: error?.extensions?.name }
}
expect(await gql(email, own)).toEqual(await gql(`nobody-${randomUUID().slice(0, 8)}@example.com`, 'x-wrong-password-1'))
await anon.dispose()
})
test('panel actions: another origin gets 403 with the admin cookie, the site itself goes through', async ({ baseURL }) => {
const foreign = await admin.fetch('/api/ipal/cookie-approval', {
data: '{"ids":[]}',
headers: { 'content-type': 'text/plain', origin: 'https://blog.example.test', 'sec-fetch-site': 'same-site' },
method: 'POST',
})
expect(foreign.status()).toBe(403)
const own = await admin.fetch('/api/ipal/cookie-approval', { data: '{"ids":[]}', headers: { 'content-type': 'text/plain', origin: baseURL! }, method: 'POST' })
expect(own.status()).toBe(200)
})
+128
View File
@@ -493,6 +493,134 @@ test('consent: withdrawal — reopen, reject: analytics cookies and listed stora
expect((await consentRecord(context))!.state).toMatchObject({ analytics: false, functional: false, marketing: false })
})
// The "cookie settings" button stays in the bottom corner of the window (1.17.2) and never moves: not above the
// footer, not at the end of the page. The footer gets room under its last row while the button is shown, so the
// button covers nothing there (consent.md → "Where the cookie button sits").
const BUTTON_PAGES = ['/pl', '/pl/kontakt', '/en', '/pl/blog', '/pl/regulamin']
const buttonState = () => {
const b = document.querySelector<HTMLElement>('[data-ipal="cookie-button"]')
const footer = [...document.querySelectorAll<HTMLElement>('footer, [role="contentinfo"]')].at(-1)!
if (!b) {return { button: false, room: footer.hasAttribute('data-ipal-cookie-space') }}
const r = b.getBoundingClientRect()
const hits = (q: DOMRect) => q.width > 0 && q.height > 0 && q.right > r.left && q.left < r.right && q.bottom > r.top && q.top < r.bottom
// every piece of footer text and every control of the page that lies under the button
const under: string[] = []
const walker = document.createTreeWalker(footer, NodeFilter.SHOW_TEXT)
const range = document.createRange()
for (let node = walker.nextNode(); node; node = walker.nextNode()) {
if (!/\S/.test(node.nodeValue ?? '')) {continue}
range.selectNodeContents(node)
if ([...range.getClientRects()].some(hits)) {under.push(`text: ${node.nodeValue!.trim().slice(0, 24)}`)}
}
for (const el of document.querySelectorAll('a[href], button, input, select, textarea, summary')) {
if (el !== b && hits(el.getBoundingClientRect())) {under.push(`control: ${(el.textContent ?? '').trim().slice(0, 24)}`)}
}
return {
button: true,
gap: Math.round(window.innerHeight - r.bottom),
inFooter: !!b.closest('footer'),
left: Math.round(r.left),
position: getComputedStyle(b).position,
room: footer.hasAttribute('data-ipal-cookie-space'),
transform: getComputedStyle(b).transform,
under,
}
}
const CORNER = { button: true, gap: 16, inFooter: false, left: 16, position: 'fixed', transform: 'none' }
for (const device of [
{ name: 'desktop', viewport: { height: 800, width: 1280 } },
{ name: 'phone', viewport: { height: 844, width: 390 } },
{ name: 'small phone', viewport: { height: 640, width: 360 } },
]) {
for (const colorScheme of ['light', 'dark'] as const) {
test(`cookie button, ${device.name}, ${colorScheme}: the corner at every scroll position, nothing under it at the end, no layout shift`, async ({ browser }) => {
const context = await browser.newContext({ colorScheme, hasTouch: device.name !== 'desktop', viewport: device.viewport })
const page = await context.newPage()
await page.addInitScript(() => {
const w = window as unknown as { __cls: number }
w.__cls = 0
new PerformanceObserver((list) => {
for (const entry of list.getEntries() as unknown as { hadRecentInput: boolean; value: number }[]) {
if (!entry.hadRecentInput) {w.__cls += entry.value}
}
}).observe({ buffered: true, type: 'layout-shift' })
})
const shifts = () => page.evaluate(() => (window as unknown as { __cls: number }).__cls)
const footerPadding = () => page.evaluate(() => getComputedStyle([...document.querySelectorAll('footer')].at(-1)!).paddingBottom)
// before a decision: no button, the footer as the project made it
await page.goto('/pl')
await expect(page.locator('[data-ipal="banner"]')).toBeVisible()
expect(await page.evaluate(buttonState)).toEqual({ button: false, room: false })
const ownPadding = await footerPadding()
await page.locator('[data-ipal="reject"]').click()
const button = page.locator('[data-ipal="cookie-button"]')
for (const path of BUTTON_PAGES) {
// a returning visitor's page load: the room is there from the first paint, so nothing shifts when the button appears
await page.goto(path)
await expect(button).toBeVisible()
await page.waitForTimeout(400)
const height = await page.evaluate(() => document.documentElement.scrollHeight)
const end = Math.max(0, height - device.viewport.height)
for (const y of [0, end / 2, end - 40, end]) {
await page.evaluate((to) => window.scrollTo(0, to), y)
await page.waitForTimeout(250)
expect(await page.evaluate(buttonState), `${path} at ${Math.round(y)} of ${end}`).toMatchObject(CORNER)
}
// the very end of the page (measured now: a form or its Turnstile widget may have grown the page since)
await page.evaluate(() => window.scrollTo(0, document.documentElement.scrollHeight))
await page.waitForTimeout(250)
expect(await page.evaluate(() => Math.round(window.innerHeight + window.scrollY - document.documentElement.scrollHeight)), `${path}: at the end`).toBe(0)
expect(await page.evaluate(buttonState), `${path} at the very end`).toMatchObject(CORNER)
// no footer text and no control under the button
expect((await page.evaluate(buttonState)).under, `${path}: under the button at the end`).toEqual([])
// and every footer link can be clicked (Playwright refuses a click another element would receive)
const links = page.locator('footer a[href]')
const count = await links.count()
expect(count).toBeGreaterThan(3)
for (let i = 0; i < count; i++) {await links.nth(i).click({ timeout: 3000, trial: true })}
expect(await shifts(), `${path}: layout shift from load to the end of the page`).toBeLessThan(0.001)
}
// keyboard: reachable and it reopens the banner; the room goes with the button
await button.focus()
await expect(button).toBeFocused()
await page.keyboard.press('Enter')
await expect(page.locator('[data-ipal="banner"]')).toBeVisible()
expect(await page.evaluate(buttonState)).toEqual({ button: false, room: false })
await page.goto('/pl') // decided again? no: reopening does not undo the stored decision, the button is back
await expect(button).toBeVisible()
await page.locator('[data-ipal="cookie-button"]').click()
expect(await footerPadding(), 'banner open: the footer as before a decision').toBe(ownPadding)
await context.close()
})
}
}
test('cookie button: for a returning visitor the room is there before the page hydrates (no application script)', async ({ browser }) => {
const context = await browser.newContext({ hasTouch: true, viewport: { height: 844, width: 390 } })
const page = await context.newPage()
const padding = () => page.evaluate(() => parseFloat(getComputedStyle([...document.querySelectorAll('footer')].at(-1)!).paddingBottom))
await page.goto('/pl')
const own = await padding()
await page.locator('[data-ipal="reject"]').click()
await expect(page.locator('[data-ipal="cookie-button"]')).toBeVisible()
const live = await padding()
expect(live).toBeGreaterThan(own)
// the same page with every application script refused: only the inline script can have made the room
await page.route(isAppScript, (route) => route.abort())
await page.goto('/pl')
await expect(page.locator('[data-ipal="cookie-button"]')).toHaveCount(0)
// the same room, to the pixel or one off: here the web font may not have arrived yet, and the row's text box follows the font
expect(Math.abs((await padding()) - live)).toBeLessThanOrEqual(2)
expect(await padding()).toBeGreaterThan(own + 30)
// the server's markup is untouched (React hydrates it without a mismatch): the room is in a style sheet
expect(await page.evaluate(() => [...document.querySelectorAll('footer')].at(-1)!.getAttribute('style'))).toBeNull()
await context.close()
})
test('admin: sign in through 2FA, agency credit, panel link preview', async ({ page, request }) => {
const head = await (await request.get('/admin/login')).text()
expect(head).toMatch(/noindex/)
+3 -2
View File
@@ -1,6 +1,6 @@
import type { CollectionConfig } from 'payload'
import { buildRevalidateHook } from '@intecion/ipal-kit'
import { adminOrEditor, buildRevalidateHook } from '@intecion/ipal-kit'
import { revalidatePath } from 'next/cache'
import { i18nConfig } from '@/i18n.config'
@@ -13,7 +13,8 @@ const revalidate = buildRevalidateHook({ config: i18nConfig, revalidatePath })
export const CaseStudies: CollectionConfig = {
slug: 'caseStudies',
admin: { defaultColumns: ['title', 'publishedAt', 'updatedAt'], useAsTitle: 'title' },
access: { read: () => true },
// write rules of its own: Payload's default is "any signed-in account" — a visitor login collection would reach it (security.md "Visitor accounts")
access: { create: adminOrEditor, delete: adminOrEditor, read: () => true, update: adminOrEditor },
defaultSort: '-publishedAt',
fields: entryFields,
hooks: { afterChange: [revalidate.afterChange], afterDelete: [revalidate.afterDelete] },
+3 -1
View File
@@ -1,6 +1,7 @@
import type { CollectionConfig } from 'payload'
import {
adminOrEditor,
buildMediaPlaceholderField,
buildMediaPlaceholderHook,
buildOptimizeUploadField,
@@ -11,7 +12,8 @@ import {
/** media.md "Full collection", 1:1. */
export const Media: CollectionConfig = {
slug: 'media',
access: { read: () => true }, // public files; media are served by the app (/api/media/file/…)
// write rules of its own: Payload's default is "any signed-in account" — a visitor login collection would reach it (security.md "Visitor accounts")
access: { create: adminOrEditor, delete: adminOrEditor, read: () => true, update: adminOrEditor }, // public files; media are served by the app (/api/media/file/…)
upload: { focalPoint: true, mimeTypes: ['image/*', 'application/pdf', 'video/mp4', 'video/webm'] },
hooks: {
beforeOperation: [normalizeFilenameHook, buildOptimizeUploadHook(), buildMediaPlaceholderHook()],
+3 -1
View File
@@ -1,6 +1,7 @@
import type { CollectionConfig } from 'payload'
import {
adminOrEditor,
buildNoindexField,
buildPreventDeleteSystemPage,
buildRevalidateHook,
@@ -19,7 +20,8 @@ const revalidate = buildRevalidateHook({ config: i18nConfig, revalidatePath })
export const Pages: CollectionConfig = {
slug: 'pages',
admin: { defaultColumns: ['title', 'slug', 'updatedAt'], useAsTitle: 'title' },
access: { read: () => true },
// write rules of its own: Payload's default is "any signed-in account" — a visitor login collection would reach it (security.md "Visitor accounts")
access: { create: adminOrEditor, delete: adminOrEditor, read: () => true, update: adminOrEditor },
fields: [
{ name: 'title', type: 'text', localized: true, required: true },
buildSlugField({ from: 'title' }),
+3 -2
View File
@@ -1,6 +1,6 @@
import type { CollectionConfig } from 'payload'
import { buildRevalidateHook } from '@intecion/ipal-kit'
import { adminOrEditor, buildRevalidateHook } from '@intecion/ipal-kit'
import { revalidatePath } from 'next/cache'
import { i18nConfig } from '@/i18n.config'
@@ -13,7 +13,8 @@ const revalidate = buildRevalidateHook({ config: i18nConfig, revalidatePath })
export const Posts: CollectionConfig = {
slug: 'posts',
admin: { defaultColumns: ['title', 'publishedAt', 'updatedAt'], useAsTitle: 'title' },
access: { read: () => true },
// write rules of its own: Payload's default is "any signed-in account" — a visitor login collection would reach it (security.md "Visitor accounts")
access: { create: adminOrEditor, delete: adminOrEditor, read: () => true, update: adminOrEditor },
defaultSort: '-publishedAt',
fields: entryFields,
hooks: { afterChange: [revalidate.afterChange], afterDelete: [revalidate.afterDelete] },
+3 -2
View File
@@ -1,12 +1,13 @@
import type { GlobalConfig } from 'payload'
import { buildGlobalRevalidateHook, rowLabel } from '@intecion/ipal-kit'
import { adminOrEditor, buildGlobalRevalidateHook, rowLabel } from '@intecion/ipal-kit'
import { revalidatePath } from 'next/cache'
/** Company data for a PL market site: footer, contact block details, LocalBusiness JSON-LD. */
export const Company: GlobalConfig = {
slug: 'company',
access: { read: () => true },
// write rules of its own: Payload's default is "any signed-in account" — a visitor login collection would reach it (security.md "Visitor accounts")
access: { read: () => true, update: adminOrEditor },
fields: [
{ name: 'name', type: 'text', required: true },
{ name: 'legalName', type: 'text' },
+3 -2
View File
@@ -1,12 +1,13 @@
import type { GlobalConfig } from 'payload'
import { buildGlobalRevalidateHook, buildLinkField, rowLabel } from '@intecion/ipal-kit'
import { adminOrEditor, buildGlobalRevalidateHook, buildLinkField, rowLabel } from '@intecion/ipal-kit'
import { revalidatePath } from 'next/cache'
/** iapl-nav: link columns and a note. Legal links come from System pages (getSystemLinks), not from here. */
export const Footer: GlobalConfig = {
slug: 'footer',
access: { read: () => true },
// write rules of its own: Payload's default is "any signed-in account" — a visitor login collection would reach it (security.md "Visitor accounts")
access: { read: () => true, update: adminOrEditor },
fields: [
{
name: 'columns',
+3 -2
View File
@@ -1,12 +1,13 @@
import type { GlobalConfig } from 'payload'
import { buildGlobalRevalidateHook, buildLinkField, buildLinksField, rowLabel } from '@intecion/ipal-kit'
import { adminOrEditor, buildGlobalRevalidateHook, buildLinkField, buildLinksField, rowLabel } from '@intecion/ipal-kit'
import { revalidatePath } from 'next/cache'
/** iapl-nav: menu with one submenu level, a CTA button, the mobile menu label. Logo comes from Site settings. */
export const Header: GlobalConfig = {
slug: 'header',
access: { read: () => true },
// write rules of its own: Payload's default is "any signed-in account" — a visitor login collection would reach it (security.md "Visitor accounts")
access: { read: () => true, update: adminOrEditor },
fields: [
{
name: 'navItems',
+7 -2
View File
@@ -16,7 +16,9 @@
* "consent" test (banner at first paint, Global Privacy Control, equal prominence, withdrawal, the consent log)
* and e2e/sign-in-look.spec.ts (the sign-in panel in the first HTML, on a phone, the language links, the 2FA screen),
* e2e/own-account.spec.ts (1.18.0: the account page asks for the current password; staff sign-in failures per place;
* staff sign-in from another origin refused).
* staff sign-in from another origin refused);
* e2e/sign-in-answers.spec.ts (1.17.2: a locked staff account answers like a wrong password; the panel actions refuse
* another origin).
*
* Needs what the reference site's "Production check" needs (reference/README.md): reference/.env with a local,
* seeded database and the E2E_* test admin. The test admins are reset by Playwright's global setup.
@@ -26,6 +28,7 @@
* Options: --only=webpack | --only=turbopack; --skip-plugin-build (dist and the injected copy are current).
*/
import { spawnSync } from 'node:child_process'
import { randomBytes } from 'node:crypto'
import { existsSync, readdirSync, readFileSync, statSync, writeFileSync } from 'node:fs'
import path from 'node:path'
import { fileURLToPath } from 'node:url'
@@ -75,6 +78,8 @@ const restore = () => {
process.on('exit', restore)
for (const signal of ['SIGINT', 'SIGTERM']) {process.on(signal, () => process.exit(130))}
// the fixture's job queue is run by the closed-doors spec with this secret (a fresh one per run)
const cronSecret = randomBytes(24).toString('base64url')
const fixture = { E2E_LATE_STAFF: '1', NODE_OPTIONS: `${process.env.NODE_OPTIONS ?? ''} --max-old-space-size=3072`.trim() }
const passed = []
for (const bundler of bundlers) {
@@ -91,7 +96,7 @@ for (const bundler of bundlers) {
process.exit(1)
}
console.log(`[e2e:built] ✓ ${bundler}: no package manifest among ${files.length} public files`)
run(`${bundler}: the built site — late-staff spec, the mail service, closed doors, the published-files check, the client hints, consent and the sign-in look`, 'pnpm', ['exec', 'playwright', 'test', 'late-staff', 'mail-relay', 'closed-doors', 'smoke', 'sign-in-look', 'own-account', '--grep', 'late staff collection|the mail service|closed doors|no package.json is published|client hints|consent|sign-in look|own account|staff sign-in'], site, { ALLOW_LOCAL_MEDIA: process.env.ALLOW_LOCAL_MEDIA ?? '1', E2E_LATE_STAFF: '1' })
run(`${bundler}: the built site — late-staff spec, the mail service, closed doors, the published-files check, the client hints, consent, the sign-in look, the sign-in answers and the own account`, 'pnpm', ['exec', 'playwright', 'test', 'late-staff', 'mail-relay', 'closed-doors', 'smoke', 'sign-in-look', 'sign-in-answers', 'own-account', '--grep', 'late staff collection|the mail service|closed doors|no package.json is published|client hints|consent|sign-in look|locked staff account|panel actions|own account|staff sign-in'], site, { ALLOW_LOCAL_MEDIA: process.env.ALLOW_LOCAL_MEDIA ?? '1', CRON_SECRET: cronSecret, E2E_LATE_STAFF: '1' })
passed.push(bundler)
}
console.log(`\n[e2e:built] passed: ${passed.join(' and ')}. (The reference site's .next now holds the ${passed.at(-1)} build WITH the fixture: rebuild with \`pnpm build\` there before other checks.)`)
+1
View File
@@ -72,6 +72,7 @@ export const DESCRIPTIONS = {
'e2e/mail-relay.spec.ts': 'the mail service on a built site: the state block in the panel, the first e-mail through the public confirm route, no token in anything the browser receives',
'e2e/smtp-sink.ts': 'a local mail sink for the smoke tests: reads what the site really sent (recipients, attachments)',
'e2e/own-account.spec.ts': 'built-site test (pnpm e2e:built, 1.18.0): the account page asks for the current password before a new e-mail is saved (accounts.confirmOwnChanges); five failed staff sign-ins from one place answer 429 there, not elsewhere (accounts.signInLimit); a staff sign-in from another origin gets 403 (accounts.signInSameOrigin)',
'e2e/sign-in-answers.spec.ts': 'built-site test (pnpm e2e:built, 1.17.2): a locked staff account gets the wrong-password answer over REST and GraphQL (accounts.lockedAnswer); the plugin\'s panel actions refuse another origin and take the site\'s own (adminSameOrigin)',
'e2e/sign-in-look.spec.ts': 'browser test of the sign-in look (whiteLabel.signIn): the panel comes with the form, sits above it on a phone in both themes, is on forgot / reset / logout too, the language links work, the 2FA code screen keeps its boxes (now named)',
'e2e/two-factor-back.spec.ts': 'browser test of the 2FA screens\' `back` link (twoFactor.safeBack): a prepared link — script or another host — ends on the admin root, an ordinary one is followed',
'e2e/routes.snapshot.json': 'every public route of the site (REST, GraphQL, Next route files) with one line saying who may use it and why — the judged list `routes:check` compares with',
+4 -1
View File
@@ -24,14 +24,17 @@ export {
ConsentProvider,
ConsentScript,
COOKIE_BUTTON_AVOID,
COOKIE_BUTTON_RESERVE,
COOKIE_BUTTON_SPACE_ATTRIBUTE,
CookieBanner,
CookieButton,
readEffectiveConsent,
reserveCookieButtonSpace,
signalVendors,
useConsent,
useConsentContext,
} from '../modules/consent/client.js'
export type { CookieBannerAction, CookieBannerClassNames, CookieButtonProps, CookieSettingsAction } from '../modules/consent/client.js'
export type { CookieBannerAction, CookieBannerClassNames, CookieButtonProps, CookieButtonSpaceOptions, CookieSettingsAction } from '../modules/consent/client.js'
export { ConstructionNotice } from '../modules/construction/ConstructionNotice.js'
export type { ConstructionNoticeClassNames } from '../modules/construction/ConstructionNotice.js'
export { CONSTRUCTION_CLOSE_LABEL, CONSTRUCTION_CLOSE_LABEL_PL, constructionCloseLabel } from '../modules/construction/texts.js'
+37 -1
View File
@@ -1,8 +1,44 @@
import type { Field } from 'payload'
import type { Field, FieldHook, NumberField } from 'payload'
import { ValidationError } from 'payload'
import { iaplT } from '../../modules/admin-i18n/t.js'
import { rowLabel } from '../../modules/admin-ui/index.js'
import { consentCategoryOptions } from '../../modules/consent/categoryLabels.js'
/**
* Cookie settings → Consent version only goes up (1.17.2). A stored consent counts only under the version it was
* given for, so a LOWER number would make old consent cookies valid again — consent given under an older policy.
* A save through access control (the panel, REST, GraphQL) with a lower number is refused with a message; the
* Local API with `overrideAccess` (a script an admin runs) may still lower it. `iapl({ cookieSettings:
* { allowLowerPolicyVersion: true } })` leaves the field free, as before.
*/
export const policyVersionNeverDown: FieldHook = ({ global, originalDoc, overrideAccess, path, req, siblingData, value }) => {
if (overrideAccess === true) {return value}
const stored = Number((originalDoc as { policyVersion?: unknown } | undefined)?.policyVersion)
// what the save SENT: Payload passes the stored value for a field that was not sent
const sent = siblingData && 'policyVersion' in siblingData ? Number((siblingData as { policyVersion?: unknown }).policyVersion) : NaN
if (!Number.isFinite(stored) || !Number.isFinite(sent) || sent >= stored) {return value}
const vars = { stored }
const message = req?.t ? iaplT(req.t as never, 'policyVersionDown', vars) : `The consent version cannot go down: it is ${stored} now.`
throw new ValidationError({ errors: [{ message, path: path.join('.') }], global: global?.slug }, req?.t)
}
export type CookieSettingsFieldOptions = {
/** `true` = an editor may lower the consent version, as before 1.17.2. Default false. */
allowLowerPolicyVersion?: boolean
}
/** The Cookie settings fields, with the consent-version rule unless it is turned off. */
export function buildCookieSettingsFields({ allowLowerPolicyVersion = false }: CookieSettingsFieldOptions = {}): Field[] {
if (allowLowerPolicyVersion) {return cookieSettingsFields}
return cookieSettingsFields.map((field) =>
'name' in field && field.name === 'policyVersion'
? ({ ...field, hooks: { ...(field as NumberField).hooks, beforeValidate: [policyVersionNeverDown, ...((field as NumberField).hooks?.beforeValidate ?? [])] } } as Field)
: field,
)
}
const DEFAULT_HINT = { en: 'Leave empty to use the default.', pl: 'Zostaw puste, aby użyć domyślnej wartości.' }
const HIDDEN_HINT = { en: 'Leave empty to hide it.', pl: 'Zostaw puste, aby go nie pokazywać.' }
+3 -3
View File
@@ -1,14 +1,14 @@
import type { GlobalConfig } from 'payload'
import { userMeetsRole } from '../../modules/access/index.js'
import { cookieSettingsFields } from './fields.js'
import { buildCookieSettingsFields, type CookieSettingsFieldOptions } from './fields.js'
/**
* Builds the CookieSettings global ("Cookies" in the admin) — consent banner copy and the
* cookie list, managed by editors. With the cookie scanner it also carries its tabs.
* Public read (the banner needs it on the frontend for anonymous visitors).
*/
export function buildCookieSettings(): GlobalConfig {
export function buildCookieSettings(options: CookieSettingsFieldOptions = {}): GlobalConfig {
return {
slug: 'cookie-settings',
access: {
@@ -18,7 +18,7 @@ export function buildCookieSettings(): GlobalConfig {
admin: {
group: { en: 'Privacy', pl: 'Prywatność' },
},
fields: cookieSettingsFields,
fields: buildCookieSettingsFields(options),
label: { en: 'Cookies', pl: 'Cookies' },
}
}
+21 -4
View File
@@ -1,3 +1,6 @@
export { buildCookieSettingsFields, policyVersionNeverDown } from './globals/CookieSettings/fields.js'
export type { CookieSettingsFieldOptions } from './globals/CookieSettings/fields.js'
export { buildCookieSettings } from './globals/CookieSettings/index.js'
export { lightboxNotificationFields } from './globals/Notifications/fields.js'
export { applyGlobalOverrides } from './globals/overrides.js'
export type { GlobalOverride, GlobalOverrides, IaplGlobalSlug, IpalGlobalSlug } from './globals/overrides.js'
@@ -15,13 +18,18 @@ export {
injectRoles,
isAdmin,
isEditor,
READ_PUBLISHED,
readPublished,
readPublishedVersions,
requireRole,
requireRoleField,
ROLE_HIERARCHY,
staffCollectionSlugs,
userMeetsRole,
withVersionReadRules,
} from './modules/access/index.js'
export { graphqlLoginName, lockedLooksWrong, withLockedAnswer } from './modules/access/lockedAnswer.js'
export type { LockedAnswerOption } from './modules/access/lockedAnswer.js'
export { applyPanelRole, countBelowPanelRole, DEFAULT_PANEL_ROLE, panelAccess, resolvePanelRole } from './modules/access/panelRole.js'
export { applyPasswordRule, buildPasswordRuleHook, checkPassword, DEFAULT_PASSWORD_MIN_LENGTH, resolvePasswordRule } from './modules/access/passwordRule.js'
export type { PasswordRuleOptions } from './modules/access/passwordRule.js'
@@ -123,6 +131,7 @@ export {
CONSENT_VERSION,
consentBannerScript,
consentCategoryOptions,
consentDecidedScript,
consentFallback,
DEFAULT_CONSENT,
getConsentTexts,
@@ -232,6 +241,7 @@ export { pathOf } from './modules/construction/visibility.js'
export type { PathVisibility } from './modules/construction/visibility.js'
export type { ContentCollectionOption, ContentOption, ResolvedRoute } from './modules/content/index.js'
export {
applyDraftRelations,
archiveFieldName,
blocksToMarkdown,
buildArchivePath,
@@ -253,8 +263,9 @@ export {
resolveRoute,
SEARCH_QUERY_LIMIT,
searchContent,
withoutDraftRelations,
} from './modules/content/index.js'
export type { ArchiveEntries } from './modules/content/index.js'
export type { ArchiveEntries, DraftRelations } from './modules/content/index.js'
export type { SearchResult } from './modules/content/index.js'
// Postgres: connections kept free of transactions, work run after a commit (docs/deployment.md "Postgres: the connection pool").
export { afterCommit, defaultConnectionReserve, inWatchedTransaction, poolSize, RESERVE_ESCAPE_MS, reserveConnections, transactionsBusy, transactionWatchState, watchTransactions } from './modules/database/transactions.js'
@@ -404,7 +415,7 @@ export type { LocaleMiddlewareResult } from './modules/i18n/localeMiddleware.js'
export { buildLocalizedPath, switchLocalePath } from './modules/i18n/localizedPath.js'
export { LOCALE_COOKIE_NAME, matchAcceptLanguage, negotiateLocale } from './modules/i18n/negotiateLocale.js'
export { resolveLocalized } from './modules/i18n/resolveLocalized.js'
export { buildIntegrationStatusBanner, buildIntegrationStatusField, recordIntegrationStatus } from './modules/integrations/index.js'
export { buildIntegrationStatusBanner, buildIntegrationStatusField, recordIntegrationStatus, writeGlobalFields } from './modules/integrations/index.js'
export type { IntegrationBannerTexts, IntegrationLabel, IntegrationState, IntegrationStatus } from './modules/integrations/index.js'
// Image lightbox — pure helpers (components live in /client).
export { formatLightboxCounter, LIGHTBOX_FALLBACK, LIGHTBOX_FALLBACK_PL, lightboxFallback, lightboxImage, lightboxIndex, resolveLightboxTexts } from './modules/lightbox/index.js'
@@ -467,6 +478,8 @@ export {
writeOnlySecrets,
} from './modules/secrets/writeOnly.js'
export type { WriteOnlySecretOptions } from './modules/secrets/writeOnly.js'
export { ADMIN_POST_ENDPOINTS, guardAdminEndpoints, requireOwnOrigin } from './modules/security/adminSameOrigin.js'
export type { AdminSameOriginOption } from './modules/security/adminSameOrigin.js'
export {
adminClientHintSources,
buildAdminCsp,
@@ -500,8 +513,10 @@ export type {
TotpUser,
WithSecurityConfigOptions,
} from './modules/security/index.js'
export type { BuildSecurityHeadersArgs, SecurityHeader } from './modules/security/index.js'
// Payload's job queue over HTTP: an admin with the second factor or Bearer CRON_SECRET (security.md "Payload's job queue")
export { CRON_SECRET_ENV, CRON_SECRET_MIN_LENGTH, cronSecretMatches, jobsRunAccess, jobsRunNotice, withJobsRunAccess } from './modules/security/jobsAccess.js'
export type { JobsRunAccessOptions } from './modules/security/jobsAccess.js'
// The doors a built config opens (REST, GraphQL, Next route files) and the judged snapshot they are checked against.
export { compareRouteSnapshot, listNextRouteFiles, listPublicRoutes, updateRouteSnapshot } from './modules/security/routeInventory.js'
export type { GraphqlSchemaLike, RouteInventoryOptions, RouteSnapshot, RouteSnapshotDiff } from './modules/security/routeInventory.js'
@@ -577,11 +592,13 @@ 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 { 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`.
export { assertDevelopmentHosts, DEFAULT_DEVELOPMENT_HOSTS, isDevelopmentHost, matchDevelopmentHost } from './modules/shared/developmentHosts.js'
export { clientIp, releaseRateLimit, setRateLimitStore, setUnknownIpFactor, UNKNOWN_IP_FACTOR } from './modules/shared/rateLimit.js'
export { clientIp, ipRateKey, releaseRateLimit, setIpv6Grouping, setRateLimitStore, setUnknownIpFactor, UNKNOWN_IP_FACTOR } from './modules/shared/rateLimit.js'
export type { Ipv6Grouping } from './modules/shared/rateLimit.js'
export type { ClientIpOptions, RateLimitStore } from './modules/shared/rateLimit.js'
export { buildSlugField, toSlug } from './modules/slug/index.js'
export { STATS_SLUG } from './modules/stats/index.js'
+38 -4
View File
@@ -21,17 +21,51 @@ export const requireRole = (minimum: Role): Access => {
return ({ req }) => hasMinimumRole(req.user, minimum, req.payload)
}
/** Marks a `readPublished()` rule, so the plugin can give `readVersions` the version form of it (a symbol, not a name). */
export const READ_PUBLISHED = Symbol.for('iapl.readPublished')
/**
* Read rule for a collection with drafts: staff of `minimum` role or higher (default editor) read everything,
* drafts and versions included; everybody else (visitors, plain `user` accounts, a session that still owes its
* Read rule for a collection (or a global) with drafts: staff of `minimum` role or higher (default editor) read
* everything, drafts included; everybody else (visitors, plain `user` accounts, a session that still owes its
* second factor) reads published documents only — by id, in lists, with `?draft=true` and over GraphQL. Payload's
* open `read: () => true` answers `?draft=true` with the draft itself (IAWL idea 23).
*
* access: { read: readPublished(), readVersions: readPublished() }
* For `read`. Version history (`readVersions`) asks for the status at another path (`version._status`): use
* `readPublishedVersions()` there. Given to `readVersions` of a collection or global that iapl() sees, this rule
* is swapped for `readPublishedVersions()` with the same role (1.17.2; in 1.17.1 it answered 500 there).
*
* access: { read: readPublished(), readVersions: readPublishedVersions() }
*/
export const readPublished = (minimum: Role = 'editor'): Access => {
assertKnownRole('readPublished', minimum)
return ({ req }) => (hasMinimumRole(req.user, minimum, req.payload) ? true : { _status: { equals: 'published' } })
const rule: Access = ({ req }) => (hasMinimumRole(req.user, minimum, req.payload) ? true : { _status: { equals: 'published' } })
return Object.assign(rule, { [READ_PUBLISHED]: minimum })
}
/**
* The version-history form of `readPublished()`, for `readVersions`: staff of `minimum` role or higher read every
* version; everybody else reads published versions only — the list, one version by id, the count, REST, GraphQL,
* the Local API with access control. A version query runs on the versions collection, where the status is
* `version._status` (a `_status` condition there is an unknown path: 500 on every database adapter).
*/
export const readPublishedVersions = (minimum: Role = 'editor'): Access => {
assertKnownRole('readPublishedVersions', minimum)
return ({ req }) => (hasMinimumRole(req.user, minimum, req.payload) ? true : { 'version._status': { equals: 'published' } })
}
type WithAccess = { access?: { readVersions?: unknown } }
/**
* Gives every `readVersions: readPublished()` the version form (`readPublishedVersions()` with the same role).
* iapl() runs it on the collections and globals it sees; a plugin listed after iapl() uses
* `readPublishedVersions()` itself, or runs this on its own entities.
*/
export function withVersionReadRules<T extends WithAccess>(entities: T[] | undefined): T[] | undefined {
return entities?.map((entity) => {
const rule = entity.access?.readVersions as (object & Partial<Record<typeof READ_PUBLISHED, Role>>) | undefined
const minimum = rule && typeof rule === 'function' ? rule[READ_PUBLISHED] : undefined
return minimum ? { ...entity, access: { ...entity.access, readVersions: readPublishedVersions(minimum) } } : entity
})
}
/**
+3
View File
@@ -6,9 +6,12 @@ export {
adminOrSelf,
adminOrSelfIn,
authenticated,
READ_PUBLISHED,
readPublished,
readPublishedVersions,
requireRole,
requireRoleField,
withVersionReadRules,
} from './access.js'
export { injectRoles } from './injectRoles.js'
export { clearStaffRegistry, hasMinimumRole, isAdmin, isEditor, registerStaffCollections, staffCollectionSlugs, userMeetsRole } from './predicates.js'
+67
View File
@@ -0,0 +1,67 @@
import type { AfterErrorHook, Config, SanitizedCollectionConfig } from 'payload'
import { AuthenticationError, formatNames, toWords } from 'payload'
import { staffCollectionSlugs } from './predicates.js'
/**
* A locked staff account answers its login exactly like a wrong password (`accounts.lockedAnswer`, 1.17.2).
*
* Payload checks the lock BEFORE the password: after five wrong passwords for `owner@site` any password gets
* `401 "This user is locked due to having too many failed login attempts."` (GraphQL: `LockedAuth`), while an
* address that has no account always gets `401 "The email or password provided is incorrect."`. Anybody could
* tell which addresses have a staff account with no password at all (IAWL idea 6). This hook turns Payload's
* `LockedAuth` on a staff collection's login into the `AuthenticationError` answer — same status, same body, same
* GraphQL `extensions.name`. The price: the owner, while locked, is told "wrong e-mail or password" too.
*
* The lock itself is not touched (it still holds for `lockTime`). `accounts: { lockedAnswer: 'payload' }` keeps
* Payload's message. The error is recognised by its `name` (`'LockedAuth'`, a string Payload sets — not a function
* name, so a minified bundle keeps it) and by the collection: a staff collection only.
*/
export type LockedAnswerOption = 'payload' | 'wrong'
const isLocked = (error: unknown): boolean => (error as { name?: unknown } | null)?.name === 'LockedAuth'
/** The GraphQL login mutation's name of a collection, as @payloadcms/graphql builds it (`login${singularName}`). */
export function graphqlLoginName(collection: Pick<SanitizedCollectionConfig, 'graphQL' | 'slug'>): null | string {
const graphQL = collection.graphQL as { singularName?: string } | false | undefined
if (graphQL === false) {return null}
const singular = graphQL?.singularName ? toWords(graphQL.singularName, true) : formatNames(collection.slug).singular
return `login${singular}`
}
type T = ConstructorParameters<typeof AuthenticationError>[0]
/** The config-level `afterError` hook (REST and GraphQL). */
export const lockedLooksWrong: AfterErrorHook = (args) => {
const { collection, error, req } = args as { error: unknown; graphqlResult?: Record<string, unknown> } & Parameters<AfterErrorHook>[0]
const payload = req?.payload
if (!payload) {return}
const staff = staffCollectionSlugs(payload)
const wrong = new AuthenticationError(req.t as T)
// GraphQL: the error is wrapped (`originalError`), the collection only shows in the mutation's name.
const graphqlResult = (args as { graphqlResult?: { extensions?: Record<string, unknown>; path?: unknown[] } }).graphqlResult
if (graphqlResult) {
const original = (error as { originalError?: unknown }).originalError
if (!isLocked(original)) {return}
const field = Array.isArray(graphqlResult.path) ? graphqlResult.path[0] : undefined
const names = new Set((payload.config.collections ?? []).filter((c) => staff.includes(c.slug)).map(graphqlLoginName))
if (typeof field !== 'string' || !names.has(field)) {return}
return {
graphqlResult: {
...graphqlResult,
extensions: { ...graphqlResult.extensions, name: wrong.name, statusCode: wrong.status },
message: wrong.message,
},
} as never
}
if (!isLocked(error) || !collection || !staff.includes(collection.slug)) {return}
return { response: { errors: [{ message: wrong.message }] }, status: wrong.status } as never
}
/** Adds the hook to a config (idempotent). */
export function withLockedAnswer(config: Config): Config {
const own = config.hooks?.afterError ?? []
if (own.includes(lockedLooksWrong)) {return config}
return { ...config, hooks: { ...config.hooks, afterError: [...own, lockedLooksWrong] } }
}
+7
View File
@@ -57,6 +57,13 @@ export type AccountsOptions = {
* whose own `create` rule allows an anonymous request keeps its route.
*/
firstUserRoute?: 'all' | 'panel' | string[]
/**
* What a staff account that Payload has locked (too many wrong passwords) is told when it logs in.
* Default (1.17.2): exactly what a wrong password gets — same status, message and GraphQL error name — so
* nobody can find out which addresses have a staff account by locking them. The lock itself is unchanged.
* `'wrong'` = the default, said out loud. `'payload'` = Payload's own "This user is locked due to having too many failed login attempts."
*/
lockedAnswer?: 'payload' | 'wrong'
/**
* The lowest role that may open the admin panel. Default `'editor'`: an
* account that holds only `user` (the default role of a new account) sees
+2
View File
@@ -9,6 +9,7 @@ export const consentTexts = defineTexts({
cookieIntegrationStats: 'Built-in statistics',
cookieIntegrationTheme: 'Theme choice',
cookieSourceProject: 'Project',
policyVersionDown: 'The consent version cannot go down: it is {{stored}} now. Raise it to ask every visitor again, or leave it as it is.',
},
pl: {
cookieIntegrationAdmin: 'Logowanie do panelu',
@@ -17,5 +18,6 @@ export const consentTexts = defineTexts({
cookieIntegrationStats: 'Wbudowane statystyki',
cookieIntegrationTheme: 'Wybór motywu',
cookieSourceProject: 'Projekt',
policyVersionDown: 'Wersji zgody nie można obniżyć: teraz wynosi {{stored}}. Podnieś ją, aby ponownie zapytać odwiedzających, albo zostaw bez zmian.',
},
})
+82 -12
View File
@@ -2,21 +2,35 @@
import type { CSSProperties } from 'react'
import { Cookie } from 'lucide-react'
import { useEffect, useRef, useState } from 'react'
import { useEffect, useLayoutEffect, useRef, useState } from 'react'
import { useConsentContext } from './ConsentContext.js'
import { COOKIE_BUTTON_RESERVE, cookieButtonSpaceScript, reserveCookieButtonSpace } from './cookieButtonSpace.js'
import { consentDecidedScript } from './firstPaint.js'
/** Elements the button moves up for, so it never covers footer links. */
/**
* The site footer: the selector of the placement before 1.17.2, when the button moved up by the visible part of
* the footer. `<CookieButton avoid={COOKIE_BUTTON_AVOID} />` brings that placement back.
*/
export const COOKIE_BUTTON_AVOID = 'footer, [role="contentinfo"]'
export type CookieButtonProps = {
/**
* CSS selector of elements the button lifts above while they are on screen
* (default: the site footer). `false` = never move.
* Placement before 1.17.2: a CSS selector of elements the button lifts above while they are on screen
* (`COOKIE_BUTTON_AVOID` = the site footer; no room is reserved then). Default: none — the button stays in the
* bottom corner of the window and never moves. `false` = the same as the default (kept for sites that set it).
*/
avoid?: false | string
/** Replaces the default classes (look and position). The lift above `avoid` still applies. */
className?: string
/**
* Room for the button at the end of the page, so the footer's last row ends above it and nothing stays covered:
* a CSS selector of the block that gets the bottom padding (the last match; default `COOKIE_BUTTON_RESERVE`, the
* footer; no match: `<body>`). Only while the button is shown, only as much as is missing (the block's own
* bottom padding counts, an empty corner needs none). `false` = no room. A fixed amount instead of the measured
* one: `--ipal-cookie-button-space` on that block (`0` = none, also per breakpoint).
*/
reserve?: false | string
/** Corner. Default 'left'. */
side?: 'left' | 'right'
}
@@ -26,19 +40,42 @@ export type CookieButtonProps = {
* after deciding (GDPR: withdrawing consent must be as easy as giving it).
* Hidden while the banner is showing.
*
* Placement (1.17.2): fixed in the bottom corner of the window, on every page and at every scroll position. It
* never moves — it does not climb above the footer any more. So that it covers nothing at the very end of a page,
* the footer gets room under its last row while the button is shown (`reserve`, cookieButtonSpace.ts). The
* placement before 1.17.2 (riding on the footer's top edge): `avoid={COOKIE_BUTTON_AVOID}`.
*
* Colours follow the same design tokens as CookieBanner (--ipal-surface,
* --ipal-border, --ipal-hover, --ipal-text). Position: --ipal-cookie-button-offset
* (distance from the bottom, default 1rem), --ipal-cookie-button-inset (from the
* side, default 1rem), z-index --ipal-z-header. When the footer scrolls into
* view the button moves up by the visible part of it, so footer links stay free.
* side, default 1rem), both plus the device's safe-area inset; z-index --ipal-z-header (below the banner and dialogs).
*/
export function CookieButton({ avoid = COOKIE_BUTTON_AVOID, className, side = 'left' }: CookieButtonProps = {}) {
const { decided, reopen, texts } = useConsentContext()
const lift = useLiftAbove(avoid, decided)
export function CookieButton({ avoid, className, reserve = COOKIE_BUTTON_RESERVE, side = 'left' }: CookieButtonProps = {}) {
const { decided, gpcMode, hydrated, nonce, reopen, serverRead, texts } = useConsentContext()
const buttonRef = useRef<HTMLButtonElement>(null)
const lift = useLiftAbove(avoid ?? false, decided)
// the old placement keeps the button off the footer by itself
const room = avoid ? false : reserve
useReservedSpace({ active: decided, buttonRef, selector: room, side })
// `decided` is the server's value while hydrating (no decision on a static page, so nothing is rendered — or the
// cookie the server read, <ConsentProvider cookieValue>, and then the button is in the HTML), the browser's after.
if (!decided) {return null}
if (!decided) {
// Static HTML, the same for every visitor: for one who already decided, the room is made before the first
// paint, so nothing shifts when the button appears with hydration. Only in the server HTML (a script React
// creates in the browser never runs); a button with classes of its own is measured once it is there.
if (hydrated || serverRead || !room || className) {return null}
return (
<script
dangerouslySetInnerHTML={{
__html: cookieButtonSpaceScript({ decided: consentDecidedScript({ gpc: gpcMode, version: texts.version }), selector: room, side }),
}}
data-ipal="cookie-button-script"
nonce={nonce}
suppressHydrationWarning
/>
)
}
const cls =
className ??
@@ -50,7 +87,7 @@ export function CookieButton({ avoid = COOKIE_BUTTON_AVOID, className, side = 'l
: {
bottom: 'calc(var(--ipal-cookie-button-offset, 1rem) + env(safe-area-inset-bottom, 0px))',
position: 'fixed',
[side]: 'var(--ipal-cookie-button-inset, 1rem)',
[side]: `calc(var(--ipal-cookie-button-inset, 1rem) + env(safe-area-inset-${side}, 0px))`,
zIndex: 'var(--ipal-z-header, 40)' as unknown as number,
}
@@ -61,6 +98,7 @@ export function CookieButton({ avoid = COOKIE_BUTTON_AVOID, className, side = 'l
className={cls}
data-ipal="cookie-button"
onClick={reopen}
ref={buttonRef}
style={{ ...position, ...(lift ? { transform: `translateY(-${lift}px)` } : {}) }}
type="button"
>
@@ -103,5 +141,37 @@ function useLiftAbove(selector: false | string, active: boolean): number {
observer?.disconnect()
}
}, [selector, active])
return selector ? lift : 0
return selector && active ? lift : 0
}
type ReservedSpaceOptions = {
active: boolean
buttonRef: { current: HTMLButtonElement | null }
selector: false | string
side: 'left' | 'right'
}
/** Keeps the room for the button while it is shown; takes it away when the button goes (banner reopened, unmount). */
function useReservedSpace({ active, buttonRef, selector, side }: ReservedSpaceOptions): void {
// before the browser paints the button: the room is there in the same frame (and already is, after the inline script)
useLayoutEffect(() => {
if (!active || !selector) {return}
let frame = 0
const apply = () => reserveCookieButtonSpace({ button: buttonRef.current, selector, side })
const later = () => {
cancelAnimationFrame(frame)
frame = requestAnimationFrame(apply)
}
apply()
window.addEventListener('resize', later)
// fonts, images, content that loads later: the footer's last row may end somewhere else
const observer = typeof ResizeObserver === 'undefined' ? null : new ResizeObserver(later)
observer?.observe(document.body)
return () => {
cancelAnimationFrame(frame)
window.removeEventListener('resize', later)
observer?.disconnect()
reserveCookieButtonSpace({ release: true, selector, side })
}
}, [active, buttonRef, selector, side])
}
+2
View File
@@ -6,6 +6,8 @@ export { CookieBanner } from './CookieBanner.js'
export type { CookieBannerAction, CookieBannerClassNames, CookieSettingsAction } from './CookieBanner.js'
export { bottomOverlap, COOKIE_BUTTON_AVOID, CookieButton } from './CookieButton.js'
export type { CookieButtonProps } from './CookieButton.js'
export { COOKIE_BUTTON_RESERVE, COOKIE_BUTTON_SPACE_ATTRIBUTE, reserveCookieButtonSpace } from './cookieButtonSpace.js'
export type { CookieButtonSpaceOptions } from './cookieButtonSpace.js'
// Client-only consent exports — hook, provider, and UI components.
export { DEFAULT_COOKIE_MAP, useConsent } from './useConsent.js'
export type { ConsentCookieMap } from './useConsent.js'
+171
View File
@@ -0,0 +1,171 @@
/**
* Room for the cookie button at the end of the page (1.17.2).
*
* The button is fixed in the bottom corner of the window and never moves. At the very end of a page whatever is in
* that corner — usually the footer's last row — would stay under it for good. So while the button is shown, the
* page's last block (`reserve`, default the footer) gets just enough bottom padding for its content to end above the
* button. Measured, not guessed: only what lies in the button's column counts, the block's own bottom padding is
* used first, and a page with nothing in that corner gets nothing.
*
* NO IMPORTS, NO OUTER NAMES in `reserveCookieButtonSpace`: <CookieButton> also puts the function's own source into
* an inline script (`cookieButtonSpaceScript`), so that a returning visitor's page has the room before the first
* paint and nothing shifts when the button appears.
*/
/** Attribute on the block that carries the room: its inline `padding-bottom` from before (may be empty). */
export const COOKIE_BUTTON_SPACE_ATTRIBUTE = 'data-ipal-cookie-space'
/** The block that gets the room: the last one on the page that matches (the site footer). No match: `<body>`. */
export const COOKIE_BUTTON_RESERVE = 'footer, [role="contentinfo"]'
export type CookieButtonSpaceOptions = {
/** The button, when it is on the page. Without it the default button's box is measured with a probe. */
button?: HTMLElement | null
/** `true` takes the room away (the button is gone or the banner is open). */
release?: boolean
/** CSS selector of the block that gets the room. */
selector: string
/**
* Before hydration: put the padding in a constructed style sheet instead of on the element, so React finds the
* server's markup untouched (no hydration warning). The next call without it moves the room onto the element.
*/
sheet?: boolean
/** The button's corner. */
side: 'left' | 'right'
}
/**
* Gives the page's last block the room the button needs, or takes it away. Returns the pixels added (0 = none).
* Safe to call again and again: it measures the block without its own addition each time.
*/
export function reserveCookieButtonSpace(options: CookieButtonSpaceOptions): number {
const ATTRIBUTE = 'data-ipal-cookie-space'
const GAP = 8
const SHEET = '__iaplCookieSpaceSheet'
const doc = document
const store = window as unknown as Record<string, CSSStyleSheet | undefined>
let i: number
// put back what an earlier call changed — every measurement starts from the page as the project made it
const marked = doc.querySelectorAll('[' + ATTRIBUTE + ']')
for (i = 0; i < marked.length; i++) {
const was = marked[i] as HTMLElement
was.style.paddingBottom = was.getAttribute(ATTRIBUTE) || ''
was.removeAttribute(ATTRIBUTE)
}
const before = store[SHEET]
if (before) {
doc.adoptedStyleSheets = doc.adoptedStyleSheets.filter(function (sheet) {return sheet !== before})
store[SHEET] = undefined
}
if (options.release || !doc.body) {return 0}
const found = doc.querySelectorAll(options.selector)
let target: HTMLElement = doc.body
for (i = found.length - 1; i >= 0; i--) {
if ((found[i] as HTMLElement).getBoundingClientRect().height > 0) {
target = found[i] as HTMLElement
break
}
}
// the button's box; before the button exists, a probe with the default button's size and place
let button = options.button || null
let probe: HTMLElement | null = null
if (!button) {
probe = doc.createElement('div')
probe.style.cssText =
'position:fixed;visibility:hidden;pointer-events:none;width:2.75rem;height:2.75rem;' +
'bottom:calc(var(--ipal-cookie-button-offset, 1rem) + env(safe-area-inset-bottom, 0px));' +
options.side + ':calc(var(--ipal-cookie-button-inset, 1rem) + env(safe-area-inset-' + options.side + ', 0px))'
doc.body.appendChild(probe)
button = probe
}
const fixed = getComputedStyle(button).position === 'fixed'
const box = button.getBoundingClientRect()
if (probe) {doc.body.removeChild(probe)}
// a button the project placed in the flow (className) covers nothing at the end of the page
if (!fixed || box.height <= 0) {return 0}
const style = getComputedStyle(target)
const own = parseFloat(style.paddingBottom) || 0
const give = function (value: string): boolean {
if (!options.sheet) {
target.setAttribute(ATTRIBUTE, target.style.paddingBottom)
target.style.paddingBottom = value
return true
}
if (typeof CSSStyleSheet !== 'function' || !('adoptedStyleSheets' in doc)) {return false}
// the one element, without marking it: its path from <body>
let path = ''
for (let el: Element | null = target; el && el !== doc.body; el = el.parentElement) {
let nth = 1
for (let prev = el.previousElementSibling; prev; prev = prev.previousElementSibling) {nth++}
path = ' > ' + el.tagName.toLowerCase() + ':nth-child(' + nth + ')' + path
}
const sheet = new CSSStyleSheet()
sheet.replaceSync('body' + path + '{padding-bottom:' + value + ' !important}')
doc.adoptedStyleSheets = doc.adoptedStyleSheets.concat(sheet)
store[SHEET] = sheet
return true
}
// a project's own amount: --ipal-cookie-button-space (any length; 0 = none on this breakpoint)
const token = style.getPropertyValue('--ipal-cookie-button-space').replace(/^\s+|\s+$/g, '')
if (token) {
if (/^[+-]?(?:0+(?:\.0+)?|\.0+)[a-z%]*$/i.test(token)) {return 0}
if (!give('calc(' + own + 'px + ' + token + ')')) {return 0}
return Math.max(0, (parseFloat(getComputedStyle(target).paddingBottom) || 0) - own)
}
// from the window's bottom edge up to the button's top, plus a gap: what must be free at the end of the page
const zone = window.innerHeight - box.top + GAP
let free: number
if (target === doc.body) {
free = own
} else {
// the lowest thing in the button's column: text and replaced elements, by their real boxes
let lowest = -Infinity
const note = function (rects: ArrayLike<{ bottom: number; height: number; left: number; right: number; width: number }>) {
for (let k = 0; k < rects.length; k++) {
const r = rects[k]
if (r.width > 0 && r.height > 0 && r.right > box.left - GAP && r.left < box.right + GAP && r.bottom > lowest) {lowest = r.bottom}
}
}
const walker = doc.createTreeWalker(target, 4) // NodeFilter.SHOW_TEXT
const range = doc.createRange()
let node = walker.nextNode()
while (node) {
if (/\S/.test(node.nodeValue || '')) {
range.selectNodeContents(node)
note(range.getClientRects())
}
node = walker.nextNode()
}
const solid = target.querySelectorAll('img, svg, video, canvas, iframe, input, select, textarea, button')
for (i = 0; i < solid.length; i++) {note([solid[i].getBoundingClientRect()])}
if (lowest === -Infinity) {return 0}
// where the page ends, in the same (window) coordinates
free = doc.documentElement.scrollHeight - window.scrollY - lowest
}
const extra = Math.ceil(Math.min(zone, zone - free))
if (extra <= 0) {return 0}
return give(own + extra + 'px') ? extra : 0
}
export type CookieButtonSpaceScriptOptions = {
/** JavaScript that leaves `true` in a variable `d` when the visitor has a current decision (consentDecidedScript). */
decided: string
selector: string
side: 'left' | 'right'
}
/**
* Inline script for the server HTML of a static page: for a visitor who already decided (the button will appear
* after hydration) the room is there before the first paint. Nothing happens for a visitor who has not.
*/
export function cookieButtonSpaceScript({ decided, selector, side }: CookieButtonSpaceScriptOptions): string {
const options = JSON.stringify({ selector, sheet: true, side: side === 'right' ? 'right' : 'left' })
.replace(/</g, '\\u003c')
.split(String.fromCharCode(0x2028)).join('\\u2028')
.split(String.fromCharCode(0x2029)).join('\\u2029')
return `(function(){try{${decided}if(d){(${reserveCookieButtonSpace.toString()})(${options})}}catch(e){}})()`
}
+14 -3
View File
@@ -37,7 +37,12 @@ export type ConsentBannerScriptOptions = {
* Exported for a project that renders its own banner: put `hidden` and `suppressHydrationWarning` on the banner's
* root, and this script in a `<script>` (with the nonce) as its next sibling.
*/
export function consentBannerScript({ cookieName = CONSENT_COOKIE, gpc = 'honour', version = CONSENT_VERSION }: ConsentBannerScriptOptions = {}): string {
/**
* JavaScript statements that leave `true` in a variable `d` when this browser holds a current decision (or sends
* Global Privacy Control under `gpc: 'honour'`), decided exactly as readConsentRecord / resolveConsent do. The shared
* start of the inline scripts that act before the first paint (the banner's, the cookie button's room).
*/
export function consentDecidedScript({ cookieName = CONSENT_COOKIE, gpc = 'honour', version = CONSENT_VERSION }: ConsentBannerScriptOptions = {}): string {
// JSON string literal, safe inside <script>: no `</script>`, no line separators
const name = JSON.stringify(`${cookieName}=`)
.replace(/</g, '\\u003c')
@@ -45,11 +50,17 @@ export function consentBannerScript({ cookieName = CONSENT_COOKIE, gpc = 'honour
.split(String.fromCharCode(0x2029)).join('\\u2029')
const v = Number.isFinite(version) ? Number(version) : CONSENT_VERSION
return (
`(function(){try{var s=document.currentScript,b=s&&s.previousElementSibling;if(!b){return}` +
`var n=${name},d=false,c=document.cookie?document.cookie.split("; "):[];` +
`for(var i=0;i<c.length;i++){if(c[i].indexOf(n)===0){try{d=JSON.parse(decodeURIComponent(c[i].split("=")[1])).version===${v}}catch(e){}break}}` +
// Global Privacy Control honoured: no banner, the same decision React makes (resolveConsent)
(gpc === 'honour' ? `if(!d&&navigator.globalPrivacyControl===true){d=true}` : '') +
(gpc === 'honour' ? `if(!d&&navigator.globalPrivacyControl===true){d=true}` : '')
)
}
export function consentBannerScript({ cookieName = CONSENT_COOKIE, gpc = 'honour', version = CONSENT_VERSION }: ConsentBannerScriptOptions = {}): string {
return (
`(function(){try{var s=document.currentScript,b=s&&s.previousElementSibling;if(!b){return}` +
consentDecidedScript({ cookieName, gpc, version }) +
`if(d){b.style.display="none"}else{b.removeAttribute("hidden");` +
// a click on a banner button before the page has hydrated is kept for <CookieBanner> to carry out
`b.addEventListener("click",function(e){if(b.hasAttribute("${BANNER_READY_ATTRIBUTE}")){return}` +
+1 -1
View File
@@ -11,7 +11,7 @@ export type { ConsentCategory, ConsentState } from './categories.js'
export { CONSENT_CATEGORY_LABELS, consentCategoryOptions } from './categoryLabels.js'
export { buildConsentLogCollection, buildConsentLogEndpoint, CONSENT_LOG_MAX_BYTES, CONSENT_LOG_PATH, CONSENT_LOG_SLUG, readCappedBody } from './consentLog.js'
export type { ConsentLogOptions } from './consentLog.js'
export { consentBannerScript } from './firstPaint.js'
export { consentBannerScript, consentDecidedScript } from './firstPaint.js'
export type { ConsentBannerScriptOptions } from './firstPaint.js'
export { CONSENT_FALLBACK, CONSENT_FALLBACK_PL, consentFallback, getConsentTexts, getCookieTable } from './getConsentTexts.js'
export type { CookieTableRow } from './getConsentTexts.js'
+2 -1
View File
@@ -7,6 +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 { CONSENT_CATEGORIES } from '../categories.js'
import { COOKIE_REVIEW_SLUG } from './collection.js'
import { textFor } from './merge.js'
@@ -156,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) && Boolean(await options.access({ req })) : userMeetsRole(req, 'editor')
options.access ? secondFactorPassed(req) && accessAllowed('cookieScanner.access', await options.access({ req })) : userMeetsRole(req, 'editor')
return [
{
handler: async (req) => {
@@ -7,6 +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 {
COOKIE_CRAWL_PATH,
COOKIE_CRAWL_RESULTS_PATH,
@@ -60,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) && Boolean(await options.access({ req })) : userMeetsRole(req, 'editor')
options.access ? secondFactorPassed(req) && accessAllowed('cookieScanner.access', await options.access({ 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 -1
View File
@@ -4,6 +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 { DEFAULT_COOKIE_INTEGRATIONS, integrationLabel } from './integrations.js'
import { cookieScanContext, enabledCookieIntegrations, parseCookieNames, runCookieScan } from './scan.js'
@@ -17,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) && Boolean(await options.access({ req })) : userMeetsRole(req, 'editor')
options.access ? secondFactorPassed(req) && accessAllowed('cookieScanner.access', await options.access({ 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) =>
+44 -24
View File
@@ -16,6 +16,9 @@ type Row = {
type Entry = { name: string; storage?: null | string } & CookieReviewValues
/** How many times a write is worked out again when the list changed under it. */
const WRITE_ATTEMPTS = 5
const empty = (v: unknown) => v === undefined || v === null || (typeof v === 'string' && !v.trim())
/**
@@ -52,13 +55,12 @@ export async function addToCookieList({
const common = { slug: 'cookie-settings' as never, context: { ipalCookieScan: true }, depth: 0, fallbackLocale: false as never, overrideAccess: true, req }
let result: 'added' | 'filled' | 'unchanged' = 'unchanged'
for (const [i, locale] of locales.entries()) {
const g = (await payload.findGlobal({ ...common, locale: locale as never })) as { cookies?: Row[] }
const rows = [...(g.cookies ?? [])]
/** Adds or fills the entry's row in `rows` (in place); what happened, or null when nothing changed. */
const applyEntry = (rows: Row[], i: number): 'added' | 'filled' | null => {
const locale = locales[i]
const row = rows.find((r) => Boolean(r.name?.trim()) && sameCookie(r.name!.trim(), entry.name))
let changed = false
if (!row) {
if (i > 0) {continue} // added in the default locale; Payload keeps the row in every locale
if (i > 0) {return null} // added in the default locale; Payload keeps the row in every locale
rows.push({
name: entry.name,
category: entry.category ?? 'necessary',
@@ -67,28 +69,46 @@ export async function addToCookieList({
purpose: text(entry.purpose, locale),
storage: entry.storage ?? 'cookie',
})
changed = true
result = 'added'
} else {
const fill = (key: 'duration' | 'provider' | 'purpose', value: null | string | undefined) => {
if (empty(row[key]) && !empty(value)) {
row[key] = value
changed = true
}
return 'added'
}
let changed = false
const fill = (key: 'duration' | 'provider' | 'purpose', value: null | string | undefined) => {
if (empty(row[key]) && !empty(value)) {
row[key] = value
changed = true
}
if (i === 0) {
fill('provider', entry.vendor)
// A row from before the type existed has none; the type is shared by every language.
if (empty(row.storage) && entry.storage) {
row.storage = entry.storage
changed = true
}
}
if (i === 0) {
fill('provider', entry.vendor)
// A row from before the type existed has none; the type is shared by every language.
if (empty(row.storage) && entry.storage) {
row.storage = entry.storage
changed = true
}
fill('purpose', text(entry.purpose, locale))
fill('duration', text(entry.retention, locale))
if (changed && result === 'unchanged') {result = 'filled'}
}
fill('purpose', text(entry.purpose, locale))
fill('duration', text(entry.retention, locale))
return changed ? 'filled' : null
}
// The list is written whole (Payload has no "add one row"): right before writing, it is read again, and when an
// editor's save changed it since, the change is worked out again on what is there now (owner's decision Q3,
// 1.18.0). What is left is the moment between that check and the write itself.
const read = async (locale: string | undefined) =>
[...(((await payload.findGlobal({ ...common, locale: locale as never })) as { cookies?: Row[] }).cookies ?? [])]
const same = (a: Row[], b: Row[]) => JSON.stringify(a) === JSON.stringify(b)
for (const [i, locale] of locales.entries()) {
for (let attempt = 0; ; attempt++) {
const seen = await read(locale)
const rows = structuredClone(seen)
const outcome = applyEntry(rows, i)
if (!outcome) {break}
if (attempt < WRITE_ATTEMPTS - 1 && !same(await read(locale), seen)) {continue}
await payload.updateGlobal({ ...common, data: { cookies: rows } as never, locale: locale as never })
if (outcome === 'added' || result === 'unchanged') {result = outcome}
break
}
if (changed) {await payload.updateGlobal({ ...common, data: { cookies: rows } as never, locale: locale as never })}
}
return result
}
+70
View File
@@ -0,0 +1,70 @@
/**
* Drafts as related documents (owner's decision Q5, 1.18.0).
*
* The public helpers read with `depth` (a page at 2, Site settings and archive entries at 1) and Payload fills
* in every related document whatever its status: a block, a menu or a System pages link pointing at a page that
* was never published showed that page's title and slug (and llms-full / the Markdown printed its text). Since
* 1.18.0 such a related document is left out of what the helpers answer, as if it did not exist:
* - a single relationship becomes `null` (a link to it resolves to nothing, a menu item drops out);
* - in a list of relationships it is removed;
* - in a polymorphic one (`{ relationTo, value }`) the `value` becomes `null`.
* A related document counts as a draft when it carries `_status` other than `'published'`, which is what a
* never-published (or unpublished) document of a collection with drafts holds. Documents without `_status`
* (collections without drafts, uploads) are never touched. The document itself is not judged here (the
* helpers already do), only what it points at.
*
* `draftRelations: 'keep'` (createContentHelpers, resolveRoute, getArchiveEntries, resolveNotFoundPage,
* collectSiteIndex) keeps the old behaviour. A preview (`draft: true`) keeps them too.
*/
export type DraftRelations = 'hide' | 'keep'
const isDraftDoc = (value: unknown): boolean => {
if (!value || typeof value !== 'object' || Array.isArray(value)) {return false}
const v = value as { _status?: unknown; id?: unknown }
return v.id !== undefined && typeof v._status === 'string' && v._status !== 'published'
}
/**
* The same value with every related document that is a draft left out (see above). Returns the SAME object
* when nothing needed changing; otherwise only the path to each change is copied (cached reads are not mutated).
*/
export function withoutDraftRelations<T>(value: T): T {
return walk(value, true) as T
}
function walk(value: unknown, root: boolean): unknown {
if (Array.isArray(value)) {
let changed = false
const next: unknown[] = []
for (const item of value) {
if (isDraftDoc(item)) {
changed = true
continue
}
const out = walk(item, false)
if (out !== item) {changed = true}
next.push(out)
}
return changed ? next : value
}
if (!value || typeof value !== 'object' || value instanceof Date) {return value}
if (!root && isDraftDoc(value)) {return null}
const obj = value as Record<string, unknown>
let result: null | Record<string, unknown> = null
for (const key of Object.keys(obj)) {
const item = obj[key]
// a polymorphic relationship keeps its shape: { relationTo, value: null }
const out = isDraftDoc(item) ? null : walk(item, false)
if (out !== item) {
result ??= { ...obj }
result[key] = out
}
}
return result ?? value
}
/** `withoutDraftRelations` unless the caller keeps them (`'keep'`) or reads a preview (`draft`). */
export function applyDraftRelations<T>(value: T, { draft = false, draftRelations = 'hide' }: { draft?: boolean; draftRelations?: DraftRelations } = {}): T {
return draft || draftRelations === 'keep' ? value : withoutDraftRelations(value)
}
+6 -1
View File
@@ -1,5 +1,7 @@
import type { BasePayload } from 'payload'
import { applyDraftRelations, type DraftRelations } from './draftRelations.js'
export type ArchiveEntries<T = Record<string, unknown>> = {
docs: T[]
hasNextPage: boolean
@@ -17,6 +19,8 @@ type GetArchiveEntriesArgs = {
depth?: number
/** Preview (draftMode): include unpublished entries and latest drafts. Default false. */
draft?: boolean
/** Related documents that are drafts: `'hide'` (default since 1.18.0) leaves them out, `'keep'` as before. */
draftRelations?: DraftRelations
locale: string
/** 1-based. Values below 1 are clamped. */
page?: number
@@ -45,6 +49,7 @@ export async function getArchiveEntries<T = Record<string, unknown>>({
collection,
depth = 1,
draft = false,
draftRelations,
locale,
page = 1,
payload,
@@ -69,7 +74,7 @@ export async function getArchiveEntries<T = Record<string, unknown>>({
})
return {
docs: result.docs as T[],
docs: applyDraftRelations(result.docs, { draft, draftRelations }) as T[],
hasNextPage: result.hasNextPage,
hasPrevPage: result.hasPrevPage,
page: result.page ?? 1,
+1
View File
@@ -2,6 +2,7 @@ export { buildArchiveFields } from './archiveFields.js'
export { blocksToMarkdown } from './blocksToMarkdown.js'
export { createMarkdownRenderer, createMarkdownRoute, markdownResponse } from './createMarkdownRenderer.js'
export { createSearchRoute } from './createSearchRoute.js'
export { applyDraftRelations, type DraftRelations, withoutDraftRelations } from './draftRelations.js'
export { getArchiveEntries } from './getArchiveEntries.js'
export type { ArchiveEntries } from './getArchiveEntries.js'
export { MARKDOWN_PREFIX, markdownHref, prefersMarkdown } from './markdownNegotiation.js'
+5 -1
View File
@@ -1,8 +1,11 @@
import type { BasePayload } from 'payload'
import { applyDraftRelations, type DraftRelations } from './draftRelations.js'
import { isPublishedDoc } from './resolveRoute.js'
type ResolveNotFoundPageArgs = {
/** Related documents that are drafts: `'hide'` (default since 1.18.0) leaves them out, `'keep'` as before. */
draftRelations?: DraftRelations
locale: string
/** Client's Pages collection slug. Defaults to 'pages'. */
pagesSlug?: string
@@ -24,6 +27,7 @@ type ResolveNotFoundPageArgs = {
* deleted page just yields null, so the 404 view can't crash the build.
*/
export async function resolveNotFoundPage({
draftRelations,
locale,
pagesSlug = 'pages',
payload,
@@ -52,7 +56,7 @@ export async function resolveNotFoundPage({
locale: locale as never,
})
// a page never published (or unpublished) is a draft: the built-in view, not its text (IAWL idea 23)
return isPublishedDoc(doc) ? (doc as Record<string, unknown>) : null
return isPublishedDoc(doc) ? applyDraftRelations(doc as Record<string, unknown>, { draftRelations }) : null
} catch (error) {
console.warn('[iapl] resolveNotFoundPage: falling back to built-in 404 view:', error)
return null
+16 -1
View File
@@ -2,6 +2,7 @@ import type { BasePayload } from 'payload'
import type { ContentOption } from './types.js'
import { applyDraftRelations, type DraftRelations } from './draftRelations.js'
import { archiveFieldName } from './types.js'
type ArchivePage = { id: number | string; slug?: unknown }
@@ -37,6 +38,11 @@ type ResolveRouteArgs = {
* requests only ever see published content.
*/
draft?: boolean
/**
* Related documents that are drafts (never published) in what the route answers: `'hide'` (default since 1.18.0)
* leaves them out — `null` for one, removed from a list — `'keep'` answers them as before. A preview keeps them.
*/
draftRelations?: DraftRelations
locale: string
/** Page number from the query string (?page=2). Defaults to 1. */
page?: number
@@ -99,7 +105,16 @@ export function isSiteLocale(payload: { config?: { localization?: unknown } }, l
return typeof locale === 'string' && localization.localeCodes.includes(locale)
}
export async function resolveRoute({
export async function resolveRoute(args: ResolveRouteArgs): Promise<null | ResolvedRoute> {
const route = await resolveRouteDocs(args)
if (!route) {return null}
const hide = <T,>(value: T) => applyDraftRelations(value, args)
return 'archive' in route && route.type === 'entry'
? { ...route, archive: hide(route.archive), doc: hide(route.doc) }
: { ...route, doc: hide(route.doc) }
}
async function resolveRouteDocs({
content,
draft = false,
locale,
+33 -1
View File
@@ -202,11 +202,19 @@ export const securityRules: DoctorRule[] = [
{
// Payload accepts the login cookie from ANY origin while its `csrf` list is empty — and it is empty
// unless `csrf` or `serverURL` is set. A page on a sibling subdomain can then act with a panel user's cookie.
// The plugin's own-origin checks (2FA verify / setup / reset, the panel actions — 1.17.2) then know the site
// only from the request's Host: behind a proxy that rewrites it, the site's own panel would be refused.
id: 'csrf-empty',
check: (ctx) => {
const fix = "serverURL: process.env.NEXT_PUBLIC_SERVER_URL (Payload then trusts that origin only; the plugin's own-origin checks know the site's address), or csrf: ['https://<site>']"
const why = 'Payload accepts the login cookie from any origin (a risk when other applications share the domain), and behind a proxy that rewrites Host the plugin cannot tell the panel\'s own requests (2FA, panel actions) from foreign ones'
// deep (the running config) wins over reading the file: serverURL may come from a spread or a helper
if (ctx.deep && typeof ctx.deep.originKnown === 'boolean') {
return ctx.deep.originKnown ? [] : [{ fix, message: `the running config has neither \`serverURL\` nor \`csrf\`: ${why}`, severity: 'warning' }]
}
const code = cfg(ctx)
if (!/buildConfig\s*\(/.test(code) || /\bcsrf\s*:/.test(code) || /\bserverURL\s*:/.test(code)) {return []}
return [{ file: configFile(ctx) ?? 'payload.config.ts', fix: "serverURL: process.env.NEXT_PUBLIC_SERVER_URL (Payload then trusts that origin only), or csrf: ['https://<site>']", message: 'neither `serverURL` nor `csrf` is set: Payload accepts the login cookie from any origin (a risk when other applications share the domain)', severity: 'warning' }]
return [{ file: configFile(ctx) ?? 'payload.config.ts', fix, message: `neither \`serverURL\` nor \`csrf\` is set: ${why}`, severity: 'warning' }]
},
docs: 'docs/security.md',
group: 'security',
@@ -225,6 +233,30 @@ export const securityRules: DoctorRule[] = [
group: 'security',
source: 'deep',
},
{
// An account of a visitor login collection (customers, members) may write content or settings: Payload fills a
// missing rule with "any signed-in account", and the plugin narrows only its own entities (owner's Q3, 1.17.2).
id: 'visitor-writes',
check: (ctx) => {
const byEntity = new Map<string, string[]>()
for (const entry of ctx.deep?.visitorWrites ?? []) {
const at = entry.lastIndexOf(':')
byEntity.set(entry.slice(0, at), [...(byEntity.get(entry.slice(0, at)) ?? []), entry.slice(at + 1)])
}
return [...byEntity].map(([entity, operations]) => {
const global = entity.startsWith('globals/')
const slug = global ? entity.slice('globals/'.length) : entity
return {
fix: `give ${global ? 'the global' : 'the collection'} "${slug}" its own ${operations.map((o) => `access.${o}`).join(' / ')} (adminOrEditor, requireRole('editor'), …) — Payload's default lets every signed-in account in (access.md "Who is staff")`,
message: `an account of a visitor login collection may ${operations.join(', ')} ${global ? 'the global' : 'in'} "${slug}"`,
severity: 'warning' as const,
}
})
},
docs: 'docs/access.md',
group: 'security',
source: 'deep',
},
{
// A staff collection that an account of another auth collection (a customer, a member) may write to:
// it can create a staff account, or change a staff account's password. The plugin's default rules close
+12 -2
View File
@@ -12,9 +12,11 @@ import { graphAvailable } from '../email/mailAdapter.js'
import { mailPanelState } from '../email/relay/panel.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 { readEnv } from '../shared/envName.js'
import { clientIp, consumeRateLimit, tooManyRequests } from '../shared/rateLimit.js'
import { turnstileSecretFromEnv } from '../turnstile/config.js'
import { visitorWritableEntities } from './visitorWrites.js'
/** The plugin's own version — a constant (src/version.ts), never a file read at run time. */
export function pluginVersion(): string {
@@ -111,7 +113,15 @@ export async function collectDoctorStatus(payload: BasePayload): Promise<DoctorS
} catch {
staffOnOwnRoles = null
}
return { mail, node: process.version, openSignUp, pendingCookies, plugin: pluginVersion(), staffOnOwnRoles, staffOpenToOthers, turnstile, turnstileSecretFromEnv: secretFromEnv, usersSetupClosed, usersWithout2fa }
let visitorWrites: null | string[] = null
try {
visitorWrites = await visitorWritableEntities(payload as never)
} catch {
visitorWrites = null
}
const { csrf, serverURL } = payload.config as { csrf?: unknown; serverURL?: unknown }
const originKnown = (typeof serverURL === 'string' && serverURL.trim() !== '') || (Array.isArray(csrf) && csrf.some((o) => typeof o === 'string' && o.trim() !== ''))
return { mail, node: process.version, openSignUp, originKnown, pendingCookies, plugin: pluginVersion(), staffOnOwnRoles, staffOpenToOthers, turnstile, turnstileSecretFromEnv: secretFromEnv, usersSetupClosed, usersWithout2fa, visitorWrites }
}
export type DoctorEndpointOptions = {
@@ -141,7 +151,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) && (await options.access({ req })) : false)
const allowed = (given && sameToken(given, token)) || (options.access ? secondFactorPassed(req) && accessAllowed('doctor.access', await options.access({ 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' } })
+11
View File
@@ -99,6 +99,11 @@ export type DoctorStatus = {
node?: string
/** Auth collections whose `create` rule lets an anonymous request through (slugs only). */
openSignUp?: null | string[]
/**
* The running config has a `serverURL` (1.17.2), or a non-empty `csrf` list. Without either Payload takes the
* login cookie from any origin, and the plugin's own-origin checks know the site only from the request's host.
*/
originKnown?: boolean
pendingCookies?: null | number
plugin?: string
/**
@@ -118,6 +123,12 @@ export type DoctorStatus = {
/** Of `usersWithout2fa`: accounts whose setup window has passed (blocked until an admin reopens setup). */
usersSetupClosed?: null | number
usersWithout2fa?: null | number
/**
* What an account of a visitor login collection (an auth collection that is not staff) may write, as `pages:create`
* or `globals/header:update` — rules that answer `true` for it, Payload's default included. Empty without a visitor
* login collection; null = could not be checked.
*/
visitorWrites?: null | string[]
}
export type DoctorLive = {
+46
View File
@@ -0,0 +1,46 @@
import { staffCollectionSlugs } from '../access/predicates.js'
type Rule = ((args: never) => unknown) | undefined
type LiveEntity = { access?: Record<string, Rule>; auth?: unknown; slug: string }
type LivePayload = {
collections?: Record<string, { config: LiveEntity }>
config?: { globals?: LiveEntity[] }
}
/**
* What an account of a visitor login collection (a shop's customers, a member zone — an auth collection that is not
* staff) may WRITE: every collection `create` / `update` / `delete` and global `update` whose rule answers a plain
* `true` for such an account, as `pages:create` or `globals/header:update`. For the doctor's `visitor-writes` rule
* (IAWL idea 35, the owner's Q3). Empty when the site has no visitor login collection.
*
* Asked by behaviour, never by the rule's name (a production build renames every function): Payload's default
* ("any signed-in account") and a project's own rule that is as wide both answer `true`. A rule that answers a query
* (e.g. "its own document") is not counted, nor one that throws. Staff collections are left to `staff-accounts-open`.
*/
export async function visitorWritableEntities(payload: LivePayload): Promise<string[]> {
const staff = staffCollectionSlugs(payload as never)
const collections = Object.values(payload.collections ?? {}).map(({ config }) => config)
const visitors = collections.filter((c) => c.auth && !staff.includes(c.slug)).map((c) => c.slug)
if (!visitors.length) {return []}
const open = new Set<string>()
const ask = async (rule: Rule, key: string) => {
for (const collection of visitors) {
const user = { id: '__iapl-visitor__', collection, email: '[email protected]' }
try {
// no rule = Payload's default: any signed-in account
if (!rule || (await rule({ id: '__iapl-other__', req: { context: {}, headers: new Headers(), payload, user } } as never)) === true) {
open.add(key)
return
}
} catch {
/* closed */
}
}
}
for (const config of collections) {
if (staff.includes(config.slug)) {continue}
for (const operation of ['create', 'update', 'delete'] as const) {await ask(config.access?.[operation], `${config.slug}:${operation}`)}
}
for (const global of payload.config?.globals ?? []) {await ask(global.access?.update, `globals/${global.slug}:update`)}
return [...open].sort()
}
+3 -3
View File
@@ -4,7 +4,7 @@ import { createHash, randomBytes } from 'node:crypto'
import type { ResolvedRelayOptions } from './options.js'
import { consumeRateLimit } from '../../shared/rateLimit.js'
import { consumeRateLimit, ipRateKey } from '../../shared/rateLimit.js'
import { type RelayAnswer, type RelayRefusal, relayRequest } from './client.js'
import { RELAY_DEFAULTS, type RelayStatusCode, relayStatusFor } from './constants.js'
import { currentMailKind, type MailKind, mailKindOf, takeExpectedMail } from './kinds.js'
@@ -136,14 +136,14 @@ export async function sendThroughRelay(payload: BasePayload, options: ResolvedRe
const windowMs = (own.windowMinutes ?? RELAY_DEFAULTS.accountMail.windowMinutes) * 60_000
const perAddress = own.perAddress ?? RELAY_DEFAULTS.accountMail.perAddress
const checks = [
...(marked?.visitor ? [{ key: `visitor:${marked.visitor}`, max: own.perVisitor ?? RELAY_DEFAULTS.accountMail.perVisitor }] : []),
...(marked?.visitor ? [{ key: `visitor:${ipRateKey(marked.visitor)}`, max: own.perVisitor ?? RELAY_DEFAULTS.accountMail.perVisitor }] : []),
// 1.18.0: one visitor (IP) gets `perAddress` mails to an address; the address gets `perAddressTotal` from everybody —
// a stranger who fills an address's count from one IP no longer stops its owner's own reset mail (IAWL idea 16).
...[...(request.to ?? []), ...(request.cc ?? []), ...(request.bcc ?? [])].flatMap((address) => {
const to = `to:${sha256Hex(address.toLowerCase())}`
return [
// no visitor known (server code, no IP header): all such requests are one visitor
{ key: marked?.visitor || 'no-visitor', max: perAddress, scope: `mail-relay-account:${to}` },
{ key: marked?.visitor ? ipRateKey(marked.visitor) : 'no-visitor', max: perAddress, scope: `mail-relay-account:${to}` },
{ key: to, max: own.perAddressTotal ?? RELAY_DEFAULTS.accountMail.perAddressTotal },
]
}),
+8 -3
View File
@@ -162,8 +162,13 @@ const builtin = (key: 'checkbox' | 'date' | 'email' | 'message' | 'number' | 'ra
/** Text-like built-ins also get a localized "Placeholder" (select already has one). */
const withHint = (key: 'email' | 'number' | 'text' | 'textarea') => withShowWhen(withPlaceholder(builtinBlocks[key] as Block))
/** REST/GraphQL: only logged-in users. Local API (submitForm) is unaffected. */
const submissionsCreateAccess = ({ req }: AccessArgs) => Boolean(req.user)
/**
* REST/GraphQL: a staff account (any role) with its second factor. Local API (submitForm) is unaffected. Before
* 1.17.2 any signed-in account was enough — a customer of a visitor login collection could POST
* /api/form-submissions past the rate limit, Turnstile, consent and validation, and the form's e-mails went out.
* `formSubmissionOverrides.access.create` is the way back.
*/
const submissionsCreateAccess = ({ req }: AccessArgs) => userMeetsRole(req, 'user')
/**
* Submissions are visitors' personal data: editors and admins only. The
* form-builder default lets ANY account of the admin collection read them —
@@ -205,7 +210,7 @@ function hideEmails(fields: Field[]): Field[] {
* SECURITY: form-builder defaults form-submissions to `create: () => true`, i.e.
* anyone can POST /api/form-submissions and skip everything submitForm enforces
* (rate limit, Turnstile, GDPR consent, schema validation). Here REST/GraphQL
* creation is limited to logged-in users; the site submits through submitForm
* creation is limited to staff accounts with their second factor; the site submits through submitForm
* (server action → Local API, which bypasses access by design). A project that
* really needs public REST submissions can override `formSubmissionOverrides.access.create`.
*/
+3 -1
View File
@@ -3,9 +3,11 @@ export {
checkRateLimit,
clientIp,
consumeRateLimit,
ipRateKey,
retryAfterSeconds,
setIpv6Grouping,
setRateLimitStore,
setUnknownIpFactor,
tooManyRequests,
} from '../shared/rateLimit.js'
export type { ClientIpOptions, RateLimitArgs, RateLimitStore } from '../shared/rateLimit.js'
export type { ClientIpOptions, Ipv6Grouping, RateLimitArgs, RateLimitStore } from '../shared/rateLimit.js'
+13 -4
View File
@@ -21,6 +21,7 @@ import { getConsentTexts } from '../consent/getConsentTexts.js'
import { isPathAllowed, isPathVisibleIn } from '../construction/logic.js'
import { pathOf } from '../construction/visibility.js'
import { createMarkdownRoute } from '../content/createMarkdownRenderer.js'
import { applyDraftRelations, type DraftRelations } from '../content/draftRelations.js'
import { getArchiveEntries, resolveRoute as resolveRouteRaw } from '../content/index.js'
import { MARKDOWN_PREFIX, markdownHref } from '../content/markdownNegotiation.js'
import { resolveRedirect as resolveRedirectRaw } from '../content/resolveRedirect.js'
@@ -54,6 +55,12 @@ type CreateContentHelpersArgs = {
config: Promise<SanitizedConfig> | SanitizedConfig
/** Archive-backed collections, same value as the plugin option. */
content?: ContentOption
/**
* Related documents that are drafts (never published) in what the helpers answer — pages, Site settings (menus,
* System pages), archive entries, the 404 page, llms-full: `'hide'` (default since 1.18.0) leaves them out, as
* if they did not exist; `'keep'` answers them as before. content.md "Drafts as related documents".
*/
draftRelations?: DraftRelations
/**
* i18n config. Required only if you want the ready-made `sitemap` / `robots`
* handlers — they need the locale list to emit hreflang.
@@ -190,6 +197,7 @@ export function createContentHelpers({
baseUrl,
config,
content,
draftRelations = 'hide',
i18n,
markdown: markdownOptions,
markdownAlternate,
@@ -229,7 +237,7 @@ export function createContentHelpers({
*/
const getSettings = cache(async (locale: string) => {
const payload = await getCachedPayload()
return payload.findGlobal({ slug: settingsSlug as never, depth: settingsDepth, locale: locale as never })
return applyDraftRelations(await payload.findGlobal({ slug: settingsSlug as never, depth: settingsDepth, locale: locale as never }), { draftRelations })
})
/** What does this URL point at? Routing only — no listing data. */
@@ -243,6 +251,7 @@ export function createContentHelpers({
const settings = (await getSettings(locale)) as Record<string, unknown>
return resolveRouteRaw({
content,
draftRelations,
locale,
page,
pagesSlug,
@@ -416,7 +425,7 @@ export function createContentHelpers({
locale: locale as never,
})
// a page never published (or unpublished) is a draft: the built-in view, not its text (IAWL idea 23)
return isPublishedDoc(doc) ? (doc as Record<string, unknown>) : null
return isPublishedDoc(doc) ? applyDraftRelations(doc as Record<string, unknown>, { draftRelations }) : null
} catch {
return null // DB unreachable (container build) or page deleted — fallback view
}
@@ -431,7 +440,7 @@ export function createContentHelpers({
perPage: number,
): Promise<ArchiveEntries> => {
const payload = await getCachedPayload()
return getArchiveEntries({ collection, locale, page, payload, perPage })
return getArchiveEntries({ collection, draftRelations, locale, page, payload, perPage })
},
)
@@ -850,7 +859,7 @@ export function createContentHelpers({
return () => (value ??= make())
}
const llms = lazy(() => createLlmsTxtRoute({ baseUrl: origin, config: needI18n('llmsRoute'), content, getCachedPayload, getIncludedPaths: constructionPaths, pagesSlug, settingsSlug, summaryField }))
const llmsFull = lazy(() => createLlmsTxtRoute({ baseUrl: origin, config: needI18n('llmsFullRoute'), content, full: true, getCachedPayload, getIncludedPaths: constructionPaths, pagesSlug, settingsSlug, summaryField }))
const llmsFull = lazy(() => createLlmsTxtRoute({ baseUrl: origin, config: needI18n('llmsFullRoute'), content, draftRelations, full: true, getCachedPayload, getIncludedPaths: constructionPaths, pagesSlug, settingsSlug, summaryField }))
const md = lazy(() => createMarkdownRoute({ baseUrl: origin || undefined, collection: pagesSlug, config: i18n, content, getCachedPayload, isPathVisible, settingsSlug, ...markdownOptions }))
const mcp = lazy(() => createMcpRoute({ baseUrl: origin, collection: pagesSlug, config: needI18n('mcpRoute'), content, getCachedPayload, isPathVisible, settingsSlug, summaryField, ...mcpOptions }))
const health = lazy(() => createHealthRoute({ collection: pagesSlug, getCachedPayload }))
+1
View File
@@ -2,6 +2,7 @@ export {
buildIntegrationStatusBanner,
buildIntegrationStatusField,
recordIntegrationStatus,
writeGlobalFields,
} from './status.js'
export type { IntegrationBannerTexts, IntegrationState, IntegrationStatus } from './status.js'
export type { IntegrationLabel } from './texts.js'
+19 -6
View File
@@ -88,6 +88,24 @@ export function buildIntegrationStatusBanner(
}
}
/**
* Writes these top-level fields of a global and nothing else (owner's decision Q3, 1.18.0). Payload's
* `updateGlobal` reads the whole document, merges the change and writes the whole result, so a status written
* after a visitor's form submit put back an admin's SMTP or Turnstile change saved in between. This writes the
* fields through the database adapter directly: no read of the rest, no merge, no hooks, no new version — fit for
* the plugin's own bookkeeping fields only. A global that does not exist yet is created the usual way.
*/
export async function writeGlobalFields(payload: BasePayload, slug: string, data: Record<string, unknown>): Promise<void> {
const db = (payload as { db?: Partial<BasePayload['db']> }).db
// a stand-in without a database adapter (a test double): the usual way
const existing = typeof db?.findGlobal === 'function' && typeof db.updateGlobal === 'function' ? await db.findGlobal({ slug, req: {} as never }) : null
if (!existing) {
await payload.updateGlobal({ slug: slug as never, context: { ipalIntegrationStatus: true }, data: data as never, depth: 0 })
return
}
await payload.db.updateGlobal({ slug, data: { ...data, updatedAt: new Date().toISOString() }, req: {} as never, returning: false })
}
/**
* Persist a status change. Never throws — a status write must not break the
* request that triggered it. The same change already being written is not
@@ -127,12 +145,7 @@ export async function recordIntegrationStatus(
}
const write = (async () => {
try {
await payload.updateGlobal({
slug: SITE_INTEGRATIONS as never,
context: { ipalIntegrationStatus: true },
data: { [field]: status } as never,
depth: 0,
})
await writeGlobalFields(payload, SITE_INTEGRATIONS, { [field]: status })
} catch (err) {
console.warn(`[iapl] could not record ${field}:`, err instanceof Error ? err.message : err)
} finally {
+71
View File
@@ -0,0 +1,71 @@
import type { Config, Endpoint, PayloadRequest } from 'payload'
import { COOKIE_APPROVAL_PATH } from '../consent/scanner/approval.js'
import { COOKIE_CRAWL_PATH } from '../consent/scanner/crawl/config.js'
import { COOKIE_SCAN_PATH } from '../consent/scanner/endpoint.js'
import { RELAY_CONNECT_PATH, RELAY_DISCONNECT_PATH } from '../email/relay/constants.js'
import { reportRefusedOrigin, requestFromOwnOrigin } from './totp/sameOrigin.js'
/**
* The plugin's panel actions only from the site's own origin (`adminSameOrigin`, 1.17.2; IAWL idea 7, owner's Q6).
*
* These endpoints act with the panel's login cookie and read a body whatever its `Content-Type` says — a
* `text/plain` POST, which another origin can send without a CORS preflight. A page on a sibling subdomain is
* "same site", so the browser sends the `SameSite=Lax` cookie along, and Payload's own CSRF list is empty unless
* `serverURL` or `csrf` is set. Such a page could make a signed-in administrator disconnect the mail service,
* connect it again, send test mails, run cookie scans and crawls, or approve every waiting cookie. The rule is the
* one 2FA verify / setup / reset use (sameOrigin.ts): a request the browser marks as coming from elsewhere
* (`Origin`, else `Sec-Fetch-Site`) gets `403` before anything is read; a request with neither header (a script,
* `curl`) passes — it rides on nobody's cookie. Refusals are logged once per origin with the ways to allow it.
*/
export type AdminSameOriginOption = {
/** More origins that may call these endpoints (a panel on another domain). */
origins?: string[]
} | boolean
/** The panel actions the rule covers: method and path (relative to the API route). */
export const ADMIN_POST_ENDPOINTS: ReadonlyArray<readonly ['post', string]> = [
['post', RELAY_CONNECT_PATH],
['post', RELAY_DISCONNECT_PATH],
['post', '/ipal/test-email'],
['post', COOKIE_SCAN_PATH],
['post', COOKIE_APPROVAL_PATH],
['post', COOKIE_CRAWL_PATH],
]
const ADMIN_REFUSAL = {
docs: 'docs/security.md "Panel actions only from the site\'s own origin"',
option: 'iapl({ adminSameOrigin',
what: 'a panel action',
}
const covered = (endpoint: Pick<Endpoint, 'method' | 'path'>): boolean =>
ADMIN_POST_ENDPOINTS.some(([method, path]) => endpoint.method === method && endpoint.path === path)
/** Wraps one endpoint: `403` for a request from another origin, the endpoint's own answer otherwise. */
export function requireOwnOrigin<T extends Pick<Endpoint, 'handler'>>(endpoint: T, origins: string[] = []): T {
const handler = endpoint.handler as (req: PayloadRequest) => Promise<Response> | Response
return {
...endpoint,
handler: (async (req: PayloadRequest) => {
if (!requestFromOwnOrigin(req as never, origins)) {
reportRefusedOrigin(req as never, origins, ADMIN_REFUSAL)
return Response.json({ message: 'Not allowed from this origin.', ok: false }, { status: 403 })
}
return handler(req)
}) as T['handler'],
}
}
/**
* Applies the rule to the covered endpoints the plugin added (`ownEndpoints`: those not in the project's config
* before iapl ran) — a project's own endpoint on the same path is left as it is.
*/
export function guardAdminEndpoints(config: Config, before: ReadonlySet<unknown>, option: AdminSameOriginOption | undefined): Config {
if (option === false) {return config}
const origins = typeof option === 'object' ? (option.origins ?? []) : []
return {
...config,
endpoints: (config.endpoints ?? []).map((e) => (!before.has(e) && covered(e) ? requireOwnOrigin(e, origins) : e)),
}
}
+78
View File
@@ -0,0 +1,78 @@
import type { Config, PayloadRequest } from 'payload'
import { createHash, timingSafeEqual } from 'node:crypto'
import { userMeetsRole } from '../access/predicates.js'
/**
* Who may run Payload's job queue over HTTP (`GET /api/payload-jobs/run`, `/api/payload-jobs/handle-schedules`,
* both checked by `jobs.access.run`). Payload's own default is any signed-in account of ANY auth collection — a
* customer of a shop included (IAWL idea 35: a route open to the web is a visitor, not the system). Since 1.17.2,
* when the project writes no `jobs.access.run`, iapl sets: an admin signed in with the second factor (an admin's API
* key counts), or `Authorization: Bearer <CRON_SECRET>`. A project's own rule always wins; `jobsRunAccess: false`
* keeps Payload's default. Jobs run in-process (`jobs.autoRun`, `payload jobs:run`, `payload.jobs.run()`) never
* pass through this rule.
*/
export type JobsRunAccessOptions = {
/** The variable holding the cron secret. Default `CRON_SECRET`. Shorter than 16 characters = not used. */
secretVar?: string
}
export const CRON_SECRET_ENV = 'CRON_SECRET'
/** The secret's minimum length: a short one would be guessable over the run route. */
export const CRON_SECRET_MIN_LENGTH = 16
const sha = (value: string) => createHash('sha256').update(value).digest()
/** True when the request carries `Authorization: Bearer <secret>` (constant-time; an unset or short secret never matches). */
export function cronSecretMatches(req: Pick<PayloadRequest, 'headers'>, secret: string | undefined): boolean {
const expected = secret?.trim() ?? ''
if (expected.length < CRON_SECRET_MIN_LENGTH) {return false}
const header = req.headers?.get?.('authorization') ?? ''
if (!/^Bearer\s+/i.test(header)) {return false}
return timingSafeEqual(sha(header.replace(/^Bearer\s+/i, '').trim()), sha(expected))
}
/**
* The rule iapl puts on `jobs.access.run` (exported for a project that writes its own and wants to keep this part):
* jobs: { access: { run: (args) => jobsRunAccess()(args) || myOwnCheck(args) } }
*/
export function jobsRunAccess({ secretVar = CRON_SECRET_ENV }: JobsRunAccessOptions = {}) {
return ({ req }: { req: PayloadRequest }): boolean =>
cronSecretMatches(req, process.env[secretVar]) || userMeetsRole(req, 'admin')
}
/**
* The config with iapl's `jobs.access.run`, only when the project wrote none (checked before Payload fills its
* default in, so a project's rule is never mistaken for Payload's). Also when the config has no `jobs` at all:
* Payload turns the queue on by itself for collections with scheduled publishing. Marks the config
* (`custom.iapl.jobsRunDefault`) so the start-up note knows the rule is iapl's.
*/
export function withJobsRunAccess(config: Config, options: false | JobsRunAccessOptions = {}): Config {
if (options === false || config.jobs?.access?.run) {return config}
const custom = (config.custom ?? {}) as Record<string, unknown>
const iapl = (custom.iapl ?? {}) as Record<string, unknown>
return {
...config,
custom: { ...custom, iapl: { ...iapl, jobsRunDefault: { secretVar: options.secretVar ?? CRON_SECRET_ENV } } },
jobs: { ...config.jobs, access: { ...config.jobs?.access, run: jobsRunAccess(options) } } as Config['jobs'],
}
}
/**
* The one line said at start when the queue is on and the rule is iapl's: how a cron reaches the run route.
* Null when there is nothing to say.
*/
export function jobsRunNotice(config: { custom?: unknown; jobs?: { enabled?: boolean } }): null | string {
const own = ((config.custom as { iapl?: { jobsRunDefault?: { secretVar?: string } } } | undefined)?.iapl)?.jobsRunDefault
if (!own || !config.jobs?.enabled) {return null}
const secretVar = own.secretVar ?? CRON_SECRET_ENV
const secret = process.env[secretVar]?.trim() ?? ''
if (secret.length >= CRON_SECRET_MIN_LENGTH) {return null}
return (
`[iapl] Payload's job queue runs over HTTP (/api/payload-jobs/run, /handle-schedules) only for an admin signed in with the second factor ` +
`or with "Authorization: Bearer <${secretVar}>" (1.17.2), and ${secretVar} is ${secret ? `shorter than ${CRON_SECRET_MIN_LENGTH} characters` : 'not set'}. ` +
`A cron that calls the run route: set ${secretVar} and send the header. In-process runs (jobs.autoRun, payload jobs:run) are not affected. ` +
'Your own jobs.access.run wins; iapl({ jobsRunAccess: false }) keeps Payload\'s default (docs/security.md "Payload\'s job queue").'
)
}
+5
View File
@@ -1,5 +1,6 @@
import type { BasePayload } from 'payload'
import type { DraftRelations } from '../content/draftRelations.js'
import type { ContentOption } from '../content/index.js'
import type { I18nConfig } from '../i18n/index.js'
import type { SiteIndexEntry } from './siteIndex.js'
@@ -19,6 +20,8 @@ type BuildLlmsTxtArgs = {
* collection's own plural label. Usually the most quotable content on a site.
*/
content?: ContentOption
/** Related documents that are drafts (llms-full): `'hide'` (default since 1.18.0) leaves them out, `'keep'` as before. */
draftRelations?: DraftRelations
/**
* Full-content mode (llms-full.txt). When true, each page's full body is
* inlined as Markdown (via blocksToMarkdown) under its heading, so an agent
@@ -78,6 +81,7 @@ export async function buildLlmsTxt({
baseUrl,
config,
content,
draftRelations,
full = false,
include,
layoutField = 'layout',
@@ -105,6 +109,7 @@ export async function buildLlmsTxt({
config,
content,
depth: full ? 1 : 0,
draftRelations,
include,
locales,
pagesSlug,
+4
View File
@@ -1,5 +1,6 @@
import type { BasePayload } from 'payload'
import type { DraftRelations } from '../content/draftRelations.js'
import type { ContentOption } from '../content/index.js'
import type { I18nConfig } from '../i18n/index.js'
import type { SitemapEntry } from './buildSitemapEntries.js'
@@ -33,6 +34,8 @@ export function createLlmsTxtRoute(opts: {
config: I18nConfig
/** Archive-backed collections (blog…) — listed too. Same value as the plugin option. */
content?: ContentOption
/** Related documents that are drafts (llms-full): `'hide'` (default since 1.18.0) leaves them out, `'keep'` as before. */
draftRelations?: DraftRelations
/** Inline every page's full Markdown (llms-full.txt). Default false. */
full?: boolean
getCachedPayload: () => Promise<BasePayload>
@@ -55,6 +58,7 @@ export function createLlmsTxtRoute(opts: {
baseUrl: opts.baseUrl,
config: opts.config,
content: opts.content,
draftRelations: opts.draftRelations,
full: opts.full,
...(allowed ? { include: (path: string) => allowed.has(normalizePath(path)) } : {}),
pagesSlug: opts.pagesSlug,
+5 -1
View File
@@ -3,6 +3,7 @@ import type { BasePayload } from 'payload'
import type { ContentOption } from '../content/index.js'
import type { I18nConfig } from '../i18n/index.js'
import { applyDraftRelations, type DraftRelations } from '../content/draftRelations.js'
import { archiveFieldName } from '../content/index.js'
import { buildLocalizedPath, getLocaleCodes, isValidLocale } from '../i18n/index.js'
import { resolveLocalized } from '../i18n/resolveLocalized.js'
@@ -39,6 +40,8 @@ export type CollectSiteIndexArgs = {
content?: ContentOption
/** Population depth of `doc`. Default 0 (1 when you render blocks with images). */
depth?: number
/** Related documents in `doc` that are drafts: `'hide'` (default since 1.18.0) leaves them out, `'keep'` as before. */
draftRelations?: DraftRelations
/**
* Only paths this returns true for — e.g. the pages still open while the site
* is under construction. Default: every path.
@@ -128,6 +131,7 @@ export async function collectSiteIndex({
config,
content,
depth = 0,
draftRelations,
include,
limit,
locales,
@@ -162,7 +166,7 @@ export async function collectSiteIndex({
if (collection !== pagesSlug && !prefix?.[locale]) {continue}
let docs: Row[] = []
try {
docs = await readDocs(payload, collection, { depth, limit, locale })
docs = applyDraftRelations(await readDocs(payload, collection, { depth, limit, locale }), { draftRelations })
} catch {
continue
}
+33
View File
@@ -0,0 +1,33 @@
/**
* 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).
*
* 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.)
*/
const warned = new Set<string>()
export type AccessAnswerOptions = {
/** 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 {
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").`,
)
}
return Boolean(answer)
}
/** For tests: forget which options were reported. */
export function resetAccessWarnings(): void {
warned.clear()
}
+118 -13
View File
@@ -94,8 +94,103 @@ export function setUnknownIpFactor(factor: number): void {
unknownIpFactor = Math.max(0, factor)
}
/**
* IPv6 is counted per network, not per address (1.17.2, IAWL idea 9). A host with IPv6 gets a whole /64
* (2^64 addresses) — every home connection and every server does — so counting per address gave one visitor
* as many budgets as it has addresses. Every limiter of the plugin (forms, search, MCP, consent log, stats,
* doctor, the mail service's confirm route and account-mail limit) counts a /64 as one client. One home network
* shares the budget then, as an IPv4 home behind one router always did.
*
* Optionally a second, roomier counter per wider network (`wide: 48`, `wideFactor` × the limit): one hosting
* customer often holds a /48 (65,536 /64s). Off by default — mobile carriers can put many phones in one /48.
*/
export type Ipv6Grouping = {
/** Prefix length one client is counted by. Default 64; 128 = per address (as before 1.17.2). 1–128. */
prefix?: number
/** A second counter per this wider prefix (e.g. 48), at `wideFactor` × the limit. Default: none. */
wide?: false | number
/** Multiplier for the wide counter's limit. Default 10. */
wideFactor?: number
}
let ipv6 = { prefix: 64, wide: 0, wideFactor: 10 }
/** How every limiter of the plugin counts IPv6 clients (call once at start). `setIpv6Grouping({ prefix: 128 })` = per address. */
export function setIpv6Grouping(next: Ipv6Grouping = {}): void {
const prefix = next.prefix ?? 64
const wide = next.wide === false || next.wide === undefined ? 0 : next.wide
const wideFactor = next.wideFactor ?? 10
for (const [name, value, min] of [['prefix', prefix, 1], ['wide', wide, 0], ['wideFactor', wideFactor, 1]] as const) {
if (!Number.isInteger(value) || value < min || value > (name === 'wideFactor' ? 1e6 : 128)) {
throw new Error(`[iapl] setIpv6Grouping: ${name} must be a whole number from ${min}${name === 'wideFactor' ? '' : ' to 128'} (received ${JSON.stringify(value)}).`)
}
}
if (wide && wide >= prefix) {throw new Error(`[iapl] setIpv6Grouping: wide (${wide}) must be a shorter prefix than prefix (${prefix}).`)}
ipv6 = { prefix, wide, wideFactor }
}
/** A dotted IPv4 address (no `node:net`: this module also reaches bundles that are not Node's). */
function isIPv4(value: string): boolean {
const parts = value.split('.')
return parts.length === 4 && parts.every((p) => /^\d{1,3}$/.test(p) && Number(p) <= 255)
}
/** The 8 groups of an IPv6 address as numbers (brackets and a zone id allowed), or null when it is not one. */
function ipv6Groups(address: string): null | number[] {
let text = address.replace(/^\[|\]$/g, '').split('%')[0]
if (!text.includes(':') || !/^[0-9a-f:.]+$/i.test(text) || text.split('::').length > 2) {return null}
const v4 = /(?:^|:)(\d+\.\d+\.\d+\.\d+)$/.exec(text)
if (v4) {
if (!isIPv4(v4[1])) {return null}
const [a, b, c, d] = v4[1].split('.').map(Number)
text = text.slice(0, -v4[1].length) + `${((a << 8) | b).toString(16)}:${((c << 8) | d).toString(16)}`
} else if (text.includes('.')) {return null}
const compressed = text.includes('::')
const [head, tail = ''] = compressed ? text.split('::') : [text]
const left = head ? head.split(':') : []
const right = tail ? tail.split(':') : []
if ([...left, ...right].some((g) => !/^[0-9a-f]{1,4}$/i.test(g))) {return null}
const missing = 8 - left.length - right.length
if (compressed ? missing < 1 : missing !== 0) {return null}
return [...left, ...Array(compressed ? missing : 0).fill('0'), ...right].map((g) => parseInt(g, 16))
}
/** `2001:db8:1:2::/64` for any address of that network (`bits` = prefix length). */
function ipv6Network(groups: number[], bits: number): string {
const out = groups.map((g, i) => {
const start = i * 16
if (start >= bits) {return 0}
const keep = Math.min(16, bits - start)
return keep === 16 ? g : g & ((0xffff << (16 - keep)) & 0xffff)
})
return `${out.map((g) => g.toString(16)).join(':')}/${bits}`
}
/**
* The key one client is counted by: an IPv4 address as it is, an IPv4-mapped IPv6 address (`::ffff:1.2.3.4`) as
* its IPv4, an IPv6 address as its network (`setIpv6Grouping`, default /64). Anything else is returned unchanged.
* Use it for a limiter of your own keyed by `clientIp()`.
*/
export function ipRateKey(ip: string): string {
const value = ip.trim()
if (!value || isIPv4(value)) {return value}
const groups = ipv6Groups(value)
if (!groups) {return value}
const mapped = groups.slice(0, 5).every((g) => g === 0) && groups[5] === 0xffff
if (mapped) {return `${groups[6] >> 8}.${groups[6] & 0xff}.${groups[7] >> 8}.${groups[7] & 0xff}`}
return ipv6Network(groups, ipv6.prefix)
}
/** The wide network of an IPv6 key, when the wide counter is on; null otherwise. */
function wideKeyOf(ip: string): null | string {
if (!ipv6.wide) {return null}
const groups = ipv6Groups(ip.trim())
if (!groups || (groups.slice(0, 5).every((g) => g === 0) && groups[5] === 0xffff)) {return null}
return ipv6Network(groups, ipv6.wide)
}
function resolveKey(key: string, max: number): { key: string; max: number } | null {
if (key) {return { key, max }}
if (key) {return { key: ipRateKey(key), max }}
return unknownIpFactor > 0 ? { key: UNKNOWN_IP_KEY, max: max * unknownIpFactor } : null
}
@@ -125,10 +220,16 @@ export function checkRateLimit({ cost = 1, key: rawKey, max: rawMax = 5, scope =
if (!resolved) {return true}
const { key, max } = resolved
const id = `${scope}:${key}`
const current = buckets.get(id)
const used = current && current.resetAt > Date.now() ? current.count : 0
if (used + cost > max) {return false}
const wide = wideKeyOf(rawKey)
const wideId = wide ? `${scope}:${wide}` : null
const used = (bucketId: string) => {
const current = buckets.get(bucketId)
return current && current.resetAt > Date.now() ? current.count : 0
}
if (used(id) + cost > max) {return false}
if (wideId && used(wideId) + cost > max * ipv6.wideFactor) {return false}
hitMemory(id, cost, windowMs)
if (wideId) {hitMemory(wideId, cost, windowMs)}
return true
}
@@ -149,21 +250,25 @@ export async function consumeRateLimit({
if (!resolved) {return { ok: true, retryAfter: 0 }}
const { key, max } = resolved
const id = `${scope}:${key}`
const wide = wideKeyOf(rawKey)
let bucket: Bucket
if (store) {
const hit = async (bucketId: string): Promise<Bucket | null> => {
if (!store) {return hitMemory(bucketId, cost, windowMs)}
try {
bucket = await store.hit(id, cost, windowMs)
return await store.hit(bucketId, cost, windowMs)
} catch (err) {
console.warn('[iapl] rate limit store failed, allowing request:', err instanceof Error ? err.message : err)
return { ok: true, retryAfter: 0 }
return null
}
} else {
bucket = hitMemory(id, cost, windowMs)
}
const bucket = await hit(id)
if (!bucket) {return { ok: true, retryAfter: 0 }}
const wideBucket = wide ? await hit(`${scope}:${wide}`) : null
const retryAfter = Math.max(1, Math.ceil((bucket.resetAt - Date.now()) / 1000))
return { ok: bucket.count <= max, retryAfter }
const over = [bucket.count > max ? bucket : null, wideBucket && wideBucket.count > max * ipv6.wideFactor ? wideBucket : null].filter((b): b is Bucket => b !== null)
const later = over.reduce((at, b) => Math.max(at, b.resetAt), bucket.resetAt)
const retryAfter = Math.max(1, Math.ceil(((over.length ? later : bucket.resetAt) - Date.now()) / 1000))
return { ok: over.length === 0, retryAfter }
}
/**
@@ -190,7 +295,7 @@ export async function releaseRateLimit({ cost = 1, key: rawKey, max: rawMax = 5,
/** Seconds until the key's IN-MEMORY window resets — for a Retry-After header. */
export function retryAfterSeconds(key: string, scope = 'form'): number {
const bucket = buckets.get(`${scope}:${key}`)
const bucket = buckets.get(`${scope}:${key ? ipRateKey(key) : UNKNOWN_IP_KEY}`)
return bucket ? Math.max(1, Math.ceil((bucket.resetAt - Date.now()) / 1000)) : 1
}
+8
View File
@@ -50,9 +50,11 @@ export function assertPluginSwitches(options: Record<string, unknown>): void {
// `accounts: 0` / `''` dropped every account rule (staff-only reads, admin-only writes, the panel role,
// the password rule, the closed first-user route).
assertSwitchOrObject('accounts', options.accounts, { allowTrue: false })
// 1.17.2: only 'payload' brings Payload's "locked" answer back (it tells which addresses have an account).
// 1.18.0: the sign-in rules. `signInLimit: 0` / `'false'` must not read as off; a limit of 0 never refuses.
const accounts = bag(options.accounts)
if (accounts) {
assertOneOf('accounts.lockedAnswer', accounts.lockedAnswer, ['payload', 'wrong'])
assertBooleanSwitch('accounts.confirmOwnChanges', accounts.confirmOwnChanges)
assertSwitchOrObject('accounts.signInLimit', accounts.signInLimit, { allowTrue: false })
const limit = bag(accounts.signInLimit)
@@ -78,6 +80,12 @@ export function assertPluginSwitches(options: Record<string, unknown>): void {
assertSwitchOrObject(name, options[name])
}
assertBooleanSwitch('indexNow', options.indexNow)
// 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)
if (adminSameOrigin && adminSameOrigin.origins !== undefined && !(Array.isArray(adminSameOrigin.origins) && adminSameOrigin.origins.every((o) => typeof o === 'string'))) {
throw new Error(`${where('adminSameOrigin.origins')} must be a list of origins such as ['https://panel.example.com'] (received ${JSON.stringify(adminSameOrigin.origins)}).`)
}
// an unknown name ('IAPL') used to mean 'ipal': the scanner declared one visitor cookie while the site set another
assertOneOf('storageNames', options.storageNames, ['ipal', 'iapl'])
assertBooleanSwitch('lightbox', options.lightbox)
+22 -2
View File
@@ -12,7 +12,8 @@ import { buildNotifications } from './globals/Notifications/index.js'
import { applyGlobalOverrides } from './globals/overrides.js'
import { buildSiteIntegrations } from './globals/SiteIntegrations/index.js'
import { buildSiteSettings } from './globals/SiteSettings/index.js'
import { adminOnly, adminOrSelfIn, injectRoles, registerStaffCollections, staffCollectionSlugs } from './modules/access/index.js'
import { adminOnly, adminOrSelfIn, injectRoles, registerStaffCollections, staffCollectionSlugs, withVersionReadRules } from './modules/access/index.js'
import { withLockedAnswer } from './modules/access/lockedAnswer.js'
import { applyPanelRole, countBelowPanelRole, resolvePanelRole } from './modules/access/panelRole.js'
import { applyPasswordRule, buildPasswordRuleHook, resolvePasswordRule } from './modules/access/passwordRule.js'
import { adoptLateAuthCollections, applyFirstUserRoute, applyStaffAccountAccess, markSeenAuthCollections, markStaffRules, staffCollectionsNobodyManages, unknownStaffCollections } from './modules/access/selfRegistration.js'
@@ -50,6 +51,8 @@ import { withFillLocales } from './modules/hooks/fillEmptyLocales.js'
import { buildLocalizationConfig, validateI18nConfig } from './modules/i18n/index.js'
import { serverText } from './modules/integrations/texts.js'
import { buildSystemPagesFields } from './modules/pages/index.js'
import { guardAdminEndpoints } from './modules/security/adminSameOrigin.js'
import { jobsRunNotice, withJobsRunAccess } from './modules/security/jobsAccess.js'
import { missingImportMapEntries } from './modules/security/totp/importMapCheck.js'
import { changedViewKeys, copyViews, SAFE_TOTP_VIEW, wrapTotpViews } from './modules/security/totp/safeBack.js'
import { reportRefusedOrigin, requestFromOwnOrigin } from './modules/security/totp/sameOrigin.js'
@@ -130,6 +133,8 @@ export const iapl = (options: IaplOptions): Plugin => {
async function transform(incomingConfig: Config): Promise<Config> {
let config = { ...incomingConfig }
/** The project's own endpoints: the panel-action origin rule (adminSameOrigin) is for the plugin's only. */
const projectEndpoints = new Set<unknown>(incomingConfig.endpoints ?? [])
// Text written in one language fills the empty languages of the same field (cookie list, cookie review).
const fillDefaults = { 'cookie-review': ['purpose', 'retention'], 'cookie-settings': ['cookies.purpose', 'cookies.duration'] }
@@ -265,6 +270,8 @@ export const iapl = (options: IaplOptions): Plugin => {
collections: (config.collections ?? []).map((c) => (staffSlugs.includes(c.slug) ? applySignInRules(c, accounts) : c)),
hooks: { ...config.hooks, afterError: [...(config.hooks?.afterError ?? []), settleFailedSignIn as never] },
}
// A locked staff account answers like a wrong password (accounts.lockedAnswer).
if (accounts.lockedAnswer !== 'payload') {config = withLockedAnswer(config)}
}
if (options.twoFactor !== false) {
const tf = options.twoFactor
@@ -773,7 +780,7 @@ export const iapl = (options: IaplOptions): Plugin => {
reenterSecretOnChange: options.secrets?.reenterOnChange !== false,
writeOnlySecrets: options.secrets?.writeOnly !== false,
}),
withFillLocales('global', buildCookieSettings(), fillLocales['cookie-settings']),
withFillLocales('global', buildCookieSettings(options.cookieSettings), fillLocales['cookie-settings']),
buildNotifications({ lightbox: options.lightbox === true }),
]
// A global feeds every page's layout — revalidate the site on save.
@@ -988,6 +995,9 @@ export const iapl = (options: IaplOptions): Plugin => {
},
}
// --- Payload's job queue over HTTP: an admin or the cron secret, unless the project wrote its own rule
config = withJobsRunAccess(config, options.jobsRunAccess ?? {})
// --- second factor on everything in the config by now: the project's
// collections (wrapped by the package already; twice is harmless), the
// plugin's globals and collections, the form builder's.
@@ -1017,6 +1027,9 @@ export const iapl = (options: IaplOptions): Plugin => {
watchTransactions(payload, options.connectionReserve === false ? false : (options.connectionReserve ?? defaultConnectionReserve(poolSize(payload) ?? 10)))
// Microsoft Graph is deprecated (removed in 2.0): one warning per start while its variables are set.
if (graphAvailable() && options.mail?.graphDeprecationWarning !== false) {payload.logger.warn(GRAPH_DEPRECATION_NOTICE)}
// The queue is on and the run route is iapl's: say how a cron reaches it, when the secret is missing.
const jobsNotice = jobsRunNotice(payload.config as never)
if (jobsNotice) {payload.logger.warn(jobsNotice)}
// Payload's dev reload swaps `payload.config` and runs no onInit: adopt the new config at once.
watchPayloadConfig(payload, adoptConfig)
if (staleSignInLook) {
@@ -1100,11 +1113,18 @@ export const iapl = (options: IaplOptions): Plugin => {
payload.logger.info('[iapl] Plugin initialized.')
}
// readVersions: readPublished() asks for `version._status` on version history (readPublishedVersions).
config.collections = withVersionReadRules(config.collections)
config.globals = withVersionReadRules(config.globals)
// Every auth collection of this config has been seen: what appears later is a late one (adoptConfig).
if (accounts) {
const panel = config.admin?.user ?? (config.collections ?? []).find((c) => c.auth)?.slug
config = markSeenAuthCollections(config, staffCollectionSlugs({ admin: { user: panel }, custom: config.custom }))
}
// The plugin's panel actions (mail service connect / disconnect, test e-mail, cookie scan / approval / crawl)
// only from the site's own origin (adminSameOrigin).
config = guardAdminEndpoints(config, projectEndpoints, options.adminSameOrigin)
return config
}
}
+28 -1
View File
@@ -26,6 +26,8 @@ import type { FormsOption } from './modules/forms/types.js'
import type { RevalidatePathFn } from './modules/hooks/buildRevalidateHook.js'
import type { I18nConfig } from './modules/i18n/types.js'
import type { PagesOption } from './modules/pages/types.js'
import type { AdminSameOriginOption } from './modules/security/adminSameOrigin.js'
import type { JobsRunAccessOptions } from './modules/security/jobsAccess.js'
import type { SafeBackRule } from './modules/security/totp/safeBack.js'
import type { RequireSetupOptions } from './modules/security/totp/setupRequired.js'
import type { VerifyLimitOptions } from './modules/security/totp/verifyLimit.js'
@@ -57,7 +59,6 @@ export type IaplOptions = {
* Keys the project sets in its own `admin.meta` always win. `false` = Payload's defaults.
*/
adminMeta?: AdminMetaOptions | false
/**
* Custom admin panel route, e.g. '/its' instead of the default '/admin'.
* The plugin sets config.routes.admin. IMPORTANT: this alone isn't enough —
@@ -70,6 +71,15 @@ export type IaplOptions = {
*/
adminRoute?: string
/**
* The plugin's panel actions — `POST` mail service connect / disconnect, test e-mail, cookie scan, cookie
* approval, cookie crawl — refuse (`403`) a request a browser marks as coming from another origin, before
* anything is read (1.17.2). Own origins: the request's host (`Host`, `X-Forwarded-Host`), `serverURL`,
* Payload's `csrf` and `cors` lists, and `origins` here. `false` = no check (as before 1.17.2).
* The 2FA endpoints follow `twoFactor.sameOrigin`. docs/security.md "Panel actions only from the site's own origin".
*/
adminSameOrigin?: AdminSameOriginOption
/**
* Who supports the technology, named in the admin credit, the panel's link
* description and its preview image. Default `{ name: 'Intecion.com', url: 'https://intecion.com' }`.
@@ -119,6 +129,13 @@ export type IaplOptions = {
*/
cookieScanner?: boolean | CookieScannerOptions
/**
* Cookie settings (the global). `allowLowerPolicyVersion: true` lets an editor LOWER the consent version, as
* before 1.17.2 — a lower number makes consent given under an older policy valid again, so by default a save
* through access control with a lower number is refused (the Local API with `overrideAccess` may still).
*/
cookieSettings?: { allowLowerPolicyVersion?: boolean }
/**
* Forms — form-builder collections (forms, form-submissions) plus the
* callable submitForm (Turnstile + persistence + SMTP-from-panel email).
@@ -200,6 +217,16 @@ export type IaplOptions = {
/** Additional fields injected into SiteIntegrations global */
integrationsFields?: Field[]
/**
* Who may run Payload's job queue over HTTP (`/api/payload-jobs/run`, `/handle-schedules`) when the project
* writes no `jobs.access.run` of its own: an admin signed in with the second factor (an admin's API key counts), or
* `Authorization: Bearer <CRON_SECRET>` (16+ characters). Default on since 1.17.2; `secretVar` names another
* variable; `false` keeps Payload's default (any signed-in account of any auth collection). A project's own
* `jobs.access.run` always wins. In-process runs (`jobs.autoRun`, `payload jobs:run`) are not affected.
* docs/security.md "Payload's job queue".
*/
jobsRunAccess?: false | JobsRunAccessOptions
/**
* Image lightbox labels in the Notifications global (a "Lightbox" group:
* close, previous, next, counter, dialog name, trigger name), localized per
+1 -1
View File
@@ -7,4 +7,4 @@
* `/_next/static/media/`. Written by `node scripts/write-version.mjs` (the `version` script of
* package.json runs it on `pnpm version …`); test/version.test.ts fails when the two differ.
*/
export const PLUGIN_VERSION = '1.17.1'
export const PLUGIN_VERSION = '1.17.2'
+52
View File
@@ -0,0 +1,52 @@
/**
* 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.
*/
import { readFileSync } from 'node:fs'
import { beforeEach, describe, expect, test, vi } from 'vitest'
import { accessAllowed, resetAccessWarnings } from '../src/modules/shared/accessAnswer.js'
beforeEach(() => resetAccessWarnings())
describe('accessAllowed', () => {
test('true and false are read as they are, without a word', () => {
const warn = vi.fn()
expect(accessAllowed('cookieScanner.access', true, { warn })).toBe(true)
expect(accessAllowed('cookieScanner.access', false, { warn })).toBe(false)
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) => {
const warn = vi.fn()
expect(accessAllowed('doctor.access', answer, { warn })).toBe(allowed)
expect(accessAllowed('doctor.access', answer, { warn })).toBe(allowed)
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')
})
test('each option is reported on its own', () => {
const warn = vi.fn()
accessAllowed('doctor.access', 'x', { warn })
accessAllowed('cookieScanner.access', 'x', { warn })
expect(warn).toHaveBeenCalledTimes(2)
})
})
test('every call of a project access callback goes through accessAllowed', () => {
const sites = ['src/modules/consent/scanner/endpoint.ts', 'src/modules/consent/scanner/approval.ts', 'src/modules/consent/scanner/crawl/endpoints.ts', 'src/modules/doctor/status.ts']
for (const file of sites) {
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)
}
})
+24
View File
@@ -159,6 +159,30 @@ describe('forms collection: public read, editor+ write, Emails hidden from plain
})
})
describe('form submissions over REST / GraphQL: staff only (1.17.2)', () => {
const build = async (forms: object = {}) => {
const config = await iapl({ access: { authCollection: 'users' }, forms, i18n, twoFactor: false })(
empty({ collections: [{ slug: 'customers', auth: true, fields: [] }] }),
)
return config.collections?.find((c) => c.slug === 'form-submissions') as CollectionConfig
}
// the staff check reads the panel's collection from the request's Payload, as in a request
const runAs = (fn: Access | undefined, u: unknown) =>
(fn as Access)({ req: { payload: { config: { admin: { user: 'users' } } }, user: u } } as never)
test('a customer account, or nobody, cannot create a submission; any staff role can', async () => {
const { access = {} } = await build()
expect(runAs(access.create, null)).toBe(false)
expect(runAs(access.create, { id: 9, collection: 'customers' })).toBe(false)
for (const staff of [user, editor, admin]) {expect(runAs(access.create, staff)).toBe(true)}
})
test('formSubmissionOverrides.access.create is the way back', async () => {
const { access = {} } = await build({ formSubmissionOverrides: { access: { create: () => true } } })
expect(runAs(access.create, { id: 9, collection: 'customers' })).toBe(true)
})
})
describe('roles field: the first-register account becomes admin', () => {
const hook = async (totalDocs: number, value: string[], pathname = '/api/users/first-register') => {
const config = await iapl({ access: { authCollection: 'users' }, i18n, twoFactor: false })(empty())
+38
View File
@@ -0,0 +1,38 @@
/** The plugin's panel actions refuse other origins (adminSameOriginSuite.ts). */
import { describe, expect, test, vi } from 'vitest'
import { guardAdminEndpoints } from '../src/modules/security/adminSameOrigin.js'
import { clearReportedOrigins } from '../src/modules/security/totp/sameOrigin.js'
import { ACTIONS, adminSite, SIBLING } from './adminSameOriginSuite.js'
vi.mock('server-only', () => ({}))
vi.mock('next/headers.js', async () => (await import('./http/server.js')).nextHeadersMock)
const { action, state } = adminSite()
describe('adminSameOrigin (default): panel actions only from the site\'s own origin', () => {
test('a page on a sibling subdomain, or a cross-site page, gets 403 on every panel action, with the admin cookie', async () => {
clearReportedOrigins()
for (const path of ACTIONS) {
expect([path, (await action(path, SIBLING)).status]).toEqual([path, 403])
expect([path, (await action(path, { 'sec-fetch-site': 'cross-site' })).status]).toEqual([path, 403])
}
// said in the log once per origin, naming this option
const lines = state.warn.filter((l) => l.includes('blog.site.example'))
expect(lines).toHaveLength(1)
expect(lines[0]).toMatch(/adminSameOrigin/)
})
test('the site\'s own page and a script without browser headers still reach them', async () => {
const own = await action('/ipal/cookie-approval', { origin: state.server.url, 'sec-fetch-site': 'same-origin' }, '{"ids":[]}')
expect(own.status).toBe(200)
const script = await action('/ipal/cookie-approval', {}, '{"ids":[]}')
expect(script.status).toBe(200)
})
test('a project\'s own endpoint on one of these paths is left as it is', () => {
const own = { handler: () => Response.json({ ok: true }), method: 'post' as const, path: '/ipal/test-email' }
const config = guardAdminEndpoints({ endpoints: [own] } as never, new Set([own]), undefined)
expect(config.endpoints?.[0]).toBe(own)
})
})
+22
View File
@@ -0,0 +1,22 @@
/** adminSameOrigin: false leaves the origin check out (adminSameOriginSuite.ts). */
import { describe, expect, test, vi } from 'vitest'
import { iapl } from '../src/plugin.js'
import { adminSite, SIBLING } from './adminSameOriginSuite.js'
vi.mock('server-only', () => ({}))
vi.mock('next/headers.js', async () => (await import('./http/server.js')).nextHeadersMock)
const { action } = adminSite(false)
describe('adminSameOrigin: false', () => {
test('a request from a sibling subdomain reaches the action, as before 1.17.2', async () => {
expect((await action('/ipal/cookie-approval', SIBLING, '{"ids":[]}')).status).toBe(200)
})
test('a value nobody understands stops the start', async () => {
const i18n = { defaultLocale: 'en', locales: [{ code: 'en', label: 'English' }] }
await expect((async () => iapl({ adminSameOrigin: 0 as never, i18n } as never)({ collections: [], secret: 'x' } as never))()).rejects.toThrow(/adminSameOrigin must be/)
await expect((async () => iapl({ adminSameOrigin: { origins: 'https://a.example' as never }, i18n } as never)({ collections: [], secret: 'x' } as never))()).rejects.toThrow(/adminSameOrigin\.origins must be a list/)
})
})
+70
View File
@@ -0,0 +1,70 @@
/**
* The plugin's panel actions only from the site's own origin (adminSameOrigin, 1.17.2). Shared by
* adminSameOrigin.test.ts (default) and adminSameOriginOff.test.ts (`adminSameOrigin: false`): one Payload per file.
* A signed-in administrator's cookie rides on a `text/plain` POST (no CORS preflight) from a page on a sibling
* subdomain. Database: SQLite in memory, or IPAL_TEST_POSTGRES_URI / IPAL_TEST_MONGO_URI (test/http/db.ts).
*/
import type { Payload } from 'payload'
import { payloadTotp } from '@clocklimited/payload-2fa'
import { lexicalEditor } from '@payloadcms/richtext-lexical'
import { getPayload } from 'payload'
import { afterAll, beforeAll } from 'vitest'
import { iapl } from '../src/plugin.js'
import { buildTestConfig } from './helpers.js'
import { testDatabase } from './http/db.js'
import { cookiesOf, startPayloadServer, type TestServer } from './http/server.js'
import { totp } from './http/totp.js'
const SECRET = 'JBSWY3DPEHPK3PXP'
const PASSWORD = 'a-long-test-password-1'
export const SIBLING = { origin: 'https://blog.site.example', 'sec-fetch-site': 'same-site' }
/** Every panel action the rule covers (path under /api). */
export const ACTIONS = ['/iapl/mail-relay/connect', '/iapl/mail-relay/disconnect', '/ipal/test-email', '/ipal/cookie-scan', '/ipal/cookie-approval', '/ipal/cookie-crawl']
export function adminSite(adminSameOrigin?: false) {
const state = {} as { cookie: string; payload: Payload; server: TestServer; warn: string[] }
beforeAll(async () => {
process.env.IAPL_COOKIE_SCAN_URL ??= 'http://127.0.0.1:9'
process.env.IAPL_COOKIE_SCAN_TOKEN ??= 'test-token-0123456789abcdef0123456789'
const config = buildTestConfig({
admin: { user: 'users' },
collections: [{ slug: 'media', fields: [], upload: { staticDir: '/tmp/iapl-admin-origin-media' } }],
db: testDatabase('adminorigin'),
editor: lexicalEditor(),
plugins: [
iapl({
access: { authCollection: 'users' },
...(adminSameOrigin === false ? { adminSameOrigin } : {}),
cookieScanner: { crawl: true },
i18n: { defaultLocale: 'en', locales: [{ code: 'en', label: 'English' }] },
twoFactor: { issuer: 'Example', plugin: payloadTotp },
}),
],
secret: 'integration-test-secret-0123456789',
telemetry: false,
})
state.payload = await getPayload({ config })
state.warn = []
const warn = state.payload.logger.warn.bind(state.payload.logger)
state.payload.logger.warn = ((msg: unknown, ...rest: unknown[]) => {
state.warn.push(String(msg))
return (warn as (...a: unknown[]) => void)(msg, ...rest)
}) as never
state.server = await startPayloadServer(config)
await state.payload.create({ collection: 'users' as never, data: { email: '[email protected]', password: PASSWORD, roles: ['admin'], totpSecret: SECRET } as never })
const login = await fetch(`${state.server.url}/api/users/login`, { body: JSON.stringify({ email: '[email protected]', password: PASSWORD }), headers: { 'content-type': 'application/json' }, method: 'POST' })
const first = cookiesOf(login)
const verify = await fetch(`${state.server.url}/api/verify-totp`, { body: JSON.stringify({ token: totp(SECRET) }), headers: { 'content-type': 'application/json', cookie: first.join('; ') }, method: 'POST' })
state.cookie = [...first, ...cookiesOf(verify)].join('; ')
}, 120_000)
afterAll(async () => {
await state.server?.close()
await state.payload?.destroy?.()
})
/** A POST as a foreign page can send it: text/plain, the admin's cookie. */
const action = (path: string, headers: Record<string, string>, body = '{"to":"[email protected]"}') =>
fetch(`${state.server.url}/api${path}`, { body, headers: { 'content-type': 'text/plain', cookie: state.cookie, ...headers }, method: 'POST', signal: AbortSignal.timeout(20_000) })
return { action, state }
}
+5 -3
View File
@@ -168,7 +168,7 @@ describe('server render', () => {
test('firstPaint={false}: nothing in the HTML, as before 1.17.0', () => {
const html = renderToString(tree({ banner: { firstPaint: false } }))
expect(html).not.toContain('data-ipal="banner"')
expect(html).not.toContain('<script')
expect(html).not.toContain('data-ipal="banner-script"')
})
test('nonce: from the provider, or the banner prop', () => {
@@ -444,9 +444,11 @@ describe('tags: nothing earlier than before', () => {
const pixels = { clarityProjectId: 'clar', consentMode: 'basic', gtmContainerId: 'GTM-TEST', metaPixelId: '123' }
const layer = () => [...((window.dataLayer ?? []))].map((entry) => (Object.prototype.toString.call(entry) === '[object Arguments]' ? Array.from(entry as ArrayLike<unknown>) : entry))
test('the server HTML holds one script, the banner one, and it names no tag', () => {
test("the server HTML holds two scripts, the banner's and the cookie button's (1.17.2), and neither names a tag", () => {
const html = renderToString(tree({ analytics: pixels }))
expect(html.match(/<script/g)).toHaveLength(1)
expect(html.match(/<script[^>]*data-ipal="(?:banner|cookie-button)-script"/g)).toHaveLength(2)
expect(html.match(/<script/g)).toHaveLength(2)
expect(html).not.toMatch(/createElement\(["']script|\.src\s*=|fetch\(|XMLHttpRequest|dataLayer|document\.cookie\s*=[^=]/)
expect(html).not.toMatch(/googletagmanager|facebook|clarity|GTM-TEST/)
})
+347
View File
@@ -0,0 +1,347 @@
// @vitest-environment happy-dom
/**
* Where <CookieButton> sits (1.17.2): the bottom corner of the window, always. It never moves — not above the
* footer, not at the end of the page. So that it covers nothing there, the footer gets room under its last row
* while the button is shown (measured, only what is missing). The placement before 1.17.2 stays available.
*/
import { act, createElement, type ReactElement } from 'react'
import { createRoot, hydrateRoot, type Root } from 'react-dom/client'
import { renderToString } from 'react-dom/server'
import { afterEach, beforeEach, describe, expect, test, vi } from 'vitest'
import { ConsentProvider } from '../src/modules/consent/ConsentContext.js'
import { resetConsentStore } from '../src/modules/consent/consentStore.js'
import { COOKIE_BUTTON_AVOID, CookieButton } from '../src/modules/consent/CookieButton.js'
import { COOKIE_BUTTON_RESERVE, COOKIE_BUTTON_SPACE_ATTRIBUTE, reserveCookieButtonSpace } from '../src/modules/consent/cookieButtonSpace.js'
import { CONSENT_FALLBACK } from '../src/modules/consent/getConsentTexts.js'
import { CONSENT_COOKIE, serializeConsent } from '../src/modules/consent/storage.js'
const h = createElement as unknown as (type: unknown, props?: null | object, ...children: unknown[]) => ReactElement
;(globalThis as { IS_REACT_ACT_ENVIRONMENT?: boolean }).IS_REACT_ACT_ENVIRONMENT = true
type Box = { bottom: number; left: number; right: number; top: number }
const box = (top: number, bottom: number, left = 16, right = 60): Box => ({ bottom, left, right, top })
const rect = (r: Box) => ({ ...r, height: r.bottom - r.top, width: r.right - r.left, x: r.left, y: r.top }) as DOMRect
/** The button's place in an 800 px high window: 44 px, 16 px from the bottom and the left. Zone to keep free: 68 px. */
const REST = box(740, 784)
const ZONE = 800 - 740 + 8
const NONE = box(0, 0, 0, 0)
/** A fake layout: boxes per element, text boxes per element whose text they are, own bottom padding per element. */
let boxes: Map<Element, Box>
let page: { height: number; scrollY: number }
const place = (el: Element, r: Box) => (boxes.set(el, r), el)
const add = (html: string, parent: Element = document.body) => {
const holder = document.createElement('div')
holder.innerHTML = html
const el = holder.firstElementChild!
parent.appendChild(el)
return el as HTMLElement
}
const liveCookies = () => document.cookie.split('; ').filter((c) => c.split('=')[1])
const clearCookies = () => {
for (const c of document.cookie.split('; ')) {
if (c.split('=')[0]) {document.cookie = `${c.split('=')[0]}=;path=/;max-age=0`}
}
}
const decide = () => {
document.cookie = `${CONSENT_COOKIE}=${serializeConsent({ analytics: false, functional: false, marketing: false, necessary: true })};path=/`
}
beforeEach(() => {
clearCookies()
resetConsentStore()
boxes = new Map()
page = { height: 3000, scrollY: 2200 } // scrolled to the end: the page ends at y = 800, the window's bottom edge
vi.spyOn(Element.prototype, 'getBoundingClientRect').mockImplementation(function (this: Element) {
// the real button, once React has put it in the page
if (this.getAttribute('data-ipal') === 'cookie-button') {return rect(REST)}
// the probe that stands in for a button that is not there yet
if (!boxes.has(this) && (this as HTMLElement).style?.position === 'fixed') {return rect(REST)}
return rect(boxes.get(this) ?? NONE)
})
vi.spyOn(Range.prototype, 'getClientRects').mockImplementation(function (this: Range) {
const parent = this.startContainer.parentElement
return [rect((parent && boxes.get(parent)) ?? NONE)] as unknown as DOMRectList
})
vi.spyOn(window, 'innerHeight', 'get').mockReturnValue(800)
vi.spyOn(window, 'scrollY', 'get').mockImplementation(() => page.scrollY)
vi.spyOn(document.documentElement, 'scrollHeight', 'get').mockImplementation(() => page.height)
})
afterEach(() => {
reserveCookieButtonSpace({ release: true, selector: COOKIE_BUTTON_RESERVE, side: 'left' })
document.body.innerHTML = ''
document.body.removeAttribute('style')
vi.restoreAllMocks()
})
/** A footer whose last row (a link) ends `gap` px above the end of the page, in the button's corner or elsewhere. */
function footer({ gap = 20, left = 30, padding = '' }: { gap?: number; left?: number; padding?: string } = {}) {
const el = add(`<footer${padding ? ` style="padding-bottom:${padding}"` : ''}><p>© Example</p><a href="/x">Instagram</a></footer>`)
place(el, box(500, 800, 0, 390))
place(el.querySelector('p')!, box(700, 720, 200, 380)) // text elsewhere on the row above
place(el.querySelector('a')!, box(800 - gap - 20, 800 - gap, left, left + 90))
return el
}
const button = () => place(add('<button style="position:fixed">cookies</button>'), REST) as HTMLElement
const reserve = (options: object = {}) => reserveCookieButtonSpace({ button: button(), selector: COOKIE_BUTTON_RESERVE, side: 'left', ...options })
describe('reserveCookieButtonSpace', () => {
test('a link in the corner, 20 px above the end of the page: the footer gets the 48 px that are missing', () => {
const el = footer()
expect(reserve()).toBe(ZONE - 20)
expect(el.style.paddingBottom).toBe('48px')
expect(el.hasAttribute(COOKIE_BUTTON_SPACE_ATTRIBUTE)).toBe(true)
})
test("the footer's own bottom padding counts: only the difference is added, and it is put back on release", () => {
const el = footer({ gap: 32, padding: '32px' })
expect(reserve()).toBe(ZONE - 32)
expect(el.style.paddingBottom).toBe('68px') // 32 own + 36
expect(reserveCookieButtonSpace({ release: true, selector: COOKIE_BUTTON_RESERVE, side: 'left' })).toBe(0)
expect(el.style.paddingBottom).toBe('32px')
expect(el.hasAttribute(COOKIE_BUTTON_SPACE_ATTRIBUTE)).toBe(false)
})
test('enough room already (a project with a generous footer): nothing is added, nothing is touched', () => {
const el = footer({ gap: 80, padding: '80px' })
expect(reserve()).toBe(0)
expect(el.style.paddingBottom).toBe('80px')
expect(el.hasAttribute(COOKIE_BUTTON_SPACE_ATTRIBUTE)).toBe(false)
})
test('nothing in the corner (the row is on the other side): no room', () => {
const el = footer({ left: 250 })
expect(reserve()).toBe(0)
expect(el.style.paddingBottom).toBe('')
})
test('side="right": the other corner is measured', () => {
footer({ left: 250 })
const right = place(add('<button style="position:fixed">cookies</button>'), box(740, 784, 330, 374)) as HTMLElement
expect(reserveCookieButtonSpace({ button: right, selector: COOKIE_BUTTON_RESERVE, side: 'right' })).toBe(48)
})
test('called again and again (resize, late content): the same room, never added twice', () => {
const el = footer()
const b = button()
for (let i = 0; i < 4; i++) {expect(reserveCookieButtonSpace({ button: b, selector: COOKIE_BUTTON_RESERVE, side: 'left' })).toBe(48)}
expect(el.style.paddingBottom).toBe('48px')
})
test('several footers (an article footer first): the last one on the page', () => {
const article = place(add('<article><footer><a href="/a">author</a></footer></article>').querySelector('footer')!, box(300, 340, 0, 390)) as HTMLElement
const el = footer()
reserve()
expect(article.style.paddingBottom).toBe('')
expect(el.style.paddingBottom).toBe('48px')
})
test('no footer on the page: <body> gets what its own padding does not cover', () => {
expect(reserve()).toBe(ZONE)
expect(document.body.style.paddingBottom).toBe('68px')
reserveCookieButtonSpace({ release: true, selector: COOKIE_BUTTON_RESERVE, side: 'left' })
expect(document.body.style.paddingBottom).toBe('')
})
test('a selector of your own', () => {
footer()
const bar = place(add('<div class="legal"><a href="/t">Terms</a></div>'), box(760, 800, 0, 390)) as HTMLElement
place(bar.querySelector('a')!, box(770, 790, 20, 80))
expect(reserve({ selector: '.legal' })).toBe(ZONE - 10)
expect(bar.style.paddingBottom).toBe('58px')
expect(document.querySelector('footer')!.style.paddingBottom).toBe('')
})
test('--ipal-cookie-button-space: the project sets the amount; 0 = none', () => {
const el = footer()
el.style.setProperty('--ipal-cookie-button-space', '5rem')
reserve()
expect(el.style.paddingBottom).toBe('calc(0px + 5rem)')
el.style.setProperty('--ipal-cookie-button-space', '0px')
expect(reserve()).toBe(0)
expect(el.style.paddingBottom).toBe('')
el.style.setProperty('--ipal-cookie-button-space', '0')
expect(reserve()).toBe(0)
})
test('a button the project placed in the flow (not fixed) covers nothing: no room', () => {
const el = footer()
const inFlow = place(add('<button>cookies</button>'), REST) as HTMLElement
expect(reserveCookieButtonSpace({ button: inFlow, selector: COOKIE_BUTTON_RESERVE, side: 'left' })).toBe(0)
expect(el.style.paddingBottom).toBe('')
})
test('before the button exists: the default button is measured with a probe that leaves no trace', () => {
const el = footer()
const nodes = document.body.childElementCount
expect(reserveCookieButtonSpace({ selector: COOKIE_BUTTON_RESERVE, side: 'left' })).toBe(48)
expect(document.body.childElementCount).toBe(nodes)
expect(el.style.paddingBottom).toBe('48px')
})
test('sheet mode (before hydration): the element is not touched; the next plain call moves the room onto it', () => {
const wrap = add('<div><span>x</span></div>')
const el = footer()
wrap.appendChild(el)
expect(reserveCookieButtonSpace({ selector: COOKIE_BUTTON_RESERVE, sheet: true, side: 'left' })).toBe(48)
expect(el.getAttribute('style')).toBeNull()
expect(el.hasAttribute(COOKIE_BUTTON_SPACE_ATTRIBUTE)).toBe(false)
expect(document.adoptedStyleSheets).toHaveLength(1)
expect(document.adoptedStyleSheets[0].cssRules[0].cssText.replace(/\s+/g, ' ')).toMatch(/^body > div:nth-child\(\d+\) > footer:nth-child\(2\) ?\{ ?padding-bottom: 48px !important;? ?\}$/)
reserve()
expect(document.adoptedStyleSheets).toHaveLength(0)
expect(el.style.paddingBottom).toBe('48px')
})
})
describe('<CookieButton>', () => {
let container: HTMLDivElement
let root: Root | undefined
let errors: ReturnType<typeof vi.spyOn>
const cookieButton = () => document.querySelector<HTMLButtonElement>('[data-ipal="cookie-button"]')
const frame = () => act(() => new Promise((resolve) => setTimeout(resolve, 40)))
const tree = (props: object = {}, provider: object = {}) => h(ConsentProvider, { texts: CONSENT_FALLBACK, ...provider }, h(CookieButton, props))
const mount = async (props: object = {}) => {
act(() => {
root = createRoot(container)
root.render(tree(props))
})
await frame()
}
beforeEach(() => {
container = document.createElement('div')
document.body.appendChild(container)
errors = vi.spyOn(console, 'error').mockImplementation(() => {})
})
afterEach(() => {
if (root) {act(() => root!.unmount())}
root = undefined
})
test('default: fixed in the bottom corner with the safe-area insets, below dialogs, a labelled button', async () => {
decide()
await mount()
const style = cookieButton()!.style
expect(style.position).toBe('fixed')
expect(style.bottom).toBe('calc(var(--ipal-cookie-button-offset, 1rem) + env(safe-area-inset-bottom, 0px))')
expect(style.left).toBe('calc(var(--ipal-cookie-button-inset, 1rem) + env(safe-area-inset-left, 0px))')
expect(style.zIndex).toBe('var(--ipal-z-header, 40)')
expect(cookieButton()!.getAttribute('aria-label')).toBe(CONSENT_FALLBACK.settingsTitle)
expect(cookieButton()!.type).toBe('button')
})
test('it never moves: footer in view, scrolling, the end of the page with a link under it', async () => {
decide()
footer()
await mount()
for (const y of [0, 1000, 2200]) {
page.scrollY = y
window.dispatchEvent(new Event('scroll'))
window.dispatchEvent(new Event('resize'))
await frame()
expect(cookieButton()!.style.transform).toBe('')
}
})
test('the room is there while the button is shown, and goes when the banner is reopened or the button unmounts', async () => {
decide()
const el = footer()
await mount()
expect(el.style.paddingBottom).toBe('48px')
act(() => cookieButton()!.click()) // reopens the banner: no button, no room
expect(cookieButton()).toBeNull()
expect(el.style.paddingBottom).toBe('')
expect(el.hasAttribute(COOKIE_BUTTON_SPACE_ATTRIBUTE)).toBe(false)
})
test('no decision yet: no button, no room', async () => {
const el = footer()
await mount()
expect(cookieButton()).toBeNull()
expect(el.style.paddingBottom).toBe('')
expect(liveCookies()).toEqual([])
})
test('reserve={false}: the button, no room', async () => {
decide()
const el = footer()
await mount({ reserve: false })
expect(cookieButton()).not.toBeNull()
expect(el.style.paddingBottom).toBe('')
})
test('avoid={COOKIE_BUTTON_AVOID}: the placement before 1.17.2 — above the footer, and no room', async () => {
decide()
const el = footer()
await mount({ avoid: COOKIE_BUTTON_AVOID })
expect(cookieButton()!.style.transform).toBe('translateY(-300px)')
expect(el.style.paddingBottom).toBe('')
})
test('avoid={false} (sites that set it): stays in the corner, with the room', async () => {
decide()
const el = footer()
await mount({ avoid: false })
expect(cookieButton()!.style.transform).toBe('')
expect(el.style.paddingBottom).toBe('48px')
})
describe('before the first paint (static HTML, the same for every visitor)', () => {
const scriptOf = (html: string) => /<script[^>]*data-ipal="cookie-button-script"[^>]*>(?<code>.*?)<\/script>/s.exec(html)?.groups?.code
test('the server HTML carries a script instead of the button; nonce from the provider', () => {
const html = renderToString(tree({}, { nonce: 'n-1' }))
expect(html).not.toContain('data-ipal="cookie-button"')
expect(html).toMatch(/<script[^>]*nonce="n-1"/)
expect(scriptOf(html)).toContain('footer, [role=\\"contentinfo\\"]')
expect(scriptOf(html)).not.toContain('</script')
})
test('no script when there is nothing to prepare: reserve off, old placement, own classes, server-read cookie', () => {
for (const props of [{ reserve: false }, { avoid: COOKIE_BUTTON_AVOID }, { className: 'mine' }]) {
expect(renderToString(tree(props))).not.toContain('<script')
}
expect(renderToString(tree({}, { cookieValue: null }))).not.toContain('<script')
})
test('a visitor who decided: the room is made by the script, the markup stays as the server sent it; no decision: nothing', () => {
const html = renderToString(tree())
const el = footer()
// eslint-disable-next-line @typescript-eslint/no-implied-eval
new Function(scriptOf(html)!)()
expect(document.adoptedStyleSheets).toHaveLength(0)
decide()
// eslint-disable-next-line @typescript-eslint/no-implied-eval
new Function(scriptOf(html)!)()
expect(document.adoptedStyleSheets).toHaveLength(1)
expect(document.adoptedStyleSheets[0].cssRules[0].cssText).toContain('48px')
expect(el.getAttribute('style')).toBeNull()
})
test('hydration: no warning; the room moves from the script’s style sheet onto the footer, the same size', async () => {
const el = footer()
decide()
const node = tree()
const html = renderToString(node)
container.innerHTML = html
// eslint-disable-next-line @typescript-eslint/no-implied-eval
new Function(scriptOf(html)!)()
act(() => {
root = hydrateRoot(container, node)
})
await frame()
expect(errors).not.toHaveBeenCalled()
expect(cookieButton()).not.toBeNull()
expect(document.querySelector('[data-ipal="cookie-button-script"]')).toBeNull()
expect(document.adoptedStyleSheets).toHaveLength(0)
expect(el.style.paddingBottom).toBe('48px')
})
})
})

Some files were not shown because too many files have changed in this diff Show More