From 60f744e3adc4b49909fe4644cf4363bf67263999 Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?Rados=C5=82aw=20Smoli=C5=84ski?= Date: Wed, 28 Oct 2026 21:27:19 +0100 Subject: [PATCH] Fix the 2FA setup loop: setup-totp?back=null redirected to itself @clocklimited/payload-2fa's admin provider reads the current path from an x-pathname request header. Nothing sets it on /admin (the createProxy matcher skips /admin), so the path was null: every admin page, the setup screen too, redirected to /admin/setup-totp?back=null, forever. Every new admin on a site with 2FA got stuck. ipalKit now swaps that provider for its own TotpRedirectProvider (@intecion/ipal-kit/admin, client-side): it reads the path in the browser, never redirects away from the setup/verify screens or logout, and renders nothing while redirecting. twoFactor.provider takes a project component, or false to keep the package's. totpRedirectTarget / totpAdminPath export the rules. Projects run generate:importmap. Test: test/totpRedirect.test.ts (redirect walk, provider swap). Dev app: IPAL_DEV_2FA=1 turns 2FA on. Docs: security.md, CHANGELOG (Unreleased), AGENT.md, ipal-setup/-upgrade/-debug/-reference, PROGRAMISTA item 51. Co-Authored-By: Claude Opus 5.5 --- dev/app/(payload)/admin/importMap.js | 8 ++ dev/payload.config.ts | 4 +- docs/CHANGELOG.md | 18 ++++ docs/agent/AGENT.md | 4 +- docs/agent/skills/ipal-debug/SKILL.md | 1 + docs/agent/skills/ipal-reference/SKILL.md | 1 + .../skills/ipal-reference/resources/api.md | 2 + docs/agent/skills/ipal-setup/SKILL.md | 2 +- docs/agent/skills/ipal-upgrade/SKILL.md | 7 ++ docs/dev/PROGRAMISTA.md | 1 + docs/security.md | 47 ++++++++-- src/exports/admin.ts | 2 + src/index.ts | 4 + src/modules/security/index.ts | 2 + .../security/totp/TotpRedirectProvider.tsx | 48 +++++++++++ src/modules/security/totp/totpRedirect.ts | 53 ++++++++++++ src/plugin.ts | 29 +++++++ src/types.ts | 13 ++- test/totpRedirect.test.ts | 85 +++++++++++++++++++ 19 files changed, 321 insertions(+), 10 deletions(-) create mode 100644 src/modules/security/totp/TotpRedirectProvider.tsx create mode 100644 src/modules/security/totp/totpRedirect.ts create mode 100644 test/totpRedirect.test.ts diff --git a/dev/app/(payload)/admin/importMap.js b/dev/app/(payload)/admin/importMap.js index 03bd16f..7871f8e 100644 --- a/dev/app/(payload)/admin/importMap.js +++ b/dev/app/(payload)/admin/importMap.js @@ -1,3 +1,4 @@ +import { TOTPField as TOTPField_3eb2cc20d1a2569c2ccbafcee15bd128 } from '@clocklimited/payload-2fa/rsc' import { OverviewComponent as OverviewComponent_a8a977ebc872c5d5ea7ee689724c0860 } from '@payloadcms/plugin-seo/client' import { MetaTitleComponent as MetaTitleComponent_a8a977ebc872c5d5ea7ee689724c0860 } from '@payloadcms/plugin-seo/client' import { MetaDescriptionComponent as MetaDescriptionComponent_a8a977ebc872c5d5ea7ee689724c0860 } from '@payloadcms/plugin-seo/client' @@ -37,11 +38,15 @@ import { StatsNavLink as StatsNavLink_7568fe47d582ff15ce85d2e1873c2c23 } from '@ import { CookieCrawlAlert as CookieCrawlAlert_7568fe47d582ff15ce85d2e1873c2c23 } from '@intecion/ipal-kit/admin' import { StatsWidget as StatsWidget_7568fe47d582ff15ce85d2e1873c2c23 } from '@intecion/ipal-kit/admin' import { IntegrationAlerts as IntegrationAlerts_7568fe47d582ff15ce85d2e1873c2c23 } from '@intecion/ipal-kit/admin' +import { TotpRedirectProvider as TotpRedirectProvider_7568fe47d582ff15ce85d2e1873c2c23 } from '@intecion/ipal-kit/admin' +import { TOTPSetup as TOTPSetup_3eb2cc20d1a2569c2ccbafcee15bd128 } from '@clocklimited/payload-2fa/rsc' +import { TOTPVerify as TOTPVerify_3eb2cc20d1a2569c2ccbafcee15bd128 } from '@clocklimited/payload-2fa/rsc' import { StatsView as StatsView_7568fe47d582ff15ce85d2e1873c2c23 } from '@intecion/ipal-kit/admin' import { CollectionCards as CollectionCards_f9c02e79a4aed9a3924487c0cd4cafb1 } from '@payloadcms/next/rsc' /** @type import('payload').ImportMap */ export const importMap = { + "@clocklimited/payload-2fa/rsc#TOTPField": TOTPField_3eb2cc20d1a2569c2ccbafcee15bd128, "@payloadcms/plugin-seo/client#OverviewComponent": OverviewComponent_a8a977ebc872c5d5ea7ee689724c0860, "@payloadcms/plugin-seo/client#MetaTitleComponent": MetaTitleComponent_a8a977ebc872c5d5ea7ee689724c0860, "@payloadcms/plugin-seo/client#MetaDescriptionComponent": MetaDescriptionComponent_a8a977ebc872c5d5ea7ee689724c0860, @@ -81,6 +86,9 @@ export const importMap = { "@intecion/ipal-kit/admin#CookieCrawlAlert": CookieCrawlAlert_7568fe47d582ff15ce85d2e1873c2c23, "@intecion/ipal-kit/admin#StatsWidget": StatsWidget_7568fe47d582ff15ce85d2e1873c2c23, "@intecion/ipal-kit/admin#IntegrationAlerts": IntegrationAlerts_7568fe47d582ff15ce85d2e1873c2c23, + "@intecion/ipal-kit/admin#TotpRedirectProvider": TotpRedirectProvider_7568fe47d582ff15ce85d2e1873c2c23, + "@clocklimited/payload-2fa/rsc#TOTPSetup": TOTPSetup_3eb2cc20d1a2569c2ccbafcee15bd128, + "@clocklimited/payload-2fa/rsc#TOTPVerify": TOTPVerify_3eb2cc20d1a2569c2ccbafcee15bd128, "@intecion/ipal-kit/admin#StatsView": StatsView_7568fe47d582ff15ce85d2e1873c2c23, "@payloadcms/next/rsc#CollectionCards": CollectionCards_f9c02e79a4aed9a3924487c0cd4cafb1 } diff --git a/dev/payload.config.ts b/dev/payload.config.ts index d9dcd27..617aba1 100644 --- a/dev/payload.config.ts +++ b/dev/payload.config.ts @@ -1,3 +1,4 @@ +import { payloadTotp } from '@clocklimited/payload-2fa' import { sqliteAdapter } from '@payloadcms/db-sqlite' import { lexicalEditor } from '@payloadcms/richtext-lexical' import { ipalKit } from '../src/index.js' @@ -73,7 +74,8 @@ export default buildConfig({ seo: { collections: ['posts', 'pages'] }, stats: true, // 2FA is enforced by default; the dev sandbox opts out so it boots without an authenticator. - twoFactor: false, + // IPAL_DEV_2FA=1 turns it on (first-login setup and verify screens). + twoFactor: process.env.IPAL_DEV_2FA ? { issuer: 'ipal-kit dev', plugin: payloadTotp } : false, }), ], secret: process.env.PAYLOAD_SECRET || 'test-secret_key', diff --git a/docs/CHANGELOG.md b/docs/CHANGELOG.md index c4f33f6..693af11 100644 --- a/docs/CHANGELOG.md +++ b/docs/CHANGELOG.md @@ -8,6 +8,24 @@ versions at once, go through every "Requires project changes" section in order, version you have. A new release = a new section at the top; we remove the oldest ones only once there are more than 20. +## Unreleased (after 1.14.1) + +### Fixed +- **2FA setup loop.** A user without TOTP (every new admin) was sent to `/admin/setup-totp?back=null`, and that page + redirected to itself forever. `@clocklimited/payload-2fa`'s admin provider reads the path from an `x-pathname` + request header, which nothing sets on `/admin` (the `createProxy` matcher skips it). ipal-kit now swaps in its own + provider, `TotpRedirectProvider` (`@intecion/ipal-kit/admin`): it reads the path in the browser, never redirects + away from the setup or verify screen or from logout, and renders nothing while a redirect is pending. + +### New +- **`twoFactor.provider`** — your own redirect component (path or `{ path, clientProps, serverProps }`), or `false` + to keep the package's (then set `x-pathname` on `/admin` yourself). **`totpRedirectTarget` / `totpAdminPath`** — + the redirect rules as a pure function, for your own provider. + +### Requires project changes +- With 2FA on: `pnpm payload generate:importmap` (adds `@intecion/ipal-kit/admin#TotpRedirectProvider`), commit + `importMap.js`, redeploy. **Check:** a new admin lands on `/admin/setup-totp?back=%2Fadmin` and sees the QR code. + ## 1.14.1 Response-header hardening from the intecion.com audit: hide `X-Powered-By`, and a Content-Security-Policy the project diff --git a/docs/agent/AGENT.md b/docs/agent/AGENT.md index 1f0e40f..f6f1789 100644 --- a/docs/agent/AGENT.md +++ b/docs/agent/AGENT.md @@ -109,7 +109,7 @@ site), **P** = a test in the panel. Full code: PROGRAMISTA.md §2. | 10 | **Forms** | every form from a **seed** (`scripts/seed-form-*.ts`: fields, confirmation, mail to the company **and** confirmation to the customer, every language); a block with `` + `formClasses.ts` (look, once); `actions.ts` = `createSubmitAction({ getCachedPayload, headers })`; `forms: {…}` in `ipalKit`; `email: mailAdapter()` | `RenderForm` (`/rsc`), `createSubmitAction`, `mailAdapter` | A, P | | 11 | **Turnstile** | `` in `[locale]/layout.tsx` (wires `TurnstileProvider` with the key from the panel); `RenderForm` renders the widget; keys in Site integrations | `SiteProviders`, `getTurnstileConfig`, `TurnstileProvider` | A, P | | 12 | Consent + analytics | Consent Mode: `'advanced'` (default — the Google tag loads at once with every signal `denied`) or `'basic'` (`` — no request to Google before consent; a client who wants zero requests), the choice goes to "Project decisions"; `ipalKit({ consentLog: true })` (without it the `/api/ipal/consent` endpoint does not exist) + `}>` (ConsentProvider, banner, CookieButton, Analytics in the right order); settings window mode (`settings`: `inline` / `modal` / `detailed`) per the design, brief is silent → `detailed`, the decision goes to "Project decisions"; tool IDs in the panel; the cookie list from a scan (`cookieScanner: true` → *Cookie review* → **Scan cookies** → the editor accepts; or cookie-scan → import) — feeds `` on the policy page **and** the lists in the `detailed` window; Cookie banner → Settings window → Cookie list headings in every language | consent.md, analytics.md | A, `ipal-consent-check` | -| 13 | Security | `buildSecurityHeaders` in `next.config.ts`; `withPayload(withSecurityConfig(nextConfig))` (no `X-Powered-By`); CSP: `buildSecurityHeaders({ csp: { mode: 'report-only', reportUri: '/api/csp-report', … } })` + `buildAdminCspHeaders` on `/admin/:path*` + `src/app/api/csp-report/route.ts` (`createCspReportRoute`) → read the reports → `mode: 'enforce'`; `twoFactor: { issuer, plugin: payloadTotp }`; `IPAL_IP_HEADER` in production | security.md, forms.md | A | +| 13 | Security | `buildSecurityHeaders` in `next.config.ts`; `withPayload(withSecurityConfig(nextConfig))` (no `X-Powered-By`); CSP: `buildSecurityHeaders({ csp: { mode: 'report-only', reportUri: '/api/csp-report', … } })` + `buildAdminCspHeaders` on `/admin/:path*` + `src/app/api/csp-report/route.ts` (`createCspReportRoute`) → read the reports → `mode: 'enforce'`; `twoFactor: { issuer, plugin: payloadTotp }` + `generate:importmap` (`TotpRedirectProvider`; check: a new admin lands on `/admin/setup-totp?back=%2Fadmin` with the QR, no reloading); `IPAL_IP_HEADER` in production | security.md, forms.md | A | | 14 | Operations | `src/app/api/health/route.ts` (`healthRoute`); `src/instrumentation.ts` with `assertEnv(ipalEnvRules({ storage: true, ipHeader: true }))`; staging with `IPAL_NOINDEX=1`; smoke tests (§8a) | `healthRoute`, `assertEnv`, `ipalEnvRules` | A | | 15 | System pages | Site settings → System pages: homepage, 404, privacy policy, cookies; legal links in the footer by role (`getSystemLinks(locale)`) | `getSystemLinks`, `getSystemPagePath`, `getNotFoundPage` | P | | 16 | **Nothing hardcoded** | every text, link, image, file, company data from the panel; domains and keys from `.env` (§2) | — | A, P | @@ -986,7 +986,7 @@ add missing hosts with flags / `extra`; (3) change `mode` to `'enforce'` in both | Consent records / stats visits: read and delete admin (stats view and chart follow `stats-visits` read access) | omit `consentLog` / `stats` | `consentLog.collectionOverrides`, `stats.collectionOverrides` (object merges `access`/`admin`/`hooks`, function takes over; `applyCollectionOverride`) | | Injected `users`: admin manages everyone, others only themselves | — | `access.authAccess` (your keys win); your own `users` collection wins whole | | First registered account = admin | `access.firstUserAdmin: false` | `buildRolesField(defaultRole, { firstUserAdmin })` | -| 2FA on the panel's login collection, mismatch = startup error | `twoFactor: false` (discouraged) | `twoFactor.collectionSlug`, `allowCollectionMismatch: true` | +| 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) | | `enabled: false` keeps the schema | — | — (no endpoints, `onInit` or admin components; no DROP TABLE in `migrate:create`) | | No client IP = one shared `unknown-ip` bucket at 20× the limit | `setUnknownIpFactor(0)` (only with a limiter in front) | `setUnknownIpFactor(n)`; `UNKNOWN_IP_FACTOR` | | Turnstile token domain not checked | (default) | `createSubmitAction({ turnstileHostnames })`, `verifyTurnstile({ hostnames })` — leave empty in dev | diff --git a/docs/agent/skills/ipal-debug/SKILL.md b/docs/agent/skills/ipal-debug/SKILL.md index 91665c7..c88d86a 100644 --- a/docs/agent/skills/ipal-debug/SKILL.md +++ b/docs/agent/skills/ipal-debug/SKILL.md @@ -52,6 +52,7 @@ 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 | +| 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 | | empty SEO tab, no Forms | mismatched `@payloadcms/*` versions | all `@payloadcms/*` = the `payload` version | | upload rejected "Image is … Tick Optimize" | `buildOptimizeUploadHook` (intended) | tick the checkbox or prepare the file; limit in the hook options | diff --git a/docs/agent/skills/ipal-reference/SKILL.md b/docs/agent/skills/ipal-reference/SKILL.md index b3fd40f..4ad8fd0 100644 --- a/docs/agent/skills/ipal-reference/SKILL.md +++ b/docs/agent/skills/ipal-reference/SKILL.md @@ -33,6 +33,7 @@ description: Complete map of everything @intecion/ipal-kit provides — every ip | `twoFactor.issuer` | — (required) | name in the authenticator app | — | | `twoFactor.plugin` | — (required) | injected `payloadTotp` (the plugin does not import the peer) | missing function → throws | | `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.allowCollectionMismatch` | `false` | allows `collectionSlug` ≠ `admin.user` (panel users of the other collection then skip 2FA) | `true` only when you protect a second auth collection on purpose | | `whiteLabel` | none | `admin.components.graphics.Logo/Icon` (`AdminLogo`/`AdminIcon`) from Site settings + vendor credit | omit / `false`; `true` = defaults | | `whiteLabel.settingsSlug` | `'site-settings'` | global it reads the logo/name from | — | diff --git a/docs/agent/skills/ipal-reference/resources/api.md b/docs/agent/skills/ipal-reference/resources/api.md index 5ee33e3..28983d9 100644 --- a/docs/agent/skills/ipal-reference/resources/api.md +++ b/docs/agent/skills/ipal-reference/resources/api.md @@ -27,6 +27,7 @@ Admin panel components from `@intecion/ipal-kit/admin` — the project does NOT | `AdminIcon` | `@intecion/ipal-kit/admin` | Server Component: small panel nav icon from SiteSettings `favicon`, fallback initials. Injected by the plugin with `whiteLabel`; after turning the option on, `pnpm generate:importmap`. | | `CookieCrawlAlert` | `@intecion/ipal-kit/admin` | Server Component: dashboard warning after a cookie crawl with violations or new unknown cookies, or a failed crawl; renders nothing otherwise. Injected with `cookieScanner.crawl` (`dashboard: false` drops it); 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`. | +| `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 supported by Intecion.com" below the nav and below the login form (`variant: 'nav' \| 'login'`). Injected by the plugin with `whiteLabel`; turn off: `whiteLabel: { credit: false }`. | ## Readable array rows in the panel (`admin-ui`) — details: `node_modules/@intecion/ipal-kit/docs/links.md` @@ -510,6 +511,7 @@ Server only (`pnpm payload run`); never import it from client code, the Payload |---|---|---| | `buildSecurityHeaders({ hsts?, csp?, additional?, coop?, frameOptions?, permissionsPolicy?, referrerPolicy?, … })` | `@intecion/ipal-kit` | Returns `SecurityHeader[]` (HSTS, X-Frame-Options, nosniff, Referrer-Policy, Permissions-Policy, COOP; with `IPAL_NOINDEX` also `X-Robots-Tag`) for `headers()` in `next.config.ts`. `csp` = `buildCsp` args → the CSP header (+ `Reporting-Endpoints` with `reportUri`); off by default. `additional` overrides by key. | | `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. | +| `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'`. | | `buildCspHeaders(args)` | `@intecion/ipal-kit` | `[csp, Reporting-Endpoints]` (the second only with `reportUri`). | | `buildAdminCsp(args)` / `buildAdminCspHeaders(args)` | `@intecion/ipal-kit` | Looser policy for Payload's admin: Monaco from `cdn.jsdelivr.net`, `blob:` workers, `https:` images, Live Preview `frame-src 'self'`, `frame-ancestors 'self'`. Rule `{ source: '/admin/:path*', headers: buildAdminCspHeaders({ mode, reportUri }) }` AFTER the site-wide rule. | diff --git a/docs/agent/skills/ipal-setup/SKILL.md b/docs/agent/skills/ipal-setup/SKILL.md index d352284..8b84fed 100644 --- a/docs/agent/skills/ipal-setup/SKILL.md +++ b/docs/agent/skills/ipal-setup/SKILL.md @@ -137,7 +137,7 @@ behind Cloudflare, `x-forwarded-for` behind a plain proxy), `IPAL_NOINDEX` (empt One language: one entry in `locales`, no `[locale]` folder (i18n.md). **Check.** `pnpm payload generate:importmap` (whiteLabel adds admin components) and `pnpm generate:types` without -errors; `pnpm dev`, `/admin`: first-user screen → after saving, TOTP setup is enforced (QR); +errors (the import map lists `@intecion/ipal-kit/admin#TotpRedirectProvider`); `pnpm dev`, `/admin`: first-user screen → after saving, TOTP setup is enforced (`/admin/setup-totp?back=%2Fadmin`, QR, no reloading); the panel shows Site settings, Site integrations, Cookie banner, Notifications, the Forms group, Consent records. `curl -s -o /dev/null -w '%{http_code}' -X POST localhost:3000/api/ipal/consent -H 'content-type: application/json' -d '{"id":"0123456789abcdef","version":1,"state":{"necessary":true,"functional":false,"analytics":false,"marketing":false}}'` → `201`. diff --git a/docs/agent/skills/ipal-upgrade/SKILL.md b/docs/agent/skills/ipal-upgrade/SKILL.md index 5072f9e..dcd9d3f 100644 --- a/docs/agent/skills/ipal-upgrade/SKILL.md +++ b/docs/agent/skills/ipal-upgrade/SKILL.md @@ -112,6 +112,13 @@ the banner → `` and remove the copy. With `d Nothing else to change: the statistics tab title, the cookie scanner's integration names and the maintenance notice's close button follow the language by themselves. +**→ after 1.14.1 (PROGRAMISTA §6, item 51; 2FA setup loop; security.md) — required with 2FA on:** +1. `pnpm payload generate:importmap` — the plugin swaps `@clocklimited/payload-2fa/rsc#TOTPProvider` for + `@intecion/ipal-kit/admin#TotpRedirectProvider`; commit `importMap.js`, `rm -rf .next`, redeploy on Coolify. + **Check:** log in as a new admin (or a throwaway one) → `/admin/setup-totp?back=%2Fadmin` with the QR code, no + reloading; after the code → back on `/admin`. A project that wrote its own `x-pathname` proxy rule for `/admin` + as a workaround can drop it. + **→ 1.14.1 (PROGRAMISTA §6, item 50; X-Powered-By, CSP; security.md) — nothing required, recommended in this order:** 1. **Hide `X-Powered-By`** — `next.config.ts`: `export default withPayload(withSecurityConfig(nextConfig))` (import `withSecurityConfig` from `@intecion/ipal-kit`); remove a hand-written `poweredByHeader: false` or a header diff --git a/docs/dev/PROGRAMISTA.md b/docs/dev/PROGRAMISTA.md index 41d1e7c..9a66eab 100644 --- a/docs/dev/PROGRAMISTA.md +++ b/docs/dev/PROGRAMISTA.md @@ -648,6 +648,7 @@ Do one item at a time, build, check. Order by importance: | 48 | **1.14.0 — image lightbox** — own image modal (`useState(index)` + `div role="dialog"`), `glightbox` / other lightbox library, thumbnails linking to the raw file in a new tab | `ipalKit({ lightbox: true })` + Postgres `migrate:create`; ``; `` around the thumbnail; delete the old dialog and `pnpm remove glightbox`; old label fields → Form messages → Image viewer | lightbox.md → "Replacing a hand-made modal" | | 49 | **1.14.0** — import map, Node, Next, audit, cookie list, admin languages | `pnpm payload generate:importmap` (`FaviconCheck`, `RowLabel`); Node 20.9+; `next@^16.4.3` + `sharp@^0.35.5` (Next ≤16.4.0 has two RCEs); `pnpm audit --prod` + `dompurify` / `undici` overrides on payload 3.90.x; hand-kept cookie list → `cookieScanner` (+ `crawl`, `IPAL_COOKIE_SCAN_URL` / `IPAL_COOKIE_SCAN_TOKEN`) + `migrate:create`; English-only admin → `i18n.supportedLanguages`; tests on validator strings → full sentences | CHANGELOG 1.14.0, cookie-scanner.md, i18n.md, AGENT.md §4 items 11–12 | | 50 | **1.14.1** — `X-Powered-By: Next.js, Payload` in responses, no CSP or a hand-written one | `withPayload(withSecurityConfig(nextConfig))`; `buildSecurityHeaders({ csp: { mode: 'report-only', reportUri: '/api/csp-report', …flags } })` + `buildAdminCspHeaders` on `/admin/:path*` + `export const POST = createCspReportRoute()`; after clean reports `mode: 'enforce'`; nonces (`createProxy({ csp })` + ``) only for dynamic sites | security.md, CHANGELOG 1.14.1 | +| 51 | **after 1.14.1** — a new admin stuck on `/admin/setup-totp?back=null` (the page keeps redirecting to itself), or an own `x-pathname` rule on `/admin` added as a workaround | `pnpm payload generate:importmap` (`TotpRedirectProvider`), commit `importMap.js`, redeploy; delete the workaround; own redirect rules → `twoFactor.provider` | security.md → "The redirect to the 2FA screens", CHANGELOG | 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`. diff --git a/docs/security.md b/docs/security.md index 75e9677..17f8d02 100644 --- a/docs/security.md +++ b/docs/security.md @@ -390,6 +390,37 @@ gets the injected plugin. The plugin sets `forceSetup: true` — every user MUST set up TOTP after logging in. There is no per-user "on/off" option. +### Import map (required) + +The 2FA screens and the redirect to them are admin components. After adding `twoFactor`, and after every +ipal-kit upgrade, run: + +```bash +pnpm generate:importmap +``` + +`src/app/(payload)/admin/importMap.js` must list `@intecion/ipal-kit/admin#TotpRedirectProvider` and +`@clocklimited/payload-2fa/rsc#TOTPSetup` / `#TOTPVerify` / `#TOTPField`. Commit the file. + +### The redirect to the 2FA screens (`twoFactor.provider`) + +The package's own admin provider decides on the server where to send the user, from an `x-pathname` +request header. Nothing sets that header on `/admin` (the `createProxy` matcher skips `/admin`), so up to +1.14.1 a user without TOTP was sent to `/admin/setup-totp?back=null`, and the setup screen redirected +to itself forever. Since the version after 1.14.1, ipal-kit swaps in its own provider, +`TotpRedirectProvider`: it reads the path in the browser, never redirects away from the setup or verify +screen or from logout, and renders nothing while a redirect is pending, so the panel does not flash. +No project change is needed apart from `generate:importmap`. + +- `twoFactor.provider: '@/components/MyTotp#MyTotp'` (or a `{ path, clientProps, serverProps }` object): + your own component. It gets clientProps `forceSetup` and the package's serverProps `pluginOptions`. + The pure logic is exported: `totpRedirectTarget({ adminRoute, forceSetup, pathname, user })` returns + the URL to send the user to, or `null`. +- `twoFactor.provider: false`: keep the package's provider. Then a proxy must set `x-pathname` on every + `/admin` request, or the loop comes back. + +The provider only steers the UI. Data access is still checked by the package's access wrapper. + ### Turning it off (DISCOURAGED) ```ts @@ -401,10 +432,14 @@ twoFactor: false // ONLY when the project really cannot use 2FA (rare) ### How it works for the user 1. Logs in (email + password) -2. On first login: redirected to TOTP Setup (QR + secret) +2. On first login: redirected to TOTP Setup (`/admin/setup-totp?back=%2Fadmin`, QR + secret) 3. Scans the QR with an app (Google Authenticator, Authy, 1Password, Microsoft Authenticator) -4. Enters the code → 2FA is active -5. Next logins: email + password + TOTP code +4. Enters the code → 2FA is active, back to the page from `back` +5. Next logins: email + password + TOTP code (`/admin/verify-totp?back=…`) + +**Check:** log in as a new admin. The address must end at `/admin/setup-totp?back=%2Fadmin` and the page must +show the QR code. `back=null` or a page that keeps reloading means the import map is stale (run +`pnpm generate:importmap`) or `provider: false` without an `x-pathname` header on `/admin`. ### Resetting 2FA (admin) @@ -454,9 +489,11 @@ data access, not just the UI. - **Override:** `additional` (the same key overrides the plugin's header and the `csp` ones), `buildCsp({ extra, override, mode, strictDynamic })`, `buildAdminCsp({ extra, override })`, `createCspReportRoute({ onReport, maxBytes })`; - 2FA — `collectionSlug`, `allowCollectionMismatch`, your own TOTP options by wrapping `plugin`; + 2FA — `collectionSlug`, `allowCollectionMismatch`, your own TOTP options by wrapping `plugin`, + `provider` (your own redirect component, or `false` for the package's); access — `access.authAccess`, `access.firstUserAdmin`, `globalOverrides` ([access.md](./access.md)). -- **Extend:** `buildCsp` / `buildCspHeaders` / `buildReportingEndpoints` / `cspHeaderKey` / +- **Extend:** `totpRedirectTarget` / `totpAdminPath` (2FA redirect rules) for your own provider; + `buildCsp` / `buildCspHeaders` / `buildReportingEndpoints` / `cspHeaderKey` / `parseCspReports` / `createCspNonce` (`CSP_NONCE_HEADER`, `DEFAULT_CSP_REPORT_GROUP`) for your own proxy or collector; `buildUploadSecurityHeaders({ collections })` for your own upload collections. - **Check:** `curl -sI https://domain/pl | grep -iE "strict-transport|x-frame|referrer|permissions|cross-origin|content-security|x-powered-by"` diff --git a/src/exports/admin.ts b/src/exports/admin.ts index 55feabe..aafbf6f 100644 --- a/src/exports/admin.ts +++ b/src/exports/admin.ts @@ -14,6 +14,8 @@ export { CookieScanButton } from '../modules/consent/scanner/CookieScanButton.js export { CookieCrawlAlert } from '../modules/consent/scanner/crawl/CookieCrawlAlert.js' export { IntegrationAlerts } from '../modules/integrations/IntegrationAlerts.js' export { IntegrationStatusBanner } from '../modules/integrations/IntegrationStatusBanner.js' +export { TotpRedirectProvider } from '../modules/security/totp/TotpRedirectProvider.js' +export type { TotpRedirectProviderProps } from '../modules/security/totp/TotpRedirectProvider.js' export { FaviconCheck } from '../modules/seo/FaviconCheck.js' export type { FaviconCheckProps } from '../modules/seo/FaviconCheck.js' export { MetaDescriptionCheck } from '../modules/seo/MetaDescriptionCheck.js' diff --git a/src/index.ts b/src/index.ts index e3cfdc7..98d9807 100644 --- a/src/index.ts +++ b/src/index.ts @@ -268,6 +268,8 @@ export { cspHeaderKey, DEFAULT_CSP_REPORT_GROUP, parseCspReports, + totpAdminPath, + totpRedirectTarget, withSecurityConfig, } from './modules/security/index.js' export type { @@ -277,6 +279,8 @@ export type { CspDirective, CspSources, CspViolation, + TotpRedirectArgs, + TotpUser, WithSecurityConfigOptions, } from './modules/security/index.js' diff --git a/src/modules/security/index.ts b/src/modules/security/index.ts index 469cd1d..40ab622 100644 --- a/src/modules/security/index.ts +++ b/src/modules/security/index.ts @@ -13,5 +13,7 @@ export type { BuildSecurityHeadersArgs, SecurityHeader } from './buildSecurityHe export { createCspReportRoute, parseCspReports } from './createCspReportRoute.js' export type { CreateCspReportRouteArgs, CspViolation } from './createCspReportRoute.js' export { createCspNonce, CSP_NONCE_HEADER } from './cspNonce.js' +export { totpAdminPath, totpRedirectTarget } from './totp/totpRedirect.js' +export type { TotpRedirectArgs, TotpUser } from './totp/totpRedirect.js' export { withSecurityConfig } from './withSecurityConfig.js' export type { WithSecurityConfigOptions } from './withSecurityConfig.js' diff --git a/src/modules/security/totp/TotpRedirectProvider.tsx b/src/modules/security/totp/TotpRedirectProvider.tsx new file mode 100644 index 0000000..75afd42 --- /dev/null +++ b/src/modules/security/totp/TotpRedirectProvider.tsx @@ -0,0 +1,48 @@ +'use client' + +import type { ReactNode } from 'react' + +import { useAuth, useConfig } from '@payloadcms/ui' +import { usePathname, useRouter } from 'next/navigation.js' +import { useEffect } from 'react' + +import type { TotpUser } from './totpRedirect.js' + +import { totpRedirectTarget } from './totpRedirect.js' + +export type TotpRedirectProviderProps = { + children?: ReactNode + /** pluginOptions.forceSetup — set by the plugin (true: 2FA is enforced). */ + forceSetup?: boolean +} + +/** + * Admin provider that sends users to the 2FA setup / verify screens. Replaces + * @clocklimited/payload-2fa's TOTPProvider, which read the path from an + * `x-pathname` request header: on /admin no proxy sets it, so the path was + * null and the setup screen redirected to itself (`setup-totp?back=null`). + * 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) { + const { user } = useAuth() + const { config } = useConfig() + const pathname = usePathname() + const router = useRouter() + const routes = config.admin?.routes + const target = totpRedirectTarget({ + adminRoute: config.routes?.admin ?? '/admin', + excludePaths: [routes?.logout ?? '/logout', routes?.inactivity ?? '/logout-inactivity'], + forceSetup, + pathname, + user: user as null | TotpUser, + }) + + useEffect(() => { + if (target) {router.replace(target)} + }, [router, target]) + + return target ? null : children +} + +export default TotpRedirectProvider diff --git a/src/modules/security/totp/totpRedirect.ts b/src/modules/security/totp/totpRedirect.ts new file mode 100644 index 0000000..b5710c6 --- /dev/null +++ b/src/modules/security/totp/totpRedirect.ts @@ -0,0 +1,53 @@ +/** The admin user fields @clocklimited/payload-2fa adds (and Payload's `_strategy`). */ +export type TotpUser = { + _strategy?: null | string + forceTotp?: boolean | null + hasTotp?: boolean | null +} + +export type TotpRedirectArgs = { + /** config.routes.admin, e.g. '/admin' or '/'. */ + adminRoute: string + /** Admin paths the redirect leaves alone (logout must still work). Default: '/logout', '/logout-inactivity'. */ + excludePaths?: string[] + /** pluginOptions.forceSetup: every user without TOTP goes to the setup screen. */ + forceSetup?: boolean + /** The current path, without origin or query (usePathname()). */ + pathname: null | string | undefined + user: null | TotpUser | undefined +} + +/** '/admin' + '/setup-totp' → '/admin/setup-totp'; an origin or trailing slash is dropped. */ +export function totpAdminPath(adminRoute: string, path: string): string { + return normalize(`${adminRoute === '/' ? '' : adminRoute}${path}`) +} + +function normalize(pathname: string): string { + const path = pathname.replace(/^[a-z][a-z\d+.-]*:\/\/[^/]+/i, '').replace(/[?#].*$/, '') + return path.replace(/\/+$/, '') || '/' +} + +/** + * Where the admin should send this user for 2FA, or null to stay. Same rules as + * @clocklimited/payload-2fa's TOTPProvider — verify when TOTP is set up but this + * session has not passed it, setup when it is required but missing — with two + * fixes: the current path comes from the browser, never a request header the + * project may not set (its absence made the package's provider redirect to + * `setup-totp?back=null` forever), and the TOTP screens themselves (and logout) + * never redirect, whether the setup URL is relative or absolute (serverURL). + */ +export function totpRedirectTarget(args: TotpRedirectArgs): null | string { + const { adminRoute, excludePaths = ['/logout', '/logout-inactivity'], forceSetup, pathname, user } = args + if (!user || !pathname || user._strategy === 'api-key') {return null} + + const here = normalize(pathname) + const setupUrl = totpAdminPath(adminRoute, '/setup-totp') + const verifyUrl = totpAdminPath(adminRoute, '/verify-totp') + const stay = [setupUrl, verifyUrl, ...excludePaths.map((p) => totpAdminPath(adminRoute, p))] + if (stay.includes(here)) {return null} + + const back = `?back=${encodeURIComponent(here)}` + if (user.hasTotp) {return user._strategy && user._strategy !== 'totp' ? verifyUrl + back : null} + if (user.forceTotp || forceSetup) {return setupUrl + back} + return null +} diff --git a/src/plugin.ts b/src/plugin.ts index 598c92d..03b1e9b 100644 --- a/src/plugin.ts +++ b/src/plugin.ts @@ -30,6 +30,9 @@ import { searchSettingsFields } from './modules/seo/searchSettings.js' import { applyCollectionOverride } from './modules/shared/collectionOverride.js' import { buildStatsCollection, buildStatsEndpoint } from './modules/stats/index.js' +/** The admin provider @clocklimited/payload-2fa registers; ipal-kit swaps it (twoFactor.provider). */ +const TOTP_PACKAGE_PROVIDER = '@clocklimited/payload-2fa/rsc#TOTPProvider' + /** * IPAL (Intecion Payload Advanced Library) plugin for Payload CMS 3. * @@ -181,6 +184,32 @@ export const ipalKit = (options: IpalOptions): Plugin => { forceSetup: true, // ENFORCED — every user must set up TOTP; no opt-out totp: { issuer: tf.issuer }, })(config) + + // The package's TOTPProvider reads the path from an `x-pathname` header + // no proxy sets on /admin, so it redirected the setup screen to itself + // (`setup-totp?back=null`). Swap in ipal-kit's client-side provider, or + // the project's (`provider`); `provider: false` keeps the package's. + if (tf.provider !== false) { + const custom = tf.provider + const ours = + typeof custom === 'object' ? custom : { path: custom ?? '@intecion/ipal-kit/admin#TotpRedirectProvider' } + const providers = config.admin?.components?.providers ?? [] + config.admin = { + ...config.admin, + components: { + ...config.admin?.components, + providers: providers.map((p) => + p && (typeof p === 'string' ? p : p.path) === TOTP_PACKAGE_PROVIDER + ? { + ...ours, + clientProps: { forceSetup: true, ...ours.clientProps }, + serverProps: { ...(typeof p === 'object' ? p.serverProps : {}), ...ours.serverProps }, + } + : p, + ), + }, + } + } } // --- white-label admin branding --- diff --git a/src/types.ts b/src/types.ts index f3b721a..73346ca 100644 --- a/src/types.ts +++ b/src/types.ts @@ -1,4 +1,4 @@ -import type { CollectionSlug, Field, Plugin } from 'payload' +import type { CollectionSlug, Field, PayloadComponent, Plugin } from 'payload' /** * Factory shape of @clocklimited/payload-2fa's `payloadTotp` export — injected @@ -200,6 +200,17 @@ export type IpalOptions = { * injected factory too. See docs/security.md. */ plugin: TotpPluginFactory + /** + * Admin provider that sends users to the TOTP setup / verify screens. + * Default: ipal-kit's `@intecion/ipal-kit/admin#TotpRedirectProvider` + * (reads the path in the browser). The package's own provider needs an + * `x-pathname` request header on every /admin request; without it the + * setup screen redirects to itself (`setup-totp?back=null`). Pass your + * own component path (it gets clientProps `forceSetup` and the package's + * serverProps `pluginOptions`), or `false` to keep the package's provider + * (then set `x-pathname` on /admin yourself). Run generate:importmap. + */ + provider?: false | PayloadComponent } | false diff --git a/test/totpRedirect.test.ts b/test/totpRedirect.test.ts new file mode 100644 index 0000000..1ae0dbd --- /dev/null +++ b/test/totpRedirect.test.ts @@ -0,0 +1,85 @@ +import type { Config } from 'payload' + +import { payloadTotp } from '@clocklimited/payload-2fa' +import { describe, expect, it } from 'vitest' + +import { ipalKit } from '../src/index.js' +import { totpRedirectTarget } from '../src/modules/security/totp/totpRedirect.js' + +const i18n = { defaultLocale: 'pl', locales: [{ code: 'pl', label: 'Polski' }] } +const fresh = { _strategy: 'local-jwt', hasTotp: false } + +const base = (): Config => + ({ admin: { user: 'users' }, collections: [{ slug: 'users', auth: true, fields: [] }] }) as unknown as Config + +const providerPaths = (config: Config) => + (config.admin?.components?.providers ?? []).map((p) => (typeof p === 'object' && p ? p.path : p)) + +/** Follows the redirects the provider would make, the way a browser would. */ +function walk(start: string, user: typeof fresh, adminRoute = '/admin') { + const visited = [start] + let url = start + for (let i = 0; i < 5; i++) { + const next = totpRedirectTarget({ adminRoute, forceSetup: true, pathname: url.split('?')[0], user }) + if (!next) {return visited} + url = next + visited.push(url) + } + throw new Error(`redirect loop: ${visited.join(' → ')}`) +} + +describe('2FA setup redirect (fresh admin, forceSetup)', () => { + it('lands on the setup screen once, with the page to return to — no loop, no back=null', () => { + expect(walk('/admin', fresh)).toEqual(['/admin', '/admin/setup-totp?back=%2Fadmin']) + expect(walk('/admin/collections/pages', fresh).at(-1)).toBe('/admin/setup-totp?back=%2Fadmin%2Fcollections%2Fpages') + }) + + it('stays on the setup and verify screens, with or without a trailing slash', () => { + for (const pathname of ['/admin/setup-totp', '/admin/setup-totp/', '/admin/verify-totp']) { + expect(totpRedirectTarget({ adminRoute: '/admin', forceSetup: true, pathname, user: fresh })).toBeNull() + } + }) + + it('never redirects on an unknown path (the package read a missing header as null → back=null)', () => { + expect(totpRedirectTarget({ adminRoute: '/admin', forceSetup: true, pathname: null, user: fresh })).toBeNull() + }) + + it('works with a custom admin route and lets logout through', () => { + expect(walk('/its', fresh, '/its')).toEqual(['/its', '/its/setup-totp?back=%2Fits']) + expect(walk('/', fresh, '/')).toEqual(['/', '/setup-totp?back=%2F']) + expect(totpRedirectTarget({ adminRoute: '/admin', forceSetup: true, pathname: '/admin/logout', user: fresh })).toBeNull() + }) + + it('sends a user with TOTP to verify until this session passed it; api keys pass', () => { + const user = { _strategy: 'local-jwt', hasTotp: true } + expect(walk('/admin', user)).toEqual(['/admin', '/admin/verify-totp?back=%2Fadmin']) + expect(walk('/admin', { _strategy: 'totp', hasTotp: true })).toEqual(['/admin']) + expect(walk('/admin', { _strategy: 'api-key', hasTotp: false })).toEqual(['/admin']) + }) + + it('leaves users alone when setup is not forced', () => { + expect(totpRedirectTarget({ adminRoute: '/admin', pathname: '/admin', user: fresh })).toBeNull() + }) +}) + +describe('twoFactor.provider', () => { + const run = (provider?: unknown) => + ipalKit({ i18n, twoFactor: { issuer: 'Test', plugin: payloadTotp, ...(provider === undefined ? {} : { provider }) } } as never)(base()) + + it("replaces the package's header-based provider with ipal-kit's by default", async () => { + const config = await run() + expect(providerPaths(config)).toContain('@intecion/ipal-kit/admin#TotpRedirectProvider') + expect(providerPaths(config)).not.toContain('@clocklimited/payload-2fa/rsc#TOTPProvider') + const ours = config.admin?.components?.providers?.find( + (p) => typeof p === 'object' && p && p.path === '@intecion/ipal-kit/admin#TotpRedirectProvider', + ) + expect(ours).toMatchObject({ clientProps: { forceSetup: true } }) + }) + + it('takes a project component, or false to keep the package provider', async () => { + expect(providerPaths(await run('@/components/MyTotp#MyTotp'))).toContain('@/components/MyTotp#MyTotp') + const kept = await run(false) + expect(providerPaths(kept)).toContain('@clocklimited/payload-2fa/rsc#TOTPProvider') + expect(providerPaths(kept)).not.toContain('@intecion/ipal-kit/admin#TotpRedirectProvider') + }) +})