From 15b5c6258d3af393d6ba01dd5c20e3c00a8070b9 Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?Rados=C5=82aw=20Smoli=C5=84ski?= Date: Tue, 1 Dec 2026 10:39:40 +0100 Subject: [PATCH 01/15] A locked staff account answers its login like a wrong password (accounts.lockedAnswer) MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit Payload checks the lock before the password, so after five wrong passwords a staff address answered "This user is locked…" to any password while an address with no account always answered "The email or password provided is incorrect.": anybody could find out which addresses have a staff account (IAWL idea 6, owner's Q1). A config-level afterError hook now answers LockedAuth on a staff collection's login exactly like AuthenticationError: REST status and body, GraphQL message and extensions.name. The lock is unchanged; visitor collections keep Payload's answer. accounts: { lockedAnswer: 'payload' } keeps Payload's message; any other value stops the start. Building blocks lockedLooksWrong, withLockedAnswer, graphqlLoginName. Co-Authored-By: Claude Opus 5.5 --- docs/access.md | 22 +++++- docs/agent/AGENT.md | 1 + docs/agent/skills/iapl-debug/SKILL.md | 1 + docs/agent/skills/iapl-reference/SKILL.md | 1 + .../skills/iapl-reference/resources/api.md | 4 +- src/index.ts | 2 + src/modules/access/lockedAnswer.ts | 67 ++++++++++++++++ src/modules/access/types.ts | 7 ++ src/modules/shared/switches.ts | 3 + src/plugin.ts | 3 + test/lockedAnswer.test.ts | 35 ++++++++ test/lockedAnswer2faOff.test.ts | 16 ++++ test/lockedAnswerPayload.test.ts | 23 ++++++ test/lockedAnswerSuite.ts | 79 +++++++++++++++++++ 14 files changed, 262 insertions(+), 2 deletions(-) create mode 100644 src/modules/access/lockedAnswer.ts create mode 100644 test/lockedAnswer.test.ts create mode 100644 test/lockedAnswer2faOff.test.ts create mode 100644 test/lockedAnswerPayload.test.ts create mode 100644 test/lockedAnswerSuite.ts diff --git a/docs/access.md b/docs/access.md index 17a9752..23539fa 100644 --- a/docs/access.md +++ b/docs/access.md @@ -250,6 +250,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: false, // none of the rules }) ``` @@ -477,10 +478,29 @@ 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) for `lockTime` (10 minutes), 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`, 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"`. + ## Turn off, override, extend - **Account rules:** `accounts: false`, or one by one — `panelRole`, `adminOnlyCreate`, `adminOnlyWrite`, - `staffOnlyRead`, `firstUserRoute`, `password` (above). + `staffOnlyRead`, `firstUserRoute`, `password`, `lockedAnswer` (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), diff --git a/docs/agent/AGENT.md b/docs/agent/AGENT.md index e40944c..ec8c534 100644 --- a/docs/agent/AGENT.md +++ b/docs/agent/AGENT.md @@ -1232,6 +1232,7 @@ add missing hosts with flags / `extra`; (3) change `mode` to `'enforce'` in both | 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` | | A password set on a staff account has at least 12 characters and is not the e-mail address; existing passwords are not checked | `accounts: { password: false }` | `password: { minLength }`; `checkPassword`, `buildPasswordRuleHook` | | While Turnstile cannot check (wrong secret, Cloudflare down): a text form is accepted, a form with files is refused | `forms: { turnstileOnConfigError: 'allow' }` | `'reject'`, `{ text, files }`; `turnstileOnConfigError` at a call site wins | | Dashboard alerts by role: integration details for admins, a neutral line for editors, nothing for others; cookie alerts for editors and above. `'all'` checks nothing — no role, no second factor | `dashboardAlerts: { integrations: 'all', cookies: 'all' }` | `integrations: 'editor'`; the components' `details` / `audience` props | diff --git a/docs/agent/skills/iapl-debug/SKILL.md b/docs/agent/skills/iapl-debug/SKILL.md index bcec0df..d747a6b 100644 --- a/docs/agent/skills/iapl-debug/SKILL.md +++ b/docs/agent/skills/iapl-debug/SKILL.md @@ -34,6 +34,7 @@ through this procedure. Ask only when you are missing something you cannot get y ### Build / TypeScript | Symptom | Cause | Fix | |---|---|---| +| 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' }` | | 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'] })` | diff --git a/docs/agent/skills/iapl-reference/SKILL.md b/docs/agent/skills/iapl-reference/SKILL.md index 878dad2..1375263 100644 --- a/docs/agent/skills/iapl-reference/SKILL.md +++ b/docs/agent/skills/iapl-reference/SKILL.md @@ -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//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 | | `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 | diff --git a/docs/agent/skills/iapl-reference/resources/api.md b/docs/agent/skills/iapl-reference/resources/api.md index d6c9082..62bb29d 100644 --- a/docs/agent/skills/iapl-reference/resources/api.md +++ b/docs/agent/skills/iapl-reference/resources/api.md @@ -85,7 +85,9 @@ 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`). +| `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. | + +**Types:** `AccountsOptions` (`accounts`: `panelRole`, `adminOnlyCreate`, `adminOnlyWrite`, `staffOnlyRead`, `firstUserRoute`, `password`, `lockedAnswer`), `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` diff --git a/src/index.ts b/src/index.ts index e014373..f224560 100644 --- a/src/index.ts +++ b/src/index.ts @@ -27,6 +27,8 @@ export { applyPasswordRule, buildPasswordRuleHook, checkPassword, DEFAULT_PASSWO export type { PasswordRuleOptions } from './modules/access/passwordRule.js' export { isPasswordRuleHook, staffRuleOf } from './modules/access/ruleMark.js' export type { StaffRuleMark } from './modules/access/ruleMark.js' +export { graphqlLoginName, lockedLooksWrong, withLockedAnswer } from './modules/access/lockedAnswer.js' +export type { LockedAnswerOption } from './modules/access/lockedAnswer.js' export { adoptLateAuthCollections, applyFirstUserRoute, diff --git a/src/modules/access/lockedAnswer.ts b/src/modules/access/lockedAnswer.ts new file mode 100644 index 0000000..acae26a --- /dev/null +++ b/src/modules/access/lockedAnswer.ts @@ -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): 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[0] + +/** The config-level `afterError` hook (REST and GraphQL). */ +export const lockedLooksWrong: AfterErrorHook = (args) => { + const { collection, error, req } = args as { error: unknown; graphqlResult?: Record } & Parameters[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; 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] } } +} diff --git a/src/modules/access/types.ts b/src/modules/access/types.ts index 156e191..6427a05 100644 --- a/src/modules/access/types.ts +++ b/src/modules/access/types.ts @@ -49,6 +49,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 diff --git a/src/modules/shared/switches.ts b/src/modules/shared/switches.ts index 3d59555..68c6292 100644 --- a/src/modules/shared/switches.ts +++ b/src/modules/shared/switches.ts @@ -50,6 +50,9 @@ export function assertPluginSwitches(options: Record): 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). + const accounts = bag(options.accounts) + if (accounts) {assertOneOf('accounts.lockedAnswer', accounts.lockedAnswer, ['payload', 'wrong'])} // Opt-in features that add public endpoints or outbound calls: `'false'` switched them ON. for (const name of ['cookieScanner', 'stats', 'consentLog', 'adminMeta', 'whiteLabel'] as const) { diff --git a/src/plugin.ts b/src/plugin.ts index 6445f7c..ddae46e 100644 --- a/src/plugin.ts +++ b/src/plugin.ts @@ -13,6 +13,7 @@ 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 { 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' @@ -258,6 +259,8 @@ export const iapl = (options: IaplOptions): Plugin => { const panelSlug = config.admin?.user ?? (config.collections ?? []).find((c) => c.auth)?.slug const staffSlugs = [...new Set([panelSlug, options.access?.authCollection, ...(options.access?.staffCollections ?? [])].filter((s): s is string => Boolean(s)))] config = applyStaffAccountAccess(config, staffSlugs, { ...accountAccess, pluginRoles: options.access?.authCollection ? [options.access.authCollection] : [] }) + // 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 diff --git a/test/lockedAnswer.test.ts b/test/lockedAnswer.test.ts new file mode 100644 index 0000000..ef88e47 --- /dev/null +++ b/test/lockedAnswer.test.ts @@ -0,0 +1,35 @@ +/** A locked staff account answers like a wrong password, REST and GraphQL (lockedAnswerSuite.ts). 2FA on. */ +import { describe, expect, test, vi } from 'vitest' + +import { lockedAnswerSite, PASSWORD } from './lockedAnswerSuite.js' + +vi.mock('server-only', () => ({})) +vi.mock('next/headers.js', async () => (await import('./http/server.js')).nextHeadersMock) + +const { gqlLogin, lock, restLogin, state } = lockedAnswerSite() + +describe('accounts.lockedAnswer (default): a locked staff account looks like a wrong password', () => { + test('REST: the locked owner, with any password, gets exactly what an invented address gets', async () => { + await lock('users', 'owner@example.com') + const invented = await restLogin('users', 'nobody@example.com', 'a-wrong-password') + expect(invented.status).toBe(401) + expect(await restLogin('users', 'owner@example.com', 'a-wrong-password')).toEqual(invented) + expect(await restLogin('users', 'owner@example.com', PASSWORD)).toEqual(invented) + expect(invented.body).not.toMatch(/locked/i) + // the lock itself is still there + const stored = (await state.payload.find({ collection: 'users' as never, overrideAccess: true, showHiddenFields: true, where: { email: { equals: 'owner@example.com' } } })).docs[0] as { lockUntil?: string } + expect(new Date(String(stored.lockUntil)).getTime()).toBeGreaterThan(Date.now()) + }) + + test('GraphQL: the same message, status and error name', async () => { + const invented = await gqlLogin('loginUser', 'nobody@example.com', 'a-wrong-password') + expect(invented.name).toBe('AuthenticationError') + expect(await gqlLogin('loginUser', 'owner@example.com', PASSWORD)).toEqual(invented) + }) + + test('a visitor collection keeps Payload\'s answer (not staff)', async () => { + await lock('customers', 'client@example.com', 3) + expect((await restLogin('customers', 'client@example.com', PASSWORD)).body).toMatch(/locked/i) + expect((await gqlLogin('loginCustomer', 'client@example.com', PASSWORD)).name).toBe('LockedAuth') + }) +}) diff --git a/test/lockedAnswer2faOff.test.ts b/test/lockedAnswer2faOff.test.ts new file mode 100644 index 0000000..24a5ef8 --- /dev/null +++ b/test/lockedAnswer2faOff.test.ts @@ -0,0 +1,16 @@ +/** A locked staff account answers like a wrong password with 2FA off too (lockedAnswerSuite.ts). */ +import { describe, expect, test, vi } from 'vitest' + +import { lockedAnswerSite, PASSWORD } from './lockedAnswerSuite.js' + +vi.mock('server-only', () => ({})) + +const { gqlLogin, lock, restLogin } = lockedAnswerSite({ twoFactor: false }) + +describe('accounts.lockedAnswer with twoFactor: false', () => { + test('REST and GraphQL answer the locked owner like an invented address', async () => { + await lock('users', 'owner@example.com') + expect(await restLogin('users', 'owner@example.com', PASSWORD)).toEqual(await restLogin('users', 'nobody@example.com', 'x-wrong-password-1')) + expect(await gqlLogin('loginUser', 'owner@example.com', PASSWORD)).toEqual(await gqlLogin('loginUser', 'nobody@example.com', 'x-wrong-password-1')) + }) +}) diff --git a/test/lockedAnswerPayload.test.ts b/test/lockedAnswerPayload.test.ts new file mode 100644 index 0000000..09eb095 --- /dev/null +++ b/test/lockedAnswerPayload.test.ts @@ -0,0 +1,23 @@ +/** accounts.lockedAnswer: 'payload' keeps Payload's "locked" answer (lockedAnswerSuite.ts). */ +import { describe, expect, test, vi } from 'vitest' + +import { iapl } from '../src/plugin.js' +import { lockedAnswerSite, PASSWORD } from './lockedAnswerSuite.js' + +vi.mock('server-only', () => ({})) +vi.mock('next/headers.js', async () => (await import('./http/server.js')).nextHeadersMock) + +const { gqlLogin, lock, restLogin } = lockedAnswerSite({ lockedAnswer: 'payload' }) + +describe("accounts.lockedAnswer: 'payload'", () => { + test('the locked owner is told it is locked, REST and GraphQL', async () => { + await lock('users', 'owner@example.com') + expect((await restLogin('users', 'owner@example.com', PASSWORD)).body).toMatch(/locked/i) + expect((await gqlLogin('loginUser', 'owner@example.com', PASSWORD)).name).toBe('LockedAuth') + }) + + test('a value nobody understands stops the start', async () => { + const config = { collections: [], secret: 'x' } as never + await expect((async () => iapl({ accounts: { lockedAnswer: 'Payload' as never }, i18n: { defaultLocale: 'en', locales: [{ code: 'en', label: 'English' }] } } as never)(config))()).rejects.toThrow(/accounts\.lockedAnswer must be one of/) + }) +}) diff --git a/test/lockedAnswerSuite.ts b/test/lockedAnswerSuite.ts new file mode 100644 index 0000000..7e73ab1 --- /dev/null +++ b/test/lockedAnswerSuite.ts @@ -0,0 +1,79 @@ +/** + * A locked staff account answers its login exactly like a wrong password (accounts.lockedAnswer, 1.17.2; IAWL + * idea 6). Shared by lockedAnswer.test.ts (default, 2FA on), lockedAnswer2fa-off.test.ts (2FA off) and + * lockedAnswerPayload.test.ts (`lockedAnswer: 'payload'`): one Payload per file. + * 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 { startPayloadServer, type TestServer } from './http/server.js' + +export const PASSWORD = 'a-long-test-password-1' + +export type Answer = { body: string; status: number } + +export function lockedAnswerSite({ lockedAnswer, twoFactor = true }: { lockedAnswer?: 'payload'; twoFactor?: boolean } = {}) { + const state = {} as { payload: Payload; server: TestServer } + beforeAll(async () => { + const config = buildTestConfig({ + admin: { user: 'users' }, + collections: [ + // a visitor collection with Payload's own lock: not staff, not changed + { slug: 'customers', access: { create: () => true }, auth: { maxLoginAttempts: 3 }, fields: [] }, + { slug: 'media', fields: [], upload: { staticDir: '/tmp/iapl-locked-answer-media' } }, + ], + db: testDatabase('lockedanswer'), + editor: lexicalEditor(), + plugins: [ + iapl({ + access: { authCollection: 'users' }, + ...(lockedAnswer ? { accounts: { lockedAnswer } } : {}), + i18n: { defaultLocale: 'en', locales: [{ code: 'en', label: 'English' }] }, + twoFactor: twoFactor ? { issuer: 'Example', plugin: payloadTotp } : false, + }), + ], + secret: 'integration-test-secret-0123456789', + telemetry: false, + }) + state.payload = await getPayload({ config }) + state.server = await startPayloadServer(config) + await state.payload.create({ collection: 'users' as never, data: { email: 'owner@example.com', password: PASSWORD, roles: ['admin'] } as never }) + await state.payload.create({ collection: 'customers' as never, data: { email: 'client@example.com', password: PASSWORD } as never }) + }, 120_000) + afterAll(async () => { + await state.server?.close() + await state.payload?.destroy?.() + }) + + const restLogin = async (collection: string, email: string, password: string): Promise => { + const res = await fetch(`${state.server.url}/api/${collection}/login`, { + body: JSON.stringify({ email, password }), + headers: { 'content-type': 'application/json' }, + method: 'POST', + }) + return { body: await res.text(), status: res.status } + } + const gqlLogin = async (mutation: string, email: string, password: string) => { + const res = await fetch(`${state.server.url}/api/graphql`, { + body: JSON.stringify({ query: `mutation { ${mutation}(email: ${JSON.stringify(email)}, password: ${JSON.stringify(password)}) { token } }` }), + headers: { 'content-type': 'application/json' }, + method: 'POST', + }) + const body = (await res.json()) as { errors?: { extensions?: { name?: string; statusCode?: number }; message: string }[] } + const e = body.errors?.[0] + return { name: e?.extensions?.name, message: e?.message, status: res.status, statusCode: e?.extensions?.statusCode } + } + /** Locks `email` with wrong passwords (Payload's default: 5). */ + const lock = async (collection: string, email: string, times = 5) => { + for (let i = 0; i < times; i++) {await restLogin(collection, email, 'a-wrong-password')} + } + return { gqlLogin, lock, restLogin, state } +} From 4b17254135eb5f4dc69ba91c477221cd18f4a8d9 Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?Rados=C5=82aw=20Smoli=C5=84ski?= Date: Tue, 1 Dec 2026 10:39:41 +0100 Subject: [PATCH 02/15] readPublished on version history: readPublishedVersions, and the documented form works (1.17.2) readVersions: readPublished(), as access.md showed, answered every version read with 500 on MongoDB, Postgres and SQLite: the rule returns the document's `_status` path, a version query runs on the versions collection where the status is `version._status` (SQL: "Cannot find field for path at _status"; MongoDB: TypeError in sanitizeQueryValue). Reported by a client project upgrading to 1.17.1. - readPublishedVersions(minimum): the version form, for readVersions. - readPublished() carries a symbol mark (READ_PUBLISHED); iapl() swaps it on readVersions of the collections and globals it sees (withVersionReadRules, exported for plugins listed after it). - Tests on the three adapters: the version list (REST, depth 0/2, Local API, GraphQL), one version by id, the count, a global, an explicit role; the 1.17.1 HTTP test now checks the status too. - access.md says where each rule goes; AGENT.md, iapl-collection and iapl-audit skills. Co-Authored-By: Claude Opus 5.5 --- docs/access.md | 20 ++- docs/agent/AGENT.md | 2 +- docs/agent/skills/iapl-audit/SKILL.md | 3 +- docs/agent/skills/iapl-collection/SKILL.md | 6 +- src/index.ts | 3 + src/modules/access/access.ts | 42 ++++- src/modules/access/index.ts | 3 + src/plugin.ts | 6 +- test/iawlIdeasBHttp.test.ts | 6 +- test/readPublishedVersions.test.ts | 173 +++++++++++++++++++++ 10 files changed, 252 insertions(+), 12 deletions(-) create mode 100644 test/readPublishedVersions.test.ts diff --git a/docs/access.md b/docs/access.md index 17a9752..57c9604 100644 --- a/docs/access.md +++ b/docs/access.md @@ -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//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 diff --git a/docs/agent/AGENT.md b/docs/agent/AGENT.md index e40944c..026dc8f 100644 --- a/docs/agent/AGENT.md +++ b/docs/agent/AGENT.md @@ -1103,7 +1103,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//?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//?draft=true` → 404 and `GET /api//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** diff --git a/docs/agent/skills/iapl-audit/SKILL.md b/docs/agent/skills/iapl-audit/SKILL.md index 00bd783..67aaf0d 100644 --- a/docs/agent/skills/iapl-audit/SKILL.md +++ b/docs/agent/skills/iapl-audit/SKILL.md @@ -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/?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//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"` diff --git a/docs/agent/skills/iapl-collection/SKILL.md b/docs/agent/skills/iapl-collection/SKILL.md index 98a5b87..2dc1712 100644 --- a/docs/agent/skills/iapl-collection/SKILL.md +++ b/docs/agent/skills/iapl-collection/SKILL.md @@ -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 (`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 /api//?draft=true` without a session → `404`; the same with an editor's token → the draft. + `curl -i /api//?draft=true` without a session → `404`; the same with an editor's token → the draft; + `curl -s -o /dev/null -w '%{http_code}' /api//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 diff --git a/src/index.ts b/src/index.ts index e014373..3579c94 100644 --- a/src/index.ts +++ b/src/index.ts @@ -15,12 +15,15 @@ export { injectRoles, isAdmin, isEditor, + READ_PUBLISHED, readPublished, + readPublishedVersions, requireRole, requireRoleField, ROLE_HIERARCHY, staffCollectionSlugs, userMeetsRole, + withVersionReadRules, } from './modules/access/index.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' diff --git a/src/modules/access/access.ts b/src/modules/access/access.ts index b8af21f..4f8b1ef 100644 --- a/src/modules/access/access.ts +++ b/src/modules/access/access.ts @@ -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(entities: T[] | undefined): T[] | undefined { + return entities?.map((entity) => { + const rule = entity.access?.readVersions as (object & Partial>) | undefined + const minimum = rule && typeof rule === 'function' ? rule[READ_PUBLISHED] : undefined + return minimum ? { ...entity, access: { ...entity.access, readVersions: readPublishedVersions(minimum) } } : entity + }) } /** diff --git a/src/modules/access/index.ts b/src/modules/access/index.ts index 1bac610..bdfe8ae 100644 --- a/src/modules/access/index.ts +++ b/src/modules/access/index.ts @@ -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' diff --git a/src/plugin.ts b/src/plugin.ts index 6445f7c..a1008e4 100644 --- a/src/plugin.ts +++ b/src/plugin.ts @@ -12,7 +12,7 @@ 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 { 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' @@ -1093,6 +1093,10 @@ 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 diff --git a/test/iawlIdeasBHttp.test.ts b/test/iawlIdeasBHttp.test.ts index 7e7f8d4..ed9a8f5 100644 --- a/test/iawlIdeasBHttp.test.ts +++ b/test/iawlIdeasBHttp.test.ts @@ -140,7 +140,11 @@ describe('idea 23: drafts over REST and GraphQL', () => { expect(asked.status).toBe(404) expect(await asked.text()).not.toContain('szkic') // the version list: a visitor sees published versions only - expect(await (await api('/guarded-pages/versions?limit=50')).text()).not.toContain('szkic') + const versions = await api('/guarded-pages/versions?limit=50&locale=pl') + expect(versions.status).toBe(200) // 1.17.1 answered 500 here: the check below alone passed on an error page + const list = await versions.text() + expect(list).toContain('Cennik') + expect(list).not.toContain('szkic') }) test('readPublished(): an editor still sees the draft', async () => { diff --git a/test/readPublishedVersions.test.ts b/test/readPublishedVersions.test.ts new file mode 100644 index 0000000..ea2de5c --- /dev/null +++ b/test/readPublishedVersions.test.ts @@ -0,0 +1,173 @@ +/** + * readPublished() on version history (`readVersions`) — reported by a client project upgrading to 1.17.1: + * `GET /api/pages/versions` answered 500 on MongoDB. The rule answered `{ _status: { equals: 'published' } }`, a path + * of the document, while a version query runs on the versions collection, where the status is `version._status`. + * + * Every way a version is read, for a visitor, a plain `user` account and an editor: the list (REST, Local API, + * GraphQL, `depth`), one version by id (REST, GraphQL — the panel's version view reads it the same way), the count. + * Real HTTP; SQLite by default, Postgres / MongoDB with IPAL_TEST_POSTGRES_URI / IPAL_TEST_MONGO_URI. + */ +import type { Payload } from 'payload' + +import { lexicalEditor } from '@payloadcms/richtext-lexical' +import os from 'os' +import path from 'path' +import { getPayload } from 'payload' +import { afterAll, beforeAll, describe, expect, test, vi } from 'vitest' + +import { READ_PUBLISHED, readPublished, readPublishedVersions, withVersionReadRules } from '../src/modules/access/access.js' +import { iapl } from '../src/plugin.js' +import { buildTestConfig } from './helpers.js' +import { testDatabase } from './http/db.js' +import { startPayloadServer, type TestServer } from './http/server.js' + +vi.mock('server-only', () => ({})) + +const PASSWORD = 'a-long-test-password-1' +let server: TestServer +let payload: Payload +const tokens: Record<'editor' | 'user', string> = { editor: '', user: '' } +let pageId: number | string +let neverPublishedId: number | string +const versionIds: { draft: (number | string)[]; published: (number | string)[] } = { draft: [], published: [] } + +type Who = 'editor' | 'user' | 'visitor' +const headers = (who: Who) => ({ 'content-type': 'application/json', ...(who === 'visitor' ? {} : { authorization: `JWT ${tokens[who]}` }) }) +const rest = async (pathname: string, who: Who) => { + const res = await fetch(`${server.url}/api${pathname}`, { headers: headers(who) }) + return { body: await res.text(), status: res.status } +} +const gql = async (query: string, who: Who) => { + const res = await fetch(`${server.url}/api/graphql`, { body: JSON.stringify({ query }), headers: headers(who), method: 'POST' }) + return { body: await res.text(), status: res.status } +} +const titles = (body: string) => [...body.matchAll(/"title":"([^"]+)"/g)].map((m) => m[1]) + +beforeAll(async () => { + const config = buildTestConfig({ + admin: { user: 'users' }, + collections: [ + { + slug: 'pages', + access: { read: readPublished(), readVersions: readPublished() }, + fields: [{ name: 'title', type: 'text', localized: true }, { name: 'related', type: 'relationship', relationTo: 'pages' }], + versions: { drafts: true, maxPerDoc: 20 }, + }, + // the explicit version rule, and a role other than the default + { slug: 'notes', access: { read: readPublished('admin'), readVersions: readPublishedVersions('admin') }, fields: [{ name: 'title', type: 'text' }], versions: { drafts: true } }, + { slug: 'media', fields: [], upload: { staticDir: path.join(os.tmpdir(), 'iapl-read-published-versions') } }, + ], + db: testDatabase('read_published_versions'), + editor: lexicalEditor(), + globals: [{ slug: 'banner', access: { read: readPublished(), readVersions: readPublished() }, fields: [{ name: 'title', type: 'text' }], versions: { drafts: true } }], + plugins: [iapl({ access: { authCollection: 'users' }, i18n: { defaultLocale: 'pl', locales: [{ code: 'pl', label: 'Polski' }, { code: 'en', label: 'English' }] }, mail: { relay: false }, twoFactor: false })], + secret: 'read-published-versions-0123456789', + telemetry: false, + }) + payload = await getPayload({ config }) + server = await startPayloadServer(config) + for (const role of ['editor', 'user'] as const) { + await payload.create({ collection: 'users' as never, data: { email: `${role}@example.com`, password: PASSWORD, roles: [role] } as never }) + tokens[role] = ((await (await fetch(`${server.url}/api/users/login`, { body: JSON.stringify({ email: `${role}@example.com`, password: PASSWORD }), headers: { 'content-type': 'application/json' }, method: 'POST' })).json()) as { token: string }).token + } + await payload.create({ collection: 'notes' as never, data: { _status: 'published', title: 'Note published' } as never }) + await payload.create({ collection: 'notes' as never, data: { _status: 'draft', title: 'Note draft' } as never, draft: true }) + await payload.updateGlobal({ slug: 'banner' as never, data: { _status: 'published', title: 'Banner published' } as never }) + await payload.updateGlobal({ slug: 'banner' as never, data: { _status: 'draft', title: 'Banner draft' } as never, draft: true }) + pageId = (await payload.create({ collection: 'pages' as never, data: { _status: 'published', title: 'Published one' } as never, locale: 'pl' })).id + await payload.update({ id: pageId, collection: 'pages' as never, data: { _status: 'draft', title: 'Draft over it' } as never, draft: true, locale: 'pl' }) + neverPublishedId = (await payload.create({ collection: 'pages' as never, data: { _status: 'draft', related: pageId, title: 'Never published' } as never, draft: true, locale: 'pl' })).id + const all = await payload.findVersions({ collection: 'pages' as never, depth: 0, limit: 100, locale: 'pl' }) + for (const v of all.docs as unknown as { id: number | string; version: { _status?: string } }[]) { + versionIds[v.version._status === 'published' ? 'published' : 'draft'].push(v.id) + } +}, 120_000) + +afterAll(async () => { + await server?.close() + await payload?.destroy?.() +}) + +describe('readPublished() as readVersions', () => { + test.each(['visitor', 'user'] as const)('the version list answers a %s with published versions only (REST, depth 0 and 2)', async (who) => { + for (const q of ['?limit=100&depth=0', '?limit=100&depth=2&locale=pl']) { + const { body, status } = await rest(`/pages/versions${q}`, who) + expect(status).toBe(200) + expect(titles(body)).toContain('Published one') + expect(body).not.toContain('Draft over it') + expect(body).not.toContain('Never published') + } + }) + + test('an editor lists every version', async () => { + const { body, status } = await rest('/pages/versions?limit=100&depth=0&locale=pl', 'editor') + expect(status).toBe(200) + expect(titles(body)).toEqual(expect.arrayContaining(['Published one', 'Draft over it', 'Never published'])) + }) + + test('one version by id: a published one is answered, a draft one is not found (REST)', async () => { + expect((await rest(`/pages/versions/${versionIds.published[0]}?locale=pl`, 'visitor')).status).toBe(200) + for (const id of versionIds.draft) { + const { body, status } = await rest(`/pages/versions/${id}?locale=pl`, 'visitor') + expect([403, 404]).toContain(status) // Payload refuses a version the rule's condition leaves out + expect(body).not.toMatch(/Draft over it|Never published/) + } + expect((await rest(`/pages/versions/${versionIds.draft[0]}?locale=pl`, 'editor')).status).toBe(200) + }) + + test('GraphQL: the list and one version, as a visitor', async () => { + const list = await gql('{ versionsPages(limit: 100, locale: pl) { totalDocs docs { id version { title _status } } } }', 'visitor') + expect(list.status).toBe(200) + expect(list.body).not.toContain('"errors"') + expect(list.body).toContain('Published one') + expect(list.body).not.toMatch(/Draft over it|Never published/) + const draft = await gql(`{ versionPage(id: "${versionIds.draft[0]}", locale: pl) { version { title } } }`, 'visitor') + expect(draft.body).not.toMatch(/Draft over it|Never published/) + }) + + test('Local API with access control: findVersions and countVersions as a visitor', async () => { + const found = await payload.findVersions({ collection: 'pages' as never, depth: 0, limit: 100, locale: 'pl', overrideAccess: false }) + expect((found.docs as unknown as { version: { title?: string } }[]).map((d) => d.version.title)).toEqual(['Published one']) + const counted = await payload.countVersions({ collection: 'pages' as never, overrideAccess: false }) + expect(counted.totalDocs).toBe(versionIds.published.length) + }) + + test('reading the documents still works as before (read: readPublished())', async () => { + expect((await rest(`/pages/${neverPublishedId}`, 'visitor')).status).toBe(404) + expect(titles((await rest(`/pages/${pageId}?locale=pl`, 'visitor')).body)).toContain('Published one') + expect(titles((await rest(`/pages/${pageId}?draft=true&locale=pl`, 'editor')).body)).toContain('Draft over it') + }) +}) + +describe('the other ways in', () => { + test('readPublishedVersions(), with its own role: an editor is a visitor when the role is admin', async () => { + for (const who of ['visitor', 'editor'] as const) { + const { body, status } = await rest('/notes/versions?limit=50', who) + expect(status).toBe(200) + expect(body).toContain('Note published') + expect(body).not.toContain('Note draft') + } + }) + + test('a global: readVersions: readPublished() lists published versions only', async () => { + const { body, status } = await rest('/globals/banner/versions?limit=50', 'visitor') + expect(status).toBe(200) + expect(body).toContain('Banner published') + expect(body).not.toContain('Banner draft') + expect((await rest('/globals/banner/versions?limit=50', 'editor')).body).toContain('Banner draft') + }) + + test('withVersionReadRules swaps only a readPublished() rule, keeping its role (a plugin listed after iapl)', () => { + const own = () => true + const [swapped, kept, none] = withVersionReadRules([ + { slug: 'late', access: { readVersions: readPublished('admin') } }, + { slug: 'mine', access: { readVersions: own } }, + { slug: 'open' }, + ] as { access?: { readVersions?: unknown }; slug: string }[])! + const rule = swapped.access!.readVersions as (a: unknown) => unknown + expect(READ_PUBLISHED in rule).toBe(false) + expect(rule({ req: { payload: undefined, user: undefined } })).toEqual({ 'version._status': { equals: 'published' } }) + expect(kept.access!.readVersions).toBe(own) + expect(none).toEqual({ slug: 'open' }) + }) +}) From 97c62f21f009cab2e64653d7e30ce09f135a709b Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?Rados=C5=82aw=20Smoli=C5=84ski?= Date: Tue, 1 Dec 2026 10:42:02 +0100 Subject: [PATCH 03/15] Every plugin limiter counts IPv6 per /64 (setIpv6Grouping) clientIp() returns the whole IPv6 address and every limiter keyed on it, so one host with a /64 had 2^64 budgets: 50 addresses of one /64 against a limit of 5 all passed (IAWL idea 9, owner's Q4). consumeRateLimit and checkRateLimit now count an IPv6 key by its /64 (an IPv4-mapped address by its IPv4); the mail service's per-visitor account-mail key too. A second counter per /48 at 10x the limit is available and off by default (setIpv6Grouping({ wide: 48 })); setIpv6Grouping({ prefix: 128 }) counts per address as before. ipRateKey(ip) is exported for own limiters. Co-Authored-By: Claude Opus 5.5 --- docs/agent/AGENT.md | 1 + .../skills/iapl-reference/resources/api.md | 1 + docs/forms.md | 12 ++ src/index.ts | 3 +- src/modules/email/relay/send.ts | 4 +- src/modules/forms/rateLimit.ts | 4 +- src/modules/shared/rateLimit.ts | 125 ++++++++++++++++-- test/rateLimitIpv6.test.ts | 105 +++++++++++++++ 8 files changed, 238 insertions(+), 17 deletions(-) create mode 100644 test/rateLimitIpv6.test.ts diff --git a/docs/agent/AGENT.md b/docs/agent/AGENT.md index ec8c534..a9a3c92 100644 --- a/docs/agent/AGENT.md +++ b/docs/agent/AGENT.md @@ -1241,6 +1241,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::` → `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 `` props (`SiteProviders analytics={false}`) | | Locale cookie: consent read under its own stored version | — | `createProxy(config, { policyVersion })` / `createLocaleMiddleware({ policyVersion })` | diff --git a/docs/agent/skills/iapl-reference/resources/api.md b/docs/agent/skills/iapl-reference/resources/api.md index 62bb29d..9f17bb8 100644 --- a/docs/agent/skills/iapl-reference/resources/api.md +++ b/docs/agent/skills/iapl-reference/resources/api.md @@ -746,6 +746,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 }`). diff --git a/docs/forms.md b/docs/forms.md index 21787af..e487370 100644 --- a/docs/forms.md +++ b/docs/forms.md @@ -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 diff --git a/src/index.ts b/src/index.ts index f224560..9c9b257 100644 --- a/src/index.ts +++ b/src/index.ts @@ -570,7 +570,8 @@ 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, setRateLimitStore, setUnknownIpFactor, UNKNOWN_IP_FACTOR } from './modules/shared/rateLimit.js' +export { clientIp, ipRateKey, 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' diff --git a/src/modules/email/relay/send.ts b/src/modules/email/relay/send.ts index fb8dfbb..4b490f8 100644 --- a/src/modules/email/relay/send.ts +++ b/src/modules/email/relay/send.ts @@ -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,7 +136,7 @@ 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 }] : []), ...[...(request.to ?? []), ...(request.cc ?? []), ...(request.bcc ?? [])].map((address) => ({ key: `to:${sha256Hex(address.toLowerCase())}`, max: perAddress })), ] for (const check of checks) { diff --git a/src/modules/forms/rateLimit.ts b/src/modules/forms/rateLimit.ts index bb1505e..2d6b128 100644 --- a/src/modules/forms/rateLimit.ts +++ b/src/modules/forms/rateLimit.ts @@ -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' diff --git a/src/modules/shared/rateLimit.ts b/src/modules/shared/rateLimit.ts index 46b0839..091d412 100644 --- a/src/modules/shared/rateLimit.ts +++ b/src/modules/shared/rateLimit.ts @@ -1,3 +1,5 @@ +import { isIPv4, isIPv6 } from 'node:net' + import { readEnv } from './envName.js' type Bucket = { count: number; resetAt: number } @@ -94,8 +96,95 @@ 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 } +} + +/** The 8 groups of an IPv6 address as numbers, or null. */ +function ipv6Groups(address: string): null | number[] { + const bare = address.replace(/^\[|\]$/g, '').split('%')[0] + if (!isIPv6(bare)) {return null} + let text = bare + const v4 = /(\d+\.\d+\.\d+\.\d+)$/.exec(text) + if (v4) { + 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)}` + } + const [head, tail] = text.includes('::') ? text.split('::') : [text, undefined] + const left = head ? head.split(':') : [] + const right = tail ? tail.split(':') : [] + const fill = tail === undefined ? [] : Array(8 - left.length - right.length).fill('0') + const groups = [...left, ...fill, ...right].map((g) => parseInt(g, 16)) + return groups.length === 8 && groups.every((g) => Number.isInteger(g) && g >= 0 && g <= 0xffff) ? groups : null +} + +/** `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 +214,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,26 +244,30 @@ 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 => { + 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 } } /** 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 } diff --git a/test/rateLimitIpv6.test.ts b/test/rateLimitIpv6.test.ts new file mode 100644 index 0000000..1bd0ce2 --- /dev/null +++ b/test/rateLimitIpv6.test.ts @@ -0,0 +1,105 @@ +/** + * IPv6 is counted per network (1.17.2, IAWL idea 9): a /64 is one client in every limiter of the plugin; a second + * counter per /48 when a project turns it on (`setIpv6Grouping({ wide: 48 })`). + */ +import { afterEach, describe, expect, test, vi } from 'vitest' + +import { buildConsentLogEndpoint } from '../src/modules/consent/consentLog.js' +import { passRateLimit } from '../src/modules/forms/submitForm.js' +import { checkRateLimit, clientIp, consumeRateLimit, ipRateKey, setIpv6Grouping } from '../src/modules/shared/rateLimit.js' + +vi.mock('server-only', () => ({})) + +let scope = 0 +const nextScope = () => `ipv6-test-${++scope}` +const hex = (n: number) => n.toString(16) + +afterEach(() => setIpv6Grouping()) + +describe('ipRateKey', () => { + test('one key for every address of a /64, whatever the spelling', () => { + const key = ipRateKey('2001:db8:1:2::1') + expect(key).toBe('2001:db8:1:2:0:0:0:0/64') + for (const a of ['2001:db8:1:2:ffff:ffff:ffff:ffff', '2001:0DB8:0001:0002:0000:0000:0000:0042', '[2001:db8:1:2::9]', '2001:db8:1:2::9%eth0']) { + expect([a, ipRateKey(a)]).toEqual([a, key]) + } + expect(ipRateKey('2001:db8:1:3::1')).not.toBe(key) + }) + + test('IPv4 as it is; an IPv4-mapped IPv6 address is its IPv4; anything else unchanged', () => { + expect(ipRateKey('198.51.100.7')).toBe('198.51.100.7') + expect(ipRateKey('::ffff:198.51.100.7')).toBe('198.51.100.7') + expect(ipRateKey('::ffff:c633:6407')).toBe('198.51.100.7') + expect(ipRateKey('')).toBe('') + expect(ipRateKey('not-an-ip')).toBe('not-an-ip') + }) + + test('setIpv6Grouping: per address again, another prefix; nonsense is refused', () => { + setIpv6Grouping({ prefix: 128 }) + expect(ipRateKey('2001:db8::1')).not.toBe(ipRateKey('2001:db8::2')) + setIpv6Grouping({ prefix: 56 }) + expect(ipRateKey('2001:db8:0:ff::1')).toBe(ipRateKey('2001:db8:0:1::1')) + expect(() => setIpv6Grouping({ prefix: 0 })).toThrow(/prefix must be/) + expect(() => setIpv6Grouping({ prefix: '64' as never })).toThrow(/prefix must be/) + expect(() => setIpv6Grouping({ prefix: 48, wide: 56 })).toThrow(/shorter prefix/) + }) +}) + +describe('the limiters count a /64 as one client', () => { + test('consumeRateLimit: fifty addresses of one /64 get five requests, not fifty', async () => { + const s = nextScope() + let allowed = 0 + for (let i = 1; i <= 50; i++) { + if ((await consumeRateLimit({ key: clientIp(new Headers({ 'x-real-ip': `2001:db8:1:1::${hex(i)}` })), max: 5, scope: s })).ok) {allowed++} + } + expect(allowed).toBe(5) + // another /64 of the same /48 is another client (the wide counter is off by default) + expect((await consumeRateLimit({ key: '2001:db8:1:2::1', max: 5, scope: s })).ok).toBe(true) + }) + + test('checkRateLimit (the synchronous one) too', () => { + const s = nextScope() + const results = Array.from({ length: 8 }, (_, i) => checkRateLimit({ key: `2001:db8:9:9::${hex(i + 1)}`, max: 3, scope: s })) + expect(results.filter(Boolean)).toHaveLength(3) + }) + + test('the forms gate (passRateLimit)', async () => { + const results = [] + for (let i = 1; i <= 8; i++) {results.push(await passRateLimit({ ip: `2001:db8:abcd:1::${hex(i)}`, maxPerMinute: 5 }))} + expect(results.filter((r) => r === null)).toHaveLength(5) + expect(results[7]).toMatchObject({ reason: 'rate_limited' }) + }) + + test('a plugin endpoint (the consent log, 20 a minute): the 21st address of one /64 gets 429', async () => { + const { handler } = buildConsentLogEndpoint() + const statuses: number[] = [] + for (let i = 1; i <= 21; i++) { + const req = { headers: new Headers({ 'x-real-ip': `2001:db8:feed:1::${hex(i)}` }), text: () => Promise.resolve('{') } + statuses.push((await (handler as (r: never) => Promise)(req as never)).status) + } + expect(statuses.slice(0, 20)).not.toContain(429) + expect(statuses[20]).toBe(429) + }) +}) + +describe('the wide counter (setIpv6Grouping({ wide: 48 }))', () => { + test('three hundred /64s of one /48: at most wideFactor × max requests', async () => { + setIpv6Grouping({ wide: 48, wideFactor: 10 }) + const s = nextScope() + let allowed = 0 + for (let i = 1; i <= 300; i++) { + if ((await consumeRateLimit({ key: `2001:db8:7:${hex(i)}::1`, max: 5, scope: s })).ok) {allowed++} + } + expect(allowed).toBe(50) + // another /48 is untouched + expect((await consumeRateLimit({ key: '2001:db8:8:1::1', max: 5, scope: s })).ok).toBe(true) + }) + + test('IPv4 is not affected by it', async () => { + setIpv6Grouping({ wide: 48 }) + const s = nextScope() + const ok = [] + for (let i = 1; i <= 6; i++) {ok.push((await consumeRateLimit({ key: `198.51.100.${i}`, max: 1, scope: s })).ok)} + expect(ok).toEqual([true, true, true, true, true, true]) + }) +}) From 4e68b7e44ac1bbc75b22011332008370ec0ffd17 Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?Rados=C5=82aw=20Smoli=C5=84ski?= Date: Tue, 1 Dec 2026 10:44:18 +0100 Subject: [PATCH 04/15] 1.17.2 (owner's Q1-Q3): form submissions over REST for staff only; Payload's job queue for an admin or Bearer CRON_SECRET; doctor visitor-writes; explicit write rules on the reference site - form-submissions create: a staff account with its second factor (formSubmissionOverrides.access.create keeps the way back) - jobsRunAccess (default on when the project writes no jobs.access.run): admin with the second factor or Bearer CRON_SECRET (16+); start-up note when the secret is missing; jobsRunAccess: false keeps Payload's default - iapl-doctor deep rule visitor-writes: entities a visitor login account may write, asked by behaviour - reference: Pages, Posts, CaseStudies, Media, Header, Footer, Company get adminOrEditor write rules - closed doors: submissions, pages, media, header, company closed for customers; the fixture's job queue refused without the secret, run with it - route snapshot reasons, docs, AGENT.md, skills, changelog draft 1.17.2 Co-Authored-By: Claude Opus 5.5 --- docs/CHANGELOG.md | 33 ++++ docs/agent/AGENT.md | 10 +- docs/agent/reference-site/INDEX.md | 75 ++------ .../resources/closed-doors.spec.template.ts | 6 +- docs/agent/skills/iapl-reference/SKILL.md | 4 +- .../skills/iapl-reference/resources/api.md | 3 + docs/agent/skills/iapl-upgrade/SKILL.md | 9 + docs/doctor.md | 1 + docs/env.md | 3 +- docs/forms.md | 4 +- docs/security.md | 34 ++++ .../resources/closed-doors.spec.template.ts | 6 +- .../.agents/skills/iapl-reference/SKILL.md | 4 +- .../skills/iapl-reference/resources/api.md | 3 + .../.agents/skills/iapl-upgrade/SKILL.md | 9 + reference/e2e/closed-doors.spec.ts | 12 +- reference/e2e/closed-doors.ts | 37 ++-- reference/e2e/late-staff-fixture.ts | 3 + reference/e2e/routes.snapshot.json | 166 +++++++++--------- reference/src/collections/CaseStudies.ts | 5 +- reference/src/collections/Media.ts | 4 +- reference/src/collections/Pages.ts | 4 +- reference/src/collections/Posts.ts | 5 +- reference/src/globals/Company.ts | 5 +- reference/src/globals/Footer.ts | 5 +- reference/src/globals/Header.ts | 5 +- scripts/e2e-built.mjs | 5 +- src/index.ts | 3 + src/modules/doctor/rules/security.ts | 24 +++ src/modules/doctor/status.ts | 9 +- src/modules/doctor/types.ts | 6 + src/modules/doctor/visitorWrites.ts | 46 +++++ src/modules/forms/formsPluginConfig.ts | 11 +- src/modules/security/jobsAccess.ts | 78 ++++++++ src/plugin.ts | 7 + src/types.ts | 11 ++ test/accessControl.test.ts | 24 +++ test/doctor.test.ts | 14 +- test/jobsAccess.test.ts | 95 ++++++++++ test/visitorWrites.test.ts | 56 ++++++ 40 files changed, 657 insertions(+), 187 deletions(-) create mode 100644 src/modules/doctor/visitorWrites.ts create mode 100644 src/modules/security/jobsAccess.ts create mode 100644 test/jobsAccess.test.ts create mode 100644 test/visitorWrites.test.ts diff --git a/docs/CHANGELOG.md b/docs/CHANGELOG.md index 5d8b4ce..9155fc4 100644 --- a/docs/CHANGELOG.md +++ b/docs/CHANGELOG.md @@ -9,6 +9,39 @@ 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 — DRAFT (security group C, round 2: the owner's Q1–Q3; not released) + +> Draft lines from session C (branch `claude/security-c-1172`); the integration session merges them with A's and B's. +> No schema, migration or import-map change. **Read the first two lines if the site has a customer login collection +> or uses Payload jobs over HTTP**; otherwise nothing changes for it. + +### Security +- **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 ` (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"). + +### 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`. + +### Changed +- 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 diff --git a/docs/agent/AGENT.md b/docs/agent/AGENT.md index e40944c..a5c8c31 100644 --- a/docs/agent/AGENT.md +++ b/docs/agent/AGENT.md @@ -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('')`, 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 ` (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 diff --git a/docs/agent/reference-site/INDEX.md b/docs/agent/reference-site/INDEX.md index 4b5895c..f5cc93b 100644 --- a/docs/agent/reference-site/INDEX.md +++ b/docs/agent/reference-site/INDEX.md @@ -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', diff --git a/docs/agent/skills/iapl-audit/resources/closed-doors.spec.template.ts b/docs/agent/skills/iapl-audit/resources/closed-doors.spec.template.ts index 816abbf..f2e8d4c 100644 --- a/docs/agent/skills/iapl-audit/resources/closed-doors.spec.template.ts +++ b/docs/agent/skills/iapl-audit/resources/closed-doors.spec.template.ts @@ -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: 'door@example.com', password: 'Door-Password-1234', roles: ['admin'] }, closedFor: ALL, method: 'POST', name: 'nobody creates a staff account', path: '/api/users', closed: status(403) }, { body: { email: 'first@example.com', 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 ` — 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) }, ] diff --git a/docs/agent/skills/iapl-reference/SKILL.md b/docs/agent/skills/iapl-reference/SKILL.md index 878dad2..a1b2eeb 100644 --- a/docs/agent/skills/iapl-reference/SKILL.md +++ b/docs/agent/skills/iapl-reference/SKILL.md @@ -93,7 +93,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") | `: 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 +102,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 === 'dpo@acme.pl' } }` — 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 ` (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 `` 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 +278,7 @@ The plugin's own variables are `IAPL_`; 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 ` 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 | diff --git a/docs/agent/skills/iapl-reference/resources/api.md b/docs/agent/skills/iapl-reference/resources/api.md index d6c9082..3c62922 100644 --- a/docs/agent/skills/iapl-reference/resources/api.md +++ b/docs/agent/skills/iapl-reference/resources/api.md @@ -872,6 +872,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 ` 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). | diff --git a/docs/agent/skills/iapl-upgrade/SKILL.md b/docs/agent/skills/iapl-upgrade/SKILL.md index 4ab83b2..97a3fd1 100644 --- a/docs/agent/skills/iapl-upgrade/SKILL.md +++ b/docs/agent/skills/iapl-upgrade/SKILL.md @@ -25,6 +25,15 @@ 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.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 ` 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.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`): diff --git a/docs/doctor.md b/docs/doctor.md index 83a6793..275d7eb 100644 --- a/docs/doctor.md +++ b/docs/doctor.md @@ -101,6 +101,7 @@ 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`) | diff --git a/docs/env.md b/docs/env.md index bb9a75f..2d38697 100644 --- a/docs/env.md +++ b/docs/env.md @@ -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 `, security.md "Payload's job queue"). Full table: [deployment.md](./deployment.md). Extending with your own variables — spread: diff --git a/docs/forms.md b/docs/forms.md index 21787af..0e94ac9 100644 --- a/docs/forms.md +++ b/docs/forms.md @@ -547,7 +547,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 +861,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.: 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. diff --git a/docs/security.md b/docs/security.md index 188c088..3d8144d 100644 --- a/docs/security.md +++ b/docs/security.md @@ -1197,6 +1197,40 @@ 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 `** +(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. + ## Turn off, override, extend - **Stored secrets:** `secrets: { writeOnly: false }`, `secrets: { reenterOnChange: false }`; `writeOnlySecret` / diff --git a/reference/.agents/skills/iapl-audit/resources/closed-doors.spec.template.ts b/reference/.agents/skills/iapl-audit/resources/closed-doors.spec.template.ts index 816abbf..f2e8d4c 100644 --- a/reference/.agents/skills/iapl-audit/resources/closed-doors.spec.template.ts +++ b/reference/.agents/skills/iapl-audit/resources/closed-doors.spec.template.ts @@ -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: 'door@example.com', password: 'Door-Password-1234', roles: ['admin'] }, closedFor: ALL, method: 'POST', name: 'nobody creates a staff account', path: '/api/users', closed: status(403) }, { body: { email: 'first@example.com', 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 ` — 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) }, ] diff --git a/reference/.agents/skills/iapl-reference/SKILL.md b/reference/.agents/skills/iapl-reference/SKILL.md index 878dad2..a1b2eeb 100644 --- a/reference/.agents/skills/iapl-reference/SKILL.md +++ b/reference/.agents/skills/iapl-reference/SKILL.md @@ -93,7 +93,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") | `: 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 +102,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 === 'dpo@acme.pl' } }` — 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 ` (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 `` 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 +278,7 @@ The plugin's own variables are `IAPL_`; 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 ` 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 | diff --git a/reference/.agents/skills/iapl-reference/resources/api.md b/reference/.agents/skills/iapl-reference/resources/api.md index d6c9082..3c62922 100644 --- a/reference/.agents/skills/iapl-reference/resources/api.md +++ b/reference/.agents/skills/iapl-reference/resources/api.md @@ -872,6 +872,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 ` 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). | diff --git a/reference/.agents/skills/iapl-upgrade/SKILL.md b/reference/.agents/skills/iapl-upgrade/SKILL.md index 4ab83b2..97a3fd1 100644 --- a/reference/.agents/skills/iapl-upgrade/SKILL.md +++ b/reference/.agents/skills/iapl-upgrade/SKILL.md @@ -25,6 +25,15 @@ 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.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 ` 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.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`): diff --git a/reference/e2e/closed-doors.spec.ts b/reference/e2e/closed-doors.spec.ts index 7a45c3a..9d39dcf 100644 --- a/reference/e2e/closed-doors.spec.ts +++ b/reference/e2e/closed-doors.spec.ts @@ -36,7 +36,7 @@ async function signIn(caller: Caller, baseURL: string, playwright: { request: { async function ask(api: APIRequestContext, door: (typeof DOORS)[number]): Promise { 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 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']) { diff --git a/reference/e2e/closed-doors.ts b/reference/e2e/closed-doors.ts index 8a5b09f..13e3a0a 100644 --- a/reference/e2e/closed-doors.ts +++ b/reference/e2e/closed-doors.ts @@ -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 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, }, diff --git a/reference/e2e/late-staff-fixture.ts b/reference/e2e/late-staff-fixture.ts index 025bcf3..e6a835a 100644 --- a/reference/e2e/late-staff-fixture.ts +++ b/reference/e2e/late-staff-fixture.ts @@ -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 }] }, diff --git a/reference/e2e/routes.snapshot.json b/reference/e2e/routes.snapshot.json index 5c2786a..a674b7f 100644 --- a/reference/e2e/routes.snapshot.json +++ b/reference/e2e/routes.snapshot.json @@ -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)", diff --git a/reference/src/collections/CaseStudies.ts b/reference/src/collections/CaseStudies.ts index 4d9ee4f..27ea21e 100644 --- a/reference/src/collections/CaseStudies.ts +++ b/reference/src/collections/CaseStudies.ts @@ -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] }, diff --git a/reference/src/collections/Media.ts b/reference/src/collections/Media.ts index d63c288..56e1695 100644 --- a/reference/src/collections/Media.ts +++ b/reference/src/collections/Media.ts @@ -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()], diff --git a/reference/src/collections/Pages.ts b/reference/src/collections/Pages.ts index eaa4e04..b9b4201 100644 --- a/reference/src/collections/Pages.ts +++ b/reference/src/collections/Pages.ts @@ -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' }), diff --git a/reference/src/collections/Posts.ts b/reference/src/collections/Posts.ts index 3954cae..c6e602c 100644 --- a/reference/src/collections/Posts.ts +++ b/reference/src/collections/Posts.ts @@ -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] }, diff --git a/reference/src/globals/Company.ts b/reference/src/globals/Company.ts index 59f22a5..0846158 100644 --- a/reference/src/globals/Company.ts +++ b/reference/src/globals/Company.ts @@ -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' }, diff --git a/reference/src/globals/Footer.ts b/reference/src/globals/Footer.ts index 3900a68..d3c786e 100644 --- a/reference/src/globals/Footer.ts +++ b/reference/src/globals/Footer.ts @@ -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', diff --git a/reference/src/globals/Header.ts b/reference/src/globals/Header.ts index 863fc16..6bd2a3c 100644 --- a/reference/src/globals/Header.ts +++ b/reference/src/globals/Header.ts @@ -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', diff --git a/scripts/e2e-built.mjs b/scripts/e2e-built.mjs index c614f0b..82a75f3 100644 --- a/scripts/e2e-built.mjs +++ b/scripts/e2e-built.mjs @@ -24,6 +24,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' @@ -73,6 +74,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) { @@ -89,7 +92,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', '--grep', 'late staff collection|the mail service|closed doors|no package.json is published|client hints|consent|sign-in look'], 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 and the sign-in look`, 'pnpm', ['exec', 'playwright', 'test', 'late-staff', 'mail-relay', 'closed-doors', 'smoke', 'sign-in-look', '--grep', 'late staff collection|the mail service|closed doors|no package.json is published|client hints|consent|sign-in look'], 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.)`) diff --git a/src/index.ts b/src/index.ts index e014373..5bc1395 100644 --- a/src/index.ts +++ b/src/index.ts @@ -489,6 +489,9 @@ export type { } 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' diff --git a/src/modules/doctor/rules/security.ts b/src/modules/doctor/rules/security.ts index 358e874..0f1aeef 100644 --- a/src/modules/doctor/rules/security.ts +++ b/src/modules/doctor/rules/security.ts @@ -225,6 +225,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() + 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 diff --git a/src/modules/doctor/status.ts b/src/modules/doctor/status.ts index e70e5b6..87c759e 100644 --- a/src/modules/doctor/status.ts +++ b/src/modules/doctor/status.ts @@ -15,6 +15,7 @@ import { countAccountsWithoutTotp } from '../security/totp/setupRequired.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 +112,13 @@ export async function collectDoctorStatus(payload: BasePayload): Promise unknown) | undefined +type LiveEntity = { access?: Record; auth?: unknown; slug: string } +type LivePayload = { + collections?: Record + 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 { + 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() + const ask = async (rule: Rule, key: string) => { + for (const collection of visitors) { + const user = { id: '__iapl-visitor__', collection, email: 'visitor@example.invalid' } + 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() +} diff --git a/src/modules/forms/formsPluginConfig.ts b/src/modules/forms/formsPluginConfig.ts index 4b3021b..6299ec4 100644 --- a/src/modules/forms/formsPluginConfig.ts +++ b/src/modules/forms/formsPluginConfig.ts @@ -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`. */ diff --git a/src/modules/security/jobsAccess.ts b/src/modules/security/jobsAccess.ts new file mode 100644 index 0000000..cbb0524 --- /dev/null +++ b/src/modules/security/jobsAccess.ts @@ -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 `. 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 ` (constant-time; an unset or short secret never matches). */ +export function cronSecretMatches(req: Pick, 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 + const iapl = (custom.iapl ?? {}) as Record + 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").' + ) +} diff --git a/src/plugin.ts b/src/plugin.ts index 6445f7c..ff86536 100644 --- a/src/plugin.ts +++ b/src/plugin.ts @@ -49,6 +49,7 @@ 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 { 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' @@ -981,6 +982,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. @@ -1010,6 +1014,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) { diff --git a/src/types.ts b/src/types.ts index bae1832..c3bcf65 100644 --- a/src/types.ts +++ b/src/types.ts @@ -26,6 +26,7 @@ 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 { 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' @@ -200,6 +201,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 ` (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 diff --git a/test/accessControl.test.ts b/test/accessControl.test.ts index b5fceeb..76da3e5 100644 --- a/test/accessControl.test.ts +++ b/test/accessControl.test.ts @@ -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()) diff --git a/test/doctor.test.ts b/test/doctor.test.ts index 7e83166..58b93ef 100644 --- a/test/doctor.test.ts +++ b/test/doctor.test.ts @@ -203,6 +203,18 @@ describe('M1 rules: access-missing, turnstile-degraded, turnstile-env-key', () = expect(await run(cfg, ['open-signup'])).toEqual([]) }) + test('visitor-writes: one warning per entity a visitor account may write, its operations named', async () => { + const cfg = "iapl({ access: { authCollection: 'users' } })" + const report = await doctor(project({ ...base(), 'src/payload.config.ts': cfg }), ['visitor-writes'], { deepStatus: { visitorWrites: ['globals/header:update', 'pages:create', 'pages:delete', 'pages:update'] } }) + expect(report.findings.map((f) => `${f.severity}: ${f.message}`)).toEqual([ + 'warning: an account of a visitor login collection may update the global "header"', + 'warning: an account of a visitor login collection may create, delete, update in "pages"', + ]) + expect(await run(cfg, ['visitor-writes'], { visitorWrites: [] })).toEqual([]) + expect(await run(cfg, ['visitor-writes'], { visitorWrites: null })).toEqual([]) + expect(await run(cfg, ['visitor-writes'])).toEqual([]) + }) + test('staff-accounts-open: a staff collection an account of another collection may write to is an error', async () => { const cfg = "iapl({ access: { authCollection: 'users' } })" expect(await run(cfg, ['staff-accounts-open'], { staffOpenToOthers: ['agents:delete', 'agents:update', 'users:create'] })).toEqual(['staff-accounts-open:error', 'staff-accounts-open:error', 'staff-accounts-open:error']) @@ -529,7 +541,7 @@ describe('security and deep status', () => { } const status = await collectDoctorStatus(payload as never) expect(status).toMatchObject({ pendingCookies: 4, usersWithout2fa: 2 }) - expect(Object.keys(status).sort()).toEqual(['mail', 'node', 'openSignUp', 'pendingCookies', 'plugin', 'staffOnOwnRoles', 'staffOpenToOthers', 'turnstile', 'turnstileSecretFromEnv', 'usersSetupClosed', 'usersWithout2fa']) + expect(Object.keys(status).sort()).toEqual(['mail', 'node', 'openSignUp', 'pendingCookies', 'plugin', 'staffOnOwnRoles', 'staffOpenToOthers', 'turnstile', 'turnstileSecretFromEnv', 'usersSetupClosed', 'usersWithout2fa', 'visitorWrites']) expect(status.usersSetupClosed).toBeNull() // no setup window in this config expect(status.mail).toBeNull() // no Site integrations global in this config }) diff --git a/test/jobsAccess.test.ts b/test/jobsAccess.test.ts new file mode 100644 index 0000000..7b3bdf8 --- /dev/null +++ b/test/jobsAccess.test.ts @@ -0,0 +1,95 @@ +/** + * Payload's job queue over HTTP (1.17.2, IAWL idea 35, owner's Q2): when the project writes no `jobs.access.run`, + * only an admin signed in with the second factor, or `Authorization: Bearer `, may run it. Payload's + * default let any signed-in account of any auth collection run the queue — a customer included. + */ +import type { Config, SanitizedConfig } from 'payload' + +import { sqliteAdapter } from '@payloadcms/db-sqlite' +import { afterEach, describe, expect, test, vi } from 'vitest' + +import { jobsRunNotice, withJobsRunAccess } from '../src/modules/security/jobsAccess.js' +import { iapl } from '../src/plugin.js' +import { buildTestConfig } from './helpers.js' + +vi.mock('server-only', () => ({})) + +const SECRET = 'a-cron-secret-of-32-characters!!' +const i18n = { defaultLocale: 'en', locales: [{ code: 'en', label: 'English' }] } + +const project = (jobs?: Config['jobs']): Config => + ({ + collections: [{ slug: 'customers', auth: true, fields: [] }, { slug: 'media', fields: [], upload: true }], + db: sqliteAdapter({ client: { url: 'file::memory:' } }), + jobs: { ...jobs, tasks: [{ slug: 'noop', handler: () => ({ output: {} }) }] }, + secret: 'jobs-access-test', + telemetry: false, + }) as unknown as Config + +const build = (jobs?: Config['jobs'], options: object = {}) => + buildTestConfig({ ...project(jobs), plugins: [iapl({ access: { authCollection: 'users' }, i18n, twoFactor: false, ...options } as never)] }) + +/** Calls the sanitized run rule the way Payload's run endpoint does. */ +const runAs = async (config: SanitizedConfig, user: unknown, authorization?: string) => { + const req = { headers: new Headers(authorization ? { authorization } : {}), payload: { config }, user } + return Boolean(await (config.jobs.access!.run as (a: { req: unknown }) => unknown)({ req })) +} + +const admin = { id: 1, collection: 'users', roles: ['admin'] } +const editor = { id: 2, collection: 'users', roles: ['editor'] } +const customer = { id: 3, collection: 'customers' } + +afterEach(() => { + vi.unstubAllEnvs() +}) + +describe('jobs.access.run when the project writes none', () => { + test('an admin, or the cron secret; not an editor, a customer or nobody', async () => { + vi.stubEnv('CRON_SECRET', SECRET) + const config = await build() + expect(await runAs(config, admin)).toBe(true) + expect(await runAs(config, null, `Bearer ${SECRET}`)).toBe(true) + expect(await runAs(config, null)).toBe(false) + expect(await runAs(config, customer)).toBe(false) + expect(await runAs(config, editor)).toBe(false) + expect(await runAs(config, null, 'Bearer wrong-secret-wrong-secret')).toBe(false) + expect(await runAs(config, customer, SECRET)).toBe(false) // without "Bearer " + }, 30_000) + + test('a missing or short secret never matches', async () => { + vi.stubEnv('CRON_SECRET', 'short') + const config = await build() + expect(await runAs(config, null, 'Bearer short')).toBe(false) + vi.stubEnv('CRON_SECRET', '') + expect(await runAs(config, null, 'Bearer ')).toBe(false) + }, 30_000) + + test('secretVar names another variable', async () => { + vi.stubEnv('MY_JOBS_SECRET', SECRET) + const config = await build(undefined, { jobsRunAccess: { secretVar: 'MY_JOBS_SECRET' } }) + expect(await runAs(config, null, `Bearer ${SECRET}`)).toBe(true) + }, 30_000) + + test('the project\'s own rule wins; jobsRunAccess: false keeps Payload\'s default', async () => { + const own = await build({ access: { run: () => true } }) + expect(await runAs(own, null)).toBe(true) + const payloadDefault = await build(undefined, { jobsRunAccess: false }) + expect(await runAs(payloadDefault, customer)).toBe(true) // Payload: any signed-in account + }, 30_000) + + test('a config without jobs gets the rule too (Payload turns the queue on for scheduled publishing)', () => { + const config = withJobsRunAccess({ secret: 'x' } as Config) + expect(typeof config.jobs?.access?.run).toBe('function') + expect(withJobsRunAccess({ secret: 'x' } as Config, false).jobs).toBeUndefined() + }) + + test('at start: a note when the queue is on, the rule is iapl\'s and the secret is missing', () => { + const custom = { iapl: { jobsRunDefault: { secretVar: 'CRON_SECRET' } } } + vi.stubEnv('CRON_SECRET', '') + expect(jobsRunNotice({ custom, jobs: { enabled: true } })).toMatch(/Authorization: Bearer .*not set/) + expect(jobsRunNotice({ custom, jobs: { enabled: false } })).toBeNull() + expect(jobsRunNotice({ custom: {}, jobs: { enabled: true } })).toBeNull() + vi.stubEnv('CRON_SECRET', SECRET) + expect(jobsRunNotice({ custom, jobs: { enabled: true } })).toBeNull() + }) +}) diff --git a/test/visitorWrites.test.ts b/test/visitorWrites.test.ts new file mode 100644 index 0000000..c6a9157 --- /dev/null +++ b/test/visitorWrites.test.ts @@ -0,0 +1,56 @@ +/** + * The doctor's `visitor-writes` probe (1.17.2, the owner's Q3 answer (b)): on a site with a visitor login collection, + * every collection and global whose write rule lets such an account in — Payload's default "any signed-in account" + * included — is listed. Asked by behaviour on the built config, never by a rule's name. + */ +import type { Config, SanitizedConfig } from 'payload' + +import { sqliteAdapter } from '@payloadcms/db-sqlite' +import { lexicalEditor } from '@payloadcms/richtext-lexical' +import { describe, expect, test, vi } from 'vitest' + +import { adminOrEditor } from '../src/modules/access/access.js' +import { visitorWritableEntities } from '../src/modules/doctor/visitorWrites.js' +import { iapl } from '../src/plugin.js' +import { buildTestConfig } from './helpers.js' + +vi.mock('server-only', () => ({})) + +const i18n = { defaultLocale: 'en', locales: [{ code: 'en', label: 'English' }] } +const build = (collections: Config['collections'], globals: Config['globals'] = []) => + buildTestConfig({ + admin: { user: 'users' }, + collections: [{ slug: 'media', fields: [], upload: true }, ...(collections ?? [])], + db: sqliteAdapter({ client: { url: 'file::memory:' } }), + editor: lexicalEditor(), + globals, + plugins: [iapl({ access: { authCollection: 'users' }, forms: {}, i18n, twoFactor: false } as never)], + secret: 'visitor-writes-test', + telemetry: false, + } as unknown as Config) +/** The live shape the probe reads (`payload.collections`, `payload.config`), from a built config. */ +const live = (config: SanitizedConfig) => ({ collections: Object.fromEntries(config.collections.map((c) => [c.slug, { config: c }])), config }) as never + +describe('visitorWritableEntities', () => { + test('with a visitor login collection: Payload\'s defaults are listed, explicit staff rules and the plugin\'s own are not', async () => { + const config = await build( + [ + { slug: 'customers', access: { create: () => true, delete: () => false, update: ({ req }) => ({ id: { equals: req.user?.id } }) }, auth: true, fields: [] }, + { slug: 'pages', access: { read: () => true }, fields: [{ name: 'title', type: 'text' }] }, + { slug: 'posts', access: { create: adminOrEditor, delete: adminOrEditor, read: () => true, update: adminOrEditor }, fields: [{ name: 'title', type: 'text' }] }, + ], + [{ slug: 'header', access: { read: () => true }, fields: [{ name: 'title', type: 'text' }] }], + ) + const open = await visitorWritableEntities(live(config)) + expect(open).toEqual(expect.arrayContaining(['customers:create', 'globals/header:update', 'media:create', 'media:delete', 'media:update', 'pages:create', 'pages:delete', 'pages:update', 'payload-locked-documents:create'])) + // explicit staff rules, a rule that answers a query, "nobody", the plugin's own entities + for (const closed of ['posts:create', 'posts:update', 'posts:delete', 'customers:update', 'customers:delete', 'form-submissions:create', 'forms:create', 'globals/site-settings:update', 'globals/site-integrations:update', 'payload-kv:create']) { + expect(open).not.toContain(closed) + } + }, 30_000) + + test('a site with only the staff login collection: nothing to report', async () => { + const config = await build([{ slug: 'pages', access: { read: () => true }, fields: [{ name: 'title', type: 'text' }] }]) + expect(await visitorWritableEntities(live(config))).toEqual([]) + }, 30_000) +}) From 03f5cf1a8d307c277e8385bd623b163866fa4308 Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?Rados=C5=82aw=20Smoli=C5=84ski?= Date: Tue, 1 Dec 2026 10:46:05 +0100 Subject: [PATCH 05/15] Panel actions only from the site's own origin (adminSameOrigin); doctor reads serverURL from the running config The plugin's panel actions (mail service connect / disconnect, test e-mail, cookie scan, approval, crawl) act with the panel's login cookie and read a text/plain body, which another origin sends without a CORS preflight; a sibling subdomain is same-site and Payload's csrf list is empty without serverURL. On 1.17.1 such a page reached connect with an admin's cookie (it called the mail service). Now each refuses a request a browser marks as coming from elsewhere (403 before anything is read), the rule of the 2FA endpoints; only endpoints the plugin added; logged once per origin, naming adminSameOrigin. adminSameOrigin: false / { origins } (owner's Q6). iapl-doctor csrf-empty: the deep status reports originKnown (serverURL or csrf in the running config, never the value) and it wins over the file. Co-Authored-By: Claude Opus 5.5 --- docs/agent/AGENT.md | 1 + docs/agent/skills/iapl-debug/SKILL.md | 1 + docs/agent/skills/iapl-reference/SKILL.md | 1 + .../skills/iapl-reference/resources/api.md | 1 + docs/doctor.md | 2 +- docs/security.md | 34 +++++++++ src/index.ts | 2 + src/modules/doctor/rules/security.ts | 10 ++- src/modules/doctor/status.ts | 4 +- src/modules/doctor/types.ts | 5 ++ src/modules/security/adminSameOrigin.ts | 71 +++++++++++++++++++ src/modules/security/totp/sameOrigin.ts | 18 +++-- src/modules/shared/switches.ts | 6 ++ src/plugin.ts | 6 ++ src/types.ts | 11 ++- test/adminSameOrigin.test.ts | 38 ++++++++++ test/adminSameOriginOff.test.ts | 22 ++++++ test/adminSameOriginSuite.ts | 70 ++++++++++++++++++ test/doctor.test.ts | 15 +++- 19 files changed, 308 insertions(+), 10 deletions(-) create mode 100644 src/modules/security/adminSameOrigin.ts create mode 100644 test/adminSameOrigin.test.ts create mode 100644 test/adminSameOriginOff.test.ts create mode 100644 test/adminSameOriginSuite.ts diff --git a/docs/agent/AGENT.md b/docs/agent/AGENT.md index a9a3c92..bee897c 100644 --- a/docs/agent/AGENT.md +++ b/docs/agent/AGENT.md @@ -1227,6 +1227,7 @@ 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 /api/ipal/test-email -H 'Origin: https://other.example' -H 'Content-Type: text/plain' -b -d '{}'` → `403` | `adminSameOrigin: false` | `adminSameOrigin: { origins: [...] }`; `requireOwnOrigin(endpoint, origins?)` for your own endpoints | | 2FA verify and setup attempts only from the site's own origin: a request a browser marks as coming from elsewhere (`Origin`, `Sec-Fetch-Site`) gets `403` and is not counted. The admin's reset `POST /api/ipal/two-factor/reset` follows the same rule (1.17.1). **Verify:** `curl -X POST /api/ipal/two-factor/reset -H 'Origin: https://other.example' -H 'Content-Type: text/plain' -b -d '{"userId":1}'` → `403`; the panel's button still works. **Set `serverURL`**: behind a proxy that rewrites `Host` and sends no `X-Forwarded-Host` the site's own page is refused without it (logged once per origin: `[iapl] 2FA: a code from origin … was refused`) | `twoFactor.sameOrigin: false` | `sameOrigin: { origins: ['https://app.example.com'] }`; `requestFromOwnOrigin`, `reportRefusedOrigin` | | Stored secrets are write-only: `smtpPassword` and `turnstileSecretKey` come back as `'********'` over REST, GraphQL and in the panel; an empty save keeps the value, `'[[clear]]'` removes it; server code reads the real value with the Local API. A query cannot name a secret (1.17.1): `where` / `sort` on it — REST, GraphQL, versions — is refused (`secretReadAccess`, the field's `read` rule; verify: `GET /api/globals/site-integrations/versions?where[version.smtpPassword][exists]=true` as an admin → 400 `QueryError`, no `totalDocs`). **The panel is the source — never add an env variable for them** (`TURNSTILE_SECRET_KEY` is deprecated) | `secrets: { writeOnly: false }` | `writeOnlySecret(field)` / `writeOnlySecrets(fields, names)` for your own secret fields; with versions on the entity add `hooks.afterRead: [maskSecretsOnRestore]` | | 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` | diff --git a/docs/agent/skills/iapl-debug/SKILL.md b/docs/agent/skills/iapl-debug/SKILL.md index d747a6b..16e17c7 100644 --- a/docs/agent/skills/iapl-debug/SKILL.md +++ b/docs/agent/skills/iapl-debug/SKILL.md @@ -34,6 +34,7 @@ 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' }` | | 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 | diff --git a/docs/agent/skills/iapl-reference/SKILL.md b/docs/agent/skills/iapl-reference/SKILL.md index 1375263..6262610 100644 --- a/docs/agent/skills/iapl-reference/SKILL.md +++ b/docs/agent/skills/iapl-reference/SKILL.md @@ -43,6 +43,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)//` 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 | — | diff --git a/docs/agent/skills/iapl-reference/resources/api.md b/docs/agent/skills/iapl-reference/resources/api.md index 9f17bb8..2027fd3 100644 --- a/docs/agent/skills/iapl-reference/resources/api.md +++ b/docs/agent/skills/iapl-reference/resources/api.md @@ -85,6 +85,7 @@ 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. | **Types:** `AccountsOptions` (`accounts`: `panelRole`, `adminOnlyCreate`, `adminOnlyWrite`, `staffOnlyRead`, `firstUserRoute`, `password`, `lockedAnswer`), `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`). diff --git a/docs/doctor.md b/docs/doctor.md index 83a6793..c95edac 100644 --- a/docs/doctor.md +++ b/docs/doctor.md @@ -106,7 +106,7 @@ Turn off: `iapl({ doctor: false })`. Adapt: `iapl({ doctor: { tokenVar: 'MY_TOKE | | `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 | diff --git a/docs/security.md b/docs/security.md index 188c088..c5f6675 100644 --- a/docs/security.md +++ b/docs/security.md @@ -419,6 +419,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 /api/ipal/test-email -H 'Origin: https://other.example' -H 'Content-Type: text/plain' + -b -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 — diff --git a/src/index.ts b/src/index.ts index 9c9b257..dd5b336 100644 --- a/src/index.ts +++ b/src/index.ts @@ -28,6 +28,8 @@ export type { PasswordRuleOptions } from './modules/access/passwordRule.js' export { isPasswordRuleHook, staffRuleOf } from './modules/access/ruleMark.js' export type { StaffRuleMark } from './modules/access/ruleMark.js' export { graphqlLoginName, lockedLooksWrong, withLockedAnswer } from './modules/access/lockedAnswer.js' +export { ADMIN_POST_ENDPOINTS, guardAdminEndpoints, requireOwnOrigin } from './modules/security/adminSameOrigin.js' +export type { AdminSameOriginOption } from './modules/security/adminSameOrigin.js' export type { LockedAnswerOption } from './modules/access/lockedAnswer.js' export { adoptLateAuthCollections, diff --git a/src/modules/doctor/rules/security.ts b/src/modules/doctor/rules/security.ts index 358e874..6facf5a 100644 --- a/src/modules/doctor/rules/security.ts +++ b/src/modules/doctor/rules/security.ts @@ -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://']" + 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://']", 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', diff --git a/src/modules/doctor/status.ts b/src/modules/doctor/status.ts index e70e5b6..a091aeb 100644 --- a/src/modules/doctor/status.ts +++ b/src/modules/doctor/status.ts @@ -111,7 +111,9 @@ export async function collectDoctorStatus(payload: BasePayload): Promise typeof o === 'string' && o.trim() !== '')) + return { mail, node: process.version, openSignUp, originKnown, pendingCookies, plugin: pluginVersion(), staffOnOwnRoles, staffOpenToOthers, turnstile, turnstileSecretFromEnv: secretFromEnv, usersSetupClosed, usersWithout2fa } } export type DoctorEndpointOptions = { diff --git a/src/modules/doctor/types.ts b/src/modules/doctor/types.ts index 2a716ff..4164185 100644 --- a/src/modules/doctor/types.ts +++ b/src/modules/doctor/types.ts @@ -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 /** diff --git a/src/modules/security/adminSameOrigin.ts b/src/modules/security/adminSameOrigin.ts new file mode 100644 index 0000000..17b79c3 --- /dev/null +++ b/src/modules/security/adminSameOrigin.ts @@ -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 = [ + ['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): 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>(endpoint: T, origins: string[] = []): T { + const handler = endpoint.handler as (req: PayloadRequest) => Promise | 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, 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)), + } +} diff --git a/src/modules/security/totp/sameOrigin.ts b/src/modules/security/totp/sameOrigin.ts index e427a3b..da54e65 100644 --- a/src/modules/security/totp/sameOrigin.ts +++ b/src/modules/security/totp/sameOrigin.ts @@ -89,21 +89,29 @@ const MAX_REPORTED = 50 * that origin. Without it a site behind a proxy that hides its address has a panel nobody can * enter and a silent log. Returns true when a line was written. */ -export function reportRefusedOrigin(req: RequestLike, extra: string[] = []): boolean { +/** What a refusal line names: the request, the option that allows an origin, and the doc section. Default: 2FA. */ +export type RefusalContext = { docs: string; option: string; what: string } +const TWO_FACTOR_REFUSAL: RefusalContext = { + docs: 'docs/security.md "Verify and setup attempts only from the site\'s own origin"', + option: 'twoFactor: { sameOrigin', + what: '2FA: a code', +} + +export function reportRefusedOrigin(req: RequestLike, extra: string[] = [], context: RefusalContext = TWO_FACTOR_REFUSAL): boolean { const origin = req.headers?.get('origin') - const key = origin ? (originOf(origin) ?? 'null') : `sec-fetch-site: ${req.headers?.get('sec-fetch-site') ?? 'none'}` + const key = `${context.option}|${origin ? (originOf(origin) ?? 'null') : `sec-fetch-site: ${req.headers?.get('sec-fetch-site') ?? 'none'}`}` if (reported.has(key) || reported.size >= MAX_REPORTED) {return false} reported.add(key) const { hosts, origins } = ownOrigins(req, extra) const known = [...origins, ...[...hosts].map((h) => `host ${h}`)].join(', ') || 'none' const how = originOf(origin) ? `If "${originOf(origin)}" is this site's own address (a reverse proxy that rewrites Host and sends no X-Forwarded-Host), set serverURL to it in the Payload config, ` + - `or pass twoFactor: { sameOrigin: { origins: ['${originOf(origin)}'] } }, or make the proxy send X-Forwarded-Host. ` + `or pass ${context.option}: { origins: ['${originOf(origin)}'] } }, or make the proxy send X-Forwarded-Host. ` : 'The browser did not name an origin this site knows. ' req.payload?.logger?.warn( - `[iapl] 2FA: a code from ${origin ? `origin "${origin}"` : `a ${key} request`} was refused and not counted — it is not one of this site's own origins (${known}). ` + + `[iapl] ${context.what} from ${origin ? `origin "${origin}"` : `a ${key.split('|')[1]} request`} was refused${context === TWO_FACTOR_REFUSAL ? ' and not counted' : ''} — it is not one of this site's own origins (${known}). ` + how + - 'If it is a foreign page, this is the protection working. twoFactor: { sameOrigin: false } turns the check off (docs/security.md "Verify and setup attempts only from the site\'s own origin"). Said once per origin.', + `If it is a foreign page, this is the protection working. ${context.option}: false } turns the check off (${context.docs}). Said once per origin.`, ) return true } diff --git a/src/modules/shared/switches.ts b/src/modules/shared/switches.ts index 68c6292..e938976 100644 --- a/src/modules/shared/switches.ts +++ b/src/modules/shared/switches.ts @@ -59,6 +59,12 @@ export function assertPluginSwitches(options: Record): 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) diff --git a/src/plugin.ts b/src/plugin.ts index ddae46e..9c4af88 100644 --- a/src/plugin.ts +++ b/src/plugin.ts @@ -50,6 +50,7 @@ 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 { 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 +131,8 @@ export const iapl = (options: IaplOptions): Plugin => { async function transform(incomingConfig: Config): Promise { let config = { ...incomingConfig } + /** The project's own endpoints: the panel-action origin rule (adminSameOrigin) is for the plugin's only. */ + const projectEndpoints = new Set(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'] } @@ -1101,6 +1104,9 @@ export const iapl = (options: IaplOptions): Plugin => { 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 } } diff --git a/src/types.ts b/src/types.ts index bae1832..c60f2e1 100644 --- a/src/types.ts +++ b/src/types.ts @@ -26,6 +26,7 @@ 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 { 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 +58,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 +70,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' }`. diff --git a/test/adminSameOrigin.test.ts b/test/adminSameOrigin.test.ts new file mode 100644 index 0000000..ac13ece --- /dev/null +++ b/test/adminSameOrigin.test.ts @@ -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) + }) +}) diff --git a/test/adminSameOriginOff.test.ts b/test/adminSameOriginOff.test.ts new file mode 100644 index 0000000..d743d17 --- /dev/null +++ b/test/adminSameOriginOff.test.ts @@ -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/) + }) +}) diff --git a/test/adminSameOriginSuite.ts b/test/adminSameOriginSuite.ts new file mode 100644 index 0000000..a02a300 --- /dev/null +++ b/test/adminSameOriginSuite.ts @@ -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: 'admin@example.com', password: PASSWORD, roles: ['admin'], totpSecret: SECRET } as never }) + const login = await fetch(`${state.server.url}/api/users/login`, { body: JSON.stringify({ email: 'admin@example.com', 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, body = '{"to":"someone@example.com"}') => + 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 } +} diff --git a/test/doctor.test.ts b/test/doctor.test.ts index 7e83166..f13f21a 100644 --- a/test/doctor.test.ts +++ b/test/doctor.test.ts @@ -193,6 +193,9 @@ describe('M1 rules: access-missing, turnstile-degraded, turnstile-env-key', () = expect(await run(build('{ serverURL: process.env.NEXT_PUBLIC_SERVER_URL, plugins: [] }'), ['csrf-empty'])).toEqual([]) expect(await run(build("{ csrf: ['https://site.example'], plugins: [] }"), ['csrf-empty'])).toEqual([]) expect(await run('// not a Payload config', ['csrf-empty'])).toEqual([]) + // deep (the running config, 1.17.2): it wins over the file — serverURL may come from a spread or a helper + expect(await run(build('{ ...base, plugins: [] }'), ['csrf-empty'], { originKnown: false })).toEqual(['csrf-empty:warning']) + expect(await run(build("{ plugins: [iapl({ access: { authCollection: 'users' } })] }"), ['csrf-empty'], { originKnown: true })).toEqual([]) }) test('open-signup: an auth collection anyone can register in is said, as info', async () => { @@ -230,6 +233,16 @@ describe('M1 rules: access-missing, turnstile-degraded, turnstile-env-key', () = expect(fromEnv.turnstileSecretFromEnv).toBe(true) expect(JSON.stringify(fromEnv)).not.toMatch(/secret-value/) }) + + test('the deep status says whether the running config knows its own origin (serverURL or csrf), never the value', async () => { + const fake = (extra: object) => ({ config: { admin: { user: 'users' }, collections: [{ slug: 'users', fields: [] }], globals: [], ...extra } }) + expect((await collectDoctorStatus(fake({}) as never)).originKnown).toBe(false) + expect((await collectDoctorStatus(fake({ serverURL: '' }) as never)).originKnown).toBe(false) + const known = await collectDoctorStatus(fake({ serverURL: 'https://secret-host.example' }) as never) + expect(known.originKnown).toBe(true) + expect(JSON.stringify(known)).not.toMatch(/secret-host/) + expect((await collectDoctorStatus(fake({ csrf: ['https://site.example'] }) as never)).originKnown).toBe(true) + }) }) describe('helpers', () => { @@ -529,7 +542,7 @@ describe('security and deep status', () => { } const status = await collectDoctorStatus(payload as never) expect(status).toMatchObject({ pendingCookies: 4, usersWithout2fa: 2 }) - expect(Object.keys(status).sort()).toEqual(['mail', 'node', 'openSignUp', 'pendingCookies', 'plugin', 'staffOnOwnRoles', 'staffOpenToOthers', 'turnstile', 'turnstileSecretFromEnv', 'usersSetupClosed', 'usersWithout2fa']) + expect(Object.keys(status).sort()).toEqual(['mail', 'node', 'openSignUp', 'originKnown', 'pendingCookies', 'plugin', 'staffOnOwnRoles', 'staffOpenToOthers', 'turnstile', 'turnstileSecretFromEnv', 'usersSetupClosed', 'usersWithout2fa']) expect(status.usersSetupClosed).toBeNull() // no setup window in this config expect(status.mail).toBeNull() // no Site integrations global in this config }) From 0f67a6884ceed0634b68bc61cab72464179fbdbe Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?Rados=C5=82aw=20Smoli=C5=84ski?= Date: Tue, 1 Dec 2026 10:46:42 +0100 Subject: [PATCH 06/15] e2e:built: a locked staff account and the panel actions checked on the built site (both bundlers) Co-Authored-By: Claude Opus 5.5 --- reference/e2e/sign-in-answers.spec.ts | 59 +++++++++++++++++++++++++++ scripts/e2e-built.mjs | 6 ++- 2 files changed, 63 insertions(+), 2 deletions(-) create mode 100644 reference/e2e/sign-in-answers.spec.ts diff --git a/reference/e2e/sign-in-answers.spec.ts b/reference/e2e/sign-in-answers.spec.ts new file mode 100644 index 0000000..64a5c8d --- /dev/null +++ b/reference/e2e/sign-in-answers.spec.ts @@ -0,0 +1,59 @@ +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 }) + const login = async (address: string, pass: string) => { + const res = await anon.post('/api/users/login', { data: { email: address, password: pass } }) + return { body: await res.text(), status: res.status() } + } + for (let i = 0; i < 5; i++) {await login(email, 'a-wrong-password-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) +}) diff --git a/scripts/e2e-built.mjs b/scripts/e2e-built.mjs index c614f0b..e6721cd 100644 --- a/scripts/e2e-built.mjs +++ b/scripts/e2e-built.mjs @@ -14,7 +14,9 @@ * route under Next, the state block in the panel's production bundle) and the smoke tests "no package.json is published", * "client hints" (Payload's colour-scheme headers on the admin only; a public page is requested once), every * "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). + * 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/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. @@ -89,7 +91,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', '--grep', 'late staff collection|the mail service|closed doors|no package.json is published|client hints|consent|sign-in look'], 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 and the sign-in answers`, 'pnpm', ['exec', 'playwright', 'test', 'late-staff', 'mail-relay', 'closed-doors', 'smoke', 'sign-in-look', 'sign-in-answers', '--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'], site, { ALLOW_LOCAL_MEDIA: process.env.ALLOW_LOCAL_MEDIA ?? '1', 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.)`) From 1025446a28aaf400efe210b609014cb2ce503f47 Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?Rados=C5=82aw=20Smoli=C5=84ski?= Date: Tue, 1 Dec 2026 10:49:23 +0100 Subject: [PATCH 07/15] Cookie button stays in the bottom corner of the window; it no longer climbs above the footer Owner, 2026-12-01: by default the cookie button should go to the bottom of the page, not to the footer. Until now the button (fixed, a child of ) 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. - Default: fixed in the bottom corner on every page and scroll position; safe-area inset also on the side. - Only at the very end of the page it steps just above a link, button or form field it would keep covered (`clear`, COOKIE_BUTTON_CLEAR, stepAbove); a transform, no layout shift. - The placement before: avoid={COOKIE_BUTTON_AVOID}; avoid={false} still means never move; className as before. Tests: test/cookieButtonPlacement.test.ts; reference e2e on desktop and phone (corner on long and short pages, no covered control at the page end, no layout shift, keyboard reopen). Docs: consent.md "Where the cookie button sits", AGENT.md, skills, PROGRAMISTA item 83, changelog draft 1.17.2. Co-Authored-By: Claude Fable 5.2 --- docs/CHANGELOG.md | 19 ++ docs/agent/AGENT.md | 1 + docs/agent/skills/iapl-consent-check/SKILL.md | 6 + .../skills/iapl-reference/resources/api.md | 5 +- docs/agent/skills/iapl-upgrade/SKILL.md | 10 +- docs/consent.md | 34 +++- docs/dev/PROGRAMISTA.md | 1 + .../skills/iapl-consent-check/SKILL.md | 6 + .../skills/iapl-reference/resources/api.md | 5 +- .../.agents/skills/iapl-upgrade/SKILL.md | 10 +- reference/e2e/smoke.spec.ts | 64 ++++++ src/exports/client.ts | 2 + src/modules/consent/CookieButton.tsx | 100 +++++++-- src/modules/consent/client.ts | 2 +- test/cookieButtonPlacement.test.ts | 189 ++++++++++++++++++ 15 files changed, 426 insertions(+), 28 deletions(-) create mode 100644 test/cookieButtonPlacement.test.ts diff --git a/docs/CHANGELOG.md b/docs/CHANGELOG.md index 5d8b4ce..547660e 100644 --- a/docs/CHANGELOG.md +++ b/docs/CHANGELOG.md @@ -9,6 +9,25 @@ 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 — (draft, not released) + +### Changed +- **What an existing site's visitors see: the "cookie settings" button stays in the bottom corner of the window** + ([consent.md → Where the cookie button sits](./consent.md#where-the-cookie-button-sits-1172)). Until now it 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. Only at the very end of the page, where it would keep a footer link or a button covered with no way to + scroll past, it steps up just above it (on the reference site: 71 px on a phone, nothing on desktop). No layout + shift, 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.** The placement before: + `` (on `SiteProviders`: `cookieButton={…}`). A site that already passes + `avoid` (a selector, or `false` = never move) or `className` keeps its behaviour. A project e2e test that expects the + button above the footer needs an update. + +### Added +- `CookieButton` prop `clear` (selector of controls freed at the end of the page; `false` = off), `COOKIE_BUTTON_CLEAR`, + `stepAbove` (`/client`). + ## 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 diff --git a/docs/agent/AGENT.md b/docs/agent/AGENT.md index e40944c..54746f1 100644 --- a/docs/agent/AGENT.md +++ b/docs/agent/AGENT.md @@ -1161,6 +1161,7 @@ project → **plugin gap**, not a copy. |---|---|---| | Banner, settings, cookie button | `}>`, `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 in or above the footer; at the page end it steps above a link it would keep covered. `CookieButton side` / `clear` / `avoid` (`avoid={COOKIE_BUTTON_AVOID}` = above the footer, as before 1.17.2; `false` = never move), tokens `--ipal-cookie-button-offset` / `-inset`. Do not render the button inside the footer or write a scroll handler for it | 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 \| 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 | `` — do not build your own window or cookie list | consent.md → "Large window with details" | | A consent-dependent script | `ConsentScript` | consent.md | diff --git a/docs/agent/skills/iapl-consent-check/SKILL.md b/docs/agent/skills/iapl-consent-check/SKILL.md index ee351d6..7e87549 100644 --- a/docs/agent/skills/iapl-consent-check/SKILL.md +++ b/docs/agent/skills/iapl-consent-check/SKILL.md @@ -44,6 +44,12 @@ before analytics or marketing consent — check the project's choice in "Project 5. Banner not found (`data-ipal="banner"`) → `` is not rendered, or an older IAPL version without `data-ipal` attributes on the buttons → **iapl-upgrade**. +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 — the button is in the bottom corner of the window at the + top, in the middle and with the footer in view (it must not ride up on the footer); scrolled to the very end it + lies on no link or button (it may step up a little); Tab reaches it and Enter reopens the banner. A footer whose + corner is all links: `side="right"` or a larger `--ipal-cookie-button-offset`. A project scroll handler or a + button rendered inside the footer → remove (AGENT.md §7). 6. Banner at first paint (1.17.0, consent.md → "First paint"): the banner is in the server HTML and an inline script shows or hides it before the browser paints; pages stay static. ```bash diff --git a/docs/agent/skills/iapl-reference/resources/api.md b/docs/agent/skills/iapl-reference/resources/api.md index d6c9082..d31d116 100644 --- a/docs/agent/skills/iapl-reference/resources/api.md +++ b/docs/agent/skills/iapl-reference/resources/api.md @@ -165,8 +165,9 @@ 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 (1.17.2: it no longer climbs above the footer); at the very end of the page it steps just above a link or button it would keep covered. Props `className`, `side` (`'left' \| 'right'`), `clear` (selector of controls to free at the page end, default `COOKIE_BUTTON_CLEAR`; `false`), `avoid` (placement before 1.17.2: selector it lifts above — `COOKIE_BUTTON_AVOID` = footer; `false` = never move). 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 (``); pixels the footer covers at the bottom of the screen (how far the button moves up then) | +| `COOKIE_BUTTON_CLEAR`, `stepAbove(button, obstacles, max)` | `@intecion/ipal-kit/client` | Default selector of controls the cookie button frees at the end of the page; how far a box must move up to lie on none of the given boxes (0 = stays, also when no free place within `max`) | | `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`). | diff --git a/docs/agent/skills/iapl-upgrade/SKILL.md b/docs/agent/skills/iapl-upgrade/SKILL.md index 4ab83b2..67cc71b 100644 --- a/docs/agent/skills/iapl-upgrade/SKILL.md +++ b/docs/agent/skills/iapl-upgrade/SKILL.md @@ -25,6 +25,14 @@ 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.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 no longer moves up +above the footer. Look at the end of a page on a phone: the button must lie on no link (it steps up by itself; a +footer corner full of links → `side="right"` or a larger `--ipal-cookie-button-offset`). The placement before: +`cookieButton={}` on `SiteProviders`. A project that passes `avoid` (a +selector or `false`) or `className` keeps what it had. A project e2e that expects the button above the footer: +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 +260,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://`), 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. diff --git a/docs/consent.md b/docs/consent.md index 1734208..31b2da0 100644 --- a/docs/consent.md +++ b/docs/consent.md @@ -113,12 +113,34 @@ 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. It is a child of `` (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). + +One exception keeps every control reachable: **at the very end of the page**, where a visitor cannot scroll a +covered link out from under a fixed button, the button steps up just far enough to lie on no link, button or form +field (`stepAbove`; 8 px gap; never more than half the window, otherwise it stays in the corner). It then usually +rests on plain text of the footer (the copyright line). Anywhere above the end of the page it stays in the corner: a +covered control is one scroll away. The step is a `transform` — no layout shift. + +| Prop | Default | What it does | +|---|---|---| +| `side` | `'left'` | corner: `'left'` or `'right'` | +| `clear` | `COOKIE_BUTTON_CLEAR` (links, buttons, form fields) | CSS selector of controls the button frees at the end of the page; `false` = stay in the corner whatever is under it | +| `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`). `false` = never move at all (also turns `clear` off) | +| `className` | — | replaces the default classes; position is then yours too (the `clear` step applies only while your classes keep it `position: fixed`) | + +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 `'), box(750, 790, 20, 140)) + await mount() + expect(lift()).toBe('42') + }) + + test('end of the page, nothing under it (text only): stays in the corner', async () => { + setRect(add('

© Example

'), box(760, 780, 30, 400)) + setRect(add('Terms'), box(760, 780, 900, 960)) + await mount() + await scrollTo(2200) + expect(lift()).toBe('0') + }) + + test('clear={false} and avoid={false}: never moves', async () => { + setRect(add('Instagram'), box(760, 780, 30, 120)) + setRect(add('
company
'), box(500, 1100, 0, 1280)) + await mount({ clear: false }) + await scrollTo(2200) + expect(lift()).toBe('0') + act(() => root.render(h(ConsentProvider, { texts: CONSENT_FALLBACK }, h(CookieButton, { avoid: false })))) + await scrollTo(2200) + expect(lift()).toBe('0') + }) + + test('a selector of your own in clear', async () => { + setRect(add('Instagram'), box(760, 780, 30, 120)) + setRect(add('
chat
'), box(700, 790, 10, 70)) + await mount({ clear: '.chat' }) + await scrollTo(2200) + expect(lift()).toBe(String(784 - 700 + 8)) + }) + + test('className (the project positions it, here not fixed): no step', async () => { + setRect(add('Instagram'), box(760, 780, 30, 120)) + await mount({ className: 'in-the-footer' }) + expect(button().style.position).toBe('') + await scrollTo(2200) + expect(lift()).toBe('0') + }) +}) From fb92b357e89e0b44e0ceb34691cdb29deb2b9256 Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?Rados=C5=82aw=20Smoli=C5=84ski?= Date: Tue, 1 Dec 2026 10:50:03 +0100 Subject: [PATCH 08/15] Consent-check skill: the cookie button step after the first-paint step Co-Authored-By: Claude Fable 5.2 --- docs/agent/skills/iapl-consent-check/SKILL.md | 12 ++++++------ reference/.agents/skills/iapl-consent-check/SKILL.md | 12 ++++++------ 2 files changed, 12 insertions(+), 12 deletions(-) diff --git a/docs/agent/skills/iapl-consent-check/SKILL.md b/docs/agent/skills/iapl-consent-check/SKILL.md index 7e87549..b7d462c 100644 --- a/docs/agent/skills/iapl-consent-check/SKILL.md +++ b/docs/agent/skills/iapl-consent-check/SKILL.md @@ -44,12 +44,6 @@ before analytics or marketing consent — check the project's choice in "Project 5. Banner not found (`data-ipal="banner"`) → `` is not rendered, or an older IAPL version without `data-ipal` attributes on the buttons → **iapl-upgrade**. -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 — the button is in the bottom corner of the window at the - top, in the middle and with the footer in view (it must not ride up on the footer); scrolled to the very end it - lies on no link or button (it may step up a little); Tab reaches it and Enter reopens the banner. A footer whose - corner is all links: `side="right"` or a larger `--ipal-cookie-button-offset`. A project scroll handler or a - button rendered inside the footer → remove (AGENT.md §7). 6. Banner at first paint (1.17.0, consent.md → "First paint"): the banner is in the server HTML and an inline script shows or hides it before the browser paints; pages stay static. ```bash @@ -61,6 +55,12 @@ before analytics or marketing consent — check the project's choice in "Project `nonce` to ``. 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 — the button is in the bottom corner of the window at the + top, in the middle and with the footer in view (it must not ride up on the footer); scrolled to the very end it + lies on no link or button (it may step up a little); Tab reaches it and Enter reopens the banner. A footer whose + corner is all links: `side="right"` or a larger `--ipal-cookie-button-offset`. A project scroll handler or a + button rendered inside the footer → remove (AGENT.md §7). 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. diff --git a/reference/.agents/skills/iapl-consent-check/SKILL.md b/reference/.agents/skills/iapl-consent-check/SKILL.md index 7e87549..b7d462c 100644 --- a/reference/.agents/skills/iapl-consent-check/SKILL.md +++ b/reference/.agents/skills/iapl-consent-check/SKILL.md @@ -44,12 +44,6 @@ before analytics or marketing consent — check the project's choice in "Project 5. Banner not found (`data-ipal="banner"`) → `` is not rendered, or an older IAPL version without `data-ipal` attributes on the buttons → **iapl-upgrade**. -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 — the button is in the bottom corner of the window at the - top, in the middle and with the footer in view (it must not ride up on the footer); scrolled to the very end it - lies on no link or button (it may step up a little); Tab reaches it and Enter reopens the banner. A footer whose - corner is all links: `side="right"` or a larger `--ipal-cookie-button-offset`. A project scroll handler or a - button rendered inside the footer → remove (AGENT.md §7). 6. Banner at first paint (1.17.0, consent.md → "First paint"): the banner is in the server HTML and an inline script shows or hides it before the browser paints; pages stay static. ```bash @@ -61,6 +55,12 @@ before analytics or marketing consent — check the project's choice in "Project `nonce` to ``. 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 — the button is in the bottom corner of the window at the + top, in the middle and with the footer in view (it must not ride up on the footer); scrolled to the very end it + lies on no link or button (it may step up a little); Tab reaches it and Enter reopens the banner. A footer whose + corner is all links: `side="right"` or a larger `--ipal-cookie-button-offset`. A project scroll handler or a + button rendered inside the footer → remove (AGENT.md §7). 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. From 910fbd75cf518ae1a974917f7a4ec089f9324293 Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?Rados=C5=82aw=20Smoli=C5=84ski?= Date: Tue, 1 Dec 2026 10:52:25 +0100 Subject: [PATCH 09/15] IPv6 grouping without node:net (the limiter also reaches non-Node bundles; webpack build); reference index entry; export order Co-Authored-By: Claude Opus 5.5 --- docs/agent/reference-site/INDEX.md | 1 + scripts/reference-index.mjs | 1 + src/index.ts | 8 ++++---- src/modules/shared/rateLimit.ts | 30 ++++++++++++++++++------------ test/rateLimitIpv6.test.ts | 3 +++ 5 files changed, 27 insertions(+), 16 deletions(-) diff --git a/docs/agent/reference-site/INDEX.md b/docs/agent/reference-site/INDEX.md index 4b5895c..b564f34 100644 --- a/docs/agent/reference-site/INDEX.md +++ b/docs/agent/reference-site/INDEX.md @@ -1175,6 +1175,7 @@ Rules: AGENT.md §8a. | `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/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) | diff --git a/scripts/reference-index.mjs b/scripts/reference-index.mjs index 67cb639..6866ced 100644 --- a/scripts/reference-index.mjs +++ b/scripts/reference-index.mjs @@ -71,6 +71,7 @@ export const DESCRIPTIONS = { 'e2e/mail-relay-setup.ts': 'for the mail-service spec: empties the SMTP fields and the stored token, so the next e-mail enrols and goes through the mail service (local database only)', '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/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', diff --git a/src/index.ts b/src/index.ts index dd5b336..9ad6a5e 100644 --- a/src/index.ts +++ b/src/index.ts @@ -22,15 +22,13 @@ export { staffCollectionSlugs, userMeetsRole, } 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' export { isPasswordRuleHook, staffRuleOf } from './modules/access/ruleMark.js' export type { StaffRuleMark } from './modules/access/ruleMark.js' -export { graphqlLoginName, lockedLooksWrong, withLockedAnswer } from './modules/access/lockedAnswer.js' -export { ADMIN_POST_ENDPOINTS, guardAdminEndpoints, requireOwnOrigin } from './modules/security/adminSameOrigin.js' -export type { AdminSameOriginOption } from './modules/security/adminSameOrigin.js' -export type { LockedAnswerOption } from './modules/access/lockedAnswer.js' export { adoptLateAuthCollections, applyFirstUserRoute, @@ -458,6 +456,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, diff --git a/src/modules/shared/rateLimit.ts b/src/modules/shared/rateLimit.ts index 091d412..efa527e 100644 --- a/src/modules/shared/rateLimit.ts +++ b/src/modules/shared/rateLimit.ts @@ -1,5 +1,3 @@ -import { isIPv4, isIPv6 } from 'node:net' - import { readEnv } from './envName.js' type Bucket = { count: number; resetAt: number } @@ -131,22 +129,30 @@ export function setIpv6Grouping(next: Ipv6Grouping = {}): void { ipv6 = { prefix, wide, wideFactor } } -/** The 8 groups of an IPv6 address as numbers, or null. */ +/** 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[] { - const bare = address.replace(/^\[|\]$/g, '').split('%')[0] - if (!isIPv6(bare)) {return null} - let text = bare - const v4 = /(\d+\.\d+\.\d+\.\d+)$/.exec(text) + 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)}` - } - const [head, tail] = text.includes('::') ? text.split('::') : [text, undefined] + } 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(':') : [] - const fill = tail === undefined ? [] : Array(8 - left.length - right.length).fill('0') - const groups = [...left, ...fill, ...right].map((g) => parseInt(g, 16)) - return groups.length === 8 && groups.every((g) => Number.isInteger(g) && g >= 0 && g <= 0xffff) ? groups : null + 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). */ diff --git a/test/rateLimitIpv6.test.ts b/test/rateLimitIpv6.test.ts index 1bd0ce2..d26e4ae 100644 --- a/test/rateLimitIpv6.test.ts +++ b/test/rateLimitIpv6.test.ts @@ -32,6 +32,9 @@ describe('ipRateKey', () => { expect(ipRateKey('::ffff:c633:6407')).toBe('198.51.100.7') expect(ipRateKey('')).toBe('') expect(ipRateKey('not-an-ip')).toBe('not-an-ip') + for (const bad of ['1::2::3', '2001:db8:1:2:3:4:5:6:7', '12345::1', '::ffff:300.1.1.1', 'to:abcdef', 'a:b']) {expect([bad, ipRateKey(bad)]).toEqual([bad, bad])} + expect(ipRateKey('::')).toBe('0:0:0:0:0:0:0:0/64') + expect(ipRateKey('256.1.1.1')).toBe('256.1.1.1') }) test('setIpv6Grouping: per address again, another prefix; nonsense is refused', () => { From 27ddbc3b41b4c508cea897defd262fcb3504ad01 Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?Rados=C5=82aw=20Smoli=C5=84ski?= Date: Tue, 1 Dec 2026 10:55:44 +0100 Subject: [PATCH 10/15] Consent version only goes up (owner's decision Q2, 1.17.2) MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit A stored consent counts only under the version it was given for, so a lower Cookies → Consent version made consent given under an older policy valid again. A save through access control (panel, REST, GraphQL) with a lower number is now refused with a message (English and Polish); the same or a higher number and saves without it pass; the Local API with overrideAccess may still lower it. iapl({ cookieSettings: { allowLowerPolicyVersion: true } }) keeps the old behaviour. Building blocks exported: policyVersionNeverDown, buildCookieSettingsFields, buildCookieSettings. No schema change. Co-Authored-By: Claude Opus 5.5 --- docs/agent/AGENT.md | 1 + docs/consent.md | 7 ++ src/globals/CookieSettings/fields.ts | 38 ++++++++- src/globals/CookieSettings/index.ts | 6 +- src/index.ts | 3 + src/modules/admin-i18n/texts/consent.ts | 2 + src/plugin.ts | 2 +- src/types.ts | 7 ++ test/policyVersionRising.test.ts | 106 ++++++++++++++++++++++++ 9 files changed, 167 insertions(+), 5 deletions(-) create mode 100644 test/policyVersionRising.test.ts diff --git a/docs/agent/AGENT.md b/docs/agent/AGENT.md index e40944c..9c682db 100644 --- a/docs/agent/AGENT.md +++ b/docs/agent/AGENT.md @@ -1217,6 +1217,7 @@ 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 /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 | | Consent log on (since 1.17.0; Postgres / SQLite: a migration in the same deploy) | `consentLog: false`; one layout: `logEndpoint={false}` | `consentLog: { retentionDays, collectionOverrides }`; `buildConsentLogCollection` / `buildConsentLogEndpoint`, `CONSENT_LOG_PATH` | | Global Privacy Control honoured: no banner, analytics and marketing off, no Google request also in Consent Mode `advanced`; a grant made without the signal is switched off when it appears | `gpc={false}` (doctor warns) | `gpc="ask"`; `resolveConsent`, `gpcFromHeaders`, `consentBannerScript({ gpc })` | | "Reject" styled like "Accept all" (`equalChoice`) | `equalChoice={false}` (doctor warns) | `classNames.rejectButton` | diff --git a/docs/consent.md b/docs/consent.md index 1734208..4bfa840 100644 --- a/docs/consent.md +++ b/docs/consent.md @@ -542,6 +542,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 `` 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: `` (added to the diff --git a/src/globals/CookieSettings/fields.ts b/src/globals/CookieSettings/fields.ts index caed549..9fa0dd9 100644 --- a/src/globals/CookieSettings/fields.ts +++ b/src/globals/CookieSettings/fields.ts @@ -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ć.' } diff --git a/src/globals/CookieSettings/index.ts b/src/globals/CookieSettings/index.ts index 3617381..a651b3f 100644 --- a/src/globals/CookieSettings/index.ts +++ b/src/globals/CookieSettings/index.ts @@ -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' }, } } diff --git a/src/index.ts b/src/index.ts index e014373..bd53c81 100644 --- a/src/index.ts +++ b/src/index.ts @@ -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' diff --git a/src/modules/admin-i18n/texts/consent.ts b/src/modules/admin-i18n/texts/consent.ts index dacbe7f..b507329 100644 --- a/src/modules/admin-i18n/texts/consent.ts +++ b/src/modules/admin-i18n/texts/consent.ts @@ -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.', }, }) diff --git a/src/plugin.ts b/src/plugin.ts index 6445f7c..3552748 100644 --- a/src/plugin.ts +++ b/src/plugin.ts @@ -766,7 +766,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. diff --git a/src/types.ts b/src/types.ts index bae1832..51abf39 100644 --- a/src/types.ts +++ b/src/types.ts @@ -119,6 +119,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). diff --git a/test/policyVersionRising.test.ts b/test/policyVersionRising.test.ts new file mode 100644 index 0000000..a1e5b26 --- /dev/null +++ b/test/policyVersionRising.test.ts @@ -0,0 +1,106 @@ +/** + * Cookie settings → Consent version only goes up (owner's decision Q2, 1.17.2). A stored consent counts only under + * the version it was given for: a LOWER number made old consent cookies valid again. A save through access control + * with a lower number is refused with a message; the Local API with `overrideAccess` may still lower it; + * `cookieSettings: { allowLowerPolicyVersion: true }` keeps the old behaviour. + * Real HTTP; SQLite by default, Postgres / MongoDB with IPAL_TEST_POSTGRES_URI / IPAL_TEST_MONGO_URI. + */ + +import { lexicalEditor } from '@payloadcms/richtext-lexical' +import os from 'os' +import path from 'path' +import { getPayload } from 'payload' +import { afterAll, beforeAll, describe, expect, test, vi } from 'vitest' + +import { iapl } from '../src/plugin.js' +import { buildTestConfig } from './helpers.js' +import { testDatabase } from './http/db.js' +import { startPayloadServer } from './http/server.js' + +vi.mock('server-only', () => ({})) + +const PASSWORD = 'a-long-test-password-1' + +async function site(name: string, cookieSettings?: { allowLowerPolicyVersion?: boolean }) { + const config = buildTestConfig({ + admin: { user: 'users' }, + collections: [{ slug: 'media', fields: [], upload: { staticDir: path.join(os.tmpdir(), `iapl-${name}`) } }], + db: testDatabase(name), + editor: lexicalEditor(), + plugins: [iapl({ access: { authCollection: 'users' }, ...(cookieSettings ? { cookieSettings } : {}), i18n: { defaultLocale: 'en', locales: [{ code: 'en', label: 'English' }] }, mail: { relay: false }, twoFactor: false })], + secret: `${name}-0123456789-0123456789`, + telemetry: false, + }) + const payload = await getPayload({ config }) + const server = await startPayloadServer(config) + await payload.create({ collection: 'users' as never, data: { email: 'editor@example.com', password: PASSWORD, roles: ['editor'] } as never }) + const { token } = (await (await fetch(`${server.url}/api/users/login`, { body: JSON.stringify({ email: 'editor@example.com', password: PASSWORD }), headers: { 'content-type': 'application/json' }, method: 'POST' })).json()) as { token: string } + await payload.updateGlobal({ slug: 'cookie-settings' as never, data: { policyVersion: 3 } as never }) + const save = (data: Record) => + fetch(`${server.url}/api/globals/cookie-settings`, { body: JSON.stringify(data), headers: { authorization: `JWT ${token}`, 'content-type': 'application/json' }, method: 'POST' }) + const gql = (query: string) => + fetch(`${server.url}/api/graphql`, { body: JSON.stringify({ query }), headers: { authorization: `JWT ${token}`, 'content-type': 'application/json' }, method: 'POST' }).then((r) => r.json() as Promise<{ errors?: { message: string }[] }>) + const stored = async () => ((await payload.findGlobal({ slug: 'cookie-settings' as never })) as { policyVersion?: number }).policyVersion + return { gql, payload, save, server, stored } +} + +describe('by default the consent version only goes up', () => { + let s: Awaited> + beforeAll(async () => { + s = await site('policy_rising') + }, 120_000) + afterAll(async () => { + await s?.server.close() + await s?.payload.destroy?.() + }) + + test('a lower number is refused with the message, and the stored one stays', async () => { + const res = await s.save({ policyVersion: 1 }) + expect(res.status).toBe(400) + expect(JSON.stringify(await res.json())).toContain('The consent version cannot go down: it is 3 now') + expect(await s.stored()).toBe(3) + }) + + test('over GraphQL too', async () => { + const res = await s.gql('mutation { updateCookieSetting(data: { policyVersion: 2 }) { policyVersion } }') + expect(res.errors?.[0]?.message ?? '').toMatch(/invalid|cannot go down/i) + expect(await s.stored()).toBe(3) + }) + + test('the same number, a higher one, and a save that does not send it all pass', async () => { + expect((await s.save({ policyVersion: 3 })).status).toBe(200) + expect((await s.save({ title: 'Cookies' })).status).toBe(200) + expect((await s.save({ policyVersion: 4 })).status).toBe(200) + expect(await s.stored()).toBe(4) + }) + + test('the Local API with access control off may lower it (a script an admin runs)', async () => { + await s.payload.updateGlobal({ slug: 'cookie-settings' as never, data: { policyVersion: 2 } as never }) + expect(await s.stored()).toBe(2) + }) + + test('the Polish text exists', async () => { + const { adminTexts } = await import('../src/modules/admin-i18n/texts/index.js') + expect(JSON.stringify(adminTexts)).toContain('Wersji zgody nie można obniżyć') + }) +}) + +describe('cookieSettings: { allowLowerPolicyVersion: true } keeps the old behaviour', () => { + test('the field has no consent-version rule then, and has it by default', async () => { + const { buildCookieSettings } = await import('../src/globals/CookieSettings/index.js') + const { policyVersionNeverDown } = await import('../src/globals/CookieSettings/fields.js') + const hooksOf = (g: { fields: unknown[] }) => + ((g.fields as { hooks?: { beforeValidate?: unknown[] }; name?: string }[]).find((f) => f.name === 'policyVersion')?.hooks?.beforeValidate ?? []) + expect(hooksOf(buildCookieSettings())).toContain(policyVersionNeverDown) + expect(hooksOf(buildCookieSettings({ allowLowerPolicyVersion: true }))).not.toContain(policyVersionNeverDown) + }) + + test('iapl() passes the option through', async () => { + const { buildConfig } = await import('payload') + const { policyVersionNeverDown } = await import('../src/globals/CookieSettings/fields.js') + const config = await iapl({ cookieSettings: { allowLowerPolicyVersion: true }, i18n: { defaultLocale: 'en', locales: [{ code: 'en', label: 'English' }] }, mail: { relay: false }, twoFactor: false })({ collections: [], secret: 'x' } as never) + void buildConfig + const g = config.globals!.find((x) => x.slug === 'cookie-settings') as { fields: { hooks?: { beforeValidate?: unknown[] }; name?: string }[] } + expect(g.fields.find((f) => f.name === 'policyVersion')?.hooks?.beforeValidate ?? []).not.toContain(policyVersionNeverDown) + }) +}) From 35bc4f094a0bb592f5d87c78ace32c254c542034 Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?Rados=C5=82aw=20Smoli=C5=84ski?= Date: Tue, 1 Dec 2026 11:07:46 +0100 Subject: [PATCH 11/15] Consent version test: no direct buildConfig import (testConfig guard) Co-Authored-By: Claude Opus 5.5 --- test/policyVersionRising.test.ts | 2 -- 1 file changed, 2 deletions(-) diff --git a/test/policyVersionRising.test.ts b/test/policyVersionRising.test.ts index a1e5b26..936c03a 100644 --- a/test/policyVersionRising.test.ts +++ b/test/policyVersionRising.test.ts @@ -96,10 +96,8 @@ describe('cookieSettings: { allowLowerPolicyVersion: true } keeps the old behavi }) test('iapl() passes the option through', async () => { - const { buildConfig } = await import('payload') const { policyVersionNeverDown } = await import('../src/globals/CookieSettings/fields.js') const config = await iapl({ cookieSettings: { allowLowerPolicyVersion: true }, i18n: { defaultLocale: 'en', locales: [{ code: 'en', label: 'English' }] }, mail: { relay: false }, twoFactor: false })({ collections: [], secret: 'x' } as never) - void buildConfig const g = config.globals!.find((x) => x.slug === 'cookie-settings') as { fields: { hooks?: { beforeValidate?: unknown[] }; name?: string }[] } expect(g.fields.find((f) => f.name === 'policyVersion')?.hooks?.beforeValidate ?? []).not.toContain(policyVersionNeverDown) }) From 21ef0fdeb0f047658d6101c5c5c3bead4f6acca2 Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?Rados=C5=82aw=20Smoli=C5=84ski?= Date: Tue, 1 Dec 2026 11:15:13 +0100 Subject: [PATCH 12/15] 1.18.0 (owner's decisions Q3, Q4, Q5): writes that keep others' saves, access answers announced, drafts out of related documents - Q3: the integration status (emailStatus, turnstileStatus) is written alone through the database adapter (writeGlobalFields, exported): a visitor's form submit no longer puts back an admin's SMTP or Turnstile change saved at the same moment. addToCookieList reads the list again right before writing and works the change out again when an editor's save changed it (up to 5 times). Both races reproduced exactly in test/statusWrites.test.ts, on the three adapters. - Q4: cookieScanner.access and the doctor's access go through accessAllowed: any truthy answer still allows, an answer that is not a boolean is reported once per option; strict (only true) is announced for 1.19.0. - Q5: related documents that are drafts are left out of what the public helpers answer (resolveRoute, getSettings, getArchiveEntries, the 404 page, llms-full; Markdown and MCP through resolveRoute): null alone, removed from a list, value null in a polymorphic one. A preview keeps them; draftRelations: 'keep' keeps the old behaviour. withoutDraftRelations, applyDraftRelations exported. - Docs: content.md, frontend.md, integrations.md, cookie-scanner.md, security.md, AGENT.md; iapl-nav and iapl-doctor skills. Co-Authored-By: Claude Opus 5.5 --- docs/agent/AGENT.md | 3 + docs/agent/skills/iapl-doctor/SKILL.md | 3 +- docs/agent/skills/iapl-nav/SKILL.md | 4 +- docs/content.md | 27 +++++ docs/cookie-scanner.md | 2 +- docs/frontend.md | 1 + docs/integrations.md | 5 + docs/security.md | 11 ++ src/index.ts | 9 +- src/modules/consent/scanner/approval.ts | 3 +- .../consent/scanner/crawl/endpoints.ts | 3 +- src/modules/consent/scanner/endpoint.ts | 3 +- src/modules/consent/scanner/sync.ts | 68 +++++++---- src/modules/content/draftRelations.ts | 70 +++++++++++ src/modules/content/getArchiveEntries.ts | 7 +- src/modules/content/index.ts | 1 + src/modules/content/resolveNotFoundPage.ts | 6 +- src/modules/content/resolveRoute.ts | 17 ++- src/modules/doctor/status.ts | 3 +- src/modules/frontend/createContentHelpers.ts | 17 ++- src/modules/integrations/index.ts | 1 + src/modules/integrations/status.ts | 25 +++- src/modules/seo/buildLlmsTxt.ts | 5 + src/modules/seo/routeHandlers.ts | 4 + src/modules/seo/siteIndex.ts | 6 +- src/modules/shared/accessAnswer.ts | 33 ++++++ test/accessAnswer.test.ts | 52 +++++++++ test/draftRelations.test.ts | 105 +++++++++++++++++ test/statusWrites.test.ts | 109 ++++++++++++++++++ 29 files changed, 555 insertions(+), 48 deletions(-) create mode 100644 src/modules/content/draftRelations.ts create mode 100644 src/modules/shared/accessAnswer.ts create mode 100644 test/accessAnswer.test.ts create mode 100644 test/draftRelations.test.ts create mode 100644 test/statusWrites.test.ts diff --git a/docs/agent/AGENT.md b/docs/agent/AGENT.md index e40944c..29b69e9 100644 --- a/docs/agent/AGENT.md +++ b/docs/agent/AGENT.md @@ -1217,6 +1217,9 @@ 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 /md/xx` → 404 | | Site integrations versions (when a project turns them on) are read by admins only (`readVersions`) | — | `globalOverrides: { 'site-integrations': { access: { readVersions } } }` | +| 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` | diff --git a/docs/agent/skills/iapl-doctor/SKILL.md b/docs/agent/skills/iapl-doctor/SKILL.md index 7a1fb57..f0d4c87 100644 --- a/docs/agent/skills/iapl-doctor/SKILL.md +++ b/docs/agent/skills/iapl-doctor/SKILL.md @@ -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 `; 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 diff --git a/docs/agent/skills/iapl-nav/SKILL.md b/docs/agent/skills/iapl-nav/SKILL.md index 8632608..70a4619 100644 --- a/docs/agent/skills/iapl-nav/SKILL.md +++ b/docs/agent/skills/iapl-nav/SKILL.md @@ -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. diff --git a/docs/content.md b/docs/content.md index f1a0592..71a875c 100644 --- a/docs/content.md +++ b/docs/content.md @@ -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: diff --git a/docs/cookie-scanner.md b/docs/cookie-scanner.md index 8356d25..4027d3d 100644 --- a/docs/cookie-scanner.md +++ b/docs/cookie-scanner.md @@ -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) | diff --git a/docs/frontend.md b/docs/frontend.md index 0230bf0..84b0b26 100644 --- a/docs/frontend.md +++ b/docs/frontend.md @@ -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` | diff --git a/docs/integrations.md b/docs/integrations.md index 004b8df..a2ff1a6 100644 --- a/docs/integrations.md +++ b/docs/integrations.md @@ -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: diff --git a/docs/security.md b/docs/security.md index 188c088..e92dd8e 100644 --- a/docs/security.md +++ b/docs/security.md @@ -1197,6 +1197,17 @@ 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. +## 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` / diff --git a/src/index.ts b/src/index.ts index e014373..2839788 100644 --- a/src/index.ts +++ b/src/index.ts @@ -219,6 +219,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, @@ -240,8 +241,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' @@ -391,7 +393,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' @@ -487,8 +489,8 @@ export type { TotpUser, WithSecurityConfigOptions, } from './modules/security/index.js' - export type { BuildSecurityHeadersArgs, SecurityHeader } from './modules/security/index.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' @@ -564,6 +566,7 @@ 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`. diff --git a/src/modules/consent/scanner/approval.ts b/src/modules/consent/scanner/approval.ts index b6339b3..a9315bc 100644 --- a/src/modules/consent/scanner/approval.ts +++ b/src/modules/consent/scanner/approval.ts @@ -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) => { diff --git a/src/modules/consent/scanner/crawl/endpoints.ts b/src/modules/consent/scanner/crawl/endpoints.ts index 8ef3e0d..ec6cdc9 100644 --- a/src/modules/consent/scanner/crawl/endpoints.ts +++ b/src/modules/consent/scanner/crawl/endpoints.ts @@ -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) => diff --git a/src/modules/consent/scanner/endpoint.ts b/src/modules/consent/scanner/endpoint.ts index 6520e3b..476133c 100644 --- a/src/modules/consent/scanner/endpoint.ts +++ b/src/modules/consent/scanner/endpoint.ts @@ -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) => diff --git a/src/modules/consent/scanner/sync.ts b/src/modules/consent/scanner/sync.ts index 8fd3f6a..4fec0bc 100644 --- a/src/modules/consent/scanner/sync.ts +++ b/src/modules/consent/scanner/sync.ts @@ -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 } diff --git a/src/modules/content/draftRelations.ts b/src/modules/content/draftRelations.ts new file mode 100644 index 0000000..764cc33 --- /dev/null +++ b/src/modules/content/draftRelations.ts @@ -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(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 + let result: null | Record = 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(value: T, { draft = false, draftRelations = 'hide' }: { draft?: boolean; draftRelations?: DraftRelations } = {}): T { + return draft || draftRelations === 'keep' ? value : withoutDraftRelations(value) +} diff --git a/src/modules/content/getArchiveEntries.ts b/src/modules/content/getArchiveEntries.ts index cfaa012..08c99ef 100644 --- a/src/modules/content/getArchiveEntries.ts +++ b/src/modules/content/getArchiveEntries.ts @@ -1,5 +1,7 @@ import type { BasePayload } from 'payload' +import { applyDraftRelations, type DraftRelations } from './draftRelations.js' + export type ArchiveEntries> = { 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>({ collection, depth = 1, draft = false, + draftRelations, locale, page = 1, payload, @@ -69,7 +74,7 @@ export async function getArchiveEntries>({ }) return { - docs: result.docs as T[], + docs: applyDraftRelations(result.docs, { draft, draftRelations }) as T[], hasNextPage: result.hasNextPage, hasPrevPage: result.hasPrevPage, page: result.page ?? 1, diff --git a/src/modules/content/index.ts b/src/modules/content/index.ts index 5e43b63..9ffa45f 100644 --- a/src/modules/content/index.ts +++ b/src/modules/content/index.ts @@ -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' diff --git a/src/modules/content/resolveNotFoundPage.ts b/src/modules/content/resolveNotFoundPage.ts index 3f3c8c3..225ac68 100644 --- a/src/modules/content/resolveNotFoundPage.ts +++ b/src/modules/content/resolveNotFoundPage.ts @@ -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) : null + return isPublishedDoc(doc) ? applyDraftRelations(doc as Record, { draftRelations }) : null } catch (error) { console.warn('[iapl] resolveNotFoundPage: falling back to built-in 404 view:', error) return null diff --git a/src/modules/content/resolveRoute.ts b/src/modules/content/resolveRoute.ts index 8af1746..4536b2e 100644 --- a/src/modules/content/resolveRoute.ts +++ b/src/modules/content/resolveRoute.ts @@ -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 { + const route = await resolveRouteDocs(args) + if (!route) {return null} + const hide = (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, diff --git a/src/modules/doctor/status.ts b/src/modules/doctor/status.ts index e70e5b6..601406e 100644 --- a/src/modules/doctor/status.ts +++ b/src/modules/doctor/status.ts @@ -12,6 +12,7 @@ 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' @@ -141,7 +142,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' } }) diff --git a/src/modules/frontend/createContentHelpers.ts b/src/modules/frontend/createContentHelpers.ts index b64aa71..2c5d974 100644 --- a/src/modules/frontend/createContentHelpers.ts +++ b/src/modules/frontend/createContentHelpers.ts @@ -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 /** 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 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) : null + return isPublishedDoc(doc) ? applyDraftRelations(doc as Record, { draftRelations }) : null } catch { return null // DB unreachable (container build) or page deleted — fallback view } @@ -431,7 +440,7 @@ export function createContentHelpers({ perPage: number, ): Promise => { 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 })) diff --git a/src/modules/integrations/index.ts b/src/modules/integrations/index.ts index 5814704..9db4c3d 100644 --- a/src/modules/integrations/index.ts +++ b/src/modules/integrations/index.ts @@ -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' diff --git a/src/modules/integrations/status.ts b/src/modules/integrations/status.ts index ec95710..ab3cff9 100644 --- a/src/modules/integrations/status.ts +++ b/src/modules/integrations/status.ts @@ -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): Promise { + const db = (payload as { db?: Partial }).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 { diff --git a/src/modules/seo/buildLlmsTxt.ts b/src/modules/seo/buildLlmsTxt.ts index 95ccd2f..fbfb9af 100644 --- a/src/modules/seo/buildLlmsTxt.ts +++ b/src/modules/seo/buildLlmsTxt.ts @@ -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, diff --git a/src/modules/seo/routeHandlers.ts b/src/modules/seo/routeHandlers.ts index 9803af9..ad5d865 100644 --- a/src/modules/seo/routeHandlers.ts +++ b/src/modules/seo/routeHandlers.ts @@ -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 @@ -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, diff --git a/src/modules/seo/siteIndex.ts b/src/modules/seo/siteIndex.ts index 41c2e07..50a4440 100644 --- a/src/modules/seo/siteIndex.ts +++ b/src/modules/seo/siteIndex.ts @@ -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 } diff --git a/src/modules/shared/accessAnswer.ts b/src/modules/shared/accessAnswer.ts new file mode 100644 index 0000000..285cc1c --- /dev/null +++ b/src/modules/shared/accessAnswer.ts @@ -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() + +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() +} diff --git a/test/accessAnswer.test.ts b/test/accessAnswer.test.ts new file mode 100644 index 0000000..99dc14b --- /dev/null +++ b/test/accessAnswer.test.ts @@ -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) + } +}) diff --git a/test/draftRelations.test.ts b/test/draftRelations.test.ts new file mode 100644 index 0000000..57b15a2 --- /dev/null +++ b/test/draftRelations.test.ts @@ -0,0 +1,105 @@ +/** + * Drafts as related documents (owner's decision Q5, 1.18.0): a block, a menu or a System pages link that points at a + * page never published no longer brings that page's title, slug and text into what the public helpers answer. + * `draftRelations: 'keep'` and a preview (`draft: true`) keep the old behaviour. + * Real database; SQLite by default, Postgres / MongoDB with IPAL_TEST_POSTGRES_URI / IPAL_TEST_MONGO_URI. + */ +import type { Payload } from 'payload' + +import { lexicalEditor } from '@payloadcms/richtext-lexical' +import os from 'os' +import path from 'path' +import { getPayload } from 'payload' +import { afterAll, beforeAll, describe, expect, test, vi } from 'vitest' + +import { withoutDraftRelations } from '../src/modules/content/draftRelations.js' +import { getArchiveEntries } from '../src/modules/content/getArchiveEntries.js' +import { resolveRoute } from '../src/modules/content/resolveRoute.js' +import { iapl } from '../src/plugin.js' +import { buildTestConfig } from './helpers.js' +import { testDatabase } from './http/db.js' + +vi.mock('server-only', () => ({})) + +describe('withoutDraftRelations', () => { + const draft = { id: 2, _status: 'draft', title: 'Secret' } + const live = { id: 1, _status: 'published', title: 'Live' } + + test('drops a draft related document: null alone, removed from a list, value null in a polymorphic one', () => { + const doc = { id: 9, _status: 'published', layout: [{ blockType: 'cards', items: [live, draft], one: draft, poly: { relationTo: 'pages', value: draft } }] } + expect(withoutDraftRelations(doc)).toEqual({ id: 9, _status: 'published', layout: [{ blockType: 'cards', items: [live], one: null, poly: { relationTo: 'pages', value: null } }] }) + }) + + test('the document itself, ids, uploads and documents without _status are left alone; nothing is mutated', () => { + const doc = { id: 3, _status: 'draft', image: { id: 5, url: '/m.png' }, page: 2, pages: [1, 2] } + expect(withoutDraftRelations(doc)).toBe(doc) + const nested = { a: { b: draft } } + const out = withoutDraftRelations(nested) + expect(out).toEqual({ a: { b: null } }) + expect(nested.a.b).toBe(draft) + }) +}) + +describe('the public helpers on a real database', () => { + let payload: Payload + beforeAll(async () => { + const config = buildTestConfig({ + collections: [ + { + slug: 'pages', + access: { read: () => true }, + fields: [ + { name: 'title', type: 'text' }, + { name: 'slug', type: 'text', localized: true }, + { name: 'related', type: 'relationship', relationTo: 'pages' }, + { name: 'list', type: 'relationship', hasMany: true, relationTo: 'pages' }, + { name: 'layout', type: 'blocks', blocks: [{ slug: 'link', fields: [{ name: 'page', type: 'relationship', relationTo: ['pages', 'posts'] }] }] }, + ], + versions: { drafts: true }, + }, + { slug: 'posts', fields: [{ name: 'title', type: 'text' }, { name: 'slug', type: 'text', localized: true }, { name: 'see', type: 'relationship', relationTo: 'pages' }], versions: { drafts: true } }, + { slug: 'media', fields: [], upload: { staticDir: path.join(os.tmpdir(), 'iapl-draft-relations') } }, + ], + db: testDatabase('draft_relations'), + editor: lexicalEditor(), + plugins: [iapl({ access: { authCollection: 'users' }, content: { collections: [{ slug: 'posts' }] }, i18n: { defaultLocale: 'pl', locales: [{ code: 'pl', label: 'Polski' }] }, mail: { relay: false }, pages: { slug: 'pages' }, twoFactor: false })], + secret: 'draft-relations-0123456789-0123456789', + telemetry: false, + }) + payload = await getPayload({ config }) + const secret = await payload.create({ collection: 'pages' as never, data: { slug: 'tajna', _status: 'draft', title: 'Secret price list' } as never, draft: true }) + const live = await payload.create({ collection: 'pages' as never, data: { slug: 'o-nas', _status: 'published', title: 'About' } as never }) + await payload.create({ + collection: 'pages' as never, + data: { slug: 'start', _status: 'published', layout: [{ blockType: 'link', page: { relationTo: 'pages', value: secret.id } }], list: [live.id, secret.id], related: secret.id, title: 'Start' } as never, + }) + await payload.create({ collection: 'posts' as never, data: { slug: 'wpis', _status: 'published', see: secret.id, title: 'Post' } as never }) + }, 120_000) + + afterAll(async () => { + await payload?.destroy?.() + }) + + const start = async (options: Record = {}) => (await resolveRoute({ locale: 'pl', payload, segments: ['start'], ...options }))?.doc as Record + + test('resolveRoute: the page answers without the draft it points at (single, list, polymorphic block)', async () => { + const doc = await start() + expect(doc.related).toBeNull() + expect((doc.list as { title: string }[]).map((p) => p.title)).toEqual(['About']) + expect((doc.layout as { page: { value: unknown } }[])[0].page.value).toBeNull() + expect(JSON.stringify(doc)).not.toContain('Secret price list') + }) + + test("draftRelations: 'keep' and a preview answer them as before", async () => { + for (const options of [{ draftRelations: 'keep' }, { draft: true }]) { + expect(JSON.stringify(await start(options))).toContain('Secret price list') + } + }) + + test('getArchiveEntries: an entry without the draft it points at; keep as before', async () => { + const hidden = await getArchiveEntries({ collection: 'posts', locale: 'pl', payload }) + expect((hidden.docs[0] as { see: unknown }).see).toBeNull() + const kept = await getArchiveEntries({ collection: 'posts', draftRelations: 'keep', locale: 'pl', payload }) + expect(JSON.stringify(kept.docs)).toContain('Secret price list') + }) +}) diff --git a/test/statusWrites.test.ts b/test/statusWrites.test.ts new file mode 100644 index 0000000..9ae9c3d --- /dev/null +++ b/test/statusWrites.test.ts @@ -0,0 +1,109 @@ +/** + * Plugin writes that do not carry an old copy of a settings global back (owner's decision Q3, 1.18.0). + * + * - The integration status (`emailStatus`, `turnstileStatus`) is written after an ANONYMOUS form submit or a mail + * send. Payload's `updateGlobal` reads the whole document, merges the change and writes the whole result: an + * admin's SMTP or Turnstile change saved in between was put back silently. The status is now written alone. + * - `addToCookieList` (cookie approval, review) read the cookie list, added a row and wrote the whole list: a row + * an editor saved in between was lost. It now checks the list again right before writing and starts over when + * it changed. + * + * The race is made exact by holding the plugin's read and letting the other save land in between. + * Real database; SQLite by default, Postgres / MongoDB with IPAL_TEST_POSTGRES_URI / IPAL_TEST_MONGO_URI. + */ +import type { Payload } from 'payload' + +import { lexicalEditor } from '@payloadcms/richtext-lexical' +import os from 'os' +import path from 'path' +import { getPayload } from 'payload' +import { afterAll, beforeAll, describe, expect, test, vi } from 'vitest' + +import { addToCookieList } from '../src/modules/consent/scanner/sync.js' +import { recordIntegrationStatus } from '../src/modules/integrations/status.js' +import { iapl } from '../src/plugin.js' +import { buildTestConfig } from './helpers.js' +import { testDatabase } from './http/db.js' + +vi.mock('server-only', () => ({})) + +let payload: Payload +const SI = 'site-integrations' +const si = async () => (await payload.findGlobal({ slug: SI as never })) as unknown as Record + +beforeAll(async () => { + const config = buildTestConfig({ + collections: [{ slug: 'media', fields: [], upload: { staticDir: path.join(os.tmpdir(), 'iapl-status-writes') } }], + db: testDatabase('status_writes'), + editor: lexicalEditor(), + plugins: [iapl({ access: { authCollection: 'users' }, cookieScanner: true, i18n: { defaultLocale: 'pl', locales: [{ code: 'pl', label: 'Polski' }, { code: 'en', label: 'English' }] }, mail: { relay: false }, twoFactor: false })], + secret: 'status-writes-0123456789-0123456789', + telemetry: false, + }) + payload = await getPayload({ config }) +}, 120_000) + +afterAll(async () => { + await payload?.destroy?.() +}) + +describe('the integration status is written alone', () => { + test("an admin's SMTP change saved while the status is written stays", async () => { + await payload.updateGlobal({ slug: SI as never, data: { smtpHost: 'old.example.com', smtpPassword: 'old-secret', smtpUser: 'u' } as never }) + // the copy any read-merge-write would hold: taken before the admin's save + const before = await payload.db.findGlobal({ slug: SI, req: {} as never }) + const real = payload.db.findGlobal.bind(payload.db) + let held = true + const spy = vi.spyOn(payload.db, 'findGlobal').mockImplementation(async (args) => { + if (args.slug === SI && held) { + held = false + // the admin's save lands while the status write is under way + await payload.updateGlobal({ slug: SI as never, data: { smtpHost: 'new.example.com', smtpPassword: 'new-secret' } as never }) + return before as never + } + return real(args) + }) + try { + await recordIntegrationStatus(payload, 'emailStatus', null, { code: 'smtp-auth', message: 'Login refused', state: 'degraded' }) + } finally { + spy.mockRestore() + } + const after = await si() + expect(after).toMatchObject({ smtpHost: 'new.example.com', smtpPassword: 'new-secret' }) + expect(after.emailStatus).toMatchObject({ code: 'smtp-auth', state: 'degraded' }) + }) + + test('the status write changes nothing else in the document', async () => { + await payload.updateGlobal({ slug: SI as never, data: { ga4MeasurementId: 'G-KEEP', smtpHost: 'keep.example.com', turnstileSiteKey: 'site-key' } as never }) + const { turnstileStatus: _t, updatedAt: _u, ...before } = await si() + await recordIntegrationStatus(payload, 'turnstileStatus', null, { code: 'bad-secret', state: 'degraded' }) + const { turnstileStatus, updatedAt: _u2, ...after } = await si() + expect(after).toEqual(before) + expect(turnstileStatus).toMatchObject({ code: 'bad-secret', state: 'degraded' }) + }) +}) + +describe('the cookie list keeps a row saved in between', () => { + test('an editor adds a row while the scanner adds its own: both rows stay', async () => { + await payload.updateGlobal({ slug: 'cookie-settings' as never, data: { cookies: [{ name: 'first', category: 'necessary' }] } as never, locale: 'pl' }) + const real = payload.findGlobal.bind(payload) + let held = true + const spy = vi.spyOn(payload, 'findGlobal').mockImplementation(async (args) => { + const result = await real(args as never) + if ((args as { slug: string }).slug === 'cookie-settings' && held) { + held = false + // the editor's save lands after the scanner read the list + const rows = ((await real({ slug: 'cookie-settings' as never, depth: 0, locale: 'pl' as never })) as { cookies?: object[] }).cookies ?? [] + await payload.updateGlobal({ slug: 'cookie-settings' as never, data: { cookies: [...rows, { name: 'editor_cookie', category: 'analytics' }] } as never, locale: 'pl' }) + } + return result as never + }) + try { + expect(await addToCookieList({ entry: { name: 'scanned_cookie', category: 'marketing' } as never, payload })).toBe('added') + } finally { + spy.mockRestore() + } + const names = (((await payload.findGlobal({ slug: 'cookie-settings' as never, depth: 0, locale: 'pl' as never })) as { cookies?: { name?: string }[] }).cookies ?? []).map((r) => r.name) + expect(names).toEqual(expect.arrayContaining(['first', 'editor_cookie', 'scanned_cookie'])) + }) +}) From 3821174be4ba4282963f62c2eeb039c96cde496e Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?Rados=C5=82aw=20Smoli=C5=84ski?= Date: Tue, 1 Dec 2026 12:08:00 +0100 Subject: [PATCH 13/15] Cookie button never moves; the footer gets room under its last row while the button is shown MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit Owner, 2026-12-01, after the review of fb92b35: option 3, "miejsce pod stopką" — the button stays in its corner at all times and covers nothing; the page gets room under its last row. - Removed: the step up at the end of the page (`clear`, COOKIE_BUTTON_CLEAR, stepAbove; never released). - New: while the button is shown, the last footer (`reserve`, COOKIE_BUTTON_RESERVE; no footer: ) gets bottom padding, measured: button height + offset + safe area + 8 px, minus what is already free under the lowest text or control in the button's column. The footer's own padding counts (no double space); an empty corner gets nothing. Not before a decision, not while the banner is open, gone with the button; `reserve={false}` turns it off, `--ipal-cookie-button-space` on the footer sets the amount (0 = none, per breakpoint). - No layout shift: on a static page renders an inline script that makes the room before the first paint for a visitor who already decided — in a constructed style sheet, so the server's markup is untouched and React hydrates without a mismatch; after hydration the same function moves it onto the element. - consentDecidedScript: the shared start of the banner's and the button's pre-paint scripts. - avoid={COOKIE_BUTTON_AVOID} is still the placement before 1.17.2 (no room then). Tests: test/cookieButtonPlacement.test.ts rewritten (24); reference e2e on desktop, 390 px and 360 px phones, light and dark, five pages: the corner at every scroll position, nothing under the button at the very end, every footer link clickable, layout shift < 0.001, the room before hydration. Docs: consent.md, AGENT.md, skills, PROGRAMISTA item 83, changelog draft 1.17.2. Co-Authored-By: Claude Fable 5.2 --- docs/CHANGELOG.md | 31 +- docs/agent/AGENT.md | 2 +- docs/agent/skills/iapl-consent-check/SKILL.md | 12 +- .../skills/iapl-reference/resources/api.md | 5 +- docs/agent/skills/iapl-upgrade/SKILL.md | 14 +- docs/consent.md | 45 +- docs/dev/PROGRAMISTA.md | 2 +- .../skills/iapl-consent-check/SKILL.md | 12 +- .../skills/iapl-reference/resources/api.md | 5 +- .../.agents/skills/iapl-upgrade/SKILL.md | 14 +- reference/e2e/smoke.spec.ts | 172 +++++--- src/exports/client.ts | 7 +- src/index.ts | 1 + src/modules/consent/CookieButton.tsx | 152 +++---- src/modules/consent/client.ts | 4 +- src/modules/consent/cookieButtonSpace.ts | 171 ++++++++ src/modules/consent/firstPaint.ts | 17 +- src/modules/consent/index.ts | 2 +- test/consentFirstPaint.test.ts | 8 +- test/cookieButtonPlacement.test.ts | 408 ++++++++++++------ 20 files changed, 763 insertions(+), 321 deletions(-) create mode 100644 src/modules/consent/cookieButtonSpace.ts diff --git a/docs/CHANGELOG.md b/docs/CHANGELOG.md index 547660e..17b1c94 100644 --- a/docs/CHANGELOG.md +++ b/docs/CHANGELOG.md @@ -12,21 +12,26 @@ once there are more than 20. ## 1.17.2 — (draft, not released) ### Changed -- **What an existing site's visitors see: the "cookie settings" button stays in the bottom corner of the window** - ([consent.md → Where the cookie button sits](./consent.md#where-the-cookie-button-sits-1172)). Until now it 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. Only at the very end of the page, where it would keep a footer link or a button covered with no way to - scroll past, it steps up just above it (on the reference site: 71 px on a phone, nothing on desktop). No layout - shift, 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.** The placement before: - `` (on `SiteProviders`: `cookieButton={…}`). A site that already passes - `avoid` (a selector, or `false` = never move) or `className` keeps its behaviour. A project e2e test that expects the - button above the footer needs an update. +- **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: ``; an amount of + your own: `--ipal-cookie-button-space` on the footer (`0` = none, also per breakpoint); the placement before: + `` (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. ### Added -- `CookieButton` prop `clear` (selector of controls freed at the end of the page; `false` = off), `COOKIE_BUTTON_CLEAR`, - `stepAbove` (`/client`). +- `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`. ## 1.17.1 — security fixes from the IAWL review; the panel's sign-in look; the sending method is chosen diff --git a/docs/agent/AGENT.md b/docs/agent/AGENT.md index 54746f1..b26d11a 100644 --- a/docs/agent/AGENT.md +++ b/docs/agent/AGENT.md @@ -1161,7 +1161,7 @@ project → **plugin gap**, not a copy. |---|---|---| | Banner, settings, cookie button | `}>`, `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 in or above the footer; at the page end it steps above a link it would keep covered. `CookieButton side` / `clear` / `avoid` (`avoid={COOKIE_BUTTON_AVOID}` = above the footer, as before 1.17.2; `false` = never move), tokens `--ipal-cookie-button-offset` / `-inset`. Do not render the button inside the footer or write a scroll handler for it | consent.md → "Where the cookie button sits" | +| 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 \| 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 | `` — do not build your own window or cookie list | consent.md → "Large window with details" | | A consent-dependent script | `ConsentScript` | consent.md | diff --git a/docs/agent/skills/iapl-consent-check/SKILL.md b/docs/agent/skills/iapl-consent-check/SKILL.md index b7d462c..71dcc81 100644 --- a/docs/agent/skills/iapl-consent-check/SKILL.md +++ b/docs/agent/skills/iapl-consent-check/SKILL.md @@ -56,11 +56,13 @@ before analytics or marketing consent — check the project's choice in "Project 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 — the button is in the bottom corner of the window at the - top, in the middle and with the footer in view (it must not ride up on the footer); scrolled to the very end it - lies on no link or button (it may step up a little); Tab reaches it and Enter reopens the banner. A footer whose - corner is all links: `side="right"` or a larger `--ipal-cookie-button-offset`. A project scroll handler or a - button rendered inside the footer → remove (AGENT.md §7). + 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. diff --git a/docs/agent/skills/iapl-reference/resources/api.md b/docs/agent/skills/iapl-reference/resources/api.md index d31d116..caafe9e 100644 --- a/docs/agent/skills/iapl-reference/resources/api.md +++ b/docs/agent/skills/iapl-reference/resources/api.md @@ -165,9 +165,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. Fixed in the bottom corner of the window on every page (1.17.2: it no longer climbs above the footer); at the very end of the page it steps just above a link or button it would keep covered. Props `className`, `side` (`'left' \| 'right'`), `clear` (selector of controls to free at the page end, default `COOKIE_BUTTON_CLEAR`; `false`), `avoid` (placement before 1.17.2: selector it lifts above — `COOKIE_BUTTON_AVOID` = footer; `false` = never move). Tokens `--ipal-cookie-button-offset`, `--ipal-cookie-button-inset`. Type `CookieButtonProps`. | +| `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 (``); pixels the footer covers at the bottom of the screen (how far the button moves up then) | -| `COOKIE_BUTTON_CLEAR`, `stepAbove(button, obstacles, max)` | `@intecion/ipal-kit/client` | Default selector of controls the cookie button frees at the end of the page; how far a box must move up to lie on none of the given boxes (0 = stays, also when no free place within `max`) | +| `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`). | diff --git a/docs/agent/skills/iapl-upgrade/SKILL.md b/docs/agent/skills/iapl-upgrade/SKILL.md index 67cc71b..2a6920c 100644 --- a/docs/agent/skills/iapl-upgrade/SKILL.md +++ b/docs/agent/skills/iapl-upgrade/SKILL.md @@ -26,12 +26,14 @@ the MANDATORY SET (GEO: llms-full, Markdown, MCP; R2; Turnstile through not an extra. Skip one only with a client decision in `AGENTS.md` (`iapl-audit-skip:`). **→ 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 no longer moves up -above the footer. Look at the end of a page on a phone: the button must lie on no link (it steps up by itself; a -footer corner full of links → `side="right"` or a larger `--ipal-cookie-button-offset`). The placement before: -`cookieButton={}` on `SiteProviders`. A project that passes `avoid` (a -selector or `false`) or `className` keeps what it had. A project e2e that expects the button above the footer: -update it. +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={}` 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`). diff --git a/docs/consent.md b/docs/consent.md index 31b2da0..c87235e 100644 --- a/docs/consent.md +++ b/docs/consent.md @@ -116,22 +116,37 @@ takes `locale` and optional `labels`; defaults: `COOKIE_TABLE_LABELS` (`@intecio ### 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. It is a child of `` (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). +position, on desktop and phone — and it **never moves**. It is a child of `` (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). -One exception keeps every control reachable: **at the very end of the page**, where a visitor cannot scroll a -covered link out from under a fixed button, the button steps up just far enough to lie on no link, button or form -field (`stepAbove`; 8 px gap; never more than half the window, otherwise it stays in the corner). It then usually -rests on plain text of the footer (the copyright line). Anywhere above the end of the page it stays in the corner: a -covered control is one scroll away. The step is a `transform` — no layout shift. +**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 → `` | | Prop | Default | What it does | |---|---|---| | `side` | `'left'` | corner: `'left'` or `'right'` | -| `clear` | `COOKIE_BUTTON_CLEAR` (links, buttons, form fields) | CSS selector of controls the button frees at the end of the page; `false` = stay in the corner whatever is under it | -| `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`). `false` = never move at all (also turns `clear` off) | -| `className` | — | replaces the default classes; position is then yours too (the `clear` step applies only while your classes keep it `position: fixed`) | +| `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 @@ -139,8 +154,10 @@ Position tokens: `--ipal-cookie-button-offset` (from the bottom, default `1rem`) Hidden while the banner is showing. Keyboard: a `