2FA back link: the stale import-map notice never replaces the screen
R2-1: the notice was rendered instead of the 2FA screen, and its flag is a text search of the importMap.js on disk — not the map in the build. A false alarm (map generated in the build with the repository's file in the running image, a re-exporting map) hid a working code form and locked everyone out. The notice is now rendered above the screen, the log line says "may be", and the flag goes to ipal-kit's own provider only. R2-2: views are compared against copies, so a factory that reuses its view objects is guarded too; copyViews, changedViewKeys, SAFE_TOTP_VIEW, totpViewImportKey, findImportMapFile and missingImportMapEntries are exported; ipal-doctor warns when the config registers the 2FA package's own view; docs wording and a misplaced comment fixed. Co-Authored-By: Claude Fable 5.2 <[email protected]>
This commit is contained in:
co-authored by
Claude Fable 5.2
parent
ad51456eaa
commit
b2c1dca5da
@@ -51,6 +51,35 @@ afterEach(() => {
|
||||
vi.unstubAllEnvs()
|
||||
})
|
||||
|
||||
describe('importmap rule and the 2FA back-link check', () => {
|
||||
const MAP = 'src/app/(payload)/admin/importMap.js'
|
||||
const entries = (...names: string[]) => `export const importMap = { ${names.map((n) => `"${n}": X`).join(', ')} }`
|
||||
const withPlugin = (admin: string) => ({ ...base(), ...installed('@clocklimited/payload-2fa', '3.0.0'), 'node_modules/@intecion/ipal-kit/dist/exports/admin.js': admin })
|
||||
const messages = (report: DoctorReport) => report.findings.filter((f) => f.rule === 'importmap').map((f) => `${f.severity}: ${f.message}`)
|
||||
|
||||
test('expects SafeTotpView when the installed plugin has it; not with safeBack: false; not for an older plugin', async () => {
|
||||
const map = entries('@clocklimited/payload-2fa/rsc#TOTPSetup', '@intecion/ipal-kit/admin#TotpRedirectProvider')
|
||||
const admin = 'export { SafeTotpView } from "./x.js"; export { TotpRedirectProvider } from "./y.js"'
|
||||
const lacking = await doctor(project({ ...withPlugin(admin), [MAP]: map, 'src/payload.config.ts': 'twoFactor: { plugin: payloadTotp }' }), ['importmap'])
|
||||
expect(messages(lacking).join()).toContain('import map lacks @intecion/ipal-kit/admin#SafeTotpView')
|
||||
const off = await doctor(project({ ...withPlugin(admin), [MAP]: map, 'src/payload.config.ts': 'twoFactor: { plugin: payloadTotp, safeBack: false }' }), ['importmap'])
|
||||
expect(messages(off).join()).not.toContain('SafeTotpView')
|
||||
const older = await doctor(project({ ...withPlugin('export { TotpRedirectProvider } from "./y.js"'), [MAP]: map, 'src/payload.config.ts': 'twoFactor: { plugin: payloadTotp }' }), ['importmap'])
|
||||
expect(messages(older).join()).not.toContain('SafeTotpView')
|
||||
})
|
||||
|
||||
test("warns when the config registers the 2FA package's own view itself", async () => {
|
||||
const map = entries('@clocklimited/payload-2fa/rsc#TOTPSetup', '@intecion/ipal-kit/admin#TotpRedirectProvider', '@intecion/ipal-kit/admin#SafeTotpView')
|
||||
const admin = 'export { SafeTotpView } from "./x.js"; export { TotpRedirectProvider } from "./y.js"'
|
||||
const own = "twoFactor: { plugin: payloadTotp }, admin: { components: { views: { Mine: { Component: '@clocklimited/payload-2fa/rsc#TOTPVerify', path: '/my-verify' } } } }"
|
||||
const raw = await doctor(project({ ...withPlugin(admin), [MAP]: map, 'src/payload.config.ts': own }), ['importmap'])
|
||||
const NOTE = /^warning: the config names the 2FA package's own setup \/ verify view/
|
||||
expect(messages(raw).filter((m) => NOTE.test(m))).toHaveLength(1)
|
||||
const plain = await doctor(project({ ...withPlugin(admin), [MAP]: map, 'src/payload.config.ts': 'twoFactor: { plugin: payloadTotp }' }), ['importmap'])
|
||||
expect(messages(plain).filter((m) => NOTE.test(m))).toEqual([])
|
||||
})
|
||||
})
|
||||
|
||||
describe('helpers', () => {
|
||||
test('parseEnvFile reads KEY=value, strips quotes, skips comments', () => {
|
||||
expect(parseEnvFile('# c\nA=1\nexport B="two"\n C = \'3\'\nbad line')).toEqual({ A: '1', B: 'two', C: '3' })
|
||||
|
||||
@@ -15,6 +15,7 @@ import { findImportMapFile, missingImportMapEntries } from '../src/modules/secur
|
||||
import { changedViewKeys, safeAdminBack, wrapTotpViews } from '../src/modules/security/totp/safeBack.js'
|
||||
import { SafeTotpView } from '../src/modules/security/totp/SafeTotpView.js'
|
||||
import { ipalKit } from '../src/plugin.js'
|
||||
import { withTotpParts } from './helpers.js'
|
||||
|
||||
const i18n: I18nConfig = { defaultLocale: 'en', locales: [{ code: 'en', label: 'English' }] }
|
||||
const admin = { adminRoute: '/admin' }
|
||||
@@ -305,6 +306,26 @@ describe('SafeTotpView', () => {
|
||||
})
|
||||
})
|
||||
|
||||
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<Config> = {}) =>
|
||||
ipalKit({ 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')
|
||||
@@ -419,6 +440,46 @@ describe('the stale import-map check', () => {
|
||||
}
|
||||
})
|
||||
|
||||
// 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 ipal-kit\'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 ipalKit({ 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 }`)
|
||||
|
||||
@@ -0,0 +1,67 @@
|
||||
import React from 'react'
|
||||
import { renderToStaticMarkup } from 'react-dom/server'
|
||||
import { beforeEach, describe, expect, test, vi } from 'vitest'
|
||||
|
||||
/**
|
||||
* The stale-import-map notice of TotpRedirectProvider. The flag behind it is a guess (a text search of the
|
||||
* importMap.js on disk, not the map in the bundle), so the notice is shown NEXT TO the screen: a wrong guess
|
||||
* must never take the code form away.
|
||||
*/
|
||||
const state = { language: 'en', pathname: '/admin/verify-totp', user: { _strategy: 'local-jwt', hasTotp: true } as null | Record<string, unknown> }
|
||||
|
||||
vi.mock('@payloadcms/ui', () => ({
|
||||
useAuth: () => ({ user: state.user }),
|
||||
useConfig: () => ({ config: { admin: { routes: {} }, routes: { admin: '/admin' } } }),
|
||||
useTranslation: () => ({ i18n: { language: state.language } }),
|
||||
}))
|
||||
vi.mock('next/navigation.js', () => ({ usePathname: () => state.pathname, useRouter: () => ({ replace: () => undefined }) }))
|
||||
|
||||
const { TotpRedirectProvider } = await import('../src/modules/security/totp/TotpRedirectProvider.js')
|
||||
|
||||
const FORM = '<form id="code-form"><input/></form>'
|
||||
const form = () => React.createElement('form', { id: 'code-form' }, React.createElement('input'))
|
||||
const render = (props: Record<string, unknown> = {}, children: React.ReactNode = form()) =>
|
||||
renderToStaticMarkup(React.createElement(TotpRedirectProvider, props, children))
|
||||
|
||||
beforeEach(() => {
|
||||
Object.assign(state, { language: 'en', pathname: '/admin/verify-totp', user: { _strategy: 'local-jwt', hasTotp: true } })
|
||||
})
|
||||
|
||||
describe('TotpRedirectProvider with staleImportMap', () => {
|
||||
// Reviewer repro 1: the build is current, but the importMap.js on disk is an older one → the flag is wrong.
|
||||
// Reviewer repro 2: the map file re-exports the generated map → the text search finds nothing → the flag is wrong.
|
||||
// In both the screen works, and must stay on the page.
|
||||
test('a false alarm: the working code form is still rendered, with the notice above it', () => {
|
||||
const html = render({ staleImportMap: true })
|
||||
expect(html).toContain(FORM)
|
||||
expect(html).toContain('role="alert"')
|
||||
expect(html).toContain('may not be available')
|
||||
expect(html.indexOf('role="alert"')).toBeLessThan(html.indexOf('code-form'))
|
||||
})
|
||||
|
||||
test('a really stale map: Payload renders nothing for the screen, the notice is what the user sees', () => {
|
||||
const html = render({ staleImportMap: true }, null)
|
||||
expect(html).toContain('role="alert"')
|
||||
expect(html).toContain('pnpm payload generate:importmap')
|
||||
})
|
||||
|
||||
test('the setup screen too; Polish for a Polish panel', () => {
|
||||
Object.assign(state, { language: 'pl', pathname: '/admin/setup-totp', user: { _strategy: 'local-jwt', hasTotp: false } })
|
||||
const html = render({ staleImportMap: true })
|
||||
expect(html).toContain('Weryfikacja dwuetapowa może być niedostępna')
|
||||
expect(html).toContain(FORM)
|
||||
})
|
||||
|
||||
test('no notice without the flag, on other pages, or for a visitor', () => {
|
||||
expect(render({})).toBe(FORM)
|
||||
Object.assign(state, { pathname: '/admin/collections/pages', user: { _strategy: 'totp', hasTotp: true } })
|
||||
expect(render({ staleImportMap: true })).toBe(FORM)
|
||||
Object.assign(state, { pathname: '/admin/verify-totp', user: null })
|
||||
expect(render({ staleImportMap: true })).toBe(FORM)
|
||||
})
|
||||
|
||||
test('a pending redirect still renders nothing', () => {
|
||||
Object.assign(state, { pathname: '/admin/collections/pages', user: { _strategy: 'local-jwt', hasTotp: true } })
|
||||
expect(render({ staleImportMap: true })).toBe('')
|
||||
})
|
||||
})
|
||||
Reference in New Issue
Block a user