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
+12
-4
@@ -30,12 +30,20 @@ once there are more than 20.
|
||||
(`@intecion/ipal-kit/admin`) are exported for projects that register the 2FA views themselves.
|
||||
- **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.
|
||||
- **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`.
|
||||
|
||||
### Requires project changes
|
||||
- **Every site with 2FA: `pnpm payload generate:importmap`, commit `importMap.js`, `rm -rf .next`, redeploy.**
|
||||
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`). Without it the setup and verify screens fail with
|
||||
`[ipal] The admin import map has no "…"` and nobody can enter a code. No option, env, schema or migration.
|
||||
- **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.
|
||||
- **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
@@ -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`; 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 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 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`) |
|
||||
|
||||
@@ -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 |
|
||||
| the 2FA setup or verify screen fails with `[ipal] The admin import map has no "@clocklimited/payload-2fa/rsc#TOTPVerify"` (or `#TOTPSetup`), or the console says `PayloadComponent not found in importMap` for `@intecion/ipal-kit/admin#SafeTotpView` | the import map was not regenerated after an upgrade that added the `back` link check (`twoFactor.safeBack`) | `pnpm payload generate:importmap`, commit `importMap.js`, `rm -rf .next`, redeploy |
|
||||
| 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 |
|
||||
| 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) |
|
||||
| `Cannot destructure property 'config'` / UI hooks without context | two copies of `@payloadcms/ui` | `pnpm why @payloadcms/ui`; one version + `pnpm.overrides`; `ls node_modules/@intecion/ipal-kit/node_modules/@payloadcms` = empty |
|
||||
|
||||
@@ -38,6 +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.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 |
|
||||
|
||||
@@ -31,7 +31,7 @@ Admin panel components from `@intecion/ipal-kit/admin` — the project does NOT
|
||||
| `CookieApprovalForm` | `@intecion/ipal-kit/admin` | Client part of the view: tick boxes, markers (New / Changed / Needs description), Edit links, the button. Props `pending`, `gone`, `unknownCategory`, `labels?`, `adminRoute?` — reuse it in your own view. |
|
||||
| `CookieCrawlAlert` | `@intecion/ipal-kit/admin` | Server Component: dashboard warning — "Waiting for approval: N" with a link to the approval view, and with the crawl violations or a failed crawl; renders nothing otherwise. Props `approval`, `crawl`. Injected with `cookieScanner` (`approval.dashboard: false` / `crawl.dashboard: false` drop its parts); after turning it on, `pnpm generate:importmap`. |
|
||||
| `CookieScanButton` | `@intecion/ipal-kit/admin` | "Scan cookies" box above the *Cookie review* list: integrations in use, optional extra names, runs `POST /api/ipal/cookie-scan`. Injected by the plugin with `cookieScanner`; after turning it on, `pnpm generate:importmap`. |
|
||||
| `SafeTotpView` | `@intecion/ipal-kit/admin` | Server admin view in front of the 2FA package's setup and verify views: replaces the `back` query value with a checked one and renders the package's view (found in the import map by the serverProp `ipalTotpView`; `ipalSafeBack` = own rule). Registered by the plugin with `twoFactor` (`twoFactor.safeBack`, on by default). After upgrading, `pnpm generate:importmap`. Check: password only → `/admin/verify-totp?back=https%3A%2F%2Fexample.com%2F` → code → `/admin`. Own registration: `Component: { path: '@intecion/ipal-kit/admin#SafeTotpView', serverProps: { ipalTotpView: '<path>' } }` + that path in `admin.dependencies`. |
|
||||
| `SafeTotpView` | `@intecion/ipal-kit/admin` | Server admin view in front of the 2FA package's setup and verify views: replaces the `back` query value with a checked one and renders the view named by the serverProp `ipalTotpView` (a path or `{ path, exportName }`, found in the import map) the way Payload renders a view: a server component gets all server props, a client component only Payload's client props, `ipalTotpClientProps`, `back` and `searchParams` (both checked). `ipalSafeBack` = own rule. Registered by the plugin with `twoFactor` (`twoFactor.safeBack`, on by default). After upgrading, `pnpm generate:importmap`. Check: password only → `/admin/verify-totp?back=https%3A%2F%2Fexample.com%2F` → code → `/admin`. Own registration: `Component: { path: '@intecion/ipal-kit/admin#SafeTotpView', serverProps: { ipalTotpView: '<path>' } }` + that path in `admin.dependencies`. |
|
||||
| `TotpRedirectProvider` | `@intecion/ipal-kit/admin` | Client admin provider: sends a user without TOTP to `/admin/setup-totp?back=…` and a user whose session has not passed TOTP to `/admin/verify-totp?back=…` (path read in the browser; never redirects away from those screens or logout; renders nothing while redirecting). Injected by the plugin with `twoFactor` in place of the package's header-based provider; swap with `twoFactor.provider`. After upgrading, `pnpm generate:importmap`. Check: a new admin lands on `setup-totp?back=%2Fadmin` with the QR code. Props type `TotpRedirectProviderProps` (`forceSetup`) |
|
||||
| `IntecionCredit` | `@intecion/ipal-kit/admin` | The line "Technology support: Intecion.com" (admin language; `agency` prop = the name) below the nav and below the login form (`variant: 'nav' \| 'login'`). Injected by the plugin with `whiteLabel`; turn off: `whiteLabel: { credit: false }` or `agency: false`. |
|
||||
| `buildAdminMeta({ agency, apiRoute?, defaultLocale?, meta?, options? })` | `@intecion/ipal-kit` | The `adminMeta` step: static panel meta (robots, preview image, icon) without overwriting keys in `meta`; returns `{ meta, resolved }` |
|
||||
@@ -588,7 +588,7 @@ Server only (`pnpm payload run`); never import it from client code, the Payload
|
||||
| `withSecurityConfig(nextConfig, { hidePoweredBy? })` | `@intecion/ipal-kit` | Next config wrapper: `poweredByHeader: false` + drops `X-Powered-By` from `headers()` (Next's "Next.js" and withPayload's "Next.js, Payload"). `withPayload(withSecurityConfig(nextConfig))`; `hidePoweredBy: false` = no change. |
|
||||
| `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; returns `{ views, dependencies }` (`dependencies` → `admin.dependencies`, so the package's views stay in the import map). What `ipalKit` runs after the 2FA factory; for a project that registers the 2FA package itself. |
|
||||
| `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. |
|
||||
| `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'`. |
|
||||
|
||||
@@ -227,7 +227,9 @@ the panel shows Site settings, Site integrations, Cookies, Form messages, the Fo
|
||||
Verify attempts: 5 per account in 10 minutes (`twoFactor.verifyLimit`).
|
||||
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.
|
||||
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).
|
||||
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`.
|
||||
|
||||
@@ -139,9 +139,13 @@ panel opens and a document saves.
|
||||
notice's close button follow the language by themselves.
|
||||
|
||||
**→ the release with `twoFactor.safeBack` (CHANGELOG "Unreleased — the `back` link of the 2FA screens"; PROGRAMISTA §6, item 67; security.md) — required with 2FA on:**
|
||||
1. `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. Without the
|
||||
new import map the two screens fail with `[ipal] The admin import map has no "…"` — nobody can enter a code.
|
||||
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.
|
||||
**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
|
||||
|
||||
@@ -674,7 +674,7 @@ Do one item at a time, build, check. Order by importance:
|
||||
| 64 | **1.16.3** — the reference site and the starter run Payload 3.94.1; the site is still on 3.90–3.93, or `node -v` (locally or in the Coolify app's Terminal) is below 22.23.5 | Recommended, not required (the plugin still accepts `^3.90.2`). First make sure Node is 22.23.5 or later everywhere, Coolify included (Nixpacks picks the patch: check `node -v`, update Coolify if lower). Then every `payload` / `@payloadcms/*` 3.94.1 (in `dependencies` and `pnpm.overrides`), `react` / `react-dom` 19.3.1, `"engines": { "node": ">=22.23.5 <23" }`; overrides: keep `dompurify` and `happy-dom`, drop `mongoose`, `undici` and `graphql-scalars`; `pnpm install`, `generate:types`, `generate:importmap`, `rm -rf .next`, build, redeploy; Postgres/SQLite: `migrate:create`; `pnpm ipal:skills` | CHANGELOG 1.16.3, AGENT.md §4 items 11–12, ipal-upgrade "Every upgrade — Payload" |
|
||||
| 65 | **1.16.4 — security** — with 2FA on, a login with the password only gets `200` from `/api/globals/site-integrations` or `/api/form-submissions`; or the project has a second auth collection (`customers`) | Upgrade and redeploy (no config change with one auth collection). With the owner: change the SMTP password and the Turnstile secret, review Site settings / Site integrations / each form's Emails tab for values nobody set. Second auth collection: `admin: { user }` in `buildConfig`, `adminOrSelfIn('<slug>')`, `access.staffCollections` only for a second STAFF collection. Every account must have 2FA set up (`ipal-doctor --url` → 0 without). Own endpoints: `secondFactorPassed(req)`; own `overrideAccess: false` calls: `user` from `payload.auth()`. `pnpm ipal:skills`; no migration | CHANGELOG 1.16.4, security.md "What the second factor covers", access.md "Who is staff" |
|
||||
| 66 | **1.16.4** — production `PAYLOAD_SECRET` shorter than 32 characters (the site would stop at `assertEnv`) | Before deploying 1.16.4, check the length in Coolify (`node -e 'console.log(process.env.PAYLOAD_SECRET.length)'`). Shorter: a random 32+ character secret (logs everyone out, asks for 2FA again, breaks stored API keys), or `ipalEnvRules({ secretMinLength: 0 })` for now | CHANGELOG 1.16.4, deployment.md "PAYLOAD_SECRET — length and changing it" |
|
||||
| 67 | **Unreleased — security** — with 2FA on, `/admin/verify-totp?back=https%3A%2F%2Fexample.com%2F` sends the user to example.com after the code (and `back=javascript:…` runs script in the panel) | Upgrade, `pnpm payload generate:importmap` (adds `@intecion/ipal-kit/admin#SafeTotpView`), commit `importMap.js`, `rm -rf .next`, redeploy on Coolify; check: the link above ends on `/admin`. No option, env or migration; off / own rule: `twoFactor.safeBack` | CHANGELOG "Unreleased", security.md "The `back` link of the 2FA screens" |
|
||||
| 67 | **Unreleased — security** — with 2FA on, `/admin/verify-totp?back=https%3A%2F%2Fexample.com%2F` sends the user to example.com after the code (and `back=javascript:…` runs script in the panel) | Upgrade and, **in the same deploy**, `pnpm payload generate:importmap` (adds `@intecion/ipal-kit/admin#SafeTotpView`), commit `importMap.js`, `rm -rf .next`, redeploy on Coolify — with the old map the 2FA screens are empty and nobody can sign in (`ipal-doctor` and the start log say so); check: the link above ends on `/admin`. No option, env or migration; off / own rule: `twoFactor.safeBack` | CHANGELOG "Unreleased", security.md "The `back` link of the 2FA screens" |
|
||||
|
||||
After updating the package: `pnpm ipal:skills` (new skill versions), `pnpm payload generate:importmap`, `rm -rf .next`, restart dev, grep for the new symbol in
|
||||
`node_modules/@intecion/ipal-kit/dist`.
|
||||
|
||||
+36
-3
@@ -587,8 +587,8 @@ leading spaces, `data:`, `https://other.example`, `//other.example`, `/\other.ex
|
||||
always a path, never an absolute URL. An absolute `back` on the site's own origin is accepted only when the
|
||||
config has `serverURL`.
|
||||
|
||||
- **On by default** with `twoFactor`. After upgrading run `pnpm payload generate:importmap` and commit
|
||||
`importMap.js`; without it the two screens fail with `[ipal] The admin import map has no "…"`.
|
||||
- **On by default** with `twoFactor`. **After upgrading run `pnpm payload generate:importmap` and commit
|
||||
`importMap.js`** — see "A stale import map" below for what happens otherwise.
|
||||
- **Your own rule:** `twoFactor: { …, safeBack: (back, { adminRoute, origin }) => string }`. It gets the raw value
|
||||
(`undefined` when absent or repeated) and returns where to go. Return a path on your own origin.
|
||||
- **Off:** `twoFactor: { …, safeBack: false }` — the package's views exactly as it registers them. Only when a
|
||||
@@ -598,6 +598,38 @@ config has `serverURL`.
|
||||
the serverProp `ipalTotpView: '<import-map path of the view to render>'` and list that path in
|
||||
`admin.dependencies`).
|
||||
|
||||
**Which views are guarded.** Every view the injected 2FA factory registers on the routes `setup-totp` and
|
||||
`verify-totp`, whatever stood under its keys before. The package replaces a view the project has under the keys
|
||||
`SetupTOTP`, `SetupTOTPBackslash`, `VerifyTOTP` or `VerifyTOTPBackslash`, so such a view is the package's, and
|
||||
guarded. The same holds when the project also lists `payloadTotp(...)` in `plugins` itself.
|
||||
|
||||
**Your own 2FA screen.** Two ways, both keep the check:
|
||||
- Through the wrapped factory (the pattern from "Resetting 2FA"): set `views.VerifyTOTP.Component` (or `SetupTOTP`)
|
||||
on the config the factory returns. ipal-kit puts `SafeTotpView` in front of it. A server component gets every
|
||||
server prop with `searchParams.back` checked. A client component (`'use client'`) gets Payload's client props,
|
||||
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.
|
||||
|
||||
**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
|
||||
`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:
|
||||
- **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.
|
||||
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).
|
||||
|
||||
**Check:** log in with the password only, open
|
||||
`/admin/verify-totp?back=https%3A%2F%2Fexample.com%2F`, enter the code: you must land on `/admin`, not on
|
||||
example.com. With `back=%2Fadmin%2Fcollections%2Fpages` you must land on that list.
|
||||
@@ -700,7 +732,8 @@ 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.
|
||||
`safeAdminBack`, `wrapTotpViews`, `SafeTotpView` are exported. The stale import-map warning that comes with it:
|
||||
`twoFactor.importMapCheck: false`.
|
||||
- **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.
|
||||
|
||||
@@ -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 |
|
||||
| the 2FA setup or verify screen fails with `[ipal] The admin import map has no "@clocklimited/payload-2fa/rsc#TOTPVerify"` (or `#TOTPSetup`), or the console says `PayloadComponent not found in importMap` for `@intecion/ipal-kit/admin#SafeTotpView` | the import map was not regenerated after an upgrade that added the `back` link check (`twoFactor.safeBack`) | `pnpm payload generate:importmap`, commit `importMap.js`, `rm -rf .next`, redeploy |
|
||||
| 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 |
|
||||
| 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) |
|
||||
| `Cannot destructure property 'config'` / UI hooks without context | two copies of `@payloadcms/ui` | `pnpm why @payloadcms/ui`; one version + `pnpm.overrides`; `ls node_modules/@intecion/ipal-kit/node_modules/@payloadcms` = empty |
|
||||
|
||||
@@ -38,6 +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.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 |
|
||||
|
||||
@@ -31,7 +31,7 @@ Admin panel components from `@intecion/ipal-kit/admin` — the project does NOT
|
||||
| `CookieApprovalForm` | `@intecion/ipal-kit/admin` | Client part of the view: tick boxes, markers (New / Changed / Needs description), Edit links, the button. Props `pending`, `gone`, `unknownCategory`, `labels?`, `adminRoute?` — reuse it in your own view. |
|
||||
| `CookieCrawlAlert` | `@intecion/ipal-kit/admin` | Server Component: dashboard warning — "Waiting for approval: N" with a link to the approval view, and with the crawl violations or a failed crawl; renders nothing otherwise. Props `approval`, `crawl`. Injected with `cookieScanner` (`approval.dashboard: false` / `crawl.dashboard: false` drop its parts); after turning it on, `pnpm generate:importmap`. |
|
||||
| `CookieScanButton` | `@intecion/ipal-kit/admin` | "Scan cookies" box above the *Cookie review* list: integrations in use, optional extra names, runs `POST /api/ipal/cookie-scan`. Injected by the plugin with `cookieScanner`; after turning it on, `pnpm generate:importmap`. |
|
||||
| `SafeTotpView` | `@intecion/ipal-kit/admin` | Server admin view in front of the 2FA package's setup and verify views: replaces the `back` query value with a checked one and renders the package's view (found in the import map by the serverProp `ipalTotpView`; `ipalSafeBack` = own rule). Registered by the plugin with `twoFactor` (`twoFactor.safeBack`, on by default). After upgrading, `pnpm generate:importmap`. Check: password only → `/admin/verify-totp?back=https%3A%2F%2Fexample.com%2F` → code → `/admin`. Own registration: `Component: { path: '@intecion/ipal-kit/admin#SafeTotpView', serverProps: { ipalTotpView: '<path>' } }` + that path in `admin.dependencies`. |
|
||||
| `SafeTotpView` | `@intecion/ipal-kit/admin` | Server admin view in front of the 2FA package's setup and verify views: replaces the `back` query value with a checked one and renders the view named by the serverProp `ipalTotpView` (a path or `{ path, exportName }`, found in the import map) the way Payload renders a view: a server component gets all server props, a client component only Payload's client props, `ipalTotpClientProps`, `back` and `searchParams` (both checked). `ipalSafeBack` = own rule. Registered by the plugin with `twoFactor` (`twoFactor.safeBack`, on by default). After upgrading, `pnpm generate:importmap`. Check: password only → `/admin/verify-totp?back=https%3A%2F%2Fexample.com%2F` → code → `/admin`. Own registration: `Component: { path: '@intecion/ipal-kit/admin#SafeTotpView', serverProps: { ipalTotpView: '<path>' } }` + that path in `admin.dependencies`. |
|
||||
| `TotpRedirectProvider` | `@intecion/ipal-kit/admin` | Client admin provider: sends a user without TOTP to `/admin/setup-totp?back=…` and a user whose session has not passed TOTP to `/admin/verify-totp?back=…` (path read in the browser; never redirects away from those screens or logout; renders nothing while redirecting). Injected by the plugin with `twoFactor` in place of the package's header-based provider; swap with `twoFactor.provider`. After upgrading, `pnpm generate:importmap`. Check: a new admin lands on `setup-totp?back=%2Fadmin` with the QR code. Props type `TotpRedirectProviderProps` (`forceSetup`) |
|
||||
| `IntecionCredit` | `@intecion/ipal-kit/admin` | The line "Technology support: Intecion.com" (admin language; `agency` prop = the name) below the nav and below the login form (`variant: 'nav' \| 'login'`). Injected by the plugin with `whiteLabel`; turn off: `whiteLabel: { credit: false }` or `agency: false`. |
|
||||
| `buildAdminMeta({ agency, apiRoute?, defaultLocale?, meta?, options? })` | `@intecion/ipal-kit` | The `adminMeta` step: static panel meta (robots, preview image, icon) without overwriting keys in `meta`; returns `{ meta, resolved }` |
|
||||
@@ -588,7 +588,7 @@ Server only (`pnpm payload run`); never import it from client code, the Payload
|
||||
| `withSecurityConfig(nextConfig, { hidePoweredBy? })` | `@intecion/ipal-kit` | Next config wrapper: `poweredByHeader: false` + drops `X-Powered-By` from `headers()` (Next's "Next.js" and withPayload's "Next.js, Payload"). `withPayload(withSecurityConfig(nextConfig))`; `hidePoweredBy: false` = no change. |
|
||||
| `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; returns `{ views, dependencies }` (`dependencies` → `admin.dependencies`, so the package's views stay in the import map). What `ipalKit` runs after the 2FA factory; for a project that registers the 2FA package itself. |
|
||||
| `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. |
|
||||
| `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'`. |
|
||||
|
||||
@@ -227,7 +227,9 @@ the panel shows Site settings, Site integrations, Cookies, Form messages, the Fo
|
||||
Verify attempts: 5 per account in 10 minutes (`twoFactor.verifyLimit`).
|
||||
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.
|
||||
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).
|
||||
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`.
|
||||
|
||||
@@ -139,9 +139,13 @@ panel opens and a document saves.
|
||||
notice's close button follow the language by themselves.
|
||||
|
||||
**→ the release with `twoFactor.safeBack` (CHANGELOG "Unreleased — the `back` link of the 2FA screens"; PROGRAMISTA §6, item 67; security.md) — required with 2FA on:**
|
||||
1. `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. Without the
|
||||
new import map the two screens fail with `[ipal] The admin import map has no "…"` — nobody can enter a code.
|
||||
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.
|
||||
**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,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]))
|
||||
|
||||
+40
-4
@@ -33,7 +33,8 @@ import { buildGlobalRevalidateHook } from './modules/hooks/buildRevalidateHook.j
|
||||
import { withFillLocales } from './modules/hooks/fillEmptyLocales.js'
|
||||
import { buildLocalizationConfig, validateI18nConfig } from './modules/i18n/index.js'
|
||||
import { buildSystemPagesFields } from './modules/pages/index.js'
|
||||
import { wrapTotpViews } from './modules/security/totp/safeBack.js'
|
||||
import { missingImportMapEntries } from './modules/security/totp/importMapCheck.js'
|
||||
import { changedViewKeys, SAFE_TOTP_VIEW, wrapTotpViews } from './modules/security/totp/safeBack.js'
|
||||
import {
|
||||
buildGuardStrategy,
|
||||
ensurePayloadGuarded,
|
||||
@@ -92,7 +93,7 @@ export const ipalKit = (options: IpalOptions): Plugin => {
|
||||
if (options.enabled === false) {
|
||||
return {
|
||||
...config,
|
||||
admin: { ...config.admin, components: incomingConfig.admin?.components },
|
||||
admin: { ...config.admin, components: incomingConfig.admin?.components, dependencies: incomingConfig.admin?.dependencies },
|
||||
endpoints: incomingConfig.endpoints,
|
||||
onInit: incomingConfig.onInit,
|
||||
}
|
||||
@@ -171,6 +172,8 @@ export const ipalKit = (options: IpalOptions): Plugin => {
|
||||
let secondFactorGuard = false
|
||||
/** The 2FA collection, when 2FA is on. */
|
||||
let twoFactorCollection: null | string = null
|
||||
/** Set when the committed admin import map lacks the 2FA view wrapper (production). */
|
||||
let staleImportMap: null | string = null
|
||||
/** This config's entry in the staff registry until a Payload instance takes it over. */
|
||||
const staffToken = {}
|
||||
/**
|
||||
@@ -230,7 +233,7 @@ export const ipalKit = (options: IpalOptions): Plugin => {
|
||||
)
|
||||
}
|
||||
const endpointsBefore = new Set(config.endpoints ?? [])
|
||||
const viewsBefore = new Set(Object.keys(config.admin?.components?.views ?? {}))
|
||||
const viewsBefore: Record<string, unknown> = { ...config.admin?.components?.views }
|
||||
const entityEndpointsBefore = new Map<string, Set<unknown>>(
|
||||
[...(config.collections ?? []), ...(config.globals ?? [])].map((e) => [e.slug, new Set<unknown>(Array.isArray(e.endpoints) ? e.endpoints : [])]),
|
||||
)
|
||||
@@ -253,6 +256,11 @@ export const ipalKit = (options: IpalOptions): Plugin => {
|
||||
config.collections = guardNewEntityEndpoints(config.collections, entityEndpointsBefore, target, guards as never)
|
||||
config.globals = guardNewEntityEndpoints(config.globals, entityEndpointsBefore, target, guards as never)
|
||||
twoFactorCollection = target
|
||||
// The views the 2FA package registered, by object: it REPLACES a view the project (or an
|
||||
// earlier run of the package, or of ipalKit) already had under its keys, so a key that
|
||||
// existed before is no sign that the view is the project's own. Taken here, before the
|
||||
// texts step below re-creates those objects.
|
||||
const viewsFromPackage = changedViewKeys(viewsBefore, { ...config.admin?.components?.views })
|
||||
|
||||
// The package wraps only what is in the config right now. ipal-kit's own
|
||||
// globals and collections come later, so they get ipal-kit's guard at the
|
||||
@@ -344,7 +352,7 @@ export const ipalKit = (options: IpalOptions): Plugin => {
|
||||
if (tf.safeBack !== false) {
|
||||
const wrapped = wrapTotpViews(
|
||||
(config.admin?.components?.views ?? {}) as Record<string, { Component?: unknown; path?: string }>,
|
||||
(key) => !viewsBefore.has(key),
|
||||
(key) => viewsFromPackage.has(key),
|
||||
typeof tf.safeBack === 'function' ? tf.safeBack : undefined,
|
||||
)
|
||||
if (Object.keys(wrapped.dependencies).length) {
|
||||
@@ -354,6 +362,27 @@ export const ipalKit = (options: IpalOptions): Plugin => {
|
||||
// keeps the package's own views in the import map: the wrapper renders them from there
|
||||
dependencies: { ...config.admin?.dependencies, ...wrapped.dependencies },
|
||||
}
|
||||
// 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.
|
||||
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}`
|
||||
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, clientProps: { ...p.clientProps, staleImportMap: true } }
|
||||
: p,
|
||||
),
|
||||
},
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
@@ -724,6 +753,13 @@ export const ipalKit = (options: IpalOptions): Plugin => {
|
||||
// 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").',
|
||||
)
|
||||
}
|
||||
if (twoFactorCollection) {
|
||||
const uncovered = staffCollectionSlugs(payload).filter((slug) => slug !== twoFactorCollection)
|
||||
if (uncovered.length) {
|
||||
|
||||
@@ -242,6 +242,15 @@ export type IpalOptions = {
|
||||
* package version the check does not recognise; docs/security.md.
|
||||
*/
|
||||
guard?: false
|
||||
/**
|
||||
* Check, at start in production, that the committed admin import map has
|
||||
* the entry `safeBack` needs (`@intecion/ipal-kit/admin#SafeTotpView`).
|
||||
* Without it Payload renders the 2FA screens empty and nobody can sign in;
|
||||
* with the check the server log says so at every start and the 2FA screens
|
||||
* show a message instead of nothing. On by default; `false` skips the file
|
||||
* read, the log line and the message.
|
||||
*/
|
||||
importMapCheck?: false
|
||||
/** Name shown in the authenticator app (e.g. company/site name). */
|
||||
issuer: string
|
||||
/**
|
||||
|
||||
+200
-5
@@ -1,13 +1,18 @@
|
||||
import type { Config } from 'payload'
|
||||
|
||||
import { payloadTotp } from '@clocklimited/payload-2fa'
|
||||
import { payloadTotp as payloadTotpBeta7 } from '@clocklimited/payload-2fa'
|
||||
import { mkdir, mkdtemp, rm, writeFile } from 'node:fs/promises'
|
||||
import os from 'node:os'
|
||||
import path from 'node:path'
|
||||
import { payloadTotp as payloadTotpBeta1 } from 'payload-2fa-beta1'
|
||||
import React from 'react'
|
||||
import { renderToStaticMarkup } from 'react-dom/server'
|
||||
import { describe, expect, test } from 'vitest'
|
||||
import { describe, expect, test, vi } from 'vitest'
|
||||
|
||||
import type { I18nConfig } from '../src/modules/i18n/types.js'
|
||||
|
||||
import { safeAdminBack, wrapTotpViews } from '../src/modules/security/totp/safeBack.js'
|
||||
import { findImportMapFile, missingImportMapEntries } from '../src/modules/security/totp/importMapCheck.js'
|
||||
import { changedViewKeys, safeAdminBack, wrapTotpViews } from '../src/modules/security/totp/safeBack.js'
|
||||
import { SafeTotpView } from '../src/modules/security/totp/SafeTotpView.js'
|
||||
import { ipalKit } from '../src/plugin.js'
|
||||
|
||||
@@ -119,6 +124,15 @@ describe('wrapTotpViews', () => {
|
||||
})
|
||||
})
|
||||
|
||||
test('keeps exportName and clientProps of the original registration', () => {
|
||||
const out = wrapTotpViews({ V: { Component: { clientProps: { tone: 'dark' }, exportName: 'Verify', path: 'mine/views' }, path: '/verify-totp' } }, () => true, undefined)
|
||||
expect(out.views.V.Component).toEqual({
|
||||
path: '@intecion/ipal-kit/admin#SafeTotpView',
|
||||
serverProps: { ipalSafeBack: undefined, ipalTotpClientProps: { tone: 'dark' }, ipalTotpView: { exportName: 'Verify', path: 'mine/views' } },
|
||||
})
|
||||
expect(out.dependencies).toEqual({ 'ipal-totp-view:mine/views#Verify': { type: 'component', exportName: 'Verify', path: 'mine/views' } })
|
||||
})
|
||||
|
||||
test('leaves alone what the project registered itself, and is safe to run twice', () => {
|
||||
expect(wrapTotpViews(views, () => false, undefined)).toEqual({ dependencies: {}, views })
|
||||
const once = wrapTotpViews(views, () => true, undefined)
|
||||
@@ -128,14 +142,68 @@ describe('wrapTotpViews', () => {
|
||||
})
|
||||
})
|
||||
|
||||
describe('ipalKit with the real 2FA package', () => {
|
||||
const build = (twoFactor: false | Record<string, unknown>, extra: Partial<Config> = {}) =>
|
||||
describe.each([
|
||||
['3.0.0-beta.7', payloadTotpBeta7],
|
||||
['3.0.0-beta.1', payloadTotpBeta1 as unknown as typeof payloadTotpBeta7],
|
||||
])('ipalKit with the real 2FA package %s', (_version, payloadTotp) => {
|
||||
const build = (twoFactor: false | Record<string, unknown>, extra: Partial<Config> = {}, options: Record<string, unknown> = {}) =>
|
||||
ipalKit({
|
||||
access: { authCollection: 'users' },
|
||||
i18n,
|
||||
twoFactor: twoFactor === false ? false : ({ issuer: 'Example', plugin: payloadTotp, ...twoFactor } as never),
|
||||
...options,
|
||||
})({ collections: [], secret: 'x', ...extra } as unknown as Config)
|
||||
|
||||
/** Keys of views that still point straight at the 2FA package: unguarded. */
|
||||
const raw = (config: Config) =>
|
||||
Object.entries(config.admin?.components?.views ?? {})
|
||||
.filter(([, view]) => {
|
||||
const c = (view as { Component?: { path?: string } | string }).Component
|
||||
return (typeof c === 'string' ? c : (c?.path ?? '')).includes('payload-2fa')
|
||||
})
|
||||
.map(([key]) => key)
|
||||
|
||||
// The package replaces a view that already stands under one of its keys: such a key is not "the project's own".
|
||||
test('a view the project had under a package key is replaced by the package, and guarded', async () => {
|
||||
const config = await build({}, { admin: { components: { views: { SetupTOTPBackslash: { Component: 'mine#S', path: '/setup-totp' }, VerifyTOTP: { Component: 'mine#V', path: '/verify-totp' } } } } } as never)
|
||||
expect(raw(config)).toEqual([])
|
||||
expect(component(config, 'VerifyTOTP')?.path).toBe('@intecion/ipal-kit/admin#SafeTotpView')
|
||||
expect(component(config, 'SetupTOTPBackslash')?.path).toBe('@intecion/ipal-kit/admin#SafeTotpView')
|
||||
})
|
||||
|
||||
test('the package registered by the project too, before ipalKit: still guarded', async () => {
|
||||
const first = payloadTotp({ collection: 'users', totp: { issuer: 'E' } } as never)({ collections: [{ slug: 'users', auth: true, fields: [] }], secret: 'x' } as never)
|
||||
expect(raw(first).length).toBe(4)
|
||||
expect(raw(await build({}, first as never))).toEqual([])
|
||||
})
|
||||
|
||||
test('ipalKit run over its own output (a config reused): still guarded', async () => {
|
||||
const once = await build({})
|
||||
const twice = await build({}, { admin: once.admin } as never)
|
||||
expect(raw(twice)).toEqual([])
|
||||
expect(component(twice, 'VerifyTOTP')?.serverProps?.ipalTotpView).toBe('@clocklimited/payload-2fa/rsc#TOTPVerify')
|
||||
})
|
||||
|
||||
test('the same incoming config object built twice', async () => {
|
||||
const incoming = { admin: { components: { views: {} } }, collections: [], secret: 'x' } as unknown as Config
|
||||
const plugin = () => ipalKit({ access: { authCollection: 'users' }, i18n, twoFactor: { issuer: 'E', plugin: payloadTotp } as never })(incoming)
|
||||
expect(raw(await plugin())).toEqual([])
|
||||
expect(raw(await plugin())).toEqual([])
|
||||
})
|
||||
|
||||
test('safeBack: true, null or undefined is on; only false is off', async () => {
|
||||
for (const value of [true, null, undefined]) {expect(raw(await build({ safeBack: value }))).toEqual([])}
|
||||
expect(raw(await build({ safeBack: false })).length).toBe(4)
|
||||
})
|
||||
|
||||
test('enabled: false leaves no views and no import-map dependencies behind', async () => {
|
||||
const config = await build({}, { admin: { dependencies: { mine: { type: 'component', path: 'mine#Thing' } } }, collections: [{ slug: 'users', auth: true, fields: [] }] } as never, { enabled: false })
|
||||
expect(JSON.stringify(config.admin?.components ?? {})).not.toMatch(/SafeTotp|payload-2fa/)
|
||||
expect(config.admin?.dependencies).toEqual({ mine: { type: 'component', path: 'mine#Thing' } })
|
||||
const bare = await build({}, { collections: [{ slug: 'users', auth: true, fields: [] }] } as never, { enabled: false })
|
||||
expect(bare.admin?.dependencies).toBeUndefined()
|
||||
})
|
||||
|
||||
const component = (config: Config, key: string) =>
|
||||
(config.admin?.components?.views as Record<string, { Component: { path: string; serverProps?: Record<string, unknown> } }> | undefined)?.[key]?.Component
|
||||
|
||||
@@ -236,3 +304,130 @@ describe('SafeTotpView', () => {
|
||||
expect(() => render({}, { importMap: {} })).toThrow(/generate:importmap/)
|
||||
})
|
||||
})
|
||||
|
||||
describe('safeAdminBack with values that are not a string', () => {
|
||||
test.each([[['/admin', 'javascript:1']], [{}], [null], [1], [{ toString: () => 'javascript:1' }]])('%s', (value) => {
|
||||
expect(safeAdminBack(value as never, { adminRoute: '/admin' })).toBe('/admin')
|
||||
})
|
||||
})
|
||||
|
||||
describe('changedViewKeys', () => {
|
||||
test('a key counts when its object is another one, whether or not the key existed', () => {
|
||||
const kept = { path: '/a' }
|
||||
expect([...changedViewKeys({ A: kept, B: { path: '/b' } }, { A: kept, B: { path: '/b' }, C: { path: '/c' } })].sort()).toEqual(['B', 'C'])
|
||||
})
|
||||
})
|
||||
|
||||
describe('SafeTotpView in front of a client component', () => {
|
||||
// What a 'use client' export looks like on the server: a reference Payload must not hand server props to.
|
||||
const ClientView = Object.assign(() => null, { $$typeof: Symbol.for('react.client.reference') })
|
||||
const ServerView = () => null
|
||||
const props = (view: unknown) => ({
|
||||
clientConfig: { routes: { admin: '/admin' } },
|
||||
i18n: { t: () => '' },
|
||||
importMap: { 'mine/views#Verify': view },
|
||||
initPageResult: { req: { payload: { config: { routes: { admin: '/admin' }, serverURL: '' } } } },
|
||||
ipalTotpClientProps: { tone: 'dark' },
|
||||
ipalTotpView: { exportName: 'Verify', path: 'mine/views' },
|
||||
payload: { find: () => null },
|
||||
pluginOptions: { adminManageAccess: () => true },
|
||||
searchParams: { back: 'javascript:alert(1)', other: 'kept' },
|
||||
viewType: 'verify',
|
||||
})
|
||||
const hasFunction = (value: unknown, seen = new Set<unknown>()): boolean => {
|
||||
if (typeof value === 'function') {return true}
|
||||
if (!value || typeof value !== 'object' || seen.has(value)) {return false}
|
||||
seen.add(value)
|
||||
return Object.values(value).some((v) => hasFunction(v, seen))
|
||||
}
|
||||
const call = SafeTotpView as unknown as (p: unknown) => React.ReactElement<Record<string, unknown>>
|
||||
|
||||
test('gets only props that can cross to the browser, with the checked back', () => {
|
||||
const element = call(props(ClientView))
|
||||
expect(element.type).toBe(ClientView)
|
||||
expect(hasFunction(element.props)).toBe(false) // a function prop is what crashed the screen with a 500
|
||||
expect(element.props).toEqual({
|
||||
back: '/admin',
|
||||
clientConfig: { routes: { admin: '/admin' } },
|
||||
searchParams: { back: '/admin', other: 'kept' },
|
||||
tone: 'dark',
|
||||
viewType: 'verify',
|
||||
})
|
||||
})
|
||||
|
||||
test('a server component still gets the server props', () => {
|
||||
const element = call(props(ServerView))
|
||||
expect(element.type).toBe(ServerView)
|
||||
expect(typeof (element.props.pluginOptions as { adminManageAccess: unknown }).adminManageAccess).toBe('function')
|
||||
expect(element.props.searchParams).toEqual({ back: '/admin', other: 'kept' })
|
||||
expect(element.props.tone).toBe('dark')
|
||||
expect(element.props.ipalTotpView).toBeUndefined()
|
||||
})
|
||||
})
|
||||
|
||||
describe('the stale import-map check', () => {
|
||||
const ENTRY = '@intecion/ipal-kit/admin#SafeTotpView'
|
||||
const project = async (layout: string, content: string) => {
|
||||
const root = await mkdtemp(path.join(os.tmpdir(), 'ipal-importmap-'))
|
||||
await mkdir(path.join(root, layout), { recursive: true })
|
||||
await writeFile(path.join(root, layout, 'importMap.js'), content)
|
||||
return root
|
||||
}
|
||||
|
||||
test('finds the file where Payload looks: app/, src/app/, a custom admin route, an explicit file', async () => {
|
||||
const a = await project('app/(payload)/admin', '')
|
||||
const b = await project('src/app/(payload)/admin', '')
|
||||
const c = await project('src/app/(payload)/panel', '')
|
||||
try {
|
||||
expect(await findImportMapFile({}, a)).toBe(path.join(a, 'app/(payload)/admin/importMap.js'))
|
||||
expect(await findImportMapFile({ admin: { importMap: { baseDir: b } } }, '/nowhere')).toBe(path.join(b, 'src/app/(payload)/admin/importMap.js'))
|
||||
expect(await findImportMapFile({ routes: { admin: '/panel' } }, c)).toBe(path.join(c, 'src/app/(payload)/panel/importMap.js'))
|
||||
expect(await findImportMapFile({ routes: { admin: '/panel' } }, a)).toBeNull()
|
||||
const explicit = path.join(a, 'app/(payload)/admin/importMap.js')
|
||||
expect(await findImportMapFile({ admin: { importMap: { importMapFile: explicit } } }, '/nowhere')).toBe(explicit)
|
||||
expect(await findImportMapFile({ admin: { importMap: { importMapFile: '/nowhere/importMap.js' } } }, a)).toBeNull()
|
||||
} finally {
|
||||
for (const dir of [a, b, c]) {await rm(dir, { force: true, recursive: true })}
|
||||
}
|
||||
})
|
||||
|
||||
test('in production ipalKit marks the redirect provider when the map lacks the wrapper; not otherwise', async () => {
|
||||
const stale = await project('src/app/(payload)/admin', 'export const importMap = { "@intecion/ipal-kit/admin#TotpRedirectProvider": X }')
|
||||
const current = await project('src/app/(payload)/admin', `export const importMap = { "${ENTRY}": Y }`)
|
||||
const flagged = async (baseDir: string, twoFactor: Record<string, unknown> = {}) => {
|
||||
const config = await ipalKit({ access: { authCollection: 'users' }, i18n, twoFactor: { issuer: 'E', plugin: payloadTotpBeta7, ...twoFactor } as never })({
|
||||
admin: { importMap: { baseDir } },
|
||||
collections: [],
|
||||
secret: 'x',
|
||||
} as unknown as Config)
|
||||
return JSON.stringify(config.admin?.components?.providers ?? []).includes('"staleImportMap":true')
|
||||
}
|
||||
const before = process.env.NODE_ENV
|
||||
try {
|
||||
vi.stubEnv('NODE_ENV', 'production')
|
||||
expect(await flagged(stale)).toBe(true)
|
||||
expect(await flagged(current)).toBe(false)
|
||||
expect(await flagged('/nowhere')).toBe(false) // file not found: unknown, not reported
|
||||
expect(await flagged(stale, { importMapCheck: false })).toBe(false)
|
||||
expect(await flagged(stale, { safeBack: false })).toBe(false) // nothing wrapped, nothing needed
|
||||
vi.stubEnv('NODE_ENV', 'development')
|
||||
expect(await flagged(stale)).toBe(false) // Payload regenerates the map in development
|
||||
} finally {
|
||||
vi.unstubAllEnvs()
|
||||
expect(process.env.NODE_ENV).toBe(before)
|
||||
for (const dir of [stale, current]) {await rm(dir, { force: true, recursive: true })}
|
||||
}
|
||||
})
|
||||
|
||||
test('reports a missing entry, never an unknown state', async () => {
|
||||
const stale = await project('src/app/(payload)/admin', 'export const importMap = { "@intecion/ipal-kit/admin#TotpRedirectProvider": X }')
|
||||
const current = await project('src/app/(payload)/admin', `export const importMap = { "${ENTRY}": Y }`)
|
||||
try {
|
||||
expect((await missingImportMapEntries({}, [ENTRY], stale)).missing).toEqual([ENTRY])
|
||||
expect((await missingImportMapEntries({}, [ENTRY], current)).missing).toEqual([])
|
||||
expect(await missingImportMapEntries({}, [ENTRY], '/nowhere')).toEqual({ file: null, missing: [] })
|
||||
} finally {
|
||||
for (const dir of [stale, current]) {await rm(dir, { force: true, recursive: true })}
|
||||
}
|
||||
})
|
||||
})
|
||||
|
||||
Reference in New Issue
Block a user