2FA setup required: an account without TOTP reaches only setup, within a 72 h window

twoFactor.requireSetup (on by default with 2FA): an account of the 2FA
collection that has not set TOTP up is refused by ipal-kit's second-factor
check on every collection, global and plugin endpoint; the setup screen and
/api/setup-totp are all it reaches. It has 72 hours from its creation or
from an admin's reset (field totpSetupFrom, stamped by a hook); after that
setup is refused too until an admin reopens it.

Accounts that existed before get their window at the first start after the
upgrade (backfill in onInit), so nobody is blocked when a site upgrades.

Admin side: status and reset / 'Reopen setup' button on the account page
(TwoFactorStatusField), POST /api/ipal/two-factor/reset, a dashboard notice
(TwoFactorAlert), a notice on the setup screen; texts in English and Polish.
ipal-doctor reports blocked accounts and a switched-off mode.

Overridable: requireSetup false, windowHours (false / 0 = none), exempt for
a service account, resetAccess; the per-entity second-factor opt-out applies.
API keys, seeds, bearer-token routes and sites with twoFactor false are not
affected.

HTTP tests (REST, GraphQL, first admin on an empty database) run on SQLite,
Postgres and MongoDB; a browser test on the reference site covers the first
admin, a new editor and the admin's reset. Docs, guide, skills, changelog.

Co-Authored-By: Claude Fable 5.2 <[email protected]>
This commit is contained in:
Radosław Smoliński
2026-11-24 18:46:32 +01:00
co-authored by Claude Fable 5.2
parent 45d52c4690
commit 2aaaaa115a
43 changed files with 1234 additions and 63 deletions
+41
View File
@@ -8,6 +8,47 @@ versions at once, go through every "Requires project changes" section in order,
version you have. A new release = a new section at the top; we remove the oldest ones only
once there are more than 20.
## Unreleased — 2FA setup required (version to be set at release)
### Changed
- **An account without two-step verification can only set it up** (`twoFactor.requireSetup`, on by default with
2FA). Until now the panel redirected such an account to the setup screen, but over the API (REST, GraphQL) its
password alone opened everything its role allowed. Now every collection, global and plugin endpoint refuses it
until TOTP is set up; the setup screen and `POST /api/setup-totp` are all it reaches.
- **A setup window of 72 hours**, counted from the account's creation or from a reset by an administrator. After
it the account is blocked — setup is refused too — until an administrator reopens it. This limits how long an
account that never set 2FA up can be taken over by someone who learned its password.
- **Accounts that already exist** get their 72 hours from the **first start after the upgrade** (not from their
creation date), so nobody is blocked at the moment of the upgrade. The server log names how many there are.
### Added
- On every account in the panel: **Two-step verification** (sidebar) — set up / open until a date / blocked — and
for administrators "Reset two-step verification" (a lost phone) and "Reopen setup" (a blocked account).
`POST /api/ipal/two-factor/reset` `{ userId }` does the same.
- A dashboard notice for administrators: accounts without two-step verification, and how many are blocked.
- A notice on the setup screen: until when setup has to be done, or that the time has passed. All texts in
English and Polish.
- Options: `twoFactor.requireSetup: false | { windowHours, exempt }`, `twoFactor.resetAccess`. Exports:
`twoFactorSetupState`, `twoFactorSetupDeadline`; admin components `TwoFactorStatusField`, `TwoFactorResetButton`,
`TwoFactorAlert`.
- ipal-doctor: the `2fa` rule says how many accounts without 2FA are blocked (`usersSetupClosed` in the deep
status), warns when `requireSetup` is switched off and notes a missing setup window.
### Requires project changes
- **Before upgrading a live site:** `pnpm exec ipal-doctor --url <site>` → accounts without 2FA. Each sets 2FA up
now, or is removed. At least one administrator must have 2FA set up, or nobody can reopen setup from the panel.
- `pnpm payload generate:importmap` (commit `importMap.js`) and `pnpm payload generate:types`.
- **Postgres / SQLite:** `pnpm payload migrate:create` — the 2FA collection gets the column `totpSetupFrom`.
MongoDB: nothing.
- **An integration that logs in with a password and has no TOTP** stops working: give it an API key (passes as
before) or exempt it on purpose: `twoFactor.requireSetup: { exempt: ({ user }) => user.email === '…' }`.
- **Own code** calling `payload.find({ …, user, overrideAccess: false })` with a user fetched by id: refused for
every account of the 2FA collection now (before: only accounts with TOTP set up). Use `payload.auth({ headers })`.
- **After deploy:** read the log line `[ipal] 2FA: N existing account(s) without two-step verification…` and tell
the owner; after 72 hours such an account needs "Reopen setup" from an administrator.
- **Not wanted on a site:** `twoFactor.requireSetup: false` (the previous behaviour), or
`{ windowHours: false }` to keep the lock without the time limit. Sites with `twoFactor: false` are not affected.
## 1.16.5
### Security
+2 -2
View File
@@ -84,8 +84,8 @@ The plugin's own staff features — Site integrations, the settings globals, for
stats, the cookie scanner, `/api/ipal/test-email` — check with `userMeetsRole(req, minimum)`, in this order:
1. the account belongs to a staff collection;
2. with 2FA on: an account that has TOTP set up has entered the code in this session
([security.md](./security.md) → "What the second factor covers");
2. with 2FA on: the account has set TOTP up and has entered the code in this session
([security.md](./security.md) → "What the second factor covers", "Setup required");
3. it holds at least the role `minimum` — **or** its collection has no `roles` field at all. Then every account
of that staff collection passes, as in Payload's default (without roles all accounts are equal).
+2 -1
View File
@@ -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`, `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 |
| 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)`; **an account without 2FA can only set it up** (`twoFactor.requireSetup`, default: nothing else answers, 72 h from creation or an admin's reset, then blocked until an admin chooses "Reopen setup" on the account) — so set 2FA up right after creating an account; `ipal-doctor --url` must report 0 accounts without 2FA; Postgres/SQLite: migration for `totpSetupFrom`; `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 |
@@ -1165,6 +1165,7 @@ add missing hosts with flags / `extra`; (3) change `mode` to `'enforce'` in both
| Injected `users`: admin manages everyone, others only themselves | — | `access.authAccess` (your keys win); your own `users` collection wins whole |
| First registered account = admin | `access.firstUserAdmin: false` | `buildRolesField(defaultRole, { firstUserAdmin })` |
| 2FA on the panel's login collection, mismatch = startup error; redirect to the 2FA screens by `TotpRedirectProvider` | `twoFactor: false` (discouraged) | `twoFactor.collectionSlug`, `allowCollectionMismatch: true`, `twoFactor.provider` (own component, or `false` for the package's) |
| 2FA setup required: an account without TOTP reaches only the setup screen; 72 h window from creation / admin reset, then blocked; status and "Reopen setup" on the account page, notice on the dashboard, `POST /api/ipal/two-factor/reset` | `twoFactor.requireSetup: false` | `requireSetup: { windowHours, exempt }`, `twoFactor.resetAccess`, texts `twoFactor*`; `twoFactorSetupState(req)` |
| 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 |
+1
View File
@@ -1162,6 +1162,7 @@ Rules: AGENT.md §8a.
| `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/two-factor-setup.spec.ts` | browser check of "2FA setup required": the first admin of a fresh site, a new editor, the administrator's reset on the account page |
### `e2e/create-test-admin.ts`
+1 -1
View File
@@ -51,7 +51,7 @@ Ask only when the brief leaves a business question open (e.g. "do posts have aut
4. **An auth collection for visitors** (`auth: true`: customers, members) only when the client requires it
(AGENT.md §5 "A second auth collection"): `admin: { user: 'users' }` in `buildConfig`, `access` with
`adminOrSelfIn('<slug>')` for read / update and an explicit `create`, never in `access.staffCollections`.
Its accounts pass none of the plugin's staff checks. Check: its token → `403` from
Its accounts pass none of the plugin's staff checks, and 2FA (setup required included) does not apply to them. Check: its token → `403` from
`/api/globals/site-integrations` and `/api/form-submissions`.
5. `pnpm generate:types`, `pnpm payload generate:importmap`.
6. Postgres with migrations → `pnpm payload migrate:create`.
+4
View File
@@ -37,6 +37,10 @@ through this procedure. Ask only when you are missing something you cannot get y
| the 2FA code screen answers "Too many codes were tried…" (`429` from `/api/verify-totp`) | more than 5 verify attempts for that account in 10 minutes (`twoFactor.verifyLimit`); repeated lines `[ipal] 2FA: too many verify attempts` in the log without the owner trying = someone has the password | wait for the window, enter the current code once; unexplained attempts: change that account's password. Tests that log in often: `verifyLimit: { max: … }` for that environment |
| `isAdmin(req.user)` says `false` for a real administrator on the server, in a process that loads two Payload configs (tests, a multi-site script) | a call without a source counts only collections that are staff in **every** config of the process | pass the source: `isAdmin(req.user, req.payload)` — with it each config gets its own answer |
| `isAdmin(user)` / `isEditor(user)` is always `false` in a client component or in `proxy.ts` | the staff collections are not known there (no config in the browser bundle / middleware), and the predicates fail closed | `isAdmin(user, config)` with `useConfig()`; in middleware `isAdmin(user, { staffCollections: ['users'] })` |
| an account logs in but every page and request answers 403 / the setup screen says "The time to set up two-step verification has passed" | 2FA setup required: the account did not set TOTP up within the window (72 h from its creation, an admin's reset, or the first start after the upgrade) | an administrator opens the account in the panel → Two-step verification → "Reopen setup" (or `POST /api/ipal/two-factor/reset` `{ userId }`); the only admin is blocked: a script with the Local API — `payload.update({ collection: 'users', id, data: { totpSetupFrom: new Date().toISOString() } })` (`pnpm payload run`), then log in and set TOTP up |
| a new account gets `403` from the API although its role allows the request | 2FA setup required: until TOTP is set up the account reaches only the setup screen | set TOTP up (log in to the panel); an integration: use an API key, or `twoFactor.requireSetup.exempt` |
| log: `[ipal] 2FA: could not start the setup window for existing accounts` | Postgres/SQLite: the migration that adds `totpSetupFrom` has not run | `pnpm payload migrate:create`, commit, deploy (migrations run in the Coolify pre-deploy command) |
| "Two-step verification" is missing on the account page / the dashboard shows a missing component | the import map is stale | `pnpm payload generate:importmap`, commit `importMap.js`, `rm -rf .next`, redeploy |
| startup: `[ipal] twoFactor: the injected 2FA plugin did not add the totpSecret field / hasTotp field / totp auth strategy` | the installed `@clocklimited/payload-2fa` is not a version ipal-kit's second-factor check recognises (tested: 3.0.0-beta.1 and beta.7), or a custom factory was injected | install a supported version; stop-gap only: `twoFactor.guard: false` (the plugin's own data is then not covered by 2FA — security.md) |
| own route or script gets `403` / "not allowed" on `form-submissions`, `forms`, a settings global with `overrideAccess: false`, although the user is an admin | the `user` was fetched by id and passed by hand: it does not carry how the account logged in, so the second-factor check refuses it | take the user from `payload.auth({ headers })` (it sets `collection` and how the account logged in), or (server-only code that needs no access check) leave `overrideAccess` at its default; a hand-built user needs at least `collection: 'users'` for its role to count |
| an account of a second auth collection (`customers`) gets `403` from a settings global, submissions, `/api/ipal/*`, `/api/setup-totp`, or `isAdmin` / `adminOnly` say no although it has `roles: ['admin']`, after an upgrade | by design since 1.16.4: roles and staff checks count only for accounts of a staff collection | write the one rule it needs (`formSubmissionOverrides`, `globalOverrides`, `collectionOverrides`); a second STAFF collection: `access.staffCollections` (access.md "Who is staff") |
+1 -1
View File
@@ -50,7 +50,7 @@ Existing client sites are not gated on it; run it there as a report only.
## The status endpoint
`GET /api/ipal/doctor` is added by `ipalKit` and answers 404 until the site has `IPAL_DOCTOR_TOKEN` (≥ 32 characters).
Then `Authorization: Bearer <token>`; counts only (`usersWithout2fa`, `pendingCookies`, `plugin`, `node`). With the same
Then `Authorization: Bearer <token>`; counts only (`usersWithout2fa`, `usersSetupClosed` = of those, blocked because the 2FA setup window has passed, `pendingCookies`, `plugin`, `node`). With the same
`IPAL_DOCTOR_TOKEN` in the doctor's environment, `--url` reads it. Off: `ipalKit({ doctor: false })`; adapt:
`ipalKit({ doctor: { tokenVar, access } })`.
@@ -42,6 +42,8 @@ description: Complete map of everything @intecion/ipal-kit provides — every ip
| `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 |
| `twoFactor.requireSetup` | on, `{ windowHours: 72 }` | an account without TOTP reaches nothing but the setup screen and `/api/setup-totp` (REST, GraphQL and the panel's data answer 403); it has `windowHours` from its creation or from an admin's reset, then it is blocked until an admin reopens setup. Adds the fields `totpSetupFrom` (date, written by the plugin) and `totpSetupStatus` (panel) to the 2FA collection, a dashboard notice and `POST /api/ipal/two-factor/reset`. Existing accounts get their window at the first start after the upgrade. Postgres/SQLite: migration; `generate:importmap` | `false` = the package's rule (API open until setup); `{ windowHours: 24 }`, `{ windowHours: false }` (no limit), `{ exempt: ({ user }) => … }` (a service account) |
| `twoFactor.resetAccess` | a staff admin | who may reset another account's TOTP / reopen its setup (the button on the account page, `POST /api/ipal/two-factor/reset`); the second factor is always required | `({ req }) => boolean` |
| `twoFactor.allowCollectionMismatch` | `false` | allows `collectionSlug` ≠ `admin.user` (panel users of the other collection then skip 2FA) | `true` only when you protect a second auth collection on purpose |
| `whiteLabel` | none | `admin.components.graphics.Logo/Icon` (`AdminLogo`/`AdminIcon`) from Site settings + vendor credit | omit / `false`; `true` = defaults |
| `whiteLabel.settingsSlug` | `'site-settings'` | global it reads the logo/name from | — |
@@ -33,6 +33,9 @@ Admin panel components from `@intecion/ipal-kit/admin` — the project does NOT
| `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`) |
| `TwoFactorStatusField` | `@intecion/ipal-kit/admin` | Server component, the `totpSetupStatus` UI field ipalKit adds to the 2FA collection (sidebar of an account): "Set up", "Not set up… until <date>" or "blocked", and for an administrator on someone else's account the reset / "Reopen setup" button. Wired by the plugin with `twoFactor.requireSetup`; needs `generate:importmap`. |
| `TwoFactorResetButton` | `@intecion/ipal-kit/admin` | Client button inside `TwoFactorStatusField`: `POST /api/ipal/two-factor/reset` `{ userId }`, then reloads the view. Props `{ kind: 'reset' \| 'reopen', userId }`. |
| `TwoFactorAlert` | `@intecion/ipal-kit/admin` | Server component on the dashboard (`beforeDashboard`), administrators only: accounts without two-step verification and how many are blocked. Wired by the plugin with `twoFactor.requireSetup`; renders nothing when every account has it. |
| `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 }` |
| `adminMetaForSite(site, resolved)`, `syncAdminMeta(payload, resolved, { nameField?, settingsSlug? })` | `@intecion/ipal-kit` | Site-name parts (suffix, description, siteName); `syncAdminMeta` writes them into the live config (onInit + Site settings afterChange, never throws) |
@@ -592,6 +595,7 @@ Server only (`pnpm payload run`); never import it from client code, the Payload
| `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`. |
| `twoFactorSetupState(req)`, `twoFactorSetupDeadline(req)` | `@intecion/ipal-kit` | Where an account stands with TOTP setup, from `{ payload, user }`: `'set-up'`, `'open'` (may set it up now), `'closed'` (the setup window has passed: blocked until an admin reopens it), `'exempt'` (`requireSetup.exempt`, or `requireSetup: false`), `'not-applicable'` (no user, another collection, 2FA off); and the moment setup closes (`Date`, or `null` without a window). Types: `TwoFactorSetupState`, `RequireSetupOptions`. |
| `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'`. |
+6
View File
@@ -234,6 +234,12 @@ the panel shows Site settings, Site integrations, Cookies, Form messages, the Fo
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`.
**Setup required** (`twoFactor.requireSetup`, default): an account without TOTP reaches only the setup screen; it
has 72 h from its creation (or an admin's "Reopen setup" on the account page), then it is blocked. So create an
account, hand over the password and have the owner set 2FA up at once. Postgres/SQLite: `pnpm payload
migrate:create` (field `totpSetupFrom`); `pnpm payload generate:importmap` (`TwoFactorStatusField`,
`TwoFactorAlert`). A service account that logs in with a password: `requireSetup: { exempt }`; an API key needs
nothing. One entity reachable without the code: `custom.ipal.secondFactor`.
- A second auth collection (`customers`, a client zone): set `admin: { user: 'users' }` in `buildConfig`; its
accounts pass none of the plugin's checks and no role counts for them (not even their own `roles: ['admin']`);
a field that grants rights is never writable at sign-up; use `adminOrSelfIn('<slug>')` in every auth collection; a second
+18
View File
@@ -380,6 +380,24 @@ gets `403` from the same addresses and from `POST /api/setup-totp`. The Coolify
strips `back`, can keep them (`twoFactor.safeBack: false` turns the plugin's check off).
2. `pnpm ipal:skills`.
**→ the release after that — 2FA setup required (PROGRAMISTA §6, item 66; security.md "Setup required") — required
with 2FA on:**
1. **Before upgrading a live site:** `pnpm exec ipal-doctor --url <site>` (doctor token) → accounts without 2FA.
Tell the owner: from the upgrade on, such an account can only set 2FA up, and has 72 hours for it; after that
an administrator must reopen setup on the account's page. Have them set it up now, or remove unused accounts.
Make sure at least one administrator has 2FA set up — otherwise nobody can reopen setup from the panel.
2. Update the package, `pnpm install`, `pnpm ipal:skills`, `pnpm payload generate:types`,
**`pnpm payload generate:importmap`** (new: `TwoFactorStatusField`, `TwoFactorAlert`; commit `importMap.js`).
3. Postgres/SQLite: `pnpm payload migrate:create` (adds `totpSetupFrom` to the 2FA collection), commit. MongoDB: nothing.
4. An integration that logs in with a password and has no TOTP: give it an API key, or
`twoFactor.requireSetup: { exempt: ({ user }) => user.email === '…' }`. `grep -rn "overrideAccess: false" src`:
a `user` fetched by id is refused for every account now — take it from `payload.auth({ headers })`.
5. `rm -rf .next`, build, redeploy on Coolify. Read the first lines of the log: `[ipal] 2FA: N existing account(s)
without two-step verification…` — pass that number to the owner.
**Check:** create a throwaway account → its token gets `403` from `/api/users/me`; in the panel it lands on the
setup screen with "Set up two-step verification by …"; after the code it is in. As an administrator open that
account → "Two-step verification: Set up." and the reset button; delete the account.
## 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
View File
@@ -675,6 +675,7 @@ Do one item at a time, build, check. Order by importance:
| 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" |
| 68 | **Unreleased — 2FA setup required** — an account that has not set 2FA up still reads data over the API with its password; or after the upgrade an account "can do nothing" / is blocked | Before upgrading: `ipal-doctor --url` → accounts without 2FA set it up or are removed; one admin must have 2FA. Then: update, `generate:types`, `generate:importmap` (`TwoFactorStatusField`, `TwoFactorAlert`), Postgres/SQLite `migrate:create` (`totpSetupFrom`), build, redeploy. Existing accounts get 72 h from the first start; blocked later → admin: account page → "Reopen setup". Password-login integrations: API key or `requireSetup.exempt`. `pnpm ipal:skills` | CHANGELOG "Unreleased — 2FA setup required", security.md "Setup required" |
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`.
+2 -2
View File
@@ -66,7 +66,7 @@ Added by `ipalKit` and **off until the site has `IPAL_DOCTOR_TOKEN`** (at least
returns counts only — never names, e-mails or values:
```json
{ "node": "v22.20.0", "pendingCookies": 0, "plugin": "1.15.0", "usersWithout2fa": 0 }
{ "node": "v22.20.0", "pendingCookies": 0, "plugin": "1.15.0", "usersSetupClosed": 0, "usersWithout2fa": 0 }
```
Turn off: `ipalKit({ doctor: false })`. Adapt: `ipalKit({ doctor: { tokenVar: 'MY_TOKEN', access: ({ req }) => isAdmin(req.user, req.payload) } })` (a logged-in staff admin may read it too; the second factor is checked for you — never test `req.user.roles` by hand, an account of another collection can carry the same value)
@@ -98,7 +98,7 @@ Turn off: `ipalKit({ doctor: false })`. Adapt: `ipalKit({ doctor: { tokenVar: 'M
| security | `security-headers` | error | `buildSecurityHeaders`; live: HSTS, nosniff, Referrer-Policy, Permissions-Policy, frame protection |
| | `powered-by` | error | `withSecurityConfig`; live: no `X-Powered-By` on `/` and the admin |
| | `csp` | warning / info | CSP on the site and the admin; report-only is info, a warning after 4 weeks (`seen`) |
| | `2fa` | error | `twoFactor: { plugin: payloadTotp }` + the package; deep: 0 users without TOTP |
| | `2fa` | error | `twoFactor: { plugin: payloadTotp }` + the package; deep: 0 users without TOTP (the message says how many of them are blocked because their setup window has passed); warning: `twoFactor.requireSetup: false`; info: no setup window (`windowHours: false`) |
| | `cookie-scanner` | error / warning / info | `cookieScanner` on (with `crawl`, else info); deep: nothing waits for approval (warning) |
| admin | `admin-meta` | warning | ipal-kit ≥ 1.14.5, no `adminMeta: false` / `agency: false`; live: the admin `og:image` is `/api/ipal/admin-og` |
| | `admin-noindex` | error | (live) the admin login page is noindex |
+83 -11
View File
@@ -425,17 +425,79 @@ that session's cookie (images from `media`) are refused, so an editor who typed
sees broken images on the site until the code is entered or they log out.
An account of the 2FA collection passes when it logged in with **password and code**, or uses an **API key**
(`auth.useAPIKey`), or has **not set TOTP up yet** (the setup screen needs that; the package behaves the same).
Everything else is refused, including a user object the check does not recognise. Accounts of other auth
(`auth.useAPIKey`). An account that has **not set TOTP up yet** is refused as well ("Setup required" below; the
package alone lets it through). Everything else is refused, including a user object the check does not recognise. Accounts of other auth
collections, anonymous visitors, bearer-token routes (`/api/ipal/doctor`, the cookie-crawl callback, MCP) and
the Local API with `overrideAccess: true` (the default) are not affected.
> **Until an account has set TOTP up, its password alone opens everything its role allows** — Site
> integrations with the SMTP password included. Enforced setup is a redirect in the panel; over the API such an
> account is an ordinary logged-in account (it has to be, or it could not set TOTP up). So: **set 2FA up right
> after an account is created** — create the account, log in as it, scan the code, in one sitting — and never
> leave an invited account waiting. `ipal-doctor --url` reports the number of accounts without 2FA
> (`2fa`, deep check); it must be 0.
### Setup required (`twoFactor.requireSetup`, on by default)
An account that has **not set TOTP up yet** reaches nothing at the access level — REST, GraphQL, the panel's
data, the plugin's endpoints — until it has. It gets the setup screen and `POST /api/setup-totp`, nothing else.
The 2FA package alone only redirects such an account inside the panel; over the API its password would open
everything its role allows.
**The setup window.** An account has **72 hours** to set TOTP up, counted from its creation or from the last
reset by an administrator. After that it is **blocked**: setup is refused too, until an administrator reopens
it. Without the window, whoever learns the password of an account that never set TOTP up could enrol their own
authenticator at any time; with it, that is possible only in the first days of the account.
| Situation | What happens |
|---|---|
| New account (also the first admin of a fresh site) | logs in → setup screen with the notice "Set up two-step verification by <date>…" → after the code, the panel |
| Not set up within the window | login still works, every request answers 403, the setup screen says the time has passed and to ask an administrator |
| Administrator reopens setup / resets a lost phone | the account's page in the panel → **Two-step verification** (sidebar) → "Reopen setup" / "Reset two-step verification"; or `POST /api/ipal/two-factor/reset` with `{ "userId": "…" }`. A new window starts |
| Administrators' overview | a notice on the dashboard: accounts without two-step verification, and how many of them are blocked; `ipal-doctor --url` reports the same as an error |
| API key (`auth.useAPIKey`) | passes, whatever the setup state |
| Seeds, scripts, the Local API with `overrideAccess` (the default) | not affected |
| Bearer-token routes (`/api/ipal/doctor`, the cookie-crawl callback), MCP | not affected (no user) |
| `twoFactor: false` | none of this exists |
**Accounts that existed before this mode** (an upgrade): their window starts at the **first start of the site
after the upgrade**, not at their creation date, so nobody is blocked the moment a site upgrades. The server log
says how many there are: `[ipal] 2FA: N existing account(s) without two-step verification. They have 72 h from
now to set it up…`. From that moment they can only set TOTP up; after 72 hours they are blocked until an
administrator reopens setup. **Before upgrading a live site, run `pnpm exec ipal-doctor --url <site>`** (accounts
without 2FA) and have those accounts set TOTP up, or remove the ones nobody uses.
```ts
twoFactor: {
issuer: 'Company Name',
plugin: payloadTotp,
// requireSetup: { windowHours: 24 }, // another window
// requireSetup: { windowHours: false }, // no time limit (0 works too): locked until set up, never blocked
// requireSetup: { exempt: ({ user }) => user.email === 'integration@example.com' }, // a service account that logs in with a password, on purpose
// requireSetup: false, // the 2FA package's rule: redirect in the panel, API open until setup
// resetAccess: ({ req }) => isAdmin(req.user, req.payload), // who may reset / reopen (default: a staff admin; the second factor is always required)
}
```
- **Data.** The mode adds a date field `totpSetupFrom` (hidden, written by the plugin only) and a panel-only field
`totpSetupStatus` to the 2FA collection. MongoDB: nothing to do. **Postgres / SQLite: create and run a
migration** (`pnpm payload migrate:create`); until it has run, the log shows `[ipal] 2FA: could not start the
setup window…` and existing accounts have no time limit yet.
- **Import map.** The status field and the dashboard notice are admin components: `pnpm payload
generate:importmap` after upgrading (`TwoFactorStatusField`, `TwoFactorAlert`).
- **Per collection or global:** the opt-out below (`custom.ipal.secondFactor`) also lets an account without TOTP
in, because it takes the entity out of the second-factor check altogether.
- **Needs** ipal-kit's check (`twoFactor.guard`, on by default); with `guard: false` the mode is off.
- **Project code** that calls `payload.find({ …, user, overrideAccess: false })` with a user fetched by id: refused
for every account of the 2FA collection now — before, only for accounts that had TOTP set up. Take the user from
`payload.auth({ headers })`.
- **In your own code:** `twoFactorSetupState(req)` → `'set-up' | 'open' | 'closed' | 'exempt' | 'not-applicable'`,
`twoFactorSetupDeadline(req)` → `Date | null`.
- **Texts** (English and Polish; override in `i18n.translations.<lang>.ipal`): `twoFactorSetupDeadline`,
`twoFactorSetupRequired`, `twoFactorSetupClosed`, `twoFactorStatus*`, `twoFactorReopen`, `twoFactorReset*`,
`twoFactorAlert*`.
**What it does not do.** Inside the window, someone who knows the password of an account that has not set TOTP up
can still set it up with their own authenticator. The real owner then cannot ("already set") and has to ask an
administrator — the takeover is visible, and the window keeps it to the first days. So still: **create the
account, hand over the password, and have the owner set 2FA up at once.**
**Check:** create an account, log in over the API with its password → `403` from `/api/users/me` and
`/api/globals/site-settings`; open the panel as that account → the setup screen with the notice; enter the code →
the panel. As an administrator open the account → "Two-step verification: Set up."
**Verify attempts are limited** (`twoFactor.verifyLimit`). The package checks the code and never counts tries;
a six-digit code has about three right answers in a million, so whoever held the password could guess. ipalKit
@@ -449,7 +511,8 @@ it off (a limiter in front of the site).
**What is NOT covered — the complete list.** (1) Anonymous requests: the access function decides. (2) Accounts
of other auth collections: 2FA is about one collection; such an account is not staff unless its collection is in
`access.staffCollections`, and then it is staff **without** a second factor (warning in the log at start).
(3) API keys. (4) An account that has not set TOTP up yet. (5) Entities the project opted out (below).
(3) API keys. (4) An account that has not set TOTP up yet — only with `requireSetup: false` or when the project
exempts it ("Setup required" below); by default it is refused. (5) Entities the project opted out (below).
(6) `access.admin`. (7) Endpoints that are not the plugin's or the 2FA package's: your own endpoints and other
plugins' endpoints check whatever they check — add `secondFactorPassed(req)` to yours. (8) Server code using the
Local API with `overrideAccess: true`. Nothing is skipped by slug, name or prefix, and a user object the check
@@ -669,7 +732,8 @@ twoFactor: false // ONLY when the project really cannot use 2FA (rare)
### How it works for the user
1. Logs in (email + password)
2. On first login: redirected to TOTP Setup (`/admin/setup-totp?back=%2Fadmin`, QR + secret)
2. On first login: redirected to TOTP Setup (`/admin/setup-totp?back=%2Fadmin`, QR + secret), with a notice
saying until when it has to be done. Until it is done the account can do nothing else ("Setup required")
3. Scans the QR with an app (Google Authenticator, Authy, 1Password, Microsoft Authenticator)
4. Enters the code → 2FA is active, back to the page from `back`
5. Next logins: email + password + TOTP code (`/admin/verify-totp?back=…`)
@@ -680,7 +744,12 @@ show the QR code. `back=null` or a page that keeps reloading means the import ma
### Resetting 2FA (admin)
An admin can reset another user's 2FA (when they lose their phone) — through
An admin resets another user's 2FA (a lost phone) or reopens setup for a blocked account on that account's page
in the panel: **Two-step verification** in the sidebar → "Reset two-step verification" / "Reopen setup". Behind
it: `POST /api/ipal/two-factor/reset` `{ userId }` — a staff admin who has passed the second factor
(`twoFactor.resetAccess` changes who). The account must set TOTP up again within a new window.
The 2FA package has its own reset, off unless you turn it on — through
`adminManageAccess` in the @clocklimited configuration. ipalKit passes it only `collection`,
`forceSetup` and `issuer`; pass other options by wrapping the injected factory:
`plugin: (opts) => payloadTotp({ ...opts, adminManageAccess: ({ req }) => isAdmin(req.user, req.payload) })`.
@@ -759,6 +828,9 @@ size while reading, content signature, container and macro checks, an optional `
`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.
- **Setup required:** `twoFactor.requireSetup: false` (off), `{ windowHours }` (another window, `false` / `0` = none),
`{ exempt }` (a service account), `twoFactor.resetAccess` (who reopens); exported: `twoFactorSetupState`,
`twoFactorSetupDeadline`.
- **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.
@@ -51,7 +51,7 @@ Ask only when the brief leaves a business question open (e.g. "do posts have aut
4. **An auth collection for visitors** (`auth: true`: customers, members) only when the client requires it
(AGENT.md §5 "A second auth collection"): `admin: { user: 'users' }` in `buildConfig`, `access` with
`adminOrSelfIn('<slug>')` for read / update and an explicit `create`, never in `access.staffCollections`.
Its accounts pass none of the plugin's staff checks. Check: its token → `403` from
Its accounts pass none of the plugin's staff checks, and 2FA (setup required included) does not apply to them. Check: its token → `403` from
`/api/globals/site-integrations` and `/api/form-submissions`.
5. `pnpm generate:types`, `pnpm payload generate:importmap`.
6. Postgres with migrations → `pnpm payload migrate:create`.
@@ -37,6 +37,10 @@ through this procedure. Ask only when you are missing something you cannot get y
| the 2FA code screen answers "Too many codes were tried…" (`429` from `/api/verify-totp`) | more than 5 verify attempts for that account in 10 minutes (`twoFactor.verifyLimit`); repeated lines `[ipal] 2FA: too many verify attempts` in the log without the owner trying = someone has the password | wait for the window, enter the current code once; unexplained attempts: change that account's password. Tests that log in often: `verifyLimit: { max: … }` for that environment |
| `isAdmin(req.user)` says `false` for a real administrator on the server, in a process that loads two Payload configs (tests, a multi-site script) | a call without a source counts only collections that are staff in **every** config of the process | pass the source: `isAdmin(req.user, req.payload)` — with it each config gets its own answer |
| `isAdmin(user)` / `isEditor(user)` is always `false` in a client component or in `proxy.ts` | the staff collections are not known there (no config in the browser bundle / middleware), and the predicates fail closed | `isAdmin(user, config)` with `useConfig()`; in middleware `isAdmin(user, { staffCollections: ['users'] })` |
| an account logs in but every page and request answers 403 / the setup screen says "The time to set up two-step verification has passed" | 2FA setup required: the account did not set TOTP up within the window (72 h from its creation, an admin's reset, or the first start after the upgrade) | an administrator opens the account in the panel → Two-step verification → "Reopen setup" (or `POST /api/ipal/two-factor/reset` `{ userId }`); the only admin is blocked: a script with the Local API — `payload.update({ collection: 'users', id, data: { totpSetupFrom: new Date().toISOString() } })` (`pnpm payload run`), then log in and set TOTP up |
| a new account gets `403` from the API although its role allows the request | 2FA setup required: until TOTP is set up the account reaches only the setup screen | set TOTP up (log in to the panel); an integration: use an API key, or `twoFactor.requireSetup.exempt` |
| log: `[ipal] 2FA: could not start the setup window for existing accounts` | Postgres/SQLite: the migration that adds `totpSetupFrom` has not run | `pnpm payload migrate:create`, commit, deploy (migrations run in the Coolify pre-deploy command) |
| "Two-step verification" is missing on the account page / the dashboard shows a missing component | the import map is stale | `pnpm payload generate:importmap`, commit `importMap.js`, `rm -rf .next`, redeploy |
| startup: `[ipal] twoFactor: the injected 2FA plugin did not add the totpSecret field / hasTotp field / totp auth strategy` | the installed `@clocklimited/payload-2fa` is not a version ipal-kit's second-factor check recognises (tested: 3.0.0-beta.1 and beta.7), or a custom factory was injected | install a supported version; stop-gap only: `twoFactor.guard: false` (the plugin's own data is then not covered by 2FA — security.md) |
| own route or script gets `403` / "not allowed" on `form-submissions`, `forms`, a settings global with `overrideAccess: false`, although the user is an admin | the `user` was fetched by id and passed by hand: it does not carry how the account logged in, so the second-factor check refuses it | take the user from `payload.auth({ headers })` (it sets `collection` and how the account logged in), or (server-only code that needs no access check) leave `overrideAccess` at its default; a hand-built user needs at least `collection: 'users'` for its role to count |
| an account of a second auth collection (`customers`) gets `403` from a settings global, submissions, `/api/ipal/*`, `/api/setup-totp`, or `isAdmin` / `adminOnly` say no although it has `roles: ['admin']`, after an upgrade | by design since 1.16.4: roles and staff checks count only for accounts of a staff collection | write the one rule it needs (`formSubmissionOverrides`, `globalOverrides`, `collectionOverrides`); a second STAFF collection: `access.staffCollections` (access.md "Who is staff") |
@@ -50,7 +50,7 @@ Existing client sites are not gated on it; run it there as a report only.
## The status endpoint
`GET /api/ipal/doctor` is added by `ipalKit` and answers 404 until the site has `IPAL_DOCTOR_TOKEN` (≥ 32 characters).
Then `Authorization: Bearer <token>`; counts only (`usersWithout2fa`, `pendingCookies`, `plugin`, `node`). With the same
Then `Authorization: Bearer <token>`; counts only (`usersWithout2fa`, `usersSetupClosed` = of those, blocked because the 2FA setup window has passed, `pendingCookies`, `plugin`, `node`). With the same
`IPAL_DOCTOR_TOKEN` in the doctor's environment, `--url` reads it. Off: `ipalKit({ doctor: false })`; adapt:
`ipalKit({ doctor: { tokenVar, access } })`.
@@ -42,6 +42,8 @@ description: Complete map of everything @intecion/ipal-kit provides — every ip
| `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 |
| `twoFactor.requireSetup` | on, `{ windowHours: 72 }` | an account without TOTP reaches nothing but the setup screen and `/api/setup-totp` (REST, GraphQL and the panel's data answer 403); it has `windowHours` from its creation or from an admin's reset, then it is blocked until an admin reopens setup. Adds the fields `totpSetupFrom` (date, written by the plugin) and `totpSetupStatus` (panel) to the 2FA collection, a dashboard notice and `POST /api/ipal/two-factor/reset`. Existing accounts get their window at the first start after the upgrade. Postgres/SQLite: migration; `generate:importmap` | `false` = the package's rule (API open until setup); `{ windowHours: 24 }`, `{ windowHours: false }` (no limit), `{ exempt: ({ user }) => … }` (a service account) |
| `twoFactor.resetAccess` | a staff admin | who may reset another account's TOTP / reopen its setup (the button on the account page, `POST /api/ipal/two-factor/reset`); the second factor is always required | `({ req }) => boolean` |
| `twoFactor.allowCollectionMismatch` | `false` | allows `collectionSlug` ≠ `admin.user` (panel users of the other collection then skip 2FA) | `true` only when you protect a second auth collection on purpose |
| `whiteLabel` | none | `admin.components.graphics.Logo/Icon` (`AdminLogo`/`AdminIcon`) from Site settings + vendor credit | omit / `false`; `true` = defaults |
| `whiteLabel.settingsSlug` | `'site-settings'` | global it reads the logo/name from | — |
@@ -33,6 +33,9 @@ Admin panel components from `@intecion/ipal-kit/admin` — the project does NOT
| `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`) |
| `TwoFactorStatusField` | `@intecion/ipal-kit/admin` | Server component, the `totpSetupStatus` UI field ipalKit adds to the 2FA collection (sidebar of an account): "Set up", "Not set up… until <date>" or "blocked", and for an administrator on someone else's account the reset / "Reopen setup" button. Wired by the plugin with `twoFactor.requireSetup`; needs `generate:importmap`. |
| `TwoFactorResetButton` | `@intecion/ipal-kit/admin` | Client button inside `TwoFactorStatusField`: `POST /api/ipal/two-factor/reset` `{ userId }`, then reloads the view. Props `{ kind: 'reset' \| 'reopen', userId }`. |
| `TwoFactorAlert` | `@intecion/ipal-kit/admin` | Server component on the dashboard (`beforeDashboard`), administrators only: accounts without two-step verification and how many are blocked. Wired by the plugin with `twoFactor.requireSetup`; renders nothing when every account has it. |
| `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 }` |
| `adminMetaForSite(site, resolved)`, `syncAdminMeta(payload, resolved, { nameField?, settingsSlug? })` | `@intecion/ipal-kit` | Site-name parts (suffix, description, siteName); `syncAdminMeta` writes them into the live config (onInit + Site settings afterChange, never throws) |
@@ -592,6 +595,7 @@ Server only (`pnpm payload run`); never import it from client code, the Payload
| `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`. |
| `twoFactorSetupState(req)`, `twoFactorSetupDeadline(req)` | `@intecion/ipal-kit` | Where an account stands with TOTP setup, from `{ payload, user }`: `'set-up'`, `'open'` (may set it up now), `'closed'` (the setup window has passed: blocked until an admin reopens it), `'exempt'` (`requireSetup.exempt`, or `requireSetup: false`), `'not-applicable'` (no user, another collection, 2FA off); and the moment setup closes (`Date`, or `null` without a window). Types: `TwoFactorSetupState`, `RequireSetupOptions`. |
| `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'`. |
@@ -234,6 +234,12 @@ the panel shows Site settings, Site integrations, Cookies, Form messages, the Fo
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`.
**Setup required** (`twoFactor.requireSetup`, default): an account without TOTP reaches only the setup screen; it
has 72 h from its creation (or an admin's "Reopen setup" on the account page), then it is blocked. So create an
account, hand over the password and have the owner set 2FA up at once. Postgres/SQLite: `pnpm payload
migrate:create` (field `totpSetupFrom`); `pnpm payload generate:importmap` (`TwoFactorStatusField`,
`TwoFactorAlert`). A service account that logs in with a password: `requireSetup: { exempt }`; an API key needs
nothing. One entity reachable without the code: `custom.ipal.secondFactor`.
- A second auth collection (`customers`, a client zone): set `admin: { user: 'users' }` in `buildConfig`; its
accounts pass none of the plugin's checks and no role counts for them (not even their own `roles: ['admin']`);
a field that grants rights is never writable at sign-up; use `adminOrSelfIn('<slug>')` in every auth collection; a second
@@ -380,6 +380,24 @@ gets `403` from the same addresses and from `POST /api/setup-totp`. The Coolify
strips `back`, can keep them (`twoFactor.safeBack: false` turns the plugin's check off).
2. `pnpm ipal:skills`.
**→ the release after that — 2FA setup required (PROGRAMISTA §6, item 66; security.md "Setup required") — required
with 2FA on:**
1. **Before upgrading a live site:** `pnpm exec ipal-doctor --url <site>` (doctor token) → accounts without 2FA.
Tell the owner: from the upgrade on, such an account can only set 2FA up, and has 72 hours for it; after that
an administrator must reopen setup on the account's page. Have them set it up now, or remove unused accounts.
Make sure at least one administrator has 2FA set up — otherwise nobody can reopen setup from the panel.
2. Update the package, `pnpm install`, `pnpm ipal:skills`, `pnpm payload generate:types`,
**`pnpm payload generate:importmap`** (new: `TwoFactorStatusField`, `TwoFactorAlert`; commit `importMap.js`).
3. Postgres/SQLite: `pnpm payload migrate:create` (adds `totpSetupFrom` to the 2FA collection), commit. MongoDB: nothing.
4. An integration that logs in with a password and has no TOTP: give it an API key, or
`twoFactor.requireSetup: { exempt: ({ user }) => user.email === '…' }`. `grep -rn "overrideAccess: false" src`:
a `user` fetched by id is refused for every account now — take it from `payload.auth({ headers })`.
5. `rm -rf .next`, build, redeploy on Coolify. Read the first lines of the log: `[ipal] 2FA: N existing account(s)
without two-step verification…` — pass that number to the owner.
**Check:** create a throwaway account → its token gets `403` from `/api/users/me`; in the panel it lands on the
setup screen with "Set up two-step verification by …"; after the code it is in. As an administrator open that
account → "Two-step verification: Set up." and the reset button; delete the account.
## 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):
+121
View File
@@ -0,0 +1,121 @@
import { type APIRequestContext, expect, type Page, test } from '@playwright/test'
import { totp } from './totp'
/**
* "2FA setup required" in a real browser: an account that has not set two-step verification up sees only the setup
* screen and gets nothing from the API; after the code it is in. Covers the first admin of a fresh site (only when
* the database has no users yet — run this file before e2e/create-test-admin.ts for that), a new editor, and the
* administrator's reset on the account page.
* E2E_BASE_URL=http://localhost:3217 pnpm exec playwright test e2e/two-factor-setup.spec.ts
*/
test.describe.configure({ mode: 'serial' })
const stamp = Date.now()
const OWNER = { email: `e2e-owner-${stamp}@example.com`, password: `owner-${stamp}-Hk29dLq` }
const EDITOR = { email: `e2e-editor-${stamp}@example.com`, password: `editor-${stamp}-Pz71mWx` }
/** The admin the later tests act as: the owner made in the first test, else the smoke-test admin. */
let admin: { email: string; password: string; secret: string } | null =
process.env.E2E_ADMIN_EMAIL && process.env.E2E_ADMIN_PASSWORD && process.env.E2E_TOTP_SECRET
? { email: process.env.E2E_ADMIN_EMAIL, password: process.env.E2E_ADMIN_PASSWORD, secret: process.env.E2E_TOTP_SECRET }
: null
let editorId: string | undefined
async function typeCode(page: Page, secret: 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(totp(secret))
}
async function signIn(page: Page, who: { email: string; password: string }) {
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')
}
/** A fully logged-in API session (password, then the code). Payload takes the cookie only with the site's Origin. */
async function adminApi(playwright: { request: { newContext: (o: object) => Promise<APIRequestContext> } }, baseURL: string) {
const api = await playwright.request.newContext({ baseURL, extraHTTPHeaders: { origin: baseURL } })
expect((await api.post('/api/users/login', { data: { email: admin!.email, password: admin!.password } })).status()).toBe(200)
expect((await (await api.post('/api/verify-totp', { data: { token: totp(admin!.secret) } })).json()).ok).toBe(true)
return api
}
test('first admin of a fresh site: created, sent to 2FA setup, in after the code', async ({ baseURL, page }) => {
// With users in the database this address leads to the login screen instead.
await page.goto('/admin/create-first-user')
const firstUserForm = await page.locator('#field-confirm-password').waitFor({ timeout: 10_000 }).then(() => true, () => false)
test.skip(!firstUserForm, 'the database already has users')
// Type like a person, once the form is live: values filled in before hydration are not in the form's state.
await page.waitForLoadState('networkidle')
await page.locator('#field-email').pressSequentially(OWNER.email)
await page.locator('#field-password').pressSequentially(OWNER.password)
await page.locator('#field-confirm-password').pressSequentially(OWNER.password)
const registered = page.waitForResponse((r) => r.url().includes('/first-register') && r.request().method() === 'POST')
await page.click('.form-submit button')
expect((await registered).status()).toBe(200)
await page.waitForURL(/setup-totp/)
await expect(page.locator('#ipal-two-factor-notice')).toContainText(/Ustaw weryfikację dwuetapową do|Set up two-step verification by/)
// nothing but setup, over the API too
for (const path of ['/api/globals/site-integrations', '/api/users', '/api/pages']) {
expect((await page.request.get(path, { headers: { origin: baseURL! } })).status(), path).toBe(403)
}
const secret = await page.locator('input[name="secret"]').inputValue()
await typeCode(page, secret)
await expect(page).toHaveTitle(/Dashboard|Pulpit/, { timeout: 20_000 })
expect((await page.request.get('/api/globals/site-integrations', { headers: { origin: baseURL! } })).status()).toBe(200)
admin = { ...OWNER, secret }
})
test('a new editor: setup screen with the deadline, nothing else, in after the code', async ({ baseURL, page, playwright }) => {
test.skip(!admin, 'no admin to create the editor with (set E2E_* or run on a fresh database)')
const api = await adminApi(playwright, baseURL!)
const created = await api.post('/api/users', { data: { ...EDITOR, roles: ['editor'] } })
expect(created.status()).toBe(201)
editorId = String((await created.json()).doc.id)
await api.dispose()
await signIn(page, EDITOR)
await page.waitForURL(/setup-totp/)
await expect(page.locator('#ipal-two-factor-notice')).toContainText(/Ustaw weryfikację dwuetapową do|Set up two-step verification by/)
for (const path of ['/api/pages', '/api/form-submissions', '/api/globals/site-settings', `/api/users/${editorId}`]) {
expect((await page.request.get(path, { headers: { origin: baseURL! } })).status(), path).toBe(403)
}
// going elsewhere in the panel leads back to setup
await page.goto('/admin/collections/pages')
await page.waitForURL(/setup-totp/)
const secret = await page.locator('input[name="secret"]').inputValue()
await typeCode(page, secret)
// back where it wanted to go, and the data opens
await page.waitForURL(/\/admin\/collections\/pages/, { timeout: 20_000 })
expect((await page.request.get('/api/pages', { headers: { origin: baseURL! } })).status()).toBe(200)
})
test('the administrator sees the status on the account and resets it; the editor must set it up again', async ({ baseURL, page, playwright }) => {
test.skip(!admin || !editorId, 'needs the editor from the previous test')
await signIn(page, admin!)
await page.waitForURL(/verify-totp|\/admin(\?|$)/, { waitUntil: 'commit' })
if (page.url().includes('verify-totp')) {await typeCode(page, admin!.secret)}
await expect(page).toHaveTitle(/Dashboard|Pulpit/, { timeout: 20_000 })
await page.goto(`/admin/collections/users/${editorId}`)
const status = page.locator('#ipal-two-factor-status')
await expect(status).toContainText(/Ustawiona\.|Set up\./)
page.once('dialog', (dialog) => dialog.accept())
await status.getByRole('button').click()
await expect(status).toContainText(/Nieustawiona\. Konto może ją ustawić do|Not set up\. The account can set it up until/, { timeout: 15_000 })
// the editor's password alone opens nothing again
const editor = await playwright.request.newContext({ baseURL, extraHTTPHeaders: { origin: baseURL! } })
expect((await editor.post('/api/users/login', { data: EDITOR })).status()).toBe(200)
expect((await editor.get('/api/pages')).status()).toBe(403)
await editor.dispose()
// clean up the account this file made
const api = await adminApi(playwright, baseURL!)
expect((await api.delete(`/api/users/${editorId}`)).status()).toBe(200)
await api.dispose()
})
@@ -29,6 +29,7 @@ import { MetaDescriptionCheck as MetaDescriptionCheck_7568fe47d582ff15ce85d2e187
import { MetaImageComponent as MetaImageComponent_a8a977ebc872c5d5ea7ee689724c0860 } from '@payloadcms/plugin-seo/client'
import { PreviewComponent as PreviewComponent_a8a977ebc872c5d5ea7ee689724c0860 } from '@payloadcms/plugin-seo/client'
import { TOTPField as TOTPField_3eb2cc20d1a2569c2ccbafcee15bd128 } from '@clocklimited/payload-2fa/rsc'
import { TwoFactorStatusField as TwoFactorStatusField_7568fe47d582ff15ce85d2e1873c2c23 } from '@intecion/ipal-kit/admin'
import { CookieScanButton as CookieScanButton_7568fe47d582ff15ce85d2e1873c2c23 } from '@intecion/ipal-kit/admin'
import { FaviconCheck as FaviconCheck_7568fe47d582ff15ce85d2e1873c2c23 } from '@intecion/ipal-kit/admin'
import { IntegrationStatusBanner as IntegrationStatusBanner_7568fe47d582ff15ce85d2e1873c2c23 } from '@intecion/ipal-kit/admin'
@@ -39,6 +40,7 @@ import { CookieSiteCheckTab as CookieSiteCheckTab_7568fe47d582ff15ce85d2e1873c2c
import { AdminIcon as AdminIcon_7568fe47d582ff15ce85d2e1873c2c23 } from '@intecion/ipal-kit/admin'
import { AdminLogo as AdminLogo_7568fe47d582ff15ce85d2e1873c2c23 } from '@intecion/ipal-kit/admin'
import { IntecionCredit as IntecionCredit_7568fe47d582ff15ce85d2e1873c2c23 } from '@intecion/ipal-kit/admin'
import { TwoFactorAlert as TwoFactorAlert_7568fe47d582ff15ce85d2e1873c2c23 } from '@intecion/ipal-kit/admin'
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'
@@ -82,6 +84,7 @@ export const importMap = {
"@payloadcms/plugin-seo/client#MetaImageComponent": MetaImageComponent_a8a977ebc872c5d5ea7ee689724c0860,
"@payloadcms/plugin-seo/client#PreviewComponent": PreviewComponent_a8a977ebc872c5d5ea7ee689724c0860,
"@clocklimited/payload-2fa/rsc#TOTPField": TOTPField_3eb2cc20d1a2569c2ccbafcee15bd128,
"@intecion/ipal-kit/admin#TwoFactorStatusField": TwoFactorStatusField_7568fe47d582ff15ce85d2e1873c2c23,
"@intecion/ipal-kit/admin#CookieScanButton": CookieScanButton_7568fe47d582ff15ce85d2e1873c2c23,
"@intecion/ipal-kit/admin#FaviconCheck": FaviconCheck_7568fe47d582ff15ce85d2e1873c2c23,
"@intecion/ipal-kit/admin#IntegrationStatusBanner": IntegrationStatusBanner_7568fe47d582ff15ce85d2e1873c2c23,
@@ -92,6 +95,7 @@ export const importMap = {
"@intecion/ipal-kit/admin#AdminIcon": AdminIcon_7568fe47d582ff15ce85d2e1873c2c23,
"@intecion/ipal-kit/admin#AdminLogo": AdminLogo_7568fe47d582ff15ce85d2e1873c2c23,
"@intecion/ipal-kit/admin#IntecionCredit": IntecionCredit_7568fe47d582ff15ce85d2e1873c2c23,
"@intecion/ipal-kit/admin#TwoFactorAlert": TwoFactorAlert_7568fe47d582ff15ce85d2e1873c2c23,
"@intecion/ipal-kit/admin#CookieCrawlAlert": CookieCrawlAlert_7568fe47d582ff15ce85d2e1873c2c23,
"@intecion/ipal-kit/admin#IntegrationAlerts": IntegrationAlerts_7568fe47d582ff15ce85d2e1873c2c23,
"@intecion/ipal-kit/admin#TotpRedirectProvider": TotpRedirectProvider_7568fe47d582ff15ce85d2e1873c2c23,
+2
View File
@@ -1292,6 +1292,7 @@ export interface User {
id: string;
totpSecret?: string | null;
hasTotp?: boolean | null;
totpSetupFrom?: string | null;
/**
* Administrators manage everything; editors manage content.
*/
@@ -2076,6 +2077,7 @@ export interface MediaSelect<T extends boolean = true> {
export interface UsersSelect<T extends boolean = true> {
totpSecret?: T;
hasTotp?: T;
totpSetupFrom?: T;
roles?: T;
updatedAt?: T;
createdAt?: T;
+1
View File
@@ -60,6 +60,7 @@ export const DESCRIPTIONS = {
'README.md': 'how to run the reference site and what is where',
'docs/DEPLOY.md': 'the Coolify runbook: local check, app settings, MongoDB resource, env, targeted seeds, DNS, rollback',
'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/two-factor-setup.spec.ts': 'browser check of "2FA setup required": the first admin of a fresh site, a new editor, the administrator\'s reset on the account page',
'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',
+3
View File
@@ -22,6 +22,9 @@ 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 { TwoFactorAlert } from '../modules/security/totp/TwoFactorAlert.js'
export { TwoFactorResetButton } from '../modules/security/totp/TwoFactorResetButton.js'
export { TwoFactorStatusField } from '../modules/security/totp/TwoFactorStatusField.js'
export { FaviconCheck } from '../modules/seo/FaviconCheck.js'
export type { FaviconCheckProps } from '../modules/seo/FaviconCheck.js'
export { MetaDescriptionCheck } from '../modules/seo/MetaDescriptionCheck.js'
+3 -1
View File
@@ -330,7 +330,9 @@ export type { BuildSecurityHeadersArgs, SecurityHeader } from './modules/securit
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 { requireSecondFactor, secondFactorPassed, twoFactorSetupDeadline, twoFactorSetupState } from './modules/security/totp/secondFactor.js'
export type { TwoFactorSetupState } from './modules/security/totp/secondFactor.js'
export type { RequireSetupOptions } from './modules/security/totp/setupRequired.js'
export { TOTP_TEXTS, TOTP_VIEW_TITLE } from './modules/security/totp/totpTexts.js'
export type { VerifyLimitOptions } from './modules/security/totp/verifyLimit.js'
export type { OgImage } from './modules/seo/buildMetadata.js'
+38
View File
@@ -3,9 +3,47 @@ import { defineTexts } from '../define.js'
/** Admin component texts — two-step verification (2FA). Placeholders use Payload's {{name}} syntax. */
export const securityTexts = defineTexts({
en: {
twoFactorAlertBlocked: 'Blocked because the time for setup has passed: {{count}}. Open the account in the user list and choose "Reopen setup".',
twoFactorAlertLink: 'Open the user list',
twoFactorAlertPending: 'Accounts without two-step verification: {{count}}. Until it is set up, such an account cannot use the panel.',
twoFactorAlertTitle: 'Two-step verification',
twoFactorReopen: 'Reopen setup',
twoFactorReset: 'Reset two-step verification',
twoFactorResetConfirm: 'This account will have to set up two-step verification again before it can use the panel. Continue?',
twoFactorResetDone: 'Done. The account can set up two-step verification now.',
twoFactorResetFailed: 'Could not reset two-step verification. Try again.',
twoFactorResetForbidden: 'Only an administrator who is fully logged in can do this.',
twoFactorSetupClosed: 'The time to set up two-step verification has passed, so this account is blocked. Ask an administrator to reopen setup for it.',
twoFactorSetupDeadline: 'Set up two-step verification by {{date}}. Until then you cannot use the panel.',
twoFactorSetupRequired: 'Set up two-step verification to use the panel.',
twoFactorStatusClosed: 'Not set up. The time for it passed on {{date}}, so the account is blocked.',
twoFactorStatusExempt: 'Not set up. This account is exempt in the site configuration.',
twoFactorStatusLabel: 'Two-step verification',
twoFactorStatusOn: 'Set up.',
twoFactorStatusOpen: 'Not set up. The account can set it up until {{date}}.',
twoFactorStatusOpenNoLimit: 'Not set up yet. The account cannot use the panel until it is.',
twoFactorTooManyAttempts: 'Too many codes were tried for this account. Wait {{minutes}} min, then enter the current code from your app.',
},
pl: {
twoFactorAlertBlocked: 'Zablokowane, bo minął czas na konfigurację: {{count}}. Otwórz konto na liście użytkowników i wybierz „Otwórz konfigurację ponownie”.',
twoFactorAlertLink: 'Otwórz listę użytkowników',
twoFactorAlertPending: 'Konta bez weryfikacji dwuetapowej: {{count}}. Dopóki nie zostanie ustawiona, takie konto nie może korzystać z panelu.',
twoFactorAlertTitle: 'Weryfikacja dwuetapowa',
twoFactorReopen: 'Otwórz konfigurację ponownie',
twoFactorReset: 'Zresetuj weryfikację dwuetapową',
twoFactorResetConfirm: 'To konto będzie musiało ponownie ustawić weryfikację dwuetapową, zanim skorzysta z panelu. Kontynuować?',
twoFactorResetDone: 'Gotowe. Konto może teraz ustawić weryfikację dwuetapową.',
twoFactorResetFailed: 'Nie udało się zresetować weryfikacji dwuetapowej. Spróbuj ponownie.',
twoFactorResetForbidden: 'Może to zrobić tylko w pełni zalogowany administrator.',
twoFactorSetupClosed: 'Czas na ustawienie weryfikacji dwuetapowej minął, więc to konto jest zablokowane. Poproś administratora o ponowne otwarcie konfiguracji.',
twoFactorSetupDeadline: 'Ustaw weryfikację dwuetapową do {{date}}. Do tego czasu nie możesz korzystać z panelu.',
twoFactorSetupRequired: 'Ustaw weryfikację dwuetapową, aby korzystać z panelu.',
twoFactorStatusClosed: 'Nieustawiona. Czas na konfigurację minął {{date}}, więc konto jest zablokowane.',
twoFactorStatusExempt: 'Nieustawiona. To konto jest zwolnione w konfiguracji strony.',
twoFactorStatusLabel: 'Weryfikacja dwuetapowa',
twoFactorStatusOn: 'Ustawiona.',
twoFactorStatusOpen: 'Nieustawiona. Konto może ją ustawić do {{date}}.',
twoFactorStatusOpenNoLimit: 'Jeszcze nieustawiona. Do tego czasu konto nie może korzystać z panelu.',
twoFactorTooManyAttempts: 'Dla tego konta wpisano zbyt wiele kodów. Odczekaj {{minutes}} min, a potem wpisz aktualny kod z aplikacji.',
},
})
+12 -1
View File
@@ -106,7 +106,18 @@ export const securityRules: DoctorRule[] = [
if (/\?\s*false\b|:\s*false\b|&&/.test(twoFactor) && /payloadTotp/.test(twoFactor)) {out.push({ file: configFile(ctx) ?? undefined, fix: 'twoFactor: { issuer, plugin: payloadTotp } without a switch', message: '2FA can be turned off at runtime (a condition on twoFactor)', severity: 'warning' })}
if (!/twoFactor\s*:[^\n]*payloadTotp|twoFactor\s*:\s*\{[\s\S]*?plugin\s*:\s*payloadTotp/.test(code)) {out.push({ file: configFile(ctx) ?? 'payload.config.ts', fix: "ipalKit({ twoFactor: { issuer: '<site>', plugin: payloadTotp } })", message: '2FA is not on (twoFactor with plugin: payloadTotp)', severity: 'error' })}
else if (!ctx.installed('@clocklimited/payload-2fa')) {out.push({ fix: 'pnpm add @clocklimited/payload-2fa', message: '@clocklimited/payload-2fa is not installed', severity: 'error' })}
if (ctx.deep?.usersWithout2fa) {out.push({ fix: 'each of them signs in and sets up TOTP (forceSetup)', message: `${ctx.deep.usersWithout2fa} panel user(s) without TOTP`, severity: 'error' })}
if (/requireSetup\s*:\s*false/.test(code)) {out.push({ file: configFile(ctx) ?? undefined, fix: 'remove twoFactor.requireSetup: false (or record the reason in ipal-doctor.json)', message: 'twoFactor.requireSetup is off: an account that has not set 2FA up opens everything with its password alone', severity: 'warning' })}
if (/windowHours\s*:\s*(?:false|0)\b/.test(code)) {out.push({ file: configFile(ctx) ?? undefined, fix: 'twoFactor.requireSetup.windowHours: 72 (the default)', message: 'no time limit for 2FA setup: an account that never sets it up can be taken over with its password at any time', severity: 'info' })}
if (ctx.deep?.usersWithout2fa) {
const closed = ctx.deep.usersSetupClosed ?? 0
out.push({
fix: closed
? 'each of them signs in and sets up TOTP; for the blocked ones an admin opens the account in the panel → "Reopen setup" (or removes the account)'
: 'each of them signs in and sets up TOTP now; remove accounts nobody uses',
message: `${ctx.deep.usersWithout2fa} panel user(s) without TOTP${closed ? ` (${closed} blocked: the setup window has passed)` : ''}`,
severity: 'error',
})
}
return out
},
docs: 'docs/security.md#2fa-totp--enforced-for-every-user',
+8 -2
View File
@@ -7,7 +7,8 @@ import type { DoctorStatus } from './types.js'
import { countPendingCookies } from '../consent/scanner/approval.js'
import { COOKIE_REVIEW_SLUG } from '../consent/scanner/collection.js'
import { secondFactorPassed } from '../security/totp/secondFactor.js'
import { secondFactorPassed, SETUP_FROM_FIELD } from '../security/totp/secondFactor.js'
import { countAccountsWithoutTotp } from '../security/totp/setupRequired.js'
import { clientIp, consumeRateLimit, tooManyRequests } from '../shared/rateLimit.js'
/** The plugin's own version (package.json next to dist/ and src/). */
@@ -30,15 +31,20 @@ export async function collectDoctorStatus(payload: BasePayload): Promise<DoctorS
const authSlug = payload.config.admin?.user
const auth = collections.find((c) => c.slug === authSlug)
let usersWithout2fa: null | number = null
let usersSetupClosed: null | number = null
// payload-2fa stores `totpSecret` (`hasTotp` is virtual and cannot be queried); counted, never read.
if (auth?.fields?.some((f) => f.name === 'totpSecret')) {
const collection = auth.slug as never
const all = (await payload.count({ collection, overrideAccess: true })).totalDocs
const withTotp = (await payload.count({ collection, overrideAccess: true, where: { and: [{ totpSecret: { exists: true } }, { totpSecret: { not_equals: '' } }] } })).totalDocs
usersWithout2fa = Math.max(0, all - withTotp)
const windowMs = (payload.config.custom as { ipal?: { twoFactor?: { setupWindowMs?: number } } } | undefined)?.ipal?.twoFactor?.setupWindowMs
if (usersWithout2fa && windowMs && auth.fields.some((f) => f.name === SETUP_FROM_FIELD)) {
usersSetupClosed = (await countAccountsWithoutTotp(payload, auth.slug, windowMs)).blocked
}
}
const pendingCookies = collections.some((c) => c.slug === COOKIE_REVIEW_SLUG) ? await countPendingCookies(payload) : null
return { node: process.version, pendingCookies, plugin: pluginVersion(), usersWithout2fa }
return { node: process.version, pendingCookies, plugin: pluginVersion(), usersSetupClosed, usersWithout2fa }
}
export type DoctorEndpointOptions = {
+2
View File
@@ -63,6 +63,8 @@ export type DoctorStatus = {
node?: string
pendingCookies?: null | number
plugin?: string
/** Of `usersWithout2fa`: accounts whose setup window has passed (blocked until an admin reopens setup). */
usersSetupClosed?: null | number
usersWithout2fa?: null | number
}
@@ -8,12 +8,17 @@ import { useEffect } from 'react'
import type { TotpUser } from './totpRedirect.js'
import { totpRedirectTarget } from './totpRedirect.js'
import { formatDateTime, ipalT } from '../../admin-i18n/t.js'
import { totpAdminPath, totpRedirectTarget } from './totpRedirect.js'
export type TotpRedirectProviderProps = {
children?: ReactNode
/** pluginOptions.forceSetup — set by the plugin (true: 2FA is enforced). */
forceSetup?: boolean
/** `twoFactor.requireSetup` is on: say so on the setup screen. Set by the plugin. */
requireSetup?: boolean
/** Hours an account has for setup (0 = no limit). Set by the plugin. */
setupWindowHours?: number
/**
* 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
@@ -42,9 +47,9 @@ const STALE_TEXT = {
* Renders nothing while a redirect is pending, so the panel does not flash.
* Swap it with `twoFactor.provider`.
*/
export function TotpRedirectProvider({ children, forceSetup = true, staleImportMap = false }: TotpRedirectProviderProps) {
export function TotpRedirectProvider({ children, forceSetup = true, requireSetup = false, setupWindowHours = 0, staleImportMap = false }: TotpRedirectProviderProps) {
const { i18n, t } = useTranslation()
const { user } = useAuth()
const { i18n } = useTranslation()
const { config } = useConfig()
const pathname = usePathname()
const router = useRouter()
@@ -62,19 +67,61 @@ export function TotpRedirectProvider({ children, forceSetup = true, staleImportM
}, [router, target])
if (target) {return null}
if (staleImportMap && user && /\/(?:setup|verify)-totp\/?$/.test(pathname ?? '')) {
// Both notices stand ABOVE the screen and never replace it: the code form must stay on the page whatever they say.
const adminRoute = config.routes?.admin ?? '/admin'
const here = (pathname ?? '').replace(/\/+$/, '')
const onSetup = here === totpAdminPath(adminRoute, '/setup-totp')
const onVerify = here === totpAdminPath(adminRoute, '/verify-totp')
// The admin import map on disk may be older than the config (importMapCheck.ts): a guess, hence only a notice.
let stale: ReactNode = null
if (staleImportMap && user && (onSetup || onVerify)) {
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}
</>
stale = (
<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>
)
}
return children
// On the setup screen: what the account is waiting for — or that its time has passed.
let setup: ReactNode = null
const account = user as ({ totpSetupFrom?: null | string } & TotpUser) | null
if (requireSetup && onSetup && account && account.hasTotp === false) {
const start = account.totpSetupFrom ? new Date(account.totpSetupFrom).getTime() : NaN
const deadline = setupWindowHours > 0 && Number.isFinite(start) ? start + setupWindowHours * 3_600_000 : null
const closed = deadline !== null && deadline < Date.now()
const notice = closed
? ipalT(t as never, 'twoFactorSetupClosed')
: deadline !== null
? ipalT(t as never, 'twoFactorSetupDeadline', { date: formatDateTime(new Date(deadline).toISOString(), i18n.language) })
: ipalT(t as never, 'twoFactorSetupRequired')
setup = (
<div
id="ipal-two-factor-notice"
role={closed ? 'alert' : 'status'}
style={{
background: closed ? 'var(--theme-error-100, #fdecea)' : 'var(--theme-elevation-100, #f3f3f3)',
borderBottom: `1px solid ${closed ? 'var(--theme-error-500, #b00020)' : 'var(--theme-elevation-200, #ddd)'}`,
padding: '.75rem 1rem',
textAlign: 'center',
}}
>
{notice}
</div>
)
}
if (!stale && !setup) {return children}
return (
<>
{setup}
{stale}
{children}
</>
)
}
export default TotpRedirectProvider
@@ -0,0 +1,47 @@
import type { BasePayload } from 'payload'
import { userMeetsRole } from '../../access/predicates.js'
import { serverText } from '../../integrations/texts.js'
import { countAccountsWithoutTotp } from './setupRequired.js'
type Props = {
/** Admin route, for the link. Default '/admin'. */
adminRoute?: string
i18n?: { language?: string; t?: (key: never, vars?: Record<string, unknown>) => string }
payload?: BasePayload
user?: null | Record<string, unknown>
}
/**
* Dashboard notice for administrators (admin.components.beforeDashboard):
* how many accounts have not set up two-step verification, and how many of
* them are blocked because the time for setup has passed. Renders nothing when
* every account has it, for non-admins, and when anything fails.
*/
export async function TwoFactorAlert({ adminRoute = '/admin', i18n, payload, user }: Props) {
if (!payload || !user || !userMeetsRole({ payload, user }, 'admin')) {return null}
const guard = (payload.config.custom as { ipal?: { twoFactor?: { collection?: string; setupWindowMs?: number } } } | undefined)?.ipal?.twoFactor
if (!guard?.collection) {return null}
let counts: { blocked: number; without: number }
try {
counts = await countAccountsWithoutTotp(payload, guard.collection, guard.setupWindowMs)
} catch {
return null
}
if (!counts.without) {return null}
const base = adminRoute === '/' ? '' : adminRoute.replace(/\/$/, '')
return (
<div
role="status"
style={{ background: 'var(--theme-warning-100, #fff8e1)', border: '1px solid var(--theme-warning-500, #f0b400)', borderRadius: 4, marginBottom: '1.5rem', padding: '1rem 1.25rem' }}
>
<strong>{serverText(i18n, 'twoFactorAlertTitle')}</strong>
<p style={{ margin: '.35rem 0 0' }}>{serverText(i18n, 'twoFactorAlertPending', { count: counts.without })}</p>
{counts.blocked > 0 && <p style={{ margin: '.35rem 0 0' }}>{serverText(i18n, 'twoFactorAlertBlocked', { count: counts.blocked })}</p>}
<p style={{ margin: '.35rem 0 0' }}>
<a href={`${base}/collections/${guard.collection}`}>{serverText(i18n, 'twoFactorAlertLink')}</a>
</p>
</div>
)
}
@@ -0,0 +1,52 @@
'use client'
import { toast, useConfig, useTranslation } from '@payloadcms/ui'
import { useState } from 'react'
import { ipalT } from '../../admin-i18n/t.js'
type Props = {
/** `reopen`: the account has no TOTP (window passed or still open). `reset`: it has one (lost phone). */
kind: 'reopen' | 'reset'
userId: number | string
}
/** The admin's button on an account: clears its TOTP so it can (or must) set it up again. */
export function TwoFactorResetButton({ kind, userId }: Props) {
const { t } = useTranslation()
const text = (key: Parameters<typeof ipalT>[1]) => ipalT(t as never, key)
const { config } = useConfig()
const [busy, setBusy] = useState(false)
const run = async () => {
if (kind === 'reset' && !window.confirm(text('twoFactorResetConfirm'))) {return}
setBusy(true)
try {
const res = await fetch(`${config.serverURL ?? ''}${config.routes?.api ?? '/api'}/ipal/two-factor/reset`, {
body: JSON.stringify({ userId }),
credentials: 'include',
headers: { 'Content-Type': 'application/json' },
method: 'POST',
})
const data = (await res.json()) as { message?: string; ok?: boolean }
if (data.ok) {
toast.success(data.message ?? text('twoFactorResetDone'))
// The status next to this button is rendered on the server with the document: load it again.
// (router.refresh() does not re-render a document's field components.)
window.location.reload()
} else {
toast.error(data.message ?? text('twoFactorResetFailed'))
}
} catch {
toast.error(text('twoFactorResetFailed'))
} finally {
setBusy(false)
}
}
return (
<button className="btn btn--style-secondary btn--size-small" disabled={busy} onClick={run} style={{ marginTop: '.5rem' }} type="button">
{text(kind === 'reopen' ? 'twoFactorReopen' : 'twoFactorReset')}
</button>
)
}
@@ -0,0 +1,64 @@
import type { BasePayload } from 'payload'
import { userMeetsRole } from '../../access/predicates.js'
import { formatDateTime } from '../../admin-i18n/t.js'
import { serverText } from '../../integrations/texts.js'
import { twoFactorSetupDeadline, twoFactorSetupState } from './secondFactor.js'
import { TwoFactorResetButton } from './TwoFactorResetButton.js'
type Props = {
/** The account being shown. Injected by Payload into field server components. */
data?: { id?: number | string } & Record<string, unknown>
i18n?: { language?: string; t?: (key: never, vars?: Record<string, unknown>) => string }
payload?: BasePayload
/** The account looking at it. */
user?: ({ id?: number | string } & Record<string, unknown>) | null
}
/**
* On an account in the panel (sidebar): where it stands with two-step
* verification — set up, open until a date, or blocked because the time for
* setup has passed — and, for an administrator looking at someone else's
* account, the button that resets it / reopens setup.
*/
export async function TwoFactorStatusField({ data, i18n, payload, user }: Props) {
if (!payload || !data?.id) {return null}
const collection = (payload.config.custom as { ipal?: { twoFactor?: { collection?: string } } } | undefined)?.ipal?.twoFactor?.collection
if (!collection) {return null}
// The document data the panel passes hides `hasTotp` from everyone but the account itself (the 2FA
// package's field access), so an admin would always read "set up". Ask the database: the secret is
// only tested for presence, never shown.
let stored: { totpSecret?: null | string; totpSetupFrom?: null | string }
try {
stored = (await payload.findByID({
id: data.id,
collection: collection as never,
depth: 0,
overrideAccess: true,
select: { totpSecret: true, totpSetupFrom: true } as never,
showHiddenFields: true,
})) as typeof stored
} catch {
return null
}
const account = { id: data.id, collection, email: data.email, hasTotp: Boolean(stored.totpSecret), totpSetupFrom: stored.totpSetupFrom }
const state = twoFactorSetupState({ payload, user: account })
if (state === 'not-applicable') {return null}
const deadline = twoFactorSetupDeadline({ payload, user: account })
const date = deadline ? formatDateTime(deadline.toISOString(), i18n?.language ?? 'en') : ''
const status =
state === 'set-up' ? serverText(i18n, 'twoFactorStatusOn')
: state === 'exempt' ? serverText(i18n, 'twoFactorStatusExempt')
: state === 'closed' ? serverText(i18n, 'twoFactorStatusClosed', { date })
: deadline ? serverText(i18n, 'twoFactorStatusOpen', { date })
: serverText(i18n, 'twoFactorStatusOpenNoLimit')
const canReset = Boolean(user && user.id !== data.id && userMeetsRole({ payload, user }, 'admin'))
return (
<div className="field-type" id="ipal-two-factor-status">
<span className="field-label">{serverText(i18n, 'twoFactorStatusLabel')}</span>
<p style={{ margin: 0, ...(state === 'closed' ? { color: 'var(--theme-error-500, #b00020)' } : {}) }}>{status}</p>
{canReset && state !== 'exempt' && <TwoFactorResetButton kind={state === 'set-up' ? 'reset' : 'reopen'} userId={data.id} />}
</div>
)
}
+69 -11
View File
@@ -21,7 +21,9 @@ import type { BasePayload, CollectionConfig, Config, GlobalConfig } from 'payloa
* logs a warning at start);
* 4. `_strategy === 'totp'` → set by the package's strategy after password and code;
* 5. `_strategy === 'api-key'` → an API key is its own credential (the package's rule);
* 6. `hasTotp === false` → TOTP not set up yet (the setup screen needs the session);
* 6. `hasTotp === false` (TOTP not set up yet) → only when setup is not required
* (`twoFactor.requireSetup: false`) or the project's `exempt` says so for that account;
* by default such an account is refused like one that owes its code;
* 7. per-entity opt-out in the project's config (`custom.totp.disableAccessWrapper`,
* `custom.ipal.secondFactor`), or the package's global `disableAccessWrapper`;
* 8. `access.admin` (may this account open the panel) is not wrapped: the code is
@@ -36,14 +38,61 @@ import type { BasePayload, CollectionConfig, Config, GlobalConfig } from 'payloa
* It fails closed. An account of the 2FA collection passes only when
* - it came through the package's `totp` strategy (password AND code), or
* - it authenticated with an API key (the package's own rule), or
* - TOTP is not set up on it yet (`hasTotp === false`) — the setup screen
* needs that, and the package lets such an account through as well.
* Anything else — code not entered, or a user object this check does not
* understand (a renamed strategy, no `hasTotp`) — is refused.
* - TOTP is not set up on it yet AND setup is not required
* (`twoFactor.requireSetup: false`), or the project exempts the account.
* Anything else — code not entered, TOTP not set up yet, or a user object this
* check does not understand (a renamed strategy, no `hasTotp`) — is refused.
*
* "Setup required" (the default): an account without TOTP reaches nothing at
* the access level. It does not need to: the setup screen is rendered from the
* session, and `/api/setup-totp` is an endpoint that writes with
* `overrideAccess`. It is the same state an account is in between its password
* and its code. The package alone only redirects such an account in the panel.
*/
/** What ipalKit records in `config.custom.ipal.twoFactor` when 2FA is on and the guard is not switched off. */
export type TwoFactorGuardConfig = { collection: string }
export type TwoFactorGuardConfig = {
collection: string
/** The project's exemption for accounts that never set TOTP up (a service account logging in with a password). */
exempt?: (args: { user: Record<string, unknown> }) => boolean
/** An account without TOTP is refused everything until it is set up. */
requireSetup?: boolean
/** How long after `totpSetupFrom` setup stays possible, in ms. 0 / undefined = no limit. */
setupWindowMs?: number
}
/** Field on the 2FA collection: when the current setup window opened (account created, or an admin reset). */
export const SETUP_FROM_FIELD = 'totpSetupFrom'
/**
* Where an account stands with TOTP setup:
* - `not-applicable`: no user, another collection, 2FA or the guard off;
* - `set-up`: TOTP is set up;
* - `exempt`: not set up, and the project exempts it (or setup is not required);
* - `open`: not set up, may set it up now;
* - `closed`: not set up and the setup window has passed — blocked until an admin reopens it.
*/
export type TwoFactorSetupState = 'closed' | 'exempt' | 'not-applicable' | 'open' | 'set-up'
/** The moment setup closes for this account, or null (no window, or no start recorded yet). */
export function twoFactorSetupDeadline({ payload, user }: MaybeReq): Date | null {
const guard = guardConfig(payload)
const from = (user as null | Record<string, unknown> | undefined)?.[SETUP_FROM_FIELD]
if (!guard?.setupWindowMs || (typeof from !== 'string' && !(from instanceof Date))) {return null}
const start = new Date(from).getTime()
return Number.isFinite(start) ? new Date(start + guard.setupWindowMs) : null
}
export function twoFactorSetupState({ payload, user }: MaybeReq, now: number = Date.now()): TwoFactorSetupState {
const guard = guardConfig(payload)
if (!guard || !user || typeof user !== 'object') {return 'not-applicable'}
const u = user as { collection?: unknown; hasTotp?: unknown }
if (u.collection !== guard.collection) {return 'not-applicable'}
if (u.hasTotp !== false || (user as { totpSecret?: unknown }).totpSecret) {return 'set-up'}
if (!guard.requireSetup || guard.exempt?.({ user: user as Record<string, unknown> })) {return 'exempt'}
const deadline = twoFactorSetupDeadline({ payload, user })
return deadline && deadline.getTime() < now ? 'closed' : 'open'
}
type MaybeReq = { payload?: Pick<BasePayload, 'config'>; user?: unknown }
@@ -51,10 +100,11 @@ const guardConfig = (payload: MaybeReq['payload']): TwoFactorGuardConfig | undef
(payload?.config?.custom as { ipal?: { twoFactor?: TwoFactorGuardConfig } } | undefined)?.ipal?.twoFactor
/**
* False only for an account that still owes the second factor: it belongs to
* the 2FA collection, has TOTP set up and has not entered the code in this
* session. True for everyone else — no user (the access function decides),
* accounts of other auth collections, 2FA off (`twoFactor: false`).
* False for an account that still owes the second factor: it belongs to the
* 2FA collection and either has TOTP set up and has not entered the code in
* this session, or has not set TOTP up at all (unless setup is not required
* or the project exempts it). True for everyone else — no user (the access
* function decides), accounts of other auth collections, 2FA off (`twoFactor: false`).
*
* Pass `req`. Use it in your own endpoints and access functions:
* if (!secondFactorPassed(req)) return Response.json({ ok: false }, { status: 403 })
@@ -72,7 +122,9 @@ export function secondFactorPassed({ payload, user }: MaybeReq): boolean {
// "Not set up yet" only when nothing says otherwise. The package computes `hasTotp` with a second
// database read and answers false when that read fails; the secret on the user object itself (it
// came with the account's own record) then still says the account has TOTP: refused.
return u.hasTotp === false && !(user as { totpSecret?: unknown }).totpSecret
if (u.hasTotp !== false || (user as { totpSecret?: unknown }).totpSecret) {return false}
// TOTP not set up: only when setup is not required, or for an account the project exempts
return !guard.requireSetup || Boolean(guard.exempt?.({ user: user as Record<string, unknown> }))
}
const GUARDED = Symbol.for('ipal.secondFactorGuard')
@@ -321,6 +373,8 @@ export type TotpEndpointGuards = {
* it. Return a Response to refuse (too many attempts), null to let it through.
*/
limitVerify?: (req: never) => null | Promise<null | Response> | Response
/** The answer for an account whose setup window has passed (in the caller's language). Default: a plain 403. */
onSetupClosed?: (req: never) => Response
}
export function guardTotpEndpoint<T extends EndpointLike>(endpoint: T, collection: string, guards: TotpEndpointGuards = {}): T {
@@ -332,6 +386,10 @@ export function guardTotpEndpoint<T extends EndpointLike>(endpoint: T, collectio
const user = req.user as { collection?: unknown } | null | undefined
if (user && user.collection !== collection) {return refused()}
if (user && !BEFORE_SECOND_FACTOR.has(endpoint.path) && !secondFactorPassed(req)) {return refused()}
// Setup after the window: blocked until an admin reopens it.
if (user && endpoint.path === '/setup-totp' && twoFactorSetupState(req) === 'closed') {
return guards.onSetupClosed ? guards.onSetupClosed(req as never) : refused()
}
// The code has about three right answers in a million and the package never counts tries.
if (user && endpoint.path === '/verify-totp' && guards.limitVerify) {
const limited = await guards.limitVerify(req as never)
+184
View File
@@ -0,0 +1,184 @@
import type { BasePayload, CollectionBeforeChangeHook, Endpoint, Field, PayloadRequest } from 'payload'
import { isAdmin, userMeetsRole } from '../../access/predicates.js'
import { serverText } from '../../integrations/texts.js'
import { secondFactorPassed, SETUP_FROM_FIELD } from './secondFactor.js'
/**
* "2FA setup required": the pieces ipalKit adds to the 2FA collection and the
* config when the mode is on (the default with `twoFactor`).
*
* - the date field `totpSetupFrom` — when the current setup window opened;
* - a hook that stamps it when an account is created and whenever its TOTP
* secret is cleared (an admin reset, a removal);
* - a backfill for accounts that existed before the mode (onInit);
* - POST /api/ipal/two-factor/reset — an admin clears an account's TOTP, which
* reopens its setup window;
* - the status / reset field shown on the account in the panel.
*
* The rule itself (who is refused) lives in secondFactor.ts.
*/
export type RequireSetupOptions = {
/**
* Accounts that may work without TOTP on purpose — a service account that
* logs in with a password. Return true to exempt. (An API key needs no
* exemption: it passes by itself.) `({ user }) => user.email === '[email protected]'`
*/
exempt?: (args: { user: Record<string, unknown> }) => boolean
/**
* Hours an account has to set TOTP up, counted from its creation or from the
* last reset by an admin. After that it is blocked until an admin reopens
* setup. Default 72. `false` or `0` = no limit (still nothing but setup until it is done).
*/
windowHours?: false | number
}
export const DEFAULT_SETUP_WINDOW_HOURS = 72
export const TWO_FACTOR_RESET_PATH = '/ipal/two-factor/reset'
/** `twoFactor.requireSetup` → what the guard reads. */
export function resolveRequireSetup(option: false | RequireSetupOptions | undefined): {
exempt?: RequireSetupOptions['exempt']
requireSetup: boolean
setupWindowMs: number
} {
if (option === false) {return { requireSetup: false, setupWindowMs: 0 }}
const hours = option?.windowHours === false ? 0 : (option?.windowHours ?? DEFAULT_SETUP_WINDOW_HOURS)
return {
...(option?.exempt ? { exempt: option.exempt } : {}),
requireSetup: true,
setupWindowMs: Number.isFinite(hours) && hours > 0 ? hours * 60 * 60 * 1000 : 0,
}
}
/** The two fields for the 2FA collection: the window start (data) and its status / reset control (panel). */
export function buildSetupFields(): Field[] {
return [
{
name: SETUP_FROM_FIELD,
type: 'date',
access: {
// Written by the hook below only — never through the API.
create: () => false,
read: ({ data, doc, req }) => isAdmin(req.user, req.payload) || Boolean(req.user && ((doc ?? data) as { id?: unknown } | undefined)?.id === req.user.id),
update: () => false,
},
admin: { disableBulkEdit: true, disableListColumn: true, disableListFilter: true, hidden: true },
label: { en: 'Two-step verification: setup open since', pl: 'Weryfikacja dwuetapowa: konfiguracja otwarta od' },
},
{
name: 'totpSetupStatus',
type: 'ui',
admin: {
components: { Field: '@intecion/ipal-kit/admin#TwoFactorStatusField' },
disableListColumn: true,
position: 'sidebar',
},
},
]
}
/**
* Stamps `totpSetupFrom`: on create, and when an account that had TOTP loses
* its secret (the 2FA package's own remove / admin endpoints). The reset
* endpoint below writes the date itself, so it also reopens the window of an
* account that never had TOTP. Neither field can be written through the API
* (field access), so only server code gets here with them.
*/
export const stampSetupFrom: CollectionBeforeChangeHook = ({ data, operation, originalDoc }) => {
if (!data) {return data}
const hadTotp = Boolean((originalDoc as { totpSecret?: unknown } | undefined)?.totpSecret)
if (operation === 'create' ? !data[SETUP_FROM_FIELD] : hadTotp && 'totpSecret' in data && !data.totpSecret) {
data[SETUP_FROM_FIELD] = new Date().toISOString()
}
return data
}
/**
* Accounts that existed before the mode have no `totpSetupFrom`. Their window
* starts now — at the first start after the upgrade — so nobody is blocked the
* moment a site upgrades: each such account gets the full window to set TOTP
* up. Runs on every start; after the first there is nothing left to do.
* Returns how many accounts it stamped; never throws (a database that has not
* been migrated yet must not stop the site).
*/
export async function backfillSetupFrom(payload: BasePayload, collection: string): Promise<number> {
try {
const where = {
and: [
{ or: [{ totpSecret: { exists: false } }, { totpSecret: { equals: '' } }] },
{ [SETUP_FROM_FIELD]: { exists: false } },
],
}
const { totalDocs } = await payload.count({ collection: collection as never, overrideAccess: true, where: where as never })
if (!totalDocs) {return 0}
const data = { [SETUP_FROM_FIELD]: new Date().toISOString() }
// One query where the adapter has it (Payload 3.9x); the Local API otherwise. Hooks have nothing to add here.
if (typeof payload.db.updateMany === 'function') {
await payload.db.updateMany({ collection: collection as never, data: data as never, where: where as never })
} else {
await payload.update({ collection: collection as never, data: data as never, overrideAccess: true, where: where as never })
}
return totalDocs
} catch (err) {
payload.logger.warn(`[ipal] 2FA: could not start the setup window for existing accounts (${err instanceof Error ? err.message : String(err)}). On Postgres / SQLite run the migration that adds "${SETUP_FROM_FIELD}".`)
return 0
}
}
export type TwoFactorResetOptions = {
/** Who may reset another account's TOTP. Default: a staff admin (`userMeetsRole(req, 'admin')`). The second factor is always required. */
access?: (args: { req: PayloadRequest }) => boolean | Promise<boolean>
}
/**
* POST /api/ipal/two-factor/reset `{ userId }` — clears that account's TOTP
* secret. The account must set TOTP up again, and its setup window starts
* anew. For a lost phone, and to reopen setup for an account whose window has
* passed. Admins only, and only after their own second factor.
*/
export function buildTwoFactorResetEndpoint(collection: string, options: TwoFactorResetOptions = {}): Endpoint {
return {
handler: async (req) => {
const i18n = req.i18n as Parameters<typeof serverText>[0]
const allowed =
Boolean(req.user) &&
secondFactorPassed(req) &&
(req.user as { collection?: unknown }).collection === collection &&
(options.access ? Boolean(await options.access({ req })) : userMeetsRole(req, 'admin'))
if (!allowed) {return Response.json({ message: serverText(i18n, 'twoFactorResetForbidden'), ok: false }, { status: 403 })}
let body: unknown
try {
body = await req.json?.()
} catch {
body = undefined
}
const userId = (body as { userId?: unknown } | undefined)?.userId
if (typeof userId !== 'string' && typeof userId !== 'number') {
return Response.json({ message: serverText(i18n, 'twoFactorResetFailed'), ok: false }, { status: 400 })
}
try {
await req.payload.update({ id: userId, collection: collection as never, data: { [SETUP_FROM_FIELD]: new Date().toISOString(), totpSecret: null } as never, overrideAccess: true, req })
} catch (err) {
req.payload.logger.error(`[ipal] 2FA reset failed: ${err instanceof Error ? err.message : String(err)}`)
return Response.json({ message: serverText(i18n, 'twoFactorResetFailed'), ok: false }, { status: 400 })
}
const actor = (req.user as { email?: string; id?: unknown }).email ?? String((req.user as { id?: unknown }).id)
req.payload.logger.info(`[ipal] 2FA reset for ${collection} ${String(userId)} by ${actor}.`)
return Response.json({ message: serverText(i18n, 'twoFactorResetDone'), ok: true })
},
method: 'post',
path: TWO_FACTOR_RESET_PATH,
}
}
/** Accounts of the 2FA collection without TOTP, and how many of those are past their setup window. */
export async function countAccountsWithoutTotp(payload: BasePayload, collection: string, setupWindowMs = 0): Promise<{ blocked: number; without: number }> {
const none = { or: [{ totpSecret: { exists: false } }, { totpSecret: { equals: '' } }] }
const without = (await payload.count({ collection: collection as never, overrideAccess: true, where: none as never })).totalDocs
if (!without || !setupWindowMs) {return { blocked: 0, without }}
const limit = new Date(Date.now() - setupWindowMs).toISOString()
const blocked = (await payload.count({ collection: collection as never, overrideAccess: true, where: { and: [none, { [SETUP_FROM_FIELD]: { less_than: limit } }] } as never })).totalDocs
return { blocked, without }
}
+46 -3
View File
@@ -32,6 +32,7 @@ import { buildFormsPlugin } from './modules/forms/formsPluginConfig.js'
import { buildGlobalRevalidateHook } from './modules/hooks/buildRevalidateHook.js'
import { withFillLocales } from './modules/hooks/fillEmptyLocales.js'
import { buildLocalizationConfig, validateI18nConfig } from './modules/i18n/index.js'
import { serverText } from './modules/integrations/texts.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'
@@ -45,6 +46,7 @@ import {
passOptOutsToPackage,
watchPayloadConfig,
} from './modules/security/totp/secondFactor.js'
import { backfillSetupFrom, buildSetupFields, buildTwoFactorResetEndpoint, resolveRequireSetup, stampSetupFrom } from './modules/security/totp/setupRequired.js'
import { TOTP_TEXTS, TOTP_VIEW_TITLE } from './modules/security/totp/totpTexts.js'
import { buildVerifyLimit } from './modules/security/totp/verifyLimit.js'
import { buildSeoPlugin, injectAutoFillMeta, injectSeoTabs } from './modules/seo/index.js'
@@ -189,6 +191,9 @@ export const ipalKit = (options: IpalOptions): Plugin => {
const late = ensurePayloadGuarded(payload)
if (late?.length) {payload.logger.info(`[ipal] 2FA also enforced on entities added after ipalKit: ${late.join(', ')}.`)}
}
/** 2FA collection when "setup required" is on — its existing accounts get their setup window in onInit. */
let setupRequiredFor: null | string = null
let setupWindowHours = 0
if (options.twoFactor !== false) {
const tf = options.twoFactor
if (!tf?.issuer) {
@@ -257,7 +262,11 @@ export const ipalKit = (options: IpalOptions): Plugin => {
// Only accounts of the 2FA collection may use them (guardTotpEndpoint) —
// whatever the package registered, also paths a later version adds.
const limitVerify = tf.verifyLimit === false ? undefined : buildVerifyLimit(target, tf.verifyLimit)
const guards = limitVerify ? { limitVerify: (req: PayloadRequest) => limitVerify(req) } : {}
const guards = {
...(limitVerify ? { limitVerify: (req: PayloadRequest) => limitVerify(req) } : {}),
onSetupClosed: (req: PayloadRequest) =>
Response.json({ message: serverText(req.i18n as never, 'twoFactorSetupClosed'), ok: false }, { status: 403 }),
}
config.endpoints = (config.endpoints ?? []).map((e) => (endpointsBefore.has(e) ? e : guardTotpEndpoint(e, target, guards as never)))
// …and the same for endpoints it may put on a collection or a global.
config.collections = guardNewEntityEndpoints(config.collections, entityEndpointsBefore, target, guards as never)
@@ -286,7 +295,31 @@ export const ipalKit = (options: IpalOptions): Plugin => {
)
}
secondFactorGuard = true
config.custom = { ...config.custom, ipal: { ...config.custom?.ipal, twoFactor: { collection: target } } }
// "Setup required" (default): an account without TOTP reaches nothing but the setup
// screen, and only within the window; requireSetup: false = the package's rule.
const setup = resolveRequireSetup(tf.requireSetup)
config.custom = { ...config.custom, ipal: { ...config.custom?.ipal, twoFactor: { collection: target, ...setup } } }
if (setup.requireSetup) {
setupRequiredFor = target
setupWindowHours = setup.setupWindowMs / 3_600_000
config.collections = (config.collections ?? []).map((c) =>
c.slug === target
? { ...c, fields: [...c.fields, ...buildSetupFields()], hooks: { ...c.hooks, beforeChange: [...(c.hooks?.beforeChange ?? []), stampSetupFrom] } }
: c,
)
config.admin = {
...config.admin,
components: {
...config.admin?.components,
beforeDashboard: [
...(config.admin?.components?.beforeDashboard ?? []),
{ path: '@intecion/ipal-kit/admin#TwoFactorAlert', serverProps: { adminRoute: options.adminRoute ?? '/admin' } },
],
},
}
}
// An admin resets an account's TOTP (lost phone) / reopens its setup window.
config.endpoints = [...(config.endpoints ?? []), buildTwoFactorResetEndpoint(target, { access: tf.resetAccess })]
// Called by Payload on every request before any access function: guards whatever
// the live config has that was added after ipalKit (start, dev hot reload).
const sweep = buildGuardStrategy(adoptConfig)
@@ -342,7 +375,7 @@ export const ipalKit = (options: IpalOptions): Plugin => {
p && (typeof p === 'string' ? p : p.path) === TOTP_PACKAGE_PROVIDER
? {
...ours,
clientProps: { forceSetup: true, ...ours.clientProps },
clientProps: { forceSetup: true, ...(setupRequiredFor ? { requireSetup: true, setupWindowHours } : {}), ...ours.clientProps },
serverProps: { ...(typeof p === 'object' ? p.serverProps : {}), ...ours.serverProps },
}
: p,
@@ -779,6 +812,16 @@ export const ipalKit = (options: IpalOptions): Plugin => {
)
}
}
// Accounts from before "setup required": their window starts now, not at their creation date.
if (setupRequiredFor) {
const started = await backfillSetupFrom(payload, setupRequiredFor)
if (started) {
payload.logger.warn(
`[ipal] 2FA: ${started} existing account(s) without two-step verification. ` +
(setupWindowHours ? `They have ${setupWindowHours} h from now to set it up; after that an administrator must reopen setup.` : 'They cannot use the panel until they set it up.'),
)
}
}
await migrateCookieSettingsSaveButton(payload)
await migrateTitleSeparator(payload, settingsSlug)
if (adminMeta) {await syncAdminMeta(payload, adminMeta, { nameField: brandFields.nameField, settingsSlug })}
+18 -1
View File
@@ -1,4 +1,4 @@
import type { CollectionSlug, Field, PayloadComponent, Plugin } from 'payload'
import type { CollectionSlug, Field, PayloadComponent, PayloadRequest, Plugin } from 'payload'
/**
* Factory shape of @clocklimited/payload-2fa's `payloadTotp` export — injected
@@ -24,6 +24,7 @@ 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 { RequireSetupOptions } from './modules/security/totp/setupRequired.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'
@@ -275,6 +276,22 @@ export type IpalOptions = {
* (then set `x-pathname` on /admin yourself). Run generate:importmap.
*/
provider?: false | PayloadComponent
/**
* "Setup required", on by default: an account that has not set TOTP up
* reaches nothing at the access level (REST, GraphQL, the panel's data) —
* only the setup screen and its endpoint. It has `windowHours` (default 72)
* from its creation, or from a reset by an admin, to set TOTP up; after that
* it is blocked until an admin reopens setup (the account's page in the
* panel, or POST /api/ipal/two-factor/reset). Accounts that existed before
* the mode get the full window from the first start after the upgrade.
* `{ windowHours: false }` = no time limit; `{ exempt: ({ user }) => … }` =
* accounts that may work without TOTP on purpose (a service account);
* `false` = the 2FA package's rule (the panel redirects, the API is open
* until setup). Needs `guard` on. docs/security.md.
*/
requireSetup?: false | RequireSetupOptions
/** Who may reset another account's TOTP / reopen its setup. Default: a staff admin. The second factor is always required. */
resetAccess?: (args: { req: PayloadRequest }) => boolean | Promise<boolean>
/**
* 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
+17 -1
View File
@@ -382,7 +382,23 @@ describe('security and deep status', () => {
}
const status = await collectDoctorStatus(payload as never)
expect(status).toMatchObject({ pendingCookies: 4, usersWithout2fa: 2 })
expect(Object.keys(status).sort()).toEqual(['node', 'pendingCookies', 'plugin', 'usersWithout2fa'])
expect(Object.keys(status).sort()).toEqual(['node', 'pendingCookies', 'plugin', 'usersSetupClosed', 'usersWithout2fa'])
expect(status.usersSetupClosed).toBeNull() // no setup window in this config
})
test('collectDoctorStatus counts the accounts whose 2FA setup window has passed', async () => {
const payload = {
config: {
admin: { user: 'users' },
collections: [{ slug: 'users', fields: [{ name: 'totpSecret' }, { name: 'hasTotp' }, { name: 'totpSetupFrom' }] }],
custom: { ipal: { twoFactor: { collection: 'users', requireSetup: true, setupWindowMs: 72 * 3_600_000 } } },
},
// all 5; with TOTP 3; without 2; of those past the window 1 (the query with `less_than`)
count: vi.fn(async ({ where }: { where?: object }) => {
const q = JSON.stringify(where ?? {})
return { totalDocs: !where ? 5 : q.includes('less_than') ? 1 : q.includes('not_equals') ? 3 : 2 }
}),
}
expect(await collectDoctorStatus(payload as never)).toMatchObject({ usersSetupClosed: 1, usersWithout2fa: 2 })
})
test('GET /api/ipal/doctor: 404 without a token, 401 with a wrong one, counts with the right one', async () => {
const endpoint = buildDoctorEndpoint()
+97 -2
View File
@@ -10,7 +10,17 @@ import type { I18nConfig } from '../src/modules/i18n/types.js'
import { adminOrSelfIn } from '../src/modules/access/access.js'
import { isAdmin, staffCollectionSlugs, userMeetsRole } from '../src/modules/access/predicates.js'
import { ensurePayloadGuarded, guardPayloadAccess, guardTotpEndpoint, requireSecondFactor, secondFactorPassed, watchPayloadConfig } from '../src/modules/security/totp/secondFactor.js'
import {
ensurePayloadGuarded,
guardPayloadAccess,
guardTotpEndpoint,
requireSecondFactor,
secondFactorPassed,
twoFactorSetupDeadline,
twoFactorSetupState,
watchPayloadConfig,
} from '../src/modules/security/totp/secondFactor.js'
import { resolveRequireSetup } from '../src/modules/security/totp/setupRequired.js'
import { buildVerifyLimit, clearVerifyLimits } from '../src/modules/security/totp/verifyLimit.js'
import { ipalKit } from '../src/plugin.js'
import { withTotpParts } from './helpers.js'
@@ -93,7 +103,7 @@ describe('secondFactorPassed', () => {
['no user', null, true],
['password and code (the totp strategy)', { _strategy: 'totp', collection: 'users', hasTotp: true }, true],
['API key', { _strategy: 'api-key', collection: 'users', hasTotp: true }, true],
['TOTP not set up yet', { _strategy: 'local-jwt', collection: 'users', hasTotp: false }, true],
['TOTP not set up yet, setup not required (requireSetup: false)', { _strategy: 'local-jwt', collection: 'users', hasTotp: false }, true],
['password only', { _strategy: 'local-jwt', collection: 'users', hasTotp: true }, false],
['a user object without the fields the check knows (fail closed)', { collection: 'users' }, false],
['an unknown strategy name (fail closed)', { _strategy: 'two-factor', collection: 'users', hasTotp: true }, false],
@@ -105,6 +115,65 @@ describe('secondFactorPassed', () => {
expect(secondFactorPassed({ payload, user })).toBe(expected)
})
describe('setup required (the default)', () => {
const HOUR = 3_600_000
const required = (extra: object = {}) => ({ config: { custom: { ipal: { twoFactor: { collection: 'users', requireSetup: true, setupWindowMs: 72 * HOUR, ...extra } } } } }) as never
const fresh = { _strategy: 'local-jwt', collection: 'users', email: '[email protected]', hasTotp: false, totpSetupFrom: new Date(Date.now() - HOUR).toISOString() }
const late = { ...fresh, totpSetupFrom: new Date(Date.now() - 73 * HOUR).toISOString() }
test('an account without TOTP is refused, inside the window and after it', () => {
expect(secondFactorPassed({ payload: required(), user: fresh })).toBe(false)
expect(secondFactorPassed({ payload: required(), user: late })).toBe(false)
expect(twoFactorSetupState({ payload: required(), user: fresh })).toBe('open')
expect(twoFactorSetupState({ payload: required(), user: late })).toBe('closed')
expect(twoFactorSetupDeadline({ payload: required(), user: fresh })!.getTime()).toBeGreaterThan(Date.now())
})
test('no window (windowHours: false / 0): never closed, still refused until set up', () => {
const noWindow = required({ setupWindowMs: 0 })
expect(twoFactorSetupState({ payload: noWindow, user: late })).toBe('open')
expect(twoFactorSetupDeadline({ payload: noWindow, user: late })).toBeNull()
expect(secondFactorPassed({ payload: noWindow, user: late })).toBe(false)
})
test('an account without a recorded start (before the first start after the upgrade) is open, not closed', () => {
const legacy = { _strategy: 'local-jwt', collection: 'users', hasTotp: false }
expect(twoFactorSetupState({ payload: required(), user: legacy })).toBe('open')
expect(secondFactorPassed({ payload: required(), user: legacy })).toBe(false)
})
test('the project exempts a service account on purpose', () => {
const exempt = required({ exempt: ({ user }: { user: { email?: string } }) => user.email === '[email protected]' })
const bot = { ...late, email: '[email protected]' }
expect(secondFactorPassed({ payload: exempt, user: bot })).toBe(true)
expect(twoFactorSetupState({ payload: exempt, user: bot })).toBe('exempt')
expect(secondFactorPassed({ payload: exempt, user: late })).toBe(false)
})
test('an API key passes whatever the setup state; the set-up and other-collection cases are unchanged', () => {
expect(secondFactorPassed({ payload: required(), user: { ...late, _strategy: 'api-key' } })).toBe(true)
expect(secondFactorPassed({ payload: required(), user: { _strategy: 'totp', collection: 'users', hasTotp: true } })).toBe(true)
expect(secondFactorPassed({ payload: required(), user: { _strategy: 'local-jwt', collection: 'customers' } })).toBe(true)
expect(twoFactorSetupState({ payload: required(), user: { collection: 'customers' } })).toBe('not-applicable')
expect(twoFactorSetupState({ payload: required(), user: { collection: 'users', hasTotp: true } })).toBe('set-up')
})
test('resolveRequireSetup: the option → what the guard reads', () => {
expect(resolveRequireSetup(undefined)).toEqual({ requireSetup: true, setupWindowMs: 72 * HOUR })
expect(resolveRequireSetup({ windowHours: 24 })).toEqual({ requireSetup: true, setupWindowMs: 24 * HOUR })
expect(resolveRequireSetup({ windowHours: false })).toEqual({ requireSetup: true, setupWindowMs: 0 })
expect(resolveRequireSetup({ windowHours: 0 })).toEqual({ requireSetup: true, setupWindowMs: 0 })
expect(resolveRequireSetup(false)).toEqual({ requireSetup: false, setupWindowMs: 0 })
})
test('the setup endpoint refuses an account whose window has passed', async () => {
const inner = () => Promise.resolve(Response.json({ ok: true }))
const endpoint = guardTotpEndpoint({ handler: inner as (req: never) => Promise<Response>, path: '/setup-totp' }, 'users')
expect((await endpoint.handler({ payload: required(), user: fresh } as never)).status).toBe(200)
expect((await endpoint.handler({ payload: required(), user: late } as never)).status).toBe(403)
})
})
test('2FA off: everyone passes', () => {
expect(secondFactorPassed({ payload: { config: {} } as never, user: { _strategy: 'local-jwt', collection: 'users', hasTotp: true } })).toBe(true)
})
@@ -292,6 +361,32 @@ describe('ipalKit and the 2FA plugin', () => {
expect(warnings.join('\n')).toMatch(/2FA covers "users" only\. Staff accounts of "partners"/)
})
test('setup required: on by default, with the field, the hook, the reset endpoint and the notices; every part can be changed', async () => {
const base = () => ({ collections: [], secret: 'x' }) as unknown as Config
const on = await ipalKit({ i18n, twoFactor: { issuer: 'A', plugin: fakeTotp as never } })(base())
const guard = (c: Config) => (c.custom as { ipal: { twoFactor: Record<string, unknown> } }).ipal.twoFactor
expect(guard(on)).toMatchObject({ collection: 'users', requireSetup: true, setupWindowMs: 72 * 3_600_000 })
const users = on.collections!.find((c) => c.slug === 'users')!
expect(users.fields.some((f) => 'name' in f && f.name === 'totpSetupFrom')).toBe(true)
expect(users.hooks?.beforeChange?.length).toBe(1)
expect(on.endpoints!.some((e) => e.path === '/ipal/two-factor/reset')).toBe(true)
expect(JSON.stringify(on.admin?.components?.beforeDashboard)).toContain('TwoFactorAlert')
const custom = await ipalKit({ i18n, twoFactor: { issuer: 'A', plugin: fakeTotp as never, requireSetup: { windowHours: 24 } } })(base())
expect(guard(custom).setupWindowMs).toBe(24 * 3_600_000)
const off = await ipalKit({ i18n, twoFactor: { issuer: 'A', plugin: fakeTotp as never, requireSetup: false } })(base())
expect(guard(off)).toMatchObject({ requireSetup: false })
expect(off.collections!.find((c) => c.slug === 'users')!.fields.some((f) => 'name' in f && f.name === 'totpSetupFrom')).toBe(false)
expect(JSON.stringify(off.admin?.components?.beforeDashboard ?? [])).not.toContain('TwoFactorAlert')
expect(off.endpoints!.some((e) => e.path === '/ipal/two-factor/reset')).toBe(true) // an admin can still reset a lost phone
// 2FA off: nothing of this exists
const none = await ipalKit({ i18n, twoFactor: false })(base())
expect(none.endpoints!.some((e) => e.path === '/ipal/two-factor/reset')).toBe(false)
expect(none.collections!.find((c) => c.slug === 'users')!.fields.some((f) => 'name' in f && f.name === 'totpSetupFrom')).toBe(false)
})
test('twoFactor: false — no guard, a password is enough (as documented)', async () => {
const config = await ipalKit({ access: { authCollection: 'users' }, i18n, twoFactor: false })({ collections: [], secret: 'x' } as unknown as Config)
const payload = payloadOf(config)
+91 -8
View File
@@ -283,14 +283,6 @@ describe('what must keep working', () => {
expect((out.data?.SiteIntegration as { smtpPassword: string }).smtpPassword).toBe('S3CRET')
})
test('an account that has not set TOTP up yet can still do so', async () => {
// The package lets such an account through until TOTP is set up (the setup screen needs it).
expect((await api('/users/me', sessions.newcomer)).status).toBe(200)
const setup = await api('/setup-totp', sessions.newcomer, { body: JSON.stringify({ secret: TOTP_SECRET, token: totp(TOTP_SECRET) }), method: 'POST' })
expect(setup.status).toBe(200)
expect(((await setup.json()) as { ok: boolean }).ok).toBe(true)
})
test('anonymous visitors still read the public globals and forms', async () => {
for (const p of ['/globals/site-settings', '/globals/notifications', '/globals/cookie-settings', '/forms']) {
expect([p, (await api(p, sessions.anonymous)).status]).toEqual([p, 200])
@@ -475,6 +467,97 @@ describe('the code cannot be guessed: verify attempts are limited per account',
})
})
// Uses the account `[email protected]` (admin role, TOTP never set up). Order matters inside this block.
describe('2FA setup required: an account without TOTP reaches nothing but setup', () => {
const NEW_SECRET = 'MFRGGZDFMZTWQ2LK'
const idOf = async (email: string) => (await payload.find({ collection: 'users' as never, where: { email: { equals: email } } })).docs[0].id
const setup = (session: Session) => api('/setup-totp', session, { body: JSON.stringify({ secret: NEW_SECRET, token: totp(NEW_SECRET) }), method: 'POST' })
test('REST: every collection and global is refused, for reading and for writing', async () => {
const open: string[] = []
for (const [kind, slugs] of [['collection', [...pluginCollections, 'pages']], ['global', pluginGlobals]] as const) {
for (const slug of slugs) {
if ((await readStatus(kind, slug, sessions.newcomer)) !== 403) {open.push(`read ${kind} ${slug}`)}
if ((await writeStatus(kind, slug, sessions.newcomer)) !== 403) {open.push(`write ${kind} ${slug}`)}
}
}
expect(open).toEqual([])
const integrations = await api('/globals/site-integrations', sessions.newcomer)
expect(await integrations.text()).not.toContain('S3CRET')
})
test('GraphQL and the staff endpoints refuse too', async () => {
for (const query of ['{ SiteIntegration { smtpPassword } }', '{ FormSubmissions { totalDocs } }', '{ Users { totalDocs } }', 'mutation { updateSiteSetting(data: { siteName: "x" }) { siteName } }']) {
const out = await gql(sessions.newcomer, query)
expect(out.errors?.length, `${query} → ${JSON.stringify(out)}`).toBeGreaterThan(0)
expect(JSON.stringify(out)).not.toContain('S3CRET')
}
expect((await api('/ipal/test-email', sessions.newcomer, { body: '{}', method: 'POST' })).status).toBe(403)
expect((await api('/ipal/cookie-scan', sessions.newcomer)).status).toBe(403)
expect((await api('/ipal/two-factor/reset', sessions.newcomer, { body: JSON.stringify({ userId: await idOf('[email protected]') }), method: 'POST' })).status).toBe(403)
})
test('the window start is stamped at creation and cannot be written through the API', async () => {
const id = await idOf('[email protected]')
const doc = (await payload.findByID({ id, collection: 'users' as never })) as unknown as { totpSetupFrom?: string }
expect(Date.now() - new Date(doc.totpSetupFrom!).getTime()).toBeLessThan(120_000)
const patch = await api(`/users/${id}`, sessions.verified, { body: JSON.stringify({ totpSetupFrom: '2030-01-01T00:00:00.000Z' }), method: 'PATCH' })
expect(patch.status).toBe(200)
const after = (await payload.findByID({ id, collection: 'users' as never })) as unknown as { totpSetupFrom?: string }
expect(after.totpSetupFrom).toBe(doc.totpSetupFrom)
})
test('after the window the account is blocked: setup refused with a message, in the admin language', async () => {
const id = await idOf('[email protected]')
await payload.update({ id, collection: 'users' as never, data: { totpSetupFrom: new Date(Date.now() - 73 * 3_600_000).toISOString() } as never })
const res = await setup(sessions.newcomer)
expect(res.status).toBe(403)
expect(((await res.json()) as { message: string }).message).toMatch(/time to set up two-step verification has passed/i)
const pl = await api('/setup-totp', { headers: { ...sessions.newcomer.headers, 'accept-language': 'pl' } }, { body: JSON.stringify({ secret: NEW_SECRET, token: totp(NEW_SECRET) }), method: 'POST' })
expect(((await pl.json()) as { message: string }).message).toMatch(/Czas na ustawienie weryfikacji dwuetapowej minął/)
expect((await api('/globals/site-integrations', sessions.newcomer)).status).toBe(403)
})
test('only a fully logged-in admin reopens setup', async () => {
const userId = await idOf('[email protected]')
const reset = (session: Session) => api('/ipal/two-factor/reset', session, { body: JSON.stringify({ userId }), method: 'POST' })
for (const session of [sessions.anonymous, sessions.customer, sessions.member, sessions.passwordOnly, sessions.newcomer]) {
expect((await reset(session)).status).toBe(403)
}
expect((await setup(sessions.newcomer)).status).toBe(403) // still blocked
const ok = await reset(sessions.verified)
expect(ok.status).toBe(200)
const doc = (await payload.findByID({ id: userId, collection: 'users' as never })) as unknown as { totpSetupFrom: string }
expect(Date.now() - new Date(doc.totpSetupFrom).getTime()).toBeLessThan(120_000)
})
test('inside the window it sets TOTP up, and then everything its role allows opens', async () => {
const res = await setup(sessions.newcomer)
expect(res.status).toBe(200)
expect(((await res.json()) as { ok: boolean }).ok).toBe(true)
const full: Session = { headers: { ...sessions.newcomer.headers, cookie: cookiesOf(res).join('; ') } }
expect((await api('/globals/site-integrations', full)).status).toBe(200)
expect((await api('/form-submissions', full)).status).toBe(200)
expect((await api('/users/me', full)).status).toBe(200)
// without the 2FA cookie the same token is a password-only session again
expect((await api('/globals/site-integrations', sessions.newcomer)).status).toBe(403)
})
test('accounts from before the mode get their window when the site starts', async () => {
const { backfillSetupFrom } = await import('../src/modules/security/totp/setupRequired.js')
const legacy = await payload.create({ collection: 'users' as never, data: { email: '[email protected]', password: PASSWORD, roles: ['editor'] } as never })
await payload.db.updateOne({ id: legacy.id, collection: 'users' as never, data: { totpSetupFrom: null } as never })
expect(await backfillSetupFrom(payload, 'users')).toBe(1)
const doc = (await payload.findByID({ id: legacy.id, collection: 'users' as never })) as unknown as { totpSetupFrom: string }
expect(Date.now() - new Date(doc.totpSetupFrom).getTime()).toBeLessThan(120_000)
expect(await backfillSetupFrom(payload, 'users')).toBe(0)
// accounts that have TOTP are left alone
const admin = (await payload.findByID({ id: await idOf('[email protected]'), collection: 'users' as never })) as unknown as { totpSetupFrom?: string }
expect(admin.totpSetupFrom).toBeTruthy()
})
})
// Last: it replaces the running config.
describe('dev hot reload', () => {
test('a freshly built config is guarded again, also what a later plugin added', async () => {
+91
View File
@@ -0,0 +1,91 @@
/**
* A fresh site with "2FA setup required": the first admin is created on Payload's "Create first user" screen
* (POST /api/users/first-register), reaches nothing until it has set TOTP up, and everything afterwards.
* Real HTTP, see securityHttp.test.ts.
*/
import type { Payload } from 'payload'
import { payloadTotp } from '@clocklimited/payload-2fa'
import { lexicalEditor } from '@payloadcms/richtext-lexical'
import os from 'os'
import path from 'path'
import { getPayload } from 'payload'
import { afterAll, beforeAll, expect, test, vi } from 'vitest'
import { ipalKit } from '../src/plugin.js'
import { buildTestConfig } from './helpers.js'
import { testDatabase } from './http/db.js'
import { cookiesOf, startPayloadServer, type TestServer } from './http/server.js'
import { totp } from './http/totp.js'
vi.mock('server-only', () => ({}))
vi.mock('next/headers.js', async () => (await import('./http/server.js')).nextHeadersMock)
const SECRET = 'JBSWY3DPEHPK3PXP'
let server: TestServer
let payload: Payload
beforeAll(async () => {
const config = buildTestConfig({
collections: [{ slug: 'media', fields: [], upload: { staticDir: path.join(os.tmpdir(), 'ipal-test-media') } }],
db: testDatabase('sechttp_first'),
editor: lexicalEditor(),
plugins: [
ipalKit({
access: { authCollection: 'users' },
forms: {},
i18n: { defaultLocale: 'pl', locales: [{ code: 'pl', label: 'Polski' }] },
twoFactor: { issuer: 'Example', plugin: payloadTotp },
}),
],
secret: 'integration-test-secret-0123456789',
telemetry: false,
})
payload = await getPayload({ config })
server = await startPayloadServer(config)
}, 120_000)
afterAll(async () => {
await server?.close()
await payload?.destroy?.()
})
const json = { 'content-type': 'application/json' }
test('the first admin: created, locked until TOTP is set up, then in', async () => {
const register = await fetch(`${server.url}/api/users/first-register`, {
body: JSON.stringify({ email: '[email protected]', password: 'a-long-test-password-1' }),
headers: json,
method: 'POST',
})
expect(register.status).toBe(200)
const body = (await register.json()) as { token?: string; user: { roles: string[] } }
expect(body.user.roles).toEqual(['admin'])
const cookie = cookiesOf(register).join('; ')
expect(cookie).toContain('payload-token')
for (const p of ['/globals/site-integrations', '/users', '/form-submissions', '/globals/site-settings']) {
expect([p, (await fetch(`${server.url}/api${p}`, { headers: { cookie } })).status]).toEqual([p, 403])
}
const setup = await fetch(`${server.url}/api/setup-totp`, { body: JSON.stringify({ secret: SECRET, token: totp(SECRET) }), headers: { ...json, cookie }, method: 'POST' })
expect(((await setup.json()) as { ok: boolean }).ok).toBe(true)
const full = [cookie, ...cookiesOf(setup)].join('; ')
for (const p of ['/globals/site-integrations', '/users', '/form-submissions']) {
expect([p, (await fetch(`${server.url}/api${p}`, { headers: { cookie: full } })).status]).toEqual([p, 200])
}
// the admin creates an editor: it gets its own setup window
const created = await fetch(`${server.url}/api/users`, {
body: JSON.stringify({ email: '[email protected]', password: 'a-long-test-password-2', roles: ['editor'] }),
headers: { ...json, cookie: full },
method: 'POST',
})
expect(created.status).toBe(201)
const editor = (await payload.find({ collection: 'users' as never, where: { email: { equals: '[email protected]' } } })).docs[0] as unknown as { totpSetupFrom?: string }
expect(editor.totpSetupFrom).toBeTruthy()
})
test('seeds and scripts are not affected: the Local API still reads and writes', async () => {
await payload.updateGlobal({ slug: 'site-settings' as never, data: { siteName: 'Seeded' } as never })
expect(((await payload.findGlobal({ slug: 'site-settings' as never })) as { siteName: string }).siteName).toBe('Seeded')
})