Compare commits

...
31 Commits
Author SHA1 Message Date
Radosław SmolińskiandClaude Opus 5.5 bc0fa65fd7 1.16.7 upgrade notes
CI / check (push) Failing after 5m54s
CI / reference (push) Skipped
CI / reference-full (push) Skipped
Co-Authored-By: Claude Opus 5.5 <[email protected]>
2026-11-25 00:40:20 +01:00
Radosław SmolińskiandClaude Opus 5.5 14c44d082d 1.16.7
Co-Authored-By: Claude Opus 5.5 <[email protected]>
2026-11-25 00:40:07 +01:00
Radosław SmolińskiandClaude Opus 5.5 7b2a2759ab Merge claude/security-m1-hardening (rebased): write-only secrets, account rules, password rule, 2FA attempts
Co-Authored-By: Claude Opus 5.5 <[email protected]>
2026-11-25 00:39:30 +01:00
Radosław SmolińskiandClaude Fable 5.2 8a01c72c2a M1 review round 3: a built-site e2e for a late staff collection (both bundlers); docs follow
Co-Authored-By: Claude Fable 5.2 <[email protected]>
2026-11-25 00:39:24 +01:00
Radosław SmolińskiandClaude Fable 5.2 6e0ad26b2c M1 review round 3: late staff collections without guessing Payload's default; rules survive a dev reload
R3-1 nothing is decided by a function's name any more (a production build renames it): on a collection that
     arrives after ipalKit the plugin's rule is put in FRONT of the rule that is there and both must allow
     (bothAllow). unlock follows the same table. The log says exactly what was put.
R3-2 the adoption walks the live config (payload.config), which Payload swaps first on a dev reload.
R3-3 readVersions gets the read rule on staff collections.
R3-5 a secret that is not text is refused.
Also: the async check of requireSetup.exempt compares the constructor, not its name.

Co-Authored-By: Claude Fable 5.2 <[email protected]>
2026-11-25 00:39:24 +01:00
Radosław SmolińskiandClaude Fable 5.2 3e44863c98 M1 review round 2: docs, agent guide, skills, changelog; the reference types without the removed field
Co-Authored-By: Claude Fable 5.2 <[email protected]>
2026-11-25 00:39:24 +01:00
Radosław SmolińskiandClaude Fable 5.2 7002ebbfa6 M1 review round 2: the transport is no way round, nobody raises its own role, late staff collections
R2-1 the SMTP password is bound to server, port and user whatever the transport says; the transport alone is not bound.
R2-2 where the plugin's update rule is in force the roles field is closed for the account itself
     (the plugin's roles: only an admin; roles of the project's own: never one's own).
R2-3 auth collections a later plugin adds get the account rules, the password rule and the first-user endpoint when
     the config goes live; a staff slug that is not an auth collection stops the start.
R2-4 smtpRequireTls is taken out: the branch adds no field, column or collection.
Also: read (a staff account) and unlock (an admin) defaults on staff collections (accounts.staffOnlyRead);
doctor staff-own-roles and read / unlock in staff-accounts-open; r1 NULL against the default, also inside a row;
r2 bound values compared exactly.

Co-Authored-By: Claude Fable 5.2 <[email protected]>
2026-11-25 00:39:24 +01:00
Radosław SmolińskiandClaude Fable 5.2 a32329fbb4 M1 review: reference site types and an e2e check of the bound SMTP password
Co-Authored-By: Claude Fable 5.2 <[email protected]>
2026-11-25 00:39:23 +01:00
Radosław SmolińskiandClaude Fable 5.2 fd203de326 M1 review: docs, agent guide, skills and changelog follow the fixes
Co-Authored-By: Claude Fable 5.2 <[email protected]>
2026-11-25 00:39:23 +01:00
Radosław SmolińskiandClaude Fable 5.2 1141c749de M1 review: account rules before 2FA, the SMTP password stays with its server, the rest of the findings
M1-1 the first-user route is the plugin's own endpoint in front of Payload's; nothing is read from the path.
M1-2 the account rules are put on the collections before the 2FA package wraps them.
M1-6 the admin rule only where the roles are the plugin's; other staff collections: an account of that collection.
     update / delete get the matching defaults (accounts.adminOnlyWrite); doctor rule staff-accounts-open.
M1-5 access.firstUserAdmin: false with a role below the panel role: the default panel role steps aside, an explicit one is refused.
M1-3 a save that changes the SMTP server, port, user or encryption must send the password again (secrets.reenterOnChange);
     new panel field smtpRequireTls.
M1-4 a restore of a version masks the secrets (maskSecretsOnRestore).
M1-7 a refused origin is logged once with the ways to allow it; default ports are normalised.
Minors: m1 day boundary, m3 e-mail check on reset and bulk update, m4 text of 'all', m5 the mask is never kept.
The account suite runs with 2FA off and on.

Co-Authored-By: Claude Fable 5.2 <[email protected]>
2026-11-25 00:39:23 +01:00
Radosław SmolińskiandClaude Fable 5.2 81cee02e78 M1: the reference e2e suite follows the stored 2FA verify count
The verify count now survives a restart of the site, so the specs can no longer
share one test admin across server runs: create-test-admin.ts makes two test
admins and clears their stored counts; the setup spec signs in as the second.
The whole suite passes in one run (20 passed, 1 skipped).

Co-Authored-By: Claude Fable 5.2 <[email protected]>
2026-11-25 00:39:23 +01:00
Radosław SmolińskiandClaude Fable 5.2 83356ab4ed M1: docs, agent guide, skills and changelog for the hardening items
security.md (stored secrets, own-origin 2FA attempts, stored verify count,
dashboard alerts by role), access.md (account rules: panel role, no
self-registration, passwords), turnstile.md (the deprecated env secret,
forms.turnstileOnConfigError), doctor.md (five new rules, the deep status),
AGENT.md, ipal-setup, ipal-upgrade, ipal-debug, ipal-reference (+ api.md),
ipal-doctor and their mirrors, PROGRAMISTA row 69, CHANGELOG under an unreleased
heading with "Requires project changes".

Co-Authored-By: Claude Fable 5.2 <[email protected]>
2026-11-25 00:39:23 +01:00
Radosław SmolińskiandClaude Opus 5.5 cff355a541 Merge claude/docs-isadmin-client-import: role checks importable in client components
Co-Authored-By: Claude Opus 5.5 <[email protected]>
2026-11-25 00:39:12 +01:00
Radosław SmolińskiandClaude Fable 5.2 f7296edc71 M1 (8): 2FA attempts only from the own origin; the verify count is stored
R3-2. (b) POST /api/verify-totp and /api/setup-totp refuse a request that a
browser marks as coming from another origin (Origin, Sec-Fetch-Site) — before it
is counted, so another page (a sibling subdomain included) cannot burn an
account's attempts and lock its owner out. Own origins: the request's host,
serverURL, Payload's csrf / cors lists, twoFactor.sameOrigin.origins; requests
without those headers pass. twoFactor.sameOrigin: false turns it off.
(a) The verify count is kept in memory (exact for parallel bursts) and in
Payload's key-value store (payload.kv, no new collection), so a restart or a
second instance does not reset it; the higher count decides, and a failing store
never opens the gate. verifyLimit.store: 'memory' = this instance only.
Doctor: csrf-empty (static, warning) when neither serverURL nor csrf is set.

Co-Authored-By: Claude Fable 5.2 <[email protected]>
2026-11-25 00:39:12 +01:00
Radosław SmolińskiandClaude Fable 5.2 0b4c4e8295 M1 (9): dashboard alerts by role
IntegrationAlerts reads the admin-only Site integrations global with access
control off and showed its error texts to everyone who opened the dashboard.
Now: an admin sees what is failing and the link, an editor a neutral "an
integration needs attention — ask an administrator", anyone else nothing.
CookieCrawlAlert is shown to editors and above (the role that may read the crawl
result). Both use userMeetsRole, so a session that still owes its second factor
sees neither. dashboardAlerts: { integrations: 'admin' | 'editor' | 'all',
cookies: 'editor' | 'all' } loosens it.

Co-Authored-By: Claude Fable 5.2 <[email protected]>
2026-11-25 00:39:12 +01:00
Radosław SmolińskiandClaude Fable 5.2 5d35b2c3f4 M1 (7): a password rule for staff accounts (accounts.password)
When a password is set on a staff collection — a new account, the first-user
screen, a change, a reset by e-mail; panel, API and Local API alike — it must
have at least 12 characters and not be the account's own e-mail address.
Existing passwords are never checked: a shorter one keeps logging in and meets
the rule when it is next changed. accounts.password: { minLength } | false.
No breached-password lookup; checkPassword and the hook are exported.

Co-Authored-By: Claude Fable 5.2 <[email protected]>
2026-11-25 00:39:12 +01:00
Radosław SmolińskiandClaude Fable 5.2 c6fc0d21fe M1 (6): nobody creates an account for themselves
accounts.adminOnlyCreate (on): a staff collection without a create rule gets
"an admin, fully signed in" instead of Payload's "any logged-in user" — also the
project's own collection; a rule the project wrote stays.
accounts.firstUserRoute ('panel'): Payload's first-user route answers only for
the collection the panel logs in with. For any other empty auth collection it is
refused, unless that collection's own create rule lets an anonymous request in.
Checked and closed: an empty second staff collection, whose first visitor became
a staff admin (test/accountRulesOff.test.ts records the old behaviour, which
accounts: false / firstUserRoute: 'all' still give).
Doctor: open-signup (deep, info) names auth collections with open sign-up.

Co-Authored-By: Claude Fable 5.2 <[email protected]>
2026-11-25 00:39:12 +01:00
Radosław SmolińskiandClaude Fable 5.2 cd60b73685 M1 (5): the lowest role stays out of the admin panel (accounts.panelRole)
The panel opens for editor and above by default: Payload's access.admin on the
collection that carries the roles. An account that holds only `user` sees
"Unauthorized" there; the API is not touched. The rule looks at the role, not
at the second factor, so the 2FA screens stay reachable. accounts.panelRole:
'user' | false (everyone, as before) | 'admin'; accounts: false turns the account
rules off; the project's own access.admin wins. At start the log says how many
accounts the rule keeps out, and is an error when it keeps everyone out.

Co-Authored-By: Claude Fable 5.2 <[email protected]>
2026-11-25 00:39:12 +01:00
Radosław SmolińskiandClaude Fable 5.2 463fd5d664 M1 (4): forms.turnstileOnConfigError — a form with files is refused while Turnstile cannot check
While Turnstile is degraded (wrong or missing secret, Cloudflare down) a text
form is still accepted, as before; a submission to the file endpoint is refused
by default. forms.turnstileOnConfigError sets it for every form or per kind
('allow' | 'reject' | { text, files }); a value at a call site still wins.
Nothing changes when Turnstile is off. The gates and the resolver are exported
from the server entry.

Co-Authored-By: Claude Fable 5.2 <[email protected]>
2026-11-25 00:39:12 +01:00
Radosław SmolińskiandClaude Fable 5.2 42fdad8c2d M1 (2, 3): the Turnstile env secret is deprecated; doctor rules access-missing, turnstile-degraded, turnstile-env-key
(2) Stage one of the deprecation: TURNSTILE_SECRET_KEY from the environment still
works when the panel field is empty, logs once that it is deprecated, and the
doctor's deep status reports it (rule turnstile-env-key, warning). Nothing is
removed.
(3) access-missing (static, warning): ipalKit without `access` means every panel
account is an admin. turnstile-degraded (deep): Turnstile is not checking forms —
warning, error after a day. The deep status carries the recorded state and where
the secret comes from, never a key.

Co-Authored-By: Claude Fable 5.2 <[email protected]>
2026-11-25 00:39:12 +01:00
Radosław SmolińskiandClaude Fable 5.2 8fa71238ce M1 (1): stored secrets are write-only
smtpPassword and turnstileSecretKey in the Site integrations global are returned
as '********' to every read that goes through access control (REST, GraphQL, the
panel's form state); the Local API with access control off still gets the value.
A save that sends nothing, an empty value or the mask keeps the stored one;
'[[clear]]' removes it. MaskedField says that a value is set and offers to
remove it. Off: secrets: { writeOnly: false }. writeOnlySecret(s) and the hooks
are exported for a project's own fields.

Co-Authored-By: Claude Fable 5.2 <[email protected]>
2026-11-25 00:39:12 +01:00
Radosław SmolińskiandClaude Opus 5.5 de414a81a8 Role checks in client components: export them from /client, fix the docs
access.md and the 1.16.4 upgrade notes led projects to import isAdmin from
'@intecion/ipal-kit' in a client component; with `next build --webpack` that
fails ('server-only' cannot be imported from a Client Component module).
No existing entry had a client-safe one, so '@intecion/ipal-kit/client' now
exports hasMinimumRole, isAdmin, isEditor and the type Role; the main entry
keeps them for server code.

Docs: access.md (snippet with imports, server vs client, useConfig() carries
admin.user only), AGENT.md, ipal-debug, ipal-reference, ipal-upgrade, the
1.16.4 note, an Unreleased changelog entry. Tests: /client reaches no
server-only module, the predicates' answers with a client config, no
client-component example in the docs imports the main entry.

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

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

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

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

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

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

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

Co-Authored-By: Claude Fable 5.2 <[email protected]>
2026-11-24 18:46:32 +01:00
Radosław SmolińskiandClaude Fable 5.2 2aaaaa115a 2FA setup required: an account without TOTP reaches only setup, within a 72 h window
twoFactor.requireSetup (on by default with 2FA): an account of the 2FA
collection that has not set TOTP up is refused by ipal-kit's second-factor
check on every collection, global and plugin endpoint; the setup screen and
/api/setup-totp are all it reaches. It has 72 hours from its creation or
from an admin's reset (field totpSetupFrom, stamped by a hook); after that
setup is refused too until an admin reopens it.

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

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

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

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

Co-Authored-By: Claude Fable 5.2 <[email protected]>
2026-11-24 18:46:32 +01:00
113 changed files with 7379 additions and 260 deletions
+299 -2
View File
@@ -8,6 +8,301 @@ versions at once, go through every "Requires project changes" section in order,
version you have. A new release = a new section at the top; we remove the oldest ones only
once there are more than 20.
## 1.16.7 — hardening
> **Read before upgrading.** Several defaults get stricter. Most sites change nothing, but check
> "Requires project changes". What can stop people: an account with only the role `user` can no longer open the
> panel; a form with files is refused while Turnstile is misconfigured; a script that creates staff accounts
> with a password under 12 characters fails; behind a proxy that hides the site's address and without
> `serverURL` nobody can enter a 2FA code; a project's own staff collection without access rules gets rules;
> changing the SMTP server in the panel asks for the password again; a slug in `access.staffCollections` that
> is not an auth collection keeps Payload from starting (with a health check the old container keeps serving).
> Not a routine patch: agree the deploy with the owner and read the first start's log. No import-map change,
> **no schema change and no migration** on any database.
### Security
- **A secret that is not text is refused** (`false`, `0`, a list, an object used to be stored as typed).
- **Stored secrets are write-only.** `smtpPassword` and `turnstileSecretKey` (Site integrations) were returned
by REST and GraphQL, and sent to the browser by the panel, for everyone who could read that global; the
"masked" field only drew dots. Now every read through access control gets `'********'` when a value is stored;
only server code (the Local API with access control off) reads the value. A save that sends nothing, an empty
value or the mask keeps the stored value; `'[[clear]]'` removes it. The panel is the source of these secrets
([security.md](./security.md) "Stored secrets").
- **The SMTP password stays with the server it was saved for.** Hiding the value was not enough: an admin
session could point the SMTP server at a machine of its own and have a test e-mail deliver the password. A
save in the panel or over the API that changes the server, the port or the user name while a password is
stored must now send the password again, or remove it (`secrets.reenterOnChange`) — whatever the transport
says (the mail adapter falls back to SMTP when Microsoft Graph is not configured). Server code with the Local
API is not asked.
- **Restoring a version of Site integrations** (only where a project turned versions on for that global)
answered with the stored secrets; they are masked there too (`maskSecretsOnRestore`).
- **Nobody creates an account for themselves, or takes one over.** (1) Payload's first-user route
(`POST /api/<slug>/first-register`) answers for every empty auth collection. On an empty **second staff
collection** (`access.staffCollections`) the first visitor became a staff account — an admin to the plugin.
It now answers only for the collection the panel logs in with, in any spelling of the URL (the plugin's own
endpoint sits in front of Payload's). (2) A project's **own** staff collection without `create`, `update` or
`delete` rules had Payload's default, "any logged-in user" — an account of any auth collection: a visitor
account could create a staff account, or change a staff account's password and roles. Such a collection now
gets rules for the operations it has none for: with the plugin's roles — an admin (update: or the account
itself); with role values of its own, or none — an account of that same collection, or a plugin admin.
`unlock` gets the admin rule and `read` "a staff account" (a visitor account could list the staff accounts
and lift their login lock). An account never changes its **own** roles: the collection's `roles` field, when
it has no field access of its own, is closed for that. `readVersions` gets the `read` rule (versions hold
what the accounts hold). The rules hold with 2FA on and off, in a production build, and for a staff
collection that a plugin listed after ipalKit adds — there they are put in front of whatever rules that
collection has (in a sanitized config Payload's default cannot be told from a rule somebody wrote). Anonymous sign-up into the staff collection was already refused; the
plugin's injected collection already had these rules. No known site has a second staff collection
([access.md](./access.md) "Account rules").
- **2FA verify and setup attempts only from the site's own origin.** A page on another origin that the browser
still sends the login cookie to (a sibling subdomain, when neither `serverURL` nor `csrf` is set) could burn an
account's five verify attempts and lock its owner out, without the password. Such requests are refused before
they are counted. A refusal is logged once per origin with the ways to allow it. **The verify count is also
stored in the database**, so a restart or a second instance no longer resets it.
- **Dashboard alerts no longer show integration error texts to every panel role**: details for admins, a neutral
line for editors, nothing for others or for a session that still owes its second factor (`'all'` restores the
old behaviour and checks neither).
### Changed
- **The admin panel opens for `editor` and above** (`accounts.panelRole`). An account that holds only `user`
sees "Unauthorized" in the panel; the API is not touched. With `access.firstUserAdmin: false` and a default
role below the panel role the first account of a fresh site could not get in: the default panel role is then
not applied (a warning at start), and an explicit `accounts.panelRole` is refused at start with the fix.
- **A password set on a staff account has at least 12 characters** and is not the account's e-mail address
(`accounts.password`) — also in a reset by e-mail and a bulk update. Existing passwords are never checked.
- **A form with files is refused while Turnstile cannot check** (wrong or missing secret, Cloudflare down); a
text form is accepted as before (`forms.turnstileOnConfigError`).
- **`TURNSTILE_SECRET_KEY` from the environment is deprecated.** It still works when the panel field is empty
and logs a notice once per start. It will be removed in a later release, named here in advance.
### Fixes
- **Role checks in a client component: import `isAdmin`, `isEditor` and `hasMinimumRole` (and the type `Role`) from
`@intecion/ipal-kit/client`.** The advice since 1.16.4 led to importing them from `@intecion/ipal-kit`, which reaches
`server-only` modules: `next build --webpack` fails with `'server-only' cannot be imported from a Client Component
module`. The main entry keeps exporting them for server code; its Turbopack behaviour is unchanged. access.md also
says now what `useConfig()` carries: `admin.user` only, so accounts of `access.staffCollections` need
`{ staffCollections: [...] }`.
### Added
- Options: `accounts` (`panelRole`, `adminOnlyCreate`, `adminOnlyWrite`, `staffOnlyRead`, `firstUserRoute`,
`password`), `secrets.writeOnly`, `secrets.reenterOnChange`, `forms.turnstileOnConfigError`,
`twoFactor.sameOrigin`, `twoFactor.verifyLimit.store`, `dashboardAlerts`.
- ipal-doctor rules: `access-missing` (no `access` option: every panel account is an admin), `csrf-empty`
(neither `serverURL` nor `csrf`), and with `--url`: `open-signup` (info), `staff-accounts-open` (error; warning
for `read` and `readVersions`: a staff collection an account of another collection may write to, read or unlock),
`staff-own-roles` (warning: a staff collection with role values of its own and no rules), `turnstile-degraded`
(warning, error after 24 hours), `turnstile-env-key`. The deep status gained `openSignUp`, `staffOnOwnRoles`,
`staffOpenToOthers`, `turnstile`,
`turnstileSecretFromEnv` (states and slugs, never a key).
- Exports: `writeOnlySecret`, `writeOnlySecrets`, `SECRET_MASK`, `SECRET_CLEAR`, `maskSecretAfterRead`,
`keepSecretBeforeValidate`, `buildKeepSecret`, `isSecretMask`, `INTEGRATION_SECRET_FIELDS`,
`SMTP_PASSWORD_BOUND_TO`, `maskSecretsOnRestore`, `maskWriteOnlySecrets`; `panelAccess`, `applyPanelRole`,
`resolvePanelRole`, `countBelowPanelRole`, `DEFAULT_PANEL_ROLE`; `staffCreateAccess`, `staffUpdateAccess`,
`staffReadAccess`, `sameStaffCollectionAccess`, `rolesByAdminOnly`, `rolesNotOwn`, `bothAllow`, `hasPluginRoles`,
`applyStaffAccountAccess`, `adoptLateAuthCollections`, `unknownStaffCollections`, `buildFirstUserEndpoint`,
`applyFirstUserRoute`, `openSignUpCollections`, `staffCollectionsOpenToOthers`, `staffCollectionsOnOwnRoles`; `checkPassword`,
`buildPasswordRuleHook`, `applyPasswordRule`, `resolvePasswordRule`, `DEFAULT_PASSWORD_MIN_LENGTH`;
`requestFromOwnOrigin`, `ownOrigins`, `reportRefusedOrigin`; `buildVerifyLimit`, `verifyLimitKey`, `clearVerifyLimits`;
`turnstileSecretFromEnv`, `TURNSTILE_SECRET_ENV`; from `/server`: `passTurnstile`, `passSubmitGates`,
`resolveTurnstileOnConfigError`, `TURNSTILE_ON_CONFIG_ERROR_DEFAULT`.
- `MaskedField` says "A value is set" for a write-only field and offers "Remove the stored value".
### Requires project changes (what projects must update)
- **No migration.** This release adds no field, column, table or collection of its own on any database. The
stored 2FA attempt count uses Payload's own `payload-kv` collection, which every schema of a Payload version
that has `payload.kv` already contains; where it cannot be reached the count stays in memory and the limit
still holds.
- **A slug in `access.staffCollections` (or `access.authCollection`) that is not an auth collection of the
config: Payload does not start.** The log says `[ipal] access names "…" as a staff collection, but this config
has no auth collection with that slug` and lists the auth collections. The process stays up, but every Payload
call fails: `/api/health` answers 503, `/api/*` and the panel 500 (a page that needs no Payload call may still
answer). With a health check ([deployment.md](./deployment.md) §4.4) Coolify keeps the old container. Check
the slugs before the deploy. (A plugin listed after ipalKit may add the collection.)
- **A staff collection added by a plugin listed after ipalKit**: the plugin's rules are put in front of the
rules that collection has, so both must allow — a rule of its own there can only narrow, not widen. To keep
its rules exactly as they are: `custom: { ipal: { accountRules: false } }` on that collection.
- **Set `serverURL`** if it is not set. Behind a reverse proxy that rewrites `Host` and sends no
`X-Forwarded-Host` (nginx's plain `proxy_pass`; Coolify / Traefik keep `Host`) the server does not know its
own address, and the 2FA code page is refused as "another origin": **nobody can enter a code**. The log says
`[ipal] 2FA: a code from origin "…" was refused` once per origin, with the fix. Other ways out:
`twoFactor: { …, sameOrigin: { origins: ['https://…'] } }`, or make the proxy send `X-Forwarded-Host`.
- **Every site: read the first start's log.** `[ipal] N account(s) of "users" are below the role "editor" and
cannot open the admin panel` — give the people who work in the panel `editor`, or set
`accounts: { panelRole: 'user' }`. `NOBODY can open the admin panel` (an error): no account has the role —
a script with the Local API (`roles: ['admin']`), or `accounts: { panelRole: false }` and redeploy.
- **Own code that read `smtpPassword` / `turnstileSecretKey` over REST or GraphQL**, or with
`overrideAccess: false`: it now gets `'********'`. Read them on the server with
`payload.findGlobal({ slug: 'site-integrations' })`. Nothing to do otherwise: stored values stay, e-mail and
Turnstile keep working.
- **A site whose Turnstile secret is only in `TURNSTILE_SECRET_KEY`:** nothing breaks. With the owner, move the
key into Site integrations → Spam protection, then remove the variable (`ipal-doctor --url` →
`turnstile-env-key`).
- **Forms with a File field:** make sure Turnstile works (`ipal-doctor --url` → no `turnstile-degraded`); while
it does not, those forms are refused. To keep accepting them: `forms: { turnstileOnConfigError: { files: 'allow' } }`.
- **A project's own staff collection without `create` / `update` / `delete` / `unlock` / `read` / `readVersions`
rules** gets
them. With the plugin's roles (`access.authCollection`, or a `roles` select with only `user` / `editor` /
`admin`): only an admin creates, deletes and unlocks accounts and changes roles; an account is changed by an
admin or by itself — if non-admins did that on your site, write the rule you want. With **role values of its
own** (`superadmin`, …) or no roles: accounts of that collection keep working as before, except that an
account no longer changes its **own** roles; accounts of other collections are refused. The plugin does not
know your roles, so write your own rules (`ipal-doctor --url` → `staff-own-roles`). `read`: only staff
accounts read a staff collection — **a front end that shows staff accounts to logged-in visitors** (an author
box read with a customer's session) needs its own `read` rule or `accounts: { staffOnlyRead: false }`. Off:
`accounts: { adminOnlyCreate: false, adminOnlyWrite: false, staffOnlyRead: false }`. `first-register` for other auth collections: `403` unless the collection allows
sign-up, or `accounts: { firstUserRoute: 'all' }`.
- **`access.firstUserAdmin: false`** with `access.defaultRole` below `editor`: the panel role is not applied (a
warning at start); with `accounts.panelRole` set the start fails — set `access.defaultRole: 'editor'` or
`accounts: { panelRole: false }`.
- **A script that changes the SMTP server, port or user name over REST / GraphQL** must send the password with
it (`400` "Enter the password again…" otherwise); a seed with the Local API is not asked. In the panel the
person types the password again. `secrets: { reenterOnChange: false }` turns it off.
- **A rolling update:** a Site integrations page opened under the new version and saved against the old one
stores `********` as the password. After the deploy send a test e-mail.
- **Scripts that create staff accounts with a password under 12 characters** fail with a validation error.
Existing accounts with short passwords keep logging in.
- **A panel or front end on another domain that posts to `/api/verify-totp`:**
`twoFactor: { …, sameOrigin: { origins: ['https://…'] } }`.
- **Only if a `'use client'` file imports `isAdmin`, `isEditor` or `hasMinimumRole` from `@intecion/ipal-kit`:**
change the import to `@intecion/ipal-kit/client` and keep the second argument (`isAdmin(user, config)`).
`grep -rlE "^['\"]use client" src | xargs grep -nE "from '@intecion/ipal-kit'"` lists the files; `import type` may stay.
- `pnpm payload generate:types`, `pnpm ipal:skills`.
### Known limitations
- Write-only protects the API and the panel, not the database: the two secrets are stored in plain text there
and in backups (encryption at rest is not part of this release). A secret equal to `********` or `[[clear]]`
cannot be stored. A session that may send e-mail can still use the mailbox through the site (send, not
read). On a port other than 465 the SMTP connection is encrypted only when the server offers STARTTLS, as
before; an option to require it is not part of this release.
- The account rules for a staff collection with role values of its own do not enforce those roles: an account
cannot change its own roles, but inside the collection every account may still create an account with any
role, and change or delete another account — the plugin cannot rank roles it does not know. Write the
collection's own rules; `staff-own-roles` in the doctor names such a collection.
- An account of a staff collection **without a `roles` field** is an admin to the plugin (unchanged): it may
manage accounts of the other staff collections too. Give every staff collection roles, or its own rules.
- The panel role and the password rule need `access` (roles) resp. a staff collection with password login; a
second staff collection without a `roles` field is not affected by `panelRole`.
- The stored verify count uses Payload's `payload.kv`; on a Payload version without it the count is in memory
only. Two instances can each let a few attempts through before the other's write lands ("max per instance" at
worst, never unlimited).
- The own-origin check trusts `Host` / `X-Forwarded-Host` as the proxy sets them, and passes requests without
`Origin` and `Sec-Fetch-Site` (non-browser clients).
- `access-missing` and `csrf-empty` are text searches of the config file and can miss or misread unusual
spellings; `open-signup` and `staff-accounts-open` call the access rules with a made-up request and count a
rule that throws as closed.
- A plugin listed after ipalKit that **copies** a staff collection of the config under a new slug
(`{ ...staff, slug: 'copy' }`) copies the rules made for the original slug with it: accounts of other
collections are refused, but "the account itself" means an account of the original collection. Give such a
copy its own `access.update`.
- **Not run for this release:** the built site and the panel were checked in Chromium on MongoDB only (the access
rules over HTTP ran on SQLite, Postgres and MongoDB); no real mail server, no second instance, no third-party
plugin that adds an auth collection.
## 1.16.6
> **Read before upgrading — this is not a routine patch.** It turns on a new default for every site with 2FA: an
> account that has not set 2FA up can do nothing but set it up, and is **blocked after 72 hours** until an
> administrator reopens it. On Postgres / SQLite it also needs a **migration in the same deploy, or nobody can log
> in**. Work through the list below, and agree the deploy day with the owner.
### Requires project changes (what projects must update)
**Every site with 2FA on. Do all of it in ONE deploy.**
- **Before upgrading a live site:** `pnpm exec ipal-doctor --url <site>` → accounts without 2FA. Each sets 2FA up
now, or is removed. At least one administrator (better two) must have 2FA set up, or nobody can reopen setup
from the panel.
- **Agree the day with the owner:** the 72 hours of every existing account without 2FA start at the deploy,
once. Deploy when those people can act within three days (not before a holiday), or have them set 2FA up first.
- **In the same deploy:** the update, `pnpm payload generate:types`, `pnpm payload generate:importmap` (commit
`importMap.js`; new: `TwoFactorStatusField`, `TwoFactorAlert`), `rm -rf .next`, redeploy. Run
`pnpm exec ipal-doctor` before deploying: it reports a map without the new entries (then the panel has no "Reopen
setup"). Coming from before 1.16.5, the map must also have `SafeTotpView`, or the 2FA screens have no code form.
- **Postgres / SQLite — required, in the same deploy: `pnpm payload migrate:create`, commit, and the migration
applied when the new container starts** (`prodMigrations`, or `pnpm payload migrate && pnpm start` —
[deployment.md §4.3](./deployment.md#43-database-migrations-postgres); not Coolify's Pre-deployment command,
which runs in the old container). The 2FA collection gets the column `totp_setup_from`.
**Without it every login answers 500 — administrators with 2FA included — and nobody can sign in to the
panel.** The log says so at start (`NOBODY CAN LOG IN`), and `ipal-doctor` reports a SQL project whose
migrations do not mention the column. Every project with 2FA on needs it, also with `requireSetup: false`.
MongoDB: nothing.
- **An integration that logs in with a password and has no TOTP** stops working: give it an API key (passes as
before) or exempt it on purpose: `twoFactor.requireSetup: { exempt: ({ user }) => user.email === '…' }`.
- **Own code** calling `payload.find({ …, user, overrideAccess: false })` with a user fetched by id: refused for
every account of the 2FA collection now (before: only accounts with TOTP set up). Use `payload.auth({ headers })`.
- **A reset by an administrator logs that account out everywhere** and needs the administrator's own TOTP code. A
script on an API key needs `twoFactor.resetAccess`. After a suspected compromise change the password too.
- **Options:** `windowHours` is a number (0 or more) or `false`; `exempt` is a plain function returning exactly
`true`, never `async`. A wrong value stops the build and the start with a clear error.
- **After deploy:** read the log line `[ipal] 2FA: N existing account(s) without two-step verification…` and tell
the owner; after 72 hours such an account needs "Reopen setup" from an administrator. Tell the staff: a new account has
72 hours to set 2FA up. `pnpm ipal:skills`.
- **An SVG favicon** has no tab icon on the 2FA screens (use a PNG if that matters).
- **Every administrator is blocked:** security.md "Every administrator is blocked" (a script, or
`{ windowHours: false }` and a redeploy).
- **Not wanted on a site:** `twoFactor.requireSetup: false` (the previous behaviour), or
`{ windowHours: false }` to keep the lock without the time limit. Sites with `twoFactor: false` are not affected.
### Changed
- **An account without two-step verification can only set it up** (`twoFactor.requireSetup`, on by default with
2FA). Until now the panel redirected such an account to the setup screen, but over the API (REST, GraphQL) its
password alone opened everything its role allowed. Now every collection, global and plugin endpoint refuses it
until TOTP is set up; the setup screen and `POST /api/setup-totp` are all it reaches.
- **A setup window of 72 hours**, counted from the account's creation or from a reset by an administrator. After
it the account is blocked — setup is refused too — until an administrator reopens it. This limits how long an
account that never set 2FA up can be taken over by someone who learned its password.
- **Accounts that already exist** get their 72 hours from the **first start after the upgrade** (not from their
creation date), so nobody is blocked at the moment of the upgrade. The server log names how many there are.
That moment is written on each account once: later restarts, redeploys and further instances do not move it,
nor does editing the account.
- **A reset by an administrator ends the account's sessions**, and by default needs a session that entered its
own TOTP code (not an API key, not an exempt account).
- **`/api/ipal/admin-icon` answers with the favicon itself when it is a bitmap** (PNG, JPEG, GIF, WebP, ICO,
AVIF — recognised by its bytes) instead of a redirect, so the tab icon also loads on the 2FA screens. An SVG
favicon is never answered from there (an SVG can carry script): it keeps the redirect to the media file.
`adminMeta.serveIcon: false` = always the redirect. `buildUploadSecurityHeaders()` now also returns a rule for
the icon path (`adminIcon: false` leaves it out).
### Added
- On every account in the panel: **Two-step verification** (sidebar) — set up / open until a date / blocked — and
for administrators "Reset two-step verification" (a lost phone) and "Reopen setup" (a blocked account).
`POST /api/ipal/two-factor/reset` `{ userId }` does the same.
- A dashboard notice for administrators: accounts without two-step verification, and how many are blocked.
- A notice on the setup screen: until when setup has to be done, or that the time has passed. All texts in
English and Polish.
- Options: `twoFactor.requireSetup: false | { windowHours, exempt, dashboardNotice, statusField, setupNotice }`,
`twoFactor.resetAccess`, `whiteLabel.inlineImages`, `adminMeta.serveIcon`. Exports: `twoFactorSetupState`,
`twoFactorSetupDeadline`, `buildSetupFields`, `stampSetupFrom`, `backfillSetupFrom`,
`buildTwoFactorResetEndpoint`, `countAccountsWithoutTotp`, `resolveRequireSetup`, `strictExempt`,
`SETUP_FROM_FIELD`, `TWO_FACTOR_RESET_PATH`, `DEFAULT_SETUP_WINDOW_HOURS`, `fetchPublicImage`,
`publicImageDataUri`, `rasterImageType`, `siteOrigin`, `PUBLIC_IMAGE_MAX_BYTES`, `UPLOAD_SECURITY_HEADERS`; admin components
`TwoFactorStatusField`, `TwoFactorResetButton`, `TwoFactorAlert`.
- `requireSetup.exempt` is strict: only an answer of exactly `true` exempts. An `async` function, and a
`windowHours` that is not a number or `false`, stop the site at start with a clear error.
- The date field `totpSetupFrom` is on the 2FA collection whenever 2FA is on, so switching `requireSetup` or
`guard` never changes the schema (and never restarts anyone's window).
- The panel's tab icon and logo load on the verify and setup screens: `GET /api/ipal/admin-icon` answers with the
image itself when it is a bitmap (no redirect to the media file), and the logo components give a session that still owes its code
the picture as an anonymous visitor would get it. No change to who can read `media`.
- ipal-doctor: a SQL project without a migration for `totp_setup_from` (error), an import map without the two
new admin components (error).
- ipal-doctor: the `2fa` rule says how many accounts without 2FA are blocked (`usersSetupClosed` in the deep
status), warns when `requireSetup` is switched off and notes a missing setup window.
### Known limitations
- **Inside the window** someone who knows the password of an account without 2FA can still set it up with their own
authenticator; the owner is then refused ("already set") and has to ask an administrator. Set 2FA up at once.
- A session without 2FA keeps what Payload gives any session about itself: `/api/access`, token refresh, logout, its own
panel preferences.
- **An exempt account** works on its password alone, with everything its role allows: give it the lowest role.
- A second staff collection (`access.staffCollections`) is outside 2FA and outside this mode, as before. With
`twoFactor.guard: false` the mode is off and the reset endpoint does not exist.
- With `auth.useSessions: false` a reset has no sessions to end: tokens live until they expire. The 2FA package's own
remove / reset endpoints do not end sessions.
- The `ipal-doctor` migration check is a text search in `src/migrations` and `migrations`.
- A site that does not use `buildUploadSecurityHeaders()` still serves a scripted SVG from its media URL as before.
- **Not run for this release:** a generated migration, `prodMigrations` and a real Coolify deploy (the missing and the
added column were tested on Postgres 17 and SQLite); an upgrade of a real site; two containers; media on R2 / S3;
`useSessions: false`; the reset by an API-key admin over HTTP; payload-2fa beta.1 and the Polish notices in a
browser; Firefox / WebKit; a Docker image; a Next `basePath`; Payload below 3.94.1.
## 1.16.5
### Security
@@ -176,8 +471,10 @@ once there are more than 20.
authenticator still works; if it does not, reset that account's 2FA and set it up again.
- **`isAdmin` / `isEditor` / `hasMinimumRole` in a client component or in `proxy.ts` / middleware** return `false`
unless they are told which collections are staff: `isAdmin(user, config)` with the config from `useConfig()`, or
`isAdmin(user, { staffCollections: ['users'] })`. On the server (`isAdmin(req.user)` in hooks, endpoints, access
functions) nothing changes; `isAdmin(req.user, req.payload)` is the explicit form.
`isAdmin(user, { staffCollections: ['users'] })`. A client component imports them from `@intecion/ipal-kit/client`
(corrected later: the main entry, which this note implied, does not build there with webpack; `/client` has them
since 1.16.7). On the server (`isAdmin(req.user)` in hooks, endpoints, access functions) nothing
changes; `isAdmin(req.user, req.payload)` is the explicit form.
- **A second staff collection (`access.staffCollections`) is not covered by 2FA** — the log says so at start.
- **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, and its
+180 -7
View File
@@ -23,7 +23,7 @@ ipalKit({
|---|---|---|
| `access.authCollection` | — (required) | the auth collection that gets the `roles` field |
| `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.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 — then mind the panel role, [Account rules](#account-rules-accounts) |
| `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 |
@@ -84,8 +84,8 @@ The plugin's own staff features — Site integrations, the settings globals, for
stats, the cookie scanner, `/api/ipal/test-email` — check with `userMeetsRole(req, minimum)`, in this order:
1. the account belongs to a staff collection;
2. with 2FA on: an account that has TOTP set up has entered the code in this session
([security.md](./security.md) → "What the second factor covers");
2. with 2FA on: the account has set TOTP up and has entered the code in this session
([security.md](./security.md) → "What the second factor covers", "Setup required");
3. it holds at least the role `minimum` — **or** its collection has no `roles` field at all. Then every account
of that staff collection passes, as in Payload's default (without roles all accounts are equal).
@@ -135,16 +135,31 @@ which collections are staff:
| Where you call it | Pass | Without it |
|---|---|---|
| access functions, hooks, endpoints (server, the config is loaded) | `req.payload` | works: the staff collections of the config `ipalKit` built in this process. With two different configs in one process, only collections that are staff in **both** count — pass `req.payload` to get that config's own answer |
| client components | the config from `useConfig()` (it has `admin.user`), or `{ staffCollections: ['users', …] }` | **always `false`** — the browser bundle has no config |
| client components — import from **`@intecion/ipal-kit/client`** | the config from `useConfig()` (it has `admin.user`, the panel's login collection), or `{ staffCollections: ['users', …] }` | **always `false`** — the browser bundle has no config |
| Next middleware / `proxy.ts`, the edge runtime | `{ staffCollections: ['users'] }` | **always `false`** — the config is not loaded there |
```tsx
'use client'
const { config } = useConfig()
const { user } = useAuth()
if (isAdmin(user, config)) { /* show the button — a hint only, the server decides */ }
import { isAdmin } from '@intecion/ipal-kit/client' // not '@intecion/ipal-kit'
import { useAuth, useConfig } from '@payloadcms/ui'
export function AdminOnlyHint() {
const { config } = useConfig()
const { user } = useAuth()
// a hint only — the server decides
return isAdmin(user, config) ? <p>…</p> : null
}
```
- **The import in a client component is `/client`** (`hasMinimumRole`, `isAdmin`, `isEditor`, the type `Role`). The main
entry reaches `server-only` modules: with `next build --webpack` it fails with `'server-only' cannot be imported from
a Client Component module` (Turbopack builds it, but the import does not belong there either).
In 1.16.4–1.16.6 `/client` does not have them — upgrade.
- **On the server** (config, hooks, access functions, endpoints, server components, `proxy.ts`) import from
`@intecion/ipal-kit`: `/client` is a `'use client'` entry, a server component that calls a function from it fails.
- `useConfig()` carries `admin.user` only (Payload strips `config.custom` from the client config). Accounts of
`access.staffCollections` need the list: `isAdmin(user, { staffCollections: ['users', 'partners'] })`.
They fail closed: where the staff collections are not known, nobody is staff, and an account without
`collection` is nobody. `isAdmin` and the others do **not** check the second factor; `userMeetsRole` and every
`access` function in the config do.
@@ -209,8 +224,166 @@ applyGlobalOverrides(globals, { notifications: { … } }) // the same logic as
Types: `AccessOption`, `Role`, `GlobalOverride`, `GlobalOverrides`, `IpalGlobalSlug`.
## Account rules (`accounts`)
Rules for the accounts of the staff collection. All on by default; each has its own switch, and
`ipalKit({ accounts: false })` turns them all off.
```ts
ipalKit({
access: { authCollection: 'users' },
// accounts: { panelRole: 'user' }, // every account may open the panel (as before)
// accounts: { adminOnlyCreate: false }, // Payload's default `create` on your own staff collection
// accounts: { adminOnlyWrite: false }, // Payload's default `update` / `delete` / `unlock` there, roles field left alone
// accounts: { staffOnlyRead: false }, // Payload's default `read` there
// accounts: { firstUserRoute: 'all' }, // Payload's first-user route for every empty auth collection
// accounts: { firstUserRoute: ['users', 'partners'] },
// accounts: { password: { minLength: 16 } }, // or password: false
// accounts: false, // none of the rules
})
```
### Who may open the panel (`accounts.panelRole`, default `'editor'`)
The lowest role, `user`, is what a new account gets (`access.defaultRole`) and has no business in the panel. The
panel opens for `editor` and above: it is Payload's `access.admin` on the collection that carries the roles. An
account that holds only `user` (or no role) logs in and sees Payload's "Unauthorized" screen. **The API is not
touched** — such an account still gets over REST / GraphQL what its role allows. The rule looks at the role, not
at the second factor, so the 2FA screens stay reachable.
- **What an existing site sees on the first start:** the log line `[ipal] N account(s) of "users" are below the
role "editor" and cannot open the admin panel` — give those people `editor`, or set `panelRole: 'user'`. When
**no** account has the role it is an error (`NOBODY can open the admin panel`): give one account the role with
a script (`payload.update`, Local API) or set `accounts: { panelRole: false }` and redeploy.
- `'admin'` = admins only; `'user'` or `false` = everyone, as before. Needs `access` (the roles). Your own
`access.admin` on the collection, or `access.authAccess.admin`, wins. Building blocks: `panelAccess(role)`,
`applyPanelRole`, `resolvePanelRole`, `countBelowPanelRole`, `DEFAULT_PANEL_ROLE`.
- **Check:** log in to `/admin` as an account with the role `user` → "Unauthorized"; `GET /api/access` for it →
`canAccessAdmin: false`; `GET /api/users/me` still answers.
### Nobody creates an account for themselves, or takes one over (`accounts.adminOnlyCreate`, `accounts.adminOnlyWrite`, `accounts.staffOnlyRead`, `accounts.firstUserRoute`)
By default only the first account of a site can be registered by a visitor, and it becomes admin
(`access.firstUserAdmin`); every other account is made by an admin, and an account is changed by an admin or by
its owner.
Payload's default for a collection without access rules is "any logged-in user" for `create`, `read`, `update`,
`delete` and `unlock` — an account of **any** auth collection. On a project's own staff collection a visitor
account (`customers`) could therefore create a staff account, `PATCH` a staff account's password and roles,
list the staff accounts, and lift the lock after failed logins.
| | Before | Now (default) |
|---|---|---|
| Anonymous `POST /api/users`, GraphQL `createUser` | refused | refused |
| The first account: `POST /api/users/first-register` on an empty collection | 200, role `admin` | the same |
| A signed-in editor or plain user creates an account in the plugin's injected collection | refused | refused |
| …in **the project's own** staff collection that has no `create` rule | **allowed** (Payload's default) | refused — an admin, fully signed in |
| A visitor account (`customers`) changes or deletes an account of the project's own staff collection that has no `update` / `delete` rule | **allowed** (Payload's default) | refused |
| A visitor account lists the accounts of such a collection, or unlocks one | **allowed** (Payload's default) | refused |
| An account of such a collection changes its **own** `roles` (the field has no access of its own) | **allowed** | refused — with the plugin's roles only an admin changes roles |
| `POST /api/<slug>/first-register` on another empty auth collection (`members`) | **200** | 403 |
| …on an empty **second staff collection** (`access.staffCollections`) | **200, and that account was staff** | 403 — an admin of the panel's collection creates its first account |
| A collection that allows sign-up (`customers` with `create: () => true`) | allowed | allowed, its first-user route too |
**Which rule a staff collection gets** (the panel's login collection, `access.authCollection`,
`access.staffCollections`) — only for an operation it has **no** rule for; a rule you wrote always stays:
| The collection | `create`, `delete`, `unlock` | `update` | the `roles` field (when it has no `access.update`) | `read`, `readVersions` |
|---|---|---|---|---|
| carries **the plugin's roles**: it is `access.authCollection`, or has a `roles` select whose values are all `user` / `editor` / `admin` (`hasPluginRoles`) | an admin (`staffCreateAccess`) | an admin, or the account itself (`staffUpdateAccess(slug)`) | only an admin changes it (`rolesByAdminOnly`) | a staff account (`staffReadAccess`) |
| has **roles of its own** (`superadmin`, `writer`, …) or no `roles` field — the plugin cannot tell who its admins are | an account of that same collection, or a plugin admin of another staff collection (`sameStaffCollectionAccess(slug)`) | the same | an account never changes its **own** (`rolesNotOwn(slug)`) | a staff account |
Always "fully signed in": a session that still owes its second factor passes none of them.
**Roles of your own — what the plugin does and does not hold.** It cannot rank `superadmin` against `writer`,
so inside such a collection it enforces one thing only: an account does not change its own roles. Everything
else that was allowed inside the collection stays allowed — **every account of it may still create an account
with any role, and change or delete another account**. That is a hole only you can close: write the
collection's `create` / `update` / `delete` rules and the field access of its `roles` field from your roles.
`ipal-doctor --url` names such a collection (`staff-own-roles`, warning). What the plugin closes for you is the
door for accounts of **other** collections.
**A staff collection without a `roles` field:** every account of it is an admin to the plugin (unchanged), so
it may also manage the accounts of the other staff collections. Give it the plugin's roles
(`buildRolesField`), or write its rules.
**A staff collection that a plugin listed after ipalKit adds** gets the same rules, the password rule and the
first-user endpoint when the config goes live — at start and on every dev reload. The log says exactly what was
put: `[ipal] "late-staff" was added after ipalKit: put on it — access rules for create, update, delete, unlock,
read, readVersions, roles; the password rule; the first-user endpoint.` One difference from a collection of your
own config: by then Payload has sanitized the collection and filled every missing rule with its default, and
that default cannot be told from a rule somebody wrote (a production build renames every function). So the
plugin does not guess: **its rule is put in front of whatever rule is there, and both must allow**
(`bothAllow`). With Payload's default behind it the result is the plugin's rule; a rule of the collection's own
is kept and can only narrow it. To keep a late collection's rules exactly as they are — an open `create`, a
wider `read` — say so on the collection: `custom: { ipal: { accountRules: false } }` (the password rule and the
first-user endpoint still apply), or list that plugin before ipalKit.
**A slug in `access.staffCollections` or `access.authCollection` that is not an auth collection of the config:**
Payload does not start. The log names the slug and the auth collections it knows. The process stays up, but
every Payload call fails — `/api/health` answers 503, `/api/*` and the panel 500; a page that needs no Payload
call may still answer. With a health check ([deployment.md](./deployment.md) §4.4) Coolify keeps the old
container serving, so a wrong slug never goes live (`unknownStaffCollections`).
- `adminOnlyCreate: false` = Payload's default `create`; `adminOnlyWrite: false` = Payload's default `update`,
`delete` and `unlock`, and the `roles` field is left alone; `staffOnlyRead: false` = Payload's default `read`.
The rules are put on the collections **before** the 2FA package wraps them, so they hold with 2FA on and off.
- `read` = "a fully signed-in account of a staff collection": staff sees staff (the panel needs it for
relationship fields and the account list), a visitor account sees nothing. The injected collection keeps its
stricter "admin or self". **A front end that shows staff accounts to logged-in visitors** needs its own `read`
rule on that collection (a rule you wrote wins), or `staffOnlyRead: false`.
- `firstUserRoute`: `'panel'` (default) = the collection the panel logs in with; a list of slugs = those;
`'all'` = Payload's behaviour. A collection whose own `create` rule lets an anonymous request through keeps
its route. The plugin puts its own `POST /first-register` endpoint in front of Payload's on every auth
collection (`buildFirstUserEndpoint`): it refuses, or hands the request to Payload's handler. It does not read
the request path, so the spelling of the URL (`/First-Register`) changes nothing. A collection with
`endpoints: false` is left alone.
- **A fresh site:** whoever opens the panel first becomes the admin — create the first account right after the
first deploy.
- **`access.firstUserAdmin: false`** gives the first account the default role. If that role is below the panel
role, nobody could open the panel on a fresh site: with the default panel role the plugin then does **not**
apply it and says so at start; with `accounts.panelRole` set by you the config is refused at start. Set
`access.defaultRole: 'editor'`, or `accounts: { panelRole: false }`.
- **What an existing site sees:** nothing, unless its own staff collection relied on Payload's defaults
(non-admins creating accounts in a collection with the plugin's roles; accounts of another collection writing
to it) — then write the rule you want, or set `adminOnlyCreate: false` / `adminOnlyWrite: false`.
- `ipal-doctor --url`: `open-signup` (info) lists auth collections with open sign-up; `staff-own-roles` (warning)
a staff collection with role values of its own on the default rules; `staff-accounts-open`
(error) names a staff collection an account of another collection may create in, read (a warning), update, delete from or unlock
(the rules are off, or your own rule is wider).
- Building blocks: `staffCreateAccess`, `staffUpdateAccess`, `staffReadAccess`, `sameStaffCollectionAccess`,
`rolesByAdminOnly`, `rolesNotOwn`, `bothAllow`, `hasPluginRoles`, `applyStaffAccountAccess`, `adoptLateAuthCollections`,
`unknownStaffCollections`, `buildFirstUserEndpoint`, `applyFirstUserRoute`, `openSignUpCollections`,
`staffCollectionsOpenToOthers`, `staffCollectionsOnOwnRoles`.
- **Check:** `curl -X POST <site>/api/members/first-register -H 'content-type: application/json' -d
'{"email":"x@example.com","password":"a-long-password-1"}'` → `403`, also as `/First-Register`; the same for
`/api/users` → `403`. Logged in as a visitor account: `PATCH /api/users/<id>` and `GET /api/users` → `403`. As a
non-admin of a staff collection: `PATCH` your own account with `roles` → the roles do not change.
### Passwords (`accounts.password`, default 12 characters)
When a password is **set** on a staff collection — a new account, the first-user screen, a change, a reset by
e-mail; in the panel, over the API and through the Local API — it must have at least 12 characters and must not
be the account's own e-mail address (Payload's own rule is 3 characters). **Existing passwords are never
checked:** an account with a shorter one keeps logging in, and meets the rule the next time its password is
changed. The message is in the panel's language, English or Polish ("The password must have at least 12
characters."; texts `passwordTooShort`, `passwordIsEmail` in `i18n.translations.<lang>.ipal`).
- `password: { minLength: 16 }`; `password: false` = Payload's rule. Visitor collections are not touched.
- Checked against the account's address also where the request carries none: a change by id, a reset by e-mail
(the account is found by its token), a bulk update (every account it matches). A password that is not text
(a number, a list) is refused with the same message.
- No breached-password lookup (it would send part of a hash of every new password to an outside service);
build one on `checkPassword` / `buildPasswordRuleHook` if a project needs it.
- A script or seed that creates a staff account with a shorter password now fails with a validation error.
- Building blocks: `checkPassword`, `buildPasswordRuleHook`, `applyPasswordRule`, `resolvePasswordRule`,
`DEFAULT_PASSWORD_MIN_LENGTH`.
- **Check:** create an account with an 11-character password → "The password must have at least 12 characters.".
## Turn off, override, extend
- **Account rules:** `accounts: false`, or one by one — `panelRole`, `adminOnlyCreate`, `adminOnlyWrite`,
`staffOnlyRead`, `firstUserRoute`, `password` (above).
- **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.staffCollections` (who is staff), `access.authAccess` (injected collection), your own auth collection (wins whole),
+12 -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`, `SafeTotpView`; check: a new admin lands on `/admin/setup-totp?back=%2Fadmin` with the QR, no reloading; a login with the password only gets `403` from `/api/globals/site-integrations` and `/api/form-submissions` — security.md "What the second factor covers"); own endpoints: `secondFactorPassed(req)` / `userMeetsRole(req, role)`; **set 2FA up right after creating an account** — until then its password alone opens everything its role allows; `ipal-doctor --url` must report 0 accounts without 2FA; `IPAL_IP_HEADER` in production | security.md, forms.md | A |
| 13 | Security | `buildSecurityHeaders` in `next.config.ts`; `withPayload(withSecurityConfig(nextConfig))` (no `X-Powered-By`); CSP: `buildSecurityHeaders({ csp: { mode: 'report-only', reportUri: '/api/csp-report', … } })` + `buildAdminCspHeaders` on `/admin/:path*` + `src/app/api/csp-report/route.ts` (`createCspReportRoute`) → read the reports → `mode: 'enforce'`; `twoFactor: { issuer, plugin: payloadTotp }` + `generate:importmap` (`TotpRedirectProvider`, `SafeTotpView`; check: a new admin lands on `/admin/setup-totp?back=%2Fadmin` with the QR, no reloading; a login with the password only gets `403` from `/api/globals/site-integrations` and `/api/form-submissions` — security.md "What the second factor covers"); own endpoints: `secondFactorPassed(req)` / `userMeetsRole(req, role)`; **an account without 2FA can only set it up** (`twoFactor.requireSetup`, default: nothing else answers, 72 h from creation or an admin's reset, then blocked until an admin chooses "Reopen setup" on the account) — so set 2FA up right after creating an account; `ipal-doctor --url` must report 0 accounts without 2FA; Postgres/SQLite: migration for `totpSetupFrom`; `IPAL_IP_HEADER` in production | security.md, forms.md | A |
| 14 | Operations | `src/app/api/health/route.ts` (`healthRoute`); `src/instrumentation.ts` with `assertEnv(ipalEnvRules({ storage: true, ipHeader: true }))`; staging with `IPAL_NOINDEX=1`; smoke tests (§8a) | `healthRoute`, `assertEnv`, `ipalEnvRules` | A |
| 15 | System pages | Site settings → System pages: homepage, 404, privacy policy, cookies; legal links in the footer by role (`getSystemLinks(locale)`) | `getSystemLinks`, `getSystemPagePath`, `getNotFoundPage` | P |
| 16 | **Nothing hardcoded** | every text, link, image, file, company data from the panel; domains and keys from `.env` (§2) | — | A, P |
@@ -1059,7 +1059,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`, `adminOrSelfIn(slug)` (several auth collections), `authenticated`, `requireRole`, `hasMinimumRole` (+ `…Field`); staff checks: `userMeetsRole(req, role)`, `isAdmin(req.user, req.payload)` (roles count only for accounts of a staff collection; in a client component `isAdmin(user, config)` with `useConfig()`, in middleware `isAdmin(user, { staffCollections: ['users'] })` — without the last argument there it is always `false`), `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 |
| Roles and access | `adminOnly`, `adminOrEditor`, `adminOrSelf`, `adminOrSelfIn(slug)` (several auth collections), `authenticated`, `requireRole`, `hasMinimumRole` (+ `…Field`); staff checks: `userMeetsRole(req, role)`, `isAdmin(req.user, req.payload)` (roles count only for accounts of a staff collection; in a client component `isAdmin(user, config)` with `useConfig()`, imported from **`@intecion/ipal-kit/client`** (the main entry does not build there with webpack), in middleware `isAdmin(user, { staffCollections: ['users'] })` — without the last argument there it is always `false`), `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**
@@ -1165,8 +1165,17 @@ add missing hosts with flags / `extra`; (3) change `mode` to `'enforce'` in both
| Injected `users`: admin manages everyone, others only themselves | — | `access.authAccess` (your keys win); your own `users` collection wins whole |
| First registered account = admin | `access.firstUserAdmin: false` | `buildRolesField(defaultRole, { firstUserAdmin })` |
| 2FA on the panel's login collection, mismatch = startup error; redirect to the 2FA screens by `TotpRedirectProvider` | `twoFactor: false` (discouraged) | `twoFactor.collectionSlug`, `allowCollectionMismatch: true`, `twoFactor.provider` (own component, or `false` for the package's) |
| 2FA setup required: an account without TOTP reaches only the setup screen; 72 h window from creation / admin reset, then blocked; status and "Reopen setup" on the account page, notice on the dashboard, `POST /api/ipal/two-factor/reset` | `twoFactor.requireSetup: false`; parts: `requireSetup: { dashboardNotice: false, statusField: false, setupNotice: false }` | `requireSetup: { windowHours, exempt }` (`exempt` returns exactly `true`, never `async`), `twoFactor.resetAccess` (default: an admin who entered its own code; the reset ends the account's sessions), texts `twoFactor*`; `twoFactorSetupState(req)`, `buildSetupFields`, `backfillSetupFrom`, `buildTwoFactorResetEndpoint`. **Postgres/SQLite: migration for `totp_setup_from` applied when the new container starts (`prodMigrations` or `pnpm payload migrate && pnpm start`; never a pre-deployment command — deployment.md §4.3), or every login answers 500** |
| The second factor on every collection and global, whichever plugin added it, and on the plugin's endpoints; an unrecognised 2FA package = startup error | per entity: `custom.ipal.secondFactor: false` or `{ read: false }` (or the package's `custom.totp.disableAccessWrapper`); everywhere: `twoFactor.guard: false` (not recommended) | `requireSecondFactor` / `secondFactorPassed` in your own access functions and endpoints |
| At most 5 verify attempts per account in 10 minutes (`POST /api/verify-totp` → `429`) | `twoFactor.verifyLimit: false` | `verifyLimit: { max, windowMinutes }` |
| At most 5 verify attempts per account in 10 minutes (`POST /api/verify-totp` → `429`); the count is kept in memory and in the database (`payload.kv`), so a restart or a second instance does not reset it | `twoFactor.verifyLimit: false` | `verifyLimit: { max, windowMinutes, store: 'memory' }` |
| 2FA verify and setup attempts only from the site's own origin: a request a browser marks as coming from elsewhere (`Origin`, `Sec-Fetch-Site`) gets `403` and is not counted. **Set `serverURL`**: behind a proxy that rewrites `Host` and sends no `X-Forwarded-Host` the site's own page is refused without it (logged once per origin: `[ipal] 2FA: a code from origin … was refused`) | `twoFactor.sameOrigin: false` | `sameOrigin: { origins: ['https://app.example.com'] }`; `requestFromOwnOrigin`, `reportRefusedOrigin` |
| Stored secrets are write-only: `smtpPassword` and `turnstileSecretKey` come back as `'********'` over REST, GraphQL and in the panel; an empty save keeps the value, `'[[clear]]'` removes it; server code reads the real value with the Local API. **The panel is the source — never add an env variable for them** (`TURNSTILE_SECRET_KEY` is deprecated) | `secrets: { writeOnly: false }` | `writeOnlySecret(field)` / `writeOnlySecrets(fields, names)` for your own secret fields; with versions on the entity add `hooks.afterRead: [maskSecretsOnRestore]` |
| The SMTP password stays with its server: a save in the panel or over the API that changes the server, port or user name without the password is refused (`400` "Enter the password again…"), whatever the transport says — otherwise an admin session points the server at its own machine and a test e-mail hands the password over. A change of the transport alone asks for nothing. Seeds and scripts (Local API, access control off) are not asked | `secrets: { reenterOnChange: false }` | `writeOnlySecret(field, { boundTo: [...] })`, `buildKeepSecret`, `SMTP_PASSWORD_BOUND_TO` |
| The admin panel opens for `editor` and above; an account with only `user` sees "Unauthorized" (the API is not touched). First start logs how many accounts are below the role | `accounts: { panelRole: 'user' }` (or `false`) | `panelRole: 'admin'`; your own `access.admin`; `panelAccess(role)` |
| Nobody creates an account for themselves, or takes one over. A staff collection (also the project's own, also one a later plugin adds) without a `create` / `update` / `delete` / `unlock` / `read` / `readVersions` rule gets one (on a collection a later plugin adds the plugin's rule is put in front of its own and both must allow; `custom: { ipal: { accountRules: false } }` on it keeps its own): with the plugin's roles — create, delete, unlock: an admin; update: an admin or the account itself; the `roles` field: only an admin. With roles of its own, or none: an account of that same collection, or a plugin admin, and an account never changes its own roles — **the plugin cannot rank a project's own roles: write that collection's rules** (`ipal-doctor` → `staff-own-roles`). `read`: a staff account. Payload's first-user route answers only for the panel's login collection (the first account, which becomes admin), in any spelling of the URL. `access.firstUserAdmin: false` with a default role below the panel role: the default panel role is not applied (logged), an explicit one is refused at start. With a slug in `access.staffCollections` that is not an auth collection Payload does not start (`/api/health` 503) | `accounts: { adminOnlyCreate: false, adminOnlyWrite: false, staffOnlyRead: false, firstUserRoute: 'all' }` | your own rule wins; `firstUserRoute: ['users', 'partners']`; a collection with open sign-up keeps its routes; `staffCreateAccess`, `staffUpdateAccess(slug)`, `staffReadAccess`, `sameStaffCollectionAccess(slug)`, `rolesByAdminOnly`, `rolesNotOwn(slug)`, `hasPluginRoles`, `applyStaffAccountAccess`, `adoptLateAuthCollections`, `buildFirstUserEndpoint` |
| A password set on a staff account has at least 12 characters and is not the e-mail address; existing passwords are not checked | `accounts: { password: false }` | `password: { minLength }`; `checkPassword`, `buildPasswordRuleHook` |
| While Turnstile cannot check (wrong secret, Cloudflare down): a text form is accepted, a form with files is refused | `forms: { turnstileOnConfigError: 'allow' }` | `'reject'`, `{ text, files }`; `turnstileOnConfigError` at a call site wins |
| Dashboard alerts by role: integration details for admins, a neutral line for editors, nothing for others; cookie alerts for editors and above. `'all'` checks nothing — no role, no second factor | `dashboardAlerts: { integrations: 'all', cookies: 'all' }` | `integrations: 'editor'`; the components' `details` / `audience` props |
| The `back` link of the 2FA setup and verify screens is checked on the server (`SafeTotpView` in front of the package's views): only a path on the site's origin inside the admin route is kept, anything else (`javascript:`, another host) becomes the admin root. Needs `generate:importmap` in the same deploy — with a stale map the 2FA screens have no code form and nobody can sign in (`ipal-doctor`, the start log and a notice above the screen report it; the notice is a hint from the file on disk and never replaces the screen; `twoFactor.importMapCheck: false` turns it off); check: password only → `/admin/verify-totp?back=https%3A%2F%2Fexample.com%2F` → code → lands on `/admin` | `twoFactor.safeBack: false` | `safeBack: (back, { adminRoute, origin }) => string`; `safeAdminBack`, `wrapTotpViews` (`@intecion/ipal-kit`), `SafeTotpView` (`@intecion/ipal-kit/admin`) for own views |
| The 2FA package's endpoints (`/api/setup-totp`, `verify-totp`, `remove-totp`, `admin/*`) answer accounts of the 2FA collection only; reset and remove need the second factor | — (always on with 2FA) | `adminManageAccess` through the wrapped factory (security.md "Resetting 2FA") |
| Roles count only for accounts of a staff collection, in every predicate and access function | — | `access.staffCollections` |
+32 -38
View File
@@ -2,7 +2,7 @@
<!-- Generated by scripts/reference-index.mjs from reference/ — do not edit by hand (pnpm reference:index). -->
The reference site is one complete client site on ipal-kit 1.16.5 ("Example Studio", made up) that uses
The reference site is one complete client site on ipal-kit 1.16.7 ("Example Studio", made up) that uses
every convention in AGENT.md. It lives in the plugin repo (`reference/`, not in the npm package). Copy the
PATTERN of the file you need; change only the project's content. Files up to
40 lines are below in full; open the rest in the repo at the tag of your plugin version:
@@ -94,6 +94,8 @@ try {
/**
* Smoke tests against a built, seeded site: pnpm build && pnpm seed && pnpm payload run e2e/create-test-admin.ts.
* Run create-test-admin.ts again before repeating the tests within ten minutes: the 2FA verify limit (5 attempts per
* account in 10 minutes) is stored in the database, and that script clears the test admins' counts.
* E2E_BASE_URL picks the port (default 3100). Playwright starts its own server there and fails when the port is
* taken, so another project's dev server is never tested by mistake; E2E_REUSE_SERVER=1 uses a server you started.
*/
@@ -1157,52 +1159,41 @@ Rules: AGENT.md §8a.
| File | What it shows |
|---|---|
| `e2e/create-test-admin.ts` | a test admin with a known TOTP secret, and e-mail sending pointed at the tests' mail sink (local / CI database only) (below) |
| `e2e/create-test-admin.ts` | two test admins with a known TOTP secret (the specs share out the five 2FA verify attempts per account), their stored verify counts cleared, and e-mail sending pointed at the tests' mail sink (local / CI database only) |
| `e2e/late-staff-fixture.ts` | test fixture, on only with E2E_LATE_STAFF=1: a plugin listed after ipalKit that adds a staff collection without rules and a visitor collection with open sign-up (below) |
| `e2e/late-staff.spec.ts` | the account rules on a BUILT site for a staff collection a later plugin adds (run after a webpack and a Turbopack build): a visitor account gets nothing, nobody raises its own role |
| `e2e/smoke.spec.ts` | the smoke tests every release must pass: pages, showcase, forms (also a file sent by e-mail), sitemap, SEO/GEO, headers, consent, 2FA |
| `e2e/smtp-sink.ts` | a local mail sink for the smoke tests: reads what the site really sent (recipients, attachments) |
| `e2e/totp.ts` | RFC 6238 code generator for the 2FA sign-in in the smoke test (below) |
| `e2e/totp.ts` | RFC 6238 code generator for the 2FA sign-in in the smoke test, and the address of the second test admin (below) |
| `e2e/two-factor-back.spec.ts` | browser test of the 2FA screens' `back` link (twoFactor.safeBack): a prepared link — script or another host — ends on the admin root, an ordinary one is followed |
| `e2e/two-factor-setup.spec.ts` | browser check of "2FA setup required": the first admin of a fresh site, a new editor, the administrator's reset on the account page |
### `e2e/create-test-admin.ts`
### `e2e/late-staff-fixture.ts`
```ts
import type { Config, Plugin } from 'payload'
/**
* Creates (or resets) the smoke-test admin with a known TOTP secret, so e2e/smoke.spec.ts signs in through
* the real 2FA screen instead of skipping it. LOCAL / CI database only:
* pnpm payload run e2e/create-test-admin.ts
* Values come from E2E_ADMIN_EMAIL / E2E_ADMIN_PASSWORD / E2E_TOTP_SECRET (.env.example). Not a seed: seeds
* never create users (docs/seeding.md). It also points e-mail sending at the tests' local mail sink
* (E2E_SMTP_PORT, default 2526).
* Test fixture, on only with E2E_LATE_STAFF=1 (e2e/late-staff.spec.ts): a plugin listed AFTER ipalKit that adds
* a staff collection (`late-staff`, named in `access.staffCollections`) and a visitor collection with open
* sign-up. ipalKit has already run when these collections appear, so it must give them its account rules when
* the config goes live — and it must do so in a BUILT site too, where bundlers rename every function.
* Never part of a real site: the starter drops `e2e/` and the lines that use this file.
*/
import config from '@payload-config'
import { isLocalDatabase } from '@intecion/ipal-kit/seed'
import { getPayload } from 'payload'
export const E2E_LATE_STAFF = process.env.E2E_LATE_STAFF === '1'
const { E2E_ADMIN_EMAIL: email, E2E_ADMIN_PASSWORD: password, E2E_TOTP_SECRET: totpSecret } = process.env
if (!email || !password || !totpSecret) {throw new Error('Set E2E_ADMIN_EMAIL, E2E_ADMIN_PASSWORD and E2E_TOTP_SECRET (.env.example).')}
if (process.env.NODE_ENV === 'production' && !process.env.CI) {throw new Error('Refusing: NODE_ENV=production outside CI.')}
if (!isLocalDatabase(process.env.DATABASE_URI ?? '')) {throw new Error('Refusing: DATABASE_URI is not a local database.')}
const payload = await getPayload({ config })
const data = { email, hasTotp: true, password, roles: ['admin'], totpSecret }
const found = await payload.find({ collection: 'users', limit: 1, overrideAccess: true, where: { email: { equals: email } } })
if (found.docs[0]) {
await payload.update({ id: found.docs[0].id, collection: 'users', data: data as never, overrideAccess: true })
} else {
await payload.create({ collection: 'users', data: data as never, overrideAccess: true })
}
console.log(`[e2e] test admin ready: ${email}`)
// E-mail for the smoke tests goes to a local sink the test itself starts (e2e/smtp-sink.ts), so the test can
// read what the site sent — the form file as an attachment. Without the sink running, sends simply fail.
const smtpPort = Number(process.env.E2E_SMTP_PORT ?? 2526)
await payload.updateGlobal({
slug: 'site-integrations',
data: { emailTransport: 'smtp', smtpFromAddress: 'site@example-studio.test', smtpHost: '127.0.0.1', smtpPassword: 'e2e-sink', smtpPort, smtpUser: 'e2e' } as never,
overrideAccess: true,
})
console.log(`[e2e] e-mail sending points at the local sink 127.0.0.1:${smtpPort}`)
process.exit(0)
export const e2eLateStaff: Plugin = (config: Config) =>
E2E_LATE_STAFF
? {
...config,
collections: [
...(config.collections ?? []),
// no access rules at all: Payload's defaults ("any logged-in user") are what ipalKit must replace
{ slug: 'late-staff', auth: true, fields: [{ name: 'roles', type: 'select', hasMany: true, options: ['user', 'editor', 'admin'], saveToJWT: true }], versions: true },
{ slug: 'e2e-visitors', access: { create: () => true }, auth: true, fields: [] },
],
}
: config
```
### `e2e/totp.ts`
@@ -1223,4 +1214,7 @@ export function totp(secret: string, now = Date.now()): string {
const code = (hmac.readUInt32BE(offset) & 0x7fffffff) % 1_000_000
return code.toString().padStart(6, '0')
}
/** The second smoke-test admin (create-test-admin.ts makes both): `e2e-admin@…` → `e2e-admin-2@…`. */
export const secondTestAdmin = (email: string): string => email.replace('@', '-2@')
```
+1 -1
View File
@@ -51,7 +51,7 @@ Ask only when the brief leaves a business question open (e.g. "do posts have aut
4. **An auth collection for visitors** (`auth: true`: customers, members) only when the client requires it
(AGENT.md §5 "A second auth collection"): `admin: { user: 'users' }` in `buildConfig`, `access` with
`adminOrSelfIn('<slug>')` for read / update and an explicit `create`, never in `access.staffCollections`.
Its accounts pass none of the plugin's staff checks. Check: its token → `403` from
Its accounts pass none of the plugin's staff checks, and 2FA (setup required included) does not apply to them. Check: its token → `403` from
`/api/globals/site-integrations` and `/api/form-submissions`.
5. `pnpm generate:types`, `pnpm payload generate:importmap`.
6. Postgres with migrations → `pnpm payload migrate:create`.
+28 -1
View File
@@ -36,7 +36,17 @@ through this procedure. Ask only when you are missing something you cannot get y
|---|---|---|
| the 2FA code screen answers "Too many codes were tried…" (`429` from `/api/verify-totp`) | more than 5 verify attempts for that account in 10 minutes (`twoFactor.verifyLimit`); repeated lines `[ipal] 2FA: too many verify attempts` in the log without the owner trying = someone has the password | wait for the window, enter the current code once; unexplained attempts: change that account's password. Tests that log in often: `verifyLimit: { max: … }` for that environment |
| `isAdmin(req.user)` says `false` for a real administrator on the server, in a process that loads two Payload configs (tests, a multi-site script) | a call without a source counts only collections that are staff in **every** config of the process | pass the source: `isAdmin(req.user, req.payload)` — with it each config gets its own answer |
| `isAdmin(user)` / `isEditor(user)` is always `false` in a client component or in `proxy.ts` | the staff collections are not known there (no config in the browser bundle / middleware), and the predicates fail closed | `isAdmin(user, config)` with `useConfig()`; in middleware `isAdmin(user, { staffCollections: ['users'] })` |
| `isAdmin(user)` / `isEditor(user)` is always `false` in a client component or in `proxy.ts` | the staff collections are not known there (no config in the browser bundle / middleware), and the predicates fail closed | `isAdmin(user, config)` with `useConfig()`, imported from `@intecion/ipal-kit/client`; in middleware `isAdmin(user, { staffCollections: ['users'] })` |
| `next build --webpack`: `'server-only' cannot be imported from a Client Component module … caused by importing '@intecion/ipal-kit/dist/index.js'` | a `'use client'` file imports the main entry (Turbopack lets it pass) | import from `@intecion/ipal-kit/client` (role predicates are there since 1.16.7; types: `import type` from the main entry is fine); data the browser needs → a prop from a server component |
| an account logs in but every page and request answers 403 / the setup screen says "The time to set up two-step verification has passed" | 2FA setup required: the account did not set TOTP up within the window (72 h from its creation, an admin's reset, or the first start after the upgrade) | an administrator opens the account in the panel → Two-step verification → "Reopen setup" (or `POST /api/ipal/two-factor/reset` `{ userId }`); every administrator is blocked: security.md "Every administrator is blocked" — a script with the Local API, `payload.update({ collection: 'users', id, data: { totpSetupFrom: new Date().toISOString() } })` (`pnpm payload run`), then log in and set TOTP up; or `requireSetup: { windowHours: false }`, redeploy, set up, put it back |
| a new account gets `403` from the API although its role allows the request | 2FA setup required: until TOTP is set up the account reaches only the setup screen | set TOTP up (log in to the panel); an integration: use an API key, or `twoFactor.requireSetup.exempt` |
| after an upgrade EVERY panel login answers `500` (also `/api/users/init`), administrators with 2FA included; log: `[ipal] 2FA: the column for "totpSetupFrom" is missing … NOBODY CAN LOG IN` or `column users.totp_setup_from does not exist` | Postgres/SQLite: the migration that adds the 2FA column has not run (needed whenever 2FA is on) | `pnpm payload migrate:create` if no migration has it, commit, and redeploy with migrations run when the new container starts — `prodMigrations` in the adapter or the start command `pnpm payload migrate && pnpm start` (deployment.md §4.3; not Coolify's Pre-deployment command, which runs in the old container); nothing is lost. `ipal-doctor` reports a project whose migrations lack `totp_setup_from` |
| the site does not start: `[ipal] twoFactor.requireSetup.exempt must not be async` / `…windowHours must be a number` | `exempt` is an `async` function, or `windowHours` is a string / negative | `exempt: ({ user }) => user.email === '…'` (returns `true` / `false` at once); `windowHours: 72` or `false` |
| log: `[ipal] twoFactor.requireSetup.exempt returned a Promise … The account is NOT exempt` (and the service account gets 403) | `exempt` does not return exactly `true` | return a boolean decided from the fields on `user` |
| an administrator's "Reset two-step verification" answers 403 from a script with an API key, or for an exempt account | by default the reset needs a session that entered its own TOTP code | reset from the panel after logging in with the code; or `twoFactor.resetAccess: ({ req }) => …` |
| after "Reset two-step verification" the user is logged out everywhere | intended: the reset ends the account's sessions | the user logs in again with the password and sets 2FA up; after a suspected compromise also change the password |
| no "Two-step verification" box on the account page / no "Reopen setup" | the import map lacks `TwoFactorStatusField` (not regenerated), or `requireSetup: { statusField: false }` | `pnpm payload generate:importmap`, commit, redeploy; meanwhile `POST /api/ipal/two-factor/reset` `{ userId }` works |
| "Two-step verification" is missing on the account page / the dashboard shows a missing component | the import map is stale | `pnpm payload generate:importmap`, commit `importMap.js`, `rm -rf .next`, redeploy |
| startup: `[ipal] twoFactor: the injected 2FA plugin did not add the totpSecret field / hasTotp field / totp auth strategy` | the installed `@clocklimited/payload-2fa` is not a version ipal-kit's second-factor check recognises (tested: 3.0.0-beta.1 and beta.7), or a custom factory was injected | install a supported version; stop-gap only: `twoFactor.guard: false` (the plugin's own data is then not covered by 2FA — security.md) |
| own route or script gets `403` / "not allowed" on `form-submissions`, `forms`, a settings global with `overrideAccess: false`, although the user is an admin | the `user` was fetched by id and passed by hand: it does not carry how the account logged in, so the second-factor check refuses it | take the user from `payload.auth({ headers })` (it sets `collection` and how the account logged in), or (server-only code that needs no access check) leave `overrideAccess` at its default; a hand-built user needs at least `collection: 'users'` for its role to count |
| an account of a second auth collection (`customers`) gets `403` from a settings global, submissions, `/api/ipal/*`, `/api/setup-totp`, or `isAdmin` / `adminOnly` say no although it has `roles: ['admin']`, after an upgrade | by design since 1.16.4: roles and staff checks count only for accounts of a staff collection | write the one rule it needs (`formSubmissionOverrides`, `globalOverrides`, `collectionOverrides`); a second STAFF collection: `access.staffCollections` (access.md "Who is staff") |
@@ -90,6 +100,23 @@ through this procedure. Ask only when you are missing something you cannot get y
| emails are not sent | no `email: mailAdapter()` / empty transport / empty Emails tab | email.md; Send test in the panel |
| old email sender | mail client cache | check the raw headers |
| form: `unknown_fields` | field outside the definition (honeypot not removed) | `ipal-form` → actions.ts |
| an account logs in to `/admin` and sees "Unauthorized" (its API calls still work) | `accounts.panelRole`: the panel opens for `editor` and above; the account has only `user`, or no role | give it `editor` (an admin edits the account), or `accounts: { panelRole: 'user' }`; nobody can get in: a script with the Local API sets `roles: ['admin']`, or `accounts: { panelRole: false }` + redeploy |
| `POST /api/<slug>/first-register` answers `403` on an empty collection | `accounts.firstUserRoute`: only the panel's login collection may register its first account that way (the plugin's own endpoint sits in front of Payload's) | an admin creates the account; or the collection's own `create: () => true` (sign-up); or `accounts: { firstUserRoute: ['<slug>'] }` |
| an editor (or a script with its token) gets `403` creating an account in the project's own `users` | `accounts.adminOnlyCreate`: only admins create staff accounts where the roles are the plugin's | create as an admin; or write the collection's `create` rule; or `adminOnlyCreate: false` |
| an account gets `403` changing or deleting ANOTHER account of a staff collection (it worked before) | `accounts.adminOnlyWrite`: an admin, or the account itself (update only); on a collection with roles of its own: accounts of that collection | do it as an admin; or write the collection's `update` / `delete` rule; or `adminOnlyWrite: false` |
| an account saves its own profile and its `roles` do not change (no error) | `accounts.adminOnlyWrite`: nobody changes its own roles; with the plugin's roles only an admin changes roles | an admin changes the role; or give the `roles` field its own `access.update` |
| a logged-in visitor (customer) gets `403` reading a staff collection — an author box went empty | `accounts.staffOnlyRead`: only staff accounts read a staff collection without a `read` rule | write that collection's `read` rule; or `staffOnlyRead: false` |
| `/api/health` answers 503, the panel and `/api/*` 500 after a deploy; log: `[ipal] access names "…" as a staff collection, but this config has no auth collection with that slug` | a slug in `access.staffCollections` / `access.authCollection` is not an auth collection (a typo, a removed collection): Payload does not start, the process stays up (with a health check Coolify keeps the old container) | fix the slug or add the collection |
| a collection added by a plugin listed after ipalKit refuses what its own access rule allows | it is in `access.staffCollections`: the plugin's account rules are put in front of its rules and both must allow (the log at start lists what was put) | `custom: { ipal: { accountRules: false } }` on that collection, or list that plugin before ipalKit |
| a fresh site with `access.firstUserAdmin: false`: the first account sees "Unauthorized", or the start fails with `leaves a fresh site with nobody who can open the panel` | the first account gets the default role, below the panel role | `access.defaultRole: 'editor'`, or `accounts: { panelRole: false }`, or drop `firstUserAdmin: false` |
| saving Site integrations fails on the password field: "Enter the password again…" | the server, port or user name changed and the stored SMTP password is kept only for the settings it was saved with — also when the transport says Microsoft Graph | type the password again; or "Remove the stored value" for a server without one; a seed with the Local API is not asked; `secrets: { reenterOnChange: false }` |
| creating an account / changing a password fails with "The password must have at least 12 characters." | `accounts.password` (applies to new passwords of staff accounts, in scripts too) | a longer password; `accounts: { password: { minLength } }` or `false` |
| the API returns `"smtpPassword":"********"` / own code "lost" the SMTP password or Turnstile secret | write-only secrets: reads through access control never get the value | read on the server: `payload.findGlobal({ slug: 'site-integrations' })` (access control off); `secrets: { writeOnly: false }` restores the old behaviour |
| the SMTP password "disappears" after saving Site integrations | it does not: the field shows "A value is set"; an empty save keeps it | to change it type a new one; to remove it press "Remove the stored value" (API: `'[[clear]]'`) |
| a form with a File field answers "verification failed" while text forms work | Turnstile is degraded (wrong / missing secret, Cloudflare down) and forms with files fail closed | fix the keys (Site integrations → Spam protection; dashboard alert; `ipal-doctor --url` → `turnstile-degraded`); or `forms: { turnstileOnConfigError: { files: 'allow' } }` |
| `POST /api/verify-totp` (or `setup-totp`) answers `403` "Not allowed from this origin." — **nobody can enter a code** | the request's `Origin` is not one the server knows as its own: a panel or front end on another domain, or a proxy that rewrites `Host` and sends no `X-Forwarded-Host` while `serverURL` is not set. The log names the origin once: `[ipal] 2FA: a code from origin "…" was refused` | set `serverURL` (best); or `twoFactor: { …, sameOrigin: { origins: ['https://<that origin>'] } }`; or make the proxy send `X-Forwarded-Host`; `sameOrigin: false` turns the check off |
| log: `[ipal] Deprecated: the Turnstile secret key comes from the TURNSTILE_SECRET_KEY environment variable` | the panel field is empty and the env variable is used | with the owner: copy the key into Site integrations → Spam protection, test a form, remove the variable; it keeps working meanwhile |
| an editor no longer sees why an integration fails on the dashboard | dashboard alerts by role: details are for admins | an admin looks; or `dashboardAlerts: { integrations: 'editor' }` |
| Turnstile always rejects | the `[ipal] Turnstile …` log says why: no secret, `invalid-input-secret`, `timeout-or-duplicate` | turnstile.md → table; secret in the panel or `TURNSTILE_SECRET_KEY`; **do not** write the secret in code |
### Environment
+1 -1
View File
@@ -50,7 +50,7 @@ Existing client sites are not gated on it; run it there as a report only.
## The status endpoint
`GET /api/ipal/doctor` is added by `ipalKit` and answers 404 until the site has `IPAL_DOCTOR_TOKEN` (≥ 32 characters).
Then `Authorization: Bearer <token>`; counts only (`usersWithout2fa`, `pendingCookies`, `plugin`, `node`). With the same
Then `Authorization: Bearer <token>`; counts and states only (`usersWithout2fa`, `usersSetupClosed` = of those, blocked because the 2FA setup window has passed, `pendingCookies`, `openSignUp` = slugs of auth collections with open sign-up, `turnstile` = the recorded state of the Turnstile check, `turnstileSecretFromEnv`, `plugin`, `node`) — never a key or a name. With the same
`IPAL_DOCTOR_TOKEN` in the doctor's environment, `--url` reads it. Off: `ipalKit({ doctor: false })`; adapt:
`ipalKit({ doctor: { tokenVar, access } })`.
+18 -1
View File
@@ -31,6 +31,16 @@ description: Complete map of everything @intecion/ipal-kit provides — every ip
| `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, besides the panel's login collection (`admin.user`) and `access.authCollection`; roles count **only** for accounts of a staff collection (every predicate and access function); such accounts are **not** covered by 2FA (one collection only — warning in the log at start); 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 |
| `accounts` | on (all rules) | rules for the accounts of the staff collection; each key below | `false` = none of them |
| `accounts.panelRole` | `'editor'` | the lowest role that may open the admin panel (Payload's `access.admin` on the collection with the roles): an account with only `user` sees "Unauthorized"; the API is not touched; the role decides, not the second factor. First start logs `N account(s) … cannot open the admin panel` (an error when it is everyone). Needs `access` | `'user'` / `false` = everyone, as before; `'admin'`; your own `access.admin` / `access.authAccess.admin` wins |
| `accounts.adminOnlyCreate` | on | a staff collection (panel login collection, `access.authCollection`, `access.staffCollections`) without a `create` rule gets one instead of Payload's "any logged-in user" — also the project's own collection. With the plugin's roles (`access.authCollection`, or a `roles` select with only `user` / `editor` / `admin`): an admin, fully signed in. With roles of its own, or none: an account of that same collection, or a plugin admin of another staff collection | `false` = Payload's default; a `create` rule you wrote always wins |
| `accounts.adminOnlyWrite` | on | the same for `update`, `delete` and `unlock`: with the plugin's roles — update: an admin or the account itself; delete, unlock: an admin; otherwise an account of that same collection, or a plugin admin. With it the collection's `roles` field (when it has no `access.update`) is closed for self-promotion: with the plugin's roles only an admin changes roles; with role values of the project's own an account never changes its own (the plugin cannot rank them — write that collection's rules). Closes Payload's default, under which a visitor account could change a staff account's password | `false` = Payload's default, the `roles` field left alone; rules you wrote always win |
| `accounts.staffOnlyRead` | on | `read` and `readVersions` on a staff collection without those rules: a fully signed-in account of a staff collection (Payload's default let a visitor account list the staff accounts) | `false` = Payload's default; a `read` rule you wrote wins |
| `accounts.firstUserRoute` | `'panel'` | which auth collections `POST /api/<slug>/first-register` answers for while they are empty: only the one the panel logs in with (the first account of a site → admin). Others get `403`, a second staff collection included, in any spelling of the URL (the plugin's own endpoint sits in front of Payload's); a collection whose own `create` allows an anonymous request keeps its route. With `access.firstUserAdmin: false` and a default role below the panel role, the default `panelRole` is not applied (logged) and an explicit one is refused at start | a list of slugs; `'all'` = Payload's behaviour |
| `accounts.password` | `{ minLength: 12 }` | when a password is SET on a staff collection (create, first-user screen, change, reset by e-mail; panel, API and Local API): at least `minLength` characters, not the account's e-mail address. Existing passwords are never checked — a shorter one keeps logging in | `{ minLength }`; `false` = Payload's rule (3 characters) |
| `secrets.writeOnly` | on | `smtpPassword` and `turnstileSecretKey` (Site integrations) are never returned: REST, GraphQL and the panel get `'********'` when a value is stored; a save with nothing / empty / the mask keeps it, a new value replaces it, `'[[clear]]'` removes it; the Local API with access control off reads the real value. The panel is the source of these secrets — no env variable. A restore of a version is masked too | `false` = returned to whoever may read the global, as before |
| `secrets.reenterOnChange` | on | a save through access control that changes `smtpHost`, `smtpPort` or `smtpUser` while a password is stored must send the password again or remove it (`400` on the field otherwise), whatever `emailTransport` says — so an admin session cannot send the stored password to a server of its own. A change of the transport alone, and the Local API with access control off, are not asked | `false` = the stored password follows the new server |
| `dashboardAlerts` | `{ integrations: 'admin', cookies: 'editor' }` | who sees the plugin's dashboard alerts: integration details (error text, link) for `integrations` and above, a neutral "ask an administrator" for editors below it, nothing for others; the cookie crawl / approval alert for `cookies` and above. With a role, a session that owes its second factor sees none | `integrations: 'editor' | 'all'`, `cookies: 'all'` (`'all'` = as before: no role and no second factor is checked) |
| `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 | — |
@@ -41,7 +51,13 @@ description: Complete map of everything @intecion/ipal-kit provides — every ip
| `twoFactor.importMapCheck` | on | production only: at start searches the `importMap.js` on disk (where Payload looks for it) for `@intecion/ipal-kit/admin#SafeTotpView`; when not found, logs `[ipal] The admin import map may be out of date …` and ipal-kit's `TotpRedirectProvider` puts the notice "Two-step verification may not be available" above the 2FA screens (never instead of them). A hint only — the map in the build can differ from the file on disk (Dockerfile runner stage, re-exporting map); a file that is not found is not reported | `false` = no file read, log line or notice |
| `twoFactor.texts` | ipal-kit's en/pl texts (`TOTP_TEXTS`) over the package's; 2FA screens titled "Two-step verification" / "Weryfikacja dwuetapowa" (site's language) | `false` = the package's texts; one text: `i18n.translations.<lang>.totpPlugin.<key>` (security.md) |
| `twoFactor.guard` | on | ipal-kit's own second-factor check on every collection and global (also the plugin's own and those of plugins listed after ipalKit) and in `userMeetsRole`; startup fails with `[ipal] twoFactor: the injected 2FA plugin did not add …` when the 2FA package lacks the `totp` strategy / `hasTotp` / `totpSecret` | per entity: `custom.ipal.secondFactor: false` / `{ read: false }` or the package's `custom.totp.disableAccessWrapper.<op>`; `false` = the package's wrapper only (the plugin's own data then opens to a password without the code; not recommended). The package's endpoints stay limited to accounts of the 2FA collection either way |
| `twoFactor.verifyLimit` | `{ max: 5, windowMinutes: 10 }` | attempts per account on `POST /api/verify-totp` (the 2FA package counts none): the sixth in the window, right or wrong, gets `429` + `Retry-After`; in memory per instance | `{ max, windowMinutes }`; `false` = no limit |
| `twoFactor.verifyLimit` | `{ max: 5, windowMinutes: 10, store: 'database' }` | attempts per account on `POST /api/verify-totp` (the 2FA package counts none): the sixth in the window, right or wrong, gets `429` + `Retry-After`. Counted in memory and in the database (`payload.kv`, the `payload-kv` collection Payload adds), so a restart or a second instance does not reset it; a failing store never opens the gate | `{ max, windowMinutes }`; `{ store: 'memory' }` = this instance only; `false` = no limit |
| `twoFactor.sameOrigin` | on | `POST /api/verify-totp` and `/api/setup-totp` refuse (`403`, not counted) a request a browser marks as coming from another origin (`Origin`, else `Sec-Fetch-Site`). Own origins: the request's host (`Host`, `X-Forwarded-Host`, a default port written out is ignored), `serverURL`, Payload's `csrf` / `cors`. Requests without those headers pass. A refusal is logged once per origin with how to allow it — behind a proxy that hides the address set `serverURL` | `{ origins: ['https://app.example.com'] }` adds origins; `false` = off |
| `twoFactor.requireSetup` | on, `{ windowHours: 72 }` | an account without TOTP reaches nothing but the setup screen and `/api/setup-totp` (REST, GraphQL and the panel's data answer 403); it has `windowHours` from its creation or from an admin's reset, then it is blocked until an admin reopens setup. Adds the field `totpSetupStatus` (panel) to the 2FA collection, a dashboard notice and `POST /api/ipal/two-factor/reset`; the date field `totpSetupFrom` is there whenever 2FA is on (also with `requireSetup: false` / `guard: false`). Existing accounts get their window at the first start after the upgrade, written once. **Postgres/SQLite: the migration must be applied when the new container starts — `prodMigrations` or `pnpm payload migrate && pnpm start`, not a pre-deployment command (deployment.md §4.3) — or every login answers 500**; `generate:importmap`. `exempt` must return exactly `true` at once (an `async` one, or a `windowHours` that is not a number / `false`, stops the start) | `false` = the package's rule (API open until setup); `{ windowHours: 24 }`, `{ windowHours: false }` (no limit), `{ exempt: ({ user }) => … }` (a service account) |
| `twoFactor.requireSetup.dashboardNotice` / `.statusField` / `.setupNotice` | on | the administrators' notice on the dashboard; the status and reset control on the account page; the notice on the setup screen | `false` each (the lock and the reset endpoint stay) |
| `twoFactor.resetAccess` (the endpoint exists with `twoFactor.guard` on; `guard: false` = no endpoint, 404) | a staff admin whose session entered its own TOTP code (not an API key, not an `exempt` account) | who may reset another account's TOTP / reopen its setup (the button on the account page, `POST /api/ipal/two-factor/reset`). The reset clears the secret and the account's sessions. A session that still owes its code is always refused | `({ req }) => boolean` — replaces the rule, so keep `req.user?._strategy === 'totp' &&` in it unless API-key / exempt admins should reset; only `true` allows; `req.user._strategy` tells `'totp'`, `'api-key'`, `'local-jwt'` apart |
| `whiteLabel.inlineImages` | on | on the 2FA screens the logo / icon is fetched by the server as an anonymous visitor gets it (max 512 KB) and inlined as `data:` — the session there is refused `media` | `false` = the browser tries the media URL |
| `adminMeta.serveIcon` | on | `/api/ipal/admin-icon` answers with the favicon's bytes when it is a bitmap (PNG, JPEG, GIF, WebP, ICO, AVIF by its bytes); an SVG favicon always gets a redirect to the media file (never SVG bytes from the site's origin) | `false` = always the redirect |
| `twoFactor.allowCollectionMismatch` | `false` | allows `collectionSlug` ≠ `admin.user` (panel users of the other collection then skip 2FA) | `true` only when you protect a second auth collection on purpose |
| `whiteLabel` | none | `admin.components.graphics.Logo/Icon` (`AdminLogo`/`AdminIcon`) from Site settings + vendor credit | omit / `false`; `true` = defaults |
| `whiteLabel.settingsSlug` | `'site-settings'` | global it reads the logo/name from | — |
@@ -72,6 +88,7 @@ description: Complete map of everything @intecion/ipal-kit provides — every ip
| `forms.redirectRelationships` | none | collections a form can redirect to | `['pages']` |
| `forms.emailLayout` | `false` | `beforeEmail` with a layout (logo, colour, footer) + Site settings → **Emails** tab; `{{*:table}}` readable | `true` |
| `forms.beforeEmail` | none | your own e-mail changes (after the layout) | form-builder function |
| `forms.turnstileOnConfigError` | `{ text: 'allow', files: 'reject' }` | what a form does while Turnstile CANNOT check (wrong / missing secret, Cloudflare down): a text form is accepted, a submission to the file endpoint is refused. Not involved while Turnstile is off | `'allow'` / `'reject'` for every form, or `{ text, files }`; `turnstileOnConfigError` at a call site (`createSubmitAction`, `attachments.submit`) wins |
| `forms.attachments` | off | **File** field in the form builder; a file is checked (size, count, type by content, refused extensions), attached to the company e-mail and dropped — **never stored**; adds `POST /api/ipal/forms/submit`, the fields `submissionFiles` / `filesDelivery` / `filesDeliveryNote` / `attemptKey` on `form-submissions`, and the **Files** texts in Form messages | `true` / `FormAttachmentsOption`: `maxSizeMB` (10), `maxTotalMB`, `maxFiles` (3), `fileTypes`, `allowRisky`, `scan` (antivirus hook — none built in), `strictPdf`, `notice`, `maxConcurrent` (2), `path`, `submit` (`maxPerMinute`, `clientIp`, `honeypotField`, `turnstileHostnames`, `turnstileOnConfigError`, `allowedOrigins`, `idleTimeoutMs`, `timeoutMs`); block only: `forms.fields.file: false` or `buildFileBlock(…)`. Postgres: `migrate:create`. Check: submit a PDF → attached to the company e-mail, absent from the customer e-mail, submission shows *File delivery: Handed to the mail server* (forms.md "Files") |
| `forms.consentFieldName` | `'consent'` | name of the GDPR consent field `submitForm` requires (read from `config.custom.ipal`) | `createSubmitAction({ consentFieldName })` / `submitForm` argument wins |
| `consentLog` | off | `consent-records` collection + `POST /api/ipal/consent` (rate limit 20/min) | `true` / `{ retentionDays }` (default 1095) |
@@ -20,7 +20,7 @@ Admin panel components from `@intecion/ipal-kit/admin` — the project does NOT
| Export | Import from | What it does / when |
|---|---|---|
| `MaskedField` | `@intecion/ipal-kit/admin` | Masked text field (••••, Reveal button) for secrets in SiteIntegrations (SMTP password, R2 key, Turnstile secret) — masking in the UI only, not encryption. Injected by the plugin; you can also wire it to your own `text` field via `admin.components.Field`, then `pnpm generate:importmap`. |
| `MaskedField` | `@intecion/ipal-kit/admin` | Text input for a secret. With a write-only field (`writeOnlySecret`, the default for the plugin's SMTP password and Turnstile secret) the value never reaches the browser: the input stays empty, says "A value is set", typing replaces it, "Remove the stored value" clears it on save. With a plain text field the value arrives and is drawn as dots with Show / Hide. Injected by the plugin; you can also wire it to your own `text` field via `admin.components.Field`, then `pnpm generate:importmap`. |
| `TestEmailButton` | `@intecion/ipal-kit/admin` | "Send test e-mail" button in the SiteIntegrations e-mail tab — POST `/api/ipal/test-email` through the selected transport (SMTP/Graph), shows the result/error. Injected by the plugin — do not call. |
| `RowLabel` | `@intecion/ipal-kit/admin` | Array row title in the panel taken from the row content (e.g. "Fast delivery" instead of "Item 01"). Do not wire by hand — use `rowLabel()`; after adding, `pnpm generate:importmap`. |
| `AdminLogo` | `@intecion/ipal-kit/admin` | Server Component: large panel logo (login screen) from SiteSettings `logo`, fallback `siteName`. Injected by the plugin with `whiteLabel`; after turning the option on, `pnpm generate:importmap`. |
@@ -33,10 +33,13 @@ Admin panel components from `@intecion/ipal-kit/admin` — the project does NOT
| `CookieScanButton` | `@intecion/ipal-kit/admin` | "Scan cookies" box above the *Cookie review* list: integrations in use, optional extra names, runs `POST /api/ipal/cookie-scan`. Injected by the plugin with `cookieScanner`; after turning it on, `pnpm generate:importmap`. |
| `SafeTotpView` | `@intecion/ipal-kit/admin` | Server admin view in front of the 2FA package's setup and verify views: replaces the `back` query value with a checked one and renders the view named by the serverProp `ipalTotpView` (a path or `{ path, exportName }`, found in the import map) the way Payload renders a view: a server component gets all server props, a client component only Payload's client props, `ipalTotpClientProps`, `back` and `searchParams` (both checked). `ipalSafeBack` = own rule. Registered by the plugin with `twoFactor` (`twoFactor.safeBack`, on by default). After upgrading, `pnpm generate:importmap`. Check: password only → `/admin/verify-totp?back=https%3A%2F%2Fexample.com%2F` → code → `/admin`. Own registration: `Component: { path: '@intecion/ipal-kit/admin#SafeTotpView', serverProps: { ipalTotpView: '<path>' } }` + that path in `admin.dependencies`. |
| `TotpRedirectProvider` | `@intecion/ipal-kit/admin` | Client admin provider: sends a user without TOTP to `/admin/setup-totp?back=…` and a user whose session has not passed TOTP to `/admin/verify-totp?back=…` (path read in the browser; never redirects away from those screens or logout; renders nothing while redirecting). Injected by the plugin with `twoFactor` in place of the package's header-based provider; swap with `twoFactor.provider`. After upgrading, `pnpm generate:importmap`. Check: a new admin lands on `setup-totp?back=%2Fadmin` with the QR code. Props type `TotpRedirectProviderProps` (`forceSetup`) |
| `TwoFactorStatusField` | `@intecion/ipal-kit/admin` | Server component, the `totpSetupStatus` UI field ipalKit adds to the 2FA collection (sidebar of an account): "Set up", "Not set up… until <date>" or "blocked", and for an administrator on someone else's account the reset / "Reopen setup" button. Wired by the plugin with `twoFactor.requireSetup`; needs `generate:importmap`. |
| `TwoFactorResetButton` | `@intecion/ipal-kit/admin` | Client button inside `TwoFactorStatusField`: `POST /api/ipal/two-factor/reset` `{ userId }`, then reloads the view. Props `{ kind: 'reset' \| 'reopen', userId }`. |
| `TwoFactorAlert` | `@intecion/ipal-kit/admin` | Server component on the dashboard (`beforeDashboard`), administrators only: accounts without two-step verification and how many are blocked. Wired by the plugin with `twoFactor.requireSetup`; renders nothing when every account has it. |
| `IntecionCredit` | `@intecion/ipal-kit/admin` | The line "Technology support: Intecion.com" (admin language; `agency` prop = the name) below the nav and below the login form (`variant: 'nav' \| 'login'`). Injected by the plugin with `whiteLabel`; turn off: `whiteLabel: { credit: false }` or `agency: false`. |
| `buildAdminMeta({ agency, apiRoute?, defaultLocale?, meta?, options? })` | `@intecion/ipal-kit` | The `adminMeta` step: static panel meta (robots, preview image, icon) without overwriting keys in `meta`; returns `{ meta, resolved }` |
| `adminMetaForSite(site, resolved)`, `syncAdminMeta(payload, resolved, { nameField?, settingsSlug? })` | `@intecion/ipal-kit` | Site-name parts (suffix, description, siteName); `syncAdminMeta` writes them into the live config (onInit + Site settings afterChange, never throws) |
| `buildAdminImageEndpoints(resolved, { settingsSlug?, nameField?, logoField?, iconField? })` | `@intecion/ipal-kit` | `GET /api/ipal/admin-og` (1200×630 PNG via `next/og`) and `GET /api/ipal/admin-icon` (favicon redirect or initials) — already added by `adminMeta` |
| `buildAdminImageEndpoints(resolved, { settingsSlug?, nameField?, logoField?, iconField? })` | `@intecion/ipal-kit` | `GET /api/ipal/admin-og` (1200×630 PNG via `next/og`) and `GET /api/ipal/admin-icon` (the favicon itself, or initials) — already added by `adminMeta` |
| `DEFAULT_AGENCY`, `ADMIN_META_TEXTS` | `@intecion/ipal-kit` | Default agency `{ name: 'Intecion.com', url }`; en/pl meta texts (`{site}`, `{agency}`). Types `AdminMetaOptions`, `AgencyOption`, `ResolvedAdminMeta` |
## Readable array rows in the panel (`admin-ui`) — details: `node_modules/@intecion/ipal-kit/docs/links.md`
@@ -60,16 +63,25 @@ Admin panel components from `@intecion/ipal-kit/admin` — the project does NOT
| `adminOnlyField` | `@intecion/ipal-kit` | `FieldAccess` (boolean only): field for admin only. In `field.access.read/update`. |
| `adminOrEditorField` | `@intecion/ipal-kit` | `FieldAccess`: field for editor or admin. |
| `requireRoleField(minimum)` | `@intecion/ipal-kit` | `FieldAccess` factory: at least the given role. |
| `hasMinimumRole(user, minimum, source?)` | `@intecion/ipal-kit` | Predicate → `boolean`: the user is an account of a **staff collection** and has a role ≥ `minimum` (reads `user.roles` and `user.collection` safely). A role on an account of another auth collection never counts. `source` says which collections are staff: `req.payload` on the server, the config from `useConfig()` in a client component, or `{ staffCollections: ['users'] }` (middleware). Without it: the staff collections of the config ipalKit built in this process (two different configs: only what both call staff) — and **`false` where there is none** (browser bundle, middleware, edge). Does not check the second factor. |
| `isAdmin(user, source?)` | `@intecion/ipal-kit` | Predicate → `boolean`: staff account with the `admin` role (see `hasMinimumRole`). In hooks and endpoints: `isAdmin(req.user, req.payload)`; in a client component: `isAdmin(user, config)`. |
| `isEditor(user, source?)` | `@intecion/ipal-kit` | Predicate → `boolean`: staff account with `editor` or higher. |
| `hasMinimumRole(user, minimum, source?)` | `@intecion/ipal-kit`; in client components `@intecion/ipal-kit/client` | Predicate → `boolean`: the user is an account of a **staff collection** and has a role ≥ `minimum` (reads `user.roles` and `user.collection` safely). A role on an account of another auth collection never counts. `source` says which collections are staff: `req.payload` on the server, the config from `useConfig()` in a client component (it has `admin.user` only; for `access.staffCollections` pass the list), or `{ staffCollections: ['users'] }` (middleware). Without it: the staff collections of the config ipalKit built in this process (two different configs: only what both call staff) — and **`false` where there is none** (browser bundle, middleware, edge). Does not check the second factor. |
| `isAdmin(user, source?)` | `@intecion/ipal-kit`; in client components `@intecion/ipal-kit/client` | Predicate → `boolean`: staff account with the `admin` role (see `hasMinimumRole`). In hooks and endpoints: `isAdmin(req.user, req.payload)`; in a client component: `isAdmin(user, config)` from `/client` — the main entry does not build there with webpack (`'server-only' cannot be imported…`). |
| `isEditor(user, source?)` | `@intecion/ipal-kit`; in client components `@intecion/ipal-kit/client` | Predicate → `boolean`: staff account with `editor` or higher. |
| `panelAccess(minimum?)`, `applyPanelRole(config, slug, role)`, `resolvePanelRole(option)`, `countBelowPanelRole(payload, slug, role)`, `DEFAULT_PANEL_ROLE` | `@intecion/ipal-kit` | `accounts.panelRole`: an `access.admin` function ("holds at least `minimum`", default `'editor'`; role only, not the second factor); the applier (skips a collection that has its own `access.admin`); the option → role or `null` when off; `{ all, below }` counts for the start-up line; `'editor'`. |
| `staffCreateAccess`, `staffUpdateAccess(slug)`, `staffReadAccess`, `sameStaffCollectionAccess(slug)`, `rolesByAdminOnly`, `rolesNotOwn(slug)`, `hasPluginRoles(collection)`, `applyStaffAccountAccess(config, staffSlugs, { create?, write?, read?, pluginRoles? })` | `@intecion/ipal-kit` | `accounts.adminOnlyCreate` / `adminOnlyWrite` / `staffOnlyRead`: the access functions — "an admin, fully signed in" (create, delete, unlock); "an admin, or the account itself" (update; self = an account of THAT collection); "a fully signed-in account of a staff collection" (read); "an account of this staff collection, or a plugin admin of another" (a collection whose roles are not the plugin's); the two field-access functions for a `roles` field (`update`: only an admin / never the account itself); whether a collection carries the plugin's roles (a `roles` select at the top level of the data with only `user` / `editor` / `admin`); the applier — puts the rules on the named staff collections for the operations that have none and closes the `roles` field where the plugin's `update` rule is in force, `pluginRoles` = slugs whose roles field is injected later. Run it before any plugin that wraps access (the 2FA package). |
| `buildFirstUserEndpoint(option?)`, `applyFirstUserRoute(config, option?)`, `adoptLateAuthCollections(config, staffSlugs, { access?, beforeOperation?, firstUserRoute? })`, `bothAllow(first, second)`, `unknownStaffCollections(config, staffSlugs)`, `openSignUpCollections(payload)`, `staffCollectionsOpenToOthers(payload)`, `staffCollectionsOnOwnRoles(payload)` | `@intecion/ipal-kit` | `accounts.firstUserRoute`: the plugin's own `POST /first-register` collection endpoint, matched before Payload's — `403` unless the collection is the panel's login collection (`'panel'`), is in the list, or its own `create` lets an anonymous request through; otherwise it calls Payload's handler (and sets `req.context.ipalFirstRegister`); the applier (every auth collection; `'all'` adds nothing; `endpoints: false` is left alone). For the doctor: slugs of auth collections with open sign-up; `'<slug>:<operation>'` for every staff collection an account of a non-staff collection may create in, read, update, delete from or unlock; slugs of staff collections with role values of their own on the default rules. `adoptLateAuthCollections` takes the LIVE config (`payload.config`) and gives auth collections that a plugin listed after ipalKit added the same rules, in place (called by the plugin at start and on every dev reload; returns `LateAdoption[]` — per collection what was put). There the rules are combined with the collection's own by `bothAllow` (an access function that allows only when both do; two query constraints are joined with `and`), because in a sanitized config Payload's default cannot be told from a written rule — never by a function's name, which a production build changes. `custom.ipal.accountRules: false` on a late collection keeps its rules as they are. `unknownStaffCollections` lists staff slugs that are not auth collections (Payload does not start on any). |
| `checkPassword(password, { email?, minLength? })`, `buildPasswordRuleHook({ minLength? })`, `applyPasswordRule(config, slugs, rule)`, `resolvePasswordRule(option)`, `DEFAULT_PASSWORD_MIN_LENGTH` | `@intecion/ipal-kit` | `accounts.password`: `'short' \| 'email' \| null` for a new password (length in characters); the `beforeOperation` hook for `create` / `update` / `resetPassword` (throws Payload's `ValidationError` on `password`, text in the panel's language; the account's address is looked up by id, reset token or bulk query when the request carries none; a password that is not text is refused; login is never checked); the applier; the option → `{ minLength }` or `null`; `12`. |
| `writeOnlySecret(field, options?)`, `writeOnlySecrets(fields, names, optionsByName?)`, `maskSecretAfterRead`, `keepSecretBeforeValidate`, `buildKeepSecret(options?)`, `SECRET_MASK`, `SECRET_CLEAR`, `isSecretMask(value)`, `INTEGRATION_SECRET_FIELDS`, `SMTP_PASSWORD_BOUND_TO` | `@intecion/ipal-kit` | Write-only secret fields (`secrets.writeOnly`): the wrapper for one field and for named fields anywhere in a tree (tabs, rows, groups); the two field hooks (reads through access control get `'********'`, the Local API with access control off gets the value; a save with nothing / empty / the mask keeps the stored value, `'[[clear]]'` removes it); the hook builder with options — `{ boundTo: ['siblingField'], appliesWhen?: (siblingData) => boolean }`: a save through access control that changes a bound sibling field without sending the secret throws a `ValidationError` on the secret (`secrets.reenterOnChange`); the two constants; the plugin's own secret field names (`smtpPassword`, `turnstileSecretKey`); the fields the SMTP password is bound to (`smtpHost`, `smtpPort`, `smtpUser` — not the transport: the mail adapter may fall back to SMTP). |
| `maskSecretsOnRestore`, `maskWriteOnlySecrets(data, fields)` | `@intecion/ipal-kit` | Versions and write-only secrets: the `afterRead` hook for a global or a collection (a restore answers with the version document, fields under `version`, where field hooks do not run — it masks them there for reads through access control); the walker it uses (masks every write-only field in `data`, following tabs, rows, groups, arrays and blocks). On Site integrations by default; add the hook to your own entity that has both. |
| `requestFromOwnOrigin(req, extraOrigins?)`, `ownOrigins(req, extraOrigins?)`, `reportRefusedOrigin(req, extraOrigins?)` | `@intecion/ipal-kit` | `twoFactor.sameOrigin`: `false` when a browser marks the request as coming from another origin (`Origin` not among the request's host, `serverURL`, `csrf`, `cors`, the extras; a default port written out on the host is ignored; else `Sec-Fetch-Site` not `same-origin` / `none`); `true` without those headers. `ownOrigins` → `{ hosts, origins }`. `reportRefusedOrigin` writes one log line per refused origin and process (at most 50) with the ways to allow it, and returns whether it wrote. For your own state-changing endpoint. |
| `buildVerifyLimit(collection, { max?, windowMinutes?, store? })`, `verifyLimitKey(collection, id)`, `clearVerifyLimits()` | `@intecion/ipal-kit` | `twoFactor.verifyLimit`: `async (req) => Response \| null` — counts an attempt of `req.user` in memory and, unless `store: 'memory'`, in `payload.kv`; a `429` with `Retry-After` past `max`. The kv key of an account's count; emptying the in-memory counts (tests). |
| `turnstileSecretFromEnv(integrations)`, `TURNSTILE_SECRET_ENV` | `@intecion/ipal-kit` | `true` when the Turnstile secret in use comes from the environment because the panel field is empty (**deprecated** path; the doctor's `turnstile-env-key`); the variable's name, `'TURNSTILE_SECRET_KEY'`. |
| `userMeetsRole(req, minimum)` | `@intecion/ipal-kit` | Predicate → `boolean` with `req` (`{ payload, user }`), in this order: the account belongs to a **staff collection** (`admin.user`, `access.authCollection`, `access.staffCollections`); with 2FA on it has passed the second factor (`secondFactorPassed`); it has a role ≥ `minimum`, **or** its collection has no `roles` field (the project omitted `access`). An account of any other auth collection never passes, whatever fields it has. 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(source?)` | `@intecion/ipal-kit` | `string[]`: the staff collections — `admin.user`, `access.authCollection` and `access.staffCollections` — from `req.payload`, a config or `{ staffCollections }`; without an argument what the configs built in this process agree on (`[]` when there is none). Roles and staff checks count only for accounts of these. |
| `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:** `VerifyLimitOptions` (`twoFactor.verifyLimit`: `{ max?, windowMinutes? }`), `SafeBackRule` / `SafeBackContext` (`twoFactor.safeBack` as a function: `(back, { adminRoute, origin? }) => string`), `TotpViewComponent` (a view component as registered: a path or `{ path, exportName?, clientProps?, serverProps? }`), `SafeTotpViewProps` (`@intecion/ipal-kit/admin`), `Role` (`'user' \| 'editor' \| 'admin'`), `AccessOption` (the plugin's `access` option: `authCollection`, `defaultRole`, `authAccess`, `firstUserAdmin`, `staffCollections`).
**Types:** `AccountsOptions` (`accounts`: `panelRole`, `adminOnlyCreate`, `adminOnlyWrite`, `staffOnlyRead`, `firstUserRoute`, `password`), `StaffAccountAccessOptions` (`{ create?, write?, read?, pluginRoles? }`), `LateAdoption` (`{ slug, applied, password, firstUser }`), `StaffAccountRules` (what the plugin put on a staff collection, in `custom.ipalAccountRules`: `{ applied, ownRoles }`), `WriteOnlySecretOptions` (`{ boundTo?, appliesWhen? }`), `PasswordRuleOptions` (`{ minLength? }`), `FirstUserRouteOption` (`'panel' \| 'all' \| string[]`), `TurnstileOnConfigError` / `TurnstileOnConfigErrorOption` / `TurnstileFormKind` (`@intecion/ipal-kit/server`), `VerifyLimitOptions` (`twoFactor.verifyLimit`: `{ max?, windowMinutes?, store? }`), `RequireSetupOptions` (`twoFactor.requireSetup`), `TwoFactorResetOptions`, `TwoFactorSetupState`, `SafeBackRule` / `SafeBackContext` (`twoFactor.safeBack` as a function: `(back, { adminRoute, origin? }) => string`), `TotpViewComponent` (a view component as registered: a path or `{ path, exportName?, clientProps?, serverProps? }`), `SafeTotpViewProps` (`@intecion/ipal-kit/admin`), `Role` (`'user' \| 'editor' \| 'admin'`), `AccessOption` (the plugin's `access` option: `authCollection`, `defaultRole`, `authAccess`, `firstUserAdmin`, `staffCollections`).
## Accessibility — widget (`accessibility`) — details: `node_modules/@intecion/ipal-kit/docs/accessibility.md`
@@ -367,7 +379,7 @@ Full option lists of `createContentHelpers` / `createPageRoute` / `SiteProviders
| `recordIntegrationStatus(payload, field, previous, { state, code?, message? })` | `@intecion/ipal-kit` | saves the state of your own integration in Site integrations (only on change / every 10 min); does not throw. For e-mail and Turnstile the plugin calls it itself — do not call |
| `buildIntegrationStatusField(name)` | `@intecion/ipal-kit` | hidden status group field (`state`, `code`, `message`, `since`, `checkedAt`) for `integrationsFields` |
| `buildIntegrationStatusBanner(statusField, label, texts?)` | `@intecion/ipal-kit` | UI field with a status banner on the integration tab (`label` string or `{ en, pl }`; `texts` = `{ failing, hint }` keys of your own `ipal` translations) (`integrationsFields`; then `pnpm generate:importmap`) |
| `IntegrationAlerts` | `@intecion/ipal-kit/admin` | dashboard alert about integrations in the `degraded` state; always injected by the plugin (`beforeDashboard`); your own integrations: a second instance with `checks` |
| `IntegrationAlerts` | `@intecion/ipal-kit/admin` | dashboard alert about integrations in the `degraded` state; always injected by the plugin (`beforeDashboard`); your own integrations: a second instance with `checks`. By role: the detail (error text, link) for `details` and above (`'admin'` default, `'editor'`, `'all'`), a neutral "ask an administrator" for editors below it, nothing for others or for a session that owes its second factor (`dashboardAlerts.integrations`). `CookieCrawlAlert` takes `audience: 'editor' \| 'all'` the same way |
| `IntegrationStatusBanner` | `@intecion/ipal-kit/admin` | status banner on the tab; injected by the plugin / `buildIntegrationStatusBanner` through the import map (`pnpm generate:importmap`), the project does not import it |
**Types:** `IntegrationState` (`'ok' | 'degraded'`), `IntegrationStatus` — integration state and saved status; `IntegrationLabel` (`string | { en, pl }`) — banner / alert label; `IntegrationBannerTexts` (`{ failing, hint }` text keys) — third argument of `buildIntegrationStatusBanner` for your own wording.
@@ -592,6 +604,13 @@ Server only (`pnpm payload run`); never import it from client code, the Payload
| `copyViews(views)` / `changedViewKeys(before, after)` | `@intecion/ipal-kit` | The comparison `ipalKit` uses to tell which views a 2FA factory registered: put `copyViews(views)` into the config before calling the factory, then `changedViewKeys(before, viewsAfter)` gives the keys whose view object changed — the `added` argument of `wrapTotpViews` (`(key) => keys.has(key)`). By object, not by key: the 2FA package replaces a view that already stands under its keys. Example: security.md "Your own 2FA screen". |
| `SAFE_TOTP_VIEW` / `totpViewImportKey(component)` | `@intecion/ipal-kit` | `'@intecion/ipal-kit/admin#SafeTotpView'`, the wrapper's import-map path (the default `wrapper` of `wrapTotpViews`); and the import-map key (`path#export`) of a component given as a string or `{ path, exportName }`. |
| `findImportMapFile(config, cwd?)` / `missingImportMapEntries(config, entries, cwd?)` | `@intecion/ipal-kit` | Where the project's `importMap.js` is on disk (`admin.importMap.importMapFile`, else `app/(payload)<admin route>/` or `src/app/…` under `admin.importMap.baseDir` / the working directory; `null` when not found), and which of `entries` its text does not contain (`{ file, missing }`). A hint from the file on disk, not the map in the build: warn on it, never block on it. Behind `twoFactor.importMapCheck`. |
| `buildSetupFields({ statusField? })`, `stampSetupFrom`, `backfillSetupFrom(payload, collection)` | `@intecion/ipal-kit` | The parts of "2FA setup required" for a project that wires them itself: the fields for the 2FA collection (`totpSetupFrom`, and the panel's `totpSetupStatus` unless `statusField: false`), the `beforeChange` hook that stamps the window start (on create, and when an account loses its TOTP secret), and the start-up step that gives accounts without TOTP and without a start their window (returns how many; once per account). |
| `buildTwoFactorResetEndpoint(collection, { access? })`, `TWO_FACTOR_RESET_PATH` | `@intecion/ipal-kit` | `POST /api/ipal/two-factor/reset` `{ userId }`: clears the account's TOTP secret and sessions and starts a new window. Default: a staff admin whose session entered its own TOTP code; `access` replaces that (only `true` allows; a session that owes its code is always refused). `ipalKit` registers it only with `twoFactor.guard` on. |
| `countAccountsWithoutTotp(payload, collection, setupWindowMs?)` | `@intecion/ipal-kit` | `{ without, blocked }` — accounts of the 2FA collection without TOTP, and how many are past their window. |
| `resolveRequireSetup(option)`, `strictExempt(fn)`, `SETUP_FROM_FIELD`, `DEFAULT_SETUP_WINDOW_HOURS` | `@intecion/ipal-kit` | `twoFactor.requireSetup` → `{ requireSetup, setupWindowMs, exempt? }` as the guard reads it (throws on a `windowHours` that is not a number ≥ 0 or `false`, and on an `async` `exempt`); the wrapper that makes an `exempt` function answer `true` only for exactly `true`; the field name `'totpSetupFrom'`; `72`. |
| `fetchPublicImage(url, base)`, `publicImageDataUri(url, base)`, `rasterImageType(bytes)`, `siteOrigin(serverURL)`, `PUBLIC_IMAGE_MAX_BYTES` | `@intecion/ipal-kit` | An image fetched the way an anonymous visitor gets it (no cookies; http(s) only; `image/*`; at most 512 KB, reading stops at the limit) as `{ bytes, type }` or a `data:` address, else `null`. Used for the logo and icon on the 2FA screens. `rasterImageType(bytes)` → the media type of a bitmap by its first bytes (PNG, JPEG, GIF, WebP, ICO, AVIF) or `null` — never trust a claimed type before answering a file's bytes from the site's origin; an SVG gives `null`. |
| `UPLOAD_SECURITY_HEADERS` | `@intecion/ipal-kit` | The two headers of `buildUploadSecurityHeaders` (`Content-Security-Policy: default-src 'none'; … sandbox`, `X-Content-Type-Options: nosniff`) for a route of your own that returns an uploaded file's bytes from the site's origin. In a Next project a site-wide `headers()` rule with the same key overrides a header the route sets itself: add a `headers()` rule for the path after the site-wide one (as `buildUploadSecurityHeaders({ collections, adminIcon })` does for the upload routes and `/api/ipal/admin-icon`), and never answer with an SVG. |
| `twoFactorSetupState(req)`, `twoFactorSetupDeadline(req)` | `@intecion/ipal-kit` | Where an account stands with TOTP setup, from `{ payload, user }`: `'set-up'`, `'open'` (may set it up now), `'closed'` (the setup window has passed: blocked until an admin reopens it), `'exempt'` (`requireSetup.exempt`, or `requireSetup: false`), `'not-applicable'` (no user, another collection, 2FA off); and the moment setup closes (`Date`, or `null` without a window). Types: `TwoFactorSetupState`, `RequireSetupOptions`. |
| `requireSecondFactor(access?)` | `@intecion/ipal-kit` | Wraps an `Access` function: refused while the second factor is owed, otherwise the function itself (Payload's default "logged in" when none). ipalKit applies it to every collection and global in the config, and to those added by plugins listed after it (in `onInit` and at the start of the first request, so also after a dev hot reload); use it for access functions that are not part of the config. Per-entity opt-out: `custom.ipal.secondFactor: false \| { read: false }` or the package's `custom.totp.disableAccessWrapper`. Wrapping twice is harmless. |
| `totpRedirectTarget({ adminRoute, forceSetup?, pathname, user, excludePaths? })`, `totpAdminPath(adminRoute, path)` | `@intecion/ipal-kit` | The 2FA redirect rules as pure functions: the setup / verify URL (with `back`) to send this user to, or `null` (no path, api key, already on a TOTP screen or logout). For an own `twoFactor.provider`. Types `TotpRedirectArgs`, `TotpUser` |
| `buildCsp({ mode?, reportUri?, reportGroup?, r2Url?, analytics?, metaPixel?, linkedIn?, tiktok?, clarity?, turnstile?, youtube?, googleMaps?, nonce?, strictDynamic?, dev?, extra?, override? })` | `@intecion/ipal-kit` | Returns `{ key, value }` with a hardened CSP (`base-uri`, `object-src`, `frame-ancestors`, `form-action`) + sources for the enabled integrations. `mode: 'report-only'` → `…-Report-Only` (start here), `'enforce'` later. `extra` adds to any directive, `override` replaces / drops one (`null`). `dev` (default `NODE_ENV === 'development'`) adds `'unsafe-eval'`. `nonce` → `'nonce-…' 'strict-dynamic'`. |
@@ -845,6 +864,7 @@ Bin: `ipal-doctor` (`pnpm exec ipal-doctor [dir] [--json] [--md] [--strict] [--f
| `useOptionalTurnstile()` | `@intecion/ipal-kit/client` | Like `useTurnstile`, but without a provider it returns `enabled: false` instead of throwing — for shared components. |
| `Turnstile({ siteKey, onToken, theme? })` | `@intecion/ipal-kit/client` | Raw widget with an explicit key — when you do not use the provider. |
| `verifyTurnstile({ token, payload, ip?, onConfigError?, hostnames? })` | `@intecion/ipal-kit/server` | Server-side token verification → `boolean` (`degraded` lets it through by default; `hostnames` = token must be solved on one of them, unset = not checked). `submitForm` does this itself — call it only in your own actions. |
| `passTurnstile({ payload, turnstileToken, turnstileKind?, turnstileOnConfigError?, … })`, `passSubmitGates(…)`, `resolveTurnstileOnConfigError(payload, kind?, explicit?)`, `TURNSTILE_ON_CONFIG_ERROR_DEFAULT` | `@intecion/ipal-kit/server` | The Turnstile gate of a form (`null` = passed, else `{ success: false, reason: 'turnstile' }`) and the rate limit + Turnstile pair; the policy for a `degraded` check: the call-site value, else `forms.turnstileOnConfigError`, else the default for the kind (`{ text: 'allow', files: 'reject' }`). |
| `checkTurnstile({ token, payload, ip? })` | `@intecion/ipal-kit/server` | As above, but returns `{ outcome: 'pass' \| 'reject' \| 'degraded', code? }` and updates the integration status in the panel. |
**Types:** `TurnstileConfig` (root) — `getTurnstileConfig` result; `TurnstileCheck`, `TurnstileOutcome` (`/server`) — verification result; `TurnstileProps`, `TurnstileTheme` (`/client`) — widget props and theme.
+43 -1
View File
@@ -198,7 +198,7 @@ export default buildConfig({
`.env.example` (no values, in the repo): `DATABASE_URI`, `PAYLOAD_SECRET`, `NEXT_PUBLIC_SERVER_URL`, `R2_BUCKET`,
`R2_ENDPOINT`, `R2_ACCESS_KEY_ID`, `R2_SECRET_ACCESS_KEY`, `R2_PUBLIC_URL` (empty = media through the app — the default), `IPAL_IP_HEADER` (`cf-connecting-ip`
behind Cloudflare, `x-forwarded-for` behind a plain proxy), `IPAL_NOINDEX` (empty; `1` on staging only), `INDEXNOW_KEY`,
`NEXT_PUBLIC_TURNSTILE_SITE_KEY`, `TURNSTILE_SECRET_KEY` (panel fallback), with Graph `GRAPH_TENANT_ID`,
`NEXT_PUBLIC_TURNSTILE_SITE_KEY`, `TURNSTILE_SECRET_KEY` (deprecated fallback — production keys go into the panel), with Graph `GRAPH_TENANT_ID`,
`GRAPH_CLIENT_ID`, `GRAPH_CLIENT_SECRET`, `GRAPH_SENDER`. Local `.env` with `PAYLOAD_SECRET` ≥ 32 characters (in production `ipalEnvRules` refuses a shorter one; `secretMinLength` changes it).
One language: one entry in `locales`, no `[locale]` folder (i18n.md).
@@ -234,6 +234,48 @@ the panel shows Site settings, Site integrations, Cookies, Form messages, the Fo
Check: password only → `/admin/verify-totp?back=https%3A%2F%2Fexample.com%2F` → code → you land on `/admin`.
**Set 2FA up right after creating an account** (log in as it, scan the code): until then its password alone
opens everything its role allows. One entity reachable without the code: `custom.ipal.secondFactor`.
**Setup required** (`twoFactor.requireSetup`, default): an account without TOTP reaches only the setup screen; it
has 72 h from its creation (or an admin's "Reopen setup" on the account page), then it is blocked. So create an
account, hand over the password and have the owner set 2FA up at once. **Postgres/SQLite: `pnpm payload
migrate:create` and have the migration applied when the container starts, before the site serves** — `prodMigrations`
or the start command `pnpm payload migrate && pnpm start`, never a pre-deployment command (deployment.md §4.3)
(column `totp_setup_from`, there whenever 2FA is
on) — without it every login answers 500; `pnpm payload generate:importmap` (`TwoFactorStatusField`,
`TwoFactorAlert`). A service account that logs in with a password: `requireSetup: { exempt }` (a plain function
returning exactly `true`; never `async`); an API key needs nothing. Parts to switch off: `requireSetup:
{ dashboardNotice: false, statusField: false, setupNotice: false }`. An admin's reset ends the account's
sessions and needs the admin's own TOTP code (`twoFactor.resetAccess` changes who). Have two administrators
with 2FA: when all are blocked, only a script or a redeploy helps (security.md "Every administrator is
blocked"). One entity reachable without the code: `custom.ipal.secondFactor`.
- **Account rules** (`accounts`, on by default; `false` or key by key to change): the panel opens for `editor`
and above (`panelRole`; an account with only `user` sees "Unauthorized", the API is not touched — give panel
users at least `editor`); only an admin creates staff accounts, and an account is changed by an admin or by
itself, nobody changes its own roles, and only staff accounts read staff accounts — also in the project's own
staff collection and in one a later plugin adds (`adminOnlyCreate`, `adminOnlyWrite`, `staffOnlyRead`). **A
staff collection with role values of its own** (not `user` / `editor` / `admin`) gets only "an account of that
collection, or a plugin admin": the plugin cannot rank your roles, so inside it every account may create an
account with any role — **write its `create` / `update` / `delete` rules and the field access of its `roles`
field yourself** (`ipal-doctor --url` → `staff-own-roles`). Give every staff collection a `roles` field: without
one each of its accounts is an admin to the plugin. Every slug in `access.staffCollections` must be an auth
collection of the config, or Payload does not start (`/api/health` 503, the slug in the log); a staff collection
from a plugin listed after ipalKit gets the rules in front of its own (`custom: { ipal: { accountRules: false } }`
on it keeps its own as they are); Payload's first-user route answers only for the
panel's login collection (`firstUserRoute`) — so **create the first account right after the first deploy**, it
becomes the admin; a new password has at least 12 characters (`password`). A customer collection with
sign-up: write its own `create: () => true`; the rules do not touch it. Do not combine
`access.firstUserAdmin: false` with a default role below the panel role (the start refuses or drops the panel
role). access.md "Account rules".
- **`serverURL`**: set it in the Payload config. Without it, behind a proxy that rewrites `Host` and sends no
`X-Forwarded-Host`, the 2FA code page is refused as "another origin" (logged once: `[ipal] 2FA: a code from
origin … was refused`). Coolify / Traefik keep `Host`, so it works there either way.
- **Stored secrets:** the SMTP password and the Turnstile secret key are entered **in the panel** (Site
integrations) and are write-only — the panel and the API show "a value is set". Do not add env variables for
them; `TURNSTILE_SECRET_KEY` is deprecated (local test keys in `.env` still work). Read them only on the
server with the Local API. `secrets: { writeOnly: false }` turns it off. Changing the SMTP server, port or
user name in the panel asks for the password again (`secrets.reenterOnChange`); a seed with the Local API is
not asked.
- **Forms with files** are refused while Turnstile cannot check (wrong keys, Cloudflare down); text forms are
still accepted. `forms: { turnstileOnConfigError: … }` changes either.
- A second auth collection (`customers`, a client zone): set `admin: { user: 'users' }` in `buildConfig`; its
accounts pass none of the plugin's checks and no role counts for them (not even their own `roles: ['admin']`);
a field that grants rights is never writable at sign-up; use `adminOrSelfIn('<slug>')` in every auth collection; a second
+117 -1
View File
@@ -350,7 +350,9 @@ for every site:**
`isAdmin(req.user)` keeps working on the server; prefer `isAdmin(req.user, req.payload)`.
`grep -rnE "isAdmin\(|isEditor\(|hasMinimumRole\(" src` — a call in a **client component** or in `proxy.ts` /
middleware now returns `false` without a source: `isAdmin(user, config)` (`useConfig()`), or
`isAdmin(user, { staffCollections: ['users'] })`.
`isAdmin(user, { staffCollections: ['users'] })`. A **client component imports them from
`@intecion/ipal-kit/client`** (not in 1.16.4–1.16.6: go to 1.16.7); the main entry there fails with
`next build --webpack` (`'server-only' cannot be imported from a Client Component module`).
4. `pnpm exec ipal-doctor --url <site>` (with the doctor token) → accounts without 2FA must be 0. An account that
has not set TOTP up opens everything with its password alone: have its owner set it up now, or remove it.
5. Tell the owner what the CHANGELOG entry says under "Requires project changes" and agree on it: new SMTP
@@ -380,6 +382,120 @@ gets `403` from the same addresses and from `POST /api/setup-totp`. The Coolify
strips `back`, can keep them (`twoFactor.safeBack: false` turns the plugin's check off).
2. `pnpm ipal:skills`.
**→ 1.16.6 — 2FA setup required (CHANGELOG 1.16.6; PROGRAMISTA §6, item 68; security.md "Setup required") — required with 2FA on:**
**Not a routine patch, although the number is one.** From this version an account without 2FA can only set it up and is
blocked after 72 hours; on Postgres / SQLite a missing migration locks everyone out of the panel. Do not upgrade a live
site without steps 1–3 and a deploy day agreed with the owner. Steps 2, 3 and 5 go in ONE deploy.
1. **Before upgrading a live site:** `pnpm exec ipal-doctor --url <site>` (doctor token) → accounts without 2FA.
Tell the owner: from the upgrade on, such an account can only set 2FA up, and has 72 hours for it; after that
an administrator must reopen setup on the account's page. Have them set it up now, or remove unused accounts.
Make sure at least one administrator (better two) has 2FA set up — otherwise nobody can reopen setup from the panel.
The 72 hours of existing accounts start at the first start after the deploy and are counted once (restarts
and redeploys do not extend them): agree the deploy day with the owner.
2. Update the package, `pnpm install`, `pnpm ipal:skills`, `pnpm payload generate:types`,
**`pnpm payload generate:importmap`** (new: `TwoFactorStatusField`, `TwoFactorAlert`; commit `importMap.js`),
then `pnpm exec ipal-doctor` before deploying.
3. **Postgres/SQLite — required, same deploy, or nobody can log in:** `pnpm payload migrate:create` (adds the
column `totp_setup_from` to the 2FA collection; needed whenever 2FA is on, also with `requireSetup: false`),
commit, and have it applied **when the new container starts**: `prodMigrations` in the database adapter, or the
start command `pnpm payload migrate && pnpm start` (deployment.md §4.3). **Never Coolify's Pre-deployment
command** — it runs in the old container, without the new migration, and the new version then starts without
the column. Without the column every login answers 500, administrators included; the log says
`[ipal] 2FA: the column for "totpSetupFrom" is missing … NOBODY CAN LOG IN`. `pnpm exec ipal-doctor` reports
it before the deploy. MongoDB: nothing.
4. An integration that logs in with a password and has no TOTP: give it an API key, or
`twoFactor.requireSetup: { exempt: ({ user }) => user.email === '…' }`. `grep -rn "overrideAccess: false" src`:
a `user` fetched by id is refused for every account now — take it from `payload.auth({ headers })`.
5. `rm -rf .next`, build, redeploy on Coolify. Read the first lines of the log: `[ipal] 2FA: N existing account(s)
without two-step verification…` — pass that number to the owner. The line appears on that first start only.
Postgres/SQLite: if logins answer 500 after the deploy, the migration from step 3 did not run — check that it
is committed and that the container runs migrations at start (deployment.md §4.3), then redeploy.
6. `requireSetup.exempt` must be a plain function returning `true` / `false` (an `async` one stops the start).
A script on an API key is refused by `POST /api/ipal/two-factor/reset` by default — pass
`twoFactor.resetAccess` if that is wanted. A reset ends the account's sessions (it logs in again); after a
suspected compromise change the password too. An SVG favicon has no tab icon on the 2FA screens.
7. Tell the owner what to tell the staff: a new account has 72 hours to set 2FA up, then an administrator must
choose "Reopen setup". Not wanted: `twoFactor.requireSetup: false`, or `{ windowHours: false }`.
**Every administrator is blocked** (all missed the 72 h): security.md "Every administrator is blocked" — a
`pnpm payload run` script that sets `totpSetupFrom` to now for one administrator, or
`requireSetup: { windowHours: false }` + redeploy, set 2FA up, put it back.
**Check:** create a throwaway account → its token gets `403` from `/api/users/me`; in the panel it lands on the
setup screen with "Set up two-step verification by …"; after the code it is in. As an administrator open that
account → "Two-step verification: Set up." and the reset button; delete the account.
**→ 1.16.7 (hardening; CHANGELOG 1.16.7; PROGRAMISTA §6, item 69) — not a routine patch: agree the deploy with the owner, read every point, most sites change nothing:**
1. Update the package, `pnpm install`, `pnpm ipal:skills`, `pnpm payload generate:types`. No import-map change, **no
schema change and no migration** on any database (the verify count uses Payload's own `payload-kv`
collection). `grep -n "staffCollections\|authCollection" src/payload.config.ts`: every slug there must be an
auth collection of the config — with a wrong one Payload does not start (the slug is in the log; `/api/health`
answers 503, so with a health check Coolify keeps the old container).
2. **Panel access by role.** After the first start read the log: `[ipal] N account(s) of "users" are below the
role "editor" and cannot open the admin panel`. Those accounts (role `user`, or no role) now see
"Unauthorized" in the panel. Give the people who work in the panel `editor`, or set
`accounts: { panelRole: 'user' }`. The line `NOBODY can open the admin panel` (an error) means no account has
the role: fix with a script (`payload.update({ collection: 'users', id, data: { roles: ['admin'] } })`,
`pnpm payload run`) or `accounts: { panelRole: false }` + redeploy.
3. **Secrets are write-only.** Nothing to do for a normal site: the SMTP password and Turnstile secret stay
stored; the panel shows "a value is set". `grep -rn "smtpPassword\|turnstileSecretKey" src` — code that read
them over REST / GraphQL as an admin, or with `overrideAccess: false`, now gets `'********'`: read them on the
server with `payload.findGlobal({ slug: 'site-integrations' })`. A script that saves the whole global back
keeps the secrets (the mask means "keep"). **New:** a save in the panel or over the API that changes the SMTP
server, port or user name must send the password again ("Enter the password again…"), also when the transport
is set to Microsoft Graph; a script that does that over REST / GraphQL sends the password with it, a seed
with the Local API is not asked. `secrets: { reenterOnChange: false }` turns it off. During a rolling update a page opened under the new version and saved against the OLD one stores
`********` as the password: after the deploy, check that a test e-mail goes out.
4. **`TURNSTILE_SECRET_KEY` is deprecated** (it still works). If the log says `[ipal] Deprecated: the Turnstile
secret key comes from the TURNSTILE_SECRET_KEY environment variable` or `ipal-doctor --url` reports
`turnstile-env-key`: with the owner, copy the key into Site integrations → Spam protection → Secret key, send a
test form, then remove the variable in Coolify. Do not do it on a client site without the owner. Nothing
breaks if you wait; the removal will be announced in the changelog.
5. **Forms with files and Turnstile.** While Turnstile cannot check (wrong keys, Cloudflare down), a form with a
File field is now refused (text forms are accepted as before). Check `ipal-doctor --url` → no
`turnstile-degraded`; to keep the old behaviour: `forms: { turnstileOnConfigError: { files: 'allow' } }`.
6. **Account creation and changes.** A project whose **own** staff collection has no `create` / `update` /
`delete` / `unlock` / `read` rule gets one (before: any signed-in account of any auth collection — a customer
could change a staff password, list the staff accounts, lift a login lock):
- the collection carries the plugin's roles (`access.authCollection`, or a `roles` select with only `user` /
`editor` / `admin`): create, delete, unlock — an admin; update — an admin or the account itself; its
`roles` field — only an admin (when the field has no `access.update` of its own). **Check:** does a
non-admin create or edit other accounts, or change roles, there today? Then write the rule you want;
- the collection has **role values of its own** (`superadmin`, …) or no roles: accounts of that collection
keep working as before, except that an account no longer changes its **own** roles; accounts of other
collections are refused. **Write your own rules** — the plugin does not know your roles, and inside the
collection every account can still create an account with any role (`ipal-doctor --url` →
`staff-own-roles`);
- `read`: only staff accounts read a staff collection. **Check:** does the front end show staff accounts
(an author box) to logged-in visitors with the visitor's session? Then write that collection's `read` rule,
or `accounts: { staffOnlyRead: false }`. Anonymous visitors never could.
A staff collection added by a plugin listed after ipalKit gets the same rules at start, put in FRONT of the
rules it has (both must allow). If that plugin's collection needs a rule wider than the plugin's default,
set `custom: { ipal: { accountRules: false } }` on it.
`first-register` on any auth collection other than the panel's login collection answers `403` unless that
collection allows sign-up. `access.firstUserAdmin: false` with a default role below `editor`: the panel role
is not applied (a warning at start), or — with `accounts.panelRole` set — the start fails with the fix in the
message. Wanted otherwise: `accounts: { adminOnlyCreate: false, adminOnlyWrite: false, staffOnlyRead: false,
firstUserRoute: 'all' }`.
7. **Passwords.** New passwords of staff accounts need 12 characters; **existing shorter passwords keep
working** — nobody is logged out or asked to change. A script that creates staff accounts with a short
password fails with a validation error: lengthen it, or `accounts: { password: { minLength: 8 } }`.
8. **2FA attempts from another origin** get `403`. A panel or front end on **another domain** than the API that
posts to `/api/verify-totp`: add it — `twoFactor: { …, sameOrigin: { origins: ['https://panel.example.com'] } }`
(or set Payload's `csrf` / `cors`). A same-domain site changes nothing **when the server knows its own
address**: `serverURL` is set, or the proxy passes `Host` (Coolify / Traefik do) or `X-Forwarded-Host`.
**Check before the deploy:** is `serverURL` set? If not and the proxy rewrites `Host` (nginx's plain
`proxy_pass`), nobody can enter a 2FA code after the upgrade — set `serverURL`. After the deploy log in with
a code; if it answers "Not allowed from this origin.", the log has `[ipal] 2FA: a code from origin "…" was
refused` with the fix.
9. **Dashboard alerts.** Editors now see "An integration needs attention. Ask an administrator." instead of the
error text; accounts with only `user` see no alerts. `dashboardAlerts: { integrations: 'all' }` restores it
(`'all'` checks no role and no second factor).
10. **Role checks in client components.** `grep -rlE "^['\"]use client" src | xargs grep -nE "from '@intecion/ipal-kit'"`
— a file that imports `isAdmin`, `isEditor` or `hasMinimumRole` there: change the import to
`@intecion/ipal-kit/client` and keep the second argument (`isAdmin(user, config)`). `import type` may stay.
**Check:** `pnpm exec ipal-doctor --url <site>` (new rules: `access-missing`, `csrf-empty`, `open-signup`,
`staff-accounts-open`, `staff-own-roles`, `turnstile-degraded`, `turnstile-env-key`); as an admin `GET /api/globals/site-integrations` shows
`"smtpPassword":"********"`; a test e-mail and a test form still work; an editor and an admin still log in.
## 2. Inventory (no code changes)
**What changed for projects** between your old and new plugin version is exactly the reference site's diff —
`git diff v<old> v<new> -- reference/` in the ipal-kit repo (or the two `docs/agent/reference-site/INDEX.md` files):
+1 -1
View File
@@ -86,7 +86,7 @@ URLs point at that domain. Outside production, `R2_PUBLIC_URL` alone → read-on
| `R2_SECRET_ACCESS_KEY` | ⬜ (✅ prod) | storage | R2 secret |
| `R2_PUBLIC_URL` | ⬜ (✅ prod only with `storage: { requirePublicUrl: true }`) | storage | media domain attached to the bucket; empty = media through the app (§6); dev: also the `/media` path |
| `IPAL_IP_HEADER` | ⬜ (✅ prod) | forms | header with the real IP for the rate limit (`cf-connecting-ip`, `x-forwarded-for`); without it, a warning in the log |
| `NEXT_PUBLIC_TURNSTILE_SITE_KEY`, `TURNSTILE_SECRET_KEY` | ⬜ | forms | fallback when the Turnstile keys are not in Site integrations |
| `NEXT_PUBLIC_TURNSTILE_SITE_KEY`, `TURNSTILE_SECRET_KEY` | ⬜ | forms | fallback when the Turnstile keys are not in Site integrations. **`TURNSTILE_SECRET_KEY` is deprecated** — put the secret key into the panel (turnstile.md); the variable keeps working until a later, announced release |
| `INDEXNOW_KEY` | ⬜ | SEO | IndexNow key (takes precedence over the key from the panel) |
| `IPAL_COOKIE_SCAN_URL`, `IPAL_COOKIE_SCAN_TOKEN` | ⬜ (✅ prod with `ipalEnvRules({ cookieCrawl: true })`) | consent | cookie crawl (`cookieScanner.crawl`): the shared scanner service's URL and this site's token ([cookie-scanner.md](./cookie-scanner.md#browser-crawl)) |
| `IPAL_NOINDEX` | ⬜ | SEO | `1`/`true`/`yes` **on staging only** — the whole site is noindex (robots, meta, `X-Robots-Tag`) |
+3
View File
@@ -675,6 +675,9 @@ Do one item at a time, build, check. Order by importance:
| 65 | **1.16.4 — security** — with 2FA on, a login with the password only gets `200` from `/api/globals/site-integrations` or `/api/form-submissions`; or the project has a second auth collection (`customers`) | Upgrade and redeploy (no config change with one auth collection). With the owner: change the SMTP password and the Turnstile secret, review Site settings / Site integrations / each form's Emails tab for values nobody set. Second auth collection: `admin: { user }` in `buildConfig`, `adminOrSelfIn('<slug>')`, `access.staffCollections` only for a second STAFF collection. Every account must have 2FA set up (`ipal-doctor --url` → 0 without). Own endpoints: `secondFactorPassed(req)`; own `overrideAccess: false` calls: `user` from `payload.auth()`. `pnpm ipal:skills`; no migration | CHANGELOG 1.16.4, security.md "What the second factor covers", access.md "Who is staff" |
| 66 | **1.16.4** — production `PAYLOAD_SECRET` shorter than 32 characters (the site would stop at `assertEnv`) | Before deploying 1.16.4, check the length in Coolify (`node -e 'console.log(process.env.PAYLOAD_SECRET.length)'`). Shorter: a random 32+ character secret (logs everyone out, asks for 2FA again, breaks stored API keys), or `ipalEnvRules({ secretMinLength: 0 })` for now | CHANGELOG 1.16.4, deployment.md "PAYLOAD_SECRET — length and changing it" |
| 67 | **1.16.5 — security** — with 2FA on, `/admin/verify-totp?back=https%3A%2F%2Fexample.com%2F` sends the user to example.com after the code (and `back=javascript:…` runs script in the panel) | Upgrade and, **in ONE deploy**, `pnpm payload generate:importmap` (adds `@intecion/ipal-kit/admin#SafeTotpView`), commit `importMap.js`, `rm -rf .next`, redeploy on Coolify — with the old map the 2FA screens have no code form and nobody can sign in (run `pnpm exec ipal-doctor` before deploying; the start log says so too); check: the link above ends on `/admin`. `pnpm ipal:skills`. No option, env or migration; off / own rule: `twoFactor.safeBack` | CHANGELOG 1.16.5, security.md "The `back` link of the 2FA screens" |
| 68 | **1.16.6 — 2FA setup required** (not a routine patch: a new default that can lock accounts out) — an account that has not set 2FA up still reads data over the API with its password; or after the upgrade an account "can do nothing" / is blocked | Before upgrading: `ipal-doctor --url` → accounts without 2FA set it up or are removed; one admin (better two) must have 2FA; deploy day agreed with the owner. Then, in ONE deploy: update, `generate:types`, `generate:importmap` (`TwoFactorStatusField`, `TwoFactorAlert`), **Postgres/SQLite: `migrate:create` and the migration applied in the same deploy when the new container starts — `prodMigrations` or `pnpm payload migrate && pnpm start`, never a pre-deployment command (deployment.md §4.3) — (column `totp_setup_from`); without it every login answers 500**, build, redeploy. Existing accounts get 72 h from the first start; blocked later → admin: account page → "Reopen setup". Password-login integrations: API key or `requireSetup.exempt`. `pnpm ipal:skills` | CHANGELOG 1.16.6, security.md "Setup required" |
| 69 | **1.16.7 — hardening** (not a routine patch: stricter defaults) — an account with only the role `user` sees "Unauthorized" in the panel; or the API returns `"smtpPassword":"********"`; or a form with a File field is refused while Turnstile is misconfigured; or "The password must have at least 12 characters."; or "Enter the password again…" on the SMTP password; or `403` "Not allowed from this origin." on the 2FA code | Update, `generate:types`, redeploy; no import map, schema or migration. Every slug in `access.staffCollections` must be an auth collection (otherwise Payload does not start: `/api/health` 503, the old container keeps serving). Set `serverURL` (a proxy that rewrites `Host` otherwise blocks the 2FA code; the log names the origin). Read the start log (`N account(s) … cannot open the admin panel`) and give panel users `editor`. Own code that read the two secrets over the API → Local API on the server. `TURNSTILE_SECRET_KEY` is deprecated: with the owner move the key into the panel. Own staff collection without rules: an admin (update: or the account itself; roles only by an admin; read by staff only) where the roles are the plugin's, accounts of that collection where they are the project's own — write that collection's own rules. Existing short passwords keep working. Switches: `accounts`, `secrets`, `forms.turnstileOnConfigError`, `twoFactor.sameOrigin`, `dashboardAlerts`. `pnpm ipal:skills` | CHANGELOG 1.16.7, access.md "Account rules", security.md "Stored secrets", turnstile.md |
| 70 | **1.16.7** — `next build --webpack`: `'server-only' cannot be imported from a Client Component module`, from a `'use client'` file that imports `isAdmin`, `isEditor` or `hasMinimumRole` | Import them from `@intecion/ipal-kit/client` in client components, keep the second argument (`isAdmin(user, config)`); `import type` may stay on the main entry | CHANGELOG 1.16.7, access.md |
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`.
+10 -3
View File
@@ -66,7 +66,7 @@ Added by `ipalKit` and **off until the site has `IPAL_DOCTOR_TOKEN`** (at least
returns counts only — never names, e-mails or values:
```json
{ "node": "v22.20.0", "pendingCookies": 0, "plugin": "1.15.0", "usersWithout2fa": 0 }
{ "node": "v22.20.0", "openSignUp": [], "pendingCookies": 0, "plugin": "1.15.0", "staffOnOwnRoles": [], "staffOpenToOthers": [], "turnstile": null, "turnstileSecretFromEnv": false, "usersSetupClosed": 0, "usersWithout2fa": 0 }
```
Turn off: `ipalKit({ doctor: false })`. Adapt: `ipalKit({ doctor: { tokenVar: 'MY_TOKEN', access: ({ req }) => isAdmin(req.user, req.payload) } })` (a logged-in staff admin may read it too; the second factor is checked for you — never test `req.user.roles` by hand, an account of another collection can carry the same value)
@@ -89,7 +89,7 @@ Turn off: `ipalKit({ doctor: false })`. Adapt: `ipalKit({ doctor: { tokenVar: 'M
| | `layout-forbidden` | error | no `middleware.ts`, no `lib/{pages,locales,navigation}.ts`, `fields/{link,sectionHeader,sectionSettings}.ts` |
| | `layout-extra` | info | `src/` entries outside the allow list (AGENT.md §3 + `seed/`, `design/`, `db.ts`, `env.rules.ts`, `content.config.ts`; extend with `layout.allow`) |
| | `naming` | warning | block folders, collection and global files PascalCase, `scripts/*` kebab-case, no `index.ts` barrels |
| | `importmap` | error | the import map exists, holds the entries for what the config turns on (2FA, R2, cookie scanner, `adminMeta`), names no export the plugin no longer has; with `--deep`, equals a fresh one. Warning: the config uses the 2FA package's own setup / verify view as a view's `Component` (outside the `back` link check — security.md); not for that path as `ipalTotpView` of `SafeTotpView` or in `admin.dependencies` |
| | `importmap` | error | the import map exists, holds the entries for what the config turns on (2FA incl. `SafeTotpView`, `TwoFactorStatusField`, `TwoFactorAlert`; R2, cookie scanner, `adminMeta`), names no export the plugin no longer has; with `--deep`, equals a fresh one. Warning: the config uses the 2FA package's own setup / verify view as a view's `Component` (outside the `back` link check — security.md); not for that path as `ipalTotpView` of `SafeTotpView` or in `admin.dependencies` |
| | `tsconfig-skills` | error | `tsconfig.json` excludes the skills folder |
| env | `db-name` | error | `DATABASE_URI` in `.env` and `.env.example` names `<domain without dots>_dev`; a local `.env` on `_prod` is an error; `--env-file` checks `_prod` (`databaseNamesFor`) |
| | `env-rules` | error / warning | `instrumentation.ts` calls `assertEnv(ipalEnvRules(…))` from `/env`, with `storage` (R2), `cookieCrawl` (crawl), `ipHeader`; `databaseName` suggested (info) |
@@ -98,7 +98,14 @@ Turn off: `ipalKit({ doctor: false })`. Adapt: `ipalKit({ doctor: { tokenVar: 'M
| security | `security-headers` | error | `buildSecurityHeaders`; live: HSTS, nosniff, Referrer-Policy, Permissions-Policy, frame protection |
| | `powered-by` | error | `withSecurityConfig`; live: no `X-Powered-By` on `/` and the admin |
| | `csp` | warning / info | CSP on the site and the admin; report-only is info, a warning after 4 weeks (`seen`) |
| | `2fa` | error | `twoFactor: { plugin: payloadTotp }` + the package; deep: 0 users without TOTP |
| | `2fa` | error | `twoFactor: { plugin: payloadTotp }` + the package; deep: 0 users without TOTP (the message says how many of them are blocked because their setup window has passed); error: a Postgres / SQLite project whose migrations do not mention the 2FA column `totp_setup_from` (every login would answer 500; a warning when there is no migrations folder — the doctor cannot see a schema that gets there another way); warning: `twoFactor.requireSetup: false`; info: no setup window (`windowHours: false`) |
| | `access-missing` | warning | `ipalKit` has an `access` option — without it there are no roles and every panel account is an admin |
| | `csrf-empty` | warning | the config sets `serverURL` or `csrf` — otherwise Payload accepts the login cookie from any origin |
| | `open-signup` | info | (deep) auth collections whose `create` rule lets an anonymous request through: sign-up is open there (intended for a customer zone — silence with a reason) |
| | `staff-own-roles` | warning | (deep) a staff collection with role values of its own (not `user` / `editor` / `admin`) that runs on the plugin's default account rules: the plugin cannot rank those roles, so inside the collection every account may create an account with any role and change or delete another. Write the collection's own rules |
| | `staff-accounts-open` | error (warning for `read`, `readVersions`) | (deep) a staff collection that an account of another, non-staff auth collection may create in, read (also its versions), update, delete from or unlock — it can make itself staff, change a staff password, list the accounts or lift a login lock. The account rules are off (`accounts: false`, `adminOnlyCreate` / `adminOnlyWrite` / `staffOnlyRead: false`) or the project's own rule is wider. Asked with a made-up outside account; a rule that throws counts as closed |
| | `turnstile-degraded` | warning / error | (deep) Turnstile is checking forms; while it is not (wrong or missing secret, Cloudflare down) a warning, an error once it has lasted 24 hours (counted from the recorded start to now) |
| | `turnstile-env-key` | warning | (deep) the Turnstile secret key is in the panel, not in the deprecated `TURNSTILE_SECRET_KEY` environment variable |
| | `cookie-scanner` | error / warning / info | `cookieScanner` on (with `crawl`, else info); deep: nothing waits for approval (warning) |
| admin | `admin-meta` | warning | ipal-kit ≥ 1.14.5, no `adminMeta: false` / `agency: false`; live: the admin `og:image` is `/api/ipal/admin-og` |
| | `admin-noindex` | error | (live) the admin login page is noindex |
+5 -1
View File
@@ -24,7 +24,11 @@ install it (nodemailer 10 ships its own types, so `@types/nodemailer` is not nee
No plugin options — SMTP (`smtpHost`, `smtpPort` (default 587), `smtpUser`,
`smtpPassword`, `smtpFromAddress`, `smtpFromName`) and `emailTransport` live in
SiteIntegrations (E-mail sending tab). The editor configures them in the panel. The plugin does **not** set
SiteIntegrations (E-mail sending tab). The editor configures them in the panel.
- **The password is write-only and stays with its server**: the panel shows "A value is set"; changing the
server, port or user name asks for the password again
([security.md](./security.md) "Stored secrets"). The plugin does **not** set
`config.email` — you wire the adapter yourself (below).
## Front — sendEmail (server)
+1 -1
View File
@@ -227,7 +227,7 @@ the File field shows "The file … was refused: …", nothing is stored or sent.
| `notice` | built-in text | the "not checked for viruses" line in the e-mail: `false` = none, a string or `(locale) => string` = your own |
| `maxConcurrent` | `2` | file submissions handled at once per instance (each holds its files in memory); more get the "too many attempts" message; `0` = no guard |
| `path` | `'/ipal/forms/submit'` | endpoint path under the API route |
| `submit` | `{}` | the endpoint's gates, same meaning as in `createSubmitAction`: `maxPerMinute`, `clientIp`, `honeypotField`, `turnstileHostnames`, `turnstileOnConfigError`; `allowedOrigins` (other origins allowed to post, e.g. a front end on another domain); `idleTimeoutMs` (default `30000`: no byte of the upload for this long → the request is given up, `0` = off) and `timeoutMs` (default `300000`: ceiling for the whole request, `0` = off) |
| `submit` | `{}` | the endpoint's gates, same meaning as in `createSubmitAction`: `maxPerMinute`, `clientIp`, `honeypotField`, `turnstileHostnames`, `turnstileOnConfigError`; `allowedOrigins` (other origins allowed to post, e.g. a front end on another domain); `idleTimeoutMs` (default `30000`: no byte of the upload for this long → the request is given up, `0` = off) and `timeoutMs` (default `300000`: ceiling for the whole request, `0` = off) **While Turnstile cannot check (wrong or missing secret, Cloudflare down) this endpoint refuses the submission by default** — `forms.turnstileOnConfigError: { files: 'allow' }` or `submit.turnstileOnConfigError: 'allow'` changes it (turnstile.md) |
Built-in types (`FORM_FILE_TYPES`): PDF, DOC, DOCX, ODT, RTF, XLS, XLSX, JPG, PNG, WebP. A new field has PDF, DOC and
DOCX ticked.
+277 -13
View File
@@ -425,17 +425,120 @@ that session's cookie (images from `media`) are refused, so an editor who typed
sees broken images on the site until the code is entered or they log out.
An account of the 2FA collection passes when it logged in with **password and code**, or uses an **API key**
(`auth.useAPIKey`), or has **not set TOTP up yet** (the setup screen needs that; the package behaves the same).
Everything else is refused, including a user object the check does not recognise. Accounts of other auth
(`auth.useAPIKey`). An account that has **not set TOTP up yet** is refused as well ("Setup required" below; the
package alone lets it through). Everything else is refused, including a user object the check does not recognise. Accounts of other auth
collections, anonymous visitors, bearer-token routes (`/api/ipal/doctor`, the cookie-crawl callback, MCP) and
the Local API with `overrideAccess: true` (the default) are not affected.
> **Until an account has set TOTP up, its password alone opens everything its role allows** — Site
> integrations with the SMTP password included. Enforced setup is a redirect in the panel; over the API such an
> account is an ordinary logged-in account (it has to be, or it could not set TOTP up). So: **set 2FA up right
> after an account is created** — create the account, log in as it, scan the code, in one sitting — and never
> leave an invited account waiting. `ipal-doctor --url` reports the number of accounts without 2FA
> (`2fa`, deep check); it must be 0.
### Setup required (`twoFactor.requireSetup`, on by default)
An account that has **not set TOTP up yet** reaches nothing at the access level — REST, GraphQL, the panel's
data, the plugin's endpoints — until it has. It gets the setup screen and `POST /api/setup-totp`, and what
Payload gives any logged-in session about itself (`/api/access`, token refresh, logout, its own panel
preferences), nothing else.
The 2FA package alone only redirects such an account inside the panel; over the API its password would open
everything its role allows.
**The setup window.** An account has **72 hours** to set TOTP up, counted from its creation or from the last
reset by an administrator. After that it is **blocked**: setup is refused too, until an administrator reopens
it. Without the window, whoever learns the password of an account that never set TOTP up could enrol their own
authenticator at any time; with it, that is possible only in the first days of the account.
| Situation | What happens |
|---|---|
| New account (also the first admin of a fresh site) | logs in → setup screen with the notice "Set up two-step verification by <date>…" → after the code, the panel |
| Not set up within the window | login still works, every request answers 403, the setup screen says the time has passed and to ask an administrator |
| Administrator reopens setup / resets a lost phone | the account's page in the panel → **Two-step verification** (sidebar) → "Reopen setup" / "Reset two-step verification"; or `POST /api/ipal/two-factor/reset` with `{ "userId": "…" }`. A new window starts |
| Administrators' overview | a notice on the dashboard: accounts without two-step verification, and how many of them are blocked; `ipal-doctor --url` reports the same as an error |
| API key (`auth.useAPIKey`) | passes, whatever the setup state |
| Seeds, scripts, the Local API with `overrideAccess` (the default) | not affected |
| Bearer-token routes (`/api/ipal/doctor`, the cookie-crawl callback), MCP | not affected (no user) |
| `twoFactor: false` | none of this exists |
**Accounts that existed before this mode** (an upgrade): their window starts at the **first start of the site
after the upgrade**, not at their creation date, so nobody is blocked the moment a site upgrades. The server log
says how many there are: `[ipal] 2FA: N existing account(s) without two-step verification. They have 72 h from
now to set it up…`. From that moment they can only set TOTP up; after 72 hours they are blocked until an
administrator reopens setup. **Before upgrading a live site, run `pnpm exec ipal-doctor --url <site>`** (accounts
without 2FA) and have those accounts set TOTP up, or remove the ones nobody uses.
That starting moment is **written once**, on each such account (`totpSetupFrom`), by the start that first finds
the account without one. Later starts, redeploys and further instances find nothing left to do (the log line
appears on that first start only), and editing the account or logging in does not move it — so a redeploy never
hands out another 72 hours. Only an administrator's reset / "Reopen setup" opens a new window. An existing
account that **has** TOTP gets no start; if its TOTP is removed later, its window starts then. On Postgres /
SQLite the migration that adds the column must run in the same deploy (see "Data" below) — the first start
after it is the one that counts.
```ts
twoFactor: {
issuer: 'Company Name',
plugin: payloadTotp,
// requireSetup: { windowHours: 24 }, // another window
// requireSetup: { windowHours: false }, // no time limit (0 works too): locked until set up, never blocked
// requireSetup: { exempt: ({ user }) => user.email === 'integration@example.com' }, // a service account that logs in with a password, on purpose
// requireSetup: { dashboardNotice: false, statusField: false, setupNotice: false }, // each panel part can be switched off; the lock stays
// requireSetup: false, // the 2FA package's rule: redirect in the panel, API open until setup
// who may reset / reopen. Default: a staff admin whose session entered its own TOTP code. Your function replaces
// that rule, so keep the code check in it unless you mean to let API-key / exempt admins reset:
// resetAccess: ({ req }) => req.user?._strategy === 'totp' && isAdmin(req.user, req.payload),
}
```
- **Data.** The 2FA collection gets a date field `totpSetupFrom` (hidden, written by the plugin only) **whenever
2FA is on** — also with `requireSetup: false` or `guard: false`, so that switching the mode does not change the
schema — and, with the mode on, a panel-only field `totpSetupStatus`. MongoDB: nothing to do.
**Postgres / SQLite: the migration is a required step of the same deploy.** Run `pnpm payload migrate:create`, commit the migration, and
have it applied **when the new container starts** — `prodMigrations` in the database adapter, or the start command `pnpm payload migrate && pnpm start` ([deployment.md §4.3](./deployment.md#43-database-migrations-postgres)). **Not Coolify's Pre-deployment command:** it runs in the old container, which does not have the new migration, so the new version would start without the column.
Without the column every query on the 2FA collection fails: **every login answers 500 —
administrators with 2FA included — and nobody can sign in to the panel** (the public site keeps working). The
log says `[ipal] 2FA: the column for "totpSetupFrom" is missing … NOBODY CAN LOG IN …` at start;
`ipal-doctor` reports a SQL project whose migrations do not mention `totp_setup_from` (error; a warning when
there is no migrations folder at all — it cannot see a schema that is pushed some other way). Recovery: run
the migration; no data is lost.
- **`exempt` must answer `true` or `false` at once.** It runs inside access checks, which cannot wait. An
`async` function stops the site at start with a clear error; any answer other than exactly `true` (a Promise,
a string, an error) exempts nobody and is logged once. Decide from the fields on `user`. An exempt account
works on its password alone, so give it the lowest role that does its job.
- **`windowHours`** must be a number (0 or more) or `false`; anything else (`'24'`, `-1`) stops the site at start.
- **Import map.** The status field and the dashboard notice are admin components: `pnpm payload
generate:importmap` after upgrading (`TwoFactorStatusField`, `TwoFactorAlert`); `ipal-doctor` reports a map
that lacks them. Without them the panel has no "Reopen setup" button (the endpoint still works).
- **Switch a part off:** `requireSetup: { dashboardNotice: false }` (the administrators' notice),
`{ statusField: false }` (the status / reset control on the account; the endpoint stays),
`{ setupNotice: false }` (the notice on the setup screen). None of them changes who is refused. The logo and
icon fetched by the server for the 2FA screens: `whiteLabel.inlineImages: false`, `adminMeta.serveIcon: false`
([white-label.md](./white-label.md)).
- **Building blocks** (`@intecion/ipal-kit`), for a project that wires the mode itself: `buildSetupFields`,
`stampSetupFrom`, `backfillSetupFrom`, `buildTwoFactorResetEndpoint`, `countAccountsWithoutTotp`,
`resolveRequireSetup`, `strictExempt`, `SETUP_FROM_FIELD`, `TWO_FACTOR_RESET_PATH`, `DEFAULT_SETUP_WINDOW_HOURS`.
- **Per collection or global:** the opt-out below (`custom.ipal.secondFactor`) also lets an account without TOTP
in, because it takes the entity out of the second-factor check altogether.
- **Needs** ipal-kit's check (`twoFactor.guard`, on by default); with `guard: false` the mode is off.
- **Project code** that calls `payload.find({ …, user, overrideAccess: false })` with a user fetched by id: refused
for every account of the 2FA collection now — before, only for accounts that had TOTP set up. Take the user from
`payload.auth({ headers })`.
- **In your own code:** `twoFactorSetupState(req)` → `'set-up' | 'open' | 'closed' | 'exempt' | 'not-applicable'`,
`twoFactorSetupDeadline(req)` → `Date | null`.
- **Texts** (English and Polish; override in `i18n.translations.<lang>.ipal`): `twoFactorSetupDeadline`,
`twoFactorSetupRequired`, `twoFactorSetupClosed`, `twoFactorStatus*`, `twoFactorReopen`, `twoFactorReset*`,
`twoFactorAlert*`.
**The brand on the setup and verify screens.** A session that still owes its code is refused `media` like every
other collection, so the browser could not load the panel's logo or tab icon from it. The plugin therefore hands
such a session the picture itself — fetched on the server without any credentials, exactly as an anonymous visitor
gets it (`AdminLogo` / `AdminIcon` as a `data:` address; `GET /api/ipal/admin-icon` answers with the image
instead of a redirect when the favicon is a bitmap — never with an SVG, which keeps the redirect). Nothing is opened by this: when `media` is not publicly readable, or the file is larger
than 512 KB, the site name (or the browser's own attempt) is used instead.
**What it does not do.** Inside the window, someone who knows the password of an account that has not set TOTP up
can still set it up with their own authenticator. The real owner then cannot ("already set") and has to ask an
administrator — the takeover is visible, and the window keeps it to the first days. So still: **create the
account, hand over the password, and have the owner set 2FA up at once.**
**Check:** create an account, log in over the API with its password → `403` from `/api/users/me` and
`/api/globals/site-settings`; open the panel as that account → the setup screen with the notice; enter the code →
the panel. As an administrator open the account → "Two-step verification: Set up."
**Verify attempts are limited** (`twoFactor.verifyLimit`). The package checks the code and never counts tries;
a six-digit code has about three right answers in a million, so whoever held the password could guess. ipalKit
@@ -443,13 +546,39 @@ counts attempts per account on `POST /api/verify-totp`: by default the **sixth a
right or wrong — is refused with `429` and `Retry-After`, and a line goes to the log. Only a session that already
passed the password reaches the endpoint, so nobody without the password can lock an account's owner out; someone
who has the password can delay the owner's login by ten minutes at a time (and that shows in the log). Counted in
memory per server instance. `verifyLimit: { max: 10, windowMinutes: 5 }` changes it, `verifyLimit: false` turns
it off (a limiter in front of the site).
memory per server instance **and in the database** (Payload's key-value store, `payload.kv` — the `payload-kv`
collection Payload itself adds; no new collection): a restart, a redeploy or a second instance does not hand out
new attempts. The higher of the two counts decides; when the database part fails, the memory count still does
(there is no "allow when the store fails" path). `verifyLimit: { max: 10, windowMinutes: 5 }` changes it,
`{ store: 'memory' }` keeps the count in this instance only, `verifyLimit: false` turns it off (a limiter in
front of the site).
**Verify and setup attempts only from the site's own origin** (`twoFactor.sameOrigin`). The limit counts every
attempt of an account, so a page that can make the browser send the account's login cookie could burn the
owner's attempts and lock them out — no password needed. A sibling subdomain is such a page (`SameSite=Lax` does
not stop it, and Payload's own `csrf` list is empty unless `serverURL` or `csrf` is set). So
`POST /api/verify-totp` and `POST /api/setup-totp` refuse (`403`) a request that the browser marks as coming from
elsewhere — the `Origin` header, else `Sec-Fetch-Site` — **before it is counted**. Own origins: the host the
request came in on (`Host`, `X-Forwarded-Host`), `serverURL`, Payload's `csrf` and `cors` lists, and
`twoFactor: { …, sameOrigin: { origins: ['https://app.example.com'] } }` for a front end on another domain.
A request with neither header (a script, `curl`, a server) passes: it cannot ride on somebody's cookie.
A default port written out (`X-Forwarded-Host: site.example:443`) is the same host.
`sameOrigin: false` turns it off.
**Behind a reverse proxy that hides the site's address** — it rewrites `Host` and sends no `X-Forwarded-Host`
(nginx's plain `proxy_pass`; Traefik and Coolify keep `Host`) — and without `serverURL`, the server cannot know
its own address: the site's own verify page is refused, and **nobody can enter a code**. It is not silent: the
first refusal of every origin is logged, `[ipal] 2FA: a code from origin "https://…" was refused and not counted
— it is not one of this site's own origins (…)`, with the three ways out: set `serverURL` (the right fix, it
also fills Payload's `csrf` list), or `twoFactor: { sameOrigin: { origins: ['https://…'] } }`, or make the proxy
send `X-Forwarded-Host` (`proxy_set_header Host $host;` in nginx). `reportRefusedOrigin` is the building block. `ipal-doctor` warns (`csrf-empty`) when the config sets neither `serverURL` nor
`csrf` — Payload then accepts the login cookie from any origin.
**What is NOT covered — the complete list.** (1) Anonymous requests: the access function decides. (2) Accounts
of other auth collections: 2FA is about one collection; such an account is not staff unless its collection is in
`access.staffCollections`, and then it is staff **without** a second factor (warning in the log at start).
(3) API keys. (4) An account that has not set TOTP up yet. (5) Entities the project opted out (below).
(3) API keys. (4) An account that has not set TOTP up yet — only with `requireSetup: false` or when the project
exempts it ("Setup required" below); by default it is refused. (5) Entities the project opted out (below).
(6) `access.admin`. (7) Endpoints that are not the plugin's or the 2FA package's: your own endpoints and other
plugins' endpoints check whatever they check — add `secondFactorPassed(req)` to yours. (8) Server code using the
Local API with `overrideAccess: true`. Nothing is skipped by slug, name or prefix, and a user object the check
@@ -669,7 +798,8 @@ twoFactor: false // ONLY when the project really cannot use 2FA (rare)
### How it works for the user
1. Logs in (email + password)
2. On first login: redirected to TOTP Setup (`/admin/setup-totp?back=%2Fadmin`, QR + secret)
2. On first login: redirected to TOTP Setup (`/admin/setup-totp?back=%2Fadmin`, QR + secret), with a notice
saying until when it has to be done. Until it is done the account can do nothing else ("Setup required")
3. Scans the QR with an app (Google Authenticator, Authy, 1Password, Microsoft Authenticator)
4. Enters the code → 2FA is active, back to the page from `back`
5. Next logins: email + password + TOTP code (`/admin/verify-totp?back=…`)
@@ -680,7 +810,51 @@ show the QR code. `back=null` or a page that keeps reloading means the import ma
### Resetting 2FA (admin)
An admin can reset another user's 2FA (when they lose their phone) — through
An admin resets another user's 2FA (a lost phone) or reopens setup for a blocked account on that account's page
in the panel: **Two-step verification** in the sidebar → "Reset two-step verification" / "Reopen setup". Behind
it: `POST /api/ipal/two-factor/reset` `{ userId }`. The account must set TOTP up again within a new window.
The endpoint comes with ipal-kit's own check: with `twoFactor.guard: false` it does not exist (404), and neither
does the control in the panel.
- **Who may reset.** By default a staff admin whose session has **entered its own TOTP code**. An admin on an API
key, and an admin that `requireSetup.exempt` lets work on its password, are refused: removing someone's second
factor should take one. `twoFactor.resetAccess: ({ req }) => boolean` replaces the rule; a session that still
owes its code is refused whatever the function says, and only an answer of exactly `true` allows
(`req.user._strategy` is `'totp'`, `'api-key'` or `'local-jwt'`). Example that keeps the default's strength and
narrows it to one address: `({ req }) => req.user?._strategy === 'totp' && req.user.email === '[email protected]'`.
`({ req }) => isAdmin(req.user, req.payload)` alone would let an API-key or exempt admin reset.
- **A reset ends the account's sessions.** Every token of that account stops working at once; its owner logs
in again with the password and sets TOTP up. This matters when the account may be in someone else's hands: a
session that had passed 2FA could otherwise enrol a new authenticator without the password (`/api/setup-totp`
asks for none). **After a suspected compromise also change the account's password** — the reset does not, and
whoever knows the password can log in and set TOTP up within the new window. With `auth.useSessions: false`
on the collection there are no sessions to end: tokens live until they expire.
- The 2FA package's own remove / reset endpoints (below) do **not** end sessions.
#### Every administrator is blocked
When no administrator can get in (each one missed the window, or the only one did), nobody can press "Reopen
setup". Two ways out, both need a deploy or shell access — which is the point: the panel alone cannot undo it.
1. **A script, no redeploy** (`pnpm payload run scripts/reopen-2fa.ts` on the server; Local API, no access
check):
```ts
import config from '@payload-config'
import { getPayload } from 'payload'
const payload = await getPayload({ config })
const { docs } = await payload.find({ collection: 'users', where: { email: { equals: 'admin@example.com' } } })
await payload.update({ id: docs[0].id, collection: 'users', data: { totpSetupFrom: new Date().toISOString() } })
process.exit(0)
```
The administrator then logs in and sets TOTP up within the new window, and reopens the others from the panel.
2. **No script, one redeploy each way:** set `twoFactor.requireSetup: { windowHours: false }` and deploy — the
lock stays (nothing but setup), the time limit is gone, so every blocked account can set TOTP up. When the
administrators have, put the option back and deploy again. Accounts that still have not set TOTP up are
blocked again from that moment (their start did not move).
Avoid it: at least two administrators with 2FA, and `ipal-doctor --url <site>` before an upgrade.
The 2FA package has its own reset, off unless you turn it on — through
`adminManageAccess` in the @clocklimited configuration. ipalKit passes it only `collection`,
`forceSetup` and `issuer`; pass other options by wrapping the injected factory:
`plugin: (opts) => payloadTotp({ ...opts, adminManageAccess: ({ req }) => isAdmin(req.user, req.payload) })`.
@@ -752,13 +926,103 @@ size while reading, content signature, container and macro checks, an optional `
Emails tab (recipients, BCC) is readable only by `editor+`.
- Full table: [access.md](./access.md#what-the-plugin-locks-down-by-itself).
## Stored secrets (`secrets.writeOnly`, `secrets.reenterOnChange`)
`smtpPassword` and `turnstileSecretKey` live in the Site integrations global: **the panel is their source**
(there is no env variable for the SMTP password, and the env fallback for the Turnstile secret is deprecated —
[turnstile.md](./turnstile.md)). They are **write-only**:
| Who reads | Gets |
|---|---|
| REST (`GET /api/globals/site-integrations`), GraphQL, the panel's form, versions — anything through access control, an admin included | `'********'` when a value is stored (`SECRET_MASK`), the empty value when none is |
| Server code through the Local API with access control off (the default of `payload.findGlobal`) — the mail adapter, the Turnstile check, your own server code | the real value |
| The Local API **with** access control (`overrideAccess: false` and a `user`) | `'********'` |
| A save sends | Result |
|---|---|
| nothing for the field, an empty value, `null`, or `'********'` back | the stored value is kept |
| a new value | replaces it (the answer shows `'********'`) |
| `'[[clear]]'` (`SECRET_CLEAR`) | removes it |
| a value that is not text (`false`, `0`, a list, an object) | **refused** (`400`): "Enter the value as text." |
| the server, the port or the user name **changed** (whatever the transport), and **no** new password | **refused** (`400`, on the password field): "Enter the password again…" |
In the panel the field says "A value is set. It is not shown; type a new one to replace it." and offers "Remove
the stored value".
**The SMTP password stays with the server it was saved for** (`secrets.reenterOnChange`). Hiding the value is
not enough on its own: an admin session could point `smtpHost` / `smtpPort` at a machine of its own, press
"Send test e-mail", and read the password off the connection. So a save **through access control** (the panel,
REST, GraphQL) that changes `smtpHost`, `smtpPort` or `smtpUser` while a password is stored must send the
password again — or remove it (`'[[clear]]'`, "Remove the stored value") for a server without one. **Whatever
the transport says:** "Microsoft Graph" in the panel does not mean Graph sends — the mail adapter falls back to
SMTP when Graph is not configured, and for attachments Graph cannot take. A change of `emailTransport` alone
asks for nothing. Values are compared exactly (`587` and `'587'` are the same; another letter case or a space
is a change), and a value never saved — or a `NULL` in a SQL row — counts as the field's default, so saving
the form unchanged asks for nothing. Server code — a seed, a script with the Local API and access control off
— is not asked. `ipalKit({ secrets: { reenterOnChange: false } })` = the stored password follows the new
server, as before.
A stolen admin session, or any way past the global's read rule, no longer yields a working mailbox password.
What it does **not** protect: the database and its backups hold the value in plain text (encryption at rest is
a separate, open question); whoever can change the config or run server code can read it; and a session that
knows nothing but may send e-mail can still **use** the mailbox through the site (send, not read). On a port
other than 465 the connection is encrypted only when the server offers STARTTLS; requiring it is a possible
later option, not part of this release.
**Versions.** The global has no versions by default. A project that turns them on
(`globalOverrides: { 'site-integrations': { versions: … } }`) stores the secret in every version — as in the
document itself — and reads of versions are masked like any read. A **restore** answers with the version
document, the fields under `version`, where field hooks do not run: the global's `afterRead` hook
`maskSecretsOnRestore` masks them there too. A restore brings back the password of that version.
- **What an existing site sees after the upgrade:** nothing to do. The stored values stay; the panel shows "a
value is set"; the API returns the mask. Code of your own that read the secret over REST / GraphQL as an admin
must read it on the server with the Local API instead.
- **Off:** `ipalKit({ secrets: { writeOnly: false } })` — the value is returned to whoever may read the global.
- **Your own secret fields:** `writeOnlySecret({ name: 'apiToken', type: 'text', admin: { components: { Field:
'@intecion/ipal-kit/admin#MaskedField' } } })`, or `writeOnlySecrets(fields, ['apiToken'])` for fields inside
tabs / rows / groups; the hooks `maskSecretAfterRead` / `keepSecretBeforeValidate`, `SECRET_MASK`,
`SECRET_CLEAR`, `isSecretMask`, `INTEGRATION_SECRET_FIELDS` are exported. A real secret equal to `********` or
`[[clear]]` cannot be stored.
- Bound to other fields, like the SMTP password: `writeOnlySecret(field, { boundTo: ['apiUrl'] })`, or
`writeOnlySecrets(fields, ['apiToken'], { apiToken: { boundTo: ['apiUrl'], appliesWhen: (data) => … } })`
(`WriteOnlySecretOptions`; `buildKeepSecret(options)` is the hook; `SMTP_PASSWORD_BOUND_TO` is the plugin's
list). The fields must be siblings of the secret.
- With versions on your entity: add `hooks: { afterRead: [maskSecretsOnRestore] }` to the global or the
collection (`maskWriteOnlySecrets(data, fields)` is the walker it uses).
- **Check:** as a fully signed-in admin, `GET /api/globals/site-integrations` → `"smtpPassword":"********"`; save
the form without touching the field → a test e-mail still goes out; change the server without typing the
password → the save is refused with "Enter the password again…".
## Dashboard alerts by role (`dashboardAlerts`)
The plugin's dashboard alerts read data that only some roles may read (with access control off, on the server),
so each decides who sees it. **Integration alerts** (Site integrations is admin-only): an admin sees what is
failing and the link; an editor sees "An integration needs attention. Ask an administrator to look at it."; anyone
else sees nothing. **Cookie alerts** (crawl result, cookies waiting): editors and above. A session that still owes
its second factor sees none of them. `ipalKit({ dashboardAlerts: { integrations: 'editor' | 'all', cookies: 'all' } })`
loosens it. **`'all'` checks nothing** — no role and no second factor: whoever the dashboard is drawn for sees
the full text, as before. The components take the same as props
(`details`, `audience`).
## Turn off, override, extend
- **Stored secrets:** `secrets: { writeOnly: false }`, `secrets: { reenterOnChange: false }`; `writeOnlySecret` /
`writeOnlySecrets` (with `boundTo`), `maskSecretsOnRestore` for your own fields.
- **2FA attempts from another origin:** `twoFactor.sameOrigin: false`, or `{ origins: [...] }`; `requestFromOwnOrigin`,
`ownOrigins` are exported. **Verify count:** `verifyLimit: { store: 'memory' }`; `buildVerifyLimit`,
`verifyLimitKey`, `clearVerifyLimits` (tests) are exported.
- **Dashboard alerts:** `dashboardAlerts: { integrations, cookies }`.
- **Verify limit:** `twoFactor.verifyLimit: { max, windowMinutes }`, or `false`.
- **`back` link check of the 2FA screens:** `twoFactor.safeBack: false`, or a function as your own rule;
`safeAdminBack`, `wrapTotpViews`, `copyViews`, `changedViewKeys`, `SAFE_TOTP_VIEW`, `SafeTotpView` are exported.
The stale import-map notice that comes with it: `twoFactor.importMapCheck: false`; its parts
(`findImportMapFile`, `missingImportMapEntries`) are exported too.
- **Setup required:** `twoFactor.requireSetup: false` (off), `{ windowHours }` (another window, `false` / `0` = none),
`{ exempt }` (a service account), `{ dashboardNotice: false }`, `{ statusField: false }`, `{ setupNotice: false }`,
`twoFactor.resetAccess` (who reopens); exported: `twoFactorSetupState`, `twoFactorSetupDeadline`,
`buildSetupFields`, `stampSetupFrom`, `backfillSetupFrom`, `buildTwoFactorResetEndpoint`,
`countAccountsWithoutTotp`, `resolveRequireSetup`, `strictExempt`, `SETUP_FROM_FIELD`.
- **2FA check:** per entity `custom.ipal.secondFactor` / `custom.totp.disableAccessWrapper` (one operation or
all); `twoFactor.guard: false` turns ipal-kit's own second-factor check off everywhere (not recommended);
`requireSecondFactor` / `secondFactorPassed` are exported for your own access functions and endpoints.
+43 -12
View File
@@ -6,9 +6,17 @@ reads the secret server-side.
## Config
No options — the `turnstileSiteKey` / `turnstileSecretKey` fields are in
SiteIntegrations (Spam protection tab). The editor enters the keys in the panel (env fallback:
`NEXT_PUBLIC_TURNSTILE_SITE_KEY` / `TURNSTILE_SECRET_KEY`).
The `turnstileSiteKey` / `turnstileSecretKey` fields are in SiteIntegrations (Spam protection tab): **the
panel is the source of the keys.** The secret key is write-only there — the panel and the API show "a value is
set", never the value ([security.md](./security.md) "Stored secrets"). Env fallback for the public site key:
`NEXT_PUBLIC_TURNSTILE_SITE_KEY`.
> **Deprecated: `TURNSTILE_SECRET_KEY` from the environment.** It still works when the panel field is empty,
> and will be removed in a later release that the changelog names in advance. A site that relies on it logs
> `[ipal] Deprecated: the Turnstile secret key comes from the TURNSTILE_SECRET_KEY environment variable…` once
> per start, and `ipal-doctor --url` reports it (`turnstile-env-key`). **Move it:** copy the key into Site
> integrations → Spam protection → Secret key, send a test form, then remove the variable from the environment
> (Coolify). Local development with Cloudflare's test keys in `.env` keeps working until the removal.
**On = both keys set.** Then the widget shows, and `submitForm`
**requires** a valid token: a missing token is a rejection, so a bot cannot skip
@@ -60,8 +68,8 @@ if (!ok) {
```
`verifyTurnstile` reads the secret from SiteIntegrations (Local API), and when the field is
empty — from the **`TURNSTILE_SECRET_KEY`** variable (the same one
`ipalEnvRules({ turnstile: true })` requires). It returns `true` for `pass`, `false` for `reject`,
empty — from the **`TURNSTILE_SECRET_KEY`** variable (deprecated, see Config; the same one
`ipalEnvRules({ turnstile: true })` names). It returns `true` for `pass`, `false` for `reject`,
and for `degraded` (a problem on our side, see below) — depending on
`onConfigError`: **by default `'allow'` → `true`**, `'reject'` → `false`. No token
→ `false`. Every result other than `pass` is **logged** in the server logs:
@@ -86,11 +94,29 @@ and for `degraded` (a problem on our side, see below) — depending on
|---|---|---|
| `pass` | valid token | accepts |
| `reject` | bad token from the **visitor**: `invalid-input-response`, `timeout-or-duplicate`, no token | **rejects** (`reason: 'turnstile'`) |
| `degraded` | an error **on our side**: no secret, `invalid-input-secret` / `missing-input-secret`, Cloudflare unreachable / 5xx / `internal-error` / unexpected response | **accepts** (`turnstileOnConfigError: 'allow'`) — rate limit, honeypot and validation still work |
| `degraded` | an error **on our side**: no secret, `invalid-input-secret` / `missing-input-secret`, Cloudflare unreachable / 5xx / `internal-error` / unexpected response | a **text form accepts** (`'allow'`) — rate limit, honeypot and validation still work; a **form with files** (the file endpoint) **rejects** (`'reject'`) |
> Note: with the default `'allow'`, a wrong secret in the panel (`invalid-input-secret`)
**`forms.turnstileOnConfigError`** sets what `degraded` means, once for the project:
```ts
ipalKit({ forms: {
// turnstileOnConfigError: 'reject', // every form fails closed
// turnstileOnConfigError: 'allow', // every form keeps working, forms with files too
// turnstileOnConfigError: { text: 'allow', files: 'allow' }, // per kind
} })
```
Default `{ text: 'allow', files: 'reject' }`: an enquiry matters more than spam, but an accepted bot submission
with a file puts an attachment into a mailbox. A value at a call site (`turnstileOnConfigError` in
`createSubmitAction` / `submitForm`, `attachments.submit.turnstileOnConfigError`) still wins. Not involved while
Turnstile is off (no keys). **What an existing site sees:** nothing while Turnstile works; while it is degraded,
forms with a File field answer "verification failed" instead of sending — fix the keys (the dashboard alert and
`ipal-doctor --url`, rule `turnstile-degraded`, say so), or set `{ files: 'allow' }`.
> Note: where the policy is `'allow'`, a wrong secret in the panel (`invalid-input-secret`)
> means forms accept submissions **without effective verification** —
> visible only as an alert in the panel and in the log. `submitForm` checks Turnstile only
> visible as an alert in the panel, in the log, and in `ipal-doctor --url` (`turnstile-degraded`: a warning,
> an error after a day). `submitForm` checks Turnstile only
> when both keys are set (`getTurnstileConfig().enabled`); then a missing token
> always → `reason: 'turnstile'`.
@@ -123,7 +149,8 @@ above), then whether the secret is in the database — in Coolify open the Mongo
`mongosh <db> --eval 'db.globals.findOne({globalType:"site-integrations"}, {turnstileSecretKey:1})'`
(the Mongo adapter keeps all globals in the `globals` collection).
Do not write the secret from code (`updateGlobal` in `onInit` / an action) — it overwrites the panel on
every start; if you prefer env, set `TURNSTILE_SECRET_KEY` and leave the field empty. `server-only` guarantees it never
every start (the env variable `TURNSTILE_SECRET_KEY` with an empty field still works but is deprecated: the
panel is the source). `server-only` guarantees it never
reaches the browser bundle.
> In forms you usually do not call `verifyTurnstile` directly —
@@ -225,9 +252,13 @@ full control or have an unusual case. The provider is a convenience layer over i
- **Turn off:** leave both keys empty (panel and env) → no widget, `submitForm` skips the check.
The Turnstile fields in Site integrations are currently always added.
- **Fail closed:** `turnstileOnConfigError: 'reject'` in `submitForm` / `createSubmitAction`
(or `onConfigError: 'reject'` in `verifyTurnstile`).
- **Keys:** the panel wins; empty field → env `NEXT_PUBLIC_TURNSTILE_SITE_KEY` / `TURNSTILE_SECRET_KEY`.
- **Fail closed / open:** `forms.turnstileOnConfigError` for the project (`'reject'`, `'allow'`, or
`{ text, files }`); `turnstileOnConfigError` in `submitForm` / `createSubmitAction` /
`attachments.submit` for one call site (or `onConfigError` in `verifyTurnstile`). From `/server`:
`passTurnstile`, `passSubmitGates`, `resolveTurnstileOnConfigError`, `TURNSTILE_ON_CONFIG_ERROR_DEFAULT`.
- **Keys:** the panel is the source; empty site key → env `NEXT_PUBLIC_TURNSTILE_SITE_KEY`; empty secret →
env `TURNSTILE_SECRET_KEY` (**deprecated**, see Config). `turnstileSecretFromEnv(integrations)` and
`TURNSTILE_SECRET_ENV` are exported.
- **Access to the keys:** Site integrations is admin-only (read and update); change it with
`ipalKit({ globalOverrides: { 'site-integrations': { access: … } } })` — keep `read` restricted, the secret lives there.
- **Look:** `theme` on `<Turnstile>` / `<TurnstileWidget theme>`, `turnstileTheme` in `RenderForm` / `BuilderForm`.
+7 -1
View File
@@ -51,6 +51,12 @@ values win over yours); `afterLogin` / `afterNavLinks` are appended.
## Technology support credit — "Technology support: Intecion.com"
**On the 2FA screens** (a session that has typed its password but not its code, or has not set 2FA up) the
panel's logo and icon cannot be loaded by the browser: that session is refused every collection, `media`
included. The server fetches them the way an anonymous visitor gets them (no cookies, images only, at most
512 KB) and puts them into the page as a `data:` image. `whiteLabel: { inlineImages: false }` turns the fetch
off (the site name is shown instead of a refused image); `fetchPublicImage` / `publicImageDataUri` are exported.
A discreet line **"Technology support: Intecion.com"** (pl `Wsparcie technologiczne: Intecion.com`,
a link to `https://intecion.com`) appears in **two places**:
- **under the panel navigation** (`afterNavLinks`, variant `nav` — left-aligned),
@@ -84,7 +90,7 @@ image. The plugin now fills the panel's `<head>` from Site settings, **with or w
| `og:site_name` | the site name | your `admin.meta.openGraph.siteName` wins |
| description | "Administration panel of <site>. Built on Payload CMS, technology support: Intecion.com." (Polish when the site's default locale is `pl`) | `adminMeta: { description: 'Panel of {site}' }` (string or `{ en, pl }`), `false`; `language: 'en' \| 'pl'`; your `admin.meta.description` wins |
| preview image | `GET /api/ipal/admin-og` — 1200×630 PNG: the site's logo (or name), "Administration panel", "Technology support: Intecion.com" | `adminMeta: { image: '/my-og.png' }` or `false`; your `admin.meta.openGraph.images` wins |
| icon | `GET /api/ipal/admin-icon` — redirects to the site's favicon, or draws the initials | `adminMeta: { icons: false }`; your `admin.meta.icons` win |
| icon | `GET /api/ipal/admin-icon` — answers with the site's favicon itself when it is a bitmap (PNG, JPEG, GIF, WebP, ICO, AVIF, recognised by its bytes; fetched as an anonymous visitor would get it, at most 512 KB). **An SVG favicon is never answered from here** — an SVG can carry script and a site-wide CSP rule overrides a route's own header — it gets a redirect to the media file, as does anything that cannot be fetched; so with an SVG favicon the tab icon is missing on the 2FA screens (use a PNG there). No favicon: the initials are drawn | `adminMeta: { icons: false }`; `adminMeta: { serveIcon: false }` = always the redirect to the media file; your `admin.meta.icons` win |
| everything | on | `adminMeta: false` = Payload's defaults |
- **How:** Payload builds every panel page's metadata from `config.admin.meta`. The plugin sets the
+1 -1
View File
@@ -1,6 +1,6 @@
{
"name": "@intecion/ipal-kit",
"version": "1.16.5",
"version": "1.16.7",
"description": "Intecion Payload Advanced Library — a Payload CMS 3 plugin: i18n, SEO, forms, consent, analytics, blog/archives.",
"license": "MIT",
"repository": {
@@ -51,7 +51,7 @@ Ask only when the brief leaves a business question open (e.g. "do posts have aut
4. **An auth collection for visitors** (`auth: true`: customers, members) only when the client requires it
(AGENT.md §5 "A second auth collection"): `admin: { user: 'users' }` in `buildConfig`, `access` with
`adminOrSelfIn('<slug>')` for read / update and an explicit `create`, never in `access.staffCollections`.
Its accounts pass none of the plugin's staff checks. Check: its token → `403` from
Its accounts pass none of the plugin's staff checks, and 2FA (setup required included) does not apply to them. Check: its token → `403` from
`/api/globals/site-integrations` and `/api/form-submissions`.
5. `pnpm generate:types`, `pnpm payload generate:importmap`.
6. Postgres with migrations → `pnpm payload migrate:create`.
+28 -1
View File
@@ -36,7 +36,17 @@ through this procedure. Ask only when you are missing something you cannot get y
|---|---|---|
| the 2FA code screen answers "Too many codes were tried…" (`429` from `/api/verify-totp`) | more than 5 verify attempts for that account in 10 minutes (`twoFactor.verifyLimit`); repeated lines `[ipal] 2FA: too many verify attempts` in the log without the owner trying = someone has the password | wait for the window, enter the current code once; unexplained attempts: change that account's password. Tests that log in often: `verifyLimit: { max: … }` for that environment |
| `isAdmin(req.user)` says `false` for a real administrator on the server, in a process that loads two Payload configs (tests, a multi-site script) | a call without a source counts only collections that are staff in **every** config of the process | pass the source: `isAdmin(req.user, req.payload)` — with it each config gets its own answer |
| `isAdmin(user)` / `isEditor(user)` is always `false` in a client component or in `proxy.ts` | the staff collections are not known there (no config in the browser bundle / middleware), and the predicates fail closed | `isAdmin(user, config)` with `useConfig()`; in middleware `isAdmin(user, { staffCollections: ['users'] })` |
| `isAdmin(user)` / `isEditor(user)` is always `false` in a client component or in `proxy.ts` | the staff collections are not known there (no config in the browser bundle / middleware), and the predicates fail closed | `isAdmin(user, config)` with `useConfig()`, imported from `@intecion/ipal-kit/client`; in middleware `isAdmin(user, { staffCollections: ['users'] })` |
| `next build --webpack`: `'server-only' cannot be imported from a Client Component module … caused by importing '@intecion/ipal-kit/dist/index.js'` | a `'use client'` file imports the main entry (Turbopack lets it pass) | import from `@intecion/ipal-kit/client` (role predicates are there since 1.16.7; types: `import type` from the main entry is fine); data the browser needs → a prop from a server component |
| an account logs in but every page and request answers 403 / the setup screen says "The time to set up two-step verification has passed" | 2FA setup required: the account did not set TOTP up within the window (72 h from its creation, an admin's reset, or the first start after the upgrade) | an administrator opens the account in the panel → Two-step verification → "Reopen setup" (or `POST /api/ipal/two-factor/reset` `{ userId }`); every administrator is blocked: security.md "Every administrator is blocked" — a script with the Local API, `payload.update({ collection: 'users', id, data: { totpSetupFrom: new Date().toISOString() } })` (`pnpm payload run`), then log in and set TOTP up; or `requireSetup: { windowHours: false }`, redeploy, set up, put it back |
| a new account gets `403` from the API although its role allows the request | 2FA setup required: until TOTP is set up the account reaches only the setup screen | set TOTP up (log in to the panel); an integration: use an API key, or `twoFactor.requireSetup.exempt` |
| after an upgrade EVERY panel login answers `500` (also `/api/users/init`), administrators with 2FA included; log: `[ipal] 2FA: the column for "totpSetupFrom" is missing … NOBODY CAN LOG IN` or `column users.totp_setup_from does not exist` | Postgres/SQLite: the migration that adds the 2FA column has not run (needed whenever 2FA is on) | `pnpm payload migrate:create` if no migration has it, commit, and redeploy with migrations run when the new container starts — `prodMigrations` in the adapter or the start command `pnpm payload migrate && pnpm start` (deployment.md §4.3; not Coolify's Pre-deployment command, which runs in the old container); nothing is lost. `ipal-doctor` reports a project whose migrations lack `totp_setup_from` |
| the site does not start: `[ipal] twoFactor.requireSetup.exempt must not be async` / `…windowHours must be a number` | `exempt` is an `async` function, or `windowHours` is a string / negative | `exempt: ({ user }) => user.email === '…'` (returns `true` / `false` at once); `windowHours: 72` or `false` |
| log: `[ipal] twoFactor.requireSetup.exempt returned a Promise … The account is NOT exempt` (and the service account gets 403) | `exempt` does not return exactly `true` | return a boolean decided from the fields on `user` |
| an administrator's "Reset two-step verification" answers 403 from a script with an API key, or for an exempt account | by default the reset needs a session that entered its own TOTP code | reset from the panel after logging in with the code; or `twoFactor.resetAccess: ({ req }) => …` |
| after "Reset two-step verification" the user is logged out everywhere | intended: the reset ends the account's sessions | the user logs in again with the password and sets 2FA up; after a suspected compromise also change the password |
| no "Two-step verification" box on the account page / no "Reopen setup" | the import map lacks `TwoFactorStatusField` (not regenerated), or `requireSetup: { statusField: false }` | `pnpm payload generate:importmap`, commit, redeploy; meanwhile `POST /api/ipal/two-factor/reset` `{ userId }` works |
| "Two-step verification" is missing on the account page / the dashboard shows a missing component | the import map is stale | `pnpm payload generate:importmap`, commit `importMap.js`, `rm -rf .next`, redeploy |
| startup: `[ipal] twoFactor: the injected 2FA plugin did not add the totpSecret field / hasTotp field / totp auth strategy` | the installed `@clocklimited/payload-2fa` is not a version ipal-kit's second-factor check recognises (tested: 3.0.0-beta.1 and beta.7), or a custom factory was injected | install a supported version; stop-gap only: `twoFactor.guard: false` (the plugin's own data is then not covered by 2FA — security.md) |
| own route or script gets `403` / "not allowed" on `form-submissions`, `forms`, a settings global with `overrideAccess: false`, although the user is an admin | the `user` was fetched by id and passed by hand: it does not carry how the account logged in, so the second-factor check refuses it | take the user from `payload.auth({ headers })` (it sets `collection` and how the account logged in), or (server-only code that needs no access check) leave `overrideAccess` at its default; a hand-built user needs at least `collection: 'users'` for its role to count |
| an account of a second auth collection (`customers`) gets `403` from a settings global, submissions, `/api/ipal/*`, `/api/setup-totp`, or `isAdmin` / `adminOnly` say no although it has `roles: ['admin']`, after an upgrade | by design since 1.16.4: roles and staff checks count only for accounts of a staff collection | write the one rule it needs (`formSubmissionOverrides`, `globalOverrides`, `collectionOverrides`); a second STAFF collection: `access.staffCollections` (access.md "Who is staff") |
@@ -90,6 +100,23 @@ through this procedure. Ask only when you are missing something you cannot get y
| emails are not sent | no `email: mailAdapter()` / empty transport / empty Emails tab | email.md; Send test in the panel |
| old email sender | mail client cache | check the raw headers |
| form: `unknown_fields` | field outside the definition (honeypot not removed) | `ipal-form` → actions.ts |
| an account logs in to `/admin` and sees "Unauthorized" (its API calls still work) | `accounts.panelRole`: the panel opens for `editor` and above; the account has only `user`, or no role | give it `editor` (an admin edits the account), or `accounts: { panelRole: 'user' }`; nobody can get in: a script with the Local API sets `roles: ['admin']`, or `accounts: { panelRole: false }` + redeploy |
| `POST /api/<slug>/first-register` answers `403` on an empty collection | `accounts.firstUserRoute`: only the panel's login collection may register its first account that way (the plugin's own endpoint sits in front of Payload's) | an admin creates the account; or the collection's own `create: () => true` (sign-up); or `accounts: { firstUserRoute: ['<slug>'] }` |
| an editor (or a script with its token) gets `403` creating an account in the project's own `users` | `accounts.adminOnlyCreate`: only admins create staff accounts where the roles are the plugin's | create as an admin; or write the collection's `create` rule; or `adminOnlyCreate: false` |
| an account gets `403` changing or deleting ANOTHER account of a staff collection (it worked before) | `accounts.adminOnlyWrite`: an admin, or the account itself (update only); on a collection with roles of its own: accounts of that collection | do it as an admin; or write the collection's `update` / `delete` rule; or `adminOnlyWrite: false` |
| an account saves its own profile and its `roles` do not change (no error) | `accounts.adminOnlyWrite`: nobody changes its own roles; with the plugin's roles only an admin changes roles | an admin changes the role; or give the `roles` field its own `access.update` |
| a logged-in visitor (customer) gets `403` reading a staff collection — an author box went empty | `accounts.staffOnlyRead`: only staff accounts read a staff collection without a `read` rule | write that collection's `read` rule; or `staffOnlyRead: false` |
| `/api/health` answers 503, the panel and `/api/*` 500 after a deploy; log: `[ipal] access names "…" as a staff collection, but this config has no auth collection with that slug` | a slug in `access.staffCollections` / `access.authCollection` is not an auth collection (a typo, a removed collection): Payload does not start, the process stays up (with a health check Coolify keeps the old container) | fix the slug or add the collection |
| a collection added by a plugin listed after ipalKit refuses what its own access rule allows | it is in `access.staffCollections`: the plugin's account rules are put in front of its rules and both must allow (the log at start lists what was put) | `custom: { ipal: { accountRules: false } }` on that collection, or list that plugin before ipalKit |
| a fresh site with `access.firstUserAdmin: false`: the first account sees "Unauthorized", or the start fails with `leaves a fresh site with nobody who can open the panel` | the first account gets the default role, below the panel role | `access.defaultRole: 'editor'`, or `accounts: { panelRole: false }`, or drop `firstUserAdmin: false` |
| saving Site integrations fails on the password field: "Enter the password again…" | the server, port or user name changed and the stored SMTP password is kept only for the settings it was saved with — also when the transport says Microsoft Graph | type the password again; or "Remove the stored value" for a server without one; a seed with the Local API is not asked; `secrets: { reenterOnChange: false }` |
| creating an account / changing a password fails with "The password must have at least 12 characters." | `accounts.password` (applies to new passwords of staff accounts, in scripts too) | a longer password; `accounts: { password: { minLength } }` or `false` |
| the API returns `"smtpPassword":"********"` / own code "lost" the SMTP password or Turnstile secret | write-only secrets: reads through access control never get the value | read on the server: `payload.findGlobal({ slug: 'site-integrations' })` (access control off); `secrets: { writeOnly: false }` restores the old behaviour |
| the SMTP password "disappears" after saving Site integrations | it does not: the field shows "A value is set"; an empty save keeps it | to change it type a new one; to remove it press "Remove the stored value" (API: `'[[clear]]'`) |
| a form with a File field answers "verification failed" while text forms work | Turnstile is degraded (wrong / missing secret, Cloudflare down) and forms with files fail closed | fix the keys (Site integrations → Spam protection; dashboard alert; `ipal-doctor --url` → `turnstile-degraded`); or `forms: { turnstileOnConfigError: { files: 'allow' } }` |
| `POST /api/verify-totp` (or `setup-totp`) answers `403` "Not allowed from this origin." — **nobody can enter a code** | the request's `Origin` is not one the server knows as its own: a panel or front end on another domain, or a proxy that rewrites `Host` and sends no `X-Forwarded-Host` while `serverURL` is not set. The log names the origin once: `[ipal] 2FA: a code from origin "…" was refused` | set `serverURL` (best); or `twoFactor: { …, sameOrigin: { origins: ['https://<that origin>'] } }`; or make the proxy send `X-Forwarded-Host`; `sameOrigin: false` turns the check off |
| log: `[ipal] Deprecated: the Turnstile secret key comes from the TURNSTILE_SECRET_KEY environment variable` | the panel field is empty and the env variable is used | with the owner: copy the key into Site integrations → Spam protection, test a form, remove the variable; it keeps working meanwhile |
| an editor no longer sees why an integration fails on the dashboard | dashboard alerts by role: details are for admins | an admin looks; or `dashboardAlerts: { integrations: 'editor' }` |
| Turnstile always rejects | the `[ipal] Turnstile …` log says why: no secret, `invalid-input-secret`, `timeout-or-duplicate` | turnstile.md → table; secret in the panel or `TURNSTILE_SECRET_KEY`; **do not** write the secret in code |
### Environment
@@ -50,7 +50,7 @@ Existing client sites are not gated on it; run it there as a report only.
## The status endpoint
`GET /api/ipal/doctor` is added by `ipalKit` and answers 404 until the site has `IPAL_DOCTOR_TOKEN` (≥ 32 characters).
Then `Authorization: Bearer <token>`; counts only (`usersWithout2fa`, `pendingCookies`, `plugin`, `node`). With the same
Then `Authorization: Bearer <token>`; counts and states only (`usersWithout2fa`, `usersSetupClosed` = of those, blocked because the 2FA setup window has passed, `pendingCookies`, `openSignUp` = slugs of auth collections with open sign-up, `turnstile` = the recorded state of the Turnstile check, `turnstileSecretFromEnv`, `plugin`, `node`) — never a key or a name. With the same
`IPAL_DOCTOR_TOKEN` in the doctor's environment, `--url` reads it. Off: `ipalKit({ doctor: false })`; adapt:
`ipalKit({ doctor: { tokenVar, access } })`.
@@ -31,6 +31,16 @@ description: Complete map of everything @intecion/ipal-kit provides — every ip
| `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, besides the panel's login collection (`admin.user`) and `access.authCollection`; roles count **only** for accounts of a staff collection (every predicate and access function); such accounts are **not** covered by 2FA (one collection only — warning in the log at start); 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 |
| `accounts` | on (all rules) | rules for the accounts of the staff collection; each key below | `false` = none of them |
| `accounts.panelRole` | `'editor'` | the lowest role that may open the admin panel (Payload's `access.admin` on the collection with the roles): an account with only `user` sees "Unauthorized"; the API is not touched; the role decides, not the second factor. First start logs `N account(s) … cannot open the admin panel` (an error when it is everyone). Needs `access` | `'user'` / `false` = everyone, as before; `'admin'`; your own `access.admin` / `access.authAccess.admin` wins |
| `accounts.adminOnlyCreate` | on | a staff collection (panel login collection, `access.authCollection`, `access.staffCollections`) without a `create` rule gets one instead of Payload's "any logged-in user" — also the project's own collection. With the plugin's roles (`access.authCollection`, or a `roles` select with only `user` / `editor` / `admin`): an admin, fully signed in. With roles of its own, or none: an account of that same collection, or a plugin admin of another staff collection | `false` = Payload's default; a `create` rule you wrote always wins |
| `accounts.adminOnlyWrite` | on | the same for `update`, `delete` and `unlock`: with the plugin's roles — update: an admin or the account itself; delete, unlock: an admin; otherwise an account of that same collection, or a plugin admin. With it the collection's `roles` field (when it has no `access.update`) is closed for self-promotion: with the plugin's roles only an admin changes roles; with role values of the project's own an account never changes its own (the plugin cannot rank them — write that collection's rules). Closes Payload's default, under which a visitor account could change a staff account's password | `false` = Payload's default, the `roles` field left alone; rules you wrote always win |
| `accounts.staffOnlyRead` | on | `read` and `readVersions` on a staff collection without those rules: a fully signed-in account of a staff collection (Payload's default let a visitor account list the staff accounts) | `false` = Payload's default; a `read` rule you wrote wins |
| `accounts.firstUserRoute` | `'panel'` | which auth collections `POST /api/<slug>/first-register` answers for while they are empty: only the one the panel logs in with (the first account of a site → admin). Others get `403`, a second staff collection included, in any spelling of the URL (the plugin's own endpoint sits in front of Payload's); a collection whose own `create` allows an anonymous request keeps its route. With `access.firstUserAdmin: false` and a default role below the panel role, the default `panelRole` is not applied (logged) and an explicit one is refused at start | a list of slugs; `'all'` = Payload's behaviour |
| `accounts.password` | `{ minLength: 12 }` | when a password is SET on a staff collection (create, first-user screen, change, reset by e-mail; panel, API and Local API): at least `minLength` characters, not the account's e-mail address. Existing passwords are never checked — a shorter one keeps logging in | `{ minLength }`; `false` = Payload's rule (3 characters) |
| `secrets.writeOnly` | on | `smtpPassword` and `turnstileSecretKey` (Site integrations) are never returned: REST, GraphQL and the panel get `'********'` when a value is stored; a save with nothing / empty / the mask keeps it, a new value replaces it, `'[[clear]]'` removes it; the Local API with access control off reads the real value. The panel is the source of these secrets — no env variable. A restore of a version is masked too | `false` = returned to whoever may read the global, as before |
| `secrets.reenterOnChange` | on | a save through access control that changes `smtpHost`, `smtpPort` or `smtpUser` while a password is stored must send the password again or remove it (`400` on the field otherwise), whatever `emailTransport` says — so an admin session cannot send the stored password to a server of its own. A change of the transport alone, and the Local API with access control off, are not asked | `false` = the stored password follows the new server |
| `dashboardAlerts` | `{ integrations: 'admin', cookies: 'editor' }` | who sees the plugin's dashboard alerts: integration details (error text, link) for `integrations` and above, a neutral "ask an administrator" for editors below it, nothing for others; the cookie crawl / approval alert for `cookies` and above. With a role, a session that owes its second factor sees none | `integrations: 'editor' | 'all'`, `cookies: 'all'` (`'all'` = as before: no role and no second factor is checked) |
| `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 | — |
@@ -41,7 +51,13 @@ description: Complete map of everything @intecion/ipal-kit provides — every ip
| `twoFactor.importMapCheck` | on | production only: at start searches the `importMap.js` on disk (where Payload looks for it) for `@intecion/ipal-kit/admin#SafeTotpView`; when not found, logs `[ipal] The admin import map may be out of date …` and ipal-kit's `TotpRedirectProvider` puts the notice "Two-step verification may not be available" above the 2FA screens (never instead of them). A hint only — the map in the build can differ from the file on disk (Dockerfile runner stage, re-exporting map); a file that is not found is not reported | `false` = no file read, log line or notice |
| `twoFactor.texts` | ipal-kit's en/pl texts (`TOTP_TEXTS`) over the package's; 2FA screens titled "Two-step verification" / "Weryfikacja dwuetapowa" (site's language) | `false` = the package's texts; one text: `i18n.translations.<lang>.totpPlugin.<key>` (security.md) |
| `twoFactor.guard` | on | ipal-kit's own second-factor check on every collection and global (also the plugin's own and those of plugins listed after ipalKit) and in `userMeetsRole`; startup fails with `[ipal] twoFactor: the injected 2FA plugin did not add …` when the 2FA package lacks the `totp` strategy / `hasTotp` / `totpSecret` | per entity: `custom.ipal.secondFactor: false` / `{ read: false }` or the package's `custom.totp.disableAccessWrapper.<op>`; `false` = the package's wrapper only (the plugin's own data then opens to a password without the code; not recommended). The package's endpoints stay limited to accounts of the 2FA collection either way |
| `twoFactor.verifyLimit` | `{ max: 5, windowMinutes: 10 }` | attempts per account on `POST /api/verify-totp` (the 2FA package counts none): the sixth in the window, right or wrong, gets `429` + `Retry-After`; in memory per instance | `{ max, windowMinutes }`; `false` = no limit |
| `twoFactor.verifyLimit` | `{ max: 5, windowMinutes: 10, store: 'database' }` | attempts per account on `POST /api/verify-totp` (the 2FA package counts none): the sixth in the window, right or wrong, gets `429` + `Retry-After`. Counted in memory and in the database (`payload.kv`, the `payload-kv` collection Payload adds), so a restart or a second instance does not reset it; a failing store never opens the gate | `{ max, windowMinutes }`; `{ store: 'memory' }` = this instance only; `false` = no limit |
| `twoFactor.sameOrigin` | on | `POST /api/verify-totp` and `/api/setup-totp` refuse (`403`, not counted) a request a browser marks as coming from another origin (`Origin`, else `Sec-Fetch-Site`). Own origins: the request's host (`Host`, `X-Forwarded-Host`, a default port written out is ignored), `serverURL`, Payload's `csrf` / `cors`. Requests without those headers pass. A refusal is logged once per origin with how to allow it — behind a proxy that hides the address set `serverURL` | `{ origins: ['https://app.example.com'] }` adds origins; `false` = off |
| `twoFactor.requireSetup` | on, `{ windowHours: 72 }` | an account without TOTP reaches nothing but the setup screen and `/api/setup-totp` (REST, GraphQL and the panel's data answer 403); it has `windowHours` from its creation or from an admin's reset, then it is blocked until an admin reopens setup. Adds the field `totpSetupStatus` (panel) to the 2FA collection, a dashboard notice and `POST /api/ipal/two-factor/reset`; the date field `totpSetupFrom` is there whenever 2FA is on (also with `requireSetup: false` / `guard: false`). Existing accounts get their window at the first start after the upgrade, written once. **Postgres/SQLite: the migration must be applied when the new container starts — `prodMigrations` or `pnpm payload migrate && pnpm start`, not a pre-deployment command (deployment.md §4.3) — or every login answers 500**; `generate:importmap`. `exempt` must return exactly `true` at once (an `async` one, or a `windowHours` that is not a number / `false`, stops the start) | `false` = the package's rule (API open until setup); `{ windowHours: 24 }`, `{ windowHours: false }` (no limit), `{ exempt: ({ user }) => … }` (a service account) |
| `twoFactor.requireSetup.dashboardNotice` / `.statusField` / `.setupNotice` | on | the administrators' notice on the dashboard; the status and reset control on the account page; the notice on the setup screen | `false` each (the lock and the reset endpoint stay) |
| `twoFactor.resetAccess` (the endpoint exists with `twoFactor.guard` on; `guard: false` = no endpoint, 404) | a staff admin whose session entered its own TOTP code (not an API key, not an `exempt` account) | who may reset another account's TOTP / reopen its setup (the button on the account page, `POST /api/ipal/two-factor/reset`). The reset clears the secret and the account's sessions. A session that still owes its code is always refused | `({ req }) => boolean` — replaces the rule, so keep `req.user?._strategy === 'totp' &&` in it unless API-key / exempt admins should reset; only `true` allows; `req.user._strategy` tells `'totp'`, `'api-key'`, `'local-jwt'` apart |
| `whiteLabel.inlineImages` | on | on the 2FA screens the logo / icon is fetched by the server as an anonymous visitor gets it (max 512 KB) and inlined as `data:` — the session there is refused `media` | `false` = the browser tries the media URL |
| `adminMeta.serveIcon` | on | `/api/ipal/admin-icon` answers with the favicon's bytes when it is a bitmap (PNG, JPEG, GIF, WebP, ICO, AVIF by its bytes); an SVG favicon always gets a redirect to the media file (never SVG bytes from the site's origin) | `false` = always the redirect |
| `twoFactor.allowCollectionMismatch` | `false` | allows `collectionSlug` ≠ `admin.user` (panel users of the other collection then skip 2FA) | `true` only when you protect a second auth collection on purpose |
| `whiteLabel` | none | `admin.components.graphics.Logo/Icon` (`AdminLogo`/`AdminIcon`) from Site settings + vendor credit | omit / `false`; `true` = defaults |
| `whiteLabel.settingsSlug` | `'site-settings'` | global it reads the logo/name from | — |
@@ -72,6 +88,7 @@ description: Complete map of everything @intecion/ipal-kit provides — every ip
| `forms.redirectRelationships` | none | collections a form can redirect to | `['pages']` |
| `forms.emailLayout` | `false` | `beforeEmail` with a layout (logo, colour, footer) + Site settings → **Emails** tab; `{{*:table}}` readable | `true` |
| `forms.beforeEmail` | none | your own e-mail changes (after the layout) | form-builder function |
| `forms.turnstileOnConfigError` | `{ text: 'allow', files: 'reject' }` | what a form does while Turnstile CANNOT check (wrong / missing secret, Cloudflare down): a text form is accepted, a submission to the file endpoint is refused. Not involved while Turnstile is off | `'allow'` / `'reject'` for every form, or `{ text, files }`; `turnstileOnConfigError` at a call site (`createSubmitAction`, `attachments.submit`) wins |
| `forms.attachments` | off | **File** field in the form builder; a file is checked (size, count, type by content, refused extensions), attached to the company e-mail and dropped — **never stored**; adds `POST /api/ipal/forms/submit`, the fields `submissionFiles` / `filesDelivery` / `filesDeliveryNote` / `attemptKey` on `form-submissions`, and the **Files** texts in Form messages | `true` / `FormAttachmentsOption`: `maxSizeMB` (10), `maxTotalMB`, `maxFiles` (3), `fileTypes`, `allowRisky`, `scan` (antivirus hook — none built in), `strictPdf`, `notice`, `maxConcurrent` (2), `path`, `submit` (`maxPerMinute`, `clientIp`, `honeypotField`, `turnstileHostnames`, `turnstileOnConfigError`, `allowedOrigins`, `idleTimeoutMs`, `timeoutMs`); block only: `forms.fields.file: false` or `buildFileBlock(…)`. Postgres: `migrate:create`. Check: submit a PDF → attached to the company e-mail, absent from the customer e-mail, submission shows *File delivery: Handed to the mail server* (forms.md "Files") |
| `forms.consentFieldName` | `'consent'` | name of the GDPR consent field `submitForm` requires (read from `config.custom.ipal`) | `createSubmitAction({ consentFieldName })` / `submitForm` argument wins |
| `consentLog` | off | `consent-records` collection + `POST /api/ipal/consent` (rate limit 20/min) | `true` / `{ retentionDays }` (default 1095) |
@@ -20,7 +20,7 @@ Admin panel components from `@intecion/ipal-kit/admin` — the project does NOT
| Export | Import from | What it does / when |
|---|---|---|
| `MaskedField` | `@intecion/ipal-kit/admin` | Masked text field (••••, Reveal button) for secrets in SiteIntegrations (SMTP password, R2 key, Turnstile secret) — masking in the UI only, not encryption. Injected by the plugin; you can also wire it to your own `text` field via `admin.components.Field`, then `pnpm generate:importmap`. |
| `MaskedField` | `@intecion/ipal-kit/admin` | Text input for a secret. With a write-only field (`writeOnlySecret`, the default for the plugin's SMTP password and Turnstile secret) the value never reaches the browser: the input stays empty, says "A value is set", typing replaces it, "Remove the stored value" clears it on save. With a plain text field the value arrives and is drawn as dots with Show / Hide. Injected by the plugin; you can also wire it to your own `text` field via `admin.components.Field`, then `pnpm generate:importmap`. |
| `TestEmailButton` | `@intecion/ipal-kit/admin` | "Send test e-mail" button in the SiteIntegrations e-mail tab — POST `/api/ipal/test-email` through the selected transport (SMTP/Graph), shows the result/error. Injected by the plugin — do not call. |
| `RowLabel` | `@intecion/ipal-kit/admin` | Array row title in the panel taken from the row content (e.g. "Fast delivery" instead of "Item 01"). Do not wire by hand — use `rowLabel()`; after adding, `pnpm generate:importmap`. |
| `AdminLogo` | `@intecion/ipal-kit/admin` | Server Component: large panel logo (login screen) from SiteSettings `logo`, fallback `siteName`. Injected by the plugin with `whiteLabel`; after turning the option on, `pnpm generate:importmap`. |
@@ -33,10 +33,13 @@ Admin panel components from `@intecion/ipal-kit/admin` — the project does NOT
| `CookieScanButton` | `@intecion/ipal-kit/admin` | "Scan cookies" box above the *Cookie review* list: integrations in use, optional extra names, runs `POST /api/ipal/cookie-scan`. Injected by the plugin with `cookieScanner`; after turning it on, `pnpm generate:importmap`. |
| `SafeTotpView` | `@intecion/ipal-kit/admin` | Server admin view in front of the 2FA package's setup and verify views: replaces the `back` query value with a checked one and renders the view named by the serverProp `ipalTotpView` (a path or `{ path, exportName }`, found in the import map) the way Payload renders a view: a server component gets all server props, a client component only Payload's client props, `ipalTotpClientProps`, `back` and `searchParams` (both checked). `ipalSafeBack` = own rule. Registered by the plugin with `twoFactor` (`twoFactor.safeBack`, on by default). After upgrading, `pnpm generate:importmap`. Check: password only → `/admin/verify-totp?back=https%3A%2F%2Fexample.com%2F` → code → `/admin`. Own registration: `Component: { path: '@intecion/ipal-kit/admin#SafeTotpView', serverProps: { ipalTotpView: '<path>' } }` + that path in `admin.dependencies`. |
| `TotpRedirectProvider` | `@intecion/ipal-kit/admin` | Client admin provider: sends a user without TOTP to `/admin/setup-totp?back=…` and a user whose session has not passed TOTP to `/admin/verify-totp?back=…` (path read in the browser; never redirects away from those screens or logout; renders nothing while redirecting). Injected by the plugin with `twoFactor` in place of the package's header-based provider; swap with `twoFactor.provider`. After upgrading, `pnpm generate:importmap`. Check: a new admin lands on `setup-totp?back=%2Fadmin` with the QR code. Props type `TotpRedirectProviderProps` (`forceSetup`) |
| `TwoFactorStatusField` | `@intecion/ipal-kit/admin` | Server component, the `totpSetupStatus` UI field ipalKit adds to the 2FA collection (sidebar of an account): "Set up", "Not set up… until <date>" or "blocked", and for an administrator on someone else's account the reset / "Reopen setup" button. Wired by the plugin with `twoFactor.requireSetup`; needs `generate:importmap`. |
| `TwoFactorResetButton` | `@intecion/ipal-kit/admin` | Client button inside `TwoFactorStatusField`: `POST /api/ipal/two-factor/reset` `{ userId }`, then reloads the view. Props `{ kind: 'reset' \| 'reopen', userId }`. |
| `TwoFactorAlert` | `@intecion/ipal-kit/admin` | Server component on the dashboard (`beforeDashboard`), administrators only: accounts without two-step verification and how many are blocked. Wired by the plugin with `twoFactor.requireSetup`; renders nothing when every account has it. |
| `IntecionCredit` | `@intecion/ipal-kit/admin` | The line "Technology support: Intecion.com" (admin language; `agency` prop = the name) below the nav and below the login form (`variant: 'nav' \| 'login'`). Injected by the plugin with `whiteLabel`; turn off: `whiteLabel: { credit: false }` or `agency: false`. |
| `buildAdminMeta({ agency, apiRoute?, defaultLocale?, meta?, options? })` | `@intecion/ipal-kit` | The `adminMeta` step: static panel meta (robots, preview image, icon) without overwriting keys in `meta`; returns `{ meta, resolved }` |
| `adminMetaForSite(site, resolved)`, `syncAdminMeta(payload, resolved, { nameField?, settingsSlug? })` | `@intecion/ipal-kit` | Site-name parts (suffix, description, siteName); `syncAdminMeta` writes them into the live config (onInit + Site settings afterChange, never throws) |
| `buildAdminImageEndpoints(resolved, { settingsSlug?, nameField?, logoField?, iconField? })` | `@intecion/ipal-kit` | `GET /api/ipal/admin-og` (1200×630 PNG via `next/og`) and `GET /api/ipal/admin-icon` (favicon redirect or initials) — already added by `adminMeta` |
| `buildAdminImageEndpoints(resolved, { settingsSlug?, nameField?, logoField?, iconField? })` | `@intecion/ipal-kit` | `GET /api/ipal/admin-og` (1200×630 PNG via `next/og`) and `GET /api/ipal/admin-icon` (the favicon itself, or initials) — already added by `adminMeta` |
| `DEFAULT_AGENCY`, `ADMIN_META_TEXTS` | `@intecion/ipal-kit` | Default agency `{ name: 'Intecion.com', url }`; en/pl meta texts (`{site}`, `{agency}`). Types `AdminMetaOptions`, `AgencyOption`, `ResolvedAdminMeta` |
## Readable array rows in the panel (`admin-ui`) — details: `node_modules/@intecion/ipal-kit/docs/links.md`
@@ -60,16 +63,25 @@ Admin panel components from `@intecion/ipal-kit/admin` — the project does NOT
| `adminOnlyField` | `@intecion/ipal-kit` | `FieldAccess` (boolean only): field for admin only. In `field.access.read/update`. |
| `adminOrEditorField` | `@intecion/ipal-kit` | `FieldAccess`: field for editor or admin. |
| `requireRoleField(minimum)` | `@intecion/ipal-kit` | `FieldAccess` factory: at least the given role. |
| `hasMinimumRole(user, minimum, source?)` | `@intecion/ipal-kit` | Predicate → `boolean`: the user is an account of a **staff collection** and has a role ≥ `minimum` (reads `user.roles` and `user.collection` safely). A role on an account of another auth collection never counts. `source` says which collections are staff: `req.payload` on the server, the config from `useConfig()` in a client component, or `{ staffCollections: ['users'] }` (middleware). Without it: the staff collections of the config ipalKit built in this process (two different configs: only what both call staff) — and **`false` where there is none** (browser bundle, middleware, edge). Does not check the second factor. |
| `isAdmin(user, source?)` | `@intecion/ipal-kit` | Predicate → `boolean`: staff account with the `admin` role (see `hasMinimumRole`). In hooks and endpoints: `isAdmin(req.user, req.payload)`; in a client component: `isAdmin(user, config)`. |
| `isEditor(user, source?)` | `@intecion/ipal-kit` | Predicate → `boolean`: staff account with `editor` or higher. |
| `hasMinimumRole(user, minimum, source?)` | `@intecion/ipal-kit`; in client components `@intecion/ipal-kit/client` | Predicate → `boolean`: the user is an account of a **staff collection** and has a role ≥ `minimum` (reads `user.roles` and `user.collection` safely). A role on an account of another auth collection never counts. `source` says which collections are staff: `req.payload` on the server, the config from `useConfig()` in a client component (it has `admin.user` only; for `access.staffCollections` pass the list), or `{ staffCollections: ['users'] }` (middleware). Without it: the staff collections of the config ipalKit built in this process (two different configs: only what both call staff) — and **`false` where there is none** (browser bundle, middleware, edge). Does not check the second factor. |
| `isAdmin(user, source?)` | `@intecion/ipal-kit`; in client components `@intecion/ipal-kit/client` | Predicate → `boolean`: staff account with the `admin` role (see `hasMinimumRole`). In hooks and endpoints: `isAdmin(req.user, req.payload)`; in a client component: `isAdmin(user, config)` from `/client` — the main entry does not build there with webpack (`'server-only' cannot be imported…`). |
| `isEditor(user, source?)` | `@intecion/ipal-kit`; in client components `@intecion/ipal-kit/client` | Predicate → `boolean`: staff account with `editor` or higher. |
| `panelAccess(minimum?)`, `applyPanelRole(config, slug, role)`, `resolvePanelRole(option)`, `countBelowPanelRole(payload, slug, role)`, `DEFAULT_PANEL_ROLE` | `@intecion/ipal-kit` | `accounts.panelRole`: an `access.admin` function ("holds at least `minimum`", default `'editor'`; role only, not the second factor); the applier (skips a collection that has its own `access.admin`); the option → role or `null` when off; `{ all, below }` counts for the start-up line; `'editor'`. |
| `staffCreateAccess`, `staffUpdateAccess(slug)`, `staffReadAccess`, `sameStaffCollectionAccess(slug)`, `rolesByAdminOnly`, `rolesNotOwn(slug)`, `hasPluginRoles(collection)`, `applyStaffAccountAccess(config, staffSlugs, { create?, write?, read?, pluginRoles? })` | `@intecion/ipal-kit` | `accounts.adminOnlyCreate` / `adminOnlyWrite` / `staffOnlyRead`: the access functions — "an admin, fully signed in" (create, delete, unlock); "an admin, or the account itself" (update; self = an account of THAT collection); "a fully signed-in account of a staff collection" (read); "an account of this staff collection, or a plugin admin of another" (a collection whose roles are not the plugin's); the two field-access functions for a `roles` field (`update`: only an admin / never the account itself); whether a collection carries the plugin's roles (a `roles` select at the top level of the data with only `user` / `editor` / `admin`); the applier — puts the rules on the named staff collections for the operations that have none and closes the `roles` field where the plugin's `update` rule is in force, `pluginRoles` = slugs whose roles field is injected later. Run it before any plugin that wraps access (the 2FA package). |
| `buildFirstUserEndpoint(option?)`, `applyFirstUserRoute(config, option?)`, `adoptLateAuthCollections(config, staffSlugs, { access?, beforeOperation?, firstUserRoute? })`, `bothAllow(first, second)`, `unknownStaffCollections(config, staffSlugs)`, `openSignUpCollections(payload)`, `staffCollectionsOpenToOthers(payload)`, `staffCollectionsOnOwnRoles(payload)` | `@intecion/ipal-kit` | `accounts.firstUserRoute`: the plugin's own `POST /first-register` collection endpoint, matched before Payload's — `403` unless the collection is the panel's login collection (`'panel'`), is in the list, or its own `create` lets an anonymous request through; otherwise it calls Payload's handler (and sets `req.context.ipalFirstRegister`); the applier (every auth collection; `'all'` adds nothing; `endpoints: false` is left alone). For the doctor: slugs of auth collections with open sign-up; `'<slug>:<operation>'` for every staff collection an account of a non-staff collection may create in, read, update, delete from or unlock; slugs of staff collections with role values of their own on the default rules. `adoptLateAuthCollections` takes the LIVE config (`payload.config`) and gives auth collections that a plugin listed after ipalKit added the same rules, in place (called by the plugin at start and on every dev reload; returns `LateAdoption[]` — per collection what was put). There the rules are combined with the collection's own by `bothAllow` (an access function that allows only when both do; two query constraints are joined with `and`), because in a sanitized config Payload's default cannot be told from a written rule — never by a function's name, which a production build changes. `custom.ipal.accountRules: false` on a late collection keeps its rules as they are. `unknownStaffCollections` lists staff slugs that are not auth collections (Payload does not start on any). |
| `checkPassword(password, { email?, minLength? })`, `buildPasswordRuleHook({ minLength? })`, `applyPasswordRule(config, slugs, rule)`, `resolvePasswordRule(option)`, `DEFAULT_PASSWORD_MIN_LENGTH` | `@intecion/ipal-kit` | `accounts.password`: `'short' \| 'email' \| null` for a new password (length in characters); the `beforeOperation` hook for `create` / `update` / `resetPassword` (throws Payload's `ValidationError` on `password`, text in the panel's language; the account's address is looked up by id, reset token or bulk query when the request carries none; a password that is not text is refused; login is never checked); the applier; the option → `{ minLength }` or `null`; `12`. |
| `writeOnlySecret(field, options?)`, `writeOnlySecrets(fields, names, optionsByName?)`, `maskSecretAfterRead`, `keepSecretBeforeValidate`, `buildKeepSecret(options?)`, `SECRET_MASK`, `SECRET_CLEAR`, `isSecretMask(value)`, `INTEGRATION_SECRET_FIELDS`, `SMTP_PASSWORD_BOUND_TO` | `@intecion/ipal-kit` | Write-only secret fields (`secrets.writeOnly`): the wrapper for one field and for named fields anywhere in a tree (tabs, rows, groups); the two field hooks (reads through access control get `'********'`, the Local API with access control off gets the value; a save with nothing / empty / the mask keeps the stored value, `'[[clear]]'` removes it); the hook builder with options — `{ boundTo: ['siblingField'], appliesWhen?: (siblingData) => boolean }`: a save through access control that changes a bound sibling field without sending the secret throws a `ValidationError` on the secret (`secrets.reenterOnChange`); the two constants; the plugin's own secret field names (`smtpPassword`, `turnstileSecretKey`); the fields the SMTP password is bound to (`smtpHost`, `smtpPort`, `smtpUser` — not the transport: the mail adapter may fall back to SMTP). |
| `maskSecretsOnRestore`, `maskWriteOnlySecrets(data, fields)` | `@intecion/ipal-kit` | Versions and write-only secrets: the `afterRead` hook for a global or a collection (a restore answers with the version document, fields under `version`, where field hooks do not run — it masks them there for reads through access control); the walker it uses (masks every write-only field in `data`, following tabs, rows, groups, arrays and blocks). On Site integrations by default; add the hook to your own entity that has both. |
| `requestFromOwnOrigin(req, extraOrigins?)`, `ownOrigins(req, extraOrigins?)`, `reportRefusedOrigin(req, extraOrigins?)` | `@intecion/ipal-kit` | `twoFactor.sameOrigin`: `false` when a browser marks the request as coming from another origin (`Origin` not among the request's host, `serverURL`, `csrf`, `cors`, the extras; a default port written out on the host is ignored; else `Sec-Fetch-Site` not `same-origin` / `none`); `true` without those headers. `ownOrigins` → `{ hosts, origins }`. `reportRefusedOrigin` writes one log line per refused origin and process (at most 50) with the ways to allow it, and returns whether it wrote. For your own state-changing endpoint. |
| `buildVerifyLimit(collection, { max?, windowMinutes?, store? })`, `verifyLimitKey(collection, id)`, `clearVerifyLimits()` | `@intecion/ipal-kit` | `twoFactor.verifyLimit`: `async (req) => Response \| null` — counts an attempt of `req.user` in memory and, unless `store: 'memory'`, in `payload.kv`; a `429` with `Retry-After` past `max`. The kv key of an account's count; emptying the in-memory counts (tests). |
| `turnstileSecretFromEnv(integrations)`, `TURNSTILE_SECRET_ENV` | `@intecion/ipal-kit` | `true` when the Turnstile secret in use comes from the environment because the panel field is empty (**deprecated** path; the doctor's `turnstile-env-key`); the variable's name, `'TURNSTILE_SECRET_KEY'`. |
| `userMeetsRole(req, minimum)` | `@intecion/ipal-kit` | Predicate → `boolean` with `req` (`{ payload, user }`), in this order: the account belongs to a **staff collection** (`admin.user`, `access.authCollection`, `access.staffCollections`); with 2FA on it has passed the second factor (`secondFactorPassed`); it has a role ≥ `minimum`, **or** its collection has no `roles` field (the project omitted `access`). An account of any other auth collection never passes, whatever fields it has. 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(source?)` | `@intecion/ipal-kit` | `string[]`: the staff collections — `admin.user`, `access.authCollection` and `access.staffCollections` — from `req.payload`, a config or `{ staffCollections }`; without an argument what the configs built in this process agree on (`[]` when there is none). Roles and staff checks count only for accounts of these. |
| `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:** `VerifyLimitOptions` (`twoFactor.verifyLimit`: `{ max?, windowMinutes? }`), `SafeBackRule` / `SafeBackContext` (`twoFactor.safeBack` as a function: `(back, { adminRoute, origin? }) => string`), `TotpViewComponent` (a view component as registered: a path or `{ path, exportName?, clientProps?, serverProps? }`), `SafeTotpViewProps` (`@intecion/ipal-kit/admin`), `Role` (`'user' \| 'editor' \| 'admin'`), `AccessOption` (the plugin's `access` option: `authCollection`, `defaultRole`, `authAccess`, `firstUserAdmin`, `staffCollections`).
**Types:** `AccountsOptions` (`accounts`: `panelRole`, `adminOnlyCreate`, `adminOnlyWrite`, `staffOnlyRead`, `firstUserRoute`, `password`), `StaffAccountAccessOptions` (`{ create?, write?, read?, pluginRoles? }`), `LateAdoption` (`{ slug, applied, password, firstUser }`), `StaffAccountRules` (what the plugin put on a staff collection, in `custom.ipalAccountRules`: `{ applied, ownRoles }`), `WriteOnlySecretOptions` (`{ boundTo?, appliesWhen? }`), `PasswordRuleOptions` (`{ minLength? }`), `FirstUserRouteOption` (`'panel' \| 'all' \| string[]`), `TurnstileOnConfigError` / `TurnstileOnConfigErrorOption` / `TurnstileFormKind` (`@intecion/ipal-kit/server`), `VerifyLimitOptions` (`twoFactor.verifyLimit`: `{ max?, windowMinutes?, store? }`), `RequireSetupOptions` (`twoFactor.requireSetup`), `TwoFactorResetOptions`, `TwoFactorSetupState`, `SafeBackRule` / `SafeBackContext` (`twoFactor.safeBack` as a function: `(back, { adminRoute, origin? }) => string`), `TotpViewComponent` (a view component as registered: a path or `{ path, exportName?, clientProps?, serverProps? }`), `SafeTotpViewProps` (`@intecion/ipal-kit/admin`), `Role` (`'user' \| 'editor' \| 'admin'`), `AccessOption` (the plugin's `access` option: `authCollection`, `defaultRole`, `authAccess`, `firstUserAdmin`, `staffCollections`).
## Accessibility — widget (`accessibility`) — details: `node_modules/@intecion/ipal-kit/docs/accessibility.md`
@@ -367,7 +379,7 @@ Full option lists of `createContentHelpers` / `createPageRoute` / `SiteProviders
| `recordIntegrationStatus(payload, field, previous, { state, code?, message? })` | `@intecion/ipal-kit` | saves the state of your own integration in Site integrations (only on change / every 10 min); does not throw. For e-mail and Turnstile the plugin calls it itself — do not call |
| `buildIntegrationStatusField(name)` | `@intecion/ipal-kit` | hidden status group field (`state`, `code`, `message`, `since`, `checkedAt`) for `integrationsFields` |
| `buildIntegrationStatusBanner(statusField, label, texts?)` | `@intecion/ipal-kit` | UI field with a status banner on the integration tab (`label` string or `{ en, pl }`; `texts` = `{ failing, hint }` keys of your own `ipal` translations) (`integrationsFields`; then `pnpm generate:importmap`) |
| `IntegrationAlerts` | `@intecion/ipal-kit/admin` | dashboard alert about integrations in the `degraded` state; always injected by the plugin (`beforeDashboard`); your own integrations: a second instance with `checks` |
| `IntegrationAlerts` | `@intecion/ipal-kit/admin` | dashboard alert about integrations in the `degraded` state; always injected by the plugin (`beforeDashboard`); your own integrations: a second instance with `checks`. By role: the detail (error text, link) for `details` and above (`'admin'` default, `'editor'`, `'all'`), a neutral "ask an administrator" for editors below it, nothing for others or for a session that owes its second factor (`dashboardAlerts.integrations`). `CookieCrawlAlert` takes `audience: 'editor' \| 'all'` the same way |
| `IntegrationStatusBanner` | `@intecion/ipal-kit/admin` | status banner on the tab; injected by the plugin / `buildIntegrationStatusBanner` through the import map (`pnpm generate:importmap`), the project does not import it |
**Types:** `IntegrationState` (`'ok' | 'degraded'`), `IntegrationStatus` — integration state and saved status; `IntegrationLabel` (`string | { en, pl }`) — banner / alert label; `IntegrationBannerTexts` (`{ failing, hint }` text keys) — third argument of `buildIntegrationStatusBanner` for your own wording.
@@ -592,6 +604,13 @@ Server only (`pnpm payload run`); never import it from client code, the Payload
| `copyViews(views)` / `changedViewKeys(before, after)` | `@intecion/ipal-kit` | The comparison `ipalKit` uses to tell which views a 2FA factory registered: put `copyViews(views)` into the config before calling the factory, then `changedViewKeys(before, viewsAfter)` gives the keys whose view object changed — the `added` argument of `wrapTotpViews` (`(key) => keys.has(key)`). By object, not by key: the 2FA package replaces a view that already stands under its keys. Example: security.md "Your own 2FA screen". |
| `SAFE_TOTP_VIEW` / `totpViewImportKey(component)` | `@intecion/ipal-kit` | `'@intecion/ipal-kit/admin#SafeTotpView'`, the wrapper's import-map path (the default `wrapper` of `wrapTotpViews`); and the import-map key (`path#export`) of a component given as a string or `{ path, exportName }`. |
| `findImportMapFile(config, cwd?)` / `missingImportMapEntries(config, entries, cwd?)` | `@intecion/ipal-kit` | Where the project's `importMap.js` is on disk (`admin.importMap.importMapFile`, else `app/(payload)<admin route>/` or `src/app/…` under `admin.importMap.baseDir` / the working directory; `null` when not found), and which of `entries` its text does not contain (`{ file, missing }`). A hint from the file on disk, not the map in the build: warn on it, never block on it. Behind `twoFactor.importMapCheck`. |
| `buildSetupFields({ statusField? })`, `stampSetupFrom`, `backfillSetupFrom(payload, collection)` | `@intecion/ipal-kit` | The parts of "2FA setup required" for a project that wires them itself: the fields for the 2FA collection (`totpSetupFrom`, and the panel's `totpSetupStatus` unless `statusField: false`), the `beforeChange` hook that stamps the window start (on create, and when an account loses its TOTP secret), and the start-up step that gives accounts without TOTP and without a start their window (returns how many; once per account). |
| `buildTwoFactorResetEndpoint(collection, { access? })`, `TWO_FACTOR_RESET_PATH` | `@intecion/ipal-kit` | `POST /api/ipal/two-factor/reset` `{ userId }`: clears the account's TOTP secret and sessions and starts a new window. Default: a staff admin whose session entered its own TOTP code; `access` replaces that (only `true` allows; a session that owes its code is always refused). `ipalKit` registers it only with `twoFactor.guard` on. |
| `countAccountsWithoutTotp(payload, collection, setupWindowMs?)` | `@intecion/ipal-kit` | `{ without, blocked }` — accounts of the 2FA collection without TOTP, and how many are past their window. |
| `resolveRequireSetup(option)`, `strictExempt(fn)`, `SETUP_FROM_FIELD`, `DEFAULT_SETUP_WINDOW_HOURS` | `@intecion/ipal-kit` | `twoFactor.requireSetup` → `{ requireSetup, setupWindowMs, exempt? }` as the guard reads it (throws on a `windowHours` that is not a number ≥ 0 or `false`, and on an `async` `exempt`); the wrapper that makes an `exempt` function answer `true` only for exactly `true`; the field name `'totpSetupFrom'`; `72`. |
| `fetchPublicImage(url, base)`, `publicImageDataUri(url, base)`, `rasterImageType(bytes)`, `siteOrigin(serverURL)`, `PUBLIC_IMAGE_MAX_BYTES` | `@intecion/ipal-kit` | An image fetched the way an anonymous visitor gets it (no cookies; http(s) only; `image/*`; at most 512 KB, reading stops at the limit) as `{ bytes, type }` or a `data:` address, else `null`. Used for the logo and icon on the 2FA screens. `rasterImageType(bytes)` → the media type of a bitmap by its first bytes (PNG, JPEG, GIF, WebP, ICO, AVIF) or `null` — never trust a claimed type before answering a file's bytes from the site's origin; an SVG gives `null`. |
| `UPLOAD_SECURITY_HEADERS` | `@intecion/ipal-kit` | The two headers of `buildUploadSecurityHeaders` (`Content-Security-Policy: default-src 'none'; … sandbox`, `X-Content-Type-Options: nosniff`) for a route of your own that returns an uploaded file's bytes from the site's origin. In a Next project a site-wide `headers()` rule with the same key overrides a header the route sets itself: add a `headers()` rule for the path after the site-wide one (as `buildUploadSecurityHeaders({ collections, adminIcon })` does for the upload routes and `/api/ipal/admin-icon`), and never answer with an SVG. |
| `twoFactorSetupState(req)`, `twoFactorSetupDeadline(req)` | `@intecion/ipal-kit` | Where an account stands with TOTP setup, from `{ payload, user }`: `'set-up'`, `'open'` (may set it up now), `'closed'` (the setup window has passed: blocked until an admin reopens it), `'exempt'` (`requireSetup.exempt`, or `requireSetup: false`), `'not-applicable'` (no user, another collection, 2FA off); and the moment setup closes (`Date`, or `null` without a window). Types: `TwoFactorSetupState`, `RequireSetupOptions`. |
| `requireSecondFactor(access?)` | `@intecion/ipal-kit` | Wraps an `Access` function: refused while the second factor is owed, otherwise the function itself (Payload's default "logged in" when none). ipalKit applies it to every collection and global in the config, and to those added by plugins listed after it (in `onInit` and at the start of the first request, so also after a dev hot reload); use it for access functions that are not part of the config. Per-entity opt-out: `custom.ipal.secondFactor: false \| { read: false }` or the package's `custom.totp.disableAccessWrapper`. Wrapping twice is harmless. |
| `totpRedirectTarget({ adminRoute, forceSetup?, pathname, user, excludePaths? })`, `totpAdminPath(adminRoute, path)` | `@intecion/ipal-kit` | The 2FA redirect rules as pure functions: the setup / verify URL (with `back`) to send this user to, or `null` (no path, api key, already on a TOTP screen or logout). For an own `twoFactor.provider`. Types `TotpRedirectArgs`, `TotpUser` |
| `buildCsp({ mode?, reportUri?, reportGroup?, r2Url?, analytics?, metaPixel?, linkedIn?, tiktok?, clarity?, turnstile?, youtube?, googleMaps?, nonce?, strictDynamic?, dev?, extra?, override? })` | `@intecion/ipal-kit` | Returns `{ key, value }` with a hardened CSP (`base-uri`, `object-src`, `frame-ancestors`, `form-action`) + sources for the enabled integrations. `mode: 'report-only'` → `…-Report-Only` (start here), `'enforce'` later. `extra` adds to any directive, `override` replaces / drops one (`null`). `dev` (default `NODE_ENV === 'development'`) adds `'unsafe-eval'`. `nonce` → `'nonce-…' 'strict-dynamic'`. |
@@ -845,6 +864,7 @@ Bin: `ipal-doctor` (`pnpm exec ipal-doctor [dir] [--json] [--md] [--strict] [--f
| `useOptionalTurnstile()` | `@intecion/ipal-kit/client` | Like `useTurnstile`, but without a provider it returns `enabled: false` instead of throwing — for shared components. |
| `Turnstile({ siteKey, onToken, theme? })` | `@intecion/ipal-kit/client` | Raw widget with an explicit key — when you do not use the provider. |
| `verifyTurnstile({ token, payload, ip?, onConfigError?, hostnames? })` | `@intecion/ipal-kit/server` | Server-side token verification → `boolean` (`degraded` lets it through by default; `hostnames` = token must be solved on one of them, unset = not checked). `submitForm` does this itself — call it only in your own actions. |
| `passTurnstile({ payload, turnstileToken, turnstileKind?, turnstileOnConfigError?, … })`, `passSubmitGates(…)`, `resolveTurnstileOnConfigError(payload, kind?, explicit?)`, `TURNSTILE_ON_CONFIG_ERROR_DEFAULT` | `@intecion/ipal-kit/server` | The Turnstile gate of a form (`null` = passed, else `{ success: false, reason: 'turnstile' }`) and the rate limit + Turnstile pair; the policy for a `degraded` check: the call-site value, else `forms.turnstileOnConfigError`, else the default for the kind (`{ text: 'allow', files: 'reject' }`). |
| `checkTurnstile({ token, payload, ip? })` | `@intecion/ipal-kit/server` | As above, but returns `{ outcome: 'pass' \| 'reject' \| 'degraded', code? }` and updates the integration status in the panel. |
**Types:** `TurnstileConfig` (root) — `getTurnstileConfig` result; `TurnstileCheck`, `TurnstileOutcome` (`/server`) — verification result; `TurnstileProps`, `TurnstileTheme` (`/client`) — widget props and theme.
+43 -1
View File
@@ -198,7 +198,7 @@ export default buildConfig({
`.env.example` (no values, in the repo): `DATABASE_URI`, `PAYLOAD_SECRET`, `NEXT_PUBLIC_SERVER_URL`, `R2_BUCKET`,
`R2_ENDPOINT`, `R2_ACCESS_KEY_ID`, `R2_SECRET_ACCESS_KEY`, `R2_PUBLIC_URL` (empty = media through the app — the default), `IPAL_IP_HEADER` (`cf-connecting-ip`
behind Cloudflare, `x-forwarded-for` behind a plain proxy), `IPAL_NOINDEX` (empty; `1` on staging only), `INDEXNOW_KEY`,
`NEXT_PUBLIC_TURNSTILE_SITE_KEY`, `TURNSTILE_SECRET_KEY` (panel fallback), with Graph `GRAPH_TENANT_ID`,
`NEXT_PUBLIC_TURNSTILE_SITE_KEY`, `TURNSTILE_SECRET_KEY` (deprecated fallback — production keys go into the panel), with Graph `GRAPH_TENANT_ID`,
`GRAPH_CLIENT_ID`, `GRAPH_CLIENT_SECRET`, `GRAPH_SENDER`. Local `.env` with `PAYLOAD_SECRET` ≥ 32 characters (in production `ipalEnvRules` refuses a shorter one; `secretMinLength` changes it).
One language: one entry in `locales`, no `[locale]` folder (i18n.md).
@@ -234,6 +234,48 @@ the panel shows Site settings, Site integrations, Cookies, Form messages, the Fo
Check: password only → `/admin/verify-totp?back=https%3A%2F%2Fexample.com%2F` → code → you land on `/admin`.
**Set 2FA up right after creating an account** (log in as it, scan the code): until then its password alone
opens everything its role allows. One entity reachable without the code: `custom.ipal.secondFactor`.
**Setup required** (`twoFactor.requireSetup`, default): an account without TOTP reaches only the setup screen; it
has 72 h from its creation (or an admin's "Reopen setup" on the account page), then it is blocked. So create an
account, hand over the password and have the owner set 2FA up at once. **Postgres/SQLite: `pnpm payload
migrate:create` and have the migration applied when the container starts, before the site serves** — `prodMigrations`
or the start command `pnpm payload migrate && pnpm start`, never a pre-deployment command (deployment.md §4.3)
(column `totp_setup_from`, there whenever 2FA is
on) — without it every login answers 500; `pnpm payload generate:importmap` (`TwoFactorStatusField`,
`TwoFactorAlert`). A service account that logs in with a password: `requireSetup: { exempt }` (a plain function
returning exactly `true`; never `async`); an API key needs nothing. Parts to switch off: `requireSetup:
{ dashboardNotice: false, statusField: false, setupNotice: false }`. An admin's reset ends the account's
sessions and needs the admin's own TOTP code (`twoFactor.resetAccess` changes who). Have two administrators
with 2FA: when all are blocked, only a script or a redeploy helps (security.md "Every administrator is
blocked"). One entity reachable without the code: `custom.ipal.secondFactor`.
- **Account rules** (`accounts`, on by default; `false` or key by key to change): the panel opens for `editor`
and above (`panelRole`; an account with only `user` sees "Unauthorized", the API is not touched — give panel
users at least `editor`); only an admin creates staff accounts, and an account is changed by an admin or by
itself, nobody changes its own roles, and only staff accounts read staff accounts — also in the project's own
staff collection and in one a later plugin adds (`adminOnlyCreate`, `adminOnlyWrite`, `staffOnlyRead`). **A
staff collection with role values of its own** (not `user` / `editor` / `admin`) gets only "an account of that
collection, or a plugin admin": the plugin cannot rank your roles, so inside it every account may create an
account with any role — **write its `create` / `update` / `delete` rules and the field access of its `roles`
field yourself** (`ipal-doctor --url` → `staff-own-roles`). Give every staff collection a `roles` field: without
one each of its accounts is an admin to the plugin. Every slug in `access.staffCollections` must be an auth
collection of the config, or Payload does not start (`/api/health` 503, the slug in the log); a staff collection
from a plugin listed after ipalKit gets the rules in front of its own (`custom: { ipal: { accountRules: false } }`
on it keeps its own as they are); Payload's first-user route answers only for the
panel's login collection (`firstUserRoute`) — so **create the first account right after the first deploy**, it
becomes the admin; a new password has at least 12 characters (`password`). A customer collection with
sign-up: write its own `create: () => true`; the rules do not touch it. Do not combine
`access.firstUserAdmin: false` with a default role below the panel role (the start refuses or drops the panel
role). access.md "Account rules".
- **`serverURL`**: set it in the Payload config. Without it, behind a proxy that rewrites `Host` and sends no
`X-Forwarded-Host`, the 2FA code page is refused as "another origin" (logged once: `[ipal] 2FA: a code from
origin … was refused`). Coolify / Traefik keep `Host`, so it works there either way.
- **Stored secrets:** the SMTP password and the Turnstile secret key are entered **in the panel** (Site
integrations) and are write-only — the panel and the API show "a value is set". Do not add env variables for
them; `TURNSTILE_SECRET_KEY` is deprecated (local test keys in `.env` still work). Read them only on the
server with the Local API. `secrets: { writeOnly: false }` turns it off. Changing the SMTP server, port or
user name in the panel asks for the password again (`secrets.reenterOnChange`); a seed with the Local API is
not asked.
- **Forms with files** are refused while Turnstile cannot check (wrong keys, Cloudflare down); text forms are
still accepted. `forms: { turnstileOnConfigError: … }` changes either.
- A second auth collection (`customers`, a client zone): set `admin: { user: 'users' }` in `buildConfig`; its
accounts pass none of the plugin's checks and no role counts for them (not even their own `roles: ['admin']`);
a field that grants rights is never writable at sign-up; use `adminOrSelfIn('<slug>')` in every auth collection; a second
+117 -1
View File
@@ -350,7 +350,9 @@ for every site:**
`isAdmin(req.user)` keeps working on the server; prefer `isAdmin(req.user, req.payload)`.
`grep -rnE "isAdmin\(|isEditor\(|hasMinimumRole\(" src` — a call in a **client component** or in `proxy.ts` /
middleware now returns `false` without a source: `isAdmin(user, config)` (`useConfig()`), or
`isAdmin(user, { staffCollections: ['users'] })`.
`isAdmin(user, { staffCollections: ['users'] })`. A **client component imports them from
`@intecion/ipal-kit/client`** (not in 1.16.4–1.16.6: go to 1.16.7); the main entry there fails with
`next build --webpack` (`'server-only' cannot be imported from a Client Component module`).
4. `pnpm exec ipal-doctor --url <site>` (with the doctor token) → accounts without 2FA must be 0. An account that
has not set TOTP up opens everything with its password alone: have its owner set it up now, or remove it.
5. Tell the owner what the CHANGELOG entry says under "Requires project changes" and agree on it: new SMTP
@@ -380,6 +382,120 @@ gets `403` from the same addresses and from `POST /api/setup-totp`. The Coolify
strips `back`, can keep them (`twoFactor.safeBack: false` turns the plugin's check off).
2. `pnpm ipal:skills`.
**→ 1.16.6 — 2FA setup required (CHANGELOG 1.16.6; PROGRAMISTA §6, item 68; security.md "Setup required") — required with 2FA on:**
**Not a routine patch, although the number is one.** From this version an account without 2FA can only set it up and is
blocked after 72 hours; on Postgres / SQLite a missing migration locks everyone out of the panel. Do not upgrade a live
site without steps 1–3 and a deploy day agreed with the owner. Steps 2, 3 and 5 go in ONE deploy.
1. **Before upgrading a live site:** `pnpm exec ipal-doctor --url <site>` (doctor token) → accounts without 2FA.
Tell the owner: from the upgrade on, such an account can only set 2FA up, and has 72 hours for it; after that
an administrator must reopen setup on the account's page. Have them set it up now, or remove unused accounts.
Make sure at least one administrator (better two) has 2FA set up — otherwise nobody can reopen setup from the panel.
The 72 hours of existing accounts start at the first start after the deploy and are counted once (restarts
and redeploys do not extend them): agree the deploy day with the owner.
2. Update the package, `pnpm install`, `pnpm ipal:skills`, `pnpm payload generate:types`,
**`pnpm payload generate:importmap`** (new: `TwoFactorStatusField`, `TwoFactorAlert`; commit `importMap.js`),
then `pnpm exec ipal-doctor` before deploying.
3. **Postgres/SQLite — required, same deploy, or nobody can log in:** `pnpm payload migrate:create` (adds the
column `totp_setup_from` to the 2FA collection; needed whenever 2FA is on, also with `requireSetup: false`),
commit, and have it applied **when the new container starts**: `prodMigrations` in the database adapter, or the
start command `pnpm payload migrate && pnpm start` (deployment.md §4.3). **Never Coolify's Pre-deployment
command** — it runs in the old container, without the new migration, and the new version then starts without
the column. Without the column every login answers 500, administrators included; the log says
`[ipal] 2FA: the column for "totpSetupFrom" is missing … NOBODY CAN LOG IN`. `pnpm exec ipal-doctor` reports
it before the deploy. MongoDB: nothing.
4. An integration that logs in with a password and has no TOTP: give it an API key, or
`twoFactor.requireSetup: { exempt: ({ user }) => user.email === '…' }`. `grep -rn "overrideAccess: false" src`:
a `user` fetched by id is refused for every account now — take it from `payload.auth({ headers })`.
5. `rm -rf .next`, build, redeploy on Coolify. Read the first lines of the log: `[ipal] 2FA: N existing account(s)
without two-step verification…` — pass that number to the owner. The line appears on that first start only.
Postgres/SQLite: if logins answer 500 after the deploy, the migration from step 3 did not run — check that it
is committed and that the container runs migrations at start (deployment.md §4.3), then redeploy.
6. `requireSetup.exempt` must be a plain function returning `true` / `false` (an `async` one stops the start).
A script on an API key is refused by `POST /api/ipal/two-factor/reset` by default — pass
`twoFactor.resetAccess` if that is wanted. A reset ends the account's sessions (it logs in again); after a
suspected compromise change the password too. An SVG favicon has no tab icon on the 2FA screens.
7. Tell the owner what to tell the staff: a new account has 72 hours to set 2FA up, then an administrator must
choose "Reopen setup". Not wanted: `twoFactor.requireSetup: false`, or `{ windowHours: false }`.
**Every administrator is blocked** (all missed the 72 h): security.md "Every administrator is blocked" — a
`pnpm payload run` script that sets `totpSetupFrom` to now for one administrator, or
`requireSetup: { windowHours: false }` + redeploy, set 2FA up, put it back.
**Check:** create a throwaway account → its token gets `403` from `/api/users/me`; in the panel it lands on the
setup screen with "Set up two-step verification by …"; after the code it is in. As an administrator open that
account → "Two-step verification: Set up." and the reset button; delete the account.
**→ 1.16.7 (hardening; CHANGELOG 1.16.7; PROGRAMISTA §6, item 69) — not a routine patch: agree the deploy with the owner, read every point, most sites change nothing:**
1. Update the package, `pnpm install`, `pnpm ipal:skills`, `pnpm payload generate:types`. No import-map change, **no
schema change and no migration** on any database (the verify count uses Payload's own `payload-kv`
collection). `grep -n "staffCollections\|authCollection" src/payload.config.ts`: every slug there must be an
auth collection of the config — with a wrong one Payload does not start (the slug is in the log; `/api/health`
answers 503, so with a health check Coolify keeps the old container).
2. **Panel access by role.** After the first start read the log: `[ipal] N account(s) of "users" are below the
role "editor" and cannot open the admin panel`. Those accounts (role `user`, or no role) now see
"Unauthorized" in the panel. Give the people who work in the panel `editor`, or set
`accounts: { panelRole: 'user' }`. The line `NOBODY can open the admin panel` (an error) means no account has
the role: fix with a script (`payload.update({ collection: 'users', id, data: { roles: ['admin'] } })`,
`pnpm payload run`) or `accounts: { panelRole: false }` + redeploy.
3. **Secrets are write-only.** Nothing to do for a normal site: the SMTP password and Turnstile secret stay
stored; the panel shows "a value is set". `grep -rn "smtpPassword\|turnstileSecretKey" src` — code that read
them over REST / GraphQL as an admin, or with `overrideAccess: false`, now gets `'********'`: read them on the
server with `payload.findGlobal({ slug: 'site-integrations' })`. A script that saves the whole global back
keeps the secrets (the mask means "keep"). **New:** a save in the panel or over the API that changes the SMTP
server, port or user name must send the password again ("Enter the password again…"), also when the transport
is set to Microsoft Graph; a script that does that over REST / GraphQL sends the password with it, a seed
with the Local API is not asked. `secrets: { reenterOnChange: false }` turns it off. During a rolling update a page opened under the new version and saved against the OLD one stores
`********` as the password: after the deploy, check that a test e-mail goes out.
4. **`TURNSTILE_SECRET_KEY` is deprecated** (it still works). If the log says `[ipal] Deprecated: the Turnstile
secret key comes from the TURNSTILE_SECRET_KEY environment variable` or `ipal-doctor --url` reports
`turnstile-env-key`: with the owner, copy the key into Site integrations → Spam protection → Secret key, send a
test form, then remove the variable in Coolify. Do not do it on a client site without the owner. Nothing
breaks if you wait; the removal will be announced in the changelog.
5. **Forms with files and Turnstile.** While Turnstile cannot check (wrong keys, Cloudflare down), a form with a
File field is now refused (text forms are accepted as before). Check `ipal-doctor --url` → no
`turnstile-degraded`; to keep the old behaviour: `forms: { turnstileOnConfigError: { files: 'allow' } }`.
6. **Account creation and changes.** A project whose **own** staff collection has no `create` / `update` /
`delete` / `unlock` / `read` rule gets one (before: any signed-in account of any auth collection — a customer
could change a staff password, list the staff accounts, lift a login lock):
- the collection carries the plugin's roles (`access.authCollection`, or a `roles` select with only `user` /
`editor` / `admin`): create, delete, unlock — an admin; update — an admin or the account itself; its
`roles` field — only an admin (when the field has no `access.update` of its own). **Check:** does a
non-admin create or edit other accounts, or change roles, there today? Then write the rule you want;
- the collection has **role values of its own** (`superadmin`, …) or no roles: accounts of that collection
keep working as before, except that an account no longer changes its **own** roles; accounts of other
collections are refused. **Write your own rules** — the plugin does not know your roles, and inside the
collection every account can still create an account with any role (`ipal-doctor --url` →
`staff-own-roles`);
- `read`: only staff accounts read a staff collection. **Check:** does the front end show staff accounts
(an author box) to logged-in visitors with the visitor's session? Then write that collection's `read` rule,
or `accounts: { staffOnlyRead: false }`. Anonymous visitors never could.
A staff collection added by a plugin listed after ipalKit gets the same rules at start, put in FRONT of the
rules it has (both must allow). If that plugin's collection needs a rule wider than the plugin's default,
set `custom: { ipal: { accountRules: false } }` on it.
`first-register` on any auth collection other than the panel's login collection answers `403` unless that
collection allows sign-up. `access.firstUserAdmin: false` with a default role below `editor`: the panel role
is not applied (a warning at start), or — with `accounts.panelRole` set — the start fails with the fix in the
message. Wanted otherwise: `accounts: { adminOnlyCreate: false, adminOnlyWrite: false, staffOnlyRead: false,
firstUserRoute: 'all' }`.
7. **Passwords.** New passwords of staff accounts need 12 characters; **existing shorter passwords keep
working** — nobody is logged out or asked to change. A script that creates staff accounts with a short
password fails with a validation error: lengthen it, or `accounts: { password: { minLength: 8 } }`.
8. **2FA attempts from another origin** get `403`. A panel or front end on **another domain** than the API that
posts to `/api/verify-totp`: add it — `twoFactor: { …, sameOrigin: { origins: ['https://panel.example.com'] } }`
(or set Payload's `csrf` / `cors`). A same-domain site changes nothing **when the server knows its own
address**: `serverURL` is set, or the proxy passes `Host` (Coolify / Traefik do) or `X-Forwarded-Host`.
**Check before the deploy:** is `serverURL` set? If not and the proxy rewrites `Host` (nginx's plain
`proxy_pass`), nobody can enter a 2FA code after the upgrade — set `serverURL`. After the deploy log in with
a code; if it answers "Not allowed from this origin.", the log has `[ipal] 2FA: a code from origin "…" was
refused` with the fix.
9. **Dashboard alerts.** Editors now see "An integration needs attention. Ask an administrator." instead of the
error text; accounts with only `user` see no alerts. `dashboardAlerts: { integrations: 'all' }` restores it
(`'all'` checks no role and no second factor).
10. **Role checks in client components.** `grep -rlE "^['\"]use client" src | xargs grep -nE "from '@intecion/ipal-kit'"`
— a file that imports `isAdmin`, `isEditor` or `hasMinimumRole` there: change the import to
`@intecion/ipal-kit/client` and keep the second argument (`isAdmin(user, config)`). `import type` may stay.
**Check:** `pnpm exec ipal-doctor --url <site>` (new rules: `access-missing`, `csrf-empty`, `open-signup`,
`staff-accounts-open`, `staff-own-roles`, `turnstile-degraded`, `turnstile-env-key`); as an admin `GET /api/globals/site-integrations` shows
`"smtpPassword":"********"`; a test e-mail and a test form still work; an editor and an admin still log in.
## 2. Inventory (no code changes)
**What changed for projects** between your old and new plugin version is exactly the reference site's diff —
`git diff v<old> v<new> -- reference/` in the ipal-kit repo (or the two `docs/agent/reference-site/INDEX.md` files):
+1 -1
View File
@@ -47,7 +47,7 @@ Write everything in this file in English.
<!-- /starter:decisions -->
<!-- ipal-kit:start -->
## ipal-kit 1.16.5 — agent guide
## ipal-kit 1.16.7 — agent guide
<!-- Managed by `pnpm exec ipal-skills` — edits between the markers are overwritten. -->
This project is built on `@intecion/ipal-kit` (a Payload CMS 3 plugin). Before you write code:
+8
View File
@@ -21,6 +21,14 @@ Production check: `pnpm build && pnpm payload run e2e/create-test-admin.ts && AL
(Playwright starts the built site on port 3100 itself; another port: `E2E_BASE_URL=http://localhost:3200`, built with
the same `NEXT_PUBLIC_SERVER_URL`; a server you started yourself: `E2E_REUSE_SERVER=1`).
Access rules on a built site, both bundlers (a staff collection that a plugin listed after ipalKit adds — unit tests
run unminified code and cannot see what a bundle renames):
```bash
E2E_LATE_STAFF=1 pnpm build && pnpm payload run e2e/create-test-admin.ts && E2E_LATE_STAFF=1 ALLOW_LOCAL_MEDIA=1 pnpm exec playwright test late-staff
E2E_LATE_STAFF=1 pnpm exec next build --turbopack && pnpm payload run e2e/create-test-admin.ts && E2E_LATE_STAFF=1 ALLOW_LOCAL_MEDIA=1 pnpm exec playwright test late-staff
```
Without `E2E_LATE_STAFF=1` the fixture adds nothing and the spec is skipped.
## What is where
| Convention | Files |
|---|---|
+15 -7
View File
@@ -7,7 +7,10 @@
* (E2E_SMTP_PORT, default 2526).
*/
import config from '@payload-config'
import { verifyLimitKey } from '@intecion/ipal-kit'
import { isLocalDatabase } from '@intecion/ipal-kit/seed'
import { secondTestAdmin } from './totp'
import { getPayload } from 'payload'
const { E2E_ADMIN_EMAIL: email, E2E_ADMIN_PASSWORD: password, E2E_TOTP_SECRET: totpSecret } = process.env
@@ -16,14 +19,19 @@ if (process.env.NODE_ENV === 'production' && !process.env.CI) {throw new Error('
if (!isLocalDatabase(process.env.DATABASE_URI ?? '')) {throw new Error('Refusing: DATABASE_URI is not a local database.')}
const payload = await getPayload({ config })
const data = { email, hasTotp: true, password, roles: ['admin'], totpSecret }
const found = await payload.find({ collection: 'users', limit: 1, overrideAccess: true, where: { email: { equals: email } } })
if (found.docs[0]) {
await payload.update({ id: found.docs[0].id, collection: 'users', data: data as never, overrideAccess: true })
} else {
await payload.create({ collection: 'users', data: data as never, overrideAccess: true })
// Two test admins with the same password and TOTP secret. The 2FA verify limit is 5 attempts per account in
// 10 minutes and is stored in the database, so it survives a restart of the site: the smoke and back-link specs
// sign in as the first account, the setup spec as the second, and this script clears both counts — run it again
// before repeating the tests within ten minutes.
for (const address of [email, secondTestAdmin(email)]) {
const data = { email: address, hasTotp: true, password, roles: ['admin'], totpSecret }
const found = await payload.find({ collection: 'users', limit: 1, overrideAccess: true, where: { email: { equals: address } } })
const doc = found.docs[0]
? await payload.update({ id: found.docs[0].id, collection: 'users', data: data as never, overrideAccess: true })
: await payload.create({ collection: 'users', data: data as never, overrideAccess: true })
await payload.kv.delete(verifyLimitKey('users', String(doc.id)))
console.log(`[e2e] test admin ready: ${address}`)
}
console.log(`[e2e] test admin ready: ${email}`)
// E-mail for the smoke tests goes to a local sink the test itself starts (e2e/smtp-sink.ts), so the test can
// read what the site sent — the form file as an attachment. Without the sink running, sends simply fail.
+23
View File
@@ -0,0 +1,23 @@
import type { Config, Plugin } from 'payload'
/**
* Test fixture, on only with E2E_LATE_STAFF=1 (e2e/late-staff.spec.ts): a plugin listed AFTER ipalKit that adds
* a staff collection (`late-staff`, named in `access.staffCollections`) and a visitor collection with open
* sign-up. ipalKit has already run when these collections appear, so it must give them its account rules when
* the config goes live — and it must do so in a BUILT site too, where bundlers rename every function.
* Never part of a real site: the starter drops `e2e/` and the lines that use this file.
*/
export const E2E_LATE_STAFF = process.env.E2E_LATE_STAFF === '1'
export const e2eLateStaff: Plugin = (config: Config) =>
E2E_LATE_STAFF
? {
...config,
collections: [
...(config.collections ?? []),
// no access rules at all: Payload's defaults ("any logged-in user") are what ipalKit must replace
{ slug: 'late-staff', auth: true, fields: [{ name: 'roles', type: 'select', hasMany: true, options: ['user', 'editor', 'admin'], saveToJWT: true }], versions: true },
{ slug: 'e2e-visitors', access: { create: () => true }, auth: true, fields: [] },
],
}
: config
+78
View File
@@ -0,0 +1,78 @@
import { type APIRequestContext, expect, test } from '@playwright/test'
import { randomUUID } from 'node:crypto'
import { totp } from './totp'
/**
* The account rules on a BUILT site, for a staff collection that a plugin listed after ipalKit adds
* (e2e/late-staff-fixture.ts). Unit tests run unminified code; a production bundle renames every function, and a
* rule that told Payload's default access function by its name was silently skipped there. Run it against both
* bundlers (README "Production check"):
* E2E_LATE_STAFF=1 pnpm build && … pnpm exec playwright test late-staff (webpack)
* E2E_LATE_STAFF=1 pnpm next build --turbopack && … the same (Turbopack)
*/
const { E2E_ADMIN_EMAIL: email, E2E_ADMIN_PASSWORD: password, E2E_LATE_STAFF: on, E2E_TOTP_SECRET: secret } = process.env
const PASSWORD = `T-${randomUUID()}`
test.describe('a late staff collection on a built site', () => {
test.skip(on !== '1', 'E2E_LATE_STAFF=1 not set (build and start the site with it)')
test.skip(!email || !password || !secret, 'E2E_* test admin not configured')
const context = (playwright: { request: { newContext: (o: object) => Promise<APIRequestContext> } }, baseURL: string) =>
playwright.request.newContext({ baseURL, extraHTTPHeaders: { origin: baseURL } })
test('a visitor account and an anonymous request get nothing; nobody raises its own role', async ({ baseURL, playwright }) => {
const tag = randomUUID().slice(0, 8)
// a fully signed-in admin of the panel's collection
const admin = await context(playwright, baseURL!)
expect((await admin.post('/api/users/login', { data: { email, password } })).status()).toBe(200)
expect((await (await admin.post('/api/verify-totp', { data: { token: totp(secret!) } })).json()).ok).toBe(true)
// anonymous: the first-user route of the (possibly empty) late collection, in two spellings
const nobody = await context(playwright, baseURL!)
for (const spelling of ['first-register', 'First-Register']) {
const res = await nobody.post(`/api/late-staff/${spelling}`, { data: { email: `first-${tag}@example.com`, password: PASSWORD, roles: ['admin'] } })
expect(res.status(), spelling).toBe(403)
}
expect((await nobody.get('/api/late-staff')).status()).toBe(403)
// the admin makes an account there (the rules let an admin through)
const made = await admin.post('/api/late-staff', { data: { email: `low-${tag}@example.com`, password: PASSWORD, roles: ['user'] } })
expect(made.status()).toBe(201)
const id = (await made.json()).doc.id as string
// a visitor account, signed up by itself
const visitor = await context(playwright, baseURL!)
expect((await visitor.post('/api/e2e-visitors', { data: { email: `v-${tag}@example.com`, password: PASSWORD } })).status()).toBe(201)
expect((await visitor.post('/api/e2e-visitors/login', { data: { email: `v-${tag}@example.com`, password: PASSWORD } })).status()).toBe(200)
const got = {
create: (await visitor.post('/api/late-staff', { data: { email: `x-${tag}@example.com`, password: PASSWORD, roles: ['admin'] } })).status(),
patch: (await visitor.patch(`/api/late-staff/${id}`, { data: { password: `taken-${PASSWORD}` } })).status(),
read: (await visitor.get('/api/late-staff')).status(),
unlock: (await visitor.post('/api/late-staff/unlock', { data: { email: `low-${tag}@example.com` } })).status(),
versions: (await visitor.get('/api/late-staff/versions')).status(),
// last: it would remove the account the other checks use
delete: (await visitor.delete(`/api/late-staff/${id}`)).status(),
}
expect(got).toEqual({ create: 403, delete: 403, patch: 403, read: 403, unlock: 403, versions: 403 })
// nothing an admin opens, either
expect((await visitor.get('/api/globals/site-integrations')).status()).toBe(403)
// the account itself (2FA covers the panel's collection only): its own password yes, its own roles no
const low = await context(playwright, baseURL!)
expect((await low.post('/api/late-staff/login', { data: { email: `low-${tag}@example.com`, password: PASSWORD } })).status()).toBe(200)
await low.patch(`/api/late-staff/${id}`, { data: { roles: ['admin'] } })
const after = await (await admin.get(`/api/late-staff/${id}`)).json()
expect(after.roles).toEqual(['user'])
expect((await low.get('/api/globals/site-integrations')).status()).toBe(403)
expect((await low.post('/api/late-staff/unlock', { data: { email: `low-${tag}@example.com` } })).status()).toBe(403)
// a short password is refused there too (the password rule)
expect((await admin.post('/api/late-staff', { data: { email: `s-${tag}@example.com`, password: 'tooshort', roles: ['user'] } })).status()).toBe(400)
// an admin: everything, and it cleans up
expect((await admin.get('/api/late-staff/versions')).status()).toBe(200)
expect((await admin.post('/api/late-staff/unlock', { data: { email: `low-${tag}@example.com` } })).status()).toBe(200)
expect((await admin.delete(`/api/late-staff/${id}`)).status()).toBe(200)
for (const api of [admin, nobody, visitor, low]) {await api.dispose()}
})
})
+7 -1
View File
@@ -249,6 +249,12 @@ test('API: a staff password without the 2FA code opens nothing; with the code it
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')
// the secret is stored (create-test-admin.ts) and never returned, also to a fully signed-in admin
expect(after.data.SiteIntegration.smtpPassword).toBe('********')
expect(JSON.stringify(after)).not.toContain('e2e-sink')
// …and it stays with the server it was saved for: moving the server without typing the password again is refused
const moved = await api.post('/api/globals/site-integrations', { data: { smtpHost: 'elsewhere.example.com' } })
expect(moved.status()).toBe(400)
expect(await moved.text()).toMatch(/Enter the password again|Wpisz hasło ponownie/)
await api.dispose()
})
+3
View File
@@ -13,3 +13,6 @@ export function totp(secret: string, now = Date.now()): string {
const code = (hmac.readUInt32BE(offset) & 0x7fffffff) % 1_000_000
return code.toString().padStart(6, '0')
}
/** The second smoke-test admin (create-test-admin.ts makes both): `e2e-admin@…` → `e2e-admin-2@…`. */
export const secondTestAdmin = (email: string): string => email.replace('@', '-2@')
+128
View File
@@ -0,0 +1,128 @@
import { type APIRequestContext, expect, type Page, test } from '@playwright/test'
import { secondTestAdmin, totp } from './totp'
/**
* "2FA setup required" in a real browser: an account that has not set two-step verification up sees only the setup
* screen and gets nothing from the API; after the code it is in. Covers the first admin of a fresh site (only when
* the database has no users yet — run this file before e2e/create-test-admin.ts for that), a new editor, and the
* administrator's reset on the account page.
* E2E_BASE_URL=http://localhost:3217 pnpm exec playwright test e2e/two-factor-setup.spec.ts
*/
test.describe.configure({ mode: 'serial' })
const stamp = Date.now()
const OWNER = { email: `e2e-owner-${stamp}@example.com`, password: `owner-${stamp}-Hk29dLq` }
const EDITOR = { email: `e2e-editor-${stamp}@example.com`, password: `editor-${stamp}-Pz71mWx` }
/** The admin the later tests act as: the owner made in the first test, else the smoke-test admin. */
let admin: { email: string; password: string; secret: string } | null =
process.env.E2E_ADMIN_EMAIL && process.env.E2E_ADMIN_PASSWORD && process.env.E2E_TOTP_SECRET
? // the second test admin: the other specs spend the first one's verify attempts (5 per account in 10 minutes)
{ email: secondTestAdmin(process.env.E2E_ADMIN_EMAIL), password: process.env.E2E_ADMIN_PASSWORD, secret: process.env.E2E_TOTP_SECRET }
: null
let editorId: string | undefined
async function typeCode(page: Page, secret: string) {
// six one-digit inputs: type the code into the first, focus moves on by itself
await page.getByRole('textbox').first().click()
await page.keyboard.type(totp(secret))
}
async function signIn(page: Page, who: { email: string; password: string }) {
await page.goto('/admin/login')
await page.fill('#field-email', who.email)
await page.fill('#field-password', who.password)
await page.click('.form-submit button')
}
/** A fully logged-in API session (password, then the code). Payload takes the cookie only with the site's Origin. */
async function adminApi(playwright: { request: { newContext: (o: object) => Promise<APIRequestContext> } }, baseURL: string) {
const api = await playwright.request.newContext({ baseURL, extraHTTPHeaders: { origin: baseURL } })
expect((await api.post('/api/users/login', { data: { email: admin!.email, password: admin!.password } })).status()).toBe(200)
expect((await (await api.post('/api/verify-totp', { data: { token: totp(admin!.secret) } })).json()).ok).toBe(true)
return api
}
test('first admin of a fresh site: created, sent to 2FA setup, in after the code', async ({ baseURL, page }) => {
// With users in the database this address leads to the login screen instead.
await page.goto('/admin/create-first-user')
const firstUserForm = await page.locator('#field-confirm-password').waitFor({ timeout: 10_000 }).then(() => true, () => false)
test.skip(!firstUserForm, 'the database already has users')
// Type like a person, once the form is live: values filled in before hydration are not in the form's state.
await page.waitForLoadState('networkidle')
await page.locator('#field-email').pressSequentially(OWNER.email)
await page.locator('#field-password').pressSequentially(OWNER.password)
await page.locator('#field-confirm-password').pressSequentially(OWNER.password)
const registered = page.waitForResponse((r) => r.url().includes('/first-register') && r.request().method() === 'POST')
await page.click('.form-submit button')
expect((await registered).status()).toBe(200)
await page.waitForURL(/setup-totp/)
await expect(page.locator('#ipal-two-factor-notice')).toContainText(/Ustaw weryfikację dwuetapową do|Set up two-step verification by/)
// nothing but setup, over the API too
for (const path of ['/api/globals/site-integrations', '/api/users', '/api/pages']) {
expect((await page.request.get(path, { headers: { origin: baseURL! } })).status(), path).toBe(403)
}
const secret = await page.locator('input[name="secret"]').inputValue()
await typeCode(page, secret)
await expect(page).toHaveTitle(/Dashboard|Pulpit/, { timeout: 20_000 })
expect((await page.request.get('/api/globals/site-integrations', { headers: { origin: baseURL! } })).status()).toBe(200)
admin = { ...OWNER, secret }
})
test('a new editor: setup screen with the deadline, nothing else, in after the code', async ({ baseURL, page, playwright }) => {
test.skip(!admin, 'no admin to create the editor with (set E2E_* or run on a fresh database)')
const api = await adminApi(playwright, baseURL!)
const created = await api.post('/api/users', { data: { ...EDITOR, roles: ['editor'] } })
expect(created.status()).toBe(201)
editorId = String((await created.json()).doc.id)
await api.dispose()
// the brand images must load on the setup screen too (the session is refused `media` itself)
const refusedImages: string[] = []
page.on('response', (r) => {
if (r.status() === 403 && /\/api\/(media\/|ipal\/admin-icon)/.test(r.url())) {refusedImages.push(r.url())}
})
await signIn(page, EDITOR)
await page.waitForURL(/setup-totp/)
await expect(page.locator('#ipal-two-factor-notice')).toContainText(/Ustaw weryfikację dwuetapową do|Set up two-step verification by/)
for (const path of ['/api/pages', '/api/form-submissions', '/api/globals/site-settings', `/api/users/${editorId}`]) {
expect((await page.request.get(path, { headers: { origin: baseURL! } })).status(), path).toBe(403)
}
expect(refusedImages).toEqual([])
// going elsewhere in the panel leads back to setup
await page.goto('/admin/collections/pages')
await page.waitForURL(/setup-totp/)
const secret = await page.locator('input[name="secret"]').inputValue()
await typeCode(page, secret)
// back where it wanted to go, and the data opens
await page.waitForURL(/\/admin\/collections\/pages/, { timeout: 20_000 })
expect((await page.request.get('/api/pages', { headers: { origin: baseURL! } })).status()).toBe(200)
})
test('the administrator sees the status on the account and resets it; the editor must set it up again', async ({ baseURL, page, playwright }) => {
test.skip(!admin || !editorId, 'needs the editor from the previous test')
await signIn(page, admin!)
await page.waitForURL(/verify-totp|\/admin(\?|$)/, { waitUntil: 'commit' })
if (page.url().includes('verify-totp')) {await typeCode(page, admin!.secret)}
await expect(page).toHaveTitle(/Dashboard|Pulpit/, { timeout: 20_000 })
await page.goto(`/admin/collections/users/${editorId}`)
const status = page.locator('#ipal-two-factor-status')
await expect(status).toContainText(/Ustawiona\.|Set up\./)
page.once('dialog', (dialog) => dialog.accept())
await status.getByRole('button').click()
await expect(status).toContainText(/Nieustawiona\. Konto może ją ustawić do|Not set up\. The account can set it up until/, { timeout: 15_000 })
// the editor's password alone opens nothing again
const editor = await playwright.request.newContext({ baseURL, extraHTTPHeaders: { origin: baseURL! } })
expect((await editor.post('/api/users/login', { data: EDITOR })).status()).toBe(200)
expect((await editor.get('/api/pages')).status()).toBe(403)
await editor.dispose()
// clean up the account this file made
const api = await adminApi(playwright, baseURL!)
expect((await api.delete(`/api/users/${editorId}`)).status()).toBe(200)
await api.dispose()
})
+2
View File
@@ -9,6 +9,8 @@ try {
/**
* Smoke tests against a built, seeded site: pnpm build && pnpm seed && pnpm payload run e2e/create-test-admin.ts.
* Run create-test-admin.ts again before repeating the tests within ten minutes: the 2FA verify limit (5 attempts per
* account in 10 minutes) is stored in the database, and that script clears the test admins' counts.
* E2E_BASE_URL picks the port (default 3100). Playwright starts its own server there and fails when the port is
* taken, so another project's dev server is never tested by mistake; E2E_REUSE_SERVER=1 uses a server you started.
*/
@@ -29,6 +29,7 @@ import { MetaDescriptionCheck as MetaDescriptionCheck_7568fe47d582ff15ce85d2e187
import { MetaImageComponent as MetaImageComponent_a8a977ebc872c5d5ea7ee689724c0860 } from '@payloadcms/plugin-seo/client'
import { PreviewComponent as PreviewComponent_a8a977ebc872c5d5ea7ee689724c0860 } from '@payloadcms/plugin-seo/client'
import { TOTPField as TOTPField_3eb2cc20d1a2569c2ccbafcee15bd128 } from '@clocklimited/payload-2fa/rsc'
import { TwoFactorStatusField as TwoFactorStatusField_7568fe47d582ff15ce85d2e1873c2c23 } from '@intecion/ipal-kit/admin'
import { CookieScanButton as CookieScanButton_7568fe47d582ff15ce85d2e1873c2c23 } from '@intecion/ipal-kit/admin'
import { FaviconCheck as FaviconCheck_7568fe47d582ff15ce85d2e1873c2c23 } from '@intecion/ipal-kit/admin'
import { IntegrationStatusBanner as IntegrationStatusBanner_7568fe47d582ff15ce85d2e1873c2c23 } from '@intecion/ipal-kit/admin'
@@ -39,6 +40,7 @@ import { CookieSiteCheckTab as CookieSiteCheckTab_7568fe47d582ff15ce85d2e1873c2c
import { AdminIcon as AdminIcon_7568fe47d582ff15ce85d2e1873c2c23 } from '@intecion/ipal-kit/admin'
import { AdminLogo as AdminLogo_7568fe47d582ff15ce85d2e1873c2c23 } from '@intecion/ipal-kit/admin'
import { IntecionCredit as IntecionCredit_7568fe47d582ff15ce85d2e1873c2c23 } from '@intecion/ipal-kit/admin'
import { TwoFactorAlert as TwoFactorAlert_7568fe47d582ff15ce85d2e1873c2c23 } from '@intecion/ipal-kit/admin'
import { CookieCrawlAlert as CookieCrawlAlert_7568fe47d582ff15ce85d2e1873c2c23 } from '@intecion/ipal-kit/admin'
import { IntegrationAlerts as IntegrationAlerts_7568fe47d582ff15ce85d2e1873c2c23 } from '@intecion/ipal-kit/admin'
import { TotpRedirectProvider as TotpRedirectProvider_7568fe47d582ff15ce85d2e1873c2c23 } from '@intecion/ipal-kit/admin'
@@ -82,6 +84,7 @@ export const importMap = {
"@payloadcms/plugin-seo/client#MetaImageComponent": MetaImageComponent_a8a977ebc872c5d5ea7ee689724c0860,
"@payloadcms/plugin-seo/client#PreviewComponent": PreviewComponent_a8a977ebc872c5d5ea7ee689724c0860,
"@clocklimited/payload-2fa/rsc#TOTPField": TOTPField_3eb2cc20d1a2569c2ccbafcee15bd128,
"@intecion/ipal-kit/admin#TwoFactorStatusField": TwoFactorStatusField_7568fe47d582ff15ce85d2e1873c2c23,
"@intecion/ipal-kit/admin#CookieScanButton": CookieScanButton_7568fe47d582ff15ce85d2e1873c2c23,
"@intecion/ipal-kit/admin#FaviconCheck": FaviconCheck_7568fe47d582ff15ce85d2e1873c2c23,
"@intecion/ipal-kit/admin#IntegrationStatusBanner": IntegrationStatusBanner_7568fe47d582ff15ce85d2e1873c2c23,
@@ -92,6 +95,7 @@ export const importMap = {
"@intecion/ipal-kit/admin#AdminIcon": AdminIcon_7568fe47d582ff15ce85d2e1873c2c23,
"@intecion/ipal-kit/admin#AdminLogo": AdminLogo_7568fe47d582ff15ce85d2e1873c2c23,
"@intecion/ipal-kit/admin#IntecionCredit": IntecionCredit_7568fe47d582ff15ce85d2e1873c2c23,
"@intecion/ipal-kit/admin#TwoFactorAlert": TwoFactorAlert_7568fe47d582ff15ce85d2e1873c2c23,
"@intecion/ipal-kit/admin#CookieCrawlAlert": CookieCrawlAlert_7568fe47d582ff15ce85d2e1873c2c23,
"@intecion/ipal-kit/admin#IntegrationAlerts": IntegrationAlerts_7568fe47d582ff15ce85d2e1873c2c23,
"@intecion/ipal-kit/admin#TotpRedirectProvider": TotpRedirectProvider_7568fe47d582ff15ce85d2e1873c2c23,
+2
View File
@@ -1292,6 +1292,7 @@ export interface User {
id: string;
totpSecret?: string | null;
hasTotp?: boolean | null;
totpSetupFrom?: string | null;
/**
* Administrators manage everything; editors manage content.
*/
@@ -2076,6 +2077,7 @@ export interface MediaSelect<T extends boolean = true> {
export interface UsersSelect<T extends boolean = true> {
totpSecret?: T;
hasTotp?: T;
totpSetupFrom?: T;
roles?: T;
updatedAt?: T;
createdAt?: T;
+12 -1
View File
@@ -18,6 +18,9 @@ import { Pages } from './collections/Pages'
// @starter:if posts
import { Posts } from './collections/Posts'
// @starter:endif
// @starter:if demo
import { E2E_LATE_STAFF, e2eLateStaff } from '../e2e/late-staff-fixture'
// @starter:endif
import { contentConfig } from './content.config'
import { db } from './db'
import { Company } from './globals/Company'
@@ -55,7 +58,12 @@ export default buildConfig({
plugins: [
ipalKit({
i18n: i18nConfig,
access: { authCollection: 'users' },
// @starter:if demo
// (the staffCollections entry exists only for e2e/late-staff.spec.ts, with E2E_LATE_STAFF=1)
access: { authCollection: 'users', ...(E2E_LATE_STAFF ? { staffCollections: ['late-staff'] } : {}) },
// @starter:else
//: access: { authCollection: 'users' },
// @starter:endif
pages: { slug: 'pages' },
content: contentConfig,
seo: {
@@ -105,5 +113,8 @@ export default buildConfig({
revalidatePath,
}),
buildR2Storage(['media'], { s3Storage }), // R2 with the full R2_* set, local disk without it
// @starter:if demo
e2eLateStaff, // a test fixture, a no-op without E2E_LATE_STAFF=1 (e2e/late-staff-fixture.ts)
// @starter:endif
],
})
+5 -2
View File
@@ -59,11 +59,14 @@ export const DESCRIPTIONS = {
'DESIGN.md': 'the human source of the look, matching src/design/tokens.ts',
'README.md': 'how to run the reference site and what is where',
'docs/DEPLOY.md': 'the Coolify runbook: local check, app settings, MongoDB resource, env, targeted seeds, DNS, rollback',
'e2e/create-test-admin.ts': 'a test admin with a known TOTP secret, and e-mail sending pointed at the tests\' mail sink (local / CI database only)',
'e2e/create-test-admin.ts': 'two test admins with a known TOTP secret (the specs share out the five 2FA verify attempts per account), their stored verify counts cleared, and e-mail sending pointed at the tests\' mail sink (local / CI database only)',
'e2e/late-staff-fixture.ts': 'test fixture, on only with E2E_LATE_STAFF=1: a plugin listed after ipalKit that adds a staff collection without rules and a visitor collection with open sign-up',
'e2e/late-staff.spec.ts': 'the account rules on a BUILT site for a staff collection a later plugin adds (run after a webpack and a Turbopack build): a visitor account gets nothing, nobody raises its own role',
'e2e/two-factor-setup.spec.ts': 'browser check of "2FA setup required": the first admin of a fresh site, a new editor, the administrator\'s reset on the account page',
'e2e/smoke.spec.ts': 'the smoke tests every release must pass: pages, showcase, forms (also a file sent by e-mail), sitemap, SEO/GEO, headers, consent, 2FA',
'e2e/smtp-sink.ts': 'a local mail sink for the smoke tests: reads what the site really sent (recipients, attachments)',
'e2e/two-factor-back.spec.ts': 'browser test of the 2FA screens\' `back` link (twoFactor.safeBack): a prepared link — script or another host — ends on the admin root, an ordinary one is followed',
'e2e/totp.ts': 'RFC 6238 code generator for the 2FA sign-in in the smoke test',
'e2e/totp.ts': 'RFC 6238 code generator for the 2FA sign-in in the smoke test, and the address of the second test admin',
'ipal-doctor.json': 'the production domain and launch state for ipal-doctor',
'next.config.ts': 'security headers, enforced CSP, admin CSP, upload headers, images, no X-Powered-By',
'package.json': 'scripts (build, start, seed, tokens, generate), pinned Payload versions and overrides',
+3
View File
@@ -22,6 +22,9 @@ export { SafeTotpView } from '../modules/security/totp/SafeTotpView.js'
export type { SafeTotpViewProps } from '../modules/security/totp/SafeTotpView.js'
export { TotpRedirectProvider } from '../modules/security/totp/TotpRedirectProvider.js'
export type { TotpRedirectProviderProps } from '../modules/security/totp/TotpRedirectProvider.js'
export { TwoFactorAlert } from '../modules/security/totp/TwoFactorAlert.js'
export { TwoFactorResetButton } from '../modules/security/totp/TwoFactorResetButton.js'
export { TwoFactorStatusField } from '../modules/security/totp/TwoFactorStatusField.js'
export { FaviconCheck } from '../modules/seo/FaviconCheck.js'
export type { FaviconCheckProps } from '../modules/seo/FaviconCheck.js'
export { MetaDescriptionCheck } from '../modules/seo/MetaDescriptionCheck.js'
+4
View File
@@ -1,4 +1,8 @@
'use client'
// Role predicates for client components (the main entry reaches 'server-only' modules and does not build
// there with webpack). Concrete file, not the access barrel. On the server import them from the main entry.
export { hasMinimumRole, isAdmin, isEditor } from '../modules/access/predicates.js'
export type { Role } from '../modules/access/types.js'
export { A11Y_DEFAULT_TEXTS, AccessibilityProvider, AccessibilityWidget, useAccessibility } from '../modules/accessibility/client.js'
export type { A11yClassNames, A11yState, A11yTexts } from '../modules/accessibility/client.js'
export { Analytics } from '../modules/analytics/client.js'
+2
View File
@@ -4,6 +4,8 @@ export { createSubmitAction, splitFormFiles } from '../modules/forms/createSubmi
export type { SubmitActionResult } from '../modules/forms/createSubmitAction.js'
export { submitForm } from '../modules/forms/index.js'
export type { SubmitFormArgs, SubmitFormResult } from '../modules/forms/index.js'
export { passSubmitGates, passTurnstile, resolveTurnstileOnConfigError, TURNSTILE_ON_CONFIG_ERROR_DEFAULT } from '../modules/forms/submitForm.js'
export type { TurnstileFormKind, TurnstileOnConfigError, TurnstileOnConfigErrorOption } from '../modules/forms/submitForm.js'
/**
* Entry point: ipal-kit/server
*
@@ -6,32 +6,35 @@ import { FieldDescription, FieldLabel, useField, useTranslation } from '@payload
import { useState } from 'react'
import { ipalT } from '../../../modules/admin-i18n/t.js'
import { SECRET_CLEAR, SECRET_MASK } from '../../../modules/secrets/constants.js'
/**
* Masked text input for sensitive values (SMTP password, R2 secret key,
* Turnstile secret key, etc.).
* Text input for a secret (SMTP password, Turnstile secret key, …).
*
* Renders the value as a password field (••••) so secrets aren't shown in
* plaintext on screen — protecting against shoulder-surfing and accidental
* exposure when the panel is open. The value is still stored and returned
* normally (UI masking, NOT hashing or encryption), because the plugin must
* read it back to authenticate with SMTP/R2/Turnstile. A toggle reveals the
* value when an authorised editor genuinely needs to check it.
* With a write-only field (modules/secrets/writeOnly.ts — the default for the plugin's own
* secrets) the stored value never reaches the browser: the field arrives as `SECRET_MASK`.
* The input then stays empty and says that a value is set; typing replaces it, leaving it
* alone keeps it, "Remove the stored value" clears it on save.
*
* Uses a raw <input> driven by useField rather than @payloadcms/ui's TextInput,
* because TextInput doesn't expose inputProps, so there's no way to switch its
* inner input to type="password".
* Without write-only (`secrets: { writeOnly: false }`, or a plain text field of a project) the
* value itself arrives; it is drawn as dots with a Show / Hide toggle, as before.
*
* Uses a raw <input> driven by useField rather than @payloadcms/ui's TextInput, because
* TextInput doesn't expose inputProps, so its inner input cannot be type="password".
*
* Assigned via a field's admin.components.Field. Works on any `text` field.
*/
export const MaskedField: TextFieldClientComponent = ({ field, path }) => {
const { t } = useTranslation()
const { setValue, value } = useField<string>({ path })
const { errorMessage, setValue, showError, value } = useField<string>({ path })
const [revealed, setRevealed] = useState(false)
// A string or one string per language — FieldLabel / FieldDescription translate it.
const label = field?.label || field?.name || path
const description = field?.admin?.description
const stored = value === SECRET_MASK // a value is set on the server; this is not it
const removing = value === SECRET_CLEAR
const link = { background: 'none', border: 'none', cursor: 'pointer', font: 'inherit', opacity: 0.75, padding: '.25rem .5rem', textDecoration: 'underline', whiteSpace: 'nowrap' } as const
return (
<div className="field-type text masked-field">
@@ -45,28 +48,38 @@ export const MaskedField: TextFieldClientComponent = ({ field, path }) => {
className="field-type__input"
id={`field-${path}`}
onChange={(e) => setValue(e.target.value)}
placeholder={stored ? '••••••••' : undefined}
style={{ flex: 1 }}
type={revealed ? 'text' : 'password'}
value={value ?? ''}
value={stored || removing ? '' : (value ?? '')}
/>
<button
onClick={() => setRevealed((r) => !r)}
style={{
background: 'none',
border: 'none',
cursor: 'pointer',
font: 'inherit',
opacity: 0.75,
padding: '.25rem .5rem',
textDecoration: 'underline',
whiteSpace: 'nowrap',
}}
type="button"
>
{ipalT(t as never, revealed ? 'maskedHide' : 'maskedShow')}
</button>
{stored ? (
<button onClick={() => setValue(SECRET_CLEAR)} style={link} type="button">
{ipalT(t as never, 'maskedRemove')}
</button>
) : removing ? (
<button onClick={() => setValue(SECRET_MASK)} style={link} type="button">
{ipalT(t as never, 'maskedKeep')}
</button>
) : (
<button onClick={() => setRevealed((r) => !r)} style={link} type="button">
{ipalT(t as never, revealed ? 'maskedHide' : 'maskedShow')}
</button>
)}
</div>
{showError && errorMessage ? (
<p className="field-description" role="alert" style={{ color: 'var(--theme-error-500)', margin: '.25rem 0 0' }}>
{errorMessage}
</p>
) : null}
{stored || removing ? (
<p className="field-description" role="status" style={{ margin: '.25rem 0 0' }}>
{ipalT(t as never, stored ? 'maskedSet' : 'maskedRemoved')}
</p>
) : null}
{description && typeof description !== 'function' ? (
<FieldDescription description={description} path={path} />
) : null}
+21 -2
View File
@@ -1,6 +1,7 @@
import type { Field, GlobalConfig } from 'payload'
import { userMeetsRole } from '../../modules/access/index.js'
import { INTEGRATION_SECRET_FIELDS, maskSecretsOnRestore, SMTP_PASSWORD_BOUND_TO, writeOnlySecrets } from '../../modules/secrets/writeOnly.js'
import { indexNowFields } from '../../modules/seo/indexNow.js'
import { analyticsFields } from './fields/analytics.js'
import { smtpFields } from './fields/smtp.js'
@@ -9,6 +10,18 @@ import { turnstileFields } from './fields/turnstile.js'
type BuildSiteIntegrationsArgs = {
/** Extra fields injected by the client project */
additionalFields?: Field[]
/**
* A save through access control that changes the SMTP server, port or user name must send the
* password again (or remove it), whatever the transport. Default true; needs write-only
* secrets. `false` = the stored password follows the new server, as before.
*/
reenterSecretOnChange?: boolean
/**
* The stored secrets (`smtpPassword`, `turnstileSecretKey`) are write-only: reads through
* access control get `SECRET_MASK`, never the value (modules/secrets/writeOnly.ts). Default
* true; `false` = the value is returned to whoever may read the global, as before.
*/
writeOnlySecrets?: boolean
}
/**
@@ -25,7 +38,11 @@ type BuildSiteIntegrationsArgs = {
*/
export function buildSiteIntegrations({
additionalFields,
reenterSecretOnChange = true,
writeOnlySecrets: writeOnly = true,
}: BuildSiteIntegrationsArgs = {}): GlobalConfig {
const secret = (fields: Field[]) =>
writeOnly ? writeOnlySecrets(fields, INTEGRATION_SECRET_FIELDS, reenterSecretOnChange ? { smtpPassword: { boundTo: SMTP_PASSWORD_BOUND_TO } } : {}) : fields
return {
slug: 'site-integrations',
access: {
@@ -48,10 +65,10 @@ export function buildSiteIntegrations({
en: 'Cloudflare Turnstile checks that forms are sent by people, not bots.',
pl: 'Cloudflare Turnstile sprawdza, czy formularze wysyłają ludzie, a nie boty.',
},
fields: turnstileFields,
fields: secret(turnstileFields),
label: { en: 'Spam protection', pl: 'Ochrona przed spamem' },
},
{ fields: smtpFields, label: { en: 'E-mail sending', pl: 'Wysyłka e-mail' } },
{ fields: secret(smtpFields), label: { en: 'E-mail sending', pl: 'Wysyłka e-mail' } },
{ fields: indexNowFields, label: { en: 'IndexNow', pl: 'IndexNow' } },
...(additionalFields?.length
? [{ fields: additionalFields, label: { en: 'More', pl: 'Więcej' } }]
@@ -60,6 +77,8 @@ export function buildSiteIntegrations({
},
],
hooks: {
// a restore answers with the version document: the secrets are masked there too
...(writeOnly ? { afterRead: [maskSecretsOnRestore] } : {}),
beforeChange: [
// Keys edited in the panel → clear that integration's old status, so a stale
// "not working" banner doesn't linger until the next form submission.
+60 -3
View File
@@ -21,6 +21,30 @@ export {
staffCollectionSlugs,
userMeetsRole,
} from './modules/access/index.js'
export { applyPanelRole, countBelowPanelRole, DEFAULT_PANEL_ROLE, panelAccess, resolvePanelRole } from './modules/access/panelRole.js'
export { applyPasswordRule, buildPasswordRuleHook, checkPassword, DEFAULT_PASSWORD_MIN_LENGTH, resolvePasswordRule } from './modules/access/passwordRule.js'
export type { PasswordRuleOptions } from './modules/access/passwordRule.js'
export {
adoptLateAuthCollections,
applyFirstUserRoute,
applyStaffAccountAccess,
bothAllow,
buildFirstUserEndpoint,
hasPluginRoles,
openSignUpCollections,
rolesByAdminOnly,
rolesNotOwn,
sameStaffCollectionAccess,
staffCollectionsOnOwnRoles,
staffCollectionsOpenToOthers,
staffCreateAccess,
staffReadAccess,
staffUpdateAccess,
unknownStaffCollections,
} from './modules/access/selfRegistration.js'
export type { LateAdoption, StaffAccountAccessOptions, StaffAccountRules } from './modules/access/selfRegistration.js'
export type { FirstUserRouteOption } from './modules/access/selfRegistration.js'
export type { AccountsOptions } from './modules/access/types.js'
// Concrete files, not module barrels: a barrel that also re-exports 'use client'
// components would load React UI into payload.config / the CLI (test/entryGraph).
export { A11Y_COOKIE, A11Y_DEFAULT, a11yAttributes, parseA11y, serializeA11y } from './modules/accessibility/state.js'
@@ -40,6 +64,7 @@ export type { SectionHeaderFieldOptions, SectionSettingsFieldOptions } from './m
export { buildAdminImageEndpoints } from './modules/branding/adminImages.js'
export { ADMIN_META_TEXTS, adminMetaForSite, buildAdminMeta, DEFAULT_AGENCY, syncAdminMeta } from './modules/branding/adminMeta.js'
export type { AdminMetaOptions, AgencyOption, ResolvedAdminMeta } from './modules/branding/adminMeta.js'
export { fetchPublicImage, PUBLIC_IMAGE_MAX_BYTES, publicImageDataUri, rasterImageType, siteOrigin } from './modules/branding/publicImage.js'
export {
ACCEPT_ALL_CONSENT,
buildConsentLogCollection,
@@ -296,6 +321,21 @@ export { buildTableOfContentsField, extractHeadings, headingText } from './modul
export type { ExtractHeadingsOptions, HeadingItem, HeadingLevel } from './modules/richtext/headings.js'
// Lexical → Markdown (pure, no React) — for AI-readable output.
export { lexicalToMarkdown } from './modules/richtext/lexicalToMarkdown.js'
export {
buildKeepSecret,
INTEGRATION_SECRET_FIELDS,
isSecretMask,
keepSecretBeforeValidate,
maskSecretAfterRead,
maskSecretsOnRestore,
maskWriteOnlySecrets,
SECRET_CLEAR,
SECRET_MASK,
SMTP_PASSWORD_BOUND_TO,
writeOnlySecret,
writeOnlySecrets,
} from './modules/secrets/writeOnly.js'
export type { WriteOnlySecretOptions } from './modules/secrets/writeOnly.js'
export {
buildAdminCsp,
buildAdminCspHeaders,
@@ -312,8 +352,10 @@ export {
parseCspReports,
totpAdminPath,
totpRedirectTarget,
UPLOAD_SECURITY_HEADERS,
withSecurityConfig,
} from './modules/security/index.js'
export type {
BuildAdminCspArgs,
BuildCspArgs,
@@ -326,12 +368,27 @@ export type {
WithSecurityConfigOptions,
} from './modules/security/index.js'
export type { BuildSecurityHeadersArgs, SecurityHeader } from './modules/security/index.js'
export { findImportMapFile, missingImportMapEntries } from './modules/security/totp/importMapCheck.js'
export { changedViewKeys, copyViews, SAFE_TOTP_VIEW, safeAdminBack, totpViewImportKey, wrapTotpViews } from './modules/security/totp/safeBack.js'
export type { SafeBackContext, SafeBackRule, TotpViewComponent } from './modules/security/totp/safeBack.js'
export { requireSecondFactor, secondFactorPassed } from './modules/security/totp/secondFactor.js'
export { ownOrigins, reportRefusedOrigin, requestFromOwnOrigin } from './modules/security/totp/sameOrigin.js'
export { requireSecondFactor, secondFactorPassed, twoFactorSetupDeadline, twoFactorSetupState } from './modules/security/totp/secondFactor.js'
export type { TwoFactorSetupState } from './modules/security/totp/secondFactor.js'
export { SETUP_FROM_FIELD } from './modules/security/totp/secondFactor.js'
export {
backfillSetupFrom,
buildSetupFields,
buildTwoFactorResetEndpoint,
countAccountsWithoutTotp,
DEFAULT_SETUP_WINDOW_HOURS,
resolveRequireSetup,
stampSetupFrom,
strictExempt,
TWO_FACTOR_RESET_PATH,
} from './modules/security/totp/setupRequired.js'
export type { RequireSetupOptions, TwoFactorResetOptions } from './modules/security/totp/setupRequired.js'
export { TOTP_TEXTS, TOTP_VIEW_TITLE } from './modules/security/totp/totpTexts.js'
export { buildVerifyLimit, clearVerifyLimits, verifyLimitKey } from './modules/security/totp/verifyLimit.js'
export type { VerifyLimitOptions } from './modules/security/totp/verifyLimit.js'
export type { OgImage } from './modules/seo/buildMetadata.js'
export type { PageMetadata, SeoMeta, SeoOption } from './modules/seo/index.js'
@@ -399,7 +456,7 @@ export type { Theme, ThemeConfig, ThemeSetting } from './modules/theme/index.js'
// which imports 'server-only'.
export { defineTokens, IPAL_BREAKPOINTS, IPAL_TOKENS, ipalVar } from './modules/tokens/index.js'
export type { IpalTokenName, TokensInput } from './modules/tokens/index.js'
export { getTurnstileConfig } from './modules/turnstile/config.js'
export { getTurnstileConfig, TURNSTILE_SECRET_ENV, turnstileSecretFromEnv } from './modules/turnstile/config.js'
export type { TurnstileConfig } from './modules/turnstile/config.js'
export { ipalKit } from './plugin.js'
export type { IpalOptions, ThemeOptions } from './types.js'
+60
View File
@@ -0,0 +1,60 @@
import type { BasePayload, CollectionConfig, Config } from 'payload'
import type { Role } from './types.js'
import { hasMinimumRole } from './predicates.js'
import { ROLE_HIERARCHY } from './types.js'
/**
* Who may open the admin panel.
*
* Payload lets every account of the login collection into the panel; what it sees there is
* decided per collection. The lowest role (`user`) is the default for a new account and has
* no business in the panel: by default the panel opens for `editor` and above
* (`accounts.panelRole`). It is Payload's own `access.admin` on the login collection, so the
* API is not touched — a `user` account still logs in over the API and gets what its role allows.
*
* The rule looks at the role only, not at the second factor: an editor who has typed the
* password must still reach the 2FA screens, which are part of the panel.
*/
export const DEFAULT_PANEL_ROLE: Role = 'editor'
/** `access.admin` for a staff collection: the account holds at least `minimum`. */
export const panelAccess =
(minimum: Role = DEFAULT_PANEL_ROLE): NonNullable<NonNullable<CollectionConfig['access']>['admin']> =>
({ req }) =>
hasMinimumRole(req.user, minimum, req.payload)
/** `accounts.panelRole` → the role to require, or null when the rule is off (`false`, or the lowest role). */
export function resolvePanelRole(option: false | Role | undefined): null | Role {
if (option === false) {return null}
const role = option ?? DEFAULT_PANEL_ROLE
if (!ROLE_HIERARCHY.includes(role)) {
throw new Error(`[ipal] accounts.panelRole must be one of ${ROLE_HIERARCHY.join(', ')} or false, got ${JSON.stringify(option)}.`)
}
return role === ROLE_HIERARCHY[0] ? null : role
}
/**
* Sets `access.admin` on the collection that carries the roles, unless the project wrote its
* own (`access.admin` on its collection, or `access.authAccess.admin` for the injected one).
*/
export function applyPanelRole(config: Config, slug: string, minimum: Role): Config {
return {
...config,
collections: (config.collections ?? []).map((collection) =>
collection.slug === slug && !collection.access?.admin ? { ...collection, access: { ...collection.access, admin: panelAccess(minimum) } } : collection,
),
}
}
/**
* How many accounts of the collection are below the panel role (no role, or only lower ones),
* and how many there are. For the start-up line that tells a site what the rule did to it.
*/
export async function countBelowPanelRole(payload: BasePayload, slug: string, minimum: Role): Promise<{ all: number; below: number }> {
const allowed = ROLE_HIERARCHY.slice(ROLE_HIERARCHY.indexOf(minimum))
const all = (await payload.count({ collection: slug as never, overrideAccess: true })).totalDocs
const able = (await payload.count({ collection: slug as never, overrideAccess: true, where: { roles: { in: [...allowed] } } as never })).totalDocs
return { all, below: Math.max(0, all - able) }
}
+104
View File
@@ -0,0 +1,104 @@
import type { CollectionBeforeOperationHook, Config } from 'payload'
import { ValidationError } from 'payload'
import { serverText } from '../integrations/texts.js'
/**
* A password rule for staff accounts.
*
* Payload's own rule is a minimum of three characters. Default here: twelve, and not the
* account's own e-mail address (`accounts.password`). It is checked when a password is SET —
* creating an account, the first-user screen, changing a password, a reset by e-mail — in the
* panel, over the API and through the Local API alike. **A password that already exists is
* never checked:** an account with a shorter one keeps logging in, and is held to the rule the
* next time its password is changed.
*
* No breached-password lookup: that would send (part of a hash of) every new password to an
* outside service, and is left to a project that wants it — `checkPassword` and the hook are
* exported to build on.
*/
export const DEFAULT_PASSWORD_MIN_LENGTH = 12
export type PasswordRuleOptions = {
/** Shortest password accepted when one is set. Default 12. */
minLength?: number
}
/** `accounts.password` → the rule, or null when it is off (`false`). Throws on a value that is not a whole number ≥ 1. */
export function resolvePasswordRule(option: false | PasswordRuleOptions | undefined): null | Required<PasswordRuleOptions> {
if (option === false) {return null}
const minLength = option?.minLength ?? DEFAULT_PASSWORD_MIN_LENGTH
if (typeof minLength !== 'number' || !Number.isInteger(minLength) || minLength < 1) {
throw new Error(`[ipal] accounts.password.minLength must be a whole number of 1 or more, got ${JSON.stringify(option?.minLength) ?? String(option?.minLength)}. Use accounts: { password: false } to turn the rule off.`)
}
return { minLength }
}
/** What is wrong with a new password, or null. Length is counted in characters, not bytes. */
export function checkPassword(password: string, { email, minLength = DEFAULT_PASSWORD_MIN_LENGTH }: { email?: null | string; minLength?: number } = {}): 'email' | 'short' | null {
if ([...password].length < minLength) {return 'short'}
if (email && password.trim().toLowerCase() === email.trim().toLowerCase()) {return 'email'}
return null
}
/**
* `beforeOperation` hook for an auth collection: validates a password that is being set
* (`create`, `update`, `resetPassword`). Login, refresh and every other operation pass untouched.
*/
export function buildPasswordRuleHook({ minLength = DEFAULT_PASSWORD_MIN_LENGTH }: PasswordRuleOptions = {}): CollectionBeforeOperationHook {
return async ({ args, collection, operation, req }) => {
if (operation !== 'create' && operation !== 'update' && operation !== 'resetPassword') {return args}
const data = (args as { data?: { email?: unknown; password?: unknown } }).data
const password = data?.password
if (password === undefined || password === null || password === '') {return args} // no password in this request: nothing is being set
const refuse = (problem: 'email' | 'short'): never => {
const i18n = req?.i18n as Parameters<typeof serverText>[0]
const message = problem === 'short' ? serverText(i18n, 'passwordTooShort', { min: minLength }) : serverText(i18n, 'passwordIsEmail')
throw new ValidationError({ collection: collection.slug, errors: [{ message, path: 'password' }] }, req?.t)
}
// a number, a list, an object: not a password (it used to end in a server error further on)
if (typeof password !== 'string') {return refuse('short')}
// The address(es) the password must differ from: the one in the request, else the account(s)
// the request is about — by id, by the reset token, or every account a bulk update matches.
const emails: string[] = typeof data?.email === 'string' ? [data.email] : []
if (!emails.length && req?.payload) {
const { id, where } = args as { id?: number | string; where?: unknown }
const token = (data as { token?: unknown }).token
const query =
operation === 'update' && id !== undefined
? { id: { equals: id } }
: operation === 'update' && where && typeof where === 'object'
? where
: operation === 'resetPassword' && typeof token === 'string' && token
? { resetPasswordToken: { equals: token } }
: null
if (query) {
try {
const found = await req.payload.find({ collection: collection.slug as never, depth: 0, limit: 0, overrideAccess: true, pagination: false, req, where: query as never })
for (const doc of found.docs as { email?: unknown }[]) {
if (typeof doc?.email === 'string') {emails.push(doc.email)}
}
} catch {
/* the account cannot be looked up: the length is still checked */
}
}
}
const problem = checkPassword(password, { minLength }) ?? (emails.some((email) => checkPassword(password, { email, minLength }) === 'email') ? 'email' : null)
if (problem) {return refuse(problem)}
return args
}
}
/** Adds the rule to the named auth collections that log in with a password. */
export function applyPasswordRule(config: Config, slugs: string[], rule: Required<PasswordRuleOptions>): Config {
const hook = buildPasswordRuleHook(rule)
return {
...config,
collections: (config.collections ?? []).map((collection) => {
const auth = collection.auth
const local = Boolean(auth) && !(typeof auth === 'object' && auth.disableLocalStrategy === true)
return local && slugs.includes(collection.slug) ? { ...collection, hooks: { ...collection.hooks, beforeOperation: [...(collection.hooks?.beforeOperation ?? []), hook] } } : collection
}),
}
}
+4 -2
View File
@@ -86,7 +86,8 @@ export function staffCollectionSlugs(source?: MaybePayload): string[] {
* - where the staff collections are not known — no source given and ipalKit
* never ran in this bundle (client components, Next middleware, the edge
* runtime) — nobody is staff. Pass the source there: `isAdmin(user, config)`
* with the config from `useConfig()`, or `isAdmin(user, { staffCollections: ['users'] })`.
* with the config from `useConfig()` (client components import from
* '@intecion/ipal-kit/client'), or `isAdmin(user, { staffCollections: ['users'] })`.
*/
function isStaffAccount(user: MaybeUser, source?: MaybePayload): boolean {
if (!user || typeof user !== 'object') {return false}
@@ -117,7 +118,8 @@ function highestRoleIndex(user: MaybeUser): number {
* functions, hooks, endpoints); without it the staff collections of the
* config ipalKit built in this process are used — and where there is none
* (a browser bundle, middleware) the answer is false: pass the config from
* `useConfig()` or `{ staffCollections: ['users'] }` there.
* `useConfig()` or `{ staffCollections: ['users'] }` there. A client component
* imports it from '@intecion/ipal-kit/client': the main entry does not build there with webpack.
*/
export function hasMinimumRole(user: MaybeUser, minimum: Role, payload?: MaybePayload): boolean {
if (!isStaffAccount(user, payload)) {return false}
+4 -1
View File
@@ -52,7 +52,10 @@ export function buildRolesField(defaultRole: Role = 'user', { firstUserAdmin = t
hooks: {
beforeChange: [
async ({ collection, operation, req, value }) => {
if (operation !== 'create' || !collection || !req.pathname?.endsWith('/first-register')) {return value}
// The first-user route: marked by the plugin's own endpoint (selfRegistration.ts); where that is off
// (accounts.firstUserRoute: 'all'), by Payload's path, in any letter case — as Payload's router matches it.
const first = req.context?.ipalFirstRegister === true || /\/first-register\/?$/i.test(req.pathname ?? '')
if (operation !== 'create' || !collection || !first) {return value}
const { totalDocs } = await req.payload.count({ collection: collection.slug, overrideAccess: true, req })
return totalDocs === 0 ? ['admin'] : value
},
+377
View File
@@ -0,0 +1,377 @@
import type { Access, CollectionConfig, Config, Endpoint, PayloadRequest } from 'payload'
import { secondFactorPassed } from '../security/totp/secondFactor.js'
import { staffCollectionSlugs, userMeetsRole } from './predicates.js'
import { ROLE_HIERARCHY } from './types.js'
/**
* Nobody creates an account for themselves, and nobody takes one over.
*
* Payload's defaults for a collection without access rules are "any logged-in user" for
* `create`, `update` and `delete` — an account of ANY auth collection. On a project's own
* staff collection that let a visitor account (`customers`) create a staff account, or change
* a staff account's password and roles. And Payload's first-user route
* (`POST /api/<slug>/first-register`) answers for EVERY auth collection while it is empty —
* on an empty second staff collection the first visitor became a staff account.
*
* Defaults now, for the staff collections (`accounts.adminOnlyCreate`, `accounts.adminOnlyWrite`,
* `accounts.firstUserRoute`) — a rule the project wrote always stays:
*
* - a collection whose roles are the plugin's (`roles` with user / editor / admin):
* create — an admin; update — an admin, or the account itself; delete — an admin;
* - a staff collection with other roles, or none (the plugin cannot tell who its admins
* are): an account of that same collection, or a plugin admin of another staff
* collection. A visitor account, and an editor of another staff collection, are refused;
* - the first-user route answers only for the collection the panel logs in with, unless a
* collection's own `create` rule lets an anonymous request through.
*
* Always "fully signed in": the second factor is part of every one of these rules. They are
* put on the collections BEFORE the 2FA package runs, because that package gives every
* collection a `create` / `update` / `delete` function of its own (Payload's default, wrapped)
* — afterwards a missing rule can no longer be told from one the project wrote.
*/
type Staffish = Pick<CollectionConfig, 'fields' | 'slug'>
const collectionOf = (req: PayloadRequest): string | undefined => (req.user as { collection?: string } | null | undefined)?.collection
/** `create` / `delete` where the roles are the plugin's: an admin, fully signed in. */
export const staffCreateAccess: Access = ({ req }) => userMeetsRole(req, 'admin')
/** `update` where the roles are the plugin's: an admin, or the account itself (fully signed in). */
export const staffUpdateAccess =
(slug: string): Access =>
({ req }) => {
if (userMeetsRole(req, 'admin')) {return true}
if (!req.user || collectionOf(req) !== slug || !secondFactorPassed(req)) {return false}
return { id: { equals: req.user.id } }
}
/**
* Any operation on a staff collection whose roles are NOT the plugin's: an account of that same
* collection (the project's own roles decide the rest), or a plugin admin of another staff
* collection. Never an account of a collection that is not staff.
*/
export const sameStaffCollectionAccess =
(slug: string): Access =>
({ req }) => {
if (!req.user || !secondFactorPassed(req)) {return false}
const from = collectionOf(req)
if (from === slug) {return staffCollectionSlugs(req.payload).includes(slug)}
return userMeetsRole(req, 'admin')
}
/** `read` on a staff collection: a fully signed-in account of a staff collection. Never a visitor account. */
export const staffReadAccess: Access = ({ req }) => {
const from = collectionOf(req)
return Boolean(req.user && from && staffCollectionSlugs(req.payload).includes(from) && secondFactorPassed(req))
}
type FieldAccessArgs = { id?: number | string; req: PayloadRequest }
/** `roles` where the roles are the plugin's: only an admin changes them — nobody raises itself. */
export const rolesByAdminOnly = ({ req }: FieldAccessArgs): boolean => userMeetsRole(req, 'admin')
/**
* `roles` where the role values are the project's own (the plugin cannot rank them): an account
* never changes its OWN roles. Another account of the collection, or a plugin admin, may.
*/
export const rolesNotOwn =
(slug: string) =>
({ id, req }: FieldAccessArgs): boolean =>
!(req.user && collectionOf(req) === slug && id !== undefined && String(req.user.id) === String(id))
type FieldLike = { access?: { update?: unknown }; fields?: FieldLike[]; name?: string; tabs?: { fields: FieldLike[]; name?: string }[] }
/** The `roles` field of a collection: at the top level of the data (also inside a row, a collapsible or an unnamed tab). */
function findRolesField(fields: FieldLike[] | undefined): FieldLike | undefined {
for (const field of fields ?? []) {
if (field.name === 'roles') {return field}
if (!field.name && field.fields) {
const found = findRolesField(field.fields)
if (found) {return found}
}
for (const tab of field.tabs ?? []) {
const found = tab.name ? undefined : findRolesField(tab.fields)
if (found) {return found}
}
}
return undefined
}
/** True when the collection carries the plugin's roles: a `roles` select at the top level of the data (also inside a row or an unnamed tab) whose values are all the plugin's. */
export function hasPluginRoles(collection: Staffish): boolean {
const field = findRolesField(collection.fields as FieldLike[]) as { options?: unknown[]; type?: string } | undefined
if (!field || field.type !== 'select' || !Array.isArray(field.options) || !field.options.length) {return false}
return field.options.every((option) => ROLE_HIERARCHY.includes((typeof option === 'string' ? option : (option as { value?: unknown })?.value) as never))
}
/** What the plugin put on a staff collection (`custom.ipalAccountRules`) — for the doctor and for late collections. */
export type StaffAccountRules = { applied: string[]; ownRoles: boolean }
/**
* BOTH rules must allow: the plugin's and the one the collection already has. For a collection
* that arrives after ipalKit ran (a later plugin), whose config is already sanitized: Payload has
* filled every missing rule with its default by then, and that default cannot be told from a
* rule somebody wrote — not by its name (a production build minifies it away) and not safely by
* identity. So nothing is guessed: the plugin's rule is put in FRONT of whatever is there. With
* Payload's default behind it the result is the plugin's rule; with a rule of the collection's
* own the result is the narrower of the two. Never wider than the plugin's rule: fail closed.
*/
export function bothAllow(first: Access, second: unknown): Access {
if (typeof second !== 'function') {return first}
return async (args) => {
const a = await first(args)
if (!a) {return false}
const b = await (second as Access)(args)
if (!b) {return false}
if (a === true) {return b}
if (b === true) {return a}
return { and: [a, b] }
}
}
export type StaffAccountAccessOptions = {
/** `create` (accounts.adminOnlyCreate). */
create?: boolean
/** Slugs that will carry the plugin's roles although the field is not there yet (`access.authCollection`). */
pluginRoles?: string[]
/** `read` (accounts.staffOnlyRead). */
read?: boolean
/** `update`, `delete`, `unlock`, and the `roles` field (accounts.adminOnlyWrite). */
write?: boolean
}
/**
* Puts the defaults on ONE staff collection, in place: the operations without a rule, and the
* `roles` field when the plugin's `update` rule is the one in force. Returns what it applied.
* `late`: the collection's config is already sanitized (see `bothAllow`) — the plugin's rule is
* combined with whatever is there instead of only filling gaps.
*/
function ruleStaffCollection(collection: CollectionConfig, { create = true, pluginRoles = [], read = true, write = true }: StaffAccountAccessOptions, late = false): StaffAccountRules {
const slug = collection.slug
const ours = pluginRoles.includes(slug) || hasPluginRoles(collection)
const other = sameStaffCollectionAccess(slug)
const access = (collection.access ?? {}) as Record<string, unknown>
const applied: string[] = []
const put = (operation: string, rule: Access) => {
if (late) {access[operation] = bothAllow(rule, access[operation])}
else if (!access[operation]) {access[operation] = rule}
else {return} // a rule the project wrote
applied.push(operation)
}
if (create) {put('create', ours ? staffCreateAccess : other)}
if (write) {
put('update', ours ? staffUpdateAccess(slug) : other)
put('delete', ours ? staffCreateAccess : other)
put('unlock', ours ? staffCreateAccess : other)
}
if (read) {
put('read', staffReadAccess)
// versions of an account hold what the account holds (e-mail addresses, roles)
put('readVersions', staffReadAccess)
}
collection.access = access as CollectionConfig['access']
// The plugin's `update` rule lets an account change itself (or, with roles of its own, every account of
// the collection change every other): a `roles` field without access of its own would let it raise itself.
const roles = findRolesField(collection.fields as FieldLike[])
if (applied.includes('update')) {
if (roles && !roles.access?.update) {
roles.access = { ...roles.access, update: ours ? rolesByAdminOnly : rolesNotOwn(slug) }
applied.push('roles')
}
}
// "roles of its own": a roles field whose values are not the plugin's (a collection without the field has no roles to rank)
const rules: StaffAccountRules = { applied, ownRoles: !ours && Boolean(roles) }
collection.custom = { ...collection.custom, ipalAccountRules: rules }
return rules
}
/** A copy of the field tree down to the `roles` field, so the project's own objects are not changed. */
const copyToRoles = (fields: FieldLike[] | undefined): FieldLike[] | undefined =>
fields?.map((field) => {
if (field.name === 'roles') {return { ...field }}
if (!field.name && field.fields) {return { ...field, fields: copyToRoles(field.fields) }}
if (field.tabs) {return { ...field, tabs: field.tabs.map((tab) => (tab.name ? tab : { ...tab, fields: copyToRoles(tab.fields)! })) }}
return field
})
/**
* Puts the defaults on the named staff collections where the project wrote no rule: `create`,
* `update`, `delete`, `unlock`, `read`, and `roles` cannot be raised by its own account.
*/
export function applyStaffAccountAccess(config: Config, staffSlugs: string[], options: StaffAccountAccessOptions = {}): Config {
const { create = true, read = true, write = true } = options
if (!create && !write && !read) {return config}
return {
...config,
collections: (config.collections ?? []).map((collection) => {
if (!collection.auth || !staffSlugs.includes(collection.slug)) {return collection}
const copy = { ...collection, access: { ...collection.access }, fields: copyToRoles(collection.fields as FieldLike[]) as CollectionConfig['fields'] }
ruleStaffCollection(copy, options)
return copy
}),
}
}
/** What was put on one late auth collection: for the log, which says only what was really done. */
export type LateAdoption = { applied: string[]; firstUser: boolean; password: boolean; slug: string }
/**
* Collections that were not in the config when ipalKit ran — a plugin listed after it added them.
* Called when a config goes live (start, dev reload) with THAT config: a late STAFF collection
* gets the account rules (in front of whatever rules it has — `bothAllow`), the roles-field rule
* and the password hook; every late auth collection gets the first-user endpoint. Changes the
* config in place; returns what it put where. A late collection that wants its own rules exactly
* as they are says so: `custom: { ipal: { accountRules: false } }`.
*/
export function adoptLateAuthCollections(
config: { collections?: CollectionConfig[] },
staffSlugs: string[],
{ access, beforeOperation, firstUserRoute = 'panel' }: { access?: false | StaffAccountAccessOptions; beforeOperation?: unknown; firstUserRoute?: FirstUserRouteOption } = {},
): LateAdoption[] {
const adopted: LateAdoption[] = []
for (const collection of config.collections ?? []) {
const custom = collection.custom as { ipal?: { accountRules?: unknown }; ipalAccounts?: boolean } | undefined
if (!collection.auth || custom?.ipalAccounts) {continue}
collection.custom = { ...collection.custom, ipalAccounts: true }
const done: LateAdoption = { slug: collection.slug, applied: [], firstUser: false, password: false }
if (staffSlugs.includes(collection.slug)) {
if (access !== false && custom?.ipal?.accountRules !== false) {done.applied = ruleStaffCollection(collection, access ?? {}, true).applied}
if (beforeOperation) {
const hooks = (collection.hooks ?? {}) as { beforeOperation?: unknown[] }
hooks.beforeOperation = [...(hooks.beforeOperation ?? []), beforeOperation]
collection.hooks = hooks as CollectionConfig['hooks']
done.password = true
}
}
if (firstUserRoute !== 'all' && Array.isArray(collection.endpoints) && !collection.endpoints.some((e) => (e.custom as { ipalFirstUser?: boolean } | undefined)?.ipalFirstUser)) {
collection.endpoints.unshift(buildFirstUserEndpoint(firstUserRoute))
done.firstUser = true
}
if (done.applied.length || done.firstUser || done.password) {adopted.push(done)}
}
return adopted
}
/** Marks the auth collections ipalKit has seen at config time, so `adoptLateAuthCollections` leaves them alone. */
export function markSeenAuthCollections(config: Config): Config {
return { ...config, collections: (config.collections ?? []).map((c) => (c.auth ? { ...c, custom: { ...c.custom, ipalAccounts: true } } : c)) }
}
/** Slugs named as staff that are not auth collections of the live config. */
export function unknownStaffCollections(config: { collections?: CollectionConfig[] }, staffSlugs: string[]): string[] {
return staffSlugs.filter((slug) => !(config.collections ?? []).some((c) => c.slug === slug && c.auth))
}
/** `accounts.firstUserRoute`: `'panel'` (default) = the panel's login collection only; slugs = those; `'all'` = Payload's behaviour. */
export type FirstUserRouteOption = 'all' | 'panel' | string[]
const FIRST_REGISTER = '/first-register'
/**
* The plugin's own `POST /first-register` for a collection. It is put in front of Payload's
* (a collection's own endpoints are matched before the built-in ones, with the same matcher —
* so whatever spelling reaches Payload's route reaches this one first): refuses unless the
* collection is allowed, then hands the request to Payload's handler. Nothing is decided
* from the request's path.
*/
export function buildFirstUserEndpoint(option: FirstUserRouteOption = 'panel'): Endpoint {
const endpoint: Endpoint = {
custom: { ipalFirstUser: true },
handler: async (req) => {
const slug = (req.routeParams as { collection?: string } | undefined)?.collection
const collection = slug ? req.payload.collections[slug as never] : undefined
const refused = () => Response.json({ errors: [{ message: req.t('error:notAllowedToPerformAction' as never) }] }, { status: 403 })
if (!slug || !collection) {return refused()}
let allowed = Array.isArray(option) ? option.includes(slug) : slug === req.payload.config.admin?.user
if (!allowed) {
// a collection that lets a visitor sign up anyway may keep its first-user route
try {
allowed = Boolean(await collection.config.access?.create?.({ data: req.data, req: { ...req, user: null } } as never))
} catch {
allowed = false
}
}
if (!allowed) {return refused()}
// Payload's own handler: the built-in endpoint of this collection with the same path and method.
const builtIn = (collection.config.endpoints || []).find((e) => e !== endpoint && e.method === 'post' && e.path === FIRST_REGISTER && !(e.custom as { ipalFirstUser?: boolean } | undefined)?.ipalFirstUser)
if (!builtIn) {return refused()}
// for hooks that need to know (the roles field makes the first account an admin)
req.context = { ...req.context, ipalFirstRegister: true }
return builtIn.handler(req)
},
method: 'post',
path: FIRST_REGISTER,
}
return endpoint
}
/** Puts the first-user endpoint in front of Payload's on every auth collection. `'all'` adds nothing. */
export function applyFirstUserRoute(config: Config, option: FirstUserRouteOption = 'panel'): Config {
if (option === 'all') {return config}
if (option !== 'panel' && !Array.isArray(option)) {
throw new Error(`[ipal] accounts.firstUserRoute must be 'panel', 'all' or a list of collection slugs, got ${JSON.stringify(option)}.`)
}
return {
...config,
collections: (config.collections ?? []).map((collection) => {
if (!collection.auth || collection.endpoints === false) {return collection}
const own = (collection.endpoints ?? []).filter((e) => !(e.custom as { ipalFirstUser?: boolean } | undefined)?.ipalFirstUser)
return { ...collection, endpoints: [buildFirstUserEndpoint(option), ...own] }
}),
}
}
type LivePayload = { collections: Record<string, { config: { access?: { create?: Access; delete?: Access; read?: Access; readVersions?: Access; unlock?: Access; update?: Access }; auth?: unknown; slug: string } }>; config?: unknown }
/**
* Auth collections whose `create` rule lets an anonymous request through — open sign-up.
* For the doctor (slugs only). A rule that throws, or needs more than `{ req }`, counts as closed.
*/
export async function openSignUpCollections(payload: LivePayload): Promise<string[]> {
const open: string[] = []
for (const { config } of Object.values(payload.collections ?? {})) {
if (!config.auth) {continue}
try {
if (await config.access?.create?.({ req: { payload, user: null } } as never)) {open.push(config.slug)}
} catch {
/* closed */
}
}
return open.sort()
}
/**
* Staff collections that an account of ANOTHER, non-staff auth collection may create in, read,
* update, delete from or unlock — `'users:update'`. For the doctor. Asked with a made-up account of
* a collection that is not staff; a rule that throws counts as closed.
*/
export async function staffCollectionsOpenToOthers(payload: LivePayload): Promise<string[]> {
const staff = staffCollectionSlugs(payload as never)
const outsider = { id: '__ipal-outsider__', collection: '__ipal-outsider__' }
const open: string[] = []
for (const { config } of Object.values(payload.collections ?? {})) {
if (!config.auth || !staff.includes(config.slug)) {continue}
for (const operation of ['create', 'read', 'readVersions', 'update', 'delete', 'unlock'] as const) {
try {
const rule = config.access?.[operation]
// no rule = Payload's default: any logged-in user
if (!rule || (await rule({ id: '__ipal-other__', req: { payload, user: outsider } } as never))) {open.push(`${config.slug}:${operation}`)}
} catch {
/* closed */
}
}
}
return open.sort()
}
/**
* Staff collections with role values of their OWN that run on the plugin's defaults: inside such a
* collection every account may create, change and delete accounts — the plugin cannot rank the
* project's roles. For the doctor: the project should write its own rules. Slugs only.
*/
export function staffCollectionsOnOwnRoles(payload: LivePayload): string[] {
return Object.values(payload.collections ?? {})
.map(({ config }) => ({ slug: config.slug, rules: (config as { custom?: { ipalAccountRules?: StaffAccountRules } }).custom?.ipalAccountRules }))
.filter(({ rules }) => rules?.ownRoles && rules.applied.some((operation) => operation === 'create' || operation === 'update' || operation === 'delete'))
.map(({ slug }) => slug)
.sort()
}
+68
View File
@@ -1,5 +1,7 @@
import type { CollectionConfig } from 'payload'
import type { PasswordRuleOptions } from './passwordRule.js'
/**
* Role hierarchy, lowest to highest privilege.
* A higher role satisfies any requirement met by a lower one.
@@ -8,6 +10,72 @@ export const ROLE_HIERARCHY = ['user', 'editor', 'admin'] as const
export type Role = (typeof ROLE_HIERARCHY)[number]
/**
* `ipalKit({ accounts })` — rules for the accounts of the staff collection. On by default
* where they apply; each one has its own switch, `accounts: false` turns them all off.
*/
export type AccountsOptions = {
/**
* Only an admin creates accounts in a staff collection (the one the panel
* logs in with, `access.authCollection`, `access.staffCollections`) — also
* in the project's own collection, where Payload's default would let any
* logged-in account do it. Where the collection's roles are not the
* plugin's (role values of its own, or no `roles` field) the plugin cannot
* tell who is an admin there: an account of that same collection, or a
* plugin admin of another staff collection. A `create` rule the project
* wrote stays. `false` = Payload's default on collections without a rule.
*/
adminOnlyCreate?: false
/**
* The same for `update` and `delete` on a staff collection without those
* rules: an admin, or — `update` only — the account itself. Payload's
* default ("any logged-in user") let an account of ANOTHER auth collection
* (a `customers` visitor) change a staff account's password. On a staff
* collection whose roles are not the plugin's: an account of that same
* collection, or a plugin admin. A rule the project wrote stays.
* With it: `unlock` gets the admin rule, and the collection's `roles`
* field (when it has no `access.update` of its own) cannot be raised by
* its own account — with the plugin's roles only an admin changes roles;
* with role values of the project's own, never the account itself.
* `false` = Payload's default on collections without a rule, as before.
*/
adminOnlyWrite?: false
/**
* Which auth collections Payload's first-user route
* (`POST /api/<slug>/first-register`) answers for while they are empty.
* Default `'panel'`: only the collection the panel logs in with — the
* first account of a site, which becomes admin. A list of slugs = those.
* `'all'` = Payload's behaviour (every empty auth collection). A collection
* whose own `create` rule allows an anonymous request keeps its route.
*/
firstUserRoute?: 'all' | 'panel' | string[]
/**
* The lowest role that may open the admin panel. Default `'editor'`: an
* account that holds only `user` (the default role of a new account) sees
* Payload's "Unauthorized" screen instead of the panel; over the API it
* still gets what its role allows. `'user'` or `false` = every account of
* the collection may open the panel, as before. `'admin'` = admins only.
* Needs `access` (the roles). The project's own `access.admin` on the
* collection (or `access.authAccess.admin`) wins. docs/access.md.
*/
panelRole?: false | Role
/**
* Rule for a password of a staff account when one is SET (a new account,
* the first-user screen, a change, a reset by e-mail): at least
* `minLength` characters (default 12) and not the account's own e-mail
* address. Existing passwords are never checked — a shorter one keeps
* logging in. `false` = Payload's own rule (3 characters).
*/
password?: false | PasswordRuleOptions
/**
* `read` on a staff collection without a `read` rule: a fully signed-in
* account of a staff collection. Payload's default let any logged-in
* account — a `customers` visitor — list the staff accounts. A rule the
* project wrote stays. `false` = Payload's default, as before.
*/
staffOnlyRead?: false
}
/**
* Access-control options.
*
@@ -4,13 +4,20 @@ import { defineTexts } from '../define.js'
export const integrationsTexts = defineTexts({
en: {
// Dashboard alert (IntegrationAlerts)
alertsAskAdmin: 'Ask an administrator to look at it.',
alertsHeading: 'An integration needs attention. The site still works.',
alertsLink: 'Go to Site integrations',
alertsUnknownError: 'Unknown error.',
// Masked secret field
maskedHide: 'Hide',
maskedKeep: 'Keep the stored value',
maskedRemove: 'Remove the stored value',
maskedRemoved: 'The stored value will be removed when you save.',
maskedSet: 'A value is set. It is not shown; type a new one to replace it.',
maskedShow: 'Show',
secretNotText: 'Enter the value as text.',
secretReenter: 'Enter the password again: the server, port or user name changed. To use the server without a password, remove the stored value.',
// Status banner on an integration's tab (IntegrationStatusBanner)
statusCode: 'Code: {{code}}.',
@@ -58,12 +65,19 @@ export const integrationsTexts = defineTexts({
testEmailWithFile: 'Attach a 10 MB test file',
},
pl: {
alertsAskAdmin: 'Poproś administratora, aby to sprawdził.',
alertsHeading: 'Integracja wymaga uwagi. Witryna nadal działa.',
alertsLink: 'Przejdź do integracji',
alertsUnknownError: 'Nieznany błąd.',
maskedHide: 'Ukryj',
maskedKeep: 'Zostaw zapisaną wartość',
maskedRemove: 'Usuń zapisaną wartość',
maskedRemoved: 'Zapisana wartość zostanie usunięta po zapisaniu.',
maskedSet: 'Wartość jest ustawiona. Nie jest wyświetlana; wpisz nową, aby ją zastąpić.',
maskedShow: 'Pokaż',
secretNotText: 'Wpisz wartość jako tekst.',
secretReenter: 'Wpisz hasło ponownie: zmienił się serwer, port lub nazwa użytkownika. Aby używać serwera bez hasła, usuń zapisaną wartość.',
statusCode: 'Kod: {{code}}.',
statusEmailFailing: 'Wysyłka e-mail nie działa. Powiadomienia z formularzy mogą nie docierać.',
+42
View File
@@ -3,9 +3,51 @@ import { defineTexts } from '../define.js'
/** Admin component texts — two-step verification (2FA). Placeholders use Payload's {{name}} syntax. */
export const securityTexts = defineTexts({
en: {
passwordIsEmail: 'The password cannot be the same as the e-mail address.',
passwordTooShort: 'The password must have at least {{min}} characters.',
twoFactorAlertBlocked: 'Blocked because the time for setup has passed: {{count}}. Open the account in the user list and choose "Reopen setup".',
twoFactorAlertLink: 'Open the user list',
twoFactorAlertPending: 'Accounts without two-step verification: {{count}}. Until it is set up, such an account cannot use the panel.',
twoFactorAlertTitle: 'Two-step verification',
twoFactorReopen: 'Reopen setup',
twoFactorReset: 'Reset two-step verification',
twoFactorResetConfirm: 'This account will have to set up two-step verification again before it can use the panel. Continue?',
twoFactorResetDone: 'Done. The account can set up two-step verification now.',
twoFactorResetFailed: 'Could not reset two-step verification. Try again.',
twoFactorResetForbidden: 'Only an administrator who is fully logged in can do this.',
twoFactorSetupClosed: 'The time to set up two-step verification has passed, so this account is blocked. Ask an administrator to reopen setup for it.',
twoFactorSetupDeadline: 'Set up two-step verification by {{date}}. Until then you cannot use the panel.',
twoFactorSetupRequired: 'Set up two-step verification to use the panel.',
twoFactorStatusClosed: 'Not set up. The time for it passed on {{date}}, so the account is blocked.',
twoFactorStatusExempt: 'Not set up. This account is exempt in the site configuration.',
twoFactorStatusLabel: 'Two-step verification',
twoFactorStatusOn: 'Set up.',
twoFactorStatusOpen: 'Not set up. The account can set it up until {{date}}.',
twoFactorStatusOpenNoLimit: 'Not set up yet. The account cannot use the panel until it is.',
twoFactorTooManyAttempts: 'Too many codes were tried for this account. Wait {{minutes}} min, then enter the current code from your app.',
},
pl: {
passwordIsEmail: 'Hasło nie może być takie samo jak adres e-mail.',
passwordTooShort: 'Hasło musi mieć co najmniej {{min}} znaków.',
twoFactorAlertBlocked: 'Zablokowane, bo minął czas na konfigurację: {{count}}. Otwórz konto na liście użytkowników i wybierz „Otwórz konfigurację ponownie”.',
twoFactorAlertLink: 'Otwórz listę użytkowników',
twoFactorAlertPending: 'Konta bez weryfikacji dwuetapowej: {{count}}. Dopóki nie zostanie ustawiona, takie konto nie może korzystać z panelu.',
twoFactorAlertTitle: 'Weryfikacja dwuetapowa',
twoFactorReopen: 'Otwórz konfigurację ponownie',
twoFactorReset: 'Zresetuj weryfikację dwuetapową',
twoFactorResetConfirm: 'To konto będzie musiało ponownie ustawić weryfikację dwuetapową, zanim skorzysta z panelu. Kontynuować?',
twoFactorResetDone: 'Gotowe. Konto może teraz ustawić weryfikację dwuetapową.',
twoFactorResetFailed: 'Nie udało się zresetować weryfikacji dwuetapowej. Spróbuj ponownie.',
twoFactorResetForbidden: 'Może to zrobić tylko w pełni zalogowany administrator.',
twoFactorSetupClosed: 'Czas na ustawienie weryfikacji dwuetapowej minął, więc to konto jest zablokowane. Poproś administratora o ponowne otwarcie konfiguracji.',
twoFactorSetupDeadline: 'Ustaw weryfikację dwuetapową do {{date}}. Do tego czasu nie możesz korzystać z panelu.',
twoFactorSetupRequired: 'Ustaw weryfikację dwuetapową, aby korzystać z panelu.',
twoFactorStatusClosed: 'Nieustawiona. Czas na konfigurację minął {{date}}, więc konto jest zablokowane.',
twoFactorStatusExempt: 'Nieustawiona. To konto jest zwolnione w konfiguracji strony.',
twoFactorStatusLabel: 'Weryfikacja dwuetapowa',
twoFactorStatusOn: 'Ustawiona.',
twoFactorStatusOpen: 'Nieustawiona. Konto może ją ustawić do {{date}}.',
twoFactorStatusOpenNoLimit: 'Jeszcze nieustawiona. Do tego czasu konto nie może korzystać z panelu.',
twoFactorTooManyAttempts: 'Dla tego konta wpisano zbyt wiele kodów. Odczekaj {{minutes}} min, a potem wpisz aktualny kod z aplikacji.',
},
})
+13
View File
@@ -2,6 +2,8 @@ import type { Payload } from 'payload'
import { ipalT } from '../admin-i18n/t.js'
import { settingsTexts } from '../admin-i18n/texts/settings.js'
import { secondFactorPassed } from '../security/totp/secondFactor.js'
import { publicImageDataUri, siteOrigin } from './publicImage.js'
/**
* White-label admin branding: the Payload admin panel's logo (login + nav) and
@@ -25,6 +27,8 @@ import { settingsTexts } from '../admin-i18n/texts/settings.js'
type BrandingProps = {
/** Upload field to render as the image. Default 'logo' (Logo) / 'favicon' (Icon). */
imageField?: string
/** `whiteLabel.inlineImages: false` — never fetch the image on the server for the 2FA screens. */
inlineImages?: false
/** Injected by Payload — current admin locale (object or code). */
locale?: { code?: string } | string
/** Field holding the site name. Default 'siteName'. */
@@ -33,6 +37,8 @@ type BrandingProps = {
payload?: Payload
/** SiteSettings global slug. Default 'site-settings'. */
settingsSlug?: string
/** Injected by Payload into admin server components — the account looking at the panel. */
user?: null | Record<string, unknown>
}
type MediaLike = { url?: null | string } | null | undefined
@@ -70,6 +76,13 @@ async function loadBranding(
const image = settings[imageField] as MediaLike
const url =
image && typeof image === 'object' && typeof image.url === 'string' ? image.url : null
// A session that still owes its 2FA code (or has not set 2FA up) is refused `media` like every
// other collection, so the browser would show a broken image on the verify / setup screens.
// Give it the picture itself, fetched as an anonymous visitor would get it; when that fails
// (media is not public), the site name is shown instead.
if (url && props.inlineImages !== false && props.user && !secondFactorPassed({ payload, user: props.user })) {
return { name, url: await publicImageDataUri(url, siteOrigin(payload.config.serverURL)) }
}
return { name, url }
} catch (error) {
console.warn('[ipal] admin branding: falling back to Payload default:', error)
+22 -3
View File
@@ -2,7 +2,9 @@ import type { Endpoint, PayloadRequest } from 'payload'
import type { AgencyOption, ResolvedAdminMeta } from './adminMeta.js'
import { UPLOAD_SECURITY_HEADERS } from '../security/buildSecurityHeaders.js'
import { ADMIN_ICON_PATH, ADMIN_META_TEXTS, ADMIN_OG_PATH } from './adminMeta.js'
import { fetchPublicImage, rasterImageType } from './publicImage.js'
/**
* The panel's link-preview image (1200×630) and icon, drawn from SiteSettings:
@@ -13,13 +15,13 @@ import { ADMIN_ICON_PATH, ADMIN_META_TEXTS, ADMIN_OG_PATH } from './adminMeta.js
* the site name, then to initials.
*/
type Fields = { iconField?: string; logoField?: string; nameField?: string; settingsSlug?: string }
type Fields = { iconField?: string; logoField?: string; nameField?: string; serveIcon?: false; settingsSlug?: string }
type Branding = { icon: null | string; logo: null | string; name: string }
const CACHE = 'public, max-age=3600, s-maxage=3600'
async function loadBranding(req: PayloadRequest, f: Required<Fields>): Promise<Branding> {
async function loadBranding(req: PayloadRequest, f: Required<Omit<Fields, 'serveIcon'>>): Promise<Branding> {
try {
const locale = req.payload.config.localization ? req.payload.config.localization.defaultLocale : undefined
const s = (await req.payload.findGlobal({ slug: f.settingsSlug as never, depth: 1, ...(locale ? { locale: locale as never } : {}), req })) as Record<string, unknown>
@@ -62,7 +64,7 @@ const initials = (name: string) =>
.join('') || 'A'
export function buildAdminImageEndpoints(resolved: ResolvedAdminMeta, fields: Fields = {}): Endpoint[] {
const f: Required<Fields> = {
const f: Required<Omit<Fields, 'serveIcon'>> = {
iconField: fields.iconField ?? 'favicon',
logoField: fields.logoField ?? 'logo',
nameField: fields.nameField ?? 'siteName',
@@ -105,6 +107,23 @@ export function buildAdminImageEndpoints(resolved: ResolvedAdminMeta, fields: Fi
handler: async (req) => {
const brand = await loadBranding(req, f)
if (brand.icon) {
// The picture itself, fetched the way an anonymous visitor gets it — not a redirect to the
// media file: a panel session that still owes its 2FA code is refused that file (it is
// refused every collection), and a cached redirect would send it there anyway. The answer
// is the same for everyone, so it can be cached like the redirect was.
const image = fields.serveIcon === false ? null : await fetchPublicImage(absolute(brand.icon, req), null)
// Only a bitmap is answered from here, recognised by its first bytes — never an SVG, which
// is a document that can run script in the site's origin. The headers below are the upload
// routes' (sandbox, no sniffing), but a Next project's site-wide CSP rule overrides a
// route's own header, so they are a second layer, not the protection.
const type = image ? rasterImageType(image.bytes) : null
if (image && type) {
return new Response(new Uint8Array(image.bytes), {
headers: { 'Cache-Control': CACHE, 'Content-Type': type, ...Object.fromEntries(UPLOAD_SECURITY_HEADERS.map((h) => [h.key, h.value])) },
})
}
// An SVG favicon, or not fetchable from here (too large, media is not public): the browser
// goes to the media file itself, where the upload route's own headers apply.
return new Response(null, { headers: { 'Cache-Control': CACHE, Location: absolute(brand.icon, req) }, status: 302 })
}
const ImageResponse = await imageResponse()
+6
View File
@@ -37,6 +37,12 @@ export type AdminMetaOptions = {
language?: 'en' | 'pl'
/** Robots meta. Default noindex, nofollow. `false` = none. */
robots?: { follow?: boolean; index?: boolean } | false
/**
* `/api/ipal/admin-icon` answers with the favicon's bytes (fetched as an anonymous visitor gets
* them, with the upload security headers), so it also loads for a session that still owes its
* 2FA code. `false` = a redirect to the media file instead, as before.
*/
serveIcon?: false
/** Browser-tab suffix; `{site}` is replaced. Default "— {site} | Panel". `false` = none. */
titleSuffix?: false | string
}
+84
View File
@@ -0,0 +1,84 @@
/**
* An image of the site's brand fetched the way an anonymous visitor would get
* it: no cookies, no credentials. For the moments when the browser itself
* cannot load it — a panel session that still owes its 2FA code (or has not
* set 2FA up) is refused every collection, `media` included, although the
* same file is public. Serving the bytes from here opens nothing: only what
* answers an anonymous request comes back, and only an image of a sane size.
*/
export const PUBLIC_IMAGE_MAX_BYTES = 512 * 1024
const MAX_BYTES = PUBLIC_IMAGE_MAX_BYTES
export async function fetchPublicImage(url: null | string | undefined, base: null | string | undefined): Promise<{ bytes: Buffer; type: string } | null> {
if (!url) {return null}
let target: URL
try {
target = new URL(url, base || undefined)
} catch {
return null // a relative address and no site origin to resolve it against
}
if (target.protocol !== 'http:' && target.protocol !== 'https:') {return null}
try {
const res = await fetch(target, { credentials: 'omit', redirect: 'follow', signal: AbortSignal.timeout(5000) })
if (!res.ok) {return null}
const type = (res.headers.get('content-type') ?? '').split(';')[0].trim()
if (!type.startsWith('image/')) {return null}
// Too large is known before reading when the server says so; otherwise stop reading at the limit.
const declared = Number(res.headers.get('content-length'))
if (Number.isFinite(declared) && declared > MAX_BYTES) {
await res.body?.cancel().catch(() => undefined)
return null
}
const bytes = await readUpTo(res, MAX_BYTES)
if (!bytes?.length) {return null}
return { type, bytes }
} catch {
return null
}
}
/**
* The media type of a bitmap image, read from the first bytes — never from what a server or a
* file name claims: PNG, JPEG, GIF, WebP, ICO, AVIF. Null for anything else, **SVG included**:
* an SVG is a document that can carry script, and bytes answered from the site's own origin
* must never be one (the site-wide CSP of a Next project overrides a route's own sandbox header).
*/
export function rasterImageType(bytes: Uint8Array): null | string {
const b = bytes
const ascii = (from: number, text: string) => text.split('').every((ch, i) => b[from + i] === ch.charCodeAt(0))
if (b.length >= 8 && b[0] === 0x89 && ascii(1, 'PNG') && b[4] === 0x0d && b[5] === 0x0a && b[6] === 0x1a && b[7] === 0x0a) {return 'image/png'}
if (b.length >= 3 && b[0] === 0xff && b[1] === 0xd8 && b[2] === 0xff) {return 'image/jpeg'}
if (b.length >= 6 && (ascii(0, 'GIF87a') || ascii(0, 'GIF89a'))) {return 'image/gif'}
if (b.length >= 12 && ascii(0, 'RIFF') && ascii(8, 'WEBP')) {return 'image/webp'}
if (b.length >= 4 && b[0] === 0 && b[1] === 0 && b[2] === 1 && b[3] === 0) {return 'image/x-icon'}
if (b.length >= 12 && ascii(4, 'ftyp') && (ascii(8, 'avif') || ascii(8, 'avis'))) {return 'image/avif'}
return null
}
/** The body, or null as soon as it grows past `limit` (the rest is not downloaded). */
async function readUpTo(res: Response, limit: number): Promise<Buffer | null> {
const reader = res.body?.getReader()
if (!reader) {return null}
const chunks: Uint8Array[] = []
let size = 0
for (;;) {
const { done, value } = await reader.read()
if (done) {break}
size += value.byteLength
if (size > limit) {
await reader.cancel().catch(() => undefined)
return null
}
chunks.push(value)
}
return Buffer.concat(chunks)
}
/** The same as a `data:` address for an `<img>`. */
export async function publicImageDataUri(url: null | string | undefined, base: null | string | undefined): Promise<null | string> {
const image = await fetchPublicImage(url, base)
return image ? `data:${image.type};base64,${image.bytes.toString('base64')}` : null
}
/** The site's own origin as the config or the environment states it, for resolving `/api/media/file/…`. */
export const siteOrigin = (serverURL: null | string | undefined): null | string => serverURL || process.env.NEXT_PUBLIC_SERVER_URL || null
@@ -2,6 +2,7 @@ import type { Payload } from 'payload'
import type { CookieScanLabels } from '../labels.js'
import { userMeetsRole } from '../../../access/predicates.js'
import { COOKIE_APPROVAL_VIEW_PATH, countPendingCookies } from '../approval.js'
import { COOKIE_REVIEW_SLUG } from '../collection.js'
import { COOKIE_SCAN_LABELS, labelFor } from '../labels.js'
@@ -11,12 +12,19 @@ type Props = {
adminRoute?: string
/** Cookie approval is on: remind while cookies wait, link to the approval view. Default true. */
approval?: boolean
/**
* Who sees the alert: `'editor'` (default — the role that may read the crawl result and the
* cookie review) or `'all'` (everyone who opens the dashboard, as before).
*/
audience?: 'all' | 'editor'
/** The browser crawl is on: report violations and failed crawls. Default true. */
crawl?: boolean
/** Injected by Payload into admin server components. */
i18n?: { language?: string }
labels?: Record<string, CookieScanLabels>
payload?: Payload
/** Injected by Payload into admin server components — the account looking at the dashboard. */
user?: null | Record<string, unknown>
}
type CrawlDoc = { error?: null | string; status?: null | string; summary?: { newUnknown?: null | number; violations?: null | number } | null }
@@ -29,8 +37,11 @@ const fill = (template: string, values: Record<string, number | string>) =>
* link to the approval view), and — with the crawl — violations or a failed
* crawl. Renders nothing when nothing needs attention, and never throws.
*/
export async function CookieCrawlAlert({ adminRoute = '/admin', approval = true, crawl = true, i18n, labels = COOKIE_SCAN_LABELS, payload }: Props) {
export async function CookieCrawlAlert({ adminRoute = '/admin', approval = true, audience = 'editor', crawl = true, i18n, labels = COOKIE_SCAN_LABELS, payload, user }: Props) {
if (!payload) {return null}
// The crawl result and the review list are for editors and above; the widget reads them with
// access control off, so it asks the same question itself (the second factor included).
if (audience !== 'all' && !(user && userMeetsRole({ payload, user }, 'editor'))) {return null}
let doc: CrawlDoc = {}
if (crawl) {
try {
+7
View File
@@ -198,6 +198,13 @@ export const layoutRules: DoctorRule[] = [
if (/payloadTotp/.test(cfg)) {
need.push('@clocklimited/payload-2fa/rsc#TOTPSetup')
if (!lt(v, '1.14.2')) {need.push('@intecion/ipal-kit/admin#TotpRedirectProvider')}
// "2FA setup required": the status / reset control on the account and the dashboard notice — when the
// installed plugin has them and the config does not switch them (or the mode) off. Without them the
// panel shows no "Reopen setup": the documented way out of a blocked account is missing.
const adminExports = ctx.read('node_modules/@intecion/ipal-kit/dist/exports/admin.js')
const modeOff = /requireSetup\s*:\s*false|guard\s*:\s*false/.test(cfg)
if (/\bTwoFactorStatusField\b/.test(adminExports) && !modeOff && !/statusField\s*:\s*false/.test(cfg)) {need.push('@intecion/ipal-kit/admin#TwoFactorStatusField')}
if (/\bTwoFactorAlert\b/.test(adminExports) && !modeOff && !/dashboardNotice\s*:\s*false/.test(cfg)) {need.push('@intecion/ipal-kit/admin#TwoFactorAlert')}
// the back-link check in front of the 2FA screens (twoFactor.safeBack) — when the installed plugin has it
if (/\bSafeTotpView\b/.test(ctx.read('node_modules/@intecion/ipal-kit/dist/exports/admin.js')) && !/safeBack\s*:\s*false/.test(cfg)) {
need.push('@intecion/ipal-kit/admin#SafeTotpView')
+144 -1
View File
@@ -106,13 +106,156 @@ export const securityRules: DoctorRule[] = [
if (/\?\s*false\b|:\s*false\b|&&/.test(twoFactor) && /payloadTotp/.test(twoFactor)) {out.push({ file: configFile(ctx) ?? undefined, fix: 'twoFactor: { issuer, plugin: payloadTotp } without a switch', message: '2FA can be turned off at runtime (a condition on twoFactor)', severity: 'warning' })}
if (!/twoFactor\s*:[^\n]*payloadTotp|twoFactor\s*:\s*\{[\s\S]*?plugin\s*:\s*payloadTotp/.test(code)) {out.push({ file: configFile(ctx) ?? 'payload.config.ts', fix: "ipalKit({ twoFactor: { issuer: '<site>', plugin: payloadTotp } })", message: '2FA is not on (twoFactor with plugin: payloadTotp)', severity: 'error' })}
else if (!ctx.installed('@clocklimited/payload-2fa')) {out.push({ fix: 'pnpm add @clocklimited/payload-2fa', message: '@clocklimited/payload-2fa is not installed', severity: 'error' })}
if (ctx.deep?.usersWithout2fa) {out.push({ fix: 'each of them signs in and sets up TOTP (forceSetup)', message: `${ctx.deep.usersWithout2fa} panel user(s) without TOTP`, severity: 'error' })}
if (/requireSetup\s*:\s*false/.test(code)) {out.push({ file: configFile(ctx) ?? undefined, fix: 'remove twoFactor.requireSetup: false (or record the reason in ipal-doctor.json)', message: 'twoFactor.requireSetup is off: an account that has not set 2FA up opens everything with its password alone', severity: 'warning' })}
if (/windowHours\s*:\s*(?:false|0)\b/.test(code)) {out.push({ file: configFile(ctx) ?? undefined, fix: 'twoFactor.requireSetup.windowHours: 72 (the default)', message: 'no time limit for 2FA setup: an account that never sets it up can be taken over with its password at any time', severity: 'info' })}
// Postgres / SQLite: the 2FA collection has the column `totp_setup_from` (whenever 2FA is on). Without a
// migration that adds it, every query on the collection fails in production — nobody can log in.
const sqlAdapter = ['@payloadcms/db-postgres', '@payloadcms/db-vercel-postgres', '@payloadcms/db-sqlite', '@payloadcms/db-d1-sqlite'].some((name) => ctx.installed(name))
const pluginHasColumn = /totpSetupFrom/.test(ctx.read('node_modules/@intecion/ipal-kit/dist/modules/security/totp/secondFactor.js'))
if (sqlAdapter && pluginHasColumn && /payloadTotp/.test(code)) {
const dirs = [`${ctx.src}migrations`, 'migrations'].filter((dir) => ctx.exists(dir))
const files = dirs.flatMap((dir) => ctx.list(dir).filter((name) => /\.(?:ts|js|mjs|sql|json)$/.test(name)).map((name) => `${dir}/${name}`))
if (!files.some((file) => /totp_setup_from|totpSetupFrom/.test(ctx.read(file)))) {
out.push({
fix: 'pnpm payload migrate:create, commit the migration, and have it applied when the new container starts — prodMigrations in the adapter, or the start command `pnpm payload migrate && pnpm start`; not a pre-deployment command (docs/deployment.md §4.3) — in the same deploy, before the new version serves requests',
message: files.length
? 'no migration adds the 2FA column `totp_setup_from`: in production every login would answer 500 — nobody could sign in to the panel'
: 'a SQL database and no migrations folder: the 2FA column `totp_setup_from` must exist before this version runs in production (migrate:create; applied at container start — docs/deployment.md §4.3), or nobody can sign in',
severity: files.length ? 'error' : 'warning',
})
}
}
if (ctx.deep?.usersWithout2fa) {
const closed = ctx.deep.usersSetupClosed ?? 0
out.push({
fix: closed
? 'each of them signs in and sets up TOTP; for the blocked ones an admin opens the account in the panel → "Reopen setup" (or removes the account)'
: 'each of them signs in and sets up TOTP now; remove accounts nobody uses',
message: `${ctx.deep.usersWithout2fa} panel user(s) without TOTP${closed ? ` (${closed} blocked: the setup window has passed)` : ''}`,
severity: 'error',
})
}
return out
},
docs: 'docs/security.md#2fa-totp--enforced-for-every-user',
group: 'security',
source: 'static',
},
{
// Without `access` the plugin adds no roles: every account that can log in to the panel is an admin.
id: 'access-missing',
check: (ctx) => {
const code = cfg(ctx)
if (!/ipalKit\s*\(/.test(code)) {return []}
// `access: { authCollection | defaultRole | … }`, an empty `access: {}`, or a variable whose name says so
const set = /\baccess\s*:\s*\{\}/.test(code.replace(/\s+/g, '')) || /\baccess\s*:\s*\{[^{}]*\b(?:authCollection|defaultRole|authAccess|firstUserAdmin|staffCollections|panelRole|selfRegistration|password)\b/.test(code) || /\baccess\s*:\s*\w*[aA]ccess\w*\s*[,}]/.test(code)
return set
? []
: [{ file: configFile(ctx) ?? 'payload.config.ts', fix: "ipalKit({ access: { authCollection: 'users' } }) — roles admin > editor > user; or record the reason in ipal-doctor.json", message: 'ipalKit has no `access` option: there are no roles, so every account that can log in to the panel is an admin', severity: 'warning' }]
},
docs: 'docs/access.md',
group: 'security',
source: 'static',
},
{
// Payload accepts the login cookie from ANY origin while its `csrf` list is empty — and it is empty
// unless `csrf` or `serverURL` is set. A page on a sibling subdomain can then act with a panel user's cookie.
id: 'csrf-empty',
check: (ctx) => {
const code = cfg(ctx)
if (!/buildConfig\s*\(/.test(code) || /\bcsrf\s*:/.test(code) || /\bserverURL\s*:/.test(code)) {return []}
return [{ file: configFile(ctx) ?? 'payload.config.ts', fix: "serverURL: process.env.NEXT_PUBLIC_SERVER_URL (Payload then trusts that origin only), or csrf: ['https://<site>']", message: 'neither `serverURL` nor `csrf` is set: Payload accepts the login cookie from any origin (a risk when other applications share the domain)', severity: 'warning' }]
},
docs: 'docs/security.md',
group: 'security',
source: 'static',
},
{
// An auth collection anyone can register in. Often exactly what the project wants (customers) — said, not judged.
id: 'open-signup',
check: (ctx) =>
(ctx.deep?.openSignUp ?? []).map((slug) => ({
fix: `intended (a customer zone)? silence it with a reason in ipal-doctor.json; otherwise give "${slug}" a create rule`,
message: `sign-up is open on "${slug}": an anonymous request can create an account there`,
severity: 'info' as const,
})),
docs: 'docs/access.md',
group: 'security',
source: 'deep',
},
{
// A staff collection that an account of another auth collection (a customer, a member) may write to:
// it can create a staff account, or change a staff account's password. The plugin's default rules close
// it (accounts.adminOnlyCreate / adminOnlyWrite); this fires when they are off or a project's own rule is wider.
id: 'staff-accounts-open',
check: (ctx) =>
(ctx.deep?.staffOpenToOthers ?? []).map((entry) => {
const [slug, operation] = entry.split(':')
const what: Record<string, string> = {
create: ': it can make itself a staff account',
read: ': it can list the staff accounts (addresses, roles)',
readVersions: ': it can read the versions of staff accounts (addresses, roles)',
unlock: ': it can lift the lock after failed logins, which helps guessing a password',
update: ": it can change a staff account's password",
}
const reads = operation === 'read' || operation === 'readVersions'
const option = operation === 'create' ? 'adminOnlyCreate' : reads ? 'staffOnlyRead' : 'adminOnlyWrite'
return {
fix: `give "${slug}" an access.${operation} rule that asks for a staff account (staffCreateAccess, staffUpdateAccess('${slug}'), staffReadAccess, adminOrSelfIn('${slug}')), or drop accounts: false / accounts.${option}: false`,
message: `an account of another auth collection may ${operation} in the staff collection "${slug}"${what[operation] ?? ''}`,
severity: reads ? ('warning' as const) : ('error' as const),
}
}),
docs: 'docs/access.md',
group: 'security',
source: 'deep',
},
{
// A staff collection with role values of its own on the plugin's default rules: the plugin cannot rank
// those roles, so inside the collection every account may create an account with any role.
id: 'staff-own-roles',
check: (ctx) =>
(ctx.deep?.staffOnOwnRoles ?? []).map((slug) => ({
fix: `write "${slug}"'s own access.create / update / delete rules (and field access on its roles field) from its own roles`,
message: `the staff collection "${slug}" has role values of its own and no access rules: accounts of other collections are kept out, but inside it every account may create, change and delete accounts, with any role`,
severity: 'warning' as const,
})),
docs: 'docs/access.md',
group: 'security',
source: 'deep',
},
{
// Turnstile lets submissions through while it is misconfigured or Cloudflare fails ("degraded") — visible here.
id: 'turnstile-degraded',
check: (ctx) => {
const status = ctx.deep?.turnstile
if (!status || status.state !== 'degraded') {return []}
// "Now": the clock when the run is for today; for another date (a test, a replay) the middle of that day.
// Not the END of the day: a state that began at 23:59 would be "a day old" a minute later.
const now = ctx.today === new Date().toISOString().slice(0, 10) ? Date.now() : Date.parse(`${ctx.today}T12:00:00Z`)
const hours = status.since ? Math.floor((now - Date.parse(status.since)) / 3_600_000) : null
const long = hours !== null && hours >= 24
return [{
fix: 'Site integrations → Spam protection: both keys from the same Cloudflare widget; then send a test form',
message: `Turnstile is not checking forms (${status.code ?? 'unknown'})${status.since ? `, since ${status.since.slice(0, 16).replace('T', ' ')}` : ''}: text forms are accepted without the check and forms with files are refused (unless forms.turnstileOnConfigError says otherwise)`,
severity: long ? 'error' : 'warning',
}]
},
docs: 'docs/turnstile.md',
group: 'security',
source: 'deep',
},
{
// The secret key from the environment is deprecated: the panel is its source.
id: 'turnstile-env-key',
check: (ctx) =>
ctx.deep?.turnstileSecretFromEnv
? [{ fix: 'copy the key into Site integrations → Spam protection → Secret key, check a form, then remove TURNSTILE_SECRET_KEY from the environment (Coolify)', message: 'the Turnstile secret key comes from the TURNSTILE_SECRET_KEY environment variable (deprecated; it will be removed in a later release)', severity: 'warning' }]
: [],
docs: 'docs/turnstile.md',
group: 'security',
source: 'deep',
},
{
id: 'cookie-scanner',
check: (ctx) => {
+44 -2
View File
@@ -5,10 +5,13 @@ import { readFileSync } from 'node:fs'
import type { DoctorStatus } from './types.js'
import { openSignUpCollections, staffCollectionsOnOwnRoles, staffCollectionsOpenToOthers } from '../access/selfRegistration.js'
import { countPendingCookies } from '../consent/scanner/approval.js'
import { COOKIE_REVIEW_SLUG } from '../consent/scanner/collection.js'
import { secondFactorPassed } from '../security/totp/secondFactor.js'
import { secondFactorPassed, SETUP_FROM_FIELD } from '../security/totp/secondFactor.js'
import { countAccountsWithoutTotp } from '../security/totp/setupRequired.js'
import { clientIp, consumeRateLimit, tooManyRequests } from '../shared/rateLimit.js'
import { turnstileSecretFromEnv } from '../turnstile/config.js'
/** The plugin's own version (package.json next to dist/ and src/). */
export function pluginVersion(): string {
@@ -30,15 +33,54 @@ export async function collectDoctorStatus(payload: BasePayload): Promise<DoctorS
const authSlug = payload.config.admin?.user
const auth = collections.find((c) => c.slug === authSlug)
let usersWithout2fa: null | number = null
let usersSetupClosed: null | number = null
// payload-2fa stores `totpSecret` (`hasTotp` is virtual and cannot be queried); counted, never read.
if (auth?.fields?.some((f) => f.name === 'totpSecret')) {
const collection = auth.slug as never
const all = (await payload.count({ collection, overrideAccess: true })).totalDocs
const withTotp = (await payload.count({ collection, overrideAccess: true, where: { and: [{ totpSecret: { exists: true } }, { totpSecret: { not_equals: '' } }] } })).totalDocs
usersWithout2fa = Math.max(0, all - withTotp)
const windowMs = (payload.config.custom as { ipal?: { twoFactor?: { setupWindowMs?: number } } } | undefined)?.ipal?.twoFactor?.setupWindowMs
if (usersWithout2fa && windowMs && auth.fields.some((f) => f.name === SETUP_FROM_FIELD)) {
usersSetupClosed = (await countAccountsWithoutTotp(payload, auth.slug, windowMs)).blocked
}
}
const pendingCookies = collections.some((c) => c.slug === COOKIE_REVIEW_SLUG) ? await countPendingCookies(payload) : null
return { node: process.version, pendingCookies, plugin: pluginVersion(), usersWithout2fa }
// Turnstile: the recorded state and where the secret comes from — never the keys themselves.
let turnstile: DoctorStatus['turnstile'] = null
let secretFromEnv: boolean | null = null
if ((payload.config.globals ?? []).some((g) => g.slug === 'site-integrations')) {
try {
const integrations = (await payload.findGlobal({ slug: 'site-integrations' as never, depth: 0, overrideAccess: true })) as unknown as {
turnstileSecretKey?: null | string
turnstileStatus?: { code?: null | string; since?: null | string; state?: null | string } | null
}
const status = integrations.turnstileStatus
turnstile = status?.state ? { code: status.code ?? null, since: status.since ?? null, state: status.state } : null
secretFromEnv = turnstileSecretFromEnv(integrations)
} catch {
/* the global cannot be read: unknown */
}
}
let openSignUp: null | string[] = null
try {
openSignUp = await openSignUpCollections(payload as never)
} catch {
openSignUp = null
}
let staffOpenToOthers: null | string[] = null
try {
staffOpenToOthers = await staffCollectionsOpenToOthers(payload as never)
} catch {
staffOpenToOthers = null
}
let staffOnOwnRoles: null | string[] = null
try {
staffOnOwnRoles = staffCollectionsOnOwnRoles(payload as never)
} catch {
staffOnOwnRoles = null
}
return { node: process.version, openSignUp, pendingCookies, plugin: pluginVersion(), staffOnOwnRoles, staffOpenToOthers, turnstile, turnstileSecretFromEnv: secretFromEnv, usersSetupClosed, usersWithout2fa }
}
export type DoctorEndpointOptions = {
+18
View File
@@ -61,8 +61,26 @@ export type DoctorStatus = {
/** null = not compared (the endpoint cannot read files). */
importMapCurrent?: boolean | null
node?: string
/** Auth collections whose `create` rule lets an anonymous request through (slugs only). */
openSignUp?: null | string[]
pendingCookies?: null | number
plugin?: string
/**
* Staff collections with role values of their own that run on the plugin's default account rules:
* inside them every account may create, change and delete accounts. Slugs only.
*/
staffOnOwnRoles?: null | string[]
/**
* Staff collections an account of ANOTHER, non-staff auth collection may create in, read, update,
* delete from or unlock: `'users:update'`. Slugs and operations only.
*/
staffOpenToOthers?: null | string[]
/** The Turnstile integration's recorded state (Site integrations): never a key, only the state. null = not known. */
turnstile?: { code?: null | string; since?: null | string; state?: null | string } | null
/** The Turnstile secret key in use comes from the environment (the panel field is empty). Deprecated. */
turnstileSecretFromEnv?: boolean | null
/** Of `usersWithout2fa`: accounts whose setup window has passed (blocked until an admin reopens setup). */
usersSetupClosed?: null | number
usersWithout2fa?: null | number
}
+1 -1
View File
@@ -87,7 +87,7 @@ export const panelSmtpAdapter =
auth: { pass, user },
host,
port,
secure: port === 465, // implicit TLS on 465, STARTTLS otherwise
secure: port === 465, // implicit TLS on 465, STARTTLS otherwise
})
try {
+1
View File
@@ -84,6 +84,7 @@ export type FormSubmitEndpointOptions = {
*/
timeoutMs?: number
turnstileHostnames?: string[]
/** While Turnstile cannot check: unset = `forms.turnstileOnConfigError`, else `'reject'` (this endpoint carries files). */
turnstileOnConfigError?: 'allow' | 'reject'
}
@@ -220,7 +220,8 @@ export async function handleFormSubmit(req: PayloadRequest): Promise<Response> {
const { [honeypot]: _honeypot, ...answers } = data
const token = fields._token?.trim() || undefined
const blocked = await passTurnstile({ ip, payload, turnstileHostnames: submit.turnstileHostnames, turnstileOnConfigError: submit.turnstileOnConfigError, turnstileToken: token })
// a form that can carry files: while Turnstile cannot check, refused by default (forms.turnstileOnConfigError)
const blocked = await passTurnstile({ ip, payload, turnstileHostnames: submit.turnstileHostnames, turnstileKind: 'files', turnstileOnConfigError: submit.turnstileOnConfigError, turnstileToken: token })
if (settled) {return}
if (blocked) {return stop(blocked)}
+38 -8
View File
@@ -51,8 +51,10 @@ export type SubmitFormArgs = {
turnstileHostnames?: string[]
/**
* Turnstile can't be verified because of OUR side (missing/wrong secret,
* Cloudflare unreachable): 'allow' (default) accepts the submission and shows
* the problem in the panel; 'reject' refuses it.
* Cloudflare unreachable): 'allow' accepts the submission and shows the
* problem in the panel; 'reject' refuses it. Unset = the plugin option
* `forms.turnstileOnConfigError`, else the default for the kind of form
* (text: 'allow'; a form with files: 'reject').
*/
turnstileOnConfigError?: 'allow' | 'reject'
/**
@@ -128,16 +130,42 @@ export type SubmitFailure =
export type SubmitFormResult = { submissionId: number | string; success: true } | SubmitFailure
/** What a form does while Turnstile cannot check (wrong or missing secret, Cloudflare down). */
export type TurnstileOnConfigError = 'allow' | 'reject'
/** Which kind of form asks: one that only carries text, or one that can carry files (the file endpoint). */
export type TurnstileFormKind = 'files' | 'text'
/** `forms.turnstileOnConfigError`: one answer for every form, or one per kind. */
export type TurnstileOnConfigErrorOption = { files?: TurnstileOnConfigError; text?: TurnstileOnConfigError } | TurnstileOnConfigError
/** Defaults: a text form keeps working (the enquiry matters more than spam); a form with files does not. */
export const TURNSTILE_ON_CONFIG_ERROR_DEFAULT: Record<TurnstileFormKind, TurnstileOnConfigError> = { files: 'reject', text: 'allow' }
/**
* The policy for one submission: the value given at the call site, else the plugin option
* `forms.turnstileOnConfigError` (one value, or per kind), else the default for the kind.
*/
export function resolveTurnstileOnConfigError(
payload: { config?: { custom?: unknown } } | null | undefined,
kind: TurnstileFormKind = 'text',
explicit?: TurnstileOnConfigError,
): TurnstileOnConfigError {
if (explicit === 'allow' || explicit === 'reject') {return explicit}
const option = (payload?.config?.custom as { ipal?: { forms?: { turnstileOnConfigError?: TurnstileOnConfigErrorOption } } } | undefined)?.ipal?.forms?.turnstileOnConfigError
const fromOption = typeof option === 'string' ? option : option?.[kind]
return fromOption === 'allow' || fromOption === 'reject' ? fromOption : TURNSTILE_ON_CONFIG_ERROR_DEFAULT[kind]
}
/** Rate limit, then Turnstile — the two gates that need nothing but the request. `null` = passed. */
export async function passSubmitGates({
ip,
maxPerMinute = 5,
payload,
turnstileHostnames,
turnstileOnConfigError = 'allow',
turnstileKind,
turnstileOnConfigError,
turnstileToken,
}: Pick<SubmitFormArgs, 'ip' | 'maxPerMinute' | 'payload' | 'turnstileHostnames' | 'turnstileOnConfigError' | 'turnstileToken'>): Promise<null | SubmitFailure> {
return (await passRateLimit({ ip, maxPerMinute })) ?? (await passTurnstile({ ip, payload, turnstileHostnames, turnstileOnConfigError, turnstileToken }))
}: { turnstileKind?: TurnstileFormKind } & Pick<SubmitFormArgs, 'ip' | 'maxPerMinute' | 'payload' | 'turnstileHostnames' | 'turnstileOnConfigError' | 'turnstileToken'>): Promise<null | SubmitFailure> {
return (await passRateLimit({ ip, maxPerMinute })) ?? (await passTurnstile({ ip, payload, turnstileHostnames, turnstileKind, turnstileOnConfigError, turnstileToken }))
}
/** 1. Rate limit — cheapest gate, drops a flood before any real work. No IP → the shared "unknown" bucket, never a free pass. */
@@ -157,13 +185,15 @@ export async function passTurnstile({
ip,
payload,
turnstileHostnames,
turnstileOnConfigError = 'allow',
turnstileKind = 'text',
turnstileOnConfigError,
turnstileToken,
}: Pick<SubmitFormArgs, 'ip' | 'payload' | 'turnstileHostnames' | 'turnstileOnConfigError' | 'turnstileToken'>): Promise<null | SubmitFailure> {
}: { turnstileKind?: TurnstileFormKind } & Pick<SubmitFormArgs, 'ip' | 'payload' | 'turnstileHostnames' | 'turnstileOnConfigError' | 'turnstileToken'>): Promise<null | SubmitFailure> {
if ((await getTurnstileConfig(payload)).enabled) {
const onConfigError = resolveTurnstileOnConfigError(payload, turnstileKind, turnstileOnConfigError)
const ok =
Boolean(turnstileToken) &&
(await verifyTurnstile({ hostnames: turnstileHostnames, ip, onConfigError: turnstileOnConfigError, payload, token: turnstileToken! }))
(await verifyTurnstile({ hostnames: turnstileHostnames, ip, onConfigError, payload, token: turnstileToken! }))
if (!ok) {return { reason: 'turnstile', success: false }}
}
return null
+14
View File
@@ -2,6 +2,7 @@ import type { BeforeEmail } from '@payloadcms/plugin-form-builder/types'
import type { Block, CollectionConfig, Field } from 'payload'
import type { FormAttachmentsOption } from './attachments/config.js'
import type { TurnstileOnConfigErrorOption } from './submitForm.js'
/**
* Receives the collection's default fields and returns the final list — add,
@@ -93,4 +94,17 @@ export type FormsOption = {
formSubmissionOverrides?: FormsCollectionOverrides
/** Collections a form can redirect to (e.g. ['pages']). */
redirectRelationships?: string[]
/**
* What a form does while Turnstile CANNOT check — the secret is missing or
* wrong, Cloudflare is down (the "degraded" state, shown in Site
* integrations and by ipal-doctor). Default: a text form is accepted
* (`'allow'`: an enquiry matters more than spam), a form that can carry
* files — the file endpoint — is refused (`'reject'`: an accepted bot
* submission would put an attachment into a mailbox).
* One value for every form, or one per kind:
* `'reject'`, `'allow'`, `{ text: 'allow', files: 'allow' }`.
* A value passed at a call site (`createSubmitAction`, `attachments.submit`)
* still wins. Not involved when Turnstile is off (no keys). docs/turnstile.md.
*/
turnstileOnConfigError?: TurnstileOnConfigErrorOption
}
+28 -1
View File
@@ -2,6 +2,7 @@ import type { Payload } from 'payload'
import type { IntegrationStatus } from './status.js'
import { userMeetsRole } from '../access/predicates.js'
import { turnstileMissingKey } from '../turnstile/config.js'
import { type IntegrationLabel, resolveLabel, serverText, STATUS_CODE_TEXTS } from './texts.js'
@@ -10,10 +11,18 @@ type Props = {
adminRoute?: string
/** Status groups to check: field name → label (one string, or one per language). */
checks?: Record<string, IntegrationLabel>
/**
* Who sees WHAT is failing (the error text and the link to Site integrations): `'admin'`
* (default — the role that may read that global), `'editor'`, or `'all'` (everyone who opens
* the dashboard, as before). Below that, an editor sees a neutral line; anyone else nothing.
*/
details?: 'admin' | 'all' | 'editor'
/** Injected by Payload into admin server components. */
i18n?: { language?: string; t?: (key: never, vars?: Record<string, unknown>) => string }
/** Injected by Payload into admin server components. */
payload?: Payload
/** Injected by Payload into admin server components — the account looking at the dashboard. */
user?: null | Record<string, unknown>
}
const DEFAULT_CHECKS: Record<string, IntegrationLabel> = {
@@ -25,9 +34,17 @@ const DEFAULT_CHECKS: Record<string, IntegrationLabel> = {
* Dashboard alert (admin.components.beforeDashboard): lists integrations that
* are currently failing, with a link to Site integrations. Renders nothing when
* everything is fine — and never throws (DB not ready → nothing).
*
* The texts come from the Site integrations global, which only admins may read: the widget
* reads it with access control off, so it decides itself who gets them (`details`). With a
* role, a session that still owes its second factor gets nothing (`userMeetsRole` includes
* it); `details: 'all'` checks nothing at all — no role, no second factor.
*/
export async function IntegrationAlerts({ adminRoute = '/admin', checks = DEFAULT_CHECKS, i18n, payload }: Props) {
export async function IntegrationAlerts({ adminRoute = '/admin', checks = DEFAULT_CHECKS, details = 'admin', i18n, payload, user }: Props) {
if (!payload) {return null}
const sees = (role: 'admin' | 'editor') => Boolean(user) && userMeetsRole({ payload, user }, role)
const full = details === 'all' || sees(details)
if (!full && !sees('editor')) {return null}
let doc: Record<string, unknown>
try {
doc = (await payload.findGlobal({ slug: 'site-integrations' as never, depth: 0 })) as Record<string, unknown>
@@ -57,8 +74,18 @@ export async function IntegrationAlerts({ adminRoute = '/admin', checks = DEFAUL
}
if (!failing.length) {return null}
// Not allowed the detail: that something needs attention, and whom to ask — nothing of what or why.
if (!full) {
return (
<div data-ipal="integration-alerts" role="status" style={{ border: '1px solid var(--theme-elevation-200, #ddd)', borderRadius: 4, marginBottom: '1.5rem', padding: '1rem 1.25rem' }}>
<strong>{serverText(i18nLike, 'alertsHeading')}</strong> {serverText(i18nLike, 'alertsAskAdmin')}
</div>
)
}
return (
<div
data-ipal="integration-alerts"
role="alert"
style={{
background: 'var(--theme-error-50, rgba(229, 72, 77, 0.08))',
+9
View File
@@ -0,0 +1,9 @@
/**
* The two values of a write-only secret that travel between the server and the panel.
* On their own, without any server code: the panel's field component imports them.
*/
/** What a read gets instead of a stored secret: "a value is set". */
export const SECRET_MASK = '********'
/** Send this as the value to remove a stored secret (an empty value keeps it). */
export const SECRET_CLEAR = '[[clear]]'
+207
View File
@@ -0,0 +1,207 @@
import type { CollectionAfterReadHook, Field, FieldHook, GlobalAfterReadHook } from 'payload'
import { ValidationError } from 'payload'
import { ipalT } from '../admin-i18n/t.js'
import { SECRET_CLEAR, SECRET_MASK } from './constants.js'
/**
* Write-only secrets: a field whose stored value never leaves the server.
*
* `smtpPassword` and `turnstileSecretKey` live in the Site integrations global — the panel is
* their source. Until now `MaskedField` only drew dots on screen: the value itself went to the
* browser, and REST and GraphQL returned it to whoever could read the global. A stolen admin
* session, or any way past the global's read rule, was a working mailbox password.
*
* With `writeOnlySecret` the value is:
* - **returned as `SECRET_MASK`** when it is set (and as it is when empty) to every read that
* goes through access control — REST, GraphQL, the panel's form state, versions;
* - **returned in full** only to a Local API read with access control off (the default of
* `payload.findGlobal` / `payload.find` on the server) — how the plugin's own code reads it;
* - **kept** when a save sends nothing, an empty value or the mask back;
* - **replaced** when a save sends a new value, and **removed** when it sends `SECRET_CLEAR`;
* - **asked for again** when a save through access control changes a field the secret is
* bound to (`boundTo`) and sends no new secret. The SMTP password is bound to the server,
* the port and the user name, whatever the transport: otherwise a stolen admin
* session points the server at its own machine, sends a test e-mail and reads the password
* off the wire. `secrets: { reenterOnChange: false }` turns that off.
*
* Restoring a version (a project that turns versions on) answers with the version document —
* the fields sit under `version`, where field hooks do not run. `maskSecretsOnRestore` is the
* global / collection `afterRead` hook that masks them there too.
*
* Off for the two built-in fields: `secrets: { writeOnly: false }`. For a field of your own:
* `writeOnlySecret({ name: 'apiToken', type: 'text', admin: { components: { Field: '@intecion/ipal-kit/admin#MaskedField' } } })`.
*/
export { SECRET_CLEAR, SECRET_MASK }
/** True when a value read from the API means "a secret is stored" rather than being one. */
export const isSecretMask = (value: unknown): boolean => value === SECRET_MASK
const dig = (doc: unknown, path: (number | string)[]): unknown => path.reduce<unknown>((at, key) => (at && typeof at === 'object' ? (at as Record<string, unknown>)[key as string] : undefined), doc)
/** Reads: the stored value only for server code that reads with access control off. */
export const maskSecretAfterRead: FieldHook = ({ overrideAccess, value }) => {
if (overrideAccess === true) {return value}
return typeof value === 'string' && value !== '' ? SECRET_MASK : value
}
/**
* Writes: nothing, an empty value or the mask keep what is stored; `SECRET_CLEAR` removes it;
* anything else is the new secret. Runs in `beforeValidate`, so every later hook (the global's
* own `beforeChange` included) already sees the real value.
*/
export type WriteOnlySecretOptions = {
/** With `boundTo`: the rule applies only to a save for which this returns true (the sibling data of the save). */
appliesWhen?: (siblingData: Record<string, unknown>) => boolean
/**
* Sibling fields the secret belongs to (the server it is sent to, the user it is for). A save
* through access control that changes one of them must send the secret again — or remove it.
*/
boundTo?: string[]
}
/** Two values of a bound field are the same setting: the same text, exactly (`587` and `'587'` are the same; another letter case or a space is a change). */
const asText = (value: unknown): string => (typeof value === 'string' || typeof value === 'number' || typeof value === 'boolean' ? String(value) : value === undefined || value === null ? '' : JSON.stringify(value))
const sameSetting = (a: unknown, b: unknown): boolean => asText(a) === asText(b)
/** A field by name among the siblings — also inside a row or a collapsible, which add no level to the data. */
const siblingField = (fields: unknown, name: string): { defaultValue?: unknown } | undefined => {
for (const field of (Array.isArray(fields) ? fields : []) as { defaultValue?: unknown; fields?: unknown; name?: string; tabs?: { fields?: unknown; name?: string }[] }[]) {
if (field.name === name) {return field}
if (!field.name && field.fields) {
const found = siblingField(field.fields, name)
if (found) {return found}
}
for (const tab of field.tabs ?? []) {
if (tab.name) {continue}
const found = siblingField(tab.fields, name)
if (found) {return found}
}
}
return undefined
}
/** The stored value of the secret — never the mask (the original document is read with access control off; a mask there is not a secret). */
const storedSecret = (originalDoc: unknown, path: (number | string)[]): null | string => {
const stored = dig(originalDoc, path)
return typeof stored === 'string' && stored !== '' && stored !== SECRET_MASK ? stored : null
}
/** The `beforeValidate` hook of a write-only secret. `keepSecretBeforeValidate` is the one without options. */
export function buildKeepSecret({ appliesWhen, boundTo = [] }: WriteOnlySecretOptions = {}): FieldHook {
return ({ collection, field, global, originalDoc, overrideAccess, path, req, siblingData, siblingFields, value: given }) => {
// What the save SENT. For a field that was not sent Payload passes a fallback as `value` — the
// stored secret itself — which must not pass for a secret typed again.
const name = (field as { name?: string } | undefined)?.name
const value = siblingData && name ? (siblingData as Record<string, unknown>)[name] : given
if (value === SECRET_CLEAR) {return null}
const refuse = (key: 'secretNotText' | 'secretReenter', fallback: string): never => {
const message = req?.t ? ipalT(req.t as never, key) : fallback
throw new ValidationError({ collection: collection?.slug, errors: [{ message, path: path.join('.') }], global: global?.slug }, req?.t)
}
const nothing = value === undefined || value === null || value === '' || value === SECRET_MASK
// a secret is text: `false`, `0`, a list or an object is refused, not stored as typed
if (!nothing && typeof value !== 'string') {return refuse('secretNotText', 'Enter the value as text.')}
if (!nothing) {return value}
const stored = storedSecret(originalDoc, path)
if (stored && boundTo.length && overrideAccess !== true && (!appliesWhen || appliesWhen((siblingData ?? {}) as Record<string, unknown>))) {
const before = dig(originalDoc, path.slice(0, -1)) as Record<string, unknown> | undefined
const changed = boundTo.filter((name) => {
const next = (siblingData as Record<string, unknown> | undefined)?.[name]
if (next === undefined) {return false} // not part of this save
// a value never saved counts as the field's default (an older document, a field added since)
// (a SQL row can hold NULL where MongoDB holds nothing; the field may sit inside a row)
const fallback = siblingField(siblingFields, name)?.defaultValue
const byDefault = typeof fallback === 'function' ? undefined : fallback
return !sameSetting(next ?? byDefault, before?.[name] ?? byDefault)
})
if (changed.length) {return refuse('secretReenter', 'Enter the password again: the settings it belongs to have changed.')}
}
return stored
}
}
/**
* Writes: nothing, an empty value or the mask keep what is stored; `SECRET_CLEAR` removes it;
* anything else is the new secret. Runs in `beforeValidate`, so every later hook (the global's
* own `beforeChange` included) already sees the real value.
*/
export const keepSecretBeforeValidate: FieldHook = buildKeepSecret()
/** Adds the two hooks to a field (a text field as a rule). The field's own hooks stay, and run around them. */
export function writeOnlySecret<F extends Field>(field: F, options: WriteOnlySecretOptions = {}): F {
const own = (field as { hooks?: { afterRead?: FieldHook[]; beforeValidate?: FieldHook[] } }).hooks ?? {}
return {
...field,
custom: { ...(field as { custom?: Record<string, unknown> }).custom, ipalWriteOnly: true },
hooks: {
...own,
afterRead: [...(own.afterRead ?? []), maskSecretAfterRead],
beforeValidate: [options.boundTo?.length ? buildKeepSecret(options) : keepSecretBeforeValidate, ...(own.beforeValidate ?? [])],
},
} as F
}
/**
* `writeOnlySecret` for the named fields, wherever they are in the tree (tabs, rows, groups, collapsibles).
* `options`: per field name (`{ smtpPassword: { boundTo: [...] } }`).
*/
export function writeOnlySecrets(fields: Field[], names: string[], options: Record<string, WriteOnlySecretOptions> = {}): Field[] {
return fields.map((field) => {
const f = field as { fields?: Field[]; name?: string; tabs?: { fields: Field[] }[] } & Field
if (f.name && names.includes(f.name) && !('fields' in f && Array.isArray(f.fields))) {return writeOnlySecret(field, options[f.name])}
if (Array.isArray(f.tabs)) {return { ...f, tabs: f.tabs.map((tab) => ({ ...tab, fields: writeOnlySecrets(tab.fields, names, options) })) } as Field}
if (Array.isArray(f.fields)) {return { ...f, fields: writeOnlySecrets(f.fields, names, options) } as Field}
return field
})
}
type Tree = { blocks?: { fields: Field[]; slug: string }[]; custom?: { ipalWriteOnly?: boolean }; fields?: Field[]; name?: string; tabs?: { fields: Field[]; name?: string }[]; type?: string }
/** Masks every write-only secret in `data`, following the field tree (tabs, rows, groups, arrays, blocks). In place. */
export function maskWriteOnlySecrets(data: unknown, fields: Field[]): void {
if (!data || typeof data !== 'object') {return}
const doc = data as Record<string, unknown>
for (const field of fields as Tree[]) {
if (Array.isArray(field.tabs)) {
for (const tab of field.tabs) {maskWriteOnlySecrets(tab.name ? doc[tab.name] : doc, tab.fields)}
} else if (!field.name) {
if (Array.isArray(field.fields)) {maskWriteOnlySecrets(doc, field.fields)}
} else if (field.custom?.ipalWriteOnly) {
if (typeof doc[field.name] === 'string' && doc[field.name] !== '') {doc[field.name] = SECRET_MASK}
} else if (Array.isArray(field.fields)) {
const value = doc[field.name]
for (const row of Array.isArray(value) ? value : [value]) {maskWriteOnlySecrets(row, field.fields)}
} else if (Array.isArray(field.blocks) && Array.isArray(doc[field.name])) {
for (const row of doc[field.name] as { blockType?: string }[]) {
const block = field.blocks.find((b) => b.slug === row?.blockType)
if (block) {maskWriteOnlySecrets(row, block.fields)}
}
}
}
}
/**
* `afterRead` hook for a global or a collection with write-only secrets AND versions: a restore
* answers with the version document, the fields under `version`, where the field hooks do not
* reach. Masks them there for every read through access control. Put on Site integrations by
* the plugin; add it to your own entity next to `writeOnlySecret`.
*/
export const maskSecretsOnRestore: CollectionAfterReadHook & GlobalAfterReadHook = (args: { collection?: { fields: Field[] }; context?: { isRestoringVersion?: unknown }; doc: unknown; global?: { fields: Field[] }; overrideAccess?: boolean }) => {
const { context, doc, overrideAccess } = args
const fields = (args.global ?? args.collection)?.fields
const version = (doc as { version?: unknown } | null)?.version
if (overrideAccess !== true && context?.isRestoringVersion && fields && version && typeof version === 'object') {maskWriteOnlySecrets(version, fields)}
return doc
}
/** The plugin's own stored secrets (Site integrations). */
export const INTEGRATION_SECRET_FIELDS = ['smtpPassword', 'turnstileSecretKey']
/**
* What the SMTP password belongs to: changing one of these through access control asks for the password again —
* whatever the transport says. `emailTransport` is not in the list: the mail adapter falls back to SMTP when Graph
* is not configured, so the transport decides nothing about where the password goes; the server, port and user do.
*/
export const SMTP_PASSWORD_BOUND_TO = ['smtpHost', 'smtpPort', 'smtpUser']
+24 -5
View File
@@ -157,13 +157,32 @@ export function buildSecurityHeaders(args: BuildSecurityHeadersArgs = {}): Secur
* ]
* }
*/
export function buildUploadSecurityHeaders({ collections = ['media'] }: { collections?: string[] } = {}): {
export function buildUploadSecurityHeaders({
adminIcon = '/api/ipal/admin-icon',
collections = ['media'],
}: {
/**
* Path of the plugin's panel icon endpoint, which answers with the favicon's bytes. It only ever
* answers with a bitmap; the rule is a second layer. Another API route: `'/cms-api/ipal/admin-icon'`;
* `false` = no rule.
*/
adminIcon?: false | string
collections?: string[]
} = {}): {
headers: SecurityHeader[]
source: string
}[] {
const headers: SecurityHeader[] = [
{ key: 'Content-Security-Policy', value: "default-src 'none'; img-src 'self' data:; style-src 'unsafe-inline'; sandbox" },
{ key: 'X-Content-Type-Options', value: 'nosniff' },
return [
...collections.map((slug) => ({ headers: [...UPLOAD_SECURITY_HEADERS], source: `/api/${slug}/file/:path*` })),
...(adminIcon ? [{ headers: [...UPLOAD_SECURITY_HEADERS], source: adminIcon }] : []),
]
return collections.map((slug) => ({ headers, source: `/api/${slug}/file/:path*` }))
}
/**
* The headers themselves: for any response that carries the bytes of an uploaded file from the
* site's own origin (the upload routes above; the plugin's `/api/ipal/admin-icon`; a route of yours).
*/
export const UPLOAD_SECURITY_HEADERS: readonly SecurityHeader[] = [
{ key: 'Content-Security-Policy', value: "default-src 'none'; img-src 'self' data:; style-src 'unsafe-inline'; sandbox" },
{ key: 'X-Content-Type-Options', value: 'nosniff' },
]
+1 -1
View File
@@ -8,7 +8,7 @@ export {
DEFAULT_CSP_REPORT_GROUP,
} from './buildCsp.js'
export type { BuildAdminCspArgs, BuildCspArgs, CspDirective, CspSources } from './buildCsp.js'
export { buildSecurityHeaders, buildUploadSecurityHeaders } from './buildSecurityHeaders.js'
export { buildSecurityHeaders, buildUploadSecurityHeaders, UPLOAD_SECURITY_HEADERS } from './buildSecurityHeaders.js'
export type { BuildSecurityHeadersArgs, SecurityHeader } from './buildSecurityHeaders.js'
export { createCspReportRoute, parseCspReports } from './createCspReportRoute.js'
export type { CreateCspReportRouteArgs, CspViolation } from './createCspReportRoute.js'
@@ -8,12 +8,17 @@ import { useEffect } from 'react'
import type { TotpUser } from './totpRedirect.js'
import { totpRedirectTarget } from './totpRedirect.js'
import { formatDateTime, ipalT } from '../../admin-i18n/t.js'
import { totpAdminPath, totpRedirectTarget } from './totpRedirect.js'
export type TotpRedirectProviderProps = {
children?: ReactNode
/** pluginOptions.forceSetup — set by the plugin (true: 2FA is enforced). */
forceSetup?: boolean
/** `twoFactor.requireSetup` is on: say so on the setup screen. Set by the plugin. */
requireSetup?: boolean
/** Hours an account has for setup (0 = no limit). Set by the plugin. */
setupWindowHours?: number
/**
* Set by the plugin when the admin import map on disk lacks the 2FA view wrapper
* (importMapCheck.ts). The 2FA screens are then probably empty, so a notice says what is
@@ -42,9 +47,9 @@ const STALE_TEXT = {
* Renders nothing while a redirect is pending, so the panel does not flash.
* Swap it with `twoFactor.provider`.
*/
export function TotpRedirectProvider({ children, forceSetup = true, staleImportMap = false }: TotpRedirectProviderProps) {
export function TotpRedirectProvider({ children, forceSetup = true, requireSetup = false, setupWindowHours = 0, staleImportMap = false }: TotpRedirectProviderProps) {
const { i18n, t } = useTranslation()
const { user } = useAuth()
const { i18n } = useTranslation()
const { config } = useConfig()
const pathname = usePathname()
const router = useRouter()
@@ -62,19 +67,61 @@ export function TotpRedirectProvider({ children, forceSetup = true, staleImportM
}, [router, target])
if (target) {return null}
if (staleImportMap && user && /\/(?:setup|verify)-totp\/?$/.test(pathname ?? '')) {
// Both notices stand ABOVE the screen and never replace it: the code form must stay on the page whatever they say.
const adminRoute = config.routes?.admin ?? '/admin'
const here = (pathname ?? '').replace(/\/+$/, '')
const onSetup = here === totpAdminPath(adminRoute, '/setup-totp')
const onVerify = here === totpAdminPath(adminRoute, '/verify-totp')
// The admin import map on disk may be older than the config (importMapCheck.ts): a guess, hence only a notice.
let stale: ReactNode = null
if (staleImportMap && user && (onSetup || onVerify)) {
const text = STALE_TEXT[i18n.language?.toLowerCase().startsWith('pl') ? 'pl' : 'en']
return (
<>
<div role="alert" style={{ margin: '2rem auto 0', maxWidth: '36rem', padding: '0 1.5rem' }}>
<p style={{ fontWeight: 600, marginBottom: '0.5rem' }}>{text.title}</p>
<p>{text.body}</p>
</div>
{children}
</>
stale = (
<div role="alert" style={{ margin: '2rem auto 0', maxWidth: '36rem', padding: '0 1.5rem' }}>
<p style={{ fontWeight: 600, marginBottom: '0.5rem' }}>{text.title}</p>
<p>{text.body}</p>
</div>
)
}
return children
// On the setup screen: what the account is waiting for — or that its time has passed.
let setup: ReactNode = null
const account = user as ({ totpSetupFrom?: null | string } & TotpUser) | null
if (requireSetup && onSetup && account && account.hasTotp === false) {
const start = account.totpSetupFrom ? new Date(account.totpSetupFrom).getTime() : NaN
const deadline = setupWindowHours > 0 && Number.isFinite(start) ? start + setupWindowHours * 3_600_000 : null
const closed = deadline !== null && deadline < Date.now()
const notice = closed
? ipalT(t as never, 'twoFactorSetupClosed')
: deadline !== null
? ipalT(t as never, 'twoFactorSetupDeadline', { date: formatDateTime(new Date(deadline).toISOString(), i18n.language) })
: ipalT(t as never, 'twoFactorSetupRequired')
setup = (
<div
id="ipal-two-factor-notice"
role={closed ? 'alert' : 'status'}
style={{
background: closed ? 'var(--theme-error-100, #fdecea)' : 'var(--theme-elevation-100, #f3f3f3)',
borderBottom: `1px solid ${closed ? 'var(--theme-error-500, #b00020)' : 'var(--theme-elevation-200, #ddd)'}`,
padding: '.75rem 1rem',
textAlign: 'center',
}}
>
{notice}
</div>
)
}
if (!stale && !setup) {return children}
return (
<>
{setup}
{stale}
{children}
</>
)
}
export default TotpRedirectProvider
@@ -0,0 +1,47 @@
import type { BasePayload } from 'payload'
import { userMeetsRole } from '../../access/predicates.js'
import { serverText } from '../../integrations/texts.js'
import { countAccountsWithoutTotp } from './setupRequired.js'
type Props = {
/** Admin route, for the link. Default '/admin'. */
adminRoute?: string
i18n?: { language?: string; t?: (key: never, vars?: Record<string, unknown>) => string }
payload?: BasePayload
user?: null | Record<string, unknown>
}
/**
* Dashboard notice for administrators (admin.components.beforeDashboard):
* how many accounts have not set up two-step verification, and how many of
* them are blocked because the time for setup has passed. Renders nothing when
* every account has it, for non-admins, and when anything fails.
*/
export async function TwoFactorAlert({ adminRoute = '/admin', i18n, payload, user }: Props) {
if (!payload || !user || !userMeetsRole({ payload, user }, 'admin')) {return null}
const guard = (payload.config.custom as { ipal?: { twoFactor?: { collection?: string; setupWindowMs?: number } } } | undefined)?.ipal?.twoFactor
if (!guard?.collection) {return null}
let counts: { blocked: number; without: number }
try {
counts = await countAccountsWithoutTotp(payload, guard.collection, guard.setupWindowMs)
} catch {
return null
}
if (!counts.without) {return null}
const base = adminRoute === '/' ? '' : adminRoute.replace(/\/$/, '')
return (
<div
role="status"
style={{ background: 'var(--theme-warning-100, #fff8e1)', border: '1px solid var(--theme-warning-500, #f0b400)', borderRadius: 4, marginBottom: '1.5rem', padding: '1rem 1.25rem' }}
>
<strong>{serverText(i18n, 'twoFactorAlertTitle')}</strong>
<p style={{ margin: '.35rem 0 0' }}>{serverText(i18n, 'twoFactorAlertPending', { count: counts.without })}</p>
{counts.blocked > 0 && <p style={{ margin: '.35rem 0 0' }}>{serverText(i18n, 'twoFactorAlertBlocked', { count: counts.blocked })}</p>}
<p style={{ margin: '.35rem 0 0' }}>
<a href={`${base}/collections/${guard.collection}`}>{serverText(i18n, 'twoFactorAlertLink')}</a>
</p>
</div>
)
}
@@ -0,0 +1,52 @@
'use client'
import { toast, useConfig, useTranslation } from '@payloadcms/ui'
import { useState } from 'react'
import { ipalT } from '../../admin-i18n/t.js'
type Props = {
/** `reopen`: the account has no TOTP (window passed or still open). `reset`: it has one (lost phone). */
kind: 'reopen' | 'reset'
userId: number | string
}
/** The admin's button on an account: clears its TOTP so it can (or must) set it up again. */
export function TwoFactorResetButton({ kind, userId }: Props) {
const { t } = useTranslation()
const text = (key: Parameters<typeof ipalT>[1]) => ipalT(t as never, key)
const { config } = useConfig()
const [busy, setBusy] = useState(false)
const run = async () => {
if (kind === 'reset' && !window.confirm(text('twoFactorResetConfirm'))) {return}
setBusy(true)
try {
const res = await fetch(`${config.serverURL ?? ''}${config.routes?.api ?? '/api'}/ipal/two-factor/reset`, {
body: JSON.stringify({ userId }),
credentials: 'include',
headers: { 'Content-Type': 'application/json' },
method: 'POST',
})
const data = (await res.json()) as { message?: string; ok?: boolean }
if (data.ok) {
toast.success(data.message ?? text('twoFactorResetDone'))
// The status next to this button is rendered on the server with the document: load it again.
// (router.refresh() does not re-render a document's field components.)
window.location.reload()
} else {
toast.error(data.message ?? text('twoFactorResetFailed'))
}
} catch {
toast.error(text('twoFactorResetFailed'))
} finally {
setBusy(false)
}
}
return (
<button className="btn btn--style-secondary btn--size-small" disabled={busy} onClick={run} style={{ marginTop: '.5rem' }} type="button">
{text(kind === 'reopen' ? 'twoFactorReopen' : 'twoFactorReset')}
</button>
)
}
@@ -0,0 +1,64 @@
import type { BasePayload } from 'payload'
import { userMeetsRole } from '../../access/predicates.js'
import { formatDateTime } from '../../admin-i18n/t.js'
import { serverText } from '../../integrations/texts.js'
import { twoFactorSetupDeadline, twoFactorSetupState } from './secondFactor.js'
import { TwoFactorResetButton } from './TwoFactorResetButton.js'
type Props = {
/** The account being shown. Injected by Payload into field server components. */
data?: { id?: number | string } & Record<string, unknown>
i18n?: { language?: string; t?: (key: never, vars?: Record<string, unknown>) => string }
payload?: BasePayload
/** The account looking at it. */
user?: ({ id?: number | string } & Record<string, unknown>) | null
}
/**
* On an account in the panel (sidebar): where it stands with two-step
* verification — set up, open until a date, or blocked because the time for
* setup has passed — and, for an administrator looking at someone else's
* account, the button that resets it / reopens setup.
*/
export async function TwoFactorStatusField({ data, i18n, payload, user }: Props) {
if (!payload || !data?.id) {return null}
const collection = (payload.config.custom as { ipal?: { twoFactor?: { collection?: string } } } | undefined)?.ipal?.twoFactor?.collection
if (!collection) {return null}
// The document data the panel passes hides `hasTotp` from everyone but the account itself (the 2FA
// package's field access), so an admin would always read "set up". Ask the database: the secret is
// only tested for presence, never shown.
let stored: { totpSecret?: null | string; totpSetupFrom?: null | string }
try {
stored = (await payload.findByID({
id: data.id,
collection: collection as never,
depth: 0,
overrideAccess: true,
select: { totpSecret: true, totpSetupFrom: true } as never,
showHiddenFields: true,
})) as typeof stored
} catch {
return null
}
const account = { id: data.id, collection, email: data.email, hasTotp: Boolean(stored.totpSecret), totpSetupFrom: stored.totpSetupFrom }
const state = twoFactorSetupState({ payload, user: account })
if (state === 'not-applicable') {return null}
const deadline = twoFactorSetupDeadline({ payload, user: account })
const date = deadline ? formatDateTime(deadline.toISOString(), i18n?.language ?? 'en') : ''
const status =
state === 'set-up' ? serverText(i18n, 'twoFactorStatusOn')
: state === 'exempt' ? serverText(i18n, 'twoFactorStatusExempt')
: state === 'closed' ? serverText(i18n, 'twoFactorStatusClosed', { date })
: deadline ? serverText(i18n, 'twoFactorStatusOpen', { date })
: serverText(i18n, 'twoFactorStatusOpenNoLimit')
const canReset = Boolean(user && user.id !== data.id && userMeetsRole({ payload, user }, 'admin'))
return (
<div className="field-type" id="ipal-two-factor-status">
<span className="field-label">{serverText(i18n, 'twoFactorStatusLabel')}</span>
<p style={{ margin: 0, ...(state === 'closed' ? { color: 'var(--theme-error-500, #b00020)' } : {}) }}>{status}</p>
{canReset && state !== 'exempt' && <TwoFactorResetButton kind={state === 'set-up' ? 'reset' : 'reopen'} userId={data.id} />}
</div>
)
}
+112
View File
@@ -0,0 +1,112 @@
/**
* 2FA verify and setup attempts only from the site's own origin.
*
* The verify limit counts every attempt of an account. A page on another origin that the
* browser still sends the login cookie to — a sibling subdomain is "same site", so
* `SameSite=Lax` does not stop it, and Payload's own `csrf` list is empty unless `serverURL`
* or `csrf` is set — could post wrong codes in the owner's name: no password needed, the
* owner's five attempts burnt, the owner locked out for the window. So a request that a
* browser marks as coming from elsewhere is refused BEFORE it is counted.
*
* What counts as the site's own origin: the host the request came in on (`Host`,
* `X-Forwarded-Host`, the request URL), `serverURL`, Payload's `csrf` and `cors` lists, and
* `twoFactor.sameOrigin.origins`. A request with neither `Origin` nor `Sec-Fetch-Site` is not
* a browser's cross-site request (a script, `curl`, a server) and passes: it cannot ride on
* somebody's cookie.
*
* A reverse proxy that rewrites `Host` and sends no `X-Forwarded-Host` (nginx's plain
* `proxy_pass`) hides the site's address from the server: without `serverURL` the site's own
* pages are then refused. That must not happen in silence — the first refusal of every origin
* is written to the log with the ways to allow it (`reportRefusedOrigin`).
*/
type RequestLike = {
headers?: { get(name: string): null | string }
payload?: { config?: { cors?: unknown; csrf?: unknown; serverURL?: unknown }; logger?: { warn(message: string): void } }
url?: null | string
}
/** `site.example:443` is `site.example` for https, `:80` for http — a proxy may write the port out. */
const withoutDefaultPort = (host: string, protocol: string): string => {
const lower = host.toLowerCase()
if (protocol === 'https:' && lower.endsWith(':443')) {return lower.slice(0, -4)}
if (protocol === 'http:' && lower.endsWith(':80')) {return lower.slice(0, -3)}
return lower
}
const originOf = (value: unknown): null | string => {
if (typeof value !== 'string' || !value) {return null}
try {
return new URL(value).origin
} catch {
return null
}
}
/** Origins and hosts this request may come from. */
export function ownOrigins(req: RequestLike, extra: string[] = []): { hosts: Set<string>; origins: Set<string> } {
const config = req.payload?.config
const cors = config?.cors
const listed = [
config?.serverURL,
...(Array.isArray(config?.csrf) ? (config.csrf as unknown[]) : []),
...(Array.isArray(cors) ? (cors as unknown[]) : Array.isArray((cors as { origins?: unknown } | undefined)?.origins) ? ((cors as { origins: unknown[] }).origins) : []),
...extra,
]
const origins = new Set(listed.map(originOf).filter((o): o is string => o !== null))
const hosts = new Set<string>()
for (const name of ['host', 'x-forwarded-host']) {
// a proxy may list several; the first is the one the browser asked for
const value = req.headers?.get(name)?.split(',')[0]?.trim().toLowerCase()
if (value) {hosts.add(value)}
}
const fromUrl = originOf(req.url)
if (fromUrl) {hosts.add(new URL(fromUrl).host)}
return { hosts, origins }
}
/** False when a browser says the request comes from another origin (see the top of the file). */
export function requestFromOwnOrigin(req: RequestLike, extra: string[] = []): boolean {
const origin = req.headers?.get('origin')
if (origin) {
const parsed = originOf(origin)
if (!parsed) {return false} // "null" (a sandboxed page, a redirect chain) or garbage
const { hosts, origins } = ownOrigins(req, extra)
if (origins.has(parsed)) {return true}
// `URL.origin` has already dropped the default port; a `Host` / `X-Forwarded-Host` may carry it
const { host, protocol } = new URL(parsed)
return [...hosts].some((own) => withoutDefaultPort(own, protocol) === host.toLowerCase())
}
const site = req.headers?.get('sec-fetch-site')
if (site) {return site === 'same-origin' || site === 'none'}
return true
}
const reported = new Set<string>()
const MAX_REPORTED = 50
/**
* Says in the log, once per origin and process, that a 2FA attempt was refused and how to allow
* that origin. Without it a site behind a proxy that hides its address has a panel nobody can
* enter and a silent log. Returns true when a line was written.
*/
export function reportRefusedOrigin(req: RequestLike, extra: string[] = []): boolean {
const origin = req.headers?.get('origin')
const key = origin ? (originOf(origin) ?? 'null') : `sec-fetch-site: ${req.headers?.get('sec-fetch-site') ?? 'none'}`
if (reported.has(key) || reported.size >= MAX_REPORTED) {return false}
reported.add(key)
const { hosts, origins } = ownOrigins(req, extra)
const known = [...origins, ...[...hosts].map((h) => `host ${h}`)].join(', ') || 'none'
const how = originOf(origin)
? `If "${originOf(origin)}" is this site's own address (a reverse proxy that rewrites Host and sends no X-Forwarded-Host), set serverURL to it in the Payload config, ` +
`or pass twoFactor: { sameOrigin: { origins: ['${originOf(origin)}'] } }, or make the proxy send X-Forwarded-Host. `
: 'The browser did not name an origin this site knows. '
req.payload?.logger?.warn(
`[ipal] 2FA: a code from ${origin ? `origin "${origin}"` : `a ${key} request`} was refused and not counted — it is not one of this site's own origins (${known}). ` +
how +
'If it is a foreign page, this is the protection working. twoFactor: { sameOrigin: false } turns the check off (docs/security.md "Verify and setup attempts only from the site\'s own origin"). Said once per origin.',
)
return true
}
/** For tests: forget which origins were reported. */
export const clearReportedOrigins = (): void => reported.clear()
+84 -11
View File
@@ -21,7 +21,9 @@ import type { BasePayload, CollectionConfig, Config, GlobalConfig } from 'payloa
* logs a warning at start);
* 4. `_strategy === 'totp'` → set by the package's strategy after password and code;
* 5. `_strategy === 'api-key'` → an API key is its own credential (the package's rule);
* 6. `hasTotp === false` → TOTP not set up yet (the setup screen needs the session);
* 6. `hasTotp === false` (TOTP not set up yet) → only when setup is not required
* (`twoFactor.requireSetup: false`) or the project's `exempt` says so for that account;
* by default such an account is refused like one that owes its code;
* 7. per-entity opt-out in the project's config (`custom.totp.disableAccessWrapper`,
* `custom.ipal.secondFactor`), or the package's global `disableAccessWrapper`;
* 8. `access.admin` (may this account open the panel) is not wrapped: the code is
@@ -36,14 +38,65 @@ import type { BasePayload, CollectionConfig, Config, GlobalConfig } from 'payloa
* It fails closed. An account of the 2FA collection passes only when
* - it came through the package's `totp` strategy (password AND code), or
* - it authenticated with an API key (the package's own rule), or
* - TOTP is not set up on it yet (`hasTotp === false`) — the setup screen
* needs that, and the package lets such an account through as well.
* Anything else — code not entered, or a user object this check does not
* understand (a renamed strategy, no `hasTotp`) — is refused.
* - TOTP is not set up on it yet AND setup is not required
* (`twoFactor.requireSetup: false`), or the project exempts the account.
* Anything else — code not entered, TOTP not set up yet, or a user object this
* check does not understand (a renamed strategy, no `hasTotp`) — is refused.
*
* "Setup required" (the default): an account without TOTP reaches nothing at
* the access level. It does not need to: the setup screen is rendered from the
* session, and `/api/setup-totp` is an endpoint that writes with
* `overrideAccess`. It is the same state an account is in between its password
* and its code. The package alone only redirects such an account in the panel.
*/
/** What ipalKit records in `config.custom.ipal.twoFactor` when 2FA is on and the guard is not switched off. */
export type TwoFactorGuardConfig = { collection: string }
export type TwoFactorGuardConfig = {
collection: string
/** The project's exemption for accounts that never set TOTP up (a service account logging in with a password). */
exempt?: (args: { user: Record<string, unknown> }) => boolean
/** An account without TOTP is refused everything until it is set up. */
requireSetup?: boolean
/** How long after `totpSetupFrom` setup stays possible, in ms. 0 / undefined = no limit. */
setupWindowMs?: number
}
/** Field on the 2FA collection: when the current setup window opened (account created, or an admin reset). */
export const SETUP_FROM_FIELD = 'totpSetupFrom'
/**
* Where an account stands with TOTP setup:
* - `not-applicable`: no user, another collection, 2FA or the guard off;
* - `set-up`: TOTP is set up;
* - `exempt`: not set up, and the project exempts it (or setup is not required);
* - `open`: not set up, may set it up now;
* - `closed`: not set up and the setup window has passed — blocked until an admin reopens it.
*/
export type TwoFactorSetupState = 'closed' | 'exempt' | 'not-applicable' | 'open' | 'set-up'
/**
* The moment setup closes for this account, or null (no window, or no start recorded yet).
* A start that is missing or unreadable counts as "no deadline yet" (the account can still only
* set TOTP up): only server code writes the field, and the start-up step fills in a missing one.
*/
export function twoFactorSetupDeadline({ payload, user }: MaybeReq): Date | null {
const guard = guardConfig(payload)
const from = (user as null | Record<string, unknown> | undefined)?.[SETUP_FROM_FIELD]
if (!guard?.setupWindowMs || (typeof from !== 'string' && !(from instanceof Date))) {return null}
const start = new Date(from).getTime()
return Number.isFinite(start) ? new Date(start + guard.setupWindowMs) : null
}
export function twoFactorSetupState({ payload, user }: MaybeReq, now: number = Date.now()): TwoFactorSetupState {
const guard = guardConfig(payload)
if (!guard || !user || typeof user !== 'object') {return 'not-applicable'}
const u = user as { collection?: unknown; hasTotp?: unknown }
if (u.collection !== guard.collection) {return 'not-applicable'}
if (u.hasTotp !== false || (user as { totpSecret?: unknown }).totpSecret) {return 'set-up'}
if (!guard.requireSetup || guard.exempt?.({ user: user as Record<string, unknown> }) === true) {return 'exempt'}
const deadline = twoFactorSetupDeadline({ payload, user })
return deadline && deadline.getTime() < now ? 'closed' : 'open'
}
type MaybeReq = { payload?: Pick<BasePayload, 'config'>; user?: unknown }
@@ -51,10 +104,11 @@ const guardConfig = (payload: MaybeReq['payload']): TwoFactorGuardConfig | undef
(payload?.config?.custom as { ipal?: { twoFactor?: TwoFactorGuardConfig } } | undefined)?.ipal?.twoFactor
/**
* False only for an account that still owes the second factor: it belongs to
* the 2FA collection, has TOTP set up and has not entered the code in this
* session. True for everyone else — no user (the access function decides),
* accounts of other auth collections, 2FA off (`twoFactor: false`).
* False for an account that still owes the second factor: it belongs to the
* 2FA collection and either has TOTP set up and has not entered the code in
* this session, or has not set TOTP up at all (unless setup is not required
* or the project exempts it). True for everyone else — no user (the access
* function decides), accounts of other auth collections, 2FA off (`twoFactor: false`).
*
* Pass `req`. Use it in your own endpoints and access functions:
* if (!secondFactorPassed(req)) return Response.json({ ok: false }, { status: 403 })
@@ -72,7 +126,10 @@ export function secondFactorPassed({ payload, user }: MaybeReq): boolean {
// "Not set up yet" only when nothing says otherwise. The package computes `hasTotp` with a second
// database read and answers false when that read fails; the secret on the user object itself (it
// came with the account's own record) then still says the account has TOTP: refused.
return u.hasTotp === false && !(user as { totpSecret?: unknown }).totpSecret
if (u.hasTotp !== false || (user as { totpSecret?: unknown }).totpSecret) {return false}
// TOTP not set up: only when setup is not required, or for an account the project exempts
// Exactly `true`: a Promise or any other truthy answer must never let an account in.
return !guard.requireSetup || guard.exempt?.({ user: user as Record<string, unknown> }) === true
}
const GUARDED = Symbol.for('ipal.secondFactorGuard')
@@ -321,6 +378,13 @@ export type TotpEndpointGuards = {
* it. Return a Response to refuse (too many attempts), null to let it through.
*/
limitVerify?: (req: never) => null | Promise<null | Response> | Response
/** The answer for an account whose setup window has passed (in the caller's language). Default: a plain 403. */
onSetupClosed?: (req: never) => Response
/**
* Whether a verify / setup attempt may come from where the browser says it comes from
* (sameOrigin.ts). False = refused, and NOT counted against the verify limit.
*/
ownOrigin?: (req: never) => boolean
}
export function guardTotpEndpoint<T extends EndpointLike>(endpoint: T, collection: string, guards: TotpEndpointGuards = {}): T {
@@ -332,6 +396,15 @@ export function guardTotpEndpoint<T extends EndpointLike>(endpoint: T, collectio
const user = req.user as { collection?: unknown } | null | undefined
if (user && user.collection !== collection) {return refused()}
if (user && !BEFORE_SECOND_FACTOR.has(endpoint.path) && !secondFactorPassed(req)) {return refused()}
// Setup after the window: blocked until an admin reopens it.
if (user && endpoint.path === '/setup-totp' && twoFactorSetupState(req) === 'closed') {
return guards.onSetupClosed ? guards.onSetupClosed(req as never) : refused()
}
// An attempt a browser marks as coming from another origin is refused before it is counted:
// otherwise another page could burn the owner's attempts and lock them out, without the password.
if (user && (endpoint.path === '/verify-totp' || endpoint.path === '/setup-totp') && guards.ownOrigin && !guards.ownOrigin(req as never)) {
return Response.json({ message: 'Not allowed from this origin.', ok: false }, { status: 403 })
}
// The code has about three right answers in a million and the package never counts tries.
if (user && endpoint.path === '/verify-totp' && guards.limitVerify) {
const limited = await guards.limitVerify(req as never)
+305
View File
@@ -0,0 +1,305 @@
import type { BasePayload, CollectionBeforeChangeHook, Endpoint, Field, PayloadRequest } from 'payload'
import { isAdmin, userMeetsRole } from '../../access/predicates.js'
import { serverText } from '../../integrations/texts.js'
import { secondFactorPassed, SETUP_FROM_FIELD } from './secondFactor.js'
/**
* "2FA setup required": the pieces ipalKit adds to the 2FA collection and the
* config when the mode is on (the default with `twoFactor`).
*
* - the date field `totpSetupFrom` — when the current setup window opened;
* - a hook that stamps it when an account is created and whenever its TOTP
* secret is cleared (an admin reset, a removal);
* - a backfill for accounts that existed before the mode (onInit);
* - POST /api/ipal/two-factor/reset — an admin clears an account's TOTP, which
* reopens its setup window;
* - the status / reset field shown on the account in the panel.
*
* The rule itself (who is refused) lives in secondFactor.ts.
*/
export type RequireSetupOptions = {
/** The notice for administrators on the dashboard (accounts without 2FA, how many are blocked). `false` = none. */
dashboardNotice?: false
/**
* Accounts that may work without TOTP on purpose — a service account that
* logs in with a password. Return **exactly `true`** to exempt, and return it
* at once: the function is called in access checks, which cannot wait. An
* `async` function stops the site at start; any other answer than `true`
* (a Promise, a string, an error thrown) exempts nobody and is logged.
* (An API key needs no exemption: it passes by itself.)
* `({ user }) => user.email === '[email protected]'`
*/
exempt?: (args: { user: Record<string, unknown> }) => boolean
/** The notice on the setup screen (until when; or that the time has passed). `false` = none. */
setupNotice?: false
/** The "Two-step verification" status and reset control on the account in the panel. `false` = none (the reset endpoint stays). */
statusField?: false
/**
* Hours an account has to set TOTP up, counted from its creation or from the
* last reset by an admin. After that it is blocked until an admin reopens
* setup. Default 72. `false` or `0` = no limit (still nothing but setup until it is done).
*/
windowHours?: false | number
}
export const DEFAULT_SETUP_WINDOW_HOURS = 72
export const TWO_FACTOR_RESET_PATH = '/ipal/two-factor/reset'
/** `twoFactor.requireSetup` → what the guard reads. */
export function resolveRequireSetup(option: false | RequireSetupOptions | undefined): {
exempt?: RequireSetupOptions['exempt']
requireSetup: boolean
setupWindowMs: number
} {
if (option === false) {return { requireSetup: false, setupWindowMs: 0 }}
// A typo must not loosen the rule: '24', -1 or NaN used to mean "no limit".
const given = option?.windowHours
if (given !== undefined && given !== false && (typeof given !== 'number' || !Number.isFinite(given) || given < 0)) {
throw new Error(
`[ipal] twoFactor.requireSetup.windowHours must be a number of hours (0 or more) or false, got ${JSON.stringify(given) ?? String(given)}. ` +
'Use 72 (the default), another number, or false / 0 for no time limit.',
)
}
const hours = given === false ? 0 : (given ?? DEFAULT_SETUP_WINDOW_HOURS)
return {
...(option?.exempt !== undefined ? { exempt: strictExempt(option.exempt) } : {}),
requireSetup: true,
setupWindowMs: hours > 0 ? hours * 60 * 60 * 1000 : 0,
}
}
/** What was already said about a wrong `exempt` answer: each kind is logged once per process. */
const exemptComplaints = new Set<string>()
/** The constructor of async functions (there is no global for it). */
const ASYNC_FUNCTION: unknown = (async () => {}).constructor
/**
* The project's `exempt`, made safe to call from an access check: only an answer of exactly
* `true` exempts. An async function is refused at start (its Promise would be truthy for every
* account — everyone let in on a password); any other answer, or an error, exempts nobody and
* is logged (once per kind of wrong answer).
*/
export function strictExempt(exempt: unknown): NonNullable<RequireSetupOptions['exempt']> {
if (typeof exempt !== 'function') {
throw new Error('[ipal] twoFactor.requireSetup.exempt must be a function: ({ user }) => boolean.')
}
// by the constructor itself, not by its name
if (exempt.constructor === ASYNC_FUNCTION) {
throw new Error(
'[ipal] twoFactor.requireSetup.exempt must not be async: it is called in access checks, which cannot wait, and a Promise ' +
'would count as "exempt" for every account. Return true or false at once (decide from the fields on `user`).',
)
}
const complain = (what: string) => {
const kind = what.replace(/\(.*\)$/, '')
if (exemptComplaints.has(kind)) {return}
exemptComplaints.add(kind)
console.error(`[ipal] twoFactor.requireSetup.exempt ${what}; it must return true or false at once. The account is NOT exempt.`)
}
return (args) => {
let answer: unknown
try {
answer = (exempt as (a: typeof args) => unknown)(args)
} catch (err) {
complain(`threw (${err instanceof Error ? err.message : String(err)})`)
return false
}
if (answer === true) {return true}
if (answer !== false && answer !== undefined && answer !== null) {
// a Promise that rejects later must not become an unhandled rejection
if (typeof (answer as { then?: unknown }).then === 'function') {void (answer as Promise<unknown>).then(undefined, () => undefined)}
complain(`returned ${typeof (answer as { then?: unknown }).then === 'function' ? 'a Promise' : `a ${typeof answer}`}`)
}
return false
}
}
/**
* The fields for the 2FA collection: the window start (data) and, unless `statusField: false`,
* its status / reset control (panel).
*
* ipalKit adds the data field **whenever 2FA is on**, also with `requireSetup: false` or
* `guard: false`: the collection's schema then does not depend on those switches — on Postgres /
* SQLite switching the mode off would otherwise drop the column with the next migration, and
* switching it on again would hand every account without TOTP a new window.
*/
export function buildSetupFields({ statusField = true }: { statusField?: boolean } = {}): Field[] {
const fields: Field[] = [
{
name: SETUP_FROM_FIELD,
type: 'date',
access: {
// Written by the hook below only — never through the API.
create: () => false,
read: ({ data, doc, req }) => isAdmin(req.user, req.payload) || Boolean(req.user && ((doc ?? data) as { id?: unknown } | undefined)?.id === req.user.id),
update: () => false,
},
admin: { disableBulkEdit: true, disableListColumn: true, disableListFilter: true, hidden: true },
label: { en: 'Two-step verification: setup open since', pl: 'Weryfikacja dwuetapowa: konfiguracja otwarta od' },
},
]
if (statusField) {
fields.push({
name: 'totpSetupStatus',
type: 'ui',
admin: {
components: { Field: '@intecion/ipal-kit/admin#TwoFactorStatusField' },
disableListColumn: true,
position: 'sidebar',
},
})
}
return fields
}
/**
* Stamps `totpSetupFrom`: on create, and when an account that had TOTP loses
* its secret (the 2FA package's own remove / admin endpoints). The reset
* endpoint below writes the date itself, so it also reopens the window of an
* account that never had TOTP. Neither field can be written through the API
* (field access), so only server code gets here with them.
*/
export const stampSetupFrom: CollectionBeforeChangeHook = ({ data, operation, originalDoc }) => {
if (!data) {return data}
const hadTotp = Boolean((originalDoc as { totpSecret?: unknown } | undefined)?.totpSecret)
if (operation === 'create' ? !data[SETUP_FROM_FIELD] : hadTotp && 'totpSecret' in data && !data.totpSecret) {
data[SETUP_FROM_FIELD] = new Date().toISOString()
}
return data
}
/**
* Accounts that existed before the mode have no `totpSetupFrom`. Their window
* starts now — at the first start after the upgrade — so nobody is blocked the
* moment a site upgrades: each such account gets the full window to set TOTP
* up. Runs on every start; after the first there is nothing left to do.
* Returns how many accounts it stamped; never throws (a database that has not
* been migrated yet must not stop the site).
*/
export async function backfillSetupFrom(payload: BasePayload, collection: string): Promise<number> {
try {
const where = {
and: [
{ or: [{ totpSecret: { exists: false } }, { totpSecret: { equals: '' } }] },
{ [SETUP_FROM_FIELD]: { exists: false } },
],
}
const { totalDocs } = await payload.count({ collection: collection as never, overrideAccess: true, where: where as never })
if (!totalDocs) {return 0}
const data = { [SETUP_FROM_FIELD]: new Date().toISOString() }
// One query where the adapter has it (Payload 3.9x); the Local API otherwise. Hooks have nothing to add here.
if (typeof payload.db.updateMany === 'function') {
await payload.db.updateMany({ collection: collection as never, data: data as never, where: where as never })
} else {
await payload.update({ collection: collection as never, data: data as never, overrideAccess: true, where: where as never })
}
return totalDocs
} catch (err) {
// The whole chain: Drizzle's own message is "Failed query: …", and what the database said
// ("column … does not exist", "no such column") is in `cause`.
const reason = errorChain(err)
// On Postgres / SQLite without the migration the column is missing — and then it is not only this step
// that fails: every query on the collection selects the column, so EVERY login answers 500 until it exists.
// Only the missing column gets this message — a database that cannot be reached is another problem.
if (/column .+ does not exist|no such column|unknown column|has no column/i.test(reason)) {
payload.logger.error(
`[ipal] 2FA: the column for "${SETUP_FROM_FIELD}" is missing on "${collection}" (${reason}). NOBODY CAN LOG IN to the panel until the ` +
'migration that adds it has run — administrators with 2FA included. Run `pnpm payload migrate:create`, commit the migration, and ' +
'have it applied when the new container starts (`prodMigrations` in the database adapter, or `pnpm payload migrate && pnpm start`) — ' +
'not in a pre-deployment command, which runs in the old container (docs/deployment.md §4.3, docs/security.md "Setup required" → Data).',
)
} else {
payload.logger.warn(`[ipal] 2FA: could not start the setup window for existing accounts (${reason}).`)
}
return 0
}
}
/** The messages of an error and of everything in its `cause` chain, outermost first. */
export function errorChain(err: unknown): string {
const parts: string[] = []
const seen = new Set<unknown>()
for (let current: unknown = err; current !== undefined && current !== null && !seen.has(current) && parts.length < 6; current = (current as { cause?: unknown }).cause) {
seen.add(current)
const message = current instanceof Error || typeof (current as { message?: unknown }).message === 'string' ? String((current as { message: unknown }).message) : typeof current === 'string' ? current : ''
if (message && !parts.includes(message)) {parts.push(message)}
if (typeof current !== 'object') {break}
}
return parts.join(' — ') || String(err)
}
export type TwoFactorResetOptions = {
/**
* Who may reset another account's TOTP. Default: a staff admin whose session has **entered its
* TOTP code** (`_strategy: 'totp'`) — not an API key, and not an account `requireSetup.exempt`
* lets work on its password. With your own function the session must still not owe a second
* factor (`secondFactorPassed`), and the rest is yours: an API-key or exempt admin passes only
* if you return true for it (`req.user._strategy` tells them apart).
*/
access?: (args: { req: PayloadRequest }) => boolean | Promise<boolean>
}
/**
* POST /api/ipal/two-factor/reset `{ userId }` — clears that account's TOTP
* secret **and its sessions**. The account must log in and set TOTP up again,
* and its setup window starts anew. For a lost phone, and to reopen setup for
* an account whose window has passed. Admins only, and only after their own
* TOTP code.
*
* The sessions go because a reset is also what an administrator presses for an
* account that may be in someone else's hands: a session that had passed 2FA
* would otherwise be a password-less way to enrol a new authenticator
* (`/api/setup-totp` asks for no password). With `auth.useSessions: false`
* there is nothing to clear — tokens then live until they expire.
*/
export function buildTwoFactorResetEndpoint(collection: string, options: TwoFactorResetOptions = {}): Endpoint {
return {
handler: async (req) => {
const i18n = req.i18n as Parameters<typeof serverText>[0]
const allowed =
Boolean(req.user) &&
secondFactorPassed(req) &&
(req.user as { collection?: unknown }).collection === collection &&
(options.access
? (await options.access({ req })) === true
: (req.user as { _strategy?: unknown })._strategy === 'totp' && userMeetsRole(req, 'admin'))
if (!allowed) {return Response.json({ message: serverText(i18n, 'twoFactorResetForbidden'), ok: false }, { status: 403 })}
let body: unknown
try {
body = await req.json?.()
} catch {
body = undefined
}
const userId = (body as { userId?: unknown } | undefined)?.userId
if (typeof userId !== 'string' && typeof userId !== 'number') {
return Response.json({ message: serverText(i18n, 'twoFactorResetFailed'), ok: false }, { status: 400 })
}
try {
const useSessions = (req.payload.collections as Record<string, { config?: { auth?: { useSessions?: boolean } } }>)[collection]?.config?.auth?.useSessions !== false
const data = { [SETUP_FROM_FIELD]: new Date().toISOString(), totpSecret: null, ...(useSessions ? { sessions: [] } : {}) }
await req.payload.update({ id: userId, collection: collection as never, data: data as never, overrideAccess: true, req })
} catch (err) {
req.payload.logger.error(`[ipal] 2FA reset failed: ${err instanceof Error ? err.message : String(err)}`)
return Response.json({ message: serverText(i18n, 'twoFactorResetFailed'), ok: false }, { status: 400 })
}
const actor = (req.user as { email?: string; id?: unknown }).email ?? String((req.user as { id?: unknown }).id)
req.payload.logger.info(`[ipal] 2FA reset for ${collection} ${String(userId)} by ${actor}.`)
return Response.json({ message: serverText(i18n, 'twoFactorResetDone'), ok: true })
},
method: 'post',
path: TWO_FACTOR_RESET_PATH,
}
}
/** Accounts of the 2FA collection without TOTP, and how many of those are past their setup window. */
export async function countAccountsWithoutTotp(payload: BasePayload, collection: string, setupWindowMs = 0): Promise<{ blocked: number; without: number }> {
const none = { or: [{ totpSecret: { exists: false } }, { totpSecret: { equals: '' } }] }
const without = (await payload.count({ collection: collection as never, overrideAccess: true, where: none as never })).totalDocs
if (!without || !setupWindowMs) {return { blocked: 0, without }}
const limit = new Date(Date.now() - setupWindowMs).toISOString()
const blocked = (await payload.count({ collection: collection as never, overrideAccess: true, where: { and: [none, { [SETUP_FROM_FIELD]: { less_than: limit } }] } as never })).totalDocs
return { blocked, without }
}
+48 -5
View File
@@ -13,12 +13,24 @@ import { serverText } from '../../integrations/texts.js'
* already passed the password reaches the endpoint, so someone without the
* password cannot use the limit to lock an account's owner out.
*
* In memory, per server instance, and always enforced (no "allow when the
* store fails" path): with several instances the limit is per instance.
* Counted twice, and the higher count decides:
* - **in memory**, per server instance — exact also for a burst of parallel requests
* (the count is taken before anything is awaited);
* - **in the database** (Payload's key-value store, `payload.kv` — the `payload-kv`
* collection Payload itself adds; no new collection, no migration of ours), so the count
* survives a restart or redeploy and is shared between instances. `store: 'memory'`
* leaves this part out.
* Always enforced: when the database part fails, the memory count still decides — there is
* no "allow when the store fails" path. Two instances can each let a few attempts through
* before the other's write lands; the bound is then "max per instance", never "no limit".
*
* Requests a browser marks as coming from another origin never get here (sameOrigin.ts).
*/
export type VerifyLimitOptions = {
/** Attempts per account in the window. Default 5. */
max?: number
/** Where the count is kept besides the instance's memory. Default `'database'`; `'memory'` = this instance only. */
store?: 'database' | 'memory'
/** Window in minutes; a refused account waits until it ends. Default 10. */
windowMinutes?: number
}
@@ -31,11 +43,37 @@ export function clearVerifyLimits(): void {
buckets.clear()
}
type KV = { get: (key: string) => Promise<unknown>; set: (key: string, value: object) => Promise<void> }
let warnedStore = false
/** Key of an account's stored count in `payload.kv`. */
export const verifyLimitKey = (collection: string, id: string) => `ipal:2fa-verify:${collection}:${id}`
/** Counts one attempt in the database and returns the stored bucket; null when there is no store or it fails. */
async function hitStored(payload: { kv?: unknown; logger?: { warn: (m: string) => void } }, key: string, windowMs: number, now: number): Promise<Bucket | null> {
const kv = payload.kv as KV | undefined
if (typeof kv?.get !== 'function' || typeof kv?.set !== 'function') {return null}
try {
const current = (await kv.get(key)) as Bucket | null
const valid = current && typeof current.count === 'number' && typeof current.resetAt === 'number' && current.resetAt > now
const next: Bucket = valid ? { count: current.count + 1, resetAt: current.resetAt } : { count: 1, resetAt: now + windowMs }
await kv.set(key, next)
return next
} catch (err) {
if (!warnedStore) {
warnedStore = true
payload.logger?.warn(`[ipal] 2FA: the verify limit could not be stored (${err instanceof Error ? err.message : String(err)}); counting in memory only.`)
}
return null
}
}
export function buildVerifyLimit(collection: string, options: VerifyLimitOptions = {}) {
const max = Number.isFinite(options.max) && options.max! > 0 ? Math.floor(options.max!) : 5
const windowMs = (Number.isFinite(options.windowMinutes) && options.windowMinutes! > 0 ? options.windowMinutes! : 10) * 60_000
const stored = options.store !== 'memory'
return (req: PayloadRequest): null | Response => {
return async (req: PayloadRequest): Promise<null | Response> => {
// No session: the package refuses by itself, and there is no account to count against.
if (!req.user) {return null}
// Whatever the id looks like, it is one bucket per value — never "no limit".
@@ -53,8 +91,13 @@ export function buildVerifyLimit(collection: string, options: VerifyLimitOptions
const bucket = current && current.resetAt > now ? current : { count: 0, resetAt: now + windowMs }
bucket.count += 1
buckets.set(key, bucket)
if (bucket.count <= max) {return null}
const retryAfter = Math.max(1, Math.ceil((bucket.resetAt - now) / 1000))
// This attempt's own number, taken now: the bucket is shared and keeps growing while we wait below.
const mine: Bucket = { count: bucket.count, resetAt: bucket.resetAt }
// …and in the database, so a restart or another instance does not start from zero. The higher count decides.
const kept = stored ? await hitStored(req.payload as never, verifyLimitKey(collection, id), windowMs, now) : null
const worst = kept && kept.count > mine.count ? kept : mine
if (worst.count <= max) {return null}
const retryAfter = Math.max(1, Math.ceil((worst.resetAt - now) / 1000))
req.payload.logger.warn(`[ipal] 2FA: too many verify attempts for ${collection} ${id}; refused for ${retryAfter} s.`)
return Response.json(
{ message: serverText(req.i18n as never, 'twoFactorTooManyAttempts', { minutes: Math.ceil(retryAfter / 60) }), ok: false },
+25 -1
View File
@@ -19,6 +19,27 @@ export type TurnstileConfig = {
}
let warnedPartial = false
let warnedEnvSecret = false
/**
* True when the secret key in use comes from the environment (`TURNSTILE_SECRET_KEY`) because
* the panel field is empty. **Deprecated:** the panel is the source of the secret; the
* environment value keeps working for now and will be removed in a later, announced release.
*/
export function turnstileSecretFromEnv(integrations: IntegrationsWithTurnstileKeys): boolean {
return !integrations.turnstileSecretKey?.trim() && Boolean(process.env[TURNSTILE_SECRET_ENV]?.trim())
}
/** Says once per process that the secret came from the environment (see turnstileSecretFromEnv). */
export function warnTurnstileEnvSecret(integrations: IntegrationsWithTurnstileKeys): void {
if (warnedEnvSecret || !turnstileSecretFromEnv(integrations)) {return}
warnedEnvSecret = true
console.warn(
`[ipal] Deprecated: the Turnstile secret key comes from the ${TURNSTILE_SECRET_ENV} environment variable. ` +
'Put it into Site integrations → Spam protection → Secret key (the panel is the source of this secret). ' +
'The environment value keeps working for now and will be removed in a later release, named in the changelog.',
)
}
function resolveKeys(integrations: IntegrationsWithTurnstileKeys) {
return {
@@ -69,7 +90,10 @@ export async function getTurnstileConfig(payload: BasePayload): Promise<Turnstil
const integrations = await getSiteIntegrations<IntegrationsWithTurnstileKeys>(payload)
const { secret, siteKey } = resolveKeys(integrations)
if (siteKey && secret) {return { enabled: true, siteKey }}
if (siteKey && secret) {
warnTurnstileEnvSecret(integrations)
return { enabled: true, siteKey }
}
if ((siteKey || secret) && !warnedPartial) {
warnedPartial = true
+1 -1
View File
@@ -83,7 +83,7 @@ const LOG_DETAIL: Record<string, string> = {
/**
* Verifies a Turnstile token with Cloudflare and classifies the result (server-only).
*
* Secret: SiteIntegrations → Turnstile (panel) first, then TURNSTILE_SECRET_KEY.
* Secret: SiteIntegrations → Turnstile (panel) first, then TURNSTILE_SECRET_KEY (deprecated: turnstile/config.ts).
* Every result is logged when not `pass`, and the integration status on
* SiteIntegrations is updated (throttled) so the panel shows failures.
*/
+193 -6
View File
@@ -2,6 +2,7 @@ import type { BasePayload, Config, PayloadRequest, Plugin } from 'payload'
import { deepMergeSimple } from 'payload/shared'
import type { AccountsOptions, Role } from './modules/access/types.js'
import type { ResolvedAdminMeta } from './modules/branding/adminMeta.js'
import type { IpalOptions, TotpPluginFactory } from './types.js'
@@ -12,6 +13,10 @@ import { applyGlobalOverrides } from './globals/overrides.js'
import { buildSiteIntegrations } from './globals/SiteIntegrations/index.js'
import { buildSiteSettings } from './globals/SiteSettings/index.js'
import { adminOnly, adminOrSelfIn, injectRoles, registerStaffCollections, staffCollectionSlugs } from './modules/access/index.js'
import { applyPanelRole, countBelowPanelRole, resolvePanelRole } from './modules/access/panelRole.js'
import { applyPasswordRule, buildPasswordRuleHook, resolvePasswordRule } from './modules/access/passwordRule.js'
import { adoptLateAuthCollections, applyFirstUserRoute, applyStaffAccountAccess, markSeenAuthCollections, unknownStaffCollections } from './modules/access/selfRegistration.js'
import { ROLE_HIERARCHY } from './modules/access/types.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'
@@ -32,9 +37,11 @@ import { buildFormsPlugin } from './modules/forms/formsPluginConfig.js'
import { buildGlobalRevalidateHook } from './modules/hooks/buildRevalidateHook.js'
import { withFillLocales } from './modules/hooks/fillEmptyLocales.js'
import { buildLocalizationConfig, validateI18nConfig } from './modules/i18n/index.js'
import { serverText } from './modules/integrations/texts.js'
import { buildSystemPagesFields } from './modules/pages/index.js'
import { missingImportMapEntries } from './modules/security/totp/importMapCheck.js'
import { changedViewKeys, copyViews, SAFE_TOTP_VIEW, wrapTotpViews } from './modules/security/totp/safeBack.js'
import { reportRefusedOrigin, requestFromOwnOrigin } from './modules/security/totp/sameOrigin.js'
import {
buildGuardStrategy,
ensurePayloadGuarded,
@@ -45,6 +52,7 @@ import {
passOptOutsToPackage,
watchPayloadConfig,
} from './modules/security/totp/secondFactor.js'
import { backfillSetupFrom, buildSetupFields, buildTwoFactorResetEndpoint, resolveRequireSetup, stampSetupFrom } from './modules/security/totp/setupRequired.js'
import { TOTP_TEXTS, TOTP_VIEW_TITLE } from './modules/security/totp/totpTexts.js'
import { buildVerifyLimit } from './modules/security/totp/verifyLimit.js'
import { buildSeoPlugin, injectAutoFillMeta, injectSeoTabs } from './modules/seo/index.js'
@@ -185,10 +193,49 @@ export const ipalKit = (options: IpalOptions): Plugin => {
const adoptConfig = (payload: BasePayload) => {
const token = (payload.config.custom as { ipal?: { staffToken?: object } } | undefined)?.ipal?.staffToken
registerStaffCollections(payload, staffCollectionSlugs(payload), token)
// Auth collections a plugin listed after ipalKit added: the account rules for them too — BEFORE the
// 2FA guard below wraps their access (it needs the rule inside its wrapper).
if (accounts) {
const rule = resolvePasswordRule(accounts.password)
// `payload.config`, not `payload.collections`: on a dev reload Payload swaps the config first, and
// `payload.collections` still holds the old one at this moment.
const lateAccounts = adoptLateAuthCollections(payload.config as never, staffCollectionSlugs(payload), {
access: { ...accountAccess, pluginRoles: [] },
beforeOperation: rule ? buildPasswordRuleHook(rule) : undefined,
firstUserRoute: accounts.firstUserRoute,
})
// said exactly: what was put, on which collection
for (const late of lateAccounts) {
const parts = [late.applied.length ? `access rules for ${late.applied.join(', ')}` : '', late.password ? 'the password rule' : '', late.firstUser ? 'the first-user endpoint' : ''].filter(Boolean)
payload.logger.info(`[ipal] "${late.slug}" was added after ipalKit: put on it — ${parts.join('; ')}.`)
}
}
if (!secondFactorGuard) {return}
const late = ensurePayloadGuarded(payload)
if (late?.length) {payload.logger.info(`[ipal] 2FA also enforced on entities added after ipalKit: ${late.join(', ')}.`)}
}
/** 2FA collection when "setup required" is on — its existing accounts get their setup window in onInit. */
let setupRequiredFor: null | string = null
let setupWindowHours = 0
/** accounts.panelRole in force: the collection and the role, for the start-up line. */
let panelRoleFor: { role: Role; slug: string } | null = null
/** Why the default panel role was not applied (said once at start). */
let panelRoleSkipped: null | string = null
/** `accounts: false` turns every account rule off. */
const accounts: AccountsOptions | null = options.accounts === false ? null : (options.accounts ?? {})
/** Which of the staff defaults are on (accounts.adminOnlyCreate / adminOnlyWrite / staffOnlyRead). */
const accountAccess = { create: accounts?.adminOnlyCreate !== false, read: accounts?.staffOnlyRead !== false, write: accounts?.adminOnlyWrite !== false }
/** requireSetup.setupNotice / statusField (on unless switched off). */
let setupNotice = true
let statusField = false
// Account rules (accounts.*): nobody creates an account for themselves, or takes one over.
// BEFORE the 2FA package: it gives every collection a create / update / delete function of
// its own, and afterwards a missing rule cannot be told from one the project wrote.
if (accounts) {
const panelSlug = config.admin?.user ?? (config.collections ?? []).find((c) => c.auth)?.slug
const staffSlugs = [...new Set([panelSlug, options.access?.authCollection, ...(options.access?.staffCollections ?? [])].filter((s): s is string => Boolean(s)))]
config = applyStaffAccountAccess(config, staffSlugs, { ...accountAccess, pluginRoles: options.access?.authCollection ? [options.access.authCollection] : [] })
}
if (options.twoFactor !== false) {
const tf = options.twoFactor
if (!tf?.issuer) {
@@ -257,12 +304,30 @@ export const ipalKit = (options: IpalOptions): Plugin => {
// Only accounts of the 2FA collection may use them (guardTotpEndpoint) —
// whatever the package registered, also paths a later version adds.
const limitVerify = tf.verifyLimit === false ? undefined : buildVerifyLimit(target, tf.verifyLimit)
const guards = limitVerify ? { limitVerify: (req: PayloadRequest) => limitVerify(req) } : {}
const extraOrigins = typeof tf.sameOrigin === 'object' ? (tf.sameOrigin.origins ?? []) : []
const guards = {
...(limitVerify ? { limitVerify: (req: PayloadRequest) => limitVerify(req) } : {}),
...(tf.sameOrigin === false
? {}
: {
ownOrigin: (req: PayloadRequest) => {
if (requestFromOwnOrigin(req as never, extraOrigins)) {return true}
reportRefusedOrigin(req as never, extraOrigins) // never in silence: once per origin, with the ways to allow it
return false
},
}),
onSetupClosed: (req: PayloadRequest) =>
Response.json({ message: serverText(req.i18n as never, 'twoFactorSetupClosed'), ok: false }, { status: 403 }),
}
config.endpoints = (config.endpoints ?? []).map((e) => (endpointsBefore.has(e) ? e : guardTotpEndpoint(e, target, guards as never)))
// …and the same for endpoints it may put on a collection or a global.
config.collections = guardNewEntityEndpoints(config.collections, entityEndpointsBefore, target, guards as never)
config.globals = guardNewEntityEndpoints(config.globals, entityEndpointsBefore, target, guards as never)
twoFactorCollection = target
// The window-start field is part of the 2FA collection whenever 2FA is on — the schema must
// not depend on requireSetup / guard (setupRequired.ts, buildSetupFields). The panel's status
// field joins it below, when the mode is on. Validates requireSetup at start either way.
if (tf.requireSetup !== false) {resolveRequireSetup(tf.requireSetup)}
// The views the 2FA package registered, by object: it REPLACES a view the project (or an
// earlier run of the package, or of ipalKit) already had under its keys, so a key that
// existed before is no sign that the view is the project's own. Taken here, before the
@@ -286,7 +351,36 @@ export const ipalKit = (options: IpalOptions): Plugin => {
)
}
secondFactorGuard = true
config.custom = { ...config.custom, ipal: { ...config.custom?.ipal, twoFactor: { collection: target } } }
// "Setup required" (default): an account without TOTP reaches nothing but the setup
// screen, and only within the window; requireSetup: false = the package's rule.
const setup = resolveRequireSetup(tf.requireSetup)
const setupParts = tf.requireSetup && typeof tf.requireSetup === 'object' ? tf.requireSetup : {} // null = the default, like undefined
config.custom = { ...config.custom, ipal: { ...config.custom?.ipal, twoFactor: { collection: target, ...setup } } }
if (setup.requireSetup) {
setupRequiredFor = target
setupWindowHours = setup.setupWindowMs / 3_600_000
setupNotice = setupParts.setupNotice !== false
statusField = setupParts.statusField !== false
// The stamp hook only while the mode is on: an account made while it is off gets its
// window when the mode is switched on (the start-up step), not a creation date long past.
config.collections = (config.collections ?? []).map((c) =>
c.slug === target ? { ...c, hooks: { ...c.hooks, beforeChange: [...(c.hooks?.beforeChange ?? []), stampSetupFrom] } } : c,
)
if (setupParts.dashboardNotice !== false) {
config.admin = {
...config.admin,
components: {
...config.admin?.components,
beforeDashboard: [
...(config.admin?.components?.beforeDashboard ?? []),
{ path: '@intecion/ipal-kit/admin#TwoFactorAlert', serverProps: { adminRoute: options.adminRoute ?? '/admin' } },
],
},
}
}
}
// An admin resets an account's TOTP (lost phone) / reopens its setup window.
config.endpoints = [...(config.endpoints ?? []), buildTwoFactorResetEndpoint(target, { access: tf.resetAccess })]
// Called by Payload on every request before any access function: guards whatever
// the live config has that was added after ipalKit (start, dev hot reload).
const sweep = buildGuardStrategy(adoptConfig)
@@ -297,6 +391,11 @@ export const ipalKit = (options: IpalOptions): Plugin => {
)
}
// The window start (data) whenever 2FA is on; the status / reset control when the mode is.
config.collections = (config.collections ?? []).map((c) =>
c.slug === target ? { ...c, fields: [...c.fields, ...buildSetupFields({ statusField })] } : c,
)
// The package's texts are long and informal: ipal-kit's (admin-ux.md) go over
// them, the project's own i18n.translations over both. The 2FA screens get a
// tab title instead of "Payload" (view meta is a plain string: the site's language).
@@ -342,7 +441,7 @@ export const ipalKit = (options: IpalOptions): Plugin => {
p && (typeof p === 'string' ? p : p.path) === TOTP_PACKAGE_PROVIDER
? {
...ours,
clientProps: { forceSetup: true, ...ours.clientProps },
clientProps: { forceSetup: true, ...(setupRequiredFor && setupNotice ? { requireSetup: true, setupWindowHours } : {}), ...ours.clientProps },
serverProps: { ...(typeof p === 'object' ? p.serverProps : {}), ...ours.serverProps },
}
: p,
@@ -408,6 +507,7 @@ export const ipalKit = (options: IpalOptions): Plugin => {
const serverProps: Record<string, unknown> = {}
if (wl.settingsSlug) {serverProps.settingsSlug = wl.settingsSlug}
if (wl.nameField) {serverProps.nameField = wl.nameField}
if (wl.inlineImages === false) {serverProps.inlineImages = false}
const logoProps = { ...serverProps, ...(wl.logoField ? { imageField: wl.logoField } : {}) }
const iconProps = { ...serverProps, ...(wl.iconField ? { imageField: wl.iconField } : {}) }
@@ -480,6 +580,7 @@ export const ipalKit = (options: IpalOptions): Plugin => {
iconField: brandFields.iconField,
logoField: brandFields.logoField,
nameField: brandFields.nameField,
serveIcon: options.adminMeta?.serveIcon,
settingsSlug,
}),
]
@@ -498,6 +599,36 @@ export const ipalKit = (options: IpalOptions): Plugin => {
// for accounts of a staff collection (staffCollectionSlugs).
const staff = [...new Set([options.access.authCollection, ...(options.access.staffCollections ?? [])])]
config.custom = { ...config.custom, ipal: { ...config.custom?.ipal, staffCollections: staff } }
// Account rules (accounts.*): the lowest role stays out of the panel.
let panelRole = accounts ? resolvePanelRole(accounts.panelRole) : null
const rolesSlug = options.access.authCollection
// With firstUserAdmin: false the first account gets the default role. Below the panel
// role, a fresh site would have nobody who can open the panel — and nobody to raise a role.
const firstRole = options.access.defaultRole ?? 'user'
if (panelRole && options.access.firstUserAdmin === false && ROLE_HIERARCHY.indexOf(firstRole) < ROLE_HIERARCHY.indexOf(panelRole)) {
if (accounts?.panelRole !== undefined) {
throw new Error(
`[ipal] access.firstUserAdmin: false with accounts.panelRole: '${panelRole}' leaves a fresh site with nobody who can open the panel: ` +
`the first account gets the role '${firstRole}', which is below the panel role. Set access.defaultRole to '${panelRole}' or higher, ` +
"or accounts: { panelRole: false }, or drop access.firstUserAdmin: false (docs/access.md \"Account rules\").",
)
}
panelRoleSkipped = `access.firstUserAdmin is false and the first account gets the role '${firstRole}'`
panelRole = null
}
// the project's own access.admin (or access.authAccess.admin) wins
if (panelRole && !(config.collections ?? []).find((c) => c.slug === rolesSlug)?.access?.admin) {
config = applyPanelRole(config, rolesSlug, panelRole)
panelRoleFor = { slug: rolesSlug, role: panelRole }
}
}
// Account rules (accounts.*): nobody creates an account for themselves.
if (accounts) {
const panelSlug = config.admin?.user ?? (config.collections ?? []).find((c) => c.auth)?.slug
const staffSlugs = [...new Set([panelSlug, options.access?.authCollection, ...(options.access?.staffCollections ?? [])].filter((s): s is string => Boolean(s)))]
config = applyFirstUserRoute(config, accounts.firstUserRoute)
const passwordRule = resolvePasswordRule(accounts.password)
if (passwordRule) {config = applyPasswordRule(config, staffSlugs, passwordRule)}
}
// For predicates called without `req.payload` (isAdmin(req.user) in a hook): what this config
// says now, under a token; the Payload instance takes the entry over when the config goes live
@@ -535,6 +666,11 @@ export const ipalKit = (options: IpalOptions): Plugin => {
if (options.forms.consentFieldName) {
config.custom = { ...config.custom, ipal: { ...config.custom?.ipal, consentFieldName: options.forms.consentFieldName } }
}
// what a form does while Turnstile cannot check — read by passTurnstile when the call site gives none
if (options.forms.turnstileOnConfigError) {
const ipal = (config.custom?.ipal ?? {}) as { forms?: object }
config.custom = { ...config.custom, ipal: { ...ipal, forms: { ...ipal.forms, turnstileOnConfigError: options.forms.turnstileOnConfigError } } }
}
}
// --- globals ---
@@ -560,7 +696,11 @@ export const ipalKit = (options: IpalOptions): Plugin => {
: { searchFields: typeof searchSettings === 'function' ? searchSettings(searchSettingsFields) : searchSettingsFields }),
systemPageFields,
}),
buildSiteIntegrations({ additionalFields: options.integrationsFields }),
buildSiteIntegrations({
additionalFields: options.integrationsFields,
reenterSecretOnChange: options.secrets?.reenterOnChange !== false,
writeOnlySecrets: options.secrets?.writeOnly !== false,
}),
withFillLocales('global', buildCookieSettings(), fillLocales['cookie-settings']),
buildNotifications({ lightbox: options.lightbox === true }),
]
@@ -673,7 +813,7 @@ export const ipalKit = (options: IpalOptions): Plugin => {
...(config.admin?.components ?? {}),
beforeDashboard: [
...(config.admin?.components?.beforeDashboard ?? []),
{ path: '@intecion/ipal-kit/admin#CookieCrawlAlert', serverProps: { adminRoute, approval: alertApproval, crawl: alertCrawl, labels } },
{ path: '@intecion/ipal-kit/admin#CookieCrawlAlert', serverProps: { adminRoute, approval: alertApproval, crawl: alertCrawl, labels, ...(options.dashboardAlerts?.cookies ? { audience: options.dashboardAlerts.cookies } : {}) } },
],
},
}
@@ -741,7 +881,7 @@ export const ipalKit = (options: IpalOptions): Plugin => {
...(config.admin?.components?.beforeDashboard ?? []),
{
path: '@intecion/ipal-kit/admin#IntegrationAlerts',
serverProps: { adminRoute: options.adminRoute ?? '/admin' },
serverProps: { adminRoute: options.adminRoute ?? '/admin', ...(options.dashboardAlerts?.integrations ? { details: options.dashboardAlerts.integrations } : {}) },
},
],
},
@@ -758,6 +898,16 @@ export const ipalKit = (options: IpalOptions): Plugin => {
const incomingOnInit = config.onInit
config.onInit = async (payload) => {
if (incomingOnInit) {await incomingOnInit(payload)}
// A staff collection that does not exist protects nothing and hides a typo: its accounts would not be staff,
// or — worse — a collection of that name added later would be, without anyone having decided it.
const unknownStaff = unknownStaffCollections(payload.config as never, [...new Set([options.access?.authCollection, ...(options.access?.staffCollections ?? [])].filter((s): s is string => Boolean(s)))])
if (unknownStaff.length) {
throw new Error(
`[ipal] access names ${unknownStaff.map((s) => `"${s}"`).join(', ')} as a staff collection, but this config has no auth collection with that slug ` +
`(auth collections: ${payload.config.collections.filter((c) => c.auth).map((c) => c.slug).join(', ') || 'none'}). ` +
'Fix the slug in access.authCollection / access.staffCollections, or add the collection (docs/access.md "Who is staff").',
)
}
adoptConfig(payload)
// Payload's dev reload swaps `payload.config` and runs no onInit: adopt the new config at once.
watchPayloadConfig(payload, adoptConfig)
@@ -779,12 +929,49 @@ export const ipalKit = (options: IpalOptions): Plugin => {
)
}
}
if (panelRoleSkipped) {
payload.logger.warn(
`[ipal] The panel role (accounts.panelRole, 'editor' by default) is NOT applied: ${panelRoleSkipped}, so nobody could open the panel on a fresh site. ` +
'Every account of the login collection can open the panel. To keep the lowest role out, set access.defaultRole to \'editor\' or drop access.firstUserAdmin: false (docs/access.md "Account rules").',
)
}
// The panel role: tell a site how many of its accounts the rule keeps out of the panel.
if (panelRoleFor) {
try {
const { all, below } = await countBelowPanelRole(payload, panelRoleFor.slug, panelRoleFor.role)
if (all && below === all) {
payload.logger.error(
`[ipal] No account of "${panelRoleFor.slug}" has the role "${panelRoleFor.role}" or higher, so NOBODY can open the admin panel ` +
'(accounts.panelRole). Give an account the role with a script (payload.update, Local API), or set accounts: { panelRole: false } and redeploy (docs/access.md "Account rules").',
)
} else if (below) {
payload.logger.warn(
`[ipal] ${below} account(s) of "${panelRoleFor.slug}" are below the role "${panelRoleFor.role}" and cannot open the admin panel ` +
'(accounts.panelRole). Give them a higher role, or set accounts: { panelRole: \'user\' } (docs/access.md "Account rules").',
)
}
} catch {
/* a database that is not ready must not stop the start */
}
}
// Accounts from before "setup required": their window starts now, not at their creation date.
if (setupRequiredFor) {
const started = await backfillSetupFrom(payload, setupRequiredFor)
if (started) {
payload.logger.warn(
`[ipal] 2FA: ${started} existing account(s) without two-step verification. ` +
(setupWindowHours ? `They have ${setupWindowHours} h from now to set it up; after that an administrator must reopen setup.` : 'They cannot use the panel until they set it up.'),
)
}
}
await migrateCookieSettingsSaveButton(payload)
await migrateTitleSeparator(payload, settingsSlug)
if (adminMeta) {await syncAdminMeta(payload, adminMeta, { nameField: brandFields.nameField, settingsSlug })}
payload.logger.info('[ipal] Plugin initialized.')
}
// Every auth collection of this config has been seen: what appears later is a late one (adoptConfig).
if (accounts) {config = markSeenAuthCollections(config)}
return config
}
}
+82 -8
View File
@@ -1,4 +1,4 @@
import type { CollectionSlug, Field, PayloadComponent, Plugin } from 'payload'
import type { CollectionSlug, Field, PayloadComponent, PayloadRequest, Plugin } from 'payload'
/**
* Factory shape of @clocklimited/payload-2fa's `payloadTotp` export — injected
@@ -13,7 +13,7 @@ export type TotpPluginFactory = (options: {
totp: { issuer: string }
}) => Plugin
import type { GlobalOverrides } from './globals/overrides.js'
import type { AccessOption } from './modules/access/types.js'
import type { AccessOption, AccountsOptions } from './modules/access/types.js'
import type { AdminMetaOptions, AgencyOption } from './modules/branding/adminMeta.js'
import type { ConsentLogOptions } from './modules/consent/consentLog.js'
import type { CookieScannerOptions } from './modules/consent/scanner/types.js'
@@ -24,6 +24,7 @@ import type { RevalidatePathFn } from './modules/hooks/buildRevalidateHook.js'
import type { I18nConfig } from './modules/i18n/types.js'
import type { PagesOption } from './modules/pages/types.js'
import type { SafeBackRule } from './modules/security/totp/safeBack.js'
import type { RequireSetupOptions } from './modules/security/totp/setupRequired.js'
import type { VerifyLimitOptions } from './modules/security/totp/verifyLimit.js'
import type { SeoOption } from './modules/seo/types.js'
import type { StatsOptions } from './modules/stats/collection.js'
@@ -38,6 +39,11 @@ export type IpalOptions = {
* (admin > editor > user) into the client's auth collection.
*/
access?: AccessOption
/**
* Rules for the accounts of the staff collection: who may open the panel
* (`panelRole`). `false` = none of them. docs/access.md "Account rules".
*/
accounts?: AccountsOptions | false
/**
* Admin panel <head> for link previews and search engines (default on):
@@ -95,6 +101,24 @@ export type IpalOptions = {
*/
cookieScanner?: boolean | CookieScannerOptions
/**
* Forms — form-builder collections (forms, form-submissions) plus the
* callable submitForm (Turnstile + persistence + SMTP-from-panel email).
*/
/**
* Who sees the plugin's dashboard alerts. They read data that only some
* roles may read, so each decides for itself:
* `integrations` — who gets WHAT is failing in Site integrations (error text
* and link): `'admin'` (default), `'editor'`, `'all'`; an editor below that
* sees a neutral "an integration needs attention — ask an administrator",
* anyone else nothing. `cookies` — who sees the cookie crawl / approval
* alert: `'editor'` (default) or `'all'`. With a role (`'admin'`,
* `'editor'`) a session that still owes its second factor sees nothing.
* `'all'` = as before, and it checks NOTHING — no role and no second
* factor: whoever the dashboard is drawn for sees the full text.
*/
dashboardAlerts?: { cookies?: 'all' | 'editor'; integrations?: 'admin' | 'all' | 'editor' }
/**
* GET /api/ipal/doctor — read-only counts for `ipal-doctor --url` (users without 2FA, cookies
* waiting for approval, versions). Answers 404 until IPAL_DOCTOR_TOKEN (≥ 32 characters) is set;
@@ -119,11 +143,6 @@ export type IpalOptions = {
* Building blocks: buildFillEmptyLocalesGlobalHook / …CollectionHook.
*/
fillEmptyLocales?: { 'cookie-review'?: string[]; 'cookie-settings'?: string[] } | boolean
/**
* Forms — form-builder collections (forms, form-submissions) plus the
* callable submitForm (Turnstile + persistence + SMTP-from-panel email).
*/
forms?: FormsOption
/**
@@ -185,6 +204,23 @@ export type IpalOptions = {
* SEO — adds meta fields to chosen collections (via @payloadcms/plugin-seo)
* and enables locale-aware metadata helpers.
*/
/**
* Stored secrets. `smtpPassword` and `turnstileSecretKey` (Site integrations)
* are **write-only** by default: REST, GraphQL and the panel get `'********'`
* ("a value is set"), never the value; a save that sends nothing, an empty
* value or the mask keeps what is stored, `'[[clear]]'` removes it. Server
* code reads the real value through the Local API (access control off, the
* default). `{ writeOnly: false }` = the value is returned to whoever may
* read the global, as before 1.16.7.
*
* The SMTP password is bound to its server: a save in the panel that changes
* the server, the port or the user name must send the password again, or
* remove it (whatever the transport says) — otherwise a stolen
* admin session points the server at its own machine and a test e-mail hands
* the password over. `{ reenterOnChange: false }` = the stored password
* follows the new server. docs/security.md "Stored secrets".
*/
secrets?: { reenterOnChange?: false; writeOnly?: false }
seo?: SeoOption
/** Additional fields injected into SiteSettings global */
@@ -275,6 +311,22 @@ export type IpalOptions = {
* (then set `x-pathname` on /admin yourself). Run generate:importmap.
*/
provider?: false | PayloadComponent
/**
* "Setup required", on by default: an account that has not set TOTP up
* reaches nothing at the access level (REST, GraphQL, the panel's data) —
* only the setup screen and its endpoint. It has `windowHours` (default 72)
* from its creation, or from a reset by an admin, to set TOTP up; after that
* it is blocked until an admin reopens setup (the account's page in the
* panel, or POST /api/ipal/two-factor/reset). Accounts that existed before
* the mode get the full window from the first start after the upgrade.
* `{ windowHours: false }` = no time limit; `{ exempt: ({ user }) => … }` =
* accounts that may work without TOTP on purpose (a service account);
* `false` = the 2FA package's rule (the panel redirects, the API is open
* until setup). Needs `guard` on. docs/security.md.
*/
requireSetup?: false | RequireSetupOptions
/** Who may reset another account's TOTP / reopen its setup. Default: a staff admin. The second factor is always required. */
resetAccess?: (args: { req: PayloadRequest }) => boolean | Promise<boolean>
/**
* Check on the `back` query value of the 2FA setup and verify screens. The
* 2FA package sends the browser there after a valid code without looking at
@@ -286,6 +338,17 @@ export type IpalOptions = {
* package's views as they are. Run generate:importmap. docs/security.md.
*/
safeBack?: false | SafeBackRule
/**
* 2FA verify and setup attempts (`POST /api/verify-totp`, `/api/setup-totp`)
* are accepted only from the site's own origin: a request that a browser
* marks as coming from elsewhere (`Origin`, `Sec-Fetch-Site`) is refused
* with 403 and not counted — so another page, a sibling subdomain included,
* cannot burn an account's verify attempts and lock its owner out. Own
* origins: the request's host, `serverURL`, Payload's `csrf` / `cors`
* lists, and `{ origins: ['https://app.example.com'] }` here. Requests
* without those headers (scripts, servers) pass. `false` = off.
*/
sameOrigin?: { origins?: string[] } | false
/**
* Texts of the 2FA screens and user field. Default: ipal-kit's English and
* Polish (`TOTP_TEXTS`), merged over the package's; your own
@@ -297,7 +360,10 @@ export type IpalOptions = {
* 2FA package never counts tries, and a six-digit code can be guessed by
* whoever holds the password. Default `{ max: 5, windowMinutes: 10 }`: the
* sixth attempt in ten minutes, right or wrong, is refused (429) until the
* window ends. `false` = no limit (a limiter in front of the site).
* window ends. The count is kept in memory and in the database (Payload's
* `payload.kv`), so a restart or a second instance does not reset it;
* `{ store: 'memory' }` = this instance only. `false` = no limit (a limiter
* in front of the site).
*/
verifyLimit?: false | VerifyLimitOptions
}
@@ -328,6 +394,14 @@ export type IpalOptions = {
| boolean
/** Upload field for the small nav icon. Default 'favicon'. */
iconField?: string
/**
* On the 2FA screens the panel's logo and icon are fetched by the server
* the way an anonymous visitor gets them and put into the page as a
* `data:` image: the session there is refused every collection, `media`
* included, so the browser could not load them. `false` = never fetch;
* the browser tries the media URL and shows the site name when refused.
*/
inlineImages?: false
/** Upload field for the login/nav logo. Default 'logo'. */
logoField?: string
/** Field with the site name. Default 'siteName'. */
+9 -1
View File
@@ -48,7 +48,15 @@ describe('injected auth collection', () => {
const config = await ipalKit({ access: { authCollection: 'users' }, i18n, twoFactor: false })(
empty({ collections: [own] as CollectionConfig[] }),
)
expect(config.collections?.find((c) => c.slug === 'users')?.access).toBe(own.access)
const access = config.collections?.find((c) => c.slug === 'users')?.access
// what the project wrote stays its own…
expect(access?.read).toBe(own.access.read)
// …and the account rules fill in only what it left out (accounts.*; `accounts: false` = nothing added)
expect(access?.admin).toBeTypeOf('function')
const untouched = await ipalKit({ access: { authCollection: 'users' }, accounts: false, i18n, twoFactor: false })(
empty({ collections: [own] as CollectionConfig[] }),
)
expect(untouched.collections?.find((c) => c.slug === 'users')?.access).toBe(own.access)
})
})
+8
View File
@@ -0,0 +1,8 @@
/** The account rules with 2FA off — see accountRulesSuite.ts. */
import { vi } from 'vitest'
import { accountRulesSuite } from './accountRulesSuite.js'
vi.mock('server-only', () => ({}))
accountRulesSuite(false)
+9
View File
@@ -0,0 +1,9 @@
/** The account rules with 2FA ON (the default on a site) — see accountRulesSuite.ts. */
import { vi } from 'vitest'
import { accountRulesSuite } from './accountRulesSuite.js'
vi.mock('server-only', () => ({}))
vi.mock('next/headers.js', async () => (await import('./http/server.js')).nextHeadersMock)
accountRulesSuite(true)
+77
View File
@@ -0,0 +1,77 @@
/**
* `accounts: false` — Payload's own behaviour, which the M1 account rules replace by default. Kept as a test
* for two reasons: the switch must really give it back, and it records what the rules close, including the
* case the first check did not cover (an empty second staff collection).
*/
import type { Payload } from 'payload'
import { lexicalEditor } from '@payloadcms/richtext-lexical'
import os from 'os'
import path from 'path'
import { getPayload } from 'payload'
import { afterAll, beforeAll, expect, test, vi } from 'vitest'
import { ipalKit } from '../src/plugin.js'
import { buildTestConfig } from './helpers.js'
import { testDatabase } from './http/db.js'
import { startPayloadServer, type TestServer } from './http/server.js'
vi.mock('server-only', () => ({}))
const PASSWORD = 'short1' // also: no password rule with accounts: false
let server: TestServer
let payload: Payload
const post = (pathname: string, body: unknown, headers: Record<string, string> = {}) =>
fetch(`${server.url}/api${pathname}`, { body: JSON.stringify(body), headers: { 'content-type': 'application/json', ...headers }, method: 'POST' })
const login = async (collection: string, email: string) => ({ authorization: `JWT ${((await (await post(`/${collection}/login`, { email, password: PASSWORD })).json()) as { token: string }).token}` })
beforeAll(async () => {
const config = buildTestConfig({
admin: { user: 'users' },
collections: [
{ slug: 'users', auth: true, fields: [] }, // the project's own staff collection, no access rules
{ slug: 'staff2', auth: true, fields: [] },
{ slug: 'members', auth: true, fields: [] },
{ slug: 'media', fields: [], upload: { staticDir: path.join(os.tmpdir(), 'ipal-test-media') } },
],
db: testDatabase('accounts_off'),
editor: lexicalEditor(),
plugins: [ipalKit({ access: { authCollection: 'users', staffCollections: ['staff2'] }, accounts: false, i18n: { defaultLocale: 'en', locales: [{ code: 'en', label: 'English' }] }, twoFactor: false })],
secret: 'integration-test-secret-0123456789',
telemetry: false,
})
payload = await getPayload({ config })
server = await startPayloadServer(config)
}, 120_000)
afterAll(async () => {
await server?.close()
await payload?.destroy?.()
})
test('an empty second staff collection: its first-user route makes the first visitor a staff admin', async () => {
const res = await post('/staff2/first-register', { email: '[email protected]', password: PASSWORD })
expect(res.status).toBe(200)
// `staff2` has no roles field, so every account of it is an admin to the plugin: the secrets global opens
const session = await login('staff2', '[email protected]')
const integrations = await fetch(`${server.url}/api/globals/site-integrations`, { headers: session })
expect(integrations.status).toBe(200)
expect((await post('/globals/site-integrations', { smtpHost: 'changed-by-the-first-visitor.example.com' }, session)).status).toBe(200)
})
test("Payload's first-user route answers for every empty auth collection", async () => {
expect((await post('/members/first-register', { email: '[email protected]', password: PASSWORD })).status).toBe(200)
})
test("the project's own staff collection without a create rule: any signed-in account makes accounts", async () => {
await payload.create({ collection: 'users' as never, data: { email: '[email protected]', password: PASSWORD, roles: ['admin'] } as never })
await payload.create({ collection: 'users' as never, data: { email: '[email protected]', password: PASSWORD, roles: ['user'] } as never })
const plain = await login('users', '[email protected]')
const made = await post('/users', { email: '[email protected]', password: PASSWORD, roles: ['admin'] }, plain)
expect(made.status).toBe(201)
const doc = (await payload.find({ collection: 'users' as never, where: { email: { equals: '[email protected]' } } })).docs[0] as unknown as { roles: string[] }
expect(doc.roles).toEqual(['user']) // the roles field still refuses the requested admin
// and the plain user may open the panel
const access = (await (await fetch(`${server.url}/api/access`, { headers: plain })).json()) as { canAccessAdmin?: boolean }
expect(access.canAccessAdmin).toBe(true)
})
+125
View File
@@ -0,0 +1,125 @@
/**
* A project with role values of its OWN and no `access` option (review of M1, M1-6): the account rules must not
* lock it out of its own accounts after an upgrade — and must still keep accounts of other collections away.
* 2FA on, as on a real site. Real HTTP; SQLite by default, Postgres / MongoDB with IPAL_TEST_POSTGRES_URI /
* IPAL_TEST_MONGO_URI.
*/
import type { Payload } from 'payload'
import { payloadTotp } from '@clocklimited/payload-2fa'
import { lexicalEditor } from '@payloadcms/richtext-lexical'
import os from 'os'
import path from 'path'
import { getPayload } from 'payload'
import { afterAll, beforeAll, expect, test, vi } from 'vitest'
import { staffCollectionsOpenToOthers } from '../src/modules/access/selfRegistration.js'
import { ipalKit } from '../src/plugin.js'
import { buildTestConfig } from './helpers.js'
import { testDatabase } from './http/db.js'
import { cookiesOf, startPayloadServer, type TestServer } from './http/server.js'
import { totp } from './http/totp.js'
vi.mock('server-only', () => ({}))
vi.mock('next/headers.js', async () => (await import('./http/server.js')).nextHeadersMock)
const PASSWORD = 'a-long-test-password-1'
const TOTP_SECRET = 'JBSWY3DPEHPK3PXP'
let server: TestServer
let payload: Payload
type Session = Record<string, string>
const call = (pathname: string, session: Session, method: string, body?: unknown) =>
fetch(`${server.url}/api${pathname}`, { body: body === undefined ? undefined : JSON.stringify(body), headers: { 'content-type': 'application/json', ...session }, method })
const idOf = async (collection: string, email: string) => (await payload.find({ collection: collection as never, where: { email: { equals: email } } })).docs[0]?.id
/** A full login: password, and for the 2FA collection the code. */
const login = async (collection: string, email: string): Promise<Session> => {
const res = await call(`/${collection}/login`, {}, 'POST', { email, password: PASSWORD })
const body = (await res.json()) as { token?: string }
if (!body.token) {throw new Error(`login failed for ${email}: ${JSON.stringify(body)}`)}
if (collection !== 'users') {return { authorization: `JWT ${body.token}` }}
await payload.update({ collection: 'users' as never, data: { totpSecret: TOTP_SECRET } as never, where: { email: { equals: email } } })
const cookies = cookiesOf(res)
const verify = await fetch(`${server.url}/api/verify-totp`, { body: JSON.stringify({ token: totp(TOTP_SECRET) }), headers: { 'content-type': 'application/json', cookie: cookies.join('; ') }, method: 'POST' })
expect(((await verify.json()) as { ok?: boolean }).ok).toBe(true)
return { cookie: [...cookies, ...cookiesOf(verify)].join('; ') }
}
beforeAll(async () => {
const config = buildTestConfig({
admin: { user: 'users' },
collections: [
// the project's own staff collection: its own role values, no access rules, no `access` option below
{ slug: 'users', auth: true, fields: [{ name: 'roles', type: 'select', hasMany: true, options: ['superadmin', 'writer'] }] },
{ slug: 'customers', access: { create: () => true }, auth: true, fields: [] },
{ slug: 'media', fields: [], upload: { staticDir: path.join(os.tmpdir(), 'ipal-test-media') } },
],
db: testDatabase('accounts_own_roles'),
editor: lexicalEditor(),
plugins: [ipalKit({ i18n: { defaultLocale: 'en', locales: [{ code: 'en', label: 'English' }] }, twoFactor: { issuer: 'Example', plugin: payloadTotp, verifyLimit: false } })],
secret: 'integration-test-secret-0123456789',
telemetry: false,
})
payload = await getPayload({ config })
server = await startPayloadServer(config)
}, 120_000)
afterAll(async () => {
await server?.close()
await payload?.destroy?.()
})
test('the first account registers; accounts of the collection create, change and delete accounts as before the upgrade', async () => {
expect((await call('/users/first-register', {}, 'POST', { email: '[email protected]', password: PASSWORD, roles: ['superadmin'] })).status).toBe(200)
const boss = await login('users', '[email protected]')
// the first M1 cut: 403 — the plugin looked for one of ITS roles and found none
expect((await call('/users', boss, 'POST', { email: '[email protected]', password: PASSWORD, roles: ['writer'] })).status).toBe(201)
const writer = await login('users', '[email protected]')
// the project's roles are the project's to enforce: inside the collection nothing changed
expect((await call('/users', writer, 'POST', { email: '[email protected]', password: PASSWORD, roles: ['writer'] })).status).toBe(201)
const third = await idOf('users', '[email protected]')
expect((await call(`/users/${third}`, boss, 'PATCH', { roles: ['superadmin'] })).status).toBe(200)
expect((await call(`/users/${third}`, boss, 'DELETE')).status).toBe(200)
})
// Review round 2 (R2-2): the plugin cannot rank the project's roles, but one thing it can hold: nobody changes its OWN.
test('an account does not change its own roles; another account of the collection does (the project\'s rules narrow that)', async () => {
const writer = await login('users', '[email protected]')
const id = await idOf('users', '[email protected]')
const roles = async () => ((await payload.findByID({ id: id as never, collection: 'users' as never })) as { roles?: string[] }).roles
await call(`/users/${id}`, writer, 'PATCH', { roles: ['superadmin'] })
await call('/users?where[email][equals][email protected]', writer, 'PATCH', { roles: ['superadmin'] })
expect(await roles()).toEqual(['writer'])
const boss = await login('users', '[email protected]')
expect((await call(`/users/${id}`, boss, 'PATCH', { roles: ['superadmin'] })).status).toBe(200)
expect(await roles()).toEqual(['superadmin'])
await payload.update({ id: id as never, collection: 'users' as never, data: { roles: ['writer'] } as never })
})
test('an account of another collection, a half-signed-in one and nobody stay out', async () => {
expect((await call('/customers', {}, 'POST', { email: '[email protected]', password: PASSWORD })).status).toBe(201)
const visitor = await login('customers', '[email protected]')
const halfRes = await call('/users/login', {}, 'POST', { email: '[email protected]', password: PASSWORD })
const half: Session = { authorization: `JWT ${((await halfRes.json()) as { token: string }).token}` } // the password only
const victim = await idOf('users', '[email protected]')
for (const [who, session] of [['visitor', visitor], ['password only', half], ['anonymous', {}]] as [string, Session][]) {
expect([who, (await call('/users', session, 'POST', { email: `by-${who.replace(' ', '-')}@example.com`, password: PASSWORD, roles: ['superadmin'] })).status]).toEqual([who, 403])
expect([who, (await call(`/users/${victim}`, session, 'PATCH', { password: 'taken-over-password-1' })).status]).toEqual([who, 403])
expect([who, (await call(`/users/${victim}`, session, 'DELETE')).status]).toEqual([who, 403])
}
expect((await call('/users/login', {}, 'POST', { email: '[email protected]', password: 'taken-over-password-1' })).status).not.toBe(200)
expect(await staffCollectionsOpenToOthers(payload as never)).toEqual([])
})
test('a staff collection that does not exist stops the start, with the slug and the fix', async () => {
const config = buildTestConfig({
admin: { user: 'users' },
collections: [{ slug: 'media', fields: [], upload: { staticDir: path.join(os.tmpdir(), 'ipal-test-media') } }],
db: testDatabase('accounts_ghost'),
editor: lexicalEditor(),
plugins: [ipalKit({ access: { authCollection: 'users', staffCollections: ['ghost-staff'] }, i18n: { defaultLocale: 'en', locales: [{ code: 'en', label: 'English' }] }, twoFactor: false })],
secret: 'integration-test-secret-0123456789',
telemetry: false,
})
await expect(getPayload({ config, key: 'ghost' })).rejects.toThrow(/"ghost-staff"[\s\S]*no auth collection with that slug[\s\S]*staffCollections/)
})
+9
View File
@@ -0,0 +1,9 @@
/** A dev reload and a late staff collection, 2FA off — see accountRulesReloadSuite.ts. */
import { vi } from 'vitest'
import { reloadSuite } from './accountRulesReloadSuite.js'
vi.mock('server-only', () => ({}))
vi.mock('next/headers.js', async () => (await import('./http/server.js')).nextHeadersMock)
reloadSuite(false)
+9
View File
@@ -0,0 +1,9 @@
/** A dev reload and a late staff collection, 2FA ON — see accountRulesReloadSuite.ts. */
import { vi } from 'vitest'
import { reloadSuite } from './accountRulesReloadSuite.js'
vi.mock('server-only', () => ({}))
vi.mock('next/headers.js', async () => (await import('./http/server.js')).nextHeadersMock)
reloadSuite(true)
+96
View File
@@ -0,0 +1,96 @@
/**
* A dev reload (review round 3, R3-2): Payload swaps `payload.config` and runs no onInit. A staff collection that a
* plugin listed after ipalKit adds must keep the account rules on the new config — with 2FA off and on.
* Real HTTP; SQLite by default, Postgres / MongoDB with IPAL_TEST_POSTGRES_URI / IPAL_TEST_MONGO_URI.
*/
import type { Config, Payload, Plugin, SanitizedConfig } from 'payload'
import { payloadTotp } from '@clocklimited/payload-2fa'
import { lexicalEditor } from '@payloadcms/richtext-lexical'
import os from 'os'
import path from 'path'
import { getPayload } from 'payload'
import { expect, test } from 'vitest'
import { ipalKit } from '../src/plugin.js'
import { buildTestConfig } from './helpers.js'
import { testDatabase } from './http/db.js'
import { startPayloadServer } from './http/server.js'
const PASSWORD = 'a-long-test-password-1'
const late: Plugin = (config: Config) => ({
...config,
collections: [...(config.collections ?? []), { slug: 'late-staff', auth: true, fields: [{ name: 'roles', type: 'select', hasMany: true, options: ['user', 'editor', 'admin'] }], versions: true }],
})
const makeConfig = (twoFactor: boolean) =>
buildTestConfig({
admin: { user: 'users' },
collections: [
{ slug: 'customers', access: { create: () => true }, auth: true, fields: [] },
{ slug: 'media', fields: [], upload: { staticDir: path.join(os.tmpdir(), 'ipal-test-media') } },
],
db: testDatabase(twoFactor ? 'reload_2fa' : 'reload'),
editor: lexicalEditor(),
plugins: [
ipalKit({ access: { authCollection: 'users', staffCollections: ['late-staff'] }, i18n: { defaultLocale: 'en', locales: [{ code: 'en', label: 'English' }] }, twoFactor: twoFactor ? { issuer: 'Example', plugin: payloadTotp, verifyLimit: false } : false }),
late,
],
secret: 'integration-test-secret-0123456789',
telemetry: false,
})
/** One Payload instance per test file (Payload caches it): run from a file of its own for 2FA off and on. */
export function reloadSuite(twoFactor: boolean): void {
test(`a late staff collection keeps its rules over a dev reload (2FA on: ${twoFactor})`, async () => {
const config = makeConfig(twoFactor)
const payload: Payload = await getPayload({ config })
const server = await startPayloadServer(config)
const call = (method: string, pathname: string, body?: unknown, headers: Record<string, string> = {}) =>
fetch(`${server.url}/api${pathname}`, { body: body === undefined ? undefined : JSON.stringify(body), headers: { 'content-type': 'application/json', ...headers }, method })
const round = async (when: string) => {
const tag = `${when.replace(/\W+/g, "-")}-${Math.random().toString(36).slice(2)}`
// an EMPTY late staff collection: its first-user route, in two spellings
const before = (await payload.count({ collection: 'late-staff' as never })).totalDocs
for (const spelling of ['/first-register', '/First-Register']) {
expect([when, spelling, (await call('POST', `/late-staff${spelling}`, { email: `first-${tag}@example.com`, password: PASSWORD, roles: ['admin'] })).status]).toEqual([when, spelling, 403])
}
expect([when, (await payload.count({ collection: 'late-staff' as never })).totalDocs]).toEqual([when, before])
// a visitor account
expect((await call('POST', '/customers', { email: `c-${tag}@example.com`, password: PASSWORD })).status).toBe(201)
const token = ((await (await call('POST', '/customers/login', { email: `c-${tag}@example.com`, password: PASSWORD })).json()) as { token: string }).token
const visitor = { authorization: `JWT ${token}` }
const victim = await payload.create({ collection: 'late-staff' as never, data: { email: `v-${tag}@example.com`, password: PASSWORD, roles: ['user'] } as never })
const got = {
create: (await call('POST', '/late-staff', { email: `x-${tag}@example.com`, password: PASSWORD, roles: ['admin'] }, visitor)).status,
delete: (await call('DELETE', `/late-staff/${victim.id}`, undefined, visitor)).status,
patch: (await call('PATCH', `/late-staff/${victim.id}`, { password: 'taken-over-password-1' }, visitor)).status,
read: (await call('GET', '/late-staff', undefined, visitor)).status,
unlock: (await call('POST', '/late-staff/unlock', { email: `v-${tag}@example.com` }, visitor)).status,
versions: (await call('GET', '/late-staff/versions', undefined, visitor)).status,
}
expect([when, got]).toEqual([when, { create: 403, delete: 403, patch: 403, read: 403, unlock: 403, versions: 403 }])
// the password rule is on the collection too
await expect(payload.create({ collection: 'late-staff' as never, data: { email: `s-${tag}@example.com`, password: 'tooshort', roles: ['user'] } as never })).rejects.toThrow()
await payload.delete({ collection: 'late-staff' as never, where: { email: { contains: tag } } })
}
try {
await round('start')
// what Payload's dev `reload()` does: a NEW sanitized config is assigned first, the collections after it
const next = await makeConfig(twoFactor)
const live = payload as unknown as { collections: Record<string, { config: unknown; customIDType?: unknown }>; config: SanitizedConfig; globals: { config: unknown } }
live.config = next
live.collections = Object.fromEntries(next.collections.map((c) => [c.slug, { config: c, customIDType: live.collections[c.slug]?.customIDType }]))
live.globals = { config: next.globals }
await round('after the reload')
// and once more: a second reload meets a fresh config again
const third = await makeConfig(twoFactor)
live.config = third
live.collections = Object.fromEntries(third.collections.map((c) => [c.slug, { config: c, customIDType: live.collections[c.slug]?.customIDType }]))
live.globals = { config: third.globals }
await round('after a second reload')
} finally {
await server.close()
await payload.destroy?.()
}
}, 120_000)
}
+755
View File
@@ -0,0 +1,755 @@
/**
* M1 account rules over real HTTP (SQLite by default; Postgres / MongoDB with IPAL_TEST_POSTGRES_URI /
* IPAL_TEST_MONGO_URI): who may open the panel, who may create, change or delete an account, what a
* password must be. One suite, run twice: with 2FA off (accountRules.test.ts) and with 2FA on
* (accountRules2fa.test.ts) — the 2FA package rewrites every collection's access, and a rule that
* holds without it may not hold with it.
*/
import type { Config, Payload, Plugin } from 'payload'
import { payloadTotp } from '@clocklimited/payload-2fa'
import { lexicalEditor } from '@payloadcms/richtext-lexical'
import { pbkdf2Sync, randomBytes } from 'node:crypto'
import os from 'os'
import path from 'path'
import { getPayload } from 'payload'
import { afterAll, beforeAll, describe, expect, test } from 'vitest'
import type { I18nConfig } from '../src/modules/i18n/types.js'
import { countBelowPanelRole, panelAccess, resolvePanelRole } from '../src/modules/access/panelRole.js'
import { checkPassword, resolvePasswordRule } from '../src/modules/access/passwordRule.js'
import { adoptLateAuthCollections, bothAllow, hasPluginRoles, openSignUpCollections, rolesByAdminOnly, rolesNotOwn, sameStaffCollectionAccess, staffCollectionsOnOwnRoles, staffCollectionsOpenToOthers, staffCreateAccess, staffReadAccess, staffUpdateAccess, unknownStaffCollections } from '../src/modules/access/selfRegistration.js'
import { ipalKit } from '../src/plugin.js'
import { buildTestConfig, withTotpParts } from './helpers.js'
import { testDatabase } from './http/db.js'
import { cookiesOf, startPayloadServer, type TestServer } from './http/server.js'
import { totp } from './http/totp.js'
const TOTP_SECRET = 'JBSWY3DPEHPK3PXP'
/** A plugin the project lists AFTER ipalKit: its auth collections did not exist when ipalKit ran (review round 2, R2-3). */
const latePlugin: Plugin = (config: Config) => ({
...config,
collections: [
...(config.collections ?? []),
{ slug: 'late-staff', auth: true, fields: [{ name: 'roles', type: 'select', hasMany: true, options: ['user', 'editor', 'admin'], saveToJWT: true }], versions: true },
{ slug: 'late-members', auth: true, fields: [] },
],
})
/** The whole suite; `twoFactor` = run it with the 2FA package on. */
export function accountRulesSuite(twoFactor: boolean): void {
const i18n: I18nConfig = { defaultLocale: 'en', locales: [{ code: 'en', label: 'English' }] }
const PASSWORD = 'a-long-test-password-1'
let server: TestServer
let payload: Payload
type Session = Record<string, string>
const call = (pathname: string, session: Session = {}, init: RequestInit = {}) =>
fetch(`${server.url}/api${pathname}`, { ...init, headers: { 'content-type': 'application/json', ...session, ...(init.headers as Record<string, string> | undefined) } })
const post = (pathname: string, body: unknown, session: Session = {}) => call(pathname, session, { body: JSON.stringify(body), method: 'POST' })
const sessions = new Map<string, Session>()
/** A full login. With 2FA on, an account of the 2FA collection (`users`) also types its code. */
const login = async (collection: string, email: string, password = PASSWORD): Promise<Session> => {
const key = `${collection}|${email}|${password}`
const known = sessions.get(key)
if (known) {return known}
const res = await post(`/${collection}/login`, { email, password })
const body = (await res.json()) as { token?: string }
if (!body.token) {throw new Error(`login failed for ${email}: ${JSON.stringify(body)}`)}
let session: Session = { authorization: `JWT ${body.token}` }
if (twoFactor && collection === 'users') {
// accounts made over HTTP in a test have no secret yet: give them one, as their owner would on the setup screen
await payload.update({ collection: 'users' as never, data: { totpSecret: TOTP_SECRET } as never, where: { email: { equals: email } } })
const cookies = cookiesOf(res)
const verify = await fetch(`${server.url}/api/verify-totp`, { body: JSON.stringify({ token: totp(TOTP_SECRET) }), headers: { 'content-type': 'application/json', cookie: cookies.join('; ') }, method: 'POST' })
const verified = (await verify.json()) as { ok?: boolean }
if (!verified.ok) {throw new Error(`2FA failed for ${email}: ${JSON.stringify(verified)}`)}
session = { cookie: [...cookies, ...cookiesOf(verify)].join('; ') }
}
sessions.set(key, session)
return session
}
/** Password only: with 2FA on, a `users` session that still owes its code. */
const passwordOnly = async (email: string): Promise<Session> => ({ authorization: `JWT ${((await (await post('/users/login', { email, password: PASSWORD })).json()) as { token: string }).token}` })
const make = (collection: string, data: Record<string, unknown>) =>
payload.create({ collection: collection as never, data: { password: PASSWORD, ...(twoFactor && collection === 'users' ? { totpSecret: TOTP_SECRET } : {}), ...data } as never })
const patch = (pathname: string, body: unknown, session: Session = {}) => call(pathname, session, { body: JSON.stringify(body), method: 'PATCH' })
const remove = (pathname: string, session: Session = {}) => call(pathname, session, { method: 'DELETE' })
const idOf = async (collection: string, email: string) => (await payload.find({ collection: collection as never, where: { email: { equals: email } } })).docs[0]?.id
const canLogIn = async (collection: string, email: string, password = PASSWORD) => (await post(`/${collection}/login`, { email, password })).status === 200
beforeAll(async () => {
const config = buildTestConfig({
admin: { user: 'users' },
collections: [
{ slug: 'customers', access: { create: () => true }, auth: true, fields: [] },
{ slug: 'members', auth: true, fields: [] },
{ slug: 'staff2', auth: true, fields: [] }, // a second staff collection, without roles and without rules
// a staff collection with the project's OWN role values and no rules: the plugin cannot tell who its admins are
{ slug: 'crew', auth: true, fields: [{ name: 'roles', type: 'select', hasMany: true, options: ['boss', 'worker'] }] },
// a staff collection with the plugin's role values, written by the project, no rules
{ slug: 'agents', auth: true, fields: [{ name: 'roles', type: 'select', hasMany: true, options: ['user', 'editor', 'admin'], saveToJWT: true }], versions: true },
{ slug: 'media', fields: [], upload: { staticDir: path.join(os.tmpdir(), 'ipal-test-media') } },
],
db: testDatabase(twoFactor ? 'accounts_2fa' : 'accounts'),
editor: lexicalEditor(),
plugins: [ipalKit({ access: { authCollection: 'users', staffCollections: ['staff2', 'crew', 'agents', 'late-staff'] }, i18n, twoFactor: twoFactor ? { issuer: 'Example', plugin: payloadTotp, verifyLimit: false } : false }), latePlugin],
secret: 'integration-test-secret-0123456789',
telemetry: false,
})
payload = await getPayload({ config })
server = await startPayloadServer(config)
}, 120_000)
afterAll(async () => {
await server?.close()
await payload?.destroy?.()
})
// The owner's rule: nobody creates an account for themselves; only the first account of a site, as admin.
describe('no self-registration (accounts.adminOnlyCreate, accounts.firstUserRoute)', () => {
const rolesOf = async (email: string) => ((await payload.find({ collection: 'users' as never, where: { email: { equals: email } } })).docs[0] as { roles?: string[] } | undefined)?.roles
const count = async (collection: string) => (await payload.count({ collection: collection as never })).totalDocs
test('an empty site: an anonymous request creates no staff account, over REST or GraphQL', async () => {
expect((await post('/users', { email: '[email protected]', password: PASSWORD })).status).toBe(403)
expect((await post('/users', { email: '[email protected]', password: PASSWORD, roles: ['admin'] })).status).toBe(403)
expect((await post('/staff2', { email: '[email protected]', password: PASSWORD })).status).toBe(403)
const gql = (await (await post('/graphql', { query: `mutation { createUser(data: { email: "[email protected]", password: "${PASSWORD}", roles: [admin] }) { id } }` })).json()) as { errors?: unknown[] }
expect(gql.errors?.length).toBeGreaterThan(0)
expect(await count('users')).toBe(0)
expect(await count('staff2')).toBe(0)
})
test("the first-user route of other empty auth collections is closed — a second STAFF collection included", async () => {
// before: 200 for each of them while empty; a first account in `staff2` would have been staff
expect((await post('/staff2/first-register', { email: '[email protected]', password: PASSWORD })).status).toBe(403)
expect((await post('/members/first-register', { email: '[email protected]', password: PASSWORD })).status).toBe(403)
expect(await count('staff2')).toBe(0)
expect(await count('members')).toBe(0)
})
test('…in every spelling Payload\'s router accepts or might: letter case, slashes, encoding, query', async () => {
// the first cut read the path and missed /First-Register: an anonymous visitor became a staff admin
const spellings = ['/first-register', '/first-register/', '/First-Register', '/FIRST-REGISTER', '/fIrSt-ReGiStEr', '/first-registe%72', '//first-register', '/first-register?x=1', '/first-register;x', '/First-Register/?x=1']
for (const collection of ['staff2', 'crew', 'agents', 'members', 'late-staff', 'late-members']) {
for (const spelling of spellings) {
const res = await post(`/${collection}${spelling}`, { email: `sp-${Math.random().toString(36).slice(2)}@example.com`, password: PASSWORD, roles: ['admin'] })
expect([collection, spelling, res.status === 200 || res.status === 201]).toEqual([collection, spelling, false])
}
expect([collection, await count(collection)]).toEqual([collection, 0])
}
})
test('a collection that allows sign-up keeps its routes', async () => {
expect((await post('/customers/first-register', { email: '[email protected]', password: PASSWORD })).status).toBe(200)
expect((await post('/customers', { email: '[email protected]', password: PASSWORD })).status).toBe(201)
expect((await post('/members', { email: '[email protected]', password: PASSWORD })).status).toBe(403)
})
test('the first account of the site registers through the first-user route and is an admin; the route then closes', async () => {
// in a spelling of its own: the account is still the first one, and still an admin
const first = await post('/users/First-Register', { email: '[email protected]', password: PASSWORD, roles: ['user'] })
expect(first.status).toBe(200)
expect(((await first.json()) as { token?: string }).token).toBeTypeOf('string')
expect(first.headers.getSetCookie().join(';')).toMatch(/payload-token=/)
expect(await rolesOf('[email protected]')).toEqual(['admin'])
for (const spelling of ['/first-register', '/First-Register', '/FIRST-REGISTER/']) {
expect((await post(`/users${spelling}`, { email: '[email protected]', password: PASSWORD })).status).toBe(403)
}
expect(await rolesOf('[email protected]')).toBeUndefined()
expect((await post('/users', { email: '[email protected]', password: PASSWORD })).status).toBe(403)
})
test('only an admin creates staff accounts — not an editor, not a plain user, not asking for a role', async () => {
await make('users', { email: '[email protected]', roles: ['editor'] })
await make('users', { email: '[email protected]', roles: ['user'] })
for (const who of ['[email protected]', '[email protected]']) {
const session = await login('users', who)
expect([who, (await post('/users', { email: `by-${who}`, password: PASSWORD, roles: ['admin'] }, session)).status]).toEqual([who, 403])
expect([who, (await post('/staff2', { email: `by-${who}`, password: PASSWORD }, session)).status]).toEqual([who, 403])
}
const admin = await login('users', '[email protected]')
expect((await post('/users', { email: '[email protected]', password: PASSWORD, roles: ['editor'] }, admin)).status).toBe(201)
expect(await rolesOf('[email protected]')).toEqual(['editor'])
// an admin of the panel's collection makes the first account of the second staff collection
expect((await post('/staff2', { email: '[email protected]', password: PASSWORD }, admin)).status).toBe(201)
// a visitor account is nobody here
const visitor = await login('customers', '[email protected]')
expect((await post('/users', { email: '[email protected]', password: PASSWORD }, visitor)).status).toBe(403)
expect((await post('/staff2', { email: '[email protected]', password: PASSWORD }, visitor)).status).toBe(403)
// GraphQL is the same rule
const gql = (await (await post('/graphql', { query: `mutation { createUser(data: { email: "[email protected]", password: "${PASSWORD}", roles: [admin] }) { id } }` }, visitor)).json()) as { errors?: unknown[] }
expect(gql.errors?.length).toBeGreaterThan(0)
expect(await idOf('users', '[email protected]')).toBeUndefined()
})
test('a session that still owes its second factor creates nothing', async () => {
if (!twoFactor) {return}
const half = await passwordOnly('[email protected]')
expect((await post('/users', { email: '[email protected]', password: PASSWORD }, half)).status).toBe(403)
expect((await post('/staff2', { email: '[email protected]', password: PASSWORD }, half)).status).toBe(403)
expect((await post('/crew', { email: '[email protected]', password: PASSWORD }, half)).status).toBe(403)
})
})
// Closing `create` alone is little help while Payload's default for `update` and `delete` is "any logged-in user".
describe('nobody takes an account over (accounts.adminOnlyWrite)', () => {
const NEW = 'taken-over-password-1'
let admin: Session
let visitor: Session
let editor: Session
let plain: Session
beforeAll(async () => {
admin = await login('users', '[email protected]')
visitor = await login('customers', '[email protected]')
await make('users', { email: '[email protected]', roles: ['editor'] })
await make('users', { email: '[email protected]', roles: ['user'] })
editor = await login('users', '[email protected]')
plain = await login('users', '[email protected]')
await make('agents', { email: '[email protected]', roles: ['admin'] })
await make('agents', { email: '[email protected]', roles: ['editor'] })
await make('staff2', { email: '[email protected]' })
await make('crew', { email: '[email protected]', roles: ['boss'] })
await make('crew', { email: '[email protected]', roles: ['worker'] })
})
test.each(['agents', 'staff2', 'crew'])('%s (the project\'s own staff collection, no rules): a visitor account and an anonymous request change and delete nothing', async (collection) => {
const email = { agents: '[email protected]', crew: '[email protected]', staff2: '[email protected]' }[collection]!
const id = await idOf(collection, email)
for (const [who, session] of [['visitor', visitor], ['anonymous', {}]] as [string, Session][]) {
// before: 200 for the visitor — a staff account's password and roles
expect([who, (await patch(`/${collection}/${id}`, { password: NEW, roles: ['admin'] }, session)).status]).toEqual([who, 403])
await patch(`/${collection}?where[email][equals]=${email}`, { password: NEW }, session) // bulk: whatever it answers…
expect([who, (await remove(`/${collection}/${id}`, session)).status]).toEqual([who, 403])
await remove(`/${collection}?where[email][equals]=${email}`, session)
}
// …nothing happened
expect(await idOf(collection, email)).toBe(id)
expect(await canLogIn(collection, email, NEW)).toBe(false)
expect(await canLogIn(collection, email)).toBe(true)
})
test('where the roles are the plugin\'s: an admin changes and deletes; anyone else only its own account, and not its roles', async () => {
const victim = await idOf('agents', '[email protected]')
const own = await idOf('agents', '[email protected]')
const agentEditor = await login('agents', '[email protected]')
// an editor of the same collection, and an editor / plain user of the panel's collection
for (const [who, session] of [['agent editor', agentEditor], ['editor', editor], ['plain', plain]] as [string, Session][]) {
expect([who, (await patch(`/agents/${victim}`, { password: NEW }, session)).status]).toEqual([who, 403])
expect([who, (await remove(`/agents/${victim}`, session)).status]).toEqual([who, 403])
}
expect(await canLogIn('agents', '[email protected]', NEW)).toBe(false)
// its own account: yes — and never a delete
expect((await patch(`/agents/${own}`, { password: 'my-own-new-password-1' }, agentEditor)).status).toBe(200)
expect(await canLogIn('agents', '[email protected]', 'my-own-new-password-1')).toBe(true)
expect((await remove(`/agents/${own}`, agentEditor)).status).toBe(403)
// the injected collection: the same, and the roles field is the admin's
const me = await idOf('users', '[email protected]')
await patch(`/users/${me}`, { roles: ['admin'] }, editor)
expect(((await payload.findByID({ id: me as never, collection: 'users' as never })) as { roles?: string[] }).roles).toEqual(['editor'])
expect((await patch(`/users/${await idOf('users', '[email protected]')}`, { password: NEW }, editor)).status).toBe(403)
// an admin: everything
const spare = await make('agents', { email: '[email protected]', roles: ['user'] })
expect((await patch(`/agents/${spare.id}`, { roles: ['editor'] }, admin)).status).toBe(200)
expect((await remove(`/agents/${spare.id}`, admin)).status).toBe(200)
})
test('where the roles are the project\'s own: accounts of that collection keep working as before; a plugin admin too; nobody else', async () => {
// the plugin cannot tell a `boss` from a `worker`: the project's own rules decide inside the collection
const boss = await login('crew', '[email protected]')
expect((await post('/crew', { email: '[email protected]', password: PASSWORD, roles: ['worker'] }, boss)).status).toBe(201)
const id = await idOf('crew', '[email protected]')
expect((await patch(`/crew/${id}`, { roles: ['boss'] }, boss)).status).toBe(200)
expect((await remove(`/crew/${id}`, boss)).status).toBe(200)
// an admin of the panel's collection
expect((await post('/crew', { email: '[email protected]', password: PASSWORD, roles: ['worker'] }, admin)).status).toBe(201)
// an editor of another staff collection, a visitor, nobody
for (const [who, session] of [['editor', editor], ['plain', plain], ['visitor', visitor], ['anonymous', {}]] as [string, Session][]) {
expect([who, (await post('/crew', { email: `by-${who}@crew.example.com`, password: PASSWORD, roles: ['boss'] }, session)).status]).toEqual([who, 403])
}
})
// Review round 2 (R2-2): the default "the account itself may update" must not reach the roles.
test('nobody raises its own role: a lowest-role account of a second staff collection stays what it is', async () => {
await make('agents', { email: '[email protected]', roles: ['user'] })
const low = await login('agents', '[email protected]')
const id = await idOf('agents', '[email protected]')
const rolesOf = async (collection: string, of: unknown) => ((await payload.findByID({ id: of as never, collection: collection as never })) as { roles?: string[] }).roles
for (const body of [{ roles: ['admin'] }, { roles: 'admin' }, { password: 'another-long-password-1', roles: ['admin', 'user'] }]) {
await patch(`/agents/${id}`, body, low)
expect(await rolesOf('agents', id)).toEqual(['user'])
}
await patch('/agents?where[email][equals][email protected]', { roles: ['admin'] }, low) // bulk
expect(await rolesOf('agents', id)).toEqual(['user'])
const gql = await post('/graphql', { query: `mutation { updateAgent(id: ${typeof id === 'number' ? id : `"${id}"`}, data: { roles: [admin] }) { id } }` }, low)
await gql.text()
expect(await rolesOf('agents', id)).toEqual(['user'])
// the rest of its own account is its own (the password above was changed)
expect(await canLogIn('agents', '[email protected]', 'another-long-password-1')).toBe(true)
// and it opens nothing an admin opens
expect((await call('/globals/site-integrations', low)).status).toBe(403)
// an admin gives roles
expect((await patch(`/agents/${id}`, { roles: ['editor'] }, admin)).status).toBe(200)
expect(await rolesOf('agents', id)).toEqual(['editor'])
// role values of the project's own: the plugin cannot rank them, but an account still never changes its own
const worker = await login('crew', '[email protected]')
const workerId = await idOf('crew', '[email protected]')
await patch(`/crew/${workerId}`, { roles: ['boss'] }, worker)
await patch('/crew?where[email][equals][email protected]', { roles: ['boss'] }, worker)
expect(await rolesOf('crew', workerId)).toEqual(['worker'])
// somebody else of the collection does (what the project's own rules must narrow — said by the doctor)
const boss = await login('crew', '[email protected]')
expect((await patch(`/crew/${workerId}`, { roles: ['boss'] }, boss)).status).toBe(200)
expect(await rolesOf('crew', workerId)).toEqual(['boss'])
await payload.update({ id: workerId as never, collection: 'crew' as never, data: { roles: ['worker'] } as never })
})
// Payload's defaults for `read` and `unlock` are "any logged-in user" too.
test('a visitor account does not list staff accounts or unlock them; staff does (accounts.staffOnlyRead)', async () => {
for (const collection of ['agents', 'staff2', 'crew', 'late-staff']) {
for (const [who, session] of [['visitor', visitor], ['anonymous', {}]] as [string, Session][]) {
expect([collection, who, (await call(`/${collection}`, session)).status]).toEqual([collection, who, 403])
expect([collection, who, (await post(`/${collection}/unlock`, { email: '[email protected]' }, session)).status]).toEqual([collection, who, 403])
}
expect([collection, (await call(`/${collection}`, editor)).status]).toEqual([collection, 200]) // staff reads staff
}
// versions hold what the accounts hold (review round 3, R3-3)
await payload.update({ collection: 'agents' as never, data: { roles: ['admin'] } as never, where: { email: { equals: '[email protected]' } } })
for (const collection of ['agents', 'late-staff']) {
for (const [who, session] of [['visitor', visitor], ['anonymous', {}]] as [string, Session][]) {
const res = await call(`/${collection}/versions`, session)
expect([collection, who, res.status]).toEqual([collection, who, 403])
expect(await res.text()).not.toContain('[email protected]')
}
expect([collection, (await call(`/${collection}/versions`, editor)).status]).toEqual([collection, 200])
}
const gql = (await (await post('/graphql', { query: '{ Agents { docs { email } } }' }, visitor)).json()) as { data?: unknown; errors?: unknown[] }
expect(JSON.stringify(gql)).not.toContain('[email protected]')
expect((await post('/agents/unlock', { email: '[email protected]' }, editor)).status).toBe(403)
expect((await post('/agents/unlock', { email: '[email protected]' }, admin)).status).toBe(200)
await make('late-staff', { email: '[email protected]', roles: ['user'] })
expect((await post('/late-staff/unlock', { email: '[email protected]' }, editor)).status).toBe(403) // a late collection: the same table
expect((await post('/late-staff/unlock', { email: '[email protected]' }, admin)).status).toBe(200)
})
// Review round 2 (R2-3): a staff collection a later plugin adds.
test('a staff collection added by a plugin listed after ipalKit has the same rules', async () => {
// (the first-user spellings above created nothing: counted there)
expect((await post('/late-staff', { email: '[email protected]', password: PASSWORD, roles: ['admin'] }, visitor)).status).toBe(403)
expect((await post('/late-staff', { email: '[email protected]', password: PASSWORD, roles: ['admin'] }, editor)).status).toBe(403)
// the password rule is there too
expect((await post('/late-staff', { email: '[email protected]', password: 'tooshort', roles: ['user'] }, admin)).status).toBe(400)
expect((await post('/late-staff', { email: '[email protected]', password: PASSWORD, roles: ['user'] }, admin)).status).toBe(201)
const id = await idOf('late-staff', '[email protected]')
expect((await patch(`/late-staff/${id}`, { password: NEW }, visitor)).status).toBe(403)
expect((await remove(`/late-staff/${id}`, visitor)).status).toBe(403)
const one = await login('late-staff', '[email protected]')
await patch(`/late-staff/${id}`, { roles: ['admin'] }, one)
expect(((await payload.findByID({ id: id as never, collection: 'late-staff' as never })) as { roles?: string[] }).roles).toEqual(['user'])
expect((await patch(`/late-staff/${id}`, { roles: ['editor'] }, admin)).status).toBe(200)
})
test('the doctor\'s check: no staff collection is open to an account of another collection', async () => {
expect(staffCollectionsOnOwnRoles(payload as never)).toEqual(['crew']) // `staff2` has no roles field: nothing to rank
expect(await staffCollectionsOpenToOthers(payload as never)).toEqual([])
expect(await openSignUpCollections(payload as never)).toEqual(['customers'])
})
})
describe('the lowest role stays out of the admin panel (accounts.panelRole)', () => {
const canAccessAdmin = async (session: Session) => Boolean(((await (await call('/access', session)).json()) as { canAccessAdmin?: boolean }).canAccessAdmin)
beforeAll(async () => {
await make('users', { email: '[email protected]', roles: ['admin'] })
await make('users', { email: '[email protected]', roles: ['editor'] })
await make('users', { email: '[email protected]', roles: ['user'] })
await make('customers', { email: '[email protected]' })
})
test('Payload reports panel access for an admin and an editor, not for a plain user or a visitor account', async () => {
expect(await canAccessAdmin(await login('users', '[email protected]'))).toBe(true)
expect(await canAccessAdmin(await login('users', '[email protected]'))).toBe(true)
expect(await canAccessAdmin(await login('users', '[email protected]'))).toBe(false)
expect(await canAccessAdmin(await login('customers', '[email protected]'))).toBe(false)
expect(await canAccessAdmin({})).toBe(false)
})
test('the API is not touched: the plain user still logs in and reads its own account', async () => {
const session = await login('users', '[email protected]')
const me = (await (await call('/users/me', session)).json()) as { user?: { email?: string } }
expect(me.user?.email).toBe('[email protected]')
})
test('the start-up count: how many accounts are below the panel role', async () => {
const all = (await payload.find({ collection: 'users' as never, limit: 100 })).docs as unknown as { roles?: string[] }[]
const has = (role: string) => all.filter((u) => u.roles?.includes(role)).length
expect(await countBelowPanelRole(payload, 'users', 'editor')).toEqual({ all: all.length, below: all.length - has('admin') - has('editor') })
expect(await countBelowPanelRole(payload, 'users', 'admin')).toEqual({ all: all.length, below: all.length - has('admin') })
expect(has('user')).toBeGreaterThan(0)
})
})
describe('the password rule (accounts.password): twelve characters when a password is set', () => {
let admin: Session
const messageOf = async (res: Response) => JSON.stringify(await res.json())
beforeAll(async () => {
admin = await login('users', '[email protected]')
})
test('a new account: 11 characters refused with a clear message, 12 accepted', async () => {
const short = await post('/users', { email: '[email protected]', password: 'abcdefghijk', roles: ['editor'] }, admin)
expect(short.status).toBe(400)
expect(await messageOf(short)).toMatch(/at least 12 characters/)
expect((await post('/users', { email: '[email protected]', password: 'abcdefghijkl', roles: ['editor'] }, admin)).status).toBe(201)
// counted in characters, not bytes
expect((await post('/users', { email: '[email protected]', password: 'zażółć gęślą', roles: ['editor'] }, admin)).status).toBe(201)
})
test('in Polish for a Polish panel', async () => {
const res = await post('/users', { email: '[email protected]', password: 'krotkie', roles: ['editor'] }, { ...admin, 'accept-language': 'pl' })
expect(res.status).toBe(400)
expect(await messageOf(res)).toMatch(/co najmniej 12 znaków/)
})
test('not the account\'s own e-mail address', async () => {
const same = await post('/users', { email: '[email protected]', password: '[email protected]', roles: ['editor'] }, admin)
expect(same.status).toBe(400)
expect(await messageOf(same)).toMatch(/same as the e-mail/)
})
test('changing a password: checked; changing anything else: not', async () => {
const doc = (await payload.find({ collection: 'users' as never, where: { email: { equals: '[email protected]' } } })).docs[0]
expect((await call(`/users/${doc.id}`, admin, { body: JSON.stringify({ password: 'tooshort' }), method: 'PATCH' })).status).toBe(400)
expect((await call(`/users/${doc.id}`, admin, { body: JSON.stringify({ password: '[email protected]' }), method: 'PATCH' })).status).toBe(400) // its own address, looked up
expect((await call(`/users/${doc.id}`, admin, { body: JSON.stringify({ roles: ['user'] }), method: 'PATCH' })).status).toBe(200)
expect((await call(`/users/${doc.id}`, admin, { body: JSON.stringify({ password: 'a-new-long-password' }), method: 'PATCH' })).status).toBe(200)
await login('users', '[email protected]', 'a-new-long-password')
})
test('an EXISTING shorter password keeps logging in — nothing is checked at login', async () => {
// an account as an earlier version left it: a 6-character password, stored the way Payload stored it then
const old = await make('users', { email: '[email protected]', roles: ['editor'] })
const salt = randomBytes(32).toString('hex')
const hash = pbkdf2Sync('short1', salt, 25000, 512, 'sha256').toString('hex')
await payload.db.updateOne({ id: old.id, collection: 'users' as never, data: { hash, salt } as never })
const session = await login('users', '[email protected]', 'short1')
expect(((await (await call('/users/me', session)).json()) as { user?: { email?: string } }).user?.email).toBe('[email protected]')
// the rule meets it the next time the password is changed
expect((await call(`/users/${old.id}`, session, { body: JSON.stringify({ password: 'short2' }), method: 'PATCH' })).status).toBe(400)
})
test('a reset by e-mail is held to the rule too', async () => {
const token = await payload.forgotPassword({ collection: 'users' as never, data: { email: '[email protected]' }, disableEmail: true })
const short = await post('/users/reset-password', { password: 'tooshort', token })
expect(short.status).toBe(400)
expect(await messageOf(short)).toMatch(/at least 12 characters/)
// not the account's own address either: there is no e-mail in a reset request, the account is found by its token
const own = await post('/users/reset-password', { password: '[email protected]', token })
expect(own.status).toBe(400)
expect(await messageOf(own)).toMatch(/same as the e-mail/)
expect((await post('/users/reset-password', { password: 'reset-to-a-long-one', token })).status).toBe(200)
})
test('a bulk update is checked against every account it matches; a password that is not text is refused, not a server error', async () => {
await make('users', { email: '[email protected]', roles: ['editor'] })
const bulk = await patch('/users?where[email][equals][email protected]', { password: '[email protected]' }, admin)
expect(JSON.stringify(await bulk.json())).toMatch(/same as the e-mail/)
expect(await canLogIn('users', '[email protected]', '[email protected]')).toBe(false)
for (const notText of [123456789012, ['a-long-enough-one'], { length: 20 }]) {
const res = await post('/users', { email: `nt-${Math.random().toString(36).slice(2)}@example.com`, password: notText, roles: ['editor'] }, admin)
expect([JSON.stringify(notText), res.status]).toEqual([JSON.stringify(notText), 400])
}
})
test('visitor collections are not touched', async () => {
expect((await post('/customers', { email: '[email protected]', password: 'abc123' })).status).toBe(201)
})
test('the option, the checker and the switch', async () => {
expect(resolvePasswordRule(undefined)).toEqual({ minLength: 12 })
expect(resolvePasswordRule({ minLength: 16 })).toEqual({ minLength: 16 })
expect(resolvePasswordRule(false)).toBeNull()
for (const bad of ['12', 0, -1, 1.5, Number.NaN]) {expect(() => resolvePasswordRule({ minLength: bad as never })).toThrow(/minLength must be/)}
expect(checkPassword('abcdefghijk')).toBe('short')
expect(checkPassword('abcdefghijkl')).toBeNull()
expect(checkPassword('abcd', { minLength: 4 })).toBeNull()
expect(checkPassword('[email protected] ', { email: '[email protected]', minLength: 4 })).toBe('email')
const hooks = async (options: Record<string, unknown>) =>
(await ipalKit({ access: { authCollection: 'users' }, i18n, twoFactor: false, ...options } as never)({ admin: { user: 'users' }, collections: [{ slug: 'customers', auth: true, fields: [] }], secret: 'x' } as unknown as Config)).collections!.map((c) => [c.slug, c.hooks?.beforeOperation?.length ?? 0])
expect(await hooks({})).toEqual([['customers', 0], ['users', 1]])
expect(await hooks({ accounts: { password: false } })).toEqual([['customers', 0], ['users', 0]])
expect(await hooks({ accounts: false })).toEqual([['customers', 0], ['users', 0]])
})
})
describe('accounts.panelRole: the config', () => {
const build = (options: Record<string, unknown>, incoming: Partial<Config> = {}) =>
ipalKit({ access: { authCollection: 'users' }, i18n, twoFactor: false, ...options } as never)({ collections: [], secret: 'x', ...incoming } as unknown as Config)
const adminRule = (config: Config) => config.collections!.find((c) => c.slug === 'users')!.access?.admin
test('on by default at editor; a role, false and accounts: false change it', async () => {
expect(resolvePanelRole(undefined)).toBe('editor')
expect(resolvePanelRole('admin')).toBe('admin')
expect(resolvePanelRole('user')).toBeNull() // the lowest role = everyone, as before
expect(resolvePanelRole(false)).toBeNull()
expect(() => resolvePanelRole('boss' as never)).toThrow(/panelRole must be one of/)
expect(adminRule(await build({}))).toBeTypeOf('function')
expect(adminRule(await build({ accounts: { panelRole: 'user' } }))).toBeUndefined()
expect(adminRule(await build({ accounts: { panelRole: false } }))).toBeUndefined()
expect(adminRule(await build({ accounts: false }))).toBeUndefined()
// without `access` there are no roles to ask about
expect(adminRule(await ipalKit({ i18n, twoFactor: false })({ collections: [], secret: 'x' } as unknown as Config))).toBeUndefined()
})
test("the project's own rule wins: on its own collection, and through access.authAccess", async () => {
const mine = () => true
const own = await build({}, { collections: [{ slug: 'users', access: { admin: mine }, auth: true, fields: [] }] } as never)
expect(adminRule(own)).toBe(mine)
const injected = await build({ access: { authAccess: { admin: mine }, authCollection: 'users' } })
expect(adminRule(injected)).toBe(mine)
// the project's own collection without a rule gets the plugin's
const plain = await build({}, { collections: [{ slug: 'users', auth: true, fields: [] }] } as never)
expect(adminRule(plain)).toBeTypeOf('function')
})
test('the rule looks at the role, not at the second factor, and only at staff accounts', () => {
const source = { staffCollections: ['users'] }
const ask = (user: unknown, minimum?: 'admin' | 'editor') => panelAccess(minimum)({ req: { payload: source, user } } as never)
expect(ask({ collection: 'users', roles: ['editor'] })).toBe(true)
expect(ask({ _strategy: 'local-jwt', collection: 'users', hasTotp: true, roles: ['admin'] })).toBe(true) // still owes its code: the 2FA screens are part of the panel
expect(ask({ collection: 'users', roles: ['user'] })).toBe(false)
expect(ask({ collection: 'users', roles: [] })).toBe(false)
expect(ask({ collection: 'users' })).toBe(false)
expect(ask({ collection: 'customers', roles: ['admin'] })).toBe(false)
expect(ask(null)).toBe(false)
expect(ask({ collection: 'users', roles: ['editor'] }, 'admin')).toBe(false)
})
})
describe('accounts.adminOnlyCreate / firstUserRoute: the config', () => {
const build = (options: Record<string, unknown>, incoming: Partial<Config> = {}) =>
ipalKit({ access: { authCollection: 'users', staffCollections: ['staff2'] }, i18n, twoFactor: false, ...options } as never)({
collections: [{ slug: 'staff2', auth: true, fields: [] }, { slug: 'customers', access: { create: () => true }, auth: true, fields: [] }, { slug: 'pages', fields: [] }],
secret: 'x',
...incoming,
} as unknown as Config)
const of = (config: Config, slug: string) => config.collections!.find((c) => c.slug === slug)!
test('staff collections without rules get them; a rule the project wrote stays; other collections are not touched', async () => {
const config = await build({})
expect(of(config, 'staff2').access?.create).toBeTypeOf('function')
expect(of(config, 'staff2').access?.update).toBeTypeOf('function')
expect(of(config, 'staff2').access?.delete).toBeTypeOf('function')
expect(of(config, 'users').access?.create).toBeTypeOf('function') // the injected collection had adminOnly already
expect(String(of(config, 'customers').access?.create)).toContain('true')
expect(of(config, 'customers').access?.update).toBeUndefined() // not a staff collection
expect(of(config, 'pages').access?.create).toBeUndefined()
const mine = () => true
const own = await build({}, { collections: [{ slug: 'users', access: { create: mine, delete: mine, update: mine }, auth: true, fields: [] }, { slug: 'staff2', auth: true, fields: [] }] } as never)
expect([of(own, 'users').access?.create, of(own, 'users').access?.update, of(own, 'users').access?.delete]).toEqual([mine, mine, mine])
// the collection that carries the plugin's roles: the admin rule, although the field is injected later
const ownNoRule = await build({}, { collections: [{ slug: 'users', auth: true, fields: [] }] } as never)
expect(of(ownNoRule, 'users').access?.create).toBe(staffCreateAccess)
expect(of(ownNoRule, 'users').access?.delete).toBe(staffCreateAccess)
})
test('whose roles: the plugin\'s rule only where the roles are the plugin\'s', () => {
const roles = (options: unknown[]) => ({ slug: 'x', fields: [{ name: 'roles', type: 'select', hasMany: true, options }] }) as never
expect(hasPluginRoles(roles(['user', 'editor', 'admin']))).toBe(true)
expect(hasPluginRoles(roles([{ label: 'Admin', value: 'admin' }, { label: 'Editor', value: 'editor' }]))).toBe(true)
expect(hasPluginRoles(roles(['superadmin', 'writer']))).toBe(false)
expect(hasPluginRoles(roles(['admin', 'writer']))).toBe(false) // one foreign value: the project's own roles
expect(hasPluginRoles(roles([]))).toBe(false)
expect(hasPluginRoles({ slug: 'x', fields: [] })).toBe(false)
expect(hasPluginRoles({ slug: 'x', fields: [{ name: 'roles', type: 'text' }] } as never)).toBe(false)
const staff = { staffCollections: ['users', 'agents', 'crew'] }
const ask = (rule: ReturnType<typeof staffUpdateAccess>, user: unknown) => rule({ req: { payload: staff, user } } as never)
const admin = { id: 1, collection: 'users', roles: ['admin'] }
const editor = { id: 2, collection: 'users', roles: ['editor'] }
const customer = { id: 2, collection: 'customers', roles: ['admin'] }
// the plugin's roles
expect(ask(staffCreateAccess, admin)).toBe(true)
expect(ask(staffCreateAccess, editor)).toBe(false)
expect(ask(staffUpdateAccess('users'), admin)).toBe(true)
expect(ask(staffUpdateAccess('users'), editor)).toEqual({ id: { equals: 2 } })
expect(ask(staffUpdateAccess('agents'), editor)).toBe(false) // "self" is an account of THAT collection: id 2 of another one is somebody else
expect(ask(staffUpdateAccess('users'), customer)).toBe(false)
expect(ask(staffUpdateAccess('users'), null)).toBe(false)
// the project's own roles
const crew = sameStaffCollectionAccess('crew')
expect(ask(crew, { id: 5, collection: 'crew', roles: ['worker'] })).toBe(true)
expect(ask(crew, admin)).toBe(true)
expect(ask(crew, editor)).toBe(false)
expect(ask(crew, customer)).toBe(false)
expect(ask(crew, null)).toBe(false)
expect(ask(sameStaffCollectionAccess('shop'), { id: 5, collection: 'shop' })).toBe(false) // not a staff collection: never by this rule
})
test('the switches', async () => {
const guards = (config: Config, slug: string) => of(config, slug).hooks?.beforeOperation?.length ?? 0
const firstUser = (config: Config, slug: string) => (of(config, slug).endpoints || []).filter((e) => e.path === '/first-register').length
const on = await build({})
// staff collections: the password rule; every auth collection: the first-user endpoint
expect([guards(on, 'users'), guards(on, 'staff2'), guards(on, 'customers'), guards(on, 'pages')]).toEqual([1, 1, 0, 0])
expect([firstUser(on, 'users'), firstUser(on, 'staff2'), firstUser(on, 'customers'), firstUser(on, 'pages')]).toEqual([1, 1, 1, 0])
const payloadWay = await build({ accounts: { adminOnlyCreate: false, adminOnlyWrite: false, firstUserRoute: 'all', password: false } })
expect(of(payloadWay, 'staff2').access).toEqual({ read: staffReadAccess, readVersions: staffReadAccess })
expect(of(await build({ accounts: { adminOnlyCreate: false, adminOnlyWrite: false, firstUserRoute: 'all', password: false, staffOnlyRead: false } }), 'staff2').access).toBeUndefined()
expect([guards(payloadWay, 'staff2'), firstUser(payloadWay, 'staff2')]).toEqual([0, 0])
// each switch on its own
const createOnly = await build({ accounts: { adminOnlyWrite: false } })
expect([typeof of(createOnly, 'staff2').access?.create, of(createOnly, 'staff2').access?.update, of(createOnly, 'staff2').access?.delete]).toEqual(['function', undefined, undefined])
const writeOnly = await build({ accounts: { adminOnlyCreate: false } })
expect([of(writeOnly, 'staff2').access?.create, typeof of(writeOnly, 'staff2').access?.update, typeof of(writeOnly, 'staff2').access?.delete]).toEqual([undefined, 'function', 'function'])
const off = await build({ accounts: false })
expect(of(off, 'staff2').access?.create).toBeUndefined()
expect(of(off, 'staff2').access?.update).toBeUndefined()
expect([guards(off, 'users'), firstUser(off, 'users')]).toEqual([0, 0])
await expect(build({ accounts: { firstUserRoute: 'everyone' } })).rejects.toThrow(/firstUserRoute must be/)
// a collection that turned its endpoints off keeps them off
const noEndpoints = await build({}, { collections: [{ slug: 'staff2', auth: true, endpoints: false, fields: [] }] } as never)
expect(of(noEndpoints, 'staff2').endpoints).toBe(false)
// without `access` the rules still apply to the panel's login collection — as "an account of this collection":
// without the plugin's roles nobody is an admin to it
const noAccess = await ipalKit({ i18n, twoFactor: false })({ collections: [{ slug: 'users', auth: true, fields: [] }], secret: 'x' } as unknown as Config)
expect(of(noAccess, 'users').access?.create).toBeTypeOf('function')
expect(of(noAccess, 'users').access?.create).not.toBe(staffCreateAccess)
})
test('the roles field: protected where the plugin\'s update rule is in force and the field has no access of its own', async () => {
const rolesField = (config: Config, slug: string) => of(config, slug).fields.find((f) => 'name' in f && f.name === 'roles') as { access?: { update?: unknown } }
const own = { name: 'roles', type: 'select', hasMany: true, options: ['user', 'editor', 'admin'] }
const collections = (extra: object = {}, field: object = own) => ({ collections: [{ slug: 'staff2', auth: true, fields: [{ type: 'row', fields: [field] }], ...extra }] }) as never
const inRow = (config: Config) => (of(config, 'staff2').fields[0] as unknown as { fields: { access?: { update?: unknown } }[] }).fields[0]
// the plugin's roles: only an admin; found inside a row too; the project's own field object is not changed
expect(inRow(await build({}, collections())).access?.update).toBe(rolesByAdminOnly)
expect((own as { access?: unknown }).access).toBeUndefined()
// roles of the project's own: never the account itself
const mine = inRow(await build({}, collections({}, { ...own, options: ['boss', 'worker'] }))).access?.update as (a: unknown) => boolean
expect(mine({ id: 5, req: { user: { id: 5, collection: 'staff2' } } })).toBe(false)
expect(mine({ id: '5', req: { user: { id: 5, collection: 'staff2' } } })).toBe(false)
expect(mine({ id: 6, req: { user: { id: 5, collection: 'staff2' } } })).toBe(true)
expect(mine({ id: 5, req: { user: { id: 5, collection: 'users' } } })).toBe(true) // id 5 of another collection is somebody else
expect(rolesNotOwn('x')({ id: undefined, req: { user: { id: 5, collection: 'x' } } } as never)).toBe(true) // a create
// left alone: a field with its own rule, a collection with its own update rule, the switch
const fieldRule = () => true
expect(inRow(await build({}, collections({}, { ...own, access: { update: fieldRule } }))).access?.update).toBe(fieldRule)
expect(inRow(await build({}, collections({ access: { update: () => true } }))).access).toBeUndefined()
expect(inRow(await build({ accounts: { adminOnlyWrite: false } }, collections())).access).toBeUndefined()
// the injected collection's field has the plugin's own access already
expect(rolesField(await build({}), 'users').access?.update).toBeTypeOf('function')
})
// Review round 3 (R3-1): nothing may depend on recognising Payload's default — a production build minifies
// its name away. The functions below have the names a bundler gives them: none that means anything.
test('late collections: the plugin\'s rule goes in FRONT of whatever is there, whatever it is called', async () => {
const g = ({ req }: { req: { user: unknown } }) => Boolean(req.user) // Payload's default as a built site holds it: no telling name
const bw = ({ req }: { req: { user: unknown } }) => Boolean(req.user)
const narrow = () => false
const where = () => ({ team: { equals: 'a' } })
const hook = () => undefined
const late = { slug: 'late', access: { create: g, delete: narrow, read: g, readVersions: g, unlock: bw, update: where }, auth: true, endpoints: [{ handler: () => undefined, method: 'post', path: '/first-register' }], fields: [{ name: 'roles', type: 'select', access: {}, options: ['user', 'admin'] }] }
const seen = { slug: 'users', access: { create: g }, auth: true, custom: { ipalAccounts: true }, endpoints: [], fields: [] }
const visitors = { slug: 'visitors', access: { create: g }, auth: true, endpoints: [], fields: [] }
const asIs = { slug: 'as-is', access: { create: g }, auth: true, custom: { ipal: { accountRules: false } }, endpoints: [], fields: [] }
const pages = { slug: 'pages', access: {}, endpoints: [], fields: [] }
const config = { collections: [late, pages, seen, visitors, asIs] } as never
const staff = { staffCollections: ['users', 'late', 'as-is'] }
expect(adoptLateAuthCollections(config, ['users', 'late', 'as-is'], { beforeOperation: hook })).toEqual([
{ slug: 'late', applied: ['create', 'update', 'delete', 'unlock', 'read', 'readVersions', 'roles'], firstUser: true, password: true },
{ slug: 'visitors', applied: [], firstUser: true, password: false },
{ slug: 'as-is', applied: [], firstUser: true, password: true }, // its own rules as they are: it said so
])
const ask = (operation: keyof typeof late.access, user: unknown) => (late.access[operation] as (a: unknown) => unknown)({ req: { payload: staff, user } })
const admin = { id: 1, collection: 'users', roles: ['admin'] }
const editor = { id: 2, collection: 'users', roles: ['editor'] }
const own = { id: 7, collection: 'late', roles: ['user'] }
const customer = { id: 9, collection: 'customers', roles: ['admin'] }
for (const operation of ['create', 'read', 'readVersions', 'update', 'delete', 'unlock'] as const) {
expect([operation, await ask(operation, customer)]).toEqual([operation, false])
expect([operation, await ask(operation, null)]).toEqual([operation, false])
}
expect(await ask('create', editor)).toBe(false)
expect(await ask('create', admin)).toBe(true)
expect(await ask('unlock', editor)).toBe(false) // an admin, as the table in the docs says
expect(await ask('unlock', admin)).toBe(true)
expect(await ask('read', editor)).toBe(true)
expect(await ask('readVersions', editor)).toBe(true)
// a rule of the collection's own is kept, and only ever narrows: both must allow
expect(await ask('delete', admin)).toBe(false)
expect(await ask('update', admin)).toEqual({ team: { equals: 'a' } })
expect(await ask('update', own)).toEqual({ and: [{ id: { equals: 7 } }, { team: { equals: 'a' } }] })
expect((late.fields[0] as { access?: { update?: unknown } }).access?.update).toBe(rolesByAdminOnly)
expect((late as { hooks?: { beforeOperation?: unknown[] } }).hooks?.beforeOperation).toEqual([hook])
expect((late.endpoints[0] as { custom?: { ipalFirstUser?: boolean } }).custom?.ipalFirstUser).toBe(true) // in FRONT of Payload's
// a late auth collection that is not staff: the first-user endpoint only
expect(visitors.access.create).toBe(g)
expect(asIs.access.create).toBe(g)
// what ipalKit saw at config time, and what is not an auth collection: untouched
expect(seen.access.create).toBe(g)
expect([seen.endpoints.length, pages.endpoints.length]).toEqual([0, 0])
// a second call (a request after the start) changes nothing
expect(adoptLateAuthCollections(config, ['users', 'late'], { beforeOperation: hook })).toEqual([])
expect(late.endpoints).toHaveLength(2)
// a staff slug without an auth collection
expect(unknownStaffCollections(config, ['users', 'late', 'pages', 'ghost'])).toEqual(['pages', 'ghost'])
// the combiner
expect(await bothAllow(() => true, undefined)({} as never)).toBe(true)
expect(await bothAllow(() => false, () => { throw new Error('not asked') })({} as never)).toBe(false)
})
test('the rules are on the collections BEFORE the 2FA package wraps them', async () => {
// the package gives every collection a create / update / delete of its own; afterwards "no rule" cannot be seen
const seen: Record<string, unknown> = {}
const factory = (o: { collection: string }) => (c: Config) => {
for (const col of c.collections ?? []) {seen[col.slug] = { ...col.access }}
return withTotpParts({ ...c, collections: (c.collections ?? []).map((col) => ({ ...col, access: { create: () => true, delete: () => true, update: () => true, ...col.access } })) }, o.collection)
}
await build({ twoFactor: { issuer: 'A', plugin: factory as never } })
expect(Object.keys(seen.staff2 as object).sort()).toEqual(['create', 'delete', 'read', 'readVersions', 'unlock', 'update'])
expect(seen.customers).toEqual({ create: expect.any(Function) })
})
test('access.firstUserAdmin: false and the panel role: the first account must be able to get in', async () => {
const adminRule = (config: Config) => of(config, 'users').access?.admin
// the default panel role steps aside (a line at start says so)…
expect(adminRule(await build({ access: { authCollection: 'users', firstUserAdmin: false } }))).toBeUndefined()
// …a role the project asked for is refused at start, with the ways out
await expect(build({ access: { authCollection: 'users', firstUserAdmin: false }, accounts: { panelRole: 'editor' } })).rejects.toThrow(/nobody who can open the panel[\s\S]*defaultRole/)
await expect(build({ access: { authCollection: 'users', defaultRole: 'editor', firstUserAdmin: false }, accounts: { panelRole: 'admin' } })).rejects.toThrow(/nobody who can open the panel/)
// a default role that reaches the panel is fine
expect(adminRule(await build({ access: { authCollection: 'users', defaultRole: 'editor', firstUserAdmin: false } }))).toBeTypeOf('function')
expect(adminRule(await build({ access: { authCollection: 'users', defaultRole: 'editor', firstUserAdmin: false }, accounts: { panelRole: 'editor' } }))).toBeTypeOf('function')
// and nothing to decide when the rule is off
expect(adminRule(await build({ access: { authCollection: 'users', firstUserAdmin: false }, accounts: { panelRole: false } }))).toBeUndefined()
})
test('openSignUpCollections: slugs of auth collections an anonymous request may create in', async () => {
const collections = {
customers: { config: { slug: 'customers', access: { create: () => true }, auth: true } },
members: { config: { slug: 'members', access: { create: ({ req }: { req: { user: unknown } }) => Boolean(req.user) }, auth: true } },
pages: { config: { slug: 'pages', access: { create: () => true } } },
weird: { config: { slug: 'weird', access: { create: () => { throw new Error('x') } }, auth: true } },
}
expect(await openSignUpCollections({ collections } as never)).toEqual(['customers'])
})
test('staffCollectionsOpenToOthers: staff collections an account of a non-staff collection may write to', async () => {
const anyone = ({ req }: { req: { user: unknown } }) => Boolean(req.user) // Payload's default
const collections = {
agents: { config: { slug: 'agents', access: { create: staffCreateAccess, delete: anyone, update: anyone }, auth: true } },
customers: { config: { slug: 'customers', access: { create: () => true, update: anyone }, auth: true } }, // not staff: not its business
users: { config: { slug: 'users', access: { create: staffCreateAccess, delete: staffCreateAccess, read: staffReadAccess, readVersions: staffReadAccess, unlock: staffCreateAccess, update: staffUpdateAccess('users') }, auth: true } },
weird: { config: { slug: 'weird', access: { update: () => { throw new Error('x') } }, auth: true } },
}
expect(await staffCollectionsOpenToOthers({ collections, config: { admin: { user: 'users' }, custom: { ipal: { staffCollections: ['agents', 'weird'] } } } } as never)).toEqual(['agents:delete', 'agents:read', 'agents:readVersions', 'agents:unlock', 'agents:update', 'weird:create', 'weird:delete', 'weird:read', 'weird:readVersions', 'weird:unlock']) // no rule = Payload's default, open; a rule that throws = closed
})
})
}
+4 -4
View File
@@ -139,7 +139,7 @@ describe('cookie crawl — panel button → service → results', () => {
expect(crawl.violations.map((v: { name: string }) => v.name).sort()).toEqual(['_fbp', 'tracker.invalid'])
expect(sendEmail).toHaveBeenCalledWith(expect.objectContaining({ subject: expect.stringContaining('2'), to: ['[email protected]'] }))
expect(await CookieCrawlAlert({ payload })).not.toBeNull()
expect(await CookieCrawlAlert({ audience: 'all', payload })).not.toBeNull()
sendEmail.mockRestore()
}, 60_000)
@@ -158,8 +158,8 @@ describe('cookie crawl — panel button → service → results', () => {
const crawl = (await payload.findGlobal({ slug: 'cookie-crawl' as never })) as unknown as CrawlDoc
expect(crawl.summary.violations).toBe(0)
// No crawl problem left; only the approval reminder remains (drafts from the first crawl wait).
expect(await CookieCrawlAlert({ approval: false, payload })).toBeNull()
expect(await CookieCrawlAlert({ crawl: false, payload })).not.toBeNull()
expect(await CookieCrawlAlert({ approval: false, audience: 'all', payload })).toBeNull()
expect(await CookieCrawlAlert({ audience: 'all', crawl: false, payload })).not.toBeNull()
})
test('a failed crawl is reported and the next one may start', async () => {
@@ -168,6 +168,6 @@ describe('cookie crawl — panel button → service → results', () => {
expect((await call(2, { body: { error: 'site down', jobId, ok: false }, token: TOKEN })).status).toBe(200)
const status = (await (await call(0, { user: editor })).json()) as Record<string, unknown>
expect(status).toMatchObject({ error: 'site down', status: 'failed' })
expect(await CookieCrawlAlert({ payload })).not.toBeNull()
expect(await CookieCrawlAlert({ audience: 'all', payload })).not.toBeNull()
})
})
+110
View File
@@ -0,0 +1,110 @@
/**
* M1: dashboard alerts by role. The widgets read data only some roles may read (with access control off), so
* they decide themselves who sees what: an admin the detail, an editor a neutral line, nobody else anything —
* and a session that still owes its second factor nothing at all.
*/
import type React from 'react'
import { renderToStaticMarkup } from 'react-dom/server'
import { describe, expect, test } from 'vitest'
import { CookieCrawlAlert } from '../src/modules/consent/scanner/crawl/CookieCrawlAlert.js'
import { IntegrationAlerts } from '../src/modules/integrations/IntegrationAlerts.js'
import { ipalKit } from '../src/plugin.js'
const ERROR_TEXT = 'SMTP-ERROR-DETAIL: 535 authentication failed for [email protected]'
const payloadWith = (twoFactor: boolean) => ({
config: {
admin: { user: 'users' },
collections: [{ slug: 'users', auth: true, fields: [{ name: 'roles', type: 'select' }] }],
custom: { ipal: { staffCollections: ['users'], ...(twoFactor ? { twoFactor: { collection: 'users', requireSetup: true } } : {}) } },
},
count: async () => ({ totalDocs: 2 }),
findGlobal: async ({ slug }: { slug: string }) =>
slug === 'site-integrations'
? { emailStatus: { code: 'custom', message: ERROR_TEXT, state: 'degraded' }, turnstileSecretKey: 's', turnstileSiteKey: 'k' }
: { error: 'CRAWL-ERROR-DETAIL', status: 'failed', summary: { newUnknown: 0, violations: 0 } },
})
const user = (roles: string[], more: Record<string, unknown> = {}) => ({ id: 1, collection: 'users', roles, ...more })
const html = async (node: Promise<React.ReactNode>) => {
const out = await node
return out ? renderToStaticMarkup(out as React.ReactElement) : ''
}
const integrations = (u: unknown, props: Record<string, unknown> = {}, twoFactor = false) => html(IntegrationAlerts({ payload: payloadWith(twoFactor) as never, user: u as never, ...props }))
const cookies = (u: unknown, props: Record<string, unknown> = {}, twoFactor = false) => html(CookieCrawlAlert({ payload: payloadWith(twoFactor) as never, user: u as never, ...props }))
describe('IntegrationAlerts', () => {
test('an admin sees what is failing and the link', async () => {
const out = await integrations(user(['admin']))
expect(out).toContain('SMTP-ERROR-DETAIL')
expect(out).toContain('/admin/globals/site-integrations')
expect(out).toContain('role="alert"')
})
test('an editor sees that something needs attention and whom to ask — no detail, no link', async () => {
const out = await integrations(user(['editor']))
expect(out).toContain('An integration needs attention')
expect(out).toContain('Ask an administrator')
expect(out).not.toContain('SMTP-ERROR-DETAIL')
expect(out).not.toContain('[email protected]')
expect(out).not.toContain('site-integrations')
expect(out).toContain('role="status"')
})
test('a plain user, a visitor account, nobody: nothing', async () => {
expect(await integrations(user(['user']))).toBe('')
expect(await integrations({ id: 1, collection: 'customers', roles: ['admin'] })).toBe('')
expect(await integrations(null)).toBe('')
expect(await integrations(undefined)).toBe('')
})
test('a session that still owes its second factor sees nothing — admin or editor', async () => {
const owes = { _strategy: 'local-jwt', hasTotp: true }
expect(await integrations(user(['admin'], owes), {}, true)).toBe('')
expect(await integrations(user(['editor'], owes), {}, true)).toBe('')
expect(await integrations(user(['admin'], { _strategy: 'local-jwt', hasTotp: false }), {}, true)).toBe('') // TOTP not set up
expect(await integrations(user(['admin'], { _strategy: 'totp', hasTotp: true }), {}, true)).toContain('SMTP-ERROR-DETAIL')
})
test('details: editor / all loosen it; nothing failing renders nothing for anyone', async () => {
expect(await integrations(user(['editor']), { details: 'editor' })).toContain('SMTP-ERROR-DETAIL')
expect(await integrations(user(['user']), { details: 'editor' })).toBe('')
expect(await integrations(user(['user']), { details: 'all' })).toContain('SMTP-ERROR-DETAIL')
expect(await integrations(null, { details: 'all' })).toContain('SMTP-ERROR-DETAIL') // as before the change
const fine = { ...payloadWith(false), findGlobal: async () => ({ turnstileSecretKey: 's', turnstileSiteKey: 'k' }) }
expect(await html(IntegrationAlerts({ payload: fine as never, user: user(['admin']) as never }))).toBe('')
})
test('Polish for a Polish panel', async () => {
expect(await integrations(user(['editor']), { i18n: { language: 'pl' } })).toContain('Poproś administratora')
})
})
describe('CookieCrawlAlert', () => {
test('editors and admins see it; others, and a session that owes its code, do not', async () => {
expect(await cookies(user(['admin']))).toContain('cookie-crawl-alert')
expect(await cookies(user(['editor']))).toContain('CRAWL-ERROR-DETAIL') // the crawl result is theirs to read
expect(await cookies(user(['user']))).toBe('')
expect(await cookies(null)).toBe('')
expect(await cookies(user(['editor'], { _strategy: 'local-jwt', hasTotp: true }), {}, true)).toBe('')
expect(await cookies(user(['user']), { audience: 'all' })).toContain('cookie-crawl-alert')
})
})
describe('ipalKit({ dashboardAlerts })', () => {
const i18n = { defaultLocale: 'en', locales: [{ code: 'en', label: 'English' }] }
const propsOf = async (options: Record<string, unknown>) => {
const config = await ipalKit({ cookieScanner: { crawl: true }, i18n, twoFactor: false, ...options } as never)({ collections: [], secret: 'x' } as never)
return JSON.stringify(config.admin?.components?.beforeDashboard)
}
test('default: the components decide (admin detail, editor cookies); the option is passed on', async () => {
const plain = await propsOf({})
expect(plain).toContain('IntegrationAlerts')
expect(plain).not.toContain('"details"')
expect(plain).not.toContain('"audience"')
const loose = await propsOf({ dashboardAlerts: { cookies: 'all', integrations: 'all' } })
expect(loose).toContain('"details":"all"')
expect(loose).toContain('"audience":"all"')
})
})
+12
View File
@@ -149,6 +149,18 @@ describe('docs ↔ code', () => {
expect(broken).toEqual([])
})
test('no client-component example imports the main entry', () => {
// '@intecion/ipal-kit' reaches server-only modules: a 'use client' file that imports it does not build with webpack.
const offending: string[] = []
for (const file of docs) {
const blocks = file.endsWith('.md') ? [...read(file).matchAll(/```[a-z]*\n([\s\S]*?)```/g)].map((m) => m[1]) : [read(file)]
for (const block of blocks) {
if (/^['"]use client['"]/m.test(block) && /^import (?!type\b)[^'"]*?from ['"]@intecion\/ipal-kit['"]/m.test(block)) {offending.push(file)}
}
}
expect(offending).toEqual([])
})
test('every module page is listed in docs/README.md', () => {
const index = read('docs/README.md')
const pages = readdirSync(path.join(root, 'docs')).filter((n) => n.endsWith('.md') && !['CHANGELOG.md', 'README.md'].includes(n))
+150 -1
View File
@@ -99,6 +99,139 @@ describe('importmap rule and the 2FA back-link check', () => {
})
})
describe('2FA setup required: what a project must have', () => {
const MAP = 'src/app/(payload)/admin/importMap.js'
const NEW = ['@intecion/ipal-kit/admin#TwoFactorStatusField', '@intecion/ipal-kit/admin#TwoFactorAlert']
const OLD = ['@clocklimited/payload-2fa/rsc#TOTPSetup', '@intecion/ipal-kit/admin#TotpRedirectProvider', '@intecion/ipal-kit/admin#SafeTotpView']
const entries = (names: string[]) => `export const importMap = { ${names.map((n) => `"${n}": X`).join(', ')} }`
const plugin = {
...base(),
...installed('@clocklimited/payload-2fa', '3.0.0'),
'node_modules/@intecion/ipal-kit/dist/exports/admin.js': 'export { SafeTotpView, TotpRedirectProvider, TwoFactorAlert, TwoFactorStatusField }',
'node_modules/@intecion/ipal-kit/dist/modules/security/totp/secondFactor.js': "export const SETUP_FROM_FIELD = 'totpSetupFrom'",
}
const lacks = async (config: string, map: string[]) =>
(await doctor(project({ ...plugin, [MAP]: entries(map), 'src/payload.config.ts': config }), ['importmap'])).findings.filter((f) => /import map lacks/.test(f.message)).map((f) => f.message).join()
test('the import map must hold the status field and the dashboard notice', async () => {
const missing = await lacks('twoFactor: { plugin: payloadTotp }', OLD)
for (const name of NEW) {expect(missing).toContain(name)}
const complete = await lacks('twoFactor: { plugin: payloadTotp }', [...OLD, ...NEW])
for (const name of NEW) {expect(complete).not.toContain(name)}
})
test.each([
['requireSetup: false', []],
['guard: false', []],
['requireSetup: { statusField: false }', [NEW[1]]],
['requireSetup: { dashboardNotice: false }', [NEW[0]]],
])('%s: only what is still on is expected', async (option, expected) => {
const missing = await lacks(`twoFactor: { plugin: payloadTotp, ${option} }`, OLD)
for (const name of NEW) {expect([name, missing.includes(name)]).toEqual([name, expected.includes(name)])}
})
const migration = async (files: Record<string, object | string>, config = 'twoFactor: { plugin: payloadTotp }') =>
(await doctor(project({ ...plugin, [MAP]: entries([...OLD, ...NEW]), 'src/payload.config.ts': config, ...files }), ['2fa'])).findings.filter((f) => /totp_setup_from/.test(f.message)).map((f) => f.severity)
test('Postgres / SQLite: a migration must add the 2FA column, or nobody can log in', async () => {
const pg = installed('@payloadcms/db-postgres', '3.94.1')
expect(await migration({ ...pg, 'src/migrations/20260101_init.ts': 'await db.execute(sql`CREATE TABLE "users" ("id" serial)`)' })).toEqual(['error'])
expect(await migration({ ...pg, 'src/migrations/20260101_init.ts': 'x', 'src/migrations/20261124_totp.ts': 'ALTER TABLE "users" ADD COLUMN "totp_setup_from" timestamp' })).toEqual([])
expect(await migration({ ...pg, 'migrations/20261124_totp.json': '{ "columns": { "totpSetupFrom": {} } }' })).toEqual([])
expect(await migration(pg)).toEqual(['warning']) // no migrations folder: the doctor cannot see how the schema gets there
expect(await migration({ ...installed('@payloadcms/db-sqlite', '3.94.1'), 'src/migrations/20260101_init.ts': 'x' })).toEqual(['error'])
})
test('MongoDB, 2FA off, or a plugin version without the column: nothing to report', async () => {
expect(await migration({ ...installed('@payloadcms/db-mongodb', '3.94.1'), 'src/migrations/20260101_init.ts': 'x' })).toEqual([])
expect(await migration({ ...installed('@payloadcms/db-postgres', '3.94.1'), 'src/migrations/20260101_init.ts': 'x' }, 'twoFactor: false')).toEqual([])
const older = { ...installed('@payloadcms/db-postgres', '3.94.1'), 'node_modules/@intecion/ipal-kit/dist/modules/security/totp/secondFactor.js': 'export {}', 'src/migrations/20260101_init.ts': 'x' }
expect(await migration(older)).toEqual([])
})
})
describe('M1 rules: access-missing, turnstile-degraded, turnstile-env-key', () => {
const run = async (config: string, only: string[], deepStatus?: object) =>
rules(await doctor(project({ ...base(), 'src/payload.config.ts': config }), only, deepStatus ? { deepStatus } : {}))
test('access-missing: ipalKit without `access` means every account is an admin', async () => {
expect(await run("plugins: [ipalKit({ i18n, twoFactor: { issuer: 'A', plugin: payloadTotp } })]", ['access-missing'])).toEqual(['access-missing:warning'])
// a collection's own access rules are not the plugin option
expect(await run("collections: [{ slug: 'pages', access: { read: () => true } }], plugins: [ipalKit({ i18n })]", ['access-missing'])).toEqual(['access-missing:warning'])
for (const ok of ["ipalKit({ access: { authCollection: 'users' }, i18n })", "ipalKit({ i18n, access: { defaultRole: 'editor' } })", 'ipalKit({ access: {}, i18n })', 'ipalKit({ access: accessOptions, i18n })', '// no plugin here']) {
expect([ok, await run(`plugins: [${ok}]`, ['access-missing'])]).toEqual([ok, []])
}
})
test('turnstile-degraded: a warning, an error after a day', async () => {
const at = (hoursAgo: number) => new Date(Date.parse(`${TODAY}T12:00:00Z`) - hoursAgo * 3_600_000).toISOString()
const cfg = "ipalKit({ access: { authCollection: 'users' } })"
expect(await run(cfg, ['turnstile-degraded'], { turnstile: { code: 'invalid-input-secret', since: at(2), state: 'degraded' } })).toEqual(['turnstile-degraded:warning'])
expect(await run(cfg, ['turnstile-degraded'], { turnstile: { code: 'invalid-input-secret', since: at(48), state: 'degraded' } })).toEqual(['turnstile-degraded:error'])
expect(await run(cfg, ['turnstile-degraded'], { turnstile: { state: 'degraded' } })).toEqual(['turnstile-degraded:warning'])
// the day is counted in hours from the middle of the run's date (the clock itself when the run is for today), not to its end:
// a state that began late the evening before is not "a day old" in the morning
expect(await run(cfg, ['turnstile-degraded'], { turnstile: { since: at(13), state: 'degraded' } })).toEqual(['turnstile-degraded:warning'])
expect(await run(cfg, ['turnstile-degraded'], { turnstile: { since: at(23), state: 'degraded' } })).toEqual(['turnstile-degraded:warning'])
expect(await run(cfg, ['turnstile-degraded'], { turnstile: { since: at(24), state: 'degraded' } })).toEqual(['turnstile-degraded:error'])
expect(await run(cfg, ['turnstile-degraded'], { turnstile: { since: at(48), state: 'ok' } })).toEqual([])
expect(await run(cfg, ['turnstile-degraded'], { turnstile: null })).toEqual([])
expect(await run(cfg, ['turnstile-degraded'])).toEqual([]) // no deep status: nothing to say
})
test('turnstile-env-key: the secret still comes from the environment', async () => {
const cfg = "ipalKit({ access: { authCollection: 'users' } })"
expect(await run(cfg, ['turnstile-env-key'], { turnstileSecretFromEnv: true })).toEqual(['turnstile-env-key:warning'])
expect(await run(cfg, ['turnstile-env-key'], { turnstileSecretFromEnv: false })).toEqual([])
expect(await run(cfg, ['turnstile-env-key'])).toEqual([])
})
test('csrf-empty: without serverURL and csrf Payload takes the login cookie from any origin', async () => {
// the word is spelled in two parts: test/testConfig.test.ts refuses test files that name Payload's config builder
const build = (body: string) => `export default ${'build'}${'Config'}(${body})`
expect(await run(build("{ plugins: [ipalKit({ access: { authCollection: 'users' } })] }"), ['csrf-empty'])).toEqual(['csrf-empty:warning'])
expect(await run(build('{ serverURL: process.env.NEXT_PUBLIC_SERVER_URL, plugins: [] }'), ['csrf-empty'])).toEqual([])
expect(await run(build("{ csrf: ['https://site.example'], plugins: [] }"), ['csrf-empty'])).toEqual([])
expect(await run('// not a Payload config', ['csrf-empty'])).toEqual([])
})
test('open-signup: an auth collection anyone can register in is said, as info', async () => {
const cfg = "ipalKit({ access: { authCollection: 'users' } })"
expect(await run(cfg, ['open-signup'], { openSignUp: ['customers', 'members'] })).toEqual(['open-signup:info', 'open-signup:info'])
expect(await run(cfg, ['open-signup'], { openSignUp: [] })).toEqual([])
expect(await run(cfg, ['open-signup'], { openSignUp: null })).toEqual([])
expect(await run(cfg, ['open-signup'])).toEqual([])
})
test('staff-accounts-open: a staff collection an account of another collection may write to is an error', async () => {
const cfg = "ipalKit({ access: { authCollection: 'users' } })"
expect(await run(cfg, ['staff-accounts-open'], { staffOpenToOthers: ['agents:delete', 'agents:update', 'users:create'] })).toEqual(['staff-accounts-open:error', 'staff-accounts-open:error', 'staff-accounts-open:error'])
expect(await run(cfg, ['staff-accounts-open'], { staffOpenToOthers: ['agents:read', 'agents:unlock'] })).toEqual(expect.arrayContaining(['staff-accounts-open:warning', 'staff-accounts-open:error']))
expect(await run(cfg, ['staff-own-roles'], { staffOnOwnRoles: ['crew'] })).toEqual(['staff-own-roles:warning'])
expect(await run(cfg, ['staff-own-roles'], { staffOnOwnRoles: [] })).toEqual([])
expect(await run(cfg, ['staff-own-roles'])).toEqual([])
expect(await run(cfg, ['staff-accounts-open'], { staffOpenToOthers: [] })).toEqual([])
expect(await run(cfg, ['staff-accounts-open'], { staffOpenToOthers: null })).toEqual([])
expect(await run(cfg, ['staff-accounts-open'])).toEqual([])
})
test('the deep status reports the state and where the secret comes from, never a key', async () => {
vi.stubEnv('TURNSTILE_SECRET_KEY', 'env-secret-value')
const fake = (integrations: object) => ({
config: { admin: { user: 'users' }, collections: [{ slug: 'users', fields: [] }], globals: [{ slug: 'site-integrations' }] },
findGlobal: async () => integrations,
})
const degraded = await collectDoctorStatus(fake({ turnstileSecretKey: 'panel-secret-value', turnstileStatus: { code: 'invalid-input-secret', message: 'x', since: '2026-10-28T10:00:00.000Z', state: 'degraded' } }) as never)
expect(degraded.turnstile).toEqual({ code: 'invalid-input-secret', since: '2026-10-28T10:00:00.000Z', state: 'degraded' })
expect(degraded.turnstileSecretFromEnv).toBe(false)
expect(JSON.stringify(degraded)).not.toMatch(/secret-value/)
const fromEnv = await collectDoctorStatus(fake({ turnstileSiteKey: 'site' }) as never)
expect(fromEnv.turnstile).toBeNull()
expect(fromEnv.turnstileSecretFromEnv).toBe(true)
expect(JSON.stringify(fromEnv)).not.toMatch(/secret-value/)
})
})
describe('helpers', () => {
test('parseEnvFile reads KEY=value, strips quotes, skips comments', () => {
expect(parseEnvFile('# c\nA=1\nexport B="two"\n C = \'3\'\nbad line')).toEqual({ A: '1', B: 'two', C: '3' })
@@ -382,7 +515,23 @@ describe('security and deep status', () => {
}
const status = await collectDoctorStatus(payload as never)
expect(status).toMatchObject({ pendingCookies: 4, usersWithout2fa: 2 })
expect(Object.keys(status).sort()).toEqual(['node', 'pendingCookies', 'plugin', 'usersWithout2fa'])
expect(Object.keys(status).sort()).toEqual(['node', 'openSignUp', 'pendingCookies', 'plugin', 'staffOnOwnRoles', 'staffOpenToOthers', 'turnstile', 'turnstileSecretFromEnv', 'usersSetupClosed', 'usersWithout2fa'])
expect(status.usersSetupClosed).toBeNull() // no setup window in this config
})
test('collectDoctorStatus counts the accounts whose 2FA setup window has passed', async () => {
const payload = {
config: {
admin: { user: 'users' },
collections: [{ slug: 'users', fields: [{ name: 'totpSecret' }, { name: 'hasTotp' }, { name: 'totpSetupFrom' }] }],
custom: { ipal: { twoFactor: { collection: 'users', requireSetup: true, setupWindowMs: 72 * 3_600_000 } } },
},
// all 5; with TOTP 3; without 2; of those past the window 1 (the query with `less_than`)
count: vi.fn(async ({ where }: { where?: object }) => {
const q = JSON.stringify(where ?? {})
return { totalDocs: !where ? 5 : q.includes('less_than') ? 1 : q.includes('not_equals') ? 3 : 2 }
}),
}
expect(await collectDoctorStatus(payload as never)).toMatchObject({ usersSetupClosed: 1, usersWithout2fa: 2 })
})
test('GET /api/ipal/doctor: 404 without a token, 401 with a wrong one, counts with the right one', async () => {
const endpoint = buildDoctorEndpoint()
+42
View File
@@ -42,3 +42,45 @@ describe('server entries load no client modules', () => {
expect(clientModulesReachable(entry)).toEqual([])
})
})
/** Modules importing 'server-only' reachable from `entry` — static and dynamic imports (a bundler follows both). */
function serverOnlyReachable(entry: string): string[] {
const seen = new Set<string>()
const hits: string[] = []
const stack = [path.join(root, entry)]
while (stack.length) {
const file = stack.pop()!
if (seen.has(file)) {continue}
seen.add(file)
const src = readFileSync(file, 'utf8')
if (/^import ['"]server-only['"]/m.test(src)) {hits.push(path.relative(root, file))}
for (const m of src.matchAll(/^(?:import|export) (?!type\b)[^'"]*?from ['"]([^'"]+)['"]|\bimport\(\s*['"]([^'"]+)['"]/gm)) {
const next = resolve(file, m[1] ?? m[2])
if (next) {stack.push(next)}
}
}
return hits.sort()
}
describe('client components', () => {
test('/client reaches no server-only module', () => {
expect(serverOnlyReachable('src/exports/client.ts')).toEqual([])
// why a client component must not import the main entry: webpack stops at these
expect(serverOnlyReachable('src/index.ts')).not.toEqual([])
})
test('/client exports the role predicates, with the same fail-closed answers', async () => {
const { hasMinimumRole, isAdmin, isEditor } = await import('../src/modules/access/predicates.js')
const client = readFileSync(path.join(root, 'src/exports/client.ts'), 'utf8')
expect(client).toMatch(/export \{ hasMinimumRole, isAdmin, isEditor \} from '\.\.\/modules\/access\/predicates\.js'/)
const config = { admin: { user: 'users' } } // what useConfig() carries: `custom` is not in the client config
const admin = { collection: 'users', roles: ['admin'] }
const editor = { collection: 'users', roles: ['editor'] }
expect([isAdmin(admin, config), isAdmin(editor, config), isAdmin(null, config)]).toEqual([true, false, false])
expect([isEditor(editor, config), hasMinimumRole(editor, 'user', config)]).toEqual([true, true])
expect(isAdmin({ ...admin, collection: 'customers' }, config)).toBe(false)
// access.staffCollections is not in the client config: name the collections
expect(isAdmin({ ...admin, collection: 'partners' }, config)).toBe(false)
expect(isAdmin({ ...admin, collection: 'partners' }, { staffCollections: ['users', 'partners'] })).toBe(true)
})
})
+3 -3
View File
@@ -167,7 +167,7 @@ describe('forms against a real Payload', () => {
test('open sign-up cannot self-assign admin — roles fall back to the default', async () => {
const user = (await payload.create({
collection: 'users',
data: { email: '[email protected]', password: 'Passw0rd!x', roles: ['admin'] } as never,
data: { email: '[email protected]', password: 'Passw0rd!x-long', roles: ['admin'] } as never,
overrideAccess: false,
})) as unknown as { roles: string[] }
expect(user.roles).toEqual(['user'])
@@ -176,7 +176,7 @@ describe('forms against a real Payload', () => {
test('seed / Local API with overrideAccess can still create an admin', async () => {
const admin = (await payload.create({
collection: 'users',
data: { email: '[email protected]', password: 'Passw0rd!x', roles: ['admin'] } as never,
data: { email: '[email protected]', password: 'Passw0rd!x-long', roles: ['admin'] } as never,
})) as unknown as { roles: string[] }
expect(admin.roles).toEqual(['admin'])
})
@@ -401,7 +401,7 @@ describe('forms access', () => {
const user = (await payload.create({
collection: 'users',
data: { email: '[email protected]', password: 'Passw0rd!x' } as never,
data: { email: '[email protected]', password: 'Passw0rd!x-long' } as never,
})) as unknown as Record<string, unknown>
await expect(
payload.find({ collection: 'form-submissions' as never, overrideAccess: false, user: { ...user, collection: 'users' } as never }),

Some files were not shown because too many files have changed in this diff Show More