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]>
92 lines
3.9 KiB
TypeScript
92 lines
3.9 KiB
TypeScript
/**
|
|
* 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')
|
|
})
|