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]>
This commit is contained in:
Radosław Smoliński
2026-10-28 21:27:19 +01:00
co-authored by Claude Opus 5.5
parent 4e254057f9
commit 60f744e3ad
19 changed files with 321 additions and 10 deletions
+2
View File
@@ -13,5 +13,7 @@ export type { BuildSecurityHeadersArgs, SecurityHeader } from './buildSecurityHe
export { createCspReportRoute, parseCspReports } from './createCspReportRoute.js'
export type { CreateCspReportRouteArgs, CspViolation } from './createCspReportRoute.js'
export { createCspNonce, CSP_NONCE_HEADER } from './cspNonce.js'
export { totpAdminPath, totpRedirectTarget } from './totp/totpRedirect.js'
export type { TotpRedirectArgs, TotpUser } from './totp/totpRedirect.js'
export { withSecurityConfig } from './withSecurityConfig.js'
export type { WithSecurityConfigOptions } from './withSecurityConfig.js'
@@ -0,0 +1,48 @@
'use client'
import type { ReactNode } from 'react'
import { useAuth, useConfig } from '@payloadcms/ui'
import { usePathname, useRouter } from 'next/navigation.js'
import { useEffect } from 'react'
import type { TotpUser } from './totpRedirect.js'
import { totpRedirectTarget } from './totpRedirect.js'
export type TotpRedirectProviderProps = {
children?: ReactNode
/** pluginOptions.forceSetup — set by the plugin (true: 2FA is enforced). */
forceSetup?: boolean
}
/**
* Admin provider that sends users to the 2FA setup / verify screens. Replaces
* @clocklimited/payload-2fa's TOTPProvider, which read the path from an
* `x-pathname` request header: on /admin no proxy sets it, so the path was
* null and the setup screen redirected to itself (`setup-totp?back=null`).
* Renders nothing while a redirect is pending, so the panel does not flash.
* Swap it with `twoFactor.provider`.
*/
export function TotpRedirectProvider({ children, forceSetup = true }: TotpRedirectProviderProps) {
const { user } = useAuth()
const { config } = useConfig()
const pathname = usePathname()
const router = useRouter()
const routes = config.admin?.routes
const target = totpRedirectTarget({
adminRoute: config.routes?.admin ?? '/admin',
excludePaths: [routes?.logout ?? '/logout', routes?.inactivity ?? '/logout-inactivity'],
forceSetup,
pathname,
user: user as null | TotpUser,
})
useEffect(() => {
if (target) {router.replace(target)}
}, [router, target])
return target ? null : children
}
export default TotpRedirectProvider
+53
View File
@@ -0,0 +1,53 @@
/** The admin user fields @clocklimited/payload-2fa adds (and Payload's `_strategy`). */
export type TotpUser = {
_strategy?: null | string
forceTotp?: boolean | null
hasTotp?: boolean | null
}
export type TotpRedirectArgs = {
/** config.routes.admin, e.g. '/admin' or '/'. */
adminRoute: string
/** Admin paths the redirect leaves alone (logout must still work). Default: '/logout', '/logout-inactivity'. */
excludePaths?: string[]
/** pluginOptions.forceSetup: every user without TOTP goes to the setup screen. */
forceSetup?: boolean
/** The current path, without origin or query (usePathname()). */
pathname: null | string | undefined
user: null | TotpUser | undefined
}
/** '/admin' + '/setup-totp' → '/admin/setup-totp'; an origin or trailing slash is dropped. */
export function totpAdminPath(adminRoute: string, path: string): string {
return normalize(`${adminRoute === '/' ? '' : adminRoute}${path}`)
}
function normalize(pathname: string): string {
const path = pathname.replace(/^[a-z][a-z\d+.-]*:\/\/[^/]+/i, '').replace(/[?#].*$/, '')
return path.replace(/\/+$/, '') || '/'
}
/**
* Where the admin should send this user for 2FA, or null to stay. Same rules as
* @clocklimited/payload-2fa's TOTPProvider — verify when TOTP is set up but this
* session has not passed it, setup when it is required but missing — with two
* fixes: the current path comes from the browser, never a request header the
* project may not set (its absence made the package's provider redirect to
* `setup-totp?back=null` forever), and the TOTP screens themselves (and logout)
* never redirect, whether the setup URL is relative or absolute (serverURL).
*/
export function totpRedirectTarget(args: TotpRedirectArgs): null | string {
const { adminRoute, excludePaths = ['/logout', '/logout-inactivity'], forceSetup, pathname, user } = args
if (!user || !pathname || user._strategy === 'api-key') {return null}
const here = normalize(pathname)
const setupUrl = totpAdminPath(adminRoute, '/setup-totp')
const verifyUrl = totpAdminPath(adminRoute, '/verify-totp')
const stay = [setupUrl, verifyUrl, ...excludePaths.map((p) => totpAdminPath(adminRoute, p))]
if (stay.includes(here)) {return null}
const back = `?back=${encodeURIComponent(here)}`
if (user.hasTotp) {return user._strategy && user._strategy !== 'totp' ? verifyUrl + back : null}
if (user.forceTotp || forceSetup) {return setupUrl + back}
return null
}