Security review fixes: staff collection first everywhere, 2FA package endpoints guarded, per-entity opt-out, hot reload

F1: roles count only for accounts of a staff collection, in every exported
predicate and access builder (isAdmin, isEditor, hasMinimumRole, adminOnly,
adminOrEditor, requireRole, adminOrSelf, adminOrSelfIn, the Field variants,
the roles field) and first in userMeetsRole. An account of another auth
collection with its own roles: ['admin'] gets nothing. Staff collections:
admin.user, access.authCollection, access.staffCollections. Predicates take
req.payload as an optional last argument and otherwise use the staff
collections of the config ipalKit built in this process.

F2: every endpoint @clocklimited/payload-2fa registers answers accounts of
the 2FA collection only (setup-totp wrote the secret into the 2FA collection
under the caller's id, whatever collection the caller came from); remove and
the admin reset/remove endpoints also need the second factor.

F3: per-entity opt-out honoured, operation by operation: the package's
custom.totp.disableAccessWrapper and ipal-kit's custom.ipal.secondFactor
(passed on to the package); the package's global disableAccessWrapper too.

F4: a no-user auth strategy on the 2FA collection guards the live config at
the start of each request, so entities from plugins listed after ipalKit
stay guarded after a dev hot reload and with disableOnInit.

Tests through HTTP for all four; the 2FA tests now run on payload-2fa
3.0.0-beta.7 (what client sites use), a second file on beta.1 (alias), and
the HTTP files can run against Postgres (IPAL_TEST_POSTGRES_URI). Docs,
agent guide, skills and changelog updated; the not-yet-enrolled limitation
is stated plainly.

Co-Authored-By: Claude Fable 5.2 <[email protected]>
This commit is contained in:
Radosław Smoliński
2026-11-24 01:02:34 +01:00
co-authored by Claude Fable 5.2
parent 97ee1289aa
commit 32faaa5e30
30 changed files with 836 additions and 187 deletions
+35 -12
View File
@@ -20,23 +20,42 @@ once there are more than 20.
earlier version.** It needed a valid staff password. Now ipal-kit runs its own second-factor check on every
collection and global — whichever plugin added it and in whatever order — and on its endpoints
([security.md](./security.md) "What the second factor covers").
- **Accounts of a second auth collection are no longer staff.** `userMeetsRole` treated an account of any auth
collection without a `roles` field as staff. In a project with a visitor account collection (`customers`, a client
zone) such an account passed every staff check of the plugin, with the same reach as above; with open sign-up,
anyone could make one. In the injected auth collection, "only my own record" also matched an account of another
collection with the same numeric id (Postgres, SQLite). **Affects only projects with more than one auth
collection.** Now only accounts of the panel's login collection (plus `access.staffCollections`) can pass, and
the injected collection uses `adminOrSelfIn` ([access.md](./access.md#who-is-staff)).
- **Accounts of a second auth collection are no longer staff.** Roles, and the rule "no `roles` field = every
account passes", counted for an account of any auth collection. In a project with a visitor account collection
(`customers`, a client zone) such an account passed the plugin's staff checks, with the same reach as above —
every check when its collection had no `roles` field, and `isAdmin` / `adminOnly` / `requireRole` and the others
when it had a `roles` field of its own. With open sign-up, anyone could make one. In the injected auth
collection, "only my own record" also matched an account of another collection with the same numeric id
(Postgres, SQLite). **Affects only projects with more than one auth collection.** Now the staff-collection check
comes first in every predicate and access function: only accounts of the panel's login collection,
`access.authCollection` and `access.staffCollections` count, and the injected collection uses `adminOrSelfIn`
([access.md](./access.md#who-is-staff)).
- **The 2FA package's endpoints accept accounts of the 2FA collection only.** `@clocklimited/payload-2fa` (checked
in 3.0.0-beta.1 and beta.7) takes the logged-in account from any auth collection and writes the TOTP secret into
the 2FA collection under that account's id. With numeric ids (Postgres, SQLite) an account of another auth
collection could set the secret of the staff account with the same id; whoever knew that staff password then
passed 2FA, and the owner's authenticator stopped working. **Affects only projects with more than one auth
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").
- **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.
### 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.
- `twoFactor.guard: false`: ipal-kit's second-factor check off, the package's wrapper only (not recommended).
for the project's own access functions and endpoints. `isAdmin`, `isEditor` and `hasMinimumRole` take
`req.payload` as an optional last argument.
- 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).
### Requires project changes
- **Every site: upgrade and redeploy.** No config change for a site with one auth collection and
`@clocklimited/payload-2fa` 3.0.0-beta.1 to beta.7. `pnpm ipal:skills` afterwards.
`@clocklimited/payload-2fa` 3.0.0-beta.7 (tested: beta.1 and beta.7). `pnpm ipal:skills` afterwards.
- **Every site: no account without 2FA.** `pnpm exec ipal-doctor --url <site>` → accounts without 2FA must be 0;
have each such account set TOTP up now, or remove it.
- **Because the earlier behaviour left no trace** (there is no audit log), decide per site with the owner:
- change the **SMTP password** and the **Turnstile secret** stored in Site integrations when a staff password
may have been known to someone else (a reused or shared password, a former employee, a phishing report) — or
@@ -48,9 +67,13 @@ once there are more than 20.
is the client's decision.
- **A site with a second auth collection:** treat the points above as required, not optional. Set
`admin: { user: '<staff collection>' }` in `buildConfig`, use `adminOrSelfIn('<slug>')` in your own auth
collections, and if the second collection really is staff, name it in `access.staffCollections`.
collections, and if the second collection really is staff, name it in `access.staffCollections`. Roles no
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.
- **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. Own
`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
endpoints: add `secondFactorPassed(req)` or `userMeetsRole(req, role)`.
- **Startup stops with `[ipal] twoFactor: the injected 2FA plugin did not add …`:** the installed 2FA package is
not one the check recognises. Install a supported version; `twoFactor.guard: false` only as a stop-gap.
+44 -25
View File
@@ -67,35 +67,49 @@ keeps Payload's default rules — without roles all accounts are equal.
## Who is staff
**Staff collections** are the auth collections whose accounts work in the panel:
- the one the admin panel logs in with (`admin.user`; Payload's default is the **first** auth collection in the
list — set `admin: { user: 'users' }` yourself as soon as the project has two);
- the one that carries the plugin's roles (`access.authCollection`);
- the ones named in `access.staffCollections`.
An account of **any other auth collection** — `customers`, `members`, a client zone — is a visitor to the
plugin. **Nothing in the plugin counts a role for it**, also when its own collection has a `roles` field with
the value `admin`: not `userMeetsRole`, not `isAdmin` / `isEditor` / `hasMinimumRole`, not `adminOnly`,
`adminOrEditor`, `requireRole`, `adminOrSelf`, `adminOrSelfIn` or the `…Field` variants, not the `roles` field
itself. The staff-collection check always comes first.
The plugin's own staff features — Site integrations, the settings globals, form submissions, consent records,
stats, the cookie scanner, `/api/ipal/test-email` — check with `userMeetsRole(req, minimum)`. It passes when:
stats, the cookie scanner, `/api/ipal/test-email` — check with `userMeetsRole(req, minimum)`, in this order:
1. the account holds at least the role `minimum`; or
2. the account belongs to a **staff collection** that has **no `roles` field**. Then every account of that
collection passes, as in Payload's default (without roles all accounts are equal).
1. the account belongs to a staff collection;
2. with 2FA on: an account that has TOTP set up has entered the code in this session
([security.md](./security.md) → "What the second factor covers");
3. it holds at least the role `minimum` — **or** its collection has no `roles` field at all. Then every account
of that staff collection passes, as in Payload's default (without roles all accounts are equal).
**Staff collections** are the auth collection the admin panel logs in with (`admin.user`, by default the first
auth collection) and the ones named in `access.staffCollections`. An account of **any other auth collection** —
`customers`, `members`, a client zone — is a visitor to the plugin and never passes rule 2, with or without
the `access` option.
What follows:
With 2FA on, an account that has TOTP set up and has not entered the code in this session passes neither rule
([security.md](./security.md) → 2FA).
- **Without `access`** there is no `roles` field, so `isAdmin` always returns `false` and rule 2 keeps the
- **Without `access`** there is no `roles` field, so `isAdmin` always returns `false` and rule 3 keeps the
staff features reachable: every account of the panel collection is admin to the plugin. To narrow that
without roles: `globalOverrides` for the globals, `forms.formSubmissionOverrides` for submissions, or add
`access` to get roles.
- **A second staff collection** (e.g. `partners` who edit content): name it in
`access.staffCollections`. Without a `roles` field every partner then passes every staff check, admin ones
included. To tell them apart, add the field: `fields: [buildRolesField('editor')]` in that collection.
`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.
- **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: `forms.formSubmissionOverrides.access.read`, `globalOverrides`,
`collectionOverrides` of the module.
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.
- **A user object you build yourself** (Local API with `overrideAccess: false`, a custom auth strategy) must
carry `collection`: `{ ...doc, collection: 'users' }`. Payload's own strategies and `payload.auth()` set it. An
account without it is not staff.
> **Changed in the release after 1.16.3.** Before, rule 2 applied to the account's own collection, whatever it
> was: an account of a second auth collection without a `roles` field passed every staff check. A project
> with one auth collection sees no difference. A project that relied on a second collection being staff sets
> **Changed in the release after 1.16.3.** Before, a role or the "no roles field" rule counted for an account
> of any auth collection: an account of a second auth collection passed staff checks — every one when its
> collection had no `roles` field, and the matching ones when it had its own `roles` field. A project with one
> auth collection sees no difference. A project that relied on a second collection being staff sets
> `access.staffCollections`.
## Predicates (front end / hooks / access)
@@ -103,14 +117,19 @@ With 2FA on, an account that has TOTP set up and has not entered the code in thi
```ts
import { isAdmin, isEditor, hasMinimumRole, staffCollectionSlugs, userMeetsRole } from '@intecion/ipal-kit'
isAdmin(user) // admin?
isEditor(user) // editor or admin (hierarchy)
hasMinimumRole(user, 'editor') // at least editor
userMeetsRole(req, 'admin') // admin — or any account of a staff collection that has no roles field ("Who is staff")
staffCollectionSlugs(req.payload) // ['users', …]: admin.user + access.staffCollections
isAdmin(req.user, req.payload) // a staff account with the admin role
isEditor(req.user, req.payload) // editor or admin (hierarchy)
hasMinimumRole(req.user, 'editor', req.payload) // at least editor
userMeetsRole(req, 'admin') // the plugin's staff check: staff collection, second factor, role ("Who is staff")
staffCollectionSlugs(req.payload) // ['users', …]
```
They take a loosely typed user (like `req.user`) and read `roles` defensively.
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.
## Ready access functions
+16 -10
View File
@@ -203,7 +203,7 @@ site), **P** = a test in the panel. Full code: PROGRAMISTA.md §2.
| 10 | **Forms** | every form from a **seed** (`scripts/seed-form-*.ts`: fields, confirmation, mail to the company **and** confirmation to the customer, every language); a block with `<RenderForm>` + `formClasses.ts` (look, once); `actions.ts` = `createSubmitAction({ getCachedPayload, headers })`; `forms: {…}` in `ipalKit`; `email: mailAdapter()` | `RenderForm` (`/rsc`), `createSubmitAction`, `mailAdapter` | A, P |
| 11 | **Turnstile** | `<SiteProviders>` in `[locale]/layout.tsx` (wires `TurnstileProvider` with the key from the panel); `RenderForm` renders the widget; keys in Site integrations | `SiteProviders`, `getTurnstileConfig`, `TurnstileProvider` | A, P |
| 12 | Consent + analytics | Consent Mode: `'advanced'` (default — the Google tag loads at once with every signal `denied`) or `'basic'` (`<SiteProviders analytics={{ consentMode: 'basic' }}>` — no request to Google before consent; a client who wants zero requests), the choice goes to "Project decisions"; `ipalKit({ consentLog: true })` (without it the `/api/ipal/consent` endpoint does not exist) + `<SiteProviders logEndpoint="/api/ipal/consent" banner={<CookieBanner equalChoice settings="detailed" />}>` (ConsentProvider, banner, CookieButton, Analytics in the right order); settings window mode (`settings`: `inline` / `modal` / `detailed`) per the design, brief is silent → `detailed`, the decision goes to "Project decisions"; tool IDs in the panel; the cookie list from a scan (`cookieScanner: true` → *Cookie review* → **Scan cookies** → *Approve cookies* → **Approve and add**; or cookie-scan → import) — feeds `<CookieTable>` on the policy page **and** the lists in the `detailed` window; Cookies → Settings window → Cookie list headings in every language | consent.md, analytics.md | A, `ipal-consent-check` |
| 13 | Security | `buildSecurityHeaders` in `next.config.ts`; `withPayload(withSecurityConfig(nextConfig))` (no `X-Powered-By`); CSP: `buildSecurityHeaders({ csp: { mode: 'report-only', reportUri: '/api/csp-report', … } })` + `buildAdminCspHeaders` on `/admin/:path*` + `src/app/api/csp-report/route.ts` (`createCspReportRoute`) → read the reports → `mode: 'enforce'`; `twoFactor: { issuer, plugin: payloadTotp }` + `generate:importmap` (`TotpRedirectProvider`; check: a new admin lands on `/admin/setup-totp?back=%2Fadmin` with the QR, no reloading; a login with the password only gets `403` from `/api/globals/site-integrations` and `/api/form-submissions` — security.md "What the second factor covers"); own endpoints: `secondFactorPassed(req)` / `userMeetsRole(req, role)`; `IPAL_IP_HEADER` in production | security.md, forms.md | A |
| 13 | Security | `buildSecurityHeaders` in `next.config.ts`; `withPayload(withSecurityConfig(nextConfig))` (no `X-Powered-By`); CSP: `buildSecurityHeaders({ csp: { mode: 'report-only', reportUri: '/api/csp-report', … } })` + `buildAdminCspHeaders` on `/admin/:path*` + `src/app/api/csp-report/route.ts` (`createCspReportRoute`) → read the reports → `mode: 'enforce'`; `twoFactor: { issuer, plugin: payloadTotp }` + `generate:importmap` (`TotpRedirectProvider`; check: a new admin lands on `/admin/setup-totp?back=%2Fadmin` with the QR, no reloading; a login with the password only gets `403` from `/api/globals/site-integrations` and `/api/form-submissions` — security.md "What the second factor covers"); own endpoints: `secondFactorPassed(req)` / `userMeetsRole(req, role)`; **set 2FA up right after creating an account** — until then its password alone opens everything its role allows; `ipal-doctor --url` must report 0 accounts without 2FA; `IPAL_IP_HEADER` in production | security.md, forms.md | A |
| 14 | Operations | `src/app/api/health/route.ts` (`healthRoute`); `src/instrumentation.ts` with `assertEnv(ipalEnvRules({ storage: true, ipHeader: true }))`; staging with `IPAL_NOINDEX=1`; smoke tests (§8a) | `healthRoute`, `assertEnv`, `ipalEnvRules` | A |
| 15 | System pages | Site settings → System pages: homepage, 404, privacy policy, cookies; legal links in the footer by role (`getSystemLinks(locale)`) | `getSystemLinks`, `getSystemPagePath`, `getNotFoundPage` | P |
| 16 | **Nothing hardcoded** | every text, link, image, file, company data from the panel; domains and keys from `.env` (§2) | — | A, P |
@@ -584,14 +584,18 @@ the plugin adds roles and 2FA to it).
for visitors. Then, all four:
1. `admin: { user: 'users' }` in `buildConfig` — Payload otherwise logs the panel in with the FIRST auth
collection in the list, and 2FA and the staff checks follow the panel collection.
2. Its accounts are visitors to the plugin: they pass none of its staff checks (`userMeetsRole`) — settings
globals, Site integrations, form submissions, consent records, stats, cookie scanner. Give them exactly
what they need with your own `access` rules; 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").
2. Its accounts are visitors to the plugin: no role counts for them (also a `roles` field of their own with
the value `admin`) and they pass none of its checks — `userMeetsRole`, `isAdmin`, `adminOnly`,
`adminOrEditor`, `requireRole`, the settings globals, Site integrations, form submissions, consent records,
stats, cookie scanner. Give them exactly what they need with your own `access` rules that check
`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('<its slug>')`, not `adminOrSelf`, for "only my own record".
4. Check: log in as such an account (`POST /api/customers/login`), then `GET /api/globals/site-integrations`
and `GET /api/form-submissions` with its token must answer `403`.
4. 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`,
`GET /api/form-submissions` and `GET /api/users` with its token must answer `403`, and so must
`POST /api/setup-totp`.
**NEVER:** a second `media`, `daneFirmy`/`settings`/
`navigation`/`footer` as collections (they are globals), FAQ/hero/features as collections
@@ -1053,7 +1057,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)`, `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), `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**
@@ -1159,7 +1163,9 @@ add missing hosts with flags / `extra`; (3) change `mode` to `'enforce'` in both
| Injected `users`: admin manages everyone, others only themselves | — | `access.authAccess` (your keys win); your own `users` collection wins whole |
| 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 | `twoFactor.guard: false` (not recommended: the package's wrapper only) | `requireSecondFactor` / `secondFactorPassed` in your own access functions and endpoints |
| 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 |
| 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`) |
| No client IP = one shared `unknown-ip` bucket at 20× the limit | `setUnknownIpFactor(0)` (only with a limiter in front) | `setUnknownIpFactor(n)`; `UNKNOWN_IP_FACTOR` |
| Turnstile token domain not checked | (default) | `createSubmitAction({ turnstileHostnames })`, `verifyTurnstile({ hostnames })` — leave empty in dev |
+3 -3
View File
@@ -34,9 +34,9 @@ through this procedure. Ask only when you are missing something you cannot get y
### Build / TypeScript
| Symptom | Cause | Fix |
|---|---|---|
| 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 (supported: 3.0.0-beta.1 to 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 })`, or (server-only code that needs no access check) leave `overrideAccess` at its default |
| an account of a second auth collection (`customers`) gets `403` from a settings global, submissions or `/api/ipal/*` after an upgrade | by design since the release after 1.16.3: only staff collections pass `userMeetsRole` | write the one rule it needs (`formSubmissionOverrides`, `globalOverrides`, `collectionOverrides`); a second STAFF collection: `access.staffCollections` (access.md "Who is staff") |
| 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") |
| `TS2307 next/navigation` in the plugin's `dist` | import without `.js` in the plugin client (NodeNext) | **ipal-kit bug** → plugin gap; the plugin imports `'next/navigation.js'` |
| `TS2307 @payloadcms/storage-s3` | package missing when using `buildR2Storage` | `pnpm add @payloadcms/storage-s3` + `buildR2Storage(['media'], { s3Storage })` |
| `does not provide an export named X` / `X is not a function` | symbol not exported from the entry point, or wrong subpath (`/client` vs root vs `/server` vs `/rsc`) | `docs/README.md` → the right import; missing from every entry → **ipal-kit bug** (export) |
+2 -2
View File
@@ -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 for `userMeetsRole`, besides the panel's login collection (`admin.user`); 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); 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)/<route>/` itself and adds the route to the proxy matcher (security.md) |
| `twoFactor` | **none = error** | `@clocklimited/payload-2fa` with `forceSetup: true` (TOTP enforced, also checked in the API) | `twoFactor: false` (discouraged); omitting the option throws `[ipal] twoFactor.issuer is required` |
| `twoFactor.issuer` | — (required) | name in the authenticator app | — |
@@ -38,7 +38,7 @@ description: Complete map of everything @intecion/ipal-kit provides — every ip
| `twoFactor.collectionSlug` | the panel's login collection (`admin.user`, else the first auth collection) | collection with 2FA; startup fails with `[ipal] twoFactor…` when it is not an auth collection or differs from `admin.user` | point it at the login collection |
| `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.<lang>.totpPlugin.<key>` (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` | `false` = the package's wrapper only (the plugin's own data then opens to a password without the code; not recommended) |
| `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.<op>`; `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.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 | — |
@@ -59,11 +59,11 @@ 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)` | `@intecion/ipal-kit` | Predicate → `boolean`: whether the user has a role ≥ `minimum` (reads `user.roles` safely). For your own access logic/hooks. |
| `isAdmin(user)` | `@intecion/ipal-kit` | Predicate → `boolean`: `admin` role. |
| `isEditor(user)` | `@intecion/ipal-kit` | Predicate → `boolean`: `editor` or higher. |
| `userMeetsRole(req, minimum)` | `@intecion/ipal-kit` | Predicate → `boolean` with `req` (`{ payload, user }`): role ≥ `minimum`, **or** any account of a **staff collection** (the panel's login collection `admin.user`, plus `access.staffCollections`) that has no `roles` field (the project omitted `access`). An account of any other auth collection never passes without a role. With 2FA on it also requires the second factor (`secondFactorPassed`). 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 `userMeetsRole` accepts — `admin.user` plus `access.staffCollections`. |
| `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. |
| `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. |
| `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. |
@@ -586,7 +586,7 @@ Server only (`pnpm payload run`); never import it from client code, the Payload
| `buildSecurityHeaders({ hsts?, csp?, additional?, coop?, frameOptions?, permissionsPolicy?, referrerPolicy?, … })` | `@intecion/ipal-kit` | Returns `SecurityHeader[]` (HSTS, X-Frame-Options, nosniff, Referrer-Policy, Permissions-Policy, COOP; with `IPAL_NOINDEX` also `X-Robots-Tag`) for `headers()` in `next.config.ts`. `csp` = `buildCsp` args → the CSP header (+ `Reporting-Endpoints` with `reportUri`); off by default. `additional` overrides by key. |
| `withSecurityConfig(nextConfig, { hidePoweredBy? })` | `@intecion/ipal-kit` | Next config wrapper: `poweredByHeader: false` + drops `X-Powered-By` from `headers()` (Next's "Next.js" and withPayload's "Next.js, Payload"). `withPayload(withSecurityConfig(nextConfig))`; `hidePoweredBy: false` = no change. |
| `secondFactorPassed(req)` | `@intecion/ipal-kit` | `boolean` with `req` (`{ payload, user }`): `false` only for an account of the 2FA collection that has TOTP set up and has not entered the code in this session (password only). `true` for a full login, an API key, an account that has not set TOTP up yet, accounts of other auth collections, no user, and with `twoFactor: false`. Guard your own endpoints with it: `if (!req.user \|\| !secondFactorPassed(req)) return 403`. |
| `requireSecondFactor(access?)` | `@intecion/ipal-kit` | Wraps an `Access` function: refused while the second factor is owed, otherwise the function itself (Payload's default "logged in" when none). ipalKit applies it to every collection and global in the config (and, in `onInit`, to those added by plugins listed after it); use it for access functions that are not part of the config. Wrapping twice is harmless. |
| `requireSecondFactor(access?)` | `@intecion/ipal-kit` | Wraps an `Access` function: refused while the second factor is owed, otherwise the function itself (Payload's default "logged in" when none). ipalKit applies it to every collection and global in the config, and to those added by plugins listed after it (in `onInit` and at the start of the first request, so also after a dev hot reload); use it for access functions that are not part of the config. Per-entity opt-out: `custom.ipal.secondFactor: false \| { read: false }` or the package's `custom.totp.disableAccessWrapper`. Wrapping twice is harmless. |
| `totpRedirectTarget({ adminRoute, forceSetup?, pathname, user, excludePaths? })`, `totpAdminPath(adminRoute, path)` | `@intecion/ipal-kit` | The 2FA redirect rules as pure functions: the setup / verify URL (with `back`) to send this user to, or `null` (no path, api key, already on a TOTP screen or logout). For an own `twoFactor.provider`. Types `TotpRedirectArgs`, `TotpUser` |
| `buildCsp({ mode?, reportUri?, reportGroup?, r2Url?, analytics?, metaPixel?, linkedIn?, tiktok?, clarity?, turnstile?, youtube?, googleMaps?, nonce?, strictDynamic?, dev?, extra?, override? })` | `@intecion/ipal-kit` | Returns `{ key, value }` with a hardened CSP (`base-uri`, `object-src`, `frame-ancestors`, `form-action`) + sources for the enabled integrations. `mode: 'report-only'` → `…-Report-Only` (start here), `'enforce'` later. `extra` adds to any directive, `override` replaces / drops one (`null`). `dev` (default `NODE_ENV === 'development'`) adds `'unsafe-eval'`. `nonce` → `'nonce-…' 'strict-dynamic'`. |
| `buildCspHeaders(args)` | `@intecion/ipal-kit` | `[csp, Reporting-Endpoints]` (the second only with `reportUri`). |
+4 -1
View File
@@ -224,8 +224,11 @@ 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").
**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
accounts pass none of the plugin's staff checks; use `adminOrSelfIn('<slug>')` in every auth collection; a second
accounts pass none of the plugin's checks and no role counts for them (not even their own `roles: ['admin']`);
a field that grants rights is never writable at sign-up; use `adminOrSelfIn('<slug>')` in every auth collection; a second
collection of STAFF goes in `access.staffCollections` (access.md "Who is staff"). Check: that account's token
gets `403` from `/api/globals/site-integrations` and `/api/form-submissions`.
- The `site-settings`, `site-integrations`, `cookie-settings`, `notifications` globals (write: editor+; Site
+11 -6
View File
@@ -331,22 +331,27 @@ recommended, not required (the plugin's peer range stays `^3.90.2`):**
**→ the release after 1.16.3 (PROGRAMISTA §6, item 65; security fixes: 2FA coverage and staff checks) — required
for every site:**
1. Update the package, `pnpm install`, `pnpm ipal:skills`, build, redeploy on Coolify. No migration, no config
change for a site with one auth collection. `pnpm ls @clocklimited/payload-2fa` must show 3.0.0-beta.1 to beta.7;
change for a site with one auth collection. `pnpm ls @clocklimited/payload-2fa` should show 3.0.0-beta.7 (tested: beta.1 and beta.7);
another version may stop startup with `[ipal] twoFactor: the injected 2FA plugin did not add …`.
2. `grep -rn "auth:" src/collections` — more than one auth collection? Then: `admin: { user: '<staff slug>' }` in
`buildConfig`; `adminOrSelfIn('<slug>')` instead of `adminOrSelf` in each; `access.staffCollections` only when
the second collection is staff (access.md "Who is staff"). Never list a visitor collection there.
the second collection is staff (access.md "Who is staff"). Never list a visitor collection there. Roles now
count only for accounts of a staff collection: code that relied on `isAdmin` / `adminOnly` for accounts of
another collection needs its own rule (`req.user.collection === '…'`).
3. `grep -rn "overrideAccess: false" src` — a call on a plugin collection or global (`form-submissions`, `forms`,
`consent-records`, `stats-visits`, `cookie-review`, the settings globals) must pass the `user` from
`payload.auth({ headers })`. Own endpoints that check `req.user`: add `secondFactorPassed(req)` or use
`userMeetsRole(req, role)`.
4. Tell the owner what the CHANGELOG entry says under "Requires project changes" and agree on it: new SMTP
`payload.auth({ headers })`; a user object built by hand needs `collection: '<staff slug>'` 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)`.
4. `pnpm exec ipal-doctor --url <site>` (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
password and Turnstile secret, a look through Site settings, Site integrations and each form's Emails tab.
Do not change those values yourself without that decision.
**Check:** with 2FA on, log in over the API with the password only (security.md → "What the second factor covers" →
Check) → `403` from `/api/globals/site-integrations`, `/api/form-submissions`, `/api/users`; log in fully in the
panel → Site integrations and a form submission open, a setting saves. With a second auth collection: its token
gets `403` from the same addresses.
gets `403` from the same addresses and from `POST /api/setup-totp`.
## 2. Inventory (no code changes)
**What changed for projects** between your old and new plugin version is exactly the reference site's diff —
+1 -1
View File
@@ -672,7 +672,7 @@ Do one item at a time, build, check. Order by importance:
| 62 | **1.16.1** — `pnpm dev` warns "Next.js 16.4.3 is affected by a known security vulnerability"; ipal-doctor `next-min` error below 16.4.5 (GHSA-mfr8-8qww-v76h) | `pnpm add [email protected] [email protected]`, `rm -rf .next`, build, commit the lockfile, redeploy on Coolify; `pnpm ipal:skills`; no option, migration or import map change | CHANGELOG 1.16.1, AGENT.md §4 item 11 |
| 63 | **1.16.2** — `pnpm audit --prod` shows `mongoose` (critical, via `@payloadcms/db-mongodb`) or `happy-dom` (high, via `@payloadcms/richtext-lexical`); ipal-doctor `transitive-min` | `pnpm.overrides`: `"mongoose@>=8 <8.24.7": "~8.24.10"` (MongoDB sites) and `"happy-dom@<21.0.4": "^21.0.4"`; `pnpm install`, build, commit the lockfile, redeploy on Coolify; `pnpm ipal:skills`; no migration | CHANGELOG 1.16.2, AGENT.md §4 item 12 |
| 64 | **1.16.3** — the reference site and the starter run Payload 3.94.1; the site is still on 3.90–3.93, or `node -v` (locally or in the Coolify app's Terminal) is below 22.23.5 | Recommended, not required (the plugin still accepts `^3.90.2`). First make sure Node is 22.23.5 or later everywhere, Coolify included (Nixpacks picks the patch: check `node -v`, update Coolify if lower). Then every `payload` / `@payloadcms/*` 3.94.1 (in `dependencies` and `pnpm.overrides`), `react` / `react-dom` 19.3.1, `"engines": { "node": ">=22.23.5 <23" }`; overrides: keep `dompurify` and `happy-dom`, drop `mongoose`, `undici` and `graphql-scalars`; `pnpm install`, `generate:types`, `generate:importmap`, `rm -rf .next`, build, redeploy; Postgres/SQLite: `migrate:create`; `pnpm ipal:skills` | CHANGELOG 1.16.3, AGENT.md §4 items 11–12, ipal-upgrade "Every upgrade — Payload" |
| 65 | **the release after 1.16.3 — security** — with 2FA on, a login with the password only gets `200` from `/api/globals/site-integrations` or `/api/form-submissions`; or the project has a second auth collection (`customers`) | Upgrade and redeploy (no config change with one auth collection). With the owner: change the SMTP password and the Turnstile secret, review Site settings / Site integrations / each form's Emails tab for values nobody set. Second auth collection: `admin: { user }` in `buildConfig`, `adminOrSelfIn('<slug>')`, `access.staffCollections` only for a second STAFF collection. Own endpoints: `secondFactorPassed(req)`; own `overrideAccess: false` calls: `user` from `payload.auth()`. `pnpm ipal:skills`; no migration | CHANGELOG "Unreleased — security fixes", security.md "What the second factor covers", access.md "Who is staff" |
| 65 | **the release after 1.16.3 — security** — with 2FA on, a login with the password only gets `200` from `/api/globals/site-integrations` or `/api/form-submissions`; or the project has a second auth collection (`customers`) | Upgrade and redeploy (no config change with one auth collection). With the owner: change the SMTP password and the Turnstile secret, review Site settings / Site integrations / each form's Emails tab for values nobody set. Second auth collection: `admin: { user }` in `buildConfig`, `adminOrSelfIn('<slug>')`, `access.staffCollections` only for a second STAFF collection. Every account must have 2FA set up (`ipal-doctor --url` → 0 without). Own endpoints: `secondFactorPassed(req)`; own `overrideAccess: false` calls: `user` from `payload.auth()`. `pnpm ipal:skills`; no migration | CHANGELOG "Unreleased — security fixes", security.md "What the second factor covers", access.md "Who is staff" |
After updating the package: `pnpm ipal:skills` (new skill versions), `pnpm payload generate:importmap`, `rm -rf .next`, restart dev, grep for the new symbol in
`node_modules/@intecion/ipal-kit/dist`.
+48 -8
View File
@@ -404,7 +404,9 @@ 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 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
@@ -416,6 +418,38 @@ Everything else is refused, including a user object the check does not recognise
collections, anonymous visitors, bearer-token routes (`/api/ipal/doctor`, the cookie-crawl callback, MCP) and
the Local API with `overrideAccess: true` (the default) are not affected.
> **Until an account has set TOTP up, its password alone opens everything its role allows** — Site
> integrations with the SMTP password included. Enforced setup is a redirect in the panel; over the API such an
> account is an ordinary logged-in account (it has to be, or it could not set TOTP up). So: **set 2FA up right
> after an account is created** — create the account, log in as it, scan the code, in one sitting — and never
> leave an invited account waiting. `ipal-doctor --url` reports the number of accounts without 2FA
> (`2fa`, deep check); it must be 0.
**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:
```ts
// the 2FA package's own key — it leaves the operation unwrapped, and so does ipal-kit
{ slug: 'notices', custom: { totp: { disableAccessWrapper: { read: true } } }, … }
// ipal-kit's key — the same, and it also works for entities the package never sees
{ slug: 'notices', custom: { ipal: { secondFactor: { read: false } } }, … } // or secondFactor: false = every operation
```
Operations: `create`, `delete`, `read`, `readVersions`, `unlock`, `update` (collections); `read`, `readDrafts`,
`readVersions`, `update` (globals). For one of the plugin's own globals set it through `globalOverrides`
(`{ notifications: { custom: { ipal: { secondFactor: { read: false } } } } }`) — and note that the plugin's
staff rules (`userMeetsRole`) ask for the second factor themselves, so also give that operation your own
`access` function there. `disableAccessWrapper: true` passed to the package's factory turns all access
wrapping off, ipal-kit's included; the endpoints stay guarded.
**The 2FA package's endpoints.** The package takes `req.user` from whatever auth collection it comes and then
acts on the 2FA collection by id: `/api/setup-totp` writes the TOTP secret under the **caller's** id. With
numeric ids (Postgres, SQLite) an account of another auth collection could therefore set the secret of the
staff account that has the same id, and whoever knew that staff password then passed 2FA. ipalKit wraps every
endpoint the package registers: a logged-in account of another collection gets `403`; remove and the admin
reset / remove endpoints also need the second factor, so a password alone cannot reset TOTP and enrol again.
This guard is on whenever 2FA is on, also with `twoFactor.guard: false`.
Two things follow for project code:
- `payload.find({ …, user, overrideAccess: false })` on a plugin collection needs a `user` that came from
@@ -438,7 +472,7 @@ access: { read: requireSecondFactor(({ req }) => isAdmin(req.user)) }
**Fails closed.** At startup ipalKit checks that the injected 2FA plugin added what the check reads (the
`totpSecret` and `hasTotp` fields and the `totp` auth strategy on the 2FA collection). When it did not — a
package version with another shape — startup stops with `[ipal] twoFactor: the injected 2FA plugin did not
add …`. Supported: `@clocklimited/payload-2fa` 3.0.0-beta.1 to beta.7. `twoFactor.guard: false` switches
add …`. Tested with `@clocklimited/payload-2fa` 3.0.0-beta.1 and 3.0.0-beta.7 (the versions in between are not run in the plugin's tests). `twoFactor.guard: false` switches
ipal-kit's check off and leaves the package's wrapper alone; the plugin's own data is then open to a password
without the code again, so use it only to get a site started while the package is being sorted out.
@@ -525,7 +559,10 @@ show the QR code. `back=null` or a page that keeps reloading means the import ma
An admin can reset another user's 2FA (when they lose their phone) — through
`adminManageAccess` in the @clocklimited configuration. ipalKit passes it only `collection`,
`forceSetup` and `issuer`; pass other options by wrapping the injected factory:
`plugin: (opts) => payloadTotp({ ...opts, adminManageAccess: ({ req }) => isAdmin(req.user) })`.
`plugin: (opts) => payloadTotp({ ...opts, adminManageAccess: ({ req }) => isAdmin(req.user, req.payload) })`.
ipal-kit's guard on those endpoints adds the rest: the caller must be an account of the 2FA collection that has
passed the second factor itself. After a reset the account is "not set up" again — have its owner set TOTP up
at once (see the note above).
### Why @clocklimited and not another one
@@ -549,12 +586,14 @@ data access, not just the UI — for what is in the config when it runs; ipal-ki
## The release after 1.16.3 — two access fixes
- **Staff checks and a second auth collection.** `userMeetsRole` treated an account of any auth collection
without a `roles` field as staff — a `customers` account passed every check of the plugin, admin ones
included. Now only accounts of a staff collection can pass: the panel's login collection plus
`access.staffCollections` ([access.md](./access.md#who-is-staff)). The injected auth collection uses
`adminOrSelfIn(slug)`, so an account of another collection with the same numeric id no longer counts as "self".
- **Staff checks and a second auth collection.** Roles and the "no roles field" rule counted for an account of
any auth collection — a `customers` account passed the plugin's staff checks, and with its own `roles` field
also `isAdmin`, `adminOnly` and the rest. Now the staff-collection check comes first everywhere: the panel's
login collection, `access.authCollection` and `access.staffCollections`
([access.md](./access.md#who-is-staff)). The injected auth collection uses `adminOrSelfIn(slug)`, so an
account of another collection with the same numeric id no longer counts as "self".
- **2FA and the plugin's own data.** See "What the second factor covers" above.
- **The 2FA package's endpoints** accept accounts of the 2FA collection only ("The 2FA package's endpoints").
- After upgrading: [PROGRAMISTA.md](./dev/PROGRAMISTA.md) upgrade table, and the CHANGELOG entry of that release.
## Form files (`forms.attachments`)
@@ -591,7 +630,8 @@ size while reading, content signature, container and macro checks, an optional `
## Turn off, override, extend
- **2FA check:** `twoFactor.guard: false` turns ipal-kit's own second-factor check off (not recommended);
- **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.
- **Turn off:** headers — do not call `buildSecurityHeaders`, or `null` / `false` per header (`frameOptions`,
`referrerPolicy`, `permissionsPolicy`, `coop`), `hsts: false`; CSP — leave out `csp` (the default);
+2
View File
@@ -149,6 +149,7 @@
"react": "^19.0.0"
},
"devDependencies": {
"@clocklimited/payload-2fa": "3.0.0-beta.7",
"@eslint/eslintrc": "^3.3.7",
"@payloadcms/db-postgres": "3.94.1",
"@payloadcms/db-sqlite": "3.94.1",
@@ -173,6 +174,7 @@
"next": "16.4.6",
"open": "^11.0.4",
"payload": "3.94.1",
"payload-2fa-beta1": "npm:@clocklimited/[email protected]",
"prettier": "^3.10.1",
"qs-esm": "8.0.2",
"react": "19.3.1",
+25 -3
View File
@@ -19,9 +19,6 @@ importers:
.:
dependencies:
'@clocklimited/payload-2fa':
specifier: ^3.0.0-0
version: 3.0.0-beta.1(@payloadcms/[email protected](@types/[email protected])([email protected])([email protected])([email protected](@babel/[email protected])(@playwright/[email protected])(@types/[email protected])([email protected]([email protected]))([email protected])([email protected]))([email protected]([email protected])([email protected]))([email protected]([email protected]))([email protected])([email protected]))(@payloadcms/[email protected])(@payloadcms/[email protected](@types/[email protected])([email protected])([email protected](@babel/[email protected])(@playwright/[email protected])(@types/[email protected])([email protected]([email protected]))([email protected])([email protected]))([email protected]([email protected])([email protected]))([email protected]([email protected]))([email protected])([email protected]))([email protected]([email protected])([email protected]))
'@payloadcms/storage-s3':
specifier: ^3.90.2
version: 3.94.1(@types/[email protected])([email protected])([email protected](@babel/[email protected])(@playwright/[email protected])(@types/[email protected])([email protected]([email protected]))([email protected])([email protected]))([email protected]([email protected])([email protected]))([email protected]([email protected]))([email protected])([email protected])
@@ -41,6 +38,9 @@ importers:
specifier: 1.6.9
version: 1.6.9
devDependencies:
'@clocklimited/payload-2fa':
specifier: 3.0.0-beta.7
version: 3.0.0-beta.7(@payloadcms/[email protected](@types/[email protected])([email protected])([email protected])([email protected](@babel/[email protected])(@playwright/[email protected])(@types/[email protected])([email protected]([email protected]))([email protected])([email protected]))([email protected]([email protected])([email protected]))([email protected]([email protected]))([email protected])([email protected]))(@payloadcms/[email protected])(@payloadcms/[email protected](@types/[email protected])([email protected])([email protected](@babel/[email protected])(@playwright/[email protected])(@types/[email protected])([email protected]([email protected]))([email protected])([email protected]))([email protected]([email protected])([email protected]))([email protected]([email protected]))([email protected])([email protected]))([email protected]([email protected])([email protected]))
'@eslint/eslintrc':
specifier: ^3.3.7
version: 3.3.7
@@ -113,6 +113,9 @@ importers:
payload:
specifier: 3.94.1
version: 3.94.1([email protected])([email protected])
payload-2fa-beta1:
specifier: npm:@clocklimited/[email protected]
version: '@clocklimited/[email protected](@payloadcms/[email protected](@types/[email protected])([email protected])([email protected])([email protected](@babel/[email protected])(@playwright/[email protected])(@types/[email protected])([email protected]([email protected]))([email protected])([email protected]))([email protected]([email protected])([email protected]))([email protected]([email protected]))([email protected])([email protected]))(@payloadcms/[email protected])(@payloadcms/[email protected](@types/[email protected])([email protected])([email protected](@babel/[email protected])(@playwright/[email protected])(@types/[email protected])([email protected]([email protected]))([email protected])([email protected]))([email protected]([email protected])([email protected]))([email protected]([email protected]))([email protected])([email protected]))([email protected]([email protected])([email protected]))'
prettier:
specifier: ^3.10.1
version: 3.10.1
@@ -318,6 +321,15 @@ packages:
'@payloadcms/ui': ^3.29.0
payload: ^3.29.0
'@clocklimited/[email protected]':
resolution: {integrity: sha512-UIeNhw6XyVBCdIKQdcO3TCMd8BJRB7LRCPxoPU+YU0Fu+9CO+Lk+Rmxkws+5tjXunccKO05nz5oq5l2nH2eJKg==}
engines: {node: ^18.20.2 || >=20.9.0, pnpm: ^10}
peerDependencies:
'@payloadcms/next': ^3.29.0
'@payloadcms/translations': ^3.29.0
'@payloadcms/ui': ^3.29.0
payload: ^3.29.0
'@date-fns/[email protected]':
resolution: {integrity: sha512-LBrd7MiJZ9McsOgxqWX7AaxrDjcFVjWH/tIKJd7pnR7McaslGYOP1QmmiBXdJH/H/yLCT+rcQ7FaPBUxRGUtrg==}
@@ -6308,6 +6320,16 @@ snapshots:
payload: 3.94.1([email protected])([email protected])
qrcode: 1.5.4
'@clocklimited/[email protected](@payloadcms/[email protected](@types/[email protected])([email protected])([email protected])([email protected](@babel/[email protected])(@playwright/[email protected])(@types/[email protected])([email protected]([email protected]))([email protected])([email protected]))([email protected]([email protected])([email protected]))([email protected]([email protected]))([email protected])([email protected]))(@payloadcms/[email protected])(@payloadcms/[email protected](@types/[email protected])([email protected])([email protected](@babel/[email protected])(@playwright/[email protected])(@types/[email protected])([email protected]([email protected]))([email protected])([email protected]))([email protected]([email protected])([email protected]))([email protected]([email protected]))([email protected])([email protected]))([email protected]([email protected])([email protected]))':
dependencies:
'@payloadcms/next': 3.94.1(@types/[email protected])([email protected])([email protected])([email protected](@babel/[email protected])(@playwright/[email protected])(@types/[email protected])([email protected]([email protected]))([email protected])([email protected]))([email protected]([email protected])([email protected]))([email protected]([email protected]))([email protected])([email protected])
'@payloadcms/translations': 3.94.1
'@payloadcms/ui': 3.94.1(@types/[email protected])([email protected])([email protected](@babel/[email protected])(@playwright/[email protected])(@types/[email protected])([email protected]([email protected]))([email protected])([email protected]))([email protected]([email protected])([email protected]))([email protected]([email protected]))([email protected])([email protected])
jsonwebtoken: 9.0.3
otpauth: 9.5.2
payload: 3.94.1([email protected])([email protected])
qrcode: 1.5.4
'@date-fns/[email protected]': {}
'@dnd-kit/[email protected]([email protected])':
+3 -3
View File
@@ -34,9 +34,9 @@ through this procedure. Ask only when you are missing something you cannot get y
### Build / TypeScript
| Symptom | Cause | Fix |
|---|---|---|
| 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 (supported: 3.0.0-beta.1 to 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 })`, or (server-only code that needs no access check) leave `overrideAccess` at its default |
| an account of a second auth collection (`customers`) gets `403` from a settings global, submissions or `/api/ipal/*` after an upgrade | by design since the release after 1.16.3: only staff collections pass `userMeetsRole` | write the one rule it needs (`formSubmissionOverrides`, `globalOverrides`, `collectionOverrides`); a second STAFF collection: `access.staffCollections` (access.md "Who is staff") |
| 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") |
| `TS2307 next/navigation` in the plugin's `dist` | import without `.js` in the plugin client (NodeNext) | **ipal-kit bug** → plugin gap; the plugin imports `'next/navigation.js'` |
| `TS2307 @payloadcms/storage-s3` | package missing when using `buildR2Storage` | `pnpm add @payloadcms/storage-s3` + `buildR2Storage(['media'], { s3Storage })` |
| `does not provide an export named X` / `X is not a function` | symbol not exported from the entry point, or wrong subpath (`/client` vs root vs `/server` vs `/rsc`) | `docs/README.md` → the right import; missing from every entry → **ipal-kit bug** (export) |
@@ -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 for `userMeetsRole`, besides the panel's login collection (`admin.user`); 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); 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)/<route>/` itself and adds the route to the proxy matcher (security.md) |
| `twoFactor` | **none = error** | `@clocklimited/payload-2fa` with `forceSetup: true` (TOTP enforced, also checked in the API) | `twoFactor: false` (discouraged); omitting the option throws `[ipal] twoFactor.issuer is required` |
| `twoFactor.issuer` | — (required) | name in the authenticator app | — |
@@ -38,7 +38,7 @@ description: Complete map of everything @intecion/ipal-kit provides — every ip
| `twoFactor.collectionSlug` | the panel's login collection (`admin.user`, else the first auth collection) | collection with 2FA; startup fails with `[ipal] twoFactor…` when it is not an auth collection or differs from `admin.user` | point it at the login collection |
| `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.<lang>.totpPlugin.<key>` (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` | `false` = the package's wrapper only (the plugin's own data then opens to a password without the code; not recommended) |
| `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.<op>`; `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.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 | — |
@@ -59,11 +59,11 @@ 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)` | `@intecion/ipal-kit` | Predicate → `boolean`: whether the user has a role ≥ `minimum` (reads `user.roles` safely). For your own access logic/hooks. |
| `isAdmin(user)` | `@intecion/ipal-kit` | Predicate → `boolean`: `admin` role. |
| `isEditor(user)` | `@intecion/ipal-kit` | Predicate → `boolean`: `editor` or higher. |
| `userMeetsRole(req, minimum)` | `@intecion/ipal-kit` | Predicate → `boolean` with `req` (`{ payload, user }`): role ≥ `minimum`, **or** any account of a **staff collection** (the panel's login collection `admin.user`, plus `access.staffCollections`) that has no `roles` field (the project omitted `access`). An account of any other auth collection never passes without a role. With 2FA on it also requires the second factor (`secondFactorPassed`). 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 `userMeetsRole` accepts — `admin.user` plus `access.staffCollections`. |
| `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. |
| `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. |
| `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. |
@@ -586,7 +586,7 @@ Server only (`pnpm payload run`); never import it from client code, the Payload
| `buildSecurityHeaders({ hsts?, csp?, additional?, coop?, frameOptions?, permissionsPolicy?, referrerPolicy?, … })` | `@intecion/ipal-kit` | Returns `SecurityHeader[]` (HSTS, X-Frame-Options, nosniff, Referrer-Policy, Permissions-Policy, COOP; with `IPAL_NOINDEX` also `X-Robots-Tag`) for `headers()` in `next.config.ts`. `csp` = `buildCsp` args → the CSP header (+ `Reporting-Endpoints` with `reportUri`); off by default. `additional` overrides by key. |
| `withSecurityConfig(nextConfig, { hidePoweredBy? })` | `@intecion/ipal-kit` | Next config wrapper: `poweredByHeader: false` + drops `X-Powered-By` from `headers()` (Next's "Next.js" and withPayload's "Next.js, Payload"). `withPayload(withSecurityConfig(nextConfig))`; `hidePoweredBy: false` = no change. |
| `secondFactorPassed(req)` | `@intecion/ipal-kit` | `boolean` with `req` (`{ payload, user }`): `false` only for an account of the 2FA collection that has TOTP set up and has not entered the code in this session (password only). `true` for a full login, an API key, an account that has not set TOTP up yet, accounts of other auth collections, no user, and with `twoFactor: false`. Guard your own endpoints with it: `if (!req.user \|\| !secondFactorPassed(req)) return 403`. |
| `requireSecondFactor(access?)` | `@intecion/ipal-kit` | Wraps an `Access` function: refused while the second factor is owed, otherwise the function itself (Payload's default "logged in" when none). ipalKit applies it to every collection and global in the config (and, in `onInit`, to those added by plugins listed after it); use it for access functions that are not part of the config. Wrapping twice is harmless. |
| `requireSecondFactor(access?)` | `@intecion/ipal-kit` | Wraps an `Access` function: refused while the second factor is owed, otherwise the function itself (Payload's default "logged in" when none). ipalKit applies it to every collection and global in the config, and to those added by plugins listed after it (in `onInit` and at the start of the first request, so also after a dev hot reload); use it for access functions that are not part of the config. Per-entity opt-out: `custom.ipal.secondFactor: false \| { read: false }` or the package's `custom.totp.disableAccessWrapper`. Wrapping twice is harmless. |
| `totpRedirectTarget({ adminRoute, forceSetup?, pathname, user, excludePaths? })`, `totpAdminPath(adminRoute, path)` | `@intecion/ipal-kit` | The 2FA redirect rules as pure functions: the setup / verify URL (with `back`) to send this user to, or `null` (no path, api key, already on a TOTP screen or logout). For an own `twoFactor.provider`. Types `TotpRedirectArgs`, `TotpUser` |
| `buildCsp({ mode?, reportUri?, reportGroup?, r2Url?, analytics?, metaPixel?, linkedIn?, tiktok?, clarity?, turnstile?, youtube?, googleMaps?, nonce?, strictDynamic?, dev?, extra?, override? })` | `@intecion/ipal-kit` | Returns `{ key, value }` with a hardened CSP (`base-uri`, `object-src`, `frame-ancestors`, `form-action`) + sources for the enabled integrations. `mode: 'report-only'` → `…-Report-Only` (start here), `'enforce'` later. `extra` adds to any directive, `override` replaces / drops one (`null`). `dev` (default `NODE_ENV === 'development'`) adds `'unsafe-eval'`. `nonce` → `'nonce-…' 'strict-dynamic'`. |
| `buildCspHeaders(args)` | `@intecion/ipal-kit` | `[csp, Reporting-Endpoints]` (the second only with `reportUri`). |
+4 -1
View File
@@ -224,8 +224,11 @@ 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").
**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
accounts pass none of the plugin's staff checks; use `adminOrSelfIn('<slug>')` in every auth collection; a second
accounts pass none of the plugin's checks and no role counts for them (not even their own `roles: ['admin']`);
a field that grants rights is never writable at sign-up; use `adminOrSelfIn('<slug>')` in every auth collection; a second
collection of STAFF goes in `access.staffCollections` (access.md "Who is staff"). Check: that account's token
gets `403` from `/api/globals/site-integrations` and `/api/form-submissions`.
- The `site-settings`, `site-integrations`, `cookie-settings`, `notifications` globals (write: editor+; Site
+11 -6
View File
@@ -331,22 +331,27 @@ recommended, not required (the plugin's peer range stays `^3.90.2`):**
**→ the release after 1.16.3 (PROGRAMISTA §6, item 65; security fixes: 2FA coverage and staff checks) — required
for every site:**
1. Update the package, `pnpm install`, `pnpm ipal:skills`, build, redeploy on Coolify. No migration, no config
change for a site with one auth collection. `pnpm ls @clocklimited/payload-2fa` must show 3.0.0-beta.1 to beta.7;
change for a site with one auth collection. `pnpm ls @clocklimited/payload-2fa` should show 3.0.0-beta.7 (tested: beta.1 and beta.7);
another version may stop startup with `[ipal] twoFactor: the injected 2FA plugin did not add …`.
2. `grep -rn "auth:" src/collections` — more than one auth collection? Then: `admin: { user: '<staff slug>' }` in
`buildConfig`; `adminOrSelfIn('<slug>')` instead of `adminOrSelf` in each; `access.staffCollections` only when
the second collection is staff (access.md "Who is staff"). Never list a visitor collection there.
the second collection is staff (access.md "Who is staff"). Never list a visitor collection there. Roles now
count only for accounts of a staff collection: code that relied on `isAdmin` / `adminOnly` for accounts of
another collection needs its own rule (`req.user.collection === '…'`).
3. `grep -rn "overrideAccess: false" src` — a call on a plugin collection or global (`form-submissions`, `forms`,
`consent-records`, `stats-visits`, `cookie-review`, the settings globals) must pass the `user` from
`payload.auth({ headers })`. Own endpoints that check `req.user`: add `secondFactorPassed(req)` or use
`userMeetsRole(req, role)`.
4. Tell the owner what the CHANGELOG entry says under "Requires project changes" and agree on it: new SMTP
`payload.auth({ headers })`; a user object built by hand needs `collection: '<staff slug>'` 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)`.
4. `pnpm exec ipal-doctor --url <site>` (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
password and Turnstile secret, a look through Site settings, Site integrations and each form's Emails tab.
Do not change those values yourself without that decision.
**Check:** with 2FA on, log in over the API with the password only (security.md → "What the second factor covers" →
Check) → `403` from `/api/globals/site-integrations`, `/api/form-submissions`, `/api/users`; log in fully in the
panel → Site integrations and a form submission open, a setting saves. With a second auth collection: its token
gets `403` from the same addresses.
gets `403` from the same addresses and from `POST /api/setup-totp`.
## 2. Inventory (no code changes)
**What changed for projects** between your old and new plugin version is exactly the reference site's diff —
+14 -12
View File
@@ -8,17 +8,17 @@ import { hasMinimumRole, isAdmin } from './predicates.js'
* Collection-level access (returns boolean | Where).
* Use in collection `access.read/create/update/delete`.
*/
export const adminOnly: Access = ({ req: { user } }) => isAdmin(user)
export const adminOnly: Access = ({ req }) => isAdmin(req.user, req.payload)
export const adminOrEditor: Access = ({ req: { user } }) => hasMinimumRole(user, 'editor')
export const adminOrEditor: Access = ({ req }) => hasMinimumRole(req.user, 'editor', req.payload)
export const authenticated: Access = ({ req: { user } }) => Boolean(user)
/** Requires at least the given role. */
export const requireRole =
(minimum: Role): Access =>
({ req: { user } }) =>
hasMinimumRole(user, minimum)
({ req }) =>
hasMinimumRole(req.user, minimum, req.payload)
/**
* Admins see all; others are constrained to their own document.
@@ -28,8 +28,9 @@ export const requireRole =
* `adminOrSelfIn(slug)` instead: with numeric ids (Postgres, SQLite) customer
* no. 5 would otherwise match staff account no. 5.
*/
export const adminOrSelf: Access = ({ req: { user } }) => {
if (isAdmin(user)) {return true}
export const adminOrSelf: Access = ({ req }) => {
const { user } = req
if (isAdmin(user, req.payload)) {return true}
if (!user) {return false}
return { id: { equals: user.id } }
}
@@ -42,8 +43,9 @@ export const adminOrSelf: Access = ({ req: { user } }) => {
*/
export const adminOrSelfIn =
(slug: string): Access =>
({ req: { user } }) => {
if (isAdmin(user)) {return true}
({ req }) => {
const { user } = req
if (isAdmin(user, req.payload)) {return true}
if (!user || (user as { collection?: unknown }).collection !== slug) {return false}
return { id: { equals: user.id } }
}
@@ -52,12 +54,12 @@ export const adminOrSelfIn =
* Field-level access (returns boolean only — no Where support).
* Use in field `access.read/update`.
*/
export const adminOnlyField: FieldAccess = ({ req: { user } }) => isAdmin(user)
export const adminOnlyField: FieldAccess = ({ req }) => isAdmin(req.user, req.payload)
export const adminOrEditorField: FieldAccess = ({ req: { user } }) => hasMinimumRole(user, 'editor')
export const adminOrEditorField: FieldAccess = ({ req }) => hasMinimumRole(req.user, 'editor', req.payload)
/** Requires at least the given role, for field-level access. */
export const requireRoleField =
(minimum: Role): FieldAccess =>
({ req: { user } }) =>
hasMinimumRole(user, minimum)
({ req }) =>
hasMinimumRole(req.user, minimum, req.payload)
+1 -1
View File
@@ -10,7 +10,7 @@ export {
requireRoleField,
} from './access.js'
export { injectRoles } from './injectRoles.js'
export { hasMinimumRole, isAdmin, isEditor, staffCollectionSlugs, userMeetsRole } from './predicates.js'
export { 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'
+72 -35
View File
@@ -13,6 +13,52 @@ import { ROLE_HIERARCHY } from './types.js'
*/
type MaybeUser = { roles?: null | Role[] } | null | Record<string, unknown> | undefined
/** `req.payload`, or anything with the sanitized config on it. */
type MaybePayload = null | Pick<BasePayload, 'config'> | undefined
/**
* 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.
*/
let registeredStaff: null | string[] = null
/** 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))]
}
/**
* The auth collections whose accounts are staff: the one the admin panel logs
* in with (`admin.user`), the one that carries the plugin's roles
* (`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.
*/
export function staffCollectionSlugs(payload?: MaybePayload): string[] {
const config = payload?.config
if (!config) {return registeredStaff ?? []}
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.
*/
function isStaffAccount(user: MaybeUser, payload?: 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)
}
/** Safely extracts the roles array from a loosely-typed user. */
function getRoles(user: MaybeUser): Role[] {
if (!user || typeof user !== 'object') {return []}
@@ -29,60 +75,51 @@ function highestRoleIndex(user: MaybeUser): number {
}
/**
* True if the user holds at least the given role in the hierarchy.
* True if the user is a staff account and holds at least the given role.
* admin satisfies 'editor' and 'user'; editor satisfies 'user'.
*
* 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.
*/
export function hasMinimumRole(user: MaybeUser, minimum: Role): boolean {
export function hasMinimumRole(user: MaybeUser, minimum: Role, payload?: MaybePayload): boolean {
if (!isStaffAccount(user, payload)) {return false}
return highestRoleIndex(user) >= ROLE_HIERARCHY.indexOf(minimum)
}
/** True if the user is an admin. */
export function isAdmin(user: MaybeUser): boolean {
return hasMinimumRole(user, 'admin')
/** True if the user is a staff account with the admin role. */
export function isAdmin(user: MaybeUser, payload?: MaybePayload): boolean {
return hasMinimumRole(user, 'admin', payload)
}
/** True if the user is an editor or higher (editor, admin). */
export function isEditor(user: MaybeUser): boolean {
return hasMinimumRole(user, 'editor')
}
/**
* The auth collections whose accounts are staff: the one the admin panel logs
* in with (`admin.user`) plus `access.staffCollections`. Accounts of any other
* auth collection — customers, members — are visitors to the plugin.
*/
export function staffCollectionSlugs(payload?: Pick<BasePayload, 'config'>): string[] {
const config = payload?.config
if (!config) {return []}
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 !== ''))]
/** True if the user is a staff account with the editor role or higher. */
export function isEditor(user: MaybeUser, payload?: MaybePayload): boolean {
return hasMinimumRole(user, 'editor', payload)
}
/**
* Role check for the plugin's own staff features (Site Integrations, the
* e-mail test, stats, consent records, form submissions, the settings
* globals). True when the user holds at least `minimum`.
* globals). In this order:
*
* Without roles: when the user belongs to a STAFF collection (the panel's
* login collection, or one named in `access.staffCollections`) and that
* collection has no `roles` field (the project omitted `access`), every
* account of it passes — without roles all staff accounts are equal, as in
* Payload's own default. An account of any other auth collection (a
* `customers` collection has no `roles` field either) never passes this way.
* 1. The account must belong to a STAFF collection (staffCollectionSlugs).
* An account of any other auth collection never passes — also when its own
* collection has a `roles` field that says `admin`.
* 2. With 2FA on, an account that has TOTP set up must have entered the code
* in this session (secondFactorPassed).
* 3. It holds at least `minimum` — or its collection has no `roles` field at
* all (the project omitted `access`): then every account of that staff
* collection passes, as in Payload's own default.
*
* With 2FA on, an account that has TOTP set up and has not entered the code in
* this session never passes (secondFactorPassed).
*
* Pass `req` (it has `payload` and `user`). Without `payload` only a held role
* counts — the strict side. A project with its own role scheme in another
* field narrows access through globalOverrides / collection overrides.
* Pass `req` (it has `payload` and `user`). A project with its own role scheme
* in another field narrows access through globalOverrides / collection overrides.
*/
export function userMeetsRole({ payload, user }: { payload?: BasePayload; user?: unknown }, minimum: Role): boolean {
if (!user || typeof user !== 'object') {return false}
if (!secondFactorPassed({ payload, user })) {return false}
if (hasMinimumRole(user as MaybeUser, minimum)) {return true}
const slug = (user as { collection?: unknown }).collection
if (typeof slug !== 'string' || !staffCollectionSlugs(payload).includes(slug)) {return false}
if (!secondFactorPassed({ payload, user })) {return false}
if (highestRoleIndex(user as MaybeUser) >= ROLE_HIERARCHY.indexOf(minimum)) {return true}
const collection = payload?.collections?.[slug as never]?.config
const fields = (collection?.flattenedFields ?? collection?.fields) as Array<{ name?: string }> | undefined
if (!fields) {return false}
+3 -2
View File
@@ -34,8 +34,9 @@ export function buildRolesField(defaultRole: Role = 'user', { firstUserAdmin = t
type: 'select',
access: {
// Only admins may assign or change roles
create: ({ req: { user } }) => isAdmin(user),
update: ({ req: { user } }) => isAdmin(user),
// …of a staff collection: a role value on an account of another auth collection does not count
create: ({ req }) => isAdmin(req.user, req.payload),
update: ({ req }) => isAdmin(req.user, req.payload),
},
admin: {
description: {
+133 -18
View File
@@ -74,47 +74,162 @@ const COLLECTION_OPERATIONS = ['create', 'delete', 'read', 'readVersions', 'unlo
const GLOBAL_OPERATIONS = ['read', 'readDrafts', 'readVersions', 'update'] as const
type AccessMap = Record<string, AnyAccess | undefined>
type GuardedEntity = { access?: unknown; custom?: Record<string, unknown>; slug: string }
type ConfigCustom = { totp?: { pluginOptions?: { disableAccessWrapper?: boolean } } } | undefined
function guardAccessMap(access: AccessMap | undefined, operations: readonly string[]): AccessMap {
const out: AccessMap = { ...access }
for (const op of operations) {out[op] = requireSecondFactor(out[op])}
return out
/**
* Per-entity opt-out, operation by operation — the project's decision that
* this collection or global may be reached with the password alone:
* - the 2FA package's own key: `custom.totp.disableAccessWrapper.<operation>: true`
* (the package leaves that operation unwrapped; so does ipal-kit);
* - ipal-kit's key, for entities the package never sees (added after it ran):
* `custom.ipal.secondFactor: false` (every operation) or `{ <operation>: false }`.
*/
function optedOut(entity: GuardedEntity, operation: string): boolean {
const custom = entity.custom as
| { ipal?: { secondFactor?: false | Record<string, boolean> }; totp?: { disableAccessWrapper?: Record<string, boolean> } }
| undefined
if (custom?.totp?.disableAccessWrapper?.[operation]) {return true}
const own = custom?.ipal?.secondFactor
return own === false || (typeof own === 'object' && own?.[operation] === false)
}
/**
* Before the 2FA package runs: ipal-kit's opt-out written in the package's own
* key as well, so the package leaves those operations unwrapped too.
*/
export function passOptOutsToPackage(config: Config): Config {
const translate = <T extends GuardedEntity>(entity: T, operations: readonly string[]): T => {
const off = operations.filter((op) => optedOut(entity, op))
if (!off.length) {return entity}
const totp = (entity.custom?.totp ?? {}) as { disableAccessWrapper?: Record<string, boolean> }
return {
...entity,
custom: { ...entity.custom, totp: { ...totp, disableAccessWrapper: { ...totp.disableAccessWrapper, ...Object.fromEntries(off.map((op) => [op, true])) } } },
}
}
return {
...config,
collections: (config.collections ?? []).map((c) => translate(c as GuardedEntity, COLLECTION_OPERATIONS) as CollectionConfig),
globals: (config.globals ?? []).map((g) => translate(g as GuardedEntity, GLOBAL_OPERATIONS) as GlobalConfig),
}
}
/** The package's global switch (`disableAccessWrapper: true` passed to its factory): no access wrapping at all. */
const wrapperDisabled = (custom: unknown): boolean => Boolean((custom as ConfigCustom)?.totp?.pluginOptions?.disableAccessWrapper)
/** The operations of one entity that still need the guard. */
function unguarded(entity: GuardedEntity, operations: readonly string[]): string[] {
const access = (entity.access ?? {}) as AccessMap
return operations.filter((op) => !optedOut(entity, op) && !(access[op] as Guarded | undefined)?.[GUARDED])
}
function guardEntity<T extends GuardedEntity>(entity: T, operations: readonly string[]): T {
const todo = unguarded(entity, operations)
if (!todo.length) {return entity}
const access: AccessMap = { ...(entity.access as AccessMap | undefined) }
for (const op of todo) {access[op] = requireSecondFactor(access[op])}
return { ...entity, 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,
collections: (config.collections ?? []).map(
(c) => ({ ...c, access: guardAccessMap(c.access as AccessMap | undefined, COLLECTION_OPERATIONS) }) as CollectionConfig,
),
globals: (config.globals ?? []).map(
(g) => ({ ...g, access: guardAccessMap(g.access as AccessMap | undefined, GLOBAL_OPERATIONS) }) as GlobalConfig,
),
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),
}
}
/**
* The same for a running Payload, in place: what plugins listed after ipalKit
* added. Called from ipalKit's onInit; returns the slugs it had to guard.
* added. Returns the slugs it had to guard.
*/
export function guardPayloadAccess(payload: BasePayload): string[] {
export function guardPayloadAccess(payload: Pick<BasePayload, 'config'>): string[] {
if (wrapperDisabled(payload.config.custom)) {return []}
const late: string[] = []
const sweep = (entity: { access?: unknown; slug: string }, operations: readonly string[]) => {
const access = (entity.access ?? {}) as AccessMap
if (operations.every((op) => (access[op] as Guarded | undefined)?.[GUARDED])) {return}
const sweep = (entity: GuardedEntity, operations: readonly string[]) => {
const todo = unguarded(entity, operations)
if (!todo.length) {return}
late.push(entity.slug)
entity.access = guardAccessMap(access, operations)
const access: AccessMap = { ...(entity.access as AccessMap | undefined) }
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, COLLECTION_OPERATIONS)}
if (!c.slug.startsWith('payload-')) {sweep(c as GuardedEntity, COLLECTION_OPERATIONS)}
}
for (const g of payload.config.globals ?? []) {sweep(g, GLOBAL_OPERATIONS)}
for (const g of payload.config.globals ?? []) {sweep(g as GuardedEntity, GLOBAL_OPERATIONS)}
return late
}
/** Configs already swept — a new sanitized config (start, dev hot reload) is swept once. */
const swept = new WeakSet<object>()
/** Sweeps `payload.config` once per config object. Returns the slugs guarded now (empty when already done). */
export function ensurePayloadGuarded(payload: Pick<BasePayload, 'config'>): string[] {
const config = payload?.config
if (!config || swept.has(config)) {return []}
swept.add(config)
return guardPayloadAccess(payload)
}
/** Name of the auth strategy ipalKit adds to the 2FA collection (see buildGuardStrategy). */
export const GUARD_STRATEGY_NAME = 'ipal-second-factor-guard'
/**
* An auth strategy that authenticates nobody. Payload runs every strategy at
* the start of every request, before any access function, so this is the one
* place ipal-kit is called on each request with the config that is live right
* now. It makes sure that config is guarded — also after a dev hot reload,
* 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) {
return {
name: GUARD_STRATEGY_NAME,
authenticate: ({ payload }: { payload: BasePayload }) => {
const late = ensurePayloadGuarded(payload)
if (late.length) {onLate?.(payload, late)}
return { user: null }
},
}
}
/** The 2FA package's endpoints an account uses BEFORE it has passed the second factor. */
const BEFORE_SECOND_FACTOR = new Set(['/setup-totp', '/verify-totp'])
type EndpointLike = { handler: (req: never) => Promise<Response> | Response; path: string }
/**
* Guards one endpoint the 2FA package registered. The package trusts
* `req.user` whatever collection it comes from: `/setup-totp` writes the TOTP
* secret into the 2FA collection under the CALLER's id, so with numeric ids an
* account of another auth collection could set the secret of the staff account
* that has the same id. So:
* - a logged-in account of another collection is refused on every endpoint
* of the package (no user: the package answers as before);
* - everything except setup and verify (remove, the admin reset / remove
* endpoints, whatever a later version adds) also needs the second factor,
* so a password alone cannot reset or remove TOTP.
*/
export function guardTotpEndpoint<T extends EndpointLike>(endpoint: T, collection: string): T {
const handler = endpoint.handler as (req: MaybeReq) => Promise<Response> | Response
const refused = () => Response.json({ message: 'Not allowed.', ok: false }, { status: 403 })
return {
...endpoint,
handler: ((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()}
return handler(req)
}) as unknown as T['handler'],
}
}
/**
* 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
+35 -7
View File
@@ -11,7 +11,7 @@ import { buildNotifications } from './globals/Notifications/index.js'
import { applyGlobalOverrides } from './globals/overrides.js'
import { buildSiteIntegrations } from './globals/SiteIntegrations/index.js'
import { buildSiteSettings } from './globals/SiteSettings/index.js'
import { adminOnly, adminOrSelfIn, injectRoles } from './modules/access/index.js'
import { adminOnly, adminOrSelfIn, injectRoles, registerStaffCollections, staffCollectionSlugs } from './modules/access/index.js'
import { applyAdminI18n } from './modules/admin-i18n/apply.js'
import { buildAdminImageEndpoints } from './modules/branding/adminImages.js'
import { buildAdminMeta, DEFAULT_AGENCY, syncAdminMeta } from './modules/branding/adminMeta.js'
@@ -33,7 +33,7 @@ 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 { guardConfigAccess, guardPayloadAccess, missingTotpParts } from './modules/security/totp/secondFactor.js'
import { buildGuardStrategy, ensurePayloadGuarded, guardConfigAccess, guardTotpEndpoint, missingTotpParts, passOptOutsToPackage } from './modules/security/totp/secondFactor.js'
import { TOTP_TEXTS, TOTP_VIEW_TITLE } from './modules/security/totp/totpTexts.js'
import { buildSeoPlugin, injectAutoFillMeta, injectSeoTabs } from './modules/seo/index.js'
import { buildIndexNowHook } from './modules/seo/indexNow.js'
@@ -203,12 +203,21 @@ export const ipalKit = (options: IpalOptions): Plugin => {
`"${adminSlug}", or pass twoFactor.allowCollectionMismatch: true if that is deliberate.`,
)
}
const endpointsBefore = new Set(config.endpoints ?? [])
// custom.ipal.secondFactor (ipal-kit's per-entity opt-out) → the package's own key
config = passOptOutsToPackage(config)
config = await totp({
collection: target,
forceSetup: true, // ENFORCED — every user must set up TOTP; no opt-out
totp: { issuer: tf.issuer },
})(config)
// The package's endpoints (setup, verify, remove, admin reset / remove) take
// `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)))
// 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
// end of this function (and other plugins' in onInit). The guard reads the
@@ -227,6 +236,16 @@ export const ipalKit = (options: IpalOptions): Plugin => {
}
secondFactorGuard = true
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(', ')}.`),
)
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
: c,
)
}
// The package's texts are long and informal: ipal-kit's (admin-ux.md) go over
@@ -381,10 +400,17 @@ export const ipalKit = (options: IpalOptions): Plugin => {
// --- access: inject roles into the client's auth collection ---
if (options.access) {
config = injectRoles(config, options.access)
// Further staff collections for userMeetsRole (the panel's login collection always is one).
if (options.access.staffCollections?.length) {
config.custom = { ...config.custom, ipal: { ...config.custom?.ipal, staffCollections: options.access.staffCollections } }
}
// Staff collections besides the panel's login collection: the one that carries
// the roles, and the ones the project names. Roles and staff checks count only
// for accounts of a staff collection (staffCollectionSlugs).
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).
{
const panel = config.admin?.user ?? (config.collections ?? []).find((c) => c.auth)?.slug
registerStaffCollections(staffCollectionSlugs({ config: { admin: { user: panel }, custom: config.custom } } as never))
}
// --- seo: apply @payloadcms/plugin-seo directly ---
@@ -637,9 +663,11 @@ 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 = guardPayloadAccess(payload)
const late = ensurePayloadGuarded(payload)
if (late.length) {payload.logger.info(`[ipal] 2FA also enforced on entities added after ipalKit: ${late.join(', ')}.`)}
}
await migrateCookieSettingsSaveButton(payload)
+36 -5
View File
@@ -2,15 +2,18 @@ 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 { buildRolesField } from '../src/modules/access/rolesField.js'
import { testEmailEndpoint } from '../src/modules/email/test/testEmailEndpoint.js'
vi.mock('payload', () => ({ addDataAndFileToRequest: vi.fn(async () => {}) }))
const admin = { id: 1, roles: ['admin'] }
const editor = { id: 2, roles: ['editor'] }
const user = { id: 3, roles: ['user'] }
const admin = { id: 1, collection: 'users', roles: ['admin'] }
const editor = { id: 2, collection: 'users', roles: ['editor'] }
const user = { id: 3, collection: 'users', roles: ['user'] }
/** `req.payload` as far as the role checks read it: the panel logs in with `users`. */
const payload = { config: { admin: { user: 'users' } } } as never
describe('role predicates', () => {
test('hierarchy admin > editor > user', () => {
@@ -26,16 +29,44 @@ describe('role predicates', () => {
expect(isAdmin({ roles: 'admin' })).toBe(false)
expect(isAdmin(null)).toBe(false)
})
test('a role counts only on an account of a staff collection', () => {
const member = { id: 1, collection: 'members', roles: ['admin'] }
expect(isAdmin(member, payload)).toBe(false)
expect(isEditor(member, payload)).toBe(false)
expect(hasMinimumRole(member, 'user', payload)).toBe(false)
expect(isAdmin({ id: 1, roles: ['admin'] }, payload)).toBe(false) // no collection: not an authenticated staff account
expect(isAdmin(admin, payload)).toBe(true)
// named in access.staffCollections → its roles count
const withMembers = { config: { admin: { user: 'users' }, custom: { ipal: { staffCollections: ['members'] } } } } as never
expect(isAdmin(member, withMembers)).toBe(true)
})
test('every ready access function refuses that account', () => {
const member = { id: 1, collection: 'members', roles: ['admin'] }
const req = { payload, user: member }
for (const fn of [adminOnly, adminOrEditor, requireRole('user'), adminOrSelfIn('users')]) {
expect(fn({ req } as never)).toBe(false)
}
for (const fn of [adminOnlyField, adminOrEditorField, requireRoleField('user')]) {
expect(fn({ req } as never)).toBe(false)
}
// adminOrSelf cannot know the collection it guards: no admin shortcut, only the id rule (use adminOrSelfIn)
expect(adminOrSelf({ req } as never)).toEqual({ id: { equals: 1 } })
expect(adminOnly({ req: { payload, user: admin } } as never)).toBe(true)
})
})
describe('roles field', () => {
const field = buildRolesField() as { access: { create: FieldAccess; update: FieldAccess } }
const call = (fn: FieldAccess, u: unknown) => fn({ req: { user: u } } as never)
const call = (fn: FieldAccess, u: unknown) => fn({ req: { payload, user: u } } as never)
test('only admins can set roles on create — no self-promotion via sign-up', () => {
expect(call(field.access.create, null)).toBe(false)
expect(call(field.access.create, user)).toBe(false)
expect(call(field.access.create, admin)).toBe(true)
// an "admin" of another auth collection is nobody here
expect(call(field.access.create, { id: 1, collection: 'members', roles: ['admin'] })).toBe(false)
})
test('only admins can change roles', () => {
@@ -49,7 +80,7 @@ describe('test-email endpoint', () => {
const sendEmail = vi.fn(async () => ({ sent: true }))
const req = {
data: { to: '[email protected]' },
payload: { logger: { error: vi.fn() }, sendEmail },
payload: { config: { admin: { user: 'users' } }, logger: { error: vi.fn() }, sendEmail },
user: u,
} as unknown as PayloadRequest
return { response: testEmailEndpoint.handler(req), sendEmail }
+16
View File
@@ -0,0 +1,16 @@
import { postgresAdapter } from '@payloadcms/db-postgres'
import { sqliteAdapter } from '@payloadcms/db-sqlite'
/**
* The database of the HTTP security tests. SQLite in memory by default; `IPAL_TEST_POSTGRES_URI` points them at a
* real Postgres (numeric ids, like SQLite — the adapters where an id of one auth collection can equal an id of
* another):
* docker run -d --rm -p 127.0.0.1:55432:5432 -e POSTGRES_PASSWORD=test postgres:17
* IPAL_TEST_POSTGRES_URI=postgres://postgres:[email protected]: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.
*/
export function testDatabase(name: string) {
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 })
}
+59 -3
View File
@@ -9,8 +9,8 @@ import { describe, expect, test } from 'vitest'
import type { I18nConfig } from '../src/modules/i18n/types.js'
import { adminOrSelfIn } from '../src/modules/access/access.js'
import { staffCollectionSlugs, userMeetsRole } from '../src/modules/access/predicates.js'
import { guardPayloadAccess, requireSecondFactor, secondFactorPassed } from '../src/modules/security/totp/secondFactor.js'
import { isAdmin, staffCollectionSlugs, userMeetsRole } from '../src/modules/access/predicates.js'
import { guardPayloadAccess, guardTotpEndpoint, requireSecondFactor, secondFactorPassed } from '../src/modules/security/totp/secondFactor.js'
import { ipalKit } from '../src/plugin.js'
import { withTotpParts } from './helpers.js'
@@ -42,6 +42,9 @@ describe('userMeetsRole: who is staff', () => {
expect(userMeetsRole({ payload, user: { collection: 'customers' } }, 'user')).toBe(false)
expect(userMeetsRole({ payload, user: { collection: 'customers' } }, 'admin')).toBe(false)
expect(userMeetsRole({ payload, user: { collection: 'no-such-collection' } }, 'user')).toBe(false)
// a role value on an account of a non-staff collection counts for nothing
expect(userMeetsRole({ payload, user: { collection: 'customers', roles: ['admin'] } }, 'user')).toBe(false)
expect(userMeetsRole({ payload, user: { roles: ['admin'] } }, 'user')).toBe(false) // no collection at all
expect(userMeetsRole({ payload, user: null }, 'user')).toBe(false)
})
@@ -58,12 +61,17 @@ describe('userMeetsRole: who is staff', () => {
const payload = payloadOf(config)
expect(staffCollectionSlugs(payload)).toEqual(['users', 'partners'])
expect(userMeetsRole({ payload, user: { collection: 'partners' } }, 'admin')).toBe(true) // no roles field there: all equal
expect(userMeetsRole({ payload, user: { collection: 'customers', roles: ['admin'] } }, 'admin')).toBe(false)
expect(userMeetsRole({ payload, user: { collection: 'customers' } }, 'admin')).toBe(false)
})
test('without a payload only a held role counts', () => {
test('without a payload: the staff collections of the config ipalKit built last; only a held role counts', async () => {
await ipalKit({ access: { authCollection: 'users' }, i18n, twoFactor: false })({ ...twoAuth(), admin: { user: 'users' } } as Config)
expect(userMeetsRole({ user: { collection: 'users' } }, 'user')).toBe(false)
expect(userMeetsRole({ user: { collection: 'users', roles: ['admin'] } }, 'admin')).toBe(true)
expect(userMeetsRole({ user: { collection: 'customers', roles: ['admin'] } }, 'admin')).toBe(false)
expect(isAdmin({ collection: 'customers', roles: ['admin'] })).toBe(false) // isAdmin(req.user) in a hook
expect(isAdmin({ collection: 'users', roles: ['admin'] })).toBe(true)
})
})
@@ -154,6 +162,54 @@ describe('ipalKit and the 2FA plugin', () => {
expect((config.custom as { ipal?: { twoFactor?: unknown } } | undefined)?.ipal?.twoFactor).toBeUndefined()
})
test('per-entity opt-out: the package key and ipal-kit\'s key, operation by operation', async () => {
const config = await ipalKit({ i18n, twoFactor: { issuer: 'A', plugin: fakeTotp as never } })({
collections: [
{ slug: 'a', custom: { totp: { disableAccessWrapper: { read: true } } }, fields: [] },
{ slug: 'b', custom: { ipal: { secondFactor: false } }, fields: [] },
],
globals: [{ slug: 'g', custom: { ipal: { secondFactor: { read: false } } }, fields: [] }],
secret: 'x',
} as unknown as Config)
const payload = payloadOf(config)
// an operation without a function = Payload's default: any logged-in account
const call = (access: unknown, op: string) => {
const fn = (access as Record<string, ((a: unknown) => unknown) | undefined> | undefined)?.[op]
return fn ? fn({ req: { payload, user: passwordOnly } }) : true
}
const col = (slug: string) => config.collections!.find((c) => c.slug === slug)!.access
expect(call(col('a'), 'read')).toBe(true)
expect(call(col('a'), 'update')).toBe(false)
// opted out of everything and no rule of its own: left exactly as the project wrote it (Payload's default applies)
expect(col('b')).toBeUndefined()
const g = config.globals!.find((x) => x.slug === 'g')!.access
expect(call(g, 'read')).toBe(true)
expect(call(g, 'update')).toBe(false)
// ipal-kit's key reaches the package in its own key, so the package leaves the operation alone too
expect((config.globals!.find((x) => x.slug === 'g')!.custom as { totp: unknown }).totp).toEqual({ disableAccessWrapper: { read: true } })
})
test("the 2FA package's endpoints: accounts of the 2FA collection only; management needs the second factor", async () => {
const payload = { config: { custom: { ipal: { twoFactor: { collection: 'users' } } } } }
const inner = () => Promise.resolve(Response.json({ ok: true }))
const call = async (path: string, user: unknown) => {
const endpoint = guardTotpEndpoint({ handler: inner as (req: never) => Promise<Response>, path }, 'users')
return (await endpoint.handler({ payload, user } as never)).status
}
const customer = { id: 1, collection: 'customers' }
const newcomer = { id: 2, _strategy: 'local-jwt', collection: 'users', hasTotp: false }
for (const path of ['/setup-totp', '/verify-totp', '/remove-totp', '/admin/reset-user-totp', '/some-future-endpoint']) {
expect([path, await call(path, customer)]).toEqual([path, 403])
expect([path, await call(path, null)]).toEqual([path, 200]) // no user: the package answers itself
}
expect(await call('/setup-totp', newcomer)).toBe(200)
expect(await call('/verify-totp', passwordOnly)).toBe(200)
expect(await call('/remove-totp', passwordOnly)).toBe(403)
expect(await call('/admin/reset-user-totp', passwordOnly)).toBe(403)
expect(await call('/some-future-endpoint', passwordOnly)).toBe(403)
expect(await call('/admin/reset-user-totp', verified)).toBe(200)
})
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)
+149 -6
View File
@@ -7,7 +7,6 @@
import type { CollectionConfig, Config, Payload, Plugin } from 'payload'
import { payloadTotp } from '@clocklimited/payload-2fa'
import { sqliteAdapter } from '@payloadcms/db-sqlite'
import { lexicalEditor } from '@payloadcms/richtext-lexical'
import os from 'os'
import path from 'path'
@@ -16,6 +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 { cookiesOf, startPayloadServer, type TestServer } from './http/server.js'
import { totp } from './http/totp.js'
@@ -34,17 +34,37 @@ const latePlugin: Plugin = (config: Config) => ({
const projectCollections: CollectionConfig[] = [
// A visitor account collection with open sign-up — a shop or a client zone.
{ slug: 'customers', access: { create: () => true }, auth: true, fields: [] },
// Another one that happens to have its own `roles` field with the same values, settable at sign-up.
{
slug: 'members',
access: { create: () => true },
auth: true,
fields: [{ name: 'roles', type: 'select', hasMany: true, options: ['user', 'editor', 'admin'], saveToJWT: true }],
},
// The 2FA package's own per-entity opt-out, and ipal-kit's.
{
slug: 'open-notes',
access: { read: ({ req }) => Boolean(req.user), update: ({ req }) => Boolean(req.user) },
custom: { totp: { disableAccessWrapper: { read: true } } },
fields: [{ name: 'note', type: 'text' }],
},
{
slug: 'open-tasks',
access: { read: ({ req }) => Boolean(req.user), update: ({ req }) => Boolean(req.user) },
custom: { ipal: { secondFactor: { read: false } } },
fields: [{ name: 'task', type: 'text' }],
},
{ slug: 'pages', fields: [{ name: 'title', type: 'text' }] },
{ slug: 'media', fields: [], upload: { staticDir: path.join(os.tmpdir(), 'ipal-test-media') } },
]
const PROJECT_SLUGS = new Set(['customers', 'media', 'pages'])
const PROJECT_SLUGS = new Set(['customers', 'media', 'members', 'open-notes', 'open-tasks', 'pages'])
type Session = { headers: Record<string, string> }
let server: TestServer
let payload: Payload
let pluginCollections: string[]
let pluginGlobals: string[]
const sessions = {} as Record<'anonymous' | 'customer' | 'newcomer' | 'passwordOnly' | 'verified', Session>
const sessions = {} as Record<'anonymous' | 'customer' | 'member' | 'newcomer' | 'passwordOnly' | 'verified', Session>
const api = (pathname: string, session: Session, init: RequestInit = {}) =>
fetch(`${server.url}/api${pathname}`, {
@@ -67,11 +87,11 @@ async function login(collection: string, email: string): Promise<{ cookies: stri
return { cookies: cookiesOf(res), token: body.token }
}
beforeAll(async () => {
const config = buildTestConfig({
const makeConfig = () =>
buildTestConfig({
admin: { user: 'users' }, // the panel logs in with the staff collection, not with `customers`
collections: projectCollections,
db: sqliteAdapter({ client: { url: 'file::memory:' }, push: true }),
db: testDatabase('sechttp'),
editor: lexicalEditor(),
plugins: [
ipalKit({
@@ -88,6 +108,9 @@ beforeAll(async () => {
secret: 'integration-test-secret-0123456789',
telemetry: false,
})
beforeAll(async () => {
const config = makeConfig()
payload = await getPayload({ config })
server = await startPayloadServer(config)
@@ -101,6 +124,15 @@ beforeAll(async () => {
await user('[email protected]', {})
await payload.create({ collection: 'customers' as never, data: { email: '[email protected]', password: PASSWORD } as never })
// Signed up over the API, asking for the admin role in its own collection.
const signUp = await fetch(`${server.url}/api/members`, {
body: JSON.stringify({ email: '[email protected]', password: PASSWORD, roles: ['admin'] }),
headers: { 'content-type': 'application/json' },
method: 'POST',
})
expect(signUp.status).toBe(201)
sessions.member = { headers: { authorization: `JWT ${(await login('members', '[email protected]')).token}` } }
sessions.anonymous = { headers: {} }
sessions.passwordOnly = { headers: { authorization: `JWT ${(await login('users', '[email protected]')).token}` } }
sessions.newcomer = { headers: { authorization: `JWT ${(await login('users', '[email protected]')).token}` } }
@@ -256,3 +288,114 @@ describe('what must keep working', () => {
expect((await api('/globals/site-integrations', sessions.anonymous)).status).toBe(403)
})
})
describe('a role value on an account of a non-staff collection counts for nothing (members with roles: [admin])', () => {
test('REST: it gets exactly what an anonymous visitor gets', async () => {
const more: string[] = []
for (const [kind, slugs] of [['collection', pluginCollections.filter((s) => s !== 'late-notes')], ['global', pluginGlobals]] as const) {
for (const slug of slugs) {
const read = [await readStatus(kind, slug, sessions.member), await readStatus(kind, slug, sessions.anonymous)]
if (read[0] !== read[1]) {more.push(`read ${kind} ${slug}: member ${read[0]}, anonymous ${read[1]}`)}
if (kind === 'collection' && slug === 'form-submissions') {continue}
const write = [await writeStatus(kind, slug, sessions.member), await writeStatus(kind, slug, sessions.anonymous)]
if (write[0] !== write[1]) {more.push(`write ${kind} ${slug}: member ${write[0]}, anonymous ${write[1]}`)}
}
}
expect(more).toEqual([])
})
test('REST: no secrets, no user list, no submissions, no staff endpoints, no unlock, no role change', async () => {
const integrations = await api('/globals/site-integrations', sessions.member)
expect(integrations.status).toBe(403)
expect(await integrations.text()).not.toContain('S3CRET')
for (const p of ['/users', '/form-submissions', '/consent-records', '/stats-visits', '/ipal/cookie-scan']) {
expect([p, (await api(p, sessions.member)).status]).toEqual([p, 403])
}
expect((await api('/ipal/test-email', sessions.member, { body: '{}', method: 'POST' })).status).toBe(403)
expect((await api('/users/unlock', sessions.member, { body: JSON.stringify({ email: '[email protected]' }), method: 'POST' })).status).toBe(403)
const staff = await payload.find({ collection: 'users' as never, where: { email: { equals: '[email protected]' } } })
const patch = await api(`/users/${staff.docs[0].id}`, sessions.member, { body: JSON.stringify({ roles: ['user'] }), method: 'PATCH' })
expect(patch.status).toBe(403)
const after = (await payload.findByID({ id: staff.docs[0].id, collection: 'users' as never })) as unknown as { roles: string[] }
expect(after.roles).toEqual(['admin'])
})
test('GraphQL: the same', async () => {
for (const query of ['{ SiteIntegration { smtpPassword } }', '{ Users { totalDocs } }', '{ FormSubmissions { totalDocs } }']) {
const out = await gql(sessions.member, query)
expect(out.errors?.length, `${query} → ${JSON.stringify(out)}`).toBeGreaterThan(0)
expect(JSON.stringify(out)).not.toContain('S3CRET')
}
})
})
describe("the 2FA package's endpoints accept accounts of the 2FA collection only", () => {
const secretOf = async (email: string) => {
const found = await payload.find({ collection: 'users' as never, showHiddenFields: true, where: { email: { equals: email } } })
return (found.docs[0] as { id: number | string; totpSecret?: null | string })
}
test('an account of another collection cannot set the TOTP secret of the staff account with the same id', async () => {
// SQL adapters number each collection from 1: the first customer and the first staff account share an id.
const customer = (await (await api('/customers/me', sessions.customer)).json()) as { user: { id: number | string } }
const admin = await secretOf('[email protected]')
const ATTACKER = 'KRSXG5CTMVRXEZLU'
const res = await api('/setup-totp', sessions.customer, { body: JSON.stringify({ secret: ATTACKER, token: totp(ATTACKER) }), method: 'POST' })
expect(res.status).toBe(403)
expect(res.headers.getSetCookie().join(';')).not.toContain('payload-totp')
const after = await secretOf('[email protected]')
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))
// 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)
})
test('verify, remove and the admin management endpoints refuse it as well', async () => {
for (const p of ['/verify-totp', '/remove-totp', '/admin/remove-user-totp', '/admin/reset-user-totp']) {
const res = await api(p, sessions.customer, { body: JSON.stringify({ token: '000000', userId: '1' }), method: 'POST' })
expect([p, res.status]).toEqual([p, 403])
}
})
test('a staff password without the code cannot reset or remove TOTP', async () => {
const admin = await secretOf('[email protected]')
for (const p of ['/remove-totp', '/admin/remove-user-totp', '/admin/reset-user-totp']) {
const res = await api(p, sessions.passwordOnly, { body: JSON.stringify({ token: totp(TOTP_SECRET), userId: String(admin.id) }), method: 'POST' })
expect([p, res.status]).toEqual([p, 403])
}
expect((await secretOf('[email protected]')).totpSecret).toBe(TOTP_SECRET)
})
})
describe('per-entity opt-out from the second factor', () => {
test("the package's key: custom.totp.disableAccessWrapper.<operation>", async () => {
expect((await api('/open-notes', sessions.passwordOnly)).status).toBe(200) // read opted out
expect((await api('/open-notes', sessions.passwordOnly, { body: '{}', method: 'POST' })).status).toBe(403) // create not
expect((await api('/open-notes', sessions.anonymous)).status).toBe(403) // its own rule still applies
})
test("ipal-kit's key: custom.ipal.secondFactor", async () => {
expect((await api('/open-tasks', sessions.passwordOnly)).status).toBe(200)
expect((await api('/open-tasks', sessions.passwordOnly, { body: '{}', method: 'POST' })).status).toBe(403)
})
})
// 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
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 }
expect((await api('/late-notes', sessions.passwordOnly)).status).toBe(403)
expect((await api('/late-notes', sessions.passwordOnly, { body: '{}', method: 'POST' })).status).toBe(403)
expect((await api('/globals/site-integrations', sessions.passwordOnly)).status).toBe(403)
expect((await api('/late-notes', sessions.verified)).status).toBe(200)
})
})
+92
View File
@@ -0,0 +1,92 @@
/**
* The same guarantees with the oldest supported 2FA package, @clocklimited/payload-2fa 3.0.0-beta.1 (installed
* here under the alias `payload-2fa-beta1`). The other HTTP tests run on the version in devDependencies, which is
* the one client sites use.
*/
import type { Payload } from 'payload'
import { lexicalEditor } from '@payloadcms/richtext-lexical'
import os from 'os'
import path from 'path'
import { getPayload } from 'payload'
import { payloadTotp } from 'payload-2fa-beta1'
import { afterAll, beforeAll, expect, test, vi } from 'vitest'
import { ipalKit } from '../src/plugin.js'
import { buildTestConfig } from './helpers.js'
import { testDatabase } from './http/db.js'
import { cookiesOf, startPayloadServer, type TestServer } from './http/server.js'
import { totp } from './http/totp.js'
vi.mock('server-only', () => ({}))
vi.mock('next/headers.js', async () => (await import('./http/server.js')).nextHeadersMock)
const SECRET = 'JBSWY3DPEHPK3PXP'
const PASSWORD = 'a-long-test-password-1'
let server: TestServer
let payload: Payload
const post = (pathname: string, body: unknown, headers: Record<string, string> = {}) =>
fetch(`${server.url}/api${pathname}`, { body: JSON.stringify(body), headers: { 'content-type': 'application/json', ...headers }, method: 'POST' })
const get = (pathname: string, headers: Record<string, string>) => fetch(`${server.url}/api${pathname}`, { headers })
beforeAll(async () => {
const config = buildTestConfig({
admin: { user: 'users' },
collections: [
{ slug: 'customers', access: { create: () => true }, auth: true, fields: [] },
{ slug: 'media', fields: [], upload: { staticDir: path.join(os.tmpdir(), 'ipal-test-media') } },
],
db: testDatabase('sechttp_b1'),
editor: lexicalEditor(),
plugins: [
ipalKit({
access: { authCollection: 'users' },
forms: {},
i18n: { defaultLocale: 'pl', locales: [{ code: 'pl', label: 'Polski' }] },
twoFactor: { issuer: 'Example', plugin: payloadTotp as never },
}),
],
secret: 'integration-test-secret-0123456789',
telemetry: false,
})
payload = await getPayload({ config })
server = await startPayloadServer(config)
await payload.updateGlobal({ slug: 'site-integrations' as never, data: { smtpPassword: 'S3CRET' } as never })
await payload.create({ collection: 'users' as never, data: { email: '[email protected]', password: PASSWORD, roles: ['admin'], totpSecret: SECRET } as never })
await payload.create({ collection: 'customers' as never, data: { email: '[email protected]', password: PASSWORD } as never })
}, 120_000)
afterAll(async () => {
await server?.close()
await payload?.destroy?.()
})
test('beta.1: password only → refused; password and code → allowed (REST and GraphQL)', async () => {
const login = await post('/users/login', { email: '[email protected]', password: PASSWORD })
const cookie = cookiesOf(login).join('; ')
for (const p of ['/globals/site-integrations', '/form-submissions', '/users', '/globals/site-settings']) {
expect([p, (await get(p, { cookie })).status]).toEqual([p, 403])
}
const before = (await (await post('/graphql', { query: '{ SiteIntegration { smtpPassword } }' }, { cookie })).json()) as { errors?: unknown[] }
expect(before.errors?.length).toBeGreaterThan(0)
const verify = await post('/verify-totp', { token: totp(SECRET) }, { cookie })
expect(((await verify.json()) as { ok: boolean }).ok).toBe(true)
const full = [cookie, ...cookiesOf(verify)].join('; ')
const integrations = await get('/globals/site-integrations', { cookie: full })
expect(integrations.status).toBe(200)
expect(((await integrations.json()) as { smtpPassword: string }).smtpPassword).toBe('S3CRET')
expect((await get('/form-submissions', { cookie: full })).status).toBe(200)
})
test('beta.1: a customers account cannot use the 2FA endpoints or reach staff data', async () => {
const login = (await (await post('/customers/login', { email: '[email protected]', password: PASSWORD })).json()) as { token: string }
const authorization = `JWT ${login.token}`
const ATTACKER = 'KRSXG5CTMVRXEZLU'
expect((await post('/setup-totp', { secret: ATTACKER, token: totp(ATTACKER) }, { authorization })).status).toBe(403)
const admin = await payload.find({ collection: 'users' as never, showHiddenFields: true })
expect((admin.docs[0] as { totpSecret?: string }).totpSecret).toBe(SECRET)
expect((await get('/globals/site-integrations', { authorization })).status).toBe(403)
expect((await get('/form-submissions', { authorization })).status).toBe(403)
})
+2 -2
View File
@@ -5,7 +5,6 @@
import type { Payload } from 'payload'
import { payloadTotp } from '@clocklimited/payload-2fa'
import { sqliteAdapter } from '@payloadcms/db-sqlite'
import { lexicalEditor } from '@payloadcms/richtext-lexical'
import os from 'os'
import path from 'path'
@@ -14,6 +13,7 @@ import { afterAll, beforeAll, expect, test, vi } from 'vitest'
import { ipalKit } from '../src/plugin.js'
import { buildTestConfig } from './helpers.js'
import { testDatabase } from './http/db.js'
import { startPayloadServer, type TestServer } from './http/server.js'
vi.mock('server-only', () => ({}))
@@ -32,7 +32,7 @@ beforeAll(async () => {
{ slug: 'users', auth: { useAPIKey: true }, fields: [] },
{ slug: 'media', fields: [], upload: { staticDir: path.join(os.tmpdir(), 'ipal-test-media') } },
],
db: sqliteAdapter({ client: { url: 'file::memory:' }, push: true }),
db: testDatabase('sechttp_tok'),
editor: lexicalEditor(),
plugins: [
ipalKit({
+1 -1
View File
@@ -22,7 +22,7 @@ export default defineConfig(() => {
hookTimeout: 30_000,
testTimeout: 30_000,
// Inlined so a test can replace `next/headers` (the package's cookie access) — test/http/server.ts.
server: { deps: { inline: ['@clocklimited/payload-2fa'] } },
server: { deps: { inline: ['@clocklimited/payload-2fa', 'payload-2fa-beta1'] } },
},
}
})