Compare commits
| Author | SHA1 | Date | |
|---|---|---|---|
|
|
45d52c4690 | ||
|
|
bef3a682b8 | ||
|
|
f96b5c15d0 | ||
|
|
3eee841dd0 | ||
|
|
b2c1dca5da | ||
|
|
ad51456eaa | ||
|
|
93e75426ab |
@@ -8,6 +8,70 @@ 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.
|
||||
|
||||
## 1.16.5
|
||||
|
||||
### 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`.
|
||||
- **A stale import map is reported** (`twoFactor.importMapCheck`, on by default, `false` turns it off): in
|
||||
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 uses the 2FA package's own setup / verify view as a view's `Component`
|
||||
(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`.
|
||||
|
||||
### Requires project changes
|
||||
- **Every site with 2FA: upgrade, `pnpm payload generate:importmap`, commit `importMap.js`, `rm -rf .next`,
|
||||
redeploy — all in ONE deploy. Run `pnpm exec ipal-doctor` before deploying.** 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 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. `pnpm ipal:skills` afterwards.
|
||||
- **A project with its own 2FA screens or view registrations:** security.md "Your own 2FA screen".
|
||||
- **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.
|
||||
- `back=/admin/logout` is inside the panel and is followed: the user is logged out after the code.
|
||||
- A client-side 2FA screen of your own that reads `useSearchParams()` gets the raw value; use the `back` prop.
|
||||
- The stale import map check is a text search of the file on disk: it can warn although everything works, and
|
||||
its notice text changes only with an own `twoFactor.provider`. The `ipal-doctor` warning about a raw view is a
|
||||
text search too and misses unusual spellings.
|
||||
- **Not run for this release:** the browser checks on Postgres, in Firefox or WebKit, with a Next `basePath` or in a
|
||||
real Docker image with a runner stage; payload-2fa beta.2 to beta.6; Payload 3.90 to 3.93. They ran in Chromium on
|
||||
MongoDB with beta.7 (production build) and, on an earlier commit of the same change, beta.1 (`next dev`).
|
||||
|
||||
## 1.16.4
|
||||
|
||||
### Security
|
||||
|
||||
+2
-1
@@ -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 `<RenderForm>` + `formClasses.ts` (look, once); `actions.ts` = `createSubmitAction({ getCachedPayload, headers })`; `forms: {…}` in `ipalKit`; `email: mailAdapter()` | `RenderForm` (`/rsc`), `createSubmitAction`, `mailAdapter` | A, P |
|
||||
| 11 | **Turnstile** | `<SiteProviders>` 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'` (`<SiteProviders analytics={{ consentMode: '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) + `<SiteProviders logEndpoint="/api/ipal/consent" banner={<CookieBanner equalChoice settings="detailed" />}>` (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 `<CookieTable>` 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` in the same deploy — with a stale map the 2FA screens have no code form and nobody can sign in (`ipal-doctor`, the start log and a notice above the screen report it; the notice is a hint from the file on disk and never replaces the screen; `twoFactor.importMapCheck: false` turns it off); check: password only → `/admin/verify-totp?back=https%3A%2F%2Fexample.com%2F` → code → lands on `/admin` | `twoFactor.safeBack: false` | `safeBack: (back, { adminRoute, origin }) => string`; `safeAdminBack`, `wrapTotpViews` (`@intecion/ipal-kit`), `SafeTotpView` (`@intecion/ipal-kit/admin`) for own views |
|
||||
| The 2FA package's endpoints (`/api/setup-totp`, `verify-totp`, `remove-totp`, `admin/*`) answer accounts of the 2FA collection only; reset and remove need the second factor | — (always on with 2FA) | `adminManageAccess` through the wrapped factory (security.md "Resetting 2FA") |
|
||||
| Roles count only for accounts of a staff collection, in every predicate and access function | — | `access.staffCollections` |
|
||||
| `enabled: false` keeps the schema | — | — (no endpoints, `onInit` or admin components; no DROP TABLE in `migrate:create`) |
|
||||
|
||||
@@ -2,7 +2,7 @@
|
||||
|
||||
<!-- Generated by scripts/reference-index.mjs from reference/ — do not edit by hand (pnpm reference:index). -->
|
||||
|
||||
The reference site is one complete client site on ipal-kit 1.16.4 ("Example Studio", made up) that uses
|
||||
The reference site is one complete client site on ipal-kit 1.16.5 ("Example Studio", made up) that uses
|
||||
every convention in AGENT.md. It lives in the plugin repo (`reference/`, not in the npm package). Copy the
|
||||
PATTERN of the file you need; change only the project's content. Files up to
|
||||
40 lines are below in full; open the rest in the repo at the tag of your plugin version:
|
||||
@@ -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`
|
||||
|
||||
|
||||
@@ -58,6 +58,10 @@ 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 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) |
|
||||
| `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 |
|
||||
|
||||
@@ -37,6 +37,8 @@ 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.importMapCheck` | on | production only: at start searches the `importMap.js` on disk (where Payload looks for it) for `@intecion/ipal-kit/admin#SafeTotpView`; when not found, logs `[ipal] The admin import map may be out of date …` and ipal-kit's `TotpRedirectProvider` puts the notice "Two-step verification may not be available" above the 2FA screens (never instead of them). A hint only — the map in the build can differ from the file on disk (Dockerfile runner stage, re-exporting map); a file that is not found is not reported | `false` = no file read, log line or notice |
|
||||
| `twoFactor.texts` | ipal-kit's en/pl texts (`TOTP_TEXTS`) over the package's; 2FA screens titled "Two-step verification" / "Weryfikacja dwuetapowa" (site's language) | `false` = the package's texts; one text: `i18n.translations.<lang>.totpPlugin.<key>` (security.md) |
|
||||
| `twoFactor.guard` | on | ipal-kit's own second-factor check on every collection and global (also the plugin's own and those of plugins listed after ipalKit) and in `userMeetsRole`; startup fails with `[ipal] twoFactor: the injected 2FA plugin did not add …` when the 2FA package lacks the `totp` strategy / `hasTotp` / `totpSecret` | per entity: `custom.ipal.secondFactor: false` / `{ read: false }` or the package's `custom.totp.disableAccessWrapper.<op>`; `false` = the package's wrapper only (the plugin's own data then opens to a password without the code; not recommended). The package's endpoints stay limited to accounts of the 2FA collection either way |
|
||||
| `twoFactor.verifyLimit` | `{ max: 5, windowMinutes: 10 }` | attempts per account on `POST /api/verify-totp` (the 2FA package counts none): the sixth in the window, right or wrong, gets `429` + `Retry-After`; in memory per instance | `{ max, windowMinutes }`; `false` = no limit |
|
||||
|
||||
@@ -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 view named by the serverProp `ipalTotpView` (a path or `{ path, exportName }`, found in the import map) the way Payload renders a view: a server component gets all server props, a client component only Payload's client props, `ipalTotpClientProps`, `back` and `searchParams` (both checked). `ipalSafeBack` = own rule. Registered by the plugin with `twoFactor` (`twoFactor.safeBack`, on by default). After upgrading, `pnpm generate:importmap`. Check: password only → `/admin/verify-totp?back=https%3A%2F%2Fexample.com%2F` → code → `/admin`. Own registration: `Component: { path: '@intecion/ipal-kit/admin#SafeTotpView', serverProps: { ipalTotpView: '<path>' } }` + that path in `admin.dependencies`. |
|
||||
| `TotpRedirectProvider` | `@intecion/ipal-kit/admin` | Client admin provider: sends a user without TOTP to `/admin/setup-totp?back=…` and a user whose session has not passed TOTP to `/admin/verify-totp?back=…` (path read in the browser; never redirects away from those screens or logout; renders nothing while redirecting). Injected by the plugin with `twoFactor` in place of the package's header-based provider; swap with `twoFactor.provider`. After upgrading, `pnpm generate:importmap`. Check: a new admin lands on `setup-totp?back=%2Fadmin` with the QR code. Props type `TotpRedirectProviderProps` (`forceSetup`) |
|
||||
| `IntecionCredit` | `@intecion/ipal-kit/admin` | The line "Technology support: Intecion.com" (admin language; `agency` prop = the name) below the nav and below the login form (`variant: 'nav' \| 'login'`). Injected by the plugin with `whiteLabel`; turn off: `whiteLabel: { credit: false }` or `agency: false`. |
|
||||
| `buildAdminMeta({ agency, apiRoute?, defaultLocale?, meta?, options? })` | `@intecion/ipal-kit` | The `adminMeta` step: static panel meta (robots, preview image, icon) without overwriting keys in `meta`; returns `{ meta, resolved }` |
|
||||
@@ -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`), `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`
|
||||
|
||||
@@ -586,6 +587,11 @@ 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 (keeps `exportName`, `serverProps`; `clientProps` travel as `ipalTotpClientProps`); returns `{ views, dependencies }` (`dependencies` → `admin.dependencies`, so the wrapped views stay in the import map). What `ipalKit` runs after the 2FA factory; for a project that registers the 2FA package itself. |
|
||||
| `copyViews(views)` / `changedViewKeys(before, after)` | `@intecion/ipal-kit` | The comparison `ipalKit` uses to tell which views a 2FA factory registered: put `copyViews(views)` into the config before calling the factory, then `changedViewKeys(before, viewsAfter)` gives the keys whose view object changed — the `added` argument of `wrapTotpViews` (`(key) => keys.has(key)`). By object, not by key: the 2FA package replaces a view that already stands under its keys. Example: security.md "Your own 2FA screen". |
|
||||
| `SAFE_TOTP_VIEW` / `totpViewImportKey(component)` | `@intecion/ipal-kit` | `'@intecion/ipal-kit/admin#SafeTotpView'`, the wrapper's import-map path (the default `wrapper` of `wrapTotpViews`); and the import-map key (`path#export`) of a component given as a string or `{ path, exportName }`. |
|
||||
| `findImportMapFile(config, cwd?)` / `missingImportMapEntries(config, entries, cwd?)` | `@intecion/ipal-kit` | Where the project's `importMap.js` is on disk (`admin.importMap.importMapFile`, else `app/(payload)<admin route>/` or `src/app/…` under `admin.importMap.baseDir` / the working directory; `null` when not found), and which of `entries` its text does not contain (`{ file, missing }`). A hint from the file on disk, not the map in the build: warn on it, never block on it. Behind `twoFactor.importMapCheck`. |
|
||||
| `requireSecondFactor(access?)` | `@intecion/ipal-kit` | Wraps an `Access` function: refused while the second factor is owed, otherwise the function itself (Payload's default "logged in" when none). ipalKit applies it to every collection and global in the config, and to those added by plugins listed after it (in `onInit` and at the start of the first request, so also after a dev hot reload); use it for access functions that are not part of the config. Per-entity opt-out: `custom.ipal.secondFactor: false \| { read: false }` or the package's `custom.totp.disableAccessWrapper`. Wrapping twice is harmless. |
|
||||
| `totpRedirectTarget({ adminRoute, forceSetup?, pathname, user, excludePaths? })`, `totpAdminPath(adminRoute, path)` | `@intecion/ipal-kit` | The 2FA redirect rules as pure functions: the setup / verify URL (with `back`) to send this user to, or `null` (no path, api key, already on a TOTP screen or logout). For an own `twoFactor.provider`. Types `TotpRedirectArgs`, `TotpUser` |
|
||||
| `buildCsp({ mode?, reportUri?, reportGroup?, r2Url?, analytics?, metaPixel?, linkedIn?, tiktok?, clarity?, turnstile?, youtube?, googleMaps?, nonce?, strictDynamic?, dev?, extra?, override? })` | `@intecion/ipal-kit` | Returns `{ key, value }` with a hardened CSP (`base-uri`, `object-src`, `frame-ancestors`, `form-action`) + sources for the enabled integrations. `mode: 'report-only'` → `…-Report-Only` (start here), `'enforce'` later. `extra` adds to any directive, `override` replaces / drops one (`null`). `dev` (default `NODE_ENV === 'development'`) adds `'unsafe-eval'`. `nonce` → `'nonce-…' 'strict-dynamic'`. |
|
||||
|
||||
@@ -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,13 @@ 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
|
||||
(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`.
|
||||
- A second auth collection (`customers`, a client zone): set `admin: { user: 'users' }` in `buildConfig`; its
|
||||
|
||||
@@ -362,6 +362,24 @@ panel → Site integrations and a form submission open, a setting saves. With a
|
||||
gets `403` from the same addresses and from `POST /api/setup-totp`. The Coolify log has no
|
||||
`PAYLOAD_SECRET must be at least`; `pnpm exec ipal-doctor` has no `env` finding.
|
||||
|
||||
**→ 1.16.5 (PROGRAMISTA §6, item 67; CHANGELOG 1.16.5; security.md "The `back` link of the 2FA screens") — required with 2FA on:**
|
||||
1. **Do this in ONE deploy with the upgrade, or the panel is locked for everyone.** Run `pnpm exec ipal-doctor`
|
||||
before deploying.
|
||||
`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 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
|
||||
strips `back`, can keep them (`twoFactor.safeBack: false` turns the plugin's check off).
|
||||
2. `pnpm ipal:skills`.
|
||||
|
||||
## 2. Inventory (no code changes)
|
||||
**What changed for projects** between your old and new plugin version is exactly the reference site's diff —
|
||||
`git diff v<old> v<new> -- reference/` in the ipal-kit repo (or the two `docs/agent/reference-site/INDEX.md` files):
|
||||
|
||||
@@ -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('<slug>')`, `access.staffCollections` only for a second STAFF collection. Every account must have 2FA set up (`ipal-doctor --url` → 0 without). Own endpoints: `secondFactorPassed(req)`; own `overrideAccess: false` calls: `user` from `payload.auth()`. `pnpm ipal:skills`; no migration | CHANGELOG 1.16.4, security.md "What the second factor covers", access.md "Who is staff" |
|
||||
| 66 | **1.16.4** — production `PAYLOAD_SECRET` shorter than 32 characters (the site would stop at `assertEnv`) | Before deploying 1.16.4, check the length in Coolify (`node -e 'console.log(process.env.PAYLOAD_SECRET.length)'`). Shorter: a random 32+ character secret (logs everyone out, asks for 2FA again, breaks stored API keys), or `ipalEnvRules({ secretMinLength: 0 })` for now | CHANGELOG 1.16.4, deployment.md "PAYLOAD_SECRET — length and changing it" |
|
||||
| 67 | **1.16.5 — 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 ONE 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 have no code form and nobody can sign in (run `pnpm exec ipal-doctor` before deploying; the start log says so too); check: the link above ends on `/admin`. `pnpm ipal:skills`. No option, env or migration; off / own rule: `twoFactor.safeBack` | CHANGELOG 1.16.5, 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`.
|
||||
|
||||
+1
-1
@@ -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 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 `<domain without dots>_dev`; a local `.env` on `_prod` is an error; `--env-file` checks `_prod` (`databaseNamesFor`) |
|
||||
| | `env-rules` | error / warning | `instrumentation.ts` calls `assertEnv(ipalEnvRules(…))` from `/env`, with `storage` (R2), `cookieCrawl` (crawl), `ipHeader`; `databaseName` suggested (info) |
|
||||
|
||||
+100
-2
@@ -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,99 @@ 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`** — 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
|
||||
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: '<import-map path of the view to render>'` and list that path in
|
||||
`admin.dependencies`).
|
||||
|
||||
**Which views are guarded.** Every view the injected 2FA factory registers on the routes `setup-totp` and
|
||||
`verify-totp`, whatever stood under its keys before. The package replaces a view the project has under the keys
|
||||
`SetupTOTP`, `SetupTOTPBackslash`, `VerifyTOTP` or `VerifyTOTPBackslash`, so such a view is the package's, and
|
||||
guarded. The same holds when the project also lists `payloadTotp(...)` in `plugins` itself.
|
||||
|
||||
**Your own 2FA screen.** Two ways, both keep the check:
|
||||
- Through the wrapped factory (the pattern from "Resetting 2FA"): set `views.VerifyTOTP.Component` (or `SetupTOTP`)
|
||||
on the config the factory returns. ipal-kit puts `SafeTotpView` in front of it. A server component gets every
|
||||
server prop with `searchParams.back` checked. A client component (`'use client'`) gets Payload's client props,
|
||||
your `clientProps`, and `back` plus `searchParams` — both checked; read `back` from the props, not from
|
||||
`useSearchParams()`, which still holds the raw query value.
|
||||
- From a plugin listed after `ipalKit`, or under another key or route: that view is yours and is not wrapped. Use
|
||||
`wrapTotpViews` or `safeAdminBack` in it. `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`):
|
||||
```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 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 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 may be out of date: … was not found
|
||||
in <file> …`.
|
||||
- **On the screen:** a notice above the 2FA screen, "Two-step verification may not be available", with what a
|
||||
developer has to run. With a really stale map the notice is all the user sees (the form is missing); it is
|
||||
shown by ipal-kit's `TotpRedirectProvider` only — with your own `twoFactor.provider`, or `provider: false`,
|
||||
there is the log line alone.
|
||||
|
||||
The start-up check is a guess, and is built so that a wrong guess costs a wrong notice and nothing else: it
|
||||
searches the text of the `importMap.js` **on disk** where Payload looks for it (`admin.importMap.importMapFile`,
|
||||
else `app/(payload)<admin route>/` or `src/app/(payload)<admin route>/` under `admin.importMap.baseDir` or the
|
||||
working directory), while the map the site really uses is inside the build. The two differ when the map is
|
||||
generated during the build and the running image carries the repository's file (a Dockerfile with a separate
|
||||
runner stage), or when the map file re-exports or computes its entries. Then the log line and the notice appear
|
||||
although the screen works — the code form stays on the page and sign-in is not affected. Turn the check off for
|
||||
such a project: `twoFactor: { …, importMapCheck: false }` (no file read, no log line, no notice). A file that is
|
||||
not found is not reported. Building in place (Coolify's Nixpacks) reads the same file the build used.
|
||||
|
||||
**Fix for a really stale map:** `pnpm payload generate:importmap`, commit `importMap.js`, rebuild, redeploy.
|
||||
A second error exists for the opposite case — the wrapper is in the map but the package's view is not:
|
||||
`[ipal] The admin import map has no "@clocklimited/payload-2fa/rsc#TOTPVerify"` (same fix).
|
||||
|
||||
**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 +755,10 @@ 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`, `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.
|
||||
|
||||
+1
-1
@@ -1,6 +1,6 @@
|
||||
{
|
||||
"name": "@intecion/ipal-kit",
|
||||
"version": "1.16.4",
|
||||
"version": "1.16.5",
|
||||
"description": "Intecion Payload Advanced Library — a Payload CMS 3 plugin: i18n, SEO, forms, consent, analytics, blog/archives.",
|
||||
"license": "MIT",
|
||||
"repository": {
|
||||
|
||||
@@ -58,6 +58,10 @@ 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 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) |
|
||||
| `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 |
|
||||
|
||||
@@ -37,6 +37,8 @@ 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.importMapCheck` | on | production only: at start searches the `importMap.js` on disk (where Payload looks for it) for `@intecion/ipal-kit/admin#SafeTotpView`; when not found, logs `[ipal] The admin import map may be out of date …` and ipal-kit's `TotpRedirectProvider` puts the notice "Two-step verification may not be available" above the 2FA screens (never instead of them). A hint only — the map in the build can differ from the file on disk (Dockerfile runner stage, re-exporting map); a file that is not found is not reported | `false` = no file read, log line or notice |
|
||||
| `twoFactor.texts` | ipal-kit's en/pl texts (`TOTP_TEXTS`) over the package's; 2FA screens titled "Two-step verification" / "Weryfikacja dwuetapowa" (site's language) | `false` = the package's texts; one text: `i18n.translations.<lang>.totpPlugin.<key>` (security.md) |
|
||||
| `twoFactor.guard` | on | ipal-kit's own second-factor check on every collection and global (also the plugin's own and those of plugins listed after ipalKit) and in `userMeetsRole`; startup fails with `[ipal] twoFactor: the injected 2FA plugin did not add …` when the 2FA package lacks the `totp` strategy / `hasTotp` / `totpSecret` | per entity: `custom.ipal.secondFactor: false` / `{ read: false }` or the package's `custom.totp.disableAccessWrapper.<op>`; `false` = the package's wrapper only (the plugin's own data then opens to a password without the code; not recommended). The package's endpoints stay limited to accounts of the 2FA collection either way |
|
||||
| `twoFactor.verifyLimit` | `{ max: 5, windowMinutes: 10 }` | attempts per account on `POST /api/verify-totp` (the 2FA package counts none): the sixth in the window, right or wrong, gets `429` + `Retry-After`; in memory per instance | `{ max, windowMinutes }`; `false` = no limit |
|
||||
|
||||
@@ -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 view named by the serverProp `ipalTotpView` (a path or `{ path, exportName }`, found in the import map) the way Payload renders a view: a server component gets all server props, a client component only Payload's client props, `ipalTotpClientProps`, `back` and `searchParams` (both checked). `ipalSafeBack` = own rule. Registered by the plugin with `twoFactor` (`twoFactor.safeBack`, on by default). After upgrading, `pnpm generate:importmap`. Check: password only → `/admin/verify-totp?back=https%3A%2F%2Fexample.com%2F` → code → `/admin`. Own registration: `Component: { path: '@intecion/ipal-kit/admin#SafeTotpView', serverProps: { ipalTotpView: '<path>' } }` + that path in `admin.dependencies`. |
|
||||
| `TotpRedirectProvider` | `@intecion/ipal-kit/admin` | Client admin provider: sends a user without TOTP to `/admin/setup-totp?back=…` and a user whose session has not passed TOTP to `/admin/verify-totp?back=…` (path read in the browser; never redirects away from those screens or logout; renders nothing while redirecting). Injected by the plugin with `twoFactor` in place of the package's header-based provider; swap with `twoFactor.provider`. After upgrading, `pnpm generate:importmap`. Check: a new admin lands on `setup-totp?back=%2Fadmin` with the QR code. Props type `TotpRedirectProviderProps` (`forceSetup`) |
|
||||
| `IntecionCredit` | `@intecion/ipal-kit/admin` | The line "Technology support: Intecion.com" (admin language; `agency` prop = the name) below the nav and below the login form (`variant: 'nav' \| 'login'`). Injected by the plugin with `whiteLabel`; turn off: `whiteLabel: { credit: false }` or `agency: false`. |
|
||||
| `buildAdminMeta({ agency, apiRoute?, defaultLocale?, meta?, options? })` | `@intecion/ipal-kit` | The `adminMeta` step: static panel meta (robots, preview image, icon) without overwriting keys in `meta`; returns `{ meta, resolved }` |
|
||||
@@ -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`), `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`
|
||||
|
||||
@@ -586,6 +587,11 @@ 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 (keeps `exportName`, `serverProps`; `clientProps` travel as `ipalTotpClientProps`); returns `{ views, dependencies }` (`dependencies` → `admin.dependencies`, so the wrapped views stay in the import map). What `ipalKit` runs after the 2FA factory; for a project that registers the 2FA package itself. |
|
||||
| `copyViews(views)` / `changedViewKeys(before, after)` | `@intecion/ipal-kit` | The comparison `ipalKit` uses to tell which views a 2FA factory registered: put `copyViews(views)` into the config before calling the factory, then `changedViewKeys(before, viewsAfter)` gives the keys whose view object changed — the `added` argument of `wrapTotpViews` (`(key) => keys.has(key)`). By object, not by key: the 2FA package replaces a view that already stands under its keys. Example: security.md "Your own 2FA screen". |
|
||||
| `SAFE_TOTP_VIEW` / `totpViewImportKey(component)` | `@intecion/ipal-kit` | `'@intecion/ipal-kit/admin#SafeTotpView'`, the wrapper's import-map path (the default `wrapper` of `wrapTotpViews`); and the import-map key (`path#export`) of a component given as a string or `{ path, exportName }`. |
|
||||
| `findImportMapFile(config, cwd?)` / `missingImportMapEntries(config, entries, cwd?)` | `@intecion/ipal-kit` | Where the project's `importMap.js` is on disk (`admin.importMap.importMapFile`, else `app/(payload)<admin route>/` or `src/app/…` under `admin.importMap.baseDir` / the working directory; `null` when not found), and which of `entries` its text does not contain (`{ file, missing }`). A hint from the file on disk, not the map in the build: warn on it, never block on it. Behind `twoFactor.importMapCheck`. |
|
||||
| `requireSecondFactor(access?)` | `@intecion/ipal-kit` | Wraps an `Access` function: refused while the second factor is owed, otherwise the function itself (Payload's default "logged in" when none). ipalKit applies it to every collection and global in the config, and to those added by plugins listed after it (in `onInit` and at the start of the first request, so also after a dev hot reload); use it for access functions that are not part of the config. Per-entity opt-out: `custom.ipal.secondFactor: false \| { read: false }` or the package's `custom.totp.disableAccessWrapper`. Wrapping twice is harmless. |
|
||||
| `totpRedirectTarget({ adminRoute, forceSetup?, pathname, user, excludePaths? })`, `totpAdminPath(adminRoute, path)` | `@intecion/ipal-kit` | The 2FA redirect rules as pure functions: the setup / verify URL (with `back`) to send this user to, or `null` (no path, api key, already on a TOTP screen or logout). For an own `twoFactor.provider`. Types `TotpRedirectArgs`, `TotpUser` |
|
||||
| `buildCsp({ mode?, reportUri?, reportGroup?, r2Url?, analytics?, metaPixel?, linkedIn?, tiktok?, clarity?, turnstile?, youtube?, googleMaps?, nonce?, strictDynamic?, dev?, extra?, override? })` | `@intecion/ipal-kit` | Returns `{ key, value }` with a hardened CSP (`base-uri`, `object-src`, `frame-ancestors`, `form-action`) + sources for the enabled integrations. `mode: 'report-only'` → `…-Report-Only` (start here), `'enforce'` later. `extra` adds to any directive, `override` replaces / drops one (`null`). `dev` (default `NODE_ENV === 'development'`) adds `'unsafe-eval'`. `nonce` → `'nonce-…' 'strict-dynamic'`. |
|
||||
|
||||
@@ -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,13 @@ 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
|
||||
(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`.
|
||||
- A second auth collection (`customers`, a client zone): set `admin: { user: 'users' }` in `buildConfig`; its
|
||||
|
||||
@@ -362,6 +362,24 @@ panel → Site integrations and a form submission open, a setting saves. With a
|
||||
gets `403` from the same addresses and from `POST /api/setup-totp`. The Coolify log has no
|
||||
`PAYLOAD_SECRET must be at least`; `pnpm exec ipal-doctor` has no `env` finding.
|
||||
|
||||
**→ 1.16.5 (PROGRAMISTA §6, item 67; CHANGELOG 1.16.5; security.md "The `back` link of the 2FA screens") — required with 2FA on:**
|
||||
1. **Do this in ONE deploy with the upgrade, or the panel is locked for everyone.** Run `pnpm exec ipal-doctor`
|
||||
before deploying.
|
||||
`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 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
|
||||
strips `back`, can keep them (`twoFactor.safeBack: false` turns the plugin's check off).
|
||||
2. `pnpm ipal:skills`.
|
||||
|
||||
## 2. Inventory (no code changes)
|
||||
**What changed for projects** between your old and new plugin version is exactly the reference site's diff —
|
||||
`git diff v<old> v<new> -- reference/` in the ipal-kit repo (or the two `docs/agent/reference-site/INDEX.md` files):
|
||||
|
||||
+1
-1
@@ -47,7 +47,7 @@ Write everything in this file in English.
|
||||
<!-- /starter:decisions -->
|
||||
|
||||
<!-- ipal-kit:start -->
|
||||
## ipal-kit 1.16.4 — agent guide
|
||||
## ipal-kit 1.16.5 — agent guide
|
||||
|
||||
<!-- Managed by `pnpm exec ipal-skills` — edits between the markers are overwritten. -->
|
||||
This project is built on `@intecion/ipal-kit` (a Payload CMS 3 plugin). Before you write code:
|
||||
|
||||
@@ -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<Page> {
|
||||
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()
|
||||
}
|
||||
})
|
||||
@@ -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
|
||||
}
|
||||
|
||||
@@ -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',
|
||||
|
||||
@@ -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'
|
||||
|
||||
@@ -327,6 +327,9 @@ export type {
|
||||
} from './modules/security/index.js'
|
||||
export type { BuildSecurityHeadersArgs, SecurityHeader } from './modules/security/index.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'
|
||||
|
||||
@@ -198,6 +198,21 @@ 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')
|
||||
}
|
||||
}
|
||||
// A view the project registers itself with the 2FA package's own component is not behind the back-link check.
|
||||
// Only as a view's component (`Component: '<path>'` or `Component: { path: '<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: '<that path>' } } plus the path in admin.dependencies) — security.md \"Your own 2FA screen\"",
|
||||
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',
|
||||
})
|
||||
}
|
||||
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')}
|
||||
|
||||
@@ -0,0 +1,70 @@
|
||||
import type { AdminViewServerProps } from 'payload'
|
||||
import type React from 'react'
|
||||
|
||||
import { RenderServerComponent } from '@payloadcms/ui/elements/RenderServerComponent'
|
||||
import { getFromImportMap } from 'payload/shared'
|
||||
|
||||
import { safeAdminBack, type SafeBackRule, type TotpViewComponent, totpViewImportKey } from './safeBack.js'
|
||||
|
||||
export type SafeTotpViewProps = {
|
||||
/** `twoFactor.safeBack` as a function: replaces the default rule. */
|
||||
ipalSafeBack?: SafeBackRule
|
||||
/** `clientProps` of the view's own registration; passed on to it. */
|
||||
ipalTotpClientProps?: Record<string, unknown>
|
||||
/** The view to render, as registered: `'@clocklimited/payload-2fa/rsc#TOTPVerify'` or `{ path, exportName }`. */
|
||||
ipalTotpView: TotpViewComponent
|
||||
} & AdminViewServerProps
|
||||
|
||||
const originOf = (serverURL: unknown): string | undefined => {
|
||||
if (typeof serverURL !== 'string' || !serverURL) {return undefined}
|
||||
try {
|
||||
return new URL(serverURL).origin
|
||||
} catch {
|
||||
return 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 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.
|
||||
*
|
||||
* 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, ipalTotpClientProps, ipalTotpView, ...rest } = props
|
||||
const config = props.initPageResult?.req?.payload?.config ?? props.payload?.config
|
||||
const query = (props.searchParams ?? {}) as Record<string, unknown>
|
||||
const back = (ipalSafeBack ?? safeAdminBack)(typeof query.back === 'string' ? query.back : undefined, {
|
||||
adminRoute: config?.routes?.admin ?? '/admin',
|
||||
origin: originOf(config?.serverURL),
|
||||
})
|
||||
const searchParams = { ...query, back }
|
||||
|
||||
if (!getFromImportMap({ importMap: props.importMap, PayloadComponent: ipalTotpView, schemaPath: '', silent: true })) {
|
||||
throw new Error(
|
||||
`[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.',
|
||||
)
|
||||
}
|
||||
const clientProps: Record<string, unknown> = { ...ipalTotpClientProps, back, searchParams }
|
||||
for (const key of CLIENT_PROPS) {
|
||||
if (key in rest) {clientProps[key] = (rest as Record<string, unknown>)[key]}
|
||||
}
|
||||
return RenderServerComponent({
|
||||
clientProps,
|
||||
Component: ipalTotpView,
|
||||
importMap: props.importMap,
|
||||
serverProps: { ...rest, searchParams },
|
||||
})
|
||||
}
|
||||
@@ -2,7 +2,7 @@
|
||||
|
||||
import type { ReactNode } from 'react'
|
||||
|
||||
import { useAuth, useConfig } from '@payloadcms/ui'
|
||||
import { useAuth, useConfig, useTranslation } from '@payloadcms/ui'
|
||||
import { usePathname, useRouter } from 'next/navigation.js'
|
||||
import { useEffect } from 'react'
|
||||
|
||||
@@ -14,6 +14,24 @@ export type TotpRedirectProviderProps = {
|
||||
children?: ReactNode
|
||||
/** pluginOptions.forceSetup — set by the plugin (true: 2FA is enforced). */
|
||||
forceSetup?: boolean
|
||||
/**
|
||||
* 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: '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: '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',
|
||||
},
|
||||
}
|
||||
|
||||
/**
|
||||
@@ -24,8 +42,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 +61,20 @@ export function TotpRedirectProvider({ children, forceSetup = true }: TotpRedire
|
||||
if (target) {router.replace(target)}
|
||||
}, [router, target])
|
||||
|
||||
return target ? null : children
|
||||
if (target) {return null}
|
||||
if (staleImportMap && user && /\/(?:setup|verify)-totp\/?$/.test(pathname ?? '')) {
|
||||
const text = STALE_TEXT[i18n.language?.toLowerCase().startsWith('pl') ? 'pl' : 'en']
|
||||
return (
|
||||
<>
|
||||
<div role="alert" style={{ margin: '2rem auto 0', maxWidth: '36rem', padding: '0 1.5rem' }}>
|
||||
<p style={{ fontWeight: 600, marginBottom: '0.5rem' }}>{text.title}</p>
|
||||
<p>{text.body}</p>
|
||||
</div>
|
||||
{children}
|
||||
</>
|
||||
)
|
||||
}
|
||||
return children
|
||||
}
|
||||
|
||||
export default TotpRedirectProvider
|
||||
|
||||
@@ -0,0 +1,56 @@
|
||||
/**
|
||||
* 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 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 } }
|
||||
|
||||
/** The file Payload reads the import map from — the same places Payload itself looks in. Null when not found. */
|
||||
export async function findImportMapFile(config: ConfigLike, cwd = process.cwd()): Promise<null | string> {
|
||||
try {
|
||||
const fs = await import('node:fs/promises')
|
||||
const path = await import('node:path')
|
||||
const exists = (file: string) => fs.access(file).then(() => true, () => false)
|
||||
const explicit = config.admin?.importMap?.importMapFile
|
||||
if (explicit) {return (await exists(explicit)) ? explicit : null}
|
||||
const rootDir = config.admin?.importMap?.baseDir ?? cwd
|
||||
// Next.js writes %5F for route segments that begin with an underscore
|
||||
const adminFolder = (config.routes?.admin ?? '/admin').replace(/(^|\/)_/g, '$1%5F')
|
||||
for (const base of [`app/(payload)${adminFolder}`, `src/app/(payload)${adminFolder}`]) {
|
||||
const file = path.resolve(rootDir, base, 'importMap.js')
|
||||
if (await exists(file)) {return file}
|
||||
}
|
||||
} catch {
|
||||
/* no file system (or not Node): nothing to check */
|
||||
}
|
||||
return null
|
||||
}
|
||||
|
||||
/**
|
||||
* The entries of `needed` that 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)
|
||||
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: [] }
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,147 @@
|
||||
/**
|
||||
* 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$/
|
||||
|
||||
/** Import-map path of the wrapper ipalKit registers. */
|
||||
export const SAFE_TOTP_VIEW = '@intecion/ipal-kit/admin#SafeTotpView'
|
||||
|
||||
/** 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 for which `added(key)` is true and whose
|
||||
* route is `setup-totp` / `verify-totp`: the wrapper cleans `back` and renders the original
|
||||
* view, which it finds in the import map (`admin.dependencies` keeps it there). ipal-kit still
|
||||
* never imports the optional package. The original's `serverProps` stay server props; its
|
||||
* `clientProps` travel as `ipalTotpClientProps`, so the wrapper can hand them to a client view.
|
||||
*/
|
||||
export function wrapTotpViews<V extends ViewLike>(
|
||||
views: Record<string, V>,
|
||||
added: (key: string) => boolean,
|
||||
rule: SafeBackRule | undefined,
|
||||
wrapper = SAFE_TOTP_VIEW,
|
||||
): { dependencies: Record<string, Dependency>; views: Record<string, V> } {
|
||||
const dependencies: Record<string, Dependency> = {}
|
||||
const out: Record<string, V> = {}
|
||||
for (const [key, view] of Object.entries(views)) {
|
||||
const component = view?.Component as TotpViewComponent | undefined
|
||||
const path = typeof component === 'string' ? component : component?.path
|
||||
if (!added(key) || !view || typeof view.path !== 'string' || !TOTP_VIEW_PATH.test(view.path) || !component || !path || path === wrapper) {
|
||||
out[key] = view
|
||||
continue
|
||||
}
|
||||
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: {
|
||||
path: wrapper,
|
||||
serverProps: { ...own?.serverProps, ipalSafeBack: rule, ipalTotpClientProps: own?.clientProps, ipalTotpView: original },
|
||||
},
|
||||
}
|
||||
}
|
||||
return { dependencies, views: out }
|
||||
}
|
||||
|
||||
/**
|
||||
* Shallow copies of a config's views. Put these into the config BEFORE calling a 2FA factory and
|
||||
* keep them as `before` for `changedViewKeys`: a view the factory registers is then never the
|
||||
* same object as one that was there, also when the factory reuses its view objects between calls.
|
||||
*/
|
||||
export const copyViews = <V>(views: Record<string, V> | undefined): Record<string, V> =>
|
||||
Object.fromEntries(Object.entries(views ?? {}).map(([key, view]) => [key, view && typeof view === 'object' ? { ...view } : view]))
|
||||
|
||||
/**
|
||||
* Keys whose view object is not the one in `before` — what a plugin added or replaced.
|
||||
* `added` for `wrapTotpViews`: `const before = copyViews(views)` → run the factory on a config
|
||||
* holding `before` → `const keys = changedViewKeys(before, viewsAfter)` → `(key) => keys.has(key)`.
|
||||
* A key alone says nothing: the 2FA package replaces a view that already stands under its keys.
|
||||
*/
|
||||
export const changedViewKeys = (before: Record<string, unknown>, after: Record<string, unknown>): Set<string> =>
|
||||
new Set(Object.keys(after).filter((key) => after[key] !== before[key]))
|
||||
+71
-2
@@ -33,6 +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 { missingImportMapEntries } from './modules/security/totp/importMapCheck.js'
|
||||
import { changedViewKeys, copyViews, SAFE_TOTP_VIEW, wrapTotpViews } from './modules/security/totp/safeBack.js'
|
||||
import {
|
||||
buildGuardStrategy,
|
||||
ensurePayloadGuarded,
|
||||
@@ -54,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.
|
||||
@@ -91,7 +95,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,
|
||||
}
|
||||
@@ -170,6 +174,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 = {}
|
||||
/**
|
||||
@@ -229,6 +235,12 @@ export const ipalKit = (options: IpalOptions): Plugin => {
|
||||
)
|
||||
}
|
||||
const endpointsBefore = new Set(config.endpoints ?? [])
|
||||
// Copies, so that a view the 2FA factory hands back is told apart from one it left alone
|
||||
// even when the factory returns the very same objects on every call.
|
||||
const viewsBefore = copyViews(config.admin?.components?.views)
|
||||
if (config.admin?.components?.views) {
|
||||
config.admin = { ...config.admin, components: { ...config.admin.components, views: viewsBefore as never } }
|
||||
}
|
||||
const entityEndpointsBefore = new Map<string, Set<unknown>>(
|
||||
[...(config.collections ?? []), ...(config.globals ?? [])].map((e) => [e.slug, new Set<unknown>(Array.isArray(e.endpoints) ? e.endpoints : [])]),
|
||||
)
|
||||
@@ -251,6 +263,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
|
||||
@@ -315,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,
|
||||
@@ -333,6 +350,50 @@ 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<string, { Component?: unknown; path?: string }>,
|
||||
(key) => viewsFromPackage.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 },
|
||||
}
|
||||
// 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(', ')} 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.path === TOTP_REDIRECT_PROVIDER // ipal-kit's own provider only
|
||||
? { ...p, clientProps: { ...p.clientProps, staleImportMap: true } }
|
||||
: p,
|
||||
),
|
||||
},
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
const agency = options.agency === undefined ? DEFAULT_AGENCY : options.agency
|
||||
@@ -700,6 +761,14 @@ 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)
|
||||
if (staleImportMap) {
|
||||
payload.logger.error(
|
||||
`[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)
|
||||
|
||||
@@ -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'
|
||||
@@ -241,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
|
||||
/**
|
||||
@@ -265,6 +275,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
|
||||
|
||||
@@ -51,6 +51,54 @@ 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')
|
||||
})
|
||||
|
||||
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 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([])
|
||||
})
|
||||
})
|
||||
})
|
||||
|
||||
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' })
|
||||
|
||||
@@ -0,0 +1,494 @@
|
||||
import type { Config } from 'payload'
|
||||
|
||||
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, vi } from 'vitest'
|
||||
|
||||
import type { I18nConfig } from '../src/modules/i18n/types.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'
|
||||
import { withTotpParts } from './helpers.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,<script>alert(1)</script>'],
|
||||
['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://[email protected]/admin'],
|
||||
['http://user:[email protected]/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://[email protected]/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('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)
|
||||
const twice = wrapTotpViews(once.views, () => true, undefined)
|
||||
expect(twice.views).toEqual(once.views)
|
||||
expect(twice.dependencies).toEqual({})
|
||||
})
|
||||
})
|
||||
|
||||
describe.each([
|
||||
['3.0.0-beta.7', payloadTotpBeta7],
|
||||
['3.0.0-beta.1', payloadTotpBeta1 as unknown as typeof payloadTotpBeta7],
|
||||
])('ipalKit with the real 2FA package %s', (_version, payloadTotp) => {
|
||||
const build = (twoFactor: false | Record<string, unknown>, extra: Partial<Config> = {}, options: Record<string, unknown> = {}) =>
|
||||
ipalKit({
|
||||
access: { authCollection: 'users' },
|
||||
i18n,
|
||||
twoFactor: twoFactor === false ? false : ({ issuer: 'Example', plugin: payloadTotp, ...twoFactor } as never),
|
||||
...options,
|
||||
})({ collections: [], secret: 'x', ...extra } as unknown as Config)
|
||||
|
||||
/** Keys of views that still point straight at the 2FA package: unguarded. */
|
||||
const raw = (config: Config) =>
|
||||
Object.entries(config.admin?.components?.views ?? {})
|
||||
.filter(([, view]) => {
|
||||
const c = (view as { Component?: { path?: string } | string }).Component
|
||||
return (typeof c === 'string' ? c : (c?.path ?? '')).includes('payload-2fa')
|
||||
})
|
||||
.map(([key]) => key)
|
||||
|
||||
// The package replaces a view that already stands under one of its keys: such a key is not "the project's own".
|
||||
test('a view the project had under a package key is replaced by the package, and guarded', async () => {
|
||||
const config = await build({}, { admin: { components: { views: { SetupTOTPBackslash: { Component: 'mine#S', path: '/setup-totp' }, VerifyTOTP: { Component: 'mine#V', path: '/verify-totp' } } } } } as never)
|
||||
expect(raw(config)).toEqual([])
|
||||
expect(component(config, 'VerifyTOTP')?.path).toBe('@intecion/ipal-kit/admin#SafeTotpView')
|
||||
expect(component(config, 'SetupTOTPBackslash')?.path).toBe('@intecion/ipal-kit/admin#SafeTotpView')
|
||||
})
|
||||
|
||||
test('the package registered by the project too, before ipalKit: still guarded', async () => {
|
||||
const first = payloadTotp({ collection: 'users', totp: { issuer: 'E' } } as never)({ collections: [{ slug: 'users', auth: true, fields: [] }], secret: 'x' } as never)
|
||||
expect(raw(first).length).toBe(4)
|
||||
expect(raw(await build({}, first as never))).toEqual([])
|
||||
})
|
||||
|
||||
test('ipalKit run over its own output (a config reused): still guarded', async () => {
|
||||
const once = await build({})
|
||||
const twice = await build({}, { admin: once.admin } as never)
|
||||
expect(raw(twice)).toEqual([])
|
||||
expect(component(twice, 'VerifyTOTP')?.serverProps?.ipalTotpView).toBe('@clocklimited/payload-2fa/rsc#TOTPVerify')
|
||||
})
|
||||
|
||||
test('the same incoming config object built twice', async () => {
|
||||
const incoming = { admin: { components: { views: {} } }, collections: [], secret: 'x' } as unknown as Config
|
||||
const plugin = () => ipalKit({ access: { authCollection: 'users' }, i18n, twoFactor: { issuer: 'E', plugin: payloadTotp } as never })(incoming)
|
||||
expect(raw(await plugin())).toEqual([])
|
||||
expect(raw(await plugin())).toEqual([])
|
||||
})
|
||||
|
||||
test('safeBack: true, null or undefined is on; only false is off', async () => {
|
||||
for (const value of [true, null, undefined]) {expect(raw(await build({ safeBack: value }))).toEqual([])}
|
||||
expect(raw(await build({ safeBack: false })).length).toBe(4)
|
||||
})
|
||||
|
||||
test('enabled: false leaves no views and no import-map dependencies behind', async () => {
|
||||
const config = await build({}, { admin: { dependencies: { mine: { type: 'component', path: 'mine#Thing' } } }, collections: [{ slug: 'users', auth: true, fields: [] }] } as never, { enabled: false })
|
||||
expect(JSON.stringify(config.admin?.components ?? {})).not.toMatch(/SafeTotp|payload-2fa/)
|
||||
expect(config.admin?.dependencies).toEqual({ mine: { type: 'component', path: 'mine#Thing' } })
|
||||
const bare = await build({}, { collections: [{ slug: 'users', auth: true, fields: [] }] } as never, { enabled: false })
|
||||
expect(bare.admin?.dependencies).toBeUndefined()
|
||||
})
|
||||
|
||||
const component = (config: Config, key: string) =>
|
||||
(config.admin?.components?.views as Record<string, { Component: { path: string; serverProps?: Record<string, unknown> } }> | undefined)?.[key]?.Component
|
||||
|
||||
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<string, { meta?: { title?: string } }>).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<string, { Component: unknown }>).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<string, unknown> }) =>
|
||||
React.createElement('p', { 'data-back': String(props.searchParams?.back), 'data-issuer': props.pluginOptions?.issuer, 'data-other': String(props.searchParams?.other) })
|
||||
const render = (searchParams: Record<string, unknown>, more: Record<string, unknown> = {}, config: Record<string, unknown> = { 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/)
|
||||
})
|
||||
})
|
||||
|
||||
describe('a 2FA factory that hands back the same view objects on every call', () => {
|
||||
const views = {
|
||||
SetupTOTP: { Component: { path: 'pkg/rsc#TOTPSetup' }, path: 'setup-totp' },
|
||||
VerifyTOTP: { Component: { path: 'pkg/rsc#TOTPVerify' }, path: 'verify-totp' },
|
||||
}
|
||||
const factory = (o: { collection: string }) => (c: Config) =>
|
||||
withTotpParts({ ...c, admin: { ...c.admin, components: { ...c.admin?.components, views: { ...c.admin?.components?.views, ...views } } } } as Config, o.collection)
|
||||
const build = (incoming: Partial<Config> = {}) =>
|
||||
ipalKit({ access: { authCollection: 'users' }, i18n, twoFactor: { issuer: 'E', plugin: factory as never } })({ collections: [], secret: 'x', ...incoming } as unknown as Config)
|
||||
const paths = (config: Config) => Object.values(config.admin?.components?.views ?? {}).map((v) => (v as { Component: { path: string } }).Component.path)
|
||||
|
||||
test('is guarded when registered once, twice, and over a config that already holds those objects', async () => {
|
||||
expect(paths(await build())).toEqual(Array(2).fill('@intecion/ipal-kit/admin#SafeTotpView'))
|
||||
const already = factory({ collection: 'users' })({ collections: [{ slug: 'users', auth: true, fields: [] }], secret: 'x' } as unknown as Config)
|
||||
expect(paths(already)).toEqual(['pkg/rsc#TOTPSetup', 'pkg/rsc#TOTPVerify']) // raw, the very objects the factory returns again
|
||||
expect(paths(await build(already))).toEqual(Array(2).fill('@intecion/ipal-kit/admin#SafeTotpView'))
|
||||
expect(views.VerifyTOTP.Component.path).toBe('pkg/rsc#TOTPVerify') // the factory's own objects are not changed
|
||||
})
|
||||
})
|
||||
|
||||
describe('safeAdminBack with values that are not a string', () => {
|
||||
test.each([[['/admin', 'javascript:1']], [{}], [null], [1], [{ toString: () => 'javascript:1' }]])('%s', (value) => {
|
||||
expect(safeAdminBack(value as never, { adminRoute: '/admin' })).toBe('/admin')
|
||||
})
|
||||
})
|
||||
|
||||
describe('changedViewKeys', () => {
|
||||
test('a key counts when its object is another one, whether or not the key existed', () => {
|
||||
const kept = { path: '/a' }
|
||||
expect([...changedViewKeys({ A: kept, B: { path: '/b' } }, { A: kept, B: { path: '/b' }, C: { path: '/c' } })].sort()).toEqual(['B', 'C'])
|
||||
})
|
||||
})
|
||||
|
||||
describe('SafeTotpView in front of a client component', () => {
|
||||
// What a 'use client' export looks like on the server: a reference Payload must not hand server props to.
|
||||
const ClientView = Object.assign(() => null, { $$typeof: Symbol.for('react.client.reference') })
|
||||
const ServerView = () => null
|
||||
const props = (view: unknown) => ({
|
||||
clientConfig: { routes: { admin: '/admin' } },
|
||||
i18n: { t: () => '' },
|
||||
importMap: { 'mine/views#Verify': view },
|
||||
initPageResult: { req: { payload: { config: { routes: { admin: '/admin' }, serverURL: '' } } } },
|
||||
ipalTotpClientProps: { tone: 'dark' },
|
||||
ipalTotpView: { exportName: 'Verify', path: 'mine/views' },
|
||||
payload: { find: () => null },
|
||||
pluginOptions: { adminManageAccess: () => true },
|
||||
searchParams: { back: 'javascript:alert(1)', other: 'kept' },
|
||||
viewType: 'verify',
|
||||
})
|
||||
const hasFunction = (value: unknown, seen = new Set<unknown>()): boolean => {
|
||||
if (typeof value === 'function') {return true}
|
||||
if (!value || typeof value !== 'object' || seen.has(value)) {return false}
|
||||
seen.add(value)
|
||||
return Object.values(value).some((v) => hasFunction(v, seen))
|
||||
}
|
||||
const call = SafeTotpView as unknown as (p: unknown) => React.ReactElement<Record<string, unknown>>
|
||||
|
||||
test('gets only props that can cross to the browser, with the checked back', () => {
|
||||
const element = call(props(ClientView))
|
||||
expect(element.type).toBe(ClientView)
|
||||
expect(hasFunction(element.props)).toBe(false) // a function prop is what crashed the screen with a 500
|
||||
expect(element.props).toEqual({
|
||||
back: '/admin',
|
||||
clientConfig: { routes: { admin: '/admin' } },
|
||||
searchParams: { back: '/admin', other: 'kept' },
|
||||
tone: 'dark',
|
||||
viewType: 'verify',
|
||||
})
|
||||
})
|
||||
|
||||
test('a server component still gets the server props', () => {
|
||||
const element = call(props(ServerView))
|
||||
expect(element.type).toBe(ServerView)
|
||||
expect(typeof (element.props.pluginOptions as { adminManageAccess: unknown }).adminManageAccess).toBe('function')
|
||||
expect(element.props.searchParams).toEqual({ back: '/admin', other: 'kept' })
|
||||
expect(element.props.tone).toBe('dark')
|
||||
expect(element.props.ipalTotpView).toBeUndefined()
|
||||
})
|
||||
})
|
||||
|
||||
describe('the stale import-map check', () => {
|
||||
const ENTRY = '@intecion/ipal-kit/admin#SafeTotpView'
|
||||
const project = async (layout: string, content: string) => {
|
||||
const root = await mkdtemp(path.join(os.tmpdir(), 'ipal-importmap-'))
|
||||
await mkdir(path.join(root, layout), { recursive: true })
|
||||
await writeFile(path.join(root, layout, 'importMap.js'), content)
|
||||
return root
|
||||
}
|
||||
|
||||
test('finds the file where Payload looks: app/, src/app/, a custom admin route, an explicit file', async () => {
|
||||
const a = await project('app/(payload)/admin', '')
|
||||
const b = await project('src/app/(payload)/admin', '')
|
||||
const c = await project('src/app/(payload)/panel', '')
|
||||
try {
|
||||
expect(await findImportMapFile({}, a)).toBe(path.join(a, 'app/(payload)/admin/importMap.js'))
|
||||
expect(await findImportMapFile({ admin: { importMap: { baseDir: b } } }, '/nowhere')).toBe(path.join(b, 'src/app/(payload)/admin/importMap.js'))
|
||||
expect(await findImportMapFile({ routes: { admin: '/panel' } }, c)).toBe(path.join(c, 'src/app/(payload)/panel/importMap.js'))
|
||||
expect(await findImportMapFile({ routes: { admin: '/panel' } }, a)).toBeNull()
|
||||
const explicit = path.join(a, 'app/(payload)/admin/importMap.js')
|
||||
expect(await findImportMapFile({ admin: { importMap: { importMapFile: explicit } } }, '/nowhere')).toBe(explicit)
|
||||
expect(await findImportMapFile({ admin: { importMap: { importMapFile: '/nowhere/importMap.js' } } }, a)).toBeNull()
|
||||
} finally {
|
||||
for (const dir of [a, b, c]) {await rm(dir, { force: true, recursive: true })}
|
||||
}
|
||||
})
|
||||
|
||||
test('in production ipalKit marks the redirect provider when the map lacks the wrapper; not otherwise', async () => {
|
||||
const stale = await project('src/app/(payload)/admin', 'export const importMap = { "@intecion/ipal-kit/admin#TotpRedirectProvider": X }')
|
||||
const current = await project('src/app/(payload)/admin', `export const importMap = { "${ENTRY}": Y }`)
|
||||
const flagged = async (baseDir: string, twoFactor: Record<string, unknown> = {}) => {
|
||||
const config = await ipalKit({ access: { authCollection: 'users' }, i18n, twoFactor: { issuer: 'E', plugin: payloadTotpBeta7, ...twoFactor } as never })({
|
||||
admin: { importMap: { baseDir } },
|
||||
collections: [],
|
||||
secret: 'x',
|
||||
} as unknown as Config)
|
||||
return JSON.stringify(config.admin?.components?.providers ?? []).includes('"staleImportMap":true')
|
||||
}
|
||||
const before = process.env.NODE_ENV
|
||||
try {
|
||||
vi.stubEnv('NODE_ENV', 'production')
|
||||
expect(await flagged(stale)).toBe(true)
|
||||
expect(await flagged(current)).toBe(false)
|
||||
expect(await flagged('/nowhere')).toBe(false) // file not found: unknown, not reported
|
||||
expect(await flagged(stale, { importMapCheck: false })).toBe(false)
|
||||
expect(await flagged(stale, { safeBack: false })).toBe(false) // nothing wrapped, nothing needed
|
||||
vi.stubEnv('NODE_ENV', 'development')
|
||||
expect(await flagged(stale)).toBe(false) // Payload regenerates the map in development
|
||||
} finally {
|
||||
vi.unstubAllEnvs()
|
||||
expect(process.env.NODE_ENV).toBe(before)
|
||||
for (const dir of [stale, current]) {await rm(dir, { force: true, recursive: true })}
|
||||
}
|
||||
})
|
||||
|
||||
// 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 }`)
|
||||
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 })}
|
||||
}
|
||||
})
|
||||
})
|
||||
@@ -0,0 +1,67 @@
|
||||
import React from 'react'
|
||||
import { renderToStaticMarkup } from 'react-dom/server'
|
||||
import { beforeEach, describe, expect, test, vi } from 'vitest'
|
||||
|
||||
/**
|
||||
* The stale-import-map notice of TotpRedirectProvider. The flag behind it is a guess (a text search of the
|
||||
* importMap.js on disk, not the map in the bundle), so the notice is shown NEXT TO the screen: a wrong guess
|
||||
* must never take the code form away.
|
||||
*/
|
||||
const state = { language: 'en', pathname: '/admin/verify-totp', user: { _strategy: 'local-jwt', hasTotp: true } as null | Record<string, unknown> }
|
||||
|
||||
vi.mock('@payloadcms/ui', () => ({
|
||||
useAuth: () => ({ user: state.user }),
|
||||
useConfig: () => ({ config: { admin: { routes: {} }, routes: { admin: '/admin' } } }),
|
||||
useTranslation: () => ({ i18n: { language: state.language } }),
|
||||
}))
|
||||
vi.mock('next/navigation.js', () => ({ usePathname: () => state.pathname, useRouter: () => ({ replace: () => undefined }) }))
|
||||
|
||||
const { TotpRedirectProvider } = await import('../src/modules/security/totp/TotpRedirectProvider.js')
|
||||
|
||||
const FORM = '<form id="code-form"><input/></form>'
|
||||
const form = () => React.createElement('form', { id: 'code-form' }, React.createElement('input'))
|
||||
const render = (props: Record<string, unknown> = {}, children: React.ReactNode = form()) =>
|
||||
renderToStaticMarkup(React.createElement(TotpRedirectProvider, props, children))
|
||||
|
||||
beforeEach(() => {
|
||||
Object.assign(state, { language: 'en', pathname: '/admin/verify-totp', user: { _strategy: 'local-jwt', hasTotp: true } })
|
||||
})
|
||||
|
||||
describe('TotpRedirectProvider with staleImportMap', () => {
|
||||
// Reviewer repro 1: the build is current, but the importMap.js on disk is an older one → the flag is wrong.
|
||||
// Reviewer repro 2: the map file re-exports the generated map → the text search finds nothing → the flag is wrong.
|
||||
// In both the screen works, and must stay on the page.
|
||||
test('a false alarm: the working code form is still rendered, with the notice above it', () => {
|
||||
const html = render({ staleImportMap: true })
|
||||
expect(html).toContain(FORM)
|
||||
expect(html).toContain('role="alert"')
|
||||
expect(html).toContain('may not be available')
|
||||
expect(html.indexOf('role="alert"')).toBeLessThan(html.indexOf('code-form'))
|
||||
})
|
||||
|
||||
test('a really stale map: Payload renders nothing for the screen, the notice is what the user sees', () => {
|
||||
const html = render({ staleImportMap: true }, null)
|
||||
expect(html).toContain('role="alert"')
|
||||
expect(html).toContain('pnpm payload generate:importmap')
|
||||
})
|
||||
|
||||
test('the setup screen too; Polish for a Polish panel', () => {
|
||||
Object.assign(state, { language: 'pl', pathname: '/admin/setup-totp', user: { _strategy: 'local-jwt', hasTotp: false } })
|
||||
const html = render({ staleImportMap: true })
|
||||
expect(html).toContain('Weryfikacja dwuetapowa może być niedostępna')
|
||||
expect(html).toContain(FORM)
|
||||
})
|
||||
|
||||
test('no notice without the flag, on other pages, or for a visitor', () => {
|
||||
expect(render({})).toBe(FORM)
|
||||
Object.assign(state, { pathname: '/admin/collections/pages', user: { _strategy: 'totp', hasTotp: true } })
|
||||
expect(render({ staleImportMap: true })).toBe(FORM)
|
||||
Object.assign(state, { pathname: '/admin/verify-totp', user: null })
|
||||
expect(render({ staleImportMap: true })).toBe(FORM)
|
||||
})
|
||||
|
||||
test('a pending redirect still renders nothing', () => {
|
||||
Object.assign(state, { pathname: '/admin/collections/pages', user: { _strategy: 'local-jwt', hasTotp: true } })
|
||||
expect(render({ staleImportMap: true })).toBe('')
|
||||
})
|
||||
})
|
||||
Reference in New Issue
Block a user