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:
co-authored by
Claude Opus 5.5
parent
4e254057f9
commit
60f744e3ad
@@ -14,6 +14,8 @@ export { CookieScanButton } from '../modules/consent/scanner/CookieScanButton.js
|
||||
export { CookieCrawlAlert } from '../modules/consent/scanner/crawl/CookieCrawlAlert.js'
|
||||
export { IntegrationAlerts } from '../modules/integrations/IntegrationAlerts.js'
|
||||
export { IntegrationStatusBanner } from '../modules/integrations/IntegrationStatusBanner.js'
|
||||
export { TotpRedirectProvider } from '../modules/security/totp/TotpRedirectProvider.js'
|
||||
export type { TotpRedirectProviderProps } from '../modules/security/totp/TotpRedirectProvider.js'
|
||||
export { FaviconCheck } from '../modules/seo/FaviconCheck.js'
|
||||
export type { FaviconCheckProps } from '../modules/seo/FaviconCheck.js'
|
||||
export { MetaDescriptionCheck } from '../modules/seo/MetaDescriptionCheck.js'
|
||||
|
||||
@@ -268,6 +268,8 @@ export {
|
||||
cspHeaderKey,
|
||||
DEFAULT_CSP_REPORT_GROUP,
|
||||
parseCspReports,
|
||||
totpAdminPath,
|
||||
totpRedirectTarget,
|
||||
withSecurityConfig,
|
||||
} from './modules/security/index.js'
|
||||
export type {
|
||||
@@ -277,6 +279,8 @@ export type {
|
||||
CspDirective,
|
||||
CspSources,
|
||||
CspViolation,
|
||||
TotpRedirectArgs,
|
||||
TotpUser,
|
||||
WithSecurityConfigOptions,
|
||||
} from './modules/security/index.js'
|
||||
|
||||
|
||||
@@ -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
|
||||
@@ -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
|
||||
}
|
||||
@@ -30,6 +30,9 @@ import { searchSettingsFields } from './modules/seo/searchSettings.js'
|
||||
import { applyCollectionOverride } from './modules/shared/collectionOverride.js'
|
||||
import { buildStatsCollection, buildStatsEndpoint } from './modules/stats/index.js'
|
||||
|
||||
/** The admin provider @clocklimited/payload-2fa registers; ipal-kit swaps it (twoFactor.provider). */
|
||||
const TOTP_PACKAGE_PROVIDER = '@clocklimited/payload-2fa/rsc#TOTPProvider'
|
||||
|
||||
/**
|
||||
* IPAL (Intecion Payload Advanced Library) plugin for Payload CMS 3.
|
||||
*
|
||||
@@ -181,6 +184,32 @@ export const ipalKit = (options: IpalOptions): Plugin => {
|
||||
forceSetup: true, // ENFORCED — every user must set up TOTP; no opt-out
|
||||
totp: { issuer: tf.issuer },
|
||||
})(config)
|
||||
|
||||
// The package's TOTPProvider reads the path from an `x-pathname` header
|
||||
// no proxy sets on /admin, so it redirected the setup screen to itself
|
||||
// (`setup-totp?back=null`). Swap in ipal-kit's client-side provider, or
|
||||
// the project's (`provider`); `provider: false` keeps the package's.
|
||||
if (tf.provider !== false) {
|
||||
const custom = tf.provider
|
||||
const ours =
|
||||
typeof custom === 'object' ? custom : { path: custom ?? '@intecion/ipal-kit/admin#TotpRedirectProvider' }
|
||||
const providers = config.admin?.components?.providers ?? []
|
||||
config.admin = {
|
||||
...config.admin,
|
||||
components: {
|
||||
...config.admin?.components,
|
||||
providers: providers.map((p) =>
|
||||
p && (typeof p === 'string' ? p : p.path) === TOTP_PACKAGE_PROVIDER
|
||||
? {
|
||||
...ours,
|
||||
clientProps: { forceSetup: true, ...ours.clientProps },
|
||||
serverProps: { ...(typeof p === 'object' ? p.serverProps : {}), ...ours.serverProps },
|
||||
}
|
||||
: p,
|
||||
),
|
||||
},
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
// --- white-label admin branding ---
|
||||
|
||||
+12
-1
@@ -1,4 +1,4 @@
|
||||
import type { CollectionSlug, Field, Plugin } from 'payload'
|
||||
import type { CollectionSlug, Field, PayloadComponent, Plugin } from 'payload'
|
||||
|
||||
/**
|
||||
* Factory shape of @clocklimited/payload-2fa's `payloadTotp` export — injected
|
||||
@@ -200,6 +200,17 @@ export type IpalOptions = {
|
||||
* injected factory too. See docs/security.md.
|
||||
*/
|
||||
plugin: TotpPluginFactory
|
||||
/**
|
||||
* Admin provider that sends users to the TOTP setup / verify screens.
|
||||
* Default: ipal-kit's `@intecion/ipal-kit/admin#TotpRedirectProvider`
|
||||
* (reads the path in the browser). The package's own provider needs an
|
||||
* `x-pathname` request header on every /admin request; without it the
|
||||
* setup screen redirects to itself (`setup-totp?back=null`). Pass your
|
||||
* own component path (it gets clientProps `forceSetup` and the package's
|
||||
* serverProps `pluginOptions`), or `false` to keep the package's provider
|
||||
* (then set `x-pathname` on /admin yourself). Run generate:importmap.
|
||||
*/
|
||||
provider?: false | PayloadComponent
|
||||
}
|
||||
| false
|
||||
|
||||
|
||||
Reference in New Issue
Block a user