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:
Radosław Smoliński
2026-11-24 16:35:16 +01:00
co-authored by Claude Fable 5.2
parent ad51456eaa
commit b2c1dca5da
23 changed files with 315 additions and 66 deletions
+3 -2
View File
@@ -327,8 +327,9 @@ export type {
} from './modules/security/index.js'
export type { BuildSecurityHeadersArgs, SecurityHeader } from './modules/security/index.js'
export { safeAdminBack, wrapTotpViews } from './modules/security/totp/safeBack.js'
export type { SafeBackContext, SafeBackRule } from './modules/security/totp/safeBack.js'
export { findImportMapFile, missingImportMapEntries } from './modules/security/totp/importMapCheck.js'
export { changedViewKeys, copyViews, SAFE_TOTP_VIEW, safeAdminBack, totpViewImportKey, wrapTotpViews } from './modules/security/totp/safeBack.js'
export type { SafeBackContext, SafeBackRule, TotpViewComponent } from './modules/security/totp/safeBack.js'
export { requireSecondFactor, secondFactorPassed } from './modules/security/totp/secondFactor.js'
export { TOTP_TEXTS, TOTP_VIEW_TITLE } from './modules/security/totp/totpTexts.js'
export type { VerifyLimitOptions } from './modules/security/totp/verifyLimit.js'
+9
View File
@@ -203,6 +203,15 @@ export const layoutRules: DoctorRule[] = [
need.push('@intecion/ipal-kit/admin#SafeTotpView')
}
}
// A view the project registers itself with the 2FA package's own component is not behind the back-link check.
if (/@clocklimited\/payload-2fa\/rsc#TOTP(?:Setup|Verify)/.test(cfg)) {
out.push({
file: configFile(ctx) ?? undefined,
fix: "register it through wrapTotpViews (or Component: { path: '@intecion/ipal-kit/admin#SafeTotpView', serverProps: { ipalTotpView: '<that path>' } } plus the path in admin.dependencies) — security.md \"Your own 2FA screen\"",
message: "the config names the 2FA package's own setup / verify view: a view registered that way sends the browser to an unchecked `back` link after the code",
severity: 'warning',
})
}
if (/buildR2Storage/.test(cfg)) {need.push('S3ClientUploadHandler')}
if (/cookieScanner\s*:\s*(?!false)/.test(cfg) && !lt(v, '1.14.4')) {need.push('@intecion/ipal-kit/admin#CookieReviewTab')}
if (!lt(v, '1.14.5') && !/adminMeta\s*:\s*false/.test(cfg)) {need.push('@intecion/ipal-kit/admin#AdminIcon')}
@@ -15,20 +15,22 @@ export type TotpRedirectProviderProps = {
/** 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.
* Set by the plugin when the admin import map on disk lacks the 2FA view wrapper
* (importMapCheck.ts). The 2FA screens are then probably empty, so a notice says what is
* wrong. The screen itself is still rendered: the check is a guess, and a wrong guess must
* cost a wrong notice at most, never the code form.
*/
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',
body: 'If there is no place to enter the code on this page, the site was deployed without a refreshed admin import map. A developer has to run "pnpm payload generate:importmap", commit importMap.js and deploy again.',
title: 'Two-step verification may not be 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',
body: 'Jeśli na tej stronie nie ma miejsca na wpisanie kodu, strona została wdrożona bez odświeżonej mapy importów panelu. Programista musi uruchomić "pnpm payload generate:importmap", zapisać importMap.js w repozytorium i wdrożyć stronę ponownie.',
title: 'Weryfikacja dwuetapowa może być niedostępna',
},
}
@@ -63,10 +65,13 @@ export function TotpRedirectProvider({ children, forceSetup = true, staleImportM
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>
<>
<div role="alert" style={{ margin: '2rem auto 0', maxWidth: '36rem', padding: '0 1.5rem' }}>
<p style={{ fontWeight: 600, marginBottom: '0.5rem' }}>{text.title}</p>
<p>{text.body}</p>
</div>
{children}
</>
)
}
return children
+11 -4
View File
@@ -6,8 +6,9 @@
* 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.
* error in the server log at start, and a notice on the 2FA screens (TotpRedirectProvider) —
* shown next to the screen, never instead of it, because the check can be wrong (see
* `missingImportMapEntries`). `twoFactor.importMapCheck: false` turns it off.
*/
type ConfigLike = { admin?: { importMap?: { baseDir?: string; importMapFile?: string } }; routes?: { admin?: string } }
@@ -33,8 +34,14 @@ export async function findImportMapFile(config: ConfigLike, cwd = process.cwd())
}
/**
* 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.
* The entries of `needed` that are not written in the import map file. An empty list when the
* file is not found or cannot be read.
*
* This is a text search of the file ON DISK, and a hint, not a fact: the map the running build
* uses is in the bundle. The two differ when the map is generated inside the build and the
* running image carries the repository's file (a Dockerfile runner stage with its own COPY), and
* the search misses a map that re-exports or builds its keys another way. So a caller may warn
* on the result, and must never block on it.
*/
export async function missingImportMapEntries(config: ConfigLike, needed: string[], cwd?: string): Promise<{ file: null | string; missing: string[] }> {
const file = await findImportMapFile(config, cwd)
+14 -1
View File
@@ -129,6 +129,19 @@ export function wrapTotpViews<V extends ViewLike>(
return { dependencies, views: out }
}
/** Keys whose view object is not the one in `before` — what a plugin added or replaced. */
/**
* Shallow copies of a config's views. Put these into the config BEFORE calling a 2FA factory and
* keep them as `before` for `changedViewKeys`: a view the factory registers is then never the
* same object as one that was there, also when the factory reuses its view objects between calls.
*/
export const copyViews = <V>(views: Record<string, V> | undefined): Record<string, V> =>
Object.fromEntries(Object.entries(views ?? {}).map(([key, view]) => [key, view && typeof view === 'object' ? { ...view } : view]))
/**
* Keys whose view object is not the one in `before` — what a plugin added or replaced.
* `added` for `wrapTotpViews`: `const before = copyViews(views)` → run the factory on a config
* holding `before` → `const keys = changedViewKeys(before, viewsAfter)` → `(key) => keys.has(key)`.
* A key alone says nothing: the 2FA package replaces a view that already stands under its keys.
*/
export const changedViewKeys = (before: Record<string, unknown>, after: Record<string, unknown>): Set<string> =>
new Set(Object.keys(after).filter((key) => after[key] !== before[key]))
+19 -9
View File
@@ -34,7 +34,7 @@ import { withFillLocales } from './modules/hooks/fillEmptyLocales.js'
import { buildLocalizationConfig, validateI18nConfig } from './modules/i18n/index.js'
import { buildSystemPagesFields } from './modules/pages/index.js'
import { missingImportMapEntries } from './modules/security/totp/importMapCheck.js'
import { changedViewKeys, SAFE_TOTP_VIEW, wrapTotpViews } from './modules/security/totp/safeBack.js'
import { changedViewKeys, copyViews, SAFE_TOTP_VIEW, wrapTotpViews } from './modules/security/totp/safeBack.js'
import {
buildGuardStrategy,
ensurePayloadGuarded,
@@ -56,6 +56,8 @@ import { buildStatsCollection, buildStatsEndpoint } from './modules/stats/index.
/** The admin provider @clocklimited/payload-2fa registers; ipal-kit swaps it (twoFactor.provider). */
const TOTP_PACKAGE_PROVIDER = '@clocklimited/payload-2fa/rsc#TOTPProvider'
/** ipal-kit's own redirect provider (twoFactor.provider default). */
const TOTP_REDIRECT_PROVIDER = '@intecion/ipal-kit/admin#TotpRedirectProvider'
/**
* IPAL (Intecion Payload Advanced Library) plugin for Payload CMS 3.
@@ -233,7 +235,12 @@ export const ipalKit = (options: IpalOptions): Plugin => {
)
}
const endpointsBefore = new Set(config.endpoints ?? [])
const viewsBefore: Record<string, unknown> = { ...config.admin?.components?.views }
// Copies, so that a view the 2FA factory hands back is told apart from one it left alone
// even when the factory returns the very same objects on every call.
const viewsBefore = copyViews(config.admin?.components?.views)
if (config.admin?.components?.views) {
config.admin = { ...config.admin, components: { ...config.admin.components, views: viewsBefore as never } }
}
const entityEndpointsBefore = new Map<string, Set<unknown>>(
[...(config.collections ?? []), ...(config.globals ?? [])].map((e) => [e.slug, new Set<unknown>(Array.isArray(e.endpoints) ? e.endpoints : [])]),
)
@@ -325,7 +332,7 @@ export const ipalKit = (options: IpalOptions): Plugin => {
if (tf.provider !== false) {
const custom = tf.provider
const ours =
typeof custom === 'object' ? custom : { path: custom ?? '@intecion/ipal-kit/admin#TotpRedirectProvider' }
typeof custom === 'object' ? custom : { path: custom ?? TOTP_REDIRECT_PROVIDER }
const providers = config.admin?.components?.providers ?? []
config.admin = {
...config.admin,
@@ -365,17 +372,19 @@ export const ipalKit = (options: IpalOptions): Plugin => {
// A production build with the import map of the previous version shows an EMPTY 2FA
// screen (Payload renders nothing for a path the map lacks): say so, in the log at
// start and on the screen itself (importMapCheck.ts). Development regenerates the map.
// The check reads the file on disk, which need not be the map in the bundle — so it
// only ever ADDS a notice; the screen itself is rendered as usual.
if (tf.importMapCheck !== false && process.env.NODE_ENV === 'production') {
const stale = await missingImportMapEntries(config, [SAFE_TOTP_VIEW])
if (stale.missing.length) {
staleImportMap = `${stale.missing.join(', ')} is not in ${stale.file}`
staleImportMap = `${stale.missing.join(', ')} was not found in ${stale.file}`
const providers = config.admin?.components?.providers ?? []
config.admin = {
...config.admin,
components: {
...config.admin?.components,
providers: providers.map((p) =>
p && typeof p === 'object' && (p.clientProps as { forceSetup?: boolean } | undefined)?.forceSetup !== undefined
p && typeof p === 'object' && p.path === TOTP_REDIRECT_PROVIDER // ipal-kit's own provider only
? { ...p, clientProps: { ...p.clientProps, staleImportMap: true } }
: p,
),
@@ -752,14 +761,15 @@ export const ipalKit = (options: IpalOptions): Plugin => {
adoptConfig(payload)
// Payload's dev reload swaps `payload.config` and runs no onInit: adopt the new config at once.
watchPayloadConfig(payload, adoptConfig)
// Staff whose collection is not the 2FA collection log in without a second factor: say so.
if (staleImportMap) {
payload.logger.error(
`[ipal] The admin import map is out of date: ${staleImportMap}. The 2FA setup and verify screens are EMPTY ` +
'until it is regenerated, so nobody can sign in to the panel. Run `pnpm payload generate:importmap`, commit ' +
'importMap.js, rebuild and redeploy (docs/security.md "The `back` link of the 2FA screens").',
`[ipal] The admin import map may be out of date: ${staleImportMap}. If the 2FA setup and verify screens are ` +
'EMPTY (no code form), nobody can sign in to the panel: run `pnpm payload generate:importmap`, commit ' +
'importMap.js, rebuild and redeploy. If the screens work, the file on disk is not the map the build used — ' +
'set twoFactor.importMapCheck: false (docs/security.md "A stale import map").',
)
}
// Staff whose collection is not the 2FA collection log in without a second factor: say so.
if (twoFactorCollection) {
const uncovered = staffCollectionSlugs(payload).filter((slug) => slug !== twoFactorCollection)
if (uncovered.length) {