From c56f0d41b85dd13e5b0a95d168735c33aab4c744 Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?Rados=C5=82aw=20Smoli=C5=84ski?= Date: Tue, 24 Nov 2026 01:46:25 +0100 Subject: [PATCH] Security review round 2: no exception by name, staff list fails closed, verify limit R2-1: the sweep skipped every collection whose slug starts with payload-, so a plugin's payload-... collection added after ipalKit was never guarded. There is no exception by name or prefix now: every collection and global is guarded, Payload's own included, and the job queue's run / queue / cancel rules too. R2-2: role predicates called without a source fail closed where the staff collections are not known (browser bundle, middleware, edge): nobody is staff. They accept req.payload, a config (also the client config) or { staffCollections } as the source. R2-3: the staff list is filed per config / Payload instance; a call without a source gets only what every config in the process calls staff. R2-4: payload.config is watched on the instance, so a config swapped in by a dev reload is guarded before any request or Local API call. R2-5: verify attempts are limited per account (default 5 in 10 minutes, twoFactor.verifyLimit), counted in memory, never skipped. R2-6: a user object without collection owes the second factor; endpoints the 2FA package may add on collections or globals are guarded too; a warning names staff collections that 2FA does not cover; docs state what is not covered, fix the one-argument examples and the doctor example. HTTP tests for each on payload-2fa beta.7, run on SQLite, Postgres and MongoDB (test adapter added). Co-Authored-By: Claude Fable 5.2 --- docs/CHANGELOG.md | 14 +- docs/access.md | 32 ++- docs/agent/AGENT.md | 9 +- docs/agent/skills/ipal-debug/SKILL.md | 2 + docs/agent/skills/ipal-reference/SKILL.md | 3 +- .../skills/ipal-reference/resources/api.md | 10 +- docs/agent/skills/ipal-setup/SKILL.md | 1 + docs/agent/skills/ipal-upgrade/SKILL.md | 5 +- docs/doctor.md | 2 +- docs/security.md | 37 +++- package.json | 1 + pnpm-lock.yaml | 203 ++++++++++++++++++ reference/.agents/skills/ipal-debug/SKILL.md | 2 + .../.agents/skills/ipal-reference/SKILL.md | 3 +- .../skills/ipal-reference/resources/api.md | 10 +- reference/.agents/skills/ipal-setup/SKILL.md | 1 + .../.agents/skills/ipal-upgrade/SKILL.md | 5 +- src/index.ts | 1 + src/modules/access/index.ts | 2 +- src/modules/access/predicates.ts | 83 +++++-- src/modules/admin-i18n/texts/index.ts | 5 +- src/modules/admin-i18n/texts/security.ts | 11 + src/modules/doctor/status.ts | 2 +- src/modules/security/totp/secondFactor.ts | 150 +++++++++++-- src/modules/security/totp/verifyLimit.ts | 64 ++++++ src/plugin.ts | 70 ++++-- src/types.ts | 9 + test/access.test.ts | 42 +++- test/http/db.ts | 11 +- test/plugin.test.ts | 2 +- test/secondFactorGuard.test.ts | 86 +++++++- test/securityHttp.test.ts | 88 +++++++- test/setup.ts | 12 ++ vitest.config.js | 1 + 34 files changed, 871 insertions(+), 108 deletions(-) create mode 100644 src/modules/admin-i18n/texts/security.ts create mode 100644 src/modules/security/totp/verifyLimit.ts create mode 100644 test/setup.ts diff --git a/docs/CHANGELOG.md b/docs/CHANGELOG.md index d0ab4c2..a0806cf 100644 --- a/docs/CHANGELOG.md +++ b/docs/CHANGELOG.md @@ -38,6 +38,10 @@ once there are more than 20. collection on Postgres or SQLite** (MongoDB ids do not repeat across collections). ipalKit now guards every endpoint the package registers; reset and remove also need the second factor ([security.md](./security.md) "The 2FA package's endpoints"). +- **The 2FA code can no longer be guessed.** The package never counted verify attempts. Now at most 5 per account + in 10 minutes (`twoFactor.verifyLimit`); further ones get `429`. +- **Every collection and global is covered, whatever its name** — Payload's own (`payload-preferences`, + `payload-jobs`, …), a plugin's `payload-…` collection, the job queue's `run / queue / cancel` rules. - **Not changed, and important:** an account that has **not set TOTP up yet** is an ordinary logged-in account — its password alone opens everything its role allows. Set 2FA up right after an account is created; `ipal-doctor --url` reports accounts without it. @@ -45,8 +49,9 @@ once there are more than 20. ### Added - `access.staffCollections`: name further auth collections whose accounts are staff. - `adminOrSelfIn(slug)`, `staffCollectionSlugs(payload)`, `secondFactorPassed(req)`, `requireSecondFactor(access)` - for the project's own access functions and endpoints. `isAdmin`, `isEditor` and `hasMinimumRole` take - `req.payload` as an optional last argument. + for the project's own access functions and endpoints. `isAdmin`, `isEditor` and `hasMinimumRole` take an optional + last argument that says which collections are staff: `req.payload`, a config, or `{ staffCollections: [...] }`. +- `twoFactor.verifyLimit: false | { max, windowMinutes }`. - Per-entity opt-out from the second factor: `custom.ipal.secondFactor: false | { read: false }` on a collection or global; the package's `custom.totp.disableAccessWrapper` is honoured as before. - `twoFactor.guard: false`: ipal-kit's second-factor check off everywhere, the package's wrapper only (not recommended). @@ -71,6 +76,11 @@ once there are more than 20. longer count for accounts of other collections: a rule that used `isAdmin` / `adminOnly` for them needs its own check of `req.user.collection`. On Postgres or SQLite also ask every staff member to confirm their authenticator still works; if it does not, reset that account's 2FA and set it up again. +- **`isAdmin` / `isEditor` / `hasMinimumRole` in a client component or in `proxy.ts` / middleware** return `false` + unless they are told which collections are staff: `isAdmin(user, config)` with the config from `useConfig()`, or + `isAdmin(user, { staffCollections: ['users'] })`. On the server (`isAdmin(req.user)` in hooks, endpoints, access + functions) nothing changes; `isAdmin(req.user, req.payload)` is the explicit form. +- **A second staff collection (`access.staffCollections`) is not covered by 2FA** — the log says so at start. - **Own code that reads a plugin collection or global with `overrideAccess: false`** must pass a `user` from `payload.auth({ headers })`; a user fetched by id and passed by hand is refused when it has TOTP set up, and its role does not count without `collection`. Own diff --git a/docs/access.md b/docs/access.md index 03c2a95..a3516b7 100644 --- a/docs/access.md +++ b/docs/access.md @@ -98,7 +98,12 @@ What follows: - **A second staff collection** (e.g. `partners` who edit content): name it in `access.staffCollections`. That is the one switch that makes its roles count. Without a `roles` field every partner passes every staff check, admin ones included; to tell them apart add the field: - `fields: [buildRolesField('editor')]` in that collection. + `fields: [buildRolesField('editor')]` in that collection. **2FA covers one collection** (`twoFactor.collectionSlug`, + by default the panel's): accounts of a further staff collection are staff with a password alone. ipalKit says + so in the log at start (`[ipal] 2FA covers "users" only…`); name such a collection only when that is acceptable. +- **Payload's own default** for a collection or global without `access` is "any logged-in account" — an account + of a visitor collection included. In a project with a second auth collection give every collection and global + explicit `access` (`adminOrEditor`, `requireRole(…)`, …). - **A visitor collection that should reach one thing** (e.g. customers read their own form submissions): do not make it staff. Write that one rule yourself — `forms.formSubmissionOverrides.access.read`, `globalOverrides`, `collectionOverrides` of the module — and check `req.user.collection` in it. @@ -124,12 +129,25 @@ userMeetsRole(req, 'admin') // the plugin's staff check: s staffCollectionSlugs(req.payload) // ['users', …] ``` -They take a loosely typed user (like `req.user`) and read `roles` defensively. The last argument (`req.payload`) -tells them which collections are staff. Without it — `isAdmin(req.user)` — they use the staff collections of -the config `ipalKit` built in this process, so existing calls in hooks and endpoints are covered too. Only in a -browser bundle, where there is no config, the roles are taken as they are: fine for showing or hiding a -button, never a security check. `isAdmin` and the others do **not** check the second factor; `userMeetsRole` -and every `access` function in the config do. +They take a loosely typed user (like `req.user`) and read `roles` defensively. The last argument tells them +which collections are staff: + +| Where you call it | Pass | Without it | +|---|---|---| +| access functions, hooks, endpoints (server, the config is loaded) | `req.payload` | works: the staff collections of the config `ipalKit` built in this process. With two different configs in one process, only collections that are staff in **both** count — pass `req.payload` to get that config's own answer | +| client components | the config from `useConfig()` (it has `admin.user`), or `{ staffCollections: ['users', …] }` | **always `false`** — the browser bundle has no config | +| Next middleware / `proxy.ts`, the edge runtime | `{ staffCollections: ['users'] }` | **always `false`** — the config is not loaded there | + +```tsx +'use client' +const { config } = useConfig() +const { user } = useAuth() +if (isAdmin(user, config)) { /* show the button — a hint only, the server decides */ } +``` + +They fail closed: where the staff collections are not known, nobody is staff, and an account without +`collection` is nobody. `isAdmin` and the others do **not** check the second factor; `userMeetsRole` and every +`access` function in the config do. ## Ready access functions diff --git a/docs/agent/AGENT.md b/docs/agent/AGENT.md index e3b2025..8fbe7ea 100644 --- a/docs/agent/AGENT.md +++ b/docs/agent/AGENT.md @@ -591,9 +591,11 @@ for visitors. Then, all four: `req.user.collection`; never add the collection to `access.staffCollections` to "make something work". `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. Never let a sign-up write a field that grants rights (`roles`, `isAdmin`, …): give such a field +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. +5. Never let a sign-up write a field that grants rights (`roles`, `isAdmin`, …): give such a field `access: { create: adminOnlyField, update: adminOnlyField }`. -5. Check: log in as such an account (`POST /api/customers/login`), then `GET /api/globals/site-integrations`, +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`. @@ -1057,7 +1059,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: `ipalKit({ revalidatePath })`; your own globals: `buildGlobalRevalidateHook({ revalidatePath })` | hooks.md | | Change a plugin global (access, hooks, fields) | `ipalKit({ globalOverrides })` | access.md | -| Roles and access | `adminOnly`, `adminOrEditor`, `adminOrSelf`, `adminOrSelfIn(slug)` (several auth collections), `authenticated`, `requireRole`, `hasMinimumRole` (+ `…Field`); staff checks: `userMeetsRole(req, role)`, `isAdmin(req.user, req.payload)` (roles count only for accounts of a staff collection), `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`); 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()`, 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** @@ -1164,6 +1166,7 @@ add missing hosts with flags / `extra`; (3) change `mode` to `'enforce'` in both | First registered account = admin | `access.firstUserAdmin: false` | `buildRolesField(defaultRole, { firstUserAdmin })` | | 2FA on the panel's login collection, mismatch = startup error; redirect to the 2FA screens by `TotpRedirectProvider` | `twoFactor: false` (discouraged) | `twoFactor.collectionSlug`, `allowCollectionMismatch: true`, `twoFactor.provider` (own component, or `false` for the package's) | | 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 verify attempts per account in 10 minutes (`POST /api/verify-totp` → `429`) | `twoFactor.verifyLimit: false` | `verifyLimit: { max, windowMinutes }` | | The 2FA package's endpoints (`/api/setup-totp`, `verify-totp`, `remove-totp`, `admin/*`) answer accounts of the 2FA collection only; reset and remove need the second factor | — (always on with 2FA) | `adminManageAccess` through the wrapped factory (security.md "Resetting 2FA") | | 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`) | diff --git a/docs/agent/skills/ipal-debug/SKILL.md b/docs/agent/skills/ipal-debug/SKILL.md index 1b5debb..888a9e0 100644 --- a/docs/agent/skills/ipal-debug/SKILL.md +++ b/docs/agent/skills/ipal-debug/SKILL.md @@ -34,6 +34,8 @@ through this procedure. Ask only when you are missing something you cannot get y ### Build / TypeScript | Symptom | Cause | Fix | |---|---|---| +| the 2FA code screen answers "Too many codes were tried…" (`429` from `/api/verify-totp`) | more than 5 verify attempts for that account in 10 minutes (`twoFactor.verifyLimit`); repeated lines `[ipal] 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(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()`; in middleware `isAdmin(user, { staffCollections: ['users'] })` | | startup: `[ipal] twoFactor: the injected 2FA plugin did not add the totpSecret field / hasTotp field / totp auth strategy` | the installed `@clocklimited/payload-2fa` is not a version ipal-kit's second-factor check recognises (tested: 3.0.0-beta.1 and beta.7), or a custom factory was injected | install a supported version; stop-gap only: `twoFactor.guard: false` (the plugin's own data is then not covered by 2FA — security.md) | | own route or script gets `403` / "not allowed" on `form-submissions`, `forms`, a settings global with `overrideAccess: false`, although the user is an admin | the `user` was fetched by id and passed by hand: it does not carry how the account logged in, so the second-factor check refuses it | take the user from `payload.auth({ headers })` (it sets `collection` and how the account logged in), or (server-only code that needs no access check) leave `overrideAccess` at its default; a hand-built user needs at least `collection: 'users'` for its role to count | | an account of a second auth collection (`customers`) gets `403` from a settings global, submissions, `/api/ipal/*`, `/api/setup-totp`, or `isAdmin` / `adminOnly` say no although it has `roles: ['admin']`, after an upgrade | by design since the release after 1.16.3: roles and staff checks count only for accounts of a staff collection | write the one rule it needs (`formSubmissionOverrides`, `globalOverrides`, `collectionOverrides`); a second STAFF collection: `access.staffCollections` (access.md "Who is staff") | diff --git a/docs/agent/skills/ipal-reference/SKILL.md b/docs/agent/skills/ipal-reference/SKILL.md index e517084..f29bf72 100644 --- a/docs/agent/skills/ipal-reference/SKILL.md +++ b/docs/agent/skills/ipal-reference/SKILL.md @@ -30,7 +30,7 @@ description: Complete map of everything @intecion/ipal-kit provides — every ip | `access.defaultRole` | `'user'` | `defaultValue` of the `roles` field | `'editor'` / `'admin'` | | `access.authAccess` | `{ create: adminOnly, delete: adminOnly, read: adminOrSelfIn(slug), unlock: adminOnly, update: adminOrSelfIn(slug) }` | access of the auth collection the plugin **injects** (Payload's default lets any logged-in account edit or delete every other account) | your keys win, e.g. `{ read: authenticated }`; your own collection with that slug wins whole (give it `adminOrSelf` / `adminOnly` yourself) | | `access.firstUserAdmin` | `true` | the account made on Payload's "Create first user" screen (`/first-register` on an empty collection) gets `roles: ['admin']`; an open sign-up still gets `defaultRole` | `false` = that account gets what was submitted | -| `access.staffCollections` | `[]` | more auth collections whose accounts are staff, besides the panel's login collection (`admin.user`) and `access.authCollection`; roles count **only** for accounts of a staff collection (every predicate and access function); without a `roles` field there, every such account passes every staff check | add `buildRolesField()` to that collection to tell roles apart; a visitor collection (`customers`) is never listed here | +| `access.staffCollections` | `[]` | more auth collections whose accounts are staff, besides the panel's login collection (`admin.user`) and `access.authCollection`; roles count **only** for accounts of a staff collection (every predicate and access function); such accounts are **not** covered by 2FA (one collection only — warning in the log at start); without a `roles` field there, every such account passes every staff check | add `buildRolesField()` to that collection to tell roles apart; a visitor collection (`customers`) is never listed here | | `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 `[ipal] twoFactor.issuer is required` | | `twoFactor.issuer` | — (required) | name in the authenticator app | — | @@ -39,6 +39,7 @@ description: Complete map of everything @intecion/ipal-kit provides — every ip | `twoFactor.provider` | `'@intecion/ipal-kit/admin#TotpRedirectProvider'` | admin provider that sends users to `setup-totp` / `verify-totp` (path read in the browser); replaces the package's header-based one | own component path / `{ path, clientProps, serverProps }` (gets clientProps `forceSetup`); `false` keeps the package's (needs `x-pathname` on `/admin`, else `setup-totp?back=null` loops) | | `twoFactor.texts` | ipal-kit's en/pl texts (`TOTP_TEXTS`) over the package's; 2FA screens titled "Two-step verification" / "Weryfikacja dwuetapowa" (site's language) | `false` = the package's texts; one text: `i18n.translations..totpPlugin.` (security.md) | | `twoFactor.guard` | on | ipal-kit's own second-factor check on every collection and global (also the plugin's own and those of plugins listed after ipalKit) and in `userMeetsRole`; startup fails with `[ipal] twoFactor: the injected 2FA plugin did not add …` when the 2FA package lacks the `totp` strategy / `hasTotp` / `totpSecret` | per entity: `custom.ipal.secondFactor: false` / `{ read: false }` or the package's `custom.totp.disableAccessWrapper.`; `false` = the package's wrapper only (the plugin's own data then opens to a password without the code; not recommended). The package's endpoints stay limited to accounts of the 2FA collection either way | +| `twoFactor.verifyLimit` | `{ max: 5, windowMinutes: 10 }` | attempts per account on `POST /api/verify-totp` (the 2FA package counts none): the sixth in the window, right or wrong, gets `429` + `Retry-After`; in memory per instance | `{ max, windowMinutes }`; `false` = no limit | | `twoFactor.allowCollectionMismatch` | `false` | allows `collectionSlug` ≠ `admin.user` (panel users of the other collection then skip 2FA) | `true` only when you protect a second auth collection on purpose | | `whiteLabel` | none | `admin.components.graphics.Logo/Icon` (`AdminLogo`/`AdminIcon`) from Site settings + vendor credit | omit / `false`; `true` = defaults | | `whiteLabel.settingsSlug` | `'site-settings'` | global it reads the logo/name from | — | diff --git a/docs/agent/skills/ipal-reference/resources/api.md b/docs/agent/skills/ipal-reference/resources/api.md index 16bdff6..2054e71 100644 --- a/docs/agent/skills/ipal-reference/resources/api.md +++ b/docs/agent/skills/ipal-reference/resources/api.md @@ -59,16 +59,16 @@ Admin panel components from `@intecion/ipal-kit/admin` — the project does NOT | `adminOnlyField` | `@intecion/ipal-kit` | `FieldAccess` (boolean only): field for admin only. In `field.access.read/update`. | | `adminOrEditorField` | `@intecion/ipal-kit` | `FieldAccess`: field for editor or admin. | | `requireRoleField(minimum)` | `@intecion/ipal-kit` | `FieldAccess` factory: at least the given role. | -| `hasMinimumRole(user, minimum, payload?)` | `@intecion/ipal-kit` | Predicate → `boolean`: the user is an account of a **staff collection** and has a role ≥ `minimum` (reads `user.roles` and `user.collection` safely). A role on an account of another auth collection never counts. Pass `req.payload` where you have it; without it the staff collections of the config ipalKit built in this process are used (in a browser bundle, where there is none, the roles are taken as they are — UI only). Does not check the second factor. | -| `isAdmin(user, payload?)` | `@intecion/ipal-kit` | Predicate → `boolean`: staff account with the `admin` role (see `hasMinimumRole`). In hooks and endpoints: `isAdmin(req.user, req.payload)`. | -| `isEditor(user, payload?)` | `@intecion/ipal-kit` | Predicate → `boolean`: staff account with `editor` or higher. | +| `hasMinimumRole(user, minimum, source?)` | `@intecion/ipal-kit` | Predicate → `boolean`: the user is an account of a **staff collection** and has a role ≥ `minimum` (reads `user.roles` and `user.collection` safely). A role on an account of another auth collection never counts. `source` says which collections are staff: `req.payload` on the server, the config from `useConfig()` in a client component, or `{ staffCollections: ['users'] }` (middleware). Without it: the staff collections of the config ipalKit built in this process (two different configs: only what both call staff) — and **`false` where there is none** (browser bundle, middleware, edge). Does not check the second factor. | +| `isAdmin(user, source?)` | `@intecion/ipal-kit` | Predicate → `boolean`: staff account with the `admin` role (see `hasMinimumRole`). In hooks and endpoints: `isAdmin(req.user, req.payload)`; in a client component: `isAdmin(user, config)`. | +| `isEditor(user, source?)` | `@intecion/ipal-kit` | Predicate → `boolean`: staff account with `editor` or higher. | | `userMeetsRole(req, minimum)` | `@intecion/ipal-kit` | Predicate → `boolean` with `req` (`{ payload, user }`), in this order: the account belongs to a **staff collection** (`admin.user`, `access.authCollection`, `access.staffCollections`); with 2FA on it has passed the second factor (`secondFactorPassed`); it has a role ≥ `minimum`, **or** its collection has no `roles` field (the project omitted `access`). An account of any other auth collection never passes, whatever fields it has. The plugin's staff features (Site integrations, settings globals, form submissions, consent records, stats, cookie scanner, the e-mail test) use it; use it in your own endpoints. | -| `staffCollectionSlugs(payload)` | `@intecion/ipal-kit` | `string[]`: the staff collections — `admin.user`, `access.authCollection` and `access.staffCollections`. Roles and staff checks count only for accounts of these. | +| `staffCollectionSlugs(source?)` | `@intecion/ipal-kit` | `string[]`: the staff collections — `admin.user`, `access.authCollection` and `access.staffCollections` — from `req.payload`, a config or `{ staffCollections }`; without an argument what the configs built in this process agree on (`[]` when there is none). Roles and staff checks count only for accounts of these. | | `ROLE_HIERARCHY` | `@intecion/ipal-kit` | Constant `['user', 'editor', 'admin']` (lowest first) — a higher role meets the requirements of a lower one. The plugin injects the `roles` field into the auth collection (`access.authCollection`). | | `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:** `Role` (`'user' \| 'editor' \| 'admin'`), `AccessOption` (the plugin's `access` option: `authCollection`, `defaultRole`, `authAccess`, `firstUserAdmin`, `staffCollections`). +**Types:** `VerifyLimitOptions` (`twoFactor.verifyLimit`: `{ max?, windowMinutes? }`), `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/docs/agent/skills/ipal-setup/SKILL.md b/docs/agent/skills/ipal-setup/SKILL.md index 7164c21..87f60cb 100644 --- a/docs/agent/skills/ipal-setup/SKILL.md +++ b/docs/agent/skills/ipal-setup/SKILL.md @@ -224,6 +224,7 @@ the panel shows Site settings, Site integrations, Cookies, Form messages, the Fo `[ipal] twoFactor…` unless `allowCollectionMismatch: true`. The second factor covers every collection and global (the plugin's own, and those of plugins listed after `ipalKit`) and the plugin's endpoints; guard your own endpoints with `secondFactorPassed(req)` or `userMeetsRole(req, role)` (security.md "What the second factor covers"). + Verify attempts: 5 per account in 10 minutes (`twoFactor.verifyLimit`). **Set 2FA up right after creating an account** (log in as it, scan the code): until then its password alone opens everything its role allows. One entity reachable without the code: `custom.ipal.secondFactor`. - A second auth collection (`customers`, a client zone): set `admin: { user: 'users' }` in `buildConfig`; its diff --git a/docs/agent/skills/ipal-upgrade/SKILL.md b/docs/agent/skills/ipal-upgrade/SKILL.md index f74e1a0..0f6a6da 100644 --- a/docs/agent/skills/ipal-upgrade/SKILL.md +++ b/docs/agent/skills/ipal-upgrade/SKILL.md @@ -342,7 +342,10 @@ for every site:** `consent-records`, `stats-visits`, `cookie-review`, the settings globals) must pass the `user` from `payload.auth({ headers })`; a user object built by hand needs `collection: ''` for its role to count. Own endpoints that check `req.user`: add `secondFactorPassed(req)` or use `userMeetsRole(req, role)`. - `isAdmin(req.user)` keeps working; prefer `isAdmin(req.user, req.payload)`. + `isAdmin(req.user)` keeps working on the server; prefer `isAdmin(req.user, req.payload)`. + `grep -rnE "isAdmin\(|isEditor\(|hasMinimumRole\(" src` — a call in a **client component** or in `proxy.ts` / + middleware now returns `false` without a source: `isAdmin(user, config)` (`useConfig()`), or + `isAdmin(user, { staffCollections: ['users'] })`. 4. `pnpm exec ipal-doctor --url ` (with the doctor token) → accounts without 2FA must be 0. An account that has not set TOTP up opens everything with its password alone: have its owner set it up now, or remove it. 5. Tell the owner what the CHANGELOG entry says under "Requires project changes" and agree on it: new SMTP diff --git a/docs/doctor.md b/docs/doctor.md index dda48f0..1b4fa4c 100644 --- a/docs/doctor.md +++ b/docs/doctor.md @@ -69,7 +69,7 @@ returns counts only — never names, e-mails or values: { "node": "v22.20.0", "pendingCookies": 0, "plugin": "1.15.0", "usersWithout2fa": 0 } ``` -Turn off: `ipalKit({ doctor: false })`. Adapt: `ipalKit({ doctor: { tokenVar: 'MY_TOKEN', access: ({ req }) => … } })` +Turn off: `ipalKit({ doctor: false })`. Adapt: `ipalKit({ doctor: { tokenVar: 'MY_TOKEN', access: ({ req }) => isAdmin(req.user, req.payload) } })` (a logged-in staff admin may read it too; the second factor is checked for you — never test `req.user.roles` by hand, an account of another collection can carry the same value) (`access` lets a logged-in admin read it without the token). Building blocks: `buildDoctorEndpoint`, `collectDoctorStatus` from `@intecion/ipal-kit/doctor`. diff --git a/docs/security.md b/docs/security.md index 7d4dcae..4407e0b 100644 --- a/docs/security.md +++ b/docs/security.md @@ -404,13 +404,21 @@ therefore read and changed them over the API.** Since the release after 1.16.3 i |---|---| | every collection and global in the config when ipalKit finishes | `access` wrapped with `requireSecondFactor` | | collections and globals added by plugins listed **after** ipalKit | wrapped in ipalKit's `onInit`; the log line `[ipal] 2FA also enforced on entities added after ipalKit: …` names them | -| the same after a dev hot reload, or when Payload runs with `disableOnInit` | an auth strategy that authenticates nobody (`ipal-second-factor-guard` on the 2FA collection) runs at the start of every request and guards the live config once | +| the same after a dev hot reload, or when Payload runs with `disableOnInit` | the instance's `config` is watched, so a swapped config is guarded the moment Payload assigns it (before any request or Local API call); as a second line an auth strategy that authenticates nobody (`ipal-second-factor-guard` on the 2FA collection) does the same at the start of every request | | the plugin's endpoints (`/api/ipal/test-email`, `cookie-scan`, `cookie-approval`, `cookie-crawl`, the `access` option of `/api/ipal/doctor`) | `userMeetsRole` and `secondFactorPassed` | | the 2FA package's own endpoints (`/api/setup-totp`, `/api/verify-totp`, `/api/remove-totp`, `/api/admin/reset-user-totp`, `/api/admin/remove-user-totp`, any a later version adds) | accounts of the 2FA collection only; everything except setup and verify also needs the second factor ("The 2FA package's endpoints" below) | -The order of the project's `plugins` array does not matter. Payload's own collections (`payload-preferences`, -`payload-locked-documents`, …) and `access.admin` (may this account open the panel) are left alone: the code is -entered inside the panel. +The order of the project's `plugins` array does not matter, and **there is no exception by name**: Payload's own +collections (in 3.94.1: `payload-preferences`, `payload-locked-documents`, `payload-migrations`, +`payload-query-presets`, `payload-folders`, `payload-jobs`, `payload-kv`, the global `payload-jobs-stats`) are +guarded like every other, and so is whatever a later Payload version or a plugin adds under any slug +(`payload-mcp-api-keys`, …). The job queue's own rules (`jobs.access.run / queue / cancel`) are guarded too. +Only `access.admin` (may this account open the panel) is left alone: the code is entered inside the panel, and +the verify and setup screens are rendered from the session, not from any collection. + +A session that still owes its code is refused **everything**, also what anonymous visitors may read (Site +settings, Notifications, the Cookie banner, forms): for that account the answer is `403` until the code is +entered. The public site is not affected — it reads on the server. An account of the 2FA collection passes when it logged in with **password and code**, or uses an **API key** (`auth.useAPIKey`), or has **not set TOTP up yet** (the setup screen needs that; the package behaves the same). @@ -425,6 +433,24 @@ the Local API with `overrideAccess: true` (the default) are not affected. > leave an invited account waiting. `ipal-doctor --url` reports the number of accounts without 2FA > (`2fa`, deep check); it must be 0. +**Verify attempts are limited** (`twoFactor.verifyLimit`). The package checks the code and never counts tries; +a six-digit code has about three right answers in a million, so whoever held the password could guess. ipalKit +counts attempts per account on `POST /api/verify-totp`: by default the **sixth attempt within 10 minutes** — +right or wrong — is refused with `429` and `Retry-After`, and a line goes to the log. Only a session that already +passed the password reaches the endpoint, so nobody without the password can lock an account's owner out; someone +who has the password can delay the owner's login by ten minutes at a time (and that shows in the log). Counted in +memory per server instance. `verifyLimit: { max: 10, windowMinutes: 5 }` changes it, `verifyLimit: false` turns +it off (a limiter in front of the site). + +**What is NOT covered — the complete list.** (1) Anonymous requests: the access function decides. (2) Accounts +of other auth collections: 2FA is about one collection; such an account is not staff unless its collection is in +`access.staffCollections`, and then it is staff **without** a second factor (warning in the log at start). +(3) API keys. (4) An account that has not set TOTP up yet. (5) Entities the project opted out (below). +(6) `access.admin`. (7) Endpoints that are not the plugin's or the 2FA package's: your own endpoints and other +plugins' endpoints check whatever they check — add `secondFactorPassed(req)` to yours. (8) Server code using the +Local API with `overrideAccess: true`. Nothing is skipped by slug, name or prefix, and a user object the check +cannot read is refused. + **Per-entity opt-out.** A collection or global that may be reached with the password alone (a project decision, e.g. a health record the panel reads before the code is entered), operation by operation: @@ -466,7 +492,7 @@ handler: async (req) => { // or: if (!userMeetsRole(req, 'editor')) … — it includes the second-factor check } // an access function (collections and globals in the config are wrapped for you; this is for the rest) -access: { read: requireSecondFactor(({ req }) => isAdmin(req.user)) } +access: { read: requireSecondFactor(({ req }) => isAdmin(req.user, req.payload)) } ``` **Fails closed.** At startup ipalKit checks that the injected 2FA plugin added what the check reads (the @@ -630,6 +656,7 @@ size while reading, content signature, container and macro checks, an optional ` ## Turn off, override, extend +- **Verify limit:** `twoFactor.verifyLimit: { max, windowMinutes }`, or `false`. - **2FA check:** per entity `custom.ipal.secondFactor` / `custom.totp.disableAccessWrapper` (one operation or all); `twoFactor.guard: false` turns ipal-kit's own second-factor check off everywhere (not recommended); `requireSecondFactor` / `secondFactorPassed` are exported for your own access functions and endpoints. diff --git a/package.json b/package.json index a826582..3a92417 100644 --- a/package.json +++ b/package.json @@ -151,6 +151,7 @@ "devDependencies": { "@clocklimited/payload-2fa": "3.0.0-beta.7", "@eslint/eslintrc": "^3.3.7", + "@payloadcms/db-mongodb": "3.94.1", "@payloadcms/db-postgres": "3.94.1", "@payloadcms/db-sqlite": "3.94.1", "@payloadcms/eslint-config": "3.28.0", diff --git a/pnpm-lock.yaml b/pnpm-lock.yaml index 8a92aed..61505a3 100644 --- a/pnpm-lock.yaml +++ b/pnpm-lock.yaml @@ -44,6 +44,9 @@ importers: '@eslint/eslintrc': specifier: ^3.3.7 version: 3.3.7 + '@payloadcms/db-mongodb': + specifier: 3.94.1 + version: 3.94.1(payload@3.94.1(graphql@16.14.2)(typescript@5.9.3)) '@payloadcms/db-postgres': specifier: 3.94.1 version: 3.94.1(@libsql/client@0.14.0)(payload@3.94.1(graphql@16.14.2)(typescript@5.9.3)) @@ -1643,6 +1646,9 @@ packages: react: ^16.8.0 || ^17.0.0 || ^18.0.0 || ^19.0.0 react-dom: ^16.8.0 || ^17.0.0 || ^18.0.0 || ^19.0.0 + '@mongodb-js/saslprep@1.6.3': + resolution: {integrity: sha512-aHGFvT95c82CoQ7hb6qXpz8Hcc5PJb3ZtQ+P01QDBbyQday0mjcrJPeNJOHCgWe0pGX0zKmKP+1mWi/I/BCX9Q==} + '@napi-rs/nice-android-arm-eabi@1.1.1': resolution: {integrity: sha512-kjirL3N6TnRPv5iuHw36wnucNqXAO46dzK9oPb0wj076R5Xm8PfUVA9nAFB5ZNMmfJQJVKACAPd/Z2KYMppthw==} engines: {node: '>= 10'} @@ -2035,6 +2041,11 @@ packages: cpu: [x64] os: [win32] + '@payloadcms/db-mongodb@3.94.1': + resolution: {integrity: sha512-Gss3kM/moqSBkCuxle7/Ja++On9cr3KkW1oULSxRdcf//iQNoDdBLnjKjChokUVJ+vzf4IMS/vThhMBTkojFMg==} + peerDependencies: + payload: 3.94.1 + '@payloadcms/db-postgres@3.94.1': resolution: {integrity: sha512-QrnE+AxFtsg8pTDcZcyqQ8K/fscflAn7+kGa4kLQl5dCUGBbpjJwc30oeNmLGvsUsXBChV6r8p0duq4ahJk1Ng==} peerDependencies: @@ -2527,9 +2538,15 @@ packages: '@types/unist@3.0.3': resolution: {integrity: sha512-ko/gIFJRv177XgZsZcBwnqJN5x/Gien8qNOn0D5bQU/zAzVf9Zt3BlcUiLqhV9y4ARk0GbT3tnUiPNgnTXzc/Q==} + '@types/webidl-conversions@7.0.3': + resolution: {integrity: sha512-CiJJvcRtIgzadHCYXw7dqEnMNRjhGZlYK05Mj9OyktqV8uVT8fD2BFOB7S1uwBE3Kj2Z+4UyPmFw/Ixgw/LAlA==} + '@types/whatwg-mimetype@3.0.2': resolution: {integrity: sha512-c2AKvDT8ToxLIOUlN51gTiHXflsfIFisS4pO7pDPoKouJCESkhZnEy623gwP9laCy5lnLDAw1vAzu2vM2YLOrA==} + '@types/whatwg-url@11.0.5': + resolution: {integrity: sha512-coYR071JRaHa+xoEvvYqvnIHaVqaYrLPbsufM9BF63HkwI5Lgmy2QR8Q5K/lYDYo5AK82wOvSOS0UsLTpTG7uQ==} + '@types/ws@8.18.1': resolution: {integrity: sha512-ThVF6DCVhA8kUGy+aazFQ4kXQ7E1Ty7A3ypFOe0IcJV8O/M511G99AW24irKrW56Wt44yG9+ij8FaqoBGkuBXg==} @@ -2990,6 +3007,10 @@ packages: bson-objectid@2.0.4: resolution: {integrity: sha512-vgnKAUzcDoa+AeyYwXCoHyF2q6u/8H46dxu5JN+4/TZeq/Dlinn0K6GvxsCLb3LHUJl0m/TLiEK31kUwtgocMQ==} + bson@6.10.4: + resolution: {integrity: sha512-WIsKqkSC0ABoBJuT1LEX+2HEvNmNKKgnTAyd0fL8qzK4SH2i9NXg+t08YtdZp/V9IZ33cxe3iV4yM0qg8lMQng==} + engines: {node: '>=16.20.1'} + buffer-equal-constant-time@1.0.1: resolution: {integrity: sha512-zRpUiDwd/xk6ADqPMATG8vc9VPrkck7T07OIx0gnjmJAnHnTVXNQG3vfvWNuiZIkwu9KrKdA1iJKfsfTVxE6NA==} @@ -4427,6 +4448,10 @@ packages: jws@4.0.1: resolution: {integrity: sha512-EKI/M/yqPncGUUh44xz0PxSidXFr/+r0pA70+gIYhjv+et7yxM+s29Y+VGDkovRofQem0fs7Uvf4+YmAdyRduA==} + kareem@2.6.3: + resolution: {integrity: sha512-C3iHfuGUXK2u8/ipq9LfjFfXFxAZMQJJq7vLS45r3D9Y2xQ/m4S8zaR4zMLFWh9AsNPXmcFfUDhTEO8UIC/V6Q==} + engines: {node: '>=12.0.0'} + keyv@4.5.4: resolution: {integrity: sha512-oxVHkHR/EJf2CNXnWxRLW6mg7JyCCUcG0DtEGmL2ctUo1PNTin1PUil+r/+4r5MpVgC/fn1kjsx7mjSujKqIpw==} @@ -4568,6 +4593,9 @@ packages: memoize-one@6.0.0: resolution: {integrity: sha512-rkpe71W0N0c0Xz6QD0eJETuWAJGnJ9afsl1srmwPrI+yBCkge5EycXXbYRyvL29zZVUWQCY7InPRCv3GDXuZNw==} + memory-pager@1.5.0: + resolution: {integrity: sha512-ZS4Bp4r/Zoeq6+NLJpP+0Zzm0pR8whtGPf1XExKLJBAczGMnSi3It14OiNCStjQjM6NU1okjQGSxgEZN8eBYKg==} + merge-stream@2.0.0: resolution: {integrity: sha512-abv/qOcuPfk3URPfDzmZU1LKmuw8kT+0nIHvKrKgFrwifol/doWcdA4ZqsWQ8ENrFKkd67Mfpo/LovbIUsbt3w==} @@ -4696,6 +4724,62 @@ packages: monaco-editor@0.55.1: resolution: {integrity: sha512-jz4x+TJNFHwHtwuV9vA9rMujcZRb0CEilTEwG2rRSpe/A7Jdkuj8xPKttCgOh+v/lkHy7HsZ64oj+q3xoAFl9A==} + mongodb-connection-string-url@3.0.2: + resolution: {integrity: sha512-rMO7CGo/9BFwyZABcKAWL8UJwH/Kc2x0g72uhDWzG48URRax5TCIcJ7Rc3RZqffZzO/Gwff/jyKwCU9TN8gehA==} + + mongodb@6.20.0: + resolution: {integrity: sha512-Tl6MEIU3K4Rq3TSHd+sZQqRBoGlFsOgNrH5ltAcFBV62Re3Fd+FcaVf8uSEQFOJ51SDowDVttBTONMfoYWrWlQ==} + engines: {node: '>=16.20.1'} + peerDependencies: + '@aws-sdk/credential-providers': ^3.188.0 + '@mongodb-js/zstd': ^1.1.0 || ^2.0.0 + gcp-metadata: ^5.2.0 + kerberos: ^2.0.1 + mongodb-client-encryption: '>=6.0.0 <7' + snappy: ^7.3.2 + socks: ^2.7.1 + peerDependenciesMeta: + '@aws-sdk/credential-providers': + optional: true + '@mongodb-js/zstd': + optional: true + gcp-metadata: + optional: true + kerberos: + optional: true + mongodb-client-encryption: + optional: true + snappy: + optional: true + socks: + optional: true + + mongoose-lean-virtuals@1.1.1: + resolution: {integrity: sha512-8chOqpVE3bcoWT2pIgcJeIZlXaOfQCavZgQZF4qytUtjRBqsNMyzUoR16qdw9XL2kC478N8iA8z0AA+NSS0d1A==} + engines: {node: '>=16.20.1'} + peerDependencies: + mongoose: '>=5.11.10' + + mongoose-paginate-v2@1.9.4: + resolution: {integrity: sha512-0LOsVEQmjrbJKVDi/IvFEhIezmuRjUE4loGgslv57j9nK/NMC+mbKT0QnaPSPpib4lByKVBcy3VbDa1TvlHZjA==} + engines: {node: '>=4.0.0'} + + mongoose@8.24.7: + resolution: {integrity: sha512-+hrEOLpLGPgOt7S/UrcBAKZ4gvB6+5qf16jspWH5xQ8WtQu9lRTzcqy04ZNQrlIox4Pl6Nh2RzlNDPSOFw9rng==} + engines: {node: '>=16.20.1'} + + mpath@0.8.4: + resolution: {integrity: sha512-DTxNZomBcTWlrMW76jy1wvV37X/cNNxPW1y2Jzd4DZkAaC5ZGsm8bfGfNOthcDuRJujXLqiuS6o3Tpy0JEoh7g==} + engines: {node: '>=4.0.0'} + + mpath@0.9.0: + resolution: {integrity: sha512-ikJRQTk8hw5DEoFVxHG1Gn9T/xcjtdnOKIU1JTmGjZZlg9LST2mBLmcX3/ICIbgJydT2GOc15RnNy5mHmzfSew==} + engines: {node: '>=4.0.0'} + + mquery@5.0.1: + resolution: {integrity: sha512-C99lWV0TFI34pS008jBsi3JrE2xZPnTgUw5yApQR71nRP0hxLy8D5m1Lbbk83c8AQWJwdJ0329HzFtZ1MRTUIw==} + engines: {node: '>=14.0.0'} + ms@2.1.3: resolution: {integrity: sha512-6FlzubTLZG3J2a/NVCAleEhjzq5oxgHyaCU9yYXvcLsvoVaHJq/s5xXI6/XXP6tz7R9xAOtHnSO/tXtF3WRTlA==} @@ -5370,6 +5454,9 @@ packages: resolution: {integrity: sha512-6x6dK6zJdpTzF4sQeNYxwtvBzf6Eg4GtlesS94HOvTudUeyK2WXAaIfmDgsyslYrRBeFIlsi54AYsFGUuhmvrQ==} engines: {node: '>= 0.4'} + sift@17.1.3: + resolution: {integrity: sha512-Rtlj66/b0ICeFzYTuNvX/EF1igRbbnGSvEyT79McoZa/DeGhMyC5pWKOEsZKnpkqtSeovd5FL/bjHWC3CIIvCQ==} + signal-exit@4.1.0: resolution: {integrity: sha512-bzyZ1e88w9O1iNJbKnOlvYTrWPDl46O1bG0D3XInv+9tkPrxrN8jUUTiFlDkkmKWgn1M6CfIA13SuGqOa9Korw==} engines: {node: '>=14'} @@ -5436,6 +5523,9 @@ packages: resolution: {integrity: sha512-i5uvt8C3ikiWeNZSVZNWcfZPItFQOsYTUAOkcUPGd8DqDy1uOUikjt5dG+uRlwyvR108Fb9DOd4GvXfT0N2/uQ==} engines: {node: '>= 12'} + sparse-bitfield@3.0.3: + resolution: {integrity: sha512-kvzhi7vqKTfkh0PZU+2D2PIllw2ymqJKujUcyPMd9Y75Nv4nPbGJZXNhxsgdQab2BmlDct1YnfQCguEvHr7VsQ==} + split2@4.2.0: resolution: {integrity: sha512-UcjcJOWknrNkF6PLX83qcHM6KHgVKNkV62Y8a5uYDVv9ydGQVwAHMKqHdJje1VTWpljG0WYpCDhrCdAOYH4TWg==} engines: {node: '>= 10.x'} @@ -5619,6 +5709,10 @@ packages: resolution: {integrity: sha512-dRXchy+C0IgK8WPC6xvCHFRIWYUbqqdEIKPaKo/AcTUNzwLTK6AH7RjdLWsEZcAN/TBdtfUw3PYEgPr5VPr6ww==} engines: {node: '>=14.16'} + tr46@5.1.1: + resolution: {integrity: sha512-hdF5ZgjTqgAntKkklYw0R03MG2x/bSzTtkxmIRw/sTNV8YXsCJ1tfLAX23lhxhHJlEf3CRCOCGGWw3vI3GaSPw==} + engines: {node: '>=18'} + truncate-utf8-bytes@1.0.2: resolution: {integrity: sha512-95Pu1QXQvruGEhv62XCMO3Mm90GscOCClvrIUwCM0PYOXK3kaF3l3sIHxx71ThJfcbM2O5Au6SO3AWCSEfW4mQ==} @@ -5879,10 +5973,18 @@ packages: web-worker@1.5.0: resolution: {integrity: sha512-RiMReJrTAiA+mBjGONMnjVDP2u3p9R1vkcGz6gDIrOMT3oGuYwX2WRMYI9ipkphSuE5XKEhydbhNEJh4NY9mlw==} + webidl-conversions@7.0.0: + resolution: {integrity: sha512-VwddBukDzu71offAQR975unBIGqfKZpM+8ZX6ySk8nYhVoo5CYaZyzt3YBvYtRtO+aoGlqxPg/B87NGVZ/fu6g==} + engines: {node: '>=12'} + whatwg-mimetype@3.0.0: resolution: {integrity: sha512-nt+N2dzIutVRxARx1nghPKGv1xHikU7HKdfafKkLNLindmPU/ch3U31NOCGGA/dmPcmb1VlofO0vnKAcsm0o/Q==} engines: {node: '>=12'} + whatwg-url@14.2.0: + resolution: {integrity: sha512-De72GdQZzNTUBBChsXueQUnPKDkg/5A5zp7pFDuQAj5UFoENpiACU0wlCvzpAGnTkj++ihpKwKyYewn/XNUbKw==} + engines: {node: '>=18'} + which-boxed-primitive@1.1.1: resolution: {integrity: sha512-TbX3mj8n0odCBFVlY8AxkqcHASw3L60jIuF8jFP78az3C2YhmGvqbHBpAjTRH2/xqYunrJ9g1jSyjCjpoWzIAA==} engines: {node: '>= 0.4'} @@ -7450,6 +7552,10 @@ snapshots: react: 19.3.1 react-dom: 19.3.1(react@19.3.1) + '@mongodb-js/saslprep@1.6.3': + dependencies: + sparse-bitfield: 3.0.3 + '@napi-rs/nice-android-arm-eabi@1.1.1': optional: true @@ -7705,6 +7811,23 @@ snapshots: '@oxc-resolver/binding-win32-x64-msvc@11.24.2': optional: true + '@payloadcms/db-mongodb@3.94.1(payload@3.94.1(graphql@16.14.2)(typescript@5.9.3))': + dependencies: + mongoose: 8.24.7 + mongoose-paginate-v2: 1.9.4(mongoose@8.24.7) + payload: 3.94.1(graphql@16.14.2)(typescript@5.9.3) + prompts: 2.4.2 + uuid: 13.0.2 + transitivePeerDependencies: + - '@aws-sdk/credential-providers' + - '@mongodb-js/zstd' + - gcp-metadata + - kerberos + - mongodb-client-encryption + - snappy + - socks + - supports-color + '@payloadcms/db-postgres@3.94.1(@libsql/client@0.14.0)(payload@3.94.1(graphql@16.14.2)(typescript@5.9.3))': dependencies: '@payloadcms/drizzle': 3.94.1(@libsql/client@0.14.0)(@types/pg@8.20.0)(payload@3.94.1(graphql@16.14.2)(typescript@5.9.3))(pg@8.20.0) @@ -8413,8 +8536,14 @@ snapshots: '@types/unist@3.0.3': {} + '@types/webidl-conversions@7.0.3': {} + '@types/whatwg-mimetype@3.0.2': {} + '@types/whatwg-url@11.0.5': + dependencies: + '@types/webidl-conversions': 7.0.3 + '@types/ws@8.18.1': dependencies: '@types/node': 22.20.5 @@ -8996,6 +9125,8 @@ snapshots: bson-objectid@2.0.4: {} + bson@6.10.4: {} + buffer-equal-constant-time@1.0.1: {} buffer-from@1.1.2: {} @@ -10721,6 +10852,8 @@ snapshots: jwa: 2.0.1 safe-buffer: 5.2.1 + kareem@2.6.3: {} + keyv@4.5.4: dependencies: json-buffer: 3.0.1 @@ -10890,6 +11023,8 @@ snapshots: memoize-one@6.0.0: {} + memory-pager@1.5.0: {} + merge-stream@2.0.0: {} merge2@1.4.1: {} @@ -11104,6 +11239,57 @@ snapshots: dompurify: 3.5.0 marked: 14.0.0 + mongodb-connection-string-url@3.0.2: + dependencies: + '@types/whatwg-url': 11.0.5 + whatwg-url: 14.2.0 + + mongodb@6.20.0: + dependencies: + '@mongodb-js/saslprep': 1.6.3 + bson: 6.10.4 + mongodb-connection-string-url: 3.0.2 + + mongoose-lean-virtuals@1.1.1(mongoose@8.24.7): + dependencies: + mongoose: 8.24.7 + mpath: 0.8.4 + + mongoose-paginate-v2@1.9.4(mongoose@8.24.7): + dependencies: + mongoose-lean-virtuals: 1.1.1(mongoose@8.24.7) + transitivePeerDependencies: + - mongoose + + mongoose@8.24.7: + dependencies: + bson: 6.10.4 + kareem: 2.6.3 + mongodb: 6.20.0 + mpath: 0.9.0 + mquery: 5.0.1 + ms: 2.1.3 + sift: 17.1.3 + transitivePeerDependencies: + - '@aws-sdk/credential-providers' + - '@mongodb-js/zstd' + - gcp-metadata + - kerberos + - mongodb-client-encryption + - snappy + - socks + - supports-color + + mpath@0.8.4: {} + + mpath@0.9.0: {} + + mquery@5.0.1: + dependencies: + debug: 4.4.3 + transitivePeerDependencies: + - supports-color + ms@2.1.3: {} nanoid@3.3.20: {} @@ -11910,6 +12096,8 @@ snapshots: side-channel-map: 1.0.1 side-channel-weakmap: 1.0.2 + sift@17.1.3: {} + signal-exit@4.1.0: {} simple-wcswidth@1.1.2: {} @@ -11964,6 +12152,10 @@ snapshots: source-map@0.7.6: {} + sparse-bitfield@3.0.3: + dependencies: + memory-pager: 1.5.0 + split2@4.2.0: {} stable-hash@0.0.4: {} @@ -12172,6 +12364,10 @@ snapshots: '@tokenizer/token': 0.3.0 ieee754: 1.2.1 + tr46@5.1.1: + dependencies: + punycode: 2.3.1 + truncate-utf8-bytes@1.0.2: dependencies: utf8-byte-length: 1.0.5 @@ -12425,8 +12621,15 @@ snapshots: web-worker@1.5.0: {} + webidl-conversions@7.0.0: {} + whatwg-mimetype@3.0.0: {} + whatwg-url@14.2.0: + dependencies: + tr46: 5.1.1 + webidl-conversions: 7.0.0 + which-boxed-primitive@1.1.1: dependencies: is-bigint: 1.1.0 diff --git a/reference/.agents/skills/ipal-debug/SKILL.md b/reference/.agents/skills/ipal-debug/SKILL.md index 1b5debb..888a9e0 100644 --- a/reference/.agents/skills/ipal-debug/SKILL.md +++ b/reference/.agents/skills/ipal-debug/SKILL.md @@ -34,6 +34,8 @@ through this procedure. Ask only when you are missing something you cannot get y ### Build / TypeScript | Symptom | Cause | Fix | |---|---|---| +| the 2FA code screen answers "Too many codes were tried…" (`429` from `/api/verify-totp`) | more than 5 verify attempts for that account in 10 minutes (`twoFactor.verifyLimit`); repeated lines `[ipal] 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(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()`; in middleware `isAdmin(user, { staffCollections: ['users'] })` | | startup: `[ipal] twoFactor: the injected 2FA plugin did not add the totpSecret field / hasTotp field / totp auth strategy` | the installed `@clocklimited/payload-2fa` is not a version ipal-kit's second-factor check recognises (tested: 3.0.0-beta.1 and beta.7), or a custom factory was injected | install a supported version; stop-gap only: `twoFactor.guard: false` (the plugin's own data is then not covered by 2FA — security.md) | | own route or script gets `403` / "not allowed" on `form-submissions`, `forms`, a settings global with `overrideAccess: false`, although the user is an admin | the `user` was fetched by id and passed by hand: it does not carry how the account logged in, so the second-factor check refuses it | take the user from `payload.auth({ headers })` (it sets `collection` and how the account logged in), or (server-only code that needs no access check) leave `overrideAccess` at its default; a hand-built user needs at least `collection: 'users'` for its role to count | | an account of a second auth collection (`customers`) gets `403` from a settings global, submissions, `/api/ipal/*`, `/api/setup-totp`, or `isAdmin` / `adminOnly` say no although it has `roles: ['admin']`, after an upgrade | by design since the release after 1.16.3: roles and staff checks count only for accounts of a staff collection | write the one rule it needs (`formSubmissionOverrides`, `globalOverrides`, `collectionOverrides`); a second STAFF collection: `access.staffCollections` (access.md "Who is staff") | diff --git a/reference/.agents/skills/ipal-reference/SKILL.md b/reference/.agents/skills/ipal-reference/SKILL.md index e517084..f29bf72 100644 --- a/reference/.agents/skills/ipal-reference/SKILL.md +++ b/reference/.agents/skills/ipal-reference/SKILL.md @@ -30,7 +30,7 @@ description: Complete map of everything @intecion/ipal-kit provides — every ip | `access.defaultRole` | `'user'` | `defaultValue` of the `roles` field | `'editor'` / `'admin'` | | `access.authAccess` | `{ create: adminOnly, delete: adminOnly, read: adminOrSelfIn(slug), unlock: adminOnly, update: adminOrSelfIn(slug) }` | access of the auth collection the plugin **injects** (Payload's default lets any logged-in account edit or delete every other account) | your keys win, e.g. `{ read: authenticated }`; your own collection with that slug wins whole (give it `adminOrSelf` / `adminOnly` yourself) | | `access.firstUserAdmin` | `true` | the account made on Payload's "Create first user" screen (`/first-register` on an empty collection) gets `roles: ['admin']`; an open sign-up still gets `defaultRole` | `false` = that account gets what was submitted | -| `access.staffCollections` | `[]` | more auth collections whose accounts are staff, besides the panel's login collection (`admin.user`) and `access.authCollection`; roles count **only** for accounts of a staff collection (every predicate and access function); without a `roles` field there, every such account passes every staff check | add `buildRolesField()` to that collection to tell roles apart; a visitor collection (`customers`) is never listed here | +| `access.staffCollections` | `[]` | more auth collections whose accounts are staff, besides the panel's login collection (`admin.user`) and `access.authCollection`; roles count **only** for accounts of a staff collection (every predicate and access function); such accounts are **not** covered by 2FA (one collection only — warning in the log at start); without a `roles` field there, every such account passes every staff check | add `buildRolesField()` to that collection to tell roles apart; a visitor collection (`customers`) is never listed here | | `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 `[ipal] twoFactor.issuer is required` | | `twoFactor.issuer` | — (required) | name in the authenticator app | — | @@ -39,6 +39,7 @@ description: Complete map of everything @intecion/ipal-kit provides — every ip | `twoFactor.provider` | `'@intecion/ipal-kit/admin#TotpRedirectProvider'` | admin provider that sends users to `setup-totp` / `verify-totp` (path read in the browser); replaces the package's header-based one | own component path / `{ path, clientProps, serverProps }` (gets clientProps `forceSetup`); `false` keeps the package's (needs `x-pathname` on `/admin`, else `setup-totp?back=null` loops) | | `twoFactor.texts` | ipal-kit's en/pl texts (`TOTP_TEXTS`) over the package's; 2FA screens titled "Two-step verification" / "Weryfikacja dwuetapowa" (site's language) | `false` = the package's texts; one text: `i18n.translations..totpPlugin.` (security.md) | | `twoFactor.guard` | on | ipal-kit's own second-factor check on every collection and global (also the plugin's own and those of plugins listed after ipalKit) and in `userMeetsRole`; startup fails with `[ipal] twoFactor: the injected 2FA plugin did not add …` when the 2FA package lacks the `totp` strategy / `hasTotp` / `totpSecret` | per entity: `custom.ipal.secondFactor: false` / `{ read: false }` or the package's `custom.totp.disableAccessWrapper.`; `false` = the package's wrapper only (the plugin's own data then opens to a password without the code; not recommended). The package's endpoints stay limited to accounts of the 2FA collection either way | +| `twoFactor.verifyLimit` | `{ max: 5, windowMinutes: 10 }` | attempts per account on `POST /api/verify-totp` (the 2FA package counts none): the sixth in the window, right or wrong, gets `429` + `Retry-After`; in memory per instance | `{ max, windowMinutes }`; `false` = no limit | | `twoFactor.allowCollectionMismatch` | `false` | allows `collectionSlug` ≠ `admin.user` (panel users of the other collection then skip 2FA) | `true` only when you protect a second auth collection on purpose | | `whiteLabel` | none | `admin.components.graphics.Logo/Icon` (`AdminLogo`/`AdminIcon`) from Site settings + vendor credit | omit / `false`; `true` = defaults | | `whiteLabel.settingsSlug` | `'site-settings'` | global it reads the logo/name from | — | diff --git a/reference/.agents/skills/ipal-reference/resources/api.md b/reference/.agents/skills/ipal-reference/resources/api.md index 16bdff6..2054e71 100644 --- a/reference/.agents/skills/ipal-reference/resources/api.md +++ b/reference/.agents/skills/ipal-reference/resources/api.md @@ -59,16 +59,16 @@ Admin panel components from `@intecion/ipal-kit/admin` — the project does NOT | `adminOnlyField` | `@intecion/ipal-kit` | `FieldAccess` (boolean only): field for admin only. In `field.access.read/update`. | | `adminOrEditorField` | `@intecion/ipal-kit` | `FieldAccess`: field for editor or admin. | | `requireRoleField(minimum)` | `@intecion/ipal-kit` | `FieldAccess` factory: at least the given role. | -| `hasMinimumRole(user, minimum, payload?)` | `@intecion/ipal-kit` | Predicate → `boolean`: the user is an account of a **staff collection** and has a role ≥ `minimum` (reads `user.roles` and `user.collection` safely). A role on an account of another auth collection never counts. Pass `req.payload` where you have it; without it the staff collections of the config ipalKit built in this process are used (in a browser bundle, where there is none, the roles are taken as they are — UI only). Does not check the second factor. | -| `isAdmin(user, payload?)` | `@intecion/ipal-kit` | Predicate → `boolean`: staff account with the `admin` role (see `hasMinimumRole`). In hooks and endpoints: `isAdmin(req.user, req.payload)`. | -| `isEditor(user, payload?)` | `@intecion/ipal-kit` | Predicate → `boolean`: staff account with `editor` or higher. | +| `hasMinimumRole(user, minimum, source?)` | `@intecion/ipal-kit` | Predicate → `boolean`: the user is an account of a **staff collection** and has a role ≥ `minimum` (reads `user.roles` and `user.collection` safely). A role on an account of another auth collection never counts. `source` says which collections are staff: `req.payload` on the server, the config from `useConfig()` in a client component, or `{ staffCollections: ['users'] }` (middleware). Without it: the staff collections of the config ipalKit built in this process (two different configs: only what both call staff) — and **`false` where there is none** (browser bundle, middleware, edge). Does not check the second factor. | +| `isAdmin(user, source?)` | `@intecion/ipal-kit` | Predicate → `boolean`: staff account with the `admin` role (see `hasMinimumRole`). In hooks and endpoints: `isAdmin(req.user, req.payload)`; in a client component: `isAdmin(user, config)`. | +| `isEditor(user, source?)` | `@intecion/ipal-kit` | Predicate → `boolean`: staff account with `editor` or higher. | | `userMeetsRole(req, minimum)` | `@intecion/ipal-kit` | Predicate → `boolean` with `req` (`{ payload, user }`), in this order: the account belongs to a **staff collection** (`admin.user`, `access.authCollection`, `access.staffCollections`); with 2FA on it has passed the second factor (`secondFactorPassed`); it has a role ≥ `minimum`, **or** its collection has no `roles` field (the project omitted `access`). An account of any other auth collection never passes, whatever fields it has. The plugin's staff features (Site integrations, settings globals, form submissions, consent records, stats, cookie scanner, the e-mail test) use it; use it in your own endpoints. | -| `staffCollectionSlugs(payload)` | `@intecion/ipal-kit` | `string[]`: the staff collections — `admin.user`, `access.authCollection` and `access.staffCollections`. Roles and staff checks count only for accounts of these. | +| `staffCollectionSlugs(source?)` | `@intecion/ipal-kit` | `string[]`: the staff collections — `admin.user`, `access.authCollection` and `access.staffCollections` — from `req.payload`, a config or `{ staffCollections }`; without an argument what the configs built in this process agree on (`[]` when there is none). Roles and staff checks count only for accounts of these. | | `ROLE_HIERARCHY` | `@intecion/ipal-kit` | Constant `['user', 'editor', 'admin']` (lowest first) — a higher role meets the requirements of a lower one. The plugin injects the `roles` field into the auth collection (`access.authCollection`). | | `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:** `Role` (`'user' \| 'editor' \| 'admin'`), `AccessOption` (the plugin's `access` option: `authCollection`, `defaultRole`, `authAccess`, `firstUserAdmin`, `staffCollections`). +**Types:** `VerifyLimitOptions` (`twoFactor.verifyLimit`: `{ max?, windowMinutes? }`), `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/reference/.agents/skills/ipal-setup/SKILL.md b/reference/.agents/skills/ipal-setup/SKILL.md index 7164c21..87f60cb 100644 --- a/reference/.agents/skills/ipal-setup/SKILL.md +++ b/reference/.agents/skills/ipal-setup/SKILL.md @@ -224,6 +224,7 @@ the panel shows Site settings, Site integrations, Cookies, Form messages, the Fo `[ipal] twoFactor…` unless `allowCollectionMismatch: true`. The second factor covers every collection and global (the plugin's own, and those of plugins listed after `ipalKit`) and the plugin's endpoints; guard your own endpoints with `secondFactorPassed(req)` or `userMeetsRole(req, role)` (security.md "What the second factor covers"). + Verify attempts: 5 per account in 10 minutes (`twoFactor.verifyLimit`). **Set 2FA up right after creating an account** (log in as it, scan the code): until then its password alone opens everything its role allows. One entity reachable without the code: `custom.ipal.secondFactor`. - A second auth collection (`customers`, a client zone): set `admin: { user: 'users' }` in `buildConfig`; its diff --git a/reference/.agents/skills/ipal-upgrade/SKILL.md b/reference/.agents/skills/ipal-upgrade/SKILL.md index f74e1a0..0f6a6da 100644 --- a/reference/.agents/skills/ipal-upgrade/SKILL.md +++ b/reference/.agents/skills/ipal-upgrade/SKILL.md @@ -342,7 +342,10 @@ for every site:** `consent-records`, `stats-visits`, `cookie-review`, the settings globals) must pass the `user` from `payload.auth({ headers })`; a user object built by hand needs `collection: ''` for its role to count. Own endpoints that check `req.user`: add `secondFactorPassed(req)` or use `userMeetsRole(req, role)`. - `isAdmin(req.user)` keeps working; prefer `isAdmin(req.user, req.payload)`. + `isAdmin(req.user)` keeps working on the server; prefer `isAdmin(req.user, req.payload)`. + `grep -rnE "isAdmin\(|isEditor\(|hasMinimumRole\(" src` — a call in a **client component** or in `proxy.ts` / + middleware now returns `false` without a source: `isAdmin(user, config)` (`useConfig()`), or + `isAdmin(user, { staffCollections: ['users'] })`. 4. `pnpm exec ipal-doctor --url ` (with the doctor token) → accounts without 2FA must be 0. An account that has not set TOTP up opens everything with its password alone: have its owner set it up now, or remove it. 5. Tell the owner what the CHANGELOG entry says under "Requires project changes" and agree on it: new SMTP diff --git a/src/index.ts b/src/index.ts index 00f399b..9134a4c 100644 --- a/src/index.ts +++ b/src/index.ts @@ -329,6 +329,7 @@ export type { BuildSecurityHeadersArgs, SecurityHeader } from './modules/securit export { requireSecondFactor, secondFactorPassed } from './modules/security/totp/secondFactor.js' export { TOTP_TEXTS, TOTP_VIEW_TITLE } from './modules/security/totp/totpTexts.js' +export type { VerifyLimitOptions } from './modules/security/totp/verifyLimit.js' export type { OgImage } from './modules/seo/buildMetadata.js' export type { PageMetadata, SeoMeta, SeoOption } from './modules/seo/index.js' export { diff --git a/src/modules/access/index.ts b/src/modules/access/index.ts index ffd2d0d..1ac0d06 100644 --- a/src/modules/access/index.ts +++ b/src/modules/access/index.ts @@ -10,7 +10,7 @@ export { requireRoleField, } from './access.js' export { injectRoles } from './injectRoles.js' -export { hasMinimumRole, isAdmin, isEditor, registerStaffCollections, staffCollectionSlugs, userMeetsRole } from './predicates.js' +export { clearStaffRegistry, hasMinimumRole, isAdmin, isEditor, registerStaffCollections, staffCollectionSlugs, userMeetsRole } from './predicates.js' export { buildRolesField } from './rolesField.js' export type { AccessOption, Role } from './types.js' export { ROLE_HIERARCHY } from './types.js' diff --git a/src/modules/access/predicates.ts b/src/modules/access/predicates.ts index 9798ffe..3dfaa9a 100644 --- a/src/modules/access/predicates.ts +++ b/src/modules/access/predicates.ts @@ -13,19 +13,50 @@ import { ROLE_HIERARCHY } from './types.js' */ type MaybeUser = { roles?: null | Role[] } | null | Record | undefined -/** `req.payload`, or anything with the sanitized config on it. */ -type MaybePayload = null | Pick | undefined +/** + * Where the staff collections come from: `req.payload` (anything with the + * sanitized `config` on it), a config itself (also the client config from + * `useConfig()` — it has `admin.user`), or the list given outright. + */ +type StaffSource = { admin?: { user?: string }; config?: StaffConfig; custom?: unknown; staffCollections?: string[] } | null | undefined +type StaffConfig = { admin?: { user?: string }; custom?: unknown } +type MaybePayload = Pick | StaffSource /** - * The staff collections of the config ipalKit last built in this process — - * what the predicates fall back to when they get no `payload` (`isAdmin(req.user)` - * in a hook or an endpoint). `null` where ipalKit never ran: a browser bundle. + * The staff lists of the configs ipalKit built in this process, by owner: the + * running Payload instance once it exists, a token of the config before that. + * Used when a predicate gets no source (`isAdmin(req.user)` in a hook). */ -let registeredStaff: null | string[] = null +const registered = new Map() -/** Called by ipalKit (config time, then onInit with the sanitized config). Not for projects. */ -export function registerStaffCollections(slugs: string[]): void { - registeredStaff = [...new Set(slugs.filter(Boolean))] +/** + * Called by ipalKit: at config time with a token, then with the Payload + * instance (`replaces` = that config's token) on init and after every reload. + * Not for projects. + */ +export function registerStaffCollections(owner: object, slugs: string[], replaces?: object): void { + if (replaces) {registered.delete(replaces)} + registered.set(owner, [...new Set(slugs.filter(Boolean))]) +} + +/** For tests. */ +export function clearStaffRegistry(): void { + registered.clear() +} + +/** For tests: how many configs / instances have a staff list filed. */ +export const staffRegistrySize = (): number => registered.size + +/** + * The staff collections every config in this process agrees on, or null when + * ipalKit never ran here (a browser bundle, Next middleware, the edge + * runtime). Two configs with different lists: only what both call staff — a + * call that does not say which config it means must not get the wider answer. + */ +function agreedStaff(): null | string[] { + if (!registered.size) {return null} + const lists = [...registered.values()] + return lists[0].filter((slug) => lists.every((list) => list.includes(slug))) } /** @@ -34,29 +65,33 @@ export function registerStaffCollections(slugs: string[]): void { * (`access.authCollection`) and `access.staffCollections`. Accounts of any * other auth collection — customers, members — are visitors to the plugin: * no role and no staff check counts for them, whatever fields they have. + * + * Pass `req.payload` (or a config, or `{ staffCollections: [...] }`). Without + * an argument: what the configs built in this process agree on, `[]` when + * there is none. */ -export function staffCollectionSlugs(payload?: MaybePayload): string[] { - const config = payload?.config - if (!config) {return registeredStaff ?? []} +export function staffCollectionSlugs(source?: MaybePayload): string[] { + if (!source) {return agreedStaff() ?? []} + const given = (source as { staffCollections?: unknown }).staffCollections + if (Array.isArray(given)) {return given.filter((s): s is string => typeof s === 'string' && s !== '')} + const config = ((source as { config?: StaffConfig }).config ?? source) as StaffConfig const extra = (config.custom as { ipal?: { staffCollections?: string[] } } | undefined)?.ipal?.staffCollections ?? [] return [...new Set([config.admin?.user, ...extra].filter((s): s is string => typeof s === 'string' && s !== ''))] } /** * Whether this account's roles may count at all: it belongs to a staff - * collection. Checked before any role. An account without `collection` (a - * user object built by hand) does not count either — pass the user Payload - * authenticated, or add `collection` yourself in server code you trust. - * - * Only where no staff list is known (no `payload` given and ipalKit never ran - * in this bundle — client components) the roles are taken as they are; that is - * for showing or hiding things, never for access control. + * collection. Checked before any role, and it fails closed: + * - an account without `collection` (a user object built by hand) is not staff; + * - where the staff collections are not known — no source given and ipalKit + * never ran in this bundle (client components, Next middleware, the edge + * runtime) — nobody is staff. Pass the source there: `isAdmin(user, config)` + * with the config from `useConfig()`, or `isAdmin(user, { staffCollections: ['users'] })`. */ -function isStaffAccount(user: MaybeUser, payload?: MaybePayload): boolean { +function isStaffAccount(user: MaybeUser, source?: MaybePayload): boolean { if (!user || typeof user !== 'object') {return false} - if (!payload?.config && registeredStaff === null) {return true} const slug = (user as { collection?: unknown }).collection - return typeof slug === 'string' && staffCollectionSlugs(payload).includes(slug) + return typeof slug === 'string' && staffCollectionSlugs(source).includes(slug) } /** Safely extracts the roles array from a loosely-typed user. */ @@ -80,7 +115,9 @@ function highestRoleIndex(user: MaybeUser): number { * * Pass `req.payload` as the third argument where you have it (access * functions, hooks, endpoints); without it the staff collections of the - * config ipalKit built in this process are used. + * config ipalKit built in this process are used — and where there is none + * (a browser bundle, middleware) the answer is false: pass the config from + * `useConfig()` or `{ staffCollections: ['users'] }` there. */ export function hasMinimumRole(user: MaybeUser, minimum: Role, payload?: MaybePayload): boolean { if (!isStaffAccount(user, payload)) {return false} diff --git a/src/modules/admin-i18n/texts/index.ts b/src/modules/admin-i18n/texts/index.ts index e9f9118..9f84f61 100644 --- a/src/modules/admin-i18n/texts/index.ts +++ b/src/modules/admin-i18n/texts/index.ts @@ -1,12 +1,13 @@ import { consentTexts } from './consent.js' import { contentTexts } from './content.js' import { integrationsTexts } from './integrations.js' +import { securityTexts } from './security.js' import { settingsTexts } from './settings.js' /** Every admin component text, by language. Payload reads them as `ipal:`. */ export const adminTexts = { - en: { ...settingsTexts.en, ...integrationsTexts.en, ...consentTexts.en, ...contentTexts.en }, - pl: { ...settingsTexts.pl, ...integrationsTexts.pl, ...consentTexts.pl, ...contentTexts.pl }, + en: { ...settingsTexts.en, ...integrationsTexts.en, ...consentTexts.en, ...contentTexts.en, ...securityTexts.en }, + pl: { ...settingsTexts.pl, ...integrationsTexts.pl, ...consentTexts.pl, ...contentTexts.pl, ...securityTexts.pl }, } export type AdminTextKey = keyof typeof adminTexts.en diff --git a/src/modules/admin-i18n/texts/security.ts b/src/modules/admin-i18n/texts/security.ts new file mode 100644 index 0000000..df8a5b6 --- /dev/null +++ b/src/modules/admin-i18n/texts/security.ts @@ -0,0 +1,11 @@ +import { defineTexts } from '../define.js' + +/** Admin component texts — two-step verification (2FA). Placeholders use Payload's {{name}} syntax. */ +export const securityTexts = defineTexts({ + en: { + twoFactorTooManyAttempts: 'Too many codes were tried for this account. Wait {{minutes}} min, then enter the current code from your app.', + }, + pl: { + twoFactorTooManyAttempts: 'Dla tego konta wpisano zbyt wiele kodów. Odczekaj {{minutes}} min, a potem wpisz aktualny kod z aplikacji.', + }, +}) diff --git a/src/modules/doctor/status.ts b/src/modules/doctor/status.ts index 93d149d..dbe8e36 100644 --- a/src/modules/doctor/status.ts +++ b/src/modules/doctor/status.ts @@ -42,7 +42,7 @@ export async function collectDoctorStatus(payload: BasePayload): Promise req.user?.roles?.includes('admin')`. */ + /** Who may read the status besides a valid token, e.g. `({ req }) => isAdmin(req.user, req.payload)` (a staff admin; the second factor is checked for you). */ access?: (args: { req: PayloadRequest }) => boolean | Promise /** Env variable that holds the token (≥ 32 characters). Default IPAL_DOCTOR_TOKEN. */ tokenVar?: string diff --git a/src/modules/security/totp/secondFactor.ts b/src/modules/security/totp/secondFactor.ts index bb319d6..060a093 100644 --- a/src/modules/security/totp/secondFactor.ts +++ b/src/modules/security/totp/secondFactor.ts @@ -12,6 +12,27 @@ import type { BasePayload, CollectionConfig, Config, GlobalConfig } from 'payloa * applies it to everything in the config when it finishes, and again in onInit * to whatever other plugins added later; `userMeetsRole` asks it too. * + * Every way past this check, and why it is safe — keep this list complete: + * 1. no user → the access function itself decides (anonymous visitors); + * 2. 2FA off or `twoFactor.guard: false` → there is no check (the project's choice); + * 3. an account of another auth collection → 2FA is about ONE collection; such an + * account is not staff unless the project names its collection in + * `access.staffCollections` (then it is staff WITHOUT a second factor — ipalKit + * logs a warning at start); + * 4. `_strategy === 'totp'` → set by the package's strategy after password and code; + * 5. `_strategy === 'api-key'` → an API key is its own credential (the package's rule); + * 6. `hasTotp === false` → TOTP not set up yet (the setup screen needs the session); + * 7. per-entity opt-out in the project's config (`custom.totp.disableAccessWrapper`, + * `custom.ipal.secondFactor`), or the package's global `disableAccessWrapper`; + * 8. `access.admin` (may this account open the panel) is not wrapped: the code is + * entered inside the panel; + * 9. endpoints are not access functions: the plugin's own check `userMeetsRole` / + * `secondFactorPassed`, the 2FA package's are wrapped (guardTotpEndpoint), a + * project's own must call `secondFactorPassed(req)`; + * 10. the Local API with `overrideAccess: true` (server code). + * There is no exception by slug, name or prefix, and a user object the check cannot + * read (no `collection`, an unknown `_strategy`, no `hasTotp`) is refused. + * * It fails closed. An account of the 2FA collection passes only when * - it came through the package's `totp` strategy (password AND code), or * - it authenticated with an API key (the package's own rule), or @@ -43,6 +64,9 @@ export function secondFactorPassed({ payload, user }: MaybeReq): boolean { const guard = guardConfig(payload) if (!guard) {return true} const u = user as { _strategy?: unknown; collection?: unknown; hasTotp?: unknown } + // A user object that does not say which collection it is from cannot be told apart from a + // 2FA account: refused. (Payload's strategies and payload.auth() always set `collection`.) + if (typeof u.collection !== 'string') {return false} if (u.collection !== guard.collection) {return true} if (u._strategy === 'totp' || u._strategy === 'api-key') {return true} return u.hasTotp === false @@ -57,7 +81,7 @@ type Guarded = { [GUARDED]?: true } & AnyAccess * otherwise the function itself (or Payload's default, "logged in", when there * is none). Wrapping twice is harmless — an already wrapped function is returned as is. * - * access: { read: requireSecondFactor(({ req }) => isAdmin(req.user)) } + * access: { read: requireSecondFactor(({ req }) => isAdmin(req.user, req.payload)) } */ export function requireSecondFactor(access?: T): T { if (access && (access as Guarded)[GUARDED]) {return access} @@ -132,11 +156,27 @@ function guardEntity(entity: T, operations: readonly st return { ...entity, access } } +const JOB_OPERATIONS = ['cancel', 'queue', 'run'] as const +type JobsLike = { access?: AccessMap } | undefined + +/** + * The job queue has its own rules outside any collection (`jobs.access.run / queue / cancel`, + * by default "logged in"): POST /api/payload-jobs/run and the Local API's queue. Guarded like + * an entity, only when the project configured `jobs` at all. + */ +function guardJobs(jobs: T): T { + if (!jobs) {return jobs} + const access: AccessMap = { ...jobs.access } + for (const op of JOB_OPERATIONS) {access[op] = requireSecondFactor(access[op])} + return { ...jobs, access } +} + /** Every collection and global of a (not yet sanitized) config, guarded. Returns a new config. */ export function guardConfigAccess(config: Config): Config { if (wrapperDisabled(config.custom)) {return config} return { ...config, + ...(config.jobs ? { jobs: guardJobs(config.jobs as JobsLike) as Config['jobs'] } : {}), collections: (config.collections ?? []).map((c) => guardEntity(c as GuardedEntity, COLLECTION_OPERATIONS) as CollectionConfig), globals: (config.globals ?? []).map((g) => guardEntity(g as GuardedEntity, GLOBAL_OPERATIONS) as GlobalConfig), } @@ -144,7 +184,17 @@ export function guardConfigAccess(config: Config): Config { /** * The same for a running Payload, in place: what plugins listed after ipalKit - * added. Returns the slugs it had to guard. + * added, and what Payload itself adds when it sanitizes the config. Returns + * the slugs it had to guard. + * + * EVERY collection and global is guarded — there is no exception by name or + * prefix. That includes Payload's own collections (in 3.94.1: + * payload-preferences, payload-locked-documents, payload-migrations, + * payload-query-presets, payload-folders, payload-jobs, payload-kv and the + * global payload-jobs-stats) and any a later Payload adds: an account that + * still owes its code needs none of them — the verify and setup screens are + * rendered from the session. A plugin that names its collection `payload-…` + * (e.g. `payload-mcp-api-keys`) is therefore covered like any other. */ export function guardPayloadAccess(payload: Pick): string[] { if (wrapperDisabled(payload.config.custom)) {return []} @@ -157,26 +207,61 @@ export function guardPayloadAccess(payload: Pick): string for (const op of todo) {access[op] = requireSecondFactor(access[op])} entity.access = access } - // Payload's own collections (payload-preferences, payload-locked-documents, …) keep their rules: - // the panel uses them before the code is entered, and the package leaves them alone too. - for (const c of payload.config.collections ?? []) { - if (!c.slug.startsWith('payload-')) {sweep(c as GuardedEntity, COLLECTION_OPERATIONS)} - } + for (const c of payload.config.collections ?? []) {sweep(c as GuardedEntity, COLLECTION_OPERATIONS)} for (const g of payload.config.globals ?? []) {sweep(g as GuardedEntity, GLOBAL_OPERATIONS)} + const jobs = (payload.config as { jobs?: JobsLike }).jobs + if (jobs && JOB_OPERATIONS.some((op) => !(jobs.access?.[op] as Guarded | undefined)?.[GUARDED])) { + jobs.access = guardJobs(jobs).access + late.push('jobs') + } return late } /** Configs already swept — a new sanitized config (start, dev hot reload) is swept once. */ const swept = new WeakSet() -/** Sweeps `payload.config` once per config object. Returns the slugs guarded now (empty when already done). */ -export function ensurePayloadGuarded(payload: Pick): string[] { +/** + * Sweeps `payload.config` once per config object. Returns the slugs guarded + * now, or null when this config was swept before. + */ +export function ensurePayloadGuarded(payload: Pick): null | string[] { const config = payload?.config - if (!config || swept.has(config)) {return []} + if (!config || swept.has(config)) {return null} swept.add(config) return guardPayloadAccess(payload) } +/** + * Makes `payload.config` an accessor on this instance, so the moment Payload + * swaps the config (its dev `reload()` assigns `payload.config = …` and runs no + * onInit) `onConfig` is called — before any request or Local API call can use + * the new config. Without it the first HTTP request would do the same (the + * guard strategy), but a Local API call made before that request would meet + * unguarded entities from plugins listed after ipalKit. Never throws. + */ +export function watchPayloadConfig(payload: BasePayload, onConfig: (payload: BasePayload) => void): void { + try { + const own = Object.getOwnPropertyDescriptor(payload, 'config') + if (!own || own.get || !own.configurable) {return} + let current = own.value as BasePayload['config'] + Object.defineProperty(payload, 'config', { + configurable: true, + enumerable: own.enumerable ?? true, + get: () => current, + set: (next: BasePayload['config']) => { + current = next + try { + onConfig(payload) + } catch { + // the guard strategy repeats it on the next request + } + }, + }) + } catch { + // an instance we cannot instrument: the guard strategy still covers HTTP + } +} + /** Name of the auth strategy ipalKit adds to the 2FA collection (see buildGuardStrategy). */ export const GUARD_STRATEGY_NAME = 'ipal-second-factor-guard' @@ -188,12 +273,15 @@ export const GUARD_STRATEGY_NAME = 'ipal-second-factor-guard' * where Payload swaps in a freshly built config and does not run onInit, and * when Payload was started with `disableOnInit`. */ -export function buildGuardStrategy(onLate?: (payload: BasePayload, slugs: string[]) => void) { +export function buildGuardStrategy(onConfig?: (payload: BasePayload) => void) { return { name: GUARD_STRATEGY_NAME, authenticate: ({ payload }: { payload: BasePayload }) => { - const late = ensurePayloadGuarded(payload) - if (late.length) {onLate?.(payload, late)} + if (onConfig) { + onConfig(payload) + } else { + ensurePayloadGuarded(payload) + } return { user: null } }, } @@ -216,20 +304,52 @@ type EndpointLike = { handler: (req: never) => Promise | Response; pat * endpoints, whatever a later version adds) also needs the second factor, * so a password alone cannot reset or remove TOTP. */ -export function guardTotpEndpoint(endpoint: T, collection: string): T { +export type TotpEndpointGuards = { + /** + * Called for a verify attempt of a logged-in account before the package sees + * it. Return a Response to refuse (too many attempts), null to let it through. + */ + limitVerify?: (req: never) => null | Promise | Response +} + +export function guardTotpEndpoint(endpoint: T, collection: string, guards: TotpEndpointGuards = {}): T { const handler = endpoint.handler as (req: MaybeReq) => Promise | Response const refused = () => Response.json({ message: 'Not allowed.', ok: false }, { status: 403 }) return { ...endpoint, - handler: ((req: MaybeReq) => { + handler: (async (req: MaybeReq) => { const user = req.user as { collection?: unknown } | null | undefined if (user && user.collection !== collection) {return refused()} if (user && !BEFORE_SECOND_FACTOR.has(endpoint.path) && !secondFactorPassed(req)) {return refused()} + // The code has about three right answers in a million and the package never counts tries. + if (user && endpoint.path === '/verify-totp' && guards.limitVerify) { + const limited = await guards.limitVerify(req as never) + if (limited) {return limited} + } return handler(req) }) as unknown as T['handler'], } } +/** + * The same for endpoints the package may register on a collection or a global + * (none in the versions seen; a later one might): every endpoint that was not + * there before the package ran gets `guardTotpEndpoint`. + */ +export function guardNewEntityEndpoints( + entities: T[] | undefined, + before: Map>, + collection: string, + guards?: TotpEndpointGuards, +): T[] { + return (entities ?? []).map((entity) => { + if (!Array.isArray(entity.endpoints)) {return entity} + const known = before.get(entity.slug) ?? new Set() + if (entity.endpoints.every((e) => known.has(e))) {return entity} + return { ...entity, endpoints: entity.endpoints.map((e) => (known.has(e) ? e : guardTotpEndpoint(e as EndpointLike, collection, guards))) } + }) +} + /** * The parts of @clocklimited/payload-2fa the guard relies on, checked right * after the injected factory ran. A missing part means a version this guard diff --git a/src/modules/security/totp/verifyLimit.ts b/src/modules/security/totp/verifyLimit.ts new file mode 100644 index 0000000..034347c --- /dev/null +++ b/src/modules/security/totp/verifyLimit.ts @@ -0,0 +1,64 @@ +import type { PayloadRequest } from 'payload' + +import { serverText } from '../../integrations/texts.js' + +/** + * A limit on TOTP verify attempts. The 2FA package checks the code and never + * counts tries: a six-digit code with a ±1 step window has about three right + * answers in a million, so whoever holds the password could simply try. + * + * Counted per ACCOUNT, not per IP (an attacker changes addresses; the account + * is what is being guessed). Every attempt counts, right or wrong — nobody + * needs more than a handful of logins in the window. Only a session that + * already passed the password reaches the endpoint, so someone without the + * password cannot use the limit to lock an account's owner out. + * + * In memory, per server instance, and always enforced (no "allow when the + * store fails" path): with several instances the limit is per instance. + */ +export type VerifyLimitOptions = { + /** Attempts per account in the window. Default 5. */ + max?: number + /** Window in minutes; a refused account waits until it ends. Default 10. */ + windowMinutes?: number +} + +type Bucket = { count: number; resetAt: number } +const buckets = new Map() + +/** For tests. */ +export function clearVerifyLimits(): void { + buckets.clear() +} + +export function buildVerifyLimit(collection: string, options: VerifyLimitOptions = {}) { + const max = Number.isFinite(options.max) && options.max! > 0 ? Math.floor(options.max!) : 5 + const windowMs = (Number.isFinite(options.windowMinutes) && options.windowMinutes! > 0 ? options.windowMinutes! : 10) * 60_000 + + return (req: PayloadRequest): null | Response => { + // No session: the package refuses by itself, and there is no account to count against. + if (!req.user) {return null} + // Whatever the id looks like, it is one bucket per value — never "no limit". + const raw = (req.user as { id?: unknown }).id + const id = typeof raw === 'string' || typeof raw === 'number' ? String(raw) : JSON.stringify(raw ?? null) + const now = Date.now() + // keep the map small: forget windows that are over + if (buckets.size > 5000) { + for (const [key, bucket] of buckets) { + if (bucket.resetAt <= now) {buckets.delete(key)} + } + } + const key = `${collection}:${id}` + const current = buckets.get(key) + const bucket = current && current.resetAt > now ? current : { count: 0, resetAt: now + windowMs } + bucket.count += 1 + buckets.set(key, bucket) + if (bucket.count <= max) {return null} + const retryAfter = Math.max(1, Math.ceil((bucket.resetAt - now) / 1000)) + req.payload.logger.warn(`[ipal] 2FA: too many verify attempts for ${collection} ${id}; refused for ${retryAfter} s.`) + return Response.json( + { message: serverText(req.i18n as never, 'twoFactorTooManyAttempts', { minutes: Math.ceil(retryAfter / 60) }), ok: false }, + { headers: { 'Retry-After': String(retryAfter) }, status: 429 }, + ) + } +} diff --git a/src/plugin.ts b/src/plugin.ts index fb54ae3..bf0db63 100644 --- a/src/plugin.ts +++ b/src/plugin.ts @@ -1,4 +1,4 @@ -import type { Config, Plugin } from 'payload' +import type { BasePayload, Config, PayloadRequest, Plugin } from 'payload' import { deepMergeSimple } from 'payload/shared' @@ -33,8 +33,18 @@ import { buildGlobalRevalidateHook } from './modules/hooks/buildRevalidateHook.j import { withFillLocales } from './modules/hooks/fillEmptyLocales.js' import { buildLocalizationConfig, validateI18nConfig } from './modules/i18n/index.js' import { buildSystemPagesFields } from './modules/pages/index.js' -import { buildGuardStrategy, ensurePayloadGuarded, guardConfigAccess, guardTotpEndpoint, missingTotpParts, passOptOutsToPackage } from './modules/security/totp/secondFactor.js' +import { + buildGuardStrategy, + ensurePayloadGuarded, + guardConfigAccess, + guardNewEntityEndpoints, + guardTotpEndpoint, + missingTotpParts, + passOptOutsToPackage, + watchPayloadConfig, +} from './modules/security/totp/secondFactor.js' import { TOTP_TEXTS, TOTP_VIEW_TITLE } from './modules/security/totp/totpTexts.js' +import { buildVerifyLimit } from './modules/security/totp/verifyLimit.js' import { buildSeoPlugin, injectAutoFillMeta, injectSeoTabs } from './modules/seo/index.js' import { buildIndexNowHook } from './modules/seo/indexNow.js' import { searchSettingsFields } from './modules/seo/searchSettings.js' @@ -158,6 +168,21 @@ export const ipalKit = (options: IpalOptions): Plugin => { // ipal-kit's own second-factor check (secondFactor.ts) covers what the 2FA // package cannot: everything added to the config after the package ran. let secondFactorGuard = false + /** The 2FA collection, when 2FA is on. */ + let twoFactorCollection: null | string = null + /** This config's entry in the staff registry until a Payload instance takes it over. */ + const staffToken = {} + /** + * A config has gone live on this instance (start, or a dev hot reload): guard what plugins + * listed after ipalKit added, and file its staff collections under the instance. + */ + const adoptConfig = (payload: BasePayload) => { + const token = (payload.config.custom as { ipal?: { staffToken?: object } } | undefined)?.ipal?.staffToken + registerStaffCollections(payload, staffCollectionSlugs(payload), token) + if (!secondFactorGuard) {return} + const late = ensurePayloadGuarded(payload) + if (late?.length) {payload.logger.info(`[ipal] 2FA also enforced on entities added after ipalKit: ${late.join(', ')}.`)} + } if (options.twoFactor !== false) { const tf = options.twoFactor if (!tf?.issuer) { @@ -204,6 +229,9 @@ export const ipalKit = (options: IpalOptions): Plugin => { ) } const endpointsBefore = new Set(config.endpoints ?? []) + const entityEndpointsBefore = new Map>( + [...(config.collections ?? []), ...(config.globals ?? [])].map((e) => [e.slug, new Set(Array.isArray(e.endpoints) ? e.endpoints : [])]), + ) // custom.ipal.secondFactor (ipal-kit's per-entity opt-out) → the package's own key config = passOptOutsToPackage(config) config = await totp({ @@ -216,7 +244,13 @@ export const ipalKit = (options: IpalOptions): Plugin => { // `req.user` from ANY auth collection and act on the 2FA collection by id. // Only accounts of the 2FA collection may use them (guardTotpEndpoint) — // whatever the package registered, also paths a later version adds. - config.endpoints = (config.endpoints ?? []).map((e) => (endpointsBefore.has(e) ? e : guardTotpEndpoint(e, target))) + const limitVerify = tf.verifyLimit === false ? undefined : buildVerifyLimit(target, tf.verifyLimit) + const guards = limitVerify ? { limitVerify: (req: PayloadRequest) => limitVerify(req) } : {} + config.endpoints = (config.endpoints ?? []).map((e) => (endpointsBefore.has(e) ? e : guardTotpEndpoint(e, target, guards as never))) + // …and the same for endpoints it may put on a collection or a global. + config.collections = guardNewEntityEndpoints(config.collections, entityEndpointsBefore, target, guards as never) + config.globals = guardNewEntityEndpoints(config.globals, entityEndpointsBefore, target, guards as never) + twoFactorCollection = target // The package wraps only what is in the config right now. ipal-kit's own // globals and collections come later, so they get ipal-kit's guard at the @@ -238,9 +272,7 @@ export const ipalKit = (options: IpalOptions): Plugin => { config.custom = { ...config.custom, ipal: { ...config.custom?.ipal, twoFactor: { collection: target } } } // Called by Payload on every request before any access function: guards whatever // the live config has that was added after ipalKit (start, dev hot reload). - const sweep = buildGuardStrategy((payload, late) => - payload.logger.info(`[ipal] 2FA also enforced on entities added after ipalKit: ${late.join(', ')}.`), - ) + const sweep = buildGuardStrategy(adoptConfig) config.collections = (config.collections ?? []).map((c) => c.slug === target && typeof c.auth === 'object' ? { ...c, auth: { ...c.auth, strategies: [sweep as never, ...(c.auth.strategies ?? [])] } } // first: a strategy that finds a user ends the round @@ -406,11 +438,13 @@ export const ipalKit = (options: IpalOptions): Plugin => { const staff = [...new Set([options.access.authCollection, ...(options.access.staffCollections ?? [])])] config.custom = { ...config.custom, ipal: { ...config.custom?.ipal, staffCollections: staff } } } - // For predicates called without `req.payload` (isAdmin(req.user) in a hook): what this - // config says now; onInit repeats it with the sanitized config (admin.user as Payload resolved it). + // For predicates called without `req.payload` (isAdmin(req.user) in a hook): what this config + // says now, under a token; the Payload instance takes the entry over when the config goes live + // (adoptConfig), with `admin.user` as Payload resolved it. { const panel = config.admin?.user ?? (config.collections ?? []).find((c) => c.auth)?.slug - registerStaffCollections(staffCollectionSlugs({ config: { admin: { user: panel }, custom: config.custom } } as never)) + config.custom = { ...config.custom, ipal: { ...config.custom?.ipal, staffToken } } + registerStaffCollections(staffToken, staffCollectionSlugs({ admin: { user: panel }, custom: config.custom })) } // --- seo: apply @payloadcms/plugin-seo directly --- @@ -663,12 +697,18 @@ export const ipalKit = (options: IpalOptions): Plugin => { const incomingOnInit = config.onInit config.onInit = async (payload) => { if (incomingOnInit) {await incomingOnInit(payload)} - registerStaffCollections(staffCollectionSlugs(payload)) - // …and on what plugins listed after ipalKit added: they did not exist above. - // (The guard strategy does the same on the first request — after a hot reload too.) - if (secondFactorGuard) { - const late = ensurePayloadGuarded(payload) - if (late.length) {payload.logger.info(`[ipal] 2FA also enforced on entities added after ipalKit: ${late.join(', ')}.`)} + adoptConfig(payload) + // Payload's dev reload swaps `payload.config` and runs no onInit: adopt the new config at once. + watchPayloadConfig(payload, adoptConfig) + // Staff whose collection is not the 2FA collection log in without a second factor: say so. + if (twoFactorCollection) { + const uncovered = staffCollectionSlugs(payload).filter((slug) => slug !== twoFactorCollection) + if (uncovered.length) { + payload.logger.warn( + `[ipal] 2FA covers "${twoFactorCollection}" only. Staff accounts of ${uncovered.map((s) => `"${s}"`).join(', ')} ` + + 'pass the staff checks with a password alone (docs/access.md "Who is staff").', + ) + } } await migrateCookieSettingsSaveButton(payload) await migrateTitleSeparator(payload, settingsSlug) diff --git a/src/types.ts b/src/types.ts index e20bdc6..ea0df2c 100644 --- a/src/types.ts +++ b/src/types.ts @@ -23,6 +23,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 { VerifyLimitOptions } from './modules/security/totp/verifyLimit.js' import type { SeoOption } from './modules/seo/types.js' import type { StatsOptions } from './modules/stats/collection.js' @@ -270,6 +271,14 @@ export type IpalOptions = { * `i18n.translations..totpPlugin` still wins. `false` keeps the package's. */ texts?: false + /** + * Limit on TOTP verify attempts (`POST /api/verify-totp`), per account: the + * 2FA package never counts tries, and a six-digit code can be guessed by + * whoever holds the password. Default `{ max: 5, windowMinutes: 10 }`: the + * sixth attempt in ten minutes, right or wrong, is refused (429) until the + * window ends. `false` = no limit (a limiter in front of the site). + */ + verifyLimit?: false | VerifyLimitOptions } | false diff --git a/test/access.test.ts b/test/access.test.ts index 0476255..88766f5 100644 --- a/test/access.test.ts +++ b/test/access.test.ts @@ -3,7 +3,7 @@ import type { FieldAccess, PayloadRequest } from 'payload' import { describe, expect, test, vi } from 'vitest' import { adminOnly, adminOnlyField, adminOrEditor, adminOrEditorField, adminOrSelf, adminOrSelfIn, requireRole, requireRoleField } from '../src/modules/access/access.js' -import { hasMinimumRole, isAdmin, isEditor } from '../src/modules/access/predicates.js' +import { hasMinimumRole, isAdmin, isEditor, registerStaffCollections, staffRegistrySize } from '../src/modules/access/predicates.js' import { buildRolesField } from '../src/modules/access/rolesField.js' import { testEmailEndpoint } from '../src/modules/email/test/testEmailEndpoint.js' @@ -17,11 +17,11 @@ const payload = { config: { admin: { user: 'users' } } } as never describe('role predicates', () => { test('hierarchy admin > editor > user', () => { - expect(isAdmin(admin)).toBe(true) - expect(isAdmin(editor)).toBe(false) - expect(isEditor(admin)).toBe(true) - expect(isEditor(user)).toBe(false) - expect(hasMinimumRole(user, 'user')).toBe(true) + expect(isAdmin(admin, payload)).toBe(true) + expect(isAdmin(editor, payload)).toBe(false) + expect(isEditor(admin, payload)).toBe(true) + expect(isEditor(user, payload)).toBe(false) + expect(hasMinimumRole(user, 'user', payload)).toBe(true) }) test('unknown roles and odd shapes grant nothing', () => { @@ -42,6 +42,36 @@ describe('role predicates', () => { expect(isAdmin(member, withMembers)).toBe(true) }) + test('where the staff collections are not known, nobody is staff (browser bundle, middleware)', () => { + // no ipalKit config in this process (test/setup.ts clears the registry) and no source given + expect(isAdmin(admin)).toBe(false) + expect(isAdmin({ collection: 'customers', roles: ['admin'] })).toBe(false) + expect(hasMinimumRole(user, 'user')).toBe(false) + // …until the caller says where staff come from: the config (also the client config), or the list itself + expect(isAdmin(admin, { admin: { user: 'users' } })).toBe(true) + expect(isAdmin(admin, { staffCollections: ['users'] })).toBe(true) + expect(isAdmin({ collection: 'customers', roles: ['admin'] }, { staffCollections: ['users'] })).toBe(false) + }) + + test('two configs in one process: a call without a source gets only what both call staff', () => { + const a = {} + const b = {} + registerStaffCollections(a, ['users']) + expect(isAdmin(admin)).toBe(true) + registerStaffCollections(b, ['staff', 'customers']) + expect(isAdmin(admin)).toBe(false) // not staff in B + expect(isAdmin({ collection: 'customers', roles: ['admin'] })).toBe(false) // not staff in A + registerStaffCollections(b, ['users', 'customers']) + expect(isAdmin(admin)).toBe(true) + expect(isAdmin({ collection: 'customers', roles: ['admin'] })).toBe(false) + // with the source, each config gets its own answer + expect(isAdmin({ collection: 'customers', roles: ['admin'] }, { staffCollections: ['users', 'customers'] })).toBe(true) + // an instance taking over its config's token replaces the entry instead of adding one + const instance = {} + registerStaffCollections(instance, ['users'], a) + expect(staffRegistrySize()).toBe(2) + }) + test('every ready access function refuses that account', () => { const member = { id: 1, collection: 'members', roles: ['admin'] } const req = { payload, user: member } diff --git a/test/http/db.ts b/test/http/db.ts index a0cb291..f078b6d 100644 --- a/test/http/db.ts +++ b/test/http/db.ts @@ -1,3 +1,4 @@ +import { mongooseAdapter } from '@payloadcms/db-mongodb' import { postgresAdapter } from '@payloadcms/db-postgres' import { sqliteAdapter } from '@payloadcms/db-sqlite' @@ -7,9 +8,17 @@ import { sqliteAdapter } from '@payloadcms/db-sqlite' * another): * docker run -d --rm -p 127.0.0.1:55432:5432 -e POSTGRES_PASSWORD=test postgres:17 * IPAL_TEST_POSTGRES_URI=postgres://postgres:test@127.0.0.1:55432/postgres pnpm vitest run test/securityHttp.test.ts - * Each test file gets its own schema (`name`), so the files can run one after another against one server. + * `IPAL_TEST_MONGO_URI` points them at MongoDB (what the client sites run): + * docker run -d --rm -p 127.0.0.1:27217:27017 mongo:7 + * IPAL_TEST_MONGO_URI=mongodb://127.0.0.1:27217 pnpm vitest run test/securityHttp.test.ts + * Each test file gets its own schema / database (`name`), so the files can run one after another against one server. */ +/** True on the adapters where ids are numbers counted per collection (an id can repeat across collections). */ +export const numericIds = () => !process.env.IPAL_TEST_MONGO_URI + export function testDatabase(name: string) { + const mongo = process.env.IPAL_TEST_MONGO_URI + if (mongo) {return mongooseAdapter({ url: `${mongo.replace(/\/$/, '')}/${name}_${Date.now()}` })} const uri = process.env.IPAL_TEST_POSTGRES_URI if (uri) {return postgresAdapter({ pool: { connectionString: uri }, push: true, schemaName: `${name}_${Date.now()}` })} return sqliteAdapter({ client: { url: 'file::memory:' }, push: true }) diff --git a/test/plugin.test.ts b/test/plugin.test.ts index 43dc694..012c954 100644 --- a/test/plugin.test.ts +++ b/test/plugin.test.ts @@ -137,7 +137,7 @@ describe('options that keep features reachable and overridable', () => { test('with `access` the roles still decide', async () => { const config = await ipalKit({ access: { authCollection: 'users' }, i18n, stats: true, twoFactor: false })(base()) const users = config.collections!.find((c) => c.slug === 'users')! - const req = (user: unknown) => ({ payload: { collections: { users: { config: users } } }, user }) as never + const req = (user: unknown) => ({ payload: { collections: { users: { config: users } }, config: { admin: { user: 'users' } } }, user }) as never const read = config.globals!.find((g) => g.slug === 'site-integrations')!.access!.read as (a: { req: unknown }) => unknown expect(read({ req: req({ id: 1, collection: 'users', roles: ['editor'] }) })).toBe(false) expect(read({ req: req({ id: 1, collection: 'users', roles: ['admin'] }) })).toBe(true) diff --git a/test/secondFactorGuard.test.ts b/test/secondFactorGuard.test.ts index e63b3ac..7c452f9 100644 --- a/test/secondFactorGuard.test.ts +++ b/test/secondFactorGuard.test.ts @@ -10,7 +10,8 @@ import type { I18nConfig } from '../src/modules/i18n/types.js' import { adminOrSelfIn } from '../src/modules/access/access.js' import { isAdmin, staffCollectionSlugs, userMeetsRole } from '../src/modules/access/predicates.js' -import { guardPayloadAccess, guardTotpEndpoint, requireSecondFactor, secondFactorPassed } from '../src/modules/security/totp/secondFactor.js' +import { ensurePayloadGuarded, guardPayloadAccess, guardTotpEndpoint, requireSecondFactor, secondFactorPassed, watchPayloadConfig } from '../src/modules/security/totp/secondFactor.js' +import { buildVerifyLimit, clearVerifyLimits } from '../src/modules/security/totp/verifyLimit.js' import { ipalKit } from '../src/plugin.js' import { withTotpParts } from './helpers.js' @@ -76,7 +77,7 @@ describe('userMeetsRole: who is staff', () => { }) describe('adminOrSelfIn', () => { - const run = (fn: Access, user: unknown) => fn({ req: { user } } as never) + const run = (fn: Access, user: unknown) => fn({ req: { payload: { config: { admin: { user: 'users' } } }, user } } as never) test('"self" is an account of that collection only', () => { const access = adminOrSelfIn('users') expect(run(access, { id: 5, collection: 'users', roles: ['user'] })).toEqual({ id: { equals: 5 } }) @@ -97,6 +98,7 @@ describe('secondFactorPassed', () => { ['a user object without the fields the check knows (fail closed)', { collection: 'users' }, false], ['an unknown strategy name (fail closed)', { _strategy: 'two-factor', collection: 'users', hasTotp: true }, false], ['an account of another auth collection', { _strategy: 'local-jwt', collection: 'customers' }, true], + ['a user object that does not say its collection (fail closed)', { _strategy: 'totp', hasTotp: true }, false], ] test.each(cases)('%s', (_, user, expected) => { expect(secondFactorPassed({ payload, user })).toBe(expected) @@ -142,14 +144,35 @@ describe('ipalKit and the 2FA plugin', () => { expect((integrations.access!.read as (a: unknown) => unknown)({ req: { payload, user: verified } })).toBe(true) }) - test('onInit guards what a later plugin added; Payload\'s own collections are left alone', () => { + test('the sweep guards everything a later plugin or Payload itself added — no exception by name or prefix', () => { const late = { slug: 'late', access: {} as Record } + const prefixed = { slug: 'payload-vault', access: {} as Record } // a plugin's collection, e.g. payload-mcp-api-keys const internal = { slug: 'payload-preferences', access: {} as Record } - const payload = { config: { collections: [late, internal], custom: { ipal: { twoFactor: { collection: 'users' } } }, globals: [] } } as never - expect(guardPayloadAccess(payload)).toEqual(['late']) - expect((late.access.read as (a: unknown) => unknown)({ req: { payload, user: passwordOnly } })).toBe(false) - expect(internal.access.read).toBeUndefined() + const jobs = { access: {} as Record } + const payload = { config: { collections: [late, prefixed, internal], custom: { ipal: { twoFactor: { collection: 'users' } } }, globals: [{ slug: 'payload-jobs-stats' }], jobs } } as never + expect(guardPayloadAccess(payload)).toEqual(['late', 'payload-vault', 'payload-preferences', 'payload-jobs-stats', 'jobs']) + for (const entity of [late, prefixed, internal]) { + expect((entity.access.read as (a: unknown) => unknown)({ req: { payload, user: passwordOnly } })).toBe(false) + expect((entity.access.read as (a: unknown) => unknown)({ req: { payload, user: verified } })).toBe(true) + } + // the job queue's own rules (run / queue / cancel) + for (const op of ['run', 'queue', 'cancel']) { + expect((jobs.access[op] as (a: unknown) => unknown)({ req: { payload, user: passwordOnly } })).toBe(false) + expect((jobs.access[op] as (a: unknown) => unknown)({ req: { payload, user: verified } })).toBe(true) + } expect(guardPayloadAccess(payload)).toEqual([]) // nothing left to do the second time + expect(ensurePayloadGuarded(payload)).toEqual([]) + expect(ensurePayloadGuarded(payload)).toBeNull() // this config object was done + }) + + test('a config swapped onto the instance (dev reload) is adopted at once, before any request', () => { + const adopted: unknown[] = [] + const instance = { config: { name: 'first' } } as never as { config: { name: string } } + watchPayloadConfig(instance as never, (p) => adopted.push((p as never as { config: { name: string } }).config.name)) + instance.config = { name: 'second' } + expect(adopted).toEqual(['second']) + expect(instance.config.name).toBe('second') + expect({ ...instance }.config.name).toBe('second') // still an ordinary enumerable property to readers }) test('a 2FA plugin without the parts the guard relies on stops the start', async () => { @@ -210,6 +233,55 @@ describe('ipalKit and the 2FA plugin', () => { expect(await call('/admin/reset-user-totp', verified)).toBe(200) }) + test('verify attempts are limited per account, and the limit can be changed or switched off', async () => { + clearVerifyLimits() + const req = (id: unknown) => ({ i18n: undefined, payload: { logger: { warn: () => {} } }, user: { id, collection: 'users' } }) as never + const limit = buildVerifyLimit('users') // 5 in 10 minutes + for (let i = 0; i < 5; i++) {expect(limit(req(1))).toBeNull()} + const refused = limit(req(1))! + expect(refused.status).toBe(429) + expect(Number(refused.headers.get('retry-after'))).toBeGreaterThan(0) + expect(((await refused.json()) as { message: string }).message).toMatch(/Too many codes/) + expect(limit(req(2))).toBeNull() // another account is not affected + expect(limit({ ...(req(1) as object), user: null } as never)).toBeNull() // no session: the package refuses by itself + const two = buildVerifyLimit('admins', { max: 2, windowMinutes: 1 }) + expect([two(req(1)), two(req(1))]).toEqual([null, null]) + expect(two(req(1))!.status).toBe(429) + + // wired by default; twoFactor.verifyLimit: false leaves the package's endpoint as it is + const base = () => ({ collections: [], endpoints: [], secret: 'x' }) as unknown as Config + const withEndpoint = (o: { collection: string }) => (c: Config) => ({ ...withTotpParts(c, o.collection), endpoints: [...(c.endpoints ?? []), { handler: () => Response.json({ ok: false }), method: 'post' as const, path: '/verify-totp' }] }) + const call = async (config: Config, n: number) => { + const endpoint = config.endpoints!.find((e) => e.path === '/verify-totp')! + let last = 0 + for (let i = 0; i < n; i++) {last = (await endpoint.handler(req(77))).status} + return last + } + clearVerifyLimits() + expect(await call(await ipalKit({ i18n, twoFactor: { issuer: 'A', plugin: withEndpoint as never } })(base()), 6)).toBe(429) + clearVerifyLimits() + expect(await call(await ipalKit({ i18n, twoFactor: { issuer: 'A', plugin: withEndpoint as never, verifyLimit: false } })(base()), 8)).toBe(200) + }) + + test('staff collections outside the 2FA collection are named in a warning at start', async () => { + const config = await ipalKit({ access: { authCollection: 'users', staffCollections: ['partners'] }, i18n, twoFactor: { issuer: 'A', plugin: fakeTotp as never } })({ + ...twoAuth(), + admin: { user: 'users' }, + } as Config) + const warnings: string[] = [] + const payload = { + collections: {}, + config: { admin: { user: 'users' }, collections: [], custom: config.custom, globals: [] }, + count: () => ({ totalDocs: 0 }), + find: () => ({ docs: [] }), + findGlobal: () => ({}), + logger: { info: () => {}, warn: (m: string) => warnings.push(m) }, + updateGlobal: () => ({}), + } + await Promise.resolve(config.onInit!(payload as never)).catch(() => {}) // later onInit steps need a real database + expect(warnings.join('\n')).toMatch(/2FA covers "users" only\. Staff accounts of "partners"/) + }) + test('twoFactor: false — no guard, a password is enough (as documented)', async () => { const config = await ipalKit({ access: { authCollection: 'users' }, i18n, twoFactor: false })({ collections: [], secret: 'x' } as unknown as Config) const payload = payloadOf(config) diff --git a/test/securityHttp.test.ts b/test/securityHttp.test.ts index 5c9000f..b1ba6b8 100644 --- a/test/securityHttp.test.ts +++ b/test/securityHttp.test.ts @@ -15,7 +15,7 @@ import { afterAll, beforeAll, describe, expect, test, vi } from 'vitest' import { ipalKit } from '../src/plugin.js' import { buildTestConfig } from './helpers.js' -import { testDatabase } from './http/db.js' +import { numericIds, testDatabase } from './http/db.js' import { cookiesOf, startPayloadServer, type TestServer } from './http/server.js' import { totp } from './http/totp.js' @@ -28,7 +28,13 @@ const PASSWORD = 'a-long-test-password-1' /** A plugin the project lists AFTER ipalKit: its collection did not exist when ipalKit ran. */ const latePlugin: Plugin = (config: Config) => ({ ...config, - collections: [...(config.collections ?? []), { slug: 'late-notes', fields: [{ name: 'note', type: 'text' }] }], + collections: [ + ...(config.collections ?? []), + { slug: 'late-notes', fields: [{ name: 'note', type: 'text' }] }, + // A plugin may well call its collection `payload-…` (@payloadcms/plugin-mcp: `payload-mcp-api-keys`). + { slug: 'payload-vault', access: { read: ({ req }) => Boolean(req.user) }, fields: [{ name: 'secret', type: 'text' }] }, + ], + globals: [...(config.globals ?? []), { slug: 'late-settings', fields: [{ name: 'note', type: 'text' }] }], }) const projectCollections: CollectionConfig[] = [ @@ -114,10 +120,14 @@ beforeAll(async () => { payload = await getPayload({ config }) server = await startPayloadServer(config) + // The plugin's own and `late-notes`. Payload's built-in collections and the late plugin's `payload-vault` / + // `late-settings` have a describe of their own below (their rule is "any logged-in account", so the comparisons + // with an anonymous visitor do not apply to them). pluginCollections = payload.config.collections.map((c) => c.slug).filter((s) => !PROJECT_SLUGS.has(s) && !s.startsWith('payload-')) - pluginGlobals = payload.config.globals.map((g) => g.slug) + pluginGlobals = payload.config.globals.map((g) => g.slug).filter((slug) => slug !== 'late-settings') await payload.updateGlobal({ slug: 'site-integrations' as never, data: { smtpPassword: 'S3CRET' } as never }) + await payload.create({ collection: 'payload-vault' as never, data: { secret: 'VAULT' } as never }) const user = (email: string, extra: object) => payload.create({ collection: 'users' as never, data: { email, password: PASSWORD, roles: ['admin'], ...extra } as never }) await user('admin@example.com', { totpSecret: TOTP_SECRET }) @@ -346,7 +356,7 @@ describe("the 2FA package's endpoints accept accounts of the 2FA collection only const after = await secretOf('admin@example.com') expect(after.totpSecret).toBe(TOTP_SECRET) // the case this test is about: the two accounts really share an id (SQL adapters; on MongoDB ids never repeat) - expect(String(customer.user.id)).toBe(String(admin.id)) + if (numericIds()) {expect(String(customer.user.id)).toBe(String(admin.id))} // an account of yet another auth collection is refused the same way const member = await api('/setup-totp', sessions.member, { body: JSON.stringify({ secret: ATTACKER, token: totp(ATTACKER) }), method: 'POST' }) expect(member.status).toBe(403) @@ -382,16 +392,86 @@ describe('per-entity opt-out from the second factor', () => { }) }) +describe('no exception by name: a later plugin\'s `payload-…` collection is guarded like any other', () => { + test('REST (list, count, by id) and GraphQL refuse a password-only session; a verified one reads it', async () => { + for (const p of ['/payload-vault', '/payload-vault/count', '/globals/late-settings']) { + const res = await api(p, sessions.passwordOnly) + expect([p, res.status]).toEqual([p, 403]) + expect(await res.text()).not.toContain('VAULT') + } + const out = await gql(sessions.passwordOnly, '{ PayloadVaults { docs { secret } } }') + expect(out.errors?.length, JSON.stringify(out)).toBeGreaterThan(0) + expect(JSON.stringify(out)).not.toContain('VAULT') + const ok = await api('/payload-vault', sessions.verified) + expect(ok.status).toBe(200) + expect(await ok.text()).toContain('VAULT') + }) + + test("Payload's own collections answer a password-only session nothing either", async () => { + const own = payload.config.collections.map((c) => c.slug).filter((slug) => slug.startsWith('payload-') && slug !== 'payload-vault') + expect(own).toEqual(expect.arrayContaining(['payload-preferences', 'payload-locked-documents', 'payload-migrations'])) + const open: string[] = [] + for (const slug of own) { + const status = (await api(`/${slug}`, sessions.passwordOnly)).status + if (status === 200) {open.push(`${slug}: ${status}`)} + } + expect(open).toEqual([]) + }) +}) + +describe('the code cannot be guessed: verify attempts are limited per account', () => { + const GUESS_SECRET = 'ONSWG4TFORRW6ZDF' + let cookie: string + beforeAll(async () => { + await payload.create({ collection: 'users' as never, data: { email: 'guessed@example.com', password: PASSWORD, roles: ['editor'], totpSecret: GUESS_SECRET } as never }) + cookie = (await login('users', 'guessed@example.com')).cookies.join('; ') + }) + const verify = (token: string, headers: Record = { cookie }) => + fetch(`${server.url}/api/verify-totp`, { body: JSON.stringify({ token }), headers: { 'content-type': 'application/json', ...headers }, method: 'POST' }) + + test('five wrong codes are answered, the sixth attempt is refused — also with the right code', async () => { + for (let i = 0; i < 5; i++) { + const res = await verify('000000') + expect(res.status).toBe(200) + expect(((await res.json()) as { ok: boolean }).ok).toBe(false) + } + const sixth = await verify('000000') + expect(sixth.status).toBe(429) + expect(Number(sixth.headers.get('retry-after'))).toBeGreaterThan(0) + const right = await verify(totp(GUESS_SECRET)) + expect(right.status).toBe(429) + expect(right.headers.getSetCookie().join(';')).not.toContain('payload-totp') + expect((await fetch(`${server.url}/api/pages`, { headers: { cookie } })).status).toBe(403) + }) + + test('the limit is the account\'s alone: nobody without its password can use it, other accounts are not affected', async () => { + // someone without the password cannot count against the account: no session, or a session of another collection + for (let i = 0; i < 8; i++) { + await verify('000000', {}) + await verify('000000', sessions.customer.headers) + } + // another staff account still verifies + const other = await login('users', 'admin@example.com') + const ok = await verify(totp(TOTP_SECRET), { cookie: other.cookies.join('; ') }) + expect(((await ok.json()) as { ok: boolean }).ok).toBe(true) + }) +}) + // Last: it replaces the running config. describe('dev hot reload', () => { test('a freshly built config is guarded again, also what a later plugin added', async () => { // What Payload's reload() does to the instance: a newly built and sanitized config, no onInit. const fresh = await makeConfig() payload.config = fresh + // Before any HTTP request: the Local API meets the new config guarded already. + const passwordOnlyUser = { ...(await payload.find({ collection: 'users' as never, where: { email: { equals: 'admin@example.com' } } })).docs[0], _strategy: 'local-jwt', collection: 'users' } payload.collections = Object.fromEntries( fresh.collections.map((c) => [c.slug, { config: c, customIDType: payload.collections[c.slug as never]?.customIDType }]), ) as never payload.globals = { config: fresh.globals } + await expect(payload.find({ collection: 'late-notes' as never, overrideAccess: false, user: passwordOnlyUser })).rejects.toThrow() + await expect(payload.find({ collection: 'payload-vault' as never, overrideAccess: false, user: passwordOnlyUser })).rejects.toThrow() + await expect(payload.findGlobal({ slug: 'late-settings' as never, overrideAccess: false, user: passwordOnlyUser })).rejects.toThrow() expect((await api('/late-notes', sessions.passwordOnly)).status).toBe(403) expect((await api('/late-notes', sessions.passwordOnly, { body: '{}', method: 'POST' })).status).toBe(403) diff --git a/test/setup.ts b/test/setup.ts new file mode 100644 index 0000000..566eb30 --- /dev/null +++ b/test/setup.ts @@ -0,0 +1,12 @@ +import { beforeEach } from 'vitest' + +import { clearStaffRegistry } from '../src/modules/access/predicates.js' + +/** + * Role predicates called without `req.payload` use the staff collections of the configs built in this process — + * what every one of them agrees on. A test file builds many unrelated configs, so each test starts with none: + * a test that builds a config and then calls an access function with a bare `{ req: { user } }` sees that config. + */ +beforeEach(() => { + clearStaffRegistry() +}) diff --git a/vitest.config.js b/vitest.config.js index 5d5219b..9cf3326 100644 --- a/vitest.config.js +++ b/vitest.config.js @@ -19,6 +19,7 @@ export default defineConfig(() => { test: { environment: 'node', include: ['test/**/*.test.ts'], + setupFiles: ['./test/setup.ts'], hookTimeout: 30_000, testTimeout: 30_000, // Inlined so a test can replace `next/headers` (the package's cookie access) — test/http/server.ts.