2FA back link: review fixes — views guarded by object, client views, a loud stale import map
SB-1: the 2FA package replaces a view that already stands under its keys, so a key that existed before the factory ran was wrongly treated as the project's own and left unguarded (also with a double registration, or ipalKit over its own output). Views are now compared by object, right after the factory. SB-2: SafeTotpView renders through Payload's RenderServerComponent: a client component set as a 2FA view gets only client props plus the checked back. SB-3: a production build with the previous import map shows an empty 2FA screen. twoFactor.importMapCheck (on, production only) reads the committed map at start: an error in the log and a message on the 2FA screens. Docs name the real symptom. SB-4: enabled: false restores admin.dependencies; wrapTotpViews keeps exportName. Co-Authored-By: Claude Fable 5.2 <[email protected]>
This commit is contained in:
co-authored by
Claude Fable 5.2
parent
93e75426ab
commit
ad51456eaa
+200
-5
@@ -1,13 +1,18 @@
|
||||
import type { Config } from 'payload'
|
||||
|
||||
import { payloadTotp } from '@clocklimited/payload-2fa'
|
||||
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 } from 'vitest'
|
||||
import { describe, expect, test, vi } from 'vitest'
|
||||
|
||||
import type { I18nConfig } from '../src/modules/i18n/types.js'
|
||||
|
||||
import { safeAdminBack, wrapTotpViews } from '../src/modules/security/totp/safeBack.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 { ipalKit } from '../src/plugin.js'
|
||||
|
||||
@@ -119,6 +124,15 @@ describe('wrapTotpViews', () => {
|
||||
})
|
||||
})
|
||||
|
||||
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)
|
||||
@@ -128,14 +142,68 @@ describe('wrapTotpViews', () => {
|
||||
})
|
||||
})
|
||||
|
||||
describe('ipalKit with the real 2FA package', () => {
|
||||
const build = (twoFactor: false | Record<string, unknown>, extra: Partial<Config> = {}) =>
|
||||
describe.each([
|
||||
['3.0.0-beta.7', payloadTotpBeta7],
|
||||
['3.0.0-beta.1', payloadTotpBeta1 as unknown as typeof payloadTotpBeta7],
|
||||
])('ipalKit with the real 2FA package %s', (_version, payloadTotp) => {
|
||||
const build = (twoFactor: false | Record<string, unknown>, extra: Partial<Config> = {}, options: Record<string, unknown> = {}) =>
|
||||
ipalKit({
|
||||
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 ipalKit: 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('ipalKit 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 = () => ipalKit({ 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<string, { Component: { path: string; serverProps?: Record<string, unknown> } }> | undefined)?.[key]?.Component
|
||||
|
||||
@@ -236,3 +304,130 @@ describe('SafeTotpView', () => {
|
||||
expect(() => render({}, { importMap: {} })).toThrow(/generate:importmap/)
|
||||
})
|
||||
})
|
||||
|
||||
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<unknown>()): 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<Record<string, unknown>>
|
||||
|
||||
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 ipalKit 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<string, unknown> = {}) => {
|
||||
const config = await ipalKit({ 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 })}
|
||||
}
|
||||
})
|
||||
|
||||
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 })}
|
||||
}
|
||||
})
|
||||
})
|
||||
|
||||
Reference in New Issue
Block a user