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:
@@ -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`,
|
||||
|
||||
@@ -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
|
||||
|
||||
@@ -79,6 +79,8 @@ export const DOORS: Door[] = [
|
||||
{ closedFor: ALL, method: 'POST', name: 'the mail service cannot be disconnected', path: '/api/iapl/mail-relay/disconnect' },
|
||||
{ closedFor: ALL, method: 'POST', name: 'the confirm route answers 404 without a nonce of this site', path: '/api/iapl/mail-relay/confirm', body: { nonce: 'n'.repeat(40), state: 'active', token: `ims_${'a'.repeat(43)}` }, closed: notFound },
|
||||
{ body: { id: NO_ID }, closedFor: ALL, method: 'POST', name: 'another account\'s 2FA cannot be reset', path: '/api/ipal/two-factor/reset' },
|
||||
{ body: { userId: NO_ID }, closedFor: ALL, method: 'POST', name: 'another account\'s waiting 2FA set-up cannot be confirmed (1.18.0)', path: '/api/iapl/two-factor/confirm-pending' },
|
||||
{ body: 'u=1&t=' + 'x'.repeat(43), closedFor: ['anonymous'], headers: { 'content-type': 'application/x-www-form-urlencoded' }, method: 'POST', name: 'a made-up 2FA confirmation link turns nothing on (1.18.0)', path: '/api/iapl/two-factor/confirm', closed: ({ status }) => status === 400 || status === 403 },
|
||||
// payload-2fa refuses with HTTP 200 and `{ ok: false }` (its own convention), so the body is what is judged
|
||||
{ body: { id: NO_ID }, closedFor: ALL, method: 'POST', name: 'another account\'s 2FA cannot be removed (payload-2fa)', path: '/api/admin/remove-user-totp', closed: refusedOrNotOk },
|
||||
{ body: { id: NO_ID }, closedFor: ALL, method: 'POST', name: 'another account\'s 2FA cannot be reset (payload-2fa)', path: '/api/admin/reset-user-totp', closed: refusedOrNotOk },
|
||||
|
||||
@@ -0,0 +1,32 @@
|
||||
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))
|
||||
}
|
||||
}
|
||||
@@ -1,6 +1,8 @@
|
||||
import { expect, test } from '@playwright/test'
|
||||
import { randomUUID } from 'node:crypto'
|
||||
|
||||
import { waitForEnrolmentLink } from './enrolment'
|
||||
import { startSmtpSink } from './smtp-sink'
|
||||
import { totp } from './totp'
|
||||
|
||||
/**
|
||||
@@ -28,7 +30,16 @@ test('own account: a new e-mail needs the current password, in the panel', async
|
||||
await admin.dispose()
|
||||
const own = await playwright.request.newContext({ baseURL, extraHTTPHeaders: { origin: baseURL! } })
|
||||
expect((await own.post('/api/users/login', { data: { email, password } })).status()).toBe(200)
|
||||
expect((await (await own.post('/api/setup-totp', { data: { secret: SECRET, token: totp(SECRET) } })).json()).ok).toBe(true)
|
||||
// the first set-up waits for its e-mail link (twoFactor.confirmByEmail): read it from the mail sink, confirm it here
|
||||
const sink = await startSmtpSink(Number(process.env.E2E_SMTP_PORT ?? 2526))
|
||||
try {
|
||||
expect((await (await own.post('/api/setup-totp', { data: { secret: SECRET, token: totp(SECRET) } })).json()).pending).toBe(true)
|
||||
const link = await waitForEnrolmentLink(sink.messages, email)
|
||||
const done = await own.post('/api/iapl/two-factor/confirm', { form: { t: link.searchParams.get('t')!, u: link.searchParams.get('u')! } })
|
||||
expect(done.status()).toBe(200)
|
||||
} finally {
|
||||
await sink.close()
|
||||
}
|
||||
await own.dispose()
|
||||
|
||||
const context = await browser.newContext({ baseURL })
|
||||
|
||||
@@ -77,6 +77,7 @@
|
||||
"GET /api/globals/site-settings/versions": "versions: readVersions = read (anyone (brand, homepage, construction mode)); no version history kept here",
|
||||
"GET /api/globals/site-settings/versions/:id": "versionByID: readVersions = read (anyone (brand, homepage, construction mode)); no version history kept here",
|
||||
"GET /api/iapl/mail-relay/status": "mail service status in the panel: admin",
|
||||
"GET /api/iapl/two-factor/confirm": "public by design: the e-mailed 2FA confirmation link's page (twoFactor.confirmByEmail); shows one button, changes nothing; 400 without a valid waiting set-up",
|
||||
"GET /api/ipal/admin-icon": "public by design: the panel's favicon (white-label)",
|
||||
"GET /api/ipal/admin-language": "public by design: the sign-in panel's language links (whiteLabel.signIn); writes Payload's payload-lng cookie for a supported language and 303s to a path inside the admin route; 400 otherwise",
|
||||
"GET /api/ipal/admin-og": "public by design: the panel's link-preview image",
|
||||
@@ -197,6 +198,8 @@
|
||||
"POST /api/iapl/mail-relay/confirm": "public by design: the mail service's call-back; 404 unless it carries a nonce this site made in the last 5 min (single use)",
|
||||
"POST /api/iapl/mail-relay/connect": "mail service, connect with a pasted token: admin",
|
||||
"POST /api/iapl/mail-relay/disconnect": "mail service, disconnect: admin",
|
||||
"POST /api/iapl/two-factor/confirm": "public by design: the link's button; own origin, the single-use 30-min token AND the enrolling browser's cookie; turns the factor on, ends the account's sessions, signs nobody in",
|
||||
"POST /api/iapl/two-factor/confirm-pending": "2FA: an admin signed in with the second factor confirms another account's waiting set-up (mail not working); own origin",
|
||||
"POST /api/ipal/consent": "public by design: a visitor's own banner choice (random id, no personal data), body capped at 4 KiB",
|
||||
"POST /api/ipal/cookie-approval": "approve cookies: editor+ with the second factor",
|
||||
"POST /api/ipal/cookie-crawl": "start a crawl: editor+, or Bearer IAPL_COOKIE_SCAN_TOKEN (the schedule); only of the configured site URL",
|
||||
|
||||
@@ -74,17 +74,15 @@ test('2FA screens: a prepared back link ends on the admin root', async ({ baseUR
|
||||
await third.goto(`/admin/setup-totp?back=${encodeURIComponent(SCRIPT)}`)
|
||||
const newSecret = await third.locator('input[type="hidden"]').evaluateAll((inputs) => inputs.map((i) => (i as HTMLInputElement).value).find((v) => /^[A-Z2-7]{16,}$/.test(v)))
|
||||
expect(newSecret).toBeTruthy()
|
||||
// twoFactor.confirmByEmail (1.18.0): a FIRST set-up waits for its e-mail link, so the setup screen does not
|
||||
// navigate at all — the script in `back` cannot run, the screen stays. (`back` after setup matters only with
|
||||
// confirmByEmail: false; test/safeBack.test.ts covers the check itself.)
|
||||
await enterCode(third, totp(newSecret!))
|
||||
await expectAdminRoot(third, baseURL!)
|
||||
await expect(third.locator('[data-sonner-toast]').first()).toBeVisible({ timeout: 15_000 })
|
||||
await expect(third).toHaveURL(/\/admin\/setup-totp/)
|
||||
expect(await third.title()).not.toContain('XSS-')
|
||||
await third.context().close()
|
||||
|
||||
// setup screen, an ordinary link back into the panel is still followed
|
||||
const fourth = await passwordOnly(browser, baseURL!, fresh[1])
|
||||
await fourth.goto(`/admin/setup-totp?back=${encodeURIComponent('/admin/collections/pages?limit=5')}`)
|
||||
const fourthSecret = await fourth.locator('input[type="hidden"]').evaluateAll((inputs) => inputs.map((i) => (i as HTMLInputElement).value).find((v) => /^[A-Z2-7]{16,}$/.test(v)))
|
||||
await enterCode(fourth, totp(fourthSecret!))
|
||||
await expect(fourth).toHaveURL(/\/admin\/collections\/pages\?limit=5$/, { timeout: 20_000 })
|
||||
await fourth.context().close()
|
||||
void fresh[1]
|
||||
} finally {
|
||||
for (const id of ids) {await first.request.delete(`/api/users/${id}`, { headers: { origin: baseURL! } })}
|
||||
await first.context().close()
|
||||
|
||||
@@ -0,0 +1,123 @@
|
||||
import { type APIRequestContext, expect, type Page, test } from '@playwright/test'
|
||||
|
||||
import { waitForEnrolmentLink } from './enrolment'
|
||||
import { startSmtpSink } from './smtp-sink'
|
||||
import { secondTestAdmin, totp } from './totp'
|
||||
|
||||
/**
|
||||
* twoFactor.confirmByEmail on the BUILT site (pnpm e2e:built, webpack and Turbopack; security audit 2026-12, F0).
|
||||
* Before 1.18.0 the password of an account inside its setup window was enough to enrol a factor of one's own — the
|
||||
* owner was then locked out. Now the first set-up waits for a link sent to the account's e-mail (read here from the
|
||||
* mail sink), opened in the browser that scanned the code.
|
||||
*/
|
||||
test.describe.configure({ mode: 'serial' })
|
||||
|
||||
const stamp = Date.now()
|
||||
const VICTIM = { email: `e2e-enrol-${stamp}@example.com`, password: `enrol-${stamp}-Hk29dLq` }
|
||||
const ATTACKER_SECRET = 'JBSWY3DPEHPK3PXPJBSWY3DPEHPK3PXP'
|
||||
let sink: Awaited<ReturnType<typeof startSmtpSink>>
|
||||
let victimId: string | undefined
|
||||
|
||||
type Ctx = { request: { newContext: (o: object) => Promise<APIRequestContext> } }
|
||||
const ctx = (playwright: Ctx, baseURL: string) => playwright.request.newContext({ baseURL, extraHTTPHeaders: { origin: baseURL } })
|
||||
|
||||
async function adminApi(playwright: Ctx, baseURL: string) {
|
||||
const api = await ctx(playwright, baseURL)
|
||||
expect((await api.post('/api/users/login', { data: { email: secondTestAdmin(process.env.E2E_ADMIN_EMAIL!), password: process.env.E2E_ADMIN_PASSWORD } })).status()).toBe(200)
|
||||
expect((await (await api.post('/api/verify-totp', { data: { token: totp(process.env.E2E_TOTP_SECRET!) } })).json()).ok).toBe(true)
|
||||
return api
|
||||
}
|
||||
|
||||
async function typeCode(page: Page, secret: string) {
|
||||
await page.getByRole('textbox').first().click()
|
||||
await page.keyboard.type(totp(secret))
|
||||
}
|
||||
|
||||
test.beforeAll(async () => {
|
||||
sink = await startSmtpSink(Number(process.env.E2E_SMTP_PORT ?? 2526))
|
||||
})
|
||||
test.afterAll(async ({ baseURL, playwright }) => {
|
||||
await sink?.close()
|
||||
if (victimId && process.env.E2E_ADMIN_EMAIL) {
|
||||
const api = await adminApi(playwright, baseURL!)
|
||||
await api.delete(`/api/users/${victimId}`)
|
||||
await api.dispose()
|
||||
}
|
||||
})
|
||||
|
||||
test('2FA enrolment: the password alone no longer takes an account inside its setup window', async ({ baseURL, playwright }) => {
|
||||
test.skip(!process.env.E2E_ADMIN_EMAIL || !process.env.E2E_ADMIN_PASSWORD || !process.env.E2E_TOTP_SECRET, 'E2E_* test admin not configured')
|
||||
const admin = await adminApi(playwright, baseURL!)
|
||||
const created = await admin.post('/api/users', { data: { ...VICTIM, roles: ['editor'] } })
|
||||
expect(created.status()).toBe(201)
|
||||
victimId = String((await created.json()).doc.id)
|
||||
await admin.dispose()
|
||||
|
||||
const attacker = await ctx(playwright, baseURL!)
|
||||
expect((await attacker.post('/api/users/login', { data: VICTIM })).status()).toBe(200)
|
||||
const setup = await attacker.post('/api/setup-totp', { data: { secret: ATTACKER_SECRET, token: totp(ATTACKER_SECRET) } })
|
||||
expect(setup.status()).toBe(202)
|
||||
expect(await setup.json()).toMatchObject({ ok: false, pending: true })
|
||||
// not signed in with a factor, nothing opens
|
||||
expect(((await (await attacker.get('/api/users/me')).json()) as { user?: { _strategy?: string } }).user?._strategy).not.toBe('totp')
|
||||
expect((await attacker.post('/api/globals/site-settings', { data: {} })).status()).toBe(403)
|
||||
// the link went to the OWNER's mailbox; opened in the owner's own browser it is refused
|
||||
const link = await waitForEnrolmentLink(sink.messages, VICTIM.email)
|
||||
expect(link.origin).toBe(new URL(baseURL!).origin)
|
||||
const owner = await ctx(playwright, baseURL!)
|
||||
const page = await owner.get(link.pathname + link.search)
|
||||
expect(page.status()).toBe(200)
|
||||
expect(await page.text()).toContain('<form method="post"')
|
||||
const refused = await owner.post('/api/iapl/two-factor/confirm', { form: { t: link.searchParams.get('t')!, u: link.searchParams.get('u')! } })
|
||||
expect(refused.status()).toBe(403)
|
||||
// the owner can still set up their own factor
|
||||
expect((await owner.post('/api/users/login', { data: VICTIM })).status()).toBe(200)
|
||||
const ownSetup = await owner.post('/api/setup-totp', { data: { secret: 'KRSXG5CTMVRXEZLUKRSXG5CTMVRXEZLU', token: totp('KRSXG5CTMVRXEZLUKRSXG5CTMVRXEZLU') } })
|
||||
expect(ownSetup.status()).toBe(202)
|
||||
await attacker.dispose()
|
||||
await owner.dispose()
|
||||
})
|
||||
|
||||
test('2FA enrolment in the panel: code, the notice on the setup screen, the e-mail link, sign in again, in', async ({ baseURL, browser, playwright }) => {
|
||||
test.skip(!process.env.E2E_ADMIN_EMAIL, 'E2E_* test admin not configured')
|
||||
const person = { email: `e2e-enrol-ui-${stamp}@example.com`, password: `enrolui-${stamp}-Pz71mWx` }
|
||||
const admin = await adminApi(playwright, baseURL!)
|
||||
const created = await admin.post('/api/users', { data: { ...person, roles: ['editor'] } })
|
||||
expect(created.status()).toBe(201)
|
||||
const id = String((await created.json()).doc.id)
|
||||
|
||||
const context = await browser.newContext({ baseURL })
|
||||
const page = await context.newPage()
|
||||
try {
|
||||
await page.goto('/admin/login')
|
||||
await page.fill('#field-email', person.email)
|
||||
await page.fill('#field-password', person.password)
|
||||
await page.click('.form-submit button')
|
||||
await page.waitForURL(/setup-totp/)
|
||||
const secret = await page.locator('input[name="secret"]').inputValue()
|
||||
await typeCode(page, secret)
|
||||
// the package's form shows the answer; the screen stays, and after a reload names where the link went
|
||||
await expect(page.locator('[data-sonner-toast]').first()).toContainText(/e…@example\.com/, { timeout: 15_000 })
|
||||
await page.reload()
|
||||
await expect(page.locator('[data-iapl="two-factor-pending"]')).toContainText(/e…@example\.com/)
|
||||
// the link, in this browser: a page with one button, then done
|
||||
const link = await waitForEnrolmentLink(sink.messages, person.email)
|
||||
await page.goto(link.toString())
|
||||
await page.getByRole('button').click()
|
||||
await expect(page.locator('body')).toContainText(/Two-step verification is on|Weryfikacja dwuetapowa jest włączona/)
|
||||
// signed out: password, then the code
|
||||
await page.goto('/admin/login')
|
||||
await page.fill('#field-email', person.email)
|
||||
await page.fill('#field-password', person.password)
|
||||
await page.click('.form-submit button')
|
||||
await page.waitForURL(/verify-totp/, { waitUntil: 'commit' })
|
||||
await typeCode(page, secret)
|
||||
await expect(page).toHaveTitle(/Dashboard|Pulpit/, { timeout: 20_000 })
|
||||
// notices: the confirmation mail, then "turned on"
|
||||
expect(sink.messages.filter((m) => m.to.some((to) => to.includes(person.email))).length).toBeGreaterThanOrEqual(2)
|
||||
} finally {
|
||||
await context.close()
|
||||
await admin.delete(`/api/users/${id}`)
|
||||
await admin.dispose()
|
||||
}
|
||||
})
|
||||
@@ -1,10 +1,12 @@
|
||||
import { type APIRequestContext, expect, type Page, test } from '@playwright/test'
|
||||
|
||||
import { waitForEnrolmentLink } from './enrolment'
|
||||
import { startSmtpSink } from './smtp-sink'
|
||||
import { secondTestAdmin, totp } from './totp'
|
||||
|
||||
/**
|
||||
* "2FA setup required" in a real browser: an account that has not set two-step verification up sees only the setup
|
||||
* screen and gets nothing from the API; after the code it is in. Covers the first admin of a fresh site (only when
|
||||
* screen and gets nothing from the API; after the code and the e-mailed link (twoFactor.confirmByEmail) it is in. Covers the first admin of a fresh site (only when
|
||||
* the database has no users yet — run this file before e2e/create-test-admin.ts for that), a new editor, and the
|
||||
* administrator's reset on the account page.
|
||||
* E2E_BASE_URL=http://localhost:3217 pnpm exec playwright test e2e/two-factor-setup.spec.ts
|
||||
@@ -43,7 +45,7 @@ async function adminApi(playwright: { request: { newContext: (o: object) => Prom
|
||||
return api
|
||||
}
|
||||
|
||||
test('first admin of a fresh site: created, sent to 2FA setup, in after the code', async ({ baseURL, page }) => {
|
||||
test('first admin of a fresh site: created, sent to 2FA setup; with no mail yet the set-up waits for the link in the server log', async ({ baseURL, page }) => {
|
||||
// With users in the database this address leads to the login screen instead.
|
||||
await page.goto('/admin/create-first-user')
|
||||
const firstUserForm = await page.locator('#field-confirm-password').waitFor({ timeout: 10_000 }).then(() => true, () => false)
|
||||
@@ -65,9 +67,10 @@ test('first admin of a fresh site: created, sent to 2FA setup, in after the code
|
||||
}
|
||||
const secret = await page.locator('input[name="secret"]').inputValue()
|
||||
await typeCode(page, secret)
|
||||
await expect(page).toHaveTitle(/Dashboard|Pulpit/, { timeout: 20_000 })
|
||||
expect((await page.request.get('/api/globals/site-integrations', { headers: { origin: baseURL! } })).status()).toBe(200)
|
||||
admin = { ...OWNER, secret }
|
||||
// twoFactor.confirmByEmail: a fresh site has no mail yet, so the set-up waits and its link is in the server log
|
||||
// (the person who set the site up opens it there); nothing opens before that
|
||||
await expect(page.locator('[data-sonner-toast]').first()).toContainText(/administrator|log/i, { timeout: 15_000 })
|
||||
expect((await page.request.get('/api/globals/site-integrations', { headers: { origin: baseURL! } })).status()).toBe(403)
|
||||
})
|
||||
|
||||
test('a new editor: setup screen with the deadline, nothing else, in after the code', async ({ baseURL, page, playwright }) => {
|
||||
@@ -95,9 +98,22 @@ test('a new editor: setup screen with the deadline, nothing else, in after the c
|
||||
await page.waitForURL(/setup-totp/)
|
||||
|
||||
const secret = await page.locator('input[name="secret"]').inputValue()
|
||||
// twoFactor.confirmByEmail: the code starts the set-up, the e-mailed link (opened in this browser) finishes it
|
||||
const sink = await startSmtpSink(Number(process.env.E2E_SMTP_PORT ?? 2526))
|
||||
try {
|
||||
await typeCode(page, secret)
|
||||
const link = await waitForEnrolmentLink(sink.messages, EDITOR.email)
|
||||
await page.goto(link.toString())
|
||||
await page.getByRole('button').click()
|
||||
await expect(page.locator('body')).toContainText(/Two-step verification is on|Weryfikacja dwuetapowa jest włączona/)
|
||||
} finally {
|
||||
await sink.close()
|
||||
}
|
||||
// signed out by the confirmation: password and code, then the data opens
|
||||
await signIn(page, EDITOR)
|
||||
await page.waitForURL(/verify-totp/, { waitUntil: 'commit' })
|
||||
await typeCode(page, secret)
|
||||
// back where it wanted to go, and the data opens
|
||||
await page.waitForURL(/\/admin\/collections\/pages/, { timeout: 20_000 })
|
||||
await expect(page).toHaveTitle(/Dashboard|Pulpit/, { timeout: 20_000 })
|
||||
expect((await page.request.get('/api/pages', { headers: { origin: baseURL! } })).status()).toBe(200)
|
||||
})
|
||||
|
||||
|
||||
@@ -18,7 +18,8 @@
|
||||
* e2e/own-account.spec.ts (1.18.0: the account page asks for the current password; staff sign-in failures per place;
|
||||
* staff sign-in from another origin refused);
|
||||
* e2e/sign-in-answers.spec.ts (1.17.2: a locked staff account answers like a wrong password; the panel actions refuse
|
||||
* another origin).
|
||||
* another origin), e2e/two-factor-enrolment.spec.ts (1.18.0: the first 2FA set-up waits for the e-mailed link,
|
||||
* read from the mail sink; the password alone no longer enrols a factor).
|
||||
*
|
||||
* Needs what the reference site's "Production check" needs (reference/README.md): reference/.env with a local,
|
||||
* seeded database and the E2E_* test admin. The test admins are reset by Playwright's global setup.
|
||||
@@ -96,7 +97,7 @@ for (const bundler of bundlers) {
|
||||
process.exit(1)
|
||||
}
|
||||
console.log(`[e2e:built] ✓ ${bundler}: no package manifest among ${files.length} public files`)
|
||||
run(`${bundler}: the built site — late-staff spec, the mail service, closed doors, the published-files check, the client hints, consent, the sign-in look, the sign-in answers and the own account`, 'pnpm', ['exec', 'playwright', 'test', 'late-staff', 'mail-relay', 'closed-doors', 'smoke', 'sign-in-look', 'sign-in-answers', 'own-account', '--grep', 'late staff collection|the mail service|closed doors|no package.json is published|client hints|consent|sign-in look|locked staff account|panel actions|own account|staff sign-in'], site, { ALLOW_LOCAL_MEDIA: process.env.ALLOW_LOCAL_MEDIA ?? '1', CRON_SECRET: cronSecret, E2E_LATE_STAFF: '1' })
|
||||
run(`${bundler}: the built site — late-staff spec, the mail service, closed doors, the published-files check, the client hints, consent, the sign-in look, the sign-in answers and the own account`, 'pnpm', ['exec', 'playwright', 'test', 'late-staff', 'mail-relay', 'closed-doors', 'smoke', 'sign-in-look', 'sign-in-answers', 'own-account', 'two-factor-enrolment', '--grep', '2FA enrolment|late staff collection|the mail service|closed doors|no package.json is published|client hints|consent|sign-in look|locked staff account|panel actions|own account|staff sign-in'], site, { ALLOW_LOCAL_MEDIA: process.env.ALLOW_LOCAL_MEDIA ?? '1', CRON_SECRET: cronSecret, E2E_LATE_STAFF: '1' })
|
||||
passed.push(bundler)
|
||||
}
|
||||
console.log(`\n[e2e:built] passed: ${passed.join(' and ')}. (The reference site's .next now holds the ${passed.at(-1)} build WITH the fixture: rebuild with \`pnpm build\` there before other checks.)`)
|
||||
|
||||
@@ -61,6 +61,8 @@ export const DESCRIPTIONS = {
|
||||
'docs/DEPLOY.md': 'the Coolify runbook: local check, app settings, MongoDB resource, env, targeted seeds, DNS, rollback',
|
||||
'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/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/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',
|
||||
'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/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/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',
|
||||
|
||||
@@ -520,6 +520,23 @@ export type { JobsRunAccessOptions } from './modules/security/jobsAccess.js'
|
||||
// The doors a built config opens (REST, GraphQL, Next route files) and the judged snapshot they are checked against.
|
||||
export { compareRouteSnapshot, listNextRouteFiles, listPublicRoutes, updateRouteSnapshot } from './modules/security/routeInventory.js'
|
||||
export type { GraphqlSchemaLike, RouteInventoryOptions, RouteSnapshot, RouteSnapshotDiff } from './modules/security/routeInventory.js'
|
||||
export {
|
||||
buildEnrolmentEndpoints,
|
||||
buildTotpNoticeHooks,
|
||||
countPendingEnrolments,
|
||||
dropPendingEnrolment,
|
||||
ENROL_ADMIN_CONFIRM_PATH,
|
||||
ENROL_CONFIRM_PATH,
|
||||
mailConfigured,
|
||||
pendingEnrolmentInfo,
|
||||
pendingEnrolmentKey,
|
||||
readPendingEnrolment,
|
||||
resolveConfirmByEmail,
|
||||
sendTwoFactorNotice,
|
||||
startEnrolment,
|
||||
verifyTotpCode,
|
||||
} from './modules/security/totp/enrolmentConfirm.js'
|
||||
export type { ConfirmByEmailOptions, EnrolmentContext, EnrolmentEndpointsOptions, PendingEnrolment, ResolvedConfirmByEmail } from './modules/security/totp/enrolmentConfirm.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'
|
||||
|
||||
@@ -15,6 +15,35 @@ export const securityTexts = defineTexts({
|
||||
twoFactorAlertTitle: 'Two-step verification',
|
||||
twoFactorBusy: 'Another code for this account is being checked right now. Try again in a moment.',
|
||||
twoFactorCodeDigit: 'Digit {{n}} of {{total}}',
|
||||
twoFactorConfirmPending: 'Confirm the waiting set-up',
|
||||
twoFactorConfirmPendingAsk: 'Confirm only after you have checked with this person, outside the panel (phone, in person), that they started the set-up themselves. Continue?',
|
||||
twoFactorConfirmPendingDone: 'Done. Two-step verification is on for this account; it signs in again with its password and code.',
|
||||
twoFactorConfirmPendingNone: 'There is no waiting set-up for this account (it was confirmed, it expired, or it never started).',
|
||||
twoFactorEnrolButton: 'Turn on two-step verification',
|
||||
twoFactorEnrolDone: 'Two-step verification is on. Sign in again with your password and the code from your app.',
|
||||
twoFactorEnrolInvalid: 'This link does not work any more: it was used, it expired, or a newer set-up was started. Scan the code on the set-up screen again to get a new one.',
|
||||
twoFactorEnrolLead: 'Turn on two-step verification for your account? Do it only if you scanned the code yourself a moment ago, in this browser.',
|
||||
twoFactorEnrolMailFailed: 'The confirmation e-mail could not be sent. Ask an administrator to confirm your set-up on your account page.',
|
||||
twoFactorEnrolMailFailedNoAdmin: 'The confirmation e-mail could not be sent. Ask the people who run the site: the confirmation link is in the server log.',
|
||||
twoFactorEnrolOtherBrowser: 'Open this link in the browser where you scanned the code. If that is not possible, scan the code there again to get a new link.',
|
||||
twoFactorEnrolPendingNotice: 'A link was sent to {{email}} at {{time}}. Open it in this browser. No e-mail? Scan the code again, or ask an administrator.',
|
||||
twoFactorEnrolSent: 'Almost done: we sent a link to {{email}}. Open it in this browser within {{minutes}} min, then sign in again.',
|
||||
twoFactorEnrolSignIn: 'Go to sign-in',
|
||||
twoFactorEnrolTitle: 'Two-step verification',
|
||||
twoFactorEnrolTooMany: 'Too many set-up attempts for this account. Try again in {{minutes}} min.',
|
||||
twoFactorMailBy: 'Done by: {{by}}.',
|
||||
twoFactorMailChangedBody: 'The authenticator app for your account was changed ({{when}}).',
|
||||
twoFactorMailChangedSubject: 'Your two-step verification was changed',
|
||||
twoFactorMailEnrolBody: 'Someone signed in with your password and set up an authenticator app. It works only after the link below is opened in the same browser within {{minutes}} min.',
|
||||
twoFactorMailEnrolButton: 'Turn on two-step verification',
|
||||
twoFactorMailEnrolFrom: 'Browser: {{agent}}. Address: {{ip}}.',
|
||||
twoFactorMailEnrolNotYou: 'If it was not you, do not open the link: someone knows your password. Change it now and tell your administrator.',
|
||||
twoFactorMailEnrolSubject: 'Confirm two-step verification for your account',
|
||||
twoFactorMailNotYou: 'If you did not expect this, tell your administrator at once and change your password.',
|
||||
twoFactorMailOffBody: 'Two-step verification was removed from your account ({{when}}). You will set it up again at your next sign-in.',
|
||||
twoFactorMailOffSubject: 'Two-step verification was removed from your account',
|
||||
twoFactorMailOnBody: 'Two-step verification was turned on for your account ({{when}}).',
|
||||
twoFactorMailOnSubject: 'Two-step verification is on for your account',
|
||||
twoFactorReopen: 'Reopen setup',
|
||||
twoFactorReset: 'Reset two-step verification',
|
||||
twoFactorResetConfirm: 'This account will have to set up two-step verification again before it can use the panel. Continue?',
|
||||
@@ -30,6 +59,7 @@ export const securityTexts = defineTexts({
|
||||
twoFactorStatusOn: 'Set up.',
|
||||
twoFactorStatusOpen: 'Not set up. The account can set it up until {{date}}.',
|
||||
twoFactorStatusOpenNoLimit: 'Not set up yet. The account cannot use the panel until it is.',
|
||||
twoFactorStatusPending: 'Not set up yet. A set-up started on {{date}} waits for confirmation by e-mail.',
|
||||
twoFactorTooManyAttempts: 'Too many codes were tried for this account. Wait {{minutes}} min, then enter the current code from your app.',
|
||||
},
|
||||
pl: {
|
||||
@@ -45,6 +75,35 @@ export const securityTexts = defineTexts({
|
||||
twoFactorAlertTitle: 'Weryfikacja dwuetapowa',
|
||||
twoFactorBusy: 'Właśnie sprawdzamy inny kod dla tego konta. Spróbuj ponownie za chwilę.',
|
||||
twoFactorCodeDigit: 'Cyfra {{n}} z {{total}}',
|
||||
twoFactorConfirmPending: 'Potwierdź oczekującą konfigurację',
|
||||
twoFactorConfirmPendingAsk: 'Potwierdź tylko wtedy, gdy poza panelem (telefonicznie, osobiście) upewnisz się, że ta osoba sama rozpoczęła konfigurację. Kontynuować?',
|
||||
twoFactorConfirmPendingDone: 'Gotowe. Weryfikacja dwuetapowa jest włączona dla tego konta; logowanie od nowa hasłem i kodem.',
|
||||
twoFactorConfirmPendingNone: 'To konto nie ma oczekującej konfiguracji (została potwierdzona, wygasła albo się nie zaczęła).',
|
||||
twoFactorEnrolButton: 'Włącz weryfikację dwuetapową',
|
||||
twoFactorEnrolDone: 'Weryfikacja dwuetapowa jest włączona. Zaloguj się ponownie hasłem i kodem z aplikacji.',
|
||||
twoFactorEnrolInvalid: 'Ten link już nie działa: został użyty, wygasł albo rozpoczęto nowszą konfigurację. Zeskanuj kod na ekranie konfiguracji ponownie, aby dostać nowy.',
|
||||
twoFactorEnrolLead: 'Włączyć weryfikację dwuetapową dla tego konta? Tylko jeśli kod został przed chwilą zeskanowany w tej przeglądarce.',
|
||||
twoFactorEnrolMailFailed: 'Nie udało się wysłać e-maila z potwierdzeniem. Poproś administratora o potwierdzenie konfiguracji na stronie Twojego konta.',
|
||||
twoFactorEnrolMailFailedNoAdmin: 'Nie udało się wysłać e-maila z potwierdzeniem. Zwróć się do osób prowadzących stronę: link potwierdzający jest w logu serwera.',
|
||||
twoFactorEnrolOtherBrowser: 'Otwórz ten link w przeglądarce, w której zeskanowano kod. Jeśli to niemożliwe, zeskanuj tam kod ponownie, aby dostać nowy link.',
|
||||
twoFactorEnrolPendingNotice: 'Link wysłano na {{email}} o {{time}}. Otwórz go w tej przeglądarce. Brak e-maila? Zeskanuj kod ponownie albo poproś administratora.',
|
||||
twoFactorEnrolSent: 'Prawie gotowe: link wysłano na {{email}}. Otwórz go w tej przeglądarce w ciągu {{minutes}} min, a potem zaloguj się ponownie.',
|
||||
twoFactorEnrolSignIn: 'Przejdź do logowania',
|
||||
twoFactorEnrolTitle: 'Weryfikacja dwuetapowa',
|
||||
twoFactorEnrolTooMany: 'Zbyt wiele prób konfiguracji dla tego konta. Spróbuj ponownie za {{minutes}} min.',
|
||||
twoFactorMailBy: 'Wykonał(a): {{by}}.',
|
||||
twoFactorMailChangedBody: 'Aplikacja uwierzytelniająca Twojego konta została zmieniona ({{when}}).',
|
||||
twoFactorMailChangedSubject: 'Twoja weryfikacja dwuetapowa została zmieniona',
|
||||
twoFactorMailEnrolBody: 'Ktoś zalogował się Twoim hasłem i ustawił aplikację uwierzytelniającą. Zadziała po otwarciu linku poniżej w tej samej przeglądarce w ciągu {{minutes}} min.',
|
||||
twoFactorMailEnrolButton: 'Włącz weryfikację dwuetapową',
|
||||
twoFactorMailEnrolFrom: 'Przeglądarka: {{agent}}. Adres: {{ip}}.',
|
||||
twoFactorMailEnrolNotYou: 'Jeśli to nie Ty, nie otwieraj linku: ktoś zna Twoje hasło. Zmień je od razu i powiadom administratora.',
|
||||
twoFactorMailEnrolSubject: 'Potwierdź weryfikację dwuetapową swojego konta',
|
||||
twoFactorMailNotYou: 'Jeśli się tego nie spodziewasz, od razu powiadom administratora i zmień hasło.',
|
||||
twoFactorMailOffBody: 'Weryfikacja dwuetapowa została usunięta z Twojego konta ({{when}}). Ustawisz ją ponownie przy następnym logowaniu.',
|
||||
twoFactorMailOffSubject: 'Weryfikacja dwuetapowa została usunięta z Twojego konta',
|
||||
twoFactorMailOnBody: 'Weryfikacja dwuetapowa została włączona dla Twojego konta ({{when}}).',
|
||||
twoFactorMailOnSubject: 'Weryfikacja dwuetapowa jest włączona dla Twojego konta',
|
||||
twoFactorReopen: 'Otwórz konfigurację ponownie',
|
||||
twoFactorReset: 'Zresetuj weryfikację dwuetapową',
|
||||
twoFactorResetConfirm: 'To konto będzie musiało ponownie ustawić weryfikację dwuetapową, zanim skorzysta z panelu. Kontynuować?',
|
||||
@@ -60,6 +119,7 @@ export const securityTexts = defineTexts({
|
||||
twoFactorStatusOn: 'Ustawiona.',
|
||||
twoFactorStatusOpen: 'Nieustawiona. Konto może ją ustawić do {{date}}.',
|
||||
twoFactorStatusOpenNoLimit: 'Jeszcze nieustawiona. Do tego czasu konto nie może korzystać z panelu.',
|
||||
twoFactorStatusPending: 'Jeszcze nieustawiona. Konfiguracja rozpoczęta {{date}} czeka na potwierdzenie e-mailem.',
|
||||
twoFactorTooManyAttempts: 'Dla tego konta wpisano zbyt wiele kodów. Odczekaj {{minutes}} min, a potem wpisz aktualny kod z aplikacji.',
|
||||
},
|
||||
})
|
||||
|
||||
@@ -183,6 +183,35 @@ export const securityRules: DoctorRule[] = [
|
||||
group: 'security',
|
||||
source: 'static',
|
||||
},
|
||||
{
|
||||
// twoFactor.confirmByEmail (1.18.0): the first enrolment waits for a link sent by e-mail. Without working mail
|
||||
// nobody finishes setting 2FA up on their own: the link is only in the server log, or an admin confirms it.
|
||||
id: '2fa-enrolment-mail',
|
||||
check: (ctx) => {
|
||||
const c = ctx.deep?.twoFactorConfirm
|
||||
if (!c?.on) {return []}
|
||||
const out: RuleFinding[] = []
|
||||
const broken = c.mailConfigured === false || Boolean(ctx.deep?.mail?.methodProblem) || ctx.deep?.mail?.transport === 'none'
|
||||
if (broken) {
|
||||
out.push({
|
||||
fix: 'set up e-mail (Site integrations → E-mail sending: the mail service or SMTP; docs/email.md), then "Send a test e-mail"',
|
||||
message: `e-mail is not working, so nobody can finish setting up two-step verification by themselves: the confirmation link goes only to the server log${c.adminConfirm ? ', or an administrator confirms each set-up on the account page' : ''}`,
|
||||
severity: 'error',
|
||||
})
|
||||
}
|
||||
if (c.pending) {
|
||||
out.push({
|
||||
fix: broken ? 'fix e-mail first; meanwhile an administrator confirms each waiting set-up (account page → "Confirm the waiting set-up") after checking with the person' : 'the people open the link they received; a link expires after its time and they scan the code again',
|
||||
message: `${c.pending} first set-up(s) of two-step verification wait for their e-mail link`,
|
||||
severity: broken ? 'error' : 'info',
|
||||
})
|
||||
}
|
||||
return out
|
||||
},
|
||||
docs: 'docs/security.md#set-up-confirmed-by-e-mail-twofactorconfirmbyemail-118',
|
||||
group: 'security',
|
||||
source: 'deep',
|
||||
},
|
||||
{
|
||||
// Without `access` the plugin adds no roles: every account that can log in to the panel is an admin.
|
||||
id: 'access-missing',
|
||||
|
||||
@@ -10,6 +10,7 @@ import { countPendingCookies } from '../consent/scanner/approval.js'
|
||||
import { COOKIE_REVIEW_SLUG } from '../consent/scanner/collection.js'
|
||||
import { graphAvailable } from '../email/mailAdapter.js'
|
||||
import { mailPanelState } from '../email/relay/panel.js'
|
||||
import { countPendingEnrolments, mailConfigured } from '../security/totp/enrolmentConfirm.js'
|
||||
import { secondFactorPassed, SETUP_FROM_FIELD } from '../security/totp/secondFactor.js'
|
||||
import { countAccountsWithoutTotp } from '../security/totp/setupRequired.js'
|
||||
import { accessAllowed } from '../shared/accessAnswer.js'
|
||||
@@ -46,6 +47,14 @@ export async function collectDoctorStatus(payload: BasePayload): Promise<DoctorS
|
||||
usersSetupClosed = (await countAccountsWithoutTotp(payload, auth.slug, windowMs)).blocked
|
||||
}
|
||||
}
|
||||
// First enrolments waiting for their e-mail link, and whether mail can carry them (twoFactor.confirmByEmail).
|
||||
let twoFactorConfirm: DoctorStatus['twoFactorConfirm'] = null
|
||||
const confirmOn = (payload.config.custom as { iapl?: { twoFactorConfirmByEmail?: { adminConfirm?: boolean } | false } } | undefined)?.iapl?.twoFactorConfirmByEmail
|
||||
if (auth && confirmOn !== undefined) {
|
||||
twoFactorConfirm = confirmOn
|
||||
? { adminConfirm: confirmOn.adminConfirm !== false, mailConfigured: mailConfigured(payload), on: true, pending: await countPendingEnrolments(payload, auth.slug) }
|
||||
: { on: false }
|
||||
}
|
||||
const pendingCookies = collections.some((c) => c.slug === COOKIE_REVIEW_SLUG) ? await countPendingCookies(payload) : null
|
||||
// Turnstile: the recorded state and where the secret comes from — never the keys themselves.
|
||||
let turnstile: DoctorStatus['turnstile'] = null
|
||||
@@ -121,7 +130,7 @@ export async function collectDoctorStatus(payload: BasePayload): Promise<DoctorS
|
||||
}
|
||||
const { csrf, serverURL } = payload.config as { csrf?: unknown; serverURL?: unknown }
|
||||
const originKnown = (typeof serverURL === 'string' && serverURL.trim() !== '') || (Array.isArray(csrf) && csrf.some((o) => typeof o === 'string' && o.trim() !== ''))
|
||||
return { mail, node: process.version, openSignUp, originKnown, pendingCookies, plugin: pluginVersion(), staffOnOwnRoles, staffOpenToOthers, turnstile, turnstileSecretFromEnv: secretFromEnv, usersSetupClosed, usersWithout2fa, visitorWrites }
|
||||
return { mail, node: process.version, openSignUp, originKnown, pendingCookies, plugin: pluginVersion(), staffOnOwnRoles, staffOpenToOthers, turnstile, turnstileSecretFromEnv: secretFromEnv, twoFactorConfirm, usersSetupClosed, usersWithout2fa, visitorWrites }
|
||||
}
|
||||
|
||||
export type DoctorEndpointOptions = {
|
||||
|
||||
@@ -120,6 +120,11 @@ export type DoctorStatus = {
|
||||
turnstile?: { code?: null | string; since?: null | string; state?: null | string } | null
|
||||
/** The Turnstile secret key in use comes from the environment (the panel field is empty). Deprecated. */
|
||||
turnstileSecretFromEnv?: boolean | null
|
||||
/**
|
||||
* twoFactor.confirmByEmail: on or off, first enrolments waiting for their e-mail link (null = could not be counted),
|
||||
* whether a mail transport is configured (Payload's console fallback = not), and whether an admin may confirm.
|
||||
*/
|
||||
twoFactorConfirm?: { adminConfirm?: boolean; mailConfigured?: boolean; on: boolean; pending?: null | number } | null
|
||||
/** Of `usersWithout2fa`: accounts whose setup window has passed (blocked until an admin reopens setup). */
|
||||
usersSetupClosed?: null | number
|
||||
usersWithout2fa?: null | number
|
||||
|
||||
@@ -11,6 +11,7 @@ import { securityTexts } from '../../admin-i18n/texts/security.js'
|
||||
import { signInProviderActive } from '../../branding/signIn/brand.js'
|
||||
import { SignInPanel } from '../../branding/signIn/SignInPanel.js'
|
||||
import { CodeInputNames } from './CodeInputNames.js'
|
||||
import { maskAddress, pendingEnrolmentInfo } from './enrolmentConfirm.js'
|
||||
import { safeAdminBack, type SafeBackRule, type TotpViewComponent, totpViewImportKey } from './safeBack.js'
|
||||
|
||||
export type SafeTotpViewProps = {
|
||||
@@ -81,9 +82,17 @@ export function SafeTotpView(props: SafeTotpViewProps): React.ReactNode {
|
||||
})
|
||||
const req = props.initPageResult?.req
|
||||
const payload = req?.payload ?? props.payload
|
||||
const i18n = (req?.i18n ?? props.i18n) as { language?: string; t: (key: never, vars?: Record<string, unknown>) => string } | undefined
|
||||
// A set-up waiting for its e-mail link (twoFactor.confirmByEmail): say where the link went, above the setup screen.
|
||||
// (its own async server component: SafeTotpView stays a plain function for projects that call it)
|
||||
const shown = pendingNoticeWanted(payload, totpViewImportKey(ipalTotpView)) ? (
|
||||
<>
|
||||
<PendingEnrolmentNotice i18n={i18n} payload={payload} user={(req?.user ?? props.user) as never} />
|
||||
{view}
|
||||
</>
|
||||
) : view
|
||||
// The look only: the panel is a sibling in front of the screen, the screen itself is rendered as above.
|
||||
if (!iaplSignIn) {return view}
|
||||
const i18n = (req?.i18n ?? props.i18n) as { t: (key: never, vars?: Record<string, unknown>) => string } | undefined
|
||||
if (!iaplSignIn) {return shown}
|
||||
const digit = i18n ? iaplT(i18n.t, 'twoFactorCodeDigit', { n: '%n', total: '%t' }) : securityTexts.en.twoFactorCodeDigit.replace('{{n}}', '%n').replace('{{total}}', '%t')
|
||||
return (
|
||||
<>
|
||||
@@ -96,8 +105,30 @@ export function SafeTotpView(props: SafeTotpViewProps): React.ReactNode {
|
||||
user={(req?.user ?? props.user) as never}
|
||||
/>
|
||||
)}
|
||||
{view}
|
||||
{shown}
|
||||
<CodeInputNames label={digit} />
|
||||
</>
|
||||
)
|
||||
}
|
||||
|
||||
const pendingNoticeWanted = (payload: SafeTotpViewProps['payload'] | undefined, viewKey: string) =>
|
||||
Boolean((payload?.config?.custom as { iapl?: { twoFactorConfirmByEmail?: unknown } } | undefined)?.iapl?.twoFactorConfirmByEmail) && /setup/i.test(viewKey)
|
||||
|
||||
/** The notice on the setup screen while the account's first set-up waits for its e-mail link; nothing otherwise. */
|
||||
async function PendingEnrolmentNotice({ i18n, payload, user }: {
|
||||
i18n: { language?: string; t: (key: never, vars?: Record<string, unknown>) => string } | undefined
|
||||
payload: SafeTotpViewProps['payload'] | undefined
|
||||
user: ({ collection?: string; email?: string; id?: number | string } & Record<string, unknown>) | null | undefined
|
||||
}): Promise<React.ReactNode> {
|
||||
if (!payload || !user?.id || typeof user.collection !== 'string') {return null}
|
||||
const pending = await pendingEnrolmentInfo(payload, user.collection, user.id).catch(() => null)
|
||||
if (!pending) {return null}
|
||||
const time = pending.createdAt.toLocaleTimeString(i18n?.language === 'pl' ? 'pl-PL' : 'en-GB', { hour: '2-digit', minute: '2-digit' })
|
||||
const vars = { email: maskAddress(typeof user.email === 'string' ? user.email : ''), time }
|
||||
const text = i18n ? iaplT(i18n.t, 'twoFactorEnrolPendingNotice', vars) : securityTexts.en.twoFactorEnrolPendingNotice.replace('{{email}}', vars.email).replace('{{time}}', time)
|
||||
return (
|
||||
<div className="banner banner--type-info" data-iapl="two-factor-pending" role="status" style={{ margin: '0 auto 1rem', maxWidth: '36rem' }}>
|
||||
{text}
|
||||
</div>
|
||||
)
|
||||
}
|
||||
|
||||
@@ -6,8 +6,11 @@ import { useState } from 'react'
|
||||
import { iaplT } from '../../admin-i18n/t.js'
|
||||
|
||||
type Props = {
|
||||
/** `reopen`: the account has no TOTP (window passed or still open). `reset`: it has one (lost phone). */
|
||||
kind: 'reopen' | 'reset'
|
||||
/**
|
||||
* `reopen`: the account has no TOTP (window passed or still open). `reset`: it has one (lost phone).
|
||||
* `confirm`: it has a set-up waiting for its e-mail confirmation, and the administrator confirms it (twoFactor.confirmByEmail).
|
||||
*/
|
||||
kind: 'confirm' | 'reopen' | 'reset'
|
||||
userId: number | string
|
||||
}
|
||||
|
||||
@@ -20,9 +23,11 @@ export function TwoFactorResetButton({ kind, userId }: Props) {
|
||||
|
||||
const run = async () => {
|
||||
if (kind === 'reset' && !window.confirm(text('twoFactorResetConfirm'))) {return}
|
||||
if (kind === 'confirm' && !window.confirm(text('twoFactorConfirmPendingAsk'))) {return}
|
||||
setBusy(true)
|
||||
try {
|
||||
const res = await fetch(`${config.serverURL ?? ''}${config.routes?.api ?? '/api'}/ipal/two-factor/reset`, {
|
||||
const path = kind === 'confirm' ? '/iapl/two-factor/confirm-pending' : '/ipal/two-factor/reset'
|
||||
const res = await fetch(`${config.serverURL ?? ''}${config.routes?.api ?? '/api'}${path}`, {
|
||||
body: JSON.stringify({ userId }),
|
||||
credentials: 'include',
|
||||
headers: { 'Content-Type': 'application/json' },
|
||||
@@ -30,7 +35,7 @@ export function TwoFactorResetButton({ kind, userId }: Props) {
|
||||
})
|
||||
const data = (await res.json()) as { message?: string; ok?: boolean }
|
||||
if (data.ok) {
|
||||
toast.success(data.message ?? text('twoFactorResetDone'))
|
||||
toast.success(data.message ?? text(kind === 'confirm' ? 'twoFactorConfirmPendingDone' : 'twoFactorResetDone'))
|
||||
// The status next to this button is rendered on the server with the document: load it again.
|
||||
// (router.refresh() does not re-render a document's field components.)
|
||||
window.location.reload()
|
||||
@@ -46,7 +51,7 @@ export function TwoFactorResetButton({ kind, userId }: Props) {
|
||||
|
||||
return (
|
||||
<button className="btn btn--style-secondary btn--size-small" disabled={busy} onClick={run} style={{ marginTop: '.5rem' }} type="button">
|
||||
{text(kind === 'reopen' ? 'twoFactorReopen' : 'twoFactorReset')}
|
||||
{text(kind === 'confirm' ? 'twoFactorConfirmPending' : kind === 'reopen' ? 'twoFactorReopen' : 'twoFactorReset')}
|
||||
</button>
|
||||
)
|
||||
}
|
||||
|
||||
@@ -3,6 +3,7 @@ import type { BasePayload } from 'payload'
|
||||
import { userMeetsRole } from '../../access/predicates.js'
|
||||
import { formatDateTime } from '../../admin-i18n/t.js'
|
||||
import { serverText } from '../../integrations/texts.js'
|
||||
import { pendingEnrolmentInfo } from './enrolmentConfirm.js'
|
||||
import { twoFactorSetupDeadline, twoFactorSetupState } from './secondFactor.js'
|
||||
import { TwoFactorResetButton } from './TwoFactorResetButton.js'
|
||||
|
||||
@@ -46,8 +47,11 @@ export async function TwoFactorStatusField({ data, i18n, payload, user }: Props)
|
||||
if (state === 'not-applicable') {return null}
|
||||
const deadline = twoFactorSetupDeadline({ payload, user: account })
|
||||
const date = deadline ? formatDateTime(deadline.toISOString(), i18n?.language ?? 'en') : ''
|
||||
const confirmOn = (payload.config.custom as { iapl?: { twoFactorConfirmByEmail?: { adminConfirm?: boolean } | false } } | undefined)?.iapl?.twoFactorConfirmByEmail
|
||||
const pending = confirmOn && (state === 'open' || state === 'exempt') ? await pendingEnrolmentInfo(payload, collection, data.id) : null
|
||||
const status =
|
||||
state === 'set-up' ? serverText(i18n, 'twoFactorStatusOn')
|
||||
pending ? serverText(i18n, 'twoFactorStatusPending', { date: formatDateTime(pending.createdAt.toISOString(), i18n?.language ?? 'en') })
|
||||
: state === 'set-up' ? serverText(i18n, 'twoFactorStatusOn')
|
||||
: state === 'exempt' ? serverText(i18n, 'twoFactorStatusExempt')
|
||||
: state === 'closed' ? serverText(i18n, 'twoFactorStatusClosed', { date })
|
||||
: deadline ? serverText(i18n, 'twoFactorStatusOpen', { date })
|
||||
@@ -58,6 +62,7 @@ export async function TwoFactorStatusField({ data, i18n, payload, user }: Props)
|
||||
<div className="field-type" id="ipal-two-factor-status">
|
||||
<span className="field-label">{serverText(i18n, 'twoFactorStatusLabel')}</span>
|
||||
<p style={{ margin: 0, ...(state === 'closed' ? { color: 'var(--theme-error-500, #b00020)' } : {}) }}>{status}</p>
|
||||
{canReset && pending && confirmOn && confirmOn.adminConfirm && <TwoFactorResetButton kind="confirm" userId={data.id} />}
|
||||
{canReset && state !== 'exempt' && <TwoFactorResetButton kind={state === 'set-up' ? 'reset' : 'reopen'} userId={data.id} />}
|
||||
</div>
|
||||
)
|
||||
|
||||
@@ -0,0 +1,554 @@
|
||||
import type { BasePayload, CollectionAfterChangeHook, CollectionBeforeChangeHook, Endpoint, PayloadRequest } from 'payload'
|
||||
|
||||
import { createHash, createHmac, randomBytes, timingSafeEqual } from 'node:crypto'
|
||||
|
||||
import type { AdminTextKey } from '../../admin-i18n/texts/index.js'
|
||||
|
||||
import { userMeetsRole } from '../../access/predicates.js'
|
||||
import { afterCommit } from '../../database/transactions.js'
|
||||
import { withMailKind } from '../../email/relay/kinds.js'
|
||||
import { serverText } from '../../integrations/texts.js'
|
||||
import { consumeRateLimit } from '../../shared/rateLimit.js'
|
||||
import { secondFactorPassed } from './secondFactor.js'
|
||||
|
||||
/**
|
||||
* Two-step verification set up by e-mail confirmation (`twoFactor.confirmByEmail`, on by default; security audit
|
||||
* 2026-12, finding F0).
|
||||
*
|
||||
* Without it, whoever has an account's password can enrol THEIR OWN authenticator while the account has none (its
|
||||
* setup window), and the owner is locked out. So the FIRST enrolment of a factor is only stored as pending:
|
||||
* 1. `POST /api/setup-totp` with a right code for the new secret → the secret is kept aside (payload-kv), a
|
||||
* single-use link goes to the account's own e-mail, and the browser that asked gets a random cookie;
|
||||
* 2. the link (`GET /api/iapl/two-factor/confirm`) 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 (hash, 30 min, single use), that the pending secret is the one the link was made
|
||||
* for, and — `sameBrowser`, on by default — that it comes from the browser that started the set-up: the owner
|
||||
* who receives a mail they did not ask for cannot turn on the attacker's factor by clicking it. Then the secret
|
||||
* 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: no factor, nothing but the setup screen.
|
||||
*
|
||||
* Mail that cannot be sent (no mail set up, the mail service pending, SMTP incomplete) must not lock anybody out:
|
||||
* - the link is written to the server log (`logLinkWhenMailFails`, on by default — the logs are read by the team
|
||||
* that runs the site, never by the person at the keyboard), and
|
||||
* - an administrator who is fully signed in confirms the waiting set-up from the account page (`adminConfirm`),
|
||||
* after checking with the person outside the panel.
|
||||
* - the doctor reports it (rule `2fa-enrolment-mail`).
|
||||
* A notice goes to the account's address on every enrolment, change and removal / reset of its factor (`notices`).
|
||||
* Mails never carry the secret.
|
||||
*/
|
||||
|
||||
export type ConfirmByEmailOptions = {
|
||||
/** An administrator (fully signed in) may confirm another account's waiting set-up from the panel. Default true. */
|
||||
adminConfirm?: boolean
|
||||
/** How long the link works, in minutes. Default 30. */
|
||||
linkMinutes?: number
|
||||
/** When the mail cannot be sent, the link is written to the server log (one line). Default true. */
|
||||
logLinkWhenMailFails?: boolean
|
||||
/** Confirmation mails per account and hour (each set-up attempt sends one). Default 5. */
|
||||
maxMailsPerHour?: number
|
||||
/** A notice to the account's address on every enrolment, change and removal / reset. Default true. */
|
||||
notices?: boolean
|
||||
/** The link works only in the browser that started the set-up. Default true. */
|
||||
sameBrowser?: boolean
|
||||
}
|
||||
|
||||
export type ResolvedConfirmByEmail = Required<ConfirmByEmailOptions>
|
||||
|
||||
export const ENROL_CONFIRM_PATH = '/iapl/two-factor/confirm'
|
||||
export const ENROL_ADMIN_CONFIRM_PATH = '/iapl/two-factor/confirm-pending'
|
||||
/** The cookie that ties a waiting set-up to the browser that started it (`<cookiePrefix>-iapl-enrol`). */
|
||||
export const ENROL_COOKIE_SUFFIX = 'iapl-enrol'
|
||||
/** The mark a write carries when it is the confirmed enrolment (afterChange sends the "turned on" notice). */
|
||||
export const ENROL_CONFIRMED_CONTEXT = 'iaplEnrolmentConfirmed'
|
||||
|
||||
const DEFAULTS: ResolvedConfirmByEmail = { adminConfirm: true, linkMinutes: 30, logLinkWhenMailFails: true, maxMailsPerHour: 5, notices: true, sameBrowser: true }
|
||||
|
||||
/** `twoFactor.confirmByEmail` → the options, or null when switched off. A value that is not understood stops the start. */
|
||||
export function resolveConfirmByEmail(option: unknown): null | ResolvedConfirmByEmail {
|
||||
if (option === false) {return null}
|
||||
if (option === undefined || option === null || option === true) {return { ...DEFAULTS }}
|
||||
if (typeof option !== 'object' || Array.isArray(option)) {
|
||||
throw new Error(`[iapl] twoFactor.confirmByEmail must be false or an object, got ${JSON.stringify(option)}.`)
|
||||
}
|
||||
const o = option as Record<string, unknown>
|
||||
const out = { ...DEFAULTS }
|
||||
for (const key of ['adminConfirm', 'logLinkWhenMailFails', 'notices', 'sameBrowser'] as const) {
|
||||
if (o[key] === undefined) {continue}
|
||||
if (typeof o[key] !== 'boolean') {throw new Error(`[iapl] twoFactor.confirmByEmail.${key} must be true or false, got ${JSON.stringify(o[key])}.`)}
|
||||
out[key] = o[key]
|
||||
}
|
||||
for (const key of ['linkMinutes', 'maxMailsPerHour'] as const) {
|
||||
if (o[key] === undefined) {continue}
|
||||
const v = o[key]
|
||||
if (typeof v !== 'number' || !Number.isInteger(v) || v < 1 || (key === 'linkMinutes' && v > 24 * 60)) {
|
||||
throw new Error(`[iapl] twoFactor.confirmByEmail.${key} must be a whole number${key === 'linkMinutes' ? ' of minutes from 1 to 1440' : ' of 1 or more'}, got ${JSON.stringify(v)}.`)
|
||||
}
|
||||
out[key] = v
|
||||
}
|
||||
return out
|
||||
}
|
||||
|
||||
// ---------------------------------------------------------------------------------------------- the code check
|
||||
|
||||
const BASE32 = 'ABCDEFGHIJKLMNOPQRSTUVWXYZ234567'
|
||||
|
||||
function base32Bytes(secret: string): Buffer | null {
|
||||
const clean = secret.replace(/=+$/, '').toUpperCase()
|
||||
if (!/^[A-Z2-7]+$/.test(clean)) {return null}
|
||||
let bits = ''
|
||||
for (const ch of clean) {bits += BASE32.indexOf(ch).toString(2).padStart(5, '0')}
|
||||
return Buffer.from((bits.match(/.{8}/g) ?? []).map((b) => parseInt(b, 2)))
|
||||
}
|
||||
|
||||
export type TotpParams = { algorithm?: string; digits?: number; period?: number }
|
||||
|
||||
/**
|
||||
* RFC 6238 check of `token` for `secret` (base32), one period either side — the same rule as the 2FA package
|
||||
* (`otpauth`'s `validate({ window: 1 })` with its options), so a code the package would accept is accepted here.
|
||||
*/
|
||||
export function verifyTotpCode(secret: string, token: string, { algorithm = 'SHA1', digits = 6, period = 30 }: TotpParams = {}, now = Date.now()): boolean {
|
||||
const key = base32Bytes(secret)
|
||||
if (!key || key.length < 10 || typeof token !== 'string' || !new RegExp(`^\\d{${digits}}$`).test(token.trim())) {return false}
|
||||
const hash = algorithm.toLowerCase().replace('-', '')
|
||||
const counter = Math.floor(now / 1000 / period)
|
||||
for (const step of [0, -1, 1]) {
|
||||
const buf = Buffer.alloc(8)
|
||||
buf.writeBigUInt64BE(BigInt(counter + step))
|
||||
const mac = createHmac(hash, key).update(buf).digest()
|
||||
const offset = mac[mac.length - 1] & 0xf
|
||||
const code = ((mac.readUInt32BE(offset) & 0x7fffffff) % 10 ** digits).toString().padStart(digits, '0')
|
||||
if (timingSafeEqual(Buffer.from(code), Buffer.from(token.trim()))) {return true}
|
||||
}
|
||||
return false
|
||||
}
|
||||
|
||||
// ---------------------------------------------------------------------------------------------- the waiting set-up
|
||||
|
||||
export type PendingEnrolment = {
|
||||
/** sha256 of the browser cookie (sameBrowser). */
|
||||
browser: string
|
||||
createdAt: number
|
||||
expiresAt: number
|
||||
/** The secret the person scanned. Stored like the 2FA package stores a confirmed one; never sent anywhere. */
|
||||
secret: string
|
||||
/** sha256 of the link's token. */
|
||||
token: string
|
||||
}
|
||||
|
||||
type KV = { delete?: (key: string) => Promise<void>; get: (key: string) => Promise<unknown>; keys?: () => Promise<string[]>; set: (key: string, value: object) => Promise<void> }
|
||||
const memory = new Map<string, PendingEnrolment>()
|
||||
let warnedMemory = false
|
||||
|
||||
/** Key of an account's waiting set-up in `payload.kv`. */
|
||||
export const pendingEnrolmentKey = (collection: string, id: number | string) => `iapl:2fa-enrol:${collection}:${String(id)}`
|
||||
const sha256 = (value: string) => createHash('sha256').update(value).digest('hex')
|
||||
const sameHash = (a: string, b: string) => a.length === b.length && timingSafeEqual(Buffer.from(a), Buffer.from(b))
|
||||
|
||||
const kvOf = (payload: BasePayload): KV | null => {
|
||||
const kv = (payload as { kv?: KV }).kv
|
||||
return kv && typeof kv.get === 'function' && typeof kv.set === 'function' ? kv : null
|
||||
}
|
||||
|
||||
export async function readPendingEnrolment(payload: BasePayload, collection: string, id: number | string, now = Date.now()): Promise<null | PendingEnrolment> {
|
||||
const key = pendingEnrolmentKey(collection, id)
|
||||
const kv = kvOf(payload)
|
||||
let entry: unknown = memory.get(key) ?? null
|
||||
if (kv) {
|
||||
try {
|
||||
entry = await kv.get(key)
|
||||
} catch {
|
||||
// the memory copy, if any
|
||||
}
|
||||
}
|
||||
const p = entry as null | PendingEnrolment
|
||||
if (!p || typeof p.secret !== 'string' || typeof p.token !== 'string' || typeof p.expiresAt !== 'number') {return null}
|
||||
return p.expiresAt > now ? p : null
|
||||
}
|
||||
|
||||
async function writePending(payload: BasePayload, key: string, value: null | PendingEnrolment): Promise<void> {
|
||||
if (value) {memory.set(key, value)} else {memory.delete(key)}
|
||||
const kv = kvOf(payload)
|
||||
if (!kv) {
|
||||
if (!warnedMemory) {
|
||||
warnedMemory = true
|
||||
payload.logger.warn('[iapl] 2FA: payload-kv is not available; waiting set-ups are kept in this process only (several instances: a link may not work on another).')
|
||||
}
|
||||
return
|
||||
}
|
||||
try {
|
||||
if (value) {await kv.set(key, value)} else if (typeof kv.delete === 'function') {await kv.delete(key)} else {await kv.set(key, { removed: true })}
|
||||
} catch (err) {
|
||||
payload.logger.warn(`[iapl] 2FA: could not store a waiting set-up (${err instanceof Error ? err.message : String(err)}); kept in this process only.`)
|
||||
}
|
||||
}
|
||||
|
||||
/** Ends an account's waiting set-up (a reset, a confirmed one). */
|
||||
export async function dropPendingEnrolment(payload: BasePayload, collection: string, id: number | string): Promise<void> {
|
||||
await writePending(payload, pendingEnrolmentKey(collection, id), null)
|
||||
}
|
||||
|
||||
/** How many accounts have a waiting set-up that has not expired (the doctor). Null when it cannot be told. */
|
||||
export async function countPendingEnrolments(payload: BasePayload, collection: string, now = Date.now()): Promise<null | number> {
|
||||
const kv = kvOf(payload)
|
||||
const prefix = `iapl:2fa-enrol:${collection}:`
|
||||
if (!kv || typeof kv.keys !== 'function') {return [...memory.entries()].filter(([k, v]) => k.startsWith(prefix) && v.expiresAt > now).length}
|
||||
try {
|
||||
const keys = (await kv.keys()).filter((k) => k.startsWith(prefix))
|
||||
let n = 0
|
||||
for (const key of keys) {
|
||||
const v = (await kv.get(key)) as null | Partial<PendingEnrolment>
|
||||
if (v && typeof v.expiresAt === 'number' && v.expiresAt > now && typeof v.secret === 'string') {n++}
|
||||
}
|
||||
return n
|
||||
} catch {
|
||||
return null
|
||||
}
|
||||
}
|
||||
|
||||
// ---------------------------------------------------------------------------------------------- mail
|
||||
|
||||
type MailNoun = { email?: unknown; id?: unknown }
|
||||
type I18nLike = Parameters<typeof serverText>[0]
|
||||
|
||||
/** The language of mails sent without a request in hand: the panel's fallback language. */
|
||||
const fallbackI18n = (payload: BasePayload): I18nLike => ({ language: (payload.config.i18n as { fallbackLanguage?: string } | undefined)?.fallbackLanguage ?? 'en' }) as I18nLike
|
||||
|
||||
/** `[email protected]` → `j…@firma.pl` (the setup screen names where the link went without spelling it out). */
|
||||
export function maskAddress(address: string): string {
|
||||
const at = address.lastIndexOf('@')
|
||||
return at > 0 ? `${address[0]}…${address.slice(at)}` : '…'
|
||||
}
|
||||
|
||||
const escapeHtml = (s: string) => s.replace(/&/g, '&').replace(/</g, '<').replace(/>/g, '>').replace(/"/g, '"')
|
||||
|
||||
/** Whether Payload has a real mail transport (its fallback only prints to the console). */
|
||||
export function mailConfigured(payload: BasePayload): boolean {
|
||||
const email = (payload as { email?: { name?: string } }).email
|
||||
return Boolean(email) && email?.name !== 'console'
|
||||
}
|
||||
|
||||
/** Sends one message; true when the transport took it. Never throws. */
|
||||
async function sendMail(payload: BasePayload, message: { html: string; subject: string; text: string; to: string }, kind: 'account' | 'security-alert'): Promise<boolean> {
|
||||
if (!mailConfigured(payload)) {return false}
|
||||
try {
|
||||
const result = (await payload.sendEmail(withMailKind(message, kind) as never)) as { sent?: boolean } | null | undefined
|
||||
return !(result && typeof result === 'object' && result.sent === false)
|
||||
} catch (err) {
|
||||
payload.logger.warn(`[iapl] 2FA: a mail to an account could not be sent (${err instanceof Error ? err.message : String(err)}).`)
|
||||
return false
|
||||
}
|
||||
}
|
||||
|
||||
const paragraph = (s: string) => `<p>${escapeHtml(s)}</p>`
|
||||
|
||||
/** A notice to the account: two-step verification was turned on, changed, or removed / reset. */
|
||||
export async function sendTwoFactorNotice(payload: BasePayload, account: MailNoun, change: 'changed' | 'off' | 'on', by?: string): Promise<boolean> {
|
||||
if (typeof account.email !== 'string' || !account.email) {return false}
|
||||
const i18n = fallbackI18n(payload)
|
||||
const t = (key: AdminTextKey, vars?: Record<string, unknown>) => serverText(i18n, key, vars)
|
||||
const subject = t(change === 'on' ? 'twoFactorMailOnSubject' : change === 'off' ? 'twoFactorMailOffSubject' : 'twoFactorMailChangedSubject')
|
||||
const when = new Date().toISOString().replace('T', ' ').slice(0, 16) + ' UTC'
|
||||
const lines = [
|
||||
t(change === 'on' ? 'twoFactorMailOnBody' : change === 'off' ? 'twoFactorMailOffBody' : 'twoFactorMailChangedBody', { when }),
|
||||
...(by ? [t('twoFactorMailBy', { by })] : []),
|
||||
t('twoFactorMailNotYou'),
|
||||
]
|
||||
const sent = await sendMail(payload, { html: lines.map(paragraph).join(''), subject, text: lines.join('\n\n'), to: account.email }, 'security-alert')
|
||||
if (!sent) {payload.logger.warn(`[iapl] 2FA: the notice "${change}" for ${account.email} was not sent (no working mail).`)}
|
||||
return sent
|
||||
}
|
||||
|
||||
// ---------------------------------------------------------------------------------------------- the set-up request
|
||||
|
||||
type SetupUser = { collection?: unknown; email?: unknown; id?: number | string }
|
||||
|
||||
/** What the plugin passes to the setup handler. */
|
||||
export type EnrolmentContext = {
|
||||
collection: string
|
||||
options: ResolvedConfirmByEmail
|
||||
/** The 2FA package's TOTP options (`totp: { algorithm, digits, period }`). */
|
||||
totp?: TotpParams
|
||||
}
|
||||
|
||||
const json = (body: Record<string, unknown>, status = 200, headers: Record<string, string> = {}) =>
|
||||
Response.json(body, { headers: { 'Cache-Control': 'no-store', ...headers }, status })
|
||||
|
||||
const secureRequest = (req: PayloadRequest) => (req.headers.get('x-forwarded-proto') ?? new URL(req.url ?? 'http://localhost').protocol.replace(':', '')) === 'https'
|
||||
|
||||
/** `<serverURL><api>/iapl/two-factor/confirm?u=…&t=…` — only from the configured serverURL, never from the request's Host. */
|
||||
function confirmLink(payload: BasePayload, id: number | string, token: string): null | string {
|
||||
const server = (payload.config.serverURL ?? '').replace(/\/+$/, '')
|
||||
if (!/^https?:\/\//i.test(server)) {return null}
|
||||
const api = payload.config.routes?.api ?? '/api'
|
||||
return `${server}${api}${ENROL_CONFIRM_PATH}?u=${encodeURIComponent(String(id))}&t=${encodeURIComponent(token)}`
|
||||
}
|
||||
|
||||
/**
|
||||
* `POST /api/setup-totp` for an account WITHOUT a factor, when confirmByEmail is on: checks the code like the 2FA
|
||||
* package, keeps the secret aside and mails the link. Answers `{ ok: false, pending: true, message }` (status 202):
|
||||
* the package's setup form shows the message and stays on the screen.
|
||||
*/
|
||||
export async function startEnrolment(req: PayloadRequest, ctx: EnrolmentContext): Promise<Response> {
|
||||
const user = req.user as null | SetupUser
|
||||
const i18n = req.i18n as I18nLike
|
||||
if (!user?.id) {return json({ message: 'Not allowed.', ok: false }, 403)}
|
||||
let body: unknown
|
||||
try {
|
||||
body = await req.json?.()
|
||||
} catch {
|
||||
body = undefined
|
||||
}
|
||||
const secret = typeof (body as { secret?: unknown })?.secret === 'string' ? (body as { secret: string }).secret.trim() : ''
|
||||
const token = typeof (body as { token?: unknown })?.token === 'string' ? (body as { token: string }).token : ''
|
||||
if (!secret || !token) {return json({ message: serverText(i18n, 'twoFactorResetFailed'), ok: false }, 400)}
|
||||
if (!verifyTotpCode(secret, token, ctx.totp)) {
|
||||
return json({ message: String(req.i18n?.t?.('totpPlugin:setup:incorrectCode' as never) ?? 'The code is not right.'), ok: false }, 400)
|
||||
}
|
||||
// Each attempt sends a mail: at most `maxMailsPerHour` per account (not per address: the attacker has the password).
|
||||
const limit = await consumeRateLimit({ key: `${ctx.collection}:${String(user.id)}`, max: ctx.options.maxMailsPerHour, scope: 'iapl-2fa-enrol', windowMs: 3_600_000 })
|
||||
if (!limit.ok) {
|
||||
return json({ message: serverText(i18n, 'twoFactorEnrolTooMany', { minutes: Math.ceil(limit.retryAfter / 60) }), ok: false }, 429, { 'Retry-After': String(limit.retryAfter) })
|
||||
}
|
||||
|
||||
const linkToken = randomBytes(32).toString('base64url')
|
||||
const browser = randomBytes(32).toString('base64url')
|
||||
const now = Date.now()
|
||||
const pending: PendingEnrolment = { browser: sha256(browser), createdAt: now, expiresAt: now + ctx.options.linkMinutes * 60_000, secret, token: sha256(linkToken) }
|
||||
// A newer set-up replaces a waiting one: its link stops working.
|
||||
await writePending(req.payload, pendingEnrolmentKey(ctx.collection, user.id), pending)
|
||||
|
||||
const address = typeof user.email === 'string' ? user.email : ''
|
||||
const link = confirmLink(req.payload, user.id, linkToken)
|
||||
const t = (key: AdminTextKey, vars?: Record<string, unknown>) => serverText(i18n, key, vars)
|
||||
let sent = false
|
||||
if (address && link) {
|
||||
const ip = req.headers.get('x-forwarded-for')?.split(',').pop()?.trim() || req.headers.get('x-real-ip') || ''
|
||||
const agent = (req.headers.get('user-agent') ?? '').slice(0, 160)
|
||||
const lines = [
|
||||
t('twoFactorMailEnrolBody', { minutes: ctx.options.linkMinutes }),
|
||||
t('twoFactorMailEnrolFrom', { agent: agent || '?', ip: ip || '?' }),
|
||||
t('twoFactorMailEnrolNotYou'),
|
||||
]
|
||||
sent = await sendMail(
|
||||
req.payload,
|
||||
{
|
||||
html: `${paragraph(lines[0])}<p><a href="${escapeHtml(link)}">${escapeHtml(t('twoFactorMailEnrolButton'))}</a></p>${lines.slice(1).map(paragraph).join('')}`,
|
||||
subject: t('twoFactorMailEnrolSubject'),
|
||||
text: `${lines[0]}\n\n${link}\n\n${lines.slice(1).join('\n\n')}`,
|
||||
to: address,
|
||||
},
|
||||
'account',
|
||||
)
|
||||
}
|
||||
if (!sent && link && ctx.options.logLinkWhenMailFails) {
|
||||
// For the team that runs the site (Coolify → Logs). Single use, short-lived, and with sameBrowser it works only
|
||||
// in the browser that started the set-up.
|
||||
req.payload.logger.warn(`[iapl] 2FA: the confirmation e-mail for ${address || String(user.id)} could not be sent (no working mail). Link (valid ${ctx.options.linkMinutes} min, single use): ${link}`)
|
||||
} else if (!link) {
|
||||
req.payload.logger.warn('[iapl] 2FA: no serverURL in the Payload config, so no confirmation link can be made (a link from the request\'s Host could point anywhere). Set serverURL (NEXT_PUBLIC_SERVER_URL).')
|
||||
}
|
||||
|
||||
const cookie = `${req.payload.config.cookiePrefix || 'payload'}-${ENROL_COOKIE_SUFFIX}=${browser}; Path=/; Max-Age=${ctx.options.linkMinutes * 60}; HttpOnly; SameSite=Lax${secureRequest(req) ? '; Secure' : ''}`
|
||||
const message = sent
|
||||
? t('twoFactorEnrolSent', { email: maskAddress(address), minutes: ctx.options.linkMinutes })
|
||||
: t(ctx.options.adminConfirm ? 'twoFactorEnrolMailFailed' : 'twoFactorEnrolMailFailedNoAdmin')
|
||||
return json({ mailed: sent, message, ok: false, pending: true }, 202, { 'Set-Cookie': cookie })
|
||||
}
|
||||
|
||||
// ---------------------------------------------------------------------------------------------- confirming
|
||||
|
||||
const page = (lang: string, title: string, body: string, status = 200) =>
|
||||
new Response(
|
||||
`<!doctype html><html lang="${lang === 'pl' ? 'pl' : 'en'}"><head><meta charset="utf-8"><meta name="viewport" content="width=device-width,initial-scale=1"><meta name="robots" content="noindex,nofollow"><title>${escapeHtml(title)}</title>` +
|
||||
'<style>body{font:16px/1.5 system-ui,sans-serif;max-width:32rem;margin:10vh auto;padding:0 1rem;color:#171717;background:#fff}button,a.b{font:inherit;padding:.6rem 1.2rem;border-radius:6px;border:0;background:#171717;color:#fff;cursor:pointer;text-decoration:none;display:inline-block}@media (prefers-color-scheme:dark){body{background:#171717;color:#f5f5f5}button,a.b{background:#f5f5f5;color:#171717}}</style>' +
|
||||
`</head><body><h1>${escapeHtml(title)}</h1>${body}</body></html>`,
|
||||
{
|
||||
headers: {
|
||||
'Cache-Control': 'no-store',
|
||||
'Content-Security-Policy': "default-src 'none'; style-src 'unsafe-inline'; form-action 'self'; frame-ancestors 'none'; base-uri 'none'",
|
||||
'Content-Type': 'text/html; charset=utf-8',
|
||||
'Referrer-Policy': 'no-referrer',
|
||||
'X-Robots-Tag': 'noindex, nofollow',
|
||||
},
|
||||
status,
|
||||
},
|
||||
)
|
||||
|
||||
const languageOf = (req: PayloadRequest) => ((req.i18n as { language?: string } | undefined)?.language === 'pl' ? 'pl' : 'en')
|
||||
|
||||
function cookieValue(req: PayloadRequest, name: string): string {
|
||||
for (const part of (req.headers.get('cookie') ?? '').split(';')) {
|
||||
const i = part.indexOf('=')
|
||||
if (i > 0 && part.slice(0, i).trim() === name) {return part.slice(i + 1).trim()}
|
||||
}
|
||||
return ''
|
||||
}
|
||||
|
||||
/** Writes the waiting secret: the confirmed enrolment. Ends every session; signs nobody in. */
|
||||
async function activate(req: PayloadRequest, collection: string, id: number | string, pending: PendingEnrolment, by?: string): Promise<boolean> {
|
||||
const useSessions = (req.payload.collections as Record<string, { config?: { auth?: { useSessions?: boolean } } }>)[collection]?.config?.auth?.useSessions !== false
|
||||
try {
|
||||
const current = (await req.payload.findByID({ id, collection: collection as never, depth: 0, overrideAccess: true, select: { totpSecret: true } as never, showHiddenFields: true })) as { totpSecret?: null | string }
|
||||
if (current.totpSecret) {return false} // set up in the meantime: nothing to confirm
|
||||
await req.payload.update({
|
||||
id,
|
||||
collection: collection as never,
|
||||
context: { [ENROL_CONFIRMED_CONTEXT]: by ?? true },
|
||||
data: { totpSecret: pending.secret, ...(useSessions ? { sessions: [] } : {}) } as never,
|
||||
overrideAccess: true,
|
||||
req,
|
||||
})
|
||||
} catch (err) {
|
||||
req.payload.logger.error(`[iapl] 2FA: confirming a set-up failed: ${err instanceof Error ? err.message : String(err)}`)
|
||||
return false
|
||||
}
|
||||
await dropPendingEnrolment(req.payload, collection, id)
|
||||
return true
|
||||
}
|
||||
|
||||
export type EnrolmentEndpointsOptions = {
|
||||
collection: string
|
||||
options: ResolvedConfirmByEmail
|
||||
/** The `twoFactor.sameOrigin` rule (the confirm POST and the admin action refuse other origins). */
|
||||
ownOrigin?: (req: PayloadRequest) => boolean
|
||||
/** Who may confirm another account's waiting set-up (default: like the 2FA reset — an admin who entered a code). */
|
||||
resetAccess?: (args: { req: PayloadRequest }) => boolean | Promise<boolean>
|
||||
}
|
||||
|
||||
/** The link's page (GET), its button (POST), and the administrator's confirm (POST, JSON). */
|
||||
export function buildEnrolmentEndpoints({ collection, options, ownOrigin, resetAccess }: EnrolmentEndpointsOptions): Endpoint[] {
|
||||
const params = (req: PayloadRequest, form?: URLSearchParams) => {
|
||||
const url = new URL(req.url ?? 'http://localhost')
|
||||
const get = (k: string) => form?.get(k) ?? url.searchParams.get(k) ?? ''
|
||||
return { token: get('t'), userId: get('u') }
|
||||
}
|
||||
const invalid = (req: PayloadRequest, key: AdminTextKey = 'twoFactorEnrolInvalid', status = 400) => {
|
||||
const i18n = req.i18n as I18nLike
|
||||
return page(languageOf(req), serverText(i18n, 'twoFactorEnrolTitle'), paragraph(serverText(i18n, key)), status)
|
||||
}
|
||||
const endpoints: Endpoint[] = [
|
||||
{
|
||||
// Opening the link changes nothing (mail scanners open links): a page with one button.
|
||||
handler: async (req) => {
|
||||
const i18n = req.i18n as I18nLike
|
||||
const { token, userId } = params(req)
|
||||
if (!token || !userId) {return invalid(req)}
|
||||
const pending = await readPendingEnrolment(req.payload, collection, userId)
|
||||
if (!pending || !sameHash(pending.token, sha256(token))) {return invalid(req)}
|
||||
const action = `${req.payload.config.routes?.api ?? '/api'}${ENROL_CONFIRM_PATH}`
|
||||
return page(
|
||||
languageOf(req),
|
||||
serverText(i18n, 'twoFactorEnrolTitle'),
|
||||
paragraph(serverText(i18n, 'twoFactorEnrolLead')) +
|
||||
`<form method="post" action="${escapeHtml(action)}"><input type="hidden" name="u" value="${escapeHtml(userId)}"><input type="hidden" name="t" value="${escapeHtml(token)}"><button type="submit">${escapeHtml(serverText(i18n, 'twoFactorEnrolButton'))}</button></form>`,
|
||||
)
|
||||
},
|
||||
method: 'get',
|
||||
path: ENROL_CONFIRM_PATH,
|
||||
},
|
||||
{
|
||||
handler: async (req) => {
|
||||
const i18n = req.i18n as I18nLike
|
||||
if (ownOrigin && !ownOrigin(req)) {return invalid(req, 'twoFactorEnrolInvalid', 403)}
|
||||
let form: URLSearchParams
|
||||
try {
|
||||
form = new URLSearchParams((await req.text?.()) ?? '')
|
||||
} catch {
|
||||
return invalid(req)
|
||||
}
|
||||
const { token, userId } = params(req, form)
|
||||
if (!token || !userId) {return invalid(req)}
|
||||
const pending = await readPendingEnrolment(req.payload, collection, userId)
|
||||
if (!pending || !sameHash(pending.token, sha256(token))) {return invalid(req)}
|
||||
if (options.sameBrowser) {
|
||||
const browser = cookieValue(req, `${req.payload.config.cookiePrefix || 'payload'}-${ENROL_COOKIE_SUFFIX}`)
|
||||
if (!browser || !sameHash(pending.browser, sha256(browser))) {return invalid(req, 'twoFactorEnrolOtherBrowser', 403)}
|
||||
}
|
||||
if (!(await activate(req, collection, userId, pending))) {return invalid(req)}
|
||||
const admin = `${req.payload.config.routes?.admin ?? '/admin'}/login`
|
||||
const res = page(
|
||||
languageOf(req),
|
||||
serverText(i18n, 'twoFactorEnrolTitle'),
|
||||
paragraph(serverText(i18n, 'twoFactorEnrolDone')) + `<p><a class="b" href="${escapeHtml(admin)}">${escapeHtml(serverText(i18n, 'twoFactorEnrolSignIn'))}</a></p>`,
|
||||
)
|
||||
res.headers.append('Set-Cookie', `${req.payload.config.cookiePrefix || 'payload'}-${ENROL_COOKIE_SUFFIX}=; Path=/; Max-Age=0; HttpOnly; SameSite=Lax`)
|
||||
return res
|
||||
},
|
||||
method: 'post',
|
||||
path: ENROL_CONFIRM_PATH,
|
||||
},
|
||||
]
|
||||
if (options.adminConfirm) {
|
||||
endpoints.push({
|
||||
handler: async (req) => {
|
||||
const i18n = req.i18n as I18nLike
|
||||
const allowed =
|
||||
Boolean(req.user) &&
|
||||
secondFactorPassed(req) &&
|
||||
(req.user as { collection?: unknown }).collection === collection &&
|
||||
(resetAccess ? (await resetAccess({ req })) === true : (req.user as { _strategy?: unknown })._strategy === 'totp' && userMeetsRole(req, 'admin'))
|
||||
if (!allowed) {return json({ message: serverText(i18n, 'twoFactorResetForbidden'), ok: false }, 403)}
|
||||
if (ownOrigin && !ownOrigin(req)) {return json({ message: 'Not allowed from this origin.', ok: false }, 403)}
|
||||
let body: unknown
|
||||
try {
|
||||
body = await req.json?.()
|
||||
} catch {
|
||||
body = undefined
|
||||
}
|
||||
const userId = (body as { userId?: unknown } | undefined)?.userId
|
||||
if ((typeof userId !== 'string' && typeof userId !== 'number') || String(userId) === String((req.user as { id?: unknown }).id)) {
|
||||
return json({ message: serverText(i18n, 'twoFactorConfirmPendingNone'), ok: false }, 400)
|
||||
}
|
||||
const pending = await readPendingEnrolment(req.payload, collection, userId)
|
||||
if (!pending) {return json({ message: serverText(i18n, 'twoFactorConfirmPendingNone'), ok: false }, 404)}
|
||||
const actor = (req.user as { email?: string; id?: unknown }).email ?? String((req.user as { id?: unknown }).id)
|
||||
if (!(await activate(req, collection, userId, pending, actor))) {return json({ message: serverText(i18n, 'twoFactorConfirmPendingNone'), ok: false }, 409)}
|
||||
req.payload.logger.info(`[iapl] 2FA: ${actor} confirmed the waiting set-up of ${collection} ${String(userId)}.`)
|
||||
return json({ message: serverText(i18n, 'twoFactorConfirmPendingDone'), ok: true })
|
||||
},
|
||||
method: 'post',
|
||||
path: ENROL_ADMIN_CONFIRM_PATH,
|
||||
})
|
||||
}
|
||||
return endpoints
|
||||
}
|
||||
|
||||
// ---------------------------------------------------------------------------------------------- notices
|
||||
|
||||
const CHANGE = 'iaplTotpChange'
|
||||
|
||||
/**
|
||||
* beforeChange + afterChange on the 2FA collection: a notice to the account whenever its factor is turned on,
|
||||
* changed or removed — through any path (setup, the package's remove / admin endpoints, IAPL's reset, the Local API).
|
||||
* A removal also ends a waiting set-up.
|
||||
*/
|
||||
export function buildTotpNoticeHooks(collection: string, { notices }: Pick<ResolvedConfirmByEmail, 'notices'>): { afterChange: CollectionAfterChangeHook; beforeChange: CollectionBeforeChangeHook } {
|
||||
return {
|
||||
afterChange: async ({ context, doc, req }) => {
|
||||
const change = context?.[CHANGE] as 'changed' | 'off' | 'on' | undefined
|
||||
if (!change || !doc) {return doc}
|
||||
if (change === 'off') {await dropPendingEnrolment(req.payload, collection, (doc as { id: number | string }).id)}
|
||||
if (!notices) {return doc}
|
||||
const actor = req.user && String((req.user as { id?: unknown }).id) !== String((doc as { id?: unknown }).id) ? ((req.user as { email?: string }).email ?? undefined) : undefined
|
||||
const by = typeof context?.[ENROL_CONFIRMED_CONTEXT] === 'string' ? (context[ENROL_CONFIRMED_CONTEXT]) : actor
|
||||
const send = () => sendTwoFactorNotice(req.payload, doc as MailNoun, change, by).then(() => undefined)
|
||||
if (!afterCommit(req, send)) {void send()}
|
||||
return doc
|
||||
},
|
||||
beforeChange: ({ context, data, operation, originalDoc }) => {
|
||||
if (!data || operation !== 'update' || !('totpSecret' in data)) {return data}
|
||||
const before = Boolean((originalDoc as { totpSecret?: unknown } | undefined)?.totpSecret)
|
||||
const after = Boolean(data.totpSecret)
|
||||
const change = !before && after ? 'on' : before && !after ? 'off' : before && after && data.totpSecret !== (originalDoc as { totpSecret?: unknown }).totpSecret ? 'changed' : null
|
||||
if (change && context) {context[CHANGE] = change}
|
||||
return data
|
||||
},
|
||||
}
|
||||
}
|
||||
|
||||
/** For the setup screen and the account page: the waiting set-up of this account (when it started), or null. */
|
||||
export async function pendingEnrolmentInfo(payload: BasePayload, collection: string, id: number | string): Promise<{ createdAt: Date; expiresAt: Date } | null> {
|
||||
const p = await readPendingEnrolment(payload, collection, id)
|
||||
return p ? { createdAt: new Date(p.createdAt), expiresAt: new Date(p.expiresAt) } : null
|
||||
}
|
||||
@@ -377,6 +377,11 @@ type EndpointLike = { handler: (req: never) => Promise<Response> | Response; pat
|
||||
* so a password alone cannot reset or remove TOTP.
|
||||
*/
|
||||
export type TotpEndpointGuards = {
|
||||
/**
|
||||
* `/setup-totp` for an account WITHOUT a factor: when set, this answers instead of the package (the enrolment
|
||||
* waits for an e-mail confirmation, enrolmentConfirm.ts) — the package never writes the secret or its cookie.
|
||||
*/
|
||||
enrol?: (req: never) => Promise<Response> | Response
|
||||
/**
|
||||
* Called for a verify attempt of a logged-in account before the package sees
|
||||
* it. Return a Response to refuse (too many attempts), null to let it through.
|
||||
@@ -414,6 +419,11 @@ export function guardTotpEndpoint<T extends EndpointLike>(endpoint: T, collectio
|
||||
if (user && (endpoint.path === '/verify-totp' || endpoint.path === '/setup-totp') && guards.ownOrigin && !guards.ownOrigin(req as never)) {
|
||||
return Response.json({ message: 'Not allowed from this origin.', ok: false }, { status: 403 })
|
||||
}
|
||||
// The first enrolment waits for the e-mail link (twoFactor.confirmByEmail): the package's handler is not called,
|
||||
// so it neither stores the secret nor sets its `-totp` cookie (which would turn valid once any secret is confirmed).
|
||||
if (user && endpoint.path === '/setup-totp' && guards.enrol && ['exempt', 'open'].includes(twoFactorSetupState(req))) {
|
||||
return guards.enrol(req as never)
|
||||
}
|
||||
// The code has about three right answers in a million and the package never counts tries.
|
||||
if (user && endpoint.path === '/verify-totp' && guards.limitVerify) {
|
||||
const limited = await guards.limitVerify(req as never)
|
||||
|
||||
@@ -53,6 +53,7 @@ import { serverText } from './modules/integrations/texts.js'
|
||||
import { buildSystemPagesFields } from './modules/pages/index.js'
|
||||
import { guardAdminEndpoints } from './modules/security/adminSameOrigin.js'
|
||||
import { jobsRunNotice, withJobsRunAccess } from './modules/security/jobsAccess.js'
|
||||
import { buildEnrolmentEndpoints, buildTotpNoticeHooks, resolveConfirmByEmail, startEnrolment } from './modules/security/totp/enrolmentConfirm.js'
|
||||
import { missingImportMapEntries } from './modules/security/totp/importMapCheck.js'
|
||||
import { changedViewKeys, copyViews, SAFE_TOTP_VIEW, wrapTotpViews } from './modules/security/totp/safeBack.js'
|
||||
import { reportRefusedOrigin, requestFromOwnOrigin } from './modules/security/totp/sameOrigin.js'
|
||||
@@ -342,6 +343,8 @@ export const iapl = (options: IaplOptions): Plugin => {
|
||||
// whatever the package registered, also paths a later version adds.
|
||||
const limitVerify = tf.verifyLimit === false ? undefined : buildVerifyLimit(target, { ...tf.verifyLimit, keyPrefix: (typeof tf.verifyLimit?.keyPrefix === 'string' && tf.verifyLimit.keyPrefix.trim()) || (options.storageNames === 'iapl' ? 'iapl' : 'ipal') })
|
||||
const extraOrigins = typeof tf.sameOrigin === 'object' ? (tf.sameOrigin.origins ?? []) : []
|
||||
// First enrolment confirmed by e-mail (on by default, 1.18.0): checked at start like every other switch.
|
||||
const confirmByEmail = resolveConfirmByEmail(tf.confirmByEmail)
|
||||
const guards = {
|
||||
...(limitVerify ? { limitVerify: (req: PayloadRequest) => limitVerify(req), settleVerify: (req: PayloadRequest, correct: boolean) => limitVerify.settle(req, correct) } : {}),
|
||||
...(tf.sameOrigin === false
|
||||
@@ -353,10 +356,21 @@ export const iapl = (options: IaplOptions): Plugin => {
|
||||
return false
|
||||
},
|
||||
}),
|
||||
...(confirmByEmail ? { enrol: (req: PayloadRequest) => startEnrolment(req, { collection: target, options: confirmByEmail }) } : {}),
|
||||
onSetupClosed: (req: PayloadRequest) =>
|
||||
Response.json({ message: serverText(req.i18n as never, 'twoFactorSetupClosed'), ok: false }, { status: 403 }),
|
||||
}
|
||||
config.endpoints = (config.endpoints ?? []).map((e) => (endpointsBefore.has(e) ? e : guardTotpEndpoint(e, target, guards as never)))
|
||||
if (confirmByEmail) {
|
||||
// the link's page and button, and the administrator's confirm of a waiting set-up
|
||||
config.endpoints = [...config.endpoints, ...buildEnrolmentEndpoints({ collection: target, options: confirmByEmail, ...(guards.ownOrigin ? { ownOrigin: guards.ownOrigin } : {}), ...(tf.resetAccess ? { resetAccess: tf.resetAccess } : {}) })]
|
||||
// a notice mail on every enrolment, change and removal / reset, whatever path wrote it
|
||||
const notice = buildTotpNoticeHooks(target, confirmByEmail)
|
||||
config.collections = (config.collections ?? []).map((c) =>
|
||||
c.slug === target ? { ...c, hooks: { ...c.hooks, afterChange: [...(c.hooks?.afterChange ?? []), notice.afterChange], beforeChange: [...(c.hooks?.beforeChange ?? []), notice.beforeChange] } } : c,
|
||||
)
|
||||
}
|
||||
config.custom = { ...config.custom, iapl: { ...(config.custom as { iapl?: object } | undefined)?.iapl, twoFactorConfirmByEmail: confirmByEmail ? { adminConfirm: confirmByEmail.adminConfirm } : false } }
|
||||
// …and the same for endpoints it may put on a collection or a global.
|
||||
config.collections = guardNewEntityEndpoints(config.collections, entityEndpointsBefore, target, guards as never)
|
||||
config.globals = guardNewEntityEndpoints(config.globals, entityEndpointsBefore, target, guards as never)
|
||||
|
||||
@@ -28,6 +28,7 @@ import type { I18nConfig } from './modules/i18n/types.js'
|
||||
import type { PagesOption } from './modules/pages/types.js'
|
||||
import type { AdminSameOriginOption } from './modules/security/adminSameOrigin.js'
|
||||
import type { JobsRunAccessOptions } from './modules/security/jobsAccess.js'
|
||||
import type { ConfirmByEmailOptions } from './modules/security/totp/enrolmentConfirm.js'
|
||||
import type { SafeBackRule } from './modules/security/totp/safeBack.js'
|
||||
import type { RequireSetupOptions } from './modules/security/totp/setupRequired.js'
|
||||
import type { VerifyLimitOptions } from './modules/security/totp/verifyLimit.js'
|
||||
@@ -359,6 +360,16 @@ export type IaplOptions = {
|
||||
* injects). Must be an auth collection.
|
||||
*/
|
||||
collectionSlug?: CollectionSlug
|
||||
/**
|
||||
* The FIRST enrolment of a factor takes effect only after a link sent to the account's own e-mail is
|
||||
* opened in the browser that scanned the code (1.18.0, on by default; security.md "Set-up confirmed by
|
||||
* e-mail"). Without it whoever has the password of an account in its setup window could enrol their own
|
||||
* authenticator. A notice mail goes out on every enrolment, change and removal / reset. When mail cannot
|
||||
* be sent the link goes to the server log and an administrator can confirm from the account page.
|
||||
* `{ linkMinutes, sameBrowser, adminConfirm, logLinkWhenMailFails, notices, maxMailsPerHour }` adapts it;
|
||||
* `false` = the 2FA package's behaviour (the code alone turns it on).
|
||||
*/
|
||||
confirmByEmail?: ConfirmByEmailOptions | false
|
||||
/**
|
||||
* IAPL's own second-factor check on every collection and global —
|
||||
* also the ones added after the 2FA package ran (IAPL's own, other
|
||||
|
||||
+1
-1
@@ -554,7 +554,7 @@ describe('security and deep status', () => {
|
||||
}
|
||||
const status = await collectDoctorStatus(payload as never)
|
||||
expect(status).toMatchObject({ pendingCookies: 4, usersWithout2fa: 2 })
|
||||
expect(Object.keys(status).sort()).toEqual(['mail', 'node', 'openSignUp', 'originKnown', 'pendingCookies', 'plugin', 'staffOnOwnRoles', 'staffOpenToOthers', 'turnstile', 'turnstileSecretFromEnv', 'usersSetupClosed', 'usersWithout2fa', 'visitorWrites'])
|
||||
expect(Object.keys(status).sort()).toEqual(['mail', 'node', 'openSignUp', 'originKnown', 'pendingCookies', 'plugin', 'staffOnOwnRoles', 'staffOpenToOthers', 'turnstile', 'turnstileSecretFromEnv', 'twoFactorConfirm', 'usersSetupClosed', 'usersWithout2fa', 'visitorWrites'])
|
||||
expect(status.usersSetupClosed).toBeNull() // no setup window in this config
|
||||
expect(status.mail).toBeNull() // no Site integrations global in this config
|
||||
})
|
||||
|
||||
@@ -0,0 +1,62 @@
|
||||
/**
|
||||
* twoFactor.confirmByEmail building blocks: the switch is read strictly, the code check agrees with the 2FA package's
|
||||
* own (RFC 6238 vectors; one period either side, like otpauth's window 1), addresses are masked, and the notice hooks see every transition. The HTTP flow is in
|
||||
* enrolmentConfirmHttp.test.ts.
|
||||
*/
|
||||
import { describe, expect, test } from 'vitest'
|
||||
|
||||
import { buildTotpNoticeHooks, maskAddress, resolveConfirmByEmail, verifyTotpCode } from '../src/modules/security/totp/enrolmentConfirm.js'
|
||||
|
||||
describe('confirmByEmail options', () => {
|
||||
test('on by default; false turns it off; nonsense stops the start', () => {
|
||||
expect(resolveConfirmByEmail(undefined)).toMatchObject({ adminConfirm: true, linkMinutes: 30, logLinkWhenMailFails: true, maxMailsPerHour: 5, notices: true, sameBrowser: true })
|
||||
expect(resolveConfirmByEmail(false)).toBeNull()
|
||||
expect(resolveConfirmByEmail({ linkMinutes: 10, sameBrowser: false })).toMatchObject({ linkMinutes: 10, sameBrowser: false })
|
||||
for (const bad of ['false', 0, [], { sameBrowser: 'false' }, { linkMinutes: 0 }, { linkMinutes: 2000 }, { maxMailsPerHour: 1.5 }]) {
|
||||
expect(() => resolveConfirmByEmail(bad), JSON.stringify(bad)).toThrow(/confirmByEmail/)
|
||||
}
|
||||
})
|
||||
})
|
||||
|
||||
describe('the code check', () => {
|
||||
const secret = 'JBSWY3DPEHPK3PXPJBSWY3DPEHPK3PXP'
|
||||
test('RFC 6238 test vectors (SHA1, SHA256, SHA512; 8 digits) and one period either side, not two', () => {
|
||||
// RFC 6238 Appendix B: seeds "1234567890…" (20 / 32 / 64 bytes) in base32
|
||||
const sha1 = 'GEZDGNBVGY3TQOJQGEZDGNBVGY3TQOJQ'
|
||||
const sha256 = 'GEZDGNBVGY3TQOJQGEZDGNBVGY3TQOJQGEZDGNBVGY3TQOJQGEZA'
|
||||
const sha512 = 'GEZDGNBVGY3TQOJQGEZDGNBVGY3TQOJQGEZDGNBVGY3TQOJQGEZDGNBVGY3TQOJQGEZDGNBVGY3TQOJQGEZDGNBVGY3TQOJQGEZDGNA'
|
||||
const at = (s: number) => s * 1000
|
||||
expect(verifyTotpCode(sha1, '94287082', { digits: 8 }, at(59))).toBe(true)
|
||||
expect(verifyTotpCode(sha256, '46119246', { algorithm: 'SHA256', digits: 8 }, at(59))).toBe(true)
|
||||
expect(verifyTotpCode(sha512, '90693936', { algorithm: 'SHA512', digits: 8 }, at(59))).toBe(true)
|
||||
expect(verifyTotpCode(sha1, '07081804', { digits: 8 }, at(1111111109))).toBe(true)
|
||||
// the same code 30 s later still passes (window 1), 90 s later not
|
||||
expect(verifyTotpCode(sha1, '07081804', { digits: 8 }, at(1111111109 + 30))).toBe(true)
|
||||
expect(verifyTotpCode(sha1, '07081804', { digits: 8 }, at(1111111109 + 90))).toBe(false)
|
||||
expect(verifyTotpCode(sha1, '1234567', { digits: 8 }, at(59))).toBe(false)
|
||||
expect(verifyTotpCode('not base32!', '123456', {}, at(59))).toBe(false)
|
||||
expect(verifyTotpCode('ABCD', '123456', {}, at(59))).toBe(false) // too short a key
|
||||
void secret
|
||||
})
|
||||
test('addresses are masked on the screen', () => {
|
||||
expect(maskAddress('[email protected]')).toBe('j…@firma.pl')
|
||||
expect(maskAddress('nope')).toBe('…')
|
||||
})
|
||||
})
|
||||
|
||||
describe('notice hooks', () => {
|
||||
const { beforeChange } = buildTotpNoticeHooks('users', { notices: true })
|
||||
const change = (before: unknown, after: unknown, operation = 'update') => {
|
||||
const context: Record<string, unknown> = {}
|
||||
beforeChange({ context, data: { totpSecret: after }, operation, originalDoc: { totpSecret: before } } as never)
|
||||
return context.iaplTotpChange ?? null
|
||||
}
|
||||
test('on, off, changed; nothing for a write that does not touch the secret, or a create', () => {
|
||||
expect(change(null, 'A')).toBe('on')
|
||||
expect(change('A', null)).toBe('off')
|
||||
expect(change('A', 'B')).toBe('changed')
|
||||
expect(change('A', 'A')).toBeNull()
|
||||
expect(change(null, null)).toBeNull()
|
||||
expect(change(null, 'A', 'create')).toBeNull()
|
||||
})
|
||||
})
|
||||
@@ -0,0 +1,290 @@
|
||||
/**
|
||||
* twoFactor.confirmByEmail (1.18.0; security audit 2026-12, finding F0): the first enrolment of a factor waits for a
|
||||
* link sent to the account's own e-mail and opened in the browser that scanned the code. Real HTTP (Payload's REST
|
||||
* and GraphQL handlers behind a server), a capturing mail transport, the 2FA package itself.
|
||||
*/
|
||||
import type { Payload } from 'payload'
|
||||
|
||||
import { payloadTotp } from '@clocklimited/payload-2fa'
|
||||
import { lexicalEditor } from '@payloadcms/richtext-lexical'
|
||||
import { createServer } from 'node:net'
|
||||
import os from 'os'
|
||||
import path from 'path'
|
||||
import { getPayload } from 'payload'
|
||||
import { afterAll, beforeAll, beforeEach, describe, expect, test, vi } from 'vitest'
|
||||
|
||||
import { pendingEnrolmentKey } from '../src/modules/security/totp/enrolmentConfirm.js'
|
||||
import { iapl } from '../src/plugin.js'
|
||||
import { buildTestConfig } from './helpers.js'
|
||||
import { testDatabase } from './http/db.js'
|
||||
import { cookiesOf, startPayloadServer, type TestServer } from './http/server.js'
|
||||
import { totp } from './http/totp.js'
|
||||
|
||||
vi.mock('server-only', () => ({}))
|
||||
vi.mock('next/headers.js', async () => (await import('./http/server.js')).nextHeadersMock)
|
||||
|
||||
const ADMIN_SECRET = 'GEZDGNBVGY3TQOJQGEZDGNBVGY3TQOJQ'
|
||||
const ATTACKER_SECRET = 'JBSWY3DPEHPK3PXPJBSWY3DPEHPK3PXP'
|
||||
const OWNER_SECRET = 'KRSXG5CTMVRXEZLUKRSXG5CTMVRXEZLU'
|
||||
const PASSWORD = 'a-long-test-password-1'
|
||||
|
||||
type Mail = { html?: string; subject?: string; text?: string; to?: string }
|
||||
const mails: Mail[] = []
|
||||
let mailBroken = false
|
||||
let server: TestServer
|
||||
let payload: Payload
|
||||
let base = ''
|
||||
|
||||
const freePort = () => new Promise<number>((resolve) => {
|
||||
const s = createServer().listen(0, '127.0.0.1', () => {
|
||||
const { port } = s.address() as { port: number }
|
||||
s.close(() => resolve(port))
|
||||
})
|
||||
})
|
||||
|
||||
beforeAll(async () => {
|
||||
const port = await freePort()
|
||||
base = `http://127.0.0.1:${port}`
|
||||
const config = buildTestConfig({
|
||||
collections: [{ slug: 'media', fields: [], upload: { staticDir: path.join(os.tmpdir(), 'ipal-test-media') } }],
|
||||
db: testDatabase('enrol_confirm'),
|
||||
editor: lexicalEditor(),
|
||||
email: () => ({
|
||||
name: 'capture',
|
||||
defaultFromAddress: '[email protected]',
|
||||
defaultFromName: 'Site',
|
||||
sendEmail: async (message: unknown) => {
|
||||
const m = message as Mail
|
||||
if (mailBroken) {throw new Error('SMTP down')}
|
||||
mails.push(m)
|
||||
return { sent: true }
|
||||
},
|
||||
}),
|
||||
plugins: [
|
||||
iapl({
|
||||
access: { authCollection: 'users' },
|
||||
forms: {},
|
||||
i18n: { defaultLocale: 'pl', locales: [{ code: 'pl', label: 'Polski' }] },
|
||||
twoFactor: { issuer: 'Example', plugin: payloadTotp },
|
||||
}),
|
||||
],
|
||||
secret: 'integration-test-secret-0123456789',
|
||||
serverURL: base,
|
||||
telemetry: false,
|
||||
})
|
||||
payload = await getPayload({ config })
|
||||
server = await startPayloadServer(config, port)
|
||||
// an administrator with a factor (made by a script, like a seed): for the admin's own actions
|
||||
await payload.create({ collection: 'users' as never, data: { email: '[email protected]', password: PASSWORD, roles: ['admin'], totpSecret: ADMIN_SECRET } as never })
|
||||
}, 120_000)
|
||||
|
||||
afterAll(async () => {
|
||||
await server?.close()
|
||||
await payload?.destroy?.()
|
||||
})
|
||||
|
||||
beforeEach(() => {
|
||||
mails.length = 0
|
||||
mailBroken = false
|
||||
})
|
||||
|
||||
const json = { 'content-type': 'application/json', origin: () => base }
|
||||
const headers = (cookie = '', extra: Record<string, string> = {}) => ({ 'content-type': 'application/json', cookie, origin: base, ...extra })
|
||||
let accounts = 0
|
||||
|
||||
/** A new editor account without a factor (inside its setup window). */
|
||||
async function newAccount(): Promise<{ email: string; id: number | string }> {
|
||||
const email = `person-${++accounts}-${Date.now()}@example.com`
|
||||
const doc = (await payload.create({ collection: 'users' as never, data: { email, password: PASSWORD, roles: ['editor'] } as never })) as unknown as { id: number | string }
|
||||
return { id: doc.id, email }
|
||||
}
|
||||
const signIn = async (email: string) => {
|
||||
const res = await fetch(`${base}/api/users/login`, { body: JSON.stringify({ email, password: PASSWORD }), headers: headers(), method: 'POST' })
|
||||
expect(res.status).toBe(200)
|
||||
return cookiesOf(res).join('; ')
|
||||
}
|
||||
const setup = (cookie: string, secret: string, token = totp(secret)) =>
|
||||
fetch(`${base}/api/setup-totp`, { body: JSON.stringify({ secret, token }), headers: headers(cookie), method: 'POST' })
|
||||
const storedSecret = async (id: number | string) =>
|
||||
((await payload.findByID({ id, collection: 'users' as never, overrideAccess: true, showHiddenFields: true })) as unknown as { totpSecret?: null | string }).totpSecret ?? null
|
||||
const linkIn = (mail: Mail | undefined) => {
|
||||
const m = (mail?.text ?? '').match(/https?:\/\/\S+\/two-factor\/confirm\?u=\S+/)
|
||||
return m ? new URL(m[0]) : null
|
||||
}
|
||||
const confirm = (link: URL, cookie = '', origin = base) =>
|
||||
fetch(`${base}/api/iapl/two-factor/confirm`, {
|
||||
body: new URLSearchParams({ t: link.searchParams.get('t')!, u: link.searchParams.get('u')! }).toString(),
|
||||
headers: { 'content-type': 'application/x-www-form-urlencoded', cookie, origin },
|
||||
method: 'POST',
|
||||
})
|
||||
void json
|
||||
|
||||
describe('F0: the password alone no longer enrols a factor', () => {
|
||||
test('an attacker with the password: the set-up waits, a link goes to the OWNER\'s mailbox, nothing opens, no -totp cookie', async () => {
|
||||
const victim = await newAccount()
|
||||
const attacker = await signIn(victim.email)
|
||||
const res = await setup(attacker, ATTACKER_SECRET)
|
||||
expect(res.status).toBe(202)
|
||||
const body = (await res.json()) as { mailed?: boolean; message?: string; ok?: boolean; pending?: boolean }
|
||||
expect(body).toMatchObject({ mailed: true, ok: false, pending: true })
|
||||
expect(body.message).toMatch(/p…@example\.com/)
|
||||
// no factor stored, and the package's cookie was never set (it would turn valid once any secret is confirmed)
|
||||
expect(await storedSecret(victim.id)).toBeNull()
|
||||
const set = res.headers.getSetCookie().join('\n')
|
||||
expect(set).not.toMatch(/payload-totp=/)
|
||||
expect(set).toMatch(/payload-iapl-enrol=[^;]+;.*HttpOnly/)
|
||||
// still nothing but setup
|
||||
for (const p of ['/globals/site-integrations', '/users', '/form-submissions']) {
|
||||
expect([p, (await fetch(`${base}/api${p}`, { headers: { cookie: attacker } })).status]).toEqual([p, 403])
|
||||
}
|
||||
// the mail: to the account, with the link, without the secret
|
||||
expect(mails).toHaveLength(1)
|
||||
expect(mails[0].to).toBe(victim.email)
|
||||
expect(`${mails[0].html}${mails[0].text}`).not.toContain(ATTACKER_SECRET)
|
||||
expect(linkIn(mails[0])?.origin).toBe(base)
|
||||
})
|
||||
|
||||
test('the owner opens the attacker\'s link in THEIR browser: refused, the attacker\'s factor is not turned on', async () => {
|
||||
const victim = await newAccount()
|
||||
const attacker = await signIn(victim.email)
|
||||
await setup(attacker, ATTACKER_SECRET)
|
||||
const link = linkIn(mails[0])!
|
||||
// opening the link (a mail scanner, a preview) changes nothing
|
||||
const page = await fetch(link)
|
||||
expect(page.status).toBe(200)
|
||||
expect(await page.text()).toContain('<form method="post"')
|
||||
expect(await storedSecret(victim.id)).toBeNull()
|
||||
// the owner's browser has no enrolment cookie
|
||||
const ownerSession = await signIn(victim.email)
|
||||
const res = await confirm(link, ownerSession)
|
||||
expect(res.status).toBe(403)
|
||||
expect(await storedSecret(victim.id)).toBeNull()
|
||||
})
|
||||
|
||||
test('the owner\'s own set-up replaces a waiting one; the older link stops working', async () => {
|
||||
const victim = await newAccount()
|
||||
const attacker = await signIn(victim.email)
|
||||
const a = await setup(attacker, ATTACKER_SECRET)
|
||||
const attackerLink = linkIn(mails[0])!
|
||||
const attackerCookie = cookiesOf(a).find((c) => c.startsWith('payload-iapl-enrol='))!
|
||||
const owner = await signIn(victim.email)
|
||||
await setup(owner, OWNER_SECRET)
|
||||
expect(mails).toHaveLength(2)
|
||||
expect((await confirm(attackerLink, `${attacker}; ${attackerCookie}`)).status).toBe(400)
|
||||
expect(await storedSecret(victim.id)).toBeNull()
|
||||
})
|
||||
})
|
||||
|
||||
describe('confirming', () => {
|
||||
test('the link in the same browser turns it on, ends every session, signs nobody in; then password + code open the panel', async () => {
|
||||
const person = await newAccount()
|
||||
const session = await signIn(person.email)
|
||||
const res = await setup(session, OWNER_SECRET)
|
||||
const enrolCookie = cookiesOf(res).find((c) => c.startsWith('payload-iapl-enrol='))!
|
||||
const link = linkIn(mails[0])!
|
||||
mails.length = 0
|
||||
const done = await confirm(link, `${session}; ${enrolCookie}`)
|
||||
expect(done.status).toBe(200)
|
||||
expect(await done.text()).toContain('/admin/login')
|
||||
expect(done.headers.getSetCookie().join('\n')).not.toMatch(/payload-token=[^;]|payload-totp=[^;]/)
|
||||
expect(await storedSecret(person.id)).toBe(OWNER_SECRET)
|
||||
// the old password-only session is gone
|
||||
const me = (await (await fetch(`${base}/api/users/me`, { headers: { cookie: session } })).json()) as { user: unknown }
|
||||
expect(me.user).toBeNull()
|
||||
// the notice "turned on"
|
||||
expect(mails.map((m) => [m.to, m.subject])).toEqual([[person.email, expect.stringMatching(/two-step|dwuetapow/i)]])
|
||||
expect(`${mails[0].html}${mails[0].text}`).not.toContain(OWNER_SECRET)
|
||||
// sign in again: password, then the code
|
||||
const again = await signIn(person.email)
|
||||
const verify = await fetch(`${base}/api/verify-totp`, { body: JSON.stringify({ token: totp(OWNER_SECRET) }), headers: headers(again), method: 'POST' })
|
||||
expect(((await verify.json()) as { ok: boolean }).ok).toBe(true)
|
||||
const full = [again, ...cookiesOf(verify)].join('; ')
|
||||
expect((await fetch(`${base}/api/globals/site-settings`, { headers: { cookie: full } })).status).toBe(200)
|
||||
// single use
|
||||
expect((await confirm(link, `${session}; ${enrolCookie}`)).status).toBe(400)
|
||||
})
|
||||
|
||||
test('a wrong code sends nothing; an expired link and a POST from another origin are refused', async () => {
|
||||
const person = await newAccount()
|
||||
const session = await signIn(person.email)
|
||||
const wrong = await setup(session, OWNER_SECRET, '000000')
|
||||
expect(wrong.status).toBe(400)
|
||||
expect(mails).toHaveLength(0)
|
||||
|
||||
const res = await setup(session, OWNER_SECRET)
|
||||
const enrolCookie = cookiesOf(res).find((c) => c.startsWith('payload-iapl-enrol='))!
|
||||
const link = linkIn(mails[0])!
|
||||
expect((await confirm(link, `${session}; ${enrolCookie}`, 'https://evil.example')).status).toBe(403)
|
||||
const key = pendingEnrolmentKey('users', person.id)
|
||||
const kv = (payload as unknown as { kv: { get: (k: string) => Promise<Record<string, unknown>>; set: (k: string, v: object) => Promise<void> } }).kv
|
||||
await kv.set(key, { ...(await kv.get(key)), expiresAt: Date.now() - 1 })
|
||||
expect((await confirm(link, `${session}; ${enrolCookie}`)).status).toBe(400)
|
||||
expect(await storedSecret(person.id)).toBeNull()
|
||||
})
|
||||
|
||||
test('at most five confirmation mails per account and hour', async () => {
|
||||
const person = await newAccount()
|
||||
const session = await signIn(person.email)
|
||||
for (let i = 0; i < 5; i++) {expect((await setup(session, OWNER_SECRET)).status).toBe(202)}
|
||||
expect((await setup(session, OWNER_SECRET)).status).toBe(429)
|
||||
expect(mails).toHaveLength(5)
|
||||
})
|
||||
})
|
||||
|
||||
describe('mail that does not work', () => {
|
||||
test('the link goes to the server log; the person is told to ask an administrator; the admin confirms it', async () => {
|
||||
const person = await newAccount()
|
||||
const session = await signIn(person.email)
|
||||
mailBroken = true
|
||||
const warn = vi.spyOn(payload.logger, 'warn')
|
||||
const res = await setup(session, OWNER_SECRET)
|
||||
const body = (await res.json()) as { mailed?: boolean; message?: string }
|
||||
expect(body.mailed).toBe(false)
|
||||
expect(body.message).toMatch(/administrator/i)
|
||||
const logged = warn.mock.calls.map(([line]) => String(line)).find((line) => line.includes('/two-factor/confirm?u='))
|
||||
warn.mockRestore()
|
||||
expect(logged).toContain(base)
|
||||
expect(await storedSecret(person.id)).toBeNull()
|
||||
|
||||
// the person themselves cannot use the admin action; an admin with the code can
|
||||
expect((await fetch(`${base}/api/iapl/two-factor/confirm-pending`, { body: JSON.stringify({ userId: person.id }), headers: headers(session), method: 'POST' })).status).toBe(403)
|
||||
const adminSession = await signIn('[email protected]')
|
||||
const passwordOnly = await fetch(`${base}/api/iapl/two-factor/confirm-pending`, { body: JSON.stringify({ userId: person.id }), headers: headers(adminSession), method: 'POST' })
|
||||
expect(passwordOnly.status).toBe(403)
|
||||
const verify = await fetch(`${base}/api/verify-totp`, { body: JSON.stringify({ token: totp(ADMIN_SECRET) }), headers: headers(adminSession), method: 'POST' })
|
||||
const admin = [adminSession, ...cookiesOf(verify)].join('; ')
|
||||
mailBroken = false
|
||||
const ok = await fetch(`${base}/api/iapl/two-factor/confirm-pending`, { body: JSON.stringify({ userId: person.id }), headers: headers(admin), method: 'POST' })
|
||||
expect(ok.status).toBe(200)
|
||||
expect(await storedSecret(person.id)).toBe(OWNER_SECRET)
|
||||
// nothing waits any more
|
||||
expect((await fetch(`${base}/api/iapl/two-factor/confirm-pending`, { body: JSON.stringify({ userId: person.id }), headers: headers(admin), method: 'POST' })).status).toBe(404)
|
||||
// the notice names who confirmed it
|
||||
expect(mails.at(-1)?.text).toContain('[email protected]')
|
||||
})
|
||||
})
|
||||
|
||||
describe('notices and the other ways to set or remove a factor', () => {
|
||||
test('an administrator\'s reset sends the account a notice; REST and GraphQL cannot write a secret', async () => {
|
||||
const person = await newAccount()
|
||||
await payload.update({ id: person.id, collection: 'users' as never, data: { totpSecret: OWNER_SECRET } as never, overrideAccess: true })
|
||||
mails.length = 0
|
||||
const adminSession = await signIn('[email protected]')
|
||||
const verify = await fetch(`${base}/api/verify-totp`, { body: JSON.stringify({ token: totp(ADMIN_SECRET) }), headers: headers(adminSession), method: 'POST' })
|
||||
const admin = [adminSession, ...cookiesOf(verify)].join('; ')
|
||||
|
||||
// REST and GraphQL: the field cannot be written, not even by an admin
|
||||
await fetch(`${base}/api/users/${person.id}`, { body: JSON.stringify({ totpSecret: ATTACKER_SECRET }), headers: headers(admin), method: 'PATCH' })
|
||||
expect(await storedSecret(person.id)).toBe(OWNER_SECRET)
|
||||
const gql = await fetch(`${base}/api/graphql`, { body: JSON.stringify({ query: `mutation { updateUser(id: ${JSON.stringify(person.id)}, data: { totpSecret: "${ATTACKER_SECRET}" }) { id } }` }), headers: headers(admin), method: 'POST' })
|
||||
expect(gql.status).toBeLessThan(500)
|
||||
expect(await storedSecret(person.id)).toBe(OWNER_SECRET)
|
||||
|
||||
const reset = await fetch(`${base}/api/ipal/two-factor/reset`, { body: JSON.stringify({ userId: person.id }), headers: headers(admin), method: 'POST' })
|
||||
expect(reset.status).toBe(200)
|
||||
expect(await storedSecret(person.id)).toBeNull()
|
||||
const notice = mails.find((m) => m.to === person.email)
|
||||
expect(notice?.subject).toMatch(/removed|usunięta/i)
|
||||
expect(notice?.text).toContain('[email protected]')
|
||||
})
|
||||
})
|
||||
@@ -21,7 +21,7 @@ import {
|
||||
twoFactorSetupState,
|
||||
watchPayloadConfig,
|
||||
} from '../src/modules/security/totp/secondFactor.js'
|
||||
import { buildTwoFactorResetEndpoint, resolveRequireSetup, strictExempt } from '../src/modules/security/totp/setupRequired.js'
|
||||
import { buildTwoFactorResetEndpoint, resolveRequireSetup, stampSetupFrom, strictExempt } from '../src/modules/security/totp/setupRequired.js'
|
||||
import { buildVerifyLimit, clearVerifyLimits, verifyLimitKey } from '../src/modules/security/totp/verifyLimit.js'
|
||||
import { iapl } from '../src/plugin.js'
|
||||
import { withTotpParts } from './helpers.js'
|
||||
@@ -480,7 +480,7 @@ describe('iapl and the 2FA plugin', () => {
|
||||
...withTotpParts(c, o.collection),
|
||||
endpoints: [...(c.endpoints ?? []), ...['/verify-totp', '/setup-totp', '/remove-totp'].map((path) => ({ handler, method: 'post' as const, path }))],
|
||||
})
|
||||
const build = (twoFactor: Record<string, unknown> = {}) => iapl({ i18n, twoFactor: { issuer: 'A', plugin: withEndpoints as never, ...twoFactor } as never })({ collections: [], endpoints: [], secret: 'x' } as unknown as Config)
|
||||
const build = (twoFactor: Record<string, unknown> = {}) => iapl({ i18n, twoFactor: { confirmByEmail: false, issuer: 'A', plugin: withEndpoints as never, ...twoFactor } as never })({ collections: [], endpoints: [], secret: 'x' } as unknown as Config)
|
||||
const call = async (config: Config, path: string, headers: Record<string, string>, user: Record<string, unknown>) =>
|
||||
(await config.endpoints!.find((e) => e.path === path)!.handler({ headers: new Headers(headers), i18n: undefined, payload: { config, logger: { warn } }, url: 'https://site.example/api' + path, user: { id: 5, collection: 'users', ...user } } as never)).status
|
||||
const elsewhere = { host: 'site.example', origin: 'https://blog.site.example' }
|
||||
@@ -538,7 +538,7 @@ describe('iapl and the 2FA plugin', () => {
|
||||
expect(guard(on)).toMatchObject({ collection: 'users', requireSetup: true, setupWindowMs: 72 * 3_600_000 })
|
||||
const users = on.collections!.find((c) => c.slug === 'users')!
|
||||
expect(users.fields.some((f) => 'name' in f && f.name === 'totpSetupFrom')).toBe(true)
|
||||
expect(users.hooks?.beforeChange?.length).toBe(1)
|
||||
expect(users.hooks?.beforeChange?.filter((h) => h === stampSetupFrom)).toHaveLength(1)
|
||||
expect(on.endpoints!.some((e) => e.path === '/ipal/two-factor/reset')).toBe(true)
|
||||
expect(JSON.stringify(on.admin?.components?.beforeDashboard)).toContain('TwoFactorAlert')
|
||||
|
||||
@@ -551,7 +551,7 @@ describe('iapl and the 2FA plugin', () => {
|
||||
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(offUsers.hooks?.beforeChange?.includes(stampSetupFrom) ?? false).toBe(false) // no stamping while the mode is off
|
||||
expect(JSON.stringify(off.admin?.components?.beforeDashboard ?? [])).not.toContain('TwoFactorAlert')
|
||||
const guardOff = await iapl({ 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)
|
||||
|
||||
@@ -107,7 +107,8 @@ const makeConfig = () =>
|
||||
forms: {},
|
||||
i18n: { defaultLocale: 'pl', locales: [{ code: 'pl', label: 'Polski' }] },
|
||||
stats: true,
|
||||
twoFactor: { issuer: 'Example', plugin: payloadTotp },
|
||||
// the e-mail step of a first enrolment has its own suite (enrolmentConfirmHttp.test.ts); here the code alone turns it on
|
||||
twoFactor: { confirmByEmail: false, issuer: 'Example', plugin: payloadTotp },
|
||||
}),
|
||||
latePlugin,
|
||||
],
|
||||
|
||||
@@ -44,7 +44,8 @@ beforeAll(async () => {
|
||||
access: { authCollection: 'users' },
|
||||
forms: {},
|
||||
i18n: { defaultLocale: 'pl', locales: [{ code: 'pl', label: 'Polski' }] },
|
||||
twoFactor: { issuer: 'Example', plugin: payloadTotp as never },
|
||||
// the e-mail step of a first enrolment has its own suite (enrolmentConfirmHttp.test.ts); here the code alone turns it on
|
||||
twoFactor: { confirmByEmail: false, issuer: 'Example', plugin: payloadTotp as never },
|
||||
}),
|
||||
],
|
||||
secret: 'integration-test-secret-0123456789',
|
||||
|
||||
@@ -35,7 +35,8 @@ beforeAll(async () => {
|
||||
access: { authCollection: 'users' },
|
||||
forms: {},
|
||||
i18n: { defaultLocale: 'pl', locales: [{ code: 'pl', label: 'Polski' }] },
|
||||
twoFactor: { issuer: 'Example', plugin: payloadTotp },
|
||||
// the e-mail step of a first enrolment has its own suite (enrolmentConfirmHttp.test.ts); here the code alone turns it on
|
||||
twoFactor: { confirmByEmail: false, issuer: 'Example', plugin: payloadTotp },
|
||||
}),
|
||||
],
|
||||
secret: 'integration-test-secret-0123456789',
|
||||
|
||||
Reference in New Issue
Block a user