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

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