Files
ipal-kit/test/securityHttp.test.ts
T
Radosław SmolińskiandClaude Fable 5.2 8fa71238ce M1 (1): stored secrets are write-only
smtpPassword and turnstileSecretKey in the Site integrations global are returned
as '********' to every read that goes through access control (REST, GraphQL, the
panel's form state); the Local API with access control off still gets the value.
A save that sends nothing, an empty value or the mask keeps the stored one;
'[[clear]]' removes it. MaskedField says that a value is set and offers to
remove it. Off: secrets: { writeOnly: false }. writeOnlySecret(s) and the hooks
are exported for a project's own fields.

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

701 lines
42 KiB
TypeScript

/**
* Who reaches what the plugin adds, through real HTTP requests (REST and GraphQL) against a running Payload:
* - a staff account that typed only its password (TOTP set up, code not entered) gets nothing;
* - an account of another auth collection (`customers`) gets no more than an anonymous visitor;
* - a fully verified staff account, an account that still has to set TOTP up, and an API key keep working.
*/
import type { CollectionConfig, Config, Payload, Plugin } 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, describe, expect, test, vi } from 'vitest'
import { ipalKit } from '../src/plugin.js'
import { buildTestConfig } from './helpers.js'
import { numericIds, 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 TOTP_SECRET = 'JBSWY3DPEHPK3PXP'
const PASSWORD = 'a-long-test-password-1'
/** A plugin the project lists AFTER ipalKit: its collection did not exist when ipalKit ran. */
const latePlugin: Plugin = (config: Config) => ({
...config,
collections: [
...(config.collections ?? []),
{ slug: 'late-notes', fields: [{ name: 'note', type: 'text' }] },
// A plugin may well call its collection `payload-…` (@payloadcms/plugin-mcp: `payload-mcp-api-keys`).
{ slug: 'payload-vault', access: { read: ({ req }) => Boolean(req.user) }, fields: [{ name: 'secret', type: 'text' }] },
],
globals: [...(config.globals ?? []), { slug: 'late-settings', fields: [{ name: 'note', type: 'text' }] }],
})
const projectCollections: CollectionConfig[] = [
// A visitor account collection with open sign-up — a shop or a client zone.
{ slug: 'customers', access: { create: () => true }, auth: true, fields: [] },
// Another one that happens to have its own `roles` field with the same values, settable at sign-up.
{
slug: 'members',
access: { create: () => true },
auth: true,
fields: [{ name: 'roles', type: 'select', hasMany: true, options: ['user', 'editor', 'admin'], saveToJWT: true }],
},
// The 2FA package's own per-entity opt-out, and ipal-kit's.
{
slug: 'open-notes',
access: { read: ({ req }) => Boolean(req.user), update: ({ req }) => Boolean(req.user) },
custom: { totp: { disableAccessWrapper: { read: true } } },
fields: [{ name: 'note', type: 'text' }],
},
{
slug: 'open-tasks',
access: { read: ({ req }) => Boolean(req.user), update: ({ req }) => Boolean(req.user) },
custom: { ipal: { secondFactor: { read: false } } },
fields: [{ name: 'task', type: 'text' }],
},
{ slug: 'pages', fields: [{ name: 'title', type: 'text' }] },
{ slug: 'media', fields: [], upload: { staticDir: path.join(os.tmpdir(), 'ipal-test-media') } },
]
const PROJECT_SLUGS = new Set(['customers', 'media', 'members', 'open-notes', 'open-tasks', 'pages'])
type Session = { headers: Record<string, string> }
let server: TestServer
let payload: Payload
let pluginCollections: string[]
let pluginGlobals: string[]
const sessions = {} as Record<'anonymous' | 'customer' | 'member' | 'newcomer' | 'passwordOnly' | 'verified', Session>
const api = (pathname: string, session: Session, init: RequestInit = {}) =>
fetch(`${server.url}/api${pathname}`, {
...init,
headers: { 'content-type': 'application/json', ...session.headers, ...(init.headers as Record<string, string>) },
})
const gql = async (session: Session, query: string) => {
const res = await api('/graphql', session, { body: JSON.stringify({ query }), method: 'POST' })
return (await res.json()) as { data?: null | Record<string, unknown>; errors?: { message: string }[] }
}
async function login(collection: string, email: string): Promise<{ cookies: string[]; token: string }> {
const res = await fetch(`${server.url}/api/${collection}/login`, {
body: JSON.stringify({ email, password: PASSWORD }),
headers: { 'content-type': 'application/json' },
method: 'POST',
})
const body = (await res.json()) as { token?: string }
if (!body.token) {throw new Error(`login failed for ${email}: ${JSON.stringify(body)}`)}
return { cookies: cookiesOf(res), token: body.token }
}
const makeConfig = () =>
buildTestConfig({
admin: { user: 'users' }, // the panel logs in with the staff collection, not with `customers`
collections: projectCollections,
db: testDatabase('sechttp'),
editor: lexicalEditor(),
plugins: [
ipalKit({
access: { authCollection: 'users' },
consentLog: true,
cookieScanner: { crawl: true },
forms: {},
i18n: { defaultLocale: 'pl', locales: [{ code: 'pl', label: 'Polski' }] },
stats: true,
twoFactor: { issuer: 'Example', plugin: payloadTotp },
}),
latePlugin,
],
secret: 'integration-test-secret-0123456789',
telemetry: false,
})
beforeAll(async () => {
const config = makeConfig()
payload = await getPayload({ config })
server = await startPayloadServer(config)
// The plugin's own and `late-notes`. Payload's built-in collections and the late plugin's `payload-vault` /
// `late-settings` have a describe of their own below (their rule is "any logged-in account", so the comparisons
// with an anonymous visitor do not apply to them).
pluginCollections = payload.config.collections.map((c) => c.slug).filter((s) => !PROJECT_SLUGS.has(s) && !s.startsWith('payload-'))
pluginGlobals = payload.config.globals.map((g) => g.slug).filter((slug) => slug !== 'late-settings')
await payload.updateGlobal({ slug: 'site-integrations' as never, data: { smtpPassword: 'S3CRET' } as never })
await payload.create({ collection: 'payload-vault' as never, data: { secret: 'VAULT' } as never })
const user = (email: string, extra: object) =>
payload.create({ collection: 'users' as never, data: { email, password: PASSWORD, roles: ['admin'], ...extra } as never })
await user('[email protected]', { totpSecret: TOTP_SECRET })
await user('[email protected]', {})
await payload.create({ collection: 'customers' as never, data: { email: '[email protected]', password: PASSWORD } as never })
// Signed up over the API, asking for the admin role in its own collection.
const signUp = await fetch(`${server.url}/api/members`, {
body: JSON.stringify({ email: '[email protected]', password: PASSWORD, roles: ['admin'] }),
headers: { 'content-type': 'application/json' },
method: 'POST',
})
expect(signUp.status).toBe(201)
sessions.member = { headers: { authorization: `JWT ${(await login('members', '[email protected]')).token}` } }
sessions.anonymous = { headers: {} }
sessions.passwordOnly = { headers: { authorization: `JWT ${(await login('users', '[email protected]')).token}` } }
sessions.newcomer = { headers: { authorization: `JWT ${(await login('users', '[email protected]')).token}` } }
sessions.customer = { headers: { authorization: `JWT ${(await login('customers', '[email protected]')).token}` } }
// The full login: password, then the code from the authenticator app → the 2FA cookie.
const full = await login('users', '[email protected]')
const verify = await fetch(`${server.url}/api/verify-totp`, {
body: JSON.stringify({ token: totp(TOTP_SECRET) }),
headers: { 'content-type': 'application/json', cookie: full.cookies.join('; ') },
method: 'POST',
})
const verified = (await verify.json()) as { message?: string; ok: boolean }
expect(verified, JSON.stringify({ cookies: full.cookies.map((c) => c.slice(0, 30)), verified })).toMatchObject({ ok: true })
sessions.verified = { headers: { cookie: [...full.cookies, ...cookiesOf(verify)].join('; ') } }
}, 120_000)
afterAll(async () => {
await server?.close()
await payload?.destroy?.()
})
const readStatus = async (kind: 'collection' | 'global', slug: string, s: Session) =>
(await api(kind === 'collection' ? `/${slug}` : `/globals/${slug}`, s)).status
const writeStatus = async (kind: 'collection' | 'global', slug: string, s: Session) =>
(await api(kind === 'collection' ? `/${slug}` : `/globals/${slug}`, s, { body: '{}', method: 'POST' })).status
describe('what the test set up', () => {
test('the plugin added the entities this file is about', () => {
expect(pluginCollections).toEqual(expect.arrayContaining(['users', 'forms', 'form-submissions', 'consent-records', 'cookie-review', 'stats-visits', 'late-notes']))
expect(pluginGlobals).toEqual(expect.arrayContaining(['site-settings', 'site-integrations', 'cookie-settings', 'notifications', 'cookie-crawl']))
})
})
describe('REST: a staff password without the TOTP code opens nothing', () => {
test('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.passwordOnly)) !== 403) {open.push(`read ${kind} ${slug}`)}
if ((await writeStatus(kind, slug, sessions.passwordOnly)) !== 403) {open.push(`write ${kind} ${slug}`)}
}
}
expect(open).toEqual([])
})
test('the SMTP password is not returned', async () => {
const res = await api('/globals/site-integrations', sessions.passwordOnly)
expect(res.status).toBe(403)
expect(await res.text()).not.toContain('S3CRET')
})
test("the plugin's own endpoints refuse too", async () => {
expect((await api('/ipal/test-email', sessions.passwordOnly, { body: JSON.stringify({ to: '[email protected]' }), method: 'POST' })).status).toBe(403)
expect((await api('/ipal/cookie-scan', sessions.passwordOnly)).status).toBe(403)
expect((await api('/ipal/cookie-scan', sessions.passwordOnly, { body: '{}', method: 'POST' })).status).toBe(403)
expect((await api('/ipal/cookie-crawl', sessions.passwordOnly)).status).toBe(403)
expect((await api('/ipal/cookie-approval', sessions.passwordOnly, { body: '{}', method: 'POST' })).status).toBe(403)
})
})
describe('GraphQL: a staff password without the TOTP code opens nothing', () => {
test.each([
['Site integrations', '{ SiteIntegration { smtpPassword } }'],
['form submissions', '{ FormSubmissions { totalDocs } }'],
['consent records', '{ ConsentRecords { totalDocs } }'],
['stats', '{ StatsVisits { totalDocs } }'],
['cookie review', '{ CookieReviews { totalDocs } }'],
['Site settings (write)', 'mutation { updateSiteSetting(data: { siteName: "x" }) { siteName } }'],
['Notifications (write)', 'mutation { updateNotification(data: {}) { updatedAt } }'],
])('%s', async (_, query) => {
const out = await gql(sessions.passwordOnly, query)
expect(out.errors?.length, JSON.stringify(out)).toBeGreaterThan(0)
expect(JSON.stringify(out)).not.toContain('S3CRET')
expect(Object.values(out.data ?? {}).filter((v) => v !== null)).toEqual([])
})
})
describe('an account of another auth collection (customers) is not staff', () => {
test('REST: it gets exactly what an anonymous visitor gets, nothing more', async () => {
const more: string[] = []
for (const [kind, slugs] of [['collection', pluginCollections.filter((s) => s !== 'late-notes')], ['global', pluginGlobals]] as const) {
for (const slug of slugs) {
const read = [await readStatus(kind, slug, sessions.customer), await readStatus(kind, slug, sessions.anonymous)]
if (read[0] !== read[1]) {more.push(`read ${kind} ${slug}: customer ${read[0]}, anonymous ${read[1]}`)}
// Creating a form submission over REST is open to every logged-in account (unchanged, see forms.md).
if (kind === 'collection' && slug === 'form-submissions') {continue}
const write = [await writeStatus(kind, slug, sessions.customer), await writeStatus(kind, slug, sessions.anonymous)]
if (write[0] !== write[1]) {more.push(`write ${kind} ${slug}: customer ${write[0]}, anonymous ${write[1]}`)}
}
}
expect(more).toEqual([])
})
test('REST: Site integrations, submissions, consent records and stats are refused', async () => {
for (const p of ['/globals/site-integrations', '/form-submissions', '/consent-records', '/stats-visits', '/cookie-review', '/globals/cookie-crawl']) {
expect([p, (await api(p, sessions.customer)).status]).toEqual([p, 403])
}
expect((await api('/globals/site-settings', sessions.customer, { body: JSON.stringify({ siteName: 'x' }), method: 'POST' })).status).toBe(403)
expect((await api('/ipal/test-email', sessions.customer, { body: JSON.stringify({ to: '[email protected]' }), method: 'POST' })).status).toBe(403)
expect((await api('/ipal/cookie-scan', sessions.customer)).status).toBe(403)
})
test('GraphQL: the same', async () => {
for (const query of ['{ SiteIntegration { smtpPassword } }', '{ FormSubmissions { totalDocs } }', '{ ConsentRecords { totalDocs } }', 'mutation { updateSiteSetting(data: { siteName: "x" }) { siteName } }']) {
const out = await gql(sessions.customer, query)
expect(out.errors?.length, `${query} → ${JSON.stringify(out)}`).toBeGreaterThan(0)
expect(JSON.stringify(out)).not.toContain('S3CRET')
}
})
test('its own collection still works for it', async () => {
expect((await api('/customers/me', sessions.customer)).status).toBe(200)
})
})
describe('what must keep working', () => {
test('a fully verified admin reads and writes everything (REST)', async () => {
const closed: string[] = []
for (const [kind, slugs] of [['collection', [...pluginCollections, 'pages']], ['global', pluginGlobals]] as const) {
for (const slug of slugs) {
const status = await readStatus(kind, slug, sessions.verified)
if (status !== 200) {closed.push(`read ${kind} ${slug}: ${status}`)}
}
}
expect(closed).toEqual([])
const integrations = (await (await api('/globals/site-integrations', sessions.verified)).json()) as { smtpPassword?: string }
expect(integrations.smtpPassword).toBe('********') // set, never returned (write-only secrets)
expect((await api('/globals/site-settings', sessions.verified, { body: JSON.stringify({ siteName: 'Verified' }), method: 'POST' })).status).toBe(200)
expect((await api('/ipal/cookie-scan', sessions.verified)).status).toBe(200)
// 400 = past the login and role gates, stopped by the missing recipient
expect((await api('/ipal/test-email', sessions.verified, { body: '{}', method: 'POST' })).status).toBe(400)
})
test('a fully verified admin reads Site integrations (GraphQL)', async () => {
const out = await gql(sessions.verified, '{ SiteIntegration { smtpPassword } FormSubmissions { totalDocs } }')
expect(out.errors).toBeUndefined()
expect((out.data?.SiteIntegration as { smtpPassword: string }).smtpPassword).toBe('********')
})
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])
}
expect((await api('/globals/site-integrations', sessions.anonymous)).status).toBe(403)
})
})
describe('a role value on an account of a non-staff collection counts for nothing (members with roles: [admin])', () => {
test('REST: it gets exactly what an anonymous visitor gets', async () => {
const more: string[] = []
for (const [kind, slugs] of [['collection', pluginCollections.filter((s) => s !== 'late-notes')], ['global', pluginGlobals]] as const) {
for (const slug of slugs) {
const read = [await readStatus(kind, slug, sessions.member), await readStatus(kind, slug, sessions.anonymous)]
if (read[0] !== read[1]) {more.push(`read ${kind} ${slug}: member ${read[0]}, anonymous ${read[1]}`)}
if (kind === 'collection' && slug === 'form-submissions') {continue}
const write = [await writeStatus(kind, slug, sessions.member), await writeStatus(kind, slug, sessions.anonymous)]
if (write[0] !== write[1]) {more.push(`write ${kind} ${slug}: member ${write[0]}, anonymous ${write[1]}`)}
}
}
expect(more).toEqual([])
})
test('REST: no secrets, no user list, no submissions, no staff endpoints, no unlock, no role change', async () => {
const integrations = await api('/globals/site-integrations', sessions.member)
expect(integrations.status).toBe(403)
expect(await integrations.text()).not.toContain('S3CRET')
for (const p of ['/users', '/form-submissions', '/consent-records', '/stats-visits', '/ipal/cookie-scan']) {
expect([p, (await api(p, sessions.member)).status]).toEqual([p, 403])
}
expect((await api('/ipal/test-email', sessions.member, { body: '{}', method: 'POST' })).status).toBe(403)
expect((await api('/users/unlock', sessions.member, { body: JSON.stringify({ email: '[email protected]' }), method: 'POST' })).status).toBe(403)
const staff = await payload.find({ collection: 'users' as never, where: { email: { equals: '[email protected]' } } })
const patch = await api(`/users/${staff.docs[0].id}`, sessions.member, { body: JSON.stringify({ roles: ['user'] }), method: 'PATCH' })
expect(patch.status).toBe(403)
const after = (await payload.findByID({ id: staff.docs[0].id, collection: 'users' as never })) as unknown as { roles: string[] }
expect(after.roles).toEqual(['admin'])
})
test('GraphQL: the same', async () => {
for (const query of ['{ SiteIntegration { smtpPassword } }', '{ Users { totalDocs } }', '{ FormSubmissions { totalDocs } }']) {
const out = await gql(sessions.member, query)
expect(out.errors?.length, `${query} → ${JSON.stringify(out)}`).toBeGreaterThan(0)
expect(JSON.stringify(out)).not.toContain('S3CRET')
}
})
})
describe("the 2FA package's endpoints accept accounts of the 2FA collection only", () => {
const secretOf = async (email: string) => {
const found = await payload.find({ collection: 'users' as never, showHiddenFields: true, where: { email: { equals: email } } })
return (found.docs[0] as { id: number | string; totpSecret?: null | string })
}
test('an account of another collection cannot set the TOTP secret of the staff account with the same id', async () => {
// SQL adapters number each collection from 1: the first customer and the first staff account share an id.
const customer = (await (await api('/customers/me', sessions.customer)).json()) as { user: { id: number | string } }
const admin = await secretOf('[email protected]')
const ATTACKER = 'KRSXG5CTMVRXEZLU'
const res = await api('/setup-totp', sessions.customer, { body: JSON.stringify({ secret: ATTACKER, token: totp(ATTACKER) }), method: 'POST' })
expect(res.status).toBe(403)
expect(res.headers.getSetCookie().join(';')).not.toContain('payload-totp')
const after = await secretOf('[email protected]')
expect(after.totpSecret).toBe(TOTP_SECRET)
// the case this test is about: the two accounts really share an id (SQL adapters; on MongoDB ids never repeat)
if (numericIds()) {expect(String(customer.user.id)).toBe(String(admin.id))}
// an account of yet another auth collection is refused the same way
const member = await api('/setup-totp', sessions.member, { body: JSON.stringify({ secret: ATTACKER, token: totp(ATTACKER) }), method: 'POST' })
expect(member.status).toBe(403)
})
test('verify, remove and the admin management endpoints refuse it as well', async () => {
for (const p of ['/verify-totp', '/remove-totp', '/admin/remove-user-totp', '/admin/reset-user-totp']) {
const res = await api(p, sessions.customer, { body: JSON.stringify({ token: '000000', userId: '1' }), method: 'POST' })
expect([p, res.status]).toEqual([p, 403])
}
})
test('a staff password without the code cannot reset or remove TOTP', async () => {
const admin = await secretOf('[email protected]')
for (const p of ['/remove-totp', '/admin/remove-user-totp', '/admin/reset-user-totp']) {
const res = await api(p, sessions.passwordOnly, { body: JSON.stringify({ token: totp(TOTP_SECRET), userId: String(admin.id) }), method: 'POST' })
expect([p, res.status]).toEqual([p, 403])
}
expect((await secretOf('[email protected]')).totpSecret).toBe(TOTP_SECRET)
})
})
describe('per-entity opt-out from the second factor', () => {
test("the package's key: custom.totp.disableAccessWrapper.<operation>", async () => {
expect((await api('/open-notes', sessions.passwordOnly)).status).toBe(200) // read opted out
expect((await api('/open-notes', sessions.passwordOnly, { body: '{}', method: 'POST' })).status).toBe(403) // create not
expect((await api('/open-notes', sessions.anonymous)).status).toBe(403) // its own rule still applies
})
test("ipal-kit's key: custom.ipal.secondFactor", async () => {
expect((await api('/open-tasks', sessions.passwordOnly)).status).toBe(200)
expect((await api('/open-tasks', sessions.passwordOnly, { body: '{}', method: 'POST' })).status).toBe(403)
})
})
describe('no exception by name: a later plugin\'s `payload-…` collection is guarded like any other', () => {
test('REST (list, count, by id) and GraphQL refuse a password-only session; a verified one reads it', async () => {
for (const p of ['/payload-vault', '/payload-vault/count', '/globals/late-settings']) {
const res = await api(p, sessions.passwordOnly)
expect([p, res.status]).toEqual([p, 403])
expect(await res.text()).not.toContain('VAULT')
}
const out = await gql(sessions.passwordOnly, '{ PayloadVaults { docs { secret } } }')
expect(out.errors?.length, JSON.stringify(out)).toBeGreaterThan(0)
expect(JSON.stringify(out)).not.toContain('VAULT')
const ok = await api('/payload-vault', sessions.verified)
expect(ok.status).toBe(200)
expect(await ok.text()).toContain('VAULT')
})
test("Payload's own collections answer a password-only session nothing either", async () => {
const own = payload.config.collections.map((c) => c.slug).filter((slug) => slug.startsWith('payload-') && slug !== 'payload-vault')
expect(own).toEqual(expect.arrayContaining(['payload-preferences', 'payload-locked-documents', 'payload-migrations']))
const open: string[] = []
for (const slug of own) {
const status = (await api(`/${slug}`, sessions.passwordOnly)).status
if (status === 200) {open.push(`${slug}: ${status}`)}
}
expect(open).toEqual([])
})
})
describe("the job queue keeps Payload's own defaults", () => {
// Payload's `defaultAccess` (3.94.1 fills run, queue and cancel with it when the config is built)
const payloadDefault = (user: unknown) => Boolean(user)
test('without a user: what Payload itself answers; a password-only session is refused; a verified one is not', async () => {
const access = payload.config.jobs.access!
const admin = (await payload.find({ collection: 'users' as never, where: { email: { equals: '[email protected]' } } })).docs[0]
const as = (user: unknown) => ({ req: { payload, user } }) as never
for (const op of ['queue', 'cancel', 'run'] as const) {
expect([op, await access[op]!(as(null))]).toEqual([op, payloadDefault(null)])
expect([op, await access[op]!(as({ ...admin, _strategy: 'local-jwt', collection: 'users' }))]).toEqual([op, false])
expect([op, await access[op]!(as({ ...admin, _strategy: 'totp', collection: 'users' }))]).toEqual([op, true])
}
// the Local API with access control on and no user: refused by Payload's own default, with or without the plugin
await expect(payload.jobs.queue({ input: {}, overrideAccess: false, task: 'no-such-task' } as never)).rejects.toThrow(/not allowed/i)
})
})
describe('the code cannot be guessed: verify attempts are limited per account', () => {
const GUESS_SECRET = 'ONSWG4TFORRW6ZDF'
let cookie: string
beforeAll(async () => {
await payload.create({ collection: 'users' as never, data: { email: '[email protected]', password: PASSWORD, roles: ['editor'], totpSecret: GUESS_SECRET } as never })
cookie = (await login('users', '[email protected]')).cookies.join('; ')
})
const verify = (token: string, headers: Record<string, string> = { cookie }) =>
fetch(`${server.url}/api/verify-totp`, { body: JSON.stringify({ token }), headers: { 'content-type': 'application/json', ...headers }, method: 'POST' })
test('five wrong codes are answered, the sixth attempt is refused — also with the right code', async () => {
for (let i = 0; i < 5; i++) {
const res = await verify('000000')
expect(res.status).toBe(200)
expect(((await res.json()) as { ok: boolean }).ok).toBe(false)
}
const sixth = await verify('000000')
expect(sixth.status).toBe(429)
expect(Number(sixth.headers.get('retry-after'))).toBeGreaterThan(0)
const right = await verify(totp(GUESS_SECRET))
expect(right.status).toBe(429)
expect(right.headers.getSetCookie().join(';')).not.toContain('payload-totp')
expect((await fetch(`${server.url}/api/pages`, { headers: { cookie } })).status).toBe(403)
})
test('the limit is the account\'s alone: nobody without its password can use it, other accounts are not affected', async () => {
// someone without the password cannot count against the account: no session, or a session of another collection
for (let i = 0; i < 8; i++) {
await verify('000000', {})
await verify('000000', sessions.customer.headers)
}
// another staff account still verifies
const other = await login('users', '[email protected]')
const ok = await verify(totp(TOTP_SECRET), { cookie: other.cookies.join('; ') })
expect(((await ok.json()) as { ok: boolean }).ok).toBe(true)
})
})
// 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)
// the reset ends the account's sessions: the token from before is nobody's now, the account logs in again
expect(((await (await api('/users/me', sessions.newcomer)).json()) as { user: unknown }).user).toBeNull()
expect(((await (await setup(sessions.newcomer)).json().catch(() => ({}))) as { ok?: boolean }).ok).not.toBe(true)
sessions.newcomer = { headers: { authorization: `JWT ${(await login('users', '[email protected]')).token}` } }
})
// A reset is also what an administrator presses for an account that may be in someone else's hands. A session of
// that account which had passed 2FA must not survive it: /api/setup-totp asks for no password, so it could
// otherwise enrol the thief's own authenticator.
test('a reset ends every session of the account: a stolen verified session cannot enrol its own authenticator', async () => {
const THIEF_SECRET = 'KRSXG5CTMVRXEZLU'
const victim = await payload.create({ collection: 'users' as never, data: { email: '[email protected]', password: PASSWORD, roles: ['editor'], totpSecret: TOTP_SECRET } as never })
// the victim's fully verified session, as a thief would hold it (token + 2FA cookie)
const signIn = await login('users', '[email protected]')
const verify = await api('/verify-totp', { headers: { authorization: `JWT ${signIn.token}` } }, { body: JSON.stringify({ token: totp(TOTP_SECRET) }), method: 'POST' })
expect(((await verify.json()) as { ok: boolean }).ok).toBe(true)
const stolen: Session = { headers: { authorization: `JWT ${signIn.token}`, cookie: cookiesOf(verify).join('; ') } }
expect((await api('/pages', stolen)).status).toBe(200)
expect((await api('/ipal/two-factor/reset', sessions.verified, { body: JSON.stringify({ userId: victim.id }), method: 'POST' })).status).toBe(200)
expect(((await (await api('/users/me', stolen)).json()) as { user: unknown }).user).toBeNull()
const enrol = await api('/setup-totp', stolen, { body: JSON.stringify({ secret: THIEF_SECRET, token: totp(THIEF_SECRET) }), method: 'POST' })
expect(((await enrol.json().catch(() => ({}))) as { ok?: boolean }).ok).not.toBe(true)
const after = (await payload.findByID({ id: victim.id, collection: 'users' as never, showHiddenFields: true })) as unknown as { sessions?: unknown[]; totpSecret?: null | string }
expect(after.totpSecret ?? null).toBeNull()
expect(after.sessions ?? []).toEqual([])
expect((await api('/form-submissions', stolen)).status).toBe(403)
// the owner logs in again with the password and sets TOTP up; the old session stays dead
const owner: Session = { headers: { authorization: `JWT ${(await login('users', '[email protected]')).token}` } }
expect((await setup(owner)).status).toBe(200)
expect(((await (await api('/users/me', stolen)).json()) as { user: unknown }).user).toBeNull()
})
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.
// 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.
const fresh = await makeConfig()
payload.config = fresh
// Before any HTTP request: the Local API meets the new config guarded already.
const passwordOnlyUser = { ...(await payload.find({ collection: 'users' as never, where: { email: { equals: '[email protected]' } } })).docs[0], _strategy: 'local-jwt', collection: 'users' }
payload.collections = Object.fromEntries(
fresh.collections.map((c) => [c.slug, { config: c, customIDType: payload.collections[c.slug as never]?.customIDType }]),
) as never
payload.globals = { config: fresh.globals }
await expect(payload.find({ collection: 'late-notes' as never, overrideAccess: false, user: passwordOnlyUser })).rejects.toThrow()
await expect(payload.find({ collection: 'payload-vault' as never, overrideAccess: false, user: passwordOnlyUser })).rejects.toThrow()
await expect(payload.findGlobal({ slug: 'late-settings' as never, overrideAccess: false, user: passwordOnlyUser })).rejects.toThrow()
expect((await api('/late-notes', sessions.passwordOnly)).status).toBe(403)
expect((await api('/late-notes', sessions.passwordOnly, { body: '{}', method: 'POST' })).status).toBe(403)
expect((await api('/globals/site-integrations', sessions.passwordOnly)).status).toBe(403)
expect((await api('/late-notes', sessions.verified)).status).toBe(200)
})
})