Files
ipal-kit/test/securityHttpFirstAdmin.test.ts
T
Radosław SmolińskiandClaude Fable 5.2 0a4f001797 IAPL rename, scripted: preferred names in src, bin, scripts, services, tests; bin files and skill folders moved
Replaced by an explicit list of forms only (ten exported names, runtime env names, project file
names and marks, commands, skill names, the log prefix, the brand in prose). Package name, import
paths, routes, CSS tokens, data attributes, custom keys, context flags, the cookie and kv keys are
not touched. package.json keeps the five old bin names beside the five new ones.
The old names stop working in this commit and come back as aliases in the next; docs follow.

Co-Authored-By: Claude Fable 5.2 <[email protected]>
2026-11-25 17:24:21 +01:00

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 { iapl } 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: [
iapl({
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')
})