Files
ipal-kit/test/totpRedirect.test.ts
T
Radosław SmolińskiandClaude Opus 5.5 60f744e3ad Fix the 2FA setup loop: setup-totp?back=null redirected to itself
@clocklimited/payload-2fa's admin provider reads the current path from an
x-pathname request header. Nothing sets it on /admin (the createProxy matcher
skips /admin), so the path was null: every admin page, the setup screen too,
redirected to /admin/setup-totp?back=null, forever. Every new admin on a site
with 2FA got stuck.

ipalKit now swaps that provider for its own TotpRedirectProvider
(@intecion/ipal-kit/admin, client-side): it reads the path in the browser,
never redirects away from the setup/verify screens or logout, and renders
nothing while redirecting. twoFactor.provider takes a project component, or
false to keep the package's. totpRedirectTarget / totpAdminPath export the
rules. Projects run generate:importmap.

Test: test/totpRedirect.test.ts (redirect walk, provider swap). Dev app:
IPAL_DEV_2FA=1 turns 2FA on. Docs: security.md, CHANGELOG (Unreleased),
AGENT.md, ipal-setup/-upgrade/-debug/-reference, PROGRAMISTA item 51.

Co-Authored-By: Claude Opus 5.5 <[email protected]>
2026-10-28 21:27:19 +01:00

86 lines
4.1 KiB
TypeScript

import type { Config } from 'payload'
import { payloadTotp } from '@clocklimited/payload-2fa'
import { describe, expect, it } from 'vitest'
import { ipalKit } from '../src/index.js'
import { totpRedirectTarget } from '../src/modules/security/totp/totpRedirect.js'
const i18n = { defaultLocale: 'pl', locales: [{ code: 'pl', label: 'Polski' }] }
const fresh = { _strategy: 'local-jwt', hasTotp: false }
const base = (): Config =>
({ admin: { user: 'users' }, collections: [{ slug: 'users', auth: true, fields: [] }] }) as unknown as Config
const providerPaths = (config: Config) =>
(config.admin?.components?.providers ?? []).map((p) => (typeof p === 'object' && p ? p.path : p))
/** Follows the redirects the provider would make, the way a browser would. */
function walk(start: string, user: typeof fresh, adminRoute = '/admin') {
const visited = [start]
let url = start
for (let i = 0; i < 5; i++) {
const next = totpRedirectTarget({ adminRoute, forceSetup: true, pathname: url.split('?')[0], user })
if (!next) {return visited}
url = next
visited.push(url)
}
throw new Error(`redirect loop: ${visited.join(' → ')}`)
}
describe('2FA setup redirect (fresh admin, forceSetup)', () => {
it('lands on the setup screen once, with the page to return to — no loop, no back=null', () => {
expect(walk('/admin', fresh)).toEqual(['/admin', '/admin/setup-totp?back=%2Fadmin'])
expect(walk('/admin/collections/pages', fresh).at(-1)).toBe('/admin/setup-totp?back=%2Fadmin%2Fcollections%2Fpages')
})
it('stays on the setup and verify screens, with or without a trailing slash', () => {
for (const pathname of ['/admin/setup-totp', '/admin/setup-totp/', '/admin/verify-totp']) {
expect(totpRedirectTarget({ adminRoute: '/admin', forceSetup: true, pathname, user: fresh })).toBeNull()
}
})
it('never redirects on an unknown path (the package read a missing header as null → back=null)', () => {
expect(totpRedirectTarget({ adminRoute: '/admin', forceSetup: true, pathname: null, user: fresh })).toBeNull()
})
it('works with a custom admin route and lets logout through', () => {
expect(walk('/its', fresh, '/its')).toEqual(['/its', '/its/setup-totp?back=%2Fits'])
expect(walk('/', fresh, '/')).toEqual(['/', '/setup-totp?back=%2F'])
expect(totpRedirectTarget({ adminRoute: '/admin', forceSetup: true, pathname: '/admin/logout', user: fresh })).toBeNull()
})
it('sends a user with TOTP to verify until this session passed it; api keys pass', () => {
const user = { _strategy: 'local-jwt', hasTotp: true }
expect(walk('/admin', user)).toEqual(['/admin', '/admin/verify-totp?back=%2Fadmin'])
expect(walk('/admin', { _strategy: 'totp', hasTotp: true })).toEqual(['/admin'])
expect(walk('/admin', { _strategy: 'api-key', hasTotp: false })).toEqual(['/admin'])
})
it('leaves users alone when setup is not forced', () => {
expect(totpRedirectTarget({ adminRoute: '/admin', pathname: '/admin', user: fresh })).toBeNull()
})
})
describe('twoFactor.provider', () => {
const run = (provider?: unknown) =>
ipalKit({ i18n, twoFactor: { issuer: 'Test', plugin: payloadTotp, ...(provider === undefined ? {} : { provider }) } } as never)(base())
it("replaces the package's header-based provider with ipal-kit's by default", async () => {
const config = await run()
expect(providerPaths(config)).toContain('@intecion/ipal-kit/admin#TotpRedirectProvider')
expect(providerPaths(config)).not.toContain('@clocklimited/payload-2fa/rsc#TOTPProvider')
const ours = config.admin?.components?.providers?.find(
(p) => typeof p === 'object' && p && p.path === '@intecion/ipal-kit/admin#TotpRedirectProvider',
)
expect(ours).toMatchObject({ clientProps: { forceSetup: true } })
})
it('takes a project component, or false to keep the package provider', async () => {
expect(providerPaths(await run('@/components/MyTotp#MyTotp'))).toContain('@/components/MyTotp#MyTotp')
const kept = await run(false)
expect(providerPaths(kept)).toContain('@clocklimited/payload-2fa/rsc#TOTPProvider')
expect(providerPaths(kept)).not.toContain('@intecion/ipal-kit/admin#TotpRedirectProvider')
})
})