2FA setup required: review fixes (SR-1 to SR-9)

SR-1: /api/ipal/admin-icon sends the upload security headers (sandbox policy,
nosniff) with the bytes: an SVG is shown, never run. fetchPublicImage stops
reading at the size limit.
SR-2: requireSetup.exempt exempts only on exactly true; an async function, and a
windowHours that is not a number or false, stop the start.
SR-3: on Postgres / SQLite the missing column makes every login fail: the log
says so, the docs call the migration a required step of the same deploy, and
ipal-doctor reports a SQL project without it.
SR-4: an admin's reset also ends the account's sessions.
SR-5: the reset needs a session that entered its own TOTP code by default.
SR-6: the doctor's import-map rule covers TwoFactorStatusField and TwoFactorAlert.
SR-7: building blocks exported; dashboard notice, status field, setup notice and
the server-side image fetch can be switched off one by one.
SR-8: totpSetupFrom is on the 2FA collection whenever 2FA is on.
SR-9: both ways out of "every administrator is blocked" in security.md.

Co-Authored-By: Claude Fable 5.2 <[email protected]>
This commit is contained in:
Radosław Smoliński
2026-11-24 19:32:34 +01:00
co-authored by Claude Fable 5.2
parent 9d2ab43438
commit 75a6f5209e
34 changed files with 780 additions and 103 deletions
+25 -6
View File
@@ -21,7 +21,11 @@ once there are more than 20.
- **Accounts that already exist** get their 72 hours from the **first start after the upgrade** (not from their
creation date), so nobody is blocked at the moment of the upgrade. The server log names how many there are.
That moment is written on each account once: later restarts, redeploys and further instances do not move it,
nor does editing the account. On Postgres / SQLite it is the first start with the migration applied.
nor does editing the account.
- **A reset by an administrator ends the account's sessions**, and by default needs a session that entered its
own TOTP code (not an API key, not an exempt account).
- **`/api/ipal/admin-icon` answers with the favicon itself** instead of a redirect, with the same sandbox headers
as the upload routes, so the tab icon also loads on the 2FA screens (`adminMeta.serveIcon: false` = the redirect).
### Added
- On every account in the panel: **Two-step verification** (sidebar) — set up / open until a date / blocked — and
@@ -30,12 +34,22 @@ once there are more than 20.
- A dashboard notice for administrators: accounts without two-step verification, and how many are blocked.
- A notice on the setup screen: until when setup has to be done, or that the time has passed. All texts in
English and Polish.
- Options: `twoFactor.requireSetup: false | { windowHours, exempt }`, `twoFactor.resetAccess`. Exports:
`twoFactorSetupState`, `twoFactorSetupDeadline`; admin components `TwoFactorStatusField`, `TwoFactorResetButton`,
`TwoFactorAlert`.
- Options: `twoFactor.requireSetup: false | { windowHours, exempt, dashboardNotice, statusField, setupNotice }`,
`twoFactor.resetAccess`, `whiteLabel.inlineImages`, `adminMeta.serveIcon`. Exports: `twoFactorSetupState`,
`twoFactorSetupDeadline`, `buildSetupFields`, `stampSetupFrom`, `backfillSetupFrom`,
`buildTwoFactorResetEndpoint`, `countAccountsWithoutTotp`, `resolveRequireSetup`, `strictExempt`,
`SETUP_FROM_FIELD`, `TWO_FACTOR_RESET_PATH`, `DEFAULT_SETUP_WINDOW_HOURS`, `fetchPublicImage`,
`publicImageDataUri`, `siteOrigin`, `PUBLIC_IMAGE_MAX_BYTES`, `UPLOAD_SECURITY_HEADERS`; admin components
`TwoFactorStatusField`, `TwoFactorResetButton`, `TwoFactorAlert`.
- `requireSetup.exempt` is strict: only an answer of exactly `true` exempts. An `async` function, and a
`windowHours` that is not a number or `false`, stop the site at start with a clear error.
- The date field `totpSetupFrom` is on the 2FA collection whenever 2FA is on, so switching `requireSetup` or
`guard` never changes the schema (and never restarts anyone's window).
- The panel's tab icon and logo load on the verify and setup screens: `GET /api/ipal/admin-icon` answers with the
image itself (no redirect to the media file), and the logo components give a session that still owes its code
the picture as an anonymous visitor would get it. No change to who can read `media`.
- ipal-doctor: a SQL project without a migration for `totp_setup_from` (error), an import map without the two
new admin components (error).
- ipal-doctor: the `2fa` rule says how many accounts without 2FA are blocked (`usersSetupClosed` in the deep
status), warns when `requireSetup` is switched off and notes a missing setup window.
@@ -43,10 +57,15 @@ once there are more than 20.
- **Before upgrading a live site:** `pnpm exec ipal-doctor --url <site>` → accounts without 2FA. Each sets 2FA up
now, or is removed. At least one administrator must have 2FA set up, or nobody can reopen setup from the panel.
- `pnpm payload generate:importmap` (commit `importMap.js`) and `pnpm payload generate:types`, in the same
deploy as the upgrade (as for 1.16.5: a stale import map leaves the 2FA screens without a code form).
deploy as the upgrade (as for 1.16.5: a stale import map leaves the 2FA screens without a code form). `ipal-doctor`
reports a map without `TwoFactorStatusField` / `TwoFactorAlert` (then the panel has no "Reopen setup").
- **Plan the upgrade with the owner:** the 72 hours of every existing account without 2FA start at the deploy,
once. Deploy when those people can act within three days (not before a holiday), or have them set 2FA up first.
- **Postgres / SQLite:** `pnpm payload migrate:create` — the 2FA collection gets the column `totpSetupFrom`.
- **Postgres / SQLite — required, in the same deploy: `pnpm payload migrate:create`, commit, and the migration
applied before the new version serves requests** (the 2FA collection gets the column `totp_setup_from`).
**Without it every login answers 500 — administrators with 2FA included — and nobody can sign in to the
panel.** The log says so at start (`NOBODY CAN LOG IN`), and `ipal-doctor` reports a SQL project whose
migrations do not mention the column. Every project with 2FA on needs it, also with `requireSetup: false`.
MongoDB: nothing.
- **An integration that logs in with a password and has no TOTP** stops working: give it an API key (passes as
before) or exempt it on purpose: `twoFactor.requireSetup: { exempt: ({ user }) => user.email === '…' }`.
+1 -1
View File
@@ -1165,7 +1165,7 @@ 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) |
| 2FA setup required: an account without TOTP reaches only the setup screen; 72 h window from creation / admin reset, then blocked; status and "Reopen setup" on the account page, notice on the dashboard, `POST /api/ipal/two-factor/reset` | `twoFactor.requireSetup: false` | `requireSetup: { windowHours, exempt }`, `twoFactor.resetAccess`, texts `twoFactor*`; `twoFactorSetupState(req)` |
| 2FA setup required: an account without TOTP reaches only the setup screen; 72 h window from creation / admin reset, then blocked; status and "Reopen setup" on the account page, notice on the dashboard, `POST /api/ipal/two-factor/reset` | `twoFactor.requireSetup: false`; parts: `requireSetup: { dashboardNotice: false, statusField: false, setupNotice: false }` | `requireSetup: { windowHours, exempt }` (`exempt` returns exactly `true`, never `async`), `twoFactor.resetAccess` (default: an admin who entered its own code; the reset ends the account's sessions), texts `twoFactor*`; `twoFactorSetupState(req)`, `buildSetupFields`, `backfillSetupFrom`, `buildTwoFactorResetEndpoint`. **Postgres/SQLite: migration for `totp_setup_from` before the version serves, or every login answers 500** |
| The second factor on every collection and global, whichever plugin added it, and on the plugin's endpoints; an unrecognised 2FA package = startup error | per entity: `custom.ipal.secondFactor: false` or `{ read: false }` (or the package's `custom.totp.disableAccessWrapper`); everywhere: `twoFactor.guard: false` (not recommended) | `requireSecondFactor` / `secondFactorPassed` in your own access functions and endpoints |
| At most 5 verify attempts per account in 10 minutes (`POST /api/verify-totp` → `429`) | `twoFactor.verifyLimit: false` | `verifyLimit: { max, windowMinutes }` |
| The `back` link of the 2FA setup and verify screens is checked on the server (`SafeTotpView` in front of the package's views): only a path on the site's origin inside the admin route is kept, anything else (`javascript:`, another host) becomes the admin root. Needs `generate:importmap` in the same deploy — with a stale map the 2FA screens have no code form and nobody can sign in (`ipal-doctor`, the start log and a notice above the screen report it; the notice is a hint from the file on disk and never replaces the screen; `twoFactor.importMapCheck: false` turns it off); check: password only → `/admin/verify-totp?back=https%3A%2F%2Fexample.com%2F` → code → lands on `/admin` | `twoFactor.safeBack: false` | `safeBack: (back, { adminRoute, origin }) => string`; `safeAdminBack`, `wrapTotpViews` (`@intecion/ipal-kit`), `SafeTotpView` (`@intecion/ipal-kit/admin`) for own views |
+7 -2
View File
@@ -37,9 +37,14 @@ through this procedure. Ask only when you are missing something you cannot get y
| the 2FA code screen answers "Too many codes were tried…" (`429` from `/api/verify-totp`) | more than 5 verify attempts for that account in 10 minutes (`twoFactor.verifyLimit`); repeated lines `[ipal] 2FA: too many verify attempts` in the log without the owner trying = someone has the password | wait for the window, enter the current code once; unexplained attempts: change that account's password. Tests that log in often: `verifyLimit: { max: … }` for that environment |
| `isAdmin(req.user)` says `false` for a real administrator on the server, in a process that loads two Payload configs (tests, a multi-site script) | a call without a source counts only collections that are staff in **every** config of the process | pass the source: `isAdmin(req.user, req.payload)` — with it each config gets its own answer |
| `isAdmin(user)` / `isEditor(user)` is always `false` in a client component or in `proxy.ts` | the staff collections are not known there (no config in the browser bundle / middleware), and the predicates fail closed | `isAdmin(user, config)` with `useConfig()`; in middleware `isAdmin(user, { staffCollections: ['users'] })` |
| an account logs in but every page and request answers 403 / the setup screen says "The time to set up two-step verification has passed" | 2FA setup required: the account did not set TOTP up within the window (72 h from its creation, an admin's reset, or the first start after the upgrade) | an administrator opens the account in the panel → Two-step verification → "Reopen setup" (or `POST /api/ipal/two-factor/reset` `{ userId }`); the only admin is blocked: a script with the Local API — `payload.update({ collection: 'users', id, data: { totpSetupFrom: new Date().toISOString() } })` (`pnpm payload run`), then log in and set TOTP up |
| an account logs in but every page and request answers 403 / the setup screen says "The time to set up two-step verification has passed" | 2FA setup required: the account did not set TOTP up within the window (72 h from its creation, an admin's reset, or the first start after the upgrade) | an administrator opens the account in the panel → Two-step verification → "Reopen setup" (or `POST /api/ipal/two-factor/reset` `{ userId }`); every administrator is blocked: security.md "Every administrator is blocked" — a script with the Local API, `payload.update({ collection: 'users', id, data: { totpSetupFrom: new Date().toISOString() } })` (`pnpm payload run`), then log in and set TOTP up; or `requireSetup: { windowHours: false }`, redeploy, set up, put it back |
| a new account gets `403` from the API although its role allows the request | 2FA setup required: until TOTP is set up the account reaches only the setup screen | set TOTP up (log in to the panel); an integration: use an API key, or `twoFactor.requireSetup.exempt` |
| log: `[ipal] 2FA: could not start the setup window for existing accounts` | Postgres/SQLite: the migration that adds `totpSetupFrom` has not run | `pnpm payload migrate:create`, commit, deploy (migrations run in the Coolify pre-deploy command) |
| after an upgrade EVERY panel login answers `500` (also `/api/users/init`), administrators with 2FA included; log: `[ipal] 2FA: the column for "totpSetupFrom" is missing … NOBODY CAN LOG IN` or `column users.totp_setup_from does not exist` | Postgres/SQLite: the migration that adds the 2FA column has not run (needed whenever 2FA is on) | `pnpm payload migrate:create` if no migration has it, commit, run `pnpm payload migrate` (the Coolify pre-deploy command) and redeploy; nothing is lost. `ipal-doctor` reports a project whose migrations lack `totp_setup_from` |
| the site does not start: `[ipal] twoFactor.requireSetup.exempt must not be async` / `…windowHours must be a number` | `exempt` is an `async` function, or `windowHours` is a string / negative | `exempt: ({ user }) => user.email === '…'` (returns `true` / `false` at once); `windowHours: 72` or `false` |
| log: `[ipal] twoFactor.requireSetup.exempt returned a Promise … The account is NOT exempt` (and the service account gets 403) | `exempt` does not return exactly `true` | return a boolean decided from the fields on `user` |
| an administrator's "Reset two-step verification" answers 403 from a script with an API key, or for an exempt account | by default the reset needs a session that entered its own TOTP code | reset from the panel after logging in with the code; or `twoFactor.resetAccess: ({ req }) => …` |
| after "Reset two-step verification" the user is logged out everywhere | intended: the reset ends the account's sessions | the user logs in again with the password and sets 2FA up; after a suspected compromise also change the password |
| no "Two-step verification" box on the account page / no "Reopen setup" | the import map lacks `TwoFactorStatusField` (not regenerated), or `requireSetup: { statusField: false }` | `pnpm payload generate:importmap`, commit, redeploy; meanwhile `POST /api/ipal/two-factor/reset` `{ userId }` works |
| "Two-step verification" is missing on the account page / the dashboard shows a missing component | the import map is stale | `pnpm payload generate:importmap`, commit `importMap.js`, `rm -rf .next`, redeploy |
| 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 |
+5 -2
View File
@@ -42,8 +42,11 @@ description: Complete map of everything @intecion/ipal-kit provides — every ip
| `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` | 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.verifyLimit` | `{ max: 5, windowMinutes: 10 }` | attempts per account on `POST /api/verify-totp` (the 2FA package counts none): the sixth in the window, right or wrong, gets `429` + `Retry-After`; in memory per instance | `{ max, windowMinutes }`; `false` = no limit |
| `twoFactor.requireSetup` | on, `{ windowHours: 72 }` | an account without TOTP reaches nothing but the setup screen and `/api/setup-totp` (REST, GraphQL and the panel's data answer 403); it has `windowHours` from its creation or from an admin's reset, then it is blocked until an admin reopens setup. Adds the fields `totpSetupFrom` (date, written by the plugin) and `totpSetupStatus` (panel) to the 2FA collection, a dashboard notice and `POST /api/ipal/two-factor/reset`. Existing accounts get their window at the first start after the upgrade. Postgres/SQLite: migration; `generate:importmap` | `false` = the package's rule (API open until setup); `{ windowHours: 24 }`, `{ windowHours: false }` (no limit), `{ exempt: ({ user }) => … }` (a service account) |
| `twoFactor.resetAccess` | a staff admin | who may reset another account's TOTP / reopen its setup (the button on the account page, `POST /api/ipal/two-factor/reset`); the second factor is always required | `({ req }) => boolean` |
| `twoFactor.requireSetup` | on, `{ windowHours: 72 }` | an account without TOTP reaches nothing but the setup screen and `/api/setup-totp` (REST, GraphQL and the panel's data answer 403); it has `windowHours` from its creation or from an admin's reset, then it is blocked until an admin reopens setup. Adds the field `totpSetupStatus` (panel) to the 2FA collection, a dashboard notice and `POST /api/ipal/two-factor/reset`; the date field `totpSetupFrom` is there whenever 2FA is on (also with `requireSetup: false` / `guard: false`). Existing accounts get their window at the first start after the upgrade, written once. **Postgres/SQLite: the migration must run before the version serves, or every login answers 500**; `generate:importmap`. `exempt` must return exactly `true` at once (an `async` one, or a `windowHours` that is not a number / `false`, stops the start) | `false` = the package's rule (API open until setup); `{ windowHours: 24 }`, `{ windowHours: false }` (no limit), `{ exempt: ({ user }) => … }` (a service account) |
| `twoFactor.requireSetup.dashboardNotice` / `.statusField` / `.setupNotice` | on | the administrators' notice on the dashboard; the status and reset control on the account page; the notice on the setup screen | `false` each (the lock and the reset endpoint stay) |
| `twoFactor.resetAccess` | a staff admin whose session entered its own TOTP code (not an API key, not an `exempt` account) | who may reset another account's TOTP / reopen its setup (the button on the account page, `POST /api/ipal/two-factor/reset`). The reset clears the secret and the account's sessions. A session that still owes its code is always refused | `({ req }) => boolean` — only `true` allows; `req.user._strategy` tells `'totp'`, `'api-key'`, `'local-jwt'` apart |
| `whiteLabel.inlineImages` | on | on the 2FA screens the logo / icon is fetched by the server as an anonymous visitor gets it (max 512 KB) and inlined as `data:` — the session there is refused `media` | `false` = the browser tries the media URL |
| `adminMeta.serveIcon` | on | `/api/ipal/admin-icon` answers with the favicon's bytes and the upload security headers (sandbox, nosniff) | `false` = a redirect to the media file |
| `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 | — |
@@ -72,7 +72,7 @@ Admin panel components from `@intecion/ipal-kit/admin` — the project does NOT
| `buildRolesField(defaultRole?, { firstUserAdmin? })` | `@intecion/ipal-kit` | The `roles` select field the plugin injects (only admins set roles; `firstUserAdmin` default `true` = the account made on "Create first user" gets `admin`). The plugin wires it itself — use it only for an auth collection the plugin does not manage. |
| `injectRoles(config, accessOption)` | `@intecion/ipal-kit` | Adds `roles` to `accessOption.authCollection` in a config. The plugin calls it itself with `access` — do not call. |
**Types:** `VerifyLimitOptions` (`twoFactor.verifyLimit`: `{ max?, windowMinutes? }`), `SafeBackRule` / `SafeBackContext` (`twoFactor.safeBack` as a function: `(back, { adminRoute, origin? }) => string`), `TotpViewComponent` (a view component as registered: a path or `{ path, exportName?, clientProps?, serverProps? }`), `SafeTotpViewProps` (`@intecion/ipal-kit/admin`), `Role` (`'user' \| 'editor' \| 'admin'`), `AccessOption` (the plugin's `access` option: `authCollection`, `defaultRole`, `authAccess`, `firstUserAdmin`, `staffCollections`).
**Types:** `VerifyLimitOptions` (`twoFactor.verifyLimit`: `{ max?, windowMinutes? }`), `RequireSetupOptions` (`twoFactor.requireSetup`), `TwoFactorResetOptions`, `TwoFactorSetupState`, `SafeBackRule` / `SafeBackContext` (`twoFactor.safeBack` as a function: `(back, { adminRoute, origin? }) => string`), `TotpViewComponent` (a view component as registered: a path or `{ path, exportName?, clientProps?, serverProps? }`), `SafeTotpViewProps` (`@intecion/ipal-kit/admin`), `Role` (`'user' \| 'editor' \| 'admin'`), `AccessOption` (the plugin's `access` option: `authCollection`, `defaultRole`, `authAccess`, `firstUserAdmin`, `staffCollections`).
## Accessibility — widget (`accessibility`) — details: `node_modules/@intecion/ipal-kit/docs/accessibility.md`
@@ -595,6 +595,12 @@ Server only (`pnpm payload run`); never import it from client code, the Payload
| `copyViews(views)` / `changedViewKeys(before, after)` | `@intecion/ipal-kit` | The comparison `ipalKit` uses to tell which views a 2FA factory registered: put `copyViews(views)` into the config before calling the factory, then `changedViewKeys(before, viewsAfter)` gives the keys whose view object changed — the `added` argument of `wrapTotpViews` (`(key) => keys.has(key)`). By object, not by key: the 2FA package replaces a view that already stands under its keys. Example: security.md "Your own 2FA screen". |
| `SAFE_TOTP_VIEW` / `totpViewImportKey(component)` | `@intecion/ipal-kit` | `'@intecion/ipal-kit/admin#SafeTotpView'`, the wrapper's import-map path (the default `wrapper` of `wrapTotpViews`); and the import-map key (`path#export`) of a component given as a string or `{ path, exportName }`. |
| `findImportMapFile(config, cwd?)` / `missingImportMapEntries(config, entries, cwd?)` | `@intecion/ipal-kit` | Where the project's `importMap.js` is on disk (`admin.importMap.importMapFile`, else `app/(payload)<admin route>/` or `src/app/…` under `admin.importMap.baseDir` / the working directory; `null` when not found), and which of `entries` its text does not contain (`{ file, missing }`). A hint from the file on disk, not the map in the build: warn on it, never block on it. Behind `twoFactor.importMapCheck`. |
| `buildSetupFields({ statusField? })`, `stampSetupFrom`, `backfillSetupFrom(payload, collection)` | `@intecion/ipal-kit` | The parts of "2FA setup required" for a project that wires them itself: the fields for the 2FA collection (`totpSetupFrom`, and the panel's `totpSetupStatus` unless `statusField: false`), the `beforeChange` hook that stamps the window start (on create, and when an account loses its TOTP secret), and the start-up step that gives accounts without TOTP and without a start their window (returns how many; once per account). |
| `buildTwoFactorResetEndpoint(collection, { access? })`, `TWO_FACTOR_RESET_PATH` | `@intecion/ipal-kit` | `POST /api/ipal/two-factor/reset` `{ userId }`: clears the account's TOTP secret and sessions and starts a new window. Default: a staff admin whose session entered its own TOTP code; `access` replaces that (only `true` allows; a session that owes its code is always refused). |
| `countAccountsWithoutTotp(payload, collection, setupWindowMs?)` | `@intecion/ipal-kit` | `{ without, blocked }` — accounts of the 2FA collection without TOTP, and how many are past their window. |
| `resolveRequireSetup(option)`, `strictExempt(fn)`, `SETUP_FROM_FIELD`, `DEFAULT_SETUP_WINDOW_HOURS` | `@intecion/ipal-kit` | `twoFactor.requireSetup` → `{ requireSetup, setupWindowMs, exempt? }` as the guard reads it (throws on a `windowHours` that is not a number ≥ 0 or `false`, and on an `async` `exempt`); the wrapper that makes an `exempt` function answer `true` only for exactly `true`; the field name `'totpSetupFrom'`; `72`. |
| `fetchPublicImage(url, base)`, `publicImageDataUri(url, base)`, `siteOrigin(serverURL)`, `PUBLIC_IMAGE_MAX_BYTES` | `@intecion/ipal-kit` | An image fetched the way an anonymous visitor gets it (no cookies; http(s) only; `image/*`; at most 512 KB, reading stops at the limit) as `{ bytes, type }` or a `data:` address, else `null`. Used for the logo and icon on the 2FA screens. |
| `UPLOAD_SECURITY_HEADERS` | `@intecion/ipal-kit` | The two headers of `buildUploadSecurityHeaders` (`Content-Security-Policy: default-src 'none'; … sandbox`, `X-Content-Type-Options: nosniff`) for a route of your own that returns an uploaded file's bytes from the site's origin. |
| `twoFactorSetupState(req)`, `twoFactorSetupDeadline(req)` | `@intecion/ipal-kit` | Where an account stands with TOTP setup, from `{ payload, user }`: `'set-up'`, `'open'` (may set it up now), `'closed'` (the setup window has passed: blocked until an admin reopens it), `'exempt'` (`requireSetup.exempt`, or `requireSetup: false`), `'not-applicable'` (no user, another collection, 2FA off); and the moment setup closes (`Date`, or `null` without a window). Types: `TwoFactorSetupState`, `RequireSetupOptions`. |
| `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` |
+9 -4
View File
@@ -236,10 +236,15 @@ the panel shows Site settings, Site integrations, Cookies, Form messages, the Fo
opens everything its role allows. One entity reachable without the code: `custom.ipal.secondFactor`.
**Setup required** (`twoFactor.requireSetup`, default): an account without TOTP reaches only the setup screen; it
has 72 h from its creation (or an admin's "Reopen setup" on the account page), then it is blocked. So create an
account, hand over the password and have the owner set 2FA up at once. Postgres/SQLite: `pnpm payload
migrate:create` (field `totpSetupFrom`); `pnpm payload generate:importmap` (`TwoFactorStatusField`,
`TwoFactorAlert`). A service account that logs in with a password: `requireSetup: { exempt }`; an API key needs
nothing. One entity reachable without the code: `custom.ipal.secondFactor`.
account, hand over the password and have the owner set 2FA up at once. **Postgres/SQLite: `pnpm payload
migrate:create` and run the migration before the site serves** (column `totp_setup_from`, there whenever 2FA is
on) — without it every login answers 500; `pnpm payload generate:importmap` (`TwoFactorStatusField`,
`TwoFactorAlert`). A service account that logs in with a password: `requireSetup: { exempt }` (a plain function
returning exactly `true`; never `async`); an API key needs nothing. Parts to switch off: `requireSetup:
{ dashboardNotice: false, statusField: false, setupNotice: false }`. An admin's reset ends the account's
sessions and needs the admin's own TOTP code (`twoFactor.resetAccess` changes who). Have two administrators
with 2FA: when all are blocked, only a script or a redeploy helps (security.md "Every administrator is
blocked"). 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 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
+13 -3
View File
@@ -390,14 +390,24 @@ with 2FA on:**
and redeploys do not extend them): agree the deploy day with the owner.
2. Update the package, `pnpm install`, `pnpm ipal:skills`, `pnpm payload generate:types`,
**`pnpm payload generate:importmap`** (new: `TwoFactorStatusField`, `TwoFactorAlert`; commit `importMap.js`).
3. Postgres/SQLite: `pnpm payload migrate:create` (adds `totpSetupFrom` to the 2FA collection), commit. MongoDB: nothing.
3. **Postgres/SQLite — required, same deploy, or nobody can log in:** `pnpm payload migrate:create` (adds the
column `totp_setup_from` to the 2FA collection; needed whenever 2FA is on, also with `requireSetup: false`),
commit, and make sure it is applied before the new version serves requests (the Coolify pre-deploy command
`pnpm payload migrate`). Without the column every login answers 500, administrators included; the log says
`[ipal] 2FA: the column for "totpSetupFrom" is missing … NOBODY CAN LOG IN`. `pnpm exec ipal-doctor` reports
it before the deploy. MongoDB: nothing.
4. An integration that logs in with a password and has no TOTP: give it an API key, or
`twoFactor.requireSetup: { exempt: ({ user }) => user.email === '…' }`. `grep -rn "overrideAccess: false" src`:
a `user` fetched by id is refused for every account now — take it from `payload.auth({ headers })`.
5. `rm -rf .next`, build, redeploy on Coolify. Read the first lines of the log: `[ipal] 2FA: N existing account(s)
without two-step verification…` — pass that number to the owner. The line appears on that first start only.
Postgres/SQLite: the migration from step 3 must run in the same deploy; without it the log says
`could not start the setup window` and the window starts at the first start that has it.
Postgres/SQLite: if logins answer 500 after the deploy, the migration from step 3 did not run — run it now.
6. `requireSetup.exempt` must be a plain function returning `true` / `false` (an `async` one stops the start).
Scripts that used `POST /api/ipal/two-factor/reset` with an API key: refused by default now — pass
`twoFactor.resetAccess` if that is wanted. A reset ends the account's sessions (it logs in again).
**Every administrator is blocked** (all missed the 72 h): security.md "Every administrator is blocked" — a
`pnpm payload run` script that sets `totpSetupFrom` to now for one administrator, or
`requireSetup: { windowHours: false }` + redeploy, set 2FA up, put it back.
**Check:** create a throwaway account → its token gets `403` from `/api/users/me`; in the panel it lands on the
setup screen with "Set up two-step verification by …"; after the code it is in. As an administrator open that
account → "Two-step verification: Set up." and the reset button; delete the account.
+1 -1
View File
@@ -675,7 +675,7 @@ Do one item at a time, build, check. Order by importance:
| 65 | **1.16.4 — 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 1.16.4, security.md "What the second factor covers", access.md "Who is staff" |
| 66 | **1.16.4** — production `PAYLOAD_SECRET` shorter than 32 characters (the site would stop at `assertEnv`) | Before deploying 1.16.4, check the length in Coolify (`node -e 'console.log(process.env.PAYLOAD_SECRET.length)'`). Shorter: a random 32+ character secret (logs everyone out, asks for 2FA again, breaks stored API keys), or `ipalEnvRules({ secretMinLength: 0 })` for now | CHANGELOG 1.16.4, deployment.md "PAYLOAD_SECRET — length and changing it" |
| 67 | **1.16.5 — security** — with 2FA on, `/admin/verify-totp?back=https%3A%2F%2Fexample.com%2F` sends the user to example.com after the code (and `back=javascript:…` runs script in the panel) | Upgrade and, **in ONE deploy**, `pnpm payload generate:importmap` (adds `@intecion/ipal-kit/admin#SafeTotpView`), commit `importMap.js`, `rm -rf .next`, redeploy on Coolify — with the old map the 2FA screens have no code form and nobody can sign in (run `pnpm exec ipal-doctor` before deploying; the start log says so too); check: the link above ends on `/admin`. `pnpm ipal:skills`. No option, env or migration; off / own rule: `twoFactor.safeBack` | CHANGELOG 1.16.5, security.md "The `back` link of the 2FA screens" |
| 68 | **Unreleased — 2FA setup required** — an account that has not set 2FA up still reads data over the API with its password; or after the upgrade an account "can do nothing" / is blocked | Before upgrading: `ipal-doctor --url` → accounts without 2FA set it up or are removed; one admin must have 2FA. Then: update, `generate:types`, `generate:importmap` (`TwoFactorStatusField`, `TwoFactorAlert`), Postgres/SQLite `migrate:create` (`totpSetupFrom`), build, redeploy. Existing accounts get 72 h from the first start; blocked later → admin: account page → "Reopen setup". Password-login integrations: API key or `requireSetup.exempt`. `pnpm ipal:skills` | CHANGELOG "Unreleased — 2FA setup required", security.md "Setup required" |
| 68 | **Unreleased — 2FA setup required** — an account that has not set 2FA up still reads data over the API with its password; or after the upgrade an account "can do nothing" / is blocked | Before upgrading: `ipal-doctor --url` → accounts without 2FA set it up or are removed; one admin must have 2FA. Then: update, `generate:types`, `generate:importmap` (`TwoFactorStatusField`, `TwoFactorAlert`), **Postgres/SQLite: `migrate:create` and the migration applied in the same deploy (column `totp_setup_from`) — without it every login answers 500**, build, redeploy. Existing accounts get 72 h from the first start; blocked later → admin: account page → "Reopen setup". Password-login integrations: API key or `requireSetup.exempt`. `pnpm ipal:skills` | CHANGELOG "Unreleased — 2FA setup required", security.md "Setup required" |
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`.
+2 -2
View File
@@ -89,7 +89,7 @@ Turn off: `ipalKit({ doctor: false })`. Adapt: `ipalKit({ doctor: { tokenVar: 'M
| | `layout-forbidden` | error | no `middleware.ts`, no `lib/{pages,locales,navigation}.ts`, `fields/{link,sectionHeader,sectionSettings}.ts` |
| | `layout-extra` | info | `src/` entries outside the allow list (AGENT.md §3 + `seed/`, `design/`, `db.ts`, `env.rules.ts`, `content.config.ts`; extend with `layout.allow`) |
| | `naming` | warning | block folders, collection and global files PascalCase, `scripts/*` kebab-case, no `index.ts` barrels |
| | `importmap` | error | the import map exists, holds the entries for what the config turns on (2FA, R2, cookie scanner, `adminMeta`), names no export the plugin no longer has; with `--deep`, equals a fresh one. Warning: the config uses the 2FA package's own setup / verify view as a view's `Component` (outside the `back` link check — security.md); not for that path as `ipalTotpView` of `SafeTotpView` or in `admin.dependencies` |
| | `importmap` | error | the import map exists, holds the entries for what the config turns on (2FA incl. `SafeTotpView`, `TwoFactorStatusField`, `TwoFactorAlert`; R2, cookie scanner, `adminMeta`), names no export the plugin no longer has; with `--deep`, equals a fresh one. Warning: the config uses the 2FA package's own setup / verify view as a view's `Component` (outside the `back` link check — security.md); not for that path as `ipalTotpView` of `SafeTotpView` or in `admin.dependencies` |
| | `tsconfig-skills` | error | `tsconfig.json` excludes the skills folder |
| env | `db-name` | error | `DATABASE_URI` in `.env` and `.env.example` names `<domain without dots>_dev`; a local `.env` on `_prod` is an error; `--env-file` checks `_prod` (`databaseNamesFor`) |
| | `env-rules` | error / warning | `instrumentation.ts` calls `assertEnv(ipalEnvRules(…))` from `/env`, with `storage` (R2), `cookieCrawl` (crawl), `ipHeader`; `databaseName` suggested (info) |
@@ -98,7 +98,7 @@ Turn off: `ipalKit({ doctor: false })`. Adapt: `ipalKit({ doctor: { tokenVar: 'M
| security | `security-headers` | error | `buildSecurityHeaders`; live: HSTS, nosniff, Referrer-Policy, Permissions-Policy, frame protection |
| | `powered-by` | error | `withSecurityConfig`; live: no `X-Powered-By` on `/` and the admin |
| | `csp` | warning / info | CSP on the site and the admin; report-only is info, a warning after 4 weeks (`seen`) |
| | `2fa` | error | `twoFactor: { plugin: payloadTotp }` + the package; deep: 0 users without TOTP (the message says how many of them are blocked because their setup window has passed); warning: `twoFactor.requireSetup: false`; info: no setup window (`windowHours: false`) |
| | `2fa` | error | `twoFactor: { plugin: payloadTotp }` + the package; deep: 0 users without TOTP (the message says how many of them are blocked because their setup window has passed); error: a Postgres / SQLite project whose migrations do not mention the 2FA column `totp_setup_from` (every login would answer 500; a warning when there is no migrations folder — the doctor cannot see a schema that gets there another way); warning: `twoFactor.requireSetup: false`; info: no setup window (`windowHours: false`) |
| | `cookie-scanner` | error / warning / info | `cookieScanner` on (with `crawl`, else info); deep: nothing waits for approval (warning) |
| admin | `admin-meta` | warning | ipal-kit ≥ 1.14.5, no `adminMeta: false` / `agency: false`; live: the admin `og:image` is `/api/ipal/admin-og` |
| | `admin-noindex` | error | (live) the admin login page is noindex |
+73 -12
View File
@@ -433,7 +433,9 @@ the Local API with `overrideAccess: true` (the default) are not affected.
### Setup required (`twoFactor.requireSetup`, on by default)
An account that has **not set TOTP up yet** reaches nothing at the access level — REST, GraphQL, the panel's
data, the plugin's endpoints — until it has. It gets the setup screen and `POST /api/setup-totp`, nothing else.
data, the plugin's endpoints — until it has. It gets the setup screen and `POST /api/setup-totp`, and what
Payload gives any logged-in session about itself (`/api/access`, token refresh, logout, its own panel
preferences), nothing else.
The 2FA package alone only redirects such an account inside the panel; over the API its password would open
everything its role allows.
@@ -465,8 +467,8 @@ the account without one. Later starts, redeploys and further instances find noth
appears on that first start only), and editing the account or logging in does not move it — so a redeploy never
hands out another 72 hours. Only an administrator's reset / "Reopen setup" opens a new window. An existing
account that **has** TOTP gets no start; if its TOTP is removed later, its window starts then. On Postgres /
SQLite "the first start" means the first start **with the migration applied**: before that there is no column
to write to, the log warns, and those accounts have no time limit yet.
SQLite the migration that adds the column must run in the same deploy (see "Data" below) — the first start
after it is the one that counts.
```ts
twoFactor: {
@@ -475,17 +477,39 @@ twoFactor: {
// requireSetup: { windowHours: 24 }, // another window
// requireSetup: { windowHours: false }, // no time limit (0 works too): locked until set up, never blocked
// requireSetup: { exempt: ({ user }) => user.email === 'integration@example.com' }, // a service account that logs in with a password, on purpose
// requireSetup: { dashboardNotice: false, statusField: false, setupNotice: false }, // each panel part can be switched off; the lock stays
// requireSetup: false, // the 2FA package's rule: redirect in the panel, API open until setup
// resetAccess: ({ req }) => isAdmin(req.user, req.payload), // who may reset / reopen (default: a staff admin; the second factor is always required)
}
```
- **Data.** The mode adds a date field `totpSetupFrom` (hidden, written by the plugin only) and a panel-only field
`totpSetupStatus` to the 2FA collection. MongoDB: nothing to do. **Postgres / SQLite: create and run a
migration** (`pnpm payload migrate:create`); until it has run, the log shows `[ipal] 2FA: could not start the
setup window…` and existing accounts have no time limit yet.
- **Data.** The 2FA collection gets a date field `totpSetupFrom` (hidden, written by the plugin only) **whenever
2FA is on** — also with `requireSetup: false` or `guard: false`, so that switching the mode does not change the
schema — and, with the mode on, a panel-only field `totpSetupStatus`. MongoDB: nothing to do.
**Postgres / SQLite: the migration is a required step of the same deploy.** Run `pnpm payload migrate:create`, commit the migration, and
make sure it is applied (`pnpm payload migrate`, the Coolify pre-deploy command) **before the new version
serves requests**. Without the column every query on the 2FA collection fails: **every login answers 500 —
administrators with 2FA included — and nobody can sign in to the panel** (the public site keeps working). The
log says `[ipal] 2FA: the column for "totpSetupFrom" is missing … NOBODY CAN LOG IN …` at start;
`ipal-doctor` reports a SQL project whose migrations do not mention `totp_setup_from` (error; a warning when
there is no migrations folder at all — it cannot see a schema that is pushed some other way). Recovery: run
the migration; no data is lost.
- **`exempt` must answer `true` or `false` at once.** It runs inside access checks, which cannot wait. An
`async` function stops the site at start with a clear error; any answer other than exactly `true` (a Promise,
a string, an error) exempts nobody and is logged once. Decide from the fields on `user`. An exempt account
works on its password alone, so give it the lowest role that does its job.
- **`windowHours`** must be a number (0 or more) or `false`; anything else (`'24'`, `-1`) stops the site at start.
- **Import map.** The status field and the dashboard notice are admin components: `pnpm payload
generate:importmap` after upgrading (`TwoFactorStatusField`, `TwoFactorAlert`).
generate:importmap` after upgrading (`TwoFactorStatusField`, `TwoFactorAlert`); `ipal-doctor` reports a map
that lacks them. Without them the panel has no "Reopen setup" button (the endpoint still works).
- **Switch a part off:** `requireSetup: { dashboardNotice: false }` (the administrators' notice),
`{ statusField: false }` (the status / reset control on the account; the endpoint stays),
`{ setupNotice: false }` (the notice on the setup screen). None of them changes who is refused. The logo and
icon fetched by the server for the 2FA screens: `whiteLabel.inlineImages: false`, `adminMeta.serveIcon: false`
([white-label.md](./white-label.md)).
- **Building blocks** (`@intecion/ipal-kit`), for a project that wires the mode itself: `buildSetupFields`,
`stampSetupFrom`, `backfillSetupFrom`, `buildTwoFactorResetEndpoint`, `countAccountsWithoutTotp`,
`resolveRequireSetup`, `strictExempt`, `SETUP_FROM_FIELD`, `TWO_FACTOR_RESET_PATH`, `DEFAULT_SETUP_WINDOW_HOURS`.
- **Per collection or global:** the opt-out below (`custom.ipal.secondFactor`) also lets an account without TOTP
in, because it takes the entity out of the second-factor check altogether.
- **Needs** ipal-kit's check (`twoFactor.guard`, on by default); with `guard: false` the mode is off.
@@ -761,8 +785,43 @@ show the QR code. `back=null` or a page that keeps reloading means the import ma
An admin resets another user's 2FA (a lost phone) or reopens setup for a blocked account on that account's page
in the panel: **Two-step verification** in the sidebar → "Reset two-step verification" / "Reopen setup". Behind
it: `POST /api/ipal/two-factor/reset` `{ userId }` — a staff admin who has passed the second factor
(`twoFactor.resetAccess` changes who). The account must set TOTP up again within a new window.
it: `POST /api/ipal/two-factor/reset` `{ userId }`. The account must set TOTP up again within a new window.
- **Who may reset.** By default a staff admin whose session has **entered its own TOTP code**. An admin on an API
key, and an admin that `requireSetup.exempt` lets work on its password, are refused: removing someone's second
factor should take one. `twoFactor.resetAccess: ({ req }) => boolean` replaces the rule; a session that still
owes its code is refused whatever the function says, and only an answer of exactly `true` allows
(`req.user._strategy` is `'totp'`, `'api-key'` or `'local-jwt'`).
- **A reset ends the account's sessions.** Every token of that account stops working at once; its owner logs
in again with the password and sets TOTP up. This matters when the account may be in someone else's hands: a
session that had passed 2FA could otherwise enrol a new authenticator without the password (`/api/setup-totp`
asks for none). **After a suspected compromise also change the account's password** — the reset does not, and
whoever knows the password can log in and set TOTP up within the new window. With `auth.useSessions: false`
on the collection there are no sessions to end: tokens live until they expire.
- The 2FA package's own remove / reset endpoints (below) do **not** end sessions.
#### Every administrator is blocked
When no administrator can get in (each one missed the window, or the only one did), nobody can press "Reopen
setup". Two ways out, both need a deploy or shell access — which is the point: the panel alone cannot undo it.
1. **A script, no redeploy** (`pnpm payload run scripts/reopen-2fa.ts` on the server; Local API, no access
check):
```ts
import config from '@payload-config'
import { getPayload } from 'payload'
const payload = await getPayload({ config })
const { docs } = await payload.find({ collection: 'users', where: { email: { equals: 'admin@example.com' } } })
await payload.update({ id: docs[0].id, collection: 'users', data: { totpSetupFrom: new Date().toISOString() } })
process.exit(0)
```
The administrator then logs in and sets TOTP up within the new window, and reopens the others from the panel.
2. **No script, one redeploy each way:** set `twoFactor.requireSetup: { windowHours: false }` and deploy — the
lock stays (nothing but setup), the time limit is gone, so every blocked account can set TOTP up. When the
administrators have, put the option back and deploy again. Accounts that still have not set TOTP up are
blocked again from that moment (their start did not move).
Avoid it: at least two administrators with 2FA, and `ipal-doctor --url <site>` before an upgrade.
The 2FA package has its own reset, off unless you turn it on — through
`adminManageAccess` in the @clocklimited configuration. ipalKit passes it only `collection`,
@@ -844,8 +903,10 @@ size while reading, content signature, container and macro checks, an optional `
The stale import-map notice that comes with it: `twoFactor.importMapCheck: false`; its parts
(`findImportMapFile`, `missingImportMapEntries`) are exported too.
- **Setup required:** `twoFactor.requireSetup: false` (off), `{ windowHours }` (another window, `false` / `0` = none),
`{ exempt }` (a service account), `twoFactor.resetAccess` (who reopens); exported: `twoFactorSetupState`,
`twoFactorSetupDeadline`.
`{ exempt }` (a service account), `{ dashboardNotice: false }`, `{ statusField: false }`, `{ setupNotice: false }`,
`twoFactor.resetAccess` (who reopens); exported: `twoFactorSetupState`, `twoFactorSetupDeadline`,
`buildSetupFields`, `stampSetupFrom`, `backfillSetupFrom`, `buildTwoFactorResetEndpoint`,
`countAccountsWithoutTotp`, `resolveRequireSetup`, `strictExempt`, `SETUP_FROM_FIELD`.
- **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.
+7 -1
View File
@@ -51,6 +51,12 @@ values win over yours); `afterLogin` / `afterNavLinks` are appended.
## Technology support credit — "Technology support: Intecion.com"
**On the 2FA screens** (a session that has typed its password but not its code, or has not set 2FA up) the
panel's logo and icon cannot be loaded by the browser: that session is refused every collection, `media`
included. The server fetches them the way an anonymous visitor gets them (no cookies, images only, at most
512 KB) and puts them into the page as a `data:` image. `whiteLabel: { inlineImages: false }` turns the fetch
off (the site name is shown instead of a refused image); `fetchPublicImage` / `publicImageDataUri` are exported.
A discreet line **"Technology support: Intecion.com"** (pl `Wsparcie technologiczne: Intecion.com`,
a link to `https://intecion.com`) appears in **two places**:
- **under the panel navigation** (`afterNavLinks`, variant `nav` — left-aligned),
@@ -84,7 +90,7 @@ image. The plugin now fills the panel's `<head>` from Site settings, **with or w
| `og:site_name` | the site name | your `admin.meta.openGraph.siteName` wins |
| description | "Administration panel of <site>. Built on Payload CMS, technology support: Intecion.com." (Polish when the site's default locale is `pl`) | `adminMeta: { description: 'Panel of {site}' }` (string or `{ en, pl }`), `false`; `language: 'en' \| 'pl'`; your `admin.meta.description` wins |
| preview image | `GET /api/ipal/admin-og` — 1200×630 PNG: the site's logo (or name), "Administration panel", "Technology support: Intecion.com" | `adminMeta: { image: '/my-og.png' }` or `false`; your `admin.meta.openGraph.images` wins |
| icon | `GET /api/ipal/admin-icon` — answers with the site's favicon itself (fetched as an anonymous visitor would get it; a redirect only when that is not possible), or draws the initials | `adminMeta: { icons: false }`; your `admin.meta.icons` win |
| icon | `GET /api/ipal/admin-icon` — answers with the site's favicon itself (fetched as an anonymous visitor would get it, at most 512 KB, sent with the upload security headers: sandbox policy and `nosniff`, so an SVG is shown but cannot run script; a redirect only when fetching is not possible), or draws the initials | `adminMeta: { icons: false }`; `adminMeta: { serveIcon: false }` = always the redirect to the media file; your `admin.meta.icons` win |
| everything | on | `adminMeta: false` = Payload's defaults |
- **How:** Payload builds every panel page's metadata from `config.admin.meta`. The plugin sets the
+7 -2
View File
@@ -37,9 +37,14 @@ through this procedure. Ask only when you are missing something you cannot get y
| the 2FA code screen answers "Too many codes were tried…" (`429` from `/api/verify-totp`) | more than 5 verify attempts for that account in 10 minutes (`twoFactor.verifyLimit`); repeated lines `[ipal] 2FA: too many verify attempts` in the log without the owner trying = someone has the password | wait for the window, enter the current code once; unexplained attempts: change that account's password. Tests that log in often: `verifyLimit: { max: … }` for that environment |
| `isAdmin(req.user)` says `false` for a real administrator on the server, in a process that loads two Payload configs (tests, a multi-site script) | a call without a source counts only collections that are staff in **every** config of the process | pass the source: `isAdmin(req.user, req.payload)` — with it each config gets its own answer |
| `isAdmin(user)` / `isEditor(user)` is always `false` in a client component or in `proxy.ts` | the staff collections are not known there (no config in the browser bundle / middleware), and the predicates fail closed | `isAdmin(user, config)` with `useConfig()`; in middleware `isAdmin(user, { staffCollections: ['users'] })` |
| an account logs in but every page and request answers 403 / the setup screen says "The time to set up two-step verification has passed" | 2FA setup required: the account did not set TOTP up within the window (72 h from its creation, an admin's reset, or the first start after the upgrade) | an administrator opens the account in the panel → Two-step verification → "Reopen setup" (or `POST /api/ipal/two-factor/reset` `{ userId }`); the only admin is blocked: a script with the Local API — `payload.update({ collection: 'users', id, data: { totpSetupFrom: new Date().toISOString() } })` (`pnpm payload run`), then log in and set TOTP up |
| an account logs in but every page and request answers 403 / the setup screen says "The time to set up two-step verification has passed" | 2FA setup required: the account did not set TOTP up within the window (72 h from its creation, an admin's reset, or the first start after the upgrade) | an administrator opens the account in the panel → Two-step verification → "Reopen setup" (or `POST /api/ipal/two-factor/reset` `{ userId }`); every administrator is blocked: security.md "Every administrator is blocked" — a script with the Local API, `payload.update({ collection: 'users', id, data: { totpSetupFrom: new Date().toISOString() } })` (`pnpm payload run`), then log in and set TOTP up; or `requireSetup: { windowHours: false }`, redeploy, set up, put it back |
| a new account gets `403` from the API although its role allows the request | 2FA setup required: until TOTP is set up the account reaches only the setup screen | set TOTP up (log in to the panel); an integration: use an API key, or `twoFactor.requireSetup.exempt` |
| log: `[ipal] 2FA: could not start the setup window for existing accounts` | Postgres/SQLite: the migration that adds `totpSetupFrom` has not run | `pnpm payload migrate:create`, commit, deploy (migrations run in the Coolify pre-deploy command) |
| after an upgrade EVERY panel login answers `500` (also `/api/users/init`), administrators with 2FA included; log: `[ipal] 2FA: the column for "totpSetupFrom" is missing … NOBODY CAN LOG IN` or `column users.totp_setup_from does not exist` | Postgres/SQLite: the migration that adds the 2FA column has not run (needed whenever 2FA is on) | `pnpm payload migrate:create` if no migration has it, commit, run `pnpm payload migrate` (the Coolify pre-deploy command) and redeploy; nothing is lost. `ipal-doctor` reports a project whose migrations lack `totp_setup_from` |
| the site does not start: `[ipal] twoFactor.requireSetup.exempt must not be async` / `…windowHours must be a number` | `exempt` is an `async` function, or `windowHours` is a string / negative | `exempt: ({ user }) => user.email === '…'` (returns `true` / `false` at once); `windowHours: 72` or `false` |
| log: `[ipal] twoFactor.requireSetup.exempt returned a Promise … The account is NOT exempt` (and the service account gets 403) | `exempt` does not return exactly `true` | return a boolean decided from the fields on `user` |
| an administrator's "Reset two-step verification" answers 403 from a script with an API key, or for an exempt account | by default the reset needs a session that entered its own TOTP code | reset from the panel after logging in with the code; or `twoFactor.resetAccess: ({ req }) => …` |
| after "Reset two-step verification" the user is logged out everywhere | intended: the reset ends the account's sessions | the user logs in again with the password and sets 2FA up; after a suspected compromise also change the password |
| no "Two-step verification" box on the account page / no "Reopen setup" | the import map lacks `TwoFactorStatusField` (not regenerated), or `requireSetup: { statusField: false }` | `pnpm payload generate:importmap`, commit, redeploy; meanwhile `POST /api/ipal/two-factor/reset` `{ userId }` works |
| "Two-step verification" is missing on the account page / the dashboard shows a missing component | the import map is stale | `pnpm payload generate:importmap`, commit `importMap.js`, `rm -rf .next`, redeploy |
| 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 |
@@ -42,8 +42,11 @@ description: Complete map of everything @intecion/ipal-kit provides — every ip
| `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` | 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.verifyLimit` | `{ max: 5, windowMinutes: 10 }` | attempts per account on `POST /api/verify-totp` (the 2FA package counts none): the sixth in the window, right or wrong, gets `429` + `Retry-After`; in memory per instance | `{ max, windowMinutes }`; `false` = no limit |
| `twoFactor.requireSetup` | on, `{ windowHours: 72 }` | an account without TOTP reaches nothing but the setup screen and `/api/setup-totp` (REST, GraphQL and the panel's data answer 403); it has `windowHours` from its creation or from an admin's reset, then it is blocked until an admin reopens setup. Adds the fields `totpSetupFrom` (date, written by the plugin) and `totpSetupStatus` (panel) to the 2FA collection, a dashboard notice and `POST /api/ipal/two-factor/reset`. Existing accounts get their window at the first start after the upgrade. Postgres/SQLite: migration; `generate:importmap` | `false` = the package's rule (API open until setup); `{ windowHours: 24 }`, `{ windowHours: false }` (no limit), `{ exempt: ({ user }) => … }` (a service account) |
| `twoFactor.resetAccess` | a staff admin | who may reset another account's TOTP / reopen its setup (the button on the account page, `POST /api/ipal/two-factor/reset`); the second factor is always required | `({ req }) => boolean` |
| `twoFactor.requireSetup` | on, `{ windowHours: 72 }` | an account without TOTP reaches nothing but the setup screen and `/api/setup-totp` (REST, GraphQL and the panel's data answer 403); it has `windowHours` from its creation or from an admin's reset, then it is blocked until an admin reopens setup. Adds the field `totpSetupStatus` (panel) to the 2FA collection, a dashboard notice and `POST /api/ipal/two-factor/reset`; the date field `totpSetupFrom` is there whenever 2FA is on (also with `requireSetup: false` / `guard: false`). Existing accounts get their window at the first start after the upgrade, written once. **Postgres/SQLite: the migration must run before the version serves, or every login answers 500**; `generate:importmap`. `exempt` must return exactly `true` at once (an `async` one, or a `windowHours` that is not a number / `false`, stops the start) | `false` = the package's rule (API open until setup); `{ windowHours: 24 }`, `{ windowHours: false }` (no limit), `{ exempt: ({ user }) => … }` (a service account) |
| `twoFactor.requireSetup.dashboardNotice` / `.statusField` / `.setupNotice` | on | the administrators' notice on the dashboard; the status and reset control on the account page; the notice on the setup screen | `false` each (the lock and the reset endpoint stay) |
| `twoFactor.resetAccess` | a staff admin whose session entered its own TOTP code (not an API key, not an `exempt` account) | who may reset another account's TOTP / reopen its setup (the button on the account page, `POST /api/ipal/two-factor/reset`). The reset clears the secret and the account's sessions. A session that still owes its code is always refused | `({ req }) => boolean` — only `true` allows; `req.user._strategy` tells `'totp'`, `'api-key'`, `'local-jwt'` apart |
| `whiteLabel.inlineImages` | on | on the 2FA screens the logo / icon is fetched by the server as an anonymous visitor gets it (max 512 KB) and inlined as `data:` — the session there is refused `media` | `false` = the browser tries the media URL |
| `adminMeta.serveIcon` | on | `/api/ipal/admin-icon` answers with the favicon's bytes and the upload security headers (sandbox, nosniff) | `false` = a redirect to the media file |
| `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 | — |
@@ -72,7 +72,7 @@ Admin panel components from `@intecion/ipal-kit/admin` — the project does NOT
| `buildRolesField(defaultRole?, { firstUserAdmin? })` | `@intecion/ipal-kit` | The `roles` select field the plugin injects (only admins set roles; `firstUserAdmin` default `true` = the account made on "Create first user" gets `admin`). The plugin wires it itself — use it only for an auth collection the plugin does not manage. |
| `injectRoles(config, accessOption)` | `@intecion/ipal-kit` | Adds `roles` to `accessOption.authCollection` in a config. The plugin calls it itself with `access` — do not call. |
**Types:** `VerifyLimitOptions` (`twoFactor.verifyLimit`: `{ max?, windowMinutes? }`), `SafeBackRule` / `SafeBackContext` (`twoFactor.safeBack` as a function: `(back, { adminRoute, origin? }) => string`), `TotpViewComponent` (a view component as registered: a path or `{ path, exportName?, clientProps?, serverProps? }`), `SafeTotpViewProps` (`@intecion/ipal-kit/admin`), `Role` (`'user' \| 'editor' \| 'admin'`), `AccessOption` (the plugin's `access` option: `authCollection`, `defaultRole`, `authAccess`, `firstUserAdmin`, `staffCollections`).
**Types:** `VerifyLimitOptions` (`twoFactor.verifyLimit`: `{ max?, windowMinutes? }`), `RequireSetupOptions` (`twoFactor.requireSetup`), `TwoFactorResetOptions`, `TwoFactorSetupState`, `SafeBackRule` / `SafeBackContext` (`twoFactor.safeBack` as a function: `(back, { adminRoute, origin? }) => string`), `TotpViewComponent` (a view component as registered: a path or `{ path, exportName?, clientProps?, serverProps? }`), `SafeTotpViewProps` (`@intecion/ipal-kit/admin`), `Role` (`'user' \| 'editor' \| 'admin'`), `AccessOption` (the plugin's `access` option: `authCollection`, `defaultRole`, `authAccess`, `firstUserAdmin`, `staffCollections`).
## Accessibility — widget (`accessibility`) — details: `node_modules/@intecion/ipal-kit/docs/accessibility.md`
@@ -595,6 +595,12 @@ Server only (`pnpm payload run`); never import it from client code, the Payload
| `copyViews(views)` / `changedViewKeys(before, after)` | `@intecion/ipal-kit` | The comparison `ipalKit` uses to tell which views a 2FA factory registered: put `copyViews(views)` into the config before calling the factory, then `changedViewKeys(before, viewsAfter)` gives the keys whose view object changed — the `added` argument of `wrapTotpViews` (`(key) => keys.has(key)`). By object, not by key: the 2FA package replaces a view that already stands under its keys. Example: security.md "Your own 2FA screen". |
| `SAFE_TOTP_VIEW` / `totpViewImportKey(component)` | `@intecion/ipal-kit` | `'@intecion/ipal-kit/admin#SafeTotpView'`, the wrapper's import-map path (the default `wrapper` of `wrapTotpViews`); and the import-map key (`path#export`) of a component given as a string or `{ path, exportName }`. |
| `findImportMapFile(config, cwd?)` / `missingImportMapEntries(config, entries, cwd?)` | `@intecion/ipal-kit` | Where the project's `importMap.js` is on disk (`admin.importMap.importMapFile`, else `app/(payload)<admin route>/` or `src/app/…` under `admin.importMap.baseDir` / the working directory; `null` when not found), and which of `entries` its text does not contain (`{ file, missing }`). A hint from the file on disk, not the map in the build: warn on it, never block on it. Behind `twoFactor.importMapCheck`. |
| `buildSetupFields({ statusField? })`, `stampSetupFrom`, `backfillSetupFrom(payload, collection)` | `@intecion/ipal-kit` | The parts of "2FA setup required" for a project that wires them itself: the fields for the 2FA collection (`totpSetupFrom`, and the panel's `totpSetupStatus` unless `statusField: false`), the `beforeChange` hook that stamps the window start (on create, and when an account loses its TOTP secret), and the start-up step that gives accounts without TOTP and without a start their window (returns how many; once per account). |
| `buildTwoFactorResetEndpoint(collection, { access? })`, `TWO_FACTOR_RESET_PATH` | `@intecion/ipal-kit` | `POST /api/ipal/two-factor/reset` `{ userId }`: clears the account's TOTP secret and sessions and starts a new window. Default: a staff admin whose session entered its own TOTP code; `access` replaces that (only `true` allows; a session that owes its code is always refused). |
| `countAccountsWithoutTotp(payload, collection, setupWindowMs?)` | `@intecion/ipal-kit` | `{ without, blocked }` — accounts of the 2FA collection without TOTP, and how many are past their window. |
| `resolveRequireSetup(option)`, `strictExempt(fn)`, `SETUP_FROM_FIELD`, `DEFAULT_SETUP_WINDOW_HOURS` | `@intecion/ipal-kit` | `twoFactor.requireSetup` → `{ requireSetup, setupWindowMs, exempt? }` as the guard reads it (throws on a `windowHours` that is not a number ≥ 0 or `false`, and on an `async` `exempt`); the wrapper that makes an `exempt` function answer `true` only for exactly `true`; the field name `'totpSetupFrom'`; `72`. |
| `fetchPublicImage(url, base)`, `publicImageDataUri(url, base)`, `siteOrigin(serverURL)`, `PUBLIC_IMAGE_MAX_BYTES` | `@intecion/ipal-kit` | An image fetched the way an anonymous visitor gets it (no cookies; http(s) only; `image/*`; at most 512 KB, reading stops at the limit) as `{ bytes, type }` or a `data:` address, else `null`. Used for the logo and icon on the 2FA screens. |
| `UPLOAD_SECURITY_HEADERS` | `@intecion/ipal-kit` | The two headers of `buildUploadSecurityHeaders` (`Content-Security-Policy: default-src 'none'; … sandbox`, `X-Content-Type-Options: nosniff`) for a route of your own that returns an uploaded file's bytes from the site's origin. |
| `twoFactorSetupState(req)`, `twoFactorSetupDeadline(req)` | `@intecion/ipal-kit` | Where an account stands with TOTP setup, from `{ payload, user }`: `'set-up'`, `'open'` (may set it up now), `'closed'` (the setup window has passed: blocked until an admin reopens it), `'exempt'` (`requireSetup.exempt`, or `requireSetup: false`), `'not-applicable'` (no user, another collection, 2FA off); and the moment setup closes (`Date`, or `null` without a window). Types: `TwoFactorSetupState`, `RequireSetupOptions`. |
| `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` |
+9 -4
View File
@@ -236,10 +236,15 @@ the panel shows Site settings, Site integrations, Cookies, Form messages, the Fo
opens everything its role allows. One entity reachable without the code: `custom.ipal.secondFactor`.
**Setup required** (`twoFactor.requireSetup`, default): an account without TOTP reaches only the setup screen; it
has 72 h from its creation (or an admin's "Reopen setup" on the account page), then it is blocked. So create an
account, hand over the password and have the owner set 2FA up at once. Postgres/SQLite: `pnpm payload
migrate:create` (field `totpSetupFrom`); `pnpm payload generate:importmap` (`TwoFactorStatusField`,
`TwoFactorAlert`). A service account that logs in with a password: `requireSetup: { exempt }`; an API key needs
nothing. One entity reachable without the code: `custom.ipal.secondFactor`.
account, hand over the password and have the owner set 2FA up at once. **Postgres/SQLite: `pnpm payload
migrate:create` and run the migration before the site serves** (column `totp_setup_from`, there whenever 2FA is
on) — without it every login answers 500; `pnpm payload generate:importmap` (`TwoFactorStatusField`,
`TwoFactorAlert`). A service account that logs in with a password: `requireSetup: { exempt }` (a plain function
returning exactly `true`; never `async`); an API key needs nothing. Parts to switch off: `requireSetup:
{ dashboardNotice: false, statusField: false, setupNotice: false }`. An admin's reset ends the account's
sessions and needs the admin's own TOTP code (`twoFactor.resetAccess` changes who). Have two administrators
with 2FA: when all are blocked, only a script or a redeploy helps (security.md "Every administrator is
blocked"). 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 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
+13 -3
View File
@@ -390,14 +390,24 @@ with 2FA on:**
and redeploys do not extend them): agree the deploy day with the owner.
2. Update the package, `pnpm install`, `pnpm ipal:skills`, `pnpm payload generate:types`,
**`pnpm payload generate:importmap`** (new: `TwoFactorStatusField`, `TwoFactorAlert`; commit `importMap.js`).
3. Postgres/SQLite: `pnpm payload migrate:create` (adds `totpSetupFrom` to the 2FA collection), commit. MongoDB: nothing.
3. **Postgres/SQLite — required, same deploy, or nobody can log in:** `pnpm payload migrate:create` (adds the
column `totp_setup_from` to the 2FA collection; needed whenever 2FA is on, also with `requireSetup: false`),
commit, and make sure it is applied before the new version serves requests (the Coolify pre-deploy command
`pnpm payload migrate`). Without the column every login answers 500, administrators included; the log says
`[ipal] 2FA: the column for "totpSetupFrom" is missing … NOBODY CAN LOG IN`. `pnpm exec ipal-doctor` reports
it before the deploy. MongoDB: nothing.
4. An integration that logs in with a password and has no TOTP: give it an API key, or
`twoFactor.requireSetup: { exempt: ({ user }) => user.email === '…' }`. `grep -rn "overrideAccess: false" src`:
a `user` fetched by id is refused for every account now — take it from `payload.auth({ headers })`.
5. `rm -rf .next`, build, redeploy on Coolify. Read the first lines of the log: `[ipal] 2FA: N existing account(s)
without two-step verification…` — pass that number to the owner. The line appears on that first start only.
Postgres/SQLite: the migration from step 3 must run in the same deploy; without it the log says
`could not start the setup window` and the window starts at the first start that has it.
Postgres/SQLite: if logins answer 500 after the deploy, the migration from step 3 did not run — run it now.
6. `requireSetup.exempt` must be a plain function returning `true` / `false` (an `async` one stops the start).
Scripts that used `POST /api/ipal/two-factor/reset` with an API key: refused by default now — pass
`twoFactor.resetAccess` if that is wanted. A reset ends the account's sessions (it logs in again).
**Every administrator is blocked** (all missed the 72 h): security.md "Every administrator is blocked" — a
`pnpm payload run` script that sets `totpSetupFrom` to now for one administrator, or
`requireSetup: { windowHours: false }` + redeploy, set 2FA up, put it back.
**Check:** create a throwaway account → its token gets `403` from `/api/users/me`; in the panel it lands on the
setup screen with "Set up two-step verification by …"; after the code it is in. As an administrator open that
account → "Two-step verification: Set up." and the reset button; delete the account.
+16 -2
View File
@@ -40,6 +40,7 @@ export type { SectionHeaderFieldOptions, SectionSettingsFieldOptions } from './m
export { buildAdminImageEndpoints } from './modules/branding/adminImages.js'
export { ADMIN_META_TEXTS, adminMetaForSite, buildAdminMeta, DEFAULT_AGENCY, syncAdminMeta } from './modules/branding/adminMeta.js'
export type { AdminMetaOptions, AgencyOption, ResolvedAdminMeta } from './modules/branding/adminMeta.js'
export { fetchPublicImage, PUBLIC_IMAGE_MAX_BYTES, publicImageDataUri, siteOrigin } from './modules/branding/publicImage.js'
export {
ACCEPT_ALL_CONSENT,
buildConsentLogCollection,
@@ -312,6 +313,7 @@ export {
parseCspReports,
totpAdminPath,
totpRedirectTarget,
UPLOAD_SECURITY_HEADERS,
withSecurityConfig,
} from './modules/security/index.js'
export type {
@@ -325,14 +327,26 @@ export type {
TotpUser,
WithSecurityConfigOptions,
} from './modules/security/index.js'
export type { BuildSecurityHeadersArgs, SecurityHeader } from './modules/security/index.js'
export type { BuildSecurityHeadersArgs, SecurityHeader } from './modules/security/index.js'
export { findImportMapFile, missingImportMapEntries } from './modules/security/totp/importMapCheck.js'
export { changedViewKeys, copyViews, SAFE_TOTP_VIEW, safeAdminBack, totpViewImportKey, wrapTotpViews } from './modules/security/totp/safeBack.js'
export type { SafeBackContext, SafeBackRule, TotpViewComponent } from './modules/security/totp/safeBack.js'
export { requireSecondFactor, secondFactorPassed, twoFactorSetupDeadline, twoFactorSetupState } from './modules/security/totp/secondFactor.js'
export type { TwoFactorSetupState } from './modules/security/totp/secondFactor.js'
export type { RequireSetupOptions } from './modules/security/totp/setupRequired.js'
export { SETUP_FROM_FIELD } from './modules/security/totp/secondFactor.js'
export {
backfillSetupFrom,
buildSetupFields,
buildTwoFactorResetEndpoint,
countAccountsWithoutTotp,
DEFAULT_SETUP_WINDOW_HOURS,
resolveRequireSetup,
stampSetupFrom,
strictExempt,
TWO_FACTOR_RESET_PATH,
} from './modules/security/totp/setupRequired.js'
export type { RequireSetupOptions, TwoFactorResetOptions } from './modules/security/totp/setupRequired.js'
export { TOTP_TEXTS, TOTP_VIEW_TITLE } from './modules/security/totp/totpTexts.js'
export type { VerifyLimitOptions } from './modules/security/totp/verifyLimit.js'
export type { OgImage } from './modules/seo/buildMetadata.js'
+3 -1
View File
@@ -27,6 +27,8 @@ import { publicImageDataUri, siteOrigin } from './publicImage.js'
type BrandingProps = {
/** Upload field to render as the image. Default 'logo' (Logo) / 'favicon' (Icon). */
imageField?: string
/** `whiteLabel.inlineImages: false` — never fetch the image on the server for the 2FA screens. */
inlineImages?: false
/** Injected by Payload — current admin locale (object or code). */
locale?: { code?: string } | string
/** Field holding the site name. Default 'siteName'. */
@@ -78,7 +80,7 @@ async function loadBranding(
// other collection, so the browser would show a broken image on the verify / setup screens.
// Give it the picture itself, fetched as an anonymous visitor would get it; when that fails
// (media is not public), the site name is shown instead.
if (url && props.user && !secondFactorPassed({ payload, user: props.user })) {
if (url && props.inlineImages !== false && props.user && !secondFactorPassed({ payload, user: props.user })) {
return { name, url: await publicImageDataUri(url, siteOrigin(payload.config.serverURL)) }
}
return { name, url }
+12 -5
View File
@@ -2,6 +2,7 @@ import type { Endpoint, PayloadRequest } from 'payload'
import type { AgencyOption, ResolvedAdminMeta } from './adminMeta.js'
import { UPLOAD_SECURITY_HEADERS } from '../security/buildSecurityHeaders.js'
import { ADMIN_ICON_PATH, ADMIN_META_TEXTS, ADMIN_OG_PATH } from './adminMeta.js'
import { fetchPublicImage } from './publicImage.js'
@@ -14,13 +15,13 @@ import { fetchPublicImage } from './publicImage.js'
* the site name, then to initials.
*/
type Fields = { iconField?: string; logoField?: string; nameField?: string; settingsSlug?: string }
type Fields = { iconField?: string; logoField?: string; nameField?: string; serveIcon?: false; settingsSlug?: string }
type Branding = { icon: null | string; logo: null | string; name: string }
const CACHE = 'public, max-age=3600, s-maxage=3600'
async function loadBranding(req: PayloadRequest, f: Required<Fields>): Promise<Branding> {
async function loadBranding(req: PayloadRequest, f: Required<Omit<Fields, 'serveIcon'>>): Promise<Branding> {
try {
const locale = req.payload.config.localization ? req.payload.config.localization.defaultLocale : undefined
const s = (await req.payload.findGlobal({ slug: f.settingsSlug as never, depth: 1, ...(locale ? { locale: locale as never } : {}), req })) as Record<string, unknown>
@@ -63,7 +64,7 @@ const initials = (name: string) =>
.join('') || 'A'
export function buildAdminImageEndpoints(resolved: ResolvedAdminMeta, fields: Fields = {}): Endpoint[] {
const f: Required<Fields> = {
const f: Required<Omit<Fields, 'serveIcon'>> = {
iconField: fields.iconField ?? 'favicon',
logoField: fields.logoField ?? 'logo',
nameField: fields.nameField ?? 'siteName',
@@ -110,8 +111,14 @@ export function buildAdminImageEndpoints(resolved: ResolvedAdminMeta, fields: Fi
// media file: a panel session that still owes its 2FA code is refused that file (it is
// refused every collection), and a cached redirect would send it there anyway. The answer
// is the same for everyone, so it can be cached like the redirect was.
const image = await fetchPublicImage(absolute(brand.icon, req), null)
if (image) {return new Response(new Uint8Array(image.bytes), { headers: { 'Cache-Control': CACHE, 'Content-Type': image.type } })}
const image = fields.serveIcon === false ? null : await fetchPublicImage(absolute(brand.icon, req), null)
// An uploaded file from the site's own origin: the same headers as the upload routes
// (an SVG may be displayed, never run script — sandbox, no sniffing).
if (image) {
return new Response(new Uint8Array(image.bytes), {
headers: { 'Cache-Control': CACHE, 'Content-Type': image.type, ...Object.fromEntries(UPLOAD_SECURITY_HEADERS.map((h) => [h.key, h.value])) },
})
}
// Not fetchable from here (too large, or media is not public): let the browser try.
return new Response(null, { headers: { 'Cache-Control': CACHE, Location: absolute(brand.icon, req) }, status: 302 })
}
+6
View File
@@ -37,6 +37,12 @@ export type AdminMetaOptions = {
language?: 'en' | 'pl'
/** Robots meta. Default noindex, nofollow. `false` = none. */
robots?: { follow?: boolean; index?: boolean } | false
/**
* `/api/ipal/admin-icon` answers with the favicon's bytes (fetched as an anonymous visitor gets
* them, with the upload security headers), so it also loads for a session that still owes its
* 2FA code. `false` = a redirect to the media file instead, as before.
*/
serveIcon?: false
/** Browser-tab suffix; `{site}` is replaced. Default "— {site} | Panel". `false` = none. */
titleSuffix?: false | string
}
+29 -3
View File
@@ -6,7 +6,8 @@
* same file is public. Serving the bytes from here opens nothing: only what
* answers an anonymous request comes back, and only an image of a sane size.
*/
const MAX_BYTES = 512 * 1024
export const PUBLIC_IMAGE_MAX_BYTES = 512 * 1024
const MAX_BYTES = PUBLIC_IMAGE_MAX_BYTES
export async function fetchPublicImage(url: null | string | undefined, base: null | string | undefined): Promise<{ bytes: Buffer; type: string } | null> {
if (!url) {return null}
@@ -22,14 +23,39 @@ export async function fetchPublicImage(url: null | string | undefined, base: nul
if (!res.ok) {return null}
const type = (res.headers.get('content-type') ?? '').split(';')[0].trim()
if (!type.startsWith('image/')) {return null}
const bytes = Buffer.from(await res.arrayBuffer())
if (!bytes.length || bytes.length > MAX_BYTES) {return null}
// Too large is known before reading when the server says so; otherwise stop reading at the limit.
const declared = Number(res.headers.get('content-length'))
if (Number.isFinite(declared) && declared > MAX_BYTES) {
await res.body?.cancel().catch(() => undefined)
return null
}
const bytes = await readUpTo(res, MAX_BYTES)
if (!bytes?.length) {return null}
return { type, bytes }
} catch {
return null
}
}
/** The body, or null as soon as it grows past `limit` (the rest is not downloaded). */
async function readUpTo(res: Response, limit: number): Promise<Buffer | null> {
const reader = res.body?.getReader()
if (!reader) {return null}
const chunks: Uint8Array[] = []
let size = 0
for (;;) {
const { done, value } = await reader.read()
if (done) {break}
size += value.byteLength
if (size > limit) {
await reader.cancel().catch(() => undefined)
return null
}
chunks.push(value)
}
return Buffer.concat(chunks)
}
/** The same as a `data:` address for an `<img>`. */
export async function publicImageDataUri(url: null | string | undefined, base: null | string | undefined): Promise<null | string> {
const image = await fetchPublicImage(url, base)
+7
View File
@@ -198,6 +198,13 @@ export const layoutRules: DoctorRule[] = [
if (/payloadTotp/.test(cfg)) {
need.push('@clocklimited/payload-2fa/rsc#TOTPSetup')
if (!lt(v, '1.14.2')) {need.push('@intecion/ipal-kit/admin#TotpRedirectProvider')}
// "2FA setup required": the status / reset control on the account and the dashboard notice — when the
// installed plugin has them and the config does not switch them (or the mode) off. Without them the
// panel shows no "Reopen setup": the documented way out of a blocked account is missing.
const adminExports = ctx.read('node_modules/@intecion/ipal-kit/dist/exports/admin.js')
const modeOff = /requireSetup\s*:\s*false|guard\s*:\s*false/.test(cfg)
if (/\bTwoFactorStatusField\b/.test(adminExports) && !modeOff && !/statusField\s*:\s*false/.test(cfg)) {need.push('@intecion/ipal-kit/admin#TwoFactorStatusField')}
if (/\bTwoFactorAlert\b/.test(adminExports) && !modeOff && !/dashboardNotice\s*:\s*false/.test(cfg)) {need.push('@intecion/ipal-kit/admin#TwoFactorAlert')}
// the back-link check in front of the 2FA screens (twoFactor.safeBack) — when the installed plugin has it
if (/\bSafeTotpView\b/.test(ctx.read('node_modules/@intecion/ipal-kit/dist/exports/admin.js')) && !/safeBack\s*:\s*false/.test(cfg)) {
need.push('@intecion/ipal-kit/admin#SafeTotpView')
+17
View File
@@ -108,6 +108,23 @@ export const securityRules: DoctorRule[] = [
else if (!ctx.installed('@clocklimited/payload-2fa')) {out.push({ fix: 'pnpm add @clocklimited/payload-2fa', message: '@clocklimited/payload-2fa is not installed', severity: 'error' })}
if (/requireSetup\s*:\s*false/.test(code)) {out.push({ file: configFile(ctx) ?? undefined, fix: 'remove twoFactor.requireSetup: false (or record the reason in ipal-doctor.json)', message: 'twoFactor.requireSetup is off: an account that has not set 2FA up opens everything with its password alone', severity: 'warning' })}
if (/windowHours\s*:\s*(?:false|0)\b/.test(code)) {out.push({ file: configFile(ctx) ?? undefined, fix: 'twoFactor.requireSetup.windowHours: 72 (the default)', message: 'no time limit for 2FA setup: an account that never sets it up can be taken over with its password at any time', severity: 'info' })}
// Postgres / SQLite: the 2FA collection has the column `totp_setup_from` (whenever 2FA is on). Without a
// migration that adds it, every query on the collection fails in production — nobody can log in.
const sqlAdapter = ['@payloadcms/db-postgres', '@payloadcms/db-vercel-postgres', '@payloadcms/db-sqlite', '@payloadcms/db-d1-sqlite'].some((name) => ctx.installed(name))
const pluginHasColumn = /totpSetupFrom/.test(ctx.read('node_modules/@intecion/ipal-kit/dist/modules/security/totp/secondFactor.js'))
if (sqlAdapter && pluginHasColumn && /payloadTotp/.test(code)) {
const dirs = [`${ctx.src}migrations`, 'migrations'].filter((dir) => ctx.exists(dir))
const files = dirs.flatMap((dir) => ctx.list(dir).filter((name) => /\.(?:ts|js|mjs|sql|json)$/.test(name)).map((name) => `${dir}/${name}`))
if (!files.some((file) => /totp_setup_from|totpSetupFrom/.test(ctx.read(file)))) {
out.push({
fix: 'pnpm payload migrate:create, commit the migration, and run it (pnpm payload migrate) in the same deploy, before the new version serves requests',
message: files.length
? 'no migration adds the 2FA column `totp_setup_from`: in production every login would answer 500 — nobody could sign in to the panel'
: 'a SQL database and no migrations folder: the 2FA column `totp_setup_from` must exist before this version runs in production (migrate:create), or nobody can sign in',
severity: files.length ? 'error' : 'warning',
})
}
}
if (ctx.deep?.usersWithout2fa) {
const closed = ctx.deep.usersSetupClosed ?? 0
out.push({
+10 -5
View File
@@ -161,9 +161,14 @@ export function buildUploadSecurityHeaders({ collections = ['media'] }: { collec
headers: SecurityHeader[]
source: string
}[] {
const headers: SecurityHeader[] = [
{ key: 'Content-Security-Policy', value: "default-src 'none'; img-src 'self' data:; style-src 'unsafe-inline'; sandbox" },
{ key: 'X-Content-Type-Options', value: 'nosniff' },
]
return collections.map((slug) => ({ headers, source: `/api/${slug}/file/:path*` }))
return collections.map((slug) => ({ headers: [...UPLOAD_SECURITY_HEADERS], source: `/api/${slug}/file/:path*` }))
}
/**
* The headers themselves: for any response that carries the bytes of an uploaded file from the
* site's own origin (the upload routes above; the plugin's `/api/ipal/admin-icon`; a route of yours).
*/
export const UPLOAD_SECURITY_HEADERS: readonly SecurityHeader[] = [
{ key: 'Content-Security-Policy', value: "default-src 'none'; img-src 'self' data:; style-src 'unsafe-inline'; sandbox" },
{ key: 'X-Content-Type-Options', value: 'nosniff' },
]
+1 -1
View File
@@ -8,7 +8,7 @@ export {
DEFAULT_CSP_REPORT_GROUP,
} from './buildCsp.js'
export type { BuildAdminCspArgs, BuildCspArgs, CspDirective, CspSources } from './buildCsp.js'
export { buildSecurityHeaders, buildUploadSecurityHeaders } from './buildSecurityHeaders.js'
export { buildSecurityHeaders, buildUploadSecurityHeaders, UPLOAD_SECURITY_HEADERS } from './buildSecurityHeaders.js'
export type { BuildSecurityHeadersArgs, SecurityHeader } from './buildSecurityHeaders.js'
export { createCspReportRoute, parseCspReports } from './createCspReportRoute.js'
export type { CreateCspReportRouteArgs, CspViolation } from './createCspReportRoute.js'
+8 -3
View File
@@ -74,7 +74,11 @@ export const SETUP_FROM_FIELD = 'totpSetupFrom'
*/
export type TwoFactorSetupState = 'closed' | 'exempt' | 'not-applicable' | 'open' | 'set-up'
/** The moment setup closes for this account, or null (no window, or no start recorded yet). */
/**
* The moment setup closes for this account, or null (no window, or no start recorded yet).
* A start that is missing or unreadable counts as "no deadline yet" (the account can still only
* set TOTP up): only server code writes the field, and the start-up step fills in a missing one.
*/
export function twoFactorSetupDeadline({ payload, user }: MaybeReq): Date | null {
const guard = guardConfig(payload)
const from = (user as null | Record<string, unknown> | undefined)?.[SETUP_FROM_FIELD]
@@ -89,7 +93,7 @@ export function twoFactorSetupState({ payload, user }: MaybeReq, now: number = D
const u = user as { collection?: unknown; hasTotp?: unknown }
if (u.collection !== guard.collection) {return 'not-applicable'}
if (u.hasTotp !== false || (user as { totpSecret?: unknown }).totpSecret) {return 'set-up'}
if (!guard.requireSetup || guard.exempt?.({ user: user as Record<string, unknown> })) {return 'exempt'}
if (!guard.requireSetup || guard.exempt?.({ user: user as Record<string, unknown> }) === true) {return 'exempt'}
const deadline = twoFactorSetupDeadline({ payload, user })
return deadline && deadline.getTime() < now ? 'closed' : 'open'
}
@@ -124,7 +128,8 @@ export function secondFactorPassed({ payload, user }: MaybeReq): boolean {
// came with the account's own record) then still says the account has TOTP: refused.
if (u.hasTotp !== false || (user as { totpSecret?: unknown }).totpSecret) {return false}
// TOTP not set up: only when setup is not required, or for an account the project exempts
return !guard.requireSetup || Boolean(guard.exempt?.({ user: user as Record<string, unknown> }))
// Exactly `true`: a Promise or any other truthy answer must never let an account in.
return !guard.requireSetup || guard.exempt?.({ user: user as Record<string, unknown> }) === true
}
const GUARDED = Symbol.for('ipal.secondFactorGuard')
+119 -18
View File
@@ -20,12 +20,22 @@ import { secondFactorPassed, SETUP_FROM_FIELD } from './secondFactor.js'
*/
export type RequireSetupOptions = {
/** The notice for administrators on the dashboard (accounts without 2FA, how many are blocked). `false` = none. */
dashboardNotice?: false
/**
* Accounts that may work without TOTP on purpose — a service account that
* logs in with a password. Return true to exempt. (An API key needs no
* exemption: it passes by itself.) `({ user }) => user.email === '[email protected]'`
* logs in with a password. Return **exactly `true`** to exempt, and return it
* at once: the function is called in access checks, which cannot wait. An
* `async` function stops the site at start; any other answer than `true`
* (a Promise, a string, an error thrown) exempts nobody and is logged.
* (An API key needs no exemption: it passes by itself.)
* `({ user }) => user.email === '[email protected]'`
*/
exempt?: (args: { user: Record<string, unknown> }) => boolean
/** The notice on the setup screen (until when; or that the time has passed). `false` = none. */
setupNotice?: false
/** The "Two-step verification" status and reset control on the account in the panel. `false` = none (the reset endpoint stays). */
statusField?: false
/**
* Hours an account has to set TOTP up, counted from its creation or from the
* last reset by an admin. After that it is blocked until an admin reopens
@@ -44,17 +54,76 @@ export function resolveRequireSetup(option: false | RequireSetupOptions | undefi
setupWindowMs: number
} {
if (option === false) {return { requireSetup: false, setupWindowMs: 0 }}
const hours = option?.windowHours === false ? 0 : (option?.windowHours ?? DEFAULT_SETUP_WINDOW_HOURS)
// A typo must not loosen the rule: '24', -1 or NaN used to mean "no limit".
const given = option?.windowHours
if (given !== undefined && given !== false && (typeof given !== 'number' || !Number.isFinite(given) || given < 0)) {
throw new Error(
`[ipal] twoFactor.requireSetup.windowHours must be a number of hours (0 or more) or false, got ${JSON.stringify(given) ?? String(given)}. ` +
'Use 72 (the default), another number, or false / 0 for no time limit.',
)
}
const hours = given === false ? 0 : (given ?? DEFAULT_SETUP_WINDOW_HOURS)
return {
...(option?.exempt ? { exempt: option.exempt } : {}),
...(option?.exempt !== undefined ? { exempt: strictExempt(option.exempt) } : {}),
requireSetup: true,
setupWindowMs: Number.isFinite(hours) && hours > 0 ? hours * 60 * 60 * 1000 : 0,
setupWindowMs: hours > 0 ? hours * 60 * 60 * 1000 : 0,
}
}
/** The two fields for the 2FA collection: the window start (data) and its status / reset control (panel). */
export function buildSetupFields(): Field[] {
return [
/** What was already said about a wrong `exempt` answer: each kind is logged once per process. */
const exemptComplaints = new Set<string>()
/**
* The project's `exempt`, made safe to call from an access check: only an answer of exactly
* `true` exempts. An async function is refused at start (its Promise would be truthy for every
* account — everyone let in on a password); any other answer, or an error, exempts nobody and
* is logged (once per kind of wrong answer).
*/
export function strictExempt(exempt: unknown): NonNullable<RequireSetupOptions['exempt']> {
if (typeof exempt !== 'function') {
throw new Error('[ipal] twoFactor.requireSetup.exempt must be a function: ({ user }) => boolean.')
}
if (exempt.constructor?.name === 'AsyncFunction') {
throw new Error(
'[ipal] twoFactor.requireSetup.exempt must not be async: it is called in access checks, which cannot wait, and a Promise ' +
'would count as "exempt" for every account. Return true or false at once (decide from the fields on `user`).',
)
}
const complain = (what: string) => {
const kind = what.replace(/\(.*\)$/, '')
if (exemptComplaints.has(kind)) {return}
exemptComplaints.add(kind)
console.error(`[ipal] twoFactor.requireSetup.exempt ${what}; it must return true or false at once. The account is NOT exempt.`)
}
return (args) => {
let answer: unknown
try {
answer = (exempt as (a: typeof args) => unknown)(args)
} catch (err) {
complain(`threw (${err instanceof Error ? err.message : String(err)})`)
return false
}
if (answer === true) {return true}
if (answer !== false && answer !== undefined && answer !== null) {
// a Promise that rejects later must not become an unhandled rejection
if (typeof (answer as { then?: unknown }).then === 'function') {void (answer as Promise<unknown>).then(undefined, () => undefined)}
complain(`returned ${typeof (answer as { then?: unknown }).then === 'function' ? 'a Promise' : `a ${typeof answer}`}`)
}
return false
}
}
/**
* The fields for the 2FA collection: the window start (data) and, unless `statusField: false`,
* its status / reset control (panel).
*
* ipalKit adds the data field **whenever 2FA is on**, also with `requireSetup: false` or
* `guard: false`: the collection's schema then does not depend on those switches — on Postgres /
* SQLite switching the mode off would otherwise drop the column with the next migration, and
* switching it on again would hand every account without TOTP a new window.
*/
export function buildSetupFields({ statusField = true }: { statusField?: boolean } = {}): Field[] {
const fields: Field[] = [
{
name: SETUP_FROM_FIELD,
type: 'date',
@@ -67,7 +136,9 @@ export function buildSetupFields(): Field[] {
admin: { disableBulkEdit: true, disableListColumn: true, disableListFilter: true, hidden: true },
label: { en: 'Two-step verification: setup open since', pl: 'Weryfikacja dwuetapowa: konfiguracja otwarta od' },
},
{
]
if (statusField) {
fields.push({
name: 'totpSetupStatus',
type: 'ui',
admin: {
@@ -75,8 +146,9 @@ export function buildSetupFields(): Field[] {
disableListColumn: true,
position: 'sidebar',
},
},
]
})
}
return fields
}
/**
@@ -122,21 +194,46 @@ export async function backfillSetupFrom(payload: BasePayload, collection: string
}
return totalDocs
} catch (err) {
payload.logger.warn(`[ipal] 2FA: could not start the setup window for existing accounts (${err instanceof Error ? err.message : String(err)}). On Postgres / SQLite run the migration that adds "${SETUP_FROM_FIELD}".`)
const reason = err instanceof Error ? err.message : String(err)
// On Postgres / SQLite this is the missing column — and then it is not only this step that fails:
// every query on the collection selects the column, so EVERY login answers 500 until it exists.
const adapter = (payload.db as { name?: unknown } | undefined)?.name
if (/postgres|sqlite/i.test(typeof adapter === 'string' ? adapter : '') || /column|no such/i.test(reason)) {
payload.logger.error(
`[ipal] 2FA: the column for "${SETUP_FROM_FIELD}" is missing on "${collection}" (${reason}). NOBODY CAN LOG IN to the panel until the ` +
'migration that adds it has run — administrators with 2FA included. Run `pnpm payload migrate:create`, commit the migration and ' +
'run it (`pnpm payload migrate`) before this version serves requests (docs/security.md "Setup required" → Data).',
)
} else {
payload.logger.warn(`[ipal] 2FA: could not start the setup window for existing accounts (${reason}).`)
}
return 0
}
}
export type TwoFactorResetOptions = {
/** Who may reset another account's TOTP. Default: a staff admin (`userMeetsRole(req, 'admin')`). The second factor is always required. */
/**
* Who may reset another account's TOTP. Default: a staff admin whose session has **entered its
* TOTP code** (`_strategy: 'totp'`) — not an API key, and not an account `requireSetup.exempt`
* lets work on its password. With your own function the session must still not owe a second
* factor (`secondFactorPassed`), and the rest is yours: an API-key or exempt admin passes only
* if you return true for it (`req.user._strategy` tells them apart).
*/
access?: (args: { req: PayloadRequest }) => boolean | Promise<boolean>
}
/**
* POST /api/ipal/two-factor/reset `{ userId }` — clears that account's TOTP
* secret. The account must set TOTP up again, and its setup window starts
* anew. For a lost phone, and to reopen setup for an account whose window has
* passed. Admins only, and only after their own second factor.
* secret **and its sessions**. The account must log in and set TOTP up again,
* and its setup window starts anew. For a lost phone, and to reopen setup for
* an account whose window has passed. Admins only, and only after their own
* TOTP code.
*
* The sessions go because a reset is also what an administrator presses for an
* account that may be in someone else's hands: a session that had passed 2FA
* would otherwise be a password-less way to enrol a new authenticator
* (`/api/setup-totp` asks for no password). With `auth.useSessions: false`
* there is nothing to clear — tokens then live until they expire.
*/
export function buildTwoFactorResetEndpoint(collection: string, options: TwoFactorResetOptions = {}): Endpoint {
return {
@@ -146,7 +243,9 @@ export function buildTwoFactorResetEndpoint(collection: string, options: TwoFact
Boolean(req.user) &&
secondFactorPassed(req) &&
(req.user as { collection?: unknown }).collection === collection &&
(options.access ? Boolean(await options.access({ req })) : userMeetsRole(req, 'admin'))
(options.access
? (await options.access({ req })) === true
: (req.user as { _strategy?: unknown })._strategy === 'totp' && userMeetsRole(req, 'admin'))
if (!allowed) {return Response.json({ message: serverText(i18n, 'twoFactorResetForbidden'), ok: false }, { status: 403 })}
let body: unknown
try {
@@ -159,7 +258,9 @@ export function buildTwoFactorResetEndpoint(collection: string, options: TwoFact
return Response.json({ message: serverText(i18n, 'twoFactorResetFailed'), ok: false }, { status: 400 })
}
try {
await req.payload.update({ id: userId, collection: collection as never, data: { [SETUP_FROM_FIELD]: new Date().toISOString(), totpSecret: null } as never, overrideAccess: true, req })
const useSessions = (req.payload.collections as Record<string, { config?: { auth?: { useSessions?: boolean } } }>)[collection]?.config?.auth?.useSessions !== false
const data = { [SETUP_FROM_FIELD]: new Date().toISOString(), totpSecret: null, ...(useSessions ? { sessions: [] } : {}) }
await req.payload.update({ id: userId, collection: collection as never, data: data as never, overrideAccess: true, req })
} catch (err) {
req.payload.logger.error(`[ipal] 2FA reset failed: ${err instanceof Error ? err.message : String(err)}`)
return Response.json({ message: serverText(i18n, 'twoFactorResetFailed'), ok: false }, { status: 400 })
+32 -13
View File
@@ -194,6 +194,9 @@ export const ipalKit = (options: IpalOptions): Plugin => {
/** 2FA collection when "setup required" is on — its existing accounts get their setup window in onInit. */
let setupRequiredFor: null | string = null
let setupWindowHours = 0
/** requireSetup.setupNotice / statusField (on unless switched off). */
let setupNotice = true
let statusField = false
if (options.twoFactor !== false) {
const tf = options.twoFactor
if (!tf?.issuer) {
@@ -272,6 +275,10 @@ export const ipalKit = (options: IpalOptions): Plugin => {
config.collections = guardNewEntityEndpoints(config.collections, entityEndpointsBefore, target, guards as never)
config.globals = guardNewEntityEndpoints(config.globals, entityEndpointsBefore, target, guards as never)
twoFactorCollection = target
// The window-start field is part of the 2FA collection whenever 2FA is on — the schema must
// not depend on requireSetup / guard (setupRequired.ts, buildSetupFields). The panel's status
// field joins it below, when the mode is on. Validates requireSetup at start either way.
if (tf.requireSetup !== false) {resolveRequireSetup(tf.requireSetup)}
// The views the 2FA package registered, by object: it REPLACES a view the project (or an
// earlier run of the package, or of ipalKit) already had under its keys, so a key that
// existed before is no sign that the view is the project's own. Taken here, before the
@@ -298,24 +305,29 @@ export const ipalKit = (options: IpalOptions): Plugin => {
// "Setup required" (default): an account without TOTP reaches nothing but the setup
// screen, and only within the window; requireSetup: false = the package's rule.
const setup = resolveRequireSetup(tf.requireSetup)
const setupParts = typeof tf.requireSetup === 'object' ? tf.requireSetup : {}
config.custom = { ...config.custom, ipal: { ...config.custom?.ipal, twoFactor: { collection: target, ...setup } } }
if (setup.requireSetup) {
setupRequiredFor = target
setupWindowHours = setup.setupWindowMs / 3_600_000
setupNotice = setupParts.setupNotice !== false
statusField = setupParts.statusField !== false
// The stamp hook only while the mode is on: an account made while it is off gets its
// window when the mode is switched on (the start-up step), not a creation date long past.
config.collections = (config.collections ?? []).map((c) =>
c.slug === target
? { ...c, fields: [...c.fields, ...buildSetupFields()], hooks: { ...c.hooks, beforeChange: [...(c.hooks?.beforeChange ?? []), stampSetupFrom] } }
: c,
c.slug === target ? { ...c, hooks: { ...c.hooks, beforeChange: [...(c.hooks?.beforeChange ?? []), stampSetupFrom] } } : c,
)
config.admin = {
...config.admin,
components: {
...config.admin?.components,
beforeDashboard: [
...(config.admin?.components?.beforeDashboard ?? []),
{ path: '@intecion/ipal-kit/admin#TwoFactorAlert', serverProps: { adminRoute: options.adminRoute ?? '/admin' } },
],
},
if (setupParts.dashboardNotice !== false) {
config.admin = {
...config.admin,
components: {
...config.admin?.components,
beforeDashboard: [
...(config.admin?.components?.beforeDashboard ?? []),
{ path: '@intecion/ipal-kit/admin#TwoFactorAlert', serverProps: { adminRoute: options.adminRoute ?? '/admin' } },
],
},
}
}
}
// An admin resets an account's TOTP (lost phone) / reopens its setup window.
@@ -330,6 +342,11 @@ export const ipalKit = (options: IpalOptions): Plugin => {
)
}
// The window start (data) whenever 2FA is on; the status / reset control when the mode is.
config.collections = (config.collections ?? []).map((c) =>
c.slug === target ? { ...c, fields: [...c.fields, ...buildSetupFields({ statusField })] } : c,
)
// The package's texts are long and informal: ipal-kit's (admin-ux.md) go over
// them, the project's own i18n.translations over both. The 2FA screens get a
// tab title instead of "Payload" (view meta is a plain string: the site's language).
@@ -375,7 +392,7 @@ export const ipalKit = (options: IpalOptions): Plugin => {
p && (typeof p === 'string' ? p : p.path) === TOTP_PACKAGE_PROVIDER
? {
...ours,
clientProps: { forceSetup: true, ...(setupRequiredFor ? { requireSetup: true, setupWindowHours } : {}), ...ours.clientProps },
clientProps: { forceSetup: true, ...(setupRequiredFor && setupNotice ? { requireSetup: true, setupWindowHours } : {}), ...ours.clientProps },
serverProps: { ...(typeof p === 'object' ? p.serverProps : {}), ...ours.serverProps },
}
: p,
@@ -441,6 +458,7 @@ export const ipalKit = (options: IpalOptions): Plugin => {
const serverProps: Record<string, unknown> = {}
if (wl.settingsSlug) {serverProps.settingsSlug = wl.settingsSlug}
if (wl.nameField) {serverProps.nameField = wl.nameField}
if (wl.inlineImages === false) {serverProps.inlineImages = false}
const logoProps = { ...serverProps, ...(wl.logoField ? { imageField: wl.logoField } : {}) }
const iconProps = { ...serverProps, ...(wl.iconField ? { imageField: wl.iconField } : {}) }
@@ -513,6 +531,7 @@ export const ipalKit = (options: IpalOptions): Plugin => {
iconField: brandFields.iconField,
logoField: brandFields.logoField,
nameField: brandFields.nameField,
serveIcon: options.adminMeta?.serveIcon,
settingsSlug,
}),
]
+8
View File
@@ -345,6 +345,14 @@ export type IpalOptions = {
| boolean
/** Upload field for the small nav icon. Default 'favicon'. */
iconField?: string
/**
* On the 2FA screens the panel's logo and icon are fetched by the server
* the way an anonymous visitor gets them and put into the page as a
* `data:` image: the session there is refused every collection, `media`
* included, so the browser could not load them. `false` = never fetch;
* the browser tries the media URL and shows the site name when refused.
*/
inlineImages?: false
/** Upload field for the login/nav logo. Default 'logo'. */
logoField?: string
/** Field with the site name. Default 'siteName'. */
+51
View File
@@ -99,6 +99,57 @@ describe('importmap rule and the 2FA back-link check', () => {
})
})
describe('2FA setup required: what a project must have', () => {
const MAP = 'src/app/(payload)/admin/importMap.js'
const NEW = ['@intecion/ipal-kit/admin#TwoFactorStatusField', '@intecion/ipal-kit/admin#TwoFactorAlert']
const OLD = ['@clocklimited/payload-2fa/rsc#TOTPSetup', '@intecion/ipal-kit/admin#TotpRedirectProvider', '@intecion/ipal-kit/admin#SafeTotpView']
const entries = (names: string[]) => `export const importMap = { ${names.map((n) => `"${n}": X`).join(', ')} }`
const plugin = {
...base(),
...installed('@clocklimited/payload-2fa', '3.0.0'),
'node_modules/@intecion/ipal-kit/dist/exports/admin.js': 'export { SafeTotpView, TotpRedirectProvider, TwoFactorAlert, TwoFactorStatusField }',
'node_modules/@intecion/ipal-kit/dist/modules/security/totp/secondFactor.js': "export const SETUP_FROM_FIELD = 'totpSetupFrom'",
}
const lacks = async (config: string, map: string[]) =>
(await doctor(project({ ...plugin, [MAP]: entries(map), 'src/payload.config.ts': config }), ['importmap'])).findings.filter((f) => /import map lacks/.test(f.message)).map((f) => f.message).join()
test('the import map must hold the status field and the dashboard notice', async () => {
const missing = await lacks('twoFactor: { plugin: payloadTotp }', OLD)
for (const name of NEW) {expect(missing).toContain(name)}
const complete = await lacks('twoFactor: { plugin: payloadTotp }', [...OLD, ...NEW])
for (const name of NEW) {expect(complete).not.toContain(name)}
})
test.each([
['requireSetup: false', []],
['guard: false', []],
['requireSetup: { statusField: false }', [NEW[1]]],
['requireSetup: { dashboardNotice: false }', [NEW[0]]],
])('%s: only what is still on is expected', async (option, expected) => {
const missing = await lacks(`twoFactor: { plugin: payloadTotp, ${option} }`, OLD)
for (const name of NEW) {expect([name, missing.includes(name)]).toEqual([name, expected.includes(name)])}
})
const migration = async (files: Record<string, object | string>, config = 'twoFactor: { plugin: payloadTotp }') =>
(await doctor(project({ ...plugin, [MAP]: entries([...OLD, ...NEW]), 'src/payload.config.ts': config, ...files }), ['2fa'])).findings.filter((f) => /totp_setup_from/.test(f.message)).map((f) => f.severity)
test('Postgres / SQLite: a migration must add the 2FA column, or nobody can log in', async () => {
const pg = installed('@payloadcms/db-postgres', '3.94.1')
expect(await migration({ ...pg, 'src/migrations/20260101_init.ts': 'await db.execute(sql`CREATE TABLE "users" ("id" serial)`)' })).toEqual(['error'])
expect(await migration({ ...pg, 'src/migrations/20260101_init.ts': 'x', 'src/migrations/20261124_totp.ts': 'ALTER TABLE "users" ADD COLUMN "totp_setup_from" timestamp' })).toEqual([])
expect(await migration({ ...pg, 'migrations/20261124_totp.json': '{ "columns": { "totpSetupFrom": {} } }' })).toEqual([])
expect(await migration(pg)).toEqual(['warning']) // no migrations folder: the doctor cannot see how the schema gets there
expect(await migration({ ...installed('@payloadcms/db-sqlite', '3.94.1'), 'src/migrations/20260101_init.ts': 'x' })).toEqual(['error'])
})
test('MongoDB, 2FA off, or a plugin version without the column: nothing to report', async () => {
expect(await migration({ ...installed('@payloadcms/db-mongodb', '3.94.1'), 'src/migrations/20260101_init.ts': 'x' })).toEqual([])
expect(await migration({ ...installed('@payloadcms/db-postgres', '3.94.1'), 'src/migrations/20260101_init.ts': 'x' }, 'twoFactor: false')).toEqual([])
const older = { ...installed('@payloadcms/db-postgres', '3.94.1'), 'node_modules/@intecion/ipal-kit/dist/modules/security/totp/secondFactor.js': 'export {}', 'src/migrations/20260101_init.ts': 'x' }
expect(await migration(older)).toEqual([])
})
})
describe('helpers', () => {
test('parseEnvFile reads KEY=value, strips quotes, skips comments', () => {
expect(parseEnvFile('# c\nA=1\nexport B="two"\n C = \'3\'\nbad line')).toEqual({ A: '1', B: 'two', C: '3' })
+74
View File
@@ -72,3 +72,77 @@ describe('the brand image for a session the browser cannot load it in', () => {
expect((await icon.handler(req as never)).status).toBe(302)
})
})
// An uploaded SVG from the site's own origin can run script when opened directly. The upload routes send a sandbox
// policy for that; the icon endpoint serves the same bytes and must send the same headers.
describe('the tab icon endpoint and an SVG', () => {
const SVG = '<svg xmlns="http://www.w3.org/2000/svg"><script>document.title="XSS"</script></svg>'
const icon = (fields: Record<string, unknown> = {}) => buildAdminImageEndpoints({ agency: false, language: 'en' } as never, fields as never).find((e) => e.path.endsWith('admin-icon'))!
const req = {
payload: { config: {}, findGlobal: async () => ({ favicon: { url: '/api/media/file/icon.svg' }, siteName: 'Example' }) },
url: 'https://example.com/api/ipal/admin-icon',
user: null,
}
test.each([
['an SVG', SVG, 'image/svg+xml'],
['a PNG', png, 'image/png'],
])('%s is served with the sandbox policy and nosniff', async (_name, body, type) => {
vi.stubGlobal('fetch', respond(body, { headers: { 'content-type': type }, status: 200 }))
const res = await icon().handler(req as never)
expect(res.status).toBe(200)
expect(res.headers.get('content-type')).toBe(type)
expect(res.headers.get('content-security-policy')).toBe("default-src 'none'; img-src 'self' data:; style-src 'unsafe-inline'; sandbox")
expect(res.headers.get('x-content-type-options')).toBe('nosniff')
})
test('the headers are the ones of the upload routes', async () => {
const { buildUploadSecurityHeaders, UPLOAD_SECURITY_HEADERS } = await import('../src/modules/security/buildSecurityHeaders.js')
expect(buildUploadSecurityHeaders()[0].headers).toEqual([...UPLOAD_SECURITY_HEADERS])
expect(UPLOAD_SECURITY_HEADERS.find((h) => h.key === 'Content-Security-Policy')?.value).toContain('sandbox')
})
test('adminMeta.serveIcon: false → the redirect to the media file, no fetch', async () => {
const fetchMock = respond(SVG, { headers: { 'content-type': 'image/svg+xml' }, status: 200 })
vi.stubGlobal('fetch', fetchMock)
const res = await icon({ serveIcon: false }).handler(req as never)
expect(res.status).toBe(302)
expect(res.headers.get('location')).toBe('https://example.com/api/media/file/icon.svg')
expect(fetchMock).not.toHaveBeenCalled()
})
})
describe('an image that is too large is not read to the end', () => {
test('a declared length over the limit: the body is not read', async () => {
const cancel = vi.fn(async () => undefined)
const body = new ReadableStream<Uint8Array>({ cancel, pull: (c) => c.enqueue(new Uint8Array(1024)) })
vi.stubGlobal('fetch', vi.fn(async () => new Response(body, { headers: { 'content-length': String(10 * 1024 * 1024), 'content-type': 'image/png' }, status: 200 })))
expect(await fetchPublicImage('/x.png', 'https://example.com')).toBeNull()
expect(cancel).toHaveBeenCalled()
})
test('no declared length: reading stops at the limit', async () => {
let sent = 0
const body = new ReadableStream<Uint8Array>({
pull: (c) => {
sent += 64 * 1024
c.enqueue(new Uint8Array(64 * 1024)) // endless
},
})
vi.stubGlobal('fetch', vi.fn(async () => new Response(body, { headers: { 'content-type': 'image/png' }, status: 200 })))
expect(await fetchPublicImage('/x.png', 'https://example.com')).toBeNull()
expect(sent).toBeLessThan(2 * 1024 * 1024) // stopped soon after 512 KB, not after "everything"
})
test('whiteLabel.inlineImages: false → the logo keeps its address, nothing is fetched', async () => {
const fetchMock = respond(png, { headers: { 'content-type': 'image/png' }, status: 200 })
vi.stubGlobal('fetch', fetchMock)
const payload = {
config: { custom: { ipal: { twoFactor: { collection: 'users' } } }, serverURL: 'https://example.com' },
findGlobal: async () => ({ logo: { url: '/api/media/file/logo.png' }, siteName: 'Example' }),
}
const out = (await AdminLogo({ inlineImages: false, payload: payload as never, user: { _strategy: 'local-jwt', collection: 'users', hasTotp: true } as never })) as { props: { src?: string } }
expect(out.props.src).toBe('/api/media/file/logo.png')
expect(fetchMock).not.toHaveBeenCalled()
})
})
+16 -2
View File
@@ -320,10 +320,12 @@ describe('requireSetup x safeBack x guard', () => {
const wrapped = totpViews.filter((v) => typeof v.Component === 'object' && v.Component.path === '@intecion/ipal-kit/admin#SafeTotpView').length
expect(wrapped).toBe(options.safeBack === false ? 0 : 4)
// setup required needs ipal-kit's own check; with either off there is no window field and no notice
// setup required needs ipal-kit's own check; with either off there is no status field, hook or notice
const setupOn = options.requireSetup !== false && options.guard !== false
const users = config.collections?.find((c) => c.slug === 'users')
expect(Boolean(users?.fields.some((f) => 'name' in f && f.name === 'totpSetupFrom'))).toBe(setupOn)
// the data field whenever 2FA is on (the schema does not follow the switches); the panel's status field with the mode
expect(Boolean(users?.fields.some((f) => 'name' in f && f.name === 'totpSetupFrom'))).toBe(true)
expect(Boolean(users?.fields.some((f) => 'name' in f && f.name === 'totpSetupStatus'))).toBe(setupOn)
// the administrator's reset (a lost phone) comes with ipal-kit's own check, also when setup is not required
expect(Boolean(config.endpoints?.some((e) => e.path === '/ipal/two-factor/reset'))).toBe(options.guard !== false)
const provider = JSON.stringify(config.admin?.components?.providers ?? [])
@@ -335,6 +337,18 @@ describe('requireSetup x safeBack x guard', () => {
})
})
describe('requireSetup.setupNotice', () => {
const providers = async (requireSetup?: Record<string, unknown>) =>
JSON.stringify((await ipalKit({ access: { authCollection: 'users' }, i18n, twoFactor: { issuer: 'E', plugin: payloadTotpBeta7, requireSetup } as never })({ collections: [], secret: 'x' } as unknown as Config)).admin?.components?.providers ?? [])
test('on by default; false removes the notice, not the lock', async () => {
expect(await providers()).toContain('"requireSetup":true')
expect(await providers({ setupNotice: false })).not.toContain('"requireSetup":true')
const config = await ipalKit({ access: { authCollection: 'users' }, i18n, twoFactor: { issuer: 'E', plugin: payloadTotpBeta7, requireSetup: { setupNotice: false } } as never })({ collections: [], secret: 'x' } as unknown as Config)
expect((config.custom as { ipal: { twoFactor: { requireSetup: boolean } } }).ipal.twoFactor.requireSetup).toBe(true)
})
})
describe('a 2FA factory that hands back the same view objects on every call', () => {
const views = {
SetupTOTP: { Component: { path: 'pkg/rsc#TOTPSetup' }, path: 'setup-totp' },
+147 -3
View File
@@ -4,7 +4,7 @@
*/
import type { Access, Config } from 'payload'
import { describe, expect, test } from 'vitest'
import { describe, expect, test, vi } from 'vitest'
import type { I18nConfig } from '../src/modules/i18n/types.js'
@@ -20,7 +20,7 @@ import {
twoFactorSetupState,
watchPayloadConfig,
} from '../src/modules/security/totp/secondFactor.js'
import { resolveRequireSetup } from '../src/modules/security/totp/setupRequired.js'
import { buildTwoFactorResetEndpoint, resolveRequireSetup, strictExempt } from '../src/modules/security/totp/setupRequired.js'
import { buildVerifyLimit, clearVerifyLimits } from '../src/modules/security/totp/verifyLimit.js'
import { ipalKit } from '../src/plugin.js'
import { withTotpParts } from './helpers.js'
@@ -377,8 +377,28 @@ describe('ipalKit and the 2FA plugin', () => {
const off = await ipalKit({ i18n, twoFactor: { issuer: 'A', plugin: fakeTotp as never, requireSetup: false } })(base())
expect(guard(off)).toMatchObject({ requireSetup: false })
expect(off.collections!.find((c) => c.slug === 'users')!.fields.some((f) => 'name' in f && f.name === 'totpSetupFrom')).toBe(false)
// the data field stays whenever 2FA is on: the schema must not depend on the switch (SQL would drop the column)
const offUsers = off.collections!.find((c) => c.slug === 'users')!
expect(offUsers.fields.some((f) => 'name' in f && f.name === 'totpSetupFrom')).toBe(true)
expect(offUsers.fields.some((f) => 'name' in f && f.name === 'totpSetupStatus')).toBe(false)
expect(offUsers.hooks?.beforeChange?.length ?? 0).toBe(0) // no stamping while the mode is off
expect(JSON.stringify(off.admin?.components?.beforeDashboard ?? [])).not.toContain('TwoFactorAlert')
const guardOff = await ipalKit({ i18n, twoFactor: { guard: false, issuer: 'A', plugin: fakeTotp as never } })(base())
expect(guardOff.collections!.find((c) => c.slug === 'users')!.fields.some((f) => 'name' in f && f.name === 'totpSetupFrom')).toBe(true)
// each part of the mode has its own switch
const has = (c: Config) => ({
dashboard: JSON.stringify(c.admin?.components?.beforeDashboard ?? []).includes('TwoFactorAlert'),
setupNotice: JSON.stringify(c.admin?.components?.providers ?? []).includes('"requireSetup":true'),
status: c.collections!.find((x) => x.slug === 'users')!.fields.some((f) => 'name' in f && f.name === 'totpSetupStatus'),
})
// fakeTotp registers no provider, so the setup notice is checked with the real package in test/safeBack.test.ts
expect(has(on)).toMatchObject({ dashboard: true, status: true })
const noDash = await ipalKit({ i18n, twoFactor: { issuer: 'A', plugin: fakeTotp as never, requireSetup: { dashboardNotice: false } } })(base())
expect(has(noDash)).toMatchObject({ dashboard: false, status: true })
const noStatus = await ipalKit({ i18n, twoFactor: { issuer: 'A', plugin: fakeTotp as never, requireSetup: { statusField: false } } })(base())
expect(has(noStatus)).toMatchObject({ dashboard: true, status: false })
expect(guard(noStatus)).toMatchObject({ requireSetup: true }) // the lock itself is unchanged
expect(off.endpoints!.some((e) => e.path === '/ipal/two-factor/reset')).toBe(true) // an admin can still reset a lost phone
// 2FA off: nothing of this exists
@@ -387,6 +407,130 @@ describe('ipalKit and the 2FA plugin', () => {
expect(none.collections!.find((c) => c.slug === 'users')!.fields.some((f) => 'name' in f && f.name === 'totpSetupFrom')).toBe(false)
})
test.each([['24'], [-1], [Number.NaN], [Number.POSITIVE_INFINITY], [true], [null]])('requireSetup.windowHours %s stops the start (a typo must not mean "no limit")', async (windowHours) => {
await expect(Promise.resolve().then(() => ipalKit({ i18n, twoFactor: { issuer: 'A', plugin: fakeTotp as never, requireSetup: { windowHours: windowHours as never } } })({ collections: [], secret: 'x' } as unknown as Config))).rejects.toThrow(/windowHours must be a number/)
// also when ipal-kit's own check is off: a wrong value is never silently accepted
await expect(Promise.resolve().then(() => ipalKit({ i18n, twoFactor: { guard: false, issuer: 'A', plugin: fakeTotp as never, requireSetup: { windowHours: windowHours as never } } })({ collections: [], secret: 'x' } as unknown as Config))).rejects.toThrow(/windowHours/)
expect(() => resolveRequireSetup({ windowHours: windowHours as never })).toThrow(/windowHours/)
})
test('windowHours: a number, 0 or false still work', () => {
expect(resolveRequireSetup({ windowHours: 1.5 }).setupWindowMs).toBe(1.5 * 3_600_000)
expect(resolveRequireSetup({ windowHours: 0 }).setupWindowMs).toBe(0)
expect(resolveRequireSetup({ windowHours: false }).setupWindowMs).toBe(0)
})
// exempt lets an account in on its password: anything but a plain `true` must never do that.
describe('requireSetup.exempt', () => {
const user = { _strategy: 'local-jwt', collection: 'users', hasTotp: false, totpSetupFrom: new Date().toISOString() }
const payloadWith = (exempt: unknown) => ({ config: { custom: { ipal: { twoFactor: { collection: 'users', ...resolveRequireSetup({ exempt: exempt as never }) } } } } })
test('an async function stops the start', async () => {
expect(() => resolveRequireSetup({ exempt: (async () => false) as never })).toThrow(/must not be async/)
await expect(Promise.resolve().then(() => ipalKit({ i18n, twoFactor: { issuer: 'A', plugin: fakeTotp as never, requireSetup: { exempt: (async () => true) as never } } })({ collections: [], secret: 'x' } as unknown as Config))).rejects.toThrow(/must not be async/)
expect(() => resolveRequireSetup({ exempt: 'yes' as never })).toThrow(/must be a function/)
})
test.each([
['a Promise from a plain function', () => Promise.resolve(false)],
['a rejecting Promise', () => Promise.reject(new Error('x'))],
['a string', () => 'yes'],
['a number', () => 1],
['an object', () => ({})],
['an error', () => { throw new Error('boom') }],
['false', () => false],
['undefined', () => undefined],
])('%s exempts nobody', (_name, exempt) => {
const error = vi.spyOn(console, 'error').mockImplementation(() => undefined)
const payload = payloadWith(exempt)
expect(secondFactorPassed({ payload: payload as never, user })).toBe(false)
expect(twoFactorSetupState({ payload: payload as never, user })).toBe('open')
error.mockRestore()
})
test('only true exempts; a wrong answer is logged', () => {
const error = vi.spyOn(console, 'error').mockImplementation(() => undefined)
const yes = payloadWith(() => true)
expect(secondFactorPassed({ payload: yes as never, user })).toBe(true)
expect(twoFactorSetupState({ payload: yes as never, user })).toBe('exempt')
expect(error).not.toHaveBeenCalled()
const odd = strictExempt(() => Symbol('yes') as never)
expect(odd({ user })).toBe(false)
expect(odd({ user })).toBe(false)
expect(error).toHaveBeenCalledTimes(1) // each kind of wrong answer once, not on every request
expect(String(error.mock.calls[0]?.[0])).toMatch(/exempt returned a symbol.*NOT exempt/)
error.mockRestore()
})
test('a guard config built without resolveRequireSetup is strict too', () => {
const payload = { config: { custom: { ipal: { twoFactor: { collection: 'users', exempt: () => Promise.resolve(true), requireSetup: true } } } } }
expect(secondFactorPassed({ payload: payload as never, user })).toBe(false)
expect(twoFactorSetupState({ payload: payload as never, user })).toBe('open')
})
})
// Postgres / SQLite without the migration: the start-up step is the first to hit the missing column. It must not
// stop the site, and must say what the real consequence is (every login fails), not only "no window yet".
test('a missing column at start: no throw, and the log says nobody can log in', async () => {
const { backfillSetupFrom } = await import('../src/modules/security/totp/setupRequired.js')
const fake = (name: string, message: string) => {
const logger = { error: vi.fn(), warn: vi.fn() }
return { logger, payload: { count: async () => { throw new Error(message) }, db: { name }, logger } }
}
const pg = fake('postgres', 'column users.totp_setup_from does not exist')
expect(await backfillSetupFrom(pg.payload as never, 'users')).toBe(0)
expect(String(pg.logger.error.mock.calls[0]?.[0])).toMatch(/NOBODY CAN LOG IN.*migrate/s)
const sqlite = fake('sqlite', 'no such column: totp_setup_from')
await backfillSetupFrom(sqlite.payload as never, 'users')
expect(sqlite.logger.error).toHaveBeenCalledTimes(1)
const mongo = fake('mongoose', 'connection lost')
await backfillSetupFrom(mongo.payload as never, 'users')
expect(mongo.logger.error).not.toHaveBeenCalled()
expect(mongo.logger.warn).toHaveBeenCalledTimes(1)
})
// The reset removes a second factor: by default only a session that entered its own TOTP code may do it.
describe('the reset endpoint: who may use it', () => {
const run = async (reqUser: Record<string, unknown>, options: Parameters<typeof buildTwoFactorResetEndpoint>[1] = {}, guardExtra: Record<string, unknown> = {}) => {
const update = vi.fn(async () => ({}))
const payload = {
collections: { users: { config: { auth: { useSessions: true } } } },
config: { collections: [{ slug: 'users', auth: true, fields: [{ name: 'roles', type: 'select' }] }], custom: { ipal: { staffCollections: ['users'], twoFactor: { collection: 'users', requireSetup: true, ...guardExtra } } } },
logger: { error: () => undefined, info: () => undefined },
update,
}
const req = { i18n: { t: (k: string) => k }, json: async () => ({ userId: '7' }), payload, user: reqUser }
const res = await buildTwoFactorResetEndpoint('users', options).handler(req as never)
return { status: res.status, update }
}
const admin = { id: 1, collection: 'users', hasTotp: true, roles: ['admin'] }
test('a session that entered its code: allowed; the account loses its secret AND its sessions', async () => {
const { status, update } = await run({ ...admin, _strategy: 'totp' })
expect(status).toBe(200)
const data = (update.mock.calls[0] as unknown as [{ data: Record<string, unknown>; id: string }])[0]
expect(data.id).toBe('7')
expect(data.data).toMatchObject({ sessions: [], totpSecret: null })
expect(typeof data.data.totpSetupFrom).toBe('string')
})
test('an exempt admin on its password, and an API-key admin: refused by default', async () => {
const exempt = { exempt: () => true }
expect((await run({ ...admin, _strategy: 'local-jwt', hasTotp: false }, {}, exempt)).status).toBe(403)
expect((await run({ ...admin, _strategy: 'api-key' })).status).toBe(403)
expect((await run({ ...admin, _strategy: 'local-jwt' })).status).toBe(403) // password only
})
test('resetAccess loosens it for those sessions — never for one that still owes its code', async () => {
const access = () => true
expect((await run({ ...admin, _strategy: 'api-key' }, { access })).status).toBe(200)
expect((await run({ ...admin, _strategy: 'local-jwt', hasTotp: false }, { access }, { exempt: () => true })).status).toBe(200)
expect((await run({ ...admin, _strategy: 'local-jwt' }, { access })).status).toBe(403)
expect((await run({ ...admin, _strategy: 'totp' }, { access: () => 'yes' as never })).status).toBe(403) // only true
expect((await run({ ...admin, _strategy: 'totp' }, { access: async () => true })).status).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)
+33
View File
@@ -529,6 +529,39 @@ describe('2FA setup required: an account without TOTP reaches nothing but setup'
expect(ok.status).toBe(200)
const doc = (await payload.findByID({ id: userId, collection: 'users' as never })) as unknown as { totpSetupFrom: string }
expect(Date.now() - new Date(doc.totpSetupFrom).getTime()).toBeLessThan(120_000)
// the reset ends the account's sessions: the token from before is nobody's now, the account logs in again
expect(((await (await api('/users/me', sessions.newcomer)).json()) as { user: unknown }).user).toBeNull()
expect(((await (await setup(sessions.newcomer)).json().catch(() => ({}))) as { ok?: boolean }).ok).not.toBe(true)
sessions.newcomer = { headers: { authorization: `JWT ${(await login('users', '[email protected]')).token}` } }
})
// A reset is also what an administrator presses for an account that may be in someone else's hands. A session of
// that account which had passed 2FA must not survive it: /api/setup-totp asks for no password, so it could
// otherwise enrol the thief's own authenticator.
test('a reset ends every session of the account: a stolen verified session cannot enrol its own authenticator', async () => {
const THIEF_SECRET = 'KRSXG5CTMVRXEZLU'
const victim = await payload.create({ collection: 'users' as never, data: { email: '[email protected]', password: PASSWORD, roles: ['editor'], totpSecret: TOTP_SECRET } as never })
// the victim's fully verified session, as a thief would hold it (token + 2FA cookie)
const signIn = await login('users', '[email protected]')
const verify = await api('/verify-totp', { headers: { authorization: `JWT ${signIn.token}` } }, { body: JSON.stringify({ token: totp(TOTP_SECRET) }), method: 'POST' })
expect(((await verify.json()) as { ok: boolean }).ok).toBe(true)
const stolen: Session = { headers: { authorization: `JWT ${signIn.token}`, cookie: cookiesOf(verify).join('; ') } }
expect((await api('/pages', stolen)).status).toBe(200)
expect((await api('/ipal/two-factor/reset', sessions.verified, { body: JSON.stringify({ userId: victim.id }), method: 'POST' })).status).toBe(200)
expect(((await (await api('/users/me', stolen)).json()) as { user: unknown }).user).toBeNull()
const enrol = await api('/setup-totp', stolen, { body: JSON.stringify({ secret: THIEF_SECRET, token: totp(THIEF_SECRET) }), method: 'POST' })
expect(((await enrol.json().catch(() => ({}))) as { ok?: boolean }).ok).not.toBe(true)
const after = (await payload.findByID({ id: victim.id, collection: 'users' as never, showHiddenFields: true })) as unknown as { sessions?: unknown[]; totpSecret?: null | string }
expect(after.totpSecret ?? null).toBeNull()
expect(after.sessions ?? []).toEqual([])
expect((await api('/form-submissions', stolen)).status).toBe(403)
// the owner logs in again with the password and sets TOTP up; the old session stays dead
const owner: Session = { headers: { authorization: `JWT ${(await login('users', '[email protected]')).token}` } }
expect((await setup(owner)).status).toBe(200)
expect(((await (await api('/users/me', stolen)).json()) as { user: unknown }).user).toBeNull()
})
test('inside the window it sets TOTP up, and then everything its role allows opens', async () => {