2FA setup required: the window of existing accounts starts once, at the first start after the upgrade

Owner's decision: for accounts that exist before the upgrade the 72 hours
count from the first start after it. The code already stamped them then; this
adds the tests that the moment is written once per account (a restart, two
instances starting at once, edits and logins do not move it; 71 h after it setup
is open, 73 h after it the account is blocked) and says so in the docs.

After the rebase on 1.16.5: tests that the setup-required notice and the stale
import-map notice both stand above the screen and never replace the code form,
and that requireSetup, safeBack and guard switch independently.

Co-Authored-By: Claude Fable 5.2 <[email protected]>
This commit is contained in:
Radosław Smoliński
2026-11-24 18:56:07 +01:00
co-authored by Claude Fable 5.2
parent 5d44ac3135
commit 9d2ab43438
7 changed files with 191 additions and 6 deletions
+6 -1
View File
@@ -20,6 +20,8 @@ once there are more than 20.
account that never set 2FA up can be taken over by someone who learned its password.
- **Accounts that already exist** get their 72 hours from the **first start after the upgrade** (not from their
creation date), so nobody is blocked at the moment of the upgrade. The server log names how many there are.
That moment is written on each account once: later restarts, redeploys and further instances do not move it,
nor does editing the account. On Postgres / SQLite it is the first start with the migration applied.
### Added
- On every account in the panel: **Two-step verification** (sidebar) — set up / open until a date / blocked — and
@@ -40,7 +42,10 @@ once there are more than 20.
### Requires project changes
- **Before upgrading a live site:** `pnpm exec ipal-doctor --url <site>` → accounts without 2FA. Each sets 2FA up
now, or is removed. At least one administrator must have 2FA set up, or nobody can reopen setup from the panel.
- `pnpm payload generate:importmap` (commit `importMap.js`) and `pnpm payload generate:types`.
- `pnpm payload generate:importmap` (commit `importMap.js`) and `pnpm payload generate:types`, in the same
deploy as the upgrade (as for 1.16.5: a stale import map leaves the 2FA screens without a code form).
- **Plan the upgrade with the owner:** the 72 hours of every existing account without 2FA start at the deploy,
once. Deploy when those people can act within three days (not before a holiday), or have them set 2FA up first.
- **Postgres / SQLite:** `pnpm payload migrate:create` — the 2FA collection gets the column `totpSetupFrom`.
MongoDB: nothing.
- **An integration that logs in with a password and has no TOTP** stops working: give it an API key (passes as
+6 -2
View File
@@ -380,12 +380,14 @@ gets `403` from the same addresses and from `POST /api/setup-totp`. The Coolify
strips `back`, can keep them (`twoFactor.safeBack: false` turns the plugin's check off).
2. `pnpm ipal:skills`.
**→ the release after that — 2FA setup required (PROGRAMISTA §6, item 66; security.md "Setup required") — required
**→ the release with `twoFactor.requireSetup` — 2FA setup required (CHANGELOG "Unreleased — 2FA setup required"; PROGRAMISTA §6, item 68; security.md "Setup required") — required
with 2FA on:**
1. **Before upgrading a live site:** `pnpm exec ipal-doctor --url <site>` (doctor token) → accounts without 2FA.
Tell the owner: from the upgrade on, such an account can only set 2FA up, and has 72 hours for it; after that
an administrator must reopen setup on the account's page. Have them set it up now, or remove unused accounts.
Make sure at least one administrator has 2FA set up — otherwise nobody can reopen setup from the panel.
The 72 hours of existing accounts start at the first start after the deploy and are counted once (restarts
and redeploys do not extend them): agree the deploy day with the owner.
2. Update the package, `pnpm install`, `pnpm ipal:skills`, `pnpm payload generate:types`,
**`pnpm payload generate:importmap`** (new: `TwoFactorStatusField`, `TwoFactorAlert`; commit `importMap.js`).
3. Postgres/SQLite: `pnpm payload migrate:create` (adds `totpSetupFrom` to the 2FA collection), commit. MongoDB: nothing.
@@ -393,7 +395,9 @@ with 2FA on:**
`twoFactor.requireSetup: { exempt: ({ user }) => user.email === '…' }`. `grep -rn "overrideAccess: false" src`:
a `user` fetched by id is refused for every account now — take it from `payload.auth({ headers })`.
5. `rm -rf .next`, build, redeploy on Coolify. Read the first lines of the log: `[ipal] 2FA: N existing account(s)
without two-step verification…` — pass that number to the owner.
without two-step verification…` — pass that number to the owner. The line appears on that first start only.
Postgres/SQLite: the migration from step 3 must run in the same deploy; without it the log says
`could not start the setup window` and the window starts at the first start that has it.
**Check:** create a throwaway account → its token gets `403` from `/api/users/me`; in the panel it lands on the
setup screen with "Set up two-step verification by …"; after the code it is in. As an administrator open that
account → "Two-step verification: Set up." and the reset button; delete the account.
+8
View File
@@ -460,6 +460,14 @@ now to set it up…`. From that moment they can only set TOTP up; after 72 hours
administrator reopens setup. **Before upgrading a live site, run `pnpm exec ipal-doctor --url <site>`** (accounts
without 2FA) and have those accounts set TOTP up, or remove the ones nobody uses.
That starting moment is **written once**, on each such account (`totpSetupFrom`), by the start that first finds
the account without one. Later starts, redeploys and further instances find nothing left to do (the log line
appears on that first start only), and editing the account or logging in does not move it — so a redeploy never
hands out another 72 hours. Only an administrator's reset / "Reopen setup" opens a new window. An existing
account that **has** TOTP gets no start; if its TOTP is removed later, its window starts then. On Postgres /
SQLite "the first start" means the first start **with the migration applied**: before that there is no column
to write to, the log warns, and those accounts have no time limit yet.
```ts
twoFactor: {
issuer: 'Company Name',
@@ -380,12 +380,14 @@ gets `403` from the same addresses and from `POST /api/setup-totp`. The Coolify
strips `back`, can keep them (`twoFactor.safeBack: false` turns the plugin's check off).
2. `pnpm ipal:skills`.
**→ the release after that — 2FA setup required (PROGRAMISTA §6, item 66; security.md "Setup required") — required
**→ the release with `twoFactor.requireSetup` — 2FA setup required (CHANGELOG "Unreleased — 2FA setup required"; PROGRAMISTA §6, item 68; security.md "Setup required") — required
with 2FA on:**
1. **Before upgrading a live site:** `pnpm exec ipal-doctor --url <site>` (doctor token) → accounts without 2FA.
Tell the owner: from the upgrade on, such an account can only set 2FA up, and has 72 hours for it; after that
an administrator must reopen setup on the account's page. Have them set it up now, or remove unused accounts.
Make sure at least one administrator has 2FA set up — otherwise nobody can reopen setup from the panel.
The 72 hours of existing accounts start at the first start after the deploy and are counted once (restarts
and redeploys do not extend them): agree the deploy day with the owner.
2. Update the package, `pnpm install`, `pnpm ipal:skills`, `pnpm payload generate:types`,
**`pnpm payload generate:importmap`** (new: `TwoFactorStatusField`, `TwoFactorAlert`; commit `importMap.js`).
3. Postgres/SQLite: `pnpm payload migrate:create` (adds `totpSetupFrom` to the 2FA collection), commit. MongoDB: nothing.
@@ -393,7 +395,9 @@ with 2FA on:**
`twoFactor.requireSetup: { exempt: ({ user }) => user.email === '…' }`. `grep -rn "overrideAccess: false" src`:
a `user` fetched by id is refused for every account now — take it from `payload.auth({ headers })`.
5. `rm -rf .next`, build, redeploy on Coolify. Read the first lines of the log: `[ipal] 2FA: N existing account(s)
without two-step verification…` — pass that number to the owner.
without two-step verification…` — pass that number to the owner. The line appears on that first start only.
Postgres/SQLite: the migration from step 3 must run in the same deploy; without it the log says
`could not start the setup window` and the window starts at the first start that has it.
**Check:** create a throwaway account → its token gets `403` from `/api/users/me`; in the panel it lands on the
setup screen with "Set up two-step verification by …"; after the code it is in. As an administrator open that
account → "Two-step verification: Set up." and the reset button; delete the account.
+29
View File
@@ -306,6 +306,35 @@ describe('SafeTotpView', () => {
})
})
// "Setup required" (requireSetup), the back-link check (safeBack) and ipal-kit's own check (guard) are separate
// switches: each combination builds, and each part is on exactly when its own switch says so.
describe('requireSetup x safeBack x guard', () => {
const combos = [undefined, false].flatMap((requireSetup) => [undefined, false].flatMap((safeBack) => [undefined, false].map((guard) => ({ guard, requireSetup, safeBack }))))
test.each(combos)('requireSetup: $requireSetup, safeBack: $safeBack, guard: $guard', async (options) => {
const config = await ipalKit({ access: { authCollection: 'users' }, i18n, twoFactor: { issuer: 'E', plugin: payloadTotpBeta7, ...options } as never })({ collections: [], secret: 'x' } as unknown as Config)
const views = Object.values(config.admin?.components?.views ?? {}) as { Component: { path?: string } | string; path: string }[]
const totpViews = views.filter((v) => /(?:setup|verify)-totp$/.test(v.path))
expect(totpViews).toHaveLength(4)
// the back-link check follows safeBack alone
const wrapped = totpViews.filter((v) => typeof v.Component === 'object' && v.Component.path === '@intecion/ipal-kit/admin#SafeTotpView').length
expect(wrapped).toBe(options.safeBack === false ? 0 : 4)
// setup required needs ipal-kit's own check; with either off there is no window field and no notice
const setupOn = options.requireSetup !== false && options.guard !== false
const users = config.collections?.find((c) => c.slug === 'users')
expect(Boolean(users?.fields.some((f) => 'name' in f && f.name === 'totpSetupFrom'))).toBe(setupOn)
// the administrator's reset (a lost phone) comes with ipal-kit's own check, also when setup is not required
expect(Boolean(config.endpoints?.some((e) => e.path === '/ipal/two-factor/reset'))).toBe(options.guard !== false)
const provider = JSON.stringify(config.admin?.components?.providers ?? [])
expect(provider.includes('"requireSetup":true')).toBe(setupOn)
expect(provider).toContain('TotpRedirectProvider')
const guardConfig = (config.custom as { ipal?: { twoFactor?: { requireSetup?: boolean } } } | undefined)?.ipal?.twoFactor
expect(Boolean(guardConfig)).toBe(options.guard !== false)
if (guardConfig) {expect(Boolean(guardConfig.requireSetup)).toBe(setupOn)}
})
})
describe('a 2FA factory that hands back the same view objects on every call', () => {
const views = {
SetupTOTP: { Component: { path: 'pkg/rsc#TOTPSetup' }, path: 'setup-totp' },
+85
View File
@@ -559,6 +559,91 @@ describe('2FA setup required: an account without TOTP reaches nothing but setup'
// Last: it replaces the running config.
// The owner's decision (2026-11-24): for accounts that exist before the upgrade, the 72 hours count from the first
// start after the upgrade. That moment is written on each account once: later starts, a second instance starting,
// and edits of the account leave it alone — otherwise every redeploy would hand out another 72 hours.
describe('2FA setup required: accounts from before the upgrade', () => {
const NEW_SECRET = 'MFRGGZDFMZTWQ2LK'
const HOUR = 3_600_000
const backfill = async () => (await import('../src/modules/security/totp/setupRequired.js')).backfillSetupFrom(payload, 'users')
const stampOf = async (id: number | string) => ((await payload.findByID({ id, collection: 'users' as never })) as unknown as { totpSetupFrom?: null | string }).totpSetupFrom
/** An account as the previous version left it: no TOTP, no window start. */
const legacy = async (email: string) => {
const doc = await payload.create({ collection: 'users' as never, data: { email, password: PASSWORD, roles: ['editor'] } as never })
await payload.db.updateOne({ id: doc.id, collection: 'users' as never, data: { totpSetupFrom: null } as never })
expect(await stampOf(doc.id)).toBeFalsy()
return doc.id
}
const sessionOf = async (email: string): Promise<Session> => ({ headers: { authorization: `JWT ${(await login('users', email)).token}` } })
const setup = (session: Session) => api('/setup-totp', session, { body: JSON.stringify({ secret: NEW_SECRET, token: totp(NEW_SECRET) }), method: 'POST' })
test('the first start stamps them with that moment; a restart does not move it', async () => {
const [a, b] = [await legacy('[email protected]'), await legacy('[email protected]')]
const startedAt = Date.now()
expect(await backfill()).toBe(2)
const first = [await stampOf(a), await stampOf(b)]
for (const stamp of first) {
expect(new Date(stamp!).getTime()).toBeGreaterThanOrEqual(startedAt - 1000)
expect(new Date(stamp!).getTime()).toBeLessThanOrEqual(Date.now() + 1000)
}
await new Promise((resolve) => setTimeout(resolve, 1100)) // a later start is at another time
expect(await backfill()).toBe(0)
expect(await backfill()).toBe(0)
expect([await stampOf(a), await stampOf(b)]).toEqual(first)
})
test('two instances starting at once: each account is stamped, and the stamp stays', async () => {
const id = await legacy('[email protected]')
const counts = await Promise.all([backfill(), backfill()])
expect(Math.max(...counts)).toBe(1)
const stamp = await stampOf(id)
expect(stamp).toBeTruthy()
await new Promise((resolve) => setTimeout(resolve, 1100))
expect(await backfill()).toBe(0)
expect(await stampOf(id)).toBe(stamp)
})
test('editing the account, or logging in, does not move the start', async () => {
const id = (await payload.find({ collection: 'users' as never, where: { email: { equals: '[email protected]' } } })).docs[0].id
const stamp = await stampOf(id)
await payload.update({ id, collection: 'users' as never, data: { password: `${PASSWORD}-2`, roles: ['admin'] } as never })
await payload.update({ id, collection: 'users' as never, data: { password: PASSWORD, roles: ['editor'] } as never })
await sessionOf('[email protected]')
expect(await stampOf(id)).toBe(stamp)
})
test('71 hours after the first start, restarts in between: setup still open; 73 hours after: blocked', async () => {
const [a, b] = await Promise.all(['[email protected]', '[email protected]'].map(async (email) => (await payload.find({ collection: 'users' as never, where: { email: { equals: email } } })).docs[0].id))
// as if the first start after the upgrade had been 71 h / 73 h ago
await payload.db.updateOne({ id: a, collection: 'users' as never, data: { totpSetupFrom: new Date(Date.now() - 71 * HOUR).toISOString() } as never })
await payload.db.updateOne({ id: b, collection: 'users' as never, data: { totpSetupFrom: new Date(Date.now() - 73 * HOUR).toISOString() } as never })
const before = [await stampOf(a), await stampOf(b)]
expect(await backfill()).toBe(0) // a restart today
expect([await stampOf(a), await stampOf(b)]).toEqual(before)
const late = await sessionOf('[email protected]')
expect((await setup(late)).status).toBe(403)
expect((await api('/globals/site-integrations', late)).status).toBe(403)
const inTime = await sessionOf('[email protected]')
expect((await api('/globals/site-integrations', inTime)).status).toBe(403) // nothing but setup
const done = await setup(inTime)
expect(done.status).toBe(200)
expect(((await done.json()) as { ok: boolean }).ok).toBe(true)
})
test('an account that has TOTP is not stamped; one created after the upgrade counts from its creation', async () => {
const withTotp = await payload.create({ collection: 'users' as never, data: { email: '[email protected]', password: PASSWORD, roles: ['editor'], totpSecret: TOTP_SECRET } as never })
await payload.db.updateOne({ id: withTotp.id, collection: 'users' as never, data: { totpSetupFrom: null } as never })
expect(await backfill()).toBe(0)
expect(await stampOf(withTotp.id)).toBeFalsy()
const created = Date.now()
const fresh = await payload.create({ collection: 'users' as never, data: { email: '[email protected]', password: PASSWORD, roles: ['editor'] } as never })
expect(Math.abs(new Date((await stampOf(fresh.id))!).getTime() - created)).toBeLessThan(60_000)
expect(await backfill()).toBe(0)
})
})
describe('dev hot reload', () => {
test('a freshly built config is guarded again, also what a later plugin added', async () => {
// What Payload's reload() does to the instance: a newly built and sanitized config, no onInit.
+51 -1
View File
@@ -12,7 +12,7 @@ const state = { language: 'en', pathname: '/admin/verify-totp', user: { _strateg
vi.mock('@payloadcms/ui', () => ({
useAuth: () => ({ user: state.user }),
useConfig: () => ({ config: { admin: { routes: {} }, routes: { admin: '/admin' } } }),
useTranslation: () => ({ i18n: { language: state.language } }),
useTranslation: () => ({ i18n: { language: state.language }, t: (key: string, vars?: Record<string, unknown>) => `${key}${vars ? JSON.stringify(vars) : ''}` }),
}))
vi.mock('next/navigation.js', () => ({ usePathname: () => state.pathname, useRouter: () => ({ replace: () => undefined }) }))
@@ -65,3 +65,53 @@ describe('TotpRedirectProvider with staleImportMap', () => {
expect(render({ staleImportMap: true })).toBe('')
})
})
// With "2FA setup required" the setup screen carries its own notice (until when, or that the time has passed).
// Neither notice, alone or together, may take the code form off the page.
describe('TotpRedirectProvider: the setup-required notice and the stale-map notice together', () => {
const HOUR = 3_600_000
const onSetup = (totpSetupFrom: string) => Object.assign(state, { language: 'en', pathname: '/admin/setup-totp', user: { _strategy: 'local-jwt', hasTotp: false, totpSetupFrom } })
test('inside the window: the deadline notice, and the form', () => {
onSetup(new Date(Date.now() - HOUR).toISOString())
const html = render({ requireSetup: true, setupWindowHours: 72 })
expect(html).toContain('id="ipal-two-factor-notice"')
expect(html).toContain('role="status"')
expect(html).toContain('twoFactorSetupDeadline')
expect(html).toContain(FORM)
})
test('after the window: the "time has passed" notice as an alert, and the screen still rendered', () => {
onSetup(new Date(Date.now() - 73 * HOUR).toISOString())
const html = render({ requireSetup: true, setupWindowHours: 72 })
expect(html).toContain('twoFactorSetupClosed')
expect(html).toContain('role="alert"')
expect(html).toContain(FORM)
})
test('both notices at once, inside and after the window: both shown, the form below them', () => {
for (const hours of [1, 73]) {
onSetup(new Date(Date.now() - hours * HOUR).toISOString())
const html = render({ requireSetup: true, setupWindowHours: 72, staleImportMap: true })
expect(html).toContain('id="ipal-two-factor-notice"')
expect(html).toContain('may not be available')
expect(html).toContain(FORM)
expect(html.indexOf('ipal-two-factor-notice')).toBeLessThan(html.indexOf('code-form'))
expect(html.indexOf('may not be available')).toBeLessThan(html.indexOf('code-form'))
}
})
test('no window (windowHours: false): the plain "setup required" notice', () => {
onSetup(new Date(Date.now() - 500 * HOUR).toISOString())
const html = render({ requireSetup: true, setupWindowHours: 0 })
expect(html).toContain('twoFactorSetupRequired')
expect(html).toContain(FORM)
})
test('requireSetup off: no setup notice; the verify screen never shows it', () => {
onSetup(new Date(Date.now() - 73 * HOUR).toISOString())
expect(render({ requireSetup: false, setupWindowHours: 72 })).toBe(FORM)
Object.assign(state, { pathname: '/admin/verify-totp', user: { _strategy: 'local-jwt', hasTotp: true } })
expect(render({ requireSetup: true, setupWindowHours: 72 })).toBe(FORM)
})
})