2FA setup required: an account without TOTP reaches only setup, within a 72 h window

twoFactor.requireSetup (on by default with 2FA): an account of the 2FA
collection that has not set TOTP up is refused by ipal-kit's second-factor
check on every collection, global and plugin endpoint; the setup screen and
/api/setup-totp are all it reaches. It has 72 hours from its creation or
from an admin's reset (field totpSetupFrom, stamped by a hook); after that
setup is refused too until an admin reopens it.

Accounts that existed before get their window at the first start after the
upgrade (backfill in onInit), so nobody is blocked when a site upgrades.

Admin side: status and reset / 'Reopen setup' button on the account page
(TwoFactorStatusField), POST /api/ipal/two-factor/reset, a dashboard notice
(TwoFactorAlert), a notice on the setup screen; texts in English and Polish.
ipal-doctor reports blocked accounts and a switched-off mode.

Overridable: requireSetup false, windowHours (false / 0 = none), exempt for
a service account, resetAccess; the per-entity second-factor opt-out applies.
API keys, seeds, bearer-token routes and sites with twoFactor false are not
affected.

HTTP tests (REST, GraphQL, first admin on an empty database) run on SQLite,
Postgres and MongoDB; a browser test on the reference site covers the first
admin, a new editor and the admin's reset. Docs, guide, skills, changelog.

Co-Authored-By: Claude Fable 5.2 <[email protected]>
This commit is contained in:
Radosław Smoliński
2026-11-24 18:46:32 +01:00
co-authored by Claude Fable 5.2
parent 45d52c4690
commit 2aaaaa115a
43 changed files with 1234 additions and 63 deletions
+17 -1
View File
@@ -382,7 +382,23 @@ 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(['node', 'pendingCookies', 'plugin', 'usersWithout2fa'])
expect(Object.keys(status).sort()).toEqual(['node', 'pendingCookies', 'plugin', 'usersSetupClosed', 'usersWithout2fa'])
expect(status.usersSetupClosed).toBeNull() // no setup window in this config
})
test('collectDoctorStatus counts the accounts whose 2FA setup window has passed', async () => {
const payload = {
config: {
admin: { user: 'users' },
collections: [{ slug: 'users', fields: [{ name: 'totpSecret' }, { name: 'hasTotp' }, { name: 'totpSetupFrom' }] }],
custom: { ipal: { twoFactor: { collection: 'users', requireSetup: true, setupWindowMs: 72 * 3_600_000 } } },
},
// all 5; with TOTP 3; without 2; of those past the window 1 (the query with `less_than`)
count: vi.fn(async ({ where }: { where?: object }) => {
const q = JSON.stringify(where ?? {})
return { totalDocs: !where ? 5 : q.includes('less_than') ? 1 : q.includes('not_equals') ? 3 : 2 }
}),
}
expect(await collectDoctorStatus(payload as never)).toMatchObject({ usersSetupClosed: 1, usersWithout2fa: 2 })
})
test('GET /api/ipal/doctor: 404 without a token, 401 with a wrong one, counts with the right one', async () => {
const endpoint = buildDoctorEndpoint()
+97 -2
View File
@@ -10,7 +10,17 @@ import type { I18nConfig } from '../src/modules/i18n/types.js'
import { adminOrSelfIn } from '../src/modules/access/access.js'
import { isAdmin, staffCollectionSlugs, userMeetsRole } from '../src/modules/access/predicates.js'
import { ensurePayloadGuarded, guardPayloadAccess, guardTotpEndpoint, requireSecondFactor, secondFactorPassed, watchPayloadConfig } from '../src/modules/security/totp/secondFactor.js'
import {
ensurePayloadGuarded,
guardPayloadAccess,
guardTotpEndpoint,
requireSecondFactor,
secondFactorPassed,
twoFactorSetupDeadline,
twoFactorSetupState,
watchPayloadConfig,
} from '../src/modules/security/totp/secondFactor.js'
import { resolveRequireSetup } from '../src/modules/security/totp/setupRequired.js'
import { buildVerifyLimit, clearVerifyLimits } from '../src/modules/security/totp/verifyLimit.js'
import { ipalKit } from '../src/plugin.js'
import { withTotpParts } from './helpers.js'
@@ -93,7 +103,7 @@ describe('secondFactorPassed', () => {
['no user', null, true],
['password and code (the totp strategy)', { _strategy: 'totp', collection: 'users', hasTotp: true }, true],
['API key', { _strategy: 'api-key', collection: 'users', hasTotp: true }, true],
['TOTP not set up yet', { _strategy: 'local-jwt', collection: 'users', hasTotp: false }, true],
['TOTP not set up yet, setup not required (requireSetup: false)', { _strategy: 'local-jwt', collection: 'users', hasTotp: false }, true],
['password only', { _strategy: 'local-jwt', collection: 'users', hasTotp: true }, false],
['a user object without the fields the check knows (fail closed)', { collection: 'users' }, false],
['an unknown strategy name (fail closed)', { _strategy: 'two-factor', collection: 'users', hasTotp: true }, false],
@@ -105,6 +115,65 @@ describe('secondFactorPassed', () => {
expect(secondFactorPassed({ payload, user })).toBe(expected)
})
describe('setup required (the default)', () => {
const HOUR = 3_600_000
const required = (extra: object = {}) => ({ config: { custom: { ipal: { twoFactor: { collection: 'users', requireSetup: true, setupWindowMs: 72 * HOUR, ...extra } } } } }) as never
const fresh = { _strategy: 'local-jwt', collection: 'users', email: '[email protected]', hasTotp: false, totpSetupFrom: new Date(Date.now() - HOUR).toISOString() }
const late = { ...fresh, totpSetupFrom: new Date(Date.now() - 73 * HOUR).toISOString() }
test('an account without TOTP is refused, inside the window and after it', () => {
expect(secondFactorPassed({ payload: required(), user: fresh })).toBe(false)
expect(secondFactorPassed({ payload: required(), user: late })).toBe(false)
expect(twoFactorSetupState({ payload: required(), user: fresh })).toBe('open')
expect(twoFactorSetupState({ payload: required(), user: late })).toBe('closed')
expect(twoFactorSetupDeadline({ payload: required(), user: fresh })!.getTime()).toBeGreaterThan(Date.now())
})
test('no window (windowHours: false / 0): never closed, still refused until set up', () => {
const noWindow = required({ setupWindowMs: 0 })
expect(twoFactorSetupState({ payload: noWindow, user: late })).toBe('open')
expect(twoFactorSetupDeadline({ payload: noWindow, user: late })).toBeNull()
expect(secondFactorPassed({ payload: noWindow, user: late })).toBe(false)
})
test('an account without a recorded start (before the first start after the upgrade) is open, not closed', () => {
const legacy = { _strategy: 'local-jwt', collection: 'users', hasTotp: false }
expect(twoFactorSetupState({ payload: required(), user: legacy })).toBe('open')
expect(secondFactorPassed({ payload: required(), user: legacy })).toBe(false)
})
test('the project exempts a service account on purpose', () => {
const exempt = required({ exempt: ({ user }: { user: { email?: string } }) => user.email === '[email protected]' })
const bot = { ...late, email: '[email protected]' }
expect(secondFactorPassed({ payload: exempt, user: bot })).toBe(true)
expect(twoFactorSetupState({ payload: exempt, user: bot })).toBe('exempt')
expect(secondFactorPassed({ payload: exempt, user: late })).toBe(false)
})
test('an API key passes whatever the setup state; the set-up and other-collection cases are unchanged', () => {
expect(secondFactorPassed({ payload: required(), user: { ...late, _strategy: 'api-key' } })).toBe(true)
expect(secondFactorPassed({ payload: required(), user: { _strategy: 'totp', collection: 'users', hasTotp: true } })).toBe(true)
expect(secondFactorPassed({ payload: required(), user: { _strategy: 'local-jwt', collection: 'customers' } })).toBe(true)
expect(twoFactorSetupState({ payload: required(), user: { collection: 'customers' } })).toBe('not-applicable')
expect(twoFactorSetupState({ payload: required(), user: { collection: 'users', hasTotp: true } })).toBe('set-up')
})
test('resolveRequireSetup: the option → what the guard reads', () => {
expect(resolveRequireSetup(undefined)).toEqual({ requireSetup: true, setupWindowMs: 72 * HOUR })
expect(resolveRequireSetup({ windowHours: 24 })).toEqual({ requireSetup: true, setupWindowMs: 24 * HOUR })
expect(resolveRequireSetup({ windowHours: false })).toEqual({ requireSetup: true, setupWindowMs: 0 })
expect(resolveRequireSetup({ windowHours: 0 })).toEqual({ requireSetup: true, setupWindowMs: 0 })
expect(resolveRequireSetup(false)).toEqual({ requireSetup: false, setupWindowMs: 0 })
})
test('the setup endpoint refuses an account whose window has passed', async () => {
const inner = () => Promise.resolve(Response.json({ ok: true }))
const endpoint = guardTotpEndpoint({ handler: inner as (req: never) => Promise<Response>, path: '/setup-totp' }, 'users')
expect((await endpoint.handler({ payload: required(), user: fresh } as never)).status).toBe(200)
expect((await endpoint.handler({ payload: required(), user: late } as never)).status).toBe(403)
})
})
test('2FA off: everyone passes', () => {
expect(secondFactorPassed({ payload: { config: {} } as never, user: { _strategy: 'local-jwt', collection: 'users', hasTotp: true } })).toBe(true)
})
@@ -292,6 +361,32 @@ describe('ipalKit and the 2FA plugin', () => {
expect(warnings.join('\n')).toMatch(/2FA covers "users" only\. Staff accounts of "partners"/)
})
test('setup required: on by default, with the field, the hook, the reset endpoint and the notices; every part can be changed', async () => {
const base = () => ({ collections: [], secret: 'x' }) as unknown as Config
const on = await ipalKit({ i18n, twoFactor: { issuer: 'A', plugin: fakeTotp as never } })(base())
const guard = (c: Config) => (c.custom as { ipal: { twoFactor: Record<string, unknown> } }).ipal.twoFactor
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(on.endpoints!.some((e) => e.path === '/ipal/two-factor/reset')).toBe(true)
expect(JSON.stringify(on.admin?.components?.beforeDashboard)).toContain('TwoFactorAlert')
const custom = await ipalKit({ i18n, twoFactor: { issuer: 'A', plugin: fakeTotp as never, requireSetup: { windowHours: 24 } } })(base())
expect(guard(custom).setupWindowMs).toBe(24 * 3_600_000)
const off = await ipalKit({ i18n, twoFactor: { issuer: 'A', plugin: fakeTotp as never, requireSetup: false } })(base())
expect(guard(off)).toMatchObject({ requireSetup: false })
expect(off.collections!.find((c) => c.slug === 'users')!.fields.some((f) => 'name' in f && f.name === 'totpSetupFrom')).toBe(false)
expect(JSON.stringify(off.admin?.components?.beforeDashboard ?? [])).not.toContain('TwoFactorAlert')
expect(off.endpoints!.some((e) => e.path === '/ipal/two-factor/reset')).toBe(true) // an admin can still reset a lost phone
// 2FA off: nothing of this exists
const none = await ipalKit({ i18n, twoFactor: false })(base())
expect(none.endpoints!.some((e) => e.path === '/ipal/two-factor/reset')).toBe(false)
expect(none.collections!.find((c) => c.slug === 'users')!.fields.some((f) => 'name' in f && f.name === 'totpSetupFrom')).toBe(false)
})
test('twoFactor: false — no guard, a password is enough (as documented)', async () => {
const config = await ipalKit({ access: { authCollection: 'users' }, i18n, twoFactor: false })({ collections: [], secret: 'x' } as unknown as Config)
const payload = payloadOf(config)
+91 -8
View File
@@ -283,14 +283,6 @@ describe('what must keep working', () => {
expect((out.data?.SiteIntegration as { smtpPassword: string }).smtpPassword).toBe('S3CRET')
})
test('an account that has not set TOTP up yet can still do so', async () => {
// The package lets such an account through until TOTP is set up (the setup screen needs it).
expect((await api('/users/me', sessions.newcomer)).status).toBe(200)
const setup = await api('/setup-totp', sessions.newcomer, { body: JSON.stringify({ secret: TOTP_SECRET, token: totp(TOTP_SECRET) }), method: 'POST' })
expect(setup.status).toBe(200)
expect(((await setup.json()) as { ok: boolean }).ok).toBe(true)
})
test('anonymous visitors still read the public globals and forms', async () => {
for (const p of ['/globals/site-settings', '/globals/notifications', '/globals/cookie-settings', '/forms']) {
expect([p, (await api(p, sessions.anonymous)).status]).toEqual([p, 200])
@@ -475,6 +467,97 @@ describe('the code cannot be guessed: verify attempts are limited per account',
})
})
// Uses the account `[email protected]` (admin role, TOTP never set up). Order matters inside this block.
describe('2FA setup required: an account without TOTP reaches nothing but setup', () => {
const NEW_SECRET = 'MFRGGZDFMZTWQ2LK'
const idOf = async (email: string) => (await payload.find({ collection: 'users' as never, where: { email: { equals: email } } })).docs[0].id
const setup = (session: Session) => api('/setup-totp', session, { body: JSON.stringify({ secret: NEW_SECRET, token: totp(NEW_SECRET) }), method: 'POST' })
test('REST: every collection and global is refused, for reading and for writing', async () => {
const open: string[] = []
for (const [kind, slugs] of [['collection', [...pluginCollections, 'pages']], ['global', pluginGlobals]] as const) {
for (const slug of slugs) {
if ((await readStatus(kind, slug, sessions.newcomer)) !== 403) {open.push(`read ${kind} ${slug}`)}
if ((await writeStatus(kind, slug, sessions.newcomer)) !== 403) {open.push(`write ${kind} ${slug}`)}
}
}
expect(open).toEqual([])
const integrations = await api('/globals/site-integrations', sessions.newcomer)
expect(await integrations.text()).not.toContain('S3CRET')
})
test('GraphQL and the staff endpoints refuse too', async () => {
for (const query of ['{ SiteIntegration { smtpPassword } }', '{ FormSubmissions { totalDocs } }', '{ Users { totalDocs } }', 'mutation { updateSiteSetting(data: { siteName: "x" }) { siteName } }']) {
const out = await gql(sessions.newcomer, query)
expect(out.errors?.length, `${query} → ${JSON.stringify(out)}`).toBeGreaterThan(0)
expect(JSON.stringify(out)).not.toContain('S3CRET')
}
expect((await api('/ipal/test-email', sessions.newcomer, { body: '{}', method: 'POST' })).status).toBe(403)
expect((await api('/ipal/cookie-scan', sessions.newcomer)).status).toBe(403)
expect((await api('/ipal/two-factor/reset', sessions.newcomer, { body: JSON.stringify({ userId: await idOf('[email protected]') }), method: 'POST' })).status).toBe(403)
})
test('the window start is stamped at creation and cannot be written through the API', async () => {
const id = await idOf('[email protected]')
const doc = (await payload.findByID({ id, collection: 'users' as never })) as unknown as { totpSetupFrom?: string }
expect(Date.now() - new Date(doc.totpSetupFrom!).getTime()).toBeLessThan(120_000)
const patch = await api(`/users/${id}`, sessions.verified, { body: JSON.stringify({ totpSetupFrom: '2030-01-01T00:00:00.000Z' }), method: 'PATCH' })
expect(patch.status).toBe(200)
const after = (await payload.findByID({ id, collection: 'users' as never })) as unknown as { totpSetupFrom?: string }
expect(after.totpSetupFrom).toBe(doc.totpSetupFrom)
})
test('after the window the account is blocked: setup refused with a message, in the admin language', async () => {
const id = await idOf('[email protected]')
await payload.update({ id, collection: 'users' as never, data: { totpSetupFrom: new Date(Date.now() - 73 * 3_600_000).toISOString() } as never })
const res = await setup(sessions.newcomer)
expect(res.status).toBe(403)
expect(((await res.json()) as { message: string }).message).toMatch(/time to set up two-step verification has passed/i)
const pl = await api('/setup-totp', { headers: { ...sessions.newcomer.headers, 'accept-language': 'pl' } }, { body: JSON.stringify({ secret: NEW_SECRET, token: totp(NEW_SECRET) }), method: 'POST' })
expect(((await pl.json()) as { message: string }).message).toMatch(/Czas na ustawienie weryfikacji dwuetapowej minął/)
expect((await api('/globals/site-integrations', sessions.newcomer)).status).toBe(403)
})
test('only a fully logged-in admin reopens setup', async () => {
const userId = await idOf('[email protected]')
const reset = (session: Session) => api('/ipal/two-factor/reset', session, { body: JSON.stringify({ userId }), method: 'POST' })
for (const session of [sessions.anonymous, sessions.customer, sessions.member, sessions.passwordOnly, sessions.newcomer]) {
expect((await reset(session)).status).toBe(403)
}
expect((await setup(sessions.newcomer)).status).toBe(403) // still blocked
const ok = await reset(sessions.verified)
expect(ok.status).toBe(200)
const doc = (await payload.findByID({ id: userId, collection: 'users' as never })) as unknown as { totpSetupFrom: string }
expect(Date.now() - new Date(doc.totpSetupFrom).getTime()).toBeLessThan(120_000)
})
test('inside the window it sets TOTP up, and then everything its role allows opens', async () => {
const res = await setup(sessions.newcomer)
expect(res.status).toBe(200)
expect(((await res.json()) as { ok: boolean }).ok).toBe(true)
const full: Session = { headers: { ...sessions.newcomer.headers, cookie: cookiesOf(res).join('; ') } }
expect((await api('/globals/site-integrations', full)).status).toBe(200)
expect((await api('/form-submissions', full)).status).toBe(200)
expect((await api('/users/me', full)).status).toBe(200)
// without the 2FA cookie the same token is a password-only session again
expect((await api('/globals/site-integrations', sessions.newcomer)).status).toBe(403)
})
test('accounts from before the mode get their window when the site starts', async () => {
const { backfillSetupFrom } = await import('../src/modules/security/totp/setupRequired.js')
const legacy = await payload.create({ collection: 'users' as never, data: { email: '[email protected]', password: PASSWORD, roles: ['editor'] } as never })
await payload.db.updateOne({ id: legacy.id, collection: 'users' as never, data: { totpSetupFrom: null } as never })
expect(await backfillSetupFrom(payload, 'users')).toBe(1)
const doc = (await payload.findByID({ id: legacy.id, collection: 'users' as never })) as unknown as { totpSetupFrom: string }
expect(Date.now() - new Date(doc.totpSetupFrom).getTime()).toBeLessThan(120_000)
expect(await backfillSetupFrom(payload, 'users')).toBe(0)
// accounts that have TOTP are left alone
const admin = (await payload.findByID({ id: await idOf('[email protected]'), collection: 'users' as never })) as unknown as { totpSetupFrom?: string }
expect(admin.totpSetupFrom).toBeTruthy()
})
})
// Last: it replaces the running config.
describe('dev hot reload', () => {
test('a freshly built config is guarded again, also what a later plugin added', async () => {
+91
View File
@@ -0,0 +1,91 @@
/**
* A fresh site with "2FA setup required": the first admin is created on Payload's "Create first user" screen
* (POST /api/users/first-register), reaches nothing until it has set TOTP up, and everything afterwards.
* Real HTTP, see securityHttp.test.ts.
*/
import type { Payload } from 'payload'
import { payloadTotp } from '@clocklimited/payload-2fa'
import { lexicalEditor } from '@payloadcms/richtext-lexical'
import os from 'os'
import path from 'path'
import { getPayload } from 'payload'
import { afterAll, beforeAll, expect, test, vi } from 'vitest'
import { ipalKit } 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 SECRET = 'JBSWY3DPEHPK3PXP'
let server: TestServer
let payload: Payload
beforeAll(async () => {
const config = buildTestConfig({
collections: [{ slug: 'media', fields: [], upload: { staticDir: path.join(os.tmpdir(), 'ipal-test-media') } }],
db: testDatabase('sechttp_first'),
editor: lexicalEditor(),
plugins: [
ipalKit({
access: { authCollection: 'users' },
forms: {},
i18n: { defaultLocale: 'pl', locales: [{ code: 'pl', label: 'Polski' }] },
twoFactor: { issuer: 'Example', plugin: payloadTotp },
}),
],
secret: 'integration-test-secret-0123456789',
telemetry: false,
})
payload = await getPayload({ config })
server = await startPayloadServer(config)
}, 120_000)
afterAll(async () => {
await server?.close()
await payload?.destroy?.()
})
const json = { 'content-type': 'application/json' }
test('the first admin: created, locked until TOTP is set up, then in', async () => {
const register = await fetch(`${server.url}/api/users/first-register`, {
body: JSON.stringify({ email: '[email protected]', password: 'a-long-test-password-1' }),
headers: json,
method: 'POST',
})
expect(register.status).toBe(200)
const body = (await register.json()) as { token?: string; user: { roles: string[] } }
expect(body.user.roles).toEqual(['admin'])
const cookie = cookiesOf(register).join('; ')
expect(cookie).toContain('payload-token')
for (const p of ['/globals/site-integrations', '/users', '/form-submissions', '/globals/site-settings']) {
expect([p, (await fetch(`${server.url}/api${p}`, { headers: { cookie } })).status]).toEqual([p, 403])
}
const setup = await fetch(`${server.url}/api/setup-totp`, { body: JSON.stringify({ secret: SECRET, token: totp(SECRET) }), headers: { ...json, cookie }, method: 'POST' })
expect(((await setup.json()) as { ok: boolean }).ok).toBe(true)
const full = [cookie, ...cookiesOf(setup)].join('; ')
for (const p of ['/globals/site-integrations', '/users', '/form-submissions']) {
expect([p, (await fetch(`${server.url}/api${p}`, { headers: { cookie: full } })).status]).toEqual([p, 200])
}
// the admin creates an editor: it gets its own setup window
const created = await fetch(`${server.url}/api/users`, {
body: JSON.stringify({ email: '[email protected]', password: 'a-long-test-password-2', roles: ['editor'] }),
headers: { ...json, cookie: full },
method: 'POST',
})
expect(created.status).toBe(201)
const editor = (await payload.find({ collection: 'users' as never, where: { email: { equals: '[email protected]' } } })).docs[0] as unknown as { totpSetupFrom?: string }
expect(editor.totpSetupFrom).toBeTruthy()
})
test('seeds and scripts are not affected: the Local API still reads and writes', async () => {
await payload.updateGlobal({ slug: 'site-settings' as never, data: { siteName: 'Seeded' } as never })
expect(((await payload.findGlobal({ slug: 'site-settings' as never })) as { siteName: string }).siteName).toBe('Seeded')
})