Merge claude/2fa-enrolment-email-confirm: the first two-step set-up is confirmed by e-mail (twoFactor.confirmByEmail, security audit F0)

Co-Authored-By: Claude Opus 5.5 <[email protected]>
This commit is contained in:
Radosław Smoliński
2026-12-01 14:57:55 +01:00
co-authored by Claude Opus 5.5
41 changed files with 1513 additions and 42 deletions
@@ -44,6 +44,7 @@ through this procedure. Ask only when you are missing something you cannot get y
| `isAdmin(user)` / `isEditor(user)` is always `false` in a client component or in `proxy.ts` | the staff collections are not known there (no config in the browser bundle / middleware), and the predicates fail closed | `isAdmin(user, config)` with `useConfig()`, imported from `@intecion/ipal-kit/client`; in middleware `isAdmin(user, { staffCollections: ['users'] })` |
| `next build --webpack`: `'server-only' cannot be imported from a Client Component module … caused by importing '@intecion/ipal-kit/dist/index.js'` | a `'use client'` file imports the main entry (Turbopack lets it pass) | import from `@intecion/ipal-kit/client` (role predicates are there since 1.16.7; types: `import type` from the main entry is fine); data the browser needs → a prop from a server component |
| 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 |
| after typing the code the setup screen says "we sent a link to …" / "the confirmation e-mail could not be sent", and nothing opens | 1.18.0 `twoFactor.confirmByEmail`: the first set-up waits for the link sent to the account's e-mail, opened in the browser that scanned the code | open the link in that browser, then sign in again; no mail: the link is in the server log (`[iapl] 2FA: … Link`), or an admin opens the account → "Confirm the waiting set-up"; fix e-mail (doctor `2fa-enrolment-mail`); "open this link in the browser where you scanned the code" = scan again in the browser you read mail in |
| 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` |
| after an upgrade EVERY panel login answers `500` (also `/api/users/init`), administrators with 2FA included; log: `[iapl] 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, and redeploy with migrations run when the new container starts — `prodMigrations` in the adapter or the start command `pnpm payload migrate && pnpm start` (deployment.md §4.3; not Coolify's Pre-deployment command, which runs in the old container); nothing is lost. `iapl-doctor` reports a project whose migrations lack `totp_setup_from` |
| the site does not start: `[iapl] 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` |
@@ -628,6 +628,9 @@ Server only (`pnpm payload run`); never import it from client code, the Payload
| `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). |
| `resolveConfirmByEmail(option)`, `startEnrolment(req, { collection, options, totp? })`, `buildEnrolmentEndpoints({ collection, options, ownOrigin?, resetAccess? })`, `ENROL_CONFIRM_PATH`, `ENROL_ADMIN_CONFIRM_PATH` | `@intecion/ipal-kit` | `twoFactor.confirmByEmail` (1.18.0, on by default; security.md "Set-up confirmed by e-mail"): the option read strictly (null = off); the `/setup-totp` answer for an account without a factor (checks the code, keeps the secret pending, mails the link, sets the browser cookie, `202 { ok: false, pending: true, mailed, message }`); the link's page `GET /api/iapl/two-factor/confirm`, its button `POST` (single use, 30 min, same browser, own origin; writes the factor, ends the sessions, signs nobody in) and the admin's `POST /api/iapl/two-factor/confirm-pending { userId }`. Types `ConfirmByEmailOptions`, `ResolvedConfirmByEmail`, `EnrolmentContext`, `EnrolmentEndpointsOptions`. |
| `readPendingEnrolment(payload, collection, id)`, `pendingEnrolmentInfo(…)`, `dropPendingEnrolment(…)`, `countPendingEnrolments(payload, collection)`, `pendingEnrolmentKey(collection, id)` | `@intecion/ipal-kit` | The waiting set-up in payload-kv (`iapl:2fa-enrol:<collection>:<id>`; memory when there is no kv): read (null when expired), `{ createdAt, expiresAt }` for screens, end it, count them (the doctor). Type `PendingEnrolment` (`{ secret, token, browser, createdAt, expiresAt }`, token and browser as sha256). |
| `buildTotpNoticeHooks(collection, { notices })`, `sendTwoFactorNotice(payload, account, 'on' \| 'off' \| 'changed', by?)`, `verifyTotpCode(secret, token, { algorithm?, digits?, period? })`, `mailConfigured(payload)` | `@intecion/ipal-kit` | beforeChange + afterChange for the 2FA collection: a notice mail on every enrolment, change, removal / reset (any path; a removal ends a waiting set-up); the notice itself; RFC 6238 check with one period either side (as the 2FA package); whether Payload has a real mail transport (its `console` fallback = false). |
| `buildTwoFactorResetEndpoint(collection, { access?, ownOrigin? })`, `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. `ownOrigin(req)` false → `403` before anything changes (the plugin passes the `twoFactor.sameOrigin` rule; wire `requestFromOwnOrigin` when you build it yourself). 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). `iapl` registers it only with `twoFactor.guard` on. |
| `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`. |
+9 -2
View File
@@ -207,7 +207,7 @@ are never added to a new site. Local `.env` with `PAYLOAD_SECRET` ≥ 32 charact
One language: one entry in `locales`, no `[locale]` folder (i18n.md).
**Check.** `pnpm payload generate:importmap` (whiteLabel adds admin components) and `pnpm generate:types` without
errors (the import map lists `@intecion/ipal-kit/admin#TotpRedirectProvider`, `#SafeTotpView` and `#SignInLook`); `pnpm dev`, `/admin`: first-user screen → after saving, TOTP setup is enforced (`/admin/setup-totp?back=%2Fadmin`, QR, no reloading);
errors (the import map lists `@intecion/ipal-kit/admin#TotpRedirectProvider`, `#SafeTotpView` and `#SignInLook`); `pnpm dev`, `/admin`: first-user screen → after saving, TOTP setup is enforced (`/admin/setup-totp?back=%2Fadmin`, QR, no reloading; after the code the confirmation link is in the dev console — no mail set up yet — open it in the same browser, then sign in again);
the panel shows Site settings, Site integrations, Cookies, Form messages, the Forms group, Consent records.
`curl -s -o /dev/null -w '%{http_code}' -X POST localhost:3000/api/ipal/consent -H 'content-type: application/json'
-d '{"id":"0123456789abcdef","version":1,"state":{"necessary":true,"functional":false,"analytics":false,"marketing":false}}'` → `201`.
@@ -240,7 +240,14 @@ 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
account, hand over the password and have the owner set 2FA up at once.
**Confirmed by e-mail** (`twoFactor.confirmByEmail`, default since 1.18.0): the code only starts the set-up; a link
to the account's own address, opened in the same browser within 30 min, turns it on (then sign in again). So set
up e-mail (Site integrations → E-mail sending, "Send a test e-mail") BEFORE people enrol, and keep `serverURL`
(`NEXT_PUBLIC_SERVER_URL`). The first administrator of a fresh site, with no mail yet: the link is in the dev
server's console / Coolify Logs (`[iapl] 2FA: … Link`); open it in the browser that scanned the code. Check: the
screen says "we sent a link to e…@…", the API still answers 403 until the link is opened. Off:
`confirmByEmail: false` (security.md "Set-up confirmed by e-mail"). **Postgres/SQLite: `pnpm payload
migrate:create` and have the migration applied when the container starts, before the site serves** — `prodMigrations`
or the start command `pnpm payload migrate && pnpm start`, never a pre-deployment command (deployment.md §4.3)
(column `totp_setup_from`, there whenever 2FA is
@@ -39,6 +39,14 @@ no migration, no import-map change; read before deploying:**
**Check:** five wrong passwords for an editor from one address → `429` there, `200` from another; the account page
shows "Current password"; `curl -X POST <site>/api/users/login -H 'Origin: https://other.example' …` → `403`.
**→ 1.18.0, two-step verification confirmed by e-mail (CHANGELOG 1.18.0; security.md "Set-up confirmed by e-mail") —
check before deploying:** (1) e-mail works on the site (Site integrations → E-mail sending → "Send a test e-mail");
(2) `serverURL` is set (`NEXT_PUBLIC_SERVER_URL`); (3) tell the staff: whoever sets two-step verification up for the
first time gets a link by e-mail and opens it in the same browser, then signs in again. Accounts that already have it
are not affected. Nothing to wire, no migration, no import-map change. Off: `twoFactor: { confirmByEmail: false }`.
**Check:** `pnpm exec iapl-doctor --deep` shows no `2fa-enrolment-mail` error; a test editor scans the code → the
screen says "we sent a link to …", the link opened in the same browser → "Two-step verification is on".
**→ 1.17.2, security (CHANGELOG 1.17.2; PROGRAMISTA §6, items 84–87) — nothing required, check:** `readVersions:
readPublished()` now works (a wrapper of your own around it: use `readPublishedVersions()` inside); behind a proxy
that rewrites `Host` without `X-Forwarded-Host`, set `serverURL` or the panel's mail / cookie buttons answer 403