Compare commits
+193
-2
@@ -8,6 +8,195 @@ 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
|
||||
@@ -282,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
|
||||
|
||||
+178
-5
@@ -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 |
|
||||
@@ -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),
|
||||
|
||||
+10
-2
@@ -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**
|
||||
@@ -1167,7 +1167,15 @@ add missing hosts with flags / `extra`; (3) change `mode` to `'enforce'` in both
|
||||
| 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` |
|
||||
|
||||
@@ -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.6 ("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,53 +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: '[email protected]', 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`
|
||||
@@ -1224,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@')
|
||||
```
|
||||
|
||||
@@ -36,7 +36,8 @@ 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` |
|
||||
@@ -99,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`, `usersSetupClosed` = of those, blocked because the 2FA setup window has passed, `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,8 @@ 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 |
|
||||
@@ -77,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`. |
|
||||
@@ -63,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? }`), `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`).
|
||||
**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`
|
||||
|
||||
@@ -370,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.
|
||||
@@ -855,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.
|
||||
|
||||
@@ -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).
|
||||
|
||||
@@ -247,6 +247,35 @@ the panel shows Site settings, Site integrations, Cookies, Form messages, the Fo
|
||||
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
|
||||
|
||||
@@ -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
|
||||
@@ -421,6 +423,79 @@ site without steps 1–3 and a deploy day agreed with the owner. Steps 2, 3 and
|
||||
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
@@ -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`) |
|
||||
|
||||
@@ -676,6 +676,8 @@ Do one item at a time, build, check. Order by importance:
|
||||
| 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`.
|
||||
|
||||
+8
-1
@@ -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", "usersSetupClosed": 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)
|
||||
@@ -99,6 +99,13 @@ Turn off: `ipalKit({ doctor: false })`. Adapt: `ipalKit({ doctor: { tokenVar: 'M
|
||||
| | `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 (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
@@ -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
@@ -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.
|
||||
|
||||
+112
-2
@@ -546,8 +546,33 @@ 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
|
||||
@@ -901,8 +926,93 @@ 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.
|
||||
|
||||
+43
-12
@@ -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`.
|
||||
|
||||
+1
-1
@@ -1,6 +1,6 @@
|
||||
{
|
||||
"name": "@intecion/ipal-kit",
|
||||
"version": "1.16.6",
|
||||
"version": "1.16.7",
|
||||
"description": "Intecion Payload Advanced Library — a Payload CMS 3 plugin: i18n, SEO, forms, consent, analytics, blog/archives.",
|
||||
"license": "MIT",
|
||||
"repository": {
|
||||
|
||||
@@ -36,7 +36,8 @@ 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` |
|
||||
@@ -99,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`, `usersSetupClosed` = of those, blocked because the 2FA setup window has passed, `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,8 @@ 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 |
|
||||
@@ -77,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`. |
|
||||
@@ -63,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? }`), `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`).
|
||||
**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`
|
||||
|
||||
@@ -370,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.
|
||||
@@ -855,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.
|
||||
|
||||
@@ -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).
|
||||
|
||||
@@ -247,6 +247,35 @@ the panel shows Site settings, Site integrations, Cookies, Form messages, the Fo
|
||||
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
|
||||
|
||||
@@ -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
|
||||
@@ -421,6 +423,79 @@ site without steps 1–3 and a deploy day agreed with the owner. Steps 2, 3 and
|
||||
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
@@ -47,7 +47,7 @@ Write everything in this file in English.
|
||||
<!-- /starter:decisions -->
|
||||
|
||||
<!-- ipal-kit:start -->
|
||||
## ipal-kit 1.16.6 — 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:
|
||||
|
||||
@@ -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 |
|
||||
|---|---|
|
||||
|
||||
@@ -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.
|
||||
|
||||
@@ -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
|
||||
@@ -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()}
|
||||
})
|
||||
})
|
||||
@@ -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()
|
||||
})
|
||||
|
||||
@@ -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@')
|
||||
|
||||
@@ -1,6 +1,6 @@
|
||||
import { type APIRequestContext, expect, type Page, test } from '@playwright/test'
|
||||
|
||||
import { totp } from './totp'
|
||||
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
|
||||
@@ -17,7 +17,8 @@ const EDITOR = { email: `e2e-editor-${stamp}@example.com`, password: `editor-${s
|
||||
/** The admin the later tests act as: the owner made in the first test, else the smoke-test admin. */
|
||||
let admin: { email: string; password: string; secret: string } | null =
|
||||
process.env.E2E_ADMIN_EMAIL && process.env.E2E_ADMIN_PASSWORD && process.env.E2E_TOTP_SECRET
|
||||
? { email: process.env.E2E_ADMIN_EMAIL, password: process.env.E2E_ADMIN_PASSWORD, secret: process.env.E2E_TOTP_SECRET }
|
||||
? // 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
|
||||
|
||||
|
||||
@@ -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.
|
||||
*/
|
||||
|
||||
@@ -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
|
||||
],
|
||||
})
|
||||
|
||||
@@ -59,12 +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',
|
||||
|
||||
@@ -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'
|
||||
|
||||
@@ -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}
|
||||
|
||||
@@ -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.
|
||||
|
||||
+43
-2
@@ -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'
|
||||
@@ -297,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,
|
||||
@@ -316,6 +355,7 @@ export {
|
||||
UPLOAD_SECURITY_HEADERS,
|
||||
withSecurityConfig,
|
||||
} from './modules/security/index.js'
|
||||
|
||||
export type {
|
||||
BuildAdminCspArgs,
|
||||
BuildCspArgs,
|
||||
@@ -327,11 +367,11 @@ export type {
|
||||
TotpUser,
|
||||
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 { 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'
|
||||
@@ -348,6 +388,7 @@ export {
|
||||
} 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'
|
||||
@@ -415,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'
|
||||
|
||||
@@ -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) }
|
||||
}
|
||||
@@ -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
|
||||
}),
|
||||
}
|
||||
}
|
||||
@@ -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}
|
||||
|
||||
@@ -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
|
||||
},
|
||||
|
||||
@@ -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()
|
||||
}
|
||||
@@ -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ć.',
|
||||
|
||||
@@ -3,6 +3,8 @@ 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.',
|
||||
@@ -25,6 +27,8 @@ export const securityTexts = defineTexts({
|
||||
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.',
|
||||
|
||||
@@ -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 {
|
||||
|
||||
@@ -141,6 +141,121 @@ export const securityRules: DoctorRule[] = [
|
||||
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) => {
|
||||
|
||||
@@ -5,11 +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, 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 {
|
||||
@@ -44,7 +46,41 @@ export async function collectDoctorStatus(payload: BasePayload): Promise<DoctorS
|
||||
}
|
||||
}
|
||||
const pendingCookies = collections.some((c) => c.slug === COOKIE_REVIEW_SLUG) ? await countPendingCookies(payload) : null
|
||||
return { node: process.version, pendingCookies, plugin: pluginVersion(), usersSetupClosed, 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 = {
|
||||
|
||||
@@ -61,8 +61,24 @@ 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
|
||||
|
||||
@@ -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 {
|
||||
|
||||
@@ -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)}
|
||||
|
||||
|
||||
@@ -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
|
||||
|
||||
@@ -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
|
||||
}
|
||||
|
||||
@@ -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))',
|
||||
|
||||
@@ -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]]'
|
||||
@@ -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']
|
||||
@@ -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()
|
||||
@@ -380,6 +380,11 @@ export type TotpEndpointGuards = {
|
||||
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 {
|
||||
@@ -395,6 +400,11 @@ export function guardTotpEndpoint<T extends EndpointLike>(endpoint: T, collectio
|
||||
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)
|
||||
|
||||
@@ -73,6 +73,9 @@ export function resolveRequireSetup(option: false | RequireSetupOptions | undefi
|
||||
/** 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
|
||||
@@ -83,7 +86,8 @@ export function strictExempt(exempt: unknown): NonNullable<RequireSetupOptions['
|
||||
if (typeof exempt !== 'function') {
|
||||
throw new Error('[ipal] twoFactor.requireSetup.exempt must be a function: ({ user }) => boolean.')
|
||||
}
|
||||
if (exempt.constructor?.name === 'AsyncFunction') {
|
||||
// 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`).',
|
||||
|
||||
@@ -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 },
|
||||
|
||||
@@ -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
|
||||
|
||||
@@ -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.
|
||||
*/
|
||||
|
||||
+128
-3
@@ -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'
|
||||
@@ -36,6 +41,7 @@ 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,
|
||||
@@ -187,6 +193,23 @@ 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(', ')}.`)}
|
||||
@@ -194,9 +217,25 @@ export const ipalKit = (options: IpalOptions): Plugin => {
|
||||
/** 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) {
|
||||
@@ -265,8 +304,18 @@ 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 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 }),
|
||||
}
|
||||
@@ -550,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
|
||||
@@ -587,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 ---
|
||||
@@ -612,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 }),
|
||||
]
|
||||
@@ -725,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 } : {}) } },
|
||||
],
|
||||
},
|
||||
}
|
||||
@@ -793,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 } : {}) },
|
||||
},
|
||||
],
|
||||
},
|
||||
@@ -810,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)
|
||||
@@ -831,6 +929,31 @@ 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)
|
||||
@@ -847,6 +970,8 @@ export const ipalKit = (options: IpalOptions): Plugin => {
|
||||
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
|
||||
}
|
||||
}
|
||||
|
||||
+56
-7
@@ -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'
|
||||
@@ -39,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):
|
||||
@@ -96,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;
|
||||
@@ -120,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
|
||||
|
||||
/**
|
||||
@@ -186,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 */
|
||||
@@ -303,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
|
||||
@@ -314,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
|
||||
}
|
||||
|
||||
@@ -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)
|
||||
})
|
||||
})
|
||||
|
||||
|
||||
@@ -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)
|
||||
@@ -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)
|
||||
@@ -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)
|
||||
})
|
||||
@@ -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/)
|
||||
})
|
||||
@@ -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)
|
||||
@@ -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)
|
||||
@@ -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)
|
||||
}
|
||||
@@ -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
|
||||
})
|
||||
})
|
||||
}
|
||||
@@ -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()
|
||||
})
|
||||
})
|
||||
|
||||
@@ -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"')
|
||||
})
|
||||
})
|
||||
@@ -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))
|
||||
|
||||
+83
-1
@@ -150,6 +150,88 @@ describe('2FA setup required: what a project must have', () => {
|
||||
})
|
||||
})
|
||||
|
||||
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' })
|
||||
@@ -433,7 +515,7 @@ 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', 'usersSetupClosed', '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 () => {
|
||||
|
||||
@@ -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)
|
||||
})
|
||||
})
|
||||
|
||||
@@ -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 }),
|
||||
|
||||
@@ -0,0 +1,108 @@
|
||||
/**
|
||||
* M1: what a form does while Turnstile cannot check (forms.turnstileOnConfigError).
|
||||
* Cloudflare is the mocked `fetch`; the rest is the real gate code.
|
||||
*/
|
||||
import { afterEach, describe, expect, test, vi } from 'vitest'
|
||||
|
||||
import { passTurnstile, resolveTurnstileOnConfigError, TURNSTILE_ON_CONFIG_ERROR_DEFAULT } from '../src/modules/forms/submitForm.js'
|
||||
import { ipalKit } from '../src/plugin.js'
|
||||
|
||||
vi.mock('server-only', () => ({}))
|
||||
|
||||
type Option = 'allow' | 'reject' | { files?: 'allow' | 'reject'; text?: 'allow' | 'reject' } | undefined
|
||||
const payloadWith = (integrations: Record<string, unknown>, option?: Option) => ({
|
||||
config: { custom: { ipal: { forms: option ? { turnstileOnConfigError: option } : {} } }, globals: [{ slug: 'site-integrations' }] },
|
||||
findGlobal: async () => integrations,
|
||||
logger: { error: () => undefined, info: () => undefined, warn: () => undefined },
|
||||
updateGlobal: async () => ({}),
|
||||
})
|
||||
const KEYS = { turnstileSecretKey: 'secret', turnstileSiteKey: 'site' }
|
||||
const cloudflare = (body: unknown, status = 200) => vi.stubGlobal('fetch', vi.fn(async () => new Response(JSON.stringify(body), { status })))
|
||||
const gate = (kind: 'files' | 'text' | undefined, option?: Option, explicit?: 'allow' | 'reject', integrations: Record<string, unknown> = KEYS, token: string | undefined = 'token') =>
|
||||
passTurnstile({ ip: '1.2.3.4', payload: payloadWith(integrations, option) as never, turnstileKind: kind, turnstileOnConfigError: explicit, turnstileToken: token })
|
||||
const REFUSED = { reason: 'turnstile', success: false }
|
||||
|
||||
afterEach(() => {
|
||||
vi.unstubAllGlobals()
|
||||
vi.unstubAllEnvs()
|
||||
vi.restoreAllMocks()
|
||||
})
|
||||
|
||||
describe('forms.turnstileOnConfigError', () => {
|
||||
test('the policy: call site, then the plugin option, then the default for the kind', () => {
|
||||
expect(TURNSTILE_ON_CONFIG_ERROR_DEFAULT).toEqual({ files: 'reject', text: 'allow' })
|
||||
const p = (option?: Option) => payloadWith(KEYS, option)
|
||||
expect(resolveTurnstileOnConfigError(p(), 'text')).toBe('allow')
|
||||
expect(resolveTurnstileOnConfigError(p(), 'files')).toBe('reject')
|
||||
expect(resolveTurnstileOnConfigError(p(), undefined)).toBe('allow') // a caller that says nothing is a text form, as before
|
||||
expect(resolveTurnstileOnConfigError(p('reject'), 'text')).toBe('reject')
|
||||
expect(resolveTurnstileOnConfigError(p('allow'), 'files')).toBe('allow')
|
||||
expect(resolveTurnstileOnConfigError(p({ files: 'allow' }), 'files')).toBe('allow')
|
||||
expect(resolveTurnstileOnConfigError(p({ files: 'allow' }), 'text')).toBe('allow')
|
||||
expect(resolveTurnstileOnConfigError(p({ text: 'reject' }), 'files')).toBe('reject')
|
||||
expect(resolveTurnstileOnConfigError(p('reject'), 'text', 'allow')).toBe('allow') // the call site wins
|
||||
expect(resolveTurnstileOnConfigError(p('allow'), 'files', 'reject')).toBe('reject')
|
||||
expect(resolveTurnstileOnConfigError(p('nonsense' as never), 'files')).toBe('reject') // an unknown value never loosens
|
||||
expect(resolveTurnstileOnConfigError(null, 'files')).toBe('reject')
|
||||
})
|
||||
|
||||
test.each([
|
||||
['Cloudflare rejects the secret', { 'error-codes': ['invalid-input-secret'], success: false }, 200],
|
||||
['Cloudflare answers 500', {}, 500],
|
||||
['an answer nobody understands', { hello: 1 }, 200],
|
||||
])('%s: a text form is accepted, a form with files is refused', async (_name, body, status) => {
|
||||
vi.spyOn(console, 'warn').mockImplementation(() => undefined)
|
||||
cloudflare(body, status)
|
||||
expect(await gate('text')).toBeNull()
|
||||
expect(await gate(undefined)).toBeNull()
|
||||
expect(await gate('files')).toEqual(REFUSED)
|
||||
})
|
||||
|
||||
test('the network fails: the same', async () => {
|
||||
vi.spyOn(console, 'warn').mockImplementation(() => undefined)
|
||||
vi.stubGlobal('fetch', vi.fn(async () => { throw new Error('ECONNRESET') }))
|
||||
expect(await gate('text')).toBeNull()
|
||||
expect(await gate('files')).toEqual(REFUSED)
|
||||
})
|
||||
|
||||
test('the plugin option and the call site change it, each way', async () => {
|
||||
vi.spyOn(console, 'warn').mockImplementation(() => undefined)
|
||||
cloudflare({ 'error-codes': ['invalid-input-secret'], success: false })
|
||||
expect(await gate('text', 'reject')).toEqual(REFUSED)
|
||||
expect(await gate('files', 'allow')).toBeNull()
|
||||
expect(await gate('files', { files: 'allow' })).toBeNull()
|
||||
expect(await gate('text', { files: 'allow' })).toBeNull()
|
||||
expect(await gate('files', undefined, 'allow')).toBeNull()
|
||||
expect(await gate('text', 'allow', 'reject')).toEqual(REFUSED)
|
||||
})
|
||||
|
||||
test('not touched by the policy: a valid token passes, a bad token and a missing token are refused, for both kinds', async () => {
|
||||
vi.spyOn(console, 'warn').mockImplementation(() => undefined)
|
||||
cloudflare({ success: true })
|
||||
expect(await gate('text')).toBeNull()
|
||||
expect(await gate('files')).toBeNull()
|
||||
cloudflare({ 'error-codes': ['invalid-input-response'], success: false })
|
||||
expect(await gate('text', 'allow')).toEqual(REFUSED)
|
||||
expect(await gate('files', 'allow')).toEqual(REFUSED)
|
||||
expect(await gate('files', 'allow', undefined, KEYS, undefined)).toEqual(REFUSED)
|
||||
})
|
||||
|
||||
test('Turnstile off (no keys): nothing is checked, forms with files included', async () => {
|
||||
const fetchMock = vi.fn()
|
||||
vi.stubGlobal('fetch', fetchMock)
|
||||
vi.stubEnv('TURNSTILE_SECRET_KEY', '')
|
||||
vi.stubEnv('NEXT_PUBLIC_TURNSTILE_SITE_KEY', '')
|
||||
expect(await gate('files', undefined, undefined, {}, undefined)).toBeNull()
|
||||
expect(await gate('text', 'reject', undefined, {}, undefined)).toBeNull()
|
||||
expect(fetchMock).not.toHaveBeenCalled()
|
||||
})
|
||||
|
||||
test('ipalKit carries the option to where the gate reads it', async () => {
|
||||
const i18n = { defaultLocale: 'en', locales: [{ code: 'en', label: 'English' }] }
|
||||
const build = async (forms: Record<string, unknown>) =>
|
||||
((await ipalKit({ forms, i18n, twoFactor: false } as never)({ collections: [], secret: 'x' } as never)).custom as { ipal?: { forms?: { turnstileOnConfigError?: unknown } } }).ipal?.forms?.turnstileOnConfigError
|
||||
expect(await build({})).toBeUndefined()
|
||||
expect(await build({ turnstileOnConfigError: 'reject' })).toBe('reject')
|
||||
expect(await build({ turnstileOnConfigError: { files: 'allow' } })).toEqual({ files: 'allow' })
|
||||
})
|
||||
})
|
||||
@@ -0,0 +1,60 @@
|
||||
/**
|
||||
* M1: the Turnstile secret key from the environment is deprecated — it still works, and says so once.
|
||||
* Cloudflare is the mocked `fetch`.
|
||||
*/
|
||||
import { afterEach, describe, expect, test, vi } from 'vitest'
|
||||
|
||||
import { passTurnstile } from '../src/modules/forms/submitForm.js'
|
||||
import { getTurnstileConfig, turnstileSecretFromEnv } from '../src/modules/turnstile/config.js'
|
||||
|
||||
vi.mock('server-only', () => ({}))
|
||||
|
||||
type Option = 'allow' | 'reject' | { files?: 'allow' | 'reject'; text?: 'allow' | 'reject' } | undefined
|
||||
const payloadWith = (integrations: Record<string, unknown>, option?: Option) => ({
|
||||
config: { custom: { ipal: { forms: option ? { turnstileOnConfigError: option } : {} } }, globals: [{ slug: 'site-integrations' }] },
|
||||
findGlobal: async () => integrations,
|
||||
logger: { error: () => undefined, info: () => undefined, warn: () => undefined },
|
||||
updateGlobal: async () => ({}),
|
||||
})
|
||||
const KEYS = { turnstileSecretKey: 'secret', turnstileSiteKey: 'site' }
|
||||
const cloudflare = (body: unknown, status = 200) => vi.stubGlobal('fetch', vi.fn(async () => new Response(JSON.stringify(body), { status })))
|
||||
|
||||
afterEach(() => {
|
||||
vi.unstubAllGlobals()
|
||||
vi.unstubAllEnvs()
|
||||
vi.restoreAllMocks()
|
||||
})
|
||||
|
||||
describe('the Turnstile secret from the environment (deprecated)', () => {
|
||||
test('turnstileSecretFromEnv: only when the panel field is empty and the variable is set', () => {
|
||||
vi.stubEnv('TURNSTILE_SECRET_KEY', 'from-env')
|
||||
expect(turnstileSecretFromEnv({})).toBe(true)
|
||||
expect(turnstileSecretFromEnv({ turnstileSecretKey: ' ' })).toBe(true)
|
||||
expect(turnstileSecretFromEnv({ turnstileSecretKey: 'from-panel' })).toBe(false)
|
||||
vi.stubEnv('TURNSTILE_SECRET_KEY', '')
|
||||
expect(turnstileSecretFromEnv({})).toBe(false)
|
||||
})
|
||||
|
||||
test('it still works, and says once that it is deprecated', async () => {
|
||||
const warn = vi.spyOn(console, 'warn').mockImplementation(() => undefined)
|
||||
vi.stubEnv('TURNSTILE_SECRET_KEY', 'from-env')
|
||||
const payload = payloadWith({ turnstileSiteKey: 'site' })
|
||||
expect(await getTurnstileConfig(payload as never)).toEqual({ enabled: true, siteKey: 'site' })
|
||||
expect(await getTurnstileConfig(payload as never)).toEqual({ enabled: true, siteKey: 'site' })
|
||||
const lines = warn.mock.calls.map((c) => String(c[0])).filter((l) => l.includes('Deprecated'))
|
||||
expect(lines).toHaveLength(1)
|
||||
expect(lines[0]).toMatch(/TURNSTILE_SECRET_KEY.*Site integrations.*keeps working for now/)
|
||||
// the check itself runs with the env secret
|
||||
cloudflare({ success: true })
|
||||
expect(await passTurnstile({ payload: payload as never, turnstileToken: 'token' })).toBeNull()
|
||||
const sent = String((vi.mocked(fetch).mock.calls[0] as unknown as [string, { body: URLSearchParams }])[1].body)
|
||||
expect(sent).toContain('secret=from-env')
|
||||
})
|
||||
|
||||
test('with the key in the panel there is nothing to say', async () => {
|
||||
const warn = vi.spyOn(console, 'warn').mockImplementation(() => undefined)
|
||||
vi.stubEnv('TURNSTILE_SECRET_KEY', 'from-env')
|
||||
await getTurnstileConfig(payloadWith(KEYS) as never)
|
||||
expect(warn.mock.calls.map((c) => String(c[0])).filter((l) => l.includes('Deprecated'))).toEqual([])
|
||||
})
|
||||
})
|
||||
@@ -10,6 +10,7 @@ import type { I18nConfig } from '../src/modules/i18n/types.js'
|
||||
|
||||
import { adminOrSelfIn } from '../src/modules/access/access.js'
|
||||
import { isAdmin, staffCollectionSlugs, userMeetsRole } from '../src/modules/access/predicates.js'
|
||||
import { clearReportedOrigins, reportRefusedOrigin, requestFromOwnOrigin } from '../src/modules/security/totp/sameOrigin.js'
|
||||
import {
|
||||
ensurePayloadGuarded,
|
||||
guardPayloadAccess,
|
||||
@@ -21,7 +22,7 @@ import {
|
||||
watchPayloadConfig,
|
||||
} from '../src/modules/security/totp/secondFactor.js'
|
||||
import { buildTwoFactorResetEndpoint, resolveRequireSetup, strictExempt } from '../src/modules/security/totp/setupRequired.js'
|
||||
import { buildVerifyLimit, clearVerifyLimits } from '../src/modules/security/totp/verifyLimit.js'
|
||||
import { buildVerifyLimit, clearVerifyLimits, verifyLimitKey } from '../src/modules/security/totp/verifyLimit.js'
|
||||
import { ipalKit } from '../src/plugin.js'
|
||||
import { withTotpParts } from './helpers.js'
|
||||
|
||||
@@ -316,16 +317,16 @@ describe('ipalKit and the 2FA plugin', () => {
|
||||
clearVerifyLimits()
|
||||
const req = (id: unknown) => ({ i18n: undefined, payload: { logger: { warn: () => {} } }, user: { id, collection: 'users' } }) as never
|
||||
const limit = buildVerifyLimit('users') // 5 in 10 minutes
|
||||
for (let i = 0; i < 5; i++) {expect(limit(req(1))).toBeNull()}
|
||||
const refused = limit(req(1))!
|
||||
for (let i = 0; i < 5; i++) {expect(await limit(req(1))).toBeNull()}
|
||||
const refused = (await limit(req(1)))!
|
||||
expect(refused.status).toBe(429)
|
||||
expect(Number(refused.headers.get('retry-after'))).toBeGreaterThan(0)
|
||||
expect(((await refused.json()) as { message: string }).message).toMatch(/Too many codes/)
|
||||
expect(limit(req(2))).toBeNull() // another account is not affected
|
||||
expect(limit({ ...(req(1) as object), user: null } as never)).toBeNull() // no session: the package refuses by itself
|
||||
expect(await limit(req(2))).toBeNull() // another account is not affected
|
||||
expect(await limit({ ...(req(1) as object), user: null } as never)).toBeNull() // no session: the package refuses by itself
|
||||
const two = buildVerifyLimit('admins', { max: 2, windowMinutes: 1 })
|
||||
expect([two(req(1)), two(req(1))]).toEqual([null, null])
|
||||
expect(two(req(1))!.status).toBe(429)
|
||||
expect([await two(req(1)), await two(req(1))]).toEqual([null, null])
|
||||
expect((await two(req(1)))!.status).toBe(429)
|
||||
|
||||
// wired by default; twoFactor.verifyLimit: false leaves the package's endpoint as it is
|
||||
const base = () => ({ collections: [], endpoints: [], secret: 'x' }) as unknown as Config
|
||||
@@ -342,15 +343,179 @@ describe('ipalKit and the 2FA plugin', () => {
|
||||
expect(await call(await ipalKit({ i18n, twoFactor: { issuer: 'A', plugin: withEndpoint as never, verifyLimit: false } })(base()), 8)).toBe(200)
|
||||
})
|
||||
|
||||
// M1 (R3-2): the count is also kept in the database, so a restart or a second instance does not reset it.
|
||||
describe('the verify limit: stored count', () => {
|
||||
const store = () => {
|
||||
const data = new Map<string, unknown>()
|
||||
return { data, get: vi.fn(async (k: string) => data.get(k) ?? null), set: vi.fn(async (k: string, v: unknown) => void data.set(k, v)) }
|
||||
}
|
||||
const req = (kv: unknown, id: unknown = 1) => ({ i18n: undefined, payload: { kv, logger: { warn: vi.fn() } }, user: { id, collection: 'users' } }) as never
|
||||
|
||||
test('a restart (the memory is empty again) does not hand out new attempts', async () => {
|
||||
clearVerifyLimits()
|
||||
const kv = store()
|
||||
const limit = buildVerifyLimit('users')
|
||||
for (let i = 0; i < 3; i++) {expect(await limit(req(kv))).toBeNull()}
|
||||
clearVerifyLimits() // the process restarted, or this is another instance
|
||||
expect(await limit(req(kv))).toBeNull() // 4th
|
||||
expect(await limit(req(kv))).toBeNull() // 5th
|
||||
expect((await limit(req(kv)))!.status).toBe(429)
|
||||
expect(kv.data.get(verifyLimitKey('users', '1'))).toMatchObject({ count: 6 })
|
||||
// and a restart while refused keeps refusing, with the stored window's Retry-After
|
||||
clearVerifyLimits()
|
||||
const again = (await limit(req(kv)))!
|
||||
expect(again.status).toBe(429)
|
||||
expect(Number(again.headers.get('retry-after'))).toBeGreaterThan(0)
|
||||
})
|
||||
|
||||
test('a burst of parallel attempts cannot slip under the limit', async () => {
|
||||
clearVerifyLimits()
|
||||
const kv = store()
|
||||
const limit = buildVerifyLimit('users')
|
||||
const answers = await Promise.all(Array.from({ length: 40 }, () => limit(req(kv))))
|
||||
expect(answers.filter((a) => a === null)).toHaveLength(5)
|
||||
})
|
||||
|
||||
test('when the window is over, the stored count starts again', async () => {
|
||||
clearVerifyLimits()
|
||||
const kv = store()
|
||||
kv.data.set(verifyLimitKey('users', '1'), { count: 99, resetAt: Date.now() - 1000 })
|
||||
expect(await buildVerifyLimit('users')(req(kv))).toBeNull()
|
||||
expect(kv.data.get(verifyLimitKey('users', '1'))).toMatchObject({ count: 1 })
|
||||
})
|
||||
|
||||
test('a failing store never opens the gate: the memory count still decides', async () => {
|
||||
clearVerifyLimits()
|
||||
const broken = { get: vi.fn(async () => { throw new Error('db down') }), set: vi.fn() }
|
||||
const limit = buildVerifyLimit('users')
|
||||
const request = req(broken)
|
||||
for (let i = 0; i < 5; i++) {expect(await limit(request)).toBeNull()}
|
||||
expect((await limit(request))!.status).toBe(429)
|
||||
// no store at all (an older Payload without payload.kv): the same
|
||||
clearVerifyLimits()
|
||||
const none = buildVerifyLimit('users')
|
||||
for (let i = 0; i < 5; i++) {expect(await none(req(undefined))).toBeNull()}
|
||||
expect((await none(req(undefined)))!.status).toBe(429)
|
||||
})
|
||||
|
||||
test("store: 'memory' leaves the database alone", async () => {
|
||||
clearVerifyLimits()
|
||||
const kv = store()
|
||||
const limit = buildVerifyLimit('users', { store: 'memory' })
|
||||
for (let i = 0; i < 6; i++) {await limit(req(kv))}
|
||||
expect(kv.get).not.toHaveBeenCalled()
|
||||
expect(kv.set).not.toHaveBeenCalled()
|
||||
})
|
||||
})
|
||||
|
||||
// M1 (R3-2): an attempt a browser marks as coming from another origin is refused before it is counted.
|
||||
describe('2FA verify and setup only from the own origin', () => {
|
||||
const req = (headers: Record<string, string>, config: Record<string, unknown> = {}, url = 'http://internal:3000/api/verify-totp') => ({ headers: new Headers(headers), payload: { config }, url })
|
||||
|
||||
test.each([
|
||||
['no Origin, no Sec-Fetch-Site (a script, curl, a server)', {}, {}, true],
|
||||
['Origin = the host the request came in on', { host: 'site.example', origin: 'https://site.example' }, {}, true],
|
||||
['Origin = the forwarded host (behind a proxy)', { host: 'internal:3000', origin: 'https://site.example', 'x-forwarded-host': 'site.example' }, {}, true],
|
||||
['Origin = serverURL', { host: 'internal:3000', origin: 'https://site.example' }, { serverURL: 'https://site.example' }, true],
|
||||
['Origin in csrf', { origin: 'https://app.example.com' }, { csrf: ['https://app.example.com'] }, true],
|
||||
['Origin in cors', { origin: 'https://app.example.com' }, { cors: { origins: ['https://app.example.com'] } }, true],
|
||||
['a sibling subdomain', { host: 'site.example', origin: 'https://blog.site.example' }, { serverURL: 'https://site.example' }, false],
|
||||
['another site', { host: 'site.example', origin: 'https://evil.example' }, {}, false],
|
||||
['the same host on another port', { host: 'site.example', origin: 'https://site.example:8443' }, {}, false],
|
||||
// a proxy that writes the default port out
|
||||
['the forwarded host with :443 for an https origin', { host: 'internal:3000', origin: 'https://site.example', 'x-forwarded-host': 'site.example:443' }, {}, true],
|
||||
['the host with :80 for an http origin', { host: 'site.example:80', origin: 'http://site.example' }, {}, true],
|
||||
['Origin with the default port written out', { host: 'site.example', origin: 'https://site.example:443' }, {}, true],
|
||||
[':443 is not the default of http', { host: 'site.example:443', origin: 'http://site.example' }, {}, false],
|
||||
[':80 is not the default of https', { host: 'site.example:80', origin: 'https://site.example' }, {}, false],
|
||||
// nginx's plain proxy_pass: Host rewritten, no X-Forwarded-Host, no serverURL — the site's own page is refused (and reported, below)
|
||||
['a proxy that hides the address, nothing configured', { host: 'upstream:3000', origin: 'https://site.example' }, {}, false],
|
||||
['Origin: null (a sandboxed page)', { host: 'site.example', origin: 'null' }, {}, false],
|
||||
['Sec-Fetch-Site: same-origin without Origin', { 'sec-fetch-site': 'same-origin' }, {}, true],
|
||||
['Sec-Fetch-Site: same-site (a sibling subdomain) without Origin', { 'sec-fetch-site': 'same-site' }, {}, false],
|
||||
['Sec-Fetch-Site: cross-site without Origin', { 'sec-fetch-site': 'cross-site' }, {}, false],
|
||||
])('%s', (_name, headers, config, expected) => {
|
||||
expect(requestFromOwnOrigin(req(headers as Record<string, string>, config))).toBe(expected)
|
||||
})
|
||||
|
||||
test('a refusal is never silent: one line per origin, with the ways to allow it', () => {
|
||||
clearReportedOrigins()
|
||||
const warn = vi.fn()
|
||||
const hidden = { headers: new Headers({ host: 'upstream:3000', origin: 'https://site.example' }), payload: { config: {}, logger: { warn } }, url: 'http://upstream:3000/api/verify-totp' }
|
||||
expect(reportRefusedOrigin(hidden)).toBe(true)
|
||||
expect(reportRefusedOrigin(hidden)).toBe(false) // once per origin
|
||||
expect(warn).toHaveBeenCalledTimes(1)
|
||||
const line = warn.mock.calls[0][0] as string
|
||||
expect(line).toContain('origin "https://site.example"')
|
||||
expect(line).toContain('host upstream:3000')
|
||||
expect(line).toMatch(/serverURL/)
|
||||
expect(line).toMatch(/sameOrigin: \{ origins: \['https:\/\/site\.example'\] \}/)
|
||||
expect(line).toMatch(/X-Forwarded-Host/)
|
||||
// another origin gets its own line; a request without Origin is named by what the browser said
|
||||
expect(reportRefusedOrigin({ ...hidden, headers: new Headers({ origin: 'https://evil.example' }) })).toBe(true)
|
||||
expect(reportRefusedOrigin({ ...hidden, headers: new Headers({ 'sec-fetch-site': 'cross-site' }) })).toBe(true)
|
||||
expect(warn.mock.calls[2][0]).toContain('sec-fetch-site: cross-site')
|
||||
// the log cannot be flooded with made-up origins
|
||||
for (let i = 0; i < 200; i++) {reportRefusedOrigin({ ...hidden, headers: new Headers({ origin: `https://n${i}.example` }) })}
|
||||
expect(warn.mock.calls.length).toBeLessThanOrEqual(50)
|
||||
clearReportedOrigins()
|
||||
})
|
||||
|
||||
test('twoFactor.sameOrigin.origins adds an origin', () => {
|
||||
const other = req({ host: 'site.example', origin: 'https://panel.example.org' })
|
||||
expect(requestFromOwnOrigin(other)).toBe(false)
|
||||
expect(requestFromOwnOrigin(other, ['https://panel.example.org'])).toBe(true)
|
||||
})
|
||||
|
||||
test('wired by default on verify and setup, before the limit; not on other endpoints; sameOrigin: false turns it off', async () => {
|
||||
const handler = vi.fn(() => Response.json({ ok: true }))
|
||||
const warn = vi.fn()
|
||||
clearReportedOrigins()
|
||||
const withEndpoints = (o: { collection: string }) => (c: Config) => ({
|
||||
...withTotpParts(c, o.collection),
|
||||
endpoints: [...(c.endpoints ?? []), ...['/verify-totp', '/setup-totp', '/remove-totp'].map((path) => ({ handler, method: 'post' as const, path }))],
|
||||
})
|
||||
const build = (twoFactor: Record<string, unknown> = {}) => ipalKit({ i18n, twoFactor: { issuer: 'A', plugin: withEndpoints as never, ...twoFactor } as never })({ collections: [], endpoints: [], secret: 'x' } as unknown as Config)
|
||||
const call = async (config: Config, path: string, headers: Record<string, string>, user: Record<string, unknown>) =>
|
||||
(await config.endpoints!.find((e) => e.path === path)!.handler({ headers: new Headers(headers), i18n: undefined, payload: { config, logger: { warn } }, url: 'https://site.example/api' + path, user: { id: 5, collection: 'users', ...user } } as never)).status
|
||||
const elsewhere = { host: 'site.example', origin: 'https://blog.site.example' }
|
||||
const own = { host: 'site.example', origin: 'https://site.example' }
|
||||
const owes = { _strategy: 'local-jwt', hasTotp: true }
|
||||
const fresh = { _strategy: 'local-jwt', hasTotp: false, totpSetupFrom: new Date().toISOString() }
|
||||
|
||||
clearVerifyLimits()
|
||||
const config = await build()
|
||||
// twenty attempts from elsewhere: all refused, none counted
|
||||
for (let i = 0; i < 20; i++) {expect(await call(config, '/verify-totp', elsewhere, owes)).toBe(403)}
|
||||
expect(handler).not.toHaveBeenCalled()
|
||||
// …and said in the log, once, with the origin and how to allow it
|
||||
expect(warn.mock.calls.filter(([line]) => String(line).includes('blog.site.example'))).toHaveLength(1)
|
||||
for (let i = 0; i < 5; i++) {expect(await call(config, '/verify-totp', own, owes)).toBe(200)} // the owner still has all five
|
||||
expect(await call(config, '/verify-totp', own, owes)).toBe(429)
|
||||
expect(await call(config, '/setup-totp', elsewhere, fresh)).toBe(403)
|
||||
expect(await call(config, '/setup-totp', own, fresh)).toBe(200)
|
||||
// other endpoints of the package are not part of this rule (they need the second factor instead)
|
||||
expect(await call(config, '/remove-totp', elsewhere, { _strategy: 'totp', hasTotp: true })).toBe(200)
|
||||
|
||||
clearVerifyLimits()
|
||||
const off = await build({ sameOrigin: false })
|
||||
expect(await call(off, '/verify-totp', elsewhere, owes)).toBe(200)
|
||||
clearVerifyLimits()
|
||||
const listed = await build({ sameOrigin: { origins: ['https://blog.site.example'] } })
|
||||
expect(await call(listed, '/verify-totp', elsewhere, owes)).toBe(200)
|
||||
})
|
||||
})
|
||||
|
||||
test('staff collections outside the 2FA collection are named in a warning at start', async () => {
|
||||
const config = await ipalKit({ access: { authCollection: 'users', staffCollections: ['partners'] }, i18n, twoFactor: { issuer: 'A', plugin: fakeTotp as never } })({
|
||||
...twoAuth(),
|
||||
admin: { user: 'users' },
|
||||
} as Config)
|
||||
const warnings: string[] = []
|
||||
const auth = (slug: string) => ({ slug, auth: true, custom: { ipalAccounts: true }, fields: [] })
|
||||
const payload = {
|
||||
collections: {},
|
||||
config: { admin: { user: 'users' }, collections: [], custom: config.custom, globals: [] },
|
||||
config: { admin: { user: 'users' }, collections: [auth('partners'), auth('users')], custom: config.custom, globals: [] },
|
||||
count: () => ({ totalDocs: 0 }),
|
||||
find: () => ({ docs: [] }),
|
||||
findGlobal: () => ({}),
|
||||
|
||||
@@ -270,7 +270,7 @@ describe('what must keep working', () => {
|
||||
}
|
||||
expect(closed).toEqual([])
|
||||
const integrations = (await (await api('/globals/site-integrations', sessions.verified)).json()) as { smtpPassword?: string }
|
||||
expect(integrations.smtpPassword).toBe('S3CRET')
|
||||
expect(integrations.smtpPassword).toBe('********') // set, never returned (write-only secrets)
|
||||
expect((await api('/globals/site-settings', sessions.verified, { body: JSON.stringify({ siteName: 'Verified' }), method: 'POST' })).status).toBe(200)
|
||||
expect((await api('/ipal/cookie-scan', sessions.verified)).status).toBe(200)
|
||||
// 400 = past the login and role gates, stopped by the missing recipient
|
||||
@@ -280,7 +280,7 @@ describe('what must keep working', () => {
|
||||
test('a fully verified admin reads Site integrations (GraphQL)', async () => {
|
||||
const out = await gql(sessions.verified, '{ SiteIntegration { smtpPassword } FormSubmissions { totalDocs } }')
|
||||
expect(out.errors).toBeUndefined()
|
||||
expect((out.data?.SiteIntegration as { smtpPassword: string }).smtpPassword).toBe('S3CRET')
|
||||
expect((out.data?.SiteIntegration as { smtpPassword: string }).smtpPassword).toBe('********')
|
||||
})
|
||||
|
||||
test('anonymous visitors still read the public globals and forms', async () => {
|
||||
@@ -454,6 +454,28 @@ describe('the code cannot be guessed: verify attempts are limited per account',
|
||||
expect((await fetch(`${server.url}/api/pages`, { headers: { cookie } })).status).toBe(403)
|
||||
})
|
||||
|
||||
// M1 (R3-2). Order matters: this runs after the account above is already refused.
|
||||
test('attempts from another origin are refused without being counted, and the count survives a restart', async () => {
|
||||
await payload.create({ collection: 'users' as never, data: { email: '[email protected]', password: PASSWORD, roles: ['editor'], totpSecret: GUESS_SECRET } as never })
|
||||
const mine = (await login('users', '[email protected]')).cookies.join('; ')
|
||||
// a page on a sibling subdomain posts wrong codes with the owner's cookie: refused, twenty times
|
||||
for (let i = 0; i < 20; i++) {
|
||||
const res = await verify('000000', { cookie: mine, origin: 'https://blog.example.com' })
|
||||
expect(res.status).toBe(403)
|
||||
}
|
||||
expect((await verify('000000', { cookie: mine, 'sec-fetch-site': 'cross-site' })).status).toBe(403)
|
||||
// …and the owner still has every attempt: three wrong ones are answered, not refused
|
||||
for (let i = 0; i < 3; i++) {expect((await verify('000000', { cookie: mine, origin: server.url })).status).toBe(200)}
|
||||
// a restart / another instance: the memory is empty, the database is not
|
||||
const { clearVerifyLimits } = await import('../src/modules/security/totp/verifyLimit.js')
|
||||
clearVerifyLimits()
|
||||
expect((await verify('000000', { cookie: mine })).status).toBe(200) // 4th
|
||||
expect((await verify('000000', { cookie: mine })).status).toBe(200) // 5th
|
||||
expect((await verify(totp(GUESS_SECRET), { cookie: mine })).status).toBe(429) // 6th: refused, also the right code
|
||||
clearVerifyLimits()
|
||||
expect((await verify(totp(GUESS_SECRET), { cookie: mine })).status).toBe(429)
|
||||
})
|
||||
|
||||
test('the limit is the account\'s alone: nobody without its password can use it, other accounts are not affected', async () => {
|
||||
// someone without the password cannot count against the account: no session, or a session of another collection
|
||||
for (let i = 0; i < 8; i++) {
|
||||
|
||||
@@ -76,7 +76,7 @@ test('beta.1: password only → refused; password and code → allowed (REST and
|
||||
const full = [cookie, ...cookiesOf(verify)].join('; ')
|
||||
const integrations = await get('/globals/site-integrations', { cookie: full })
|
||||
expect(integrations.status).toBe(200)
|
||||
expect(((await integrations.json()) as { smtpPassword: string }).smtpPassword).toBe('S3CRET')
|
||||
expect(((await integrations.json()) as { smtpPassword: string }).smtpPassword).toBe('********') // set, never returned (write-only secrets)
|
||||
expect((await get('/form-submissions', { cookie: full })).status).toBe(200)
|
||||
})
|
||||
|
||||
|
||||
@@ -0,0 +1,199 @@
|
||||
/**
|
||||
* Write-only secrets over real HTTP: the SMTP password and the Turnstile secret key stored in the Site
|
||||
* integrations global never come back — not over REST, not over GraphQL, not to an admin — while server code
|
||||
* still reads them, and a save that does not carry a new value keeps the old one.
|
||||
* Runs on SQLite by default, on Postgres / MongoDB with IPAL_TEST_POSTGRES_URI / IPAL_TEST_MONGO_URI.
|
||||
*/
|
||||
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, describe, expect, test, vi } from 'vitest'
|
||||
|
||||
import { buildSiteIntegrations } from '../src/globals/SiteIntegrations/index.js'
|
||||
import { keepSecretBeforeValidate, maskSecretAfterRead, SECRET_CLEAR, SECRET_MASK, writeOnlySecret, writeOnlySecrets } from '../src/modules/secrets/writeOnly.js'
|
||||
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 = 'a-long-test-password-1'
|
||||
const SMTP = 'S3CRET-smtp-value'
|
||||
const TURNSTILE = 'S3CRET-turnstile-value'
|
||||
let server: TestServer
|
||||
let payload: Payload
|
||||
let auth: Record<string, string>
|
||||
|
||||
const stored = async () => (await payload.findGlobal({ slug: 'site-integrations' as never })) as unknown as Record<string, null | string | undefined>
|
||||
const get = async () => fetch(`${server.url}/api/globals/site-integrations`, { headers: auth })
|
||||
const save = async (data: Record<string, unknown>) => fetch(`${server.url}/api/globals/site-integrations`, { body: JSON.stringify(data), headers: { 'content-type': 'application/json', ...auth }, method: 'POST' })
|
||||
const gql = async (query: string) => (await (await fetch(`${server.url}/api/graphql`, { body: JSON.stringify({ query }), headers: { 'content-type': 'application/json', ...auth }, method: 'POST' })).json()) as { data?: Record<string, Record<string, unknown>>; errors?: unknown[] }
|
||||
|
||||
beforeAll(async () => {
|
||||
const config = buildTestConfig({
|
||||
admin: { user: 'users' },
|
||||
collections: [{ slug: 'media', fields: [], upload: { staticDir: path.join(os.tmpdir(), 'ipal-test-media') } }],
|
||||
db: testDatabase('secrets'),
|
||||
editor: lexicalEditor(),
|
||||
plugins: [ipalKit({ access: { authCollection: 'users' }, forms: {}, 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)
|
||||
await payload.create({ collection: 'users' as never, data: { email: '[email protected]', password: PASSWORD, roles: ['admin'] } as never })
|
||||
const login = (await (await fetch(`${server.url}/api/users/login`, { body: JSON.stringify({ email: '[email protected]', password: PASSWORD }), headers: { 'content-type': 'application/json' }, method: 'POST' })).json()) as { token: string }
|
||||
auth = { authorization: `JWT ${login.token}` }
|
||||
// as a seed or the panel's first save would
|
||||
await payload.updateGlobal({ slug: 'site-integrations' as never, data: { smtpHost: 'smtp.example.com', smtpPassword: SMTP, smtpUser: 'mailer', turnstileSecretKey: TURNSTILE, turnstileSiteKey: 'site-key' } as never })
|
||||
}, 120_000)
|
||||
|
||||
afterAll(async () => {
|
||||
await server?.close()
|
||||
await payload?.destroy?.()
|
||||
})
|
||||
|
||||
describe('reading', () => {
|
||||
test('REST: an admin gets "a value is set", never the value', async () => {
|
||||
const res = await get()
|
||||
expect(res.status).toBe(200)
|
||||
const text = await res.text()
|
||||
expect(text).not.toContain('S3CRET')
|
||||
const body = JSON.parse(text) as Record<string, unknown>
|
||||
expect(body.smtpPassword).toBe(SECRET_MASK)
|
||||
expect(body.turnstileSecretKey).toBe(SECRET_MASK)
|
||||
expect(body.smtpUser).toBe('mailer') // the rest of the global is as before
|
||||
expect(body.turnstileSiteKey).toBe('site-key')
|
||||
})
|
||||
|
||||
test('GraphQL: the same', async () => {
|
||||
const out = await gql('{ SiteIntegration { smtpPassword turnstileSecretKey smtpUser } }')
|
||||
expect(out.errors).toBeUndefined()
|
||||
expect(JSON.stringify(out)).not.toContain('S3CRET')
|
||||
expect(out.data?.SiteIntegration).toMatchObject({ smtpPassword: SECRET_MASK, smtpUser: 'mailer', turnstileSecretKey: SECRET_MASK })
|
||||
})
|
||||
|
||||
test('server code (the Local API, access control off) reads the real values', async () => {
|
||||
expect(await stored()).toMatchObject({ smtpPassword: SMTP, turnstileSecretKey: TURNSTILE })
|
||||
})
|
||||
|
||||
test('the Local API WITH access control (a user, overrideAccess: false) is masked like the API', async () => {
|
||||
const user = { ...(await payload.find({ collection: 'users' as never })).docs[0], collection: 'users' }
|
||||
const doc = (await payload.findGlobal({ slug: 'site-integrations' as never, overrideAccess: false, user: user as never })) as unknown as Record<string, unknown>
|
||||
expect(doc.smtpPassword).toBe(SECRET_MASK)
|
||||
expect(doc.turnstileSecretKey).toBe(SECRET_MASK)
|
||||
})
|
||||
})
|
||||
|
||||
describe('saving', () => {
|
||||
test('another field alone: the secrets stay, and the answer does not carry them', async () => {
|
||||
// (a field the SMTP password belongs to — server, port, user — asks for it again: writeOnlySecretsBound.test.ts)
|
||||
const res = await save({ smtpFromName: 'The site' })
|
||||
expect(res.status).toBe(200)
|
||||
expect(await res.text()).not.toContain('S3CRET')
|
||||
expect(await stored()).toMatchObject({ smtpFromName: 'The site', smtpPassword: SMTP, turnstileSecretKey: TURNSTILE })
|
||||
})
|
||||
|
||||
test('what the panel sends back when nothing was typed (the mask), an empty value, null: kept', async () => {
|
||||
for (const value of [SECRET_MASK, '', null]) {
|
||||
expect((await save({ smtpPassword: value, turnstileSecretKey: value })).status).toBe(200)
|
||||
expect(await stored()).toMatchObject({ smtpPassword: SMTP, turnstileSecretKey: TURNSTILE })
|
||||
}
|
||||
})
|
||||
|
||||
test('a whole document read over the API and saved back unchanged keeps the secrets', async () => {
|
||||
const doc = (await (await get()).json()) as Record<string, unknown>
|
||||
for (const key of ['id', 'createdAt', 'updatedAt', 'globalType']) {delete doc[key]}
|
||||
expect((await save(doc)).status).toBe(200)
|
||||
expect(await stored()).toMatchObject({ smtpPassword: SMTP, turnstileSecretKey: TURNSTILE })
|
||||
})
|
||||
|
||||
test('a new value replaces the old one; the answer shows the mask', async () => {
|
||||
const res = await save({ smtpPassword: 'S3CRET-new-value' })
|
||||
const body = (await res.json()) as { result: Record<string, unknown> }
|
||||
expect(JSON.stringify(body)).not.toContain('S3CRET')
|
||||
expect(body.result.smtpPassword).toBe(SECRET_MASK)
|
||||
expect(await stored()).toMatchObject({ smtpPassword: 'S3CRET-new-value', turnstileSecretKey: TURNSTILE })
|
||||
})
|
||||
|
||||
test('SECRET_CLEAR removes the stored value; an empty field then reads as empty, not as "set"', async () => {
|
||||
expect((await save({ smtpPassword: SECRET_CLEAR })).status).toBe(200)
|
||||
expect((await stored()).smtpPassword ?? null).toBeNull()
|
||||
const body = (await (await get()).json()) as Record<string, unknown>
|
||||
expect(body.smtpPassword ?? null).toBeNull()
|
||||
expect(body.turnstileSecretKey).toBe(SECRET_MASK)
|
||||
// and an empty save on an empty field stays empty
|
||||
expect((await save({ smtpPassword: '' })).status).toBe(200)
|
||||
expect((await stored()).smtpPassword ?? null).toBeNull()
|
||||
})
|
||||
|
||||
test('a value that is not text is refused, and the stored one stays', async () => {
|
||||
await payload.updateGlobal({ slug: 'site-integrations' as never, data: { smtpPassword: SMTP, turnstileSecretKey: TURNSTILE } as never })
|
||||
for (const notText of [false, 0, 5, {}, { a: 1 }, [SECRET_MASK], ['x']]) {
|
||||
const res = await save({ smtpPassword: notText })
|
||||
expect([JSON.stringify(notText), res.status]).toEqual([JSON.stringify(notText), 400])
|
||||
expect(await res.text()).not.toContain('S3CRET')
|
||||
expect((await save({ turnstileSecretKey: notText })).status).toBe(400)
|
||||
}
|
||||
expect(await stored()).toMatchObject({ smtpPassword: SMTP, turnstileSecretKey: TURNSTILE })
|
||||
})
|
||||
|
||||
test('GraphQL mutation: the mask keeps, a value replaces', async () => {
|
||||
await payload.updateGlobal({ slug: 'site-integrations' as never, data: { smtpPassword: SMTP } as never })
|
||||
let out = await gql(`mutation { updateSiteIntegration(data: { smtpPassword: "${SECRET_MASK}", smtpFromName: "By GraphQL" }) { smtpPassword smtpFromName } }`)
|
||||
expect(out.errors).toBeUndefined()
|
||||
expect(out.data?.updateSiteIntegration).toMatchObject({ smtpFromName: 'By GraphQL', smtpPassword: SECRET_MASK })
|
||||
// a field the password belongs to, without the password: refused here as over REST
|
||||
const moved = await gql(`mutation { updateSiteIntegration(data: { smtpPassword: "${SECRET_MASK}", smtpHost: "other.example.com" }) { smtpHost } }`)
|
||||
expect(moved.errors?.length).toBeGreaterThan(0)
|
||||
expect((await stored()).smtpHost).not.toBe('other.example.com')
|
||||
expect((await stored()).smtpPassword).toBe(SMTP)
|
||||
out = await gql('mutation { updateSiteIntegration(data: { smtpPassword: "S3CRET-by-graphql" }) { smtpPassword } }')
|
||||
expect(JSON.stringify(out)).not.toContain('S3CRET')
|
||||
expect((await stored()).smtpPassword).toBe('S3CRET-by-graphql')
|
||||
})
|
||||
})
|
||||
|
||||
describe('the building blocks', () => {
|
||||
test('the hooks', () => {
|
||||
const read = (value: unknown, overrideAccess?: boolean) => maskSecretAfterRead({ overrideAccess, value } as never)
|
||||
expect(read('x', false)).toBe(SECRET_MASK)
|
||||
expect(read('x', undefined)).toBe(SECRET_MASK) // not told that access control is off → masked
|
||||
expect(read('x', true)).toBe('x')
|
||||
expect(read('', false)).toBe('')
|
||||
expect(read(null, false)).toBeNull()
|
||||
const write = (value: unknown, originalDoc: unknown, p: (number | string)[] = ['token']) => keepSecretBeforeValidate({ originalDoc, path: p, value } as never)
|
||||
expect(write('new', { token: 'old' })).toBe('new')
|
||||
for (const nothing of [undefined, null, '', SECRET_MASK]) {expect(write(nothing, { token: 'old' })).toBe('old')}
|
||||
expect(write(SECRET_CLEAR, { token: 'old' })).toBeNull()
|
||||
expect(write(SECRET_MASK, undefined)).toBeNull() // nothing stored: never the mask itself
|
||||
expect(write(SECRET_MASK, { token: SECRET_MASK })).toBeNull() // a stored mask is not a secret: never written back
|
||||
expect(write('', { group: { items: [{ token: 'deep' }] } }, ['group', 'items', 0, 'token'])).toBe('deep')
|
||||
})
|
||||
|
||||
test('writeOnlySecret keeps a field\'s own hooks; writeOnlySecrets finds fields inside tabs, rows and groups', () => {
|
||||
const mine = () => 'mine'
|
||||
const field = writeOnlySecret({ name: 'apiToken', type: 'text', hooks: { afterRead: [mine], beforeValidate: [mine] } })
|
||||
expect(field.hooks?.afterRead).toEqual([mine, maskSecretAfterRead])
|
||||
expect(field.hooks?.beforeValidate).toEqual([keepSecretBeforeValidate, mine])
|
||||
const tree = writeOnlySecrets(
|
||||
[{ type: 'tabs', tabs: [{ fields: [{ type: 'row', fields: [{ name: 'a', type: 'text' }, { name: 'b', type: 'text' }] }], label: 'T' }] }, { name: 'g', type: 'group', fields: [{ name: 'a', type: 'text' }] }],
|
||||
['a'],
|
||||
)
|
||||
const flat = JSON.stringify(tree, (_k, v) => (typeof v === 'function' ? v.name : v))
|
||||
expect(flat.match(/maskSecretAfterRead/g)).toHaveLength(2)
|
||||
expect(flat).toContain('"name":"b","type":"text"}')
|
||||
})
|
||||
|
||||
test('the opt-out: secrets: { writeOnly: false } leaves the fields as plain text fields', async () => {
|
||||
const hooked = (fields: unknown) => JSON.stringify(fields, (_k, v) => (typeof v === 'function' ? v.name : v)).includes('maskSecretAfterRead')
|
||||
expect(hooked(buildSiteIntegrations().fields)).toBe(true)
|
||||
expect(hooked(buildSiteIntegrations({ writeOnlySecrets: false }).fields)).toBe(false)
|
||||
const off = await ipalKit({ i18n: { defaultLocale: 'en', locales: [{ code: 'en', label: 'English' }] }, secrets: { writeOnly: false }, twoFactor: false })({ collections: [], secret: 'x' } as never)
|
||||
expect(hooked(off.globals!.find((g) => g.slug === 'site-integrations')!.fields)).toBe(false)
|
||||
})
|
||||
})
|
||||
@@ -0,0 +1,276 @@
|
||||
/**
|
||||
* Write-only secrets, the two ways a stored value still got out (review of M1):
|
||||
* - the SMTP password went to whatever server an admin session pointed the settings at;
|
||||
* - with versions on for the global, a restore answered with the stored value.
|
||||
* Real HTTP; SQLite by default, Postgres / MongoDB with IPAL_TEST_POSTGRES_URI / IPAL_TEST_MONGO_URI.
|
||||
*/
|
||||
import type { Payload } from 'payload'
|
||||
|
||||
import { lexicalEditor } from '@payloadcms/richtext-lexical'
|
||||
import net from 'node:net'
|
||||
import os from 'os'
|
||||
import path from 'path'
|
||||
import { getPayload } from 'payload'
|
||||
import { afterAll, beforeAll, beforeEach, describe, expect, test, vi } from 'vitest'
|
||||
|
||||
import { buildSiteIntegrations } from '../src/globals/SiteIntegrations/index.js'
|
||||
import { mailAdapter } from '../src/modules/email/mailAdapter.js'
|
||||
import { buildKeepSecret, keepSecretBeforeValidate, maskSecretsOnRestore, maskWriteOnlySecrets, SECRET_CLEAR, SECRET_MASK, writeOnlySecret } from '../src/modules/secrets/writeOnly.js'
|
||||
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 = 'a-long-test-password-1'
|
||||
const SMTP = 'S3CRET-smtp-value'
|
||||
const G = '/globals/site-integrations'
|
||||
let server: TestServer
|
||||
let payload: Payload
|
||||
let auth: Record<string, string>
|
||||
|
||||
const stored = async () => (await payload.findGlobal({ slug: 'site-integrations' as never })) as unknown as Record<string, unknown>
|
||||
const api = (pathname: string, init: RequestInit = {}, headers: Record<string, string> = {}) => fetch(`${server.url}/api${pathname}`, { ...init, headers: { 'content-type': 'application/json', ...auth, ...headers } })
|
||||
const save = (data: Record<string, unknown>, headers: Record<string, string> = {}) => api(G, { body: JSON.stringify(data), method: 'POST' }, headers)
|
||||
const reset = () => payload.updateGlobal({ slug: 'site-integrations' as never, data: { emailTransport: 'smtp', smtpFromAddress: '[email protected]', smtpHost: 'smtp.example.com', smtpPassword: SMTP, smtpPort: 587, smtpUser: 'mailer' } as never })
|
||||
|
||||
/** An SMTP server that offers no STARTTLS and writes down what a client logs in with. */
|
||||
const fakeSmtp = async () => {
|
||||
const seen = { auth: '', mails: 0 }
|
||||
const srv = net.createServer((c) => {
|
||||
c.on('error', () => {})
|
||||
let body = false
|
||||
c.write('220 fake ESMTP\r\n')
|
||||
c.on('data', (d) => {
|
||||
for (const line of d.toString().split('\r\n').filter(Boolean)) {
|
||||
if (body) {
|
||||
if (line === '.') {
|
||||
body = false
|
||||
seen.mails += 1
|
||||
c.write('250 ok\r\n')
|
||||
}
|
||||
} else if (/^EHLO/i.test(line)) {c.write('250-fake\r\n250 AUTH PLAIN LOGIN\r\n')}
|
||||
else if (/^AUTH PLAIN/i.test(line)) {
|
||||
seen.auth = Buffer.from(line.split(' ')[2] ?? '', 'base64').toString().replace(/\0/g, '|')
|
||||
c.write('235 ok\r\n')
|
||||
} else if (/^(?:MAIL|RCPT|RSET)/i.test(line)) {c.write('250 ok\r\n')}
|
||||
else if (/^DATA/i.test(line)) {
|
||||
body = true
|
||||
c.write('354 go\r\n')
|
||||
} else if (/^QUIT/i.test(line)) {c.end('221 bye\r\n')}
|
||||
else {c.write('502 not implemented\r\n')} // STARTTLS among them
|
||||
}
|
||||
})
|
||||
})
|
||||
await new Promise<void>((resolve) => srv.listen(0, '127.0.0.1', resolve))
|
||||
return { close: () => new Promise<void>((resolve) => srv.close(() => resolve())), port: (srv.address() as net.AddressInfo).port, seen }
|
||||
}
|
||||
const testEmail = () => api('/ipal/test-email', { body: JSON.stringify({ to: '[email protected]' }), method: 'POST' })
|
||||
|
||||
beforeAll(async () => {
|
||||
const config = buildTestConfig({
|
||||
admin: { user: 'users' },
|
||||
collections: [{ slug: 'media', fields: [], upload: { staticDir: path.join(os.tmpdir(), 'ipal-test-media') } }],
|
||||
db: testDatabase('secrets_bound'),
|
||||
editor: lexicalEditor(),
|
||||
email: mailAdapter(),
|
||||
plugins: [
|
||||
ipalKit({
|
||||
access: { authCollection: 'users' },
|
||||
forms: {},
|
||||
// a project that turns versions on for the global
|
||||
globalOverrides: { 'site-integrations': { versions: { drafts: true } } as never },
|
||||
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)
|
||||
await payload.create({ collection: 'users' as never, data: { email: '[email protected]', password: PASSWORD, roles: ['admin'] } as never })
|
||||
const login = (await (await fetch(`${server.url}/api/users/login`, { body: JSON.stringify({ email: '[email protected]', password: PASSWORD }), headers: { 'content-type': 'application/json' }, method: 'POST' })).json()) as { token: string }
|
||||
auth = { authorization: `JWT ${login.token}` }
|
||||
}, 120_000)
|
||||
|
||||
afterAll(async () => {
|
||||
await server?.close()
|
||||
await payload?.destroy?.()
|
||||
})
|
||||
|
||||
beforeEach(async () => {
|
||||
await reset()
|
||||
})
|
||||
|
||||
describe('the SMTP password stays with the server it was saved for (secrets.reenterOnChange)', () => {
|
||||
test('an admin session cannot send the stored password to a server of its own', async () => {
|
||||
const mine = await fakeSmtp()
|
||||
try {
|
||||
// before: 200, then the test e-mail logged in to the new server with the stored password
|
||||
const moved = await save({ smtpHost: '127.0.0.1', smtpPort: mine.port })
|
||||
expect(moved.status).toBe(400)
|
||||
const body = JSON.stringify(await moved.json())
|
||||
expect(body).toMatch(/Enter the password again/)
|
||||
expect(body).toContain('smtpPassword')
|
||||
expect(body).not.toContain(SMTP)
|
||||
expect(await stored()).toMatchObject({ smtpHost: 'smtp.example.com', smtpPassword: SMTP, smtpPort: 587 })
|
||||
await testEmail()
|
||||
expect(mine.seen).toEqual({ auth: '', mails: 0 })
|
||||
} finally {
|
||||
await mine.close()
|
||||
}
|
||||
})
|
||||
|
||||
test.each([
|
||||
['the server', { smtpHost: 'other.example.com' }],
|
||||
['the port', { smtpPort: 2525 }],
|
||||
['the user name', { smtpUser: 'someone-else' }],
|
||||
['the server to another letter case', { smtpHost: 'SMTP.example.com' }],
|
||||
['the server by a space', { smtpHost: 'smtp.example.com ' }],
|
||||
['the server while naming Microsoft Graph as the transport', { emailTransport: 'graph', smtpHost: 'other.example.com' }],
|
||||
['the port while naming Microsoft Graph as the transport', { emailTransport: 'graph', smtpPort: 2525 }],
|
||||
['the server, sending the mask back as the panel does', { smtpHost: 'other.example.com', smtpPassword: SECRET_MASK }],
|
||||
['the server, with an empty password', { smtpHost: 'other.example.com', smtpPassword: '' }],
|
||||
['the server, in a draft', { _status: 'draft', smtpHost: 'other.example.com' }],
|
||||
])('changing %s without the password is refused, and nothing is stored', async (_what, data) => {
|
||||
const draft = '_status' in data
|
||||
const res = await api(`${G}${draft ? '?draft=true' : ''}`, { body: JSON.stringify(data), method: 'POST' })
|
||||
expect(res.status).toBe(400)
|
||||
expect(await stored()).toMatchObject({ smtpHost: 'smtp.example.com', smtpPassword: SMTP, smtpPort: 587, smtpUser: 'mailer' })
|
||||
})
|
||||
|
||||
test('in Polish for a Polish panel', async () => {
|
||||
const res = await save({ smtpHost: 'other.example.com' }, { 'accept-language': 'pl' })
|
||||
expect(res.status).toBe(400)
|
||||
expect(JSON.stringify(await res.json())).toMatch(/Wpisz hasło ponownie/)
|
||||
})
|
||||
|
||||
test('with the password typed again the new server is saved; removing the stored value works too', async () => {
|
||||
expect((await save({ smtpHost: 'other.example.com', smtpPassword: 'typed-again' })).status).toBe(200)
|
||||
expect(await stored()).toMatchObject({ smtpHost: 'other.example.com', smtpPassword: 'typed-again' })
|
||||
expect((await save({ smtpHost: 'third.example.com', smtpPassword: SECRET_CLEAR })).status).toBe(200)
|
||||
expect(await stored()).toMatchObject({ smtpHost: 'third.example.com' })
|
||||
expect((await stored()).smtpPassword ?? null).toBeNull()
|
||||
// nothing stored = nothing to protect: the server can be changed freely
|
||||
expect((await save({ smtpHost: 'fourth.example.com' })).status).toBe(200)
|
||||
})
|
||||
|
||||
test('a save that changes nothing the password belongs to keeps it: the same values sent back, other fields, the port as text', async () => {
|
||||
const doc = (await (await api(G)).json()) as Record<string, unknown>
|
||||
for (const key of ['id', 'createdAt', 'updatedAt', 'globalType']) {delete doc[key]}
|
||||
expect((await save(doc)).status).toBe(200) // the whole form, as the panel sends it
|
||||
expect((await save({ smtpFromName: 'The site', smtpHost: 'smtp.example.com', smtpPort: '587', smtpUser: 'mailer' })).status).toBe(200)
|
||||
expect((await save({ turnstileSiteKey: 'site-key' })).status).toBe(200)
|
||||
expect(await stored()).toMatchObject({ smtpFromName: 'The site', smtpPassword: SMTP })
|
||||
})
|
||||
|
||||
test('a stored NULL where the field has a default (a SQL row, an older document) is not a change', async () => {
|
||||
// the port sits inside a row; its default is 587, the transport's is 'smtp'
|
||||
await payload.db.updateGlobal({ slug: 'site-integrations', data: { ...(await stored()), emailTransport: null, smtpPort: null } as never })
|
||||
expect((await save({ smtpFromName: 'Again' })).status).toBe(200)
|
||||
expect((await save({ emailTransport: 'smtp', smtpFromName: 'Again', smtpPort: 587 })).status).toBe(200)
|
||||
await payload.db.updateGlobal({ slug: 'site-integrations', data: { ...(await stored()), emailTransport: null, smtpPort: null } as never })
|
||||
expect((await save({ smtpFromName: 'Again', smtpPort: null })).status).toBe(200)
|
||||
const doc = (await (await api(G)).json()) as Record<string, unknown>
|
||||
for (const key of ['id', 'createdAt', 'updatedAt', 'globalType']) {delete doc[key]}
|
||||
expect((await save(doc)).status).toBe(200)
|
||||
expect((await save({ smtpPort: 2525 })).status).toBe(400)
|
||||
expect((await stored()).smtpPassword).toBe(SMTP)
|
||||
})
|
||||
|
||||
// Review round 2 (R2-1): "Microsoft Graph" in the panel does not mean Graph sends — the mail adapter falls back to
|
||||
// SMTP when the GRAPH_* variables are missing. The transport decides nothing; the server, port and user do.
|
||||
test('the transport switch is not a way round: Graph + my server in one save, or Graph first and my server after', async () => {
|
||||
const mine = await fakeSmtp()
|
||||
try {
|
||||
const gql = async (data: string) => (await (await api('/graphql', { body: JSON.stringify({ query: `mutation { updateSiteIntegration(data: { ${data} }) { smtpHost } }` }), method: 'POST' })).json()) as { errors?: unknown[] }
|
||||
// 1. in one save, over REST and over GraphQL
|
||||
expect((await save({ emailTransport: 'graph', smtpHost: '127.0.0.1', smtpPort: mine.port })).status).toBe(400)
|
||||
expect((await gql(`emailTransport: graph, smtpHost: "127.0.0.1", smtpPort: ${mine.port}`)).errors?.length).toBeGreaterThan(0)
|
||||
await testEmail()
|
||||
// 2. the switch alone passes (the password is not asked for, and stays)…
|
||||
expect((await save({ emailTransport: 'graph' })).status).toBe(200)
|
||||
// …and the server afterwards does not, with or without naming the transport again
|
||||
expect((await save({ smtpHost: '127.0.0.1', smtpPort: mine.port })).status).toBe(400)
|
||||
expect((await save({ emailTransport: 'graph', smtpHost: '127.0.0.1', smtpPort: mine.port })).status).toBe(400)
|
||||
expect((await save({ emailTransport: 'smtp', smtpHost: '127.0.0.1', smtpPort: mine.port })).status).toBe(400)
|
||||
expect((await gql(`smtpHost: "127.0.0.1", smtpPort: ${mine.port}`)).errors?.length).toBeGreaterThan(0)
|
||||
await testEmail()
|
||||
await api('/ipal/test-email', { body: JSON.stringify({ attachmentMB: 5, to: '[email protected]' }), method: 'POST' })
|
||||
expect(mine.seen).toEqual({ auth: '', mails: 0 })
|
||||
expect(await stored()).toMatchObject({ emailTransport: 'graph', smtpHost: 'smtp.example.com', smtpPassword: SMTP, smtpPort: 587 })
|
||||
// back to SMTP alone: the same server as before, nothing to ask
|
||||
expect((await save({ emailTransport: 'smtp' })).status).toBe(200)
|
||||
} finally {
|
||||
await mine.close()
|
||||
}
|
||||
})
|
||||
|
||||
test('server code (a seed, the Local API with access control off) moves the server and keeps the password', async () => {
|
||||
await payload.updateGlobal({ slug: 'site-integrations' as never, data: { smtpHost: 'seeded.example.com' } as never })
|
||||
expect(await stored()).toMatchObject({ smtpHost: 'seeded.example.com', smtpPassword: SMTP })
|
||||
})
|
||||
|
||||
test('the option and the building block', () => {
|
||||
const hooksOf = (global: ReturnType<typeof buildSiteIntegrations>) => {
|
||||
const found: unknown[] = []
|
||||
JSON.stringify(global.fields, (_k, v) => {
|
||||
if (v && typeof v === 'object' && (v as { name?: string }).name === 'smtpPassword') {found.push((v as { hooks: { beforeValidate: unknown[] } }).hooks?.beforeValidate?.[0])}
|
||||
return v as unknown
|
||||
})
|
||||
return found[0]
|
||||
}
|
||||
expect(hooksOf(buildSiteIntegrations())).not.toBe(keepSecretBeforeValidate)
|
||||
expect(hooksOf(buildSiteIntegrations({ reenterSecretOnChange: false }))).toBe(keepSecretBeforeValidate)
|
||||
// a field of a project's own
|
||||
const field = writeOnlySecret({ name: 'apiToken', type: 'text' }, { boundTo: ['apiUrl'] })
|
||||
const hook = (field as unknown as { hooks: { beforeValidate: ((args: never) => unknown)[] } }).hooks.beforeValidate[0]
|
||||
const run = (siblingData: unknown, overrideAccess?: boolean) => hook({ originalDoc: { apiToken: 'old', apiUrl: 'https://a.example' }, overrideAccess, path: ['apiToken'], siblingData, value: undefined } as never)
|
||||
expect(run({ apiUrl: 'https://a.example' })).toBe('old')
|
||||
expect(run({})).toBe('old')
|
||||
expect(() => run({ apiUrl: 'https://b.example' })).toThrow()
|
||||
expect(run({ apiUrl: 'https://b.example' }, true)).toBe('old')
|
||||
expect(buildKeepSecret({ appliesWhen: () => false, boundTo: ['apiUrl'] })({ originalDoc: { apiToken: 'old', apiUrl: 'a' }, path: ['apiToken'], siblingData: { apiUrl: 'b' }, value: '' } as never)).toBe('old')
|
||||
})
|
||||
})
|
||||
|
||||
describe('versions on the global: a restore does not hand the value back', () => {
|
||||
test('REST restore answers with the mask; the stored value is the restored one', async () => {
|
||||
await save({ smtpFromName: 'One' })
|
||||
await save({ smtpFromName: 'Two' })
|
||||
const versions = (await (await api(`${G}/versions?limit=50`)).json()) as { docs: { id: number | string; version: Record<string, unknown> }[] }
|
||||
expect(versions.docs.length).toBeGreaterThan(1)
|
||||
expect(JSON.stringify(versions)).not.toContain(SMTP)
|
||||
const target = versions.docs.find((d) => d.version.smtpFromName === 'One')!
|
||||
const restored = await api(`${G}/versions/${target.id}`, { method: 'POST' })
|
||||
expect(restored.status).toBe(200)
|
||||
const text = await restored.text()
|
||||
// before: the stored password, under `version`
|
||||
expect(text).not.toContain(SMTP)
|
||||
expect(text).toContain(SECRET_MASK)
|
||||
expect(await stored()).toMatchObject({ smtpFromName: 'One', smtpPassword: SMTP })
|
||||
// server code that restores with access control off still gets the document as it is
|
||||
const local = (await payload.restoreGlobalVersion({ id: target.id as never, slug: 'site-integrations' as never })) as unknown as { version?: Record<string, unknown> }
|
||||
expect(JSON.stringify(local)).toContain(SMTP)
|
||||
})
|
||||
|
||||
test('the hook and the walker', () => {
|
||||
const fields = [
|
||||
{ type: 'tabs', tabs: [{ fields: [writeOnlySecret({ name: 'a', type: 'text' }), { name: 'plain', type: 'text' }], label: 'T' }, { name: 'named', fields: [writeOnlySecret({ name: 'b', type: 'text' })] }] },
|
||||
{ name: 'g', type: 'group', fields: [{ type: 'row', fields: [writeOnlySecret({ name: 'c', type: 'text' })] }] },
|
||||
{ name: 'rows', type: 'array', fields: [writeOnlySecret({ name: 'd', type: 'text' })] },
|
||||
{ name: 'layout', type: 'blocks', blocks: [{ slug: 'x', fields: [writeOnlySecret({ name: 'e', type: 'text' })] }] },
|
||||
] as never
|
||||
const doc = () => ({ a: 's', g: { c: 's' }, layout: [{ blockType: 'x', e: 's' }, { blockType: 'other', e: 'kept' }], named: { b: 's' }, plain: 'p', rows: [{ d: 's' }, { d: '' }] })
|
||||
const masked = doc()
|
||||
maskWriteOnlySecrets(masked, fields)
|
||||
expect(masked).toEqual({ a: SECRET_MASK, g: { c: SECRET_MASK }, layout: [{ blockType: 'x', e: SECRET_MASK }, { blockType: 'other', e: 'kept' }], named: { b: SECRET_MASK }, plain: 'p', rows: [{ d: SECRET_MASK }, { d: '' }] })
|
||||
const hook = (extra: Record<string, unknown>) => JSON.stringify(maskSecretsOnRestore({ context: { isRestoringVersion: true }, doc: { version: doc() }, global: { fields }, ...extra } as never))
|
||||
expect(hook({})).not.toContain('"s"')
|
||||
expect(hook({ overrideAccess: true })).toContain('"s"')
|
||||
expect(hook({ context: {} })).toContain('"s"') // an ordinary read: the field hooks did the work already
|
||||
expect(hook({ collection: { fields }, global: undefined })).not.toContain('"s"')
|
||||
})
|
||||
})
|
||||
Reference in New Issue
Block a user