Compare commits

...
16 Commits
Author SHA1 Message Date
Radosław SmolińskiandClaude Opus 5.5 1270ebc3d1 1.16.6 upgrade notes
CI / check (push) Failing after 5m28s
CI / reference (push) Skipped
CI / reference-full (push) Skipped
Co-Authored-By: Claude Opus 5.5 <[email protected]>
2026-11-24 20:38:42 +01:00
Radosław SmolińskiandClaude Opus 5.5 0356a329ca 1.16.6
Co-Authored-By: Claude Opus 5.5 <[email protected]>
2026-11-24 20:38:42 +01:00
Radosław SmolińskiandClaude Opus 5.5 b3a5ea1323 Merge claude/2fa-setup-required: an account without 2FA can only set it up (twoFactor.requireSetup)
Co-Authored-By: Claude Opus 5.5 <[email protected]>
2026-11-24 20:38:00 +01:00
Radosław SmolińskiandClaude Fable 5.2 b52193ae47 2FA setup required: the missing-column log reads the error's cause chain
R3-1: the SQL adapters throw "Failed query: …" and put the database's own words
("column … does not exist", "no such column") in the error's cause, so the loud
start-up line never appeared on a real Postgres or SQLite. The reason is now
built from the whole cause chain; other failures (ECONNREFUSED, a locked
database) still only warn. Tested with wrapped errors and against the real
adapter with the column dropped.

Docs and the doctor's fix text name how the migration is applied
(deployment.md 4.3) wherever they said only "before the site serves".

Co-Authored-By: Claude Fable 5.2 <[email protected]>
2026-11-24 20:31:44 +01:00
Radosław SmolińskiandClaude Fable 5.2 01e3813723 2FA setup required: review round 2 — no SVG from the icon endpoint, migrations at container start
R2-1: /api/ipal/admin-icon answers with bytes only for a bitmap recognised by its
first bytes (PNG, JPEG, GIF, WebP, ICO, AVIF). An SVG favicon keeps the redirect
to the media file: a site-wide CSP rule overrides a route's own sandbox header,
so the header alone protected nothing in a built site. buildUploadSecurityHeaders
also returns a rule for the icon path, as a second layer.
R2-2: the SQL migration runs when the new container starts (prodMigrations, or
the start command), never in Coolify's pre-deployment command; docs and the log
line say so and point to deployment.md 4.3.
R2-3: requireSetup: null is the default. R2-4: the missing-column log line only
for a column error. R2-5, R2-6: the resetAccess example keeps the code check;
with guard: false the reset endpoint does not exist.

Co-Authored-By: Claude Fable 5.2 <[email protected]>
2026-11-24 20:18:47 +01:00
Radosław SmolińskiandClaude Fable 5.2 75a6f5209e 2FA setup required: review fixes (SR-1 to SR-9)
SR-1: /api/ipal/admin-icon sends the upload security headers (sandbox policy,
nosniff) with the bytes: an SVG is shown, never run. fetchPublicImage stops
reading at the size limit.
SR-2: requireSetup.exempt exempts only on exactly true; an async function, and a
windowHours that is not a number or false, stop the start.
SR-3: on Postgres / SQLite the missing column makes every login fail: the log
says so, the docs call the migration a required step of the same deploy, and
ipal-doctor reports a SQL project without it.
SR-4: an admin's reset also ends the account's sessions.
SR-5: the reset needs a session that entered its own TOTP code by default.
SR-6: the doctor's import-map rule covers TwoFactorStatusField and TwoFactorAlert.
SR-7: building blocks exported; dashboard notice, status field, setup notice and
the server-side image fetch can be switched off one by one.
SR-8: totpSetupFrom is on the 2FA collection whenever 2FA is on.
SR-9: both ways out of "every administrator is blocked" in security.md.

Co-Authored-By: Claude Fable 5.2 <[email protected]>
2026-11-24 19:32:34 +01:00
Radosław SmolińskiandClaude Fable 5.2 9d2ab43438 2FA setup required: the window of existing accounts starts once, at the first start after the upgrade
Owner's decision: for accounts that exist before the upgrade the 72 hours
count from the first start after it. The code already stamped them then; this
adds the tests that the moment is written once per account (a restart, two
instances starting at once, edits and logins do not move it; 71 h after it setup
is open, 73 h after it the account is blocked) and says so in the docs.

After the rebase on 1.16.5: tests that the setup-required notice and the stale
import-map notice both stand above the screen and never replace the code form,
and that requireSetup, safeBack and guard switch independently.

Co-Authored-By: Claude Fable 5.2 <[email protected]>
2026-11-24 18:56:07 +01:00
Radosław SmolińskiandClaude Fable 5.2 5d44ac3135 2FA screens: the brand image loads for a session that still owes its code; browser spec checks it
The tab icon endpoint answers with the image itself instead of a redirect
to the media file, and the logo components hand a session that owes its
2FA code (or has not set 2FA up) the picture fetched without credentials,
as an anonymous visitor gets it. Who can read media is unchanged; when the
file is not public or is larger than 512 KB the site name is used.

Co-Authored-By: Claude Fable 5.2 <[email protected]>
2026-11-24 18:46:32 +01:00
Radosław SmolińskiandClaude Fable 5.2 2aaaaa115a 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]>
2026-11-24 18:46:32 +01:00
Radosław SmolińskiandClaude Opus 5.5 45d52c4690 1.16.5 upgrade notes
CI / check (push) Failing after 5m27s
CI / reference (push) Skipped
CI / reference-full (push) Skipped
Co-Authored-By: Claude Opus 5.5 <[email protected]>
2026-11-24 17:50:25 +01:00
Radosław SmolińskiandClaude Opus 5.5 bef3a682b8 1.16.5
Co-Authored-By: Claude Opus 5.5 <[email protected]>
2026-11-24 17:50:25 +01:00
Radosław SmolińskiandClaude Opus 5.5 f96b5c15d0 Merge claude/2fa-safe-back: the back link of the 2FA screens is checked on the server (twoFactor.safeBack)
Co-Authored-By: Claude Opus 5.5 <[email protected]>
2026-11-24 17:49:47 +01:00
Radosław SmolińskiandClaude Fable 5.2 3eee841dd0 ipal-doctor: the raw 2FA view warning only for a view component
R3-1: the warning fired on any mention of the 2FA package's setup / verify view
in the config, so it stayed after the fix its own text suggests (SafeTotpView
with the path as ipalTotpView, plus the path in admin.dependencies). It now
warns only when the path is a view's Component.

Co-Authored-By: Claude Fable 5.2 <[email protected]>
2026-11-24 17:49:06 +01:00
Radosław SmolińskiandClaude Fable 5.2 b2c1dca5da 2FA back link: the stale import-map notice never replaces the screen
R2-1: the notice was rendered instead of the 2FA screen, and its flag is a text
search of the importMap.js on disk — not the map in the build. A false alarm
(map generated in the build with the repository's file in the running image, a
re-exporting map) hid a working code form and locked everyone out. The notice
is now rendered above the screen, the log line says "may be", and the flag goes
to ipal-kit's own provider only.

R2-2: views are compared against copies, so a factory that reuses its view
objects is guarded too; copyViews, changedViewKeys, SAFE_TOTP_VIEW,
totpViewImportKey, findImportMapFile and missingImportMapEntries are exported;
ipal-doctor warns when the config registers the 2FA package's own view; docs
wording and a misplaced comment fixed.

Co-Authored-By: Claude Fable 5.2 <[email protected]>
2026-11-24 16:35:16 +01:00
Radosław SmolińskiandClaude Fable 5.2 ad51456eaa 2FA back link: review fixes — views guarded by object, client views, a loud stale import map
SB-1: the 2FA package replaces a view that already stands under its keys, so a
key that existed before the factory ran was wrongly treated as the project's own
and left unguarded (also with a double registration, or ipalKit over its own
output). Views are now compared by object, right after the factory.

SB-2: SafeTotpView renders through Payload's RenderServerComponent: a client
component set as a 2FA view gets only client props plus the checked back.

SB-3: a production build with the previous import map shows an empty 2FA screen.
twoFactor.importMapCheck (on, production only) reads the committed map at start:
an error in the log and a message on the 2FA screens. Docs name the real symptom.

SB-4: enabled: false restores admin.dependencies; wrapTotpViews keeps exportName.

Co-Authored-By: Claude Fable 5.2 <[email protected]>
2026-11-24 16:16:39 +01:00
Radosław SmolińskiandClaude Fable 5.2 93e75426ab 2FA screens: the back link is checked on the server (twoFactor.safeBack)
@clocklimited/payload-2fa sends the browser to the `back` query value after a
valid code without checking it (GHSA-rffw-fq79-g3ch upstream, not fixed in the
fork): a prepared link ran script in the panel or left the site.

SafeTotpView now stands in front of the package's setup and verify views and
passes on a checked value: a path on the site's origin inside the admin route,
else the admin root. The package's views stay in the import map through
admin.dependencies, so ipal-kit still never imports the package.

twoFactor.safeBack: false turns it off, a function replaces the rule;
safeAdminBack, wrapTotpViews and SafeTotpView are exported. Projects with 2FA
must regenerate the admin import map.

Co-Authored-By: Claude Fable 5.2 <[email protected]>
2026-11-24 15:29:06 +01:00
62 changed files with 3896 additions and 85 deletions
+170
View File
@@ -8,6 +8,176 @@ versions at once, go through every "Requires project changes" section in order,
version you have. A new release = a new section at the top; we remove the oldest ones only
once there are more than 20.
## 1.16.6
> **Read before upgrading — this is not a routine patch.** It turns on a new default for every site with 2FA: an
> account that has not set 2FA up can do nothing but set it up, and is **blocked after 72 hours** until an
> administrator reopens it. On Postgres / SQLite it also needs a **migration in the same deploy, or nobody can log
> in**. Work through the list below, and agree the deploy day with the owner.
### Requires project changes (what projects must update)
**Every site with 2FA on. Do all of it in ONE deploy.**
- **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 (better two) must have 2FA set up, or nobody can reopen setup
from the panel.
- **Agree the day with the owner:** the 72 hours of every existing account without 2FA start at the deploy,
once. Deploy when those people can act within three days (not before a holiday), or have them set 2FA up first.
- **In the same deploy:** the update, `pnpm payload generate:types`, `pnpm payload generate:importmap` (commit
`importMap.js`; new: `TwoFactorStatusField`, `TwoFactorAlert`), `rm -rf .next`, redeploy. Run
`pnpm exec ipal-doctor` before deploying: it reports a map without the new entries (then the panel has no "Reopen
setup"). Coming from before 1.16.5, the map must also have `SafeTotpView`, or the 2FA screens have no code form.
- **Postgres / SQLite — required, in the same deploy: `pnpm payload migrate:create`, commit, and the migration
applied when the new container starts** (`prodMigrations`, or `pnpm payload migrate && pnpm start` —
[deployment.md §4.3](./deployment.md#43-database-migrations-postgres); not Coolify's Pre-deployment command,
which runs in the old container). The 2FA collection gets the column `totp_setup_from`.
**Without it every login answers 500 — administrators with 2FA included — and nobody can sign in to the
panel.** The log says so at start (`NOBODY CAN LOG IN`), and `ipal-doctor` reports a SQL project whose
migrations do not mention the column. Every project with 2FA on needs it, also with `requireSetup: false`.
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 })`.
- **A reset by an administrator logs that account out everywhere** and needs the administrator's own TOTP code. A
script on an API key needs `twoFactor.resetAccess`. After a suspected compromise change the password too.
- **Options:** `windowHours` is a number (0 or more) or `false`; `exempt` is a plain function returning exactly
`true`, never `async`. A wrong value stops the build and the start with a clear error.
- **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. Tell the staff: a new account has
72 hours to set 2FA up. `pnpm ipal:skills`.
- **An SVG favicon** has no tab icon on the 2FA screens (use a PNG if that matters).
- **Every administrator is blocked:** security.md "Every administrator is blocked" (a script, or
`{ windowHours: false }` and a redeploy).
- **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.
### 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.
That moment is written on each account once: later restarts, redeploys and further instances do not move it,
nor does editing the account.
- **A reset by an administrator ends the account's sessions**, and by default needs a session that entered its
own TOTP code (not an API key, not an exempt account).
- **`/api/ipal/admin-icon` answers with the favicon itself when it is a bitmap** (PNG, JPEG, GIF, WebP, ICO,
AVIF — recognised by its bytes) instead of a redirect, so the tab icon also loads on the 2FA screens. An SVG
favicon is never answered from there (an SVG can carry script): it keeps the redirect to the media file.
`adminMeta.serveIcon: false` = always the redirect. `buildUploadSecurityHeaders()` now also returns a rule for
the icon path (`adminIcon: false` leaves it out).
### 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, dashboardNotice, statusField, setupNotice }`,
`twoFactor.resetAccess`, `whiteLabel.inlineImages`, `adminMeta.serveIcon`. Exports: `twoFactorSetupState`,
`twoFactorSetupDeadline`, `buildSetupFields`, `stampSetupFrom`, `backfillSetupFrom`,
`buildTwoFactorResetEndpoint`, `countAccountsWithoutTotp`, `resolveRequireSetup`, `strictExempt`,
`SETUP_FROM_FIELD`, `TWO_FACTOR_RESET_PATH`, `DEFAULT_SETUP_WINDOW_HOURS`, `fetchPublicImage`,
`publicImageDataUri`, `rasterImageType`, `siteOrigin`, `PUBLIC_IMAGE_MAX_BYTES`, `UPLOAD_SECURITY_HEADERS`; admin components
`TwoFactorStatusField`, `TwoFactorResetButton`, `TwoFactorAlert`.
- `requireSetup.exempt` is strict: only an answer of exactly `true` exempts. An `async` function, and a
`windowHours` that is not a number or `false`, stop the site at start with a clear error.
- The date field `totpSetupFrom` is on the 2FA collection whenever 2FA is on, so switching `requireSetup` or
`guard` never changes the schema (and never restarts anyone's window).
- The panel's tab icon and logo load on the verify and setup screens: `GET /api/ipal/admin-icon` answers with the
image itself when it is a bitmap (no redirect to the media file), and the logo components give a session that still owes its code
the picture as an anonymous visitor would get it. No change to who can read `media`.
- ipal-doctor: a SQL project without a migration for `totp_setup_from` (error), an import map without the two
new admin components (error).
- 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.
### Known limitations
- **Inside the window** someone who knows the password of an account without 2FA can still set it up with their own
authenticator; the owner is then refused ("already set") and has to ask an administrator. Set 2FA up at once.
- A session without 2FA keeps what Payload gives any session about itself: `/api/access`, token refresh, logout, its own
panel preferences.
- **An exempt account** works on its password alone, with everything its role allows: give it the lowest role.
- A second staff collection (`access.staffCollections`) is outside 2FA and outside this mode, as before. With
`twoFactor.guard: false` the mode is off and the reset endpoint does not exist.
- With `auth.useSessions: false` a reset has no sessions to end: tokens live until they expire. The 2FA package's own
remove / reset endpoints do not end sessions.
- The `ipal-doctor` migration check is a text search in `src/migrations` and `migrations`.
- A site that does not use `buildUploadSecurityHeaders()` still serves a scripted SVG from its media URL as before.
- **Not run for this release:** a generated migration, `prodMigrations` and a real Coolify deploy (the missing and the
added column were tested on Postgres 17 and SQLite); an upgrade of a real site; two containers; media on R2 / S3;
`useSessions: false`; the reset by an API-key admin over HTTP; payload-2fa beta.1 and the Polish notices in a
browser; Firefox / WebKit; a Docker image; a Next `basePath`; Payload below 3.94.1.
## 1.16.5
### Security
- **The 2FA setup and verify screens no longer follow an unchecked `back` link.** `@clocklimited/payload-2fa`
(beta.1 to beta.7) sends the browser to the `back` query value once the code is accepted, without checking it.
A panel user who had typed the password, opened a prepared link to `/admin/verify-totp` or `/admin/setup-totp`
and then entered the code could be sent to another site, or have script run in the panel under their freshly
verified session. The panel's CSP does not stop this. **Affects every site with 2FA on, in every earlier
version.** It needs the user to open such a link between the password and the code; a logged-out or a fully
logged-in user is not affected. The original package fixed it in `payload-totp` 3.0.5 (GHSA-rffw-fq79-g3ch);
the fork has not.
Now ipal-kit checks `back` on the server before the package's screen gets it: only a path on the site's own
origin, inside the admin route, is kept; anything else leads to the admin root
([security.md](./security.md) "The `back` link of the 2FA screens"). The 2FA package itself is unchanged.
### Added
- **`twoFactor.safeBack`** — on by default; `false` turns the check off, a function
`(back, { adminRoute, origin }) => string` replaces the rule.
- **`safeAdminBack`**, **`wrapTotpViews`** (`@intecion/ipal-kit`) and **`SafeTotpView`**
(`@intecion/ipal-kit/admin`) are exported for projects that register the 2FA views themselves.
- **ipal-doctor**: the import-map rule also expects `@intecion/ipal-kit/admin#SafeTotpView` when the installed
plugin has it and the config does not set `safeBack: false`.
- **A stale import map is reported** (`twoFactor.importMapCheck`, on by default, `false` turns it off): in
production the plugin searches the `importMap.js` on disk at start; when the entry above is not found it logs
an error and puts a notice above the 2FA screens. The notice never replaces the screen: the file on disk is
not always the map the build used (a Dockerfile with a separate runner stage, a re-exporting map file), and
then the notice is wrong and sign-in still works — turn the check off for such a project.
- **More building blocks exported** for a project that wraps the 2FA views itself: `copyViews`,
`changedViewKeys`, `SAFE_TOTP_VIEW`, `totpViewImportKey`, `findImportMapFile`, `missingImportMapEntries`.
- **ipal-doctor** warns when the config uses the 2FA package's own setup / verify view as a view's `Component`
(such a view is outside the check).
- **A project's own 2FA screen set through the wrapped factory** (a server or a client component) is rendered
behind the check and gets the checked `back`.
### Requires project changes
- **Every site with 2FA: upgrade, `pnpm payload generate:importmap`, commit `importMap.js`, `rm -rf .next`,
redeploy — all in ONE deploy. Run `pnpm exec ipal-doctor` before deploying.** The plugin's view now stands in front of the package's two screens and
needs its import-map entry (`@intecion/ipal-kit/admin#SafeTotpView`). **If you skip this, the build still
passes and the site starts, but the 2FA setup and verify screens have no code form (HTTP 200), so nobody can
sign in to the panel.** There is no error page. What tells you: `pnpm exec ipal-doctor` before the deploy
(`import map lacks …SafeTotpView`); the line `[ipal] The admin import map may be out of date` in the log at
every start; and, where the form should be, the notice "Two-step verification may not be available". No
option, env, schema or migration. `pnpm ipal:skills` afterwards.
- **A project with its own 2FA screens or view registrations:** security.md "Your own 2FA screen".
- **Check after deploy:** log in with the password only, open
`/admin/verify-totp?back=https%3A%2F%2Fexample.com%2F`, enter the code → you land on `/admin`. A normal login
still returns to the page you came from.
### Known limitations
- After the code, the screen always goes somewhere inside the panel. A `back` that pointed at a page of the
public site (not used by the plugin or the package) now leads to the admin root; pass your own rule if a
project relied on that.
- An absolute `back` on the site's own origin is kept only when the Payload config has `serverURL`; without it
only relative values are (the plugin and the package only ever produce relative ones).
- A missing `back` used to mean "go back in browser history"; it now means the admin root.
- `back=/admin/logout` is inside the panel and is followed: the user is logged out after the code.
- A client-side 2FA screen of your own that reads `useSearchParams()` gets the raw value; use the `back` prop.
- The stale import map check is a text search of the file on disk: it can warn although everything works, and
its notice text changes only with an own `twoFactor.provider`. The `ipal-doctor` warning about a raw view is a
text search too and misses unusual spellings.
- **Not run for this release:** the browser checks on Postgres, in Firefox or WebKit, with a Next `basePath` or in a
real Docker image with a runner stage; payload-2fa beta.2 to beta.6; Payload 3.90 to 3.93. They ran in Chromium on
MongoDB with beta.7 (production build) and, on an earlier commit of the same change, beta.1 (`next dev`).
## 1.16.4
### Security
+2 -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).
+3 -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`; 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,8 +1165,10 @@ 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`; parts: `requireSetup: { dashboardNotice: false, statusField: false, setupNotice: false }` | `requireSetup: { windowHours, exempt }` (`exempt` returns exactly `true`, never `async`), `twoFactor.resetAccess` (default: an admin who entered its own code; the reset ends the account's sessions), texts `twoFactor*`; `twoFactorSetupState(req)`, `buildSetupFields`, `backfillSetupFrom`, `buildTwoFactorResetEndpoint`. **Postgres/SQLite: migration for `totp_setup_from` applied when the new container starts (`prodMigrations` or `pnpm payload migrate && pnpm start`; never a pre-deployment command — deployment.md §4.3), or every login answers 500** |
| The second factor on every collection and global, whichever plugin added it, and on the plugin's endpoints; an unrecognised 2FA package = startup error | per entity: `custom.ipal.secondFactor: false` or `{ read: false }` (or the package's `custom.totp.disableAccessWrapper`); everywhere: `twoFactor.guard: false` (not recommended) | `requireSecondFactor` / `secondFactorPassed` in your own access functions and endpoints |
| At most 5 verify attempts per account in 10 minutes (`POST /api/verify-totp` → `429`) | `twoFactor.verifyLimit: false` | `verifyLimit: { max, windowMinutes }` |
| The `back` link of the 2FA setup and verify screens is checked on the server (`SafeTotpView` in front of the package's views): only a path on the site's origin inside the admin route is kept, anything else (`javascript:`, another host) becomes the admin root. Needs `generate:importmap` in the same deploy — with a stale map the 2FA screens have no code form and nobody can sign in (`ipal-doctor`, the start log and a notice above the screen report it; the notice is a hint from the file on disk and never replaces the screen; `twoFactor.importMapCheck: false` turns it off); check: password only → `/admin/verify-totp?back=https%3A%2F%2Fexample.com%2F` → code → lands on `/admin` | `twoFactor.safeBack: false` | `safeBack: (back, { adminRoute, origin }) => string`; `safeAdminBack`, `wrapTotpViews` (`@intecion/ipal-kit`), `SafeTotpView` (`@intecion/ipal-kit/admin`) for own views |
| The 2FA package's endpoints (`/api/setup-totp`, `verify-totp`, `remove-totp`, `admin/*`) answer accounts of the 2FA collection only; reset and remove need the second factor | — (always on with 2FA) | `adminManageAccess` through the wrapped factory (security.md "Resetting 2FA") |
| Roles count only for accounts of a staff collection, in every predicate and access function | — | `access.staffCollections` |
| `enabled: false` keeps the schema | — | — (no endpoints, `onInit` or admin components; no DROP TABLE in `migrate:create`) |
+3 -1
View File
@@ -2,7 +2,7 @@
<!-- Generated by scripts/reference-index.mjs from reference/ — do not edit by hand (pnpm reference:index). -->
The reference site is one complete client site on ipal-kit 1.16.4 ("Example Studio", made up) that uses
The reference site is one complete client site on ipal-kit 1.16.6 ("Example Studio", made up) that uses
every convention in AGENT.md. It lives in the plugin repo (`reference/`, not in the npm package). Copy the
PATTERN of the file you need; change only the project's content. Files up to
40 lines are below in full; open the rest in the repo at the tag of your plugin version:
@@ -1161,6 +1161,8 @@ Rules: AGENT.md §8a.
| `e2e/smoke.spec.ts` | the smoke tests every release must pass: pages, showcase, forms (also a file sent by e-mail), sitemap, SEO/GEO, headers, consent, 2FA |
| `e2e/smtp-sink.ts` | a local mail sink for the smoke tests: reads what the site really sent (recipients, attachments) |
| `e2e/totp.ts` | RFC 6238 code generator for the 2FA sign-in in the smoke test (below) |
| `e2e/two-factor-back.spec.ts` | browser test of the 2FA screens' `back` link (twoFactor.safeBack): a prepared link — script or another host — ends on the admin root, an ordinary one is followed |
| `e2e/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`.
+13
View File
@@ -37,6 +37,15 @@ 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 }`); every administrator is blocked: security.md "Every administrator 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; or `requireSetup: { windowHours: false }`, redeploy, set up, put it back |
| 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` |
| after an upgrade EVERY panel login answers `500` (also `/api/users/init`), administrators with 2FA included; log: `[ipal] 2FA: the column for "totpSetupFrom" is missing … NOBODY CAN LOG IN` or `column users.totp_setup_from does not exist` | Postgres/SQLite: the migration that adds the 2FA column has not run (needed whenever 2FA is on) | `pnpm payload migrate:create` if no migration has it, commit, and redeploy with migrations run when the new container starts — `prodMigrations` in the adapter or the start command `pnpm payload migrate && pnpm start` (deployment.md §4.3; not Coolify's Pre-deployment command, which runs in the old container); nothing is lost. `ipal-doctor` reports a project whose migrations lack `totp_setup_from` |
| the site does not start: `[ipal] twoFactor.requireSetup.exempt must not be async` / `…windowHours must be a number` | `exempt` is an `async` function, or `windowHours` is a string / negative | `exempt: ({ user }) => user.email === '…'` (returns `true` / `false` at once); `windowHours: 72` or `false` |
| log: `[ipal] twoFactor.requireSetup.exempt returned a Promise … The account is NOT exempt` (and the service account gets 403) | `exempt` does not return exactly `true` | return a boolean decided from the fields on `user` |
| an administrator's "Reset two-step verification" answers 403 from a script with an API key, or for an exempt account | by default the reset needs a session that entered its own TOTP code | reset from the panel after logging in with the code; or `twoFactor.resetAccess: ({ req }) => …` |
| after "Reset two-step verification" the user is logged out everywhere | intended: the reset ends the account's sessions | the user logs in again with the password and sets 2FA up; after a suspected compromise also change the password |
| no "Two-step verification" box on the account page / no "Reopen setup" | the import map lacks `TwoFactorStatusField` (not regenerated), or `requireSetup: { statusField: false }` | `pnpm payload generate:importmap`, commit, redeploy; meanwhile `POST /api/ipal/two-factor/reset` `{ userId }` works |
| "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") |
@@ -58,6 +67,10 @@ through this procedure. Ask only when you are missing something you cannot get y
| Symptom | Cause | Fix |
|---|---|---|
| `PayloadComponent not found in importMap` (e.g. `@intecion/ipal-kit/admin#RowLabel`) | importMap out of date after a plugin update / adding `rowLabel` | `pnpm payload generate:importmap`, restart |
| after an upgrade the 2FA setup / verify screen has no code form (HTTP 200), only the notice "Two-step verification may not be available" (or nothing at all with `importMapCheck: false` / an own provider); nobody can sign in; the log has `[ipal] The admin import map may be out of date` and `getFromImportMap: PayloadComponent not found in importMap … @intecion/ipal-kit/admin#SafeTotpView` | the import map was not regenerated after the upgrade that added the `back` link check (`twoFactor.safeBack`); the production build uses the committed, old `importMap.js` | `pnpm payload generate:importmap`, commit `importMap.js`, `rm -rf .next`, redeploy; `pnpm exec ipal-doctor` shows it before a deploy. The opposite case (wrapper present, package view missing) throws `[ipal] The admin import map has no "@clocklimited/payload-2fa/rsc#TOTPVerify"` — same fix |
| the notice "Two-step verification may not be available" and the log line `[ipal] The admin import map may be out of date` appear, but the code form is there and sign-in works | false alarm: the check searches the `importMap.js` on disk, which is not the map inside the build (map generated during the build and a Dockerfile runner stage that copies the repository's file; a map file that re-exports or computes its entries) | `twoFactor: { …, importMapCheck: false }`; or ship the generated `importMap.js` in the image |
| an own 2FA screen (set through the wrapped factory) ignores the check on `back` | a client component reading `useSearchParams()` gets the raw query value | read the `back` prop (or `searchParams.back`) the wrapper passes — both are checked (security.md "Your own 2FA screen") |
| after the 2FA code the user lands on `/admin` instead of the page in `back` | `back` pointed outside the admin route or to another origin (the check keeps only a path inside `routes.admin`; an absolute URL only on the `serverURL` origin) | expected; for another rule pass `twoFactor.safeBack: (back, { adminRoute, origin }) => string` (security.md) |
| new admin stuck on `/admin/setup-totp?back=null` (the page keeps redirecting to itself) | ipal-kit ≤ 1.14.1: the 2FA package's provider needs an `x-pathname` header nothing sets on `/admin`; or `twoFactor.provider: false` without that header | update ipal-kit, `pnpm payload generate:importmap` (`TotpRedirectProvider`), restart; check: `/admin/setup-totp?back=%2Fadmin` shows the QR (security.md) |
| `Cannot destructure property 'config'` / UI hooks without context | two copies of `@payloadcms/ui` | `pnpm why @payloadcms/ui`; one version + `pnpm.overrides`; `ls node_modules/@intecion/ipal-kit/node_modules/@payloadcms` = empty |
| empty SEO tab, no Forms | mismatched `@payloadcms/*` versions | all `@payloadcms/*` = the `payload` version |
+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 } })`.
@@ -37,9 +37,16 @@ description: Complete map of everything @intecion/ipal-kit provides — every ip
| `twoFactor.plugin` | — (required) | injected `payloadTotp` (the plugin does not import the peer) | missing function → throws |
| `twoFactor.collectionSlug` | the panel's login collection (`admin.user`, else the first auth collection) | collection with 2FA; startup fails with `[ipal] twoFactor…` when it is not an auth collection or differs from `admin.user` | point it at the login collection |
| `twoFactor.provider` | `'@intecion/ipal-kit/admin#TotpRedirectProvider'` | admin provider that sends users to `setup-totp` / `verify-totp` (path read in the browser); replaces the package's header-based one | own component path / `{ path, clientProps, serverProps }` (gets clientProps `forceSetup`); `false` keeps the package's (needs `x-pathname` on `/admin`, else `setup-totp?back=null` loops) |
| `twoFactor.safeBack` | on | the `back` query value of the 2FA setup and verify screens is checked on the server before the package's view gets it (`SafeTotpView` registered in place of the package's four views): kept only as a path on the site's origin inside `routes.admin`, else the admin root — no `javascript:` / off-site redirect after the code. Needs `generate:importmap` (`@intecion/ipal-kit/admin#SafeTotpView`) | `false` = the package's views untouched; a function `(back, { adminRoute, origin }) => string` = your own rule |
| `twoFactor.importMapCheck` | on | production only: at start searches the `importMap.js` on disk (where Payload looks for it) for `@intecion/ipal-kit/admin#SafeTotpView`; when not found, logs `[ipal] The admin import map may be out of date …` and ipal-kit's `TotpRedirectProvider` puts the notice "Two-step verification may not be available" above the 2FA screens (never instead of them). A hint only — the map in the build can differ from the file on disk (Dockerfile runner stage, re-exporting map); a file that is not found is not reported | `false` = no file read, log line or notice |
| `twoFactor.texts` | ipal-kit's en/pl texts (`TOTP_TEXTS`) over the package's; 2FA screens titled "Two-step verification" / "Weryfikacja dwuetapowa" (site's language) | `false` = the package's texts; one text: `i18n.translations.<lang>.totpPlugin.<key>` (security.md) |
| `twoFactor.guard` | on | ipal-kit's own second-factor check on every collection and global (also the plugin's own and those of plugins listed after ipalKit) and in `userMeetsRole`; startup fails with `[ipal] twoFactor: the injected 2FA plugin did not add …` when the 2FA package lacks the `totp` strategy / `hasTotp` / `totpSecret` | per entity: `custom.ipal.secondFactor: false` / `{ read: false }` or the package's `custom.totp.disableAccessWrapper.<op>`; `false` = the package's wrapper only (the plugin's own data then opens to a password without the code; not recommended). The package's endpoints stay limited to accounts of the 2FA collection either way |
| `twoFactor.verifyLimit` | `{ max: 5, windowMinutes: 10 }` | attempts per account on `POST /api/verify-totp` (the 2FA package counts none): the sixth in the window, right or wrong, gets `429` + `Retry-After`; in memory per instance | `{ max, windowMinutes }`; `false` = no limit |
| `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 field `totpSetupStatus` (panel) to the 2FA collection, a dashboard notice and `POST /api/ipal/two-factor/reset`; the date field `totpSetupFrom` is there whenever 2FA is on (also with `requireSetup: false` / `guard: false`). Existing accounts get their window at the first start after the upgrade, written once. **Postgres/SQLite: the migration must be applied when the new container starts — `prodMigrations` or `pnpm payload migrate && pnpm start`, not a pre-deployment command (deployment.md §4.3) — or every login answers 500**; `generate:importmap`. `exempt` must return exactly `true` at once (an `async` one, or a `windowHours` that is not a number / `false`, stops the start) | `false` = the package's rule (API open until setup); `{ windowHours: 24 }`, `{ windowHours: false }` (no limit), `{ exempt: ({ user }) => … }` (a service account) |
| `twoFactor.requireSetup.dashboardNotice` / `.statusField` / `.setupNotice` | on | the administrators' notice on the dashboard; the status and reset control on the account page; the notice on the setup screen | `false` each (the lock and the reset endpoint stay) |
| `twoFactor.resetAccess` (the endpoint exists with `twoFactor.guard` on; `guard: false` = no endpoint, 404) | a staff admin whose session entered its own TOTP code (not an API key, not an `exempt` account) | who may reset another account's TOTP / reopen its setup (the button on the account page, `POST /api/ipal/two-factor/reset`). The reset clears the secret and the account's sessions. A session that still owes its code is always refused | `({ req }) => boolean` — replaces the rule, so keep `req.user?._strategy === 'totp' &&` in it unless API-key / exempt admins should reset; only `true` allows; `req.user._strategy` tells `'totp'`, `'api-key'`, `'local-jwt'` apart |
| `whiteLabel.inlineImages` | on | on the 2FA screens the logo / icon is fetched by the server as an anonymous visitor gets it (max 512 KB) and inlined as `data:` — the session there is refused `media` | `false` = the browser tries the media URL |
| `adminMeta.serveIcon` | on | `/api/ipal/admin-icon` answers with the favicon's bytes when it is a bitmap (PNG, JPEG, GIF, WebP, ICO, AVIF by its bytes); an SVG favicon always gets a redirect to the media file (never SVG bytes from the site's origin) | `false` = always the redirect |
| `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 | — |
@@ -31,11 +31,15 @@ Admin panel components from `@intecion/ipal-kit/admin` — the project does NOT
| `CookieApprovalForm` | `@intecion/ipal-kit/admin` | Client part of the view: tick boxes, markers (New / Changed / Needs description), Edit links, the button. Props `pending`, `gone`, `unknownCategory`, `labels?`, `adminRoute?` — reuse it in your own view. |
| `CookieCrawlAlert` | `@intecion/ipal-kit/admin` | Server Component: dashboard warning — "Waiting for approval: N" with a link to the approval view, and with the crawl violations or a failed crawl; renders nothing otherwise. Props `approval`, `crawl`. Injected with `cookieScanner` (`approval.dashboard: false` / `crawl.dashboard: false` drop its parts); after turning it on, `pnpm generate:importmap`. |
| `CookieScanButton` | `@intecion/ipal-kit/admin` | "Scan cookies" box above the *Cookie review* list: integrations in use, optional extra names, runs `POST /api/ipal/cookie-scan`. Injected by the plugin with `cookieScanner`; after turning it on, `pnpm generate:importmap`. |
| `SafeTotpView` | `@intecion/ipal-kit/admin` | Server admin view in front of the 2FA package's setup and verify views: replaces the `back` query value with a checked one and renders the view named by the serverProp `ipalTotpView` (a path or `{ path, exportName }`, found in the import map) the way Payload renders a view: a server component gets all server props, a client component only Payload's client props, `ipalTotpClientProps`, `back` and `searchParams` (both checked). `ipalSafeBack` = own rule. Registered by the plugin with `twoFactor` (`twoFactor.safeBack`, on by default). After upgrading, `pnpm generate:importmap`. Check: password only → `/admin/verify-totp?back=https%3A%2F%2Fexample.com%2F` → code → `/admin`. Own registration: `Component: { path: '@intecion/ipal-kit/admin#SafeTotpView', serverProps: { ipalTotpView: '<path>' } }` + that path in `admin.dependencies`. |
| `TotpRedirectProvider` | `@intecion/ipal-kit/admin` | Client admin provider: sends a user without TOTP to `/admin/setup-totp?back=…` and a user whose session has not passed TOTP to `/admin/verify-totp?back=…` (path read in the browser; never redirects away from those screens or logout; renders nothing while redirecting). Injected by the plugin with `twoFactor` in place of the package's header-based provider; swap with `twoFactor.provider`. After upgrading, `pnpm generate:importmap`. Check: a new admin lands on `setup-totp?back=%2Fadmin` with the QR code. Props type `TotpRedirectProviderProps` (`forceSetup`) |
| `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) |
| `buildAdminImageEndpoints(resolved, { settingsSlug?, nameField?, logoField?, iconField? })` | `@intecion/ipal-kit` | `GET /api/ipal/admin-og` (1200×630 PNG via `next/og`) and `GET /api/ipal/admin-icon` (favicon redirect or initials) — already added by `adminMeta` |
| `buildAdminImageEndpoints(resolved, { settingsSlug?, nameField?, logoField?, iconField? })` | `@intecion/ipal-kit` | `GET /api/ipal/admin-og` (1200×630 PNG via `next/og`) and `GET /api/ipal/admin-icon` (the favicon itself, or initials) — already added by `adminMeta` |
| `DEFAULT_AGENCY`, `ADMIN_META_TEXTS` | `@intecion/ipal-kit` | Default agency `{ name: 'Intecion.com', url }`; en/pl meta texts (`{site}`, `{agency}`). Types `AdminMetaOptions`, `AgencyOption`, `ResolvedAdminMeta` |
## Readable array rows in the panel (`admin-ui`) — details: `node_modules/@intecion/ipal-kit/docs/links.md`
@@ -68,7 +72,7 @@ Admin panel components from `@intecion/ipal-kit/admin` — the project does NOT
| `buildRolesField(defaultRole?, { firstUserAdmin? })` | `@intecion/ipal-kit` | The `roles` select field the plugin injects (only admins set roles; `firstUserAdmin` default `true` = the account made on "Create first user" gets `admin`). The plugin wires it itself — use it only for an auth collection the plugin does not manage. |
| `injectRoles(config, accessOption)` | `@intecion/ipal-kit` | Adds `roles` to `accessOption.authCollection` in a config. The plugin calls it itself with `access` — do not call. |
**Types:** `VerifyLimitOptions` (`twoFactor.verifyLimit`: `{ max?, windowMinutes? }`), `Role` (`'user' \| 'editor' \| 'admin'`), `AccessOption` (the plugin's `access` option: `authCollection`, `defaultRole`, `authAccess`, `firstUserAdmin`, `staffCollections`).
**Types:** `VerifyLimitOptions` (`twoFactor.verifyLimit`: `{ max?, windowMinutes? }`), `RequireSetupOptions` (`twoFactor.requireSetup`), `TwoFactorResetOptions`, `TwoFactorSetupState`, `SafeBackRule` / `SafeBackContext` (`twoFactor.safeBack` as a function: `(back, { adminRoute, origin? }) => string`), `TotpViewComponent` (a view component as registered: a path or `{ path, exportName?, clientProps?, serverProps? }`), `SafeTotpViewProps` (`@intecion/ipal-kit/admin`), `Role` (`'user' \| 'editor' \| 'admin'`), `AccessOption` (the plugin's `access` option: `authCollection`, `defaultRole`, `authAccess`, `firstUserAdmin`, `staffCollections`).
## Accessibility — widget (`accessibility`) — details: `node_modules/@intecion/ipal-kit/docs/accessibility.md`
@@ -586,6 +590,18 @@ Server only (`pnpm payload run`); never import it from client code, the Payload
| `buildSecurityHeaders({ hsts?, csp?, additional?, coop?, frameOptions?, permissionsPolicy?, referrerPolicy?, … })` | `@intecion/ipal-kit` | Returns `SecurityHeader[]` (HSTS, X-Frame-Options, nosniff, Referrer-Policy, Permissions-Policy, COOP; with `IPAL_NOINDEX` also `X-Robots-Tag`) for `headers()` in `next.config.ts`. `csp` = `buildCsp` args → the CSP header (+ `Reporting-Endpoints` with `reportUri`); off by default. `additional` overrides by key. |
| `withSecurityConfig(nextConfig, { hidePoweredBy? })` | `@intecion/ipal-kit` | Next config wrapper: `poweredByHeader: false` + drops `X-Powered-By` from `headers()` (Next's "Next.js" and withPayload's "Next.js, Payload"). `withPayload(withSecurityConfig(nextConfig))`; `hidePoweredBy: false` = no change. |
| `secondFactorPassed(req)` | `@intecion/ipal-kit` | `boolean` with `req` (`{ payload, user }`): `false` only for an account of the 2FA collection that has TOTP set up and has not entered the code in this session (password only). `true` for a full login, an API key, an account that has not set TOTP up yet, accounts of other auth collections, no user, and with `twoFactor: false`. Guard your own endpoints with it: `if (!req.user \|\| !secondFactorPassed(req)) return 403`. |
| `safeAdminBack(back, { adminRoute, origin? })` | `@intecion/ipal-kit` | The default `back` rule of the 2FA screens: returns `back` as a path when it resolves to the site's origin (the placeholder origin for relative values, `origin` for absolute ones), over HTTP(S), without credentials, inside `adminRoute`; otherwise the admin root. `safeAdminBack('javascript:alert(1)', { adminRoute: '/admin' })` → `'/admin'`; `safeAdminBack('/admin/collections/pages?page=2', { adminRoute: '/admin' })` → the same path. Use it in your own rule or view. |
| `wrapTotpViews(views, added, rule?, wrapper?)` | `@intecion/ipal-kit` | Puts `SafeTotpView` in front of the views whose route is `setup-totp` / `verify-totp` and for which `added(key)` is true (keeps `exportName`, `serverProps`; `clientProps` travel as `ipalTotpClientProps`); returns `{ views, dependencies }` (`dependencies` → `admin.dependencies`, so the wrapped views stay in the import map). What `ipalKit` runs after the 2FA factory; for a project that registers the 2FA package itself. |
| `copyViews(views)` / `changedViewKeys(before, after)` | `@intecion/ipal-kit` | The comparison `ipalKit` uses to tell which views a 2FA factory registered: put `copyViews(views)` into the config before calling the factory, then `changedViewKeys(before, viewsAfter)` gives the keys whose view object changed — the `added` argument of `wrapTotpViews` (`(key) => keys.has(key)`). By object, not by key: the 2FA package replaces a view that already stands under its keys. Example: security.md "Your own 2FA screen". |
| `SAFE_TOTP_VIEW` / `totpViewImportKey(component)` | `@intecion/ipal-kit` | `'@intecion/ipal-kit/admin#SafeTotpView'`, the wrapper's import-map path (the default `wrapper` of `wrapTotpViews`); and the import-map key (`path#export`) of a component given as a string or `{ path, exportName }`. |
| `findImportMapFile(config, cwd?)` / `missingImportMapEntries(config, entries, cwd?)` | `@intecion/ipal-kit` | Where the project's `importMap.js` is on disk (`admin.importMap.importMapFile`, else `app/(payload)<admin route>/` or `src/app/…` under `admin.importMap.baseDir` / the working directory; `null` when not found), and which of `entries` its text does not contain (`{ file, missing }`). A hint from the file on disk, not the map in the build: warn on it, never block on it. Behind `twoFactor.importMapCheck`. |
| `buildSetupFields({ statusField? })`, `stampSetupFrom`, `backfillSetupFrom(payload, collection)` | `@intecion/ipal-kit` | The parts of "2FA setup required" for a project that wires them itself: the fields for the 2FA collection (`totpSetupFrom`, and the panel's `totpSetupStatus` unless `statusField: false`), the `beforeChange` hook that stamps the window start (on create, and when an account loses its TOTP secret), and the start-up step that gives accounts without TOTP and without a start their window (returns how many; once per account). |
| `buildTwoFactorResetEndpoint(collection, { access? })`, `TWO_FACTOR_RESET_PATH` | `@intecion/ipal-kit` | `POST /api/ipal/two-factor/reset` `{ userId }`: clears the account's TOTP secret and sessions and starts a new window. Default: a staff admin whose session entered its own TOTP code; `access` replaces that (only `true` allows; a session that owes its code is always refused). `ipalKit` registers it only with `twoFactor.guard` on. |
| `countAccountsWithoutTotp(payload, collection, setupWindowMs?)` | `@intecion/ipal-kit` | `{ without, blocked }` — accounts of the 2FA collection without TOTP, and how many are past their window. |
| `resolveRequireSetup(option)`, `strictExempt(fn)`, `SETUP_FROM_FIELD`, `DEFAULT_SETUP_WINDOW_HOURS` | `@intecion/ipal-kit` | `twoFactor.requireSetup` → `{ requireSetup, setupWindowMs, exempt? }` as the guard reads it (throws on a `windowHours` that is not a number ≥ 0 or `false`, and on an `async` `exempt`); the wrapper that makes an `exempt` function answer `true` only for exactly `true`; the field name `'totpSetupFrom'`; `72`. |
| `fetchPublicImage(url, base)`, `publicImageDataUri(url, base)`, `rasterImageType(bytes)`, `siteOrigin(serverURL)`, `PUBLIC_IMAGE_MAX_BYTES` | `@intecion/ipal-kit` | An image fetched the way an anonymous visitor gets it (no cookies; http(s) only; `image/*`; at most 512 KB, reading stops at the limit) as `{ bytes, type }` or a `data:` address, else `null`. Used for the logo and icon on the 2FA screens. `rasterImageType(bytes)` → the media type of a bitmap by its first bytes (PNG, JPEG, GIF, WebP, ICO, AVIF) or `null` — never trust a claimed type before answering a file's bytes from the site's origin; an SVG gives `null`. |
| `UPLOAD_SECURITY_HEADERS` | `@intecion/ipal-kit` | The two headers of `buildUploadSecurityHeaders` (`Content-Security-Policy: default-src 'none'; … sandbox`, `X-Content-Type-Options: nosniff`) for a route of your own that returns an uploaded file's bytes from the site's origin. In a Next project a site-wide `headers()` rule with the same key overrides a header the route sets itself: add a `headers()` rule for the path after the site-wide one (as `buildUploadSecurityHeaders({ collections, adminIcon })` does for the upload routes and `/api/ipal/admin-icon`), and never answer with an SVG. |
| `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'`. |
+21 -1
View File
@@ -203,7 +203,7 @@ behind Cloudflare, `x-forwarded-for` behind a plain proxy), `IPAL_NOINDEX` (empt
One language: one entry in `locales`, no `[locale]` folder (i18n.md).
**Check.** `pnpm payload generate:importmap` (whiteLabel adds admin components) and `pnpm generate:types` without
errors (the import map lists `@intecion/ipal-kit/admin#TotpRedirectProvider`); `pnpm dev`, `/admin`: first-user screen → after saving, TOTP setup is enforced (`/admin/setup-totp?back=%2Fadmin`, QR, no reloading);
errors (the import map lists `@intecion/ipal-kit/admin#TotpRedirectProvider` and `#SafeTotpView`); `pnpm dev`, `/admin`: first-user screen → after saving, TOTP setup is enforced (`/admin/setup-totp?back=%2Fadmin`, QR, no reloading);
the panel shows Site settings, Site integrations, Cookies, Form messages, the Forms group, Consent records.
`curl -s -o /dev/null -w '%{http_code}' -X POST localhost:3000/api/ipal/consent -H 'content-type: application/json'
-d '{"id":"0123456789abcdef","version":1,"state":{"necessary":true,"functional":false,"analytics":false,"marketing":false}}'` → `201`.
@@ -225,8 +225,28 @@ the panel shows Site settings, Site integrations, Cookies, Form messages, the Fo
(the plugin's own, and those of plugins listed after `ipalKit`) and the plugin's endpoints; guard your own
endpoints with `secondFactorPassed(req)` or `userMeetsRole(req, role)` (security.md "What the second factor covers").
Verify attempts: 5 per account in 10 minutes (`twoFactor.verifyLimit`).
The `back` link of the setup and verify screens is checked on the server (`twoFactor.safeBack`, on by default:
only a path inside the admin route is kept; `false` turns it off, a function replaces the rule). It needs the
import map entry `@intecion/ipal-kit/admin#SafeTotpView` — run `pnpm payload generate:importmap` and commit
(a production build with a map that lacks it shows 2FA screens without a code form: nobody can sign in;
`ipal-doctor`, the start log and a notice above the screen report it; `twoFactor.importMapCheck: false` turns the
log line and the notice off — needed when the `importMap.js` on disk is not the one the build used).
Check: password only → `/admin/verify-totp?back=https%3A%2F%2Fexample.com%2F` → code → you land on `/admin`.
**Set 2FA up right after creating an account** (log in as it, scan the code): until then its password alone
opens everything its role allows. One entity reachable without the code: `custom.ipal.secondFactor`.
**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` and have the migration applied when the container starts, before the site serves** — `prodMigrations`
or the start command `pnpm payload migrate && pnpm start`, never a pre-deployment command (deployment.md §4.3)
(column `totp_setup_from`, there whenever 2FA is
on) — without it every login answers 500; `pnpm payload generate:importmap` (`TwoFactorStatusField`,
`TwoFactorAlert`). A service account that logs in with a password: `requireSetup: { exempt }` (a plain function
returning exactly `true`; never `async`); an API key needs nothing. Parts to switch off: `requireSetup:
{ dashboardNotice: false, statusField: false, setupNotice: false }`. An admin's reset ends the account's
sessions and needs the admin's own TOTP code (`twoFactor.resetAccess` changes who). Have two administrators
with 2FA: when all are blocked, only a script or a redeploy helps (security.md "Every administrator is
blocked"). 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
+59
View File
@@ -362,6 +362,65 @@ panel → Site integrations and a form submission open, a setting saves. With a
gets `403` from the same addresses and from `POST /api/setup-totp`. The Coolify log has no
`PAYLOAD_SECRET must be at least`; `pnpm exec ipal-doctor` has no `env` finding.
**→ 1.16.5 (PROGRAMISTA §6, item 67; CHANGELOG 1.16.5; security.md "The `back` link of the 2FA screens") — required with 2FA on:**
1. **Do this in ONE deploy with the upgrade, or the panel is locked for everyone.** Run `pnpm exec ipal-doctor`
before deploying.
`pnpm payload generate:importmap` — the plugin puts `@intecion/ipal-kit/admin#SafeTotpView` in front of the
2FA package's setup and verify views; commit `importMap.js`, `rm -rf .next`, redeploy on Coolify. With the old
import map the build passes and the site starts, but the 2FA screens have no code form (HTTP 200) — nobody can
sign in. Signs: `pnpm exec ipal-doctor` → `import map lacks …SafeTotpView` (run it before deploying); the log
line `[ipal] The admin import map may be out of date` at start; the notice "Two-step verification may not be
available" where the form should be. Fix: the same command, commit, redeploy.
The log line and the notice with a **working** code form mean a false alarm (the `importMap.js` on disk is not
the one the build used — a Dockerfile runner stage, a re-exporting map): sign-in works; set
`twoFactor.importMapCheck: false`.
**Check:** log in with the password only → open `/admin/verify-totp?back=https%3A%2F%2Fexample.com%2F` → enter
the code → you land on `/admin` (not on example.com); a normal login still returns to the page you came from.
No option, env, schema or migration. A project that registered its own 2FA views, or wrote a proxy rule that
strips `back`, can keep them (`twoFactor.safeBack: false` turns the plugin's check off).
2. `pnpm ipal:skills`.
**→ 1.16.6 — 2FA setup required (CHANGELOG 1.16.6; PROGRAMISTA §6, item 68; security.md "Setup required") — required with 2FA on:**
**Not a routine patch, although the number is one.** From this version an account without 2FA can only set it up and is
blocked after 72 hours; on Postgres / SQLite a missing migration locks everyone out of the panel. Do not upgrade a live
site without steps 1–3 and a deploy day agreed with the owner. Steps 2, 3 and 5 go in ONE deploy.
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 (better two) has 2FA set up — otherwise nobody can reopen setup from the panel.
The 72 hours of existing accounts start at the first start after the deploy and are counted once (restarts
and redeploys do not extend them): agree the deploy day with the owner.
2. Update the package, `pnpm install`, `pnpm ipal:skills`, `pnpm payload generate:types`,
**`pnpm payload generate:importmap`** (new: `TwoFactorStatusField`, `TwoFactorAlert`; commit `importMap.js`),
then `pnpm exec ipal-doctor` before deploying.
3. **Postgres/SQLite — required, same deploy, or nobody can log in:** `pnpm payload migrate:create` (adds the
column `totp_setup_from` to the 2FA collection; needed whenever 2FA is on, also with `requireSetup: false`),
commit, and have it applied **when the new container starts**: `prodMigrations` in the database adapter, or the
start command `pnpm payload migrate && pnpm start` (deployment.md §4.3). **Never Coolify's Pre-deployment
command** — it runs in the old container, without the new migration, and the new version then starts without
the column. Without the column every login answers 500, administrators included; the log says
`[ipal] 2FA: the column for "totpSetupFrom" is missing … NOBODY CAN LOG IN`. `pnpm exec ipal-doctor` reports
it before the deploy. 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. The line appears on that first start only.
Postgres/SQLite: if logins answer 500 after the deploy, the migration from step 3 did not run — check that it
is committed and that the container runs migrations at start (deployment.md §4.3), then redeploy.
6. `requireSetup.exempt` must be a plain function returning `true` / `false` (an `async` one stops the start).
A script on an API key is refused by `POST /api/ipal/two-factor/reset` by default — pass
`twoFactor.resetAccess` if that is wanted. A reset ends the account's sessions (it logs in again); after a
suspected compromise change the password too. An SVG favicon has no tab icon on the 2FA screens.
7. Tell the owner what to tell the staff: a new account has 72 hours to set 2FA up, then an administrator must
choose "Reopen setup". Not wanted: `twoFactor.requireSetup: false`, or `{ windowHours: false }`.
**Every administrator is blocked** (all missed the 72 h): security.md "Every administrator is blocked" — a
`pnpm payload run` script that sets `totpSetupFrom` to now for one administrator, or
`requireSetup: { windowHours: false }` + redeploy, set 2FA up, put it back.
**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):
+2
View File
@@ -674,6 +674,8 @@ Do one item at a time, build, check. Order by importance:
| 64 | **1.16.3** — the reference site and the starter run Payload 3.94.1; the site is still on 3.90–3.93, or `node -v` (locally or in the Coolify app's Terminal) is below 22.23.5 | Recommended, not required (the plugin still accepts `^3.90.2`). First make sure Node is 22.23.5 or later everywhere, Coolify included (Nixpacks picks the patch: check `node -v`, update Coolify if lower). Then every `payload` / `@payloadcms/*` 3.94.1 (in `dependencies` and `pnpm.overrides`), `react` / `react-dom` 19.3.1, `"engines": { "node": ">=22.23.5 <23" }`; overrides: keep `dompurify` and `happy-dom`, drop `mongoose`, `undici` and `graphql-scalars`; `pnpm install`, `generate:types`, `generate:importmap`, `rm -rf .next`, build, redeploy; Postgres/SQLite: `migrate:create`; `pnpm ipal:skills` | CHANGELOG 1.16.3, AGENT.md §4 items 11–12, ipal-upgrade "Every upgrade — Payload" |
| 65 | **1.16.4 — security** — with 2FA on, a login with the password only gets `200` from `/api/globals/site-integrations` or `/api/form-submissions`; or the project has a second auth collection (`customers`) | Upgrade and redeploy (no config change with one auth collection). With the owner: change the SMTP password and the Turnstile secret, review Site settings / Site integrations / each form's Emails tab for values nobody set. Second auth collection: `admin: { user }` in `buildConfig`, `adminOrSelfIn('<slug>')`, `access.staffCollections` only for a second STAFF collection. Every account must have 2FA set up (`ipal-doctor --url` → 0 without). Own endpoints: `secondFactorPassed(req)`; own `overrideAccess: false` calls: `user` from `payload.auth()`. `pnpm ipal:skills`; no migration | CHANGELOG 1.16.4, security.md "What the second factor covers", access.md "Who is staff" |
| 66 | **1.16.4** — production `PAYLOAD_SECRET` shorter than 32 characters (the site would stop at `assertEnv`) | Before deploying 1.16.4, check the length in Coolify (`node -e 'console.log(process.env.PAYLOAD_SECRET.length)'`). Shorter: a random 32+ character secret (logs everyone out, asks for 2FA again, breaks stored API keys), or `ipalEnvRules({ secretMinLength: 0 })` for now | CHANGELOG 1.16.4, deployment.md "PAYLOAD_SECRET — length and changing it" |
| 67 | **1.16.5 — security** — with 2FA on, `/admin/verify-totp?back=https%3A%2F%2Fexample.com%2F` sends the user to example.com after the code (and `back=javascript:…` runs script in the panel) | Upgrade and, **in ONE deploy**, `pnpm payload generate:importmap` (adds `@intecion/ipal-kit/admin#SafeTotpView`), commit `importMap.js`, `rm -rf .next`, redeploy on Coolify — with the old map the 2FA screens have no code form and nobody can sign in (run `pnpm exec ipal-doctor` before deploying; the start log says so too); check: the link above ends on `/admin`. `pnpm ipal:skills`. No option, env or migration; off / own rule: `twoFactor.safeBack` | CHANGELOG 1.16.5, security.md "The `back` link of the 2FA screens" |
| 68 | **1.16.6 — 2FA setup required** (not a routine patch: a new default that can lock accounts out) — 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 (better two) must have 2FA; deploy day agreed with the owner. Then, in ONE deploy: update, `generate:types`, `generate:importmap` (`TwoFactorStatusField`, `TwoFactorAlert`), **Postgres/SQLite: `migrate:create` and the migration applied in the same deploy when the new container starts — `prodMigrations` or `pnpm payload migrate && pnpm start`, never a pre-deployment command (deployment.md §4.3) — (column `totp_setup_from`); without it every login answers 500**, 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 1.16.6, 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`.
+3 -3
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)
@@ -89,7 +89,7 @@ Turn off: `ipalKit({ doctor: false })`. Adapt: `ipalKit({ doctor: { tokenVar: 'M
| | `layout-forbidden` | error | no `middleware.ts`, no `lib/{pages,locales,navigation}.ts`, `fields/{link,sectionHeader,sectionSettings}.ts` |
| | `layout-extra` | info | `src/` entries outside the allow list (AGENT.md §3 + `seed/`, `design/`, `db.ts`, `env.rules.ts`, `content.config.ts`; extend with `layout.allow`) |
| | `naming` | warning | block folders, collection and global files PascalCase, `scripts/*` kebab-case, no `index.ts` barrels |
| | `importmap` | error | the import map exists, holds the entries for what the config turns on (2FA, R2, cookie scanner, `adminMeta`), names no export the plugin no longer has; with `--deep`, equals a fresh one |
| | `importmap` | error | the import map exists, holds the entries for what the config turns on (2FA incl. `SafeTotpView`, `TwoFactorStatusField`, `TwoFactorAlert`; R2, cookie scanner, `adminMeta`), names no export the plugin no longer has; with `--deep`, equals a fresh one. Warning: the config uses the 2FA package's own setup / verify view as a view's `Component` (outside the `back` link check — security.md); not for that path as `ipalTotpView` of `SafeTotpView` or in `admin.dependencies` |
| | `tsconfig-skills` | error | `tsconfig.json` excludes the skills folder |
| env | `db-name` | error | `DATABASE_URI` in `.env` and `.env.example` names `<domain without dots>_dev`; a local `.env` on `_prod` is an error; `--env-file` checks `_prod` (`databaseNamesFor`) |
| | `env-rules` | error / warning | `instrumentation.ts` calls `assertEnv(ipalEnvRules(…))` from `/env`, with `storage` (R2), `cookieCrawl` (crawl), `ipHeader`; `databaseName` suggested (info) |
@@ -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); error: a Postgres / SQLite project whose migrations do not mention the 2FA column `totp_setup_from` (every login would answer 500; a warning when there is no migrations folder — the doctor cannot see a schema that gets there another way); 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 |
+265 -13
View File
@@ -425,17 +425,120 @@ 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`, and what
Payload gives any logged-in session about itself (`/api/access`, token refresh, logout, its own panel
preferences), 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.
That starting moment is **written once**, on each such account (`totpSetupFrom`), by the start that first finds
the account without one. Later starts, redeploys and further instances find nothing left to do (the log line
appears on that first start only), and editing the account or logging in does not move it — so a redeploy never
hands out another 72 hours. Only an administrator's reset / "Reopen setup" opens a new window. An existing
account that **has** TOTP gets no start; if its TOTP is removed later, its window starts then. On Postgres /
SQLite the migration that adds the column must run in the same deploy (see "Data" below) — the first start
after it is the one that counts.
```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: { dashboardNotice: false, statusField: false, setupNotice: false }, // each panel part can be switched off; the lock stays
// requireSetup: false, // the 2FA package's rule: redirect in the panel, API open until setup
// who may reset / reopen. Default: a staff admin whose session entered its own TOTP code. Your function replaces
// that rule, so keep the code check in it unless you mean to let API-key / exempt admins reset:
// resetAccess: ({ req }) => req.user?._strategy === 'totp' && isAdmin(req.user, req.payload),
}
```
- **Data.** The 2FA collection gets a date field `totpSetupFrom` (hidden, written by the plugin only) **whenever
2FA is on** — also with `requireSetup: false` or `guard: false`, so that switching the mode does not change the
schema — and, with the mode on, a panel-only field `totpSetupStatus`. MongoDB: nothing to do.
**Postgres / SQLite: the migration is a required step of the same deploy.** Run `pnpm payload migrate:create`, commit the migration, and
have it applied **when the new container starts** — `prodMigrations` in the database adapter, or the start command `pnpm payload migrate && pnpm start` ([deployment.md §4.3](./deployment.md#43-database-migrations-postgres)). **Not Coolify's Pre-deployment command:** it runs in the old container, which does not have the new migration, so the new version would start without the column.
Without the column every query on the 2FA collection fails: **every login answers 500 —
administrators with 2FA included — and nobody can sign in to the panel** (the public site keeps working). The
log says `[ipal] 2FA: the column for "totpSetupFrom" is missing … NOBODY CAN LOG IN …` at start;
`ipal-doctor` reports a SQL project whose migrations do not mention `totp_setup_from` (error; a warning when
there is no migrations folder at all — it cannot see a schema that is pushed some other way). Recovery: run
the migration; no data is lost.
- **`exempt` must answer `true` or `false` at once.** It runs inside access checks, which cannot wait. An
`async` function stops the site at start with a clear error; any answer other than exactly `true` (a Promise,
a string, an error) exempts nobody and is logged once. Decide from the fields on `user`. An exempt account
works on its password alone, so give it the lowest role that does its job.
- **`windowHours`** must be a number (0 or more) or `false`; anything else (`'24'`, `-1`) stops the site at start.
- **Import map.** The status field and the dashboard notice are admin components: `pnpm payload
generate:importmap` after upgrading (`TwoFactorStatusField`, `TwoFactorAlert`); `ipal-doctor` reports a map
that lacks them. Without them the panel has no "Reopen setup" button (the endpoint still works).
- **Switch a part off:** `requireSetup: { dashboardNotice: false }` (the administrators' notice),
`{ statusField: false }` (the status / reset control on the account; the endpoint stays),
`{ setupNotice: false }` (the notice on the setup screen). None of them changes who is refused. The logo and
icon fetched by the server for the 2FA screens: `whiteLabel.inlineImages: false`, `adminMeta.serveIcon: false`
([white-label.md](./white-label.md)).
- **Building blocks** (`@intecion/ipal-kit`), for a project that wires the mode itself: `buildSetupFields`,
`stampSetupFrom`, `backfillSetupFrom`, `buildTwoFactorResetEndpoint`, `countAccountsWithoutTotp`,
`resolveRequireSetup`, `strictExempt`, `SETUP_FROM_FIELD`, `TWO_FACTOR_RESET_PATH`, `DEFAULT_SETUP_WINDOW_HOURS`.
- **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*`.
**The brand on the setup and verify screens.** A session that still owes its code is refused `media` like every
other collection, so the browser could not load the panel's logo or tab icon from it. The plugin therefore hands
such a session the picture itself — fetched on the server without any credentials, exactly as an anonymous visitor
gets it (`AdminLogo` / `AdminIcon` as a `data:` address; `GET /api/ipal/admin-icon` answers with the image
instead of a redirect when the favicon is a bitmap — never with an SVG, which keeps the redirect). Nothing is opened by this: when `media` is not publicly readable, or the file is larger
than 512 KB, the site name (or the browser's own attempt) is used instead.
**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 +552,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
@@ -526,8 +630,9 @@ ipal-kit upgrade, run:
pnpm generate:importmap
```
`src/app/(payload)/admin/importMap.js` must list `@intecion/ipal-kit/admin#TotpRedirectProvider` and
`@clocklimited/payload-2fa/rsc#TOTPSetup` / `#TOTPVerify` / `#TOTPField`. Commit the file.
`src/app/(payload)/admin/importMap.js` must list `@intecion/ipal-kit/admin#TotpRedirectProvider`,
`@intecion/ipal-kit/admin#SafeTotpView` and `@clocklimited/payload-2fa/rsc#TOTPSetup` / `#TOTPVerify` /
`#TOTPField`. Commit the file.
### Texts of the 2FA screens (`twoFactor.texts`)
@@ -564,6 +669,99 @@ No project change is needed apart from `generate:importmap`.
The provider only steers the UI. Data access is still checked by the package's access wrapper.
### The `back` link of the 2FA screens (`twoFactor.safeBack`)
The setup and verify screens take a `back` query value (`/admin/verify-totp?back=%2Fadmin%2Fcollections%2Fpages`)
and the 2FA package sends the browser there once the code is accepted, without looking at it. A link with
`back=javascript:…` therefore ran script in the panel, as the user who had just passed the second factor, and a
link with an outside address sent the user off the site straight after a real login step. The original package
fixed this in `payload-totp` 3.0.5 (GHSA-rffw-fq79-g3ch); `@clocklimited/payload-2fa` (beta.1 to beta.7) has not.
The panel's CSP does not stop it: the admin needs inline script.
ipal-kit closes it without changing the package. `SafeTotpView` (`@intecion/ipal-kit/admin`) is registered in
place of the package's four views (`setup-totp`, `verify-totp`, each with and without a leading slash). It checks
`back` on the server and renders the package's view with the checked value. The package's views stay in the
import map through `admin.dependencies`, so ipal-kit still never imports the package.
The rule (`safeAdminBack`, the same as upstream's): `back` is resolved the way a browser resolves it and kept
only when it stays on the site's origin, over HTTP(S), without credentials, inside the admin route
(`routes.admin`, also a custom one). Everything else gives the admin root: `javascript:` in any case or with
leading spaces, `data:`, `https://other.example`, `//other.example`, `/\other.example`, `\\other.example`,
`https:other.example`, a path outside the panel, a repeated `back`, no `back` at all. The value passed on is
always a path, never an absolute URL. An absolute `back` on the site's own origin is accepted only when the
config has `serverURL`.
- **On by default** with `twoFactor`. **After upgrading run `pnpm payload generate:importmap` and commit
`importMap.js`** — see "A stale import map" below for what happens otherwise.
- **Your own rule:** `twoFactor: { …, safeBack: (back, { adminRoute, origin }) => string }`. It gets the raw value
(`undefined` when absent or repeated) and returns where to go. Return a path on your own origin.
- **Off:** `twoFactor: { …, safeBack: false }` — the package's views exactly as it registers them. Only when a
later version of the 2FA package checks `back` itself, or something in front of the site does.
- **Building blocks:** `safeAdminBack(back, { adminRoute, origin })` and `wrapTotpViews(views, added, rule)` from
`@intecion/ipal-kit`; `SafeTotpView` from `@intecion/ipal-kit/admin` for your own 2FA view registration (give it
the serverProp `ipalTotpView: '<import-map path of the view to render>'` and list that path in
`admin.dependencies`).
**Which views are guarded.** Every view the injected 2FA factory registers on the routes `setup-totp` and
`verify-totp`, whatever stood under its keys before. The package replaces a view the project has under the keys
`SetupTOTP`, `SetupTOTPBackslash`, `VerifyTOTP` or `VerifyTOTPBackslash`, so such a view is the package's, and
guarded. The same holds when the project also lists `payloadTotp(...)` in `plugins` itself.
**Your own 2FA screen.** Two ways, both keep the check:
- Through the wrapped factory (the pattern from "Resetting 2FA"): set `views.VerifyTOTP.Component` (or `SetupTOTP`)
on the config the factory returns. ipal-kit puts `SafeTotpView` in front of it. A server component gets every
server prop with `searchParams.back` checked. A client component (`'use client'`) gets Payload's client props,
your `clientProps`, and `back` plus `searchParams` — both checked; read `back` from the props, not from
`useSearchParams()`, which still holds the raw query value.
- From a plugin listed after `ipalKit`, or under another key or route: that view is yours and is not wrapped. Use
`wrapTotpViews` or `safeAdminBack` in it. `ipal-doctor` warns when the config uses the package's own view
(`@clocklimited/payload-2fa/rsc#TOTPVerify` / `#TOTPSetup`) as a view's `Component`; the same path as the
`ipalTotpView` of `SafeTotpView`, or in `admin.dependencies`, is fine.
Wrapping views yourself, for a project that runs the 2FA package without `ipalKit`'s `twoFactor` (all from
`@intecion/ipal-kit`):
```ts
const before = copyViews(config.admin?.components?.views) // copies: the factory's views are then never "the same object"
config = await payloadTotp(options)({ ...config, admin: { ...config.admin, components: { ...config.admin?.components, views: before } } })
const fromPackage = changedViewKeys(before, config.admin?.components?.views ?? {}) // by object — the package replaces views under its keys
const { dependencies, views } = wrapTotpViews(config.admin?.components?.views ?? {}, (key) => fromPackage.has(key), undefined)
config.admin = { ...config.admin, components: { ...config.admin?.components, views }, dependencies: { ...config.admin?.dependencies, ...dependencies } }
```
`SAFE_TOTP_VIEW` is the wrapper's import-map path; `findImportMapFile` / `missingImportMapEntries` are the
stale-map check below (a hint from the file on disk — warn on it, never block on it).
**A stale import map (read this before upgrading a site with 2FA).** The check needs the import-map entry
`@intecion/ipal-kit/admin#SafeTotpView`. A production build made with the import map of the previous version
passes and the site starts, but Payload renders nothing for a path its map lacks: the 2FA setup and verify
screens have no code form (HTTP 200), so nobody can sign in to the panel. Payload's only trace is
`getFromImportMap: PayloadComponent not found in importMap` in the server log. Development is not affected (Payload
regenerates the map there). ipal-kit reports it in three places:
- **Before deploy:** `pnpm exec ipal-doctor` reports `import map lacks @intecion/ipal-kit/admin#SafeTotpView` (error).
- **At every start in production:** the log has `[ipal] The admin import map may be out of date: … was not found
in <file> …`.
- **On the screen:** a notice above the 2FA screen, "Two-step verification may not be available", with what a
developer has to run. With a really stale map the notice is all the user sees (the form is missing); it is
shown by ipal-kit's `TotpRedirectProvider` only — with your own `twoFactor.provider`, or `provider: false`,
there is the log line alone.
The start-up check is a guess, and is built so that a wrong guess costs a wrong notice and nothing else: it
searches the text of the `importMap.js` **on disk** where Payload looks for it (`admin.importMap.importMapFile`,
else `app/(payload)<admin route>/` or `src/app/(payload)<admin route>/` under `admin.importMap.baseDir` or the
working directory), while the map the site really uses is inside the build. The two differ when the map is
generated during the build and the running image carries the repository's file (a Dockerfile with a separate
runner stage), or when the map file re-exports or computes its entries. Then the log line and the notice appear
although the screen works — the code form stays on the page and sign-in is not affected. Turn the check off for
such a project: `twoFactor: { …, importMapCheck: false }` (no file read, no log line, no notice). A file that is
not found is not reported. Building in place (Coolify's Nixpacks) reads the same file the build used.
**Fix for a really stale map:** `pnpm payload generate:importmap`, commit `importMap.js`, rebuild, redeploy.
A second error exists for the opposite case — the wrapper is in the map but the package's view is not:
`[ipal] The admin import map has no "@clocklimited/payload-2fa/rsc#TOTPVerify"` (same fix).
**Check:** log in with the password only, open
`/admin/verify-totp?back=https%3A%2F%2Fexample.com%2F`, enter the code: you must land on `/admin`, not on
example.com. With `back=%2Fadmin%2Fcollections%2Fpages` you must land on that list.
### Turning it off (DISCOURAGED)
```ts
@@ -575,7 +773,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=…`)
@@ -586,7 +785,51 @@ 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 }`. The account must set TOTP up again within a new window.
The endpoint comes with ipal-kit's own check: with `twoFactor.guard: false` it does not exist (404), and neither
does the control in the panel.
- **Who may reset.** By default a staff admin whose session has **entered its own TOTP code**. An admin on an API
key, and an admin that `requireSetup.exempt` lets work on its password, are refused: removing someone's second
factor should take one. `twoFactor.resetAccess: ({ req }) => boolean` replaces the rule; a session that still
owes its code is refused whatever the function says, and only an answer of exactly `true` allows
(`req.user._strategy` is `'totp'`, `'api-key'` or `'local-jwt'`). Example that keeps the default's strength and
narrows it to one address: `({ req }) => req.user?._strategy === 'totp' && req.user.email === '[email protected]'`.
`({ req }) => isAdmin(req.user, req.payload)` alone would let an API-key or exempt admin reset.
- **A reset ends the account's sessions.** Every token of that account stops working at once; its owner logs
in again with the password and sets TOTP up. This matters when the account may be in someone else's hands: a
session that had passed 2FA could otherwise enrol a new authenticator without the password (`/api/setup-totp`
asks for none). **After a suspected compromise also change the account's password** — the reset does not, and
whoever knows the password can log in and set TOTP up within the new window. With `auth.useSessions: false`
on the collection there are no sessions to end: tokens live until they expire.
- The 2FA package's own remove / reset endpoints (below) do **not** end sessions.
#### Every administrator is blocked
When no administrator can get in (each one missed the window, or the only one did), nobody can press "Reopen
setup". Two ways out, both need a deploy or shell access — which is the point: the panel alone cannot undo it.
1. **A script, no redeploy** (`pnpm payload run scripts/reopen-2fa.ts` on the server; Local API, no access
check):
```ts
import config from '@payload-config'
import { getPayload } from 'payload'
const payload = await getPayload({ config })
const { docs } = await payload.find({ collection: 'users', where: { email: { equals: 'admin@example.com' } } })
await payload.update({ id: docs[0].id, collection: 'users', data: { totpSetupFrom: new Date().toISOString() } })
process.exit(0)
```
The administrator then logs in and sets TOTP up within the new window, and reopens the others from the panel.
2. **No script, one redeploy each way:** set `twoFactor.requireSetup: { windowHours: false }` and deploy — the
lock stays (nothing but setup), the time limit is gone, so every blocked account can set TOTP up. When the
administrators have, put the option back and deploy again. Accounts that still have not set TOTP up are
blocked again from that moment (their start did not move).
Avoid it: at least two administrators with 2FA, and `ipal-doctor --url <site>` before an upgrade.
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) })`.
@@ -661,6 +904,15 @@ size while reading, content signature, container and macro checks, an optional `
## Turn off, override, extend
- **Verify limit:** `twoFactor.verifyLimit: { max, windowMinutes }`, or `false`.
- **`back` link check of the 2FA screens:** `twoFactor.safeBack: false`, or a function as your own rule;
`safeAdminBack`, `wrapTotpViews`, `copyViews`, `changedViewKeys`, `SAFE_TOTP_VIEW`, `SafeTotpView` are exported.
The stale import-map notice that comes with it: `twoFactor.importMapCheck: false`; its parts
(`findImportMapFile`, `missingImportMapEntries`) are exported too.
- **Setup required:** `twoFactor.requireSetup: false` (off), `{ windowHours }` (another window, `false` / `0` = none),
`{ exempt }` (a service account), `{ dashboardNotice: false }`, `{ statusField: false }`, `{ setupNotice: false }`,
`twoFactor.resetAccess` (who reopens); exported: `twoFactorSetupState`, `twoFactorSetupDeadline`,
`buildSetupFields`, `stampSetupFrom`, `backfillSetupFrom`, `buildTwoFactorResetEndpoint`,
`countAccountsWithoutTotp`, `resolveRequireSetup`, `strictExempt`, `SETUP_FROM_FIELD`.
- **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.
+7 -1
View File
@@ -51,6 +51,12 @@ values win over yours); `afterLogin` / `afterNavLinks` are appended.
## Technology support credit — "Technology support: Intecion.com"
**On the 2FA screens** (a session that has typed its password but not its code, or has not set 2FA up) the
panel's logo and icon cannot be loaded by the browser: that session is refused every collection, `media`
included. The server fetches them the way an anonymous visitor gets them (no cookies, images only, at most
512 KB) and puts them into the page as a `data:` image. `whiteLabel: { inlineImages: false }` turns the fetch
off (the site name is shown instead of a refused image); `fetchPublicImage` / `publicImageDataUri` are exported.
A discreet line **"Technology support: Intecion.com"** (pl `Wsparcie technologiczne: Intecion.com`,
a link to `https://intecion.com`) appears in **two places**:
- **under the panel navigation** (`afterNavLinks`, variant `nav` — left-aligned),
@@ -84,7 +90,7 @@ image. The plugin now fills the panel's `<head>` from Site settings, **with or w
| `og:site_name` | the site name | your `admin.meta.openGraph.siteName` wins |
| description | "Administration panel of <site>. Built on Payload CMS, technology support: Intecion.com." (Polish when the site's default locale is `pl`) | `adminMeta: { description: 'Panel of {site}' }` (string or `{ en, pl }`), `false`; `language: 'en' \| 'pl'`; your `admin.meta.description` wins |
| preview image | `GET /api/ipal/admin-og` — 1200×630 PNG: the site's logo (or name), "Administration panel", "Technology support: Intecion.com" | `adminMeta: { image: '/my-og.png' }` or `false`; your `admin.meta.openGraph.images` wins |
| icon | `GET /api/ipal/admin-icon` — redirects to the site's favicon, or draws the initials | `adminMeta: { icons: false }`; your `admin.meta.icons` win |
| icon | `GET /api/ipal/admin-icon` — answers with the site's favicon itself when it is a bitmap (PNG, JPEG, GIF, WebP, ICO, AVIF, recognised by its bytes; fetched as an anonymous visitor would get it, at most 512 KB). **An SVG favicon is never answered from here** — an SVG can carry script and a site-wide CSP rule overrides a route's own header — it gets a redirect to the media file, as does anything that cannot be fetched; so with an SVG favicon the tab icon is missing on the 2FA screens (use a PNG there). No favicon: the initials are drawn | `adminMeta: { icons: false }`; `adminMeta: { serveIcon: false }` = always the redirect to the media file; your `admin.meta.icons` win |
| everything | on | `adminMeta: false` = Payload's defaults |
- **How:** Payload builds every panel page's metadata from `config.admin.meta`. The plugin sets the
+1 -1
View File
@@ -1,6 +1,6 @@
{
"name": "@intecion/ipal-kit",
"version": "1.16.4",
"version": "1.16.6",
"description": "Intecion Payload Advanced Library — a Payload CMS 3 plugin: i18n, SEO, forms, consent, analytics, blog/archives.",
"license": "MIT",
"repository": {
@@ -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,15 @@ 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 }`); every administrator is blocked: security.md "Every administrator 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; or `requireSetup: { windowHours: false }`, redeploy, set up, put it back |
| 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` |
| after an upgrade EVERY panel login answers `500` (also `/api/users/init`), administrators with 2FA included; log: `[ipal] 2FA: the column for "totpSetupFrom" is missing … NOBODY CAN LOG IN` or `column users.totp_setup_from does not exist` | Postgres/SQLite: the migration that adds the 2FA column has not run (needed whenever 2FA is on) | `pnpm payload migrate:create` if no migration has it, commit, and redeploy with migrations run when the new container starts — `prodMigrations` in the adapter or the start command `pnpm payload migrate && pnpm start` (deployment.md §4.3; not Coolify's Pre-deployment command, which runs in the old container); nothing is lost. `ipal-doctor` reports a project whose migrations lack `totp_setup_from` |
| the site does not start: `[ipal] twoFactor.requireSetup.exempt must not be async` / `…windowHours must be a number` | `exempt` is an `async` function, or `windowHours` is a string / negative | `exempt: ({ user }) => user.email === '…'` (returns `true` / `false` at once); `windowHours: 72` or `false` |
| log: `[ipal] twoFactor.requireSetup.exempt returned a Promise … The account is NOT exempt` (and the service account gets 403) | `exempt` does not return exactly `true` | return a boolean decided from the fields on `user` |
| an administrator's "Reset two-step verification" answers 403 from a script with an API key, or for an exempt account | by default the reset needs a session that entered its own TOTP code | reset from the panel after logging in with the code; or `twoFactor.resetAccess: ({ req }) => …` |
| after "Reset two-step verification" the user is logged out everywhere | intended: the reset ends the account's sessions | the user logs in again with the password and sets 2FA up; after a suspected compromise also change the password |
| no "Two-step verification" box on the account page / no "Reopen setup" | the import map lacks `TwoFactorStatusField` (not regenerated), or `requireSetup: { statusField: false }` | `pnpm payload generate:importmap`, commit, redeploy; meanwhile `POST /api/ipal/two-factor/reset` `{ userId }` works |
| "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") |
@@ -58,6 +67,10 @@ through this procedure. Ask only when you are missing something you cannot get y
| Symptom | Cause | Fix |
|---|---|---|
| `PayloadComponent not found in importMap` (e.g. `@intecion/ipal-kit/admin#RowLabel`) | importMap out of date after a plugin update / adding `rowLabel` | `pnpm payload generate:importmap`, restart |
| after an upgrade the 2FA setup / verify screen has no code form (HTTP 200), only the notice "Two-step verification may not be available" (or nothing at all with `importMapCheck: false` / an own provider); nobody can sign in; the log has `[ipal] The admin import map may be out of date` and `getFromImportMap: PayloadComponent not found in importMap … @intecion/ipal-kit/admin#SafeTotpView` | the import map was not regenerated after the upgrade that added the `back` link check (`twoFactor.safeBack`); the production build uses the committed, old `importMap.js` | `pnpm payload generate:importmap`, commit `importMap.js`, `rm -rf .next`, redeploy; `pnpm exec ipal-doctor` shows it before a deploy. The opposite case (wrapper present, package view missing) throws `[ipal] The admin import map has no "@clocklimited/payload-2fa/rsc#TOTPVerify"` — same fix |
| the notice "Two-step verification may not be available" and the log line `[ipal] The admin import map may be out of date` appear, but the code form is there and sign-in works | false alarm: the check searches the `importMap.js` on disk, which is not the map inside the build (map generated during the build and a Dockerfile runner stage that copies the repository's file; a map file that re-exports or computes its entries) | `twoFactor: { …, importMapCheck: false }`; or ship the generated `importMap.js` in the image |
| an own 2FA screen (set through the wrapped factory) ignores the check on `back` | a client component reading `useSearchParams()` gets the raw query value | read the `back` prop (or `searchParams.back`) the wrapper passes — both are checked (security.md "Your own 2FA screen") |
| after the 2FA code the user lands on `/admin` instead of the page in `back` | `back` pointed outside the admin route or to another origin (the check keeps only a path inside `routes.admin`; an absolute URL only on the `serverURL` origin) | expected; for another rule pass `twoFactor.safeBack: (back, { adminRoute, origin }) => string` (security.md) |
| new admin stuck on `/admin/setup-totp?back=null` (the page keeps redirecting to itself) | ipal-kit ≤ 1.14.1: the 2FA package's provider needs an `x-pathname` header nothing sets on `/admin`; or `twoFactor.provider: false` without that header | update ipal-kit, `pnpm payload generate:importmap` (`TotpRedirectProvider`), restart; check: `/admin/setup-totp?back=%2Fadmin` shows the QR (security.md) |
| `Cannot destructure property 'config'` / UI hooks without context | two copies of `@payloadcms/ui` | `pnpm why @payloadcms/ui`; one version + `pnpm.overrides`; `ls node_modules/@intecion/ipal-kit/node_modules/@payloadcms` = empty |
| empty SEO tab, no Forms | mismatched `@payloadcms/*` versions | all `@payloadcms/*` = the `payload` version |
@@ -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 } })`.
@@ -37,9 +37,16 @@ description: Complete map of everything @intecion/ipal-kit provides — every ip
| `twoFactor.plugin` | — (required) | injected `payloadTotp` (the plugin does not import the peer) | missing function → throws |
| `twoFactor.collectionSlug` | the panel's login collection (`admin.user`, else the first auth collection) | collection with 2FA; startup fails with `[ipal] twoFactor…` when it is not an auth collection or differs from `admin.user` | point it at the login collection |
| `twoFactor.provider` | `'@intecion/ipal-kit/admin#TotpRedirectProvider'` | admin provider that sends users to `setup-totp` / `verify-totp` (path read in the browser); replaces the package's header-based one | own component path / `{ path, clientProps, serverProps }` (gets clientProps `forceSetup`); `false` keeps the package's (needs `x-pathname` on `/admin`, else `setup-totp?back=null` loops) |
| `twoFactor.safeBack` | on | the `back` query value of the 2FA setup and verify screens is checked on the server before the package's view gets it (`SafeTotpView` registered in place of the package's four views): kept only as a path on the site's origin inside `routes.admin`, else the admin root — no `javascript:` / off-site redirect after the code. Needs `generate:importmap` (`@intecion/ipal-kit/admin#SafeTotpView`) | `false` = the package's views untouched; a function `(back, { adminRoute, origin }) => string` = your own rule |
| `twoFactor.importMapCheck` | on | production only: at start searches the `importMap.js` on disk (where Payload looks for it) for `@intecion/ipal-kit/admin#SafeTotpView`; when not found, logs `[ipal] The admin import map may be out of date …` and ipal-kit's `TotpRedirectProvider` puts the notice "Two-step verification may not be available" above the 2FA screens (never instead of them). A hint only — the map in the build can differ from the file on disk (Dockerfile runner stage, re-exporting map); a file that is not found is not reported | `false` = no file read, log line or notice |
| `twoFactor.texts` | ipal-kit's en/pl texts (`TOTP_TEXTS`) over the package's; 2FA screens titled "Two-step verification" / "Weryfikacja dwuetapowa" (site's language) | `false` = the package's texts; one text: `i18n.translations.<lang>.totpPlugin.<key>` (security.md) |
| `twoFactor.guard` | on | ipal-kit's own second-factor check on every collection and global (also the plugin's own and those of plugins listed after ipalKit) and in `userMeetsRole`; startup fails with `[ipal] twoFactor: the injected 2FA plugin did not add …` when the 2FA package lacks the `totp` strategy / `hasTotp` / `totpSecret` | per entity: `custom.ipal.secondFactor: false` / `{ read: false }` or the package's `custom.totp.disableAccessWrapper.<op>`; `false` = the package's wrapper only (the plugin's own data then opens to a password without the code; not recommended). The package's endpoints stay limited to accounts of the 2FA collection either way |
| `twoFactor.verifyLimit` | `{ max: 5, windowMinutes: 10 }` | attempts per account on `POST /api/verify-totp` (the 2FA package counts none): the sixth in the window, right or wrong, gets `429` + `Retry-After`; in memory per instance | `{ max, windowMinutes }`; `false` = no limit |
| `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 field `totpSetupStatus` (panel) to the 2FA collection, a dashboard notice and `POST /api/ipal/two-factor/reset`; the date field `totpSetupFrom` is there whenever 2FA is on (also with `requireSetup: false` / `guard: false`). Existing accounts get their window at the first start after the upgrade, written once. **Postgres/SQLite: the migration must be applied when the new container starts — `prodMigrations` or `pnpm payload migrate && pnpm start`, not a pre-deployment command (deployment.md §4.3) — or every login answers 500**; `generate:importmap`. `exempt` must return exactly `true` at once (an `async` one, or a `windowHours` that is not a number / `false`, stops the start) | `false` = the package's rule (API open until setup); `{ windowHours: 24 }`, `{ windowHours: false }` (no limit), `{ exempt: ({ user }) => … }` (a service account) |
| `twoFactor.requireSetup.dashboardNotice` / `.statusField` / `.setupNotice` | on | the administrators' notice on the dashboard; the status and reset control on the account page; the notice on the setup screen | `false` each (the lock and the reset endpoint stay) |
| `twoFactor.resetAccess` (the endpoint exists with `twoFactor.guard` on; `guard: false` = no endpoint, 404) | a staff admin whose session entered its own TOTP code (not an API key, not an `exempt` account) | who may reset another account's TOTP / reopen its setup (the button on the account page, `POST /api/ipal/two-factor/reset`). The reset clears the secret and the account's sessions. A session that still owes its code is always refused | `({ req }) => boolean` — replaces the rule, so keep `req.user?._strategy === 'totp' &&` in it unless API-key / exempt admins should reset; only `true` allows; `req.user._strategy` tells `'totp'`, `'api-key'`, `'local-jwt'` apart |
| `whiteLabel.inlineImages` | on | on the 2FA screens the logo / icon is fetched by the server as an anonymous visitor gets it (max 512 KB) and inlined as `data:` — the session there is refused `media` | `false` = the browser tries the media URL |
| `adminMeta.serveIcon` | on | `/api/ipal/admin-icon` answers with the favicon's bytes when it is a bitmap (PNG, JPEG, GIF, WebP, ICO, AVIF by its bytes); an SVG favicon always gets a redirect to the media file (never SVG bytes from the site's origin) | `false` = always the redirect |
| `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 | — |
@@ -31,11 +31,15 @@ Admin panel components from `@intecion/ipal-kit/admin` — the project does NOT
| `CookieApprovalForm` | `@intecion/ipal-kit/admin` | Client part of the view: tick boxes, markers (New / Changed / Needs description), Edit links, the button. Props `pending`, `gone`, `unknownCategory`, `labels?`, `adminRoute?` — reuse it in your own view. |
| `CookieCrawlAlert` | `@intecion/ipal-kit/admin` | Server Component: dashboard warning — "Waiting for approval: N" with a link to the approval view, and with the crawl violations or a failed crawl; renders nothing otherwise. Props `approval`, `crawl`. Injected with `cookieScanner` (`approval.dashboard: false` / `crawl.dashboard: false` drop its parts); after turning it on, `pnpm generate:importmap`. |
| `CookieScanButton` | `@intecion/ipal-kit/admin` | "Scan cookies" box above the *Cookie review* list: integrations in use, optional extra names, runs `POST /api/ipal/cookie-scan`. Injected by the plugin with `cookieScanner`; after turning it on, `pnpm generate:importmap`. |
| `SafeTotpView` | `@intecion/ipal-kit/admin` | Server admin view in front of the 2FA package's setup and verify views: replaces the `back` query value with a checked one and renders the view named by the serverProp `ipalTotpView` (a path or `{ path, exportName }`, found in the import map) the way Payload renders a view: a server component gets all server props, a client component only Payload's client props, `ipalTotpClientProps`, `back` and `searchParams` (both checked). `ipalSafeBack` = own rule. Registered by the plugin with `twoFactor` (`twoFactor.safeBack`, on by default). After upgrading, `pnpm generate:importmap`. Check: password only → `/admin/verify-totp?back=https%3A%2F%2Fexample.com%2F` → code → `/admin`. Own registration: `Component: { path: '@intecion/ipal-kit/admin#SafeTotpView', serverProps: { ipalTotpView: '<path>' } }` + that path in `admin.dependencies`. |
| `TotpRedirectProvider` | `@intecion/ipal-kit/admin` | Client admin provider: sends a user without TOTP to `/admin/setup-totp?back=…` and a user whose session has not passed TOTP to `/admin/verify-totp?back=…` (path read in the browser; never redirects away from those screens or logout; renders nothing while redirecting). Injected by the plugin with `twoFactor` in place of the package's header-based provider; swap with `twoFactor.provider`. After upgrading, `pnpm generate:importmap`. Check: a new admin lands on `setup-totp?back=%2Fadmin` with the QR code. Props type `TotpRedirectProviderProps` (`forceSetup`) |
| `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) |
| `buildAdminImageEndpoints(resolved, { settingsSlug?, nameField?, logoField?, iconField? })` | `@intecion/ipal-kit` | `GET /api/ipal/admin-og` (1200×630 PNG via `next/og`) and `GET /api/ipal/admin-icon` (favicon redirect or initials) — already added by `adminMeta` |
| `buildAdminImageEndpoints(resolved, { settingsSlug?, nameField?, logoField?, iconField? })` | `@intecion/ipal-kit` | `GET /api/ipal/admin-og` (1200×630 PNG via `next/og`) and `GET /api/ipal/admin-icon` (the favicon itself, or initials) — already added by `adminMeta` |
| `DEFAULT_AGENCY`, `ADMIN_META_TEXTS` | `@intecion/ipal-kit` | Default agency `{ name: 'Intecion.com', url }`; en/pl meta texts (`{site}`, `{agency}`). Types `AdminMetaOptions`, `AgencyOption`, `ResolvedAdminMeta` |
## Readable array rows in the panel (`admin-ui`) — details: `node_modules/@intecion/ipal-kit/docs/links.md`
@@ -68,7 +72,7 @@ Admin panel components from `@intecion/ipal-kit/admin` — the project does NOT
| `buildRolesField(defaultRole?, { firstUserAdmin? })` | `@intecion/ipal-kit` | The `roles` select field the plugin injects (only admins set roles; `firstUserAdmin` default `true` = the account made on "Create first user" gets `admin`). The plugin wires it itself — use it only for an auth collection the plugin does not manage. |
| `injectRoles(config, accessOption)` | `@intecion/ipal-kit` | Adds `roles` to `accessOption.authCollection` in a config. The plugin calls it itself with `access` — do not call. |
**Types:** `VerifyLimitOptions` (`twoFactor.verifyLimit`: `{ max?, windowMinutes? }`), `Role` (`'user' \| 'editor' \| 'admin'`), `AccessOption` (the plugin's `access` option: `authCollection`, `defaultRole`, `authAccess`, `firstUserAdmin`, `staffCollections`).
**Types:** `VerifyLimitOptions` (`twoFactor.verifyLimit`: `{ max?, windowMinutes? }`), `RequireSetupOptions` (`twoFactor.requireSetup`), `TwoFactorResetOptions`, `TwoFactorSetupState`, `SafeBackRule` / `SafeBackContext` (`twoFactor.safeBack` as a function: `(back, { adminRoute, origin? }) => string`), `TotpViewComponent` (a view component as registered: a path or `{ path, exportName?, clientProps?, serverProps? }`), `SafeTotpViewProps` (`@intecion/ipal-kit/admin`), `Role` (`'user' \| 'editor' \| 'admin'`), `AccessOption` (the plugin's `access` option: `authCollection`, `defaultRole`, `authAccess`, `firstUserAdmin`, `staffCollections`).
## Accessibility — widget (`accessibility`) — details: `node_modules/@intecion/ipal-kit/docs/accessibility.md`
@@ -586,6 +590,18 @@ Server only (`pnpm payload run`); never import it from client code, the Payload
| `buildSecurityHeaders({ hsts?, csp?, additional?, coop?, frameOptions?, permissionsPolicy?, referrerPolicy?, … })` | `@intecion/ipal-kit` | Returns `SecurityHeader[]` (HSTS, X-Frame-Options, nosniff, Referrer-Policy, Permissions-Policy, COOP; with `IPAL_NOINDEX` also `X-Robots-Tag`) for `headers()` in `next.config.ts`. `csp` = `buildCsp` args → the CSP header (+ `Reporting-Endpoints` with `reportUri`); off by default. `additional` overrides by key. |
| `withSecurityConfig(nextConfig, { hidePoweredBy? })` | `@intecion/ipal-kit` | Next config wrapper: `poweredByHeader: false` + drops `X-Powered-By` from `headers()` (Next's "Next.js" and withPayload's "Next.js, Payload"). `withPayload(withSecurityConfig(nextConfig))`; `hidePoweredBy: false` = no change. |
| `secondFactorPassed(req)` | `@intecion/ipal-kit` | `boolean` with `req` (`{ payload, user }`): `false` only for an account of the 2FA collection that has TOTP set up and has not entered the code in this session (password only). `true` for a full login, an API key, an account that has not set TOTP up yet, accounts of other auth collections, no user, and with `twoFactor: false`. Guard your own endpoints with it: `if (!req.user \|\| !secondFactorPassed(req)) return 403`. |
| `safeAdminBack(back, { adminRoute, origin? })` | `@intecion/ipal-kit` | The default `back` rule of the 2FA screens: returns `back` as a path when it resolves to the site's origin (the placeholder origin for relative values, `origin` for absolute ones), over HTTP(S), without credentials, inside `adminRoute`; otherwise the admin root. `safeAdminBack('javascript:alert(1)', { adminRoute: '/admin' })` → `'/admin'`; `safeAdminBack('/admin/collections/pages?page=2', { adminRoute: '/admin' })` → the same path. Use it in your own rule or view. |
| `wrapTotpViews(views, added, rule?, wrapper?)` | `@intecion/ipal-kit` | Puts `SafeTotpView` in front of the views whose route is `setup-totp` / `verify-totp` and for which `added(key)` is true (keeps `exportName`, `serverProps`; `clientProps` travel as `ipalTotpClientProps`); returns `{ views, dependencies }` (`dependencies` → `admin.dependencies`, so the wrapped views stay in the import map). What `ipalKit` runs after the 2FA factory; for a project that registers the 2FA package itself. |
| `copyViews(views)` / `changedViewKeys(before, after)` | `@intecion/ipal-kit` | The comparison `ipalKit` uses to tell which views a 2FA factory registered: put `copyViews(views)` into the config before calling the factory, then `changedViewKeys(before, viewsAfter)` gives the keys whose view object changed — the `added` argument of `wrapTotpViews` (`(key) => keys.has(key)`). By object, not by key: the 2FA package replaces a view that already stands under its keys. Example: security.md "Your own 2FA screen". |
| `SAFE_TOTP_VIEW` / `totpViewImportKey(component)` | `@intecion/ipal-kit` | `'@intecion/ipal-kit/admin#SafeTotpView'`, the wrapper's import-map path (the default `wrapper` of `wrapTotpViews`); and the import-map key (`path#export`) of a component given as a string or `{ path, exportName }`. |
| `findImportMapFile(config, cwd?)` / `missingImportMapEntries(config, entries, cwd?)` | `@intecion/ipal-kit` | Where the project's `importMap.js` is on disk (`admin.importMap.importMapFile`, else `app/(payload)<admin route>/` or `src/app/…` under `admin.importMap.baseDir` / the working directory; `null` when not found), and which of `entries` its text does not contain (`{ file, missing }`). A hint from the file on disk, not the map in the build: warn on it, never block on it. Behind `twoFactor.importMapCheck`. |
| `buildSetupFields({ statusField? })`, `stampSetupFrom`, `backfillSetupFrom(payload, collection)` | `@intecion/ipal-kit` | The parts of "2FA setup required" for a project that wires them itself: the fields for the 2FA collection (`totpSetupFrom`, and the panel's `totpSetupStatus` unless `statusField: false`), the `beforeChange` hook that stamps the window start (on create, and when an account loses its TOTP secret), and the start-up step that gives accounts without TOTP and without a start their window (returns how many; once per account). |
| `buildTwoFactorResetEndpoint(collection, { access? })`, `TWO_FACTOR_RESET_PATH` | `@intecion/ipal-kit` | `POST /api/ipal/two-factor/reset` `{ userId }`: clears the account's TOTP secret and sessions and starts a new window. Default: a staff admin whose session entered its own TOTP code; `access` replaces that (only `true` allows; a session that owes its code is always refused). `ipalKit` registers it only with `twoFactor.guard` on. |
| `countAccountsWithoutTotp(payload, collection, setupWindowMs?)` | `@intecion/ipal-kit` | `{ without, blocked }` — accounts of the 2FA collection without TOTP, and how many are past their window. |
| `resolveRequireSetup(option)`, `strictExempt(fn)`, `SETUP_FROM_FIELD`, `DEFAULT_SETUP_WINDOW_HOURS` | `@intecion/ipal-kit` | `twoFactor.requireSetup` → `{ requireSetup, setupWindowMs, exempt? }` as the guard reads it (throws on a `windowHours` that is not a number ≥ 0 or `false`, and on an `async` `exempt`); the wrapper that makes an `exempt` function answer `true` only for exactly `true`; the field name `'totpSetupFrom'`; `72`. |
| `fetchPublicImage(url, base)`, `publicImageDataUri(url, base)`, `rasterImageType(bytes)`, `siteOrigin(serverURL)`, `PUBLIC_IMAGE_MAX_BYTES` | `@intecion/ipal-kit` | An image fetched the way an anonymous visitor gets it (no cookies; http(s) only; `image/*`; at most 512 KB, reading stops at the limit) as `{ bytes, type }` or a `data:` address, else `null`. Used for the logo and icon on the 2FA screens. `rasterImageType(bytes)` → the media type of a bitmap by its first bytes (PNG, JPEG, GIF, WebP, ICO, AVIF) or `null` — never trust a claimed type before answering a file's bytes from the site's origin; an SVG gives `null`. |
| `UPLOAD_SECURITY_HEADERS` | `@intecion/ipal-kit` | The two headers of `buildUploadSecurityHeaders` (`Content-Security-Policy: default-src 'none'; … sandbox`, `X-Content-Type-Options: nosniff`) for a route of your own that returns an uploaded file's bytes from the site's origin. In a Next project a site-wide `headers()` rule with the same key overrides a header the route sets itself: add a `headers()` rule for the path after the site-wide one (as `buildUploadSecurityHeaders({ collections, adminIcon })` does for the upload routes and `/api/ipal/admin-icon`), and never answer with an SVG. |
| `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'`. |
+21 -1
View File
@@ -203,7 +203,7 @@ behind Cloudflare, `x-forwarded-for` behind a plain proxy), `IPAL_NOINDEX` (empt
One language: one entry in `locales`, no `[locale]` folder (i18n.md).
**Check.** `pnpm payload generate:importmap` (whiteLabel adds admin components) and `pnpm generate:types` without
errors (the import map lists `@intecion/ipal-kit/admin#TotpRedirectProvider`); `pnpm dev`, `/admin`: first-user screen → after saving, TOTP setup is enforced (`/admin/setup-totp?back=%2Fadmin`, QR, no reloading);
errors (the import map lists `@intecion/ipal-kit/admin#TotpRedirectProvider` and `#SafeTotpView`); `pnpm dev`, `/admin`: first-user screen → after saving, TOTP setup is enforced (`/admin/setup-totp?back=%2Fadmin`, QR, no reloading);
the panel shows Site settings, Site integrations, Cookies, Form messages, the Forms group, Consent records.
`curl -s -o /dev/null -w '%{http_code}' -X POST localhost:3000/api/ipal/consent -H 'content-type: application/json'
-d '{"id":"0123456789abcdef","version":1,"state":{"necessary":true,"functional":false,"analytics":false,"marketing":false}}'` → `201`.
@@ -225,8 +225,28 @@ the panel shows Site settings, Site integrations, Cookies, Form messages, the Fo
(the plugin's own, and those of plugins listed after `ipalKit`) and the plugin's endpoints; guard your own
endpoints with `secondFactorPassed(req)` or `userMeetsRole(req, role)` (security.md "What the second factor covers").
Verify attempts: 5 per account in 10 minutes (`twoFactor.verifyLimit`).
The `back` link of the setup and verify screens is checked on the server (`twoFactor.safeBack`, on by default:
only a path inside the admin route is kept; `false` turns it off, a function replaces the rule). It needs the
import map entry `@intecion/ipal-kit/admin#SafeTotpView` — run `pnpm payload generate:importmap` and commit
(a production build with a map that lacks it shows 2FA screens without a code form: nobody can sign in;
`ipal-doctor`, the start log and a notice above the screen report it; `twoFactor.importMapCheck: false` turns the
log line and the notice off — needed when the `importMap.js` on disk is not the one the build used).
Check: password only → `/admin/verify-totp?back=https%3A%2F%2Fexample.com%2F` → code → you land on `/admin`.
**Set 2FA up right after creating an account** (log in as it, scan the code): until then its password alone
opens everything its role allows. One entity reachable without the code: `custom.ipal.secondFactor`.
**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` and have the migration applied when the container starts, before the site serves** — `prodMigrations`
or the start command `pnpm payload migrate && pnpm start`, never a pre-deployment command (deployment.md §4.3)
(column `totp_setup_from`, there whenever 2FA is
on) — without it every login answers 500; `pnpm payload generate:importmap` (`TwoFactorStatusField`,
`TwoFactorAlert`). A service account that logs in with a password: `requireSetup: { exempt }` (a plain function
returning exactly `true`; never `async`); an API key needs nothing. Parts to switch off: `requireSetup:
{ dashboardNotice: false, statusField: false, setupNotice: false }`. An admin's reset ends the account's
sessions and needs the admin's own TOTP code (`twoFactor.resetAccess` changes who). Have two administrators
with 2FA: when all are blocked, only a script or a redeploy helps (security.md "Every administrator is
blocked"). 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
@@ -362,6 +362,65 @@ panel → Site integrations and a form submission open, a setting saves. With a
gets `403` from the same addresses and from `POST /api/setup-totp`. The Coolify log has no
`PAYLOAD_SECRET must be at least`; `pnpm exec ipal-doctor` has no `env` finding.
**→ 1.16.5 (PROGRAMISTA §6, item 67; CHANGELOG 1.16.5; security.md "The `back` link of the 2FA screens") — required with 2FA on:**
1. **Do this in ONE deploy with the upgrade, or the panel is locked for everyone.** Run `pnpm exec ipal-doctor`
before deploying.
`pnpm payload generate:importmap` — the plugin puts `@intecion/ipal-kit/admin#SafeTotpView` in front of the
2FA package's setup and verify views; commit `importMap.js`, `rm -rf .next`, redeploy on Coolify. With the old
import map the build passes and the site starts, but the 2FA screens have no code form (HTTP 200) — nobody can
sign in. Signs: `pnpm exec ipal-doctor` → `import map lacks …SafeTotpView` (run it before deploying); the log
line `[ipal] The admin import map may be out of date` at start; the notice "Two-step verification may not be
available" where the form should be. Fix: the same command, commit, redeploy.
The log line and the notice with a **working** code form mean a false alarm (the `importMap.js` on disk is not
the one the build used — a Dockerfile runner stage, a re-exporting map): sign-in works; set
`twoFactor.importMapCheck: false`.
**Check:** log in with the password only → open `/admin/verify-totp?back=https%3A%2F%2Fexample.com%2F` → enter
the code → you land on `/admin` (not on example.com); a normal login still returns to the page you came from.
No option, env, schema or migration. A project that registered its own 2FA views, or wrote a proxy rule that
strips `back`, can keep them (`twoFactor.safeBack: false` turns the plugin's check off).
2. `pnpm ipal:skills`.
**→ 1.16.6 — 2FA setup required (CHANGELOG 1.16.6; PROGRAMISTA §6, item 68; security.md "Setup required") — required with 2FA on:**
**Not a routine patch, although the number is one.** From this version an account without 2FA can only set it up and is
blocked after 72 hours; on Postgres / SQLite a missing migration locks everyone out of the panel. Do not upgrade a live
site without steps 1–3 and a deploy day agreed with the owner. Steps 2, 3 and 5 go in ONE deploy.
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 (better two) has 2FA set up — otherwise nobody can reopen setup from the panel.
The 72 hours of existing accounts start at the first start after the deploy and are counted once (restarts
and redeploys do not extend them): agree the deploy day with the owner.
2. Update the package, `pnpm install`, `pnpm ipal:skills`, `pnpm payload generate:types`,
**`pnpm payload generate:importmap`** (new: `TwoFactorStatusField`, `TwoFactorAlert`; commit `importMap.js`),
then `pnpm exec ipal-doctor` before deploying.
3. **Postgres/SQLite — required, same deploy, or nobody can log in:** `pnpm payload migrate:create` (adds the
column `totp_setup_from` to the 2FA collection; needed whenever 2FA is on, also with `requireSetup: false`),
commit, and have it applied **when the new container starts**: `prodMigrations` in the database adapter, or the
start command `pnpm payload migrate && pnpm start` (deployment.md §4.3). **Never Coolify's Pre-deployment
command** — it runs in the old container, without the new migration, and the new version then starts without
the column. Without the column every login answers 500, administrators included; the log says
`[ipal] 2FA: the column for "totpSetupFrom" is missing … NOBODY CAN LOG IN`. `pnpm exec ipal-doctor` reports
it before the deploy. 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. The line appears on that first start only.
Postgres/SQLite: if logins answer 500 after the deploy, the migration from step 3 did not run — check that it
is committed and that the container runs migrations at start (deployment.md §4.3), then redeploy.
6. `requireSetup.exempt` must be a plain function returning `true` / `false` (an `async` one stops the start).
A script on an API key is refused by `POST /api/ipal/two-factor/reset` by default — pass
`twoFactor.resetAccess` if that is wanted. A reset ends the account's sessions (it logs in again); after a
suspected compromise change the password too. An SVG favicon has no tab icon on the 2FA screens.
7. Tell the owner what to tell the staff: a new account has 72 hours to set 2FA up, then an administrator must
choose "Reopen setup". Not wanted: `twoFactor.requireSetup: false`, or `{ windowHours: false }`.
**Every administrator is blocked** (all missed the 72 h): security.md "Every administrator is blocked" — a
`pnpm payload run` script that sets `totpSetupFrom` to now for one administrator, or
`requireSetup: { windowHours: false }` + redeploy, set 2FA up, put it back.
**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 -1
View File
@@ -47,7 +47,7 @@ Write everything in this file in English.
<!-- /starter:decisions -->
<!-- ipal-kit:start -->
## ipal-kit 1.16.4 — agent guide
## ipal-kit 1.16.6 — agent guide
<!-- Managed by `pnpm exec ipal-skills` — edits between the markers are overwritten. -->
This project is built on `@intecion/ipal-kit` (a Payload CMS 3 plugin). Before you write code:
+92
View File
@@ -0,0 +1,92 @@
import { type Browser, expect, type Page, test } from '@playwright/test'
import { randomUUID } from 'node:crypto'
import { totp } from './totp'
/**
* The `back` link of the 2FA screens (twoFactor.safeBack, security.md). The 2FA package sends the browser to
* `back` after a valid code; ipal-kit checks the value first. A prepared link must end on the admin root:
* no script in the panel, no other site. Run against a built site with the test admin (create-test-admin.ts).
*
* Two verify attempts for the test admin here; the smoke spec makes two more (the limit is 5 in 10 minutes).
*/
const { E2E_ADMIN_EMAIL: email, E2E_ADMIN_PASSWORD: password, E2E_TOTP_SECRET: secret } = process.env
/** Script that would mark the page: runs only if the browser follows `back` as given. */
const SCRIPT = "javascript:void(document.title='XSS-'+document.domain)"
async function passwordOnly(browser: Browser, baseURL: string, who: { email: string; password: string }): Promise<Page> {
const context = await browser.newContext({ baseURL })
const page = await context.newPage()
await page.goto('/admin/login')
await page.fill('#field-email', who.email)
await page.fill('#field-password', who.password)
await page.click('.form-submit button')
await page.waitForURL(/(verify|setup)-totp/, { waitUntil: 'commit' })
return page
}
async function enterCode(page: Page, code: string) {
// six one-digit inputs: type the code into the first, focus moves on by itself
await page.getByRole('textbox').first().click()
await page.keyboard.type(code)
}
/** The page ended on the admin root of this site, and the marker script did not run. */
async function expectAdminRoot(page: Page, baseURL: string) {
await expect(page).toHaveURL(new RegExp(`^${baseURL.replace(/[.*+?^${}()|[\]\\]/g, '\\$&')}/admin/?$`), { timeout: 20_000 })
await expect(page).toHaveTitle(/Dashboard|Pulpit/, { timeout: 20_000 })
expect(await page.title()).not.toContain('XSS-')
}
test('2FA screens: a prepared back link ends on the admin root', async ({ baseURL, browser }) => {
test.skip(!email || !password || !secret, 'E2E_* test admin not configured')
test.setTimeout(120_000)
const admin = { email: email!, password: password! }
const other = new URL(baseURL!)
other.hostname = other.hostname === 'localhost' ? '127.0.0.1' : 'localhost' // another origin, still this machine
// verify screen, script in `back`
const first = await passwordOnly(browser, baseURL!, admin)
await first.goto(`/admin/verify-totp?back=${encodeURIComponent(SCRIPT)}`)
await enterCode(first, totp(secret!))
await expectAdminRoot(first, baseURL!)
// two accounts that have not set TOTP up yet, made by the admin who is now fully signed in
const fresh = [0, 1].map(() => ({ email: `e2e-back-${randomUUID()}@example.com`, password: `T-${randomUUID()}` }))
const ids: string[] = []
for (const account of fresh) {
const created = await first.request.post('/api/users', { data: { ...account, roles: ['editor'] }, headers: { origin: baseURL! } })
expect(created.status()).toBe(201)
ids.push((await created.json()).doc.id)
}
try {
// verify screen, another host written with a backslash
const second = await passwordOnly(browser, baseURL!, admin)
await second.goto(`/admin/verify-totp?back=${encodeURIComponent(`/\\${other.host}/admin/login?landed=elsewhere`)}`)
await enterCode(second, totp(secret!))
await expectAdminRoot(second, baseURL!)
await second.context().close()
// setup screen, script in `back`
const third = await passwordOnly(browser, baseURL!, fresh[0])
await third.goto(`/admin/setup-totp?back=${encodeURIComponent(SCRIPT)}`)
const newSecret = await third.locator('input[type="hidden"]').evaluateAll((inputs) => inputs.map((i) => (i as HTMLInputElement).value).find((v) => /^[A-Z2-7]{16,}$/.test(v)))
expect(newSecret).toBeTruthy()
await enterCode(third, totp(newSecret!))
await expectAdminRoot(third, baseURL!)
await third.context().close()
// setup screen, an ordinary link back into the panel is still followed
const fourth = await passwordOnly(browser, baseURL!, fresh[1])
await fourth.goto(`/admin/setup-totp?back=${encodeURIComponent('/admin/collections/pages?limit=5')}`)
const fourthSecret = await fourth.locator('input[type="hidden"]').evaluateAll((inputs) => inputs.map((i) => (i as HTMLInputElement).value).find((v) => /^[A-Z2-7]{16,}$/.test(v)))
await enterCode(fourth, totp(fourthSecret!))
await expect(fourth).toHaveURL(/\/admin\/collections\/pages\?limit=5$/, { timeout: 20_000 })
await fourth.context().close()
} finally {
for (const id of ids) {await first.request.delete(`/api/users/${id}`, { headers: { origin: baseURL! } })}
await first.context().close()
}
})
+127
View File
@@ -0,0 +1,127 @@
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()
// the brand images must load on the setup screen too (the session is refused `media` itself)
const refusedImages: string[] = []
page.on('response', (r) => {
if (r.status() === 403 && /\/api\/(media\/|ipal\/admin-icon)/.test(r.url())) {refusedImages.push(r.url())}
})
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)
}
expect(refusedImages).toEqual([])
// 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()
})
+10 -4
View File
@@ -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,13 +40,15 @@ 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'
import { TOTPSetup as TOTPSetup_3eb2cc20d1a2569c2ccbafcee15bd128 } from '@clocklimited/payload-2fa/rsc'
import { TOTPVerify as TOTPVerify_3eb2cc20d1a2569c2ccbafcee15bd128 } from '@clocklimited/payload-2fa/rsc'
import { SafeTotpView as SafeTotpView_7568fe47d582ff15ce85d2e1873c2c23 } from '@intecion/ipal-kit/admin'
import { CookieApprovalView as CookieApprovalView_7568fe47d582ff15ce85d2e1873c2c23 } from '@intecion/ipal-kit/admin'
import { CollectionCards as CollectionCards_f9c02e79a4aed9a3924487c0cd4cafb1 } from '@payloadcms/next/rsc'
import { TOTPSetup as TOTPSetup_3eb2cc20d1a2569c2ccbafcee15bd128 } from '@clocklimited/payload-2fa/rsc'
import { TOTPVerify as TOTPVerify_3eb2cc20d1a2569c2ccbafcee15bd128 } from '@clocklimited/payload-2fa/rsc'
import { S3ClientUploadHandler as S3ClientUploadHandler_f97aa6c64367fa259c5bc0567239ef24 } from '@payloadcms/storage-s3/client'
/** @type import('payload').ImportMap */
@@ -81,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,
@@ -91,12 +95,14 @@ 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,
"@clocklimited/payload-2fa/rsc#TOTPSetup": TOTPSetup_3eb2cc20d1a2569c2ccbafcee15bd128,
"@clocklimited/payload-2fa/rsc#TOTPVerify": TOTPVerify_3eb2cc20d1a2569c2ccbafcee15bd128,
"@intecion/ipal-kit/admin#SafeTotpView": SafeTotpView_7568fe47d582ff15ce85d2e1873c2c23,
"@intecion/ipal-kit/admin#CookieApprovalView": CookieApprovalView_7568fe47d582ff15ce85d2e1873c2c23,
"@payloadcms/next/rsc#CollectionCards": CollectionCards_f9c02e79a4aed9a3924487c0cd4cafb1,
"@clocklimited/payload-2fa/rsc#TOTPSetup": TOTPSetup_3eb2cc20d1a2569c2ccbafcee15bd128,
"@clocklimited/payload-2fa/rsc#TOTPVerify": TOTPVerify_3eb2cc20d1a2569c2ccbafcee15bd128,
"@payloadcms/storage-s3/client#S3ClientUploadHandler": S3ClientUploadHandler_f97aa6c64367fa259c5bc0567239ef24
}
+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;
+2
View File
@@ -60,8 +60,10 @@ 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',
'e2e/totp.ts': 'RFC 6238 code generator for the 2FA sign-in in the smoke test',
'ipal-doctor.json': 'the production domain and launch state for ipal-doctor',
'next.config.ts': 'security headers, enforced CSP, admin CSP, upload headers, images, no X-Powered-By',
+5
View File
@@ -18,8 +18,13 @@ export { CookieSiteCheckTab } from '../modules/consent/scanner/CookieSiteCheckTa
export { CookieCrawlAlert } from '../modules/consent/scanner/crawl/CookieCrawlAlert.js'
export { IntegrationAlerts } from '../modules/integrations/IntegrationAlerts.js'
export { IntegrationStatusBanner } from '../modules/integrations/IntegrationStatusBanner.js'
export { SafeTotpView } from '../modules/security/totp/SafeTotpView.js'
export type { SafeTotpViewProps } from '../modules/security/totp/SafeTotpView.js'
export { TotpRedirectProvider } from '../modules/security/totp/TotpRedirectProvider.js'
export type { TotpRedirectProviderProps } from '../modules/security/totp/TotpRedirectProvider.js'
export { 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'
+21 -2
View File
@@ -40,6 +40,7 @@ export type { SectionHeaderFieldOptions, SectionSettingsFieldOptions } from './m
export { buildAdminImageEndpoints } from './modules/branding/adminImages.js'
export { ADMIN_META_TEXTS, adminMetaForSite, buildAdminMeta, DEFAULT_AGENCY, syncAdminMeta } from './modules/branding/adminMeta.js'
export type { AdminMetaOptions, AgencyOption, ResolvedAdminMeta } from './modules/branding/adminMeta.js'
export { fetchPublicImage, PUBLIC_IMAGE_MAX_BYTES, publicImageDataUri, rasterImageType, siteOrigin } from './modules/branding/publicImage.js'
export {
ACCEPT_ALL_CONSENT,
buildConsentLogCollection,
@@ -312,6 +313,7 @@ export {
parseCspReports,
totpAdminPath,
totpRedirectTarget,
UPLOAD_SECURITY_HEADERS,
withSecurityConfig,
} from './modules/security/index.js'
export type {
@@ -325,9 +327,26 @@ export type {
TotpUser,
WithSecurityConfigOptions,
} from './modules/security/index.js'
export type { BuildSecurityHeadersArgs, SecurityHeader } from './modules/security/index.js'
export { requireSecondFactor, secondFactorPassed } from './modules/security/totp/secondFactor.js'
export type { BuildSecurityHeadersArgs, SecurityHeader } from './modules/security/index.js'
export { findImportMapFile, missingImportMapEntries } from './modules/security/totp/importMapCheck.js'
export { changedViewKeys, copyViews, SAFE_TOTP_VIEW, safeAdminBack, totpViewImportKey, wrapTotpViews } from './modules/security/totp/safeBack.js'
export type { SafeBackContext, SafeBackRule, TotpViewComponent } from './modules/security/totp/safeBack.js'
export { requireSecondFactor, secondFactorPassed, twoFactorSetupDeadline, twoFactorSetupState } from './modules/security/totp/secondFactor.js'
export type { TwoFactorSetupState } from './modules/security/totp/secondFactor.js'
export { SETUP_FROM_FIELD } from './modules/security/totp/secondFactor.js'
export {
backfillSetupFrom,
buildSetupFields,
buildTwoFactorResetEndpoint,
countAccountsWithoutTotp,
DEFAULT_SETUP_WINDOW_HOURS,
resolveRequireSetup,
stampSetupFrom,
strictExempt,
TWO_FACTOR_RESET_PATH,
} from './modules/security/totp/setupRequired.js'
export type { RequireSetupOptions, TwoFactorResetOptions } 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.',
},
})
+13
View File
@@ -2,6 +2,8 @@ import type { Payload } from 'payload'
import { ipalT } from '../admin-i18n/t.js'
import { settingsTexts } from '../admin-i18n/texts/settings.js'
import { secondFactorPassed } from '../security/totp/secondFactor.js'
import { publicImageDataUri, siteOrigin } from './publicImage.js'
/**
* White-label admin branding: the Payload admin panel's logo (login + nav) and
@@ -25,6 +27,8 @@ import { settingsTexts } from '../admin-i18n/texts/settings.js'
type BrandingProps = {
/** Upload field to render as the image. Default 'logo' (Logo) / 'favicon' (Icon). */
imageField?: string
/** `whiteLabel.inlineImages: false` — never fetch the image on the server for the 2FA screens. */
inlineImages?: false
/** Injected by Payload — current admin locale (object or code). */
locale?: { code?: string } | string
/** Field holding the site name. Default 'siteName'. */
@@ -33,6 +37,8 @@ type BrandingProps = {
payload?: Payload
/** SiteSettings global slug. Default 'site-settings'. */
settingsSlug?: string
/** Injected by Payload into admin server components — the account looking at the panel. */
user?: null | Record<string, unknown>
}
type MediaLike = { url?: null | string } | null | undefined
@@ -70,6 +76,13 @@ async function loadBranding(
const image = settings[imageField] as MediaLike
const url =
image && typeof image === 'object' && typeof image.url === 'string' ? image.url : null
// A session that still owes its 2FA code (or has not set 2FA up) is refused `media` like every
// other collection, so the browser would show a broken image on the verify / setup screens.
// Give it the picture itself, fetched as an anonymous visitor would get it; when that fails
// (media is not public), the site name is shown instead.
if (url && props.inlineImages !== false && props.user && !secondFactorPassed({ payload, user: props.user })) {
return { name, url: await publicImageDataUri(url, siteOrigin(payload.config.serverURL)) }
}
return { name, url }
} catch (error) {
console.warn('[ipal] admin branding: falling back to Payload default:', error)
+22 -3
View File
@@ -2,7 +2,9 @@ import type { Endpoint, PayloadRequest } from 'payload'
import type { AgencyOption, ResolvedAdminMeta } from './adminMeta.js'
import { UPLOAD_SECURITY_HEADERS } from '../security/buildSecurityHeaders.js'
import { ADMIN_ICON_PATH, ADMIN_META_TEXTS, ADMIN_OG_PATH } from './adminMeta.js'
import { fetchPublicImage, rasterImageType } from './publicImage.js'
/**
* The panel's link-preview image (1200×630) and icon, drawn from SiteSettings:
@@ -13,13 +15,13 @@ import { ADMIN_ICON_PATH, ADMIN_META_TEXTS, ADMIN_OG_PATH } from './adminMeta.js
* the site name, then to initials.
*/
type Fields = { iconField?: string; logoField?: string; nameField?: string; settingsSlug?: string }
type Fields = { iconField?: string; logoField?: string; nameField?: string; serveIcon?: false; settingsSlug?: string }
type Branding = { icon: null | string; logo: null | string; name: string }
const CACHE = 'public, max-age=3600, s-maxage=3600'
async function loadBranding(req: PayloadRequest, f: Required<Fields>): Promise<Branding> {
async function loadBranding(req: PayloadRequest, f: Required<Omit<Fields, 'serveIcon'>>): Promise<Branding> {
try {
const locale = req.payload.config.localization ? req.payload.config.localization.defaultLocale : undefined
const s = (await req.payload.findGlobal({ slug: f.settingsSlug as never, depth: 1, ...(locale ? { locale: locale as never } : {}), req })) as Record<string, unknown>
@@ -62,7 +64,7 @@ const initials = (name: string) =>
.join('') || 'A'
export function buildAdminImageEndpoints(resolved: ResolvedAdminMeta, fields: Fields = {}): Endpoint[] {
const f: Required<Fields> = {
const f: Required<Omit<Fields, 'serveIcon'>> = {
iconField: fields.iconField ?? 'favicon',
logoField: fields.logoField ?? 'logo',
nameField: fields.nameField ?? 'siteName',
@@ -105,6 +107,23 @@ export function buildAdminImageEndpoints(resolved: ResolvedAdminMeta, fields: Fi
handler: async (req) => {
const brand = await loadBranding(req, f)
if (brand.icon) {
// The picture itself, fetched the way an anonymous visitor gets it — not a redirect to the
// media file: a panel session that still owes its 2FA code is refused that file (it is
// refused every collection), and a cached redirect would send it there anyway. The answer
// is the same for everyone, so it can be cached like the redirect was.
const image = fields.serveIcon === false ? null : await fetchPublicImage(absolute(brand.icon, req), null)
// Only a bitmap is answered from here, recognised by its first bytes — never an SVG, which
// is a document that can run script in the site's origin. The headers below are the upload
// routes' (sandbox, no sniffing), but a Next project's site-wide CSP rule overrides a
// route's own header, so they are a second layer, not the protection.
const type = image ? rasterImageType(image.bytes) : null
if (image && type) {
return new Response(new Uint8Array(image.bytes), {
headers: { 'Cache-Control': CACHE, 'Content-Type': type, ...Object.fromEntries(UPLOAD_SECURITY_HEADERS.map((h) => [h.key, h.value])) },
})
}
// An SVG favicon, or not fetchable from here (too large, media is not public): the browser
// goes to the media file itself, where the upload route's own headers apply.
return new Response(null, { headers: { 'Cache-Control': CACHE, Location: absolute(brand.icon, req) }, status: 302 })
}
const ImageResponse = await imageResponse()
+6
View File
@@ -37,6 +37,12 @@ export type AdminMetaOptions = {
language?: 'en' | 'pl'
/** Robots meta. Default noindex, nofollow. `false` = none. */
robots?: { follow?: boolean; index?: boolean } | false
/**
* `/api/ipal/admin-icon` answers with the favicon's bytes (fetched as an anonymous visitor gets
* them, with the upload security headers), so it also loads for a session that still owes its
* 2FA code. `false` = a redirect to the media file instead, as before.
*/
serveIcon?: false
/** Browser-tab suffix; `{site}` is replaced. Default "— {site} | Panel". `false` = none. */
titleSuffix?: false | string
}
+84
View File
@@ -0,0 +1,84 @@
/**
* An image of the site's brand fetched the way an anonymous visitor would get
* it: no cookies, no credentials. For the moments when the browser itself
* cannot load it — a panel session that still owes its 2FA code (or has not
* set 2FA up) is refused every collection, `media` included, although the
* same file is public. Serving the bytes from here opens nothing: only what
* answers an anonymous request comes back, and only an image of a sane size.
*/
export const PUBLIC_IMAGE_MAX_BYTES = 512 * 1024
const MAX_BYTES = PUBLIC_IMAGE_MAX_BYTES
export async function fetchPublicImage(url: null | string | undefined, base: null | string | undefined): Promise<{ bytes: Buffer; type: string } | null> {
if (!url) {return null}
let target: URL
try {
target = new URL(url, base || undefined)
} catch {
return null // a relative address and no site origin to resolve it against
}
if (target.protocol !== 'http:' && target.protocol !== 'https:') {return null}
try {
const res = await fetch(target, { credentials: 'omit', redirect: 'follow', signal: AbortSignal.timeout(5000) })
if (!res.ok) {return null}
const type = (res.headers.get('content-type') ?? '').split(';')[0].trim()
if (!type.startsWith('image/')) {return null}
// Too large is known before reading when the server says so; otherwise stop reading at the limit.
const declared = Number(res.headers.get('content-length'))
if (Number.isFinite(declared) && declared > MAX_BYTES) {
await res.body?.cancel().catch(() => undefined)
return null
}
const bytes = await readUpTo(res, MAX_BYTES)
if (!bytes?.length) {return null}
return { type, bytes }
} catch {
return null
}
}
/**
* The media type of a bitmap image, read from the first bytes — never from what a server or a
* file name claims: PNG, JPEG, GIF, WebP, ICO, AVIF. Null for anything else, **SVG included**:
* an SVG is a document that can carry script, and bytes answered from the site's own origin
* must never be one (the site-wide CSP of a Next project overrides a route's own sandbox header).
*/
export function rasterImageType(bytes: Uint8Array): null | string {
const b = bytes
const ascii = (from: number, text: string) => text.split('').every((ch, i) => b[from + i] === ch.charCodeAt(0))
if (b.length >= 8 && b[0] === 0x89 && ascii(1, 'PNG') && b[4] === 0x0d && b[5] === 0x0a && b[6] === 0x1a && b[7] === 0x0a) {return 'image/png'}
if (b.length >= 3 && b[0] === 0xff && b[1] === 0xd8 && b[2] === 0xff) {return 'image/jpeg'}
if (b.length >= 6 && (ascii(0, 'GIF87a') || ascii(0, 'GIF89a'))) {return 'image/gif'}
if (b.length >= 12 && ascii(0, 'RIFF') && ascii(8, 'WEBP')) {return 'image/webp'}
if (b.length >= 4 && b[0] === 0 && b[1] === 0 && b[2] === 1 && b[3] === 0) {return 'image/x-icon'}
if (b.length >= 12 && ascii(4, 'ftyp') && (ascii(8, 'avif') || ascii(8, 'avis'))) {return 'image/avif'}
return null
}
/** The body, or null as soon as it grows past `limit` (the rest is not downloaded). */
async function readUpTo(res: Response, limit: number): Promise<Buffer | null> {
const reader = res.body?.getReader()
if (!reader) {return null}
const chunks: Uint8Array[] = []
let size = 0
for (;;) {
const { done, value } = await reader.read()
if (done) {break}
size += value.byteLength
if (size > limit) {
await reader.cancel().catch(() => undefined)
return null
}
chunks.push(value)
}
return Buffer.concat(chunks)
}
/** The same as a `data:` address for an `<img>`. */
export async function publicImageDataUri(url: null | string | undefined, base: null | string | undefined): Promise<null | string> {
const image = await fetchPublicImage(url, base)
return image ? `data:${image.type};base64,${image.bytes.toString('base64')}` : null
}
/** The site's own origin as the config or the environment states it, for resolving `/api/media/file/…`. */
export const siteOrigin = (serverURL: null | string | undefined): null | string => serverURL || process.env.NEXT_PUBLIC_SERVER_URL || null
+22
View File
@@ -198,6 +198,28 @@ export const layoutRules: DoctorRule[] = [
if (/payloadTotp/.test(cfg)) {
need.push('@clocklimited/payload-2fa/rsc#TOTPSetup')
if (!lt(v, '1.14.2')) {need.push('@intecion/ipal-kit/admin#TotpRedirectProvider')}
// "2FA setup required": the status / reset control on the account and the dashboard notice — when the
// installed plugin has them and the config does not switch them (or the mode) off. Without them the
// panel shows no "Reopen setup": the documented way out of a blocked account is missing.
const adminExports = ctx.read('node_modules/@intecion/ipal-kit/dist/exports/admin.js')
const modeOff = /requireSetup\s*:\s*false|guard\s*:\s*false/.test(cfg)
if (/\bTwoFactorStatusField\b/.test(adminExports) && !modeOff && !/statusField\s*:\s*false/.test(cfg)) {need.push('@intecion/ipal-kit/admin#TwoFactorStatusField')}
if (/\bTwoFactorAlert\b/.test(adminExports) && !modeOff && !/dashboardNotice\s*:\s*false/.test(cfg)) {need.push('@intecion/ipal-kit/admin#TwoFactorAlert')}
// the back-link check in front of the 2FA screens (twoFactor.safeBack) — when the installed plugin has it
if (/\bSafeTotpView\b/.test(ctx.read('node_modules/@intecion/ipal-kit/dist/exports/admin.js')) && !/safeBack\s*:\s*false/.test(cfg)) {
need.push('@intecion/ipal-kit/admin#SafeTotpView')
}
}
// A view the project registers itself with the 2FA package's own component is not behind the back-link check.
// Only as a view's component (`Component: '<path>'` or `Component: { path: '<path>' }`): the same path as the
// value of `ipalTotpView` or of an `admin.dependencies` entry is the fix, not the problem.
if (/\bComponent\s*:\s*(?:\{[^{}]*?\bpath\s*:\s*)?['"`]@clocklimited\/payload-2fa\/rsc#TOTP(?:Setup|Verify)\b/.test(cfg)) {
out.push({
file: configFile(ctx) ?? undefined,
fix: "register it through wrapTotpViews (or Component: { path: '@intecion/ipal-kit/admin#SafeTotpView', serverProps: { ipalTotpView: '<that path>' } } plus the path in admin.dependencies) — security.md \"Your own 2FA screen\"",
message: "the config registers the 2FA package's own setup / verify view as a view component: it sends the browser to an unchecked `back` link after the code",
severity: 'warning',
})
}
if (/buildR2Storage/.test(cfg)) {need.push('S3ClientUploadHandler')}
if (/cookieScanner\s*:\s*(?!false)/.test(cfg) && !lt(v, '1.14.4')) {need.push('@intecion/ipal-kit/admin#CookieReviewTab')}
+29 -1
View File
@@ -106,7 +106,35 @@ 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' })}
// Postgres / SQLite: the 2FA collection has the column `totp_setup_from` (whenever 2FA is on). Without a
// migration that adds it, every query on the collection fails in production — nobody can log in.
const sqlAdapter = ['@payloadcms/db-postgres', '@payloadcms/db-vercel-postgres', '@payloadcms/db-sqlite', '@payloadcms/db-d1-sqlite'].some((name) => ctx.installed(name))
const pluginHasColumn = /totpSetupFrom/.test(ctx.read('node_modules/@intecion/ipal-kit/dist/modules/security/totp/secondFactor.js'))
if (sqlAdapter && pluginHasColumn && /payloadTotp/.test(code)) {
const dirs = [`${ctx.src}migrations`, 'migrations'].filter((dir) => ctx.exists(dir))
const files = dirs.flatMap((dir) => ctx.list(dir).filter((name) => /\.(?:ts|js|mjs|sql|json)$/.test(name)).map((name) => `${dir}/${name}`))
if (!files.some((file) => /totp_setup_from|totpSetupFrom/.test(ctx.read(file)))) {
out.push({
fix: 'pnpm payload migrate:create, commit the migration, and have it applied when the new container starts — prodMigrations in the adapter, or the start command `pnpm payload migrate && pnpm start`; not a pre-deployment command (docs/deployment.md §4.3) — in the same deploy, before the new version serves requests',
message: files.length
? 'no migration adds the 2FA column `totp_setup_from`: in production every login would answer 500 — nobody could sign in to the panel'
: 'a SQL database and no migrations folder: the 2FA column `totp_setup_from` must exist before this version runs in production (migrate:create; applied at container start — docs/deployment.md §4.3), or nobody can sign in',
severity: files.length ? 'error' : 'warning',
})
}
}
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
}
+24 -5
View File
@@ -157,13 +157,32 @@ export function buildSecurityHeaders(args: BuildSecurityHeadersArgs = {}): Secur
* ]
* }
*/
export function buildUploadSecurityHeaders({ collections = ['media'] }: { collections?: string[] } = {}): {
export function buildUploadSecurityHeaders({
adminIcon = '/api/ipal/admin-icon',
collections = ['media'],
}: {
/**
* Path of the plugin's panel icon endpoint, which answers with the favicon's bytes. It only ever
* answers with a bitmap; the rule is a second layer. Another API route: `'/cms-api/ipal/admin-icon'`;
* `false` = no rule.
*/
adminIcon?: false | string
collections?: string[]
} = {}): {
headers: SecurityHeader[]
source: string
}[] {
const headers: SecurityHeader[] = [
{ key: 'Content-Security-Policy', value: "default-src 'none'; img-src 'self' data:; style-src 'unsafe-inline'; sandbox" },
{ key: 'X-Content-Type-Options', value: 'nosniff' },
return [
...collections.map((slug) => ({ headers: [...UPLOAD_SECURITY_HEADERS], source: `/api/${slug}/file/:path*` })),
...(adminIcon ? [{ headers: [...UPLOAD_SECURITY_HEADERS], source: adminIcon }] : []),
]
return collections.map((slug) => ({ headers, source: `/api/${slug}/file/:path*` }))
}
/**
* The headers themselves: for any response that carries the bytes of an uploaded file from the
* site's own origin (the upload routes above; the plugin's `/api/ipal/admin-icon`; a route of yours).
*/
export const UPLOAD_SECURITY_HEADERS: readonly SecurityHeader[] = [
{ key: 'Content-Security-Policy', value: "default-src 'none'; img-src 'self' data:; style-src 'unsafe-inline'; sandbox" },
{ key: 'X-Content-Type-Options', value: 'nosniff' },
]
+1 -1
View File
@@ -8,7 +8,7 @@ export {
DEFAULT_CSP_REPORT_GROUP,
} from './buildCsp.js'
export type { BuildAdminCspArgs, BuildCspArgs, CspDirective, CspSources } from './buildCsp.js'
export { buildSecurityHeaders, buildUploadSecurityHeaders } from './buildSecurityHeaders.js'
export { buildSecurityHeaders, buildUploadSecurityHeaders, UPLOAD_SECURITY_HEADERS } from './buildSecurityHeaders.js'
export type { BuildSecurityHeadersArgs, SecurityHeader } from './buildSecurityHeaders.js'
export { createCspReportRoute, parseCspReports } from './createCspReportRoute.js'
export type { CreateCspReportRouteArgs, CspViolation } from './createCspReportRoute.js'
@@ -0,0 +1,70 @@
import type { AdminViewServerProps } from 'payload'
import type React from 'react'
import { RenderServerComponent } from '@payloadcms/ui/elements/RenderServerComponent'
import { getFromImportMap } from 'payload/shared'
import { safeAdminBack, type SafeBackRule, type TotpViewComponent, totpViewImportKey } from './safeBack.js'
export type SafeTotpViewProps = {
/** `twoFactor.safeBack` as a function: replaces the default rule. */
ipalSafeBack?: SafeBackRule
/** `clientProps` of the view's own registration; passed on to it. */
ipalTotpClientProps?: Record<string, unknown>
/** The view to render, as registered: `'@clocklimited/payload-2fa/rsc#TOTPVerify'` or `{ path, exportName }`. */
ipalTotpView: TotpViewComponent
} & AdminViewServerProps
const originOf = (serverURL: unknown): string | undefined => {
if (typeof serverURL !== 'string' || !serverURL) {return undefined}
try {
return new URL(serverURL).origin
} catch {
return undefined
}
}
/** What Payload itself hands a client view (AdminViewClientProps): all serializable. */
const CLIENT_PROPS = ['browseByFolderSlugs', 'clientConfig', 'collectionSlug', 'docID', 'documentSubViewType', 'folderID', 'globalSlug', 'viewType'] as const
/**
* In front of the 2FA package's setup and verify views: replaces the `back` query value with a
* checked one (safeBack.ts) and renders the view with it. The package's form sends the browser
* to `back` after a valid code, so what it receives must be safe to navigate to.
*
* The view is rendered the way Payload renders any view: a server component gets every server
* prop, with `searchParams.back` checked; a client component (a project's own screen set through
* the wrapped factory) gets only what can cross to the browser — Payload's client props, its own
* `clientProps`, `searchParams` and `back`, both checked.
*
* ipalKit registers it (twoFactor.safeBack, on by default). A project that registers 2FA views
* itself can use it too: `wrapTotpViews`, or give it `ipalTotpView` and list that path in
* `admin.dependencies`.
*/
export function SafeTotpView(props: SafeTotpViewProps): React.ReactNode {
const { ipalSafeBack, ipalTotpClientProps, ipalTotpView, ...rest } = props
const config = props.initPageResult?.req?.payload?.config ?? props.payload?.config
const query = (props.searchParams ?? {}) as Record<string, unknown>
const back = (ipalSafeBack ?? safeAdminBack)(typeof query.back === 'string' ? query.back : undefined, {
adminRoute: config?.routes?.admin ?? '/admin',
origin: originOf(config?.serverURL),
})
const searchParams = { ...query, back }
if (!getFromImportMap({ importMap: props.importMap, PayloadComponent: ipalTotpView, schemaPath: '', silent: true })) {
throw new Error(
`[ipal] The admin import map has no "${totpViewImportKey(ipalTotpView)}" (the 2FA screen ipal-kit puts its back-link check in front of). ` +
'Run `pnpm payload generate:importmap` and commit the result.',
)
}
const clientProps: Record<string, unknown> = { ...ipalTotpClientProps, back, searchParams }
for (const key of CLIENT_PROPS) {
if (key in rest) {clientProps[key] = (rest as Record<string, unknown>)[key]}
}
return RenderServerComponent({
clientProps,
Component: ipalTotpView,
importMap: props.importMap,
serverProps: { ...rest, searchParams },
})
}
@@ -2,18 +2,41 @@
import type { ReactNode } from 'react'
import { useAuth, useConfig } from '@payloadcms/ui'
import { useAuth, useConfig, useTranslation } from '@payloadcms/ui'
import { usePathname, useRouter } from 'next/navigation.js'
import { useEffect } from 'react'
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
* wrong. The screen itself is still rendered: the check is a guess, and a wrong guess must
* cost a wrong notice at most, never the code form.
*/
staleImportMap?: boolean
}
const STALE_TEXT = {
en: {
body: 'If there is no place to enter the code on this page, the site was deployed without a refreshed admin import map. A developer has to run "pnpm payload generate:importmap", commit importMap.js and deploy again.',
title: 'Two-step verification may not be available',
},
pl: {
body: 'Jeśli na tej stronie nie ma miejsca na wpisanie kodu, strona została wdrożona bez odświeżonej mapy importów panelu. Programista musi uruchomić "pnpm payload generate:importmap", zapisać importMap.js w repozytorium i wdrożyć stronę ponownie.',
title: 'Weryfikacja dwuetapowa może być niedostępna',
},
}
/**
@@ -24,7 +47,8 @@ export type TotpRedirectProviderProps = {
* Renders nothing while a redirect is pending, so the panel does not flash.
* Swap it with `twoFactor.provider`.
*/
export function TotpRedirectProvider({ children, forceSetup = true }: TotpRedirectProviderProps) {
export function TotpRedirectProvider({ children, forceSetup = true, requireSetup = false, setupWindowHours = 0, staleImportMap = false }: TotpRedirectProviderProps) {
const { i18n, t } = useTranslation()
const { user } = useAuth()
const { config } = useConfig()
const pathname = usePathname()
@@ -42,7 +66,62 @@ export function TotpRedirectProvider({ children, forceSetup = true }: TotpRedire
if (target) {router.replace(target)}
}, [router, target])
return target ? null : children
if (target) {return null}
// 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']
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>
)
}
// 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>
)
}
@@ -0,0 +1,56 @@
/**
* Is the project's committed admin import map older than the config?
*
* ipalKit registers `SafeTotpView` in front of the 2FA screens. Payload resolves view components
* through the import map file, and a path that is not in it renders NOTHING: the 2FA screen comes
* back empty (HTTP 200, no code form), so nobody can sign in — after an upgrade where
* `pnpm payload generate:importmap` was forgotten. In development Payload regenerates the file
* by itself; a production build uses the committed one. This check makes that state loud: an
* error in the server log at start, and a notice on the 2FA screens (TotpRedirectProvider) —
* shown next to the screen, never instead of it, because the check can be wrong (see
* `missingImportMapEntries`). `twoFactor.importMapCheck: false` turns it off.
*/
type ConfigLike = { admin?: { importMap?: { baseDir?: string; importMapFile?: string } }; routes?: { admin?: string } }
/** The file Payload reads the import map from — the same places Payload itself looks in. Null when not found. */
export async function findImportMapFile(config: ConfigLike, cwd = process.cwd()): Promise<null | string> {
try {
const fs = await import('node:fs/promises')
const path = await import('node:path')
const exists = (file: string) => fs.access(file).then(() => true, () => false)
const explicit = config.admin?.importMap?.importMapFile
if (explicit) {return (await exists(explicit)) ? explicit : null}
const rootDir = config.admin?.importMap?.baseDir ?? cwd
// Next.js writes %5F for route segments that begin with an underscore
const adminFolder = (config.routes?.admin ?? '/admin').replace(/(^|\/)_/g, '$1%5F')
for (const base of [`app/(payload)${adminFolder}`, `src/app/(payload)${adminFolder}`]) {
const file = path.resolve(rootDir, base, 'importMap.js')
if (await exists(file)) {return file}
}
} catch {
/* no file system (or not Node): nothing to check */
}
return null
}
/**
* The entries of `needed` that are not written in the import map file. An empty list when the
* file is not found or cannot be read.
*
* This is a text search of the file ON DISK, and a hint, not a fact: the map the running build
* uses is in the bundle. The two differ when the map is generated inside the build and the
* running image carries the repository's file (a Dockerfile runner stage with its own COPY), and
* the search misses a map that re-exports or builds its keys another way. So a caller may warn
* on the result, and must never block on it.
*/
export async function missingImportMapEntries(config: ConfigLike, needed: string[], cwd?: string): Promise<{ file: null | string; missing: string[] }> {
const file = await findImportMapFile(config, cwd)
if (!file) {return { file: null, missing: [] }}
try {
const fs = await import('node:fs/promises')
const text = await fs.readFile(file, 'utf8')
return { file, missing: needed.filter((entry) => !text.includes(`"${entry}"`) && !text.includes(`'${entry}'`)) }
} catch {
return { file, missing: [] }
}
}
+147
View File
@@ -0,0 +1,147 @@
/**
* The `back` query parameter of the 2FA setup and verify screens.
*
* @clocklimited/payload-2fa passes it, unchecked, to `location.replace()` once the code is
* accepted. Anyone can put it in a link in front of a panel user: `javascript:…` then runs in
* the admin origin with the session that has just passed the second factor, and an absolute
* URL sends the user off-site straight after a genuine login step (GHSA-rffw-fq79-g3ch in the
* original `payload-totp`, fixed there in 3.0.5; the fork does not have the fix).
*
* ipal-kit therefore cleans the value on the server before the package's view sees it
* (SafeTotpView.tsx): `twoFactor.safeBack` — on by default, a function replaces the rule,
* `false` turns it off.
*/
/** What a `back` rule is told about the panel. */
export type SafeBackContext = {
/** `routes.admin` of the Payload config, e.g. `/admin`. */
adminRoute: string
/**
* The site's own origin (from `serverURL`), when the config has one. An absolute `back` on
* this origin is accepted; without it only relative values are.
*/
origin?: string
}
/**
* A `back` rule: gets the raw query value (undefined when absent or repeated) and returns the
* URL the screen goes to after a valid code. Return a path on the site's own origin.
*/
export type SafeBackRule = (back: string | undefined, context: SafeBackContext) => string
/** Never a real site: a relative `back` is resolved against it, and anything that leaves it is refused. */
const PLACEHOLDER_ORIGIN = 'http://ipal-safe-back.invalid'
const trimSlashes = (path: string) => `/${path.replace(/^\/+|\/+$/g, '')}`
/**
* The default rule, the same as upstream's: `back` is resolved the way a browser resolves it
* and kept only when it stays on the site's origin, over HTTP(S), without credentials, inside
* the admin route. Anything else — `javascript:`, `data:`, `//host`, `/\host`, `\\host`,
* `https:host`, a path outside the panel, no value at all — gives the admin root.
*
* Returns a path (`/admin/collections/pages?page=2`), never an absolute URL, so the browser
* goes to exactly what was checked and cannot be taken off the origin.
*/
export const safeAdminBack: SafeBackRule = (back, { adminRoute, origin }) => {
const adminPath = trimSlashes(adminRoute || '/')
if (typeof back !== 'string' || !back) {return adminPath}
let base = PLACEHOLDER_ORIGIN
if (origin) {
try {
base = new URL(origin).origin
} catch {
/* not a URL: relative values only */
}
}
let url: URL
try {
url = new URL(back, base)
} catch {
return adminPath
}
// `blob:` URLs report the origin that made them, hence the protocol check.
if (url.origin !== base || !['http:', 'https:'].includes(url.protocol) || url.username || url.password) {
return adminPath
}
const inside = adminPath === '/' || url.pathname === adminPath || url.pathname.startsWith(`${adminPath}/`)
// The parser collapses `//`, but a path that still starts with two slashes would be read as a host.
if (!inside || url.pathname.startsWith('//')) {return adminPath}
return `${url.pathname}${url.search}${url.hash}`
}
/** The package's views that take `back` — matched by the route the package gives them. */
const TOTP_VIEW_PATH = /^\/?(?:setup|verify)-totp$/
/** Import-map path of the wrapper ipalKit registers. */
export const SAFE_TOTP_VIEW = '@intecion/ipal-kit/admin#SafeTotpView'
/** A view component as it stands in a Payload config. */
export type TotpViewComponent = { clientProps?: object; exportName?: string; path: string; serverProps?: object } | string
type ViewLike = { Component?: unknown; path?: string }
type Dependency = { exportName?: string; path: string; type: 'component' }
/** `path#export` of a component — the key it has in the import map. */
export const totpViewImportKey = (component: TotpViewComponent): string => {
const [path, hash] = (typeof component === 'string' ? component : component.path).split('#')
const exportName = (typeof component === 'object' ? component.exportName : undefined) ?? hash ?? 'default'
return `${path}#${exportName}`
}
/** Key of the `admin.dependencies` entry that keeps a wrapped view importable. */
export const totpViewDependencyKey = (component: TotpViewComponent) => `ipal-totp-view:${totpViewImportKey(component)}`
/**
* Puts ipal-kit's wrapper in front of the 2FA views for which `added(key)` is true and whose
* route is `setup-totp` / `verify-totp`: the wrapper cleans `back` and renders the original
* view, which it finds in the import map (`admin.dependencies` keeps it there). ipal-kit still
* never imports the optional package. The original's `serverProps` stay server props; its
* `clientProps` travel as `ipalTotpClientProps`, so the wrapper can hand them to a client view.
*/
export function wrapTotpViews<V extends ViewLike>(
views: Record<string, V>,
added: (key: string) => boolean,
rule: SafeBackRule | undefined,
wrapper = SAFE_TOTP_VIEW,
): { dependencies: Record<string, Dependency>; views: Record<string, V> } {
const dependencies: Record<string, Dependency> = {}
const out: Record<string, V> = {}
for (const [key, view] of Object.entries(views)) {
const component = view?.Component as TotpViewComponent | undefined
const path = typeof component === 'string' ? component : component?.path
if (!added(key) || !view || typeof view.path !== 'string' || !TOTP_VIEW_PATH.test(view.path) || !component || !path || path === wrapper) {
out[key] = view
continue
}
const own = typeof component === 'object' ? component : undefined
const original = own?.exportName ? { exportName: own.exportName, path } : path
dependencies[totpViewDependencyKey(component)] = { type: 'component', ...(own?.exportName ? { exportName: own.exportName } : {}), path }
out[key] = {
...view,
Component: {
path: wrapper,
serverProps: { ...own?.serverProps, ipalSafeBack: rule, ipalTotpClientProps: own?.clientProps, ipalTotpView: original },
},
}
}
return { dependencies, views: out }
}
/**
* Shallow copies of a config's views. Put these into the config BEFORE calling a 2FA factory and
* keep them as `before` for `changedViewKeys`: a view the factory registers is then never the
* same object as one that was there, also when the factory reuses its view objects between calls.
*/
export const copyViews = <V>(views: Record<string, V> | undefined): Record<string, V> =>
Object.fromEntries(Object.entries(views ?? {}).map(([key, view]) => [key, view && typeof view === 'object' ? { ...view } : view]))
/**
* Keys whose view object is not the one in `before` — what a plugin added or replaced.
* `added` for `wrapTotpViews`: `const before = copyViews(views)` → run the factory on a config
* holding `before` → `const keys = changedViewKeys(before, viewsAfter)` → `(key) => keys.has(key)`.
* A key alone says nothing: the 2FA package replaces a view that already stands under its keys.
*/
export const changedViewKeys = (before: Record<string, unknown>, after: Record<string, unknown>): Set<string> =>
new Set(Object.keys(after).filter((key) => after[key] !== before[key]))
+74 -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,65 @@ 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).
* A start that is missing or unreadable counts as "no deadline yet" (the account can still only
* set TOTP up): only server code writes the field, and the start-up step fills in a missing one.
*/
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> }) === true) {return 'exempt'}
const deadline = twoFactorSetupDeadline({ payload, user })
return deadline && deadline.getTime() < now ? 'closed' : 'open'
}
type MaybeReq = { payload?: Pick<BasePayload, 'config'>; user?: unknown }
@@ -51,10 +104,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 +126,10 @@ 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
// Exactly `true`: a Promise or any other truthy answer must never let an account in.
return !guard.requireSetup || guard.exempt?.({ user: user as Record<string, unknown> }) === true
}
const GUARDED = Symbol.for('ipal.secondFactorGuard')
@@ -321,6 +378,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 +391,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)
+301
View File
@@ -0,0 +1,301 @@
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 = {
/** The notice for administrators on the dashboard (accounts without 2FA, how many are blocked). `false` = none. */
dashboardNotice?: false
/**
* Accounts that may work without TOTP on purpose — a service account that
* logs in with a password. Return **exactly `true`** to exempt, and return it
* at once: the function is called in access checks, which cannot wait. An
* `async` function stops the site at start; any other answer than `true`
* (a Promise, a string, an error thrown) exempts nobody and is logged.
* (An API key needs no exemption: it passes by itself.)
* `({ user }) => user.email === '[email protected]'`
*/
exempt?: (args: { user: Record<string, unknown> }) => boolean
/** The notice on the setup screen (until when; or that the time has passed). `false` = none. */
setupNotice?: false
/** The "Two-step verification" status and reset control on the account in the panel. `false` = none (the reset endpoint stays). */
statusField?: false
/**
* 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 }}
// A typo must not loosen the rule: '24', -1 or NaN used to mean "no limit".
const given = option?.windowHours
if (given !== undefined && given !== false && (typeof given !== 'number' || !Number.isFinite(given) || given < 0)) {
throw new Error(
`[ipal] twoFactor.requireSetup.windowHours must be a number of hours (0 or more) or false, got ${JSON.stringify(given) ?? String(given)}. ` +
'Use 72 (the default), another number, or false / 0 for no time limit.',
)
}
const hours = given === false ? 0 : (given ?? DEFAULT_SETUP_WINDOW_HOURS)
return {
...(option?.exempt !== undefined ? { exempt: strictExempt(option.exempt) } : {}),
requireSetup: true,
setupWindowMs: hours > 0 ? hours * 60 * 60 * 1000 : 0,
}
}
/** What was already said about a wrong `exempt` answer: each kind is logged once per process. */
const exemptComplaints = new Set<string>()
/**
* The project's `exempt`, made safe to call from an access check: only an answer of exactly
* `true` exempts. An async function is refused at start (its Promise would be truthy for every
* account — everyone let in on a password); any other answer, or an error, exempts nobody and
* is logged (once per kind of wrong answer).
*/
export function strictExempt(exempt: unknown): NonNullable<RequireSetupOptions['exempt']> {
if (typeof exempt !== 'function') {
throw new Error('[ipal] twoFactor.requireSetup.exempt must be a function: ({ user }) => boolean.')
}
if (exempt.constructor?.name === 'AsyncFunction') {
throw new Error(
'[ipal] twoFactor.requireSetup.exempt must not be async: it is called in access checks, which cannot wait, and a Promise ' +
'would count as "exempt" for every account. Return true or false at once (decide from the fields on `user`).',
)
}
const complain = (what: string) => {
const kind = what.replace(/\(.*\)$/, '')
if (exemptComplaints.has(kind)) {return}
exemptComplaints.add(kind)
console.error(`[ipal] twoFactor.requireSetup.exempt ${what}; it must return true or false at once. The account is NOT exempt.`)
}
return (args) => {
let answer: unknown
try {
answer = (exempt as (a: typeof args) => unknown)(args)
} catch (err) {
complain(`threw (${err instanceof Error ? err.message : String(err)})`)
return false
}
if (answer === true) {return true}
if (answer !== false && answer !== undefined && answer !== null) {
// a Promise that rejects later must not become an unhandled rejection
if (typeof (answer as { then?: unknown }).then === 'function') {void (answer as Promise<unknown>).then(undefined, () => undefined)}
complain(`returned ${typeof (answer as { then?: unknown }).then === 'function' ? 'a Promise' : `a ${typeof answer}`}`)
}
return false
}
}
/**
* The fields for the 2FA collection: the window start (data) and, unless `statusField: false`,
* its status / reset control (panel).
*
* ipalKit adds the data field **whenever 2FA is on**, also with `requireSetup: false` or
* `guard: false`: the collection's schema then does not depend on those switches — on Postgres /
* SQLite switching the mode off would otherwise drop the column with the next migration, and
* switching it on again would hand every account without TOTP a new window.
*/
export function buildSetupFields({ statusField = true }: { statusField?: boolean } = {}): Field[] {
const fields: Field[] = [
{
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' },
},
]
if (statusField) {
fields.push({
name: 'totpSetupStatus',
type: 'ui',
admin: {
components: { Field: '@intecion/ipal-kit/admin#TwoFactorStatusField' },
disableListColumn: true,
position: 'sidebar',
},
})
}
return fields
}
/**
* 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) {
// The whole chain: Drizzle's own message is "Failed query: …", and what the database said
// ("column … does not exist", "no such column") is in `cause`.
const reason = errorChain(err)
// On Postgres / SQLite without the migration the column is missing — and then it is not only this step
// that fails: every query on the collection selects the column, so EVERY login answers 500 until it exists.
// Only the missing column gets this message — a database that cannot be reached is another problem.
if (/column .+ does not exist|no such column|unknown column|has no column/i.test(reason)) {
payload.logger.error(
`[ipal] 2FA: the column for "${SETUP_FROM_FIELD}" is missing on "${collection}" (${reason}). NOBODY CAN LOG IN to the panel until the ` +
'migration that adds it has run — administrators with 2FA included. Run `pnpm payload migrate:create`, commit the migration, and ' +
'have it applied when the new container starts (`prodMigrations` in the database adapter, or `pnpm payload migrate && pnpm start`) — ' +
'not in a pre-deployment command, which runs in the old container (docs/deployment.md §4.3, docs/security.md "Setup required" → Data).',
)
} else {
payload.logger.warn(`[ipal] 2FA: could not start the setup window for existing accounts (${reason}).`)
}
return 0
}
}
/** The messages of an error and of everything in its `cause` chain, outermost first. */
export function errorChain(err: unknown): string {
const parts: string[] = []
const seen = new Set<unknown>()
for (let current: unknown = err; current !== undefined && current !== null && !seen.has(current) && parts.length < 6; current = (current as { cause?: unknown }).cause) {
seen.add(current)
const message = current instanceof Error || typeof (current as { message?: unknown }).message === 'string' ? String((current as { message: unknown }).message) : typeof current === 'string' ? current : ''
if (message && !parts.includes(message)) {parts.push(message)}
if (typeof current !== 'object') {break}
}
return parts.join(' — ') || String(err)
}
export type TwoFactorResetOptions = {
/**
* Who may reset another account's TOTP. Default: a staff admin whose session has **entered its
* TOTP code** (`_strategy: 'totp'`) — not an API key, and not an account `requireSetup.exempt`
* lets work on its password. With your own function the session must still not owe a second
* factor (`secondFactorPassed`), and the rest is yours: an API-key or exempt admin passes only
* if you return true for it (`req.user._strategy` tells them apart).
*/
access?: (args: { req: PayloadRequest }) => boolean | Promise<boolean>
}
/**
* POST /api/ipal/two-factor/reset `{ userId }` — clears that account's TOTP
* secret **and its sessions**. The account must log in and 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
* TOTP code.
*
* The sessions go because a reset is also what an administrator presses for an
* account that may be in someone else's hands: a session that had passed 2FA
* would otherwise be a password-less way to enrol a new authenticator
* (`/api/setup-totp` asks for no password). With `auth.useSessions: false`
* there is nothing to clear — tokens then live until they expire.
*/
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
? (await options.access({ req })) === true
: (req.user as { _strategy?: unknown })._strategy === 'totp' && 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 {
const useSessions = (req.payload.collections as Record<string, { config?: { auth?: { useSessions?: boolean } } }>)[collection]?.config?.auth?.useSessions !== false
const data = { [SETUP_FROM_FIELD]: new Date().toISOString(), totpSecret: null, ...(useSessions ? { sessions: [] } : {}) }
await req.payload.update({ id: userId, collection: collection as never, data: data 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 }
}
+136 -5
View File
@@ -32,7 +32,10 @@ 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'
import {
buildGuardStrategy,
ensurePayloadGuarded,
@@ -43,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'
@@ -54,6 +58,8 @@ import { buildStatsCollection, buildStatsEndpoint } from './modules/stats/index.
/** The admin provider @clocklimited/payload-2fa registers; ipal-kit swaps it (twoFactor.provider). */
const TOTP_PACKAGE_PROVIDER = '@clocklimited/payload-2fa/rsc#TOTPProvider'
/** ipal-kit's own redirect provider (twoFactor.provider default). */
const TOTP_REDIRECT_PROVIDER = '@intecion/ipal-kit/admin#TotpRedirectProvider'
/**
* IPAL (Intecion Payload Advanced Library) plugin for Payload CMS 3.
@@ -91,7 +97,7 @@ export const ipalKit = (options: IpalOptions): Plugin => {
if (options.enabled === false) {
return {
...config,
admin: { ...config.admin, components: incomingConfig.admin?.components },
admin: { ...config.admin, components: incomingConfig.admin?.components, dependencies: incomingConfig.admin?.dependencies },
endpoints: incomingConfig.endpoints,
onInit: incomingConfig.onInit,
}
@@ -170,6 +176,8 @@ export const ipalKit = (options: IpalOptions): Plugin => {
let secondFactorGuard = false
/** The 2FA collection, when 2FA is on. */
let twoFactorCollection: null | string = null
/** Set when the committed admin import map lacks the 2FA view wrapper (production). */
let staleImportMap: null | string = null
/** This config's entry in the staff registry until a Payload instance takes it over. */
const staffToken = {}
/**
@@ -183,6 +191,12 @@ 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
/** requireSetup.setupNotice / statusField (on unless switched off). */
let setupNotice = true
let statusField = false
if (options.twoFactor !== false) {
const tf = options.twoFactor
if (!tf?.issuer) {
@@ -229,6 +243,12 @@ export const ipalKit = (options: IpalOptions): Plugin => {
)
}
const endpointsBefore = new Set(config.endpoints ?? [])
// Copies, so that a view the 2FA factory hands back is told apart from one it left alone
// even when the factory returns the very same objects on every call.
const viewsBefore = copyViews(config.admin?.components?.views)
if (config.admin?.components?.views) {
config.admin = { ...config.admin, components: { ...config.admin.components, views: viewsBefore as never } }
}
const entityEndpointsBefore = new Map<string, Set<unknown>>(
[...(config.collections ?? []), ...(config.globals ?? [])].map((e) => [e.slug, new Set<unknown>(Array.isArray(e.endpoints) ? e.endpoints : [])]),
)
@@ -245,12 +265,25 @@ 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)
config.globals = guardNewEntityEndpoints(config.globals, entityEndpointsBefore, target, guards as never)
twoFactorCollection = target
// The window-start field is part of the 2FA collection whenever 2FA is on — the schema must
// not depend on requireSetup / guard (setupRequired.ts, buildSetupFields). The panel's status
// field joins it below, when the mode is on. Validates requireSetup at start either way.
if (tf.requireSetup !== false) {resolveRequireSetup(tf.requireSetup)}
// The views the 2FA package registered, by object: it REPLACES a view the project (or an
// earlier run of the package, or of ipalKit) already had under its keys, so a key that
// existed before is no sign that the view is the project's own. Taken here, before the
// texts step below re-creates those objects.
const viewsFromPackage = changedViewKeys(viewsBefore, { ...config.admin?.components?.views })
// The package wraps only what is in the config right now. ipal-kit's own
// globals and collections come later, so they get ipal-kit's guard at the
@@ -269,7 +302,36 @@ 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)
const setupParts = tf.requireSetup && typeof tf.requireSetup === 'object' ? tf.requireSetup : {} // null = the default, like undefined
config.custom = { ...config.custom, ipal: { ...config.custom?.ipal, twoFactor: { collection: target, ...setup } } }
if (setup.requireSetup) {
setupRequiredFor = target
setupWindowHours = setup.setupWindowMs / 3_600_000
setupNotice = setupParts.setupNotice !== false
statusField = setupParts.statusField !== false
// The stamp hook only while the mode is on: an account made while it is off gets its
// window when the mode is switched on (the start-up step), not a creation date long past.
config.collections = (config.collections ?? []).map((c) =>
c.slug === target ? { ...c, hooks: { ...c.hooks, beforeChange: [...(c.hooks?.beforeChange ?? []), stampSetupFrom] } } : c,
)
if (setupParts.dashboardNotice !== false) {
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)
@@ -280,6 +342,11 @@ export const ipalKit = (options: IpalOptions): Plugin => {
)
}
// The window start (data) whenever 2FA is on; the status / reset control when the mode is.
config.collections = (config.collections ?? []).map((c) =>
c.slug === target ? { ...c, fields: [...c.fields, ...buildSetupFields({ statusField })] } : c,
)
// The package's texts are long and informal: ipal-kit's (admin-ux.md) go over
// them, the project's own i18n.translations over both. The 2FA screens get a
// tab title instead of "Payload" (view meta is a plain string: the site's language).
@@ -315,7 +382,7 @@ export const ipalKit = (options: IpalOptions): Plugin => {
if (tf.provider !== false) {
const custom = tf.provider
const ours =
typeof custom === 'object' ? custom : { path: custom ?? '@intecion/ipal-kit/admin#TotpRedirectProvider' }
typeof custom === 'object' ? custom : { path: custom ?? TOTP_REDIRECT_PROVIDER }
const providers = config.admin?.components?.providers ?? []
config.admin = {
...config.admin,
@@ -325,7 +392,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 && setupNotice ? { requireSetup: true, setupWindowHours } : {}), ...ours.clientProps },
serverProps: { ...(typeof p === 'object' ? p.serverProps : {}), ...ours.serverProps },
}
: p,
@@ -333,6 +400,50 @@ export const ipalKit = (options: IpalOptions): Plugin => {
},
}
}
// The package's setup and verify screens send the browser to the `back` query
// value after a valid code, unchecked: a crafted link runs script in the panel
// or leaves the site (safeBack.ts). ipal-kit's view goes in front of them and
// hands the package's view a checked value. `safeBack: false` leaves them as
// the package registered them; a function replaces the rule.
if (tf.safeBack !== false) {
const wrapped = wrapTotpViews(
(config.admin?.components?.views ?? {}) as Record<string, { Component?: unknown; path?: string }>,
(key) => viewsFromPackage.has(key),
typeof tf.safeBack === 'function' ? tf.safeBack : undefined,
)
if (Object.keys(wrapped.dependencies).length) {
config.admin = {
...config.admin,
components: { ...config.admin?.components, views: wrapped.views as never },
// keeps the package's own views in the import map: the wrapper renders them from there
dependencies: { ...config.admin?.dependencies, ...wrapped.dependencies },
}
// A production build with the import map of the previous version shows an EMPTY 2FA
// screen (Payload renders nothing for a path the map lacks): say so, in the log at
// start and on the screen itself (importMapCheck.ts). Development regenerates the map.
// The check reads the file on disk, which need not be the map in the bundle — so it
// only ever ADDS a notice; the screen itself is rendered as usual.
if (tf.importMapCheck !== false && process.env.NODE_ENV === 'production') {
const stale = await missingImportMapEntries(config, [SAFE_TOTP_VIEW])
if (stale.missing.length) {
staleImportMap = `${stale.missing.join(', ')} was not found in ${stale.file}`
const providers = config.admin?.components?.providers ?? []
config.admin = {
...config.admin,
components: {
...config.admin?.components,
providers: providers.map((p) =>
p && typeof p === 'object' && p.path === TOTP_REDIRECT_PROVIDER // ipal-kit's own provider only
? { ...p, clientProps: { ...p.clientProps, staleImportMap: true } }
: p,
),
},
}
}
}
}
}
}
const agency = options.agency === undefined ? DEFAULT_AGENCY : options.agency
@@ -347,6 +458,7 @@ export const ipalKit = (options: IpalOptions): Plugin => {
const serverProps: Record<string, unknown> = {}
if (wl.settingsSlug) {serverProps.settingsSlug = wl.settingsSlug}
if (wl.nameField) {serverProps.nameField = wl.nameField}
if (wl.inlineImages === false) {serverProps.inlineImages = false}
const logoProps = { ...serverProps, ...(wl.logoField ? { imageField: wl.logoField } : {}) }
const iconProps = { ...serverProps, ...(wl.iconField ? { imageField: wl.iconField } : {}) }
@@ -419,6 +531,7 @@ export const ipalKit = (options: IpalOptions): Plugin => {
iconField: brandFields.iconField,
logoField: brandFields.logoField,
nameField: brandFields.nameField,
serveIcon: options.adminMeta?.serveIcon,
settingsSlug,
}),
]
@@ -700,6 +813,14 @@ export const ipalKit = (options: IpalOptions): Plugin => {
adoptConfig(payload)
// Payload's dev reload swaps `payload.config` and runs no onInit: adopt the new config at once.
watchPayloadConfig(payload, adoptConfig)
if (staleImportMap) {
payload.logger.error(
`[ipal] The admin import map may be out of date: ${staleImportMap}. If the 2FA setup and verify screens are ` +
'EMPTY (no code form), nobody can sign in to the panel: run `pnpm payload generate:importmap`, commit ' +
'importMap.js, rebuild and redeploy. If the screens work, the file on disk is not the map the build used — ' +
'set twoFactor.importMapCheck: false (docs/security.md "A stale import map").',
)
}
// Staff whose collection is not the 2FA collection log in without a second factor: say so.
if (twoFactorCollection) {
const uncovered = staffCollectionSlugs(payload).filter((slug) => slug !== twoFactorCollection)
@@ -710,6 +831,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 })}
+47 -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
@@ -23,6 +23,8 @@ import type { FormsOption } from './modules/forms/types.js'
import type { RevalidatePathFn } from './modules/hooks/buildRevalidateHook.js'
import type { I18nConfig } from './modules/i18n/types.js'
import type { PagesOption } from './modules/pages/types.js'
import type { SafeBackRule } from './modules/security/totp/safeBack.js'
import type { 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'
@@ -241,6 +243,15 @@ export type IpalOptions = {
* package version the check does not recognise; docs/security.md.
*/
guard?: false
/**
* Check, at start in production, that the committed admin import map has
* the entry `safeBack` needs (`@intecion/ipal-kit/admin#SafeTotpView`).
* Without it Payload renders the 2FA screens empty and nobody can sign in;
* with the check the server log says so at every start and the 2FA screens
* show a message instead of nothing. On by default; `false` skips the file
* read, the log line and the message.
*/
importMapCheck?: false
/** Name shown in the authenticator app (e.g. company/site name). */
issuer: string
/**
@@ -265,6 +276,33 @@ 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
* it, so a crafted link could run script in the panel (`javascript:`) or
* leave the site. On by default: ipal-kit's `SafeTotpView` goes in front of
* the package's views and passes on a value that stays on the site's origin,
* inside the admin route — anything else becomes the admin root
* (`safeAdminBack`). A function replaces the rule; `false` leaves the
* package's views as they are. Run generate:importmap. docs/security.md.
*/
safeBack?: false | SafeBackRule
/**
* Texts of the 2FA screens and user field. Default: ipal-kit's English and
* Polish (`TOTP_TEXTS`), merged over the package's; your own
@@ -307,6 +345,14 @@ export type IpalOptions = {
| boolean
/** Upload field for the small nav icon. Default 'favicon'. */
iconField?: string
/**
* On the 2FA screens the panel's logo and icon are fetched by the server
* the way an anonymous visitor gets them and put into the page as a
* `data:` image: the session there is refused every collection, `media`
* included, so the browser could not load them. `false` = never fetch;
* the browser tries the media URL and shows the site name when refused.
*/
inlineImages?: false
/** Upload field for the login/nav logo. Default 'logo'. */
logoField?: string
/** Field with the site name. Default 'siteName'. */
+116 -1
View File
@@ -51,6 +51,105 @@ afterEach(() => {
vi.unstubAllEnvs()
})
describe('importmap rule and the 2FA back-link check', () => {
const MAP = 'src/app/(payload)/admin/importMap.js'
const entries = (...names: string[]) => `export const importMap = { ${names.map((n) => `"${n}": X`).join(', ')} }`
const withPlugin = (admin: string) => ({ ...base(), ...installed('@clocklimited/payload-2fa', '3.0.0'), 'node_modules/@intecion/ipal-kit/dist/exports/admin.js': admin })
const messages = (report: DoctorReport) => report.findings.filter((f) => f.rule === 'importmap').map((f) => `${f.severity}: ${f.message}`)
test('expects SafeTotpView when the installed plugin has it; not with safeBack: false; not for an older plugin', async () => {
const map = entries('@clocklimited/payload-2fa/rsc#TOTPSetup', '@intecion/ipal-kit/admin#TotpRedirectProvider')
const admin = 'export { SafeTotpView } from "./x.js"; export { TotpRedirectProvider } from "./y.js"'
const lacking = await doctor(project({ ...withPlugin(admin), [MAP]: map, 'src/payload.config.ts': 'twoFactor: { plugin: payloadTotp }' }), ['importmap'])
expect(messages(lacking).join()).toContain('import map lacks @intecion/ipal-kit/admin#SafeTotpView')
const off = await doctor(project({ ...withPlugin(admin), [MAP]: map, 'src/payload.config.ts': 'twoFactor: { plugin: payloadTotp, safeBack: false }' }), ['importmap'])
expect(messages(off).join()).not.toContain('SafeTotpView')
const older = await doctor(project({ ...withPlugin('export { TotpRedirectProvider } from "./y.js"'), [MAP]: map, 'src/payload.config.ts': 'twoFactor: { plugin: payloadTotp }' }), ['importmap'])
expect(messages(older).join()).not.toContain('SafeTotpView')
})
describe("the 2FA package's own view in the config", () => {
const map = entries('@clocklimited/payload-2fa/rsc#TOTPSetup', '@intecion/ipal-kit/admin#TotpRedirectProvider', '@intecion/ipal-kit/admin#SafeTotpView')
const admin = 'export { SafeTotpView } from "./x.js"; export { TotpRedirectProvider } from "./y.js"'
const NOTE = /^warning: the config registers the 2FA package's own setup \/ verify view/
const notes = async (config: string) =>
messages(await doctor(project({ ...withPlugin(admin), [MAP]: map, 'src/payload.config.ts': `twoFactor: { plugin: payloadTotp }, ${config}` }), ['importmap'])).filter((m) => NOTE.test(m))
const RAW = '@clocklimited/payload-2fa/rsc#TOTPVerify'
test.each([
['a string component', `admin: { components: { views: { Mine: { Component: '${RAW}', path: '/my-verify' } } } }`],
['an object component', `admin: { components: { views: { Mine: { Component: { path: "${RAW}", serverProps: { a: 1 } }, path: '/my-verify' } } } }`],
['an object component over several lines', `views: { Mine: { Component: {\n clientProps,\n path: \`${RAW}\`,\n}, path: '/my-verify' } }`],
['the setup view', "views: { Mine: { Component: '@clocklimited/payload-2fa/rsc#TOTPSetup', path: '/my-setup' } }"],
])('warns for %s', async (_name, config) => {
expect(await notes(config)).toHaveLength(1)
})
test.each([
['no such view', ''],
// the fix the warning itself suggests
['the wrapper with the raw path as ipalTotpView, and the path in admin.dependencies',
`admin: { components: { views: { Mine: { Component: { path: '@intecion/ipal-kit/admin#SafeTotpView', serverProps: { ipalTotpView: '${RAW}' } }, path: '/my-verify' } } }, dependencies: { 'my-verify': { path: '${RAW}', type: 'component' } } }`],
['the wrapper with serverProps written first', `views: { Mine: { Component: { serverProps: { ipalTotpView: '${RAW}' }, path: '@intecion/ipal-kit/admin#SafeTotpView' }, path: '/my-verify' } }`],
['a dependencies entry alone', `admin: { dependencies: { keep: { type: 'component', path: '${RAW}' } } }`],
['a comment', `// Component: '${RAW}'`],
])('does not warn for %s', async (_name, config) => {
expect(await notes(config)).toEqual([])
})
})
})
describe('2FA setup required: what a project must have', () => {
const MAP = 'src/app/(payload)/admin/importMap.js'
const NEW = ['@intecion/ipal-kit/admin#TwoFactorStatusField', '@intecion/ipal-kit/admin#TwoFactorAlert']
const OLD = ['@clocklimited/payload-2fa/rsc#TOTPSetup', '@intecion/ipal-kit/admin#TotpRedirectProvider', '@intecion/ipal-kit/admin#SafeTotpView']
const entries = (names: string[]) => `export const importMap = { ${names.map((n) => `"${n}": X`).join(', ')} }`
const plugin = {
...base(),
...installed('@clocklimited/payload-2fa', '3.0.0'),
'node_modules/@intecion/ipal-kit/dist/exports/admin.js': 'export { SafeTotpView, TotpRedirectProvider, TwoFactorAlert, TwoFactorStatusField }',
'node_modules/@intecion/ipal-kit/dist/modules/security/totp/secondFactor.js': "export const SETUP_FROM_FIELD = 'totpSetupFrom'",
}
const lacks = async (config: string, map: string[]) =>
(await doctor(project({ ...plugin, [MAP]: entries(map), 'src/payload.config.ts': config }), ['importmap'])).findings.filter((f) => /import map lacks/.test(f.message)).map((f) => f.message).join()
test('the import map must hold the status field and the dashboard notice', async () => {
const missing = await lacks('twoFactor: { plugin: payloadTotp }', OLD)
for (const name of NEW) {expect(missing).toContain(name)}
const complete = await lacks('twoFactor: { plugin: payloadTotp }', [...OLD, ...NEW])
for (const name of NEW) {expect(complete).not.toContain(name)}
})
test.each([
['requireSetup: false', []],
['guard: false', []],
['requireSetup: { statusField: false }', [NEW[1]]],
['requireSetup: { dashboardNotice: false }', [NEW[0]]],
])('%s: only what is still on is expected', async (option, expected) => {
const missing = await lacks(`twoFactor: { plugin: payloadTotp, ${option} }`, OLD)
for (const name of NEW) {expect([name, missing.includes(name)]).toEqual([name, expected.includes(name)])}
})
const migration = async (files: Record<string, object | string>, config = 'twoFactor: { plugin: payloadTotp }') =>
(await doctor(project({ ...plugin, [MAP]: entries([...OLD, ...NEW]), 'src/payload.config.ts': config, ...files }), ['2fa'])).findings.filter((f) => /totp_setup_from/.test(f.message)).map((f) => f.severity)
test('Postgres / SQLite: a migration must add the 2FA column, or nobody can log in', async () => {
const pg = installed('@payloadcms/db-postgres', '3.94.1')
expect(await migration({ ...pg, 'src/migrations/20260101_init.ts': 'await db.execute(sql`CREATE TABLE "users" ("id" serial)`)' })).toEqual(['error'])
expect(await migration({ ...pg, 'src/migrations/20260101_init.ts': 'x', 'src/migrations/20261124_totp.ts': 'ALTER TABLE "users" ADD COLUMN "totp_setup_from" timestamp' })).toEqual([])
expect(await migration({ ...pg, 'migrations/20261124_totp.json': '{ "columns": { "totpSetupFrom": {} } }' })).toEqual([])
expect(await migration(pg)).toEqual(['warning']) // no migrations folder: the doctor cannot see how the schema gets there
expect(await migration({ ...installed('@payloadcms/db-sqlite', '3.94.1'), 'src/migrations/20260101_init.ts': 'x' })).toEqual(['error'])
})
test('MongoDB, 2FA off, or a plugin version without the column: nothing to report', async () => {
expect(await migration({ ...installed('@payloadcms/db-mongodb', '3.94.1'), 'src/migrations/20260101_init.ts': 'x' })).toEqual([])
expect(await migration({ ...installed('@payloadcms/db-postgres', '3.94.1'), 'src/migrations/20260101_init.ts': 'x' }, 'twoFactor: false')).toEqual([])
const older = { ...installed('@payloadcms/db-postgres', '3.94.1'), 'node_modules/@intecion/ipal-kit/dist/modules/security/totp/secondFactor.js': 'export {}', 'src/migrations/20260101_init.ts': 'x' }
expect(await migration(older)).toEqual([])
})
})
describe('helpers', () => {
test('parseEnvFile reads KEY=value, strips quotes, skips comments', () => {
expect(parseEnvFile('# c\nA=1\nexport B="two"\n C = \'3\'\nbad line')).toEqual({ A: '1', B: 'two', C: '3' })
@@ -334,7 +433,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()
+185
View File
@@ -0,0 +1,185 @@
import { afterEach, describe, expect, test, vi } from 'vitest'
import { AdminLogo } from '../src/modules/branding/adminGraphics.js'
import { buildAdminImageEndpoints } from '../src/modules/branding/adminImages.js'
import { fetchPublicImage, publicImageDataUri } from '../src/modules/branding/publicImage.js'
const png = Buffer.from('89504e470d0a1a0a', 'hex')
const respond = (body: BodyInit | null, init: ResponseInit) => vi.fn(async () => new Response(body, init))
afterEach(() => {
vi.unstubAllGlobals()
})
describe('the brand image for a session the browser cannot load it in', () => {
test('fetched without credentials; only an image of a sane size comes back', async () => {
const fetchMock = respond(png, { headers: { 'content-type': 'image/png' }, status: 200 })
vi.stubGlobal('fetch', fetchMock)
const image = await fetchPublicImage('/api/media/file/logo.png', 'https://example.com')
expect(image?.type).toBe('image/png')
const [url, init] = fetchMock.mock.calls[0] as unknown as [URL, RequestInit]
expect(String(url)).toBe('https://example.com/api/media/file/logo.png')
expect(init.credentials).toBe('omit')
expect(init.headers).toBeUndefined() // no cookie, no authorization
expect(await publicImageDataUri('/api/media/file/logo.png', 'https://example.com')).toMatch(/^data:image\/png;base64,/)
})
test.each([
['media is not public (403)', respond('no', { status: 403 })],
['not an image', respond('<html>', { headers: { 'content-type': 'text/html' }, status: 200 })],
['too large', respond(Buffer.alloc(600 * 1024), { headers: { 'content-type': 'image/png' }, status: 200 })],
])('%s → nothing', async (_, fetchMock) => {
vi.stubGlobal('fetch', fetchMock)
expect(await fetchPublicImage('/x.png', 'https://example.com')).toBeNull()
})
test('no origin for a relative address, or another scheme → nothing, and no request', async () => {
const fetchMock = respond(png, { headers: { 'content-type': 'image/png' }, status: 200 })
vi.stubGlobal('fetch', fetchMock)
expect(await fetchPublicImage('/x.png', null)).toBeNull()
expect(await fetchPublicImage('file:///etc/passwd', null)).toBeNull()
expect(fetchMock).not.toHaveBeenCalled()
})
test('the panel logo: a data address for a session that owes its code, the plain address otherwise', async () => {
vi.stubGlobal('fetch', respond(png, { headers: { 'content-type': 'image/png' }, status: 200 }))
const payload = {
config: { custom: { ipal: { twoFactor: { collection: 'users' } } }, serverURL: 'https://example.com' },
findGlobal: async () => ({ logo: { url: '/api/media/file/logo.png' }, siteName: 'Example' }),
}
const src = async (user: unknown) => ((await AdminLogo({ payload: payload as never, user: user as never })) as { props: { src?: string } }).props.src
expect(await src({ _strategy: 'local-jwt', collection: 'users', hasTotp: true })).toMatch(/^data:image\/png;base64,/)
expect(await src({ _strategy: 'totp', collection: 'users', hasTotp: true })).toBe('/api/media/file/logo.png')
expect(await src(null)).toBe('/api/media/file/logo.png') // the login screen: an anonymous visitor loads it as before
})
test('the tab icon endpoint serves the picture itself, so no session is sent to a file it is refused', async () => {
const fetchMock = respond(png, { headers: { 'content-type': 'image/png' }, status: 200 })
vi.stubGlobal('fetch', fetchMock)
const icon = buildAdminImageEndpoints({ agency: false, language: 'en' } as never).find((e) => e.path.endsWith('admin-icon'))!
const req = {
payload: { config: {}, findGlobal: async () => ({ favicon: { url: '/api/media/file/icon.png' }, siteName: 'Example' }) },
url: 'https://example.com/api/ipal/admin-icon',
user: { _strategy: 'local-jwt', collection: 'users', hasTotp: true },
}
const res = await icon.handler(req as never)
expect(res.status).toBe(200)
expect(res.headers.get('content-type')).toBe('image/png')
expect(res.headers.get('location')).toBeNull()
expect(String((fetchMock.mock.calls[0] as unknown as [URL])[0])).toBe('https://example.com/api/media/file/icon.png')
// not fetchable → the redirect, as before
vi.stubGlobal('fetch', respond('no', { status: 403 }))
expect((await icon.handler(req as never)).status).toBe(302)
})
})
// An uploaded SVG from the site's own origin can run script when opened directly. The upload routes send a sandbox
// policy for that; the icon endpoint serves the same bytes and must send the same headers.
describe('the tab icon endpoint and an SVG', () => {
const SVG = '<svg xmlns="http://www.w3.org/2000/svg"><script>document.title="XSS"</script></svg>'
const icon = (fields: Record<string, unknown> = {}) => buildAdminImageEndpoints({ agency: false, language: 'en' } as never, fields as never).find((e) => e.path.endsWith('admin-icon'))!
const req = {
payload: { config: {}, findGlobal: async () => ({ favicon: { url: '/api/media/file/icon.svg' }, siteName: 'Example' }) },
url: 'https://example.com/api/ipal/admin-icon',
user: null,
}
// A Next project's site-wide CSP rule overrides a route's own header, so the sandbox header alone protects
// nothing in a real site: the endpoint must not answer with an SVG at all.
test.each([
['an SVG', SVG, 'image/svg+xml'],
['an SVG that the media server calls a PNG', SVG, 'image/png'],
['an SVG with a byte-order mark and an XML header', `\ufeff<?xml version="1.0"?>${SVG}`, 'image/svg+xml'],
['HTML that claims to be an image', '<html><script>1</script></html>', 'image/gif'],
])('%s is never answered from here: a redirect to the media file instead', async (_name, body, type) => {
vi.stubGlobal('fetch', respond(body, { headers: { 'content-type': type }, status: 200 }))
const res = await icon().handler(req as never)
expect(res.status).toBe(302)
expect(res.headers.get('location')).toBe('https://example.com/api/media/file/icon.svg')
expect(res.headers.get('content-type') ?? '').not.toContain('svg')
expect(await res.text()).toBe('')
})
test.each([
['PNG', Buffer.from('89504e470d0a1a0a0000', 'hex'), 'image/png'],
['JPEG', Buffer.from('ffd8ffe000104a46', 'hex'), 'image/jpeg'],
['GIF', Buffer.from('GIF89a..'), 'image/gif'],
['WebP', Buffer.concat([Buffer.from('RIFF'), Buffer.alloc(4), Buffer.from('WEBPVP8 ')]), 'image/webp'],
['ICO', Buffer.from('000001000100', 'hex'), 'image/x-icon'],
['AVIF', Buffer.concat([Buffer.alloc(4), Buffer.from('ftypavif')]), 'image/avif'],
])('a %s is served, typed by its own bytes, with the sandbox policy and nosniff', async (_name, body, type) => {
// the media server's claim is ignored — here it even claims SVG
vi.stubGlobal('fetch', respond(body, { headers: { 'content-type': 'image/svg+xml' }, status: 200 }))
const res = await icon().handler(req as never)
expect(res.status).toBe(200)
expect(res.headers.get('content-type')).toBe(type)
expect(res.headers.get('content-security-policy')).toBe("default-src 'none'; img-src 'self' data:; style-src 'unsafe-inline'; sandbox")
expect(res.headers.get('x-content-type-options')).toBe('nosniff')
})
test('rasterImageType knows bitmaps only', async () => {
const { rasterImageType } = await import('../src/modules/branding/publicImage.js')
expect(rasterImageType(Buffer.from(SVG))).toBeNull()
expect(rasterImageType(Buffer.from(''))).toBeNull()
expect(rasterImageType(Buffer.from('%PDF-1.7'))).toBeNull()
expect(rasterImageType(png)).toBe('image/png')
})
test('buildUploadSecurityHeaders also covers the icon path (a second layer; the project lists it after the site-wide rule)', async () => {
const { buildUploadSecurityHeaders, UPLOAD_SECURITY_HEADERS } = await import('../src/modules/security/buildSecurityHeaders.js')
expect(buildUploadSecurityHeaders().map((r) => r.source)).toEqual(['/api/media/file/:path*', '/api/ipal/admin-icon'])
expect(buildUploadSecurityHeaders()[1].headers).toEqual([...UPLOAD_SECURITY_HEADERS])
expect(buildUploadSecurityHeaders({ adminIcon: '/cms/ipal/admin-icon', collections: ['media', 'files'] }).map((r) => r.source)).toEqual(['/api/media/file/:path*', '/api/files/file/:path*', '/cms/ipal/admin-icon'])
expect(buildUploadSecurityHeaders({ adminIcon: false }).map((r) => r.source)).toEqual(['/api/media/file/:path*'])
})
test('the headers are the ones of the upload routes', async () => {
const { buildUploadSecurityHeaders, UPLOAD_SECURITY_HEADERS } = await import('../src/modules/security/buildSecurityHeaders.js')
expect(buildUploadSecurityHeaders()[0].headers).toEqual([...UPLOAD_SECURITY_HEADERS])
expect(UPLOAD_SECURITY_HEADERS.find((h) => h.key === 'Content-Security-Policy')?.value).toContain('sandbox')
})
test('adminMeta.serveIcon: false → the redirect to the media file, no fetch', async () => {
const fetchMock = respond(png, { headers: { 'content-type': 'image/png' }, status: 200 })
vi.stubGlobal('fetch', fetchMock)
const res = await icon({ serveIcon: false }).handler(req as never)
expect(res.status).toBe(302)
expect(res.headers.get('location')).toBe('https://example.com/api/media/file/icon.svg')
expect(fetchMock).not.toHaveBeenCalled()
})
})
describe('an image that is too large is not read to the end', () => {
test('a declared length over the limit: the body is not read', async () => {
const cancel = vi.fn(async () => undefined)
const body = new ReadableStream<Uint8Array>({ cancel, pull: (c) => c.enqueue(new Uint8Array(1024)) })
vi.stubGlobal('fetch', vi.fn(async () => new Response(body, { headers: { 'content-length': String(10 * 1024 * 1024), 'content-type': 'image/png' }, status: 200 })))
expect(await fetchPublicImage('/x.png', 'https://example.com')).toBeNull()
expect(cancel).toHaveBeenCalled()
})
test('no declared length: reading stops at the limit', async () => {
let sent = 0
const body = new ReadableStream<Uint8Array>({
pull: (c) => {
sent += 64 * 1024
c.enqueue(new Uint8Array(64 * 1024)) // endless
},
})
vi.stubGlobal('fetch', vi.fn(async () => new Response(body, { headers: { 'content-type': 'image/png' }, status: 200 })))
expect(await fetchPublicImage('/x.png', 'https://example.com')).toBeNull()
expect(sent).toBeLessThan(2 * 1024 * 1024) // stopped soon after 512 KB, not after "everything"
})
test('whiteLabel.inlineImages: false → the logo keeps its address, nothing is fetched', async () => {
const fetchMock = respond(png, { headers: { 'content-type': 'image/png' }, status: 200 })
vi.stubGlobal('fetch', fetchMock)
const payload = {
config: { custom: { ipal: { twoFactor: { collection: 'users' } } }, serverURL: 'https://example.com' },
findGlobal: async () => ({ logo: { url: '/api/media/file/logo.png' }, siteName: 'Example' }),
}
const out = (await AdminLogo({ inlineImages: false, payload: payload as never, user: { _strategy: 'local-jwt', collection: 'users', hasTotp: true } as never })) as { props: { src?: string } }
expect(out.props.src).toBe('/api/media/file/logo.png')
expect(fetchMock).not.toHaveBeenCalled()
})
})
+537
View File
@@ -0,0 +1,537 @@
import type { Config } from 'payload'
import { payloadTotp as payloadTotpBeta7 } from '@clocklimited/payload-2fa'
import { mkdir, mkdtemp, rm, writeFile } from 'node:fs/promises'
import os from 'node:os'
import path from 'node:path'
import { payloadTotp as payloadTotpBeta1 } from 'payload-2fa-beta1'
import React from 'react'
import { renderToStaticMarkup } from 'react-dom/server'
import { describe, expect, test, vi } from 'vitest'
import type { I18nConfig } from '../src/modules/i18n/types.js'
import { findImportMapFile, missingImportMapEntries } from '../src/modules/security/totp/importMapCheck.js'
import { changedViewKeys, safeAdminBack, wrapTotpViews } from '../src/modules/security/totp/safeBack.js'
import { SafeTotpView } from '../src/modules/security/totp/SafeTotpView.js'
import { ipalKit } from '../src/plugin.js'
import { withTotpParts } from './helpers.js'
const i18n: I18nConfig = { defaultLocale: 'en', locales: [{ code: 'en', label: 'English' }] }
const admin = { adminRoute: '/admin' }
describe('safeAdminBack', () => {
test.each([
['/admin', '/admin'],
['/admin/', '/admin/'],
['/admin/collections/pages?page=2&limit=10#row', '/admin/collections/pages?page=2&limit=10#row'],
['/admin/collections/pages/../media', '/admin/collections/media'],
])('keeps a path inside the panel: %s', (back, expected) => {
expect(safeAdminBack(back, admin)).toBe(expected)
})
test.each([
['javascript:alert(document.domain)'],
['JaVaScRiPt:alert(1)'],
[' javascript:alert(1)'],
['\tjavascript:alert(1)'],
['java\nscript:alert(1)'],
['data:text/html,<script>alert(1)</script>'],
['vbscript:msgbox(1)'],
['blob:http://ipal-safe-back.invalid/1'],
['https://evil.example/admin'],
['http://evil.example/admin'],
['//evil.example/admin'],
['/\\evil.example/admin'],
['\\\\evil.example/admin'],
['\\/evil.example/admin'],
['https:evil.example/admin'],
['https:/evil.example/admin'],
['http://[email protected]/admin'],
['http://user:[email protected]/admin'],
['http://ipal-safe-back.invalid/admin'], // the placeholder is not the site: absolute values need `origin`
['http://ipal-safe-back.invalid:8080/admin'],
['/'],
['/login'],
['/administrator'],
['/admin/../api/users'],
['/admin/%2e%2e/api/users'],
['/api/users'],
['collections/pages'], // relative to nothing: resolves outside the panel
[''],
[undefined],
])('falls back to the admin root: %s', (back) => {
expect(safeAdminBack(back, admin)).toBe('/admin')
})
test('never returns an absolute URL or a value a browser reads as another host', () => {
for (const back of ['//evil.example', '/\\evil.example', '/admin//evil.example', 'https://evil.example/admin', '/admin/x']) {
const out = safeAdminBack(back, admin)
expect(out.startsWith('/')).toBe(true)
expect(out.startsWith('//')).toBe(false)
expect(new URL(out, 'https://site.example').origin).toBe('https://site.example')
}
})
test('a custom admin route', () => {
const panel = { adminRoute: '/panel' }
expect(safeAdminBack('/panel/collections/pages', panel)).toBe('/panel/collections/pages')
expect(safeAdminBack('/admin/collections/pages', panel)).toBe('/panel')
expect(safeAdminBack('javascript:alert(1)', panel)).toBe('/panel')
expect(safeAdminBack('/panel-other', panel)).toBe('/panel')
expect(safeAdminBack(undefined, { adminRoute: '/cms/panel/' })).toBe('/cms/panel')
expect(safeAdminBack('/cms/panel/x', { adminRoute: '/cms/panel/' })).toBe('/cms/panel/x')
})
test('an admin route of "/" keeps any path on the site, still nothing off it', () => {
const root = { adminRoute: '/' }
expect(safeAdminBack('/collections/pages', root)).toBe('/collections/pages')
expect(safeAdminBack('//evil.example/x', root)).toBe('/')
expect(safeAdminBack('javascript:alert(1)', root)).toBe('/')
})
test('with the site origin, an absolute URL on that origin is kept — as a path', () => {
const site = { adminRoute: '/admin', origin: 'https://site.example' }
expect(safeAdminBack('https://site.example/admin/collections/pages?x=1', site)).toBe('/admin/collections/pages?x=1')
expect(safeAdminBack('http://site.example/admin', site)).toBe('/admin') // other scheme = other origin
expect(safeAdminBack('https://site.example:8443/admin', site)).toBe('/admin')
expect(safeAdminBack('https://site.example.evil.example/admin', site)).toBe('/admin')
expect(safeAdminBack('https://[email protected]/admin/x', site)).toBe('/admin')
expect(safeAdminBack('/admin/x', site)).toBe('/admin/x')
expect(safeAdminBack('/admin/x', { adminRoute: '/admin', origin: 'not a url' })).toBe('/admin/x')
})
})
describe('wrapTotpViews', () => {
const views = {
Other: { Component: 'my#View', path: '/reports' },
SetupTOTP: { Component: { path: 'pkg/rsc#TOTPSetup', serverProps: { pluginOptions: { a: 1 } } }, exact: true, path: 'setup-totp' },
VerifyTOTPBackslash: { Component: 'pkg/rsc#TOTPVerify', path: '/verify-totp' },
}
test('wraps the views the package added, keeps their props, lists the originals as dependencies', () => {
const rule = () => '/x'
const out = wrapTotpViews(views, () => true, rule)
expect(out.views.Other).toBe(views.Other)
expect(out.views.SetupTOTP).toEqual({
Component: { path: '@intecion/ipal-kit/admin#SafeTotpView', serverProps: { ipalSafeBack: rule, ipalTotpView: 'pkg/rsc#TOTPSetup', pluginOptions: { a: 1 } } },
exact: true,
path: 'setup-totp',
})
expect((out.views.VerifyTOTPBackslash.Component as unknown as { serverProps: { ipalTotpView: string } }).serverProps.ipalTotpView).toBe('pkg/rsc#TOTPVerify')
expect(out.dependencies).toEqual({
'ipal-totp-view:pkg/rsc#TOTPSetup': { type: 'component', path: 'pkg/rsc#TOTPSetup' },
'ipal-totp-view:pkg/rsc#TOTPVerify': { type: 'component', path: 'pkg/rsc#TOTPVerify' },
})
})
test('keeps exportName and clientProps of the original registration', () => {
const out = wrapTotpViews({ V: { Component: { clientProps: { tone: 'dark' }, exportName: 'Verify', path: 'mine/views' }, path: '/verify-totp' } }, () => true, undefined)
expect(out.views.V.Component).toEqual({
path: '@intecion/ipal-kit/admin#SafeTotpView',
serverProps: { ipalSafeBack: undefined, ipalTotpClientProps: { tone: 'dark' }, ipalTotpView: { exportName: 'Verify', path: 'mine/views' } },
})
expect(out.dependencies).toEqual({ 'ipal-totp-view:mine/views#Verify': { type: 'component', exportName: 'Verify', path: 'mine/views' } })
})
test('leaves alone what the project registered itself, and is safe to run twice', () => {
expect(wrapTotpViews(views, () => false, undefined)).toEqual({ dependencies: {}, views })
const once = wrapTotpViews(views, () => true, undefined)
const twice = wrapTotpViews(once.views, () => true, undefined)
expect(twice.views).toEqual(once.views)
expect(twice.dependencies).toEqual({})
})
})
describe.each([
['3.0.0-beta.7', payloadTotpBeta7],
['3.0.0-beta.1', payloadTotpBeta1 as unknown as typeof payloadTotpBeta7],
])('ipalKit with the real 2FA package %s', (_version, payloadTotp) => {
const build = (twoFactor: false | Record<string, unknown>, extra: Partial<Config> = {}, options: Record<string, unknown> = {}) =>
ipalKit({
access: { authCollection: 'users' },
i18n,
twoFactor: twoFactor === false ? false : ({ issuer: 'Example', plugin: payloadTotp, ...twoFactor } as never),
...options,
})({ collections: [], secret: 'x', ...extra } as unknown as Config)
/** Keys of views that still point straight at the 2FA package: unguarded. */
const raw = (config: Config) =>
Object.entries(config.admin?.components?.views ?? {})
.filter(([, view]) => {
const c = (view as { Component?: { path?: string } | string }).Component
return (typeof c === 'string' ? c : (c?.path ?? '')).includes('payload-2fa')
})
.map(([key]) => key)
// The package replaces a view that already stands under one of its keys: such a key is not "the project's own".
test('a view the project had under a package key is replaced by the package, and guarded', async () => {
const config = await build({}, { admin: { components: { views: { SetupTOTPBackslash: { Component: 'mine#S', path: '/setup-totp' }, VerifyTOTP: { Component: 'mine#V', path: '/verify-totp' } } } } } as never)
expect(raw(config)).toEqual([])
expect(component(config, 'VerifyTOTP')?.path).toBe('@intecion/ipal-kit/admin#SafeTotpView')
expect(component(config, 'SetupTOTPBackslash')?.path).toBe('@intecion/ipal-kit/admin#SafeTotpView')
})
test('the package registered by the project too, before ipalKit: still guarded', async () => {
const first = payloadTotp({ collection: 'users', totp: { issuer: 'E' } } as never)({ collections: [{ slug: 'users', auth: true, fields: [] }], secret: 'x' } as never)
expect(raw(first).length).toBe(4)
expect(raw(await build({}, first as never))).toEqual([])
})
test('ipalKit run over its own output (a config reused): still guarded', async () => {
const once = await build({})
const twice = await build({}, { admin: once.admin } as never)
expect(raw(twice)).toEqual([])
expect(component(twice, 'VerifyTOTP')?.serverProps?.ipalTotpView).toBe('@clocklimited/payload-2fa/rsc#TOTPVerify')
})
test('the same incoming config object built twice', async () => {
const incoming = { admin: { components: { views: {} } }, collections: [], secret: 'x' } as unknown as Config
const plugin = () => ipalKit({ access: { authCollection: 'users' }, i18n, twoFactor: { issuer: 'E', plugin: payloadTotp } as never })(incoming)
expect(raw(await plugin())).toEqual([])
expect(raw(await plugin())).toEqual([])
})
test('safeBack: true, null or undefined is on; only false is off', async () => {
for (const value of [true, null, undefined]) {expect(raw(await build({ safeBack: value }))).toEqual([])}
expect(raw(await build({ safeBack: false })).length).toBe(4)
})
test('enabled: false leaves no views and no import-map dependencies behind', async () => {
const config = await build({}, { admin: { dependencies: { mine: { type: 'component', path: 'mine#Thing' } } }, collections: [{ slug: 'users', auth: true, fields: [] }] } as never, { enabled: false })
expect(JSON.stringify(config.admin?.components ?? {})).not.toMatch(/SafeTotp|payload-2fa/)
expect(config.admin?.dependencies).toEqual({ mine: { type: 'component', path: 'mine#Thing' } })
const bare = await build({}, { collections: [{ slug: 'users', auth: true, fields: [] }] } as never, { enabled: false })
expect(bare.admin?.dependencies).toBeUndefined()
})
const component = (config: Config, key: string) =>
(config.admin?.components?.views as Record<string, { Component: { path: string; serverProps?: Record<string, unknown> } }> | undefined)?.[key]?.Component
test('by default all four 2FA views go through SafeTotpView and the package views stay in the import map', async () => {
const config = await build({})
for (const key of ['SetupTOTP', 'SetupTOTPBackslash', 'VerifyTOTP', 'VerifyTOTPBackslash']) {
const c = component(config, key)
expect([key, c?.path]).toEqual([key, '@intecion/ipal-kit/admin#SafeTotpView'])
expect(c?.serverProps?.ipalTotpView).toBe(`@clocklimited/payload-2fa/rsc#TOTP${key.startsWith('Setup') ? 'Setup' : 'Verify'}`)
expect(c?.serverProps?.pluginOptions).toBeDefined() // the package's own props are kept
expect(c?.serverProps?.ipalSafeBack).toBeUndefined()
}
expect(config.admin?.dependencies).toEqual({
'ipal-totp-view:@clocklimited/payload-2fa/rsc#TOTPSetup': { type: 'component', path: '@clocklimited/payload-2fa/rsc#TOTPSetup' },
'ipal-totp-view:@clocklimited/payload-2fa/rsc#TOTPVerify': { type: 'component', path: '@clocklimited/payload-2fa/rsc#TOTPVerify' },
})
// the tab title ipal-kit gives the screens is still there
expect((config.admin?.components?.views as Record<string, { meta?: { title?: string } }>).VerifyTOTP.meta?.title).toBeTruthy()
})
test('safeBack: false leaves the package views as registered', async () => {
const config = await build({ safeBack: false })
expect(component(config, 'VerifyTOTP')?.path).toBe('@clocklimited/payload-2fa/rsc#TOTPVerify')
expect(component(config, 'SetupTOTP')?.path).toBe('@clocklimited/payload-2fa/rsc#TOTPSetup')
expect(config.admin?.dependencies).toBeUndefined()
})
test('a function replaces the rule', async () => {
const rule = () => '/admin/account'
const config = await build({ safeBack: rule })
expect(component(config, 'VerifyTOTP')?.serverProps?.ipalSafeBack).toBe(rule)
})
test('still on with twoFactor.guard: false', async () => {
const config = await build({ guard: false })
expect(component(config, 'VerifyTOTP')?.path).toBe('@intecion/ipal-kit/admin#SafeTotpView')
})
test("the project's own dependencies and views are kept", async () => {
const config = await build({}, { admin: { components: { views: { Mine: { Component: 'mine#View', path: '/verify-totp-help' } } }, dependencies: { mine: { type: 'component', path: 'mine#Thing' } } } } as never)
expect((config.admin?.components?.views as Record<string, { Component: unknown }>).Mine.Component).toBe('mine#View')
expect(config.admin?.dependencies?.mine).toEqual({ type: 'component', path: 'mine#Thing' })
})
test('without 2FA nothing is registered', async () => {
const config = await build(false)
expect(JSON.stringify(config.admin ?? {})).not.toContain('SafeTotpView')
expect(JSON.stringify(config.admin ?? {})).not.toContain('ipal-totp-view')
})
})
describe('SafeTotpView', () => {
const PackageView = (props: { pluginOptions?: { issuer?: string }; searchParams?: Record<string, unknown> }) =>
React.createElement('p', { 'data-back': String(props.searchParams?.back), 'data-issuer': props.pluginOptions?.issuer, 'data-other': String(props.searchParams?.other) })
const render = (searchParams: Record<string, unknown>, more: Record<string, unknown> = {}, config: Record<string, unknown> = { routes: { admin: '/admin' }, serverURL: '' }) =>
renderToStaticMarkup(
React.createElement(SafeTotpView as never, {
importMap: { 'pkg/rsc#TOTPVerify': PackageView },
initPageResult: { req: { payload: { config } } },
ipalTotpView: 'pkg/rsc#TOTPVerify',
pluginOptions: { issuer: 'Example' },
searchParams,
...more,
}),
)
test.each([
['javascript:void(document.title=1)', '/admin'],
['http://127.0.0.1:3218/admin/login?landed=absolute', '/admin'],
['/\\127.0.0.1:3218/admin/login', '/admin'],
['//127.0.0.1:3218/admin', '/admin'],
['/admin/collections/pages?page=2', '/admin/collections/pages?page=2'],
])('the package view receives a checked back: %s', (back, expected) => {
const html = render({ back, other: 'kept' })
expect(html).toContain(`data-back="${expected.replace(/&/g, '&amp;')}"`)
expect(html).toContain('data-issuer="Example"') // the package's serverProps reach its view
expect(html).toContain('data-other="kept"')
})
test('no back, or a repeated one, gives the admin root (the package would otherwise go back in history)', () => {
expect(render({})).toContain('data-back="/admin"')
expect(render({ back: ['/admin/a', 'javascript:alert(1)'] })).toContain('data-back="/admin"')
})
test('a custom admin route and serverURL', () => {
const config = { routes: { admin: '/panel' }, serverURL: 'https://site.example' }
expect(render({ back: '/admin/x' }, {}, config)).toContain('data-back="/panel"')
expect(render({ back: 'https://site.example/panel/x' }, {}, config)).toContain('data-back="/panel/x"')
expect(render({ back: 'https://evil.example/panel/x' }, {}, config)).toContain('data-back="/panel"')
})
test("the project's rule is used instead", () => {
const html = render({ back: 'javascript:alert(1)' }, { ipalSafeBack: (back: string | undefined, ctx: { adminRoute: string }) => `${ctx.adminRoute}/account?was=${back ? 'set' : 'empty'}` })
expect(html).toContain('data-back="/admin/account?was=set"')
})
test('a missing import-map entry says what to run', () => {
expect(() => render({}, { importMap: {} })).toThrow(/generate:importmap/)
})
})
// "Setup required" (requireSetup), the back-link check (safeBack) and ipal-kit's own check (guard) are separate
// switches: each combination builds, and each part is on exactly when its own switch says so.
describe('requireSetup x safeBack x guard', () => {
const combos = [undefined, false].flatMap((requireSetup) => [undefined, false].flatMap((safeBack) => [undefined, false].map((guard) => ({ guard, requireSetup, safeBack }))))
test.each(combos)('requireSetup: $requireSetup, safeBack: $safeBack, guard: $guard', async (options) => {
const config = await ipalKit({ access: { authCollection: 'users' }, i18n, twoFactor: { issuer: 'E', plugin: payloadTotpBeta7, ...options } as never })({ collections: [], secret: 'x' } as unknown as Config)
const views = Object.values(config.admin?.components?.views ?? {}) as { Component: { path?: string } | string; path: string }[]
const totpViews = views.filter((v) => /(?:setup|verify)-totp$/.test(v.path))
expect(totpViews).toHaveLength(4)
// the back-link check follows safeBack alone
const wrapped = totpViews.filter((v) => typeof v.Component === 'object' && v.Component.path === '@intecion/ipal-kit/admin#SafeTotpView').length
expect(wrapped).toBe(options.safeBack === false ? 0 : 4)
// setup required needs ipal-kit's own check; with either off there is no status field, hook or notice
const setupOn = options.requireSetup !== false && options.guard !== false
const users = config.collections?.find((c) => c.slug === 'users')
// the data field whenever 2FA is on (the schema does not follow the switches); the panel's status field with the mode
expect(Boolean(users?.fields.some((f) => 'name' in f && f.name === 'totpSetupFrom'))).toBe(true)
expect(Boolean(users?.fields.some((f) => 'name' in f && f.name === 'totpSetupStatus'))).toBe(setupOn)
// the administrator's reset (a lost phone) comes with ipal-kit's own check, also when setup is not required
expect(Boolean(config.endpoints?.some((e) => e.path === '/ipal/two-factor/reset'))).toBe(options.guard !== false)
const provider = JSON.stringify(config.admin?.components?.providers ?? [])
expect(provider.includes('"requireSetup":true')).toBe(setupOn)
expect(provider).toContain('TotpRedirectProvider')
const guardConfig = (config.custom as { ipal?: { twoFactor?: { requireSetup?: boolean } } } | undefined)?.ipal?.twoFactor
expect(Boolean(guardConfig)).toBe(options.guard !== false)
if (guardConfig) {expect(Boolean(guardConfig.requireSetup)).toBe(setupOn)}
})
})
describe('requireSetup.setupNotice', () => {
const providers = async (requireSetup?: Record<string, unknown>) =>
JSON.stringify((await ipalKit({ access: { authCollection: 'users' }, i18n, twoFactor: { issuer: 'E', plugin: payloadTotpBeta7, requireSetup } as never })({ collections: [], secret: 'x' } as unknown as Config)).admin?.components?.providers ?? [])
test('on by default; false removes the notice, not the lock', async () => {
expect(await providers()).toContain('"requireSetup":true')
expect(await providers({ setupNotice: false })).not.toContain('"requireSetup":true')
const config = await ipalKit({ access: { authCollection: 'users' }, i18n, twoFactor: { issuer: 'E', plugin: payloadTotpBeta7, requireSetup: { setupNotice: false } } as never })({ collections: [], secret: 'x' } as unknown as Config)
expect((config.custom as { ipal: { twoFactor: { requireSetup: boolean } } }).ipal.twoFactor.requireSetup).toBe(true)
})
})
describe('a 2FA factory that hands back the same view objects on every call', () => {
const views = {
SetupTOTP: { Component: { path: 'pkg/rsc#TOTPSetup' }, path: 'setup-totp' },
VerifyTOTP: { Component: { path: 'pkg/rsc#TOTPVerify' }, path: 'verify-totp' },
}
const factory = (o: { collection: string }) => (c: Config) =>
withTotpParts({ ...c, admin: { ...c.admin, components: { ...c.admin?.components, views: { ...c.admin?.components?.views, ...views } } } } as Config, o.collection)
const build = (incoming: Partial<Config> = {}) =>
ipalKit({ access: { authCollection: 'users' }, i18n, twoFactor: { issuer: 'E', plugin: factory as never } })({ collections: [], secret: 'x', ...incoming } as unknown as Config)
const paths = (config: Config) => Object.values(config.admin?.components?.views ?? {}).map((v) => (v as { Component: { path: string } }).Component.path)
test('is guarded when registered once, twice, and over a config that already holds those objects', async () => {
expect(paths(await build())).toEqual(Array(2).fill('@intecion/ipal-kit/admin#SafeTotpView'))
const already = factory({ collection: 'users' })({ collections: [{ slug: 'users', auth: true, fields: [] }], secret: 'x' } as unknown as Config)
expect(paths(already)).toEqual(['pkg/rsc#TOTPSetup', 'pkg/rsc#TOTPVerify']) // raw, the very objects the factory returns again
expect(paths(await build(already))).toEqual(Array(2).fill('@intecion/ipal-kit/admin#SafeTotpView'))
expect(views.VerifyTOTP.Component.path).toBe('pkg/rsc#TOTPVerify') // the factory's own objects are not changed
})
})
describe('safeAdminBack with values that are not a string', () => {
test.each([[['/admin', 'javascript:1']], [{}], [null], [1], [{ toString: () => 'javascript:1' }]])('%s', (value) => {
expect(safeAdminBack(value as never, { adminRoute: '/admin' })).toBe('/admin')
})
})
describe('changedViewKeys', () => {
test('a key counts when its object is another one, whether or not the key existed', () => {
const kept = { path: '/a' }
expect([...changedViewKeys({ A: kept, B: { path: '/b' } }, { A: kept, B: { path: '/b' }, C: { path: '/c' } })].sort()).toEqual(['B', 'C'])
})
})
describe('SafeTotpView in front of a client component', () => {
// What a 'use client' export looks like on the server: a reference Payload must not hand server props to.
const ClientView = Object.assign(() => null, { $$typeof: Symbol.for('react.client.reference') })
const ServerView = () => null
const props = (view: unknown) => ({
clientConfig: { routes: { admin: '/admin' } },
i18n: { t: () => '' },
importMap: { 'mine/views#Verify': view },
initPageResult: { req: { payload: { config: { routes: { admin: '/admin' }, serverURL: '' } } } },
ipalTotpClientProps: { tone: 'dark' },
ipalTotpView: { exportName: 'Verify', path: 'mine/views' },
payload: { find: () => null },
pluginOptions: { adminManageAccess: () => true },
searchParams: { back: 'javascript:alert(1)', other: 'kept' },
viewType: 'verify',
})
const hasFunction = (value: unknown, seen = new Set<unknown>()): boolean => {
if (typeof value === 'function') {return true}
if (!value || typeof value !== 'object' || seen.has(value)) {return false}
seen.add(value)
return Object.values(value).some((v) => hasFunction(v, seen))
}
const call = SafeTotpView as unknown as (p: unknown) => React.ReactElement<Record<string, unknown>>
test('gets only props that can cross to the browser, with the checked back', () => {
const element = call(props(ClientView))
expect(element.type).toBe(ClientView)
expect(hasFunction(element.props)).toBe(false) // a function prop is what crashed the screen with a 500
expect(element.props).toEqual({
back: '/admin',
clientConfig: { routes: { admin: '/admin' } },
searchParams: { back: '/admin', other: 'kept' },
tone: 'dark',
viewType: 'verify',
})
})
test('a server component still gets the server props', () => {
const element = call(props(ServerView))
expect(element.type).toBe(ServerView)
expect(typeof (element.props.pluginOptions as { adminManageAccess: unknown }).adminManageAccess).toBe('function')
expect(element.props.searchParams).toEqual({ back: '/admin', other: 'kept' })
expect(element.props.tone).toBe('dark')
expect(element.props.ipalTotpView).toBeUndefined()
})
})
describe('the stale import-map check', () => {
const ENTRY = '@intecion/ipal-kit/admin#SafeTotpView'
const project = async (layout: string, content: string) => {
const root = await mkdtemp(path.join(os.tmpdir(), 'ipal-importmap-'))
await mkdir(path.join(root, layout), { recursive: true })
await writeFile(path.join(root, layout, 'importMap.js'), content)
return root
}
test('finds the file where Payload looks: app/, src/app/, a custom admin route, an explicit file', async () => {
const a = await project('app/(payload)/admin', '')
const b = await project('src/app/(payload)/admin', '')
const c = await project('src/app/(payload)/panel', '')
try {
expect(await findImportMapFile({}, a)).toBe(path.join(a, 'app/(payload)/admin/importMap.js'))
expect(await findImportMapFile({ admin: { importMap: { baseDir: b } } }, '/nowhere')).toBe(path.join(b, 'src/app/(payload)/admin/importMap.js'))
expect(await findImportMapFile({ routes: { admin: '/panel' } }, c)).toBe(path.join(c, 'src/app/(payload)/panel/importMap.js'))
expect(await findImportMapFile({ routes: { admin: '/panel' } }, a)).toBeNull()
const explicit = path.join(a, 'app/(payload)/admin/importMap.js')
expect(await findImportMapFile({ admin: { importMap: { importMapFile: explicit } } }, '/nowhere')).toBe(explicit)
expect(await findImportMapFile({ admin: { importMap: { importMapFile: '/nowhere/importMap.js' } } }, a)).toBeNull()
} finally {
for (const dir of [a, b, c]) {await rm(dir, { force: true, recursive: true })}
}
})
test('in production ipalKit marks the redirect provider when the map lacks the wrapper; not otherwise', async () => {
const stale = await project('src/app/(payload)/admin', 'export const importMap = { "@intecion/ipal-kit/admin#TotpRedirectProvider": X }')
const current = await project('src/app/(payload)/admin', `export const importMap = { "${ENTRY}": Y }`)
const flagged = async (baseDir: string, twoFactor: Record<string, unknown> = {}) => {
const config = await ipalKit({ access: { authCollection: 'users' }, i18n, twoFactor: { issuer: 'E', plugin: payloadTotpBeta7, ...twoFactor } as never })({
admin: { importMap: { baseDir } },
collections: [],
secret: 'x',
} as unknown as Config)
return JSON.stringify(config.admin?.components?.providers ?? []).includes('"staleImportMap":true')
}
const before = process.env.NODE_ENV
try {
vi.stubEnv('NODE_ENV', 'production')
expect(await flagged(stale)).toBe(true)
expect(await flagged(current)).toBe(false)
expect(await flagged('/nowhere')).toBe(false) // file not found: unknown, not reported
expect(await flagged(stale, { importMapCheck: false })).toBe(false)
expect(await flagged(stale, { safeBack: false })).toBe(false) // nothing wrapped, nothing needed
vi.stubEnv('NODE_ENV', 'development')
expect(await flagged(stale)).toBe(false) // Payload regenerates the map in development
} finally {
vi.unstubAllEnvs()
expect(process.env.NODE_ENV).toBe(before)
for (const dir of [stale, current]) {await rm(dir, { force: true, recursive: true })}
}
})
// The search reads text on disk: these maps work in the build and are still reported. That is why the result
// only ever adds a notice (test/totpRedirectProvider.test.ts) and the log line says "may be".
test('a map that re-exports, spreads or computes its keys is reported although it may be fine', async () => {
const maps = [
"export { importMap } from './generatedMap.js'",
"import { generated } from './generatedMap.js'\nexport const importMap = { ...generated }",
'export const importMap = { [`@intecion/ipal-kit/admin#${name}`]: X }',
'',
]
for (const content of maps) {
const root = await project('src/app/(payload)/admin', content)
try {
expect([content, (await missingImportMapEntries({}, [ENTRY], root)).missing]).toEqual([content, [ENTRY]])
} finally {
await rm(root, { force: true, recursive: true })
}
}
})
test('only ipal-kit\'s own redirect provider gets the flag, not a project\'s provider', async () => {
const stale = await project('src/app/(payload)/admin', 'export const importMap = {}')
const providers = async (provider?: unknown) => {
const config = await ipalKit({ access: { authCollection: 'users' }, i18n, twoFactor: { issuer: 'E', plugin: payloadTotpBeta7, provider } as never })({
admin: { importMap: { baseDir: stale } },
collections: [],
secret: 'x',
} as unknown as Config)
return JSON.stringify(config.admin?.components?.providers ?? [])
}
try {
vi.stubEnv('NODE_ENV', 'production')
expect(await providers()).toContain('"staleImportMap":true')
expect(await providers({ clientProps: { forceSetup: true }, path: '@/components/MyTotp#MyTotp' })).not.toContain('staleImportMap')
expect(await providers('@/components/MyTotp#MyTotp')).not.toContain('staleImportMap')
} finally {
vi.unstubAllEnvs()
await rm(stale, { force: true, recursive: true })
}
})
test('reports a missing entry, never an unknown state', async () => {
const stale = await project('src/app/(payload)/admin', 'export const importMap = { "@intecion/ipal-kit/admin#TotpRedirectProvider": X }')
const current = await project('src/app/(payload)/admin', `export const importMap = { "${ENTRY}": Y }`)
try {
expect((await missingImportMapEntries({}, [ENTRY], stale)).missing).toEqual([ENTRY])
expect((await missingImportMapEntries({}, [ENTRY], current)).missing).toEqual([])
expect(await missingImportMapEntries({}, [ENTRY], '/nowhere')).toEqual({ file: null, missing: [] })
} finally {
for (const dir of [stale, current]) {await rm(dir, { force: true, recursive: true })}
}
})
})
+285 -3
View File
@@ -4,13 +4,23 @@
*/
import type { Access, Config } from 'payload'
import { describe, expect, test } from 'vitest'
import { describe, expect, test, vi } from 'vitest'
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 { buildTwoFactorResetEndpoint, resolveRequireSetup, strictExempt } 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,219 @@ 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 })
// the data field stays whenever 2FA is on: the schema must not depend on the switch (SQL would drop the column)
const offUsers = off.collections!.find((c) => c.slug === 'users')!
expect(offUsers.fields.some((f) => 'name' in f && f.name === 'totpSetupFrom')).toBe(true)
expect(offUsers.fields.some((f) => 'name' in f && f.name === 'totpSetupStatus')).toBe(false)
expect(offUsers.hooks?.beforeChange?.length ?? 0).toBe(0) // no stamping while the mode is off
expect(JSON.stringify(off.admin?.components?.beforeDashboard ?? [])).not.toContain('TwoFactorAlert')
const guardOff = await ipalKit({ i18n, twoFactor: { guard: false, issuer: 'A', plugin: fakeTotp as never } })(base())
expect(guardOff.collections!.find((c) => c.slug === 'users')!.fields.some((f) => 'name' in f && f.name === 'totpSetupFrom')).toBe(true)
// each part of the mode has its own switch
const has = (c: Config) => ({
dashboard: JSON.stringify(c.admin?.components?.beforeDashboard ?? []).includes('TwoFactorAlert'),
setupNotice: JSON.stringify(c.admin?.components?.providers ?? []).includes('"requireSetup":true'),
status: c.collections!.find((x) => x.slug === 'users')!.fields.some((f) => 'name' in f && f.name === 'totpSetupStatus'),
})
// fakeTotp registers no provider, so the setup notice is checked with the real package in test/safeBack.test.ts
expect(has(on)).toMatchObject({ dashboard: true, status: true })
const noDash = await ipalKit({ i18n, twoFactor: { issuer: 'A', plugin: fakeTotp as never, requireSetup: { dashboardNotice: false } } })(base())
expect(has(noDash)).toMatchObject({ dashboard: false, status: true })
const noStatus = await ipalKit({ i18n, twoFactor: { issuer: 'A', plugin: fakeTotp as never, requireSetup: { statusField: false } } })(base())
expect(has(noStatus)).toMatchObject({ dashboard: true, status: false })
expect(guard(noStatus)).toMatchObject({ requireSetup: true }) // the lock itself is unchanged
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.each([['24'], [-1], [Number.NaN], [Number.POSITIVE_INFINITY], [true], [null]])('requireSetup.windowHours %s stops the start (a typo must not mean "no limit")', async (windowHours) => {
await expect(Promise.resolve().then(() => ipalKit({ i18n, twoFactor: { issuer: 'A', plugin: fakeTotp as never, requireSetup: { windowHours: windowHours as never } } })({ collections: [], secret: 'x' } as unknown as Config))).rejects.toThrow(/windowHours must be a number/)
// also when ipal-kit's own check is off: a wrong value is never silently accepted
await expect(Promise.resolve().then(() => ipalKit({ i18n, twoFactor: { guard: false, issuer: 'A', plugin: fakeTotp as never, requireSetup: { windowHours: windowHours as never } } })({ collections: [], secret: 'x' } as unknown as Config))).rejects.toThrow(/windowHours/)
expect(() => resolveRequireSetup({ windowHours: windowHours as never })).toThrow(/windowHours/)
})
test('requireSetup: null is the default, like leaving it out', async () => {
const config = await ipalKit({ i18n, twoFactor: { issuer: 'A', plugin: fakeTotp as never, requireSetup: null as never } })({ collections: [], secret: 'x' } as unknown as Config)
expect((config.custom as { ipal: { twoFactor: Record<string, unknown> } }).ipal.twoFactor).toMatchObject({ requireSetup: true, setupWindowMs: 72 * 3_600_000 })
expect(JSON.stringify(config.admin?.components?.beforeDashboard)).toContain('TwoFactorAlert')
expect(resolveRequireSetup(null as never)).toEqual({ requireSetup: true, setupWindowMs: 72 * 3_600_000 })
})
test('windowHours: a number, 0 or false still work', () => {
expect(resolveRequireSetup({ windowHours: 1.5 }).setupWindowMs).toBe(1.5 * 3_600_000)
expect(resolveRequireSetup({ windowHours: 0 }).setupWindowMs).toBe(0)
expect(resolveRequireSetup({ windowHours: false }).setupWindowMs).toBe(0)
})
// exempt lets an account in on its password: anything but a plain `true` must never do that.
describe('requireSetup.exempt', () => {
const user = { _strategy: 'local-jwt', collection: 'users', hasTotp: false, totpSetupFrom: new Date().toISOString() }
const payloadWith = (exempt: unknown) => ({ config: { custom: { ipal: { twoFactor: { collection: 'users', ...resolveRequireSetup({ exempt: exempt as never }) } } } } })
test('an async function stops the start', async () => {
expect(() => resolveRequireSetup({ exempt: (async () => false) as never })).toThrow(/must not be async/)
await expect(Promise.resolve().then(() => ipalKit({ i18n, twoFactor: { issuer: 'A', plugin: fakeTotp as never, requireSetup: { exempt: (async () => true) as never } } })({ collections: [], secret: 'x' } as unknown as Config))).rejects.toThrow(/must not be async/)
expect(() => resolveRequireSetup({ exempt: 'yes' as never })).toThrow(/must be a function/)
})
test.each([
['a Promise from a plain function', () => Promise.resolve(false)],
['a rejecting Promise', () => Promise.reject(new Error('x'))],
['a string', () => 'yes'],
['a number', () => 1],
['an object', () => ({})],
['an error', () => { throw new Error('boom') }],
['false', () => false],
['undefined', () => undefined],
])('%s exempts nobody', (_name, exempt) => {
const error = vi.spyOn(console, 'error').mockImplementation(() => undefined)
const payload = payloadWith(exempt)
expect(secondFactorPassed({ payload: payload as never, user })).toBe(false)
expect(twoFactorSetupState({ payload: payload as never, user })).toBe('open')
error.mockRestore()
})
test('only true exempts; a wrong answer is logged', () => {
const error = vi.spyOn(console, 'error').mockImplementation(() => undefined)
const yes = payloadWith(() => true)
expect(secondFactorPassed({ payload: yes as never, user })).toBe(true)
expect(twoFactorSetupState({ payload: yes as never, user })).toBe('exempt')
expect(error).not.toHaveBeenCalled()
const odd = strictExempt(() => Symbol('yes') as never)
expect(odd({ user })).toBe(false)
expect(odd({ user })).toBe(false)
expect(error).toHaveBeenCalledTimes(1) // each kind of wrong answer once, not on every request
expect(String(error.mock.calls[0]?.[0])).toMatch(/exempt returned a symbol.*NOT exempt/)
error.mockRestore()
})
test('a guard config built without resolveRequireSetup is strict too', () => {
const payload = { config: { custom: { ipal: { twoFactor: { collection: 'users', exempt: () => Promise.resolve(true), requireSetup: true } } } } }
expect(secondFactorPassed({ payload: payload as never, user })).toBe(false)
expect(twoFactorSetupState({ payload: payload as never, user })).toBe('open')
})
})
// Postgres / SQLite without the migration: the start-up step is the first to hit the missing column. It must not
// stop the site, and must say what the real consequence is (every login fails), not only "no window yet".
test('a missing column at start: no throw, and the log says nobody can log in', async () => {
const { backfillSetupFrom } = await import('../src/modules/security/totp/setupRequired.js')
const fake = (name: string, message: string) => {
const logger = { error: vi.fn(), warn: vi.fn() }
return { logger, payload: { count: async () => { throw new Error(message) }, db: { name }, logger } }
}
const pg = fake('postgres', 'column users.totp_setup_from does not exist')
expect(await backfillSetupFrom(pg.payload as never, 'users')).toBe(0)
expect(String(pg.logger.error.mock.calls[0]?.[0])).toMatch(/NOBODY CAN LOG IN.*migrate/s)
const sqlite = fake('sqlite', 'no such column: totp_setup_from')
await backfillSetupFrom(sqlite.payload as never, 'users')
expect(sqlite.logger.error).toHaveBeenCalledTimes(1)
// any other failure — also on a SQL adapter — is not "the column is missing"
for (const other of [fake('mongoose', 'connection lost'), fake('postgres', 'connect ECONNREFUSED 127.0.0.1:5432'), fake('sqlite', 'database is locked'), fake('postgres', 'relation "users" does not exist')]) {
await backfillSetupFrom(other.payload as never, 'users')
expect(other.logger.error).not.toHaveBeenCalled()
expect(other.logger.warn).toHaveBeenCalledTimes(1)
}
expect(String(pg.logger.error.mock.calls[0]?.[0])).toMatch(/prodMigrations.*not in a pre-deployment command/s)
// What the SQL adapters really throw: Drizzle's "Failed query: …" with the database's own words in `cause`.
const wrapped = (name: string, cause: unknown, message = 'Failed query: select count(*) from "users" where …') => {
const logger = { error: vi.fn(), warn: vi.fn() }
return { logger, payload: { count: async () => { throw Object.assign(new Error(message), { cause }) }, db: { name }, logger } }
}
for (const real of [
wrapped('postgres', Object.assign(new Error('column users.totp_setup_from does not exist'), { code: '42703' })),
wrapped('sqlite', new Error('SQLITE_ERROR: no such column: users.totp_setup_from')),
wrapped('sqlite', { message: 'no such column: totp_setup_from' }), // a plain object as the cause
wrapped('postgres', Object.assign(new Error('driver'), { cause: new Error('column "totp_setup_from" does not exist') })), // two levels down
]) {
await backfillSetupFrom(real.payload as never, 'users')
expect(real.logger.warn).not.toHaveBeenCalled()
expect(String(real.logger.error.mock.calls[0]?.[0])).toMatch(/NOBODY CAN LOG IN/)
expect(String(real.logger.error.mock.calls[0]?.[0])).toMatch(/totp_setup_from/) // the database's own words are in the line
}
for (const other of [
wrapped('postgres', Object.assign(new Error('connect ECONNREFUSED 127.0.0.1:5432'), { code: 'ECONNREFUSED' })),
wrapped('sqlite', new Error('SQLITE_BUSY: database is locked')),
wrapped('postgres', new Error('relation "users" does not exist')),
]) {
await backfillSetupFrom(other.payload as never, 'users')
expect(other.logger.error).not.toHaveBeenCalled()
expect(other.logger.warn).toHaveBeenCalledTimes(1)
}
// a cause that points at itself does not loop
const loop = new Error('Failed query') as { cause?: unknown } & Error
loop.cause = loop
const looping = { logger: { error: vi.fn(), warn: vi.fn() }, payload: {} as Record<string, unknown> }
looping.payload = { count: async () => { throw loop }, db: { name: 'postgres' }, logger: looping.logger }
await backfillSetupFrom(looping.payload as never, 'users')
expect(looping.logger.warn).toHaveBeenCalledTimes(1)
})
// The reset removes a second factor: by default only a session that entered its own TOTP code may do it.
describe('the reset endpoint: who may use it', () => {
const run = async (reqUser: Record<string, unknown>, options: Parameters<typeof buildTwoFactorResetEndpoint>[1] = {}, guardExtra: Record<string, unknown> = {}) => {
const update = vi.fn(async () => ({}))
const payload = {
collections: { users: { config: { auth: { useSessions: true } } } },
config: { collections: [{ slug: 'users', auth: true, fields: [{ name: 'roles', type: 'select' }] }], custom: { ipal: { staffCollections: ['users'], twoFactor: { collection: 'users', requireSetup: true, ...guardExtra } } } },
logger: { error: () => undefined, info: () => undefined },
update,
}
const req = { i18n: { t: (k: string) => k }, json: async () => ({ userId: '7' }), payload, user: reqUser }
const res = await buildTwoFactorResetEndpoint('users', options).handler(req as never)
return { status: res.status, update }
}
const admin = { id: 1, collection: 'users', hasTotp: true, roles: ['admin'] }
test('a session that entered its code: allowed; the account loses its secret AND its sessions', async () => {
const { status, update } = await run({ ...admin, _strategy: 'totp' })
expect(status).toBe(200)
const data = (update.mock.calls[0] as unknown as [{ data: Record<string, unknown>; id: string }])[0]
expect(data.id).toBe('7')
expect(data.data).toMatchObject({ sessions: [], totpSecret: null })
expect(typeof data.data.totpSetupFrom).toBe('string')
})
test('an exempt admin on its password, and an API-key admin: refused by default', async () => {
const exempt = { exempt: () => true }
expect((await run({ ...admin, _strategy: 'local-jwt', hasTotp: false }, {}, exempt)).status).toBe(403)
expect((await run({ ...admin, _strategy: 'api-key' })).status).toBe(403)
expect((await run({ ...admin, _strategy: 'local-jwt' })).status).toBe(403) // password only
})
test('resetAccess loosens it for those sessions — never for one that still owes its code', async () => {
const access = () => true
expect((await run({ ...admin, _strategy: 'api-key' }, { access })).status).toBe(200)
expect((await run({ ...admin, _strategy: 'local-jwt', hasTotp: false }, { access }, { exempt: () => true })).status).toBe(200)
expect((await run({ ...admin, _strategy: 'local-jwt' }, { access })).status).toBe(403)
expect((await run({ ...admin, _strategy: 'totp' }, { access: () => 'yes' as never })).status).toBe(403) // only true
expect((await run({ ...admin, _strategy: 'totp' }, { access: async () => true })).status).toBe(200)
})
})
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)
+209 -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,7 +467,216 @@ 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)
// the reset ends the account's sessions: the token from before is nobody's now, the account logs in again
expect(((await (await api('/users/me', sessions.newcomer)).json()) as { user: unknown }).user).toBeNull()
expect(((await (await setup(sessions.newcomer)).json().catch(() => ({}))) as { ok?: boolean }).ok).not.toBe(true)
sessions.newcomer = { headers: { authorization: `JWT ${(await login('users', '[email protected]')).token}` } }
})
// A reset is also what an administrator presses for an account that may be in someone else's hands. A session of
// that account which had passed 2FA must not survive it: /api/setup-totp asks for no password, so it could
// otherwise enrol the thief's own authenticator.
test('a reset ends every session of the account: a stolen verified session cannot enrol its own authenticator', async () => {
const THIEF_SECRET = 'KRSXG5CTMVRXEZLU'
const victim = await payload.create({ collection: 'users' as never, data: { email: '[email protected]', password: PASSWORD, roles: ['editor'], totpSecret: TOTP_SECRET } as never })
// the victim's fully verified session, as a thief would hold it (token + 2FA cookie)
const signIn = await login('users', '[email protected]')
const verify = await api('/verify-totp', { headers: { authorization: `JWT ${signIn.token}` } }, { body: JSON.stringify({ token: totp(TOTP_SECRET) }), method: 'POST' })
expect(((await verify.json()) as { ok: boolean }).ok).toBe(true)
const stolen: Session = { headers: { authorization: `JWT ${signIn.token}`, cookie: cookiesOf(verify).join('; ') } }
expect((await api('/pages', stolen)).status).toBe(200)
expect((await api('/ipal/two-factor/reset', sessions.verified, { body: JSON.stringify({ userId: victim.id }), method: 'POST' })).status).toBe(200)
expect(((await (await api('/users/me', stolen)).json()) as { user: unknown }).user).toBeNull()
const enrol = await api('/setup-totp', stolen, { body: JSON.stringify({ secret: THIEF_SECRET, token: totp(THIEF_SECRET) }), method: 'POST' })
expect(((await enrol.json().catch(() => ({}))) as { ok?: boolean }).ok).not.toBe(true)
const after = (await payload.findByID({ id: victim.id, collection: 'users' as never, showHiddenFields: true })) as unknown as { sessions?: unknown[]; totpSecret?: null | string }
expect(after.totpSecret ?? null).toBeNull()
expect(after.sessions ?? []).toEqual([])
expect((await api('/form-submissions', stolen)).status).toBe(403)
// the owner logs in again with the password and sets TOTP up; the old session stays dead
const owner: Session = { headers: { authorization: `JWT ${(await login('users', '[email protected]')).token}` } }
expect((await setup(owner)).status).toBe(200)
expect(((await (await api('/users/me', stolen)).json()) as { user: unknown }).user).toBeNull()
})
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.
// The owner's decision (2026-11-24): for accounts that exist before the upgrade, the 72 hours count from the first
// start after the upgrade. That moment is written on each account once: later starts, a second instance starting,
// and edits of the account leave it alone — otherwise every redeploy would hand out another 72 hours.
describe('2FA setup required: accounts from before the upgrade', () => {
const NEW_SECRET = 'MFRGGZDFMZTWQ2LK'
const HOUR = 3_600_000
const backfill = async () => (await import('../src/modules/security/totp/setupRequired.js')).backfillSetupFrom(payload, 'users')
const stampOf = async (id: number | string) => ((await payload.findByID({ id, collection: 'users' as never })) as unknown as { totpSetupFrom?: null | string }).totpSetupFrom
/** An account as the previous version left it: no TOTP, no window start. */
const legacy = async (email: string) => {
const doc = await payload.create({ collection: 'users' as never, data: { email, password: PASSWORD, roles: ['editor'] } as never })
await payload.db.updateOne({ id: doc.id, collection: 'users' as never, data: { totpSetupFrom: null } as never })
expect(await stampOf(doc.id)).toBeFalsy()
return doc.id
}
const sessionOf = async (email: string): Promise<Session> => ({ headers: { authorization: `JWT ${(await login('users', email)).token}` } })
const setup = (session: Session) => api('/setup-totp', session, { body: JSON.stringify({ secret: NEW_SECRET, token: totp(NEW_SECRET) }), method: 'POST' })
test('the first start stamps them with that moment; a restart does not move it', async () => {
const [a, b] = [await legacy('[email protected]'), await legacy('[email protected]')]
const startedAt = Date.now()
expect(await backfill()).toBe(2)
const first = [await stampOf(a), await stampOf(b)]
for (const stamp of first) {
expect(new Date(stamp!).getTime()).toBeGreaterThanOrEqual(startedAt - 1000)
expect(new Date(stamp!).getTime()).toBeLessThanOrEqual(Date.now() + 1000)
}
await new Promise((resolve) => setTimeout(resolve, 1100)) // a later start is at another time
expect(await backfill()).toBe(0)
expect(await backfill()).toBe(0)
expect([await stampOf(a), await stampOf(b)]).toEqual(first)
})
test('two instances starting at once: each account is stamped, and the stamp stays', async () => {
const id = await legacy('[email protected]')
const counts = await Promise.all([backfill(), backfill()])
expect(Math.max(...counts)).toBe(1)
const stamp = await stampOf(id)
expect(stamp).toBeTruthy()
await new Promise((resolve) => setTimeout(resolve, 1100))
expect(await backfill()).toBe(0)
expect(await stampOf(id)).toBe(stamp)
})
test('editing the account, or logging in, does not move the start', async () => {
const id = (await payload.find({ collection: 'users' as never, where: { email: { equals: '[email protected]' } } })).docs[0].id
const stamp = await stampOf(id)
await payload.update({ id, collection: 'users' as never, data: { password: `${PASSWORD}-2`, roles: ['admin'] } as never })
await payload.update({ id, collection: 'users' as never, data: { password: PASSWORD, roles: ['editor'] } as never })
await sessionOf('[email protected]')
expect(await stampOf(id)).toBe(stamp)
})
test('71 hours after the first start, restarts in between: setup still open; 73 hours after: blocked', async () => {
const [a, b] = await Promise.all(['[email protected]', '[email protected]'].map(async (email) => (await payload.find({ collection: 'users' as never, where: { email: { equals: email } } })).docs[0].id))
// as if the first start after the upgrade had been 71 h / 73 h ago
await payload.db.updateOne({ id: a, collection: 'users' as never, data: { totpSetupFrom: new Date(Date.now() - 71 * HOUR).toISOString() } as never })
await payload.db.updateOne({ id: b, collection: 'users' as never, data: { totpSetupFrom: new Date(Date.now() - 73 * HOUR).toISOString() } as never })
const before = [await stampOf(a), await stampOf(b)]
expect(await backfill()).toBe(0) // a restart today
expect([await stampOf(a), await stampOf(b)]).toEqual(before)
const late = await sessionOf('[email protected]')
expect((await setup(late)).status).toBe(403)
expect((await api('/globals/site-integrations', late)).status).toBe(403)
const inTime = await sessionOf('[email protected]')
expect((await api('/globals/site-integrations', inTime)).status).toBe(403) // nothing but setup
const done = await setup(inTime)
expect(done.status).toBe(200)
expect(((await done.json()) as { ok: boolean }).ok).toBe(true)
})
test('an account that has TOTP is not stamped; one created after the upgrade counts from its creation', async () => {
const withTotp = await payload.create({ collection: 'users' as never, data: { email: '[email protected]', password: PASSWORD, roles: ['editor'], totpSecret: TOTP_SECRET } as never })
await payload.db.updateOne({ id: withTotp.id, collection: 'users' as never, data: { totpSetupFrom: null } as never })
expect(await backfill()).toBe(0)
expect(await stampOf(withTotp.id)).toBeFalsy()
const created = Date.now()
const fresh = await payload.create({ collection: 'users' as never, data: { email: '[email protected]', password: PASSWORD, roles: ['editor'] } as never })
expect(Math.abs(new Date((await stampOf(fresh.id))!).getTime() - created)).toBeLessThan(60_000)
expect(await backfill()).toBe(0)
})
})
describe('dev hot reload', () => {
test('a freshly built config is guarded again, also what a later plugin added', async () => {
// What Payload's reload() does to the instance: a newly built and sanitized config, no onInit.
+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')
})
+2 -1
View File
@@ -232,7 +232,8 @@ describe('buildUploadSecurityHeaders', () => {
test('sandboxes files served from upload routes', async () => {
const { buildUploadSecurityHeaders } = await import('../src/modules/security/buildSecurityHeaders.js')
const rules = buildUploadSecurityHeaders({ collections: ['media', 'documents'] })
expect(rules.map((r) => r.source)).toEqual(['/api/media/file/:path*', '/api/documents/file/:path*'])
// the upload routes, and the panel icon endpoint (it answers with a file's bytes too)
expect(rules.map((r) => r.source)).toEqual(['/api/media/file/:path*', '/api/documents/file/:path*', '/api/ipal/admin-icon'])
const csp = rules[0].headers.find((h) => h.key === 'Content-Security-Policy')?.value ?? ''
expect(csp).toContain('sandbox')
expect(csp).toContain("default-src 'none'")
+72
View File
@@ -0,0 +1,72 @@
/**
* Postgres / SQLite without the migration that adds the 2FA column, against the REAL adapter: the start-up step
* must log the loud line (the database's own words are in the error's `cause`, not in its message), and every
* query on the collection fails — which is why the docs call the migration a required step of the same deploy.
* SQLite in memory by default; `IPAL_TEST_POSTGRES_URI` runs it on Postgres. Not for MongoDB (no columns).
*/
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 { backfillSetupFrom } from '../src/modules/security/totp/setupRequired.js'
import { ipalKit } from '../src/plugin.js'
import { buildTestConfig } from './helpers.js'
import { testDatabase } from './http/db.js'
vi.mock('server-only', () => ({}))
vi.mock('next/headers.js', async () => (await import('./http/server.js')).nextHeadersMock)
const sql = !process.env.IPAL_TEST_MONGO_URI
let payload: Payload
beforeAll(async () => {
if (!sql) {return}
const config = buildTestConfig({
admin: { user: 'users' },
collections: [{ slug: 'media', fields: [], upload: { staticDir: path.join(os.tmpdir(), 'ipal-test-media') } }],
db: testDatabase('setupcol'),
editor: lexicalEditor(),
plugins: [ipalKit({ access: { authCollection: 'users' }, i18n: { defaultLocale: 'en', locales: [{ code: 'en', label: 'English' }] }, twoFactor: { issuer: 'Example', plugin: payloadTotp as never } })],
secret: 'integration-test-secret-0123456789',
telemetry: false,
})
payload = await getPayload({ config })
}, 120_000)
afterAll(async () => {
await payload?.destroy?.()
})
test.skipIf(!sql)('without the column: the loud log line, and every query on the collection fails; with it: the window starts', async () => {
await payload.create({ collection: 'users' as never, data: { email: '[email protected]', password: 'a-long-test-password-1', roles: ['admin'] } as never })
const db = payload.db as unknown as { client?: { execute: (q: string) => Promise<unknown> }; name: string; pool?: { query: (q: string) => Promise<unknown> }; schemaName?: string }
const run = (statement: string) => (db.pool ? db.pool.query(statement) : db.client!.execute(statement))
const table = db.pool && db.schemaName ? `"${db.schemaName}"."users"` : '"users"'
// the schema as the previous version left it
await run(`ALTER TABLE ${table} DROP COLUMN "totp_setup_from"`)
const error = vi.spyOn(payload.logger, 'error').mockImplementation(() => undefined as never)
const warn = vi.spyOn(payload.logger, 'warn').mockImplementation(() => undefined as never)
expect(await backfillSetupFrom(payload, 'users')).toBe(0) // does not throw: the public site must keep running
expect(error).toHaveBeenCalledTimes(1)
expect(String(error.mock.calls[0]?.[0])).toMatch(/the column for "totpSetupFrom" is missing.*NOBODY CAN LOG IN.*prodMigrations/s)
expect(warn).not.toHaveBeenCalled()
// what "nobody can log in" means: the account cannot even be read
await expect(payload.find({ collection: 'users' as never })).rejects.toThrow()
await expect(payload.login({ collection: 'users' as never, data: { email: '[email protected]', password: 'a-long-test-password-1' } as never })).rejects.toThrow()
// the migration: the column is there → the start-up step gives the existing account its window, once
await run(`ALTER TABLE ${table} ADD COLUMN "totp_setup_from" ${db.pool ? 'timestamp(3) with time zone' : 'text'}`)
error.mockClear()
expect(await backfillSetupFrom(payload, 'users')).toBe(1)
expect(await backfillSetupFrom(payload, 'users')).toBe(0)
expect(error).not.toHaveBeenCalled()
expect((await payload.login({ collection: 'users' as never, data: { email: '[email protected]', password: 'a-long-test-password-1' } as never })).token).toBeTruthy()
error.mockRestore()
warn.mockRestore()
})
+117
View File
@@ -0,0 +1,117 @@
import React from 'react'
import { renderToStaticMarkup } from 'react-dom/server'
import { beforeEach, describe, expect, test, vi } from 'vitest'
/**
* The stale-import-map notice of TotpRedirectProvider. The flag behind it is a guess (a text search of the
* importMap.js on disk, not the map in the bundle), so the notice is shown NEXT TO the screen: a wrong guess
* must never take the code form away.
*/
const state = { language: 'en', pathname: '/admin/verify-totp', user: { _strategy: 'local-jwt', hasTotp: true } as null | Record<string, unknown> }
vi.mock('@payloadcms/ui', () => ({
useAuth: () => ({ user: state.user }),
useConfig: () => ({ config: { admin: { routes: {} }, routes: { admin: '/admin' } } }),
useTranslation: () => ({ i18n: { language: state.language }, t: (key: string, vars?: Record<string, unknown>) => `${key}${vars ? JSON.stringify(vars) : ''}` }),
}))
vi.mock('next/navigation.js', () => ({ usePathname: () => state.pathname, useRouter: () => ({ replace: () => undefined }) }))
const { TotpRedirectProvider } = await import('../src/modules/security/totp/TotpRedirectProvider.js')
const FORM = '<form id="code-form"><input/></form>'
const form = () => React.createElement('form', { id: 'code-form' }, React.createElement('input'))
const render = (props: Record<string, unknown> = {}, children: React.ReactNode = form()) =>
renderToStaticMarkup(React.createElement(TotpRedirectProvider, props, children))
beforeEach(() => {
Object.assign(state, { language: 'en', pathname: '/admin/verify-totp', user: { _strategy: 'local-jwt', hasTotp: true } })
})
describe('TotpRedirectProvider with staleImportMap', () => {
// Reviewer repro 1: the build is current, but the importMap.js on disk is an older one → the flag is wrong.
// Reviewer repro 2: the map file re-exports the generated map → the text search finds nothing → the flag is wrong.
// In both the screen works, and must stay on the page.
test('a false alarm: the working code form is still rendered, with the notice above it', () => {
const html = render({ staleImportMap: true })
expect(html).toContain(FORM)
expect(html).toContain('role="alert"')
expect(html).toContain('may not be available')
expect(html.indexOf('role="alert"')).toBeLessThan(html.indexOf('code-form'))
})
test('a really stale map: Payload renders nothing for the screen, the notice is what the user sees', () => {
const html = render({ staleImportMap: true }, null)
expect(html).toContain('role="alert"')
expect(html).toContain('pnpm payload generate:importmap')
})
test('the setup screen too; Polish for a Polish panel', () => {
Object.assign(state, { language: 'pl', pathname: '/admin/setup-totp', user: { _strategy: 'local-jwt', hasTotp: false } })
const html = render({ staleImportMap: true })
expect(html).toContain('Weryfikacja dwuetapowa może być niedostępna')
expect(html).toContain(FORM)
})
test('no notice without the flag, on other pages, or for a visitor', () => {
expect(render({})).toBe(FORM)
Object.assign(state, { pathname: '/admin/collections/pages', user: { _strategy: 'totp', hasTotp: true } })
expect(render({ staleImportMap: true })).toBe(FORM)
Object.assign(state, { pathname: '/admin/verify-totp', user: null })
expect(render({ staleImportMap: true })).toBe(FORM)
})
test('a pending redirect still renders nothing', () => {
Object.assign(state, { pathname: '/admin/collections/pages', user: { _strategy: 'local-jwt', hasTotp: true } })
expect(render({ staleImportMap: true })).toBe('')
})
})
// With "2FA setup required" the setup screen carries its own notice (until when, or that the time has passed).
// Neither notice, alone or together, may take the code form off the page.
describe('TotpRedirectProvider: the setup-required notice and the stale-map notice together', () => {
const HOUR = 3_600_000
const onSetup = (totpSetupFrom: string) => Object.assign(state, { language: 'en', pathname: '/admin/setup-totp', user: { _strategy: 'local-jwt', hasTotp: false, totpSetupFrom } })
test('inside the window: the deadline notice, and the form', () => {
onSetup(new Date(Date.now() - HOUR).toISOString())
const html = render({ requireSetup: true, setupWindowHours: 72 })
expect(html).toContain('id="ipal-two-factor-notice"')
expect(html).toContain('role="status"')
expect(html).toContain('twoFactorSetupDeadline')
expect(html).toContain(FORM)
})
test('after the window: the "time has passed" notice as an alert, and the screen still rendered', () => {
onSetup(new Date(Date.now() - 73 * HOUR).toISOString())
const html = render({ requireSetup: true, setupWindowHours: 72 })
expect(html).toContain('twoFactorSetupClosed')
expect(html).toContain('role="alert"')
expect(html).toContain(FORM)
})
test('both notices at once, inside and after the window: both shown, the form below them', () => {
for (const hours of [1, 73]) {
onSetup(new Date(Date.now() - hours * HOUR).toISOString())
const html = render({ requireSetup: true, setupWindowHours: 72, staleImportMap: true })
expect(html).toContain('id="ipal-two-factor-notice"')
expect(html).toContain('may not be available')
expect(html).toContain(FORM)
expect(html.indexOf('ipal-two-factor-notice')).toBeLessThan(html.indexOf('code-form'))
expect(html.indexOf('may not be available')).toBeLessThan(html.indexOf('code-form'))
}
})
test('no window (windowHours: false): the plain "setup required" notice', () => {
onSetup(new Date(Date.now() - 500 * HOUR).toISOString())
const html = render({ requireSetup: true, setupWindowHours: 0 })
expect(html).toContain('twoFactorSetupRequired')
expect(html).toContain(FORM)
})
test('requireSetup off: no setup notice; the verify screen never shows it', () => {
onSetup(new Date(Date.now() - 73 * HOUR).toISOString())
expect(render({ requireSetup: false, setupWindowHours: 72 })).toBe(FORM)
Object.assign(state, { pathname: '/admin/verify-totp', user: { _strategy: 'local-jwt', hasTotp: true } })
expect(render({ requireSetup: true, setupWindowHours: 72 })).toBe(FORM)
})
})