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
+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)
})
})