import type { Config } from 'payload'
import { payloadTotp as payloadTotpBeta7 } from '@clocklimited/payload-2fa'
import { mkdir, mkdtemp, rm, writeFile } from 'node:fs/promises'
import os from 'node:os'
import path from 'node:path'
import { payloadTotp as payloadTotpBeta1 } from 'payload-2fa-beta1'
import React from 'react'
import { renderToStaticMarkup } from 'react-dom/server'
import { describe, expect, test, vi } from 'vitest'
import type { I18nConfig } from '../src/modules/i18n/types.js'
import { findImportMapFile, missingImportMapEntries } from '../src/modules/security/totp/importMapCheck.js'
import { changedViewKeys, safeAdminBack, wrapTotpViews } from '../src/modules/security/totp/safeBack.js'
import { SafeTotpView } from '../src/modules/security/totp/SafeTotpView.js'
import { iapl } from '../src/plugin.js'
import { withTotpParts } from './helpers.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,'],
['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://ipal-safe-back.invalid@evil.example/admin'],
['http://user:pass@ipal-safe-back.invalid/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://site.example@evil.example/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('keeps exportName and clientProps of the original registration', () => {
const out = wrapTotpViews({ V: { Component: { clientProps: { tone: 'dark' }, exportName: 'Verify', path: 'mine/views' }, path: '/verify-totp' } }, () => true, undefined)
expect(out.views.V.Component).toEqual({
path: '@intecion/ipal-kit/admin#SafeTotpView',
serverProps: { ipalSafeBack: undefined, ipalTotpClientProps: { tone: 'dark' }, ipalTotpView: { exportName: 'Verify', path: 'mine/views' } },
})
expect(out.dependencies).toEqual({ 'ipal-totp-view:mine/views#Verify': { type: 'component', exportName: 'Verify', path: 'mine/views' } })
})
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.each([
['3.0.0-beta.7', payloadTotpBeta7],
['3.0.0-beta.1', payloadTotpBeta1 as unknown as typeof payloadTotpBeta7],
])('iapl with the real 2FA package %s', (_version, payloadTotp) => {
const build = (twoFactor: false | Record, extra: Partial = {}, options: Record = {}) =>
iapl({
access: { authCollection: 'users' },
i18n,
twoFactor: twoFactor === false ? false : ({ issuer: 'Example', plugin: payloadTotp, ...twoFactor } as never),
...options,
})({ collections: [], secret: 'x', ...extra } as unknown as Config)
/** Keys of views that still point straight at the 2FA package: unguarded. */
const raw = (config: Config) =>
Object.entries(config.admin?.components?.views ?? {})
.filter(([, view]) => {
const c = (view as { Component?: { path?: string } | string }).Component
return (typeof c === 'string' ? c : (c?.path ?? '')).includes('payload-2fa')
})
.map(([key]) => key)
// The package replaces a view that already stands under one of its keys: such a key is not "the project's own".
test('a view the project had under a package key is replaced by the package, and guarded', async () => {
const config = await build({}, { admin: { components: { views: { SetupTOTPBackslash: { Component: 'mine#S', path: '/setup-totp' }, VerifyTOTP: { Component: 'mine#V', path: '/verify-totp' } } } } } as never)
expect(raw(config)).toEqual([])
expect(component(config, 'VerifyTOTP')?.path).toBe('@intecion/ipal-kit/admin#SafeTotpView')
expect(component(config, 'SetupTOTPBackslash')?.path).toBe('@intecion/ipal-kit/admin#SafeTotpView')
})
test('the package registered by the project too, before iapl: still guarded', async () => {
const first = payloadTotp({ collection: 'users', totp: { issuer: 'E' } } as never)({ collections: [{ slug: 'users', auth: true, fields: [] }], secret: 'x' } as never)
expect(raw(first).length).toBe(4)
expect(raw(await build({}, first as never))).toEqual([])
})
test('iapl run over its own output (a config reused): still guarded', async () => {
const once = await build({})
const twice = await build({}, { admin: once.admin } as never)
expect(raw(twice)).toEqual([])
expect(component(twice, 'VerifyTOTP')?.serverProps?.ipalTotpView).toBe('@clocklimited/payload-2fa/rsc#TOTPVerify')
})
test('the same incoming config object built twice', async () => {
const incoming = { admin: { components: { views: {} } }, collections: [], secret: 'x' } as unknown as Config
const plugin = () => iapl({ access: { authCollection: 'users' }, i18n, twoFactor: { issuer: 'E', plugin: payloadTotp } as never })(incoming)
expect(raw(await plugin())).toEqual([])
expect(raw(await plugin())).toEqual([])
})
test('safeBack: true, null or undefined is on; only false is off', async () => {
for (const value of [true, null, undefined]) {expect(raw(await build({ safeBack: value }))).toEqual([])}
expect(raw(await build({ safeBack: false })).length).toBe(4)
})
test('enabled: false leaves no views and no import-map dependencies behind', async () => {
const config = await build({}, { admin: { dependencies: { mine: { type: 'component', path: 'mine#Thing' } } }, collections: [{ slug: 'users', auth: true, fields: [] }] } as never, { enabled: false })
expect(JSON.stringify(config.admin?.components ?? {})).not.toMatch(/SafeTotp|payload-2fa/)
expect(config.admin?.dependencies).toEqual({ mine: { type: 'component', path: 'mine#Thing' } })
const bare = await build({}, { collections: [{ slug: 'users', auth: true, fields: [] }] } as never, { enabled: false })
expect(bare.admin?.dependencies).toBeUndefined()
})
const component = (config: Config, key: string) =>
(config.admin?.components?.views as Record } }> | 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 IAPL gives the screens is still there
expect((config.admin?.components?.views as Record).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).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 }) =>
React.createElement('p', { 'data-back': String(props.searchParams?.back), 'data-issuer': props.pluginOptions?.issuer, 'data-other': String(props.searchParams?.other) })
const render = (searchParams: Record, more: Record = {}, config: Record = { 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, '&')}"`)
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/)
})
})
// "Setup required" (requireSetup), the back-link check (safeBack) and IAPL's own check (guard) are separate
// switches: each combination builds, and each part is on exactly when its own switch says so.
describe('requireSetup x safeBack x guard', () => {
const combos = [undefined, false].flatMap((requireSetup) => [undefined, false].flatMap((safeBack) => [undefined, false].map((guard) => ({ guard, requireSetup, safeBack }))))
test.each(combos)('requireSetup: $requireSetup, safeBack: $safeBack, guard: $guard', async (options) => {
const config = await iapl({ access: { authCollection: 'users' }, i18n, twoFactor: { issuer: 'E', plugin: payloadTotpBeta7, ...options } as never })({ collections: [], secret: 'x' } as unknown as Config)
const views = Object.values(config.admin?.components?.views ?? {}) as { Component: { path?: string } | string; path: string }[]
const totpViews = views.filter((v) => /(?:setup|verify)-totp$/.test(v.path))
expect(totpViews).toHaveLength(4)
// the back-link check follows safeBack alone
const wrapped = totpViews.filter((v) => typeof v.Component === 'object' && v.Component.path === '@intecion/ipal-kit/admin#SafeTotpView').length
expect(wrapped).toBe(options.safeBack === false ? 0 : 4)
// setup required needs IAPL's own check; with either off there is no status field, hook or notice
const setupOn = options.requireSetup !== false && options.guard !== false
const users = config.collections?.find((c) => c.slug === 'users')
// the data field whenever 2FA is on (the schema does not follow the switches); the panel's status field with the mode
expect(Boolean(users?.fields.some((f) => 'name' in f && f.name === 'totpSetupFrom'))).toBe(true)
expect(Boolean(users?.fields.some((f) => 'name' in f && f.name === 'totpSetupStatus'))).toBe(setupOn)
// the administrator's reset (a lost phone) comes with IAPL's own check, also when setup is not required
expect(Boolean(config.endpoints?.some((e) => e.path === '/ipal/two-factor/reset'))).toBe(options.guard !== false)
const provider = JSON.stringify(config.admin?.components?.providers ?? [])
expect(provider.includes('"requireSetup":true')).toBe(setupOn)
expect(provider).toContain('TotpRedirectProvider')
const guardConfig = (config.custom as { ipal?: { twoFactor?: { requireSetup?: boolean } } } | undefined)?.ipal?.twoFactor
expect(Boolean(guardConfig)).toBe(options.guard !== false)
if (guardConfig) {expect(Boolean(guardConfig.requireSetup)).toBe(setupOn)}
})
})
describe('requireSetup.setupNotice', () => {
const providers = async (requireSetup?: Record) =>
JSON.stringify((await iapl({ access: { authCollection: 'users' }, i18n, twoFactor: { issuer: 'E', plugin: payloadTotpBeta7, requireSetup } as never })({ collections: [], secret: 'x' } as unknown as Config)).admin?.components?.providers ?? [])
test('on by default; false removes the notice, not the lock', async () => {
expect(await providers()).toContain('"requireSetup":true')
expect(await providers({ setupNotice: false })).not.toContain('"requireSetup":true')
const config = await iapl({ access: { authCollection: 'users' }, i18n, twoFactor: { issuer: 'E', plugin: payloadTotpBeta7, requireSetup: { setupNotice: false } } as never })({ collections: [], secret: 'x' } as unknown as Config)
expect((config.custom as { ipal: { twoFactor: { requireSetup: boolean } } }).ipal.twoFactor.requireSetup).toBe(true)
})
})
describe('a 2FA factory that hands back the same view objects on every call', () => {
const views = {
SetupTOTP: { Component: { path: 'pkg/rsc#TOTPSetup' }, path: 'setup-totp' },
VerifyTOTP: { Component: { path: 'pkg/rsc#TOTPVerify' }, path: 'verify-totp' },
}
const factory = (o: { collection: string }) => (c: Config) =>
withTotpParts({ ...c, admin: { ...c.admin, components: { ...c.admin?.components, views: { ...c.admin?.components?.views, ...views } } } } as Config, o.collection)
const build = (incoming: Partial = {}) =>
iapl({ access: { authCollection: 'users' }, i18n, twoFactor: { issuer: 'E', plugin: factory as never } })({ collections: [], secret: 'x', ...incoming } as unknown as Config)
const paths = (config: Config) => Object.values(config.admin?.components?.views ?? {}).map((v) => (v as { Component: { path: string } }).Component.path)
test('is guarded when registered once, twice, and over a config that already holds those objects', async () => {
expect(paths(await build())).toEqual(Array(2).fill('@intecion/ipal-kit/admin#SafeTotpView'))
const already = factory({ collection: 'users' })({ collections: [{ slug: 'users', auth: true, fields: [] }], secret: 'x' } as unknown as Config)
expect(paths(already)).toEqual(['pkg/rsc#TOTPSetup', 'pkg/rsc#TOTPVerify']) // raw, the very objects the factory returns again
expect(paths(await build(already))).toEqual(Array(2).fill('@intecion/ipal-kit/admin#SafeTotpView'))
expect(views.VerifyTOTP.Component.path).toBe('pkg/rsc#TOTPVerify') // the factory's own objects are not changed
})
})
describe('safeAdminBack with values that are not a string', () => {
test.each([[['/admin', 'javascript:1']], [{}], [null], [1], [{ toString: () => 'javascript:1' }]])('%s', (value) => {
expect(safeAdminBack(value as never, { adminRoute: '/admin' })).toBe('/admin')
})
})
describe('changedViewKeys', () => {
test('a key counts when its object is another one, whether or not the key existed', () => {
const kept = { path: '/a' }
expect([...changedViewKeys({ A: kept, B: { path: '/b' } }, { A: kept, B: { path: '/b' }, C: { path: '/c' } })].sort()).toEqual(['B', 'C'])
})
})
describe('SafeTotpView in front of a client component', () => {
// What a 'use client' export looks like on the server: a reference Payload must not hand server props to.
const ClientView = Object.assign(() => null, { $$typeof: Symbol.for('react.client.reference') })
const ServerView = () => null
const props = (view: unknown) => ({
clientConfig: { routes: { admin: '/admin' } },
i18n: { t: () => '' },
importMap: { 'mine/views#Verify': view },
initPageResult: { req: { payload: { config: { routes: { admin: '/admin' }, serverURL: '' } } } },
ipalTotpClientProps: { tone: 'dark' },
ipalTotpView: { exportName: 'Verify', path: 'mine/views' },
payload: { find: () => null },
pluginOptions: { adminManageAccess: () => true },
searchParams: { back: 'javascript:alert(1)', other: 'kept' },
viewType: 'verify',
})
const hasFunction = (value: unknown, seen = new Set()): boolean => {
if (typeof value === 'function') {return true}
if (!value || typeof value !== 'object' || seen.has(value)) {return false}
seen.add(value)
return Object.values(value).some((v) => hasFunction(v, seen))
}
const call = SafeTotpView as unknown as (p: unknown) => React.ReactElement>
test('gets only props that can cross to the browser, with the checked back', () => {
const element = call(props(ClientView))
expect(element.type).toBe(ClientView)
expect(hasFunction(element.props)).toBe(false) // a function prop is what crashed the screen with a 500
expect(element.props).toEqual({
back: '/admin',
clientConfig: { routes: { admin: '/admin' } },
searchParams: { back: '/admin', other: 'kept' },
tone: 'dark',
viewType: 'verify',
})
})
test('a server component still gets the server props', () => {
const element = call(props(ServerView))
expect(element.type).toBe(ServerView)
expect(typeof (element.props.pluginOptions as { adminManageAccess: unknown }).adminManageAccess).toBe('function')
expect(element.props.searchParams).toEqual({ back: '/admin', other: 'kept' })
expect(element.props.tone).toBe('dark')
expect(element.props.ipalTotpView).toBeUndefined()
})
})
describe('the stale import-map check', () => {
const ENTRY = '@intecion/ipal-kit/admin#SafeTotpView'
const project = async (layout: string, content: string) => {
const root = await mkdtemp(path.join(os.tmpdir(), 'ipal-importmap-'))
await mkdir(path.join(root, layout), { recursive: true })
await writeFile(path.join(root, layout, 'importMap.js'), content)
return root
}
test('finds the file where Payload looks: app/, src/app/, a custom admin route, an explicit file', async () => {
const a = await project('app/(payload)/admin', '')
const b = await project('src/app/(payload)/admin', '')
const c = await project('src/app/(payload)/panel', '')
try {
expect(await findImportMapFile({}, a)).toBe(path.join(a, 'app/(payload)/admin/importMap.js'))
expect(await findImportMapFile({ admin: { importMap: { baseDir: b } } }, '/nowhere')).toBe(path.join(b, 'src/app/(payload)/admin/importMap.js'))
expect(await findImportMapFile({ routes: { admin: '/panel' } }, c)).toBe(path.join(c, 'src/app/(payload)/panel/importMap.js'))
expect(await findImportMapFile({ routes: { admin: '/panel' } }, a)).toBeNull()
const explicit = path.join(a, 'app/(payload)/admin/importMap.js')
expect(await findImportMapFile({ admin: { importMap: { importMapFile: explicit } } }, '/nowhere')).toBe(explicit)
expect(await findImportMapFile({ admin: { importMap: { importMapFile: '/nowhere/importMap.js' } } }, a)).toBeNull()
} finally {
for (const dir of [a, b, c]) {await rm(dir, { force: true, recursive: true })}
}
})
test('in production iapl marks the redirect provider when the map lacks the wrapper; not otherwise', async () => {
const stale = await project('src/app/(payload)/admin', 'export const importMap = { "@intecion/ipal-kit/admin#TotpRedirectProvider": X }')
const current = await project('src/app/(payload)/admin', `export const importMap = { "${ENTRY}": Y }`)
const flagged = async (baseDir: string, twoFactor: Record = {}) => {
const config = await iapl({ access: { authCollection: 'users' }, i18n, twoFactor: { issuer: 'E', plugin: payloadTotpBeta7, ...twoFactor } as never })({
admin: { importMap: { baseDir } },
collections: [],
secret: 'x',
} as unknown as Config)
return JSON.stringify(config.admin?.components?.providers ?? []).includes('"staleImportMap":true')
}
const before = process.env.NODE_ENV
try {
vi.stubEnv('NODE_ENV', 'production')
expect(await flagged(stale)).toBe(true)
expect(await flagged(current)).toBe(false)
expect(await flagged('/nowhere')).toBe(false) // file not found: unknown, not reported
expect(await flagged(stale, { importMapCheck: false })).toBe(false)
expect(await flagged(stale, { safeBack: false })).toBe(false) // nothing wrapped, nothing needed
vi.stubEnv('NODE_ENV', 'development')
expect(await flagged(stale)).toBe(false) // Payload regenerates the map in development
} finally {
vi.unstubAllEnvs()
expect(process.env.NODE_ENV).toBe(before)
for (const dir of [stale, current]) {await rm(dir, { force: true, recursive: true })}
}
})
// The search reads text on disk: these maps work in the build and are still reported. That is why the result
// only ever adds a notice (test/totpRedirectProvider.test.ts) and the log line says "may be".
test('a map that re-exports, spreads or computes its keys is reported although it may be fine', async () => {
const maps = [
"export { importMap } from './generatedMap.js'",
"import { generated } from './generatedMap.js'\nexport const importMap = { ...generated }",
'export const importMap = { [`@intecion/ipal-kit/admin#${name}`]: X }',
'',
]
for (const content of maps) {
const root = await project('src/app/(payload)/admin', content)
try {
expect([content, (await missingImportMapEntries({}, [ENTRY], root)).missing]).toEqual([content, [ENTRY]])
} finally {
await rm(root, { force: true, recursive: true })
}
}
})
test('only IAPL\'s own redirect provider gets the flag, not a project\'s provider', async () => {
const stale = await project('src/app/(payload)/admin', 'export const importMap = {}')
const providers = async (provider?: unknown) => {
const config = await iapl({ access: { authCollection: 'users' }, i18n, twoFactor: { issuer: 'E', plugin: payloadTotpBeta7, provider } as never })({
admin: { importMap: { baseDir: stale } },
collections: [],
secret: 'x',
} as unknown as Config)
return JSON.stringify(config.admin?.components?.providers ?? [])
}
try {
vi.stubEnv('NODE_ENV', 'production')
expect(await providers()).toContain('"staleImportMap":true')
expect(await providers({ clientProps: { forceSetup: true }, path: '@/components/MyTotp#MyTotp' })).not.toContain('staleImportMap')
expect(await providers('@/components/MyTotp#MyTotp')).not.toContain('staleImportMap')
} finally {
vi.unstubAllEnvs()
await rm(stale, { force: true, recursive: true })
}
})
test('reports a missing entry, never an unknown state', async () => {
const stale = await project('src/app/(payload)/admin', 'export const importMap = { "@intecion/ipal-kit/admin#TotpRedirectProvider": X }')
const current = await project('src/app/(payload)/admin', `export const importMap = { "${ENTRY}": Y }`)
try {
expect((await missingImportMapEntries({}, [ENTRY], stale)).missing).toEqual([ENTRY])
expect((await missingImportMapEntries({}, [ENTRY], current)).missing).toEqual([])
expect(await missingImportMapEntries({}, [ENTRY], '/nowhere')).toEqual({ file: null, missing: [] })
} finally {
for (const dir of [stale, current]) {await rm(dir, { force: true, recursive: true })}
}
})
})