2FA: the first set-up is confirmed by e-mail (twoFactor.confirmByEmail, 1.18.0)
Security audit 2026-12, F0: inside an account's setup window its password alone enrolled an authenticator of the caller's choosing; the owner was locked out. - /setup-totp for an account without a factor: IAPL checks the code, keeps the secret pending (payload-kv), mails a single-use 30-min link to the account and ties it to the enrolling browser; the package's handler (and its -totp cookie) is never used for a first enrolment - GET /api/iapl/two-factor/confirm = a page with one button; POST confirms (own origin, same browser), ends the account's sessions, signs nobody in - notice mails on every enrolment, change, removal / reset (any path) - mail not working: link to the server log, admin confirms on the account page (POST /api/iapl/two-factor/confirm-pending), doctor rule 2fa-enrolment-mail - options and opt-out (confirmByEmail: false), building blocks exported - tests: HTTP suite on SQLite, MongoDB, Postgres; built-site spec in e2e:built; closed doors and judged routes; docs, AGENT.md, skills, changelog Co-Authored-By: Claude Opus 5.5 <[email protected]>
This commit is contained in:
co-authored by
Claude Opus 5.5
parent
84717804ae
commit
c9d1f4b340
@@ -9,6 +9,30 @@ versions at once, go through every "Requires project changes" section in order,
|
||||
version you have. A new release = a new section at the top; we remove the oldest ones only
|
||||
once there are more than 20.
|
||||
|
||||
## Unreleased (for 1.18.0) — two-step verification: the first set-up is confirmed by e-mail
|
||||
|
||||
> **Read before upgrading — what changes for an existing site, most important first:**
|
||||
>
|
||||
> 1. **Setting up two-step verification now ends with an e-mail.** Whoever sets it up for the first time (a new
|
||||
> account, an account whose setup was reset or reopened, every account that never finished it) scans the code as
|
||||
> before, then gets a link at the **account's own e-mail address**; the factor is on only after that link is opened
|
||||
> **in the same browser** within 30 minutes, and then they sign in again with password and code. Accounts that
|
||||
> already have two-step verification are not affected. Tell the staff before the upgrade.
|
||||
> 2. **E-mail must work before that.** Check Site integrations → E-mail sending → "Send a test e-mail". Where it does
|
||||
> not work, nobody is locked out: the link is written to the server log (Coolify → Logs) and an administrator can
|
||||
> choose "Confirm the waiting set-up" on the account page; `iapl-doctor --deep` reports it as an error
|
||||
> (`2fa-enrolment-mail`).
|
||||
> 3. **Notice mails:** the account's address now gets a mail when its two-step verification is turned on, changed,
|
||||
> removed or reset.
|
||||
> 4. `serverURL` must be set (it is, from `NEXT_PUBLIC_SERVER_URL`, on every site made with `iapl create`): the link is
|
||||
> made from it, never from the request.
|
||||
>
|
||||
> Why: with the password of an account inside its setup window, anybody could enrol their own authenticator and lock
|
||||
> the owner out (security audit 2026-12, F0; every release since 1.16.6 within the window, earlier without one). No
|
||||
> schema change, no migration, no import-map change. Turn off: `twoFactor: { confirmByEmail: false }`; adapt:
|
||||
> `confirmByEmail: { linkMinutes, sameBrowser, adminConfirm, logLinkWhenMailFails, notices, maxMailsPerHour }`
|
||||
> (security.md "Set-up confirmed by e-mail").
|
||||
|
||||
## 1.17.2 — version history with readPublished, sign-in and panel actions, staff-only REST submissions and jobs, the cookie button
|
||||
|
||||
> **Read before upgrading.** No schema change, no migration on any database, no import-map change. What changes for
|
||||
|
||||
+2
-1
@@ -247,7 +247,7 @@ site), **P** = a test in the panel. Full code: PROGRAMISTA.md §2.
|
||||
| 10 | **Forms** | every form from a **seed** (`scripts/seed-form-*.ts`: fields, confirmation, mail to the company **and** confirmation to the customer, every language); a block with `<RenderForm>` + `formClasses.ts` (look, once); `actions.ts` = `createSubmitAction({ getCachedPayload, headers })`; `forms: {…}` in `iapl`; `email: mailAdapter()` | `RenderForm` (`/rsc`), `createSubmitAction`, `mailAdapter` | A, P |
|
||||
| 11 | **Turnstile** | `<SiteProviders>` in `[locale]/layout.tsx` (wires `TurnstileProvider` with the key from the panel); `RenderForm` renders the widget; keys in Site integrations | `SiteProviders`, `getTurnstileConfig`, `TurnstileProvider` | A, P |
|
||||
| 12 | Consent + analytics | Consent Mode: `'advanced'` (default — the Google tag loads at once with every signal `denied`) or `'basic'` (`<SiteProviders analytics={{ consentMode: 'basic' }}>` — no request to Google before consent; a client who wants zero requests), the choice goes to "Project decisions"; the consent log is on by default since 1.17.0 (`consentLog: false` turns it off; **Postgres / SQLite: `pnpm payload migrate:create consent-log` and apply it in the same deploy**, doctor `consent-log-migration`) + `<SiteProviders banner={<CookieBanner settings="detailed" />}>` (posts every decision to the log by itself; "Reject" is as prominent as "Accept all" by default — `equalChoice`; Global Privacy Control honoured by default — `gpc`, consent.md → "Global Privacy Control"; ConsentProvider, banner, CookieButton, Analytics in the right order; the banner is in the server HTML and painted with the page — pages stay static, an inline script decides before the first paint; with a nonce CSP pass `nonce` to `SiteProviders`; never wrap the banner in a "mounted" guard or `dynamic(…, { ssr: false })`, never read the consent cookie in the layout unless the site is dynamic anyway: `consentCookie`, consent.md → "First paint"); settings window mode (`settings`: `inline` / `modal` / `detailed`) per the design, brief is silent → `detailed`, the decision goes to "Project decisions"; tool IDs in the panel; the cookie list from a scan (`cookieScanner: true` → *Cookie review* → **Scan cookies** → *Approve cookies* → **Approve and add**; or cookie-scan → import) — feeds `<CookieTable>` on the policy page **and** the lists in the `detailed` window; Cookies → Settings window → Cookie list headings in every language | consent.md, analytics.md | A, `iapl-consent-check` |
|
||||
| 13 | Security | `buildSecurityHeaders` in `next.config.ts`; `withSecurityConfig(withPayload(nextConfig))` — this order (no `X-Powered-By`; Payload's colour-scheme client hints for `/admin` only, check: `curl -sI localhost:3000/pl \| grep -i critical-ch` → nothing); CSP: `buildSecurityHeaders({ csp: { mode: 'report-only', reportUri: '/api/csp-report', … } })` + `buildAdminCspHeaders` on `/admin/:path*` + `src/app/api/csp-report/route.ts` (`createCspReportRoute`) → read the reports → `mode: 'enforce'`; `twoFactor: { issuer, plugin: payloadTotp }` + `generate:importmap` (`TotpRedirectProvider`, `SafeTotpView`; check: a new admin lands on `/admin/setup-totp?back=%2Fadmin` with the QR, no reloading; a login with the password only gets `403` from `/api/globals/site-integrations` and `/api/form-submissions` — security.md "What the second factor covers"); own endpoints: `secondFactorPassed(req)` / `userMeetsRole(req, role)`; **an account without 2FA can only set it up** (`twoFactor.requireSetup`, default: nothing else answers, 72 h from creation or an admin's reset, then blocked until an admin chooses "Reopen setup" on the account) — so set 2FA up right after creating an account; `iapl-doctor --url` must report 0 accounts without 2FA; Postgres/SQLite: migration for `totpSetupFrom`; `IAPL_IP_HEADER` in production | security.md, forms.md | A |
|
||||
| 13 | Security | `buildSecurityHeaders` in `next.config.ts`; `withSecurityConfig(withPayload(nextConfig))` — this order (no `X-Powered-By`; Payload's colour-scheme client hints for `/admin` only, check: `curl -sI localhost:3000/pl \| grep -i critical-ch` → nothing); CSP: `buildSecurityHeaders({ csp: { mode: 'report-only', reportUri: '/api/csp-report', … } })` + `buildAdminCspHeaders` on `/admin/:path*` + `src/app/api/csp-report/route.ts` (`createCspReportRoute`) → read the reports → `mode: 'enforce'`; `twoFactor: { issuer, plugin: payloadTotp }` + `generate:importmap` (`TotpRedirectProvider`, `SafeTotpView`; check: a new admin lands on `/admin/setup-totp?back=%2Fadmin` with the QR, no reloading; a login with the password only gets `403` from `/api/globals/site-integrations` and `/api/form-submissions` — security.md "What the second factor covers"); own endpoints: `secondFactorPassed(req)` / `userMeetsRole(req, role)`; **an account without 2FA can only set it up** (`twoFactor.requireSetup`, default: nothing else answers, 72 h from creation or an admin's reset, then blocked until an admin chooses "Reopen setup" on the account) — so set 2FA up right after creating an account; **the first set-up ends with a link sent to the account's e-mail** (`twoFactor.confirmByEmail`, 1.18.0): e-mail must work first (Site integrations → "Send a test e-mail"; without it the link is only in the server log and an admin confirms on the account page; `iapl-doctor --deep` rule `2fa-enrolment-mail`), `serverURL` must be set (the link is made from it), check: a new editor scans the code → the screen names `e…@…`, `/api/globals/site-integrations` stays `403` until the link is opened in the same browser; `iapl-doctor --url` must report 0 accounts without 2FA; Postgres/SQLite: migration for `totpSetupFrom`; `IAPL_IP_HEADER` in production | security.md, forms.md | A |
|
||||
| 14 | Operations | `src/app/api/health/route.ts` (`healthRoute`); `src/instrumentation.ts` with `assertEnv(iaplEnvRules({ storage: true, ipHeader: true }))`; staging with `IAPL_NOINDEX=1`; smoke tests (§8a) | `healthRoute`, `assertEnv`, `iaplEnvRules` | A |
|
||||
| 15 | System pages | Site settings → System pages: homepage, 404, privacy policy, cookies; legal links in the footer by role (`getSystemLinks(locale)`) | `getSystemLinks`, `getSystemPagePath`, `getNotFoundPage` | P |
|
||||
| 16 | **Nothing hardcoded** | every text, link, image, file, company data from the panel; domains and keys from `.env` (§2) | — | A, P |
|
||||
@@ -1239,6 +1239,7 @@ add missing hosts with flags / `extra`; (3) change `mode` to `'enforce'` in both
|
||||
| The second factor on every collection and global, whichever plugin added it, and on the plugin's endpoints; an unrecognised 2FA package = startup error | per entity: `custom.ipal.secondFactor: false` or `{ read: false }` (or the package's `custom.totp.disableAccessWrapper`); everywhere: `twoFactor.guard: false` (not recommended) | `requireSecondFactor` / `secondFactorPassed` in your own access functions and endpoints |
|
||||
| At most 5 **wrong** verify codes per account in 10 minutes (`POST /api/verify-totp` → `429`); a right code gives its place back (1.17.1), so correct logins are never refused; an attempt held out only by others still being checked gets `429` + `Retry-After: 2` ("try again in a moment"); the count is kept in memory and in the database (`payload.kv`), so a restart or a second instance does not reset it. **Verify:** log in correctly 7 times in a row → all in; 5 wrong codes → the next gets `429` with a long `Retry-After` | `twoFactor.verifyLimit: false` | `verifyLimit: { max, windowMinutes, store: 'memory' }`; own wiring: `buildVerifyLimit(...)` + `limit.settle(req, correct)` |
|
||||
| The plugin's panel actions (`POST` mail service connect / disconnect, test e-mail, cookie scan / approval / crawl) refuse a request a browser marks as coming from another origin (`403`, before anything is read; 1.17.2). The panel's buttons are not affected; set `serverURL` (doctor `csrf-empty` warns without it). **Verify:** `curl -X POST <site>/api/ipal/test-email -H 'Origin: https://other.example' -H 'Content-Type: text/plain' -b <admin cookies> -d '{}'` → `403` | `adminSameOrigin: false` | `adminSameOrigin: { origins: [...] }`; `requireOwnOrigin(endpoint, origins?)` for your own endpoints |
|
||||
| 2FA first set-up confirmed by e-mail (1.18.0): the code only starts it; a link to the account's own address, opened in the same browser within 30 min, turns it on and ends the account's sessions; notice mails on every enrolment, change, removal / reset; without working mail the link goes to the server log and an admin confirms on the account page ("Confirm the waiting set-up", `POST /api/iapl/two-factor/confirm-pending`). **Verify:** security.md "Set-up confirmed by e-mail" → Verify; doctor `2fa-enrolment-mail` | `twoFactor.confirmByEmail: false` | `confirmByEmail: { linkMinutes, sameBrowser, adminConfirm, logLinkWhenMailFails, notices, maxMailsPerHour }`; `startEnrolment`, `buildEnrolmentEndpoints`, `buildTotpNoticeHooks`, `sendTwoFactorNotice`, `verifyTotpCode`, `readPendingEnrolment`, `pendingEnrolmentInfo`, `countPendingEnrolments`, `mailConfigured` |
|
||||
| 2FA verify and setup attempts only from the site's own origin: a request a browser marks as coming from elsewhere (`Origin`, `Sec-Fetch-Site`) gets `403` and is not counted. The admin's reset `POST /api/ipal/two-factor/reset` follows the same rule (1.17.1). **Verify:** `curl -X POST <site>/api/ipal/two-factor/reset -H 'Origin: https://other.example' -H 'Content-Type: text/plain' -b <admin cookies> -d '{"userId":1}'` → `403`; the panel's button still works. **Set `serverURL`**: behind a proxy that rewrites `Host` and sends no `X-Forwarded-Host` the site's own page is refused without it (logged once per origin: `[iapl] 2FA: a code from origin … was refused`) | `twoFactor.sameOrigin: false` | `sameOrigin: { origins: ['https://app.example.com'] }`; `requestFromOwnOrigin`, `reportRefusedOrigin` |
|
||||
| Stored secrets are write-only: `smtpPassword` and `turnstileSecretKey` come back as `'********'` over REST, GraphQL and in the panel; an empty save keeps the value, `'[[clear]]'` removes it; server code reads the real value with the Local API. A query cannot name a secret (1.17.1): `where` / `sort` on it — REST, GraphQL, versions — is refused (`secretReadAccess`, the field's `read` rule; verify: `GET /api/globals/site-integrations/versions?where[version.smtpPassword][exists]=true` as an admin → 400 `QueryError`, no `totalDocs`). **The panel is the source — never add an env variable for them** (`TURNSTILE_SECRET_KEY` is deprecated) | `secrets: { writeOnly: false }` | `writeOnlySecret(field)` / `writeOnlySecrets(fields, names)` for your own secret fields; with versions on the entity add `hooks.afterRead: [maskSecretsOnRestore]` |
|
||||
| The SMTP password stays with its server: a save in the panel or over the API that changes the server, port or user name without the password is refused (`400` "Enter the password again…"), whatever the transport says — otherwise an admin session points the server at its own machine and a test e-mail hands the password over. A change of the transport alone asks for nothing. Seeds and scripts (Local API, access control off) are not asked | `secrets: { reenterOnChange: false }` | `writeOnlySecret(field, { boundTo: [...] })`, `buildKeepSecret`, `SMTP_PASSWORD_BOUND_TO` |
|
||||
|
||||
@@ -1130,6 +1130,7 @@ Rules: AGENT.md §8a.
|
||||
| `e2e/closed-doors.spec.ts` | closed doors from outside (run by `pnpm e2e:built` in both bundlers): every door of e2e/closed-doors.ts asked on the production build as an anonymous visitor, a customer (the fixture's `e2e-visitors`) and an editor; doors still open while the owner decides are asserted open (`test.fail`) |
|
||||
| `e2e/closed-doors.ts` | the doors that must stay closed, who each is closed for and how a closed answer looks; a project adds its own (security.md "Closed doors from outside") |
|
||||
| `e2e/create-test-admin.ts` | two test admins with a known TOTP secret (the specs share out the five 2FA verify attempts per account), their stored verify counts cleared, and e-mail sending pointed at the tests' mail sink (local / CI database only) |
|
||||
| `e2e/enrolment.ts` | reads the two-step verification confirmation link (twoFactor.confirmByEmail, 1.18.0) from the mail sink: quoted-printable undone, the latest message to an address, waited for (below) |
|
||||
| `e2e/global-setup.ts` | Playwright global setup: resets the test admins and clears their stored 2FA attempt counts before every run, so specs do not depend on run order (below) |
|
||||
| `e2e/late-staff-fixture.ts` | test fixture, on only with E2E_LATE_STAFF=1: one plugin before iapl (staff collections of the config: roles with one more value, the plugin's roles, roles of the project's own) and one after it (a staff collection without rules, one whose roles field is text, copies of staff collections under new slugs — plain, with rules of their own, one rule used for another operation, other role values, the opt-out, not staff — and a visitor collection with open sign-up) |
|
||||
| `e2e/late-staff.spec.ts` | the account rules on a BUILT site (run by `pnpm e2e:built` after a webpack and a Turbopack build): a staff collection a later plugin adds, staff collections whose accounts can hold `admin`, and copies of staff collections — a visitor account gets nothing, nobody raises its own role or makes an admin, a copy is never wider than the plugin's rule |
|
||||
@@ -1145,8 +1146,46 @@ Rules: AGENT.md §8a.
|
||||
| `e2e/smtp-sink.ts` | a local mail sink for the smoke tests: reads what the site really sent (recipients, attachments) |
|
||||
| `e2e/totp.ts` | RFC 6238 code generator for the 2FA sign-in in the smoke test, and the addresses of the second test admin and the test editor (below) |
|
||||
| `e2e/two-factor-back.spec.ts` | browser test of the 2FA screens' `back` link (twoFactor.safeBack): a prepared link — script or another host — ends on the admin root, an ordinary one is followed |
|
||||
| `e2e/two-factor-enrolment.spec.ts` | the first 2FA set-up confirmed by e-mail on the built site (run by `pnpm e2e:built` in both bundlers): the password alone no longer enrols an attacker's factor (the link goes to the owner and is refused in another browser), and the panel flow — code, notice, link from the mail sink, sign in again |
|
||||
| `e2e/two-factor-setup.spec.ts` | browser check of "2FA setup required": the first admin of a fresh site, a new editor, the administrator's reset on the account page |
|
||||
|
||||
### `e2e/enrolment.ts`
|
||||
|
||||
```ts
|
||||
import type { SinkMessage } from './smtp-sink'
|
||||
|
||||
/**
|
||||
* twoFactor.confirmByEmail (IAPL 1.18.0, on by default): the first set-up of two-step verification waits for a link
|
||||
* sent to the account's e-mail. The specs read that link from the mail sink (e2e/smtp-sink.ts; create-test-admin.ts
|
||||
* points the site's SMTP at it).
|
||||
*/
|
||||
|
||||
/** A raw message body as text: quoted-printable soft breaks and escapes undone. */
|
||||
export const decodeMail = (raw: string): string =>
|
||||
raw.replace(/=\r?\n/g, '').replace(/=([0-9A-F]{2})/g, (_, hex: string) => String.fromCharCode(parseInt(hex, 16)))
|
||||
|
||||
/** The confirmation link of the latest message to `email`, or null. */
|
||||
export function enrolmentLink(messages: SinkMessage[], email: string): null | URL {
|
||||
for (const message of [...messages].reverse()) {
|
||||
if (!message.to.some((to) => to.toLowerCase().includes(email.toLowerCase()))) {continue}
|
||||
const found = decodeMail(message.data).match(/https?:\/\/[^\s"<>]+\/two-factor\/confirm\?u=[^\s"<>&]+&(?:amp;)?t=[\w-]+/)
|
||||
if (found) {return new URL(found[0].replace('&', '&'))}
|
||||
}
|
||||
return null
|
||||
}
|
||||
|
||||
/** Waits until a message with the confirmation link for `email` arrives (mail goes out right after the request). */
|
||||
export async function waitForEnrolmentLink(messages: SinkMessage[], email: string, timeoutMs = 10_000): Promise<URL> {
|
||||
const until = Date.now() + timeoutMs
|
||||
for (;;) {
|
||||
const link = enrolmentLink(messages, email)
|
||||
if (link) {return link}
|
||||
if (Date.now() > until) {throw new Error(`no confirmation e-mail for ${email} in the mail sink`)}
|
||||
await new Promise((r) => setTimeout(r, 200))
|
||||
}
|
||||
}
|
||||
```
|
||||
|
||||
### `e2e/global-setup.ts`
|
||||
|
||||
```ts
|
||||
|
||||
@@ -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`. |
|
||||
|
||||
@@ -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
|
||||
|
||||
@@ -106,6 +106,7 @@ Turn off: `iapl({ doctor: false })`. Adapt: `iapl({ doctor: { tokenVar: 'MY_TOKE
|
||||
| | `client-hints` | info | `withSecurityConfig` is the outer wrapper (`withSecurityConfig(withPayload(…))`), so Payload's colour-scheme client hints go to the admin only; live: `/` sends no `Critical-CH: Sec-CH-Prefers-Color-Scheme`. Not reported with `adminClientHints: false` |
|
||||
| | `csp` | warning / info | CSP on the site and the admin; report-only is info, a warning after 4 weeks (`seen`) |
|
||||
| | `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`) |
|
||||
| | `2fa-enrolment-mail` | error / info | (deep) `twoFactor.confirmByEmail` is on (the default since 1.18.0) and e-mail does not work (no transport, no method chosen, SMTP incomplete): nobody finishes setting up two-step verification alone — the link is only in the server log, or an admin confirms each set-up (error); set-ups waiting for their link (info; error while mail does not work) |
|
||||
| | `access-missing` | warning | `iapl` has an `access` option — without it there are no roles and every panel account is an admin |
|
||||
| | `csrf-empty` | warning | the config sets `serverURL` or `csrf` — otherwise Payload accepts the login cookie from any origin, and behind a proxy that rewrites `Host` the plugin's own-origin checks (2FA, panel actions) refuse the site's own panel. With `--url` (deep) the running config decides (`originKnown` in the status), not the file |
|
||||
| | `open-signup` | info | (deep) auth collections whose `create` rule lets an anonymous request through: sign-up is open there (intended for a customer zone — silence with a reason) |
|
||||
|
||||
@@ -791,6 +791,79 @@ for p in globals/site-integrations form-submissions users; do
|
||||
done
|
||||
```
|
||||
|
||||
### Set-up confirmed by e-mail (`twoFactor.confirmByEmail`, 1.18.0)
|
||||
|
||||
**Why.** Inside an account's setup window the password alone used to be enough to enrol an authenticator — so
|
||||
whoever learned the password (phishing, a reused password) could enrol THEIR OWN app first: they were in with full
|
||||
rights, and the owner was locked out. The window opens for every existing account at the first start after an
|
||||
upgrade to 1.16.6 or later, for every new account, and after every reset (security audit 2026-12, finding F0).
|
||||
|
||||
**What happens now (on by default):**
|
||||
1. The person scans the code and types it on the setup screen (`POST /api/setup-totp`). IAPL checks the code like
|
||||
the 2FA package does, but **does not turn the factor on**: it keeps the secret aside (payload-kv), sends a link
|
||||
to the **account's own e-mail address**, and gives this browser a random cookie (`<cookiePrefix>-iapl-enrol`,
|
||||
HttpOnly). The screen says where the link went (`p…@example.com`); after a reload a notice shows it too.
|
||||
2. Opening the link (`GET /api/iapl/two-factor/confirm?u=…&t=…`) shows a page with one button — a mail scanner that
|
||||
opens links changes nothing. The button posts it back.
|
||||
3. The POST checks: the link's token (stored as a hash; single use; **30 minutes**), that no newer set-up replaced it,
|
||||
the site's own origin, and — `sameBrowser`, on by default — the cookie of the browser that scanned the code. Then
|
||||
the factor is written, **every session of the account ends**, and nobody is signed in: the person signs in again
|
||||
with the password and the code.
|
||||
- Until then the account stays in its setup state: nothing but the setup screen, as before. The window keeps running.
|
||||
- A new set-up (scanning again) replaces a waiting one; its link stops working. At most **5 confirmation mails per
|
||||
account and hour** (`429` after that).
|
||||
- The link is made from Payload's `serverURL` (`NEXT_PUBLIC_SERVER_URL`), never from the request's `Host`; without
|
||||
`serverURL` no link is made (logged).
|
||||
- Why the same browser: someone with the password who starts a set-up gets the link sent to the OWNER, who may open
|
||||
it thinking it is theirs. With `sameBrowser` that click is refused ("open this link in the browser where you scanned
|
||||
the code"); the mail also says "if it was not you, do not open the link: someone knows your password".
|
||||
|
||||
**Notices.** The account's address gets a mail whenever its factor is turned on (with who confirmed it, when an
|
||||
administrator did), changed, or removed / reset (with the administrator's address) — whatever path wrote it: the
|
||||
setup screen, the package's remove and admin endpoints, IAPL's reset, the Local API. Mails never carry the secret.
|
||||
They go in the language of the panel's fallback language (`i18n.fallbackLanguage`), as kind `account` (the link) or
|
||||
`security-alert` (notices) through the site's mail (the mail service or SMTP, [email.md](./email.md)).
|
||||
|
||||
**When mail does not work** (no sending method chosen, the mail service still pending, SMTP incomplete, or no mail
|
||||
transport at all) nobody is locked out, and the doctor says it loudly:
|
||||
- the person's screen says the e-mail could not be sent and to ask an administrator;
|
||||
- the **link is written to the server log** (one `[iapl] 2FA: … Link (valid 30 min, single use): …` line; Coolify →
|
||||
Logs) — for the team that runs the site. With `sameBrowser` it still works only in the browser that scanned the
|
||||
code (the person at the keyboard opens what the team reads out to them). A fresh site's first administrator, who
|
||||
has no mail yet, finishes this way;
|
||||
- an **administrator** who is fully signed in (password and code) opens the account page and chooses **"Confirm the
|
||||
waiting set-up"** (`POST /api/iapl/two-factor/confirm-pending { userId }`; same rule as the reset: `resetAccess`,
|
||||
own origin) — only after checking with the person, outside the panel, that they started it;
|
||||
- `iapl-doctor --deep` (or `--url` with `IAPL_DOCTOR_TOKEN`): rule `2fa-enrolment-mail` — **error** while mail does
|
||||
not work, and the number of set-ups waiting.
|
||||
|
||||
**What to do on a site:** make sure e-mail works BEFORE people set up two-step verification (Site integrations →
|
||||
E-mail sending → "Send a test e-mail"); after an upgrade, tell the staff that the set-up now ends with a link in their
|
||||
mailbox. Nothing to wire: the endpoints and hooks come with `twoFactor`, the import map does not change.
|
||||
|
||||
**Options** — `twoFactor.confirmByEmail`:
|
||||
|
||||
| Option | Default | Role |
|
||||
|---|---|---|
|
||||
| (the whole) | on | `false` = the 2FA package's behaviour: the code alone turns the factor on (no link, no notices) |
|
||||
| `linkMinutes` | `30` | how long a link works (1–1440) |
|
||||
| `sameBrowser` | `true` | the link works only in the browser that scanned the code; `false` = any browser (weaker: the owner can confirm an attacker's set-up by clicking) |
|
||||
| `adminConfirm` | `true` | an administrator can confirm a waiting set-up from the account page |
|
||||
| `logLinkWhenMailFails` | `true` | write the link to the server log when the mail cannot be sent |
|
||||
| `notices` | `true` | notice mails on enrolment, change, removal / reset |
|
||||
| `maxMailsPerHour` | `5` | confirmation mails per account and hour |
|
||||
|
||||
A value that is not understood stops the start (like every switch since 1.17.1). **Building blocks** (exported):
|
||||
`startEnrolment`, `buildEnrolmentEndpoints`, `buildTotpNoticeHooks`, `sendTwoFactorNotice`, `verifyTotpCode`,
|
||||
`readPendingEnrolment`, `pendingEnrolmentInfo`, `dropPendingEnrolment`, `countPendingEnrolments`,
|
||||
`pendingEnrolmentKey`, `mailConfigured`, `resolveConfirmByEmail`, `ENROL_CONFIRM_PATH`, `ENROL_ADMIN_CONFIRM_PATH`.
|
||||
|
||||
**Verify:** a new editor signs in, scans the code → the screen says "we sent a link to e…@…" and
|
||||
`curl -s -o /dev/null -w '%{http_code}' -b <its cookies> <site>/api/globals/site-integrations` is still `403`; the
|
||||
mail arrives; opened in another browser it answers "open this link in the browser where you scanned the code"; in the
|
||||
same browser → "Two-step verification is on", then sign-in with password and code works and the mailbox has the
|
||||
"turned on" notice. The built reference site runs this in `e2e/two-factor-enrolment.spec.ts` (`pnpm e2e:built`).
|
||||
|
||||
### Import map (required)
|
||||
|
||||
The 2FA screens and the redirect to them are admin components. After adding `twoFactor`, and after every
|
||||
@@ -1296,6 +1369,8 @@ every answer: `accessAllowed(option, answer)` (exported). The second factor is c
|
||||
`safeAdminBack`, `wrapTotpViews`, `copyViews`, `changedViewKeys`, `SAFE_TOTP_VIEW`, `SafeTotpView` are exported.
|
||||
The stale import-map notice that comes with it: `twoFactor.importMapCheck: false`; its parts
|
||||
(`findImportMapFile`, `missingImportMapEntries`) are exported too.
|
||||
- **Set-up confirmed by e-mail:** `twoFactor.confirmByEmail: false` (off), or `{ linkMinutes, sameBrowser, adminConfirm,
|
||||
logLinkWhenMailFails, notices, maxMailsPerHour }`; the building blocks above.
|
||||
- **Setup required:** `twoFactor.requireSetup: false` (off), `{ windowHours }` (another window, `false` / `0` = none),
|
||||
`{ exempt }` (a service account), `{ dashboardNotice: false }`, `{ statusField: false }`, `{ setupNotice: false }`,
|
||||
`twoFactor.resetAccess` (who reopens); exported: `twoFactorSetupState`, `twoFactorSetupDeadline`,
|
||||
|
||||
Reference in New Issue
Block a user