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]>
This commit is contained in:
Radosław Smoliński
2026-11-24 20:18:47 +01:00
co-authored by Claude Fable 5.2
parent 75a6f5209e
commit 01e3813723
20 changed files with 155 additions and 53 deletions
+9 -4
View File
@@ -24,8 +24,11 @@ once there are more than 20.
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** instead of a redirect, with the same sandbox headers
as the upload routes, so the tab icon also loads on the 2FA screens (`adminMeta.serveIcon: false` = the redirect).
- **`/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
@@ -46,7 +49,7 @@ once there are more than 20.
- 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 (no redirect to the media file), and the logo components give a session that still owes its code
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).
@@ -62,7 +65,9 @@ once there are more than 20.
- **Plan the upgrade 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.
- **Postgres / SQLite — required, in the same deploy: `pnpm payload migrate:create`, commit, and the migration
applied before the new version serves requests** (the 2FA collection gets the column `totp_setup_from`).
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`.
+1 -1
View File
@@ -39,7 +39,7 @@ through this procedure. Ask only when you are missing something you cannot get y
| `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, run `pnpm payload migrate` (the Coolify pre-deploy command) and redeploy; nothing is lost. `ipal-doctor` reports a project whose migrations lack `totp_setup_from` |
| 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 }) => …` |
+2 -2
View File
@@ -44,9 +44,9 @@ description: Complete map of everything @intecion/ipal-kit provides — every ip
| `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 run before the version serves, 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` | 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` — only `true` allows; `req.user._strategy` tells `'totp'`, `'api-key'`, `'local-jwt'` apart |
| `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 and the upload security headers (sandbox, nosniff) | `false` = a redirect to the media file |
| `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 | — |
@@ -596,11 +596,11 @@ Server only (`pnpm payload run`); never import it from client code, the Payload
| `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). |
| `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)`, `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. |
| `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. |
| `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` |
+6 -3
View File
@@ -392,8 +392,10 @@ with 2FA on:**
**`pnpm payload generate:importmap`** (new: `TwoFactorStatusField`, `TwoFactorAlert`; commit `importMap.js`).
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 make sure it is applied before the new version serves requests (the Coolify pre-deploy command
`pnpm payload migrate`). Without the column every login answers 500, administrators included; the log says
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
@@ -401,7 +403,8 @@ with 2FA on:**
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 — run it now.
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).
Scripts that used `POST /api/ipal/two-factor/reset` with an API key: refused by default now — pass
`twoFactor.resetAccess` if that is wanted. A reset ends the account's sessions (it logs in again).
+12 -6
View File
@@ -479,7 +479,9 @@ twoFactor: {
// 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
// resetAccess: ({ req }) => isAdmin(req.user, req.payload), // who may reset / reopen (default: a staff admin; the second factor is always required)
// 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),
}
```
@@ -487,8 +489,8 @@ twoFactor: {
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
make sure it is applied (`pnpm payload migrate`, the Coolify pre-deploy command) **before the new version
serves requests**. Without the column every query on the 2FA collection fails: **every login answers 500 —
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
@@ -525,8 +527,8 @@ twoFactor: {
**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` always answers with the image
instead of a redirect). Nothing is opened by this: when `media` is not publicly readable, or the file is larger
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
@@ -786,12 +788,16 @@ show the QR code. `back=null` or a page that keeps reloading means the import ma
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'`).
(`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`
+1 -1
View File
@@ -90,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` — answers with the site's favicon itself (fetched as an anonymous visitor would get it, at most 512 KB, sent with the upload security headers: sandbox policy and `nosniff`, so an SVG is shown but cannot run script; a redirect only when fetching is not possible), or draws the initials | `adminMeta: { icons: false }`; `adminMeta: { serveIcon: false }` = always the redirect to the media file; 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
@@ -39,7 +39,7 @@ through this procedure. Ask only when you are missing something you cannot get y
| `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, run `pnpm payload migrate` (the Coolify pre-deploy command) and redeploy; nothing is lost. `ipal-doctor` reports a project whose migrations lack `totp_setup_from` |
| 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 }) => …` |
@@ -44,9 +44,9 @@ description: Complete map of everything @intecion/ipal-kit provides — every ip
| `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 run before the version serves, 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` | 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` — only `true` allows; `req.user._strategy` tells `'totp'`, `'api-key'`, `'local-jwt'` apart |
| `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 and the upload security headers (sandbox, nosniff) | `false` = a redirect to the media file |
| `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 | — |
@@ -596,11 +596,11 @@ Server only (`pnpm payload run`); never import it from client code, the Payload
| `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). |
| `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)`, `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. |
| `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. |
| `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` |
@@ -392,8 +392,10 @@ with 2FA on:**
**`pnpm payload generate:importmap`** (new: `TwoFactorStatusField`, `TwoFactorAlert`; commit `importMap.js`).
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 make sure it is applied before the new version serves requests (the Coolify pre-deploy command
`pnpm payload migrate`). Without the column every login answers 500, administrators included; the log says
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
@@ -401,7 +403,8 @@ with 2FA on:**
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 — run it now.
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).
Scripts that used `POST /api/ipal/two-factor/reset` with an API key: refused by default now — pass
`twoFactor.resetAccess` if that is wanted. A reset ends the account's sessions (it logs in again).
+1 -1
View File
@@ -40,7 +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, siteOrigin } from './modules/branding/publicImage.js'
export { fetchPublicImage, PUBLIC_IMAGE_MAX_BYTES, publicImageDataUri, rasterImageType, siteOrigin } from './modules/branding/publicImage.js'
export {
ACCEPT_ALL_CONSENT,
buildConsentLogCollection,
+10 -6
View File
@@ -4,7 +4,7 @@ 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 } from './publicImage.js'
import { fetchPublicImage, rasterImageType } from './publicImage.js'
/**
* The panel's link-preview image (1200×630) and icon, drawn from SiteSettings:
@@ -112,14 +112,18 @@ export function buildAdminImageEndpoints(resolved: ResolvedAdminMeta, fields: Fi
// 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)
// An uploaded file from the site's own origin: the same headers as the upload routes
// (an SVG may be displayed, never run script — sandbox, no sniffing).
if (image) {
// 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': image.type, ...Object.fromEntries(UPLOAD_SECURITY_HEADERS.map((h) => [h.key, h.value])) },
headers: { 'Cache-Control': CACHE, 'Content-Type': type, ...Object.fromEntries(UPLOAD_SECURITY_HEADERS.map((h) => [h.key, h.value])) },
})
}
// Not fetchable from here (too large, or media is not public): let the browser try.
// 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()
+18
View File
@@ -37,6 +37,24 @@ export async function fetchPublicImage(url: null | string | undefined, base: nul
}
}
/**
* 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()
+16 -2
View File
@@ -157,11 +157,25 @@ 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
}[] {
return collections.map((slug) => ({ headers: [...UPLOAD_SECURITY_HEADERS], source: `/api/${slug}/file/:path*` }))
return [
...collections.map((slug) => ({ headers: [...UPLOAD_SECURITY_HEADERS], source: `/api/${slug}/file/:path*` })),
...(adminIcon ? [{ headers: [...UPLOAD_SECURITY_HEADERS], source: adminIcon }] : []),
]
}
/**
+7 -6
View File
@@ -195,14 +195,15 @@ export async function backfillSetupFrom(payload: BasePayload, collection: string
return totalDocs
} catch (err) {
const reason = err instanceof Error ? err.message : String(err)
// On Postgres / SQLite this is the missing column — 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.
const adapter = (payload.db as { name?: unknown } | undefined)?.name
if (/postgres|sqlite/i.test(typeof adapter === 'string' ? adapter : '') || /column|no such/i.test(reason)) {
// 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 ' +
'run it (`pnpm payload migrate`) before this version serves requests (docs/security.md "Setup required" → Data).',
'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}).`)
+1 -1
View File
@@ -305,7 +305,7 @@ export const ipalKit = (options: IpalOptions): Plugin => {
// "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 = typeof tf.requireSetup === 'object' ? 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
+40 -3
View File
@@ -84,18 +84,55 @@ describe('the tab icon endpoint and an SVG', () => {
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'],
['a PNG', png, 'image/png'],
])('%s is served with the sandbox policy and nosniff', async (_name, body, type) => {
['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])
@@ -103,7 +140,7 @@ describe('the tab icon endpoint and an SVG', () => {
})
test('adminMeta.serveIcon: false → the redirect to the media file, no fetch', async () => {
const fetchMock = respond(SVG, { headers: { 'content-type': 'image/svg+xml' }, status: 200 })
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)
+14 -4
View File
@@ -414,6 +414,13 @@ describe('ipalKit and the 2FA plugin', () => {
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)
@@ -483,10 +490,13 @@ describe('ipalKit and the 2FA plugin', () => {
const sqlite = fake('sqlite', 'no such column: totp_setup_from')
await backfillSetupFrom(sqlite.payload as never, 'users')
expect(sqlite.logger.error).toHaveBeenCalledTimes(1)
const mongo = fake('mongoose', 'connection lost')
await backfillSetupFrom(mongo.payload as never, 'users')
expect(mongo.logger.error).not.toHaveBeenCalled()
expect(mongo.logger.warn).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)
})
// The reset removes a second factor: by default only a session that entered its own TOTP code may do it.
+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'")