2FA screens: the back link is checked on the server (twoFactor.safeBack)

@clocklimited/payload-2fa sends the browser to the `back` query value after a
valid code without checking it (GHSA-rffw-fq79-g3ch upstream, not fixed in the
fork): a prepared link ran script in the panel or left the site.

SafeTotpView now stands in front of the package's setup and verify views and
passes on a checked value: a path on the site's origin inside the admin route,
else the admin root. The package's views stay in the import map through
admin.dependencies, so ipal-kit still never imports the package.

twoFactor.safeBack: false turns it off, a function replaces the rule;
safeAdminBack, wrapTotpViews and SafeTotpView are exported. Projects with 2FA
must regenerate the admin import map.

Co-Authored-By: Claude Fable 5.2 <[email protected]>
This commit is contained in:
Radosław Smoliński
2026-11-24 15:29:06 +01:00
co-authored by Claude Fable 5.2
parent 39309c5c1c
commit 93e75426ab
26 changed files with 678 additions and 11 deletions
+116
View File
@@ -0,0 +1,116 @@
/**
* The `back` query parameter of the 2FA setup and verify screens.
*
* @clocklimited/payload-2fa passes it, unchecked, to `location.replace()` once the code is
* accepted. Anyone can put it in a link in front of a panel user: `javascript:…` then runs in
* the admin origin with the session that has just passed the second factor, and an absolute
* URL sends the user off-site straight after a genuine login step (GHSA-rffw-fq79-g3ch in the
* original `payload-totp`, fixed there in 3.0.5; the fork does not have the fix).
*
* ipal-kit therefore cleans the value on the server before the package's view sees it
* (SafeTotpView.tsx): `twoFactor.safeBack` — on by default, a function replaces the rule,
* `false` turns it off.
*/
/** What a `back` rule is told about the panel. */
export type SafeBackContext = {
/** `routes.admin` of the Payload config, e.g. `/admin`. */
adminRoute: string
/**
* The site's own origin (from `serverURL`), when the config has one. An absolute `back` on
* this origin is accepted; without it only relative values are.
*/
origin?: string
}
/**
* A `back` rule: gets the raw query value (undefined when absent or repeated) and returns the
* URL the screen goes to after a valid code. Return a path on the site's own origin.
*/
export type SafeBackRule = (back: string | undefined, context: SafeBackContext) => string
/** Never a real site: a relative `back` is resolved against it, and anything that leaves it is refused. */
const PLACEHOLDER_ORIGIN = 'http://ipal-safe-back.invalid'
const trimSlashes = (path: string) => `/${path.replace(/^\/+|\/+$/g, '')}`
/**
* The default rule, the same as upstream's: `back` is resolved the way a browser resolves it
* and kept only when it stays on the site's origin, over HTTP(S), without credentials, inside
* the admin route. Anything else — `javascript:`, `data:`, `//host`, `/\host`, `\\host`,
* `https:host`, a path outside the panel, no value at all — gives the admin root.
*
* Returns a path (`/admin/collections/pages?page=2`), never an absolute URL, so the browser
* goes to exactly what was checked and cannot be taken off the origin.
*/
export const safeAdminBack: SafeBackRule = (back, { adminRoute, origin }) => {
const adminPath = trimSlashes(adminRoute || '/')
if (typeof back !== 'string' || !back) {return adminPath}
let base = PLACEHOLDER_ORIGIN
if (origin) {
try {
base = new URL(origin).origin
} catch {
/* not a URL: relative values only */
}
}
let url: URL
try {
url = new URL(back, base)
} catch {
return adminPath
}
// `blob:` URLs report the origin that made them, hence the protocol check.
if (url.origin !== base || !['http:', 'https:'].includes(url.protocol) || url.username || url.password) {
return adminPath
}
const inside = adminPath === '/' || url.pathname === adminPath || url.pathname.startsWith(`${adminPath}/`)
// The parser collapses `//`, but a path that still starts with two slashes would be read as a host.
if (!inside || url.pathname.startsWith('//')) {return adminPath}
return `${url.pathname}${url.search}${url.hash}`
}
/** The package's views that take `back` — matched by the route the package gives them. */
const TOTP_VIEW_PATH = /^\/?(?:setup|verify)-totp$/
type ViewComponent = { clientProps?: object; path: string; serverProps?: object } | string
type ViewLike = { Component?: unknown; path?: string }
/** Key of the import-map entry that keeps the package's own view importable. */
export const totpViewDependencyKey = (path: string) => `ipal-totp-view:${path}`
/**
* Puts ipal-kit's wrapper in front of the 2FA views the package added (`added` = their keys):
* the wrapper cleans `back` and renders the package's view, which it finds in the import map
* (`admin.dependencies` keeps it there). ipal-kit still never imports the optional package.
*/
export function wrapTotpViews<V extends ViewLike>(
views: Record<string, V>,
added: (key: string) => boolean,
rule: SafeBackRule | undefined,
wrapper = '@intecion/ipal-kit/admin#SafeTotpView',
): { dependencies: Record<string, { path: string; type: 'component' }>; views: Record<string, V> } {
const dependencies: Record<string, { path: string; type: 'component' }> = {}
const out: Record<string, V> = {}
for (const [key, view] of Object.entries(views)) {
const component = view?.Component as undefined | ViewComponent
const path = typeof component === 'string' ? component : component?.path
if (!added(key) || !view || typeof view.path !== 'string' || !TOTP_VIEW_PATH.test(view.path) || !path || path === wrapper) {
out[key] = view
continue
}
dependencies[totpViewDependencyKey(path)] = { type: 'component', path }
const own = typeof component === 'object' ? component : undefined
out[key] = {
...view,
Component: {
...(own?.clientProps ? { clientProps: own.clientProps } : {}),
path: wrapper,
serverProps: { ...own?.serverProps, ipalSafeBack: rule, ipalTotpView: path },
},
}
}
return { dependencies, views: out }
}