Security: staff checks only for staff collections; 2FA covers what the plugin adds

Staff check (userMeetsRole): the 'no roles field = every account passes'
rule applied to the account's own collection, so an account of a second
auth collection (customers) passed every staff check. It now applies only
to staff collections: the panel's login collection plus the new
access.staffCollections. The injected auth collection uses the new
adminOrSelfIn(slug), so an account of another collection with the same
numeric id is not 'self'.

2FA: @clocklimited/payload-2fa wraps the collections and globals present
when it runs; ipalKit's own globals and collections were added later and
stayed unwrapped, so a password without the TOTP code opened them over
REST and GraphQL. ipal-kit now has its own second-factor check
(secondFactorPassed / requireSecondFactor): applied to every collection
and global at the end of ipalKit, again in onInit for entities added by
plugins listed after it, and inside userMeetsRole and the endpoints that
take a project access function. It fails closed: an unrecognised user
shape is refused, and startup stops when the injected 2FA plugin lacks
the parts the check reads (twoFactor.guard: false opts out).

Tests through real HTTP requests (REST and GraphQL) against Payload's
route handlers, plus the reference smoke test. Docs, agent guide, skills
and the reference skills copy updated; changelog entry without a version.

Co-Authored-By: Claude Fable 5.2 <[email protected]>
This commit is contained in:
Radosław Smoliński
2026-11-24 00:31:55 +01:00
co-authored by Claude Fable 5.2
parent bc1045a5b7
commit 0c61ac231b
40 changed files with 1224 additions and 63 deletions
+49
View File
@@ -8,6 +8,55 @@ versions at once, go through every "Requires project changes" section in order,
version you have. A new release = a new section at the top; we remove the oldest ones only
once there are more than 20.
## Unreleased — security fixes (version to be set at release)
### Security
- **2FA now covers what the plugin adds.** The 2FA package wraps the collections and globals that exist when it
runs; the plugin's own globals and collections were added afterwards and were not wrapped. With 2FA on, an
account that had typed its **password but not the code** could read and change them over the API (REST and
GraphQL): Site settings, Site integrations (including the SMTP password and the Turnstile secret), Cookie banner,
Notifications, forms, form submissions, consent records, cookie review, stats, and the plugin's staff endpoints.
The project's own collections and the user accounts were protected. **Affects every site with 2FA on, in every
earlier version.** It needed a valid staff password. Now ipal-kit runs its own second-factor check on every
collection and global — whichever plugin added it and in whatever order — and on its endpoints
([security.md](./security.md) "What the second factor covers").
- **Accounts of a second auth collection are no longer staff.** `userMeetsRole` treated an account of any auth
collection without a `roles` field as staff. In a project with a visitor account collection (`customers`, a client
zone) such an account passed every staff check of the plugin, with the same reach as above; with open sign-up,
anyone could make one. In the injected auth collection, "only my own record" also matched an account of another
collection with the same numeric id (Postgres, SQLite). **Affects only projects with more than one auth
collection.** Now only accounts of the panel's login collection (plus `access.staffCollections`) can pass, and
the injected collection uses `adminOrSelfIn` ([access.md](./access.md#who-is-staff)).
### Added
- `access.staffCollections`: name further auth collections whose accounts are staff.
- `adminOrSelfIn(slug)`, `staffCollectionSlugs(payload)`, `secondFactorPassed(req)`, `requireSecondFactor(access)`
for the project's own access functions and endpoints.
- `twoFactor.guard: false`: ipal-kit's second-factor check off, the package's wrapper only (not recommended).
### Requires project changes
- **Every site: upgrade and redeploy.** No config change for a site with one auth collection and
`@clocklimited/payload-2fa` 3.0.0-beta.1 to beta.7. `pnpm ipal:skills` afterwards.
- **Because the earlier behaviour left no trace** (there is no audit log), decide per site with the owner:
- change the **SMTP password** and the **Turnstile secret** stored in Site integrations when a staff password
may have been known to someone else (a reused or shared password, a former employee, a phishing report) — or
simply do it once, it is cheap;
- look through **Site settings and Site integrations** for values nobody on the team set (analytics and tag
manager IDs, sender address, construction mode), and through each **form's Emails tab** for unknown
recipients or BCC addresses;
- form submissions and consent records could have been read; whether that needs a data-protection assessment
is the client's decision.
- **A site with a second auth collection:** treat the points above as required, not optional. Set
`admin: { user: '<staff collection>' }` in `buildConfig`, use `adminOrSelfIn('<slug>')` in your own auth
collections, and if the second collection really is staff, name it in `access.staffCollections`.
- **Own code that reads a plugin collection or global with `overrideAccess: false`** must pass a `user` from
`payload.auth({ headers })`; a user fetched by id and passed by hand is refused when it has TOTP set up. Own
endpoints: add `secondFactorPassed(req)` or `userMeetsRole(req, role)`.
- **Startup stops with `[ipal] twoFactor: the injected 2FA plugin did not add …`:** the installed 2FA package is
not one the check recognises. Install a supported version; `twoFactor.guard: false` only as a stop-gap.
- **Check after deploy:** security.md → "What the second factor covers" → Check (three `403`), then log in fully
and open Site integrations and a form submission in the panel.
## 1.16.3
### Changed
+48 -15
View File
@@ -13,6 +13,7 @@ ipalKit({
// defaultRole: 'user', // role of new accounts
// firstUserAdmin: true, // the account from "Create first user" → admin
// authAccess: { … }, // access of the injected auth collection (your keys win)
// staffCollections: ['partners'], // more auth collections whose accounts are staff
},
// globalOverrides: { … }, // access / admin / hooks / fields of the plugin's globals
})
@@ -24,6 +25,7 @@ ipalKit({
| `access.defaultRole` | `'user'` | role of a new account when an admin did not set one |
| `access.firstUserAdmin` | `true` | the account from the "Create first user" screen (`…/first-register` on an empty collection) gets `['admin']`, even when the form picked `user`; `false` = it gets what was submitted |
| `access.authAccess` | see the table below | `access` of the **injected** auth collection, merged over the default (your keys win) |
| `access.staffCollections` | `[]` | more auth collections whose accounts count as **staff**, besides the one the panel logs in with (`admin.user`); see "Who is staff" |
| `globalOverrides` | — | changes to the plugin's globals: an object merges `access` / `admin` key by key (your keys win) and appends `hooks` (yours run after the plugin's), other keys (label, fields, …) replace; a function `(global) => global` takes over the whole global |
The `roles` field (select hasMany, required, `saveToJWT`): readable without limits; only an admin
@@ -40,7 +42,7 @@ only checks that someone is logged in.
| Resource | Read | Write | How to change |
|---|---|---|---|
| auth collection **injected** by the plugin, with roles | admin: everyone; others: only themselves | `create` / `delete` / `unlock`: admin; `update`: admin or self | `access.authAccess`, or your own collection |
| auth collection **injected** by the plugin, with roles | admin: everyone; other accounts **of that collection**: only themselves (`adminOrSelfIn`) | `create` / `delete` / `unlock`: admin; `update`: admin or self | `access.authAccess`, or your own collection |
| Site settings, Cookie banner, Notifications | public | `editor+` | `globalOverrides` |
| Site integrations | admin | admin | `globalOverrides` |
| Forms | public (Emails tab only `editor+`) | `editor+` | `forms.formOverrides.access`, the Emails field in `formOverrides.fields` |
@@ -58,27 +60,54 @@ ipalKit({
```
The project's own auth collection keeps its own `access` — the plugin only adds the
`roles` field. Give it at least `update: adminOrSelf`, `delete: adminOnly`, `create: adminOnly`,
`roles` field. Give it at least `update: adminOrSelfIn('users')`, `delete: adminOnly`, `create: adminOnly`,
`unlock: adminOnly`: Payload's default lets any logged-in account change the email and password
of another account and unlock any account. A collection injected **without** `access` (no roles)
keeps Payload's default rules — without roles all accounts are equal.
> **Without `access` there is no `roles` field**, so `isAdmin` always returns `false`. The plugin's own
> staff features therefore check with `userMeetsRole(req, minimum)`: when the user's auth collection has no
> `roles` field, every logged-in account passes (as in Payload's default — without roles all accounts are
> equal). That keeps Site integrations, the settings globals, `/api/ipal/test-email`, stats, consent records
> and form submissions reachable. To narrow them without roles: `globalOverrides` for the globals,
> `forms.formSubmissionOverrides` for submissions, or add `access` to get roles.
## Who is staff
The plugin's own staff features — Site integrations, the settings globals, form submissions, consent records,
stats, the cookie scanner, `/api/ipal/test-email` — check with `userMeetsRole(req, minimum)`. It passes when:
1. the account holds at least the role `minimum`; or
2. the account belongs to a **staff collection** that has **no `roles` field**. Then every account of that
collection passes, as in Payload's default (without roles all accounts are equal).
**Staff collections** are the auth collection the admin panel logs in with (`admin.user`, by default the first
auth collection) and the ones named in `access.staffCollections`. An account of **any other auth collection** —
`customers`, `members`, a client zone — is a visitor to the plugin and never passes rule 2, with or without
the `access` option.
With 2FA on, an account that has TOTP set up and has not entered the code in this session passes neither rule
([security.md](./security.md) → 2FA).
- **Without `access`** there is no `roles` field, so `isAdmin` always returns `false` and rule 2 keeps the
staff features reachable: every account of the panel collection is admin to the plugin. To narrow that
without roles: `globalOverrides` for the globals, `forms.formSubmissionOverrides` for submissions, or add
`access` to get roles.
- **A second staff collection** (e.g. `partners` who edit content): name it in
`access.staffCollections`. Without a `roles` field every partner then passes every staff check, admin ones
included. To tell them apart, add the field: `fields: [buildRolesField('editor')]` in that collection.
- **A visitor collection that should reach one thing** (e.g. customers read their own form submissions):
do not make it staff. Write that one rule: `forms.formSubmissionOverrides.access.read`, `globalOverrides`,
`collectionOverrides` of the module.
> **Changed in the release after 1.16.3.** Before, rule 2 applied to the account's own collection, whatever it
> was: an account of a second auth collection without a `roles` field passed every staff check. A project
> with one auth collection sees no difference. A project that relied on a second collection being staff sets
> `access.staffCollections`.
## Predicates (front end / hooks / access)
```ts
import { isAdmin, isEditor, hasMinimumRole, userMeetsRole } from '@intecion/ipal-kit'
import { isAdmin, isEditor, hasMinimumRole, staffCollectionSlugs, userMeetsRole } from '@intecion/ipal-kit'
isAdmin(user) // admin?
isEditor(user) // editor or admin (hierarchy)
hasMinimumRole(user, 'editor') // at least editor
userMeetsRole(req, 'admin') // admin — or any logged-in user when the auth collection has no roles field
userMeetsRole(req, 'admin') // admin — or any account of a staff collection that has no roles field ("Who is staff")
staffCollectionSlugs(req.payload) // ['users', …]: admin.user + access.staffCollections
```
They take a loosely typed user (like `req.user`) and read `roles` defensively.
@@ -88,7 +117,7 @@ They take a loosely typed user (like `req.user`) and read `roles` defensively.
### Collection-level (return boolean | Where)
```ts
import { adminOnly, adminOrEditor, adminOrSelf, requireRole, authenticated } from '@intecion/ipal-kit'
import { adminOnly, adminOrEditor, adminOrSelf, adminOrSelfIn, requireRole, authenticated } from '@intecion/ipal-kit'
export const Articles = {
slug: 'articles',
@@ -101,8 +130,12 @@ export const Articles = {
// ...
}
// Users: everyone sees themselves, an admin sees everyone
access: { read: adminOrSelf }
// Users: everyone sees themselves, an admin sees everyone.
// adminOrSelfIn(slug): "self" = an account of THAT collection. Use it for an auth collection whenever
// the project has more than one: adminOrSelf only compares ids, and with numeric ids (Postgres, SQLite)
// customer no. 5 would match staff account no. 5.
access: { read: adminOrSelfIn('users') }
access: { read: adminOrSelf } // fine with a single auth collection
// any minimum threshold
access: { update: requireRole('editor') }
@@ -143,10 +176,10 @@ Types: `AccessOption`, `Role`, `GlobalOverride`, `GlobalOverrides`, `IpalGlobalS
- **Turn off:** leave out `access` — no `roles` field, the auth collection keeps Payload's rules
(or yours). `access.firstUserAdmin: false` stops giving admin to the first account.
- **Override:** `access.authAccess` (injected collection), your own auth collection (wins whole),
- **Override:** `access.staffCollections` (who is staff), `access.authAccess` (injected collection), your own auth collection (wins whole),
`globalOverrides` (globals), `forms.formOverrides` / `formSubmissionOverrides` (forms),
`defaultRole`. The role hierarchy (`ROLE_HIERARCHY`) is fixed.
- **Extend:** `requireRole` / `requireRoleField`, predicates, `buildRolesField`, `injectRoles`,
- **Extend:** `requireRole` / `requireRoleField`, `adminOrSelfIn`, predicates (`userMeetsRole`, `staffCollectionSlugs`), `buildRolesField`, `injectRoles`,
`applyGlobalOverrides` in your own collections and globals.
- **Check:** log in with a `user` account → `PATCH /api/globals/site-settings` = 403,
`DELETE /api/users/<admin id>` = 403; the account from "Create first user" has the `admin` role.
+17 -3
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); `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`; 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)`; `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 |
@@ -580,6 +580,19 @@ By default: `pages`, `media` + the plugin's globals (`site-settings`,
you need extra fields (then your own `Users.ts` with the slug from `access.authCollection`;
the plugin adds roles and 2FA to it).
**A second auth collection** (`customers`, `members`, a client zone) — only when the client requires accounts
for visitors. Then, all four:
1. `admin: { user: 'users' }` in `buildConfig` — Payload otherwise logs the panel in with the FIRST auth
collection in the list, and 2FA and the staff checks follow the panel collection.
2. Its accounts are visitors to the plugin: they pass none of its staff checks (`userMeetsRole`) — settings
globals, Site integrations, form submissions, consent records, stats, cookie scanner. Give them exactly
what they need with your own `access` rules; never add the collection to `access.staffCollections` to
"make something work". `access.staffCollections` is for a second collection of STAFF (access.md → "Who
is staff").
3. In every auth collection use `adminOrSelfIn('<its slug>')`, not `adminOrSelf`, for "only my own record".
4. Check: log in as such an account (`POST /api/customers/login`), then `GET /api/globals/site-integrations`
and `GET /api/form-submissions` with its token must answer `403`.
**NEVER:** a second `media`, `daneFirmy`/`settings`/
`navigation`/`footer` as collections (they are globals), FAQ/hero/features as collections
(they are blocks), a collection for a single thing (that is a page or a global).
@@ -1040,7 +1053,7 @@ project → **plugin gap**, not a copy.
| ISR after save, old slug → 308, images across languages | `buildRevalidateHook`, `trackSlugHistoryHook`, `buildCrossLocaleFieldSync` | hooks.md |
| ISR after a global is saved | plugin globals: `ipalKit({ revalidatePath })`; your own globals: `buildGlobalRevalidateHook({ revalidatePath })` | hooks.md |
| Change a plugin global (access, hooks, fields) | `ipalKit({ globalOverrides })` | access.md |
| Roles and access | `adminOnly`, `adminOrEditor`, `adminOrSelf`, `authenticated`, `requireRole`, `hasMinimumRole` (+ `…Field`); injected `users`: `access.authAccess`, first user = admin (`access.firstUserAdmin`) | access.md |
| Roles and access | `adminOnly`, `adminOrEditor`, `adminOrSelf`, `adminOrSelfIn(slug)` (several auth collections), `authenticated`, `requireRole`, `hasMinimumRole` (+ `…Field`); staff checks: `userMeetsRole(req, role)`, `staffCollectionSlugs(payload)`, `access.staffCollections`; second factor in your own code: `secondFactorPassed(req)`, `requireSecondFactor(access)`; injected `users`: `access.authAccess`, first user = admin (`access.firstUserAdmin`) | access.md, security.md |
| Data from globals | `getGlobal`, `getSiteSettings`, `getSiteIntegrations` | payload-helpers.md |
**Links and navigation**
@@ -1134,7 +1147,7 @@ add missing hosts with flags / `extra`; (3) change `mode` to `'enforce'` in both
| Plugin globals: write editor+ (Site integrations: admin) | — | `ipalKit({ globalOverrides: { <slug>: { access, admin, hooks } } })`; a function `(global) => global` takes over (`applyGlobalOverrides`) |
| Global saves revalidate the layout (with `ipalKit({ revalidatePath })`) | omit `revalidatePath`; once: `context: { disableRevalidate: true }` | `buildGlobalRevalidateHook` on your own globals |
| Form files (`forms.attachments`): off; when on — 10 MB, PDF/DOC/DOCX ticked, programs/macros/archives refused, no antivirus, Graph sends files of 3 MB and more through a draft it deletes | omit `attachments`; `forms.fields.file: false`; `mailAdapter({ graph: { largeAttachments: false } })` | `maxSizeMB` / `maxTotalMB` / `maxFiles` / `fileTypes` / `allowRisky` / `scan` / `strictPdf` / `notice` / `submit`; `buildFileBlock`; `formSubmissionOverrides.fields` for the file fields of a submission |
| Staff features without `access` (no roles field): every logged-in account passes (`userMeetsRole`) | add `access` (roles decide) | `globalOverrides`, `forms.formSubmissionOverrides`, `consentLog.collectionOverrides`, `stats.collectionOverrides` |
| Staff features without `access` (no roles field): every account of the panel's login collection passes (`userMeetsRole`); accounts of other auth collections never do | add `access` (roles decide) | `access.staffCollections` (more staff collections), `globalOverrides`, `forms.formSubmissionOverrides`, `consentLog.collectionOverrides`, `stats.collectionOverrides` |
| Cookie check (`crawl`): start editor+ or the token, results token-only for the running job, latest result only, dashboard warning on, e-mail off until recipients are set | omit `crawl`; `crawl.dashboard: false` | `crawl.serviceUrl` / `token` / `siteUrl` / `maxPages` / `acceptSelector` / `consentMode` / `trackerHosts` / `globalOverride`; *Cookie check → Warning e-mails to*; building blocks `ingestCrawlResult`, `findCrawlViolations`, `parseCrawlResult` |
| Cookie admin: one *Cookies* entry — review list and site check as tabs, their own entries out of the navigation (pages and API kept) | `cookieScanner.adminLayout: 'separate'` | `addCookieScannerTabs`, `CookieReviewTab`, `CookieSiteCheckTab`; `collectionOverrides` / `crawl.globalOverride` win |
| Theme choice in localStorage under `theme` (next-themes' key); old `ipal-theme` moved before paint; declared to the cookie scanner as necessary local storage | — | `ipalKit({ theme: { storageKey } })`; `<ThemeSwitcher storageKey>` / `useTheme({ storageKey })` |
@@ -1146,6 +1159,7 @@ add missing hosts with flags / `extra`; (3) change `mode` to `'enforce'` in both
| Injected `users`: admin manages everyone, others only themselves | — | `access.authAccess` (your keys win); your own `users` collection wins whole |
| First registered account = admin | `access.firstUserAdmin: false` | `buildRolesField(defaultRole, { firstUserAdmin })` |
| 2FA on the panel's login collection, mismatch = startup error; redirect to the 2FA screens by `TotpRedirectProvider` | `twoFactor: false` (discouraged) | `twoFactor.collectionSlug`, `allowCollectionMismatch: true`, `twoFactor.provider` (own component, or `false` for the package's) |
| The second factor on every collection and global, whichever plugin added it, and on the plugin's endpoints; an unrecognised 2FA package = startup error | `twoFactor.guard: false` (not recommended: the package's wrapper only) | `requireSecondFactor` / `secondFactorPassed` in your own access functions and endpoints |
| `enabled: false` keeps the schema | — | — (no endpoints, `onInit` or admin components; no DROP TABLE in `migrate:create`) |
| No client IP = one shared `unknown-ip` bucket at 20× the limit | `setUnknownIpFactor(0)` (only with a limiter in front) | `setUnknownIpFactor(n)`; `UNKNOWN_IP_FACTOR` |
| Turnstile token domain not checked | (default) | `createSubmitAction({ turnstileHostnames })`, `verifyTurnstile({ hostnames })` — leave empty in dev |
+7 -2
View File
@@ -48,8 +48,13 @@ Ask only when the brief leaves a business question open (e.g. "do posts have aut
generateStaticParams, hreflang.
3. Entry list = a block (EntriesList) with `getEntries`; the entry page uses
`resolveRoute` (type `entry`); JSON-LD per seo.md (e.g. Article).
4. `pnpm generate:types`, `pnpm payload generate:importmap`.
5. Postgres with migrations → `pnpm payload migrate:create`.
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
`/api/globals/site-integrations` and `/api/form-submissions`.
5. `pnpm generate:types`, `pnpm payload generate:importmap`.
6. Postgres with migrations → `pnpm payload migrate:create`.
## 4. Check
The **ipal-audit** skill. By hand: an entry in the panel → visible at `/<locale>/<archive>/<slug>`,
+3
View File
@@ -34,6 +34,9 @@ through this procedure. Ask only when you are missing something you cannot get y
### Build / TypeScript
| Symptom | Cause | Fix |
|---|---|---|
| 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 (supported: 3.0.0-beta.1 to 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 })`, or (server-only code that needs no access check) leave `overrideAccess` at its default |
| an account of a second auth collection (`customers`) gets `403` from a settings global, submissions or `/api/ipal/*` after an upgrade | by design since the release after 1.16.3: only staff collections pass `userMeetsRole` | write the one rule it needs (`formSubmissionOverrides`, `globalOverrides`, `collectionOverrides`); a second STAFF collection: `access.staffCollections` (access.md "Who is staff") |
| `TS2307 next/navigation` in the plugin's `dist` | import without `.js` in the plugin client (NodeNext) | **ipal-kit bug** → plugin gap; the plugin imports `'next/navigation.js'` |
| `TS2307 @payloadcms/storage-s3` | package missing when using `buildR2Storage` | `pnpm add @payloadcms/storage-s3` + `buildR2Storage(['media'], { s3Storage })` |
| `does not provide an export named X` / `X is not a function` | symbol not exported from the entry point, or wrong subpath (`/client` vs root vs `/server` vs `/rsc`) | `docs/README.md` → the right import; missing from every entry → **ipal-kit bug** (export) |
+4 -2
View File
@@ -25,11 +25,12 @@ description: Complete map of everything @intecion/ipal-kit provides — every ip
| `i18n.fallback` | `true` | `localization.fallback` | `false` |
| `i18n.locales[]` `{ code, label, rtl? }` | — | list of languages (min. 1); `rtl: true` → `rtl` in Payload | adding a language: skill **ipal-locale-add** |
| admin languages (no option) | English + Polish | `i18n.supportedLanguages` set to `{ en, pl }` when the project has none; plugin component texts in `i18n.translations.<lang>.ipal` (`adminTexts`); every plugin label is `{ en, pl }` (rules: `docs/dev/admin-ux.md`) | your own `i18n.supportedLanguages` wins; override a component text with `i18n.translations.<lang>.ipal.<key>`; field/global labels via `globalOverrides` / `collectionOverrides` — see i18n.md "Admin panel languages and texts" |
| `access` | none | `roles` field (`user` < `editor` < `admin`, `saveToJWT`) in the auth collection | omit → **no roles**: every logged-in account passes the plugin's admin/editor checks (`userMeetsRole`): Site integrations, the e-mail test, stats, consent-records, settings globals, `form-submissions`. Narrow them with `globalOverrides` / collection overrides |
| `access` | none | `roles` field (`user` < `editor` < `admin`, `saveToJWT`) in the auth collection | omit → **no roles**: every account of the panel's login collection passes the plugin's admin/editor checks (`userMeetsRole`; accounts of other auth collections never pass): Site integrations, the e-mail test, stats, consent-records, settings globals, `form-submissions`. Narrow them with `globalOverrides` / collection overrides |
| `access.authCollection` | — (required in `access`) | collection that gets `roles`; also the slug of the injected auth collection | your own collection with that slug wins |
| `access.defaultRole` | `'user'` | `defaultValue` of the `roles` field | `'editor'` / `'admin'` |
| `access.authAccess` | `{ create: adminOnly, delete: adminOnly, read: adminOrSelf, unlock: adminOnly, update: adminOrSelf }` | access of the auth collection the plugin **injects** (Payload's default lets any logged-in account edit or delete every other account) | your keys win, e.g. `{ read: authenticated }`; your own collection with that slug wins whole (give it `adminOrSelf` / `adminOnly` yourself) |
| `access.authAccess` | `{ create: adminOnly, delete: adminOnly, read: adminOrSelfIn(slug), unlock: adminOnly, update: adminOrSelfIn(slug) }` | access of the auth collection the plugin **injects** (Payload's default lets any logged-in account edit or delete every other account) | your keys win, e.g. `{ read: authenticated }`; your own collection with that slug wins whole (give it `adminOrSelf` / `adminOnly` yourself) |
| `access.firstUserAdmin` | `true` | the account made on Payload's "Create first user" screen (`/first-register` on an empty collection) gets `roles: ['admin']`; an open sign-up still gets `defaultRole` | `false` = that account gets what was submitted |
| `access.staffCollections` | `[]` | more auth collections whose accounts are staff for `userMeetsRole`, besides the panel's login collection (`admin.user`); without a `roles` field there, every such account passes every staff check | add `buildRolesField()` to that collection to tell roles apart; a visitor collection (`customers`) is never listed here |
| `adminRoute` | `'/admin'` | `config.routes.admin`; stats link and views, `IntegrationAlerts` | the project moves `app/(payload)/<route>/` itself and adds the route to the proxy matcher (security.md) |
| `twoFactor` | **none = error** | `@clocklimited/payload-2fa` with `forceSetup: true` (TOTP enforced, also checked in the API) | `twoFactor: false` (discouraged); omitting the option throws `[ipal] twoFactor.issuer is required` |
| `twoFactor.issuer` | — (required) | name in the authenticator app | — |
@@ -37,6 +38,7 @@ description: Complete map of everything @intecion/ipal-kit provides — every ip
| `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.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` | `false` = the package's wrapper only (the plugin's own data then opens to a password without the code; not recommended) |
| `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 | — |
@@ -53,6 +53,7 @@ Admin panel components from `@intecion/ipal-kit/admin` — the project does NOT
| `adminOnly` | `@intecion/ipal-kit` | Collection `Access`: `admin` role only. In `access.read/create/update/delete`. |
| `adminOrEditor` | `@intecion/ipal-kit` | Collection `Access`: `editor` or `admin`. Typical for content edited in the panel. |
| `adminOrSelf` | `@intecion/ipal-kit` | Collection `Access`: admin sees everything, a logged-in user only their own document (`Where` `id = user.id`), anonymous nothing. E.g. `users.read`. |
| `adminOrSelfIn(slug)` | `@intecion/ipal-kit` | `adminOrSelf` for the auth collection `slug`: only an account **of that collection** is "self"; an account of another auth collection gets nothing. Use it whenever the project has more than one auth collection (with numeric ids `adminOrSelf` would match customer no. 5 with staff account no. 5). The injected auth collection uses it. |
| `authenticated` | `@intecion/ipal-kit` | Collection `Access`: any logged-in user. |
| `requireRole(minimum)` | `@intecion/ipal-kit` | Collection `Access` factory: at least the given role (`'user' \| 'editor' \| 'admin'`). |
| `adminOnlyField` | `@intecion/ipal-kit` | `FieldAccess` (boolean only): field for admin only. In `field.access.read/update`. |
@@ -61,12 +62,13 @@ Admin panel components from `@intecion/ipal-kit/admin` — the project does NOT
| `hasMinimumRole(user, minimum)` | `@intecion/ipal-kit` | Predicate → `boolean`: whether the user has a role ≥ `minimum` (reads `user.roles` safely). For your own access logic/hooks. |
| `isAdmin(user)` | `@intecion/ipal-kit` | Predicate → `boolean`: `admin` role. |
| `isEditor(user)` | `@intecion/ipal-kit` | Predicate → `boolean`: `editor` or higher. |
| `userMeetsRole(req, minimum)` | `@intecion/ipal-kit` | Predicate → `boolean` with `req` (`{ payload, user }`): role ≥ `minimum`, **or** any logged-in user when the user's auth collection has no `roles` field (the project omitted `access`). The plugin's staff features use it (Site integrations, settings globals, test e-mail, stats, consent records, form submissions). Use it in your own access when the project may run without roles. |
| `userMeetsRole(req, minimum)` | `@intecion/ipal-kit` | Predicate → `boolean` with `req` (`{ payload, user }`): role ≥ `minimum`, **or** any account of a **staff collection** (the panel's login collection `admin.user`, plus `access.staffCollections`) that has no `roles` field (the project omitted `access`). An account of any other auth collection never passes without a role. With 2FA on it also requires the second factor (`secondFactorPassed`). The plugin's staff features (Site integrations, settings globals, form submissions, consent records, stats, cookie scanner, the e-mail test) use it; use it in your own endpoints. |
| `staffCollectionSlugs(payload)` | `@intecion/ipal-kit` | `string[]`: the staff collections `userMeetsRole` accepts — `admin.user` plus `access.staffCollections`. |
| `ROLE_HIERARCHY` | `@intecion/ipal-kit` | Constant `['user', 'editor', 'admin']` (lowest first) — a higher role meets the requirements of a lower one. The plugin injects the `roles` field into the auth collection (`access.authCollection`). |
| `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:** `Role` (`'user' \| 'editor' \| 'admin'`), `AccessOption` (the plugin's `access` option: `authCollection`, `defaultRole`, `authAccess`, `firstUserAdmin`).
**Types:** `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`
@@ -583,6 +585,8 @@ Server only (`pnpm payload run`); never import it from client code, the Payload
|---|---|---|
| `buildSecurityHeaders({ hsts?, csp?, additional?, coop?, frameOptions?, permissionsPolicy?, referrerPolicy?, … })` | `@intecion/ipal-kit` | Returns `SecurityHeader[]` (HSTS, X-Frame-Options, nosniff, Referrer-Policy, Permissions-Policy, COOP; with `IPAL_NOINDEX` also `X-Robots-Tag`) for `headers()` in `next.config.ts`. `csp` = `buildCsp` args → the CSP header (+ `Reporting-Endpoints` with `reportUri`); off by default. `additional` overrides by key. |
| `withSecurityConfig(nextConfig, { hidePoweredBy? })` | `@intecion/ipal-kit` | Next config wrapper: `poweredByHeader: false` + drops `X-Powered-By` from `headers()` (Next's "Next.js" and withPayload's "Next.js, Payload"). `withPayload(withSecurityConfig(nextConfig))`; `hidePoweredBy: false` = no change. |
| `secondFactorPassed(req)` | `@intecion/ipal-kit` | `boolean` with `req` (`{ payload, user }`): `false` only for an account of the 2FA collection that has TOTP set up and has not entered the code in this session (password only). `true` for a full login, an API key, an account that has not set TOTP up yet, accounts of other auth collections, no user, and with `twoFactor: false`. Guard your own endpoints with it: `if (!req.user \|\| !secondFactorPassed(req)) return 403`. |
| `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, in `onInit`, to those added by plugins listed after it); use it for access functions that are not part of the config. 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'`. |
| `buildCspHeaders(args)` | `@intecion/ipal-kit` | `[csp, Reporting-Endpoints]` (the second only with `reportUri`). |
+8 -2
View File
@@ -217,11 +217,17 @@ the panel shows Site settings, Site integrations, Cookies, Form messages, the Fo
(discouraged); without an injected `plugin: payloadTotp` it also throws. `forceSetup` currently always `true`.
- `users`: the injected collection lets admins manage everyone and others only themselves — loosen with
`access: { authCollection: 'users', authAccess: { read: authenticated } }` (your keys win); your own collection with
that slug wins whole (the plugin only adds `roles` — give it `adminOrSelf` / `adminOnly`). The first account
that slug wins whole (the plugin only adds `roles` — give it `adminOrSelfIn('users')` / `adminOnly`). The first account
(Create first user) gets `admin` — `access.firstUserAdmin: false` turns that off. `localization` currently always
overridden from `i18n`.
- 2FA wraps the panel's login collection (`admin.user`); a different `twoFactor.collectionSlug` stops startup with
`[ipal] twoFactor…` unless `allowCollectionMismatch: true`.
`[ipal] twoFactor…` unless `allowCollectionMismatch: true`. The second factor covers every collection and global
(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").
- A second auth collection (`customers`, a client zone): set `admin: { user: 'users' }` in `buildConfig`; its
accounts pass none of the plugin's staff checks; use `adminOrSelfIn('<slug>')` in every auth collection; a second
collection of STAFF goes in `access.staffCollections` (access.md "Who is staff"). Check: that account's token
gets `403` from `/api/globals/site-integrations` and `/api/form-submissions`.
- The `site-settings`, `site-integrations`, `cookie-settings`, `notifications` globals (write: editor+; Site
Integrations: admin), the `/api/ipal/test-email` endpoint and dashboard alerts — currently always present; extend
`siteSettingsFields` / `integrationsFields`; change access, admin or hooks with
+20
View File
@@ -328,6 +328,26 @@ recommended, not required (the plugin's peer range stays `^3.90.2`):**
21.0.4; `pnpm audit --prod` → no high or critical; `pnpm exec ipal-doctor` → no `versions` finding; Coolify Terminal
`node -v` → 22.23.5 or later; the panel opens, a document saves, a form submission arrives.
**→ the release after 1.16.3 (PROGRAMISTA §6, item 65; security fixes: 2FA coverage and staff checks) — required
for every site:**
1. Update the package, `pnpm install`, `pnpm ipal:skills`, build, redeploy on Coolify. No migration, no config
change for a site with one auth collection. `pnpm ls @clocklimited/payload-2fa` must show 3.0.0-beta.1 to beta.7;
another version may stop startup with `[ipal] twoFactor: the injected 2FA plugin did not add …`.
2. `grep -rn "auth:" src/collections` — more than one auth collection? Then: `admin: { user: '<staff slug>' }` in
`buildConfig`; `adminOrSelfIn('<slug>')` instead of `adminOrSelf` in each; `access.staffCollections` only when
the second collection is staff (access.md "Who is staff"). Never list a visitor collection there.
3. `grep -rn "overrideAccess: false" src` — a call on a plugin collection or global (`form-submissions`, `forms`,
`consent-records`, `stats-visits`, `cookie-review`, the settings globals) must pass the `user` from
`payload.auth({ headers })`. Own endpoints that check `req.user`: add `secondFactorPassed(req)` or use
`userMeetsRole(req, role)`.
4. Tell the owner what the CHANGELOG entry says under "Requires project changes" and agree on it: new SMTP
password and Turnstile secret, a look through Site settings, Site integrations and each form's Emails tab.
Do not change those values yourself without that decision.
**Check:** with 2FA on, log in over the API with the password only (security.md → "What the second factor covers" →
Check) → `403` from `/api/globals/site-integrations`, `/api/form-submissions`, `/api/users`; log in fully in the
panel → Site integrations and a form submission open, a setting saves. With a second auth collection: its token
gets `403` from the same addresses.
## 2. Inventory (no code changes)
**What changed for projects** between your old and new plugin version is exactly the reference site's diff —
`git diff v<old> v<new> -- reference/` in the ipal-kit repo (or the two `docs/agent/reference-site/INDEX.md` files):
+1
View File
@@ -672,6 +672,7 @@ Do one item at a time, build, check. Order by importance:
| 62 | **1.16.1** — `pnpm dev` warns "Next.js 16.4.3 is affected by a known security vulnerability"; ipal-doctor `next-min` error below 16.4.5 (GHSA-mfr8-8qww-v76h) | `pnpm add [email protected] [email protected]`, `rm -rf .next`, build, commit the lockfile, redeploy on Coolify; `pnpm ipal:skills`; no option, migration or import map change | CHANGELOG 1.16.1, AGENT.md §4 item 11 |
| 63 | **1.16.2** — `pnpm audit --prod` shows `mongoose` (critical, via `@payloadcms/db-mongodb`) or `happy-dom` (high, via `@payloadcms/richtext-lexical`); ipal-doctor `transitive-min` | `pnpm.overrides`: `"mongoose@>=8 <8.24.7": "~8.24.10"` (MongoDB sites) and `"happy-dom@<21.0.4": "^21.0.4"`; `pnpm install`, build, commit the lockfile, redeploy on Coolify; `pnpm ipal:skills`; no migration | CHANGELOG 1.16.2, AGENT.md §4 item 12 |
| 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 | **the release after 1.16.3 — 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. Own endpoints: `secondFactorPassed(req)`; own `overrideAccess: false` calls: `user` from `payload.auth()`. `pnpm ipal:skills`; no migration | CHANGELOG "Unreleased — security fixes", security.md "What the second factor covers", access.md "Who is staff" |
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`.
+79 -3
View File
@@ -344,8 +344,9 @@ addition to real safeguards, not a replacement for them.
The plugin enforces two-factor authentication (TOTP) for ALL panel users —
with no way to turn it off per user. Every project gets it automatically.
It uses the proven `@clocklimited/payload-2fa` (it wraps access control — TOTP is
checked before access to DATA, not only the panel UI).
It uses `@clocklimited/payload-2fa`, which wraps access control: TOTP is checked before access to DATA
(REST, GraphQL), not only in the panel UI. On top of the package ipal-kit runs its own check, so the second
factor also covers what the package cannot see — see "What the second factor covers" below.
### Dependency
@@ -368,6 +369,7 @@ ipalKit({
plugin: payloadTotp, // ← INJECT — see below why
// collectionSlug: 'users', // default: the panel login collection (admin.user, else the first auth collection)
// allowCollectionMismatch: true, // deliberate only: 2FA on a collection other than admin.user
// guard: false, // NOT recommended: ipal-kit's own check off, the package's wrapper only
},
})
```
@@ -390,6 +392,67 @@ gets the injected plugin.
The plugin sets `forceSetup: true` — every user MUST set up TOTP after
logging in. There is no per-user "on/off" option.
### What the second factor covers
The package wraps the `access` functions of the collections and globals that are in the config **at the moment
it runs**. ipalKit runs it early, so the plugin's own globals and collections (Site settings, Site integrations,
Cookie banner, Notifications, forms, form submissions, consent records, cookie review, stats) and anything a
plugin listed after `ipalKit` adds were not wrapped. **Up to 1.16.3 a staff password without the TOTP code
therefore read and changed them over the API.** Since the release after 1.16.3 ipal-kit closes that itself:
| Where | How |
|---|---|
| every collection and global in the config when ipalKit finishes | `access` wrapped with `requireSecondFactor` |
| collections and globals added by plugins listed **after** ipalKit | wrapped in ipalKit's `onInit`; the log line `[ipal] 2FA also enforced on entities added after ipalKit: …` names them |
| the plugin's endpoints (`/api/ipal/test-email`, `cookie-scan`, `cookie-approval`, `cookie-crawl`, the `access` option of `/api/ipal/doctor`) | `userMeetsRole` and `secondFactorPassed` |
The order of the project's `plugins` array does not matter. Payload's own collections (`payload-preferences`,
`payload-locked-documents`, …) and `access.admin` (may this account open the panel) are left alone: the code is
entered inside the panel.
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
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.
Two things follow for project code:
- `payload.find({ …, user, overrideAccess: false })` on a plugin collection needs a `user` that came from
`payload.auth({ headers })` (it carries how the account logged in). A user fetched with `findByID` and passed
by hand is refused when it has TOTP set up.
- Your own endpoints do not go through `access`. Guard them:
```ts
import { requireSecondFactor, secondFactorPassed, userMeetsRole } from '@intecion/ipal-kit'
// an endpoint
handler: async (req) => {
if (!req.user || !secondFactorPassed(req)) return Response.json({ ok: false }, { status: 403 })
// or: if (!userMeetsRole(req, 'editor')) … — it includes the second-factor check
}
// an access function (collections and globals in the config are wrapped for you; this is for the rest)
access: { read: requireSecondFactor(({ req }) => isAdmin(req.user)) }
```
**Fails closed.** At startup ipalKit checks that the injected 2FA plugin added what the check reads (the
`totpSecret` and `hasTotp` fields and the `totp` auth strategy on the 2FA collection). When it did not — a
package version with another shape — startup stops with `[ipal] twoFactor: the injected 2FA plugin did not
add …`. Supported: `@clocklimited/payload-2fa` 3.0.0-beta.1 to beta.7. `twoFactor.guard: false` switches
ipal-kit's check off and leaves the package's wrapper alone; the plugin's own data is then open to a password
without the code again, so use it only to get a site started while the package is being sorted out.
**Check** (replace the address and the account):
```bash
# password only, no code → 403 on all three
TOKEN=$(curl -s https://example.com/api/users/login -H 'content-type: application/json' \
-d '{"email":"admin@example.com","password":"…"}' | node -pe 'JSON.parse(require("fs").readFileSync(0)).token')
for p in globals/site-integrations form-submissions users; do
curl -s -o /dev/null -w "$p %{http_code}\n" -H "Authorization: JWT $TOKEN" https://example.com/api/$p
done
```
### Import map (required)
The 2FA screens and the redirect to them are admin components. After adding `twoFactor`, and after every
@@ -469,7 +532,8 @@ An admin can reset another user's 2FA (when they lose their phone) — through
Chosen because it wraps ACCESS CONTROL (TOTP before data access) + forceSetup
(enforced for everyone). Other 2FA plugins for Payload only gate /admin
navigation — a user with a password can bypass them through REST/GraphQL/Bearer. @clocklimited protects
data access, not just the UI.
data access, not just the UI — for what is in the config when it runs; ipal-kit's own check covers the rest
("What the second factor covers").
## 1.9.1 — security review results
@@ -483,6 +547,16 @@ data access, not just the UI.
- Uploads: `buildUploadSecurityHeaders()` in `next.config.ts` (an SVG cannot run a script on the site's domain).
- `users`: the plugin injects an auth collection when the project has none (roles and 2FA always attach).
## The release after 1.16.3 — two access fixes
- **Staff checks and a second auth collection.** `userMeetsRole` treated an account of any auth collection
without a `roles` field as staff — a `customers` account passed every check of the plugin, admin ones
included. Now only accounts of a staff collection can pass: the panel's login collection plus
`access.staffCollections` ([access.md](./access.md#who-is-staff)). The injected auth collection uses
`adminOrSelfIn(slug)`, so an account of another collection with the same numeric id no longer counts as "self".
- **2FA and the plugin's own data.** See "What the second factor covers" above.
- After upgrading: [PROGRAMISTA.md](./dev/PROGRAMISTA.md) upgrade table, and the CHANGELOG entry of that release.
## Form files (`forms.attachments`)
Files attached to a form are **never stored and cannot be downloaded**: they are checked in memory, attached to
@@ -517,6 +591,8 @@ size while reading, content signature, container and macro checks, an optional `
## Turn off, override, extend
- **2FA check:** `twoFactor.guard: false` turns ipal-kit's own second-factor check off (not recommended);
`requireSecondFactor` / `secondFactorPassed` are exported for your own access functions and endpoints.
- **Turn off:** headers — do not call `buildSecurityHeaders`, or `null` / `false` per header (`frameOptions`,
`referrerPolicy`, `permissionsPolicy`, `coop`), `hsts: false`; CSP — leave out `csp` (the default);
X-Powered-By hiding — `withSecurityConfig(config, { hidePoweredBy: false })` or do not call it;
@@ -48,8 +48,13 @@ Ask only when the brief leaves a business question open (e.g. "do posts have aut
generateStaticParams, hreflang.
3. Entry list = a block (EntriesList) with `getEntries`; the entry page uses
`resolveRoute` (type `entry`); JSON-LD per seo.md (e.g. Article).
4. `pnpm generate:types`, `pnpm payload generate:importmap`.
5. Postgres with migrations → `pnpm payload migrate:create`.
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
`/api/globals/site-integrations` and `/api/form-submissions`.
5. `pnpm generate:types`, `pnpm payload generate:importmap`.
6. Postgres with migrations → `pnpm payload migrate:create`.
## 4. Check
The **ipal-audit** skill. By hand: an entry in the panel → visible at `/<locale>/<archive>/<slug>`,
@@ -34,6 +34,9 @@ through this procedure. Ask only when you are missing something you cannot get y
### Build / TypeScript
| Symptom | Cause | Fix |
|---|---|---|
| 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 (supported: 3.0.0-beta.1 to 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 })`, or (server-only code that needs no access check) leave `overrideAccess` at its default |
| an account of a second auth collection (`customers`) gets `403` from a settings global, submissions or `/api/ipal/*` after an upgrade | by design since the release after 1.16.3: only staff collections pass `userMeetsRole` | write the one rule it needs (`formSubmissionOverrides`, `globalOverrides`, `collectionOverrides`); a second STAFF collection: `access.staffCollections` (access.md "Who is staff") |
| `TS2307 next/navigation` in the plugin's `dist` | import without `.js` in the plugin client (NodeNext) | **ipal-kit bug** → plugin gap; the plugin imports `'next/navigation.js'` |
| `TS2307 @payloadcms/storage-s3` | package missing when using `buildR2Storage` | `pnpm add @payloadcms/storage-s3` + `buildR2Storage(['media'], { s3Storage })` |
| `does not provide an export named X` / `X is not a function` | symbol not exported from the entry point, or wrong subpath (`/client` vs root vs `/server` vs `/rsc`) | `docs/README.md` → the right import; missing from every entry → **ipal-kit bug** (export) |
@@ -25,11 +25,12 @@ description: Complete map of everything @intecion/ipal-kit provides — every ip
| `i18n.fallback` | `true` | `localization.fallback` | `false` |
| `i18n.locales[]` `{ code, label, rtl? }` | — | list of languages (min. 1); `rtl: true` → `rtl` in Payload | adding a language: skill **ipal-locale-add** |
| admin languages (no option) | English + Polish | `i18n.supportedLanguages` set to `{ en, pl }` when the project has none; plugin component texts in `i18n.translations.<lang>.ipal` (`adminTexts`); every plugin label is `{ en, pl }` (rules: `docs/dev/admin-ux.md`) | your own `i18n.supportedLanguages` wins; override a component text with `i18n.translations.<lang>.ipal.<key>`; field/global labels via `globalOverrides` / `collectionOverrides` — see i18n.md "Admin panel languages and texts" |
| `access` | none | `roles` field (`user` < `editor` < `admin`, `saveToJWT`) in the auth collection | omit → **no roles**: every logged-in account passes the plugin's admin/editor checks (`userMeetsRole`): Site integrations, the e-mail test, stats, consent-records, settings globals, `form-submissions`. Narrow them with `globalOverrides` / collection overrides |
| `access` | none | `roles` field (`user` < `editor` < `admin`, `saveToJWT`) in the auth collection | omit → **no roles**: every account of the panel's login collection passes the plugin's admin/editor checks (`userMeetsRole`; accounts of other auth collections never pass): Site integrations, the e-mail test, stats, consent-records, settings globals, `form-submissions`. Narrow them with `globalOverrides` / collection overrides |
| `access.authCollection` | — (required in `access`) | collection that gets `roles`; also the slug of the injected auth collection | your own collection with that slug wins |
| `access.defaultRole` | `'user'` | `defaultValue` of the `roles` field | `'editor'` / `'admin'` |
| `access.authAccess` | `{ create: adminOnly, delete: adminOnly, read: adminOrSelf, unlock: adminOnly, update: adminOrSelf }` | access of the auth collection the plugin **injects** (Payload's default lets any logged-in account edit or delete every other account) | your keys win, e.g. `{ read: authenticated }`; your own collection with that slug wins whole (give it `adminOrSelf` / `adminOnly` yourself) |
| `access.authAccess` | `{ create: adminOnly, delete: adminOnly, read: adminOrSelfIn(slug), unlock: adminOnly, update: adminOrSelfIn(slug) }` | access of the auth collection the plugin **injects** (Payload's default lets any logged-in account edit or delete every other account) | your keys win, e.g. `{ read: authenticated }`; your own collection with that slug wins whole (give it `adminOrSelf` / `adminOnly` yourself) |
| `access.firstUserAdmin` | `true` | the account made on Payload's "Create first user" screen (`/first-register` on an empty collection) gets `roles: ['admin']`; an open sign-up still gets `defaultRole` | `false` = that account gets what was submitted |
| `access.staffCollections` | `[]` | more auth collections whose accounts are staff for `userMeetsRole`, besides the panel's login collection (`admin.user`); without a `roles` field there, every such account passes every staff check | add `buildRolesField()` to that collection to tell roles apart; a visitor collection (`customers`) is never listed here |
| `adminRoute` | `'/admin'` | `config.routes.admin`; stats link and views, `IntegrationAlerts` | the project moves `app/(payload)/<route>/` itself and adds the route to the proxy matcher (security.md) |
| `twoFactor` | **none = error** | `@clocklimited/payload-2fa` with `forceSetup: true` (TOTP enforced, also checked in the API) | `twoFactor: false` (discouraged); omitting the option throws `[ipal] twoFactor.issuer is required` |
| `twoFactor.issuer` | — (required) | name in the authenticator app | — |
@@ -37,6 +38,7 @@ description: Complete map of everything @intecion/ipal-kit provides — every ip
| `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.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` | `false` = the package's wrapper only (the plugin's own data then opens to a password without the code; not recommended) |
| `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 | — |
@@ -53,6 +53,7 @@ Admin panel components from `@intecion/ipal-kit/admin` — the project does NOT
| `adminOnly` | `@intecion/ipal-kit` | Collection `Access`: `admin` role only. In `access.read/create/update/delete`. |
| `adminOrEditor` | `@intecion/ipal-kit` | Collection `Access`: `editor` or `admin`. Typical for content edited in the panel. |
| `adminOrSelf` | `@intecion/ipal-kit` | Collection `Access`: admin sees everything, a logged-in user only their own document (`Where` `id = user.id`), anonymous nothing. E.g. `users.read`. |
| `adminOrSelfIn(slug)` | `@intecion/ipal-kit` | `adminOrSelf` for the auth collection `slug`: only an account **of that collection** is "self"; an account of another auth collection gets nothing. Use it whenever the project has more than one auth collection (with numeric ids `adminOrSelf` would match customer no. 5 with staff account no. 5). The injected auth collection uses it. |
| `authenticated` | `@intecion/ipal-kit` | Collection `Access`: any logged-in user. |
| `requireRole(minimum)` | `@intecion/ipal-kit` | Collection `Access` factory: at least the given role (`'user' \| 'editor' \| 'admin'`). |
| `adminOnlyField` | `@intecion/ipal-kit` | `FieldAccess` (boolean only): field for admin only. In `field.access.read/update`. |
@@ -61,12 +62,13 @@ Admin panel components from `@intecion/ipal-kit/admin` — the project does NOT
| `hasMinimumRole(user, minimum)` | `@intecion/ipal-kit` | Predicate → `boolean`: whether the user has a role ≥ `minimum` (reads `user.roles` safely). For your own access logic/hooks. |
| `isAdmin(user)` | `@intecion/ipal-kit` | Predicate → `boolean`: `admin` role. |
| `isEditor(user)` | `@intecion/ipal-kit` | Predicate → `boolean`: `editor` or higher. |
| `userMeetsRole(req, minimum)` | `@intecion/ipal-kit` | Predicate → `boolean` with `req` (`{ payload, user }`): role ≥ `minimum`, **or** any logged-in user when the user's auth collection has no `roles` field (the project omitted `access`). The plugin's staff features use it (Site integrations, settings globals, test e-mail, stats, consent records, form submissions). Use it in your own access when the project may run without roles. |
| `userMeetsRole(req, minimum)` | `@intecion/ipal-kit` | Predicate → `boolean` with `req` (`{ payload, user }`): role ≥ `minimum`, **or** any account of a **staff collection** (the panel's login collection `admin.user`, plus `access.staffCollections`) that has no `roles` field (the project omitted `access`). An account of any other auth collection never passes without a role. With 2FA on it also requires the second factor (`secondFactorPassed`). The plugin's staff features (Site integrations, settings globals, form submissions, consent records, stats, cookie scanner, the e-mail test) use it; use it in your own endpoints. |
| `staffCollectionSlugs(payload)` | `@intecion/ipal-kit` | `string[]`: the staff collections `userMeetsRole` accepts — `admin.user` plus `access.staffCollections`. |
| `ROLE_HIERARCHY` | `@intecion/ipal-kit` | Constant `['user', 'editor', 'admin']` (lowest first) — a higher role meets the requirements of a lower one. The plugin injects the `roles` field into the auth collection (`access.authCollection`). |
| `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:** `Role` (`'user' \| 'editor' \| 'admin'`), `AccessOption` (the plugin's `access` option: `authCollection`, `defaultRole`, `authAccess`, `firstUserAdmin`).
**Types:** `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`
@@ -583,6 +585,8 @@ Server only (`pnpm payload run`); never import it from client code, the Payload
|---|---|---|
| `buildSecurityHeaders({ hsts?, csp?, additional?, coop?, frameOptions?, permissionsPolicy?, referrerPolicy?, … })` | `@intecion/ipal-kit` | Returns `SecurityHeader[]` (HSTS, X-Frame-Options, nosniff, Referrer-Policy, Permissions-Policy, COOP; with `IPAL_NOINDEX` also `X-Robots-Tag`) for `headers()` in `next.config.ts`. `csp` = `buildCsp` args → the CSP header (+ `Reporting-Endpoints` with `reportUri`); off by default. `additional` overrides by key. |
| `withSecurityConfig(nextConfig, { hidePoweredBy? })` | `@intecion/ipal-kit` | Next config wrapper: `poweredByHeader: false` + drops `X-Powered-By` from `headers()` (Next's "Next.js" and withPayload's "Next.js, Payload"). `withPayload(withSecurityConfig(nextConfig))`; `hidePoweredBy: false` = no change. |
| `secondFactorPassed(req)` | `@intecion/ipal-kit` | `boolean` with `req` (`{ payload, user }`): `false` only for an account of the 2FA collection that has TOTP set up and has not entered the code in this session (password only). `true` for a full login, an API key, an account that has not set TOTP up yet, accounts of other auth collections, no user, and with `twoFactor: false`. Guard your own endpoints with it: `if (!req.user \|\| !secondFactorPassed(req)) return 403`. |
| `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, in `onInit`, to those added by plugins listed after it); use it for access functions that are not part of the config. 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'`. |
| `buildCspHeaders(args)` | `@intecion/ipal-kit` | `[csp, Reporting-Endpoints]` (the second only with `reportUri`). |
+8 -2
View File
@@ -217,11 +217,17 @@ the panel shows Site settings, Site integrations, Cookies, Form messages, the Fo
(discouraged); without an injected `plugin: payloadTotp` it also throws. `forceSetup` currently always `true`.
- `users`: the injected collection lets admins manage everyone and others only themselves — loosen with
`access: { authCollection: 'users', authAccess: { read: authenticated } }` (your keys win); your own collection with
that slug wins whole (the plugin only adds `roles` — give it `adminOrSelf` / `adminOnly`). The first account
that slug wins whole (the plugin only adds `roles` — give it `adminOrSelfIn('users')` / `adminOnly`). The first account
(Create first user) gets `admin` — `access.firstUserAdmin: false` turns that off. `localization` currently always
overridden from `i18n`.
- 2FA wraps the panel's login collection (`admin.user`); a different `twoFactor.collectionSlug` stops startup with
`[ipal] twoFactor…` unless `allowCollectionMismatch: true`.
`[ipal] twoFactor…` unless `allowCollectionMismatch: true`. The second factor covers every collection and global
(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").
- A second auth collection (`customers`, a client zone): set `admin: { user: 'users' }` in `buildConfig`; its
accounts pass none of the plugin's staff checks; use `adminOrSelfIn('<slug>')` in every auth collection; a second
collection of STAFF goes in `access.staffCollections` (access.md "Who is staff"). Check: that account's token
gets `403` from `/api/globals/site-integrations` and `/api/form-submissions`.
- The `site-settings`, `site-integrations`, `cookie-settings`, `notifications` globals (write: editor+; Site
Integrations: admin), the `/api/ipal/test-email` endpoint and dashboard alerts — currently always present; extend
`siteSettingsFields` / `integrationsFields`; change access, admin or hooks with
@@ -328,6 +328,26 @@ recommended, not required (the plugin's peer range stays `^3.90.2`):**
21.0.4; `pnpm audit --prod` → no high or critical; `pnpm exec ipal-doctor` → no `versions` finding; Coolify Terminal
`node -v` → 22.23.5 or later; the panel opens, a document saves, a form submission arrives.
**→ the release after 1.16.3 (PROGRAMISTA §6, item 65; security fixes: 2FA coverage and staff checks) — required
for every site:**
1. Update the package, `pnpm install`, `pnpm ipal:skills`, build, redeploy on Coolify. No migration, no config
change for a site with one auth collection. `pnpm ls @clocklimited/payload-2fa` must show 3.0.0-beta.1 to beta.7;
another version may stop startup with `[ipal] twoFactor: the injected 2FA plugin did not add …`.
2. `grep -rn "auth:" src/collections` — more than one auth collection? Then: `admin: { user: '<staff slug>' }` in
`buildConfig`; `adminOrSelfIn('<slug>')` instead of `adminOrSelf` in each; `access.staffCollections` only when
the second collection is staff (access.md "Who is staff"). Never list a visitor collection there.
3. `grep -rn "overrideAccess: false" src` — a call on a plugin collection or global (`form-submissions`, `forms`,
`consent-records`, `stats-visits`, `cookie-review`, the settings globals) must pass the `user` from
`payload.auth({ headers })`. Own endpoints that check `req.user`: add `secondFactorPassed(req)` or use
`userMeetsRole(req, role)`.
4. Tell the owner what the CHANGELOG entry says under "Requires project changes" and agree on it: new SMTP
password and Turnstile secret, a look through Site settings, Site integrations and each form's Emails tab.
Do not change those values yourself without that decision.
**Check:** with 2FA on, log in over the API with the password only (security.md → "What the second factor covers" →
Check) → `403` from `/api/globals/site-integrations`, `/api/form-submissions`, `/api/users`; log in fully in the
panel → Site integrations and a form submission open, a setting saves. With a second auth collection: its token
gets `403` from the same addresses.
## 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):
+31
View File
@@ -219,3 +219,34 @@ test('admin: sign in through 2FA, agency credit, panel link preview', async ({ p
await expect(page).toHaveTitle(/Dashboard|Pulpit/, { timeout: 20_000 })
await expect(page.getByText(/Intecion/).first()).toBeVisible()
})
// 2FA covers what the plugin adds, over the API too (REST and GraphQL): a correct password without the code
// from the authenticator app opens neither the settings nor visitors' data; the code does.
test('API: a staff password without the 2FA code opens nothing; with the code it does', async ({ playwright, baseURL }) => {
const { E2E_ADMIN_EMAIL: email, E2E_ADMIN_PASSWORD: password, E2E_TOTP_SECRET: secret } = process.env
test.skip(!email || !password || !secret, 'E2E_* test admin not configured')
const api = await playwright.request.newContext({ baseURL }) // its own cookie jar
const login = await api.post('/api/users/login', { data: { email, password } })
expect(login.status()).toBe(200)
const guarded = ['/api/globals/site-integrations', '/api/form-submissions', '/api/consent-records', '/api/users', '/api/globals/site-settings', '/api/forms']
for (const path of guarded) {
const res = await api.get(path)
expect(res.status(), `${path} without the code`).toBe(403)
expect(await res.text()).not.toContain('e2e-sink') // the SMTP password create-test-admin.ts stored
}
expect((await api.post('/api/globals/site-settings', { data: {} })).status()).toBe(403)
expect((await api.post('/api/ipal/test-email', { data: { to: '[email protected]' } })).status()).toBe(403)
const query = '{ SiteIntegration { smtpPassword } FormSubmissions { totalDocs } }'
const before = await (await api.post('/api/graphql', { data: { query } })).json()
expect(before.errors?.length).toBeGreaterThan(0)
expect(JSON.stringify(before)).not.toContain('e2e-sink')
const verify = await api.post('/api/verify-totp', { data: { token: totp(secret!) } })
expect((await verify.json()).ok).toBe(true)
for (const path of guarded) {expect((await api.get(path)).status(), `${path} with the code`).toBe(200)}
const after = await (await api.post('/api/graphql', { data: { query } })).json()
expect(after.errors).toBeUndefined()
expect(after.data.SiteIntegration.smtpPassword).toBe('e2e-sink')
await api.dispose()
})
+3
View File
@@ -8,6 +8,7 @@ export {
adminOrEditor,
adminOrEditorField,
adminOrSelf,
adminOrSelfIn,
authenticated,
buildRolesField,
hasMinimumRole,
@@ -17,6 +18,7 @@ export {
requireRole,
requireRoleField,
ROLE_HIERARCHY,
staffCollectionSlugs,
userMeetsRole,
} from './modules/access/index.js'
// Concrete files, not module barrels: a barrel that also re-exports 'use client'
@@ -325,6 +327,7 @@ export type {
} from './modules/security/index.js'
export type { BuildSecurityHeadersArgs, SecurityHeader } from './modules/security/index.js'
export { requireSecondFactor, secondFactorPassed } from './modules/security/totp/secondFactor.js'
export { TOTP_TEXTS, TOTP_VIEW_TITLE } from './modules/security/totp/totpTexts.js'
export type { OgImage } from './modules/seo/buildMetadata.js'
export type { PageMetadata, SeoMeta, SeoOption } from './modules/seo/index.js'
+22 -1
View File
@@ -20,13 +20,34 @@ export const requireRole =
({ req: { user } }) =>
hasMinimumRole(user, minimum)
/** Admins see all; others are constrained to their own document. */
/**
* Admins see all; others are constrained to their own document.
*
* It cannot know which collection it guards, so "own document" means "the
* document with my id". In a project with a second auth collection use
* `adminOrSelfIn(slug)` instead: with numeric ids (Postgres, SQLite) customer
* no. 5 would otherwise match staff account no. 5.
*/
export const adminOrSelf: Access = ({ req: { user } }) => {
if (isAdmin(user)) {return true}
if (!user) {return false}
return { id: { equals: user.id } }
}
/**
* `adminOrSelf` for the auth collection `slug`: only an account OF THAT
* collection is "self". An account of another auth collection gets nothing.
*
* { slug: 'users', auth: true, access: { read: adminOrSelfIn('users'), update: adminOrSelfIn('users') } }
*/
export const adminOrSelfIn =
(slug: string): Access =>
({ req: { user } }) => {
if (isAdmin(user)) {return true}
if (!user || (user as { collection?: unknown }).collection !== slug) {return false}
return { id: { equals: user.id } }
}
/**
* Field-level access (returns boolean only — no Where support).
* Use in field `access.read/update`.
+2 -1
View File
@@ -4,12 +4,13 @@ export {
adminOrEditor,
adminOrEditorField,
adminOrSelf,
adminOrSelfIn,
authenticated,
requireRole,
requireRoleField,
} from './access.js'
export { injectRoles } from './injectRoles.js'
export { hasMinimumRole, isAdmin, isEditor, userMeetsRole } from './predicates.js'
export { hasMinimumRole, isAdmin, isEditor, staffCollectionSlugs, userMeetsRole } from './predicates.js'
export { buildRolesField } from './rolesField.js'
export type { AccessOption, Role } from './types.js'
export { ROLE_HIERARCHY } from './types.js'
+32 -9
View File
@@ -2,6 +2,7 @@ import type { BasePayload } from 'payload'
import type { Role } from './types.js'
import { secondFactorPassed } from '../security/totp/secondFactor.js'
import { ROLE_HIERARCHY } from './types.js'
/**
@@ -45,23 +46,45 @@ export function isEditor(user: MaybeUser): boolean {
return hasMinimumRole(user, 'editor')
}
/**
* The auth collections whose accounts are staff: the one the admin panel logs
* in with (`admin.user`) plus `access.staffCollections`. Accounts of any other
* auth collection — customers, members — are visitors to the plugin.
*/
export function staffCollectionSlugs(payload?: Pick<BasePayload, 'config'>): string[] {
const config = payload?.config
if (!config) {return []}
const extra = (config.custom as { ipal?: { staffCollections?: string[] } } | undefined)?.ipal?.staffCollections ?? []
return [...new Set([config.admin?.user, ...extra].filter((s): s is string => typeof s === 'string' && s !== ''))]
}
/**
* Role check for the plugin's own staff features (Site Integrations, the
* e-mail test, stats, consent records, form submissions, the settings
* globals): true when the user holds at least `minimum` — or, when the
* user's auth collection has no `roles` field (the project omitted `access`),
* for every logged-in user. Without roles all accounts are equal, as in
* Payload's own default; nobody being "admin" would lock those features away.
* globals). True when the user holds at least `minimum`.
*
* Pass `req` (it has `payload` and `user`). An unknown collection counts as
* having roles — the strict side. A project with its own role scheme in
* another field narrows access through globalOverrides / collection overrides.
* Without roles: when the user belongs to a STAFF collection (the panel's
* login collection, or one named in `access.staffCollections`) and that
* collection has no `roles` field (the project omitted `access`), every
* account of it passes — without roles all staff accounts are equal, as in
* Payload's own default. An account of any other auth collection (a
* `customers` collection has no `roles` field either) never passes this way.
*
* With 2FA on, an account that has TOTP set up and has not entered the code in
* this session never passes (secondFactorPassed).
*
* Pass `req` (it has `payload` and `user`). Without `payload` only a held role
* counts — the strict side. A project with its own role scheme in another
* field narrows access through globalOverrides / collection overrides.
*/
export function userMeetsRole({ payload, user }: { payload?: BasePayload; user?: unknown }, minimum: Role): boolean {
if (!user || typeof user !== 'object') {return false}
if (!secondFactorPassed({ payload, user })) {return false}
if (hasMinimumRole(user as MaybeUser, minimum)) {return true}
const slug = (user as { collection?: unknown }).collection
const fields = typeof slug === 'string' ? payload?.collections?.[slug as never]?.config.fields : undefined
if (typeof slug !== 'string' || !staffCollectionSlugs(payload).includes(slug)) {return false}
const collection = payload?.collections?.[slug as never]?.config
const fields = (collection?.flattenedFields ?? collection?.fields) as Array<{ name?: string }> | undefined
if (!fields) {return false}
return !fields.some((f) => 'name' in f && f.name === 'roles')
return !fields.some((f) => f.name === 'roles')
}
+10
View File
@@ -34,4 +34,14 @@ export type AccessOption = {
* `false` = that account gets what was submitted (`defaultRole` by default).
*/
firstUserAdmin?: boolean
/**
* More auth collections whose accounts are staff, besides the one the admin
* panel logs in with (`admin.user`). Only accounts of a staff collection can
* pass the plugin's staff checks (`userMeetsRole`): the settings globals,
* Site integrations, form submissions, consent records, stats, the cookie
* scanner. A staff collection WITHOUT a `roles` field passes them all (every
* account is admin to the plugin); add `buildRolesField()` to it to tell
* admins, editors and users apart. Default: none.
*/
staffCollections?: string[]
}
+2 -1
View File
@@ -6,6 +6,7 @@ import type { CookieChange } from './scan.js'
import type { CookieScannerOptions, CookieStorage } from './types.js'
import { userMeetsRole } from '../../access/predicates.js'
import { secondFactorPassed } from '../../security/totp/secondFactor.js'
import { CONSENT_CATEGORIES } from '../categories.js'
import { COOKIE_REVIEW_SLUG } from './collection.js'
import { textFor } from './merge.js'
@@ -155,7 +156,7 @@ export async function approveCookies({
export function buildCookieApprovalEndpoints(options: CookieScannerOptions): Endpoint[] {
const approval = typeof options.approval === 'object' ? options.approval : {}
const allowed = async (req: PayloadRequest) =>
options.access ? Boolean(await options.access({ req })) : userMeetsRole(req, 'editor')
options.access ? secondFactorPassed(req) && Boolean(await options.access({ req })) : userMeetsRole(req, 'editor')
return [
{
handler: async (req) => {
@@ -6,6 +6,7 @@ import type { CookieScanLabels } from '../labels.js'
import type { CookieCrawlOptions, CookieScanContext, CookieScannerOptions } from '../types.js'
import { userMeetsRole } from '../../../access/predicates.js'
import { secondFactorPassed } from '../../../security/totp/secondFactor.js'
import {
COOKIE_CRAWL_PATH,
COOKIE_CRAWL_RESULTS_PATH,
@@ -59,7 +60,7 @@ export function buildCookieCrawlEndpoints({
}): Endpoint[] {
const crawl: CookieCrawlOptions = typeof options.crawl === 'object' ? options.crawl : {}
const isStaff = async (req: PayloadRequest) =>
options.access ? Boolean(await options.access({ req })) : userMeetsRole(req, 'editor')
options.access ? secondFactorPassed(req) && Boolean(await options.access({ req })) : userMeetsRole(req, 'editor')
const read = async (req: PayloadRequest) =>
(await req.payload.findGlobal({ slug: COOKIE_CRAWL_SLUG as never, depth: 0, overrideAccess: true, req })) as CrawlDoc
const write = (req: PayloadRequest, data: Partial<CrawlDoc>) =>
+2 -1
View File
@@ -3,6 +3,7 @@ import type { Endpoint, PayloadRequest } from 'payload'
import type { CookieIntegration, CookieScanContext, CookieScannerOptions } from './types.js'
import { userMeetsRole } from '../../access/predicates.js'
import { secondFactorPassed } from '../../security/totp/secondFactor.js'
import { DEFAULT_COOKIE_INTEGRATIONS, integrationLabel } from './integrations.js'
import { cookieScanContext, enabledCookieIntegrations, parseCookieNames, runCookieScan } from './scan.js'
@@ -16,7 +17,7 @@ export const COOKIE_SCAN_PATH = '/ipal/cookie-scan'
*/
export function buildCookieScanEndpoints(options: CookieScannerOptions, plugin: CookieScanContext['plugin']): Endpoint[] {
const allowed = async (req: PayloadRequest) =>
options.access ? Boolean(await options.access({ req })) : userMeetsRole(req, 'editor')
options.access ? secondFactorPassed(req) && Boolean(await options.access({ req })) : userMeetsRole(req, 'editor')
const integrations = options.integrations ? options.integrations(DEFAULT_COOKIE_INTEGRATIONS) : DEFAULT_COOKIE_INTEGRATIONS
// Names in the admin language of the editor who asks.
const list = (items: CookieIntegration[], req: PayloadRequest) =>
+2 -1
View File
@@ -7,6 +7,7 @@ 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 { clientIp, consumeRateLimit, tooManyRequests } from '../shared/rateLimit.js'
/** The plugin's own version (package.json next to dist/ and src/). */
@@ -67,7 +68,7 @@ export function buildDoctorEndpoint(options: DoctorEndpointOptions = {}): Endpoi
const limit = await consumeRateLimit({ key: clientIp(req.headers), max: 10, scope: 'ipal-doctor', windowMs: 60_000 })
if (!limit.ok) {return tooManyRequests(limit.retryAfter, { error: 'Too many requests' })}
const given = (req.headers.get('authorization') ?? '').replace(/^Bearer\s+/i, '').trim()
const allowed = (given && sameToken(given, token)) || (options.access ? await options.access({ req }) : false)
const allowed = (given && sameToken(given, token)) || (options.access ? secondFactorPassed(req) && (await options.access({ req })) : false)
if (!allowed) {return Response.json({ error: 'Unauthorized' }, { status: 401 })}
const status = await collectDoctorStatus(req.payload)
return Response.json(status, { headers: { 'cache-control': 'no-store' } })
+134
View File
@@ -0,0 +1,134 @@
import type { BasePayload, CollectionConfig, Config, GlobalConfig } from 'payload'
/**
* ipal-kit's own second-factor check, next to the access wrapper of
* @clocklimited/payload-2fa.
*
* Why it exists: the package wraps the `access` functions of the collections
* and globals that are in the config at the moment it runs. Whatever is added
* afterwards — ipal-kit's globals and collections, a plugin listed after
* ipalKit — was left unwrapped, so a staff password without the TOTP code
* opened it over the API. This check does not depend on that order: ipalKit
* applies it to everything in the config when it finishes, and again in onInit
* to whatever other plugins added later; `userMeetsRole` asks it too.
*
* 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.
*/
/** What ipalKit records in `config.custom.ipal.twoFactor` when 2FA is on and the guard is not switched off. */
export type TwoFactorGuardConfig = { collection: string }
type MaybeReq = { payload?: Pick<BasePayload, 'config'>; user?: unknown }
const guardConfig = (payload: MaybeReq['payload']): TwoFactorGuardConfig | undefined =>
(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`).
*
* Pass `req`. Use it in your own endpoints and access functions:
* if (!secondFactorPassed(req)) return Response.json({ ok: false }, { status: 403 })
*/
export function secondFactorPassed({ payload, user }: MaybeReq): boolean {
if (!user || typeof user !== 'object') {return true}
const guard = guardConfig(payload)
if (!guard) {return true}
const u = user as { _strategy?: unknown; collection?: unknown; hasTotp?: unknown }
if (u.collection !== guard.collection) {return true}
if (u._strategy === 'totp' || u._strategy === 'api-key') {return true}
return u.hasTotp === false
}
const GUARDED = Symbol.for('ipal.secondFactorGuard')
type AnyAccess = (args: never) => unknown
type Guarded = { [GUARDED]?: true } & AnyAccess
/**
* Wraps one access function: refused while the second factor is owed,
* otherwise the function itself (or Payload's default, "logged in", when there
* is none). Wrapping twice is harmless — an already wrapped function is returned as is.
*
* access: { read: requireSecondFactor(({ req }) => isAdmin(req.user)) }
*/
export function requireSecondFactor<T extends AnyAccess>(access?: T): T {
if (access && (access as Guarded)[GUARDED]) {return access}
const wrapped = ((args: { req: MaybeReq }) => {
if (!secondFactorPassed(args.req)) {return false}
return access ? access(args as never) : Boolean(args.req?.user)
}) as unknown as Guarded
wrapped[GUARDED] = true
return wrapped as unknown as T
}
/** `admin` (may this account open the panel) stays unwrapped: the code is entered inside the panel. */
const COLLECTION_OPERATIONS = ['create', 'delete', 'read', 'readVersions', 'unlock', 'update'] as const
const GLOBAL_OPERATIONS = ['read', 'readDrafts', 'readVersions', 'update'] as const
type AccessMap = Record<string, AnyAccess | undefined>
function guardAccessMap(access: AccessMap | undefined, operations: readonly string[]): AccessMap {
const out: AccessMap = { ...access }
for (const op of operations) {out[op] = requireSecondFactor(out[op])}
return out
}
/** Every collection and global of a (not yet sanitized) config, guarded. Returns a new config. */
export function guardConfigAccess(config: Config): Config {
return {
...config,
collections: (config.collections ?? []).map(
(c) => ({ ...c, access: guardAccessMap(c.access as AccessMap | undefined, COLLECTION_OPERATIONS) }) as CollectionConfig,
),
globals: (config.globals ?? []).map(
(g) => ({ ...g, access: guardAccessMap(g.access as AccessMap | undefined, GLOBAL_OPERATIONS) }) as GlobalConfig,
),
}
}
/**
* The same for a running Payload, in place: what plugins listed after ipalKit
* added. Called from ipalKit's onInit; returns the slugs it had to guard.
*/
export function guardPayloadAccess(payload: BasePayload): string[] {
const late: string[] = []
const sweep = (entity: { access?: unknown; slug: string }, operations: readonly string[]) => {
const access = (entity.access ?? {}) as AccessMap
if (operations.every((op) => (access[op] as Guarded | undefined)?.[GUARDED])) {return}
late.push(entity.slug)
entity.access = guardAccessMap(access, operations)
}
// Payload's own collections (payload-preferences, payload-locked-documents, …) keep their rules:
// the panel uses them before the code is entered, and the package leaves them alone too.
for (const c of payload.config.collections ?? []) {
if (!c.slug.startsWith('payload-')) {sweep(c, COLLECTION_OPERATIONS)}
}
for (const g of payload.config.globals ?? []) {sweep(g, GLOBAL_OPERATIONS)}
return late
}
/**
* The parts of @clocklimited/payload-2fa the guard relies on, checked right
* after the injected factory ran. A missing part means a version this guard
* was not written for: it would refuse every staff request, or — worse — the
* package itself may no longer protect what it used to. Returns what is
* missing; ipalKit refuses to start with it.
*/
export function missingTotpParts(config: Config, collection: string): string[] {
const target = (config.collections ?? []).find((c) => c.slug === collection)
const fields = (target?.fields ?? []) as Array<{ name?: string }>
const strategies = typeof target?.auth === 'object' ? (target.auth.strategies ?? []) : []
const missing: string[] = []
if (!fields.some((f) => f.name === 'totpSecret')) {missing.push('the `totpSecret` field')}
if (!fields.some((f) => f.name === 'hasTotp')) {missing.push('the `hasTotp` field')}
if (!strategies.some((s) => s.name === 'totp')) {missing.push('the `totp` auth strategy')}
return missing
}
+45 -3
View File
@@ -11,7 +11,7 @@ import { buildNotifications } from './globals/Notifications/index.js'
import { applyGlobalOverrides } from './globals/overrides.js'
import { buildSiteIntegrations } from './globals/SiteIntegrations/index.js'
import { buildSiteSettings } from './globals/SiteSettings/index.js'
import { adminOnly, adminOrSelf, injectRoles } from './modules/access/index.js'
import { adminOnly, adminOrSelfIn, injectRoles } from './modules/access/index.js'
import { applyAdminI18n } from './modules/admin-i18n/apply.js'
import { buildAdminImageEndpoints } from './modules/branding/adminImages.js'
import { buildAdminMeta, DEFAULT_AGENCY, syncAdminMeta } from './modules/branding/adminMeta.js'
@@ -33,6 +33,7 @@ import { buildGlobalRevalidateHook } from './modules/hooks/buildRevalidateHook.j
import { withFillLocales } from './modules/hooks/fillEmptyLocales.js'
import { buildLocalizationConfig, validateI18nConfig } from './modules/i18n/index.js'
import { buildSystemPagesFields } from './modules/pages/index.js'
import { guardConfigAccess, guardPayloadAccess, missingTotpParts } from './modules/security/totp/secondFactor.js'
import { TOTP_TEXTS, TOTP_VIEW_TITLE } from './modules/security/totp/totpTexts.js'
import { buildSeoPlugin, injectAutoFillMeta, injectSeoTabs } from './modules/seo/index.js'
import { buildIndexNowHook } from './modules/seo/indexNow.js'
@@ -125,9 +126,11 @@ export const ipalKit = (options: IpalOptions): Plugin => {
access: {
create: adminOnly,
delete: adminOnly,
read: adminOrSelf,
// "self" = an account of THIS collection: with numeric ids a customer
// account no. 5 must not match staff account no. 5.
read: adminOrSelfIn(authSlug),
unlock: adminOnly,
update: adminOrSelf,
update: adminOrSelfIn(authSlug),
...options.access?.authAccess,
},
}
@@ -152,6 +155,9 @@ export const ipalKit = (options: IpalOptions): Plugin => {
// or import it, so projects that opt out (twoFactor: false) needn't install it.
// Wrapping access control (not just admin UI) means TOTP gates data access —
// no API bypass.
// ipal-kit's own second-factor check (secondFactor.ts) covers what the 2FA
// package cannot: everything added to the config after the package ran.
let secondFactorGuard = false
if (options.twoFactor !== false) {
const tf = options.twoFactor
if (!tf?.issuer) {
@@ -203,6 +209,26 @@ export const ipalKit = (options: IpalOptions): Plugin => {
totp: { issuer: tf.issuer },
})(config)
// 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
// end of this function (and other plugins' in onInit). The guard reads the
// package's `totp` strategy and `hasTotp` field: when those are not there,
// this is a version it was not written for — refuse to start rather than
// run with a second factor that may protect nothing.
if (tf.guard !== false) {
const missing = missingTotpParts(config, target)
if (missing.length) {
throw new Error(
`[ipal] twoFactor: the injected 2FA plugin did not add ${missing.join(', ')} to "${target}". ` +
'ipal-kit enforces the second factor on its own globals and collections through them, so it ' +
'cannot do that with this version of @clocklimited/payload-2fa. Use a supported version, or pass ' +
'twoFactor.guard: false to rely on the package alone (docs/security.md — not recommended).',
)
}
secondFactorGuard = true
config.custom = { ...config.custom, ipal: { ...config.custom?.ipal, twoFactor: { collection: target } } }
}
// 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).
@@ -355,6 +381,10 @@ export const ipalKit = (options: IpalOptions): Plugin => {
// --- access: inject roles into the client's auth collection ---
if (options.access) {
config = injectRoles(config, options.access)
// Further staff collections for userMeetsRole (the panel's login collection always is one).
if (options.access.staffCollections?.length) {
config.custom = { ...config.custom, ipal: { ...config.custom?.ipal, staffCollections: options.access.staffCollections } }
}
}
// --- seo: apply @payloadcms/plugin-seo directly ---
@@ -596,10 +626,22 @@ export const ipalKit = (options: IpalOptions): Plugin => {
},
}
// --- second factor on everything in the config by now: the project's
// collections (wrapped by the package already; twice is harmless), the
// plugin's globals and collections, the form builder's.
if (secondFactorGuard) {
config = guardConfigAccess(config)
}
// --- hooks: onInit ---
const incomingOnInit = config.onInit
config.onInit = async (payload) => {
if (incomingOnInit) {await incomingOnInit(payload)}
// …and on what plugins listed after ipalKit added: they did not exist above.
if (secondFactorGuard) {
const late = guardPayloadAccess(payload)
if (late.length) {payload.logger.info(`[ipal] 2FA also enforced on entities added after ipalKit: ${late.join(', ')}.`)}
}
await migrateCookieSettingsSaveButton(payload)
await migrateTitleSeparator(payload, settingsSlug)
if (adminMeta) {await syncAdminMeta(payload, adminMeta, { nameField: brandFields.nameField, settingsSlug })}
+9
View File
@@ -231,6 +231,15 @@ export type IpalOptions = {
* injects). Must be an auth collection.
*/
collectionSlug?: CollectionSlug
/**
* ipal-kit's own second-factor check on every collection and global —
* also the ones added after the 2FA package ran (ipal-kit's own, other
* plugins') — and in `userMeetsRole`. On by default. `false` leaves only
* the package's wrapper, which does not cover those: a staff password
* without the TOTP code then reads them over the API. Only for a 2FA
* package version the check does not recognise; docs/security.md.
*/
guard?: false
/** Name shown in the authenticator app (e.g. company/site name). */
issuer: string
/**
+5 -4
View File
@@ -5,6 +5,7 @@ import { describe, expect, test, vi } from 'vitest'
import type { I18nConfig } from '../src/modules/i18n/types.js'
import { ipalKit } from '../src/plugin.js'
import { withTotpParts } from './helpers.js'
const i18n: I18nConfig = {
defaultLocale: 'pl',
@@ -17,9 +18,9 @@ const i18n: I18nConfig = {
const empty = (extra: Partial<Config> = {}): Config =>
({ collections: [], secret: 'x', ...extra }) as unknown as Config
const admin = { id: 1, roles: ['admin'] }
const editor = { id: 2, roles: ['editor'] }
const user = { id: 3, roles: ['user'] }
const admin = { id: 1, collection: 'users', roles: ['admin'] }
const editor = { id: 2, collection: 'users', roles: ['editor'] }
const user = { id: 3, collection: 'users', roles: ['user'] }
/** Runs a collection/global access function the way Payload does. */
const run = (fn: Access | undefined, u: unknown) =>
@@ -52,7 +53,7 @@ describe('injected auth collection', () => {
})
describe('2FA wraps the auth collection people log in with', () => {
const totp = () => vi.fn((_: unknown) => (c: Config) => c)
const totp = () => vi.fn((o: { collection: string }) => (c: Config) => withTotpParts(c, o.collection))
test('defaults to access.authCollection, not a literal "users"', async () => {
const plugin = totp()
+20
View File
@@ -13,6 +13,26 @@ import { vi } from 'vitest'
export const buildTestConfig = (config: Config) =>
buildConfig({ ...config, typescript: { ...config.typescript, autoGenerate: false } })
/**
* The parts of @clocklimited/payload-2fa that ipalKit checks for after the injected factory ran
* (missingTotpParts): the two fields and the `totp` strategy on the target collection.
* A fake 2FA factory in a test wraps its config in this.
*/
export function withTotpParts(config: Config, collection: string): Config {
return {
...config,
collections: (config.collections ?? []).map((c) =>
c.slug === collection
? {
...c,
auth: { ...(typeof c.auth === 'object' ? c.auth : {}), strategies: [{ name: 'totp', authenticate: () => ({ user: null }) }] },
fields: [...c.fields, { name: 'totpSecret', type: 'text' }, { name: 'hasTotp', type: 'checkbox', virtual: true }],
}
: c,
),
}
}
type FakeOptions = {
forms?: Record<string, { fields: Record<string, unknown>[] }>
integrations?: Record<string, unknown>
+89
View File
@@ -0,0 +1,89 @@
import type { SanitizedConfig } from 'payload'
import { GRAPHQL_POST, REST_DELETE, REST_GET, REST_PATCH, REST_POST } from '@payloadcms/next/routes'
import { AsyncLocalStorage } from 'node:async_hooks'
import { createServer, type Server } from 'node:http'
/**
* Payload's own REST and GraphQL route handlers (the ones a Next app mounts under /api) behind a real HTTP
* server, so a test sends real requests: login, cookies, `Authorization` headers.
*
* @clocklimited/payload-2fa reads and writes its cookie through `next/headers`, which only works inside a Next
* request. A test file that turns 2FA on mocks that module with `nextHeadersMock` below:
* vi.mock('next/headers.js', async () => (await import('./http/server.js')).nextHeadersMock)
*/
type CookieJar = { incoming: Map<string, string>; outgoing: string[] }
const jar = new AsyncLocalStorage<CookieJar>()
export const nextHeadersMock = {
cookies: () => {
const store = jar.getStore()
return Promise.resolve({
get: (name: string) => (store?.incoming.has(name) ? { name, value: store.incoming.get(name)! } : undefined),
set: (name: string, value: string) => {
store?.outgoing.push(`${name}=${value}; Path=/; HttpOnly`)
},
})
},
headers: () => Promise.resolve(new Headers()),
}
export type TestServer = { close: () => Promise<void>; url: string }
export async function startPayloadServer(config: Promise<SanitizedConfig>): Promise<TestServer> {
const rest = { DELETE: REST_DELETE(config), GET: REST_GET(config), PATCH: REST_PATCH(config), POST: REST_POST(config) }
const graphql = GRAPHQL_POST(config)
const server: Server = createServer((req, res) => {
const chunks: Buffer[] = []
req.on('data', (c: Buffer) => chunks.push(c))
req.on('end', () => {
void (async () => {
const url = new URL(req.url ?? '/', `http://${req.headers.host}`)
const headers = new Headers()
for (const [k, v] of Object.entries(req.headers)) {
if (typeof v === 'string') {headers.set(k, v)}
}
const method = (req.method ?? 'GET').toUpperCase()
const body = method === 'GET' || method === 'HEAD' ? undefined : Buffer.concat(chunks)
const request = new Request(url, { body, headers, method })
const incoming = new Map(
(req.headers.cookie ?? '').split(';').map((p) => p.trim()).filter(Boolean).map((p) => {
const i = p.indexOf('=')
return [p.slice(0, i), p.slice(i + 1)] as [string, string]
}),
)
const store: CookieJar = { incoming, outgoing: [] }
try {
const response = await jar.run(store, async () => {
if (url.pathname === '/api/graphql') {return graphql(request)}
const handler = rest[method as keyof typeof rest]
if (!handler) {return new Response('Method not allowed', { status: 405 })}
const slug = url.pathname.replace(/^\/api\/?/, '').split('/').filter(Boolean)
return handler(request, { params: Promise.resolve({ slug }) })
})
const setCookies = [...response.headers.getSetCookie(), ...store.outgoing]
response.headers.forEach((value, key) => {
if (key !== 'set-cookie') {res.setHeader(key, value)}
})
if (setCookies.length) {res.setHeader('set-cookie', setCookies)}
res.statusCode = response.status
res.end(Buffer.from(await response.arrayBuffer()))
} catch (err) {
res.statusCode = 500
res.end(err instanceof Error ? err.stack : String(err))
}
})()
})
})
await new Promise<void>((resolve) => server.listen(0, '127.0.0.1', resolve))
const address = server.address()
const port = typeof address === 'object' && address ? address.port : 0
return {
close: () => new Promise<void>((resolve) => server.close(() => resolve())),
url: `http://127.0.0.1:${port}`,
}
}
/** `name=value` pairs of a response's Set-Cookie headers, ready for a `cookie` request header. */
export const cookiesOf = (res: Response): string[] => res.headers.getSetCookie().map((c) => c.split(';')[0])
+15
View File
@@ -0,0 +1,15 @@
import { createHmac } from 'node:crypto'
/** RFC 6238 TOTP (SHA-1, 6 digits, 30 s) — the code an authenticator app shows for `secret` (base32). */
export function totp(secret: string, now = Date.now()): string {
const alphabet = 'ABCDEFGHIJKLMNOPQRSTUVWXYZ234567'
let bits = ''
for (const ch of secret.replace(/=+$/, '').toUpperCase()) {bits += alphabet.indexOf(ch).toString(2).padStart(5, '0')}
const key = Buffer.from((bits.match(/.{8}/g) ?? []).map((b) => parseInt(b, 2)))
const counter = Buffer.alloc(8)
counter.writeBigUInt64BE(BigInt(Math.floor(now / 1000 / 30)))
const hmac = createHmac('sha1', key).update(counter).digest()
const offset = hmac[hmac.length - 1] & 0xf
const code = (hmac.readUInt32BE(offset) & 0x7fffffff) % 1_000_000
return code.toString().padStart(6, '0')
}
+4 -2
View File
@@ -5,6 +5,7 @@ import { describe, expect, test, vi } from 'vitest'
import type { I18nConfig } from '../src/modules/i18n/types.js'
import { ipalKit } from '../src/plugin.js'
import { withTotpParts } from './helpers.js'
const i18n: I18nConfig = {
defaultLocale: 'pl',
@@ -40,7 +41,7 @@ describe('ipalKit — config transform', () => {
/no 2FA plugin was injected/,
)
const totp = vi.fn(() => (c: Config) => c)
const totp = vi.fn((o: { collection: string }) => (c: Config) => withTotpParts(c, o.collection))
await ipalKit({ i18n, twoFactor: { issuer: 'Acme', plugin: totp as never } })(base())
expect(totp).toHaveBeenCalledWith(expect.objectContaining({ forceSetup: true, totp: { issuer: 'Acme' } }))
})
@@ -119,7 +120,8 @@ describe('options that keep features reachable and overridable', () => {
test('without `access` (no roles field) admin and editor features stay reachable for logged-in users', async () => {
const config = await ipalKit({ consentLog: true, forms: {}, i18n, stats: true, twoFactor: false })(base())
const users = config.collections!.find((c) => c.slug === 'users')!
const req = (user: unknown) => ({ payload: { collections: { users: { config: users } } }, user }) as never
// `admin.user` is what Payload's sanitize fills in: the panel's login collection = the staff collection.
const req = (user: unknown) => ({ payload: { collections: { users: { config: users } }, config: { admin: { user: 'users' } } }, user }) as never
const member = { id: 1, collection: 'users', email: '[email protected]' }
const run = (access: unknown, user: unknown) => (access as (a: { req: unknown }) => unknown)({ req: req(user) })
+163
View File
@@ -0,0 +1,163 @@
/**
* The rules behind test/securityHttp.test.ts, one by one: who is staff (userMeetsRole), when the second
* factor counts as passed, and what ipalKit does with a 2FA plugin it does not recognise.
*/
import type { Access, Config } from 'payload'
import { describe, expect, test } from 'vitest'
import type { I18nConfig } from '../src/modules/i18n/types.js'
import { adminOrSelfIn } from '../src/modules/access/access.js'
import { staffCollectionSlugs, userMeetsRole } from '../src/modules/access/predicates.js'
import { guardPayloadAccess, requireSecondFactor, secondFactorPassed } from '../src/modules/security/totp/secondFactor.js'
import { ipalKit } from '../src/plugin.js'
import { withTotpParts } from './helpers.js'
const i18n: I18nConfig = { defaultLocale: 'pl', locales: [{ code: 'pl', label: 'Polski' }] }
const fakeTotp = (o: { collection: string }) => (c: Config) => withTotpParts(c, o.collection)
/** A payload as the access functions see it: sanitized `admin.user`, the collections by slug, `custom`. */
const payloadOf = (config: Config, adminUser = 'users') =>
({
collections: Object.fromEntries((config.collections ?? []).map((c) => [c.slug, { config: c }])),
config: { admin: { user: adminUser }, collections: config.collections, custom: config.custom, globals: config.globals },
}) as never
const twoAuth = (): Config =>
({
collections: [
{ slug: 'customers', auth: true, fields: [] },
{ slug: 'partners', auth: true, fields: [] },
],
secret: 'x',
}) as unknown as Config
describe('userMeetsRole: who is staff', () => {
test('with roles: the role decides; an account of another auth collection never passes', async () => {
const config = await ipalKit({ access: { authCollection: 'users' }, i18n, twoFactor: false })(twoAuth())
const payload = payloadOf(config)
expect(userMeetsRole({ payload, user: { collection: 'users', roles: ['admin'] } }, 'admin')).toBe(true)
expect(userMeetsRole({ payload, user: { collection: 'users', roles: ['user'] } }, 'editor')).toBe(false)
expect(userMeetsRole({ payload, user: { collection: 'customers' } }, 'user')).toBe(false)
expect(userMeetsRole({ payload, user: { collection: 'customers' } }, 'admin')).toBe(false)
expect(userMeetsRole({ payload, user: { collection: 'no-such-collection' } }, 'user')).toBe(false)
expect(userMeetsRole({ payload, user: null }, 'user')).toBe(false)
})
test('without `access`: every account of the panel collection passes, other auth collections do not', async () => {
const config = await ipalKit({ i18n, twoFactor: false })({ ...twoAuth(), admin: { user: 'users' } } as Config)
const payload = payloadOf(config)
expect(staffCollectionSlugs(payload)).toEqual(['users'])
expect(userMeetsRole({ payload, user: { collection: 'users' } }, 'admin')).toBe(true)
expect(userMeetsRole({ payload, user: { collection: 'customers' } }, 'admin')).toBe(false)
})
test('access.staffCollections names more staff collections, on purpose', async () => {
const config = await ipalKit({ access: { authCollection: 'users', staffCollections: ['partners'] }, i18n, twoFactor: false })(twoAuth())
const payload = payloadOf(config)
expect(staffCollectionSlugs(payload)).toEqual(['users', 'partners'])
expect(userMeetsRole({ payload, user: { collection: 'partners' } }, 'admin')).toBe(true) // no roles field there: all equal
expect(userMeetsRole({ payload, user: { collection: 'customers' } }, 'admin')).toBe(false)
})
test('without a payload only a held role counts', () => {
expect(userMeetsRole({ user: { collection: 'users' } }, 'user')).toBe(false)
expect(userMeetsRole({ user: { collection: 'users', roles: ['admin'] } }, 'admin')).toBe(true)
})
})
describe('adminOrSelfIn', () => {
const run = (fn: Access, user: unknown) => fn({ req: { user } } as never)
test('"self" is an account of that collection only', () => {
const access = adminOrSelfIn('users')
expect(run(access, { id: 5, collection: 'users', roles: ['user'] })).toEqual({ id: { equals: 5 } })
expect(run(access, { id: 5, collection: 'customers' })).toBe(false) // same id, other collection
expect(run(access, { id: 1, collection: 'users', roles: ['admin'] })).toBe(true)
expect(run(access, null)).toBe(false)
})
})
describe('secondFactorPassed', () => {
const payload = { config: { custom: { ipal: { twoFactor: { collection: 'users' } } } } } as never
const cases: [string, unknown, boolean][] = [
['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],
['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],
['an account of another auth collection', { _strategy: 'local-jwt', collection: 'customers' }, true],
]
test.each(cases)('%s', (_, user, expected) => {
expect(secondFactorPassed({ payload, user })).toBe(expected)
})
test('2FA off: everyone passes', () => {
expect(secondFactorPassed({ payload: { config: {} } as never, user: { _strategy: 'local-jwt', collection: 'users', hasTotp: true } })).toBe(true)
})
test('requireSecondFactor wraps once and keeps the inner rule', () => {
const inner: Access = ({ req }) => Boolean((req.user as { ok?: boolean } | null)?.ok)
const wrapped = requireSecondFactor(inner)
expect(requireSecondFactor(wrapped)).toBe(wrapped)
const call = (user: unknown) => wrapped({ req: { payload, user } } as never)
expect(call({ _strategy: 'totp', collection: 'users', hasTotp: true, ok: true })).toBe(true)
expect(call({ _strategy: 'totp', collection: 'users', hasTotp: true })).toBe(false)
expect(call({ _strategy: 'local-jwt', collection: 'users', hasTotp: true, ok: true })).toBe(false)
})
})
describe('ipalKit and the 2FA plugin', () => {
const passwordOnly = { id: 1, _strategy: 'local-jwt', collection: 'users', hasTotp: true, roles: ['admin'] }
const verified = { ...passwordOnly, _strategy: 'totp' }
test('every collection and global in the config is guarded, whenever it was added', async () => {
const config = await ipalKit({
access: { authCollection: 'users' }, consentLog: true, cookieScanner: { crawl: true }, forms: {}, i18n, stats: true,
twoFactor: { issuer: 'A', plugin: fakeTotp as never },
})({ collections: [{ slug: 'pages', fields: [] }], globals: [{ slug: 'own', fields: [] }], secret: 'x' } as unknown as Config)
const payload = payloadOf(config)
const open: string[] = []
const check = (kind: string, slug: string, access: Record<string, unknown> | undefined, ops: string[]) => {
for (const op of ops) {
const fn = access?.[op] as ((a: unknown) => unknown) | undefined
if (!fn || fn({ req: { payload, user: passwordOnly } }) !== false) {open.push(`${kind} ${slug}.${op}`)}
}
}
for (const c of config.collections ?? []) {check('collection', c.slug, c.access as never, ['create', 'delete', 'read', 'readVersions', 'unlock', 'update'])}
for (const g of config.globals ?? []) {check('global', g.slug, g.access as never, ['read', 'readDrafts', 'readVersions', 'update'])}
expect(open).toEqual([])
// and a verified admin still gets in
const integrations = config.globals!.find((g) => g.slug === 'site-integrations')!
expect((integrations.access!.read as (a: unknown) => unknown)({ req: { payload, user: verified } })).toBe(true)
})
test('onInit guards what a later plugin added; Payload\'s own collections are left alone', () => {
const late = { slug: 'late', access: {} as Record<string, unknown> }
const internal = { slug: 'payload-preferences', access: {} as Record<string, unknown> }
const payload = { config: { collections: [late, internal], custom: { ipal: { twoFactor: { collection: 'users' } } }, globals: [] } } as never
expect(guardPayloadAccess(payload)).toEqual(['late'])
expect((late.access.read as (a: unknown) => unknown)({ req: { payload, user: passwordOnly } })).toBe(false)
expect(internal.access.read).toBeUndefined()
expect(guardPayloadAccess(payload)).toEqual([]) // nothing left to do the second time
})
test('a 2FA plugin without the parts the guard relies on stops the start', async () => {
const unknown = () => (c: Config) => c
const run = (guard?: false) =>
ipalKit({ i18n, twoFactor: { issuer: 'A', plugin: unknown as never, ...(guard === false ? { guard } : {}) } })({ collections: [], secret: 'x' } as unknown as Config)
await expect(run()).rejects.toThrow(/did not add the `totpSecret` field, the `hasTotp` field, the `totp` auth strategy/)
// twoFactor.guard: false = the package alone, as before
const config = await run(false)
expect((config.custom as { ipal?: { twoFactor?: unknown } } | undefined)?.ipal?.twoFactor).toBeUndefined()
})
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)
const read = config.globals!.find((g) => g.slug === 'site-integrations')!.access!.read as (a: unknown) => unknown
expect(read({ req: { payload, user: { collection: 'users', roles: ['admin'] } } })).toBe(true)
})
})
+258
View File
@@ -0,0 +1,258 @@
/**
* Who reaches what the plugin adds, through real HTTP requests (REST and GraphQL) against a running Payload:
* - a staff account that typed only its password (TOTP set up, code not entered) gets nothing;
* - an account of another auth collection (`customers`) gets no more than an anonymous visitor;
* - a fully verified staff account, an account that still has to set TOTP up, and an API key keep working.
*/
import type { CollectionConfig, Config, Payload, Plugin } from 'payload'
import { payloadTotp } from '@clocklimited/payload-2fa'
import { sqliteAdapter } from '@payloadcms/db-sqlite'
import { lexicalEditor } from '@payloadcms/richtext-lexical'
import os from 'os'
import path from 'path'
import { getPayload } from 'payload'
import { afterAll, beforeAll, describe, expect, test, vi } from 'vitest'
import { ipalKit } from '../src/plugin.js'
import { buildTestConfig } from './helpers.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 TOTP_SECRET = 'JBSWY3DPEHPK3PXP'
const PASSWORD = 'a-long-test-password-1'
/** A plugin the project lists AFTER ipalKit: its collection did not exist when ipalKit ran. */
const latePlugin: Plugin = (config: Config) => ({
...config,
collections: [...(config.collections ?? []), { slug: 'late-notes', fields: [{ name: 'note', type: 'text' }] }],
})
const projectCollections: CollectionConfig[] = [
// A visitor account collection with open sign-up — a shop or a client zone.
{ slug: 'customers', access: { create: () => true }, auth: true, fields: [] },
{ slug: 'pages', fields: [{ name: 'title', type: 'text' }] },
{ slug: 'media', fields: [], upload: { staticDir: path.join(os.tmpdir(), 'ipal-test-media') } },
]
const PROJECT_SLUGS = new Set(['customers', 'media', 'pages'])
type Session = { headers: Record<string, string> }
let server: TestServer
let payload: Payload
let pluginCollections: string[]
let pluginGlobals: string[]
const sessions = {} as Record<'anonymous' | 'customer' | 'newcomer' | 'passwordOnly' | 'verified', Session>
const api = (pathname: string, session: Session, init: RequestInit = {}) =>
fetch(`${server.url}/api${pathname}`, {
...init,
headers: { 'content-type': 'application/json', ...session.headers, ...(init.headers as Record<string, string>) },
})
const gql = async (session: Session, query: string) => {
const res = await api('/graphql', session, { body: JSON.stringify({ query }), method: 'POST' })
return (await res.json()) as { data?: null | Record<string, unknown>; errors?: { message: string }[] }
}
async function login(collection: string, email: string): Promise<{ cookies: string[]; token: string }> {
const res = await fetch(`${server.url}/api/${collection}/login`, {
body: JSON.stringify({ email, password: PASSWORD }),
headers: { 'content-type': 'application/json' },
method: 'POST',
})
const body = (await res.json()) as { token?: string }
if (!body.token) {throw new Error(`login failed for ${email}: ${JSON.stringify(body)}`)}
return { cookies: cookiesOf(res), token: body.token }
}
beforeAll(async () => {
const config = buildTestConfig({
admin: { user: 'users' }, // the panel logs in with the staff collection, not with `customers`
collections: projectCollections,
db: sqliteAdapter({ client: { url: 'file::memory:' }, push: true }),
editor: lexicalEditor(),
plugins: [
ipalKit({
access: { authCollection: 'users' },
consentLog: true,
cookieScanner: { crawl: true },
forms: {},
i18n: { defaultLocale: 'pl', locales: [{ code: 'pl', label: 'Polski' }] },
stats: true,
twoFactor: { issuer: 'Example', plugin: payloadTotp },
}),
latePlugin,
],
secret: 'integration-test-secret-0123456789',
telemetry: false,
})
payload = await getPayload({ config })
server = await startPayloadServer(config)
pluginCollections = payload.config.collections.map((c) => c.slug).filter((s) => !PROJECT_SLUGS.has(s) && !s.startsWith('payload-'))
pluginGlobals = payload.config.globals.map((g) => g.slug)
await payload.updateGlobal({ slug: 'site-integrations' as never, data: { smtpPassword: 'S3CRET' } as never })
const user = (email: string, extra: object) =>
payload.create({ collection: 'users' as never, data: { email, password: PASSWORD, roles: ['admin'], ...extra } as never })
await user('[email protected]', { totpSecret: TOTP_SECRET })
await user('[email protected]', {})
await payload.create({ collection: 'customers' as never, data: { email: '[email protected]', password: PASSWORD } as never })
sessions.anonymous = { headers: {} }
sessions.passwordOnly = { headers: { authorization: `JWT ${(await login('users', '[email protected]')).token}` } }
sessions.newcomer = { headers: { authorization: `JWT ${(await login('users', '[email protected]')).token}` } }
sessions.customer = { headers: { authorization: `JWT ${(await login('customers', '[email protected]')).token}` } }
// The full login: password, then the code from the authenticator app → the 2FA cookie.
const full = await login('users', '[email protected]')
const verify = await fetch(`${server.url}/api/verify-totp`, {
body: JSON.stringify({ token: totp(TOTP_SECRET) }),
headers: { 'content-type': 'application/json', cookie: full.cookies.join('; ') },
method: 'POST',
})
const verified = (await verify.json()) as { message?: string; ok: boolean }
expect(verified, JSON.stringify({ cookies: full.cookies.map((c) => c.slice(0, 30)), verified })).toMatchObject({ ok: true })
sessions.verified = { headers: { cookie: [...full.cookies, ...cookiesOf(verify)].join('; ') } }
}, 120_000)
afterAll(async () => {
await server?.close()
await payload?.destroy?.()
})
const readStatus = async (kind: 'collection' | 'global', slug: string, s: Session) =>
(await api(kind === 'collection' ? `/${slug}` : `/globals/${slug}`, s)).status
const writeStatus = async (kind: 'collection' | 'global', slug: string, s: Session) =>
(await api(kind === 'collection' ? `/${slug}` : `/globals/${slug}`, s, { body: '{}', method: 'POST' })).status
describe('what the test set up', () => {
test('the plugin added the entities this file is about', () => {
expect(pluginCollections).toEqual(expect.arrayContaining(['users', 'forms', 'form-submissions', 'consent-records', 'cookie-review', 'stats-visits', 'late-notes']))
expect(pluginGlobals).toEqual(expect.arrayContaining(['site-settings', 'site-integrations', 'cookie-settings', 'notifications', 'cookie-crawl']))
})
})
describe('REST: a staff password without the TOTP code opens nothing', () => {
test('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.passwordOnly)) !== 403) {open.push(`read ${kind} ${slug}`)}
if ((await writeStatus(kind, slug, sessions.passwordOnly)) !== 403) {open.push(`write ${kind} ${slug}`)}
}
}
expect(open).toEqual([])
})
test('the SMTP password is not returned', async () => {
const res = await api('/globals/site-integrations', sessions.passwordOnly)
expect(res.status).toBe(403)
expect(await res.text()).not.toContain('S3CRET')
})
test("the plugin's own endpoints refuse too", async () => {
expect((await api('/ipal/test-email', sessions.passwordOnly, { body: JSON.stringify({ to: '[email protected]' }), method: 'POST' })).status).toBe(403)
expect((await api('/ipal/cookie-scan', sessions.passwordOnly)).status).toBe(403)
expect((await api('/ipal/cookie-scan', sessions.passwordOnly, { body: '{}', method: 'POST' })).status).toBe(403)
expect((await api('/ipal/cookie-crawl', sessions.passwordOnly)).status).toBe(403)
expect((await api('/ipal/cookie-approval', sessions.passwordOnly, { body: '{}', method: 'POST' })).status).toBe(403)
})
})
describe('GraphQL: a staff password without the TOTP code opens nothing', () => {
test.each([
['Site integrations', '{ SiteIntegration { smtpPassword } }'],
['form submissions', '{ FormSubmissions { totalDocs } }'],
['consent records', '{ ConsentRecords { totalDocs } }'],
['stats', '{ StatsVisits { totalDocs } }'],
['cookie review', '{ CookieReviews { totalDocs } }'],
['Site settings (write)', 'mutation { updateSiteSetting(data: { siteName: "x" }) { siteName } }'],
['Notifications (write)', 'mutation { updateNotification(data: {}) { updatedAt } }'],
])('%s', async (_, query) => {
const out = await gql(sessions.passwordOnly, query)
expect(out.errors?.length, JSON.stringify(out)).toBeGreaterThan(0)
expect(JSON.stringify(out)).not.toContain('S3CRET')
expect(Object.values(out.data ?? {}).filter((v) => v !== null)).toEqual([])
})
})
describe('an account of another auth collection (customers) is not staff', () => {
test('REST: it gets exactly what an anonymous visitor gets, nothing more', async () => {
const more: string[] = []
for (const [kind, slugs] of [['collection', pluginCollections.filter((s) => s !== 'late-notes')], ['global', pluginGlobals]] as const) {
for (const slug of slugs) {
const read = [await readStatus(kind, slug, sessions.customer), await readStatus(kind, slug, sessions.anonymous)]
if (read[0] !== read[1]) {more.push(`read ${kind} ${slug}: customer ${read[0]}, anonymous ${read[1]}`)}
// Creating a form submission over REST is open to every logged-in account (unchanged, see forms.md).
if (kind === 'collection' && slug === 'form-submissions') {continue}
const write = [await writeStatus(kind, slug, sessions.customer), await writeStatus(kind, slug, sessions.anonymous)]
if (write[0] !== write[1]) {more.push(`write ${kind} ${slug}: customer ${write[0]}, anonymous ${write[1]}`)}
}
}
expect(more).toEqual([])
})
test('REST: Site integrations, submissions, consent records and stats are refused', async () => {
for (const p of ['/globals/site-integrations', '/form-submissions', '/consent-records', '/stats-visits', '/cookie-review', '/globals/cookie-crawl']) {
expect([p, (await api(p, sessions.customer)).status]).toEqual([p, 403])
}
expect((await api('/globals/site-settings', sessions.customer, { body: JSON.stringify({ siteName: 'x' }), method: 'POST' })).status).toBe(403)
expect((await api('/ipal/test-email', sessions.customer, { body: JSON.stringify({ to: '[email protected]' }), method: 'POST' })).status).toBe(403)
expect((await api('/ipal/cookie-scan', sessions.customer)).status).toBe(403)
})
test('GraphQL: the same', async () => {
for (const query of ['{ SiteIntegration { smtpPassword } }', '{ FormSubmissions { totalDocs } }', '{ ConsentRecords { totalDocs } }', 'mutation { updateSiteSetting(data: { siteName: "x" }) { siteName } }']) {
const out = await gql(sessions.customer, query)
expect(out.errors?.length, `${query} → ${JSON.stringify(out)}`).toBeGreaterThan(0)
expect(JSON.stringify(out)).not.toContain('S3CRET')
}
})
test('its own collection still works for it', async () => {
expect((await api('/customers/me', sessions.customer)).status).toBe(200)
})
})
describe('what must keep working', () => {
test('a fully verified admin reads and writes everything (REST)', async () => {
const closed: string[] = []
for (const [kind, slugs] of [['collection', [...pluginCollections, 'pages']], ['global', pluginGlobals]] as const) {
for (const slug of slugs) {
const status = await readStatus(kind, slug, sessions.verified)
if (status !== 200) {closed.push(`read ${kind} ${slug}: ${status}`)}
}
}
expect(closed).toEqual([])
const integrations = (await (await api('/globals/site-integrations', sessions.verified)).json()) as { smtpPassword?: string }
expect(integrations.smtpPassword).toBe('S3CRET')
expect((await api('/globals/site-settings', sessions.verified, { body: JSON.stringify({ siteName: 'Verified' }), method: 'POST' })).status).toBe(200)
expect((await api('/ipal/cookie-scan', sessions.verified)).status).toBe(200)
// 400 = past the login and role gates, stopped by the missing recipient
expect((await api('/ipal/test-email', sessions.verified, { body: '{}', method: 'POST' })).status).toBe(400)
})
test('a fully verified admin reads Site integrations (GraphQL)', async () => {
const out = await gql(sessions.verified, '{ SiteIntegration { smtpPassword } FormSubmissions { totalDocs } }')
expect(out.errors).toBeUndefined()
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])
}
expect((await api('/globals/site-integrations', sessions.anonymous)).status).toBe(403)
})
})
+79
View File
@@ -0,0 +1,79 @@
/**
* The documented non-interactive paths keep working with 2FA on (real HTTP, see securityHttp.test.ts):
* an API key of a staff account, and the bearer token of GET /api/ipal/doctor.
*/
import type { Payload } from 'payload'
import { payloadTotp } from '@clocklimited/payload-2fa'
import { sqliteAdapter } from '@payloadcms/db-sqlite'
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 { startPayloadServer, type TestServer } from './http/server.js'
vi.mock('server-only', () => ({}))
vi.mock('next/headers.js', async () => (await import('./http/server.js')).nextHeadersMock)
const API_KEY = 'b7f0c3a2-5d1e-4f6a-9c8b-0e1d2f3a4b5c'
const DOCTOR_TOKEN = 'doctor-token-0123456789-0123456789-abcdef'
let server: TestServer
let payload: Payload
beforeAll(async () => {
process.env.IPAL_DOCTOR_TOKEN = DOCTOR_TOKEN
const config = buildTestConfig({
collections: [
// The project's own staff collection, with API keys.
{ slug: 'users', auth: { useAPIKey: true }, fields: [] },
{ slug: 'media', fields: [], upload: { staticDir: path.join(os.tmpdir(), 'ipal-test-media') } },
],
db: sqliteAdapter({ client: { url: 'file::memory:' }, push: true }),
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)
await payload.create({
collection: 'users' as never,
data: { apiKey: API_KEY, email: '[email protected]', enableAPIKey: true, password: 'a-long-test-password-1', roles: ['admin'], totpSecret: 'JBSWY3DPEHPK3PXP' } as never,
})
}, 120_000)
afterAll(async () => {
delete process.env.IPAL_DOCTOR_TOKEN
await server?.close()
await payload?.destroy?.()
})
const get = (pathname: string, authorization?: string) =>
fetch(`${server.url}/api${pathname}`, { headers: authorization ? { authorization } : {} })
test('an API key of an admin account reads Site integrations and form submissions without a TOTP code', async () => {
const key = `users API-Key ${API_KEY}`
expect((await get('/globals/site-integrations', key)).status).toBe(200)
expect((await get('/form-submissions', key)).status).toBe(200)
expect((await get('/users', key)).status).toBe(200)
expect((await get('/globals/site-integrations', 'users API-Key wrong-key')).status).toBe(403)
})
test('GET /api/ipal/doctor answers its bearer token, and nobody else', async () => {
const ok = await get('/ipal/doctor', `Bearer ${DOCTOR_TOKEN}`)
expect(ok.status).toBe(200)
expect(await ok.json()).toMatchObject({ usersWithout2fa: 0 })
expect((await get('/ipal/doctor')).status).toBe(401)
expect((await get('/ipal/doctor', 'Bearer not-the-token-0123456789-0123456789')).status).toBe(401)
})
+3 -2
View File
@@ -5,12 +5,13 @@ import { describe, expect, test } from 'vitest'
import { bottomOverlap } from '../src/modules/consent/CookieButton.js'
import { TOTP_TEXTS } from '../src/modules/security/totp/totpTexts.js'
import { ipalKit } from '../src/plugin.js'
import { withTotpParts } from './helpers.js'
const i18n = { defaultLocale: 'pl', locales: [{ code: 'pl', label: 'Polski' }, { code: 'en', label: 'English' }] }
/** Stand-in for @clocklimited/payload-2fa: its own texts and the two views, as the package adds them. */
const fakeTotp = () => (config: Config) => ({
...config,
const fakeTotp = (o: { collection: string }) => (config: Config) => ({
...withTotpParts(config, o.collection),
admin: {
...config.admin,
components: {
+2
View File
@@ -21,6 +21,8 @@ export default defineConfig(() => {
include: ['test/**/*.test.ts'],
hookTimeout: 30_000,
testTimeout: 30_000,
// Inlined so a test can replace `next/headers` (the package's cookie access) — test/http/server.ts.
server: { deps: { inline: ['@clocklimited/payload-2fa'] } },
},
}
})