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
@@ -1,15 +1,18 @@
|
||||
import type { AdminViewServerProps } from 'payload'
|
||||
import type React from 'react'
|
||||
|
||||
import { RenderServerComponent } from '@payloadcms/ui/elements/RenderServerComponent'
|
||||
import { getFromImportMap } from 'payload/shared'
|
||||
import React from 'react'
|
||||
|
||||
import { safeAdminBack, type SafeBackRule } from './safeBack.js'
|
||||
import { safeAdminBack, type SafeBackRule, type TotpViewComponent, totpViewImportKey } from './safeBack.js'
|
||||
|
||||
export type SafeTotpViewProps = {
|
||||
/** `twoFactor.safeBack` as a function: replaces the default rule. */
|
||||
ipalSafeBack?: SafeBackRule
|
||||
/** Import-map path of the 2FA package's own view (`@clocklimited/payload-2fa/rsc#TOTPVerify`). */
|
||||
ipalTotpView: string
|
||||
/** `clientProps` of the view's own registration; passed on to it. */
|
||||
ipalTotpClientProps?: Record<string, unknown>
|
||||
/** The view to render, as registered: `'@clocklimited/payload-2fa/rsc#TOTPVerify'` or `{ path, exportName }`. */
|
||||
ipalTotpView: TotpViewComponent
|
||||
} & AdminViewServerProps
|
||||
|
||||
const originOf = (serverURL: unknown): string | undefined => {
|
||||
@@ -21,34 +24,47 @@ const originOf = (serverURL: unknown): string | undefined => {
|
||||
}
|
||||
}
|
||||
|
||||
/** What Payload itself hands a client view (AdminViewClientProps): all serializable. */
|
||||
const CLIENT_PROPS = ['browseByFolderSlugs', 'clientConfig', 'collectionSlug', 'docID', 'documentSubViewType', 'folderID', 'globalSlug', 'viewType'] as const
|
||||
|
||||
/**
|
||||
* In front of the 2FA package's setup and verify views: replaces the `back` query value with a
|
||||
* checked one (safeBack.ts) and renders the package's view with it. The package's form sends
|
||||
* the browser to `back` after a valid code, so what it receives must be safe to navigate to.
|
||||
* checked one (safeBack.ts) and renders the view with it. The package's form sends the browser
|
||||
* to `back` after a valid code, so what it receives must be safe to navigate to.
|
||||
*
|
||||
* ipalKit registers it (twoFactor.safeBack, on by default). A project that builds its own 2FA
|
||||
* screens can use it too: give it `ipalTotpView` and list that path in `admin.dependencies`.
|
||||
* The view is rendered the way Payload renders any view: a server component gets every server
|
||||
* prop, with `searchParams.back` checked; a client component (a project's own screen set through
|
||||
* the wrapped factory) gets only what can cross to the browser — Payload's client props, its own
|
||||
* `clientProps`, `searchParams` and `back`, both checked.
|
||||
*
|
||||
* ipalKit registers it (twoFactor.safeBack, on by default). A project that registers 2FA views
|
||||
* itself can use it too: `wrapTotpViews`, or give it `ipalTotpView` and list that path in
|
||||
* `admin.dependencies`.
|
||||
*/
|
||||
export function SafeTotpView(props: SafeTotpViewProps): React.ReactNode {
|
||||
const { ipalSafeBack, ipalTotpView, ...rest } = props
|
||||
const { ipalSafeBack, ipalTotpClientProps, ipalTotpView, ...rest } = props
|
||||
const config = props.initPageResult?.req?.payload?.config ?? props.payload?.config
|
||||
const raw = (props.searchParams as Record<string, unknown> | undefined)?.back
|
||||
const back = (ipalSafeBack ?? safeAdminBack)(typeof raw === 'string' ? raw : undefined, {
|
||||
const query = (props.searchParams ?? {}) as Record<string, unknown>
|
||||
const back = (ipalSafeBack ?? safeAdminBack)(typeof query.back === 'string' ? query.back : undefined, {
|
||||
adminRoute: config?.routes?.admin ?? '/admin',
|
||||
origin: originOf(config?.serverURL),
|
||||
})
|
||||
const searchParams = { ...query, back }
|
||||
|
||||
const View = getFromImportMap<React.ComponentType<Record<string, unknown>>>({
|
||||
importMap: props.importMap,
|
||||
PayloadComponent: ipalTotpView,
|
||||
schemaPath: '',
|
||||
silent: true,
|
||||
})
|
||||
if (!View) {
|
||||
if (!getFromImportMap({ importMap: props.importMap, PayloadComponent: ipalTotpView, schemaPath: '', silent: true })) {
|
||||
throw new Error(
|
||||
`[ipal] The admin import map has no "${ipalTotpView}" (the 2FA screen ipal-kit puts its back-link check in front of). ` +
|
||||
`[ipal] The admin import map has no "${totpViewImportKey(ipalTotpView)}" (the 2FA screen ipal-kit puts its back-link check in front of). ` +
|
||||
'Run `pnpm payload generate:importmap` and commit the result.',
|
||||
)
|
||||
}
|
||||
return <View {...rest} searchParams={{ ...props.searchParams, back }} />
|
||||
const clientProps: Record<string, unknown> = { ...ipalTotpClientProps, back, searchParams }
|
||||
for (const key of CLIENT_PROPS) {
|
||||
if (key in rest) {clientProps[key] = (rest as Record<string, unknown>)[key]}
|
||||
}
|
||||
return RenderServerComponent({
|
||||
clientProps,
|
||||
Component: ipalTotpView,
|
||||
importMap: props.importMap,
|
||||
serverProps: { ...rest, searchParams },
|
||||
})
|
||||
}
|
||||
|
||||
@@ -2,7 +2,7 @@
|
||||
|
||||
import type { ReactNode } from 'react'
|
||||
|
||||
import { useAuth, useConfig } from '@payloadcms/ui'
|
||||
import { useAuth, useConfig, useTranslation } from '@payloadcms/ui'
|
||||
import { usePathname, useRouter } from 'next/navigation.js'
|
||||
import { useEffect } from 'react'
|
||||
|
||||
@@ -14,6 +14,22 @@ export type TotpRedirectProviderProps = {
|
||||
children?: ReactNode
|
||||
/** pluginOptions.forceSetup — set by the plugin (true: 2FA is enforced). */
|
||||
forceSetup?: boolean
|
||||
/**
|
||||
* Set by the plugin when the committed admin import map lacks the 2FA view wrapper
|
||||
* (importMapCheck.ts): the 2FA screens would be empty, so they say what is wrong instead.
|
||||
*/
|
||||
staleImportMap?: boolean
|
||||
}
|
||||
|
||||
const STALE_TEXT = {
|
||||
en: {
|
||||
body: 'The site was deployed without a refreshed admin import map, so this screen cannot load and nobody can sign in. A developer has to run "pnpm payload generate:importmap", commit importMap.js and deploy again.',
|
||||
title: 'Two-step verification is not available',
|
||||
},
|
||||
pl: {
|
||||
body: 'Strona została wdrożona bez odświeżonej mapy importów panelu, więc ten ekran nie może się załadować i nikt nie może się zalogować. Programista musi uruchomić "pnpm payload generate:importmap", zapisać importMap.js w repozytorium i wdrożyć stronę ponownie.',
|
||||
title: 'Weryfikacja dwuetapowa jest niedostępna',
|
||||
},
|
||||
}
|
||||
|
||||
/**
|
||||
@@ -24,8 +40,9 @@ export type TotpRedirectProviderProps = {
|
||||
* Renders nothing while a redirect is pending, so the panel does not flash.
|
||||
* Swap it with `twoFactor.provider`.
|
||||
*/
|
||||
export function TotpRedirectProvider({ children, forceSetup = true }: TotpRedirectProviderProps) {
|
||||
export function TotpRedirectProvider({ children, forceSetup = true, staleImportMap = false }: TotpRedirectProviderProps) {
|
||||
const { user } = useAuth()
|
||||
const { i18n } = useTranslation()
|
||||
const { config } = useConfig()
|
||||
const pathname = usePathname()
|
||||
const router = useRouter()
|
||||
@@ -42,7 +59,17 @@ export function TotpRedirectProvider({ children, forceSetup = true }: TotpRedire
|
||||
if (target) {router.replace(target)}
|
||||
}, [router, target])
|
||||
|
||||
return target ? null : children
|
||||
if (target) {return null}
|
||||
if (staleImportMap && user && /\/(?:setup|verify)-totp\/?$/.test(pathname ?? '')) {
|
||||
const text = STALE_TEXT[i18n.language?.toLowerCase().startsWith('pl') ? 'pl' : 'en']
|
||||
return (
|
||||
<div role="alert" style={{ margin: '15vh auto 0', maxWidth: '36rem', padding: '0 1.5rem' }}>
|
||||
<h1 style={{ fontSize: '1.5rem', marginBottom: '1rem' }}>{text.title}</h1>
|
||||
<p>{text.body}</p>
|
||||
</div>
|
||||
)
|
||||
}
|
||||
return children
|
||||
}
|
||||
|
||||
export default TotpRedirectProvider
|
||||
|
||||
@@ -0,0 +1,49 @@
|
||||
/**
|
||||
* Is the project's committed admin import map older than the config?
|
||||
*
|
||||
* ipalKit registers `SafeTotpView` in front of the 2FA screens. Payload resolves view components
|
||||
* through the import map file, and a path that is not in it renders NOTHING: the 2FA screen comes
|
||||
* back empty (HTTP 200, no code form), so nobody can sign in — after an upgrade where
|
||||
* `pnpm payload generate:importmap` was forgotten. In development Payload regenerates the file
|
||||
* by itself; a production build uses the committed one. This check makes that state loud: an
|
||||
* error in the server log at start, and a message on the 2FA screens (TotpRedirectProvider).
|
||||
* `twoFactor.importMapCheck: false` turns it off.
|
||||
*/
|
||||
type ConfigLike = { admin?: { importMap?: { baseDir?: string; importMapFile?: string } }; routes?: { admin?: string } }
|
||||
|
||||
/** The file Payload reads the import map from — the same places Payload itself looks in. Null when not found. */
|
||||
export async function findImportMapFile(config: ConfigLike, cwd = process.cwd()): Promise<null | string> {
|
||||
try {
|
||||
const fs = await import('node:fs/promises')
|
||||
const path = await import('node:path')
|
||||
const exists = (file: string) => fs.access(file).then(() => true, () => false)
|
||||
const explicit = config.admin?.importMap?.importMapFile
|
||||
if (explicit) {return (await exists(explicit)) ? explicit : null}
|
||||
const rootDir = config.admin?.importMap?.baseDir ?? cwd
|
||||
// Next.js writes %5F for route segments that begin with an underscore
|
||||
const adminFolder = (config.routes?.admin ?? '/admin').replace(/(^|\/)_/g, '$1%5F')
|
||||
for (const base of [`app/(payload)${adminFolder}`, `src/app/(payload)${adminFolder}`]) {
|
||||
const file = path.resolve(rootDir, base, 'importMap.js')
|
||||
if (await exists(file)) {return file}
|
||||
}
|
||||
} catch {
|
||||
/* no file system (or not Node): nothing to check */
|
||||
}
|
||||
return null
|
||||
}
|
||||
|
||||
/**
|
||||
* The entries of `needed` that the import map file lacks. An empty list also when the file is
|
||||
* not found or cannot be read: an unknown state is never reported as a problem.
|
||||
*/
|
||||
export async function missingImportMapEntries(config: ConfigLike, needed: string[], cwd?: string): Promise<{ file: null | string; missing: string[] }> {
|
||||
const file = await findImportMapFile(config, cwd)
|
||||
if (!file) {return { file: null, missing: [] }}
|
||||
try {
|
||||
const fs = await import('node:fs/promises')
|
||||
const text = await fs.readFile(file, 'utf8')
|
||||
return { file, missing: needed.filter((entry) => !text.includes(`"${entry}"`) && !text.includes(`'${entry}'`)) }
|
||||
} catch {
|
||||
return { file, missing: [] }
|
||||
}
|
||||
}
|
||||
@@ -75,42 +75,60 @@ export const safeAdminBack: SafeBackRule = (back, { adminRoute, origin }) => {
|
||||
/** 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 }
|
||||
/** Import-map path of the wrapper ipalKit registers. */
|
||||
export const SAFE_TOTP_VIEW = '@intecion/ipal-kit/admin#SafeTotpView'
|
||||
|
||||
/** Key of the import-map entry that keeps the package's own view importable. */
|
||||
export const totpViewDependencyKey = (path: string) => `ipal-totp-view:${path}`
|
||||
/** A view component as it stands in a Payload config. */
|
||||
export type TotpViewComponent = { clientProps?: object; exportName?: string; path: string; serverProps?: object } | string
|
||||
type ViewLike = { Component?: unknown; path?: string }
|
||||
type Dependency = { exportName?: string; path: string; type: 'component' }
|
||||
|
||||
/** `path#export` of a component — the key it has in the import map. */
|
||||
export const totpViewImportKey = (component: TotpViewComponent): string => {
|
||||
const [path, hash] = (typeof component === 'string' ? component : component.path).split('#')
|
||||
const exportName = (typeof component === 'object' ? component.exportName : undefined) ?? hash ?? 'default'
|
||||
return `${path}#${exportName}`
|
||||
}
|
||||
|
||||
/** Key of the `admin.dependencies` entry that keeps a wrapped view importable. */
|
||||
export const totpViewDependencyKey = (component: TotpViewComponent) => `ipal-totp-view:${totpViewImportKey(component)}`
|
||||
|
||||
/**
|
||||
* 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.
|
||||
* Puts ipal-kit's wrapper in front of the 2FA views for which `added(key)` is true and whose
|
||||
* route is `setup-totp` / `verify-totp`: the wrapper cleans `back` and renders the original
|
||||
* view, which it finds in the import map (`admin.dependencies` keeps it there). ipal-kit still
|
||||
* never imports the optional package. The original's `serverProps` stay server props; its
|
||||
* `clientProps` travel as `ipalTotpClientProps`, so the wrapper can hand them to a client view.
|
||||
*/
|
||||
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' }> = {}
|
||||
wrapper = SAFE_TOTP_VIEW,
|
||||
): { dependencies: Record<string, Dependency>; views: Record<string, V> } {
|
||||
const dependencies: Record<string, Dependency> = {}
|
||||
const out: Record<string, V> = {}
|
||||
for (const [key, view] of Object.entries(views)) {
|
||||
const component = view?.Component as undefined | ViewComponent
|
||||
const component = view?.Component as TotpViewComponent | undefined
|
||||
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) {
|
||||
if (!added(key) || !view || typeof view.path !== 'string' || !TOTP_VIEW_PATH.test(view.path) || !component || !path || path === wrapper) {
|
||||
out[key] = view
|
||||
continue
|
||||
}
|
||||
dependencies[totpViewDependencyKey(path)] = { type: 'component', path }
|
||||
const own = typeof component === 'object' ? component : undefined
|
||||
const original = own?.exportName ? { exportName: own.exportName, path } : path
|
||||
dependencies[totpViewDependencyKey(component)] = { type: 'component', ...(own?.exportName ? { exportName: own.exportName } : {}), path }
|
||||
out[key] = {
|
||||
...view,
|
||||
Component: {
|
||||
...(own?.clientProps ? { clientProps: own.clientProps } : {}),
|
||||
path: wrapper,
|
||||
serverProps: { ...own?.serverProps, ipalSafeBack: rule, ipalTotpView: path },
|
||||
serverProps: { ...own?.serverProps, ipalSafeBack: rule, ipalTotpClientProps: own?.clientProps, ipalTotpView: original },
|
||||
},
|
||||
}
|
||||
}
|
||||
return { dependencies, views: out }
|
||||
}
|
||||
|
||||
/** Keys whose view object is not the one in `before` — what a plugin added or replaced. */
|
||||
export const changedViewKeys = (before: Record<string, unknown>, after: Record<string, unknown>): Set<string> =>
|
||||
new Set(Object.keys(after).filter((key) => after[key] !== before[key]))
|
||||
|
||||
Reference in New Issue
Block a user