From 93e75426aba71ec973e3b523777984e39cb94ab1 Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?Rados=C5=82aw=20Smoli=C5=84ski?= Date: Tue, 24 Nov 2026 15:29:06 +0100 Subject: [PATCH 1/4] 2FA screens: the back link is checked on the server (twoFactor.safeBack) @clocklimited/payload-2fa sends the browser to the `back` query value after a valid code without checking it (GHSA-rffw-fq79-g3ch upstream, not fixed in the fork): a prepared link ran script in the panel or left the site. SafeTotpView now stands in front of the package's setup and verify views and passes on a checked value: a path on the site's origin inside the admin route, else the admin root. The package's views stay in the import map through admin.dependencies, so ipal-kit still never imports the package. twoFactor.safeBack: false turns it off, a function replaces the rule; safeAdminBack, wrapTotpViews and SafeTotpView are exported. Projects with 2FA must regenerate the admin import map. Co-Authored-By: Claude Fable 5.2 --- docs/CHANGELOG.md | 40 +++ docs/agent/AGENT.md | 3 +- docs/agent/reference-site/INDEX.md | 1 + docs/agent/skills/ipal-debug/SKILL.md | 2 + docs/agent/skills/ipal-reference/SKILL.md | 1 + .../skills/ipal-reference/resources/api.md | 5 +- docs/agent/skills/ipal-setup/SKILL.md | 6 +- docs/agent/skills/ipal-upgrade/SKILL.md | 9 + docs/dev/PROGRAMISTA.md | 1 + docs/security.md | 44 +++- reference/.agents/skills/ipal-debug/SKILL.md | 2 + .../.agents/skills/ipal-reference/SKILL.md | 1 + .../skills/ipal-reference/resources/api.md | 5 +- reference/.agents/skills/ipal-setup/SKILL.md | 6 +- .../.agents/skills/ipal-upgrade/SKILL.md | 9 + reference/e2e/two-factor-back.spec.ts | 92 +++++++ .../src/app/(payload)/admin/importMap.js | 10 +- scripts/reference-index.mjs | 1 + src/exports/admin.ts | 2 + src/index.ts | 2 + src/modules/doctor/rules/layout.ts | 4 + src/modules/security/totp/SafeTotpView.tsx | 54 ++++ src/modules/security/totp/safeBack.ts | 116 +++++++++ src/plugin.ts | 23 ++ src/types.ts | 12 + test/safeBack.test.ts | 238 ++++++++++++++++++ 26 files changed, 678 insertions(+), 11 deletions(-) create mode 100644 reference/e2e/two-factor-back.spec.ts create mode 100644 src/modules/security/totp/SafeTotpView.tsx create mode 100644 src/modules/security/totp/safeBack.ts create mode 100644 test/safeBack.test.ts diff --git a/docs/CHANGELOG.md b/docs/CHANGELOG.md index f361839..1ed2c70 100644 --- a/docs/CHANGELOG.md +++ b/docs/CHANGELOG.md @@ -8,6 +8,46 @@ 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 — the `back` link of the 2FA screens + +### Security +- **The 2FA setup and verify screens no longer follow an unchecked `back` link.** `@clocklimited/payload-2fa` + (beta.1 to beta.7) sends the browser to the `back` query value once the code is accepted, without checking it. + A panel user who had typed the password, opened a prepared link to `/admin/verify-totp` or `/admin/setup-totp` + and then entered the code could be sent to another site, or have script run in the panel under their freshly + verified session. The panel's CSP does not stop this. **Affects every site with 2FA on, in every earlier + version.** It needs the user to open such a link between the password and the code; a logged-out or a fully + logged-in user is not affected. The original package fixed it in `payload-totp` 3.0.5 (GHSA-rffw-fq79-g3ch); + the fork has not. + Now ipal-kit checks `back` on the server before the package's screen gets it: only a path on the site's own + origin, inside the admin route, is kept; anything else leads to the admin root + ([security.md](./security.md) "The `back` link of the 2FA screens"). The 2FA package itself is unchanged. + +### Added +- **`twoFactor.safeBack`** — on by default; `false` turns the check off, a function + `(back, { adminRoute, origin }) => string` replaces the rule. +- **`safeAdminBack`**, **`wrapTotpViews`** (`@intecion/ipal-kit`) and **`SafeTotpView`** + (`@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`. + +### 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. +- **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. + +### Known limitations +- After the code, the screen always goes somewhere inside the panel. A `back` that pointed at a page of the + public site (not used by the plugin or the package) now leads to the admin root; pass your own rule if a + project relied on that. +- An absolute `back` on the site's own origin is kept only when the Payload config has `serverURL`; without it + only relative values are (the plugin and the package only ever produce relative ones). +- A missing `back` used to mean "go back in browser history"; it now means the admin root. + ## 1.16.4 ### Security diff --git a/docs/agent/AGENT.md b/docs/agent/AGENT.md index 8fbe7ea..fe159ad 100644 --- a/docs/agent/AGENT.md +++ b/docs/agent/AGENT.md @@ -203,7 +203,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** → *Approve cookies* → **Approve and add**; or cookie-scan → import) — feeds `` on the policy page **and** the lists in the `detailed` window; Cookies → 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 }` + `generate:importmap` (`TotpRedirectProvider`; check: a new admin lands on `/admin/setup-totp?back=%2Fadmin` with the QR, no reloading; a login with the password only gets `403` from `/api/globals/site-integrations` and `/api/form-submissions` — security.md "What the second factor covers"); own endpoints: `secondFactorPassed(req)` / `userMeetsRole(req, role)`; **set 2FA up right after creating an account** — until then its password alone opens everything its role allows; `ipal-doctor --url` must report 0 accounts without 2FA; `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`, `SafeTotpView`; check: a new admin lands on `/admin/setup-totp?back=%2Fadmin` with the QR, no reloading; a login with the password only gets `403` from `/api/globals/site-integrations` and `/api/form-submissions` — security.md "What the second factor covers"); own endpoints: `secondFactorPassed(req)` / `userMeetsRole(req, role)`; **set 2FA up right after creating an account** — until then its password alone opens everything its role allows; `ipal-doctor --url` must report 0 accounts without 2FA; `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 | @@ -1167,6 +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 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`) | diff --git a/docs/agent/reference-site/INDEX.md b/docs/agent/reference-site/INDEX.md index d9312b4..9fb495e 100644 --- a/docs/agent/reference-site/INDEX.md +++ b/docs/agent/reference-site/INDEX.md @@ -1161,6 +1161,7 @@ Rules: AGENT.md §8a. | `e2e/smoke.spec.ts` | the smoke tests every release must pass: pages, showcase, forms (also a file sent by e-mail), sitemap, SEO/GEO, headers, consent, 2FA | | `e2e/smtp-sink.ts` | a local mail sink for the smoke tests: reads what the site really sent (recipients, attachments) | | `e2e/totp.ts` | RFC 6238 code generator for the 2FA sign-in in the smoke test (below) | +| `e2e/two-factor-back.spec.ts` | browser test of the 2FA screens' `back` link (twoFactor.safeBack): a prepared link — script or another host — ends on the admin root, an ordinary one is followed | ### `e2e/create-test-admin.ts` diff --git a/docs/agent/skills/ipal-debug/SKILL.md b/docs/agent/skills/ipal-debug/SKILL.md index ca2adad..224d438 100644 --- a/docs/agent/skills/ipal-debug/SKILL.md +++ b/docs/agent/skills/ipal-debug/SKILL.md @@ -58,6 +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 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 | | empty SEO tab, no Forms | mismatched `@payloadcms/*` versions | all `@payloadcms/*` = the `payload` version | diff --git a/docs/agent/skills/ipal-reference/SKILL.md b/docs/agent/skills/ipal-reference/SKILL.md index f29bf72..7a9bb31 100644 --- a/docs/agent/skills/ipal-reference/SKILL.md +++ b/docs/agent/skills/ipal-reference/SKILL.md @@ -37,6 +37,7 @@ description: Complete map of everything @intecion/ipal-kit provides — every ip | `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.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.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..totpPlugin.` (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.`; `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 | diff --git a/docs/agent/skills/ipal-reference/resources/api.md b/docs/agent/skills/ipal-reference/resources/api.md index 2054e71..abf1e2c 100644 --- a/docs/agent/skills/ipal-reference/resources/api.md +++ b/docs/agent/skills/ipal-reference/resources/api.md @@ -31,6 +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: '' } }` + 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 }` | @@ -68,7 +69,7 @@ Admin panel components from `@intecion/ipal-kit/admin` — the project does NOT | `buildRolesField(defaultRole?, { firstUserAdmin? })` | `@intecion/ipal-kit` | The `roles` select field the plugin injects (only admins set roles; `firstUserAdmin` default `true` = the account made on "Create first user" gets `admin`). The plugin wires it itself — use it only for an auth collection the plugin does not manage. | | `injectRoles(config, accessOption)` | `@intecion/ipal-kit` | Adds `roles` to `accessOption.authCollection` in a config. The plugin calls it itself with `access` — do not call. | -**Types:** `VerifyLimitOptions` (`twoFactor.verifyLimit`: `{ max?, windowMinutes? }`), `Role` (`'user' \| 'editor' \| 'admin'`), `AccessOption` (the plugin's `access` option: `authCollection`, `defaultRole`, `authAccess`, `firstUserAdmin`, `staffCollections`). +**Types:** `VerifyLimitOptions` (`twoFactor.verifyLimit`: `{ max?, windowMinutes? }`), `SafeBackRule` / `SafeBackContext` (`twoFactor.safeBack` as a function: `(back, { adminRoute, origin? }) => string`), `SafeTotpViewProps` (`@intecion/ipal-kit/admin`), `Role` (`'user' \| 'editor' \| 'admin'`), `AccessOption` (the plugin's `access` option: `authCollection`, `defaultRole`, `authAccess`, `firstUserAdmin`, `staffCollections`). ## Accessibility — widget (`accessibility`) — details: `node_modules/@intecion/ipal-kit/docs/accessibility.md` @@ -586,6 +587,8 @@ 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. | | `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. | | `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'`. | diff --git a/docs/agent/skills/ipal-setup/SKILL.md b/docs/agent/skills/ipal-setup/SKILL.md index 87f60cb..d1e4b7e 100644 --- a/docs/agent/skills/ipal-setup/SKILL.md +++ b/docs/agent/skills/ipal-setup/SKILL.md @@ -203,7 +203,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 (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); +errors (the import map lists `@intecion/ipal-kit/admin#TotpRedirectProvider` and `#SafeTotpView`); `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, Cookies, Form messages, 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`. @@ -225,6 +225,10 @@ the panel shows Site settings, Site integrations, Cookies, Form messages, the Fo (the plugin's own, and those of plugins listed after `ipalKit`) and the plugin's endpoints; guard your own endpoints with `secondFactorPassed(req)` or `userMeetsRole(req, role)` (security.md "What the second factor covers"). 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. + 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`. - A second auth collection (`customers`, a client zone): set `admin: { user: 'users' }` in `buildConfig`; its diff --git a/docs/agent/skills/ipal-upgrade/SKILL.md b/docs/agent/skills/ipal-upgrade/SKILL.md index a098ff7..e9f6d8b 100644 --- a/docs/agent/skills/ipal-upgrade/SKILL.md +++ b/docs/agent/skills/ipal-upgrade/SKILL.md @@ -138,6 +138,15 @@ panel opens and a document saves. 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. +**→ 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. + **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 + strips `back`, can keep them (`twoFactor.safeBack: false` turns the plugin's check off). + **→ 1.14.2 (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. diff --git a/docs/dev/PROGRAMISTA.md b/docs/dev/PROGRAMISTA.md index 2577e91..3e46567 100644 --- a/docs/dev/PROGRAMISTA.md +++ b/docs/dev/PROGRAMISTA.md @@ -674,6 +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('')`, `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" | 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 0c756b8..0ef3edd 100644 --- a/docs/security.md +++ b/docs/security.md @@ -526,8 +526,9 @@ ipal-kit upgrade, run: 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. +`src/app/(payload)/admin/importMap.js` must list `@intecion/ipal-kit/admin#TotpRedirectProvider`, +`@intecion/ipal-kit/admin#SafeTotpView` and `@clocklimited/payload-2fa/rsc#TOTPSetup` / `#TOTPVerify` / +`#TOTPField`. Commit the file. ### Texts of the 2FA screens (`twoFactor.texts`) @@ -564,6 +565,43 @@ No project change is needed apart from `generate:importmap`. The provider only steers the UI. Data access is still checked by the package's access wrapper. +### The `back` link of the 2FA screens (`twoFactor.safeBack`) + +The setup and verify screens take a `back` query value (`/admin/verify-totp?back=%2Fadmin%2Fcollections%2Fpages`) +and the 2FA package sends the browser there once the code is accepted, without looking at it. A link with +`back=javascript:…` therefore ran script in the panel, as the user who had just passed the second factor, and a +link with an outside address sent the user off the site straight after a real login step. The original package +fixed this in `payload-totp` 3.0.5 (GHSA-rffw-fq79-g3ch); `@clocklimited/payload-2fa` (beta.1 to beta.7) has not. +The panel's CSP does not stop it: the admin needs inline script. + +ipal-kit closes it without changing the package. `SafeTotpView` (`@intecion/ipal-kit/admin`) is registered in +place of the package's four views (`setup-totp`, `verify-totp`, each with and without a leading slash). It checks +`back` on the server and renders the package's view with the checked value. The package's views stay in the +import map through `admin.dependencies`, so ipal-kit still never imports the package. + +The rule (`safeAdminBack`, the same as upstream's): `back` is resolved the way a browser resolves it and kept +only when it stays on the site's origin, over HTTP(S), without credentials, inside the admin route +(`routes.admin`, also a custom one). Everything else gives the admin root: `javascript:` in any case or with +leading spaces, `data:`, `https://other.example`, `//other.example`, `/\other.example`, `\\other.example`, +`https:other.example`, a path outside the panel, a repeated `back`, no `back` at all. The value passed on is +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 "…"`. +- **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 + later version of the 2FA package checks `back` itself, or something in front of the site does. +- **Building blocks:** `safeAdminBack(back, { adminRoute, origin })` and `wrapTotpViews(views, added, rule)` from + `@intecion/ipal-kit`; `SafeTotpView` from `@intecion/ipal-kit/admin` for your own 2FA view registration (give it + the serverProp `ipalTotpView: ''` and list that path in + `admin.dependencies`). + +**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. + ### Turning it off (DISCOURAGED) ```ts @@ -661,6 +699,8 @@ size while reading, content signature, container and macro checks, an optional ` ## Turn off, override, extend - **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. - **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. diff --git a/reference/.agents/skills/ipal-debug/SKILL.md b/reference/.agents/skills/ipal-debug/SKILL.md index ca2adad..224d438 100644 --- a/reference/.agents/skills/ipal-debug/SKILL.md +++ b/reference/.agents/skills/ipal-debug/SKILL.md @@ -58,6 +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 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 | | empty SEO tab, no Forms | mismatched `@payloadcms/*` versions | all `@payloadcms/*` = the `payload` version | diff --git a/reference/.agents/skills/ipal-reference/SKILL.md b/reference/.agents/skills/ipal-reference/SKILL.md index f29bf72..7a9bb31 100644 --- a/reference/.agents/skills/ipal-reference/SKILL.md +++ b/reference/.agents/skills/ipal-reference/SKILL.md @@ -37,6 +37,7 @@ description: Complete map of everything @intecion/ipal-kit provides — every ip | `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.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.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..totpPlugin.` (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.`; `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 | diff --git a/reference/.agents/skills/ipal-reference/resources/api.md b/reference/.agents/skills/ipal-reference/resources/api.md index 2054e71..abf1e2c 100644 --- a/reference/.agents/skills/ipal-reference/resources/api.md +++ b/reference/.agents/skills/ipal-reference/resources/api.md @@ -31,6 +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: '' } }` + 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 }` | @@ -68,7 +69,7 @@ Admin panel components from `@intecion/ipal-kit/admin` — the project does NOT | `buildRolesField(defaultRole?, { firstUserAdmin? })` | `@intecion/ipal-kit` | The `roles` select field the plugin injects (only admins set roles; `firstUserAdmin` default `true` = the account made on "Create first user" gets `admin`). The plugin wires it itself — use it only for an auth collection the plugin does not manage. | | `injectRoles(config, accessOption)` | `@intecion/ipal-kit` | Adds `roles` to `accessOption.authCollection` in a config. The plugin calls it itself with `access` — do not call. | -**Types:** `VerifyLimitOptions` (`twoFactor.verifyLimit`: `{ max?, windowMinutes? }`), `Role` (`'user' \| 'editor' \| 'admin'`), `AccessOption` (the plugin's `access` option: `authCollection`, `defaultRole`, `authAccess`, `firstUserAdmin`, `staffCollections`). +**Types:** `VerifyLimitOptions` (`twoFactor.verifyLimit`: `{ max?, windowMinutes? }`), `SafeBackRule` / `SafeBackContext` (`twoFactor.safeBack` as a function: `(back, { adminRoute, origin? }) => string`), `SafeTotpViewProps` (`@intecion/ipal-kit/admin`), `Role` (`'user' \| 'editor' \| 'admin'`), `AccessOption` (the plugin's `access` option: `authCollection`, `defaultRole`, `authAccess`, `firstUserAdmin`, `staffCollections`). ## Accessibility — widget (`accessibility`) — details: `node_modules/@intecion/ipal-kit/docs/accessibility.md` @@ -586,6 +587,8 @@ 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. | | `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. | | `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'`. | diff --git a/reference/.agents/skills/ipal-setup/SKILL.md b/reference/.agents/skills/ipal-setup/SKILL.md index 87f60cb..d1e4b7e 100644 --- a/reference/.agents/skills/ipal-setup/SKILL.md +++ b/reference/.agents/skills/ipal-setup/SKILL.md @@ -203,7 +203,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 (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); +errors (the import map lists `@intecion/ipal-kit/admin#TotpRedirectProvider` and `#SafeTotpView`); `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, Cookies, Form messages, 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`. @@ -225,6 +225,10 @@ the panel shows Site settings, Site integrations, Cookies, Form messages, the Fo (the plugin's own, and those of plugins listed after `ipalKit`) and the plugin's endpoints; guard your own endpoints with `secondFactorPassed(req)` or `userMeetsRole(req, role)` (security.md "What the second factor covers"). 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. + 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`. - A second auth collection (`customers`, a client zone): set `admin: { user: 'users' }` in `buildConfig`; its diff --git a/reference/.agents/skills/ipal-upgrade/SKILL.md b/reference/.agents/skills/ipal-upgrade/SKILL.md index a098ff7..e9f6d8b 100644 --- a/reference/.agents/skills/ipal-upgrade/SKILL.md +++ b/reference/.agents/skills/ipal-upgrade/SKILL.md @@ -138,6 +138,15 @@ panel opens and a document saves. 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. +**→ 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. + **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 + strips `back`, can keep them (`twoFactor.safeBack: false` turns the plugin's check off). + **→ 1.14.2 (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. diff --git a/reference/e2e/two-factor-back.spec.ts b/reference/e2e/two-factor-back.spec.ts new file mode 100644 index 0000000..182e58c --- /dev/null +++ b/reference/e2e/two-factor-back.spec.ts @@ -0,0 +1,92 @@ +import { type Browser, expect, type Page, test } from '@playwright/test' +import { randomUUID } from 'node:crypto' + +import { totp } from './totp' + +/** + * The `back` link of the 2FA screens (twoFactor.safeBack, security.md). The 2FA package sends the browser to + * `back` after a valid code; ipal-kit checks the value first. A prepared link must end on the admin root: + * no script in the panel, no other site. Run against a built site with the test admin (create-test-admin.ts). + * + * Two verify attempts for the test admin here; the smoke spec makes two more (the limit is 5 in 10 minutes). + */ +const { E2E_ADMIN_EMAIL: email, E2E_ADMIN_PASSWORD: password, E2E_TOTP_SECRET: secret } = process.env + +/** Script that would mark the page: runs only if the browser follows `back` as given. */ +const SCRIPT = "javascript:void(document.title='XSS-'+document.domain)" + +async function passwordOnly(browser: Browser, baseURL: string, who: { email: string; password: string }): Promise { + const context = await browser.newContext({ baseURL }) + const page = await context.newPage() + await page.goto('/admin/login') + await page.fill('#field-email', who.email) + await page.fill('#field-password', who.password) + await page.click('.form-submit button') + await page.waitForURL(/(verify|setup)-totp/, { waitUntil: 'commit' }) + return page +} + +async function enterCode(page: Page, code: string) { + // six one-digit inputs: type the code into the first, focus moves on by itself + await page.getByRole('textbox').first().click() + await page.keyboard.type(code) +} + +/** The page ended on the admin root of this site, and the marker script did not run. */ +async function expectAdminRoot(page: Page, baseURL: string) { + await expect(page).toHaveURL(new RegExp(`^${baseURL.replace(/[.*+?^${}()|[\]\\]/g, '\\$&')}/admin/?$`), { timeout: 20_000 }) + await expect(page).toHaveTitle(/Dashboard|Pulpit/, { timeout: 20_000 }) + expect(await page.title()).not.toContain('XSS-') +} + +test('2FA screens: a prepared back link ends on the admin root', async ({ baseURL, browser }) => { + test.skip(!email || !password || !secret, 'E2E_* test admin not configured') + test.setTimeout(120_000) + const admin = { email: email!, password: password! } + const other = new URL(baseURL!) + other.hostname = other.hostname === 'localhost' ? '127.0.0.1' : 'localhost' // another origin, still this machine + + // verify screen, script in `back` + const first = await passwordOnly(browser, baseURL!, admin) + await first.goto(`/admin/verify-totp?back=${encodeURIComponent(SCRIPT)}`) + await enterCode(first, totp(secret!)) + await expectAdminRoot(first, baseURL!) + + // two accounts that have not set TOTP up yet, made by the admin who is now fully signed in + const fresh = [0, 1].map(() => ({ email: `e2e-back-${randomUUID()}@example.com`, password: `T-${randomUUID()}` })) + const ids: string[] = [] + for (const account of fresh) { + const created = await first.request.post('/api/users', { data: { ...account, roles: ['editor'] }, headers: { origin: baseURL! } }) + expect(created.status()).toBe(201) + ids.push((await created.json()).doc.id) + } + + try { + // verify screen, another host written with a backslash + const second = await passwordOnly(browser, baseURL!, admin) + await second.goto(`/admin/verify-totp?back=${encodeURIComponent(`/\\${other.host}/admin/login?landed=elsewhere`)}`) + await enterCode(second, totp(secret!)) + await expectAdminRoot(second, baseURL!) + await second.context().close() + + // setup screen, script in `back` + const third = await passwordOnly(browser, baseURL!, fresh[0]) + await third.goto(`/admin/setup-totp?back=${encodeURIComponent(SCRIPT)}`) + const newSecret = await third.locator('input[type="hidden"]').evaluateAll((inputs) => inputs.map((i) => (i as HTMLInputElement).value).find((v) => /^[A-Z2-7]{16,}$/.test(v))) + expect(newSecret).toBeTruthy() + await enterCode(third, totp(newSecret!)) + await expectAdminRoot(third, baseURL!) + await third.context().close() + + // setup screen, an ordinary link back into the panel is still followed + const fourth = await passwordOnly(browser, baseURL!, fresh[1]) + await fourth.goto(`/admin/setup-totp?back=${encodeURIComponent('/admin/collections/pages?limit=5')}`) + const fourthSecret = await fourth.locator('input[type="hidden"]').evaluateAll((inputs) => inputs.map((i) => (i as HTMLInputElement).value).find((v) => /^[A-Z2-7]{16,}$/.test(v))) + await enterCode(fourth, totp(fourthSecret!)) + await expect(fourth).toHaveURL(/\/admin\/collections\/pages\?limit=5$/, { timeout: 20_000 }) + await fourth.context().close() + } finally { + for (const id of ids) {await first.request.delete(`/api/users/${id}`, { headers: { origin: baseURL! } })} + await first.context().close() + } +}) diff --git a/reference/src/app/(payload)/admin/importMap.js b/reference/src/app/(payload)/admin/importMap.js index 0f1f73d..2564512 100644 --- a/reference/src/app/(payload)/admin/importMap.js +++ b/reference/src/app/(payload)/admin/importMap.js @@ -42,10 +42,11 @@ import { IntecionCredit as IntecionCredit_7568fe47d582ff15ce85d2e1873c2c23 } fro import { CookieCrawlAlert as CookieCrawlAlert_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 { SafeTotpView as SafeTotpView_7568fe47d582ff15ce85d2e1873c2c23 } from '@intecion/ipal-kit/admin' import { CookieApprovalView as CookieApprovalView_7568fe47d582ff15ce85d2e1873c2c23 } from '@intecion/ipal-kit/admin' import { CollectionCards as CollectionCards_f9c02e79a4aed9a3924487c0cd4cafb1 } from '@payloadcms/next/rsc' +import { TOTPSetup as TOTPSetup_3eb2cc20d1a2569c2ccbafcee15bd128 } from '@clocklimited/payload-2fa/rsc' +import { TOTPVerify as TOTPVerify_3eb2cc20d1a2569c2ccbafcee15bd128 } from '@clocklimited/payload-2fa/rsc' import { S3ClientUploadHandler as S3ClientUploadHandler_f97aa6c64367fa259c5bc0567239ef24 } from '@payloadcms/storage-s3/client' /** @type import('payload').ImportMap */ @@ -94,9 +95,10 @@ export const importMap = { "@intecion/ipal-kit/admin#CookieCrawlAlert": CookieCrawlAlert_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#SafeTotpView": SafeTotpView_7568fe47d582ff15ce85d2e1873c2c23, "@intecion/ipal-kit/admin#CookieApprovalView": CookieApprovalView_7568fe47d582ff15ce85d2e1873c2c23, "@payloadcms/next/rsc#CollectionCards": CollectionCards_f9c02e79a4aed9a3924487c0cd4cafb1, + "@clocklimited/payload-2fa/rsc#TOTPSetup": TOTPSetup_3eb2cc20d1a2569c2ccbafcee15bd128, + "@clocklimited/payload-2fa/rsc#TOTPVerify": TOTPVerify_3eb2cc20d1a2569c2ccbafcee15bd128, "@payloadcms/storage-s3/client#S3ClientUploadHandler": S3ClientUploadHandler_f97aa6c64367fa259c5bc0567239ef24 } diff --git a/scripts/reference-index.mjs b/scripts/reference-index.mjs index 6973a7b..b958bcb 100644 --- a/scripts/reference-index.mjs +++ b/scripts/reference-index.mjs @@ -62,6 +62,7 @@ export const DESCRIPTIONS = { 'e2e/create-test-admin.ts': 'a test admin with a known TOTP secret, and e-mail sending pointed at the tests\' mail sink (local / CI database only)', 'e2e/smoke.spec.ts': 'the smoke tests every release must pass: pages, showcase, forms (also a file sent by e-mail), sitemap, SEO/GEO, headers, consent, 2FA', 'e2e/smtp-sink.ts': 'a local mail sink for the smoke tests: reads what the site really sent (recipients, attachments)', + 'e2e/two-factor-back.spec.ts': 'browser test of the 2FA screens\' `back` link (twoFactor.safeBack): a prepared link — script or another host — ends on the admin root, an ordinary one is followed', 'e2e/totp.ts': 'RFC 6238 code generator for the 2FA sign-in in the smoke test', 'ipal-doctor.json': 'the production domain and launch state for ipal-doctor', 'next.config.ts': 'security headers, enforced CSP, admin CSP, upload headers, images, no X-Powered-By', diff --git a/src/exports/admin.ts b/src/exports/admin.ts index 7188dd8..8f2af17 100644 --- a/src/exports/admin.ts +++ b/src/exports/admin.ts @@ -18,6 +18,8 @@ export { CookieSiteCheckTab } from '../modules/consent/scanner/CookieSiteCheckTa export { CookieCrawlAlert } from '../modules/consent/scanner/crawl/CookieCrawlAlert.js' export { IntegrationAlerts } from '../modules/integrations/IntegrationAlerts.js' export { IntegrationStatusBanner } from '../modules/integrations/IntegrationStatusBanner.js' +export { SafeTotpView } from '../modules/security/totp/SafeTotpView.js' +export type { SafeTotpViewProps } from '../modules/security/totp/SafeTotpView.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' diff --git a/src/index.ts b/src/index.ts index 9134a4c..a45b238 100644 --- a/src/index.ts +++ b/src/index.ts @@ -327,6 +327,8 @@ export type { } from './modules/security/index.js' export type { BuildSecurityHeadersArgs, SecurityHeader } from './modules/security/index.js' +export { safeAdminBack, wrapTotpViews } from './modules/security/totp/safeBack.js' +export type { SafeBackContext, SafeBackRule } from './modules/security/totp/safeBack.js' export { requireSecondFactor, secondFactorPassed } from './modules/security/totp/secondFactor.js' export { TOTP_TEXTS, TOTP_VIEW_TITLE } from './modules/security/totp/totpTexts.js' export type { VerifyLimitOptions } from './modules/security/totp/verifyLimit.js' diff --git a/src/modules/doctor/rules/layout.ts b/src/modules/doctor/rules/layout.ts index a3c5e22..08412c8 100644 --- a/src/modules/doctor/rules/layout.ts +++ b/src/modules/doctor/rules/layout.ts @@ -198,6 +198,10 @@ export const layoutRules: DoctorRule[] = [ if (/payloadTotp/.test(cfg)) { need.push('@clocklimited/payload-2fa/rsc#TOTPSetup') if (!lt(v, '1.14.2')) {need.push('@intecion/ipal-kit/admin#TotpRedirectProvider')} + // the back-link check in front of the 2FA screens (twoFactor.safeBack) — when the installed plugin has it + if (/\bSafeTotpView\b/.test(ctx.read('node_modules/@intecion/ipal-kit/dist/exports/admin.js')) && !/safeBack\s*:\s*false/.test(cfg)) { + need.push('@intecion/ipal-kit/admin#SafeTotpView') + } } if (/buildR2Storage/.test(cfg)) {need.push('S3ClientUploadHandler')} if (/cookieScanner\s*:\s*(?!false)/.test(cfg) && !lt(v, '1.14.4')) {need.push('@intecion/ipal-kit/admin#CookieReviewTab')} diff --git a/src/modules/security/totp/SafeTotpView.tsx b/src/modules/security/totp/SafeTotpView.tsx new file mode 100644 index 0000000..473ca31 --- /dev/null +++ b/src/modules/security/totp/SafeTotpView.tsx @@ -0,0 +1,54 @@ +import type { AdminViewServerProps } from 'payload' + +import { getFromImportMap } from 'payload/shared' +import React from 'react' + +import { safeAdminBack, type SafeBackRule } 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 +} & AdminViewServerProps + +const originOf = (serverURL: unknown): string | undefined => { + if (typeof serverURL !== 'string' || !serverURL) {return undefined} + try { + return new URL(serverURL).origin + } catch { + return undefined + } +} + +/** + * 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. + * + * 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`. + */ +export function SafeTotpView(props: SafeTotpViewProps): React.ReactNode { + const { ipalSafeBack, ipalTotpView, ...rest } = props + const config = props.initPageResult?.req?.payload?.config ?? props.payload?.config + const raw = (props.searchParams as Record | undefined)?.back + const back = (ipalSafeBack ?? safeAdminBack)(typeof raw === 'string' ? raw : undefined, { + adminRoute: config?.routes?.admin ?? '/admin', + origin: originOf(config?.serverURL), + }) + + const View = getFromImportMap>>({ + importMap: props.importMap, + PayloadComponent: ipalTotpView, + schemaPath: '', + silent: true, + }) + if (!View) { + throw new Error( + `[ipal] The admin import map has no "${ipalTotpView}" (the 2FA screen ipal-kit puts its back-link check in front of). ` + + 'Run `pnpm payload generate:importmap` and commit the result.', + ) + } + return +} diff --git a/src/modules/security/totp/safeBack.ts b/src/modules/security/totp/safeBack.ts new file mode 100644 index 0000000..f158340 --- /dev/null +++ b/src/modules/security/totp/safeBack.ts @@ -0,0 +1,116 @@ +/** + * The `back` query parameter of the 2FA setup and verify screens. + * + * @clocklimited/payload-2fa passes it, unchecked, to `location.replace()` once the code is + * accepted. Anyone can put it in a link in front of a panel user: `javascript:…` then runs in + * the admin origin with the session that has just passed the second factor, and an absolute + * URL sends the user off-site straight after a genuine login step (GHSA-rffw-fq79-g3ch in the + * original `payload-totp`, fixed there in 3.0.5; the fork does not have the fix). + * + * ipal-kit therefore cleans the value on the server before the package's view sees it + * (SafeTotpView.tsx): `twoFactor.safeBack` — on by default, a function replaces the rule, + * `false` turns it off. + */ + +/** What a `back` rule is told about the panel. */ +export type SafeBackContext = { + /** `routes.admin` of the Payload config, e.g. `/admin`. */ + adminRoute: string + /** + * The site's own origin (from `serverURL`), when the config has one. An absolute `back` on + * this origin is accepted; without it only relative values are. + */ + origin?: string +} + +/** + * A `back` rule: gets the raw query value (undefined when absent or repeated) and returns the + * URL the screen goes to after a valid code. Return a path on the site's own origin. + */ +export type SafeBackRule = (back: string | undefined, context: SafeBackContext) => string + +/** Never a real site: a relative `back` is resolved against it, and anything that leaves it is refused. */ +const PLACEHOLDER_ORIGIN = 'http://ipal-safe-back.invalid' + +const trimSlashes = (path: string) => `/${path.replace(/^\/+|\/+$/g, '')}` + +/** + * The default rule, the same as upstream's: `back` is resolved the way a browser resolves it + * and kept only when it stays on the site's origin, over HTTP(S), without credentials, inside + * the admin route. Anything else — `javascript:`, `data:`, `//host`, `/\host`, `\\host`, + * `https:host`, a path outside the panel, no value at all — gives the admin root. + * + * Returns a path (`/admin/collections/pages?page=2`), never an absolute URL, so the browser + * goes to exactly what was checked and cannot be taken off the origin. + */ +export const safeAdminBack: SafeBackRule = (back, { adminRoute, origin }) => { + const adminPath = trimSlashes(adminRoute || '/') + if (typeof back !== 'string' || !back) {return adminPath} + + let base = PLACEHOLDER_ORIGIN + if (origin) { + try { + base = new URL(origin).origin + } catch { + /* not a URL: relative values only */ + } + } + + let url: URL + try { + url = new URL(back, base) + } catch { + return adminPath + } + // `blob:` URLs report the origin that made them, hence the protocol check. + if (url.origin !== base || !['http:', 'https:'].includes(url.protocol) || url.username || url.password) { + return adminPath + } + const inside = adminPath === '/' || url.pathname === adminPath || url.pathname.startsWith(`${adminPath}/`) + // The parser collapses `//`, but a path that still starts with two slashes would be read as a host. + if (!inside || url.pathname.startsWith('//')) {return adminPath} + return `${url.pathname}${url.search}${url.hash}` +} + +/** 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 } + +/** Key of the import-map entry that keeps the package's own view importable. */ +export const totpViewDependencyKey = (path: string) => `ipal-totp-view:${path}` + +/** + * 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. + */ +export function wrapTotpViews( + views: Record, + added: (key: string) => boolean, + rule: SafeBackRule | undefined, + wrapper = '@intecion/ipal-kit/admin#SafeTotpView', +): { dependencies: Record; views: Record } { + const dependencies: Record = {} + const out: Record = {} + for (const [key, view] of Object.entries(views)) { + const component = view?.Component as undefined | ViewComponent + 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) { + out[key] = view + continue + } + dependencies[totpViewDependencyKey(path)] = { type: 'component', path } + const own = typeof component === 'object' ? component : undefined + out[key] = { + ...view, + Component: { + ...(own?.clientProps ? { clientProps: own.clientProps } : {}), + path: wrapper, + serverProps: { ...own?.serverProps, ipalSafeBack: rule, ipalTotpView: path }, + }, + } + } + return { dependencies, views: out } +} diff --git a/src/plugin.ts b/src/plugin.ts index bf0db63..da74082 100644 --- a/src/plugin.ts +++ b/src/plugin.ts @@ -33,6 +33,7 @@ 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 { buildGuardStrategy, ensurePayloadGuarded, @@ -229,6 +230,7 @@ export const ipalKit = (options: IpalOptions): Plugin => { ) } const endpointsBefore = new Set(config.endpoints ?? []) + const viewsBefore = new Set(Object.keys(config.admin?.components?.views ?? {})) const entityEndpointsBefore = new Map>( [...(config.collections ?? []), ...(config.globals ?? [])].map((e) => [e.slug, new Set(Array.isArray(e.endpoints) ? e.endpoints : [])]), ) @@ -333,6 +335,27 @@ export const ipalKit = (options: IpalOptions): Plugin => { }, } } + + // The package's setup and verify screens send the browser to the `back` query + // value after a valid code, unchecked: a crafted link runs script in the panel + // or leaves the site (safeBack.ts). ipal-kit's view goes in front of them and + // hands the package's view a checked value. `safeBack: false` leaves them as + // the package registered them; a function replaces the rule. + if (tf.safeBack !== false) { + const wrapped = wrapTotpViews( + (config.admin?.components?.views ?? {}) as Record, + (key) => !viewsBefore.has(key), + typeof tf.safeBack === 'function' ? tf.safeBack : undefined, + ) + if (Object.keys(wrapped.dependencies).length) { + config.admin = { + ...config.admin, + components: { ...config.admin?.components, views: wrapped.views as never }, + // keeps the package's own views in the import map: the wrapper renders them from there + dependencies: { ...config.admin?.dependencies, ...wrapped.dependencies }, + } + } + } } const agency = options.agency === undefined ? DEFAULT_AGENCY : options.agency diff --git a/src/types.ts b/src/types.ts index ea0df2c..cf74d5f 100644 --- a/src/types.ts +++ b/src/types.ts @@ -23,6 +23,7 @@ import type { FormsOption } from './modules/forms/types.js' import type { RevalidatePathFn } from './modules/hooks/buildRevalidateHook.js' import type { I18nConfig } from './modules/i18n/types.js' import type { PagesOption } from './modules/pages/types.js' +import type { SafeBackRule } from './modules/security/totp/safeBack.js' import type { VerifyLimitOptions } from './modules/security/totp/verifyLimit.js' import type { SeoOption } from './modules/seo/types.js' import type { StatsOptions } from './modules/stats/collection.js' @@ -265,6 +266,17 @@ export type IpalOptions = { * (then set `x-pathname` on /admin yourself). Run generate:importmap. */ provider?: false | PayloadComponent + /** + * Check on the `back` query value of the 2FA setup and verify screens. The + * 2FA package sends the browser there after a valid code without looking at + * it, so a crafted link could run script in the panel (`javascript:`) or + * leave the site. On by default: ipal-kit's `SafeTotpView` goes in front of + * the package's views and passes on a value that stays on the site's origin, + * inside the admin route — anything else becomes the admin root + * (`safeAdminBack`). A function replaces the rule; `false` leaves the + * package's views as they are. Run generate:importmap. docs/security.md. + */ + safeBack?: false | SafeBackRule /** * Texts of the 2FA screens and user field. Default: ipal-kit's English and * Polish (`TOTP_TEXTS`), merged over the package's; your own diff --git a/test/safeBack.test.ts b/test/safeBack.test.ts new file mode 100644 index 0000000..6cf9022 --- /dev/null +++ b/test/safeBack.test.ts @@ -0,0 +1,238 @@ +import type { Config } from 'payload' + +import { payloadTotp } from '@clocklimited/payload-2fa' +import React from 'react' +import { renderToStaticMarkup } from 'react-dom/server' +import { describe, expect, test } from 'vitest' + +import type { I18nConfig } from '../src/modules/i18n/types.js' + +import { safeAdminBack, wrapTotpViews } from '../src/modules/security/totp/safeBack.js' +import { SafeTotpView } from '../src/modules/security/totp/SafeTotpView.js' +import { ipalKit } from '../src/plugin.js' + +const i18n: I18nConfig = { defaultLocale: 'en', locales: [{ code: 'en', label: 'English' }] } +const admin = { adminRoute: '/admin' } + +describe('safeAdminBack', () => { + test.each([ + ['/admin', '/admin'], + ['/admin/', '/admin/'], + ['/admin/collections/pages?page=2&limit=10#row', '/admin/collections/pages?page=2&limit=10#row'], + ['/admin/collections/pages/../media', '/admin/collections/media'], + ])('keeps a path inside the panel: %s', (back, expected) => { + expect(safeAdminBack(back, admin)).toBe(expected) + }) + + test.each([ + ['javascript:alert(document.domain)'], + ['JaVaScRiPt:alert(1)'], + [' javascript:alert(1)'], + ['\tjavascript:alert(1)'], + ['java\nscript:alert(1)'], + ['data:text/html,'], + ['vbscript:msgbox(1)'], + ['blob:http://ipal-safe-back.invalid/1'], + ['https://evil.example/admin'], + ['http://evil.example/admin'], + ['//evil.example/admin'], + ['/\\evil.example/admin'], + ['\\\\evil.example/admin'], + ['\\/evil.example/admin'], + ['https:evil.example/admin'], + ['https:/evil.example/admin'], + ['http://ipal-safe-back.invalid@evil.example/admin'], + ['http://user:pass@ipal-safe-back.invalid/admin'], + ['http://ipal-safe-back.invalid/admin'], // the placeholder is not the site: absolute values need `origin` + ['http://ipal-safe-back.invalid:8080/admin'], + ['/'], + ['/login'], + ['/administrator'], + ['/admin/../api/users'], + ['/admin/%2e%2e/api/users'], + ['/api/users'], + ['collections/pages'], // relative to nothing: resolves outside the panel + [''], + [undefined], + ])('falls back to the admin root: %s', (back) => { + expect(safeAdminBack(back, admin)).toBe('/admin') + }) + + test('never returns an absolute URL or a value a browser reads as another host', () => { + for (const back of ['//evil.example', '/\\evil.example', '/admin//evil.example', 'https://evil.example/admin', '/admin/x']) { + const out = safeAdminBack(back, admin) + expect(out.startsWith('/')).toBe(true) + expect(out.startsWith('//')).toBe(false) + expect(new URL(out, 'https://site.example').origin).toBe('https://site.example') + } + }) + + test('a custom admin route', () => { + const panel = { adminRoute: '/panel' } + expect(safeAdminBack('/panel/collections/pages', panel)).toBe('/panel/collections/pages') + expect(safeAdminBack('/admin/collections/pages', panel)).toBe('/panel') + expect(safeAdminBack('javascript:alert(1)', panel)).toBe('/panel') + expect(safeAdminBack('/panel-other', panel)).toBe('/panel') + expect(safeAdminBack(undefined, { adminRoute: '/cms/panel/' })).toBe('/cms/panel') + expect(safeAdminBack('/cms/panel/x', { adminRoute: '/cms/panel/' })).toBe('/cms/panel/x') + }) + + test('an admin route of "/" keeps any path on the site, still nothing off it', () => { + const root = { adminRoute: '/' } + expect(safeAdminBack('/collections/pages', root)).toBe('/collections/pages') + expect(safeAdminBack('//evil.example/x', root)).toBe('/') + expect(safeAdminBack('javascript:alert(1)', root)).toBe('/') + }) + + test('with the site origin, an absolute URL on that origin is kept — as a path', () => { + const site = { adminRoute: '/admin', origin: 'https://site.example' } + expect(safeAdminBack('https://site.example/admin/collections/pages?x=1', site)).toBe('/admin/collections/pages?x=1') + expect(safeAdminBack('http://site.example/admin', site)).toBe('/admin') // other scheme = other origin + expect(safeAdminBack('https://site.example:8443/admin', site)).toBe('/admin') + expect(safeAdminBack('https://site.example.evil.example/admin', site)).toBe('/admin') + expect(safeAdminBack('https://site.example@evil.example/admin/x', site)).toBe('/admin') + expect(safeAdminBack('/admin/x', site)).toBe('/admin/x') + expect(safeAdminBack('/admin/x', { adminRoute: '/admin', origin: 'not a url' })).toBe('/admin/x') + }) +}) + +describe('wrapTotpViews', () => { + const views = { + Other: { Component: 'my#View', path: '/reports' }, + SetupTOTP: { Component: { path: 'pkg/rsc#TOTPSetup', serverProps: { pluginOptions: { a: 1 } } }, exact: true, path: 'setup-totp' }, + VerifyTOTPBackslash: { Component: 'pkg/rsc#TOTPVerify', path: '/verify-totp' }, + } + + test('wraps the views the package added, keeps their props, lists the originals as dependencies', () => { + const rule = () => '/x' + const out = wrapTotpViews(views, () => true, rule) + expect(out.views.Other).toBe(views.Other) + expect(out.views.SetupTOTP).toEqual({ + Component: { path: '@intecion/ipal-kit/admin#SafeTotpView', serverProps: { ipalSafeBack: rule, ipalTotpView: 'pkg/rsc#TOTPSetup', pluginOptions: { a: 1 } } }, + exact: true, + path: 'setup-totp', + }) + expect((out.views.VerifyTOTPBackslash.Component as unknown as { serverProps: { ipalTotpView: string } }).serverProps.ipalTotpView).toBe('pkg/rsc#TOTPVerify') + expect(out.dependencies).toEqual({ + 'ipal-totp-view:pkg/rsc#TOTPSetup': { type: 'component', path: 'pkg/rsc#TOTPSetup' }, + 'ipal-totp-view:pkg/rsc#TOTPVerify': { type: 'component', path: 'pkg/rsc#TOTPVerify' }, + }) + }) + + 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) + const twice = wrapTotpViews(once.views, () => true, undefined) + expect(twice.views).toEqual(once.views) + expect(twice.dependencies).toEqual({}) + }) +}) + +describe('ipalKit with the real 2FA package', () => { + const build = (twoFactor: false | Record, extra: Partial = {}) => + ipalKit({ + access: { authCollection: 'users' }, + i18n, + twoFactor: twoFactor === false ? false : ({ issuer: 'Example', plugin: payloadTotp, ...twoFactor } as never), + })({ collections: [], secret: 'x', ...extra } as unknown as Config) + + const component = (config: Config, key: string) => + (config.admin?.components?.views as Record } }> | undefined)?.[key]?.Component + + test('by default all four 2FA views go through SafeTotpView and the package views stay in the import map', async () => { + const config = await build({}) + for (const key of ['SetupTOTP', 'SetupTOTPBackslash', 'VerifyTOTP', 'VerifyTOTPBackslash']) { + const c = component(config, key) + expect([key, c?.path]).toEqual([key, '@intecion/ipal-kit/admin#SafeTotpView']) + expect(c?.serverProps?.ipalTotpView).toBe(`@clocklimited/payload-2fa/rsc#TOTP${key.startsWith('Setup') ? 'Setup' : 'Verify'}`) + expect(c?.serverProps?.pluginOptions).toBeDefined() // the package's own props are kept + expect(c?.serverProps?.ipalSafeBack).toBeUndefined() + } + expect(config.admin?.dependencies).toEqual({ + 'ipal-totp-view:@clocklimited/payload-2fa/rsc#TOTPSetup': { type: 'component', path: '@clocklimited/payload-2fa/rsc#TOTPSetup' }, + 'ipal-totp-view:@clocklimited/payload-2fa/rsc#TOTPVerify': { type: 'component', path: '@clocklimited/payload-2fa/rsc#TOTPVerify' }, + }) + // the tab title ipal-kit gives the screens is still there + expect((config.admin?.components?.views as Record).VerifyTOTP.meta?.title).toBeTruthy() + }) + + test('safeBack: false leaves the package views as registered', async () => { + const config = await build({ safeBack: false }) + expect(component(config, 'VerifyTOTP')?.path).toBe('@clocklimited/payload-2fa/rsc#TOTPVerify') + expect(component(config, 'SetupTOTP')?.path).toBe('@clocklimited/payload-2fa/rsc#TOTPSetup') + expect(config.admin?.dependencies).toBeUndefined() + }) + + test('a function replaces the rule', async () => { + const rule = () => '/admin/account' + const config = await build({ safeBack: rule }) + expect(component(config, 'VerifyTOTP')?.serverProps?.ipalSafeBack).toBe(rule) + }) + + test('still on with twoFactor.guard: false', async () => { + const config = await build({ guard: false }) + expect(component(config, 'VerifyTOTP')?.path).toBe('@intecion/ipal-kit/admin#SafeTotpView') + }) + + test("the project's own dependencies and views are kept", async () => { + const config = await build({}, { admin: { components: { views: { Mine: { Component: 'mine#View', path: '/verify-totp-help' } } }, dependencies: { mine: { type: 'component', path: 'mine#Thing' } } } } as never) + expect((config.admin?.components?.views as Record).Mine.Component).toBe('mine#View') + expect(config.admin?.dependencies?.mine).toEqual({ type: 'component', path: 'mine#Thing' }) + }) + + test('without 2FA nothing is registered', async () => { + const config = await build(false) + expect(JSON.stringify(config.admin ?? {})).not.toContain('SafeTotpView') + expect(JSON.stringify(config.admin ?? {})).not.toContain('ipal-totp-view') + }) +}) + +describe('SafeTotpView', () => { + const PackageView = (props: { pluginOptions?: { issuer?: string }; searchParams?: Record }) => + React.createElement('p', { 'data-back': String(props.searchParams?.back), 'data-issuer': props.pluginOptions?.issuer, 'data-other': String(props.searchParams?.other) }) + const render = (searchParams: Record, more: Record = {}, config: Record = { routes: { admin: '/admin' }, serverURL: '' }) => + renderToStaticMarkup( + React.createElement(SafeTotpView as never, { + importMap: { 'pkg/rsc#TOTPVerify': PackageView }, + initPageResult: { req: { payload: { config } } }, + ipalTotpView: 'pkg/rsc#TOTPVerify', + pluginOptions: { issuer: 'Example' }, + searchParams, + ...more, + }), + ) + + test.each([ + ['javascript:void(document.title=1)', '/admin'], + ['http://127.0.0.1:3218/admin/login?landed=absolute', '/admin'], + ['/\\127.0.0.1:3218/admin/login', '/admin'], + ['//127.0.0.1:3218/admin', '/admin'], + ['/admin/collections/pages?page=2', '/admin/collections/pages?page=2'], + ])('the package view receives a checked back: %s', (back, expected) => { + const html = render({ back, other: 'kept' }) + expect(html).toContain(`data-back="${expected.replace(/&/g, '&')}"`) + expect(html).toContain('data-issuer="Example"') // the package's serverProps reach its view + expect(html).toContain('data-other="kept"') + }) + + test('no back, or a repeated one, gives the admin root (the package would otherwise go back in history)', () => { + expect(render({})).toContain('data-back="/admin"') + expect(render({ back: ['/admin/a', 'javascript:alert(1)'] })).toContain('data-back="/admin"') + }) + + test('a custom admin route and serverURL', () => { + const config = { routes: { admin: '/panel' }, serverURL: 'https://site.example' } + expect(render({ back: '/admin/x' }, {}, config)).toContain('data-back="/panel"') + expect(render({ back: 'https://site.example/panel/x' }, {}, config)).toContain('data-back="/panel/x"') + expect(render({ back: 'https://evil.example/panel/x' }, {}, config)).toContain('data-back="/panel"') + }) + + test("the project's rule is used instead", () => { + const html = render({ back: 'javascript:alert(1)' }, { ipalSafeBack: (back: string | undefined, ctx: { adminRoute: string }) => `${ctx.adminRoute}/account?was=${back ? 'set' : 'empty'}` }) + expect(html).toContain('data-back="/admin/account?was=set"') + }) + + test('a missing import-map entry says what to run', () => { + expect(() => render({}, { importMap: {} })).toThrow(/generate:importmap/) + }) +}) From ad51456eaab0b9c9a1a193c15ffa64236f69f4e8 Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?Rados=C5=82aw=20Smoli=C5=84ski?= Date: Tue, 24 Nov 2026 16:16:39 +0100 Subject: [PATCH 2/4] =?UTF-8?q?2FA=20back=20link:=20review=20fixes=20?= =?UTF-8?q?=E2=80=94=20views=20guarded=20by=20object,=20client=20views,=20?= =?UTF-8?q?a=20loud=20stale=20import=20map?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit 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 --- docs/CHANGELOG.md | 16 +- docs/agent/AGENT.md | 2 +- docs/agent/skills/ipal-debug/SKILL.md | 3 +- docs/agent/skills/ipal-reference/SKILL.md | 1 + .../skills/ipal-reference/resources/api.md | 4 +- docs/agent/skills/ipal-setup/SKILL.md | 4 +- docs/agent/skills/ipal-upgrade/SKILL.md | 10 +- docs/dev/PROGRAMISTA.md | 2 +- docs/security.md | 39 +++- reference/.agents/skills/ipal-debug/SKILL.md | 3 +- .../.agents/skills/ipal-reference/SKILL.md | 1 + .../skills/ipal-reference/resources/api.md | 4 +- reference/.agents/skills/ipal-setup/SKILL.md | 4 +- .../.agents/skills/ipal-upgrade/SKILL.md | 10 +- src/modules/security/totp/SafeTotpView.tsx | 56 +++-- .../security/totp/TotpRedirectProvider.tsx | 33 ++- src/modules/security/totp/importMapCheck.ts | 49 +++++ src/modules/security/totp/safeBack.ts | 48 ++-- src/plugin.ts | 44 +++- src/types.ts | 9 + test/safeBack.test.ts | 205 +++++++++++++++++- 21 files changed, 477 insertions(+), 70 deletions(-) create mode 100644 src/modules/security/totp/importMapCheck.ts diff --git a/docs/CHANGELOG.md b/docs/CHANGELOG.md index 1ed2c70..dcd285b 100644 --- a/docs/CHANGELOG.md +++ b/docs/CHANGELOG.md @@ -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. diff --git a/docs/agent/AGENT.md b/docs/agent/AGENT.md index fe159ad..2ca5549 100644 --- a/docs/agent/AGENT.md +++ b/docs/agent/AGENT.md @@ -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`) | diff --git a/docs/agent/skills/ipal-debug/SKILL.md b/docs/agent/skills/ipal-debug/SKILL.md index 224d438..34b43b9 100644 --- a/docs/agent/skills/ipal-debug/SKILL.md +++ b/docs/agent/skills/ipal-debug/SKILL.md @@ -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 | diff --git a/docs/agent/skills/ipal-reference/SKILL.md b/docs/agent/skills/ipal-reference/SKILL.md index 7a9bb31..6f8ca3b 100644 --- a/docs/agent/skills/ipal-reference/SKILL.md +++ b/docs/agent/skills/ipal-reference/SKILL.md @@ -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..totpPlugin.` (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.`; `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 | diff --git a/docs/agent/skills/ipal-reference/resources/api.md b/docs/agent/skills/ipal-reference/resources/api.md index abf1e2c..cf86951 100644 --- a/docs/agent/skills/ipal-reference/resources/api.md +++ b/docs/agent/skills/ipal-reference/resources/api.md @@ -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: '' } }` + 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: '' } }` + 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'`. | diff --git a/docs/agent/skills/ipal-setup/SKILL.md b/docs/agent/skills/ipal-setup/SKILL.md index d1e4b7e..ba163c6 100644 --- a/docs/agent/skills/ipal-setup/SKILL.md +++ b/docs/agent/skills/ipal-setup/SKILL.md @@ -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`. diff --git a/docs/agent/skills/ipal-upgrade/SKILL.md b/docs/agent/skills/ipal-upgrade/SKILL.md index e9f6d8b..ae07ef4 100644 --- a/docs/agent/skills/ipal-upgrade/SKILL.md +++ b/docs/agent/skills/ipal-upgrade/SKILL.md @@ -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 diff --git a/docs/dev/PROGRAMISTA.md b/docs/dev/PROGRAMISTA.md index 3e46567..458fb1f 100644 --- a/docs/dev/PROGRAMISTA.md +++ b/docs/dev/PROGRAMISTA.md @@ -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('')`, `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`. diff --git a/docs/security.md b/docs/security.md index 0ef3edd..26780d3 100644 --- a/docs/security.md +++ b/docs/security.md @@ -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: ''` 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)/` or `src/app/(payload)/` 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. diff --git a/reference/.agents/skills/ipal-debug/SKILL.md b/reference/.agents/skills/ipal-debug/SKILL.md index 224d438..34b43b9 100644 --- a/reference/.agents/skills/ipal-debug/SKILL.md +++ b/reference/.agents/skills/ipal-debug/SKILL.md @@ -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 | diff --git a/reference/.agents/skills/ipal-reference/SKILL.md b/reference/.agents/skills/ipal-reference/SKILL.md index 7a9bb31..6f8ca3b 100644 --- a/reference/.agents/skills/ipal-reference/SKILL.md +++ b/reference/.agents/skills/ipal-reference/SKILL.md @@ -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..totpPlugin.` (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.`; `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 | diff --git a/reference/.agents/skills/ipal-reference/resources/api.md b/reference/.agents/skills/ipal-reference/resources/api.md index abf1e2c..cf86951 100644 --- a/reference/.agents/skills/ipal-reference/resources/api.md +++ b/reference/.agents/skills/ipal-reference/resources/api.md @@ -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: '' } }` + 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: '' } }` + 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'`. | diff --git a/reference/.agents/skills/ipal-setup/SKILL.md b/reference/.agents/skills/ipal-setup/SKILL.md index d1e4b7e..ba163c6 100644 --- a/reference/.agents/skills/ipal-setup/SKILL.md +++ b/reference/.agents/skills/ipal-setup/SKILL.md @@ -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`. diff --git a/reference/.agents/skills/ipal-upgrade/SKILL.md b/reference/.agents/skills/ipal-upgrade/SKILL.md index e9f6d8b..ae07ef4 100644 --- a/reference/.agents/skills/ipal-upgrade/SKILL.md +++ b/reference/.agents/skills/ipal-upgrade/SKILL.md @@ -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 diff --git a/src/modules/security/totp/SafeTotpView.tsx b/src/modules/security/totp/SafeTotpView.tsx index 473ca31..77568b3 100644 --- a/src/modules/security/totp/SafeTotpView.tsx +++ b/src/modules/security/totp/SafeTotpView.tsx @@ -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 + /** 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 | undefined)?.back - const back = (ipalSafeBack ?? safeAdminBack)(typeof raw === 'string' ? raw : undefined, { + const query = (props.searchParams ?? {}) as Record + 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>>({ - 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 + const clientProps: Record = { ...ipalTotpClientProps, back, searchParams } + for (const key of CLIENT_PROPS) { + if (key in rest) {clientProps[key] = (rest as Record)[key]} + } + return RenderServerComponent({ + clientProps, + Component: ipalTotpView, + importMap: props.importMap, + serverProps: { ...rest, searchParams }, + }) } diff --git a/src/modules/security/totp/TotpRedirectProvider.tsx b/src/modules/security/totp/TotpRedirectProvider.tsx index 75afd42..a7b7eda 100644 --- a/src/modules/security/totp/TotpRedirectProvider.tsx +++ b/src/modules/security/totp/TotpRedirectProvider.tsx @@ -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 ( +
+

{text.title}

+

{text.body}

+
+ ) + } + return children } export default TotpRedirectProvider diff --git a/src/modules/security/totp/importMapCheck.ts b/src/modules/security/totp/importMapCheck.ts new file mode 100644 index 0000000..41237b0 --- /dev/null +++ b/src/modules/security/totp/importMapCheck.ts @@ -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 { + 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: [] } + } +} diff --git a/src/modules/security/totp/safeBack.ts b/src/modules/security/totp/safeBack.ts index f158340..a6f0e36 100644 --- a/src/modules/security/totp/safeBack.ts +++ b/src/modules/security/totp/safeBack.ts @@ -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( views: Record, added: (key: string) => boolean, rule: SafeBackRule | undefined, - wrapper = '@intecion/ipal-kit/admin#SafeTotpView', -): { dependencies: Record; views: Record } { - const dependencies: Record = {} + wrapper = SAFE_TOTP_VIEW, +): { dependencies: Record; views: Record } { + const dependencies: Record = {} const out: Record = {} 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, after: Record): Set => + new Set(Object.keys(after).filter((key) => after[key] !== before[key])) diff --git a/src/plugin.ts b/src/plugin.ts index da74082..a371849 100644 --- a/src/plugin.ts +++ b/src/plugin.ts @@ -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 = { ...config.admin?.components?.views } const entityEndpointsBefore = new Map>( [...(config.collections ?? []), ...(config.globals ?? [])].map((e) => [e.slug, new Set(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, - (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) { diff --git a/src/types.ts b/src/types.ts index cf74d5f..41c0830 100644 --- a/src/types.ts +++ b/src/types.ts @@ -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 /** diff --git a/test/safeBack.test.ts b/test/safeBack.test.ts index 6cf9022..82623de 100644 --- a/test/safeBack.test.ts +++ b/test/safeBack.test.ts @@ -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, extra: Partial = {}) => +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, extra: Partial = {}, options: Record = {}) => 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 } }> | 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()): 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> + + 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 = {}) => { + 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 })} + } + }) +}) From b2c1dca5dabefdb62e8acd9da690bf34a9bf205b Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?Rados=C5=82aw=20Smoli=C5=84ski?= Date: Tue, 24 Nov 2026 16:35:16 +0100 Subject: [PATCH 3/4] 2FA back link: the stale import-map notice never replaces the screen MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit R2-1: the notice was rendered instead of the 2FA screen, and its flag is a text search of the importMap.js on disk — not the map in the build. A false alarm (map generated in the build with the repository's file in the running image, a re-exporting map) hid a working code form and locked everyone out. The notice is now rendered above the screen, the log line says "may be", and the flag goes to ipal-kit's own provider only. R2-2: views are compared against copies, so a factory that reuses its view objects is guarded too; copyViews, changedViewKeys, SAFE_TOTP_VIEW, totpViewImportKey, findImportMapFile and missingImportMapEntries are exported; ipal-doctor warns when the config registers the 2FA package's own view; docs wording and a misplaced comment fixed. Co-Authored-By: Claude Fable 5.2 --- docs/CHANGELOG.md | 19 ++++-- docs/agent/AGENT.md | 2 +- docs/agent/skills/ipal-debug/SKILL.md | 3 +- docs/agent/skills/ipal-reference/SKILL.md | 2 +- .../skills/ipal-reference/resources/api.md | 5 +- docs/agent/skills/ipal-setup/SKILL.md | 5 +- docs/agent/skills/ipal-upgrade/SKILL.md | 11 +-- docs/doctor.md | 2 +- docs/security.md | 52 ++++++++++---- reference/.agents/skills/ipal-debug/SKILL.md | 3 +- .../.agents/skills/ipal-reference/SKILL.md | 2 +- .../skills/ipal-reference/resources/api.md | 5 +- reference/.agents/skills/ipal-setup/SKILL.md | 5 +- .../.agents/skills/ipal-upgrade/SKILL.md | 11 +-- src/index.ts | 5 +- src/modules/doctor/rules/layout.ts | 9 +++ .../security/totp/TotpRedirectProvider.tsx | 25 ++++--- src/modules/security/totp/importMapCheck.ts | 15 +++-- src/modules/security/totp/safeBack.ts | 15 ++++- src/plugin.ts | 28 +++++--- test/doctor.test.ts | 29 ++++++++ test/safeBack.test.ts | 61 +++++++++++++++++ test/totpRedirectProvider.test.ts | 67 +++++++++++++++++++ 23 files changed, 315 insertions(+), 66 deletions(-) create mode 100644 test/totpRedirectProvider.test.ts diff --git a/docs/CHANGELOG.md b/docs/CHANGELOG.md index dcd285b..55cbb65 100644 --- a/docs/CHANGELOG.md +++ b/docs/CHANGELOG.md @@ -31,8 +31,14 @@ once there are more than 20. - **ipal-doctor**: the import-map rule also expects `@intecion/ipal-kit/admin#SafeTotpView` when the installed plugin has it and the config does not set `safeBack: false`. - **A stale import map is reported** (`twoFactor.importMapCheck`, on by default, `false` turns it off): in - production the plugin reads the committed `importMap.js` at start; when the entry above is missing it logs an - error and the 2FA screens show a message instead of staying empty. + production the plugin searches the `importMap.js` on disk at start; when the entry above is not found it logs + an error and puts a notice above the 2FA screens. The notice never replaces the screen: the file on disk is + not always the map the build used (a Dockerfile with a separate runner stage, a re-exporting map file), and + then the notice is wrong and sign-in still works — turn the check off for such a project. +- **More building blocks exported** for a project that wraps the 2FA views itself: `copyViews`, + `changedViewKeys`, `SAFE_TOTP_VIEW`, `totpViewImportKey`, `findImportMapFile`, `missingImportMapEntries`. +- **ipal-doctor** warns when the config registers the 2FA package's own setup / verify view directly (such a + view is outside the check). - **A project's own 2FA screen set through the wrapped factory** (a server or a client component) is rendered behind the check and gets the checked `back`. @@ -40,10 +46,11 @@ once there are more than 20. - **Every site with 2FA: `pnpm payload generate:importmap`, commit `importMap.js`, `rm -rf .next`, redeploy — in the same deploy as the upgrade.** The plugin's view now stands in front of the package's two screens and needs its import-map entry (`@intecion/ipal-kit/admin#SafeTotpView`). **If you skip this, the build still - passes and the site starts, but the 2FA setup and verify screens come back **empty** (HTTP 200, no code form), so nobody can sign in to the panel.** There is no error page. What tells you: `pnpm exec ipal-doctor` - before the deploy (`import map lacks …SafeTotpView`), the line `[ipal] The admin import map is out of date` in - the log at every start, and a message on the 2FA screens instead of an empty page ("Two-step verification is - not available"). No option, env, schema or migration. + passes and the site starts, but the 2FA setup and verify screens have no code form (HTTP 200), so nobody can + sign in to the panel.** There is no error page. What tells you: `pnpm exec ipal-doctor` before the deploy + (`import map lacks …SafeTotpView`); the line `[ipal] The admin import map may be out of date` in the log at + every start; and, where the form should be, the notice "Two-step verification may not be available". No + option, env, schema or migration. - **Check after deploy:** log in with the password only, open `/admin/verify-totp?back=https%3A%2F%2Fexample.com%2F`, enter the code → you land on `/admin`. A normal login still returns to the page you came from. diff --git a/docs/agent/AGENT.md b/docs/agent/AGENT.md index 2ca5549..0c35937 100644 --- a/docs/agent/AGENT.md +++ b/docs/agent/AGENT.md @@ -1167,7 +1167,7 @@ add missing hosts with flags / `extra`; (3) change `mode` to `'enforce'` in both | 2FA on the panel's login collection, mismatch = startup error; redirect to the 2FA screens by `TotpRedirectProvider` | `twoFactor: false` (discouraged) | `twoFactor.collectionSlug`, `allowCollectionMismatch: true`, `twoFactor.provider` (own component, or `false` for the package's) | | The second factor on every collection and global, whichever plugin added it, and on the plugin's endpoints; an unrecognised 2FA package = startup error | per entity: `custom.ipal.secondFactor: false` or `{ read: false }` (or the package's `custom.totp.disableAccessWrapper`); everywhere: `twoFactor.guard: false` (not recommended) | `requireSecondFactor` / `secondFactorPassed` in your own access functions and endpoints | | At most 5 verify attempts per account in 10 minutes (`POST /api/verify-totp` → `429`) | `twoFactor.verifyLimit: false` | `verifyLimit: { max, windowMinutes }` | -| The `back` link of the 2FA setup and verify screens is checked on the server (`SafeTotpView` in front of the package's views): only a path on the site's origin inside the admin route is kept, anything else (`javascript:`, another host) becomes the admin root. Needs `generate:importmap` in the same deploy — with a stale map the 2FA screens are empty and nobody can sign in (`ipal-doctor`, the start log and a message on the screen report it; `twoFactor.importMapCheck: false` silences that); check: password only → `/admin/verify-totp?back=https%3A%2F%2Fexample.com%2F` → code → lands on `/admin` | `twoFactor.safeBack: false` | `safeBack: (back, { adminRoute, origin }) => string`; `safeAdminBack`, `wrapTotpViews` (`@intecion/ipal-kit`), `SafeTotpView` (`@intecion/ipal-kit/admin`) for own views | +| The `back` link of the 2FA setup and verify screens is checked on the server (`SafeTotpView` in front of the package's views): only a path on the site's origin inside the admin route is kept, anything else (`javascript:`, another host) becomes the admin root. Needs `generate:importmap` in the same deploy — with a stale map the 2FA screens have no code form and nobody can sign in (`ipal-doctor`, the start log and a notice above the screen report it; the notice is a hint from the file on disk and never replaces the screen; `twoFactor.importMapCheck: false` turns it off); check: password only → `/admin/verify-totp?back=https%3A%2F%2Fexample.com%2F` → code → lands on `/admin` | `twoFactor.safeBack: false` | `safeBack: (back, { adminRoute, origin }) => string`; `safeAdminBack`, `wrapTotpViews` (`@intecion/ipal-kit`), `SafeTotpView` (`@intecion/ipal-kit/admin`) for own views | | The 2FA package's endpoints (`/api/setup-totp`, `verify-totp`, `remove-totp`, `admin/*`) answer accounts of the 2FA collection only; reset and remove need the second factor | — (always on with 2FA) | `adminManageAccess` through the wrapped factory (security.md "Resetting 2FA") | | Roles count only for accounts of a staff collection, in every predicate and access function | — | `access.staffCollections` | | `enabled: false` keeps the schema | — | — (no endpoints, `onInit` or admin components; no DROP TABLE in `migrate:create`) | diff --git a/docs/agent/skills/ipal-debug/SKILL.md b/docs/agent/skills/ipal-debug/SKILL.md index 34b43b9..6d19025 100644 --- a/docs/agent/skills/ipal-debug/SKILL.md +++ b/docs/agent/skills/ipal-debug/SKILL.md @@ -58,7 +58,8 @@ through this procedure. Ask only when you are missing something you cannot get y | Symptom | Cause | Fix | |---|---|---| | `PayloadComponent not found in importMap` (e.g. `@intecion/ipal-kit/admin#RowLabel`) | importMap out of date after a plugin update / adding `rowLabel` | `pnpm payload generate:importmap`, restart | -| after an upgrade the 2FA setup / verify screen is **empty** (HTTP 200, no code form) or says "Two-step verification is not available"; nobody can sign in; the log has `[ipal] The admin import map is out of date` and `getFromImportMap: PayloadComponent not found in importMap … @intecion/ipal-kit/admin#SafeTotpView` | the import map was not regenerated after the upgrade that added the `back` link check (`twoFactor.safeBack`); the production build uses the committed, old `importMap.js` | `pnpm payload generate:importmap`, commit `importMap.js`, `rm -rf .next`, redeploy; `pnpm exec ipal-doctor` shows it before a deploy. The opposite case (wrapper present, package view missing) throws `[ipal] The admin import map has no "@clocklimited/payload-2fa/rsc#TOTPVerify"` — same fix | +| after an upgrade the 2FA setup / verify screen has no code form (HTTP 200), only the notice "Two-step verification may not be available" (or nothing at all with `importMapCheck: false` / an own provider); nobody can sign in; the log has `[ipal] The admin import map may be out of date` and `getFromImportMap: PayloadComponent not found in importMap … @intecion/ipal-kit/admin#SafeTotpView` | the import map was not regenerated after the upgrade that added the `back` link check (`twoFactor.safeBack`); the production build uses the committed, old `importMap.js` | `pnpm payload generate:importmap`, commit `importMap.js`, `rm -rf .next`, redeploy; `pnpm exec ipal-doctor` shows it before a deploy. The opposite case (wrapper present, package view missing) throws `[ipal] The admin import map has no "@clocklimited/payload-2fa/rsc#TOTPVerify"` — same fix | +| the notice "Two-step verification may not be available" and the log line `[ipal] The admin import map may be out of date` appear, but the code form is there and sign-in works | false alarm: the check searches the `importMap.js` on disk, which is not the map inside the build (map generated during the build and a Dockerfile runner stage that copies the repository's file; a map file that re-exports or computes its entries) | `twoFactor: { …, importMapCheck: false }`; or ship the generated `importMap.js` in the image | | an own 2FA screen (set through the wrapped factory) ignores the check on `back` | a client component reading `useSearchParams()` gets the raw query value | read the `back` prop (or `searchParams.back`) the wrapper passes — both are checked (security.md "Your own 2FA screen") | | after the 2FA code the user lands on `/admin` instead of the page in `back` | `back` pointed outside the admin route or to another origin (the check keeps only a path inside `routes.admin`; an absolute URL only on the `serverURL` origin) | expected; for another rule pass `twoFactor.safeBack: (back, { adminRoute, origin }) => string` (security.md) | | new admin stuck on `/admin/setup-totp?back=null` (the page keeps redirecting to itself) | ipal-kit ≤ 1.14.1: the 2FA package's provider needs an `x-pathname` header nothing sets on `/admin`; or `twoFactor.provider: false` without that header | update ipal-kit, `pnpm payload generate:importmap` (`TotpRedirectProvider`), restart; check: `/admin/setup-totp?back=%2Fadmin` shows the QR (security.md) | diff --git a/docs/agent/skills/ipal-reference/SKILL.md b/docs/agent/skills/ipal-reference/SKILL.md index 6f8ca3b..1850182 100644 --- a/docs/agent/skills/ipal-reference/SKILL.md +++ b/docs/agent/skills/ipal-reference/SKILL.md @@ -38,7 +38,7 @@ description: Complete map of everything @intecion/ipal-kit provides — every ip | `twoFactor.collectionSlug` | the panel's login collection (`admin.user`, else the first auth collection) | collection with 2FA; startup fails with `[ipal] twoFactor…` when it is not an auth collection or differs from `admin.user` | point it at the login collection | | `twoFactor.provider` | `'@intecion/ipal-kit/admin#TotpRedirectProvider'` | admin provider that sends users to `setup-totp` / `verify-totp` (path read in the browser); replaces the package's header-based one | own component path / `{ path, clientProps, serverProps }` (gets clientProps `forceSetup`); `false` keeps the package's (needs `x-pathname` on `/admin`, else `setup-totp?back=null` loops) | | `twoFactor.safeBack` | on | the `back` query value of the 2FA setup and verify screens is checked on the server before the package's view gets it (`SafeTotpView` registered in place of the package's four views): kept only as a path on the site's origin inside `routes.admin`, else the admin root — no `javascript:` / off-site redirect after the code. Needs `generate:importmap` (`@intecion/ipal-kit/admin#SafeTotpView`) | `false` = the package's views untouched; a function `(back, { adminRoute, origin }) => string` = your own rule | -| `twoFactor.importMapCheck` | on | production only: at start reads the committed `importMap.js` (where Payload looks for it); when `@intecion/ipal-kit/admin#SafeTotpView` is missing, logs `[ipal] The admin import map is out of date …` and the 2FA screens show "Two-step verification is not available" instead of staying empty. A file that cannot be found is not reported | `false` = no file read, log line or message | +| `twoFactor.importMapCheck` | on | production only: at start searches the `importMap.js` on disk (where Payload looks for it) for `@intecion/ipal-kit/admin#SafeTotpView`; when not found, logs `[ipal] The admin import map may be out of date …` and ipal-kit's `TotpRedirectProvider` puts the notice "Two-step verification may not be available" above the 2FA screens (never instead of them). A hint only — the map in the build can differ from the file on disk (Dockerfile runner stage, re-exporting map); a file that is not found is not reported | `false` = no file read, log line or notice | | `twoFactor.texts` | ipal-kit's en/pl texts (`TOTP_TEXTS`) over the package's; 2FA screens titled "Two-step verification" / "Weryfikacja dwuetapowa" (site's language) | `false` = the package's texts; one text: `i18n.translations..totpPlugin.` (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.`; `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 | diff --git a/docs/agent/skills/ipal-reference/resources/api.md b/docs/agent/skills/ipal-reference/resources/api.md index cf86951..1c4efcb 100644 --- a/docs/agent/skills/ipal-reference/resources/api.md +++ b/docs/agent/skills/ipal-reference/resources/api.md @@ -69,7 +69,7 @@ Admin panel components from `@intecion/ipal-kit/admin` — the project does NOT | `buildRolesField(defaultRole?, { firstUserAdmin? })` | `@intecion/ipal-kit` | The `roles` select field the plugin injects (only admins set roles; `firstUserAdmin` default `true` = the account made on "Create first user" gets `admin`). The plugin wires it itself — use it only for an auth collection the plugin does not manage. | | `injectRoles(config, accessOption)` | `@intecion/ipal-kit` | Adds `roles` to `accessOption.authCollection` in a config. The plugin calls it itself with `access` — do not call. | -**Types:** `VerifyLimitOptions` (`twoFactor.verifyLimit`: `{ max?, windowMinutes? }`), `SafeBackRule` / `SafeBackContext` (`twoFactor.safeBack` as a function: `(back, { adminRoute, origin? }) => string`), `SafeTotpViewProps` (`@intecion/ipal-kit/admin`), `Role` (`'user' \| 'editor' \| 'admin'`), `AccessOption` (the plugin's `access` option: `authCollection`, `defaultRole`, `authAccess`, `firstUserAdmin`, `staffCollections`). +**Types:** `VerifyLimitOptions` (`twoFactor.verifyLimit`: `{ max?, windowMinutes? }`), `SafeBackRule` / `SafeBackContext` (`twoFactor.safeBack` as a function: `(back, { adminRoute, origin? }) => string`), `TotpViewComponent` (a view component as registered: a path or `{ path, exportName?, clientProps?, serverProps? }`), `SafeTotpViewProps` (`@intecion/ipal-kit/admin`), `Role` (`'user' \| 'editor' \| 'admin'`), `AccessOption` (the plugin's `access` option: `authCollection`, `defaultRole`, `authAccess`, `firstUserAdmin`, `staffCollections`). ## Accessibility — widget (`accessibility`) — details: `node_modules/@intecion/ipal-kit/docs/accessibility.md` @@ -589,6 +589,9 @@ Server only (`pnpm payload run`); never import it from client code, the Payload | `secondFactorPassed(req)` | `@intecion/ipal-kit` | `boolean` with `req` (`{ payload, user }`): `false` only for an account of the 2FA collection that has TOTP set up and has not entered the code in this session (password only). `true` for a full login, an API key, an account that has not set TOTP up yet, accounts of other auth collections, no user, and with `twoFactor: false`. Guard your own endpoints with it: `if (!req.user \|\| !secondFactorPassed(req)) return 403`. | | `safeAdminBack(back, { adminRoute, origin? })` | `@intecion/ipal-kit` | The default `back` rule of the 2FA screens: returns `back` as a path when it resolves to the site's origin (the placeholder origin for relative values, `origin` for absolute ones), over HTTP(S), without credentials, inside `adminRoute`; otherwise the admin root. `safeAdminBack('javascript:alert(1)', { adminRoute: '/admin' })` → `'/admin'`; `safeAdminBack('/admin/collections/pages?page=2', { adminRoute: '/admin' })` → the same path. Use it in your own rule or view. | | `wrapTotpViews(views, added, rule?, wrapper?)` | `@intecion/ipal-kit` | Puts `SafeTotpView` in front of the views whose route is `setup-totp` / `verify-totp` and for which `added(key)` is true (keeps `exportName`, `serverProps`; `clientProps` travel as `ipalTotpClientProps`); returns `{ views, dependencies }` (`dependencies` → `admin.dependencies`, so the wrapped views stay in the import map). What `ipalKit` runs after the 2FA factory; for a project that registers the 2FA package itself. | +| `copyViews(views)` / `changedViewKeys(before, after)` | `@intecion/ipal-kit` | The comparison `ipalKit` uses to tell which views a 2FA factory registered: put `copyViews(views)` into the config before calling the factory, then `changedViewKeys(before, viewsAfter)` gives the keys whose view object changed — the `added` argument of `wrapTotpViews` (`(key) => keys.has(key)`). By object, not by key: the 2FA package replaces a view that already stands under its keys. Example: security.md "Your own 2FA screen". | +| `SAFE_TOTP_VIEW` / `totpViewImportKey(component)` | `@intecion/ipal-kit` | `'@intecion/ipal-kit/admin#SafeTotpView'`, the wrapper's import-map path (the default `wrapper` of `wrapTotpViews`); and the import-map key (`path#export`) of a component given as a string or `{ path, exportName }`. | +| `findImportMapFile(config, cwd?)` / `missingImportMapEntries(config, entries, cwd?)` | `@intecion/ipal-kit` | Where the project's `importMap.js` is on disk (`admin.importMap.importMapFile`, else `app/(payload)/` or `src/app/…` under `admin.importMap.baseDir` / the working directory; `null` when not found), and which of `entries` its text does not contain (`{ file, missing }`). A hint from the file on disk, not the map in the build: warn on it, never block on it. Behind `twoFactor.importMapCheck`. | | `requireSecondFactor(access?)` | `@intecion/ipal-kit` | Wraps an `Access` function: refused while the second factor is owed, otherwise the function itself (Payload's default "logged in" when none). ipalKit applies it to every collection and global in the config, and to those added by plugins listed after it (in `onInit` and at the start of the first request, so also after a dev hot reload); use it for access functions that are not part of the config. Per-entity opt-out: `custom.ipal.secondFactor: false \| { read: false }` or the package's `custom.totp.disableAccessWrapper`. Wrapping twice is harmless. | | `totpRedirectTarget({ adminRoute, forceSetup?, pathname, user, excludePaths? })`, `totpAdminPath(adminRoute, path)` | `@intecion/ipal-kit` | The 2FA redirect rules as pure functions: the setup / verify URL (with `back`) to send this user to, or `null` (no path, api key, already on a TOTP screen or logout). For an own `twoFactor.provider`. Types `TotpRedirectArgs`, `TotpUser` | | `buildCsp({ mode?, reportUri?, reportGroup?, r2Url?, analytics?, metaPixel?, linkedIn?, tiktok?, clarity?, turnstile?, youtube?, googleMaps?, nonce?, strictDynamic?, dev?, extra?, override? })` | `@intecion/ipal-kit` | Returns `{ key, value }` with a hardened CSP (`base-uri`, `object-src`, `frame-ancestors`, `form-action`) + sources for the enabled integrations. `mode: 'report-only'` → `…-Report-Only` (start here), `'enforce'` later. `extra` adds to any directive, `override` replaces / drops one (`null`). `dev` (default `NODE_ENV === 'development'`) adds `'unsafe-eval'`. `nonce` → `'nonce-…' 'strict-dynamic'`. | diff --git a/docs/agent/skills/ipal-setup/SKILL.md b/docs/agent/skills/ipal-setup/SKILL.md index ba163c6..b413b49 100644 --- a/docs/agent/skills/ipal-setup/SKILL.md +++ b/docs/agent/skills/ipal-setup/SKILL.md @@ -228,8 +228,9 @@ the panel shows Site settings, Site integrations, Cookies, Form messages, the Fo The `back` link of the setup and verify screens is checked on the server (`twoFactor.safeBack`, on by default: only a path inside the admin route is kept; `false` turns it off, a function replaces the rule). It needs the import map entry `@intecion/ipal-kit/admin#SafeTotpView` — run `pnpm payload generate:importmap` and commit - (a production build with a map that lacks it shows empty 2FA screens: nobody can sign in; `ipal-doctor` and the - start log report it, `twoFactor.importMapCheck: false` turns that report off). + (a production build with a map that lacks it shows 2FA screens without a code form: nobody can sign in; + `ipal-doctor`, the start log and a notice above the screen report it; `twoFactor.importMapCheck: false` turns the + log line and the notice off — needed when the `importMap.js` on disk is not the one the build used). Check: password only → `/admin/verify-totp?back=https%3A%2F%2Fexample.com%2F` → code → you land on `/admin`. **Set 2FA up right after creating an account** (log in as it, scan the code): until then its password alone opens everything its role allows. One entity reachable without the code: `custom.ipal.secondFactor`. diff --git a/docs/agent/skills/ipal-upgrade/SKILL.md b/docs/agent/skills/ipal-upgrade/SKILL.md index ae07ef4..e9ab2b1 100644 --- a/docs/agent/skills/ipal-upgrade/SKILL.md +++ b/docs/agent/skills/ipal-upgrade/SKILL.md @@ -142,10 +142,13 @@ panel opens and a document saves. 1. **Do this in the same deploy as the upgrade, or the panel is locked for everyone.** `pnpm payload generate:importmap` — the plugin puts `@intecion/ipal-kit/admin#SafeTotpView` in front of the 2FA package's setup and verify views; commit `importMap.js`, `rm -rf .next`, redeploy on Coolify. With the old - import map the build passes and the site starts, but the 2FA screens are **empty** (HTTP 200, no code form) — - nobody can sign in. Signs: `pnpm exec ipal-doctor` → `import map lacks …SafeTotpView` (run it before deploying); - the log line `[ipal] The admin import map is out of date` at start; the screen says "Two-step verification is - not available". Fix: the same command, commit, redeploy. + import map the build passes and the site starts, but the 2FA screens have no code form (HTTP 200) — nobody can + sign in. Signs: `pnpm exec ipal-doctor` → `import map lacks …SafeTotpView` (run it before deploying); the log + line `[ipal] The admin import map may be out of date` at start; the notice "Two-step verification may not be + available" where the form should be. Fix: the same command, commit, redeploy. + The log line and the notice with a **working** code form mean a false alarm (the `importMap.js` on disk is not + the one the build used — a Dockerfile runner stage, a re-exporting map): sign-in works; set + `twoFactor.importMapCheck: false`. **Check:** log in with the password only → open `/admin/verify-totp?back=https%3A%2F%2Fexample.com%2F` → enter the code → you land on `/admin` (not on example.com); a normal login still returns to the page you came from. No option, env, schema or migration. A project that registered its own 2FA views, or wrote a proxy rule that diff --git a/docs/doctor.md b/docs/doctor.md index 1b4fa4c..f7b14ee 100644 --- a/docs/doctor.md +++ b/docs/doctor.md @@ -89,7 +89,7 @@ Turn off: `ipalKit({ doctor: false })`. Adapt: `ipalKit({ doctor: { tokenVar: 'M | | `layout-forbidden` | error | no `middleware.ts`, no `lib/{pages,locales,navigation}.ts`, `fields/{link,sectionHeader,sectionSettings}.ts` | | | `layout-extra` | info | `src/` entries outside the allow list (AGENT.md §3 + `seed/`, `design/`, `db.ts`, `env.rules.ts`, `content.config.ts`; extend with `layout.allow`) | | | `naming` | warning | block folders, collection and global files PascalCase, `scripts/*` kebab-case, no `index.ts` barrels | -| | `importmap` | error | the import map exists, holds the entries for what the config turns on (2FA, R2, cookie scanner, `adminMeta`), names no export the plugin no longer has; with `--deep`, equals a fresh one | +| | `importmap` | error | the import map exists, holds the entries for what the config turns on (2FA, R2, cookie scanner, `adminMeta`), names no export the plugin no longer has; with `--deep`, equals a fresh one. Warning: the config registers the 2FA package's own setup / verify view directly (outside the `back` link check — security.md) | | | `tsconfig-skills` | error | `tsconfig.json` excludes the skills folder | | env | `db-name` | error | `DATABASE_URI` in `.env` and `.env.example` names `_dev`; a local `.env` on `_prod` is an error; `--env-file` checks `_prod` (`databaseNamesFor`) | | | `env-rules` | error / warning | `instrumentation.ts` calls `assertEnv(ipalEnvRules(…))` from `/env`, with `storage` (R2), `cookieCrawl` (crawl), `ipHeader`; `databaseName` suggested (info) | diff --git a/docs/security.md b/docs/security.md index 26780d3..abca596 100644 --- a/docs/security.md +++ b/docs/security.md @@ -610,23 +610,46 @@ guarded. The same holds when the project also lists `payloadTotp(...)` in `plugi your `clientProps`, and `back` plus `searchParams` — both checked; read `back` from the props, not from `useSearchParams()`, which still holds the raw query value. - From a plugin listed after `ipalKit`, or under another key or route: that view is yours and is not wrapped. Use - `wrapTotpViews` or `safeAdminBack` in it. + `wrapTotpViews` or `safeAdminBack` in it. `ipal-doctor` warns when the config names the package's own view + (`@clocklimited/payload-2fa/rsc#TOTPVerify` / `#TOTPSetup`) directly. + + Wrapping views yourself, for a project that runs the 2FA package without `ipalKit`'s `twoFactor` (all from + `@intecion/ipal-kit`): + ```ts + const before = copyViews(config.admin?.components?.views) // copies: the factory's views are then never "the same object" + config = await payloadTotp(options)({ ...config, admin: { ...config.admin, components: { ...config.admin?.components, views: before } } }) + const fromPackage = changedViewKeys(before, config.admin?.components?.views ?? {}) // by object — the package replaces views under its keys + const { dependencies, views } = wrapTotpViews(config.admin?.components?.views ?? {}, (key) => fromPackage.has(key), undefined) + config.admin = { ...config.admin, components: { ...config.admin?.components, views }, dependencies: { ...config.admin?.dependencies, ...dependencies } } + ``` + `SAFE_TOTP_VIEW` is the wrapper's import-map path; `findImportMapFile` / `missingImportMapEntries` are the + stale-map check below (a hint from the file on disk — warn on it, never block on it). **A stale import map (read this before upgrading a site with 2FA).** The check needs the import-map entry `@intecion/ipal-kit/admin#SafeTotpView`. A production build made with the import map of the previous version -passes, the site starts, and the 2FA setup and verify screens come back **empty** (HTTP 200, no code form), so nobody can sign in to the panel. Payload renders nothing for a path its map lacks; the only trace is +passes and the site starts, but Payload renders nothing for a path its map lacks: the 2FA setup and verify +screens have no code form (HTTP 200), so nobody can sign in to the panel. Payload's only trace is `getFromImportMap: PayloadComponent not found in importMap` in the server log. Development is not affected (Payload -regenerates the map there). ipal-kit makes this loud in three places: +regenerates the map there). ipal-kit reports it in three places: - **Before deploy:** `pnpm exec ipal-doctor` reports `import map lacks @intecion/ipal-kit/admin#SafeTotpView` (error). -- **At every start in production:** the log has `[ipal] The admin import map is out of date: … The 2FA setup and - verify screens are EMPTY …`. -- **On the screen:** instead of nothing, the 2FA screens say "Two-step verification is not available" and what a - developer has to run (shown by `TotpRedirectProvider`; with your own `twoFactor.provider` it gets the clientProp - `staleImportMap`, with `provider: false` there is only the log line). -The check reads `importMap.js` where Payload looks for it (`admin.importMap.importMapFile`, else -`app/(payload)/` or `src/app/(payload)/` under `admin.importMap.baseDir` or the working -directory). A file it cannot find is never reported. `twoFactor: { …, importMapCheck: false }` turns the file read, -the log line and the message off. **Fix:** `pnpm payload generate:importmap`, commit `importMap.js`, rebuild, redeploy. +- **At every start in production:** the log has `[ipal] The admin import map may be out of date: … was not found + in …`. +- **On the screen:** a notice above the 2FA screen, "Two-step verification may not be available", with what a + developer has to run. With a really stale map the notice is all the user sees (the form is missing); it is + shown by ipal-kit's `TotpRedirectProvider` only — with your own `twoFactor.provider`, or `provider: false`, + there is the log line alone. + +The start-up check is a guess, and is built so that a wrong guess costs a wrong notice and nothing else: it +searches the text of the `importMap.js` **on disk** where Payload looks for it (`admin.importMap.importMapFile`, +else `app/(payload)/` or `src/app/(payload)/` under `admin.importMap.baseDir` or the +working directory), while the map the site really uses is inside the build. The two differ when the map is +generated during the build and the running image carries the repository's file (a Dockerfile with a separate +runner stage), or when the map file re-exports or computes its entries. Then the log line and the notice appear +although the screen works — the code form stays on the page and sign-in is not affected. Turn the check off for +such a project: `twoFactor: { …, importMapCheck: false }` (no file read, no log line, no notice). A file that is +not found is not reported. Building in place (Coolify's Nixpacks) reads the same file the build used. + +**Fix for a really stale map:** `pnpm payload generate:importmap`, commit `importMap.js`, rebuild, redeploy. A second error exists for the opposite case — the wrapper is in the map but the package's view is not: `[ipal] The admin import map has no "@clocklimited/payload-2fa/rsc#TOTPVerify"` (same fix). @@ -732,8 +755,9 @@ size while reading, content signature, container and macro checks, an optional ` - **Verify limit:** `twoFactor.verifyLimit: { max, windowMinutes }`, or `false`. - **`back` link check of the 2FA screens:** `twoFactor.safeBack: false`, or a function as your own rule; - `safeAdminBack`, `wrapTotpViews`, `SafeTotpView` are exported. The stale import-map warning that comes with it: - `twoFactor.importMapCheck: false`. + `safeAdminBack`, `wrapTotpViews`, `copyViews`, `changedViewKeys`, `SAFE_TOTP_VIEW`, `SafeTotpView` are exported. + The stale import-map notice that comes with it: `twoFactor.importMapCheck: false`; its parts + (`findImportMapFile`, `missingImportMapEntries`) are exported too. - **2FA check:** per entity `custom.ipal.secondFactor` / `custom.totp.disableAccessWrapper` (one operation or all); `twoFactor.guard: false` turns ipal-kit's own second-factor check off everywhere (not recommended); `requireSecondFactor` / `secondFactorPassed` are exported for your own access functions and endpoints. diff --git a/reference/.agents/skills/ipal-debug/SKILL.md b/reference/.agents/skills/ipal-debug/SKILL.md index 34b43b9..6d19025 100644 --- a/reference/.agents/skills/ipal-debug/SKILL.md +++ b/reference/.agents/skills/ipal-debug/SKILL.md @@ -58,7 +58,8 @@ through this procedure. Ask only when you are missing something you cannot get y | Symptom | Cause | Fix | |---|---|---| | `PayloadComponent not found in importMap` (e.g. `@intecion/ipal-kit/admin#RowLabel`) | importMap out of date after a plugin update / adding `rowLabel` | `pnpm payload generate:importmap`, restart | -| after an upgrade the 2FA setup / verify screen is **empty** (HTTP 200, no code form) or says "Two-step verification is not available"; nobody can sign in; the log has `[ipal] The admin import map is out of date` and `getFromImportMap: PayloadComponent not found in importMap … @intecion/ipal-kit/admin#SafeTotpView` | the import map was not regenerated after the upgrade that added the `back` link check (`twoFactor.safeBack`); the production build uses the committed, old `importMap.js` | `pnpm payload generate:importmap`, commit `importMap.js`, `rm -rf .next`, redeploy; `pnpm exec ipal-doctor` shows it before a deploy. The opposite case (wrapper present, package view missing) throws `[ipal] The admin import map has no "@clocklimited/payload-2fa/rsc#TOTPVerify"` — same fix | +| after an upgrade the 2FA setup / verify screen has no code form (HTTP 200), only the notice "Two-step verification may not be available" (or nothing at all with `importMapCheck: false` / an own provider); nobody can sign in; the log has `[ipal] The admin import map may be out of date` and `getFromImportMap: PayloadComponent not found in importMap … @intecion/ipal-kit/admin#SafeTotpView` | the import map was not regenerated after the upgrade that added the `back` link check (`twoFactor.safeBack`); the production build uses the committed, old `importMap.js` | `pnpm payload generate:importmap`, commit `importMap.js`, `rm -rf .next`, redeploy; `pnpm exec ipal-doctor` shows it before a deploy. The opposite case (wrapper present, package view missing) throws `[ipal] The admin import map has no "@clocklimited/payload-2fa/rsc#TOTPVerify"` — same fix | +| the notice "Two-step verification may not be available" and the log line `[ipal] The admin import map may be out of date` appear, but the code form is there and sign-in works | false alarm: the check searches the `importMap.js` on disk, which is not the map inside the build (map generated during the build and a Dockerfile runner stage that copies the repository's file; a map file that re-exports or computes its entries) | `twoFactor: { …, importMapCheck: false }`; or ship the generated `importMap.js` in the image | | an own 2FA screen (set through the wrapped factory) ignores the check on `back` | a client component reading `useSearchParams()` gets the raw query value | read the `back` prop (or `searchParams.back`) the wrapper passes — both are checked (security.md "Your own 2FA screen") | | after the 2FA code the user lands on `/admin` instead of the page in `back` | `back` pointed outside the admin route or to another origin (the check keeps only a path inside `routes.admin`; an absolute URL only on the `serverURL` origin) | expected; for another rule pass `twoFactor.safeBack: (back, { adminRoute, origin }) => string` (security.md) | | new admin stuck on `/admin/setup-totp?back=null` (the page keeps redirecting to itself) | ipal-kit ≤ 1.14.1: the 2FA package's provider needs an `x-pathname` header nothing sets on `/admin`; or `twoFactor.provider: false` without that header | update ipal-kit, `pnpm payload generate:importmap` (`TotpRedirectProvider`), restart; check: `/admin/setup-totp?back=%2Fadmin` shows the QR (security.md) | diff --git a/reference/.agents/skills/ipal-reference/SKILL.md b/reference/.agents/skills/ipal-reference/SKILL.md index 6f8ca3b..1850182 100644 --- a/reference/.agents/skills/ipal-reference/SKILL.md +++ b/reference/.agents/skills/ipal-reference/SKILL.md @@ -38,7 +38,7 @@ description: Complete map of everything @intecion/ipal-kit provides — every ip | `twoFactor.collectionSlug` | the panel's login collection (`admin.user`, else the first auth collection) | collection with 2FA; startup fails with `[ipal] twoFactor…` when it is not an auth collection or differs from `admin.user` | point it at the login collection | | `twoFactor.provider` | `'@intecion/ipal-kit/admin#TotpRedirectProvider'` | admin provider that sends users to `setup-totp` / `verify-totp` (path read in the browser); replaces the package's header-based one | own component path / `{ path, clientProps, serverProps }` (gets clientProps `forceSetup`); `false` keeps the package's (needs `x-pathname` on `/admin`, else `setup-totp?back=null` loops) | | `twoFactor.safeBack` | on | the `back` query value of the 2FA setup and verify screens is checked on the server before the package's view gets it (`SafeTotpView` registered in place of the package's four views): kept only as a path on the site's origin inside `routes.admin`, else the admin root — no `javascript:` / off-site redirect after the code. Needs `generate:importmap` (`@intecion/ipal-kit/admin#SafeTotpView`) | `false` = the package's views untouched; a function `(back, { adminRoute, origin }) => string` = your own rule | -| `twoFactor.importMapCheck` | on | production only: at start reads the committed `importMap.js` (where Payload looks for it); when `@intecion/ipal-kit/admin#SafeTotpView` is missing, logs `[ipal] The admin import map is out of date …` and the 2FA screens show "Two-step verification is not available" instead of staying empty. A file that cannot be found is not reported | `false` = no file read, log line or message | +| `twoFactor.importMapCheck` | on | production only: at start searches the `importMap.js` on disk (where Payload looks for it) for `@intecion/ipal-kit/admin#SafeTotpView`; when not found, logs `[ipal] The admin import map may be out of date …` and ipal-kit's `TotpRedirectProvider` puts the notice "Two-step verification may not be available" above the 2FA screens (never instead of them). A hint only — the map in the build can differ from the file on disk (Dockerfile runner stage, re-exporting map); a file that is not found is not reported | `false` = no file read, log line or notice | | `twoFactor.texts` | ipal-kit's en/pl texts (`TOTP_TEXTS`) over the package's; 2FA screens titled "Two-step verification" / "Weryfikacja dwuetapowa" (site's language) | `false` = the package's texts; one text: `i18n.translations..totpPlugin.` (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.`; `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 | diff --git a/reference/.agents/skills/ipal-reference/resources/api.md b/reference/.agents/skills/ipal-reference/resources/api.md index cf86951..1c4efcb 100644 --- a/reference/.agents/skills/ipal-reference/resources/api.md +++ b/reference/.agents/skills/ipal-reference/resources/api.md @@ -69,7 +69,7 @@ Admin panel components from `@intecion/ipal-kit/admin` — the project does NOT | `buildRolesField(defaultRole?, { firstUserAdmin? })` | `@intecion/ipal-kit` | The `roles` select field the plugin injects (only admins set roles; `firstUserAdmin` default `true` = the account made on "Create first user" gets `admin`). The plugin wires it itself — use it only for an auth collection the plugin does not manage. | | `injectRoles(config, accessOption)` | `@intecion/ipal-kit` | Adds `roles` to `accessOption.authCollection` in a config. The plugin calls it itself with `access` — do not call. | -**Types:** `VerifyLimitOptions` (`twoFactor.verifyLimit`: `{ max?, windowMinutes? }`), `SafeBackRule` / `SafeBackContext` (`twoFactor.safeBack` as a function: `(back, { adminRoute, origin? }) => string`), `SafeTotpViewProps` (`@intecion/ipal-kit/admin`), `Role` (`'user' \| 'editor' \| 'admin'`), `AccessOption` (the plugin's `access` option: `authCollection`, `defaultRole`, `authAccess`, `firstUserAdmin`, `staffCollections`). +**Types:** `VerifyLimitOptions` (`twoFactor.verifyLimit`: `{ max?, windowMinutes? }`), `SafeBackRule` / `SafeBackContext` (`twoFactor.safeBack` as a function: `(back, { adminRoute, origin? }) => string`), `TotpViewComponent` (a view component as registered: a path or `{ path, exportName?, clientProps?, serverProps? }`), `SafeTotpViewProps` (`@intecion/ipal-kit/admin`), `Role` (`'user' \| 'editor' \| 'admin'`), `AccessOption` (the plugin's `access` option: `authCollection`, `defaultRole`, `authAccess`, `firstUserAdmin`, `staffCollections`). ## Accessibility — widget (`accessibility`) — details: `node_modules/@intecion/ipal-kit/docs/accessibility.md` @@ -589,6 +589,9 @@ Server only (`pnpm payload run`); never import it from client code, the Payload | `secondFactorPassed(req)` | `@intecion/ipal-kit` | `boolean` with `req` (`{ payload, user }`): `false` only for an account of the 2FA collection that has TOTP set up and has not entered the code in this session (password only). `true` for a full login, an API key, an account that has not set TOTP up yet, accounts of other auth collections, no user, and with `twoFactor: false`. Guard your own endpoints with it: `if (!req.user \|\| !secondFactorPassed(req)) return 403`. | | `safeAdminBack(back, { adminRoute, origin? })` | `@intecion/ipal-kit` | The default `back` rule of the 2FA screens: returns `back` as a path when it resolves to the site's origin (the placeholder origin for relative values, `origin` for absolute ones), over HTTP(S), without credentials, inside `adminRoute`; otherwise the admin root. `safeAdminBack('javascript:alert(1)', { adminRoute: '/admin' })` → `'/admin'`; `safeAdminBack('/admin/collections/pages?page=2', { adminRoute: '/admin' })` → the same path. Use it in your own rule or view. | | `wrapTotpViews(views, added, rule?, wrapper?)` | `@intecion/ipal-kit` | Puts `SafeTotpView` in front of the views whose route is `setup-totp` / `verify-totp` and for which `added(key)` is true (keeps `exportName`, `serverProps`; `clientProps` travel as `ipalTotpClientProps`); returns `{ views, dependencies }` (`dependencies` → `admin.dependencies`, so the wrapped views stay in the import map). What `ipalKit` runs after the 2FA factory; for a project that registers the 2FA package itself. | +| `copyViews(views)` / `changedViewKeys(before, after)` | `@intecion/ipal-kit` | The comparison `ipalKit` uses to tell which views a 2FA factory registered: put `copyViews(views)` into the config before calling the factory, then `changedViewKeys(before, viewsAfter)` gives the keys whose view object changed — the `added` argument of `wrapTotpViews` (`(key) => keys.has(key)`). By object, not by key: the 2FA package replaces a view that already stands under its keys. Example: security.md "Your own 2FA screen". | +| `SAFE_TOTP_VIEW` / `totpViewImportKey(component)` | `@intecion/ipal-kit` | `'@intecion/ipal-kit/admin#SafeTotpView'`, the wrapper's import-map path (the default `wrapper` of `wrapTotpViews`); and the import-map key (`path#export`) of a component given as a string or `{ path, exportName }`. | +| `findImportMapFile(config, cwd?)` / `missingImportMapEntries(config, entries, cwd?)` | `@intecion/ipal-kit` | Where the project's `importMap.js` is on disk (`admin.importMap.importMapFile`, else `app/(payload)/` or `src/app/…` under `admin.importMap.baseDir` / the working directory; `null` when not found), and which of `entries` its text does not contain (`{ file, missing }`). A hint from the file on disk, not the map in the build: warn on it, never block on it. Behind `twoFactor.importMapCheck`. | | `requireSecondFactor(access?)` | `@intecion/ipal-kit` | Wraps an `Access` function: refused while the second factor is owed, otherwise the function itself (Payload's default "logged in" when none). ipalKit applies it to every collection and global in the config, and to those added by plugins listed after it (in `onInit` and at the start of the first request, so also after a dev hot reload); use it for access functions that are not part of the config. Per-entity opt-out: `custom.ipal.secondFactor: false \| { read: false }` or the package's `custom.totp.disableAccessWrapper`. Wrapping twice is harmless. | | `totpRedirectTarget({ adminRoute, forceSetup?, pathname, user, excludePaths? })`, `totpAdminPath(adminRoute, path)` | `@intecion/ipal-kit` | The 2FA redirect rules as pure functions: the setup / verify URL (with `back`) to send this user to, or `null` (no path, api key, already on a TOTP screen or logout). For an own `twoFactor.provider`. Types `TotpRedirectArgs`, `TotpUser` | | `buildCsp({ mode?, reportUri?, reportGroup?, r2Url?, analytics?, metaPixel?, linkedIn?, tiktok?, clarity?, turnstile?, youtube?, googleMaps?, nonce?, strictDynamic?, dev?, extra?, override? })` | `@intecion/ipal-kit` | Returns `{ key, value }` with a hardened CSP (`base-uri`, `object-src`, `frame-ancestors`, `form-action`) + sources for the enabled integrations. `mode: 'report-only'` → `…-Report-Only` (start here), `'enforce'` later. `extra` adds to any directive, `override` replaces / drops one (`null`). `dev` (default `NODE_ENV === 'development'`) adds `'unsafe-eval'`. `nonce` → `'nonce-…' 'strict-dynamic'`. | diff --git a/reference/.agents/skills/ipal-setup/SKILL.md b/reference/.agents/skills/ipal-setup/SKILL.md index ba163c6..b413b49 100644 --- a/reference/.agents/skills/ipal-setup/SKILL.md +++ b/reference/.agents/skills/ipal-setup/SKILL.md @@ -228,8 +228,9 @@ the panel shows Site settings, Site integrations, Cookies, Form messages, the Fo The `back` link of the setup and verify screens is checked on the server (`twoFactor.safeBack`, on by default: only a path inside the admin route is kept; `false` turns it off, a function replaces the rule). It needs the import map entry `@intecion/ipal-kit/admin#SafeTotpView` — run `pnpm payload generate:importmap` and commit - (a production build with a map that lacks it shows empty 2FA screens: nobody can sign in; `ipal-doctor` and the - start log report it, `twoFactor.importMapCheck: false` turns that report off). + (a production build with a map that lacks it shows 2FA screens without a code form: nobody can sign in; + `ipal-doctor`, the start log and a notice above the screen report it; `twoFactor.importMapCheck: false` turns the + log line and the notice off — needed when the `importMap.js` on disk is not the one the build used). Check: password only → `/admin/verify-totp?back=https%3A%2F%2Fexample.com%2F` → code → you land on `/admin`. **Set 2FA up right after creating an account** (log in as it, scan the code): until then its password alone opens everything its role allows. One entity reachable without the code: `custom.ipal.secondFactor`. diff --git a/reference/.agents/skills/ipal-upgrade/SKILL.md b/reference/.agents/skills/ipal-upgrade/SKILL.md index ae07ef4..e9ab2b1 100644 --- a/reference/.agents/skills/ipal-upgrade/SKILL.md +++ b/reference/.agents/skills/ipal-upgrade/SKILL.md @@ -142,10 +142,13 @@ panel opens and a document saves. 1. **Do this in the same deploy as the upgrade, or the panel is locked for everyone.** `pnpm payload generate:importmap` — the plugin puts `@intecion/ipal-kit/admin#SafeTotpView` in front of the 2FA package's setup and verify views; commit `importMap.js`, `rm -rf .next`, redeploy on Coolify. With the old - import map the build passes and the site starts, but the 2FA screens are **empty** (HTTP 200, no code form) — - nobody can sign in. Signs: `pnpm exec ipal-doctor` → `import map lacks …SafeTotpView` (run it before deploying); - the log line `[ipal] The admin import map is out of date` at start; the screen says "Two-step verification is - not available". Fix: the same command, commit, redeploy. + import map the build passes and the site starts, but the 2FA screens have no code form (HTTP 200) — nobody can + sign in. Signs: `pnpm exec ipal-doctor` → `import map lacks …SafeTotpView` (run it before deploying); the log + line `[ipal] The admin import map may be out of date` at start; the notice "Two-step verification may not be + available" where the form should be. Fix: the same command, commit, redeploy. + The log line and the notice with a **working** code form mean a false alarm (the `importMap.js` on disk is not + the one the build used — a Dockerfile runner stage, a re-exporting map): sign-in works; set + `twoFactor.importMapCheck: false`. **Check:** log in with the password only → open `/admin/verify-totp?back=https%3A%2F%2Fexample.com%2F` → enter the code → you land on `/admin` (not on example.com); a normal login still returns to the page you came from. No option, env, schema or migration. A project that registered its own 2FA views, or wrote a proxy rule that diff --git a/src/index.ts b/src/index.ts index a45b238..8ffb2b6 100644 --- a/src/index.ts +++ b/src/index.ts @@ -327,8 +327,9 @@ export type { } from './modules/security/index.js' export type { BuildSecurityHeadersArgs, SecurityHeader } from './modules/security/index.js' -export { safeAdminBack, wrapTotpViews } from './modules/security/totp/safeBack.js' -export type { SafeBackContext, SafeBackRule } from './modules/security/totp/safeBack.js' +export { findImportMapFile, missingImportMapEntries } from './modules/security/totp/importMapCheck.js' +export { changedViewKeys, copyViews, SAFE_TOTP_VIEW, safeAdminBack, totpViewImportKey, wrapTotpViews } from './modules/security/totp/safeBack.js' +export type { SafeBackContext, SafeBackRule, TotpViewComponent } from './modules/security/totp/safeBack.js' export { requireSecondFactor, secondFactorPassed } from './modules/security/totp/secondFactor.js' export { TOTP_TEXTS, TOTP_VIEW_TITLE } from './modules/security/totp/totpTexts.js' export type { VerifyLimitOptions } from './modules/security/totp/verifyLimit.js' diff --git a/src/modules/doctor/rules/layout.ts b/src/modules/doctor/rules/layout.ts index 08412c8..65f71a8 100644 --- a/src/modules/doctor/rules/layout.ts +++ b/src/modules/doctor/rules/layout.ts @@ -203,6 +203,15 @@ export const layoutRules: DoctorRule[] = [ need.push('@intecion/ipal-kit/admin#SafeTotpView') } } + // A view the project registers itself with the 2FA package's own component is not behind the back-link check. + if (/@clocklimited\/payload-2fa\/rsc#TOTP(?:Setup|Verify)/.test(cfg)) { + out.push({ + file: configFile(ctx) ?? undefined, + fix: "register it through wrapTotpViews (or Component: { path: '@intecion/ipal-kit/admin#SafeTotpView', serverProps: { ipalTotpView: '' } } plus the path in admin.dependencies) — security.md \"Your own 2FA screen\"", + message: "the config names the 2FA package's own setup / verify view: a view registered that way sends the browser to an unchecked `back` link after the code", + severity: 'warning', + }) + } if (/buildR2Storage/.test(cfg)) {need.push('S3ClientUploadHandler')} if (/cookieScanner\s*:\s*(?!false)/.test(cfg) && !lt(v, '1.14.4')) {need.push('@intecion/ipal-kit/admin#CookieReviewTab')} if (!lt(v, '1.14.5') && !/adminMeta\s*:\s*false/.test(cfg)) {need.push('@intecion/ipal-kit/admin#AdminIcon')} diff --git a/src/modules/security/totp/TotpRedirectProvider.tsx b/src/modules/security/totp/TotpRedirectProvider.tsx index a7b7eda..a42a2c9 100644 --- a/src/modules/security/totp/TotpRedirectProvider.tsx +++ b/src/modules/security/totp/TotpRedirectProvider.tsx @@ -15,20 +15,22 @@ export type TotpRedirectProviderProps = { /** pluginOptions.forceSetup — set by the plugin (true: 2FA is enforced). */ forceSetup?: boolean /** - * Set by the plugin when the committed admin import map lacks the 2FA view wrapper - * (importMapCheck.ts): the 2FA screens would be empty, so they say what is wrong instead. + * Set by the plugin when the admin import map on disk lacks the 2FA view wrapper + * (importMapCheck.ts). The 2FA screens are then probably empty, so a notice says what is + * wrong. The screen itself is still rendered: the check is a guess, and a wrong guess must + * cost a wrong notice at most, never the code form. */ staleImportMap?: boolean } const STALE_TEXT = { en: { - body: 'The site was deployed without a refreshed admin import map, so this screen cannot load and nobody can sign in. A developer has to run "pnpm payload generate:importmap", commit importMap.js and deploy again.', - title: 'Two-step verification is not available', + body: 'If there is no place to enter the code on this page, the site was deployed without a refreshed admin import map. A developer has to run "pnpm payload generate:importmap", commit importMap.js and deploy again.', + title: 'Two-step verification may not be available', }, pl: { - body: 'Strona została wdrożona bez odświeżonej mapy importów panelu, więc ten ekran nie może się załadować i nikt nie może się zalogować. Programista musi uruchomić "pnpm payload generate:importmap", zapisać importMap.js w repozytorium i wdrożyć stronę ponownie.', - title: 'Weryfikacja dwuetapowa jest niedostępna', + body: 'Jeśli na tej stronie nie ma miejsca na wpisanie kodu, strona została wdrożona bez odświeżonej mapy importów panelu. Programista musi uruchomić "pnpm payload generate:importmap", zapisać importMap.js w repozytorium i wdrożyć stronę ponownie.', + title: 'Weryfikacja dwuetapowa może być niedostępna', }, } @@ -63,10 +65,13 @@ export function TotpRedirectProvider({ children, forceSetup = true, staleImportM if (staleImportMap && user && /\/(?:setup|verify)-totp\/?$/.test(pathname ?? '')) { const text = STALE_TEXT[i18n.language?.toLowerCase().startsWith('pl') ? 'pl' : 'en'] return ( -
-

{text.title}

-

{text.body}

-
+ <> +
+

{text.title}

+

{text.body}

+
+ {children} + ) } return children diff --git a/src/modules/security/totp/importMapCheck.ts b/src/modules/security/totp/importMapCheck.ts index 41237b0..fca8610 100644 --- a/src/modules/security/totp/importMapCheck.ts +++ b/src/modules/security/totp/importMapCheck.ts @@ -6,8 +6,9 @@ * back empty (HTTP 200, no code form), so nobody can sign in — after an upgrade where * `pnpm payload generate:importmap` was forgotten. In development Payload regenerates the file * by itself; a production build uses the committed one. This check makes that state loud: an - * error in the server log at start, and a message on the 2FA screens (TotpRedirectProvider). - * `twoFactor.importMapCheck: false` turns it off. + * error in the server log at start, and a notice on the 2FA screens (TotpRedirectProvider) — + * shown next to the screen, never instead of it, because the check can be wrong (see + * `missingImportMapEntries`). `twoFactor.importMapCheck: false` turns it off. */ type ConfigLike = { admin?: { importMap?: { baseDir?: string; importMapFile?: string } }; routes?: { admin?: string } } @@ -33,8 +34,14 @@ export async function findImportMapFile(config: ConfigLike, cwd = process.cwd()) } /** - * The entries of `needed` that the import map file lacks. An empty list also when the file is - * not found or cannot be read: an unknown state is never reported as a problem. + * The entries of `needed` that are not written in the import map file. An empty list when the + * file is not found or cannot be read. + * + * This is a text search of the file ON DISK, and a hint, not a fact: the map the running build + * uses is in the bundle. The two differ when the map is generated inside the build and the + * running image carries the repository's file (a Dockerfile runner stage with its own COPY), and + * the search misses a map that re-exports or builds its keys another way. So a caller may warn + * on the result, and must never block on it. */ export async function missingImportMapEntries(config: ConfigLike, needed: string[], cwd?: string): Promise<{ file: null | string; missing: string[] }> { const file = await findImportMapFile(config, cwd) diff --git a/src/modules/security/totp/safeBack.ts b/src/modules/security/totp/safeBack.ts index a6f0e36..8eb6ab9 100644 --- a/src/modules/security/totp/safeBack.ts +++ b/src/modules/security/totp/safeBack.ts @@ -129,6 +129,19 @@ export function wrapTotpViews( return { dependencies, views: out } } -/** Keys whose view object is not the one in `before` — what a plugin added or replaced. */ +/** + * Shallow copies of a config's views. Put these into the config BEFORE calling a 2FA factory and + * keep them as `before` for `changedViewKeys`: a view the factory registers is then never the + * same object as one that was there, also when the factory reuses its view objects between calls. + */ +export const copyViews = (views: Record | undefined): Record => + Object.fromEntries(Object.entries(views ?? {}).map(([key, view]) => [key, view && typeof view === 'object' ? { ...view } : view])) + +/** + * Keys whose view object is not the one in `before` — what a plugin added or replaced. + * `added` for `wrapTotpViews`: `const before = copyViews(views)` → run the factory on a config + * holding `before` → `const keys = changedViewKeys(before, viewsAfter)` → `(key) => keys.has(key)`. + * A key alone says nothing: the 2FA package replaces a view that already stands under its keys. + */ export const changedViewKeys = (before: Record, after: Record): Set => new Set(Object.keys(after).filter((key) => after[key] !== before[key])) diff --git a/src/plugin.ts b/src/plugin.ts index a371849..4554cf4 100644 --- a/src/plugin.ts +++ b/src/plugin.ts @@ -34,7 +34,7 @@ import { withFillLocales } from './modules/hooks/fillEmptyLocales.js' import { buildLocalizationConfig, validateI18nConfig } from './modules/i18n/index.js' import { buildSystemPagesFields } from './modules/pages/index.js' import { missingImportMapEntries } from './modules/security/totp/importMapCheck.js' -import { changedViewKeys, SAFE_TOTP_VIEW, wrapTotpViews } from './modules/security/totp/safeBack.js' +import { changedViewKeys, copyViews, SAFE_TOTP_VIEW, wrapTotpViews } from './modules/security/totp/safeBack.js' import { buildGuardStrategy, ensurePayloadGuarded, @@ -56,6 +56,8 @@ import { buildStatsCollection, buildStatsEndpoint } from './modules/stats/index. /** The admin provider @clocklimited/payload-2fa registers; ipal-kit swaps it (twoFactor.provider). */ const TOTP_PACKAGE_PROVIDER = '@clocklimited/payload-2fa/rsc#TOTPProvider' +/** ipal-kit's own redirect provider (twoFactor.provider default). */ +const TOTP_REDIRECT_PROVIDER = '@intecion/ipal-kit/admin#TotpRedirectProvider' /** * IPAL (Intecion Payload Advanced Library) plugin for Payload CMS 3. @@ -233,7 +235,12 @@ export const ipalKit = (options: IpalOptions): Plugin => { ) } const endpointsBefore = new Set(config.endpoints ?? []) - const viewsBefore: Record = { ...config.admin?.components?.views } + // Copies, so that a view the 2FA factory hands back is told apart from one it left alone + // even when the factory returns the very same objects on every call. + const viewsBefore = copyViews(config.admin?.components?.views) + if (config.admin?.components?.views) { + config.admin = { ...config.admin, components: { ...config.admin.components, views: viewsBefore as never } } + } const entityEndpointsBefore = new Map>( [...(config.collections ?? []), ...(config.globals ?? [])].map((e) => [e.slug, new Set(Array.isArray(e.endpoints) ? e.endpoints : [])]), ) @@ -325,7 +332,7 @@ export const ipalKit = (options: IpalOptions): Plugin => { if (tf.provider !== false) { const custom = tf.provider const ours = - typeof custom === 'object' ? custom : { path: custom ?? '@intecion/ipal-kit/admin#TotpRedirectProvider' } + typeof custom === 'object' ? custom : { path: custom ?? TOTP_REDIRECT_PROVIDER } const providers = config.admin?.components?.providers ?? [] config.admin = { ...config.admin, @@ -365,17 +372,19 @@ export const ipalKit = (options: IpalOptions): Plugin => { // A production build with the import map of the previous version shows an EMPTY 2FA // screen (Payload renders nothing for a path the map lacks): say so, in the log at // start and on the screen itself (importMapCheck.ts). Development regenerates the map. + // The check reads the file on disk, which need not be the map in the bundle — so it + // only ever ADDS a notice; the screen itself is rendered as usual. if (tf.importMapCheck !== false && process.env.NODE_ENV === 'production') { const stale = await missingImportMapEntries(config, [SAFE_TOTP_VIEW]) if (stale.missing.length) { - staleImportMap = `${stale.missing.join(', ')} is not in ${stale.file}` + staleImportMap = `${stale.missing.join(', ')} was not found in ${stale.file}` const providers = config.admin?.components?.providers ?? [] config.admin = { ...config.admin, components: { ...config.admin?.components, providers: providers.map((p) => - p && typeof p === 'object' && (p.clientProps as { forceSetup?: boolean } | undefined)?.forceSetup !== undefined + p && typeof p === 'object' && p.path === TOTP_REDIRECT_PROVIDER // ipal-kit's own provider only ? { ...p, clientProps: { ...p.clientProps, staleImportMap: true } } : p, ), @@ -752,14 +761,15 @@ export const ipalKit = (options: IpalOptions): Plugin => { adoptConfig(payload) // Payload's dev reload swaps `payload.config` and runs no onInit: adopt the new config at once. watchPayloadConfig(payload, adoptConfig) - // Staff whose collection is not the 2FA collection log in without a second factor: say so. if (staleImportMap) { payload.logger.error( - `[ipal] The admin import map is out of date: ${staleImportMap}. The 2FA setup and verify screens are EMPTY ` + - 'until it is regenerated, so nobody can sign in to the panel. Run `pnpm payload generate:importmap`, commit ' + - 'importMap.js, rebuild and redeploy (docs/security.md "The `back` link of the 2FA screens").', + `[ipal] The admin import map may be out of date: ${staleImportMap}. If the 2FA setup and verify screens are ` + + 'EMPTY (no code form), nobody can sign in to the panel: run `pnpm payload generate:importmap`, commit ' + + 'importMap.js, rebuild and redeploy. If the screens work, the file on disk is not the map the build used — ' + + 'set twoFactor.importMapCheck: false (docs/security.md "A stale import map").', ) } + // Staff whose collection is not the 2FA collection log in without a second factor: say so. if (twoFactorCollection) { const uncovered = staffCollectionSlugs(payload).filter((slug) => slug !== twoFactorCollection) if (uncovered.length) { diff --git a/test/doctor.test.ts b/test/doctor.test.ts index 37b7ba9..2b8eea2 100644 --- a/test/doctor.test.ts +++ b/test/doctor.test.ts @@ -51,6 +51,35 @@ afterEach(() => { vi.unstubAllEnvs() }) +describe('importmap rule and the 2FA back-link check', () => { + const MAP = 'src/app/(payload)/admin/importMap.js' + const entries = (...names: string[]) => `export const importMap = { ${names.map((n) => `"${n}": X`).join(', ')} }` + const withPlugin = (admin: string) => ({ ...base(), ...installed('@clocklimited/payload-2fa', '3.0.0'), 'node_modules/@intecion/ipal-kit/dist/exports/admin.js': admin }) + const messages = (report: DoctorReport) => report.findings.filter((f) => f.rule === 'importmap').map((f) => `${f.severity}: ${f.message}`) + + test('expects SafeTotpView when the installed plugin has it; not with safeBack: false; not for an older plugin', async () => { + const map = entries('@clocklimited/payload-2fa/rsc#TOTPSetup', '@intecion/ipal-kit/admin#TotpRedirectProvider') + const admin = 'export { SafeTotpView } from "./x.js"; export { TotpRedirectProvider } from "./y.js"' + const lacking = await doctor(project({ ...withPlugin(admin), [MAP]: map, 'src/payload.config.ts': 'twoFactor: { plugin: payloadTotp }' }), ['importmap']) + expect(messages(lacking).join()).toContain('import map lacks @intecion/ipal-kit/admin#SafeTotpView') + const off = await doctor(project({ ...withPlugin(admin), [MAP]: map, 'src/payload.config.ts': 'twoFactor: { plugin: payloadTotp, safeBack: false }' }), ['importmap']) + expect(messages(off).join()).not.toContain('SafeTotpView') + const older = await doctor(project({ ...withPlugin('export { TotpRedirectProvider } from "./y.js"'), [MAP]: map, 'src/payload.config.ts': 'twoFactor: { plugin: payloadTotp }' }), ['importmap']) + expect(messages(older).join()).not.toContain('SafeTotpView') + }) + + test("warns when the config registers the 2FA package's own view itself", async () => { + const map = entries('@clocklimited/payload-2fa/rsc#TOTPSetup', '@intecion/ipal-kit/admin#TotpRedirectProvider', '@intecion/ipal-kit/admin#SafeTotpView') + const admin = 'export { SafeTotpView } from "./x.js"; export { TotpRedirectProvider } from "./y.js"' + const own = "twoFactor: { plugin: payloadTotp }, admin: { components: { views: { Mine: { Component: '@clocklimited/payload-2fa/rsc#TOTPVerify', path: '/my-verify' } } } }" + const raw = await doctor(project({ ...withPlugin(admin), [MAP]: map, 'src/payload.config.ts': own }), ['importmap']) + const NOTE = /^warning: the config names the 2FA package's own setup \/ verify view/ + expect(messages(raw).filter((m) => NOTE.test(m))).toHaveLength(1) + const plain = await doctor(project({ ...withPlugin(admin), [MAP]: map, 'src/payload.config.ts': 'twoFactor: { plugin: payloadTotp }' }), ['importmap']) + expect(messages(plain).filter((m) => NOTE.test(m))).toEqual([]) + }) +}) + describe('helpers', () => { test('parseEnvFile reads KEY=value, strips quotes, skips comments', () => { expect(parseEnvFile('# c\nA=1\nexport B="two"\n C = \'3\'\nbad line')).toEqual({ A: '1', B: 'two', C: '3' }) diff --git a/test/safeBack.test.ts b/test/safeBack.test.ts index 82623de..5bee0e6 100644 --- a/test/safeBack.test.ts +++ b/test/safeBack.test.ts @@ -15,6 +15,7 @@ import { findImportMapFile, missingImportMapEntries } from '../src/modules/secur import { changedViewKeys, safeAdminBack, wrapTotpViews } from '../src/modules/security/totp/safeBack.js' import { SafeTotpView } from '../src/modules/security/totp/SafeTotpView.js' import { ipalKit } from '../src/plugin.js' +import { withTotpParts } from './helpers.js' const i18n: I18nConfig = { defaultLocale: 'en', locales: [{ code: 'en', label: 'English' }] } const admin = { adminRoute: '/admin' } @@ -305,6 +306,26 @@ describe('SafeTotpView', () => { }) }) +describe('a 2FA factory that hands back the same view objects on every call', () => { + const views = { + SetupTOTP: { Component: { path: 'pkg/rsc#TOTPSetup' }, path: 'setup-totp' }, + VerifyTOTP: { Component: { path: 'pkg/rsc#TOTPVerify' }, path: 'verify-totp' }, + } + const factory = (o: { collection: string }) => (c: Config) => + withTotpParts({ ...c, admin: { ...c.admin, components: { ...c.admin?.components, views: { ...c.admin?.components?.views, ...views } } } } as Config, o.collection) + const build = (incoming: Partial = {}) => + ipalKit({ access: { authCollection: 'users' }, i18n, twoFactor: { issuer: 'E', plugin: factory as never } })({ collections: [], secret: 'x', ...incoming } as unknown as Config) + const paths = (config: Config) => Object.values(config.admin?.components?.views ?? {}).map((v) => (v as { Component: { path: string } }).Component.path) + + test('is guarded when registered once, twice, and over a config that already holds those objects', async () => { + expect(paths(await build())).toEqual(Array(2).fill('@intecion/ipal-kit/admin#SafeTotpView')) + const already = factory({ collection: 'users' })({ collections: [{ slug: 'users', auth: true, fields: [] }], secret: 'x' } as unknown as Config) + expect(paths(already)).toEqual(['pkg/rsc#TOTPSetup', 'pkg/rsc#TOTPVerify']) // raw, the very objects the factory returns again + expect(paths(await build(already))).toEqual(Array(2).fill('@intecion/ipal-kit/admin#SafeTotpView')) + expect(views.VerifyTOTP.Component.path).toBe('pkg/rsc#TOTPVerify') // the factory's own objects are not changed + }) +}) + describe('safeAdminBack with values that are not a string', () => { test.each([[['/admin', 'javascript:1']], [{}], [null], [1], [{ toString: () => 'javascript:1' }]])('%s', (value) => { expect(safeAdminBack(value as never, { adminRoute: '/admin' })).toBe('/admin') @@ -419,6 +440,46 @@ describe('the stale import-map check', () => { } }) + // The search reads text on disk: these maps work in the build and are still reported. That is why the result + // only ever adds a notice (test/totpRedirectProvider.test.ts) and the log line says "may be". + test('a map that re-exports, spreads or computes its keys is reported although it may be fine', async () => { + const maps = [ + "export { importMap } from './generatedMap.js'", + "import { generated } from './generatedMap.js'\nexport const importMap = { ...generated }", + 'export const importMap = { [`@intecion/ipal-kit/admin#${name}`]: X }', + '', + ] + for (const content of maps) { + const root = await project('src/app/(payload)/admin', content) + try { + expect([content, (await missingImportMapEntries({}, [ENTRY], root)).missing]).toEqual([content, [ENTRY]]) + } finally { + await rm(root, { force: true, recursive: true }) + } + } + }) + + test('only ipal-kit\'s own redirect provider gets the flag, not a project\'s provider', async () => { + const stale = await project('src/app/(payload)/admin', 'export const importMap = {}') + const providers = async (provider?: unknown) => { + const config = await ipalKit({ access: { authCollection: 'users' }, i18n, twoFactor: { issuer: 'E', plugin: payloadTotpBeta7, provider } as never })({ + admin: { importMap: { baseDir: stale } }, + collections: [], + secret: 'x', + } as unknown as Config) + return JSON.stringify(config.admin?.components?.providers ?? []) + } + try { + vi.stubEnv('NODE_ENV', 'production') + expect(await providers()).toContain('"staleImportMap":true') + expect(await providers({ clientProps: { forceSetup: true }, path: '@/components/MyTotp#MyTotp' })).not.toContain('staleImportMap') + expect(await providers('@/components/MyTotp#MyTotp')).not.toContain('staleImportMap') + } finally { + vi.unstubAllEnvs() + await rm(stale, { force: true, recursive: true }) + } + }) + test('reports a missing entry, never an unknown state', async () => { const stale = await project('src/app/(payload)/admin', 'export const importMap = { "@intecion/ipal-kit/admin#TotpRedirectProvider": X }') const current = await project('src/app/(payload)/admin', `export const importMap = { "${ENTRY}": Y }`) diff --git a/test/totpRedirectProvider.test.ts b/test/totpRedirectProvider.test.ts new file mode 100644 index 0000000..059c000 --- /dev/null +++ b/test/totpRedirectProvider.test.ts @@ -0,0 +1,67 @@ +import React from 'react' +import { renderToStaticMarkup } from 'react-dom/server' +import { beforeEach, describe, expect, test, vi } from 'vitest' + +/** + * The stale-import-map notice of TotpRedirectProvider. The flag behind it is a guess (a text search of the + * importMap.js on disk, not the map in the bundle), so the notice is shown NEXT TO the screen: a wrong guess + * must never take the code form away. + */ +const state = { language: 'en', pathname: '/admin/verify-totp', user: { _strategy: 'local-jwt', hasTotp: true } as null | Record } + +vi.mock('@payloadcms/ui', () => ({ + useAuth: () => ({ user: state.user }), + useConfig: () => ({ config: { admin: { routes: {} }, routes: { admin: '/admin' } } }), + useTranslation: () => ({ i18n: { language: state.language } }), +})) +vi.mock('next/navigation.js', () => ({ usePathname: () => state.pathname, useRouter: () => ({ replace: () => undefined }) })) + +const { TotpRedirectProvider } = await import('../src/modules/security/totp/TotpRedirectProvider.js') + +const FORM = '
' +const form = () => React.createElement('form', { id: 'code-form' }, React.createElement('input')) +const render = (props: Record = {}, children: React.ReactNode = form()) => + renderToStaticMarkup(React.createElement(TotpRedirectProvider, props, children)) + +beforeEach(() => { + Object.assign(state, { language: 'en', pathname: '/admin/verify-totp', user: { _strategy: 'local-jwt', hasTotp: true } }) +}) + +describe('TotpRedirectProvider with staleImportMap', () => { + // Reviewer repro 1: the build is current, but the importMap.js on disk is an older one → the flag is wrong. + // Reviewer repro 2: the map file re-exports the generated map → the text search finds nothing → the flag is wrong. + // In both the screen works, and must stay on the page. + test('a false alarm: the working code form is still rendered, with the notice above it', () => { + const html = render({ staleImportMap: true }) + expect(html).toContain(FORM) + expect(html).toContain('role="alert"') + expect(html).toContain('may not be available') + expect(html.indexOf('role="alert"')).toBeLessThan(html.indexOf('code-form')) + }) + + test('a really stale map: Payload renders nothing for the screen, the notice is what the user sees', () => { + const html = render({ staleImportMap: true }, null) + expect(html).toContain('role="alert"') + expect(html).toContain('pnpm payload generate:importmap') + }) + + test('the setup screen too; Polish for a Polish panel', () => { + Object.assign(state, { language: 'pl', pathname: '/admin/setup-totp', user: { _strategy: 'local-jwt', hasTotp: false } }) + const html = render({ staleImportMap: true }) + expect(html).toContain('Weryfikacja dwuetapowa może być niedostępna') + expect(html).toContain(FORM) + }) + + test('no notice without the flag, on other pages, or for a visitor', () => { + expect(render({})).toBe(FORM) + Object.assign(state, { pathname: '/admin/collections/pages', user: { _strategy: 'totp', hasTotp: true } }) + expect(render({ staleImportMap: true })).toBe(FORM) + Object.assign(state, { pathname: '/admin/verify-totp', user: null }) + expect(render({ staleImportMap: true })).toBe(FORM) + }) + + test('a pending redirect still renders nothing', () => { + Object.assign(state, { pathname: '/admin/collections/pages', user: { _strategy: 'local-jwt', hasTotp: true } }) + expect(render({ staleImportMap: true })).toBe('') + }) +}) From 3eee841dd0b0127f1ab3500b17e512c8bd434db6 Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?Rados=C5=82aw=20Smoli=C5=84ski?= Date: Tue, 24 Nov 2026 17:49:06 +0100 Subject: [PATCH 4/4] ipal-doctor: the raw 2FA view warning only for a view component R3-1: the warning fired on any mention of the 2FA package's setup / verify view in the config, so it stayed after the fix its own text suggests (SafeTotpView with the path as ipalTotpView, plus the path in admin.dependencies). It now warns only when the path is a view's Component. Co-Authored-By: Claude Fable 5.2 --- docs/doctor.md | 2 +- docs/security.md | 5 +++-- src/modules/doctor/rules/layout.ts | 6 ++++-- test/doctor.test.ts | 33 +++++++++++++++++++++++------- 4 files changed, 34 insertions(+), 12 deletions(-) diff --git a/docs/doctor.md b/docs/doctor.md index f7b14ee..b9d1f85 100644 --- a/docs/doctor.md +++ b/docs/doctor.md @@ -89,7 +89,7 @@ Turn off: `ipalKit({ doctor: false })`. Adapt: `ipalKit({ doctor: { tokenVar: 'M | | `layout-forbidden` | error | no `middleware.ts`, no `lib/{pages,locales,navigation}.ts`, `fields/{link,sectionHeader,sectionSettings}.ts` | | | `layout-extra` | info | `src/` entries outside the allow list (AGENT.md §3 + `seed/`, `design/`, `db.ts`, `env.rules.ts`, `content.config.ts`; extend with `layout.allow`) | | | `naming` | warning | block folders, collection and global files PascalCase, `scripts/*` kebab-case, no `index.ts` barrels | -| | `importmap` | error | the import map exists, holds the entries for what the config turns on (2FA, R2, cookie scanner, `adminMeta`), names no export the plugin no longer has; with `--deep`, equals a fresh one. Warning: the config registers the 2FA package's own setup / verify view directly (outside the `back` link check — security.md) | +| | `importmap` | error | the import map exists, holds the entries for what the config turns on (2FA, R2, cookie scanner, `adminMeta`), names no export the plugin no longer has; with `--deep`, equals a fresh one. Warning: the config uses the 2FA package's own setup / verify view as a view's `Component` (outside the `back` link check — security.md); not for that path as `ipalTotpView` of `SafeTotpView` or in `admin.dependencies` | | | `tsconfig-skills` | error | `tsconfig.json` excludes the skills folder | | env | `db-name` | error | `DATABASE_URI` in `.env` and `.env.example` names `_dev`; a local `.env` on `_prod` is an error; `--env-file` checks `_prod` (`databaseNamesFor`) | | | `env-rules` | error / warning | `instrumentation.ts` calls `assertEnv(ipalEnvRules(…))` from `/env`, with `storage` (R2), `cookieCrawl` (crawl), `ipHeader`; `databaseName` suggested (info) | diff --git a/docs/security.md b/docs/security.md index abca596..f1fee7d 100644 --- a/docs/security.md +++ b/docs/security.md @@ -610,8 +610,9 @@ guarded. The same holds when the project also lists `payloadTotp(...)` in `plugi your `clientProps`, and `back` plus `searchParams` — both checked; read `back` from the props, not from `useSearchParams()`, which still holds the raw query value. - From a plugin listed after `ipalKit`, or under another key or route: that view is yours and is not wrapped. Use - `wrapTotpViews` or `safeAdminBack` in it. `ipal-doctor` warns when the config names the package's own view - (`@clocklimited/payload-2fa/rsc#TOTPVerify` / `#TOTPSetup`) directly. + `wrapTotpViews` or `safeAdminBack` in it. `ipal-doctor` warns when the config uses the package's own view + (`@clocklimited/payload-2fa/rsc#TOTPVerify` / `#TOTPSetup`) as a view's `Component`; the same path as the + `ipalTotpView` of `SafeTotpView`, or in `admin.dependencies`, is fine. Wrapping views yourself, for a project that runs the 2FA package without `ipalKit`'s `twoFactor` (all from `@intecion/ipal-kit`): diff --git a/src/modules/doctor/rules/layout.ts b/src/modules/doctor/rules/layout.ts index 65f71a8..981f565 100644 --- a/src/modules/doctor/rules/layout.ts +++ b/src/modules/doctor/rules/layout.ts @@ -204,11 +204,13 @@ export const layoutRules: DoctorRule[] = [ } } // A view the project registers itself with the 2FA package's own component is not behind the back-link check. - if (/@clocklimited\/payload-2fa\/rsc#TOTP(?:Setup|Verify)/.test(cfg)) { + // Only as a view's component (`Component: ''` or `Component: { path: '' }`): the same path as the + // value of `ipalTotpView` or of an `admin.dependencies` entry is the fix, not the problem. + if (/\bComponent\s*:\s*(?:\{[^{}]*?\bpath\s*:\s*)?['"`]@clocklimited\/payload-2fa\/rsc#TOTP(?:Setup|Verify)\b/.test(cfg)) { out.push({ file: configFile(ctx) ?? undefined, fix: "register it through wrapTotpViews (or Component: { path: '@intecion/ipal-kit/admin#SafeTotpView', serverProps: { ipalTotpView: '' } } plus the path in admin.dependencies) — security.md \"Your own 2FA screen\"", - message: "the config names the 2FA package's own setup / verify view: a view registered that way sends the browser to an unchecked `back` link after the code", + message: "the config registers the 2FA package's own setup / verify view as a view component: it sends the browser to an unchecked `back` link after the code", severity: 'warning', }) } diff --git a/test/doctor.test.ts b/test/doctor.test.ts index 2b8eea2..b6bafc0 100644 --- a/test/doctor.test.ts +++ b/test/doctor.test.ts @@ -68,15 +68,34 @@ describe('importmap rule and the 2FA back-link check', () => { expect(messages(older).join()).not.toContain('SafeTotpView') }) - test("warns when the config registers the 2FA package's own view itself", async () => { + describe("the 2FA package's own view in the config", () => { const map = entries('@clocklimited/payload-2fa/rsc#TOTPSetup', '@intecion/ipal-kit/admin#TotpRedirectProvider', '@intecion/ipal-kit/admin#SafeTotpView') const admin = 'export { SafeTotpView } from "./x.js"; export { TotpRedirectProvider } from "./y.js"' - const own = "twoFactor: { plugin: payloadTotp }, admin: { components: { views: { Mine: { Component: '@clocklimited/payload-2fa/rsc#TOTPVerify', path: '/my-verify' } } } }" - const raw = await doctor(project({ ...withPlugin(admin), [MAP]: map, 'src/payload.config.ts': own }), ['importmap']) - const NOTE = /^warning: the config names the 2FA package's own setup \/ verify view/ - expect(messages(raw).filter((m) => NOTE.test(m))).toHaveLength(1) - const plain = await doctor(project({ ...withPlugin(admin), [MAP]: map, 'src/payload.config.ts': 'twoFactor: { plugin: payloadTotp }' }), ['importmap']) - expect(messages(plain).filter((m) => NOTE.test(m))).toEqual([]) + const NOTE = /^warning: the config registers the 2FA package's own setup \/ verify view/ + const notes = async (config: string) => + messages(await doctor(project({ ...withPlugin(admin), [MAP]: map, 'src/payload.config.ts': `twoFactor: { plugin: payloadTotp }, ${config}` }), ['importmap'])).filter((m) => NOTE.test(m)) + const RAW = '@clocklimited/payload-2fa/rsc#TOTPVerify' + + test.each([ + ['a string component', `admin: { components: { views: { Mine: { Component: '${RAW}', path: '/my-verify' } } } }`], + ['an object component', `admin: { components: { views: { Mine: { Component: { path: "${RAW}", serverProps: { a: 1 } }, path: '/my-verify' } } } }`], + ['an object component over several lines', `views: { Mine: { Component: {\n clientProps,\n path: \`${RAW}\`,\n}, path: '/my-verify' } }`], + ['the setup view', "views: { Mine: { Component: '@clocklimited/payload-2fa/rsc#TOTPSetup', path: '/my-setup' } }"], + ])('warns for %s', async (_name, config) => { + expect(await notes(config)).toHaveLength(1) + }) + + test.each([ + ['no such view', ''], + // the fix the warning itself suggests + ['the wrapper with the raw path as ipalTotpView, and the path in admin.dependencies', + `admin: { components: { views: { Mine: { Component: { path: '@intecion/ipal-kit/admin#SafeTotpView', serverProps: { ipalTotpView: '${RAW}' } }, path: '/my-verify' } } }, dependencies: { 'my-verify': { path: '${RAW}', type: 'component' } } }`], + ['the wrapper with serverProps written first', `views: { Mine: { Component: { serverProps: { ipalTotpView: '${RAW}' }, path: '@intecion/ipal-kit/admin#SafeTotpView' }, path: '/my-verify' } }`], + ['a dependencies entry alone', `admin: { dependencies: { keep: { type: 'component', path: '${RAW}' } } }`], + ['a comment', `// Component: '${RAW}'`], + ])('does not warn for %s', async (_name, config) => { + expect(await notes(config)).toEqual([]) + }) }) })