Files
ipal-kit/test/safeBack.test.ts
T
Radosław SmolińskiandClaude Fable 5.2 93e75426ab 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]>
2026-11-24 15:29:06 +01:00

239 lines
12 KiB
TypeScript

import type { Config } from 'payload'
import { payloadTotp } from '@clocklimited/payload-2fa'
import React from 'react'
import { renderToStaticMarkup } from 'react-dom/server'
import { describe, expect, test } from 'vitest'
import type { I18nConfig } from '../src/modules/i18n/types.js'
import { safeAdminBack, wrapTotpViews } from '../src/modules/security/totp/safeBack.js'
import { SafeTotpView } from '../src/modules/security/totp/SafeTotpView.js'
import { ipalKit } from '../src/plugin.js'
const i18n: I18nConfig = { defaultLocale: 'en', locales: [{ code: 'en', label: 'English' }] }
const admin = { adminRoute: '/admin' }
describe('safeAdminBack', () => {
test.each([
['/admin', '/admin'],
['/admin/', '/admin/'],
['/admin/collections/pages?page=2&limit=10#row', '/admin/collections/pages?page=2&limit=10#row'],
['/admin/collections/pages/../media', '/admin/collections/media'],
])('keeps a path inside the panel: %s', (back, expected) => {
expect(safeAdminBack(back, admin)).toBe(expected)
})
test.each([
['javascript:alert(document.domain)'],
['JaVaScRiPt:alert(1)'],
[' javascript:alert(1)'],
['\tjavascript:alert(1)'],
['java\nscript:alert(1)'],
['data:text/html,<script>alert(1)</script>'],
['vbscript:msgbox(1)'],
['blob:http://ipal-safe-back.invalid/1'],
['https://evil.example/admin'],
['http://evil.example/admin'],
['//evil.example/admin'],
['/\\evil.example/admin'],
['\\\\evil.example/admin'],
['\\/evil.example/admin'],
['https:evil.example/admin'],
['https:/evil.example/admin'],
['http://[email protected]/admin'],
['http://user:[email protected]/admin'],
['http://ipal-safe-back.invalid/admin'], // the placeholder is not the site: absolute values need `origin`
['http://ipal-safe-back.invalid:8080/admin'],
['/'],
['/login'],
['/administrator'],
['/admin/../api/users'],
['/admin/%2e%2e/api/users'],
['/api/users'],
['collections/pages'], // relative to nothing: resolves outside the panel
[''],
[undefined],
])('falls back to the admin root: %s', (back) => {
expect(safeAdminBack(back, admin)).toBe('/admin')
})
test('never returns an absolute URL or a value a browser reads as another host', () => {
for (const back of ['//evil.example', '/\\evil.example', '/admin//evil.example', 'https://evil.example/admin', '/admin/x']) {
const out = safeAdminBack(back, admin)
expect(out.startsWith('/')).toBe(true)
expect(out.startsWith('//')).toBe(false)
expect(new URL(out, 'https://site.example').origin).toBe('https://site.example')
}
})
test('a custom admin route', () => {
const panel = { adminRoute: '/panel' }
expect(safeAdminBack('/panel/collections/pages', panel)).toBe('/panel/collections/pages')
expect(safeAdminBack('/admin/collections/pages', panel)).toBe('/panel')
expect(safeAdminBack('javascript:alert(1)', panel)).toBe('/panel')
expect(safeAdminBack('/panel-other', panel)).toBe('/panel')
expect(safeAdminBack(undefined, { adminRoute: '/cms/panel/' })).toBe('/cms/panel')
expect(safeAdminBack('/cms/panel/x', { adminRoute: '/cms/panel/' })).toBe('/cms/panel/x')
})
test('an admin route of "/" keeps any path on the site, still nothing off it', () => {
const root = { adminRoute: '/' }
expect(safeAdminBack('/collections/pages', root)).toBe('/collections/pages')
expect(safeAdminBack('//evil.example/x', root)).toBe('/')
expect(safeAdminBack('javascript:alert(1)', root)).toBe('/')
})
test('with the site origin, an absolute URL on that origin is kept — as a path', () => {
const site = { adminRoute: '/admin', origin: 'https://site.example' }
expect(safeAdminBack('https://site.example/admin/collections/pages?x=1', site)).toBe('/admin/collections/pages?x=1')
expect(safeAdminBack('http://site.example/admin', site)).toBe('/admin') // other scheme = other origin
expect(safeAdminBack('https://site.example:8443/admin', site)).toBe('/admin')
expect(safeAdminBack('https://site.example.evil.example/admin', site)).toBe('/admin')
expect(safeAdminBack('https://[email protected]/admin/x', site)).toBe('/admin')
expect(safeAdminBack('/admin/x', site)).toBe('/admin/x')
expect(safeAdminBack('/admin/x', { adminRoute: '/admin', origin: 'not a url' })).toBe('/admin/x')
})
})
describe('wrapTotpViews', () => {
const views = {
Other: { Component: 'my#View', path: '/reports' },
SetupTOTP: { Component: { path: 'pkg/rsc#TOTPSetup', serverProps: { pluginOptions: { a: 1 } } }, exact: true, path: 'setup-totp' },
VerifyTOTPBackslash: { Component: 'pkg/rsc#TOTPVerify', path: '/verify-totp' },
}
test('wraps the views the package added, keeps their props, lists the originals as dependencies', () => {
const rule = () => '/x'
const out = wrapTotpViews(views, () => true, rule)
expect(out.views.Other).toBe(views.Other)
expect(out.views.SetupTOTP).toEqual({
Component: { path: '@intecion/ipal-kit/admin#SafeTotpView', serverProps: { ipalSafeBack: rule, ipalTotpView: 'pkg/rsc#TOTPSetup', pluginOptions: { a: 1 } } },
exact: true,
path: 'setup-totp',
})
expect((out.views.VerifyTOTPBackslash.Component as unknown as { serverProps: { ipalTotpView: string } }).serverProps.ipalTotpView).toBe('pkg/rsc#TOTPVerify')
expect(out.dependencies).toEqual({
'ipal-totp-view:pkg/rsc#TOTPSetup': { type: 'component', path: 'pkg/rsc#TOTPSetup' },
'ipal-totp-view:pkg/rsc#TOTPVerify': { type: 'component', path: 'pkg/rsc#TOTPVerify' },
})
})
test('leaves alone what the project registered itself, and is safe to run twice', () => {
expect(wrapTotpViews(views, () => false, undefined)).toEqual({ dependencies: {}, views })
const once = wrapTotpViews(views, () => true, undefined)
const twice = wrapTotpViews(once.views, () => true, undefined)
expect(twice.views).toEqual(once.views)
expect(twice.dependencies).toEqual({})
})
})
describe('ipalKit with the real 2FA package', () => {
const build = (twoFactor: false | Record<string, unknown>, extra: Partial<Config> = {}) =>
ipalKit({
access: { authCollection: 'users' },
i18n,
twoFactor: twoFactor === false ? false : ({ issuer: 'Example', plugin: payloadTotp, ...twoFactor } as never),
})({ collections: [], secret: 'x', ...extra } as unknown as Config)
const component = (config: Config, key: string) =>
(config.admin?.components?.views as Record<string, { Component: { path: string; serverProps?: Record<string, unknown> } }> | undefined)?.[key]?.Component
test('by default all four 2FA views go through SafeTotpView and the package views stay in the import map', async () => {
const config = await build({})
for (const key of ['SetupTOTP', 'SetupTOTPBackslash', 'VerifyTOTP', 'VerifyTOTPBackslash']) {
const c = component(config, key)
expect([key, c?.path]).toEqual([key, '@intecion/ipal-kit/admin#SafeTotpView'])
expect(c?.serverProps?.ipalTotpView).toBe(`@clocklimited/payload-2fa/rsc#TOTP${key.startsWith('Setup') ? 'Setup' : 'Verify'}`)
expect(c?.serverProps?.pluginOptions).toBeDefined() // the package's own props are kept
expect(c?.serverProps?.ipalSafeBack).toBeUndefined()
}
expect(config.admin?.dependencies).toEqual({
'ipal-totp-view:@clocklimited/payload-2fa/rsc#TOTPSetup': { type: 'component', path: '@clocklimited/payload-2fa/rsc#TOTPSetup' },
'ipal-totp-view:@clocklimited/payload-2fa/rsc#TOTPVerify': { type: 'component', path: '@clocklimited/payload-2fa/rsc#TOTPVerify' },
})
// the tab title ipal-kit gives the screens is still there
expect((config.admin?.components?.views as Record<string, { meta?: { title?: string } }>).VerifyTOTP.meta?.title).toBeTruthy()
})
test('safeBack: false leaves the package views as registered', async () => {
const config = await build({ safeBack: false })
expect(component(config, 'VerifyTOTP')?.path).toBe('@clocklimited/payload-2fa/rsc#TOTPVerify')
expect(component(config, 'SetupTOTP')?.path).toBe('@clocklimited/payload-2fa/rsc#TOTPSetup')
expect(config.admin?.dependencies).toBeUndefined()
})
test('a function replaces the rule', async () => {
const rule = () => '/admin/account'
const config = await build({ safeBack: rule })
expect(component(config, 'VerifyTOTP')?.serverProps?.ipalSafeBack).toBe(rule)
})
test('still on with twoFactor.guard: false', async () => {
const config = await build({ guard: false })
expect(component(config, 'VerifyTOTP')?.path).toBe('@intecion/ipal-kit/admin#SafeTotpView')
})
test("the project's own dependencies and views are kept", async () => {
const config = await build({}, { admin: { components: { views: { Mine: { Component: 'mine#View', path: '/verify-totp-help' } } }, dependencies: { mine: { type: 'component', path: 'mine#Thing' } } } } as never)
expect((config.admin?.components?.views as Record<string, { Component: unknown }>).Mine.Component).toBe('mine#View')
expect(config.admin?.dependencies?.mine).toEqual({ type: 'component', path: 'mine#Thing' })
})
test('without 2FA nothing is registered', async () => {
const config = await build(false)
expect(JSON.stringify(config.admin ?? {})).not.toContain('SafeTotpView')
expect(JSON.stringify(config.admin ?? {})).not.toContain('ipal-totp-view')
})
})
describe('SafeTotpView', () => {
const PackageView = (props: { pluginOptions?: { issuer?: string }; searchParams?: Record<string, unknown> }) =>
React.createElement('p', { 'data-back': String(props.searchParams?.back), 'data-issuer': props.pluginOptions?.issuer, 'data-other': String(props.searchParams?.other) })
const render = (searchParams: Record<string, unknown>, more: Record<string, unknown> = {}, config: Record<string, unknown> = { routes: { admin: '/admin' }, serverURL: '' }) =>
renderToStaticMarkup(
React.createElement(SafeTotpView as never, {
importMap: { 'pkg/rsc#TOTPVerify': PackageView },
initPageResult: { req: { payload: { config } } },
ipalTotpView: 'pkg/rsc#TOTPVerify',
pluginOptions: { issuer: 'Example' },
searchParams,
...more,
}),
)
test.each([
['javascript:void(document.title=1)', '/admin'],
['http://127.0.0.1:3218/admin/login?landed=absolute', '/admin'],
['/\\127.0.0.1:3218/admin/login', '/admin'],
['//127.0.0.1:3218/admin', '/admin'],
['/admin/collections/pages?page=2', '/admin/collections/pages?page=2'],
])('the package view receives a checked back: %s', (back, expected) => {
const html = render({ back, other: 'kept' })
expect(html).toContain(`data-back="${expected.replace(/&/g, '&amp;')}"`)
expect(html).toContain('data-issuer="Example"') // the package's serverProps reach its view
expect(html).toContain('data-other="kept"')
})
test('no back, or a repeated one, gives the admin root (the package would otherwise go back in history)', () => {
expect(render({})).toContain('data-back="/admin"')
expect(render({ back: ['/admin/a', 'javascript:alert(1)'] })).toContain('data-back="/admin"')
})
test('a custom admin route and serverURL', () => {
const config = { routes: { admin: '/panel' }, serverURL: 'https://site.example' }
expect(render({ back: '/admin/x' }, {}, config)).toContain('data-back="/panel"')
expect(render({ back: 'https://site.example/panel/x' }, {}, config)).toContain('data-back="/panel/x"')
expect(render({ back: 'https://evil.example/panel/x' }, {}, config)).toContain('data-back="/panel"')
})
test("the project's rule is used instead", () => {
const html = render({ back: 'javascript:alert(1)' }, { ipalSafeBack: (back: string | undefined, ctx: { adminRoute: string }) => `${ctx.adminRoute}/account?was=${back ? 'set' : 'empty'}` })
expect(html).toContain('data-back="/admin/account?was=set"')
})
test('a missing import-map entry says what to run', () => {
expect(() => render({}, { importMap: {} })).toThrow(/generate:importmap/)
})
})