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/) + }) +})