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
+13 -6
View File
@@ -31,8 +31,14 @@ once there are more than 20.
- **ipal-doctor**: the import-map rule also expects `@intecion/ipal-kit/admin#SafeTotpView` when the installed
plugin has it and the config does not set `safeBack: false`.
- **A stale import map is reported** (`twoFactor.importMapCheck`, on by default, `false` turns it off): in
production the plugin reads the committed `importMap.js` at start; when the entry above is missing it logs an
error and the 2FA screens show a message instead of staying empty.
production the plugin searches the `importMap.js` on disk at start; when the entry above is not found it logs
an error and puts a notice above the 2FA screens. The notice never replaces the screen: the file on disk is
not always the map the build used (a Dockerfile with a separate runner stage, a re-exporting map file), and
then the notice is wrong and sign-in still works — turn the check off for such a project.
- **More building blocks exported** for a project that wraps the 2FA views itself: `copyViews`,
`changedViewKeys`, `SAFE_TOTP_VIEW`, `totpViewImportKey`, `findImportMapFile`, `missingImportMapEntries`.
- **ipal-doctor** warns when the config registers the 2FA package's own setup / verify view directly (such a
view is outside the check).
- **A project's own 2FA screen set through the wrapped factory** (a server or a client component) is rendered
behind the check and gets the checked `back`.
@@ -40,10 +46,11 @@ once there are more than 20.
- **Every site with 2FA: `pnpm payload generate:importmap`, commit `importMap.js`, `rm -rf .next`, redeploy —
in the same deploy as the upgrade.** The plugin's view now stands in front of the package's two screens and
needs its import-map entry (`@intecion/ipal-kit/admin#SafeTotpView`). **If you skip this, the build still
passes and the site starts, but the 2FA setup and verify screens come back **empty** (HTTP 200, no code form), so nobody can sign in to the panel.** There is no error page. What tells you: `pnpm exec ipal-doctor`
before the deploy (`import map lacks …SafeTotpView`), the line `[ipal] The admin import map is out of date` in
the log at every start, and a message on the 2FA screens instead of an empty page ("Two-step verification is
not available"). No option, env, schema or migration.
passes and the site starts, but the 2FA setup and verify screens have no code form (HTTP 200), so nobody can
sign in to the panel.** There is no error page. What tells you: `pnpm exec ipal-doctor` before the deploy
(`import map lacks …SafeTotpView`); the line `[ipal] The admin import map may be out of date` in the log at
every start; and, where the form should be, the notice "Two-step verification may not be available". No
option, env, schema or migration.
- **Check after deploy:** log in with the password only, open
`/admin/verify-totp?back=https%3A%2F%2Fexample.com%2F`, enter the code → you land on `/admin`. A normal login
still returns to the page you came from.
+1 -1
View File
@@ -1167,7 +1167,7 @@ add missing hosts with flags / `extra`; (3) change `mode` to `'enforce'` in both
| 2FA on the panel's login collection, mismatch = startup error; redirect to the 2FA screens by `TotpRedirectProvider` | `twoFactor: false` (discouraged) | `twoFactor.collectionSlug`, `allowCollectionMismatch: true`, `twoFactor.provider` (own component, or `false` for the package's) |
| The second factor on every collection and global, whichever plugin added it, and on the plugin's endpoints; an unrecognised 2FA package = startup error | per entity: `custom.ipal.secondFactor: false` or `{ read: false }` (or the package's `custom.totp.disableAccessWrapper`); everywhere: `twoFactor.guard: false` (not recommended) | `requireSecondFactor` / `secondFactorPassed` in your own access functions and endpoints |
| At most 5 verify attempts per account in 10 minutes (`POST /api/verify-totp` → `429`) | `twoFactor.verifyLimit: false` | `verifyLimit: { max, windowMinutes }` |
| The `back` link of the 2FA setup and verify screens is checked on the server (`SafeTotpView` in front of the package's views): only a path on the site's origin inside the admin route is kept, anything else (`javascript:`, another host) becomes the admin root. Needs `generate:importmap` in the same deploy — with a stale map the 2FA screens are empty and nobody can sign in (`ipal-doctor`, the start log and a message on the screen report it; `twoFactor.importMapCheck: false` silences that); check: password only → `/admin/verify-totp?back=https%3A%2F%2Fexample.com%2F` → code → lands on `/admin` | `twoFactor.safeBack: false` | `safeBack: (back, { adminRoute, origin }) => string`; `safeAdminBack`, `wrapTotpViews` (`@intecion/ipal-kit`), `SafeTotpView` (`@intecion/ipal-kit/admin`) for own views |
| The `back` link of the 2FA setup and verify screens is checked on the server (`SafeTotpView` in front of the package's views): only a path on the site's origin inside the admin route is kept, anything else (`javascript:`, another host) becomes the admin root. Needs `generate:importmap` in the same deploy — with a stale map the 2FA screens have no code form and nobody can sign in (`ipal-doctor`, the start log and a notice above the screen report it; the notice is a hint from the file on disk and never replaces the screen; `twoFactor.importMapCheck: false` turns it off); check: password only → `/admin/verify-totp?back=https%3A%2F%2Fexample.com%2F` → code → lands on `/admin` | `twoFactor.safeBack: false` | `safeBack: (back, { adminRoute, origin }) => string`; `safeAdminBack`, `wrapTotpViews` (`@intecion/ipal-kit`), `SafeTotpView` (`@intecion/ipal-kit/admin`) for own views |
| The 2FA package's endpoints (`/api/setup-totp`, `verify-totp`, `remove-totp`, `admin/*`) answer accounts of the 2FA collection only; reset and remove need the second factor | — (always on with 2FA) | `adminManageAccess` through the wrapped factory (security.md "Resetting 2FA") |
| Roles count only for accounts of a staff collection, in every predicate and access function | — | `access.staffCollections` |
| `enabled: false` keeps the schema | — | — (no endpoints, `onInit` or admin components; no DROP TABLE in `migrate:create`) |
+2 -1
View File
@@ -58,7 +58,8 @@ through this procedure. Ask only when you are missing something you cannot get y
| Symptom | Cause | Fix |
|---|---|---|
| `PayloadComponent not found in importMap` (e.g. `@intecion/ipal-kit/admin#RowLabel`) | importMap out of date after a plugin update / adding `rowLabel` | `pnpm payload generate:importmap`, restart |
| after an upgrade the 2FA setup / verify screen is **empty** (HTTP 200, no code form) or says "Two-step verification is not available"; nobody can sign in; the log has `[ipal] The admin import map is out of date` and `getFromImportMap: PayloadComponent not found in importMap … @intecion/ipal-kit/admin#SafeTotpView` | the import map was not regenerated after the upgrade that added the `back` link check (`twoFactor.safeBack`); the production build uses the committed, old `importMap.js` | `pnpm payload generate:importmap`, commit `importMap.js`, `rm -rf .next`, redeploy; `pnpm exec ipal-doctor` shows it before a deploy. The opposite case (wrapper present, package view missing) throws `[ipal] The admin import map has no "@clocklimited/payload-2fa/rsc#TOTPVerify"` — same fix |
| after an upgrade the 2FA setup / verify screen has no code form (HTTP 200), only the notice "Two-step verification may not be available" (or nothing at all with `importMapCheck: false` / an own provider); nobody can sign in; the log has `[ipal] The admin import map may be out of date` and `getFromImportMap: PayloadComponent not found in importMap … @intecion/ipal-kit/admin#SafeTotpView` | the import map was not regenerated after the upgrade that added the `back` link check (`twoFactor.safeBack`); the production build uses the committed, old `importMap.js` | `pnpm payload generate:importmap`, commit `importMap.js`, `rm -rf .next`, redeploy; `pnpm exec ipal-doctor` shows it before a deploy. The opposite case (wrapper present, package view missing) throws `[ipal] The admin import map has no "@clocklimited/payload-2fa/rsc#TOTPVerify"` — same fix |
| the notice "Two-step verification may not be available" and the log line `[ipal] The admin import map may be out of date` appear, but the code form is there and sign-in works | false alarm: the check searches the `importMap.js` on disk, which is not the map inside the build (map generated during the build and a Dockerfile runner stage that copies the repository's file; a map file that re-exports or computes its entries) | `twoFactor: { …, importMapCheck: false }`; or ship the generated `importMap.js` in the image |
| an own 2FA screen (set through the wrapped factory) ignores the check on `back` | a client component reading `useSearchParams()` gets the raw query value | read the `back` prop (or `searchParams.back`) the wrapper passes — both are checked (security.md "Your own 2FA screen") |
| after the 2FA code the user lands on `/admin` instead of the page in `back` | `back` pointed outside the admin route or to another origin (the check keeps only a path inside `routes.admin`; an absolute URL only on the `serverURL` origin) | expected; for another rule pass `twoFactor.safeBack: (back, { adminRoute, origin }) => string` (security.md) |
| new admin stuck on `/admin/setup-totp?back=null` (the page keeps redirecting to itself) | ipal-kit ≤ 1.14.1: the 2FA package's provider needs an `x-pathname` header nothing sets on `/admin`; or `twoFactor.provider: false` without that header | update ipal-kit, `pnpm payload generate:importmap` (`TotpRedirectProvider`), restart; check: `/admin/setup-totp?back=%2Fadmin` shows the QR (security.md) |
+1 -1
View File
@@ -38,7 +38,7 @@ description: Complete map of everything @intecion/ipal-kit provides — every ip
| `twoFactor.collectionSlug` | the panel's login collection (`admin.user`, else the first auth collection) | collection with 2FA; startup fails with `[ipal] twoFactor…` when it is not an auth collection or differs from `admin.user` | point it at the login collection |
| `twoFactor.provider` | `'@intecion/ipal-kit/admin#TotpRedirectProvider'` | admin provider that sends users to `setup-totp` / `verify-totp` (path read in the browser); replaces the package's header-based one | own component path / `{ path, clientProps, serverProps }` (gets clientProps `forceSetup`); `false` keeps the package's (needs `x-pathname` on `/admin`, else `setup-totp?back=null` loops) |
| `twoFactor.safeBack` | on | the `back` query value of the 2FA setup and verify screens is checked on the server before the package's view gets it (`SafeTotpView` registered in place of the package's four views): kept only as a path on the site's origin inside `routes.admin`, else the admin root — no `javascript:` / off-site redirect after the code. Needs `generate:importmap` (`@intecion/ipal-kit/admin#SafeTotpView`) | `false` = the package's views untouched; a function `(back, { adminRoute, origin }) => string` = your own rule |
| `twoFactor.importMapCheck` | on | production only: at start reads the committed `importMap.js` (where Payload looks for it); when `@intecion/ipal-kit/admin#SafeTotpView` is missing, logs `[ipal] The admin import map is out of date …` and the 2FA screens show "Two-step verification is not available" instead of staying empty. A file that cannot be found is not reported | `false` = no file read, log line or message |
| `twoFactor.importMapCheck` | on | production only: at start searches the `importMap.js` on disk (where Payload looks for it) for `@intecion/ipal-kit/admin#SafeTotpView`; when not found, logs `[ipal] The admin import map may be out of date …` and ipal-kit's `TotpRedirectProvider` puts the notice "Two-step verification may not be available" above the 2FA screens (never instead of them). A hint only — the map in the build can differ from the file on disk (Dockerfile runner stage, re-exporting map); a file that is not found is not reported | `false` = no file read, log line or notice |
| `twoFactor.texts` | ipal-kit's en/pl texts (`TOTP_TEXTS`) over the package's; 2FA screens titled "Two-step verification" / "Weryfikacja dwuetapowa" (site's language) | `false` = the package's texts; one text: `i18n.translations.<lang>.totpPlugin.<key>` (security.md) |
| `twoFactor.guard` | on | ipal-kit's own second-factor check on every collection and global (also the plugin's own and those of plugins listed after ipalKit) and in `userMeetsRole`; startup fails with `[ipal] twoFactor: the injected 2FA plugin did not add …` when the 2FA package lacks the `totp` strategy / `hasTotp` / `totpSecret` | per entity: `custom.ipal.secondFactor: false` / `{ read: false }` or the package's `custom.totp.disableAccessWrapper.<op>`; `false` = the package's wrapper only (the plugin's own data then opens to a password without the code; not recommended). The package's endpoints stay limited to accounts of the 2FA collection either way |
| `twoFactor.verifyLimit` | `{ max: 5, windowMinutes: 10 }` | attempts per account on `POST /api/verify-totp` (the 2FA package counts none): the sixth in the window, right or wrong, gets `429` + `Retry-After`; in memory per instance | `{ max, windowMinutes }`; `false` = no limit |
@@ -69,7 +69,7 @@ Admin panel components from `@intecion/ipal-kit/admin` — the project does NOT
| `buildRolesField(defaultRole?, { firstUserAdmin? })` | `@intecion/ipal-kit` | The `roles` select field the plugin injects (only admins set roles; `firstUserAdmin` default `true` = the account made on "Create first user" gets `admin`). The plugin wires it itself — use it only for an auth collection the plugin does not manage. |
| `injectRoles(config, accessOption)` | `@intecion/ipal-kit` | Adds `roles` to `accessOption.authCollection` in a config. The plugin calls it itself with `access` — do not call. |
**Types:** `VerifyLimitOptions` (`twoFactor.verifyLimit`: `{ max?, windowMinutes? }`), `SafeBackRule` / `SafeBackContext` (`twoFactor.safeBack` as a function: `(back, { adminRoute, origin? }) => string`), `SafeTotpViewProps` (`@intecion/ipal-kit/admin`), `Role` (`'user' \| 'editor' \| 'admin'`), `AccessOption` (the plugin's `access` option: `authCollection`, `defaultRole`, `authAccess`, `firstUserAdmin`, `staffCollections`).
**Types:** `VerifyLimitOptions` (`twoFactor.verifyLimit`: `{ max?, windowMinutes? }`), `SafeBackRule` / `SafeBackContext` (`twoFactor.safeBack` as a function: `(back, { adminRoute, origin? }) => string`), `TotpViewComponent` (a view component as registered: a path or `{ path, exportName?, clientProps?, serverProps? }`), `SafeTotpViewProps` (`@intecion/ipal-kit/admin`), `Role` (`'user' \| 'editor' \| 'admin'`), `AccessOption` (the plugin's `access` option: `authCollection`, `defaultRole`, `authAccess`, `firstUserAdmin`, `staffCollections`).
## Accessibility — widget (`accessibility`) — details: `node_modules/@intecion/ipal-kit/docs/accessibility.md`
@@ -589,6 +589,9 @@ Server only (`pnpm payload run`); never import it from client code, the Payload
| `secondFactorPassed(req)` | `@intecion/ipal-kit` | `boolean` with `req` (`{ payload, user }`): `false` only for an account of the 2FA collection that has TOTP set up and has not entered the code in this session (password only). `true` for a full login, an API key, an account that has not set TOTP up yet, accounts of other auth collections, no user, and with `twoFactor: false`. Guard your own endpoints with it: `if (!req.user \|\| !secondFactorPassed(req)) return 403`. |
| `safeAdminBack(back, { adminRoute, origin? })` | `@intecion/ipal-kit` | The default `back` rule of the 2FA screens: returns `back` as a path when it resolves to the site's origin (the placeholder origin for relative values, `origin` for absolute ones), over HTTP(S), without credentials, inside `adminRoute`; otherwise the admin root. `safeAdminBack('javascript:alert(1)', { adminRoute: '/admin' })` → `'/admin'`; `safeAdminBack('/admin/collections/pages?page=2', { adminRoute: '/admin' })` → the same path. Use it in your own rule or view. |
| `wrapTotpViews(views, added, rule?, wrapper?)` | `@intecion/ipal-kit` | Puts `SafeTotpView` in front of the views whose route is `setup-totp` / `verify-totp` and for which `added(key)` is true (keeps `exportName`, `serverProps`; `clientProps` travel as `ipalTotpClientProps`); returns `{ views, dependencies }` (`dependencies` → `admin.dependencies`, so the wrapped views stay in the import map). What `ipalKit` runs after the 2FA factory; for a project that registers the 2FA package itself. |
| `copyViews(views)` / `changedViewKeys(before, after)` | `@intecion/ipal-kit` | The comparison `ipalKit` uses to tell which views a 2FA factory registered: put `copyViews(views)` into the config before calling the factory, then `changedViewKeys(before, viewsAfter)` gives the keys whose view object changed — the `added` argument of `wrapTotpViews` (`(key) => keys.has(key)`). By object, not by key: the 2FA package replaces a view that already stands under its keys. Example: security.md "Your own 2FA screen". |
| `SAFE_TOTP_VIEW` / `totpViewImportKey(component)` | `@intecion/ipal-kit` | `'@intecion/ipal-kit/admin#SafeTotpView'`, the wrapper's import-map path (the default `wrapper` of `wrapTotpViews`); and the import-map key (`path#export`) of a component given as a string or `{ path, exportName }`. |
| `findImportMapFile(config, cwd?)` / `missingImportMapEntries(config, entries, cwd?)` | `@intecion/ipal-kit` | Where the project's `importMap.js` is on disk (`admin.importMap.importMapFile`, else `app/(payload)<admin route>/` or `src/app/…` under `admin.importMap.baseDir` / the working directory; `null` when not found), and which of `entries` its text does not contain (`{ file, missing }`). A hint from the file on disk, not the map in the build: warn on it, never block on it. Behind `twoFactor.importMapCheck`. |
| `requireSecondFactor(access?)` | `@intecion/ipal-kit` | Wraps an `Access` function: refused while the second factor is owed, otherwise the function itself (Payload's default "logged in" when none). ipalKit applies it to every collection and global in the config, and to those added by plugins listed after it (in `onInit` and at the start of the first request, so also after a dev hot reload); use it for access functions that are not part of the config. Per-entity opt-out: `custom.ipal.secondFactor: false \| { read: false }` or the package's `custom.totp.disableAccessWrapper`. Wrapping twice is harmless. |
| `totpRedirectTarget({ adminRoute, forceSetup?, pathname, user, excludePaths? })`, `totpAdminPath(adminRoute, path)` | `@intecion/ipal-kit` | The 2FA redirect rules as pure functions: the setup / verify URL (with `back`) to send this user to, or `null` (no path, api key, already on a TOTP screen or logout). For an own `twoFactor.provider`. Types `TotpRedirectArgs`, `TotpUser` |
| `buildCsp({ mode?, reportUri?, reportGroup?, r2Url?, analytics?, metaPixel?, linkedIn?, tiktok?, clarity?, turnstile?, youtube?, googleMaps?, nonce?, strictDynamic?, dev?, extra?, override? })` | `@intecion/ipal-kit` | Returns `{ key, value }` with a hardened CSP (`base-uri`, `object-src`, `frame-ancestors`, `form-action`) + sources for the enabled integrations. `mode: 'report-only'` → `…-Report-Only` (start here), `'enforce'` later. `extra` adds to any directive, `override` replaces / drops one (`null`). `dev` (default `NODE_ENV === 'development'`) adds `'unsafe-eval'`. `nonce` → `'nonce-…' 'strict-dynamic'`. |
+3 -2
View File
@@ -228,8 +228,9 @@ the panel shows Site settings, Site integrations, Cookies, Form messages, the Fo
The `back` link of the setup and verify screens is checked on the server (`twoFactor.safeBack`, on by default:
only a path inside the admin route is kept; `false` turns it off, a function replaces the rule). It needs the
import map entry `@intecion/ipal-kit/admin#SafeTotpView` — run `pnpm payload generate:importmap` and commit
(a production build with a map that lacks it shows empty 2FA screens: nobody can sign in; `ipal-doctor` and the
start log report it, `twoFactor.importMapCheck: false` turns that report off).
(a production build with a map that lacks it shows 2FA screens without a code form: nobody can sign in;
`ipal-doctor`, the start log and a notice above the screen report it; `twoFactor.importMapCheck: false` turns the
log line and the notice off — needed when the `importMap.js` on disk is not the one the build used).
Check: password only → `/admin/verify-totp?back=https%3A%2F%2Fexample.com%2F` → code → you land on `/admin`.
**Set 2FA up right after creating an account** (log in as it, scan the code): until then its password alone
opens everything its role allows. One entity reachable without the code: `custom.ipal.secondFactor`.
+7 -4
View File
@@ -142,10 +142,13 @@ panel opens and a document saves.
1. **Do this in the same deploy as the upgrade, or the panel is locked for everyone.**
`pnpm payload generate:importmap` — the plugin puts `@intecion/ipal-kit/admin#SafeTotpView` in front of the
2FA package's setup and verify views; commit `importMap.js`, `rm -rf .next`, redeploy on Coolify. With the old
import map the build passes and the site starts, but the 2FA screens are **empty** (HTTP 200, no code form) —
nobody can sign in. Signs: `pnpm exec ipal-doctor` → `import map lacks …SafeTotpView` (run it before deploying);
the log line `[ipal] The admin import map is out of date` at start; the screen says "Two-step verification is
not available". Fix: the same command, commit, redeploy.
import map the build passes and the site starts, but the 2FA screens have no code form (HTTP 200) — nobody can
sign in. Signs: `pnpm exec ipal-doctor` → `import map lacks …SafeTotpView` (run it before deploying); the log
line `[ipal] The admin import map may be out of date` at start; the notice "Two-step verification may not be
available" where the form should be. Fix: the same command, commit, redeploy.
The log line and the notice with a **working** code form mean a false alarm (the `importMap.js` on disk is not
the one the build used — a Dockerfile runner stage, a re-exporting map): sign-in works; set
`twoFactor.importMapCheck: false`.
**Check:** log in with the password only → open `/admin/verify-totp?back=https%3A%2F%2Fexample.com%2F` → enter
the code → you land on `/admin` (not on example.com); a normal login still returns to the page you came from.
No option, env, schema or migration. A project that registered its own 2FA views, or wrote a proxy rule that
+1 -1
View File
@@ -89,7 +89,7 @@ Turn off: `ipalKit({ doctor: false })`. Adapt: `ipalKit({ doctor: { tokenVar: 'M
| | `layout-forbidden` | error | no `middleware.ts`, no `lib/{pages,locales,navigation}.ts`, `fields/{link,sectionHeader,sectionSettings}.ts` |
| | `layout-extra` | info | `src/` entries outside the allow list (AGENT.md §3 + `seed/`, `design/`, `db.ts`, `env.rules.ts`, `content.config.ts`; extend with `layout.allow`) |
| | `naming` | warning | block folders, collection and global files PascalCase, `scripts/*` kebab-case, no `index.ts` barrels |
| | `importmap` | error | the import map exists, holds the entries for what the config turns on (2FA, R2, cookie scanner, `adminMeta`), names no export the plugin no longer has; with `--deep`, equals a fresh one |
| | `importmap` | error | the import map exists, holds the entries for what the config turns on (2FA, R2, cookie scanner, `adminMeta`), names no export the plugin no longer has; with `--deep`, equals a fresh one. Warning: the config registers the 2FA package's own setup / verify view directly (outside the `back` link check — security.md) |
| | `tsconfig-skills` | error | `tsconfig.json` excludes the skills folder |
| env | `db-name` | error | `DATABASE_URI` in `.env` and `.env.example` names `<domain without dots>_dev`; a local `.env` on `_prod` is an error; `--env-file` checks `_prod` (`databaseNamesFor`) |
| | `env-rules` | error / warning | `instrumentation.ts` calls `assertEnv(ipalEnvRules(…))` from `/env`, with `storage` (R2), `cookieCrawl` (crawl), `ipHeader`; `databaseName` suggested (info) |
+38 -14
View File
@@ -610,23 +610,46 @@ guarded. The same holds when the project also lists `payloadTotp(...)` in `plugi
your `clientProps`, and `back` plus `searchParams` — both checked; read `back` from the props, not from
`useSearchParams()`, which still holds the raw query value.
- From a plugin listed after `ipalKit`, or under another key or route: that view is yours and is not wrapped. Use
`wrapTotpViews` or `safeAdminBack` in it.
`wrapTotpViews` or `safeAdminBack` in it. `ipal-doctor` warns when the config names the package's own view
(`@clocklimited/payload-2fa/rsc#TOTPVerify` / `#TOTPSetup`) directly.
Wrapping views yourself, for a project that runs the 2FA package without `ipalKit`'s `twoFactor` (all from
`@intecion/ipal-kit`):
```ts
const before = copyViews(config.admin?.components?.views) // copies: the factory's views are then never "the same object"
config = await payloadTotp(options)({ ...config, admin: { ...config.admin, components: { ...config.admin?.components, views: before } } })
const fromPackage = changedViewKeys(before, config.admin?.components?.views ?? {}) // by object — the package replaces views under its keys
const { dependencies, views } = wrapTotpViews(config.admin?.components?.views ?? {}, (key) => fromPackage.has(key), undefined)
config.admin = { ...config.admin, components: { ...config.admin?.components, views }, dependencies: { ...config.admin?.dependencies, ...dependencies } }
```
`SAFE_TOTP_VIEW` is the wrapper's import-map path; `findImportMapFile` / `missingImportMapEntries` are the
stale-map check below (a hint from the file on disk — warn on it, never block on it).
**A stale import map (read this before upgrading a site with 2FA).** The check needs the import-map entry
`@intecion/ipal-kit/admin#SafeTotpView`. A production build made with the import map of the previous version
passes, the site starts, and the 2FA setup and verify screens come back **empty** (HTTP 200, no code form), so nobody can sign in to the panel. Payload renders nothing for a path its map lacks; the only trace is
passes and the site starts, but Payload renders nothing for a path its map lacks: the 2FA setup and verify
screens have no code form (HTTP 200), so nobody can sign in to the panel. Payload's only trace is
`getFromImportMap: PayloadComponent not found in importMap` in the server log. Development is not affected (Payload
regenerates the map there). ipal-kit makes this loud in three places:
regenerates the map there). ipal-kit reports it in three places:
- **Before deploy:** `pnpm exec ipal-doctor` reports `import map lacks @intecion/ipal-kit/admin#SafeTotpView` (error).
- **At every start in production:** the log has `[ipal] The admin import map is out of date: … The 2FA setup and
verify screens are EMPTY …`.
- **On the screen:** instead of nothing, the 2FA screens say "Two-step verification is not available" and what a
developer has to run (shown by `TotpRedirectProvider`; with your own `twoFactor.provider` it gets the clientProp
`staleImportMap`, with `provider: false` there is only the log line).
The check reads `importMap.js` where Payload looks for it (`admin.importMap.importMapFile`, else
`app/(payload)<admin route>/` or `src/app/(payload)<admin route>/` under `admin.importMap.baseDir` or the working
directory). A file it cannot find is never reported. `twoFactor: { …, importMapCheck: false }` turns the file read,
the log line and the message off. **Fix:** `pnpm payload generate:importmap`, commit `importMap.js`, rebuild, redeploy.
- **At every start in production:** the log has `[ipal] The admin import map may be out of date: … was not found
in <file> …`.
- **On the screen:** a notice above the 2FA screen, "Two-step verification may not be available", with what a
developer has to run. With a really stale map the notice is all the user sees (the form is missing); it is
shown by ipal-kit's `TotpRedirectProvider` only — with your own `twoFactor.provider`, or `provider: false`,
there is the log line alone.
The start-up check is a guess, and is built so that a wrong guess costs a wrong notice and nothing else: it
searches the text of the `importMap.js` **on disk** where Payload looks for it (`admin.importMap.importMapFile`,
else `app/(payload)<admin route>/` or `src/app/(payload)<admin route>/` under `admin.importMap.baseDir` or the
working directory), while the map the site really uses is inside the build. The two differ when the map is
generated during the build and the running image carries the repository's file (a Dockerfile with a separate
runner stage), or when the map file re-exports or computes its entries. Then the log line and the notice appear
although the screen works — the code form stays on the page and sign-in is not affected. Turn the check off for
such a project: `twoFactor: { …, importMapCheck: false }` (no file read, no log line, no notice). A file that is
not found is not reported. Building in place (Coolify's Nixpacks) reads the same file the build used.
**Fix for a really stale map:** `pnpm payload generate:importmap`, commit `importMap.js`, rebuild, redeploy.
A second error exists for the opposite case — the wrapper is in the map but the package's view is not:
`[ipal] The admin import map has no "@clocklimited/payload-2fa/rsc#TOTPVerify"` (same fix).
@@ -732,8 +755,9 @@ size while reading, content signature, container and macro checks, an optional `
- **Verify limit:** `twoFactor.verifyLimit: { max, windowMinutes }`, or `false`.
- **`back` link check of the 2FA screens:** `twoFactor.safeBack: false`, or a function as your own rule;
`safeAdminBack`, `wrapTotpViews`, `SafeTotpView` are exported. The stale import-map warning that comes with it:
`twoFactor.importMapCheck: false`.
`safeAdminBack`, `wrapTotpViews`, `copyViews`, `changedViewKeys`, `SAFE_TOTP_VIEW`, `SafeTotpView` are exported.
The stale import-map notice that comes with it: `twoFactor.importMapCheck: false`; its parts
(`findImportMapFile`, `missingImportMapEntries`) are exported too.
- **2FA check:** per entity `custom.ipal.secondFactor` / `custom.totp.disableAccessWrapper` (one operation or
all); `twoFactor.guard: false` turns ipal-kit's own second-factor check off everywhere (not recommended);
`requireSecondFactor` / `secondFactorPassed` are exported for your own access functions and endpoints.
+2 -1
View File
@@ -58,7 +58,8 @@ through this procedure. Ask only when you are missing something you cannot get y
| Symptom | Cause | Fix |
|---|---|---|
| `PayloadComponent not found in importMap` (e.g. `@intecion/ipal-kit/admin#RowLabel`) | importMap out of date after a plugin update / adding `rowLabel` | `pnpm payload generate:importmap`, restart |
| after an upgrade the 2FA setup / verify screen is **empty** (HTTP 200, no code form) or says "Two-step verification is not available"; nobody can sign in; the log has `[ipal] The admin import map is out of date` and `getFromImportMap: PayloadComponent not found in importMap … @intecion/ipal-kit/admin#SafeTotpView` | the import map was not regenerated after the upgrade that added the `back` link check (`twoFactor.safeBack`); the production build uses the committed, old `importMap.js` | `pnpm payload generate:importmap`, commit `importMap.js`, `rm -rf .next`, redeploy; `pnpm exec ipal-doctor` shows it before a deploy. The opposite case (wrapper present, package view missing) throws `[ipal] The admin import map has no "@clocklimited/payload-2fa/rsc#TOTPVerify"` — same fix |
| after an upgrade the 2FA setup / verify screen has no code form (HTTP 200), only the notice "Two-step verification may not be available" (or nothing at all with `importMapCheck: false` / an own provider); nobody can sign in; the log has `[ipal] The admin import map may be out of date` and `getFromImportMap: PayloadComponent not found in importMap … @intecion/ipal-kit/admin#SafeTotpView` | the import map was not regenerated after the upgrade that added the `back` link check (`twoFactor.safeBack`); the production build uses the committed, old `importMap.js` | `pnpm payload generate:importmap`, commit `importMap.js`, `rm -rf .next`, redeploy; `pnpm exec ipal-doctor` shows it before a deploy. The opposite case (wrapper present, package view missing) throws `[ipal] The admin import map has no "@clocklimited/payload-2fa/rsc#TOTPVerify"` — same fix |
| the notice "Two-step verification may not be available" and the log line `[ipal] The admin import map may be out of date` appear, but the code form is there and sign-in works | false alarm: the check searches the `importMap.js` on disk, which is not the map inside the build (map generated during the build and a Dockerfile runner stage that copies the repository's file; a map file that re-exports or computes its entries) | `twoFactor: { …, importMapCheck: false }`; or ship the generated `importMap.js` in the image |
| an own 2FA screen (set through the wrapped factory) ignores the check on `back` | a client component reading `useSearchParams()` gets the raw query value | read the `back` prop (or `searchParams.back`) the wrapper passes — both are checked (security.md "Your own 2FA screen") |
| after the 2FA code the user lands on `/admin` instead of the page in `back` | `back` pointed outside the admin route or to another origin (the check keeps only a path inside `routes.admin`; an absolute URL only on the `serverURL` origin) | expected; for another rule pass `twoFactor.safeBack: (back, { adminRoute, origin }) => string` (security.md) |
| new admin stuck on `/admin/setup-totp?back=null` (the page keeps redirecting to itself) | ipal-kit ≤ 1.14.1: the 2FA package's provider needs an `x-pathname` header nothing sets on `/admin`; or `twoFactor.provider: false` without that header | update ipal-kit, `pnpm payload generate:importmap` (`TotpRedirectProvider`), restart; check: `/admin/setup-totp?back=%2Fadmin` shows the QR (security.md) |
@@ -38,7 +38,7 @@ description: Complete map of everything @intecion/ipal-kit provides — every ip
| `twoFactor.collectionSlug` | the panel's login collection (`admin.user`, else the first auth collection) | collection with 2FA; startup fails with `[ipal] twoFactor…` when it is not an auth collection or differs from `admin.user` | point it at the login collection |
| `twoFactor.provider` | `'@intecion/ipal-kit/admin#TotpRedirectProvider'` | admin provider that sends users to `setup-totp` / `verify-totp` (path read in the browser); replaces the package's header-based one | own component path / `{ path, clientProps, serverProps }` (gets clientProps `forceSetup`); `false` keeps the package's (needs `x-pathname` on `/admin`, else `setup-totp?back=null` loops) |
| `twoFactor.safeBack` | on | the `back` query value of the 2FA setup and verify screens is checked on the server before the package's view gets it (`SafeTotpView` registered in place of the package's four views): kept only as a path on the site's origin inside `routes.admin`, else the admin root — no `javascript:` / off-site redirect after the code. Needs `generate:importmap` (`@intecion/ipal-kit/admin#SafeTotpView`) | `false` = the package's views untouched; a function `(back, { adminRoute, origin }) => string` = your own rule |
| `twoFactor.importMapCheck` | on | production only: at start reads the committed `importMap.js` (where Payload looks for it); when `@intecion/ipal-kit/admin#SafeTotpView` is missing, logs `[ipal] The admin import map is out of date …` and the 2FA screens show "Two-step verification is not available" instead of staying empty. A file that cannot be found is not reported | `false` = no file read, log line or message |
| `twoFactor.importMapCheck` | on | production only: at start searches the `importMap.js` on disk (where Payload looks for it) for `@intecion/ipal-kit/admin#SafeTotpView`; when not found, logs `[ipal] The admin import map may be out of date …` and ipal-kit's `TotpRedirectProvider` puts the notice "Two-step verification may not be available" above the 2FA screens (never instead of them). A hint only — the map in the build can differ from the file on disk (Dockerfile runner stage, re-exporting map); a file that is not found is not reported | `false` = no file read, log line or notice |
| `twoFactor.texts` | ipal-kit's en/pl texts (`TOTP_TEXTS`) over the package's; 2FA screens titled "Two-step verification" / "Weryfikacja dwuetapowa" (site's language) | `false` = the package's texts; one text: `i18n.translations.<lang>.totpPlugin.<key>` (security.md) |
| `twoFactor.guard` | on | ipal-kit's own second-factor check on every collection and global (also the plugin's own and those of plugins listed after ipalKit) and in `userMeetsRole`; startup fails with `[ipal] twoFactor: the injected 2FA plugin did not add …` when the 2FA package lacks the `totp` strategy / `hasTotp` / `totpSecret` | per entity: `custom.ipal.secondFactor: false` / `{ read: false }` or the package's `custom.totp.disableAccessWrapper.<op>`; `false` = the package's wrapper only (the plugin's own data then opens to a password without the code; not recommended). The package's endpoints stay limited to accounts of the 2FA collection either way |
| `twoFactor.verifyLimit` | `{ max: 5, windowMinutes: 10 }` | attempts per account on `POST /api/verify-totp` (the 2FA package counts none): the sixth in the window, right or wrong, gets `429` + `Retry-After`; in memory per instance | `{ max, windowMinutes }`; `false` = no limit |
@@ -69,7 +69,7 @@ Admin panel components from `@intecion/ipal-kit/admin` — the project does NOT
| `buildRolesField(defaultRole?, { firstUserAdmin? })` | `@intecion/ipal-kit` | The `roles` select field the plugin injects (only admins set roles; `firstUserAdmin` default `true` = the account made on "Create first user" gets `admin`). The plugin wires it itself — use it only for an auth collection the plugin does not manage. |
| `injectRoles(config, accessOption)` | `@intecion/ipal-kit` | Adds `roles` to `accessOption.authCollection` in a config. The plugin calls it itself with `access` — do not call. |
**Types:** `VerifyLimitOptions` (`twoFactor.verifyLimit`: `{ max?, windowMinutes? }`), `SafeBackRule` / `SafeBackContext` (`twoFactor.safeBack` as a function: `(back, { adminRoute, origin? }) => string`), `SafeTotpViewProps` (`@intecion/ipal-kit/admin`), `Role` (`'user' \| 'editor' \| 'admin'`), `AccessOption` (the plugin's `access` option: `authCollection`, `defaultRole`, `authAccess`, `firstUserAdmin`, `staffCollections`).
**Types:** `VerifyLimitOptions` (`twoFactor.verifyLimit`: `{ max?, windowMinutes? }`), `SafeBackRule` / `SafeBackContext` (`twoFactor.safeBack` as a function: `(back, { adminRoute, origin? }) => string`), `TotpViewComponent` (a view component as registered: a path or `{ path, exportName?, clientProps?, serverProps? }`), `SafeTotpViewProps` (`@intecion/ipal-kit/admin`), `Role` (`'user' \| 'editor' \| 'admin'`), `AccessOption` (the plugin's `access` option: `authCollection`, `defaultRole`, `authAccess`, `firstUserAdmin`, `staffCollections`).
## Accessibility — widget (`accessibility`) — details: `node_modules/@intecion/ipal-kit/docs/accessibility.md`
@@ -589,6 +589,9 @@ Server only (`pnpm payload run`); never import it from client code, the Payload
| `secondFactorPassed(req)` | `@intecion/ipal-kit` | `boolean` with `req` (`{ payload, user }`): `false` only for an account of the 2FA collection that has TOTP set up and has not entered the code in this session (password only). `true` for a full login, an API key, an account that has not set TOTP up yet, accounts of other auth collections, no user, and with `twoFactor: false`. Guard your own endpoints with it: `if (!req.user \|\| !secondFactorPassed(req)) return 403`. |
| `safeAdminBack(back, { adminRoute, origin? })` | `@intecion/ipal-kit` | The default `back` rule of the 2FA screens: returns `back` as a path when it resolves to the site's origin (the placeholder origin for relative values, `origin` for absolute ones), over HTTP(S), without credentials, inside `adminRoute`; otherwise the admin root. `safeAdminBack('javascript:alert(1)', { adminRoute: '/admin' })` → `'/admin'`; `safeAdminBack('/admin/collections/pages?page=2', { adminRoute: '/admin' })` → the same path. Use it in your own rule or view. |
| `wrapTotpViews(views, added, rule?, wrapper?)` | `@intecion/ipal-kit` | Puts `SafeTotpView` in front of the views whose route is `setup-totp` / `verify-totp` and for which `added(key)` is true (keeps `exportName`, `serverProps`; `clientProps` travel as `ipalTotpClientProps`); returns `{ views, dependencies }` (`dependencies` → `admin.dependencies`, so the wrapped views stay in the import map). What `ipalKit` runs after the 2FA factory; for a project that registers the 2FA package itself. |
| `copyViews(views)` / `changedViewKeys(before, after)` | `@intecion/ipal-kit` | The comparison `ipalKit` uses to tell which views a 2FA factory registered: put `copyViews(views)` into the config before calling the factory, then `changedViewKeys(before, viewsAfter)` gives the keys whose view object changed — the `added` argument of `wrapTotpViews` (`(key) => keys.has(key)`). By object, not by key: the 2FA package replaces a view that already stands under its keys. Example: security.md "Your own 2FA screen". |
| `SAFE_TOTP_VIEW` / `totpViewImportKey(component)` | `@intecion/ipal-kit` | `'@intecion/ipal-kit/admin#SafeTotpView'`, the wrapper's import-map path (the default `wrapper` of `wrapTotpViews`); and the import-map key (`path#export`) of a component given as a string or `{ path, exportName }`. |
| `findImportMapFile(config, cwd?)` / `missingImportMapEntries(config, entries, cwd?)` | `@intecion/ipal-kit` | Where the project's `importMap.js` is on disk (`admin.importMap.importMapFile`, else `app/(payload)<admin route>/` or `src/app/…` under `admin.importMap.baseDir` / the working directory; `null` when not found), and which of `entries` its text does not contain (`{ file, missing }`). A hint from the file on disk, not the map in the build: warn on it, never block on it. Behind `twoFactor.importMapCheck`. |
| `requireSecondFactor(access?)` | `@intecion/ipal-kit` | Wraps an `Access` function: refused while the second factor is owed, otherwise the function itself (Payload's default "logged in" when none). ipalKit applies it to every collection and global in the config, and to those added by plugins listed after it (in `onInit` and at the start of the first request, so also after a dev hot reload); use it for access functions that are not part of the config. Per-entity opt-out: `custom.ipal.secondFactor: false \| { read: false }` or the package's `custom.totp.disableAccessWrapper`. Wrapping twice is harmless. |
| `totpRedirectTarget({ adminRoute, forceSetup?, pathname, user, excludePaths? })`, `totpAdminPath(adminRoute, path)` | `@intecion/ipal-kit` | The 2FA redirect rules as pure functions: the setup / verify URL (with `back`) to send this user to, or `null` (no path, api key, already on a TOTP screen or logout). For an own `twoFactor.provider`. Types `TotpRedirectArgs`, `TotpUser` |
| `buildCsp({ mode?, reportUri?, reportGroup?, r2Url?, analytics?, metaPixel?, linkedIn?, tiktok?, clarity?, turnstile?, youtube?, googleMaps?, nonce?, strictDynamic?, dev?, extra?, override? })` | `@intecion/ipal-kit` | Returns `{ key, value }` with a hardened CSP (`base-uri`, `object-src`, `frame-ancestors`, `form-action`) + sources for the enabled integrations. `mode: 'report-only'` → `…-Report-Only` (start here), `'enforce'` later. `extra` adds to any directive, `override` replaces / drops one (`null`). `dev` (default `NODE_ENV === 'development'`) adds `'unsafe-eval'`. `nonce` → `'nonce-…' 'strict-dynamic'`. |
+3 -2
View File
@@ -228,8 +228,9 @@ the panel shows Site settings, Site integrations, Cookies, Form messages, the Fo
The `back` link of the setup and verify screens is checked on the server (`twoFactor.safeBack`, on by default:
only a path inside the admin route is kept; `false` turns it off, a function replaces the rule). It needs the
import map entry `@intecion/ipal-kit/admin#SafeTotpView` — run `pnpm payload generate:importmap` and commit
(a production build with a map that lacks it shows empty 2FA screens: nobody can sign in; `ipal-doctor` and the
start log report it, `twoFactor.importMapCheck: false` turns that report off).
(a production build with a map that lacks it shows 2FA screens without a code form: nobody can sign in;
`ipal-doctor`, the start log and a notice above the screen report it; `twoFactor.importMapCheck: false` turns the
log line and the notice off — needed when the `importMap.js` on disk is not the one the build used).
Check: password only → `/admin/verify-totp?back=https%3A%2F%2Fexample.com%2F` → code → you land on `/admin`.
**Set 2FA up right after creating an account** (log in as it, scan the code): until then its password alone
opens everything its role allows. One entity reachable without the code: `custom.ipal.secondFactor`.
@@ -142,10 +142,13 @@ panel opens and a document saves.
1. **Do this in the same deploy as the upgrade, or the panel is locked for everyone.**
`pnpm payload generate:importmap` — the plugin puts `@intecion/ipal-kit/admin#SafeTotpView` in front of the
2FA package's setup and verify views; commit `importMap.js`, `rm -rf .next`, redeploy on Coolify. With the old
import map the build passes and the site starts, but the 2FA screens are **empty** (HTTP 200, no code form) —
nobody can sign in. Signs: `pnpm exec ipal-doctor` → `import map lacks …SafeTotpView` (run it before deploying);
the log line `[ipal] The admin import map is out of date` at start; the screen says "Two-step verification is
not available". Fix: the same command, commit, redeploy.
import map the build passes and the site starts, but the 2FA screens have no code form (HTTP 200) — nobody can
sign in. Signs: `pnpm exec ipal-doctor` → `import map lacks …SafeTotpView` (run it before deploying); the log
line `[ipal] The admin import map may be out of date` at start; the notice "Two-step verification may not be
available" where the form should be. Fix: the same command, commit, redeploy.
The log line and the notice with a **working** code form mean a false alarm (the `importMap.js` on disk is not
the one the build used — a Dockerfile runner stage, a re-exporting map): sign-in works; set
`twoFactor.importMapCheck: false`.
**Check:** log in with the password only → open `/admin/verify-totp?back=https%3A%2F%2Fexample.com%2F` → enter
the code → you land on `/admin` (not on example.com); a normal login still returns to the page you came from.
No option, env, schema or migration. A project that registered its own 2FA views, or wrote a proxy rule that
+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) {
+29
View File
@@ -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' })
+61
View File
@@ -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 }`)
+67
View File
@@ -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('')
})
})